id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_good_3187_0 | /* This file is part of libmspack.
* (C) 2003-2013 Stuart Caie.
*
* The LZX method was created by Jonathan Forbes and Tomi Poutanen, adapted
* by Microsoft Corporation.
*
* libmspack is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License (LGPL) version 2.1
*
* For further details, see the file COPYING.LIB distributed with libmspack
*/
/* LZX decompression implementation */
#include <system.h>
#include <lzx.h>
/* Microsoft's LZX document (in cab-sdk.exe) and their implementation
* of the com.ms.util.cab Java package do not concur.
*
* In the LZX document, there is a table showing the correlation between
* window size and the number of position slots. It states that the 1MB
* window = 40 slots and the 2MB window = 42 slots. In the implementation,
* 1MB = 42 slots, 2MB = 50 slots. The actual calculation is 'find the
* first slot whose position base is equal to or more than the required
* window size'. This would explain why other tables in the document refer
* to 50 slots rather than 42.
*
* The constant NUM_PRIMARY_LENGTHS used in the decompression pseudocode
* is not defined in the specification.
*
* The LZX document does not state the uncompressed block has an
* uncompressed length field. Where does this length field come from, so
* we can know how large the block is? The implementation has it as the 24
* bits following after the 3 blocktype bits, before the alignment
* padding.
*
* The LZX document states that aligned offset blocks have their aligned
* offset huffman tree AFTER the main and length trees. The implementation
* suggests that the aligned offset tree is BEFORE the main and length
* trees.
*
* The LZX document decoding algorithm states that, in an aligned offset
* block, if an extra_bits value is 1, 2 or 3, then that number of bits
* should be read and the result added to the match offset. This is
* correct for 1 and 2, but not 3, where just a huffman symbol (using the
* aligned tree) should be read.
*
* Regarding the E8 preprocessing, the LZX document states 'No translation
* may be performed on the last 6 bytes of the input block'. This is
* correct. However, the pseudocode provided checks for the *E8 leader*
* up to the last 6 bytes. If the leader appears between -10 and -7 bytes
* from the end, this would cause the next four bytes to be modified, at
* least one of which would be in the last 6 bytes, which is not allowed
* according to the spec.
*
* The specification states that the huffman trees must always contain at
* least one element. However, many CAB files contain blocks where the
* length tree is completely empty (because there are no matches), and
* this is expected to succeed.
*
* The errors in LZX documentation appear have been corrected in the
* new documentation for the LZX DELTA format.
*
* http://msdn.microsoft.com/en-us/library/cc483133.aspx
*
* However, this is a different format, an extension of regular LZX.
* I have noticed the following differences, there may be more:
*
* The maximum window size has increased from 2MB to 32MB. This also
* increases the maximum number of position slots, etc.
*
* If the match length is 257 (the maximum possible), this signals
* a further length decoding step, that allows for matches up to
* 33024 bytes long.
*
* The format now allows for "reference data", supplied by the caller.
* If match offsets go further back than the number of bytes
* decompressed so far, that is them accessing the reference data.
*/
/* import bit-reading macros and code */
#define BITS_TYPE struct lzxd_stream
#define BITS_VAR lzx
#define BITS_ORDER_MSB
#define READ_BYTES do { \
unsigned char b0, b1; \
READ_IF_NEEDED; b0 = *i_ptr++; \
READ_IF_NEEDED; b1 = *i_ptr++; \
INJECT_BITS((b1 << 8) | b0, 16); \
} while (0)
#include <readbits.h>
/* import huffman-reading macros and code */
#define TABLEBITS(tbl) LZX_##tbl##_TABLEBITS
#define MAXSYMBOLS(tbl) LZX_##tbl##_MAXSYMBOLS
#define HUFF_TABLE(tbl,idx) lzx->tbl##_table[idx]
#define HUFF_LEN(tbl,idx) lzx->tbl##_len[idx]
#define HUFF_ERROR return lzx->error = MSPACK_ERR_DECRUNCH
#include <readhuff.h>
/* BUILD_TABLE(tbl) builds a huffman lookup table from code lengths */
#define BUILD_TABLE(tbl) \
if (make_decode_table(MAXSYMBOLS(tbl), TABLEBITS(tbl), \
&HUFF_LEN(tbl,0), &HUFF_TABLE(tbl,0))) \
{ \
D(("failed to build %s table", #tbl)) \
return lzx->error = MSPACK_ERR_DECRUNCH; \
}
#define BUILD_TABLE_MAYBE_EMPTY(tbl) do { \
lzx->tbl##_empty = 0; \
if (make_decode_table(MAXSYMBOLS(tbl), TABLEBITS(tbl), \
&HUFF_LEN(tbl,0), &HUFF_TABLE(tbl,0))) \
{ \
for (i = 0; i < MAXSYMBOLS(tbl); i++) { \
if (HUFF_LEN(tbl, i) > 0) { \
D(("failed to build %s table", #tbl)) \
return lzx->error = MSPACK_ERR_DECRUNCH; \
} \
} \
/* empty tree - allow it, but don't decode symbols with it */ \
lzx->tbl##_empty = 1; \
} \
} while (0)
/* READ_LENGTHS(tablename, first, last) reads in code lengths for symbols
* first to last in the given table. The code lengths are stored in their
* own special LZX way.
*/
#define READ_LENGTHS(tbl, first, last) do { \
STORE_BITS; \
if (lzxd_read_lens(lzx, &HUFF_LEN(tbl, 0), (first), \
(unsigned int)(last))) return lzx->error; \
RESTORE_BITS; \
} while (0)
static int lzxd_read_lens(struct lzxd_stream *lzx, unsigned char *lens,
unsigned int first, unsigned int last)
{
/* bit buffer and huffman symbol decode variables */
register unsigned int bit_buffer;
register int bits_left, i;
register unsigned short sym;
unsigned char *i_ptr, *i_end;
unsigned int x, y;
int z;
RESTORE_BITS;
/* read lengths for pretree (20 symbols, lengths stored in fixed 4 bits) */
for (x = 0; x < 20; x++) {
READ_BITS(y, 4);
lzx->PRETREE_len[x] = y;
}
BUILD_TABLE(PRETREE);
for (x = first; x < last; ) {
READ_HUFFSYM(PRETREE, z);
if (z == 17) {
/* code = 17, run of ([read 4 bits]+4) zeros */
READ_BITS(y, 4); y += 4;
while (y--) lens[x++] = 0;
}
else if (z == 18) {
/* code = 18, run of ([read 5 bits]+20) zeros */
READ_BITS(y, 5); y += 20;
while (y--) lens[x++] = 0;
}
else if (z == 19) {
/* code = 19, run of ([read 1 bit]+4) [read huffman symbol] */
READ_BITS(y, 1); y += 4;
READ_HUFFSYM(PRETREE, z);
z = lens[x] - z; if (z < 0) z += 17;
while (y--) lens[x++] = z;
}
else {
/* code = 0 to 16, delta current length entry */
z = lens[x] - z; if (z < 0) z += 17;
lens[x++] = z;
}
}
STORE_BITS;
return MSPACK_ERR_OK;
}
/* LZX static data tables:
*
* LZX uses 'position slots' to represent match offsets. For every match,
* a small 'position slot' number and a small offset from that slot are
* encoded instead of one large offset.
*
* The number of slots is decided by how many are needed to encode the
* largest offset for a given window size. This is easy when the gap between
* slots is less than 128Kb, it's a linear relationship. But when extra_bits
* reaches its limit of 17 (because LZX can only ensure reading 17 bits of
* data at a time), we can only jump 128Kb at a time and have to start
* using more and more position slots as each window size doubles.
*
* position_base[] is an index to the position slot bases
*
* extra_bits[] states how many bits of offset-from-base data is needed.
*
* They are calculated as follows:
* extra_bits[i] = 0 where i < 4
* extra_bits[i] = floor(i/2)-1 where i >= 4 && i < 36
* extra_bits[i] = 17 where i >= 36
* position_base[0] = 0
* position_base[i] = position_base[i-1] + (1 << extra_bits[i-1])
*/
static const unsigned int position_slots[11] = {
30, 32, 34, 36, 38, 42, 50, 66, 98, 162, 290
};
static const unsigned char extra_bits[36] = {
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16
};
static const unsigned int position_base[290] = {
0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512,
768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576, 32768,
49152, 65536, 98304, 131072, 196608, 262144, 393216, 524288, 655360,
786432, 917504, 1048576, 1179648, 1310720, 1441792, 1572864, 1703936,
1835008, 1966080, 2097152, 2228224, 2359296, 2490368, 2621440, 2752512,
2883584, 3014656, 3145728, 3276800, 3407872, 3538944, 3670016, 3801088,
3932160, 4063232, 4194304, 4325376, 4456448, 4587520, 4718592, 4849664,
4980736, 5111808, 5242880, 5373952, 5505024, 5636096, 5767168, 5898240,
6029312, 6160384, 6291456, 6422528, 6553600, 6684672, 6815744, 6946816,
7077888, 7208960, 7340032, 7471104, 7602176, 7733248, 7864320, 7995392,
8126464, 8257536, 8388608, 8519680, 8650752, 8781824, 8912896, 9043968,
9175040, 9306112, 9437184, 9568256, 9699328, 9830400, 9961472, 10092544,
10223616, 10354688, 10485760, 10616832, 10747904, 10878976, 11010048,
11141120, 11272192, 11403264, 11534336, 11665408, 11796480, 11927552,
12058624, 12189696, 12320768, 12451840, 12582912, 12713984, 12845056,
12976128, 13107200, 13238272, 13369344, 13500416, 13631488, 13762560,
13893632, 14024704, 14155776, 14286848, 14417920, 14548992, 14680064,
14811136, 14942208, 15073280, 15204352, 15335424, 15466496, 15597568,
15728640, 15859712, 15990784, 16121856, 16252928, 16384000, 16515072,
16646144, 16777216, 16908288, 17039360, 17170432, 17301504, 17432576,
17563648, 17694720, 17825792, 17956864, 18087936, 18219008, 18350080,
18481152, 18612224, 18743296, 18874368, 19005440, 19136512, 19267584,
19398656, 19529728, 19660800, 19791872, 19922944, 20054016, 20185088,
20316160, 20447232, 20578304, 20709376, 20840448, 20971520, 21102592,
21233664, 21364736, 21495808, 21626880, 21757952, 21889024, 22020096,
22151168, 22282240, 22413312, 22544384, 22675456, 22806528, 22937600,
23068672, 23199744, 23330816, 23461888, 23592960, 23724032, 23855104,
23986176, 24117248, 24248320, 24379392, 24510464, 24641536, 24772608,
24903680, 25034752, 25165824, 25296896, 25427968, 25559040, 25690112,
25821184, 25952256, 26083328, 26214400, 26345472, 26476544, 26607616,
26738688, 26869760, 27000832, 27131904, 27262976, 27394048, 27525120,
27656192, 27787264, 27918336, 28049408, 28180480, 28311552, 28442624,
28573696, 28704768, 28835840, 28966912, 29097984, 29229056, 29360128,
29491200, 29622272, 29753344, 29884416, 30015488, 30146560, 30277632,
30408704, 30539776, 30670848, 30801920, 30932992, 31064064, 31195136,
31326208, 31457280, 31588352, 31719424, 31850496, 31981568, 32112640,
32243712, 32374784, 32505856, 32636928, 32768000, 32899072, 33030144,
33161216, 33292288, 33423360
};
static void lzxd_reset_state(struct lzxd_stream *lzx) {
int i;
lzx->R0 = 1;
lzx->R1 = 1;
lzx->R2 = 1;
lzx->header_read = 0;
lzx->block_remaining = 0;
lzx->block_type = LZX_BLOCKTYPE_INVALID;
/* initialise tables to 0 (because deltas will be applied to them) */
for (i = 0; i < LZX_MAINTREE_MAXSYMBOLS; i++) lzx->MAINTREE_len[i] = 0;
for (i = 0; i < LZX_LENGTH_MAXSYMBOLS; i++) lzx->LENGTH_len[i] = 0;
}
/*-------- main LZX code --------*/
struct lzxd_stream *lzxd_init(struct mspack_system *system,
struct mspack_file *input,
struct mspack_file *output,
int window_bits,
int reset_interval,
int input_buffer_size,
off_t output_length,
char is_delta)
{
unsigned int window_size = 1 << window_bits;
struct lzxd_stream *lzx;
if (!system) return NULL;
/* LZX DELTA window sizes are between 2^17 (128KiB) and 2^25 (32MiB),
* regular LZX windows are between 2^15 (32KiB) and 2^21 (2MiB)
*/
if (is_delta) {
if (window_bits < 17 || window_bits > 25) return NULL;
}
else {
if (window_bits < 15 || window_bits > 21) return NULL;
}
input_buffer_size = (input_buffer_size + 1) & -2;
if (!input_buffer_size) return NULL;
/* allocate decompression state */
if (!(lzx = (struct lzxd_stream *) system->alloc(system, sizeof(struct lzxd_stream)))) {
return NULL;
}
/* allocate decompression window and input buffer */
lzx->window = (unsigned char *) system->alloc(system, (size_t) window_size);
lzx->inbuf = (unsigned char *) system->alloc(system, (size_t) input_buffer_size);
if (!lzx->window || !lzx->inbuf) {
system->free(lzx->window);
system->free(lzx->inbuf);
system->free(lzx);
return NULL;
}
/* initialise decompression state */
lzx->sys = system;
lzx->input = input;
lzx->output = output;
lzx->offset = 0;
lzx->length = output_length;
lzx->inbuf_size = input_buffer_size;
lzx->window_size = 1 << window_bits;
lzx->ref_data_size = 0;
lzx->window_posn = 0;
lzx->frame_posn = 0;
lzx->frame = 0;
lzx->reset_interval = reset_interval;
lzx->intel_filesize = 0;
lzx->intel_curpos = 0;
lzx->intel_started = 0;
lzx->error = MSPACK_ERR_OK;
lzx->num_offsets = position_slots[window_bits - 15] << 3;
lzx->is_delta = is_delta;
lzx->o_ptr = lzx->o_end = &lzx->e8_buf[0];
lzxd_reset_state(lzx);
INIT_BITS;
return lzx;
}
int lzxd_set_reference_data(struct lzxd_stream *lzx,
struct mspack_system *system,
struct mspack_file *input,
unsigned int length)
{
if (!lzx) return MSPACK_ERR_ARGS;
if (!lzx->is_delta) {
D(("only LZX DELTA streams support reference data"))
return MSPACK_ERR_ARGS;
}
if (lzx->offset) {
D(("too late to set reference data after decoding starts"))
return MSPACK_ERR_ARGS;
}
if (length > lzx->window_size) {
D(("reference length (%u) is longer than the window", length))
return MSPACK_ERR_ARGS;
}
if (length > 0 && (!system || !input)) {
D(("length > 0 but no system or input"))
return MSPACK_ERR_ARGS;
}
lzx->ref_data_size = length;
if (length > 0) {
/* copy reference data */
unsigned char *pos = &lzx->window[lzx->window_size - length];
int bytes = system->read(input, pos, length);
/* length can't be more than 2^25, so no signedness problem */
if (bytes < (int)length) return MSPACK_ERR_READ;
}
lzx->ref_data_size = length;
return MSPACK_ERR_OK;
}
void lzxd_set_output_length(struct lzxd_stream *lzx, off_t out_bytes) {
if (lzx) lzx->length = out_bytes;
}
int lzxd_decompress(struct lzxd_stream *lzx, off_t out_bytes) {
/* bitstream and huffman reading variables */
register unsigned int bit_buffer;
register int bits_left, i=0;
unsigned char *i_ptr, *i_end;
register unsigned short sym;
int match_length, length_footer, extra, verbatim_bits, bytes_todo;
int this_run, main_element, aligned_bits, j;
unsigned char *window, *runsrc, *rundest, buf[12];
unsigned int frame_size=0, end_frame, match_offset, window_posn;
unsigned int R0, R1, R2;
/* easy answers */
if (!lzx || (out_bytes < 0)) return MSPACK_ERR_ARGS;
if (lzx->error) return lzx->error;
/* flush out any stored-up bytes before we begin */
i = lzx->o_end - lzx->o_ptr;
if ((off_t) i > out_bytes) i = (int) out_bytes;
if (i) {
if (lzx->sys->write(lzx->output, lzx->o_ptr, i) != i) {
return lzx->error = MSPACK_ERR_WRITE;
}
lzx->o_ptr += i;
lzx->offset += i;
out_bytes -= i;
}
if (out_bytes == 0) return MSPACK_ERR_OK;
/* restore local state */
RESTORE_BITS;
window = lzx->window;
window_posn = lzx->window_posn;
R0 = lzx->R0;
R1 = lzx->R1;
R2 = lzx->R2;
end_frame = (unsigned int)((lzx->offset + out_bytes) / LZX_FRAME_SIZE) + 1;
while (lzx->frame < end_frame) {
/* have we reached the reset interval? (if there is one?) */
if (lzx->reset_interval && ((lzx->frame % lzx->reset_interval) == 0)) {
if (lzx->block_remaining) {
D(("%d bytes remaining at reset interval", lzx->block_remaining))
return lzx->error = MSPACK_ERR_DECRUNCH;
}
/* re-read the intel header and reset the huffman lengths */
lzxd_reset_state(lzx);
R0 = lzx->R0;
R1 = lzx->R1;
R2 = lzx->R2;
}
/* LZX DELTA format has chunk_size, not present in LZX format */
if (lzx->is_delta) {
ENSURE_BITS(16);
REMOVE_BITS(16);
}
/* read header if necessary */
if (!lzx->header_read) {
/* read 1 bit. if bit=0, intel filesize = 0.
* if bit=1, read intel filesize (32 bits) */
j = 0; READ_BITS(i, 1); if (i) { READ_BITS(i, 16); READ_BITS(j, 16); }
lzx->intel_filesize = (i << 16) | j;
lzx->header_read = 1;
}
/* calculate size of frame: all frames are 32k except the final frame
* which is 32kb or less. this can only be calculated when lzx->length
* has been filled in. */
frame_size = LZX_FRAME_SIZE;
if (lzx->length && (lzx->length - lzx->offset) < (off_t)frame_size) {
frame_size = lzx->length - lzx->offset;
}
/* decode until one more frame is available */
bytes_todo = lzx->frame_posn + frame_size - window_posn;
while (bytes_todo > 0) {
/* initialise new block, if one is needed */
if (lzx->block_remaining == 0) {
/* realign if previous block was an odd-sized UNCOMPRESSED block */
if ((lzx->block_type == LZX_BLOCKTYPE_UNCOMPRESSED) &&
(lzx->block_length & 1))
{
READ_IF_NEEDED;
i_ptr++;
}
/* read block type (3 bits) and block length (24 bits) */
READ_BITS(lzx->block_type, 3);
READ_BITS(i, 16); READ_BITS(j, 8);
lzx->block_remaining = lzx->block_length = (i << 8) | j;
/*D(("new block t%d len %u", lzx->block_type, lzx->block_length))*/
/* read individual block headers */
switch (lzx->block_type) {
case LZX_BLOCKTYPE_ALIGNED:
/* read lengths of and build aligned huffman decoding tree */
for (i = 0; i < 8; i++) { READ_BITS(j, 3); lzx->ALIGNED_len[i] = j; }
BUILD_TABLE(ALIGNED);
/* no break -- rest of aligned header is same as verbatim */
case LZX_BLOCKTYPE_VERBATIM:
/* read lengths of and build main huffman decoding tree */
READ_LENGTHS(MAINTREE, 0, 256);
READ_LENGTHS(MAINTREE, 256, LZX_NUM_CHARS + lzx->num_offsets);
BUILD_TABLE(MAINTREE);
/* if the literal 0xE8 is anywhere in the block... */
if (lzx->MAINTREE_len[0xE8] != 0) lzx->intel_started = 1;
/* read lengths of and build lengths huffman decoding tree */
READ_LENGTHS(LENGTH, 0, LZX_NUM_SECONDARY_LENGTHS);
BUILD_TABLE_MAYBE_EMPTY(LENGTH);
break;
case LZX_BLOCKTYPE_UNCOMPRESSED:
/* because we can't assume otherwise */
lzx->intel_started = 1;
/* read 1-16 (not 0-15) bits to align to bytes */
if (bits_left == 0) ENSURE_BITS(16);
bits_left = 0; bit_buffer = 0;
/* read 12 bytes of stored R0 / R1 / R2 values */
for (rundest = &buf[0], i = 0; i < 12; i++) {
READ_IF_NEEDED;
*rundest++ = *i_ptr++;
}
R0 = buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
R1 = buf[4] | (buf[5] << 8) | (buf[6] << 16) | (buf[7] << 24);
R2 = buf[8] | (buf[9] << 8) | (buf[10] << 16) | (buf[11] << 24);
break;
default:
D(("bad block type"))
return lzx->error = MSPACK_ERR_DECRUNCH;
}
}
/* decode more of the block:
* run = min(what's available, what's needed) */
this_run = lzx->block_remaining;
if (this_run > bytes_todo) this_run = bytes_todo;
/* assume we decode exactly this_run bytes, for now */
bytes_todo -= this_run;
lzx->block_remaining -= this_run;
/* decode at least this_run bytes */
switch (lzx->block_type) {
case LZX_BLOCKTYPE_VERBATIM:
while (this_run > 0) {
READ_HUFFSYM(MAINTREE, main_element);
if (main_element < LZX_NUM_CHARS) {
/* literal: 0 to LZX_NUM_CHARS-1 */
window[window_posn++] = main_element;
this_run--;
}
else {
/* match: LZX_NUM_CHARS + ((slot<<3) | length_header (3 bits)) */
main_element -= LZX_NUM_CHARS;
/* get match length */
match_length = main_element & LZX_NUM_PRIMARY_LENGTHS;
if (match_length == LZX_NUM_PRIMARY_LENGTHS) {
if (lzx->LENGTH_empty) {
D(("LENGTH symbol needed but tree is empty"))
return lzx->error = MSPACK_ERR_DECRUNCH;
}
READ_HUFFSYM(LENGTH, length_footer);
match_length += length_footer;
}
match_length += LZX_MIN_MATCH;
/* get match offset */
switch ((match_offset = (main_element >> 3))) {
case 0: match_offset = R0; break;
case 1: match_offset = R1; R1=R0; R0 = match_offset; break;
case 2: match_offset = R2; R2=R0; R0 = match_offset; break;
case 3: match_offset = 1; R2=R1; R1=R0; R0 = match_offset; break;
default:
extra = (match_offset >= 36) ? 17 : extra_bits[match_offset];
READ_BITS(verbatim_bits, extra);
match_offset = position_base[match_offset] - 2 + verbatim_bits;
R2 = R1; R1 = R0; R0 = match_offset;
}
/* LZX DELTA uses max match length to signal even longer match */
if (match_length == LZX_MAX_MATCH && lzx->is_delta) {
int extra_len = 0;
ENSURE_BITS(3); /* 4 entry huffman tree */
if (PEEK_BITS(1) == 0) {
REMOVE_BITS(1); /* '0' -> 8 extra length bits */
READ_BITS(extra_len, 8);
}
else if (PEEK_BITS(2) == 2) {
REMOVE_BITS(2); /* '10' -> 10 extra length bits + 0x100 */
READ_BITS(extra_len, 10);
extra_len += 0x100;
}
else if (PEEK_BITS(3) == 6) {
REMOVE_BITS(3); /* '110' -> 12 extra length bits + 0x500 */
READ_BITS(extra_len, 12);
extra_len += 0x500;
}
else {
REMOVE_BITS(3); /* '111' -> 15 extra length bits */
READ_BITS(extra_len, 15);
}
match_length += extra_len;
}
if ((window_posn + match_length) > lzx->window_size) {
D(("match ran over window wrap"))
return lzx->error = MSPACK_ERR_DECRUNCH;
}
/* copy match */
rundest = &window[window_posn];
i = match_length;
/* does match offset wrap the window? */
if (match_offset > window_posn) {
if (match_offset > lzx->offset &&
(match_offset - window_posn) > lzx->ref_data_size)
{
D(("match offset beyond LZX stream"))
return lzx->error = MSPACK_ERR_DECRUNCH;
}
/* j = length from match offset to end of window */
j = match_offset - window_posn;
if (j > (int) lzx->window_size) {
D(("match offset beyond window boundaries"))
return lzx->error = MSPACK_ERR_DECRUNCH;
}
runsrc = &window[lzx->window_size - j];
if (j < i) {
/* if match goes over the window edge, do two copy runs */
i -= j; while (j-- > 0) *rundest++ = *runsrc++;
runsrc = window;
}
while (i-- > 0) *rundest++ = *runsrc++;
}
else {
runsrc = rundest - match_offset;
while (i-- > 0) *rundest++ = *runsrc++;
}
this_run -= match_length;
window_posn += match_length;
}
} /* while (this_run > 0) */
break;
case LZX_BLOCKTYPE_ALIGNED:
while (this_run > 0) {
READ_HUFFSYM(MAINTREE, main_element);
if (main_element < LZX_NUM_CHARS) {
/* literal: 0 to LZX_NUM_CHARS-1 */
window[window_posn++] = main_element;
this_run--;
}
else {
/* match: LZX_NUM_CHARS + ((slot<<3) | length_header (3 bits)) */
main_element -= LZX_NUM_CHARS;
/* get match length */
match_length = main_element & LZX_NUM_PRIMARY_LENGTHS;
if (match_length == LZX_NUM_PRIMARY_LENGTHS) {
if (lzx->LENGTH_empty) {
D(("LENGTH symbol needed but tree is empty"))
return lzx->error = MSPACK_ERR_DECRUNCH;
}
READ_HUFFSYM(LENGTH, length_footer);
match_length += length_footer;
}
match_length += LZX_MIN_MATCH;
/* get match offset */
switch ((match_offset = (main_element >> 3))) {
case 0: match_offset = R0; break;
case 1: match_offset = R1; R1 = R0; R0 = match_offset; break;
case 2: match_offset = R2; R2 = R0; R0 = match_offset; break;
default:
extra = (match_offset >= 36) ? 17 : extra_bits[match_offset];
match_offset = position_base[match_offset] - 2;
if (extra > 3) {
/* verbatim and aligned bits */
extra -= 3;
READ_BITS(verbatim_bits, extra);
match_offset += (verbatim_bits << 3);
READ_HUFFSYM(ALIGNED, aligned_bits);
match_offset += aligned_bits;
}
else if (extra == 3) {
/* aligned bits only */
READ_HUFFSYM(ALIGNED, aligned_bits);
match_offset += aligned_bits;
}
else if (extra > 0) { /* extra==1, extra==2 */
/* verbatim bits only */
READ_BITS(verbatim_bits, extra);
match_offset += verbatim_bits;
}
else /* extra == 0 */ {
/* ??? not defined in LZX specification! */
match_offset = 1;
}
/* update repeated offset LRU queue */
R2 = R1; R1 = R0; R0 = match_offset;
}
/* LZX DELTA uses max match length to signal even longer match */
if (match_length == LZX_MAX_MATCH && lzx->is_delta) {
int extra_len = 0;
ENSURE_BITS(3); /* 4 entry huffman tree */
if (PEEK_BITS(1) == 0) {
REMOVE_BITS(1); /* '0' -> 8 extra length bits */
READ_BITS(extra_len, 8);
}
else if (PEEK_BITS(2) == 2) {
REMOVE_BITS(2); /* '10' -> 10 extra length bits + 0x100 */
READ_BITS(extra_len, 10);
extra_len += 0x100;
}
else if (PEEK_BITS(3) == 6) {
REMOVE_BITS(3); /* '110' -> 12 extra length bits + 0x500 */
READ_BITS(extra_len, 12);
extra_len += 0x500;
}
else {
REMOVE_BITS(3); /* '111' -> 15 extra length bits */
READ_BITS(extra_len, 15);
}
match_length += extra_len;
}
if ((window_posn + match_length) > lzx->window_size) {
D(("match ran over window wrap"))
return lzx->error = MSPACK_ERR_DECRUNCH;
}
/* copy match */
rundest = &window[window_posn];
i = match_length;
/* does match offset wrap the window? */
if (match_offset > window_posn) {
if (match_offset > lzx->offset &&
(match_offset - window_posn) > lzx->ref_data_size)
{
D(("match offset beyond LZX stream"))
return lzx->error = MSPACK_ERR_DECRUNCH;
}
/* j = length from match offset to end of window */
j = match_offset - window_posn;
if (j > (int) lzx->window_size) {
D(("match offset beyond window boundaries"))
return lzx->error = MSPACK_ERR_DECRUNCH;
}
runsrc = &window[lzx->window_size - j];
if (j < i) {
/* if match goes over the window edge, do two copy runs */
i -= j; while (j-- > 0) *rundest++ = *runsrc++;
runsrc = window;
}
while (i-- > 0) *rundest++ = *runsrc++;
}
else {
runsrc = rundest - match_offset;
while (i-- > 0) *rundest++ = *runsrc++;
}
this_run -= match_length;
window_posn += match_length;
}
} /* while (this_run > 0) */
break;
case LZX_BLOCKTYPE_UNCOMPRESSED:
/* as this_run is limited not to wrap a frame, this also means it
* won't wrap the window (as the window is a multiple of 32k) */
if (window_posn + this_run > lzx->window_size) {
D(("match ran over window boundary"))
return lzx->error = MSPACK_ERR_DECRUNCH;
}
rundest = &window[window_posn];
window_posn += this_run;
while (this_run > 0) {
if ((i = i_end - i_ptr) == 0) {
READ_IF_NEEDED;
}
else {
if (i > this_run) i = this_run;
lzx->sys->copy(i_ptr, rundest, (size_t) i);
rundest += i;
i_ptr += i;
this_run -= i;
}
}
break;
default:
return lzx->error = MSPACK_ERR_DECRUNCH; /* might as well */
}
/* did the final match overrun our desired this_run length? */
if (this_run < 0) {
if ((unsigned int)(-this_run) > lzx->block_remaining) {
D(("overrun went past end of block by %d (%d remaining)",
-this_run, lzx->block_remaining ))
return lzx->error = MSPACK_ERR_DECRUNCH;
}
lzx->block_remaining -= -this_run;
}
} /* while (bytes_todo > 0) */
/* streams don't extend over frame boundaries */
if ((window_posn - lzx->frame_posn) != frame_size) {
D(("decode beyond output frame limits! %d != %d",
window_posn - lzx->frame_posn, frame_size))
return lzx->error = MSPACK_ERR_DECRUNCH;
}
/* re-align input bitstream */
if (bits_left > 0) ENSURE_BITS(16);
if (bits_left & 15) REMOVE_BITS(bits_left & 15);
/* check that we've used all of the previous frame first */
if (lzx->o_ptr != lzx->o_end) {
D(("%ld avail bytes, new %d frame",
(long)(lzx->o_end - lzx->o_ptr), frame_size))
return lzx->error = MSPACK_ERR_DECRUNCH;
}
/* does this intel block _really_ need decoding? */
if (lzx->intel_started && lzx->intel_filesize &&
(lzx->frame <= 32768) && (frame_size > 10))
{
unsigned char *data = &lzx->e8_buf[0];
unsigned char *dataend = &lzx->e8_buf[frame_size - 10];
signed int curpos = lzx->intel_curpos;
signed int filesize = lzx->intel_filesize;
signed int abs_off, rel_off;
/* copy e8 block to the e8 buffer and tweak if needed */
lzx->o_ptr = data;
lzx->sys->copy(&lzx->window[lzx->frame_posn], data, frame_size);
while (data < dataend) {
if (*data++ != 0xE8) { curpos++; continue; }
abs_off = data[0] | (data[1]<<8) | (data[2]<<16) | (data[3]<<24);
if ((abs_off >= -curpos) && (abs_off < filesize)) {
rel_off = (abs_off >= 0) ? abs_off - curpos : abs_off + filesize;
data[0] = (unsigned char) rel_off;
data[1] = (unsigned char) (rel_off >> 8);
data[2] = (unsigned char) (rel_off >> 16);
data[3] = (unsigned char) (rel_off >> 24);
}
data += 4;
curpos += 5;
}
lzx->intel_curpos += frame_size;
}
else {
lzx->o_ptr = &lzx->window[lzx->frame_posn];
if (lzx->intel_filesize) lzx->intel_curpos += frame_size;
}
lzx->o_end = &lzx->o_ptr[frame_size];
/* write a frame */
i = (out_bytes < (off_t)frame_size) ? (unsigned int)out_bytes : frame_size;
if (lzx->sys->write(lzx->output, lzx->o_ptr, i) != i) {
return lzx->error = MSPACK_ERR_WRITE;
}
lzx->o_ptr += i;
lzx->offset += i;
out_bytes -= i;
/* advance frame start position */
lzx->frame_posn += frame_size;
lzx->frame++;
/* wrap window / frame position pointers */
if (window_posn == lzx->window_size) window_posn = 0;
if (lzx->frame_posn == lzx->window_size) lzx->frame_posn = 0;
} /* while (lzx->frame < end_frame) */
if (out_bytes) {
D(("bytes left to output"))
return lzx->error = MSPACK_ERR_DECRUNCH;
}
/* store local state */
STORE_BITS;
lzx->window_posn = window_posn;
lzx->R0 = R0;
lzx->R1 = R1;
lzx->R2 = R2;
return MSPACK_ERR_OK;
}
void lzxd_free(struct lzxd_stream *lzx) {
struct mspack_system *sys;
if (lzx) {
sys = lzx->sys;
if(lzx->inbuf)
sys->free(lzx->inbuf);
if(lzx->window)
sys->free(lzx->window);
sys->free(lzx);
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3187_0 |
crossvul-cpp_data_good_525_1 | /*
* GPAC - Multimedia Framework C SDK
*
* Authors: Jean Le Feuvre
* Copyright (c) Telecom ParisTech 2005-2012
* All rights reserved
*
* This file is part of GPAC / command-line client
*
* GPAC is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* GPAC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
/*includes both terminal and od browser*/
#include <gpac/terminal.h>
#include <gpac/term_info.h>
#include <gpac/constants.h>
#include <gpac/events.h>
#include <gpac/media_tools.h>
#include <gpac/options.h>
#include <gpac/modules/service.h>
#include <gpac/avparse.h>
#include <gpac/network.h>
#include <gpac/utf.h>
#include <time.h>
/*ISO 639 languages*/
#include <gpac/iso639.h>
//FIXME we need a plugin for playlists
#include <gpac/internal/terminal_dev.h>
#ifndef WIN32
#include <dlfcn.h>
#include <pwd.h>
#include <unistd.h>
#if defined(__DARWIN__) || defined(__APPLE__)
#include <sys/types.h>
#include <sys/stat.h>
void carbon_init();
void carbon_uninit();
#endif
#else
#include <windows.h> /*for GetModuleFileName*/
#endif //WIN32
/*local prototypes*/
void PrintWorldInfo(GF_Terminal *term);
void ViewOD(GF_Terminal *term, u32 OD_ID, u32 number, const char *URL);
void PrintODList(GF_Terminal *term, GF_ObjectManager *root_odm, u32 num, u32 indent, char *root_name);
void ViewODs(GF_Terminal *term, Bool show_timing);
void PrintGPACConfig();
static u32 gui_mode = 0;
static Bool restart = GF_FALSE;
static Bool reload = GF_FALSE;
Bool no_prog = 0;
#if defined(__DARWIN__) || defined(__APPLE__)
//we keep no decoder thread because of JS_GC deadlocks between threads ...
static u32 threading_flags = GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_NO_DECODER_THREAD;
#define VK_MOD GF_KEY_MOD_ALT
#else
static u32 threading_flags = 0;
#define VK_MOD GF_KEY_MOD_CTRL
#endif
static Bool no_audio = GF_FALSE;
static Bool term_step = GF_FALSE;
static Bool no_regulation = GF_FALSE;
static u32 bench_mode = 0;
static u32 bench_mode_start = 0;
static u32 bench_buffer = 0;
static Bool eos_seen = GF_FALSE;
static Bool addon_visible = GF_TRUE;
Bool is_connected = GF_FALSE;
Bool startup_file = GF_FALSE;
GF_User user;
GF_Terminal *term;
u64 Duration;
GF_Err last_error = GF_OK;
static Bool enable_add_ons = GF_TRUE;
static Fixed playback_speed = FIX_ONE;
static s32 request_next_playlist_item = GF_FALSE;
FILE *playlist = NULL;
static Bool readonly_playlist = GF_FALSE;
static GF_Config *cfg_file;
static u32 display_rti = 0;
static Bool Run;
static Bool CanSeek = GF_FALSE;
static char the_url[GF_MAX_PATH];
static char pl_path[GF_MAX_PATH];
static Bool no_mime_check = GF_TRUE;
static Bool be_quiet = GF_FALSE;
static u64 log_time_start = 0;
static Bool log_utc_time = GF_FALSE;
static Bool loop_at_end = GF_FALSE;
static u32 forced_width=0;
static u32 forced_height=0;
/*windowless options*/
u32 align_mode = 0;
u32 init_w = 0;
u32 init_h = 0;
u32 last_x, last_y;
Bool right_down = GF_FALSE;
void dump_frame(GF_Terminal *term, char *rad_path, u32 dump_type, u32 frameNum);
enum
{
DUMP_NONE = 0,
DUMP_AVI = 1,
DUMP_BMP = 2,
DUMP_PNG = 3,
DUMP_RAW = 4,
DUMP_SHA1 = 5,
//DuMP flags
DUMP_DEPTH_ONLY = 1<<16,
DUMP_RGB_DEPTH = 1<<17,
DUMP_RGB_DEPTH_SHAPE = 1<<18
};
Bool dump_file(char *the_url, char *out_url, u32 dump_mode, Double fps, u32 width, u32 height, Float scale, u32 *times, u32 nb_times);
static Bool shell_visible = GF_TRUE;
void hide_shell(u32 cmd_type)
{
#if defined(WIN32) && !defined(_WIN32_WCE)
typedef HWND (WINAPI *GetConsoleWindowT)(void);
HMODULE hk32 = GetModuleHandle("kernel32.dll");
GetConsoleWindowT GetConsoleWindow = (GetConsoleWindowT ) GetProcAddress(hk32,"GetConsoleWindow");
if (cmd_type==0) {
ShowWindow( GetConsoleWindow(), SW_SHOW);
shell_visible = GF_TRUE;
}
else if (cmd_type==1) {
ShowWindow( GetConsoleWindow(), SW_HIDE);
shell_visible = GF_FALSE;
}
else if (cmd_type==2) PostMessage(GetConsoleWindow(), WM_CLOSE, 0, 0);
#endif
}
void send_open_url(const char *url)
{
GF_Event evt;
memset(&evt, 0, sizeof(GF_Event));
evt.type = GF_EVENT_NAVIGATE;
evt.navigate.to_url = url;
gf_term_send_event(term, &evt);
}
void PrintUsage()
{
fprintf(stderr, "Usage MP4Client [options] [filename]\n"
"\t-c fileName: user-defined configuration file. Also works with -cfg\n"
#ifdef GPAC_MEMORY_TRACKING
"\t-mem-track: enables memory tracker\n"
"\t-mem-track-stack: enables memory tracker with stack dumping\n"
#endif
"\t-rti fileName: logs run-time info (FPS, CPU, Mem usage) to file\n"
"\t-rtix fileName: same as -rti but driven by GPAC logs\n"
"\t-quiet: removes script message, buffering and downloading status\n"
"\t-strict-error: exit when the player reports its first error\n"
"\t-opt option: Overrides an option in the configuration file. String format is section:key=value. \n"
"\t \"section:key=null\" removes the key\n"
"\t \"section:*=null\" removes the section\n"
"\t-conf option: Same as -opt but does not start player.\n"
"\t-log-file file: sets output log file. Also works with -lf\n"
"\t-logs log_args: sets log tools and levels, formatted as a ':'-separated list of toolX[:toolZ]@levelX\n"
"\t levelX can be one of:\n"
"\t \"quiet\" : skip logs\n"
"\t \"error\" : logs only error messages\n"
"\t \"warning\" : logs error+warning messages\n"
"\t \"info\" : logs error+warning+info messages\n"
"\t \"debug\" : logs all messages\n"
"\t toolX can be one of:\n"
"\t \"core\" : libgpac core\n"
"\t \"coding\" : bitstream formats (audio, video, scene)\n"
"\t \"container\" : container formats (ISO File, MPEG-2 TS, AVI, ...)\n"
"\t \"network\" : network data exept RTP trafic\n"
"\t \"rtp\" : rtp trafic\n"
"\t \"author\" : authoring tools (hint, import, export)\n"
"\t \"sync\" : terminal sync layer\n"
"\t \"codec\" : terminal codec messages\n"
"\t \"parser\" : scene parsers (svg, xmt, bt) and other\n"
"\t \"media\" : terminal media object management\n"
"\t \"scene\" : scene graph and scene manager\n"
"\t \"script\" : scripting engine messages\n"
"\t \"interact\" : interaction engine (events, scripts, etc)\n"
"\t \"smil\" : SMIL timing engine\n"
"\t \"compose\" : composition engine (2D, 3D, etc)\n"
"\t \"mmio\" : Audio/Video HW I/O management\n"
"\t \"rti\" : various run-time stats\n"
"\t \"cache\" : HTTP cache subsystem\n"
"\t \"audio\" : Audio renderer and mixers\n"
#ifdef GPAC_MEMORY_TRACKING
"\t \"mem\" : GPAC memory tracker\n"
#endif
#ifndef GPAC_DISABLE_DASH_CLIENT
"\t \"dash\" : HTTP streaming logs\n"
#endif
"\t \"module\" : GPAC modules debugging\n"
"\t \"mutex\" : mutex\n"
"\t \"all\" : all tools logged - other tools can be specified afterwards.\n"
"\tThe special value \"ncl\" disables color logs.\n"
"\n"
"\t-log-clock or -lc : logs time in micro sec since start time of GPAC before each log line.\n"
"\t-log-utc or -lu : logs UTC time in ms before each log line.\n"
"\t-ifce IPIFCE : Sets default Multicast interface\n"
"\t-size WxH: specifies visual size (default: scene size)\n"
#if defined(__DARWIN__) || defined(__APPLE__)
"\t-thread: enables thread usage for terminal and compositor \n"
#else
"\t-no-thread: disables thread usage (except for audio)\n"
#endif
"\t-no-cthread: disables compositor thread (iOS and Android mode)\n"
"\t-no-audio: disables audio \n"
"\t-no-wnd: uses windowless mode (Win32 only)\n"
"\t-no-back: uses transparent background for output window when no background is specified (Win32 only)\n"
"\t-align vh: specifies v and h alignment for windowless mode\n"
"\t possible v values: t(op), m(iddle), b(ottom)\n"
"\t possible h values: l(eft), m(iddle), r(ight)\n"
"\t default alignment is top-left\n"
"\t default alignment is top-left\n"
"\t-pause: pauses at first frame\n"
"\t-play-from T: starts from T seconds in media\n"
"\t-speed S: starts with speed S\n"
"\t-loop: loops presentation\n"
"\t-no-regulation: disables framerate regulation\n"
"\t-bench: disable a/v output and bench source decoding (as fast as possible)\n"
"\t-vbench: disable audio output, video sync bench source decoding/display (as fast as possible)\n"
"\t-sbench: disable all decoders and bench systems layer (as fast as possible)\n"
"\t-fs: starts in fullscreen mode\n"
"\t-views v1:.:vN: creates an auto-stereo scene of N views. vN can be any type of URL supported by GPAC.\n"
"\t in this mode, URL argument of GPAC is ignored, GUI as well.\n"
"\t this is equivalent as using views://v1:.:N as an URL.\n"
"\t-mosaic v1:.:vN: creates a mosaic of N views. vN can be any type of URL supported by GPAC.\n"
"\t in this mode, URL argument of GPAC is ignored.\n"
"\t this is equivalent as using mosaic://v1:.:N as an URL.\n"
"\n"
"\t-exit: automatically exits when presentation is over\n"
"\t-run-for TIME: runs for TIME seconds and exits\n"
"\t-service ID: auto-tune to given service ID in a multiplex\n"
"\t-noprog: disable progress report\n"
"\t-no-save: disable saving config file on exit\n"
"\t-no-addon: disable automatic loading of media addons declared in source URL\n"
"\t-gui: starts in GUI mode. The GUI is indicated in GPAC config, section General, by the key [StartupFile]\n"
"\t-ntp-shift T: shifts NTP clock of T (signed int) milliseconds\n"
"\n"
"Dumper Options (times is a formated as start-end, with start being sec, h:m:s:f/fps or h:m:s:ms):\n"
"\t-bmp [times]: dumps given frames to bmp\n"
"\t-png [times]: dumps given frames to png\n"
"\t-raw [times]: dumps given frames to raw\n"
"\t-avi [times]: dumps given file to raw avi\n"
"\t-sha [times]: dumps given file to raw SHA-1 (1 hash per frame)\n"
"\r-out filename: name of the output file\n"
"\t-rgbds: dumps the RGBDS pixel format texture\n"
"\t with -avi [times]: dumps an rgbds-format .avi\n"
"\t-rgbd: dumps the RGBD pixel format texture\n"
"\t with -avi [times]: dumps an rgbd-format .avi\n"
"\t-depth: dumps depthmap (z-buffer) frames\n"
"\t with -avi [times]: dumps depthmap in grayscale .avi\n"
"\t with -bmp: dumps depthmap in grayscale .bmp\n"
"\t with -png: dumps depthmap in grayscale .png\n"
"\t-fps FPS: specifies frame rate for AVI dumping (default: %f)\n"
"\t-scale s: scales the visual size (default: 1)\n"
"\t-fill: uses fill aspect ratio for dumping (default: none)\n"
"\t-show: shows window while dumping (default: no)\n"
"\n"
"\t-uncache: Revert all cached items to their original name and location. Does not start player.\n"
"\n"
"\t-help: shows this screen\n"
"\n"
"MP4Client - GPAC command line player and dumper - version "GPAC_FULL_VERSION"\n"
"(c) Telecom ParisTech 2000-2018 - Licence LGPL v2\n"
"GPAC Configuration: " GPAC_CONFIGURATION "\n"
"Features: %s\n",
GF_IMPORT_DEFAULT_FPS,
gpac_features()
);
}
void PrintHelp()
{
fprintf(stderr, "MP4Client command keys:\n"
"\tq: quit\n"
"\tX: kill\n"
"\to: connect to the specified URL\n"
"\tO: connect to the specified playlist\n"
"\tN: switch to the next URL in the playlist. Also works with \\n\n"
"\tP: jumps to a given number ahead in the playlist\n"
"\tr: reload current presentation\n"
"\tD: disconnects the current presentation\n"
"\tG: selects object or service ID\n"
"\n"
"\tp: play/pause the presentation\n"
"\ts: step one frame ahead\n"
"\tz: seek into presentation by percentage\n"
"\tT: seek into presentation by time\n"
"\tt: print current timing\n"
"\n"
"\tu: sends a command (BIFS or LASeR) to the main scene\n"
"\te: evaluates JavaScript code\n"
"\tZ: dumps output video to PNG\n"
"\n"
"\tw: view world info\n"
"\tv: view Object Descriptor list\n"
"\ti: view Object Descriptor info (by ID)\n"
"\tj: view Object Descriptor info (by number)\n"
"\tb: view media objects timing and buffering info\n"
"\tm: view media objects buffering and memory info\n"
"\td: dumps scene graph\n"
"\n"
"\tk: turns stress mode on/off\n"
"\tn: changes navigation mode\n"
"\tx: reset to last active viewpoint\n"
"\n"
"\t3: switch OpenGL on or off for 2D scenes\n"
"\n"
"\t4: forces 4/3 Aspect Ratio\n"
"\t5: forces 16/9 Aspect Ratio\n"
"\t6: forces no Aspect Ratio (always fill screen)\n"
"\t7: forces original Aspect Ratio (default)\n"
"\n"
"\tL: changes to new log level. CF MP4Client usage for possible values\n"
"\tT: select new tools to log. CF MP4Client usage for possible values\n"
"\n"
"\tl: list available modules\n"
"\tc: prints some GPAC configuration info\n"
"\tE: forces reload of GPAC configuration\n"
"\n"
"\tR: toggles run-time info display in window title bar on/off\n"
"\tF: toggle displaying of FPS in stderr on/off\n"
"\tg: print GPAC allocated memory\n"
"\th: print this message\n"
"\n"
"\tEXPERIMENTAL/UNSTABLE OPTIONS\n"
"\tC: Enable Streaming Cache\n"
"\tS: Stops Streaming Cache and save to file\n"
"\tA: Aborts Streaming Cache\n"
"\tM: specifies video cache memory for 2D objects\n"
"\n"
"MP4Client - GPAC command line player - version %s\n"
"GPAC Written by Jean Le Feuvre (c) 2001-2005 - ENST (c) 2005-200X\n",
GPAC_FULL_VERSION
);
}
static void PrintTime(u64 time)
{
u32 ms, h, m, s;
h = (u32) (time / 1000 / 3600);
m = (u32) (time / 1000 / 60 - h*60);
s = (u32) (time / 1000 - h*3600 - m*60);
ms = (u32) (time - (h*3600 + m*60 + s) * 1000);
fprintf(stderr, "%02d:%02d:%02d.%03d", h, m, s, ms);
}
void PrintAVInfo(Bool final);
static u32 rti_update_time_ms = 200;
static FILE *rti_logs = NULL;
static void UpdateRTInfo(const char *legend)
{
GF_SystemRTInfo rti;
/*refresh every second*/
if (!display_rti && !rti_logs) return;
if (!gf_sys_get_rti(rti_update_time_ms, &rti, 0) && !legend)
return;
if (display_rti) {
char szMsg[1024];
if (rti.total_cpu_usage && (bench_mode<2) ) {
sprintf(szMsg, "FPS %02.02f CPU %2d (%02d) Mem %d kB",
gf_term_get_framerate(term, 0), rti.total_cpu_usage, rti.process_cpu_usage, (u32) (rti.gpac_memory / 1024));
} else {
sprintf(szMsg, "FPS %02.02f CPU %02d Mem %d kB",
gf_term_get_framerate(term, 0), rti.process_cpu_usage, (u32) (rti.gpac_memory / 1024) );
}
if (display_rti==2) {
if (bench_mode>=2) {
PrintAVInfo(GF_FALSE);
}
fprintf(stderr, "%s\r", szMsg);
} else {
GF_Event evt;
evt.type = GF_EVENT_SET_CAPTION;
evt.caption.caption = szMsg;
gf_term_user_event(term, &evt);
}
}
if (rti_logs) {
fprintf(rti_logs, "% 8d\t% 8d\t% 8d\t% 4d\t% 8d\t%s",
gf_sys_clock(),
gf_term_get_time_in_ms(term),
rti.total_cpu_usage,
(u32) gf_term_get_framerate(term, 0),
(u32) (rti.gpac_memory / 1024),
legend ? legend : ""
);
if (!legend) fprintf(rti_logs, "\n");
}
}
static void ResetCaption()
{
GF_Event event;
if (display_rti) return;
event.type = GF_EVENT_SET_CAPTION;
if (is_connected) {
char szName[1024];
NetInfoCommand com;
event.caption.caption = NULL;
/*get any service info*/
if (!startup_file && gf_term_get_service_info(term, gf_term_get_root_object(term), &com) == GF_OK) {
strcpy(szName, "");
if (com.track_info) {
char szBuf[10];
sprintf(szBuf, "%02d ", (u32) (com.track_info>>16) );
strcat(szName, szBuf);
}
if (com.artist) {
strcat(szName, com.artist);
strcat(szName, " ");
}
if (com.name) {
strcat(szName, com.name);
strcat(szName, " ");
}
if (com.album) {
strcat(szName, "(");
strcat(szName, com.album);
strcat(szName, ")");
}
if (com.provider) {
strcat(szName, "(");
strcat(szName, com.provider);
strcat(szName, ")");
}
if (strlen(szName)) event.caption.caption = szName;
}
if (!event.caption.caption) {
char *str = strrchr(the_url, '\\');
if (!str) str = strrchr(the_url, '/');
event.caption.caption = str ? str+1 : the_url;
}
} else {
event.caption.caption = "GPAC MP4Client " GPAC_FULL_VERSION;
}
gf_term_user_event(term, &event);
}
#ifdef WIN32
u32 get_sys_col(int idx)
{
u32 res;
DWORD val = GetSysColor(idx);
res = (val)&0xFF;
res<<=8;
res |= (val>>8)&0xFF;
res<<=8;
res |= (val>>16)&0xFF;
return res;
}
#endif
void switch_bench(u32 is_on)
{
bench_mode = is_on;
display_rti = is_on ? 2 : 0;
ResetCaption();
gf_term_set_option(term, GF_OPT_VIDEO_BENCH, is_on);
}
#ifndef WIN32
#include <termios.h>
int getch() {
struct termios old;
struct termios new;
int rc;
if (tcgetattr(0, &old) == -1) {
return -1;
}
new = old;
new.c_lflag &= ~(ICANON | ECHO);
new.c_cc[VMIN] = 1;
new.c_cc[VTIME] = 0;
if (tcsetattr(0, TCSANOW, &new) == -1) {
return -1;
}
rc = getchar();
(void) tcsetattr(0, TCSANOW, &old);
return rc;
}
#else
int getch() {
return getchar();
}
#endif
/**
* Reads a line of input from stdin
* @param line the buffer to fill
* @param maxSize the maximum size of the line to read
* @param showContent boolean indicating if the line read should be printed on stderr or not
*/
static const char * read_line_input(char * line, int maxSize, Bool showContent) {
char read;
int i = 0;
if (fflush( stderr ))
perror("Failed to flush buffer %s");
do {
line[i] = '\0';
if (i >= maxSize - 1)
return line;
read = getch();
if (read == 8 || read == 127) {
if (i > 0) {
fprintf(stderr, "\b \b");
i--;
}
} else if (read > 32) {
fputc(showContent ? read : '*', stderr);
line[i++] = read;
}
fflush(stderr);
} while (read != '\n');
if (!read)
return 0;
return line;
}
static void do_set_speed(Fixed desired_speed)
{
if (gf_term_set_speed(term, desired_speed) == GF_OK) {
playback_speed = desired_speed;
fprintf(stderr, "Playing at %g speed\n", FIX2FLT(playback_speed));
} else {
fprintf(stderr, "Adjusting speed to %g not supported for this content\n", FIX2FLT(desired_speed));
}
}
Bool GPAC_EventProc(void *ptr, GF_Event *evt)
{
if (!term) return 0;
if (gui_mode==1) {
if (evt->type==GF_EVENT_QUIT) {
Run = 0;
} else if (evt->type==GF_EVENT_KEYDOWN) {
switch (evt->key.key_code) {
case GF_KEY_C:
if (evt->key.flags & (GF_KEY_MOD_CTRL|GF_KEY_MOD_ALT)) {
hide_shell(shell_visible ? 1 : 0);
if (shell_visible) gui_mode=2;
}
break;
default:
break;
}
}
return 0;
}
switch (evt->type) {
case GF_EVENT_DURATION:
Duration = (u64) ( 1000 * (s64) evt->duration.duration);
CanSeek = evt->duration.can_seek;
break;
case GF_EVENT_MESSAGE:
{
const char *servName;
if (!evt->message.service || !strcmp(evt->message.service, the_url)) {
servName = "";
} else if (!strnicmp(evt->message.service, "data:", 5)) {
servName = "(embedded data)";
} else {
servName = evt->message.service;
}
if (!evt->message.message) return 0;
if (evt->message.error) {
if (!is_connected) last_error = evt->message.error;
if (evt->message.error==GF_SCRIPT_INFO) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONSOLE, ("%s\n", evt->message.message));
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONSOLE, ("%s %s: %s\n", servName, evt->message.message, gf_error_to_string(evt->message.error)));
}
} else if (!be_quiet)
GF_LOG(GF_LOG_INFO, GF_LOG_CONSOLE, ("%s %s\n", servName, evt->message.message));
}
break;
case GF_EVENT_PROGRESS:
{
char *szTitle = "";
if (evt->progress.progress_type==0) {
szTitle = "Buffer ";
if (bench_mode && (bench_mode!=3) ) {
if (evt->progress.done >= evt->progress.total) bench_buffer = 0;
else bench_buffer = 1 + 100*evt->progress.done / evt->progress.total;
break;
}
}
else if (evt->progress.progress_type==1) {
if (bench_mode) break;
szTitle = "Download ";
}
else if (evt->progress.progress_type==2) szTitle = "Import ";
gf_set_progress(szTitle, evt->progress.done, evt->progress.total);
}
break;
case GF_EVENT_DBLCLICK:
gf_term_set_option(term, GF_OPT_FULLSCREEN, !gf_term_get_option(term, GF_OPT_FULLSCREEN));
return 0;
case GF_EVENT_MOUSEDOWN:
if (evt->mouse.button==GF_MOUSE_RIGHT) {
right_down = 1;
last_x = evt->mouse.x;
last_y = evt->mouse.y;
}
return 0;
case GF_EVENT_MOUSEUP:
if (evt->mouse.button==GF_MOUSE_RIGHT) {
right_down = 0;
last_x = evt->mouse.x;
last_y = evt->mouse.y;
}
return 0;
case GF_EVENT_MOUSEMOVE:
if (right_down && (user.init_flags & GF_TERM_WINDOWLESS) ) {
GF_Event move;
move.move.x = evt->mouse.x - last_x;
move.move.y = last_y-evt->mouse.y;
move.type = GF_EVENT_MOVE;
move.move.relative = 1;
gf_term_user_event(term, &move);
}
return 0;
case GF_EVENT_KEYUP:
switch (evt->key.key_code) {
case GF_KEY_SPACE:
if (evt->key.flags & GF_KEY_MOD_CTRL) switch_bench(!bench_mode);
break;
}
break;
case GF_EVENT_KEYDOWN:
gf_term_process_shortcut(term, evt);
switch (evt->key.key_code) {
case GF_KEY_SPACE:
if (evt->key.flags & GF_KEY_MOD_CTRL) {
/*ignore key repeat*/
if (!bench_mode) switch_bench(!bench_mode);
}
break;
case GF_KEY_PAGEDOWN:
case GF_KEY_MEDIANEXTTRACK:
request_next_playlist_item = 1;
break;
case GF_KEY_MEDIAPREVIOUSTRACK:
break;
case GF_KEY_ESCAPE:
gf_term_set_option(term, GF_OPT_FULLSCREEN, !gf_term_get_option(term, GF_OPT_FULLSCREEN));
break;
case GF_KEY_C:
if (evt->key.flags & (GF_KEY_MOD_CTRL|GF_KEY_MOD_ALT)) {
hide_shell(shell_visible ? 1 : 0);
if (!shell_visible) gui_mode=1;
}
break;
case GF_KEY_F:
if (evt->key.flags & GF_KEY_MOD_CTRL) fprintf(stderr, "Rendering rate: %f FPS\n", gf_term_get_framerate(term, 0));
break;
case GF_KEY_T:
if (evt->key.flags & GF_KEY_MOD_CTRL) fprintf(stderr, "Scene Time: %f \n", gf_term_get_time_in_ms(term)/1000.0);
break;
case GF_KEY_D:
if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_DRAW_MODE, (gf_term_get_option(term, GF_OPT_DRAW_MODE)==GF_DRAW_MODE_DEFER) ? GF_DRAW_MODE_IMMEDIATE : GF_DRAW_MODE_DEFER );
break;
case GF_KEY_4:
if (evt->key.flags & GF_KEY_MOD_CTRL)
gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_4_3);
break;
case GF_KEY_5:
if (evt->key.flags & GF_KEY_MOD_CTRL)
gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_16_9);
break;
case GF_KEY_6:
if (evt->key.flags & GF_KEY_MOD_CTRL)
gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN);
break;
case GF_KEY_7:
if (evt->key.flags & GF_KEY_MOD_CTRL)
gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_KEEP);
break;
case GF_KEY_O:
if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) {
if (gf_term_get_option(term, GF_OPT_MAIN_ADDON)) {
fprintf(stderr, "Resuming to main content\n");
gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_PLAY_LIVE);
} else {
fprintf(stderr, "Main addon not enabled\n");
}
}
break;
case GF_KEY_P:
if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) {
u32 pause_state = gf_term_get_option(term, GF_OPT_PLAY_STATE) ;
fprintf(stderr, "[Status: %s]\n", pause_state ? "Playing" : "Paused");
if ((pause_state == GF_STATE_PAUSED) && (evt->key.flags & GF_KEY_MOD_SHIFT)) {
gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_PLAY_LIVE);
} else {
gf_term_set_option(term, GF_OPT_PLAY_STATE, (pause_state==GF_STATE_PAUSED) ? GF_STATE_PLAYING : GF_STATE_PAUSED);
}
}
break;
case GF_KEY_S:
if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) {
gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_STEP_PAUSE);
fprintf(stderr, "Step time: ");
PrintTime(gf_term_get_time_in_ms(term));
fprintf(stderr, "\n");
}
break;
case GF_KEY_B:
if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected)
ViewODs(term, 1);
break;
case GF_KEY_M:
if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected)
ViewODs(term, 0);
break;
case GF_KEY_H:
if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) {
gf_term_switch_quality(term, 1);
// gf_term_set_option(term, GF_OPT_MULTIVIEW_MODE, 0);
}
break;
case GF_KEY_L:
if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) {
gf_term_switch_quality(term, 0);
// gf_term_set_option(term, GF_OPT_MULTIVIEW_MODE, 1);
}
break;
case GF_KEY_F5:
if (is_connected)
reload = 1;
break;
case GF_KEY_A:
addon_visible = !addon_visible;
gf_term_toggle_addons(term, addon_visible);
break;
case GF_KEY_UP:
if ((evt->key.flags & VK_MOD) && is_connected) {
do_set_speed(playback_speed * 2);
}
break;
case GF_KEY_DOWN:
if ((evt->key.flags & VK_MOD) && is_connected) {
do_set_speed(playback_speed / 2);
}
break;
case GF_KEY_LEFT:
if ((evt->key.flags & VK_MOD) && is_connected) {
do_set_speed(-1 * playback_speed );
}
break;
}
break;
case GF_EVENT_CONNECT:
if (evt->connect.is_connected) {
is_connected = 1;
fprintf(stderr, "Service Connected\n");
eos_seen = GF_FALSE;
if (playback_speed != FIX_ONE)
gf_term_set_speed(term, playback_speed);
} else if (is_connected) {
fprintf(stderr, "Service %s\n", is_connected ? "Disconnected" : "Connection Failed");
is_connected = 0;
Duration = 0;
}
if (init_w && init_h) {
gf_term_set_size(term, init_w, init_h);
}
ResetCaption();
break;
case GF_EVENT_EOS:
eos_seen = GF_TRUE;
if (playlist) {
if (Duration>1500)
request_next_playlist_item = GF_TRUE;
}
else if (loop_at_end) {
restart = 1;
}
break;
case GF_EVENT_SIZE:
if (user.init_flags & GF_TERM_WINDOWLESS) {
GF_Event move;
move.type = GF_EVENT_MOVE;
move.move.align_x = align_mode & 0xFF;
move.move.align_y = (align_mode>>8) & 0xFF;
move.move.relative = 2;
gf_term_user_event(term, &move);
}
break;
case GF_EVENT_SCENE_SIZE:
if (forced_width && forced_height) {
GF_Event size;
size.type = GF_EVENT_SIZE;
size.size.width = forced_width;
size.size.height = forced_height;
gf_term_user_event(term, &size);
}
break;
case GF_EVENT_METADATA:
ResetCaption();
break;
case GF_EVENT_RELOAD:
if (is_connected)
reload = 1;
break;
case GF_EVENT_DROPFILE:
{
u32 i, pos;
/*todo - force playlist mode*/
if (readonly_playlist) {
gf_fclose(playlist);
playlist = NULL;
}
readonly_playlist = 0;
if (!playlist) {
readonly_playlist = 0;
playlist = gf_temp_file_new(NULL);
}
pos = ftell(playlist);
i=0;
while (i<evt->open_file.nb_files) {
if (evt->open_file.files[i] != NULL) {
fprintf(playlist, "%s\n", evt->open_file.files[i]);
}
i++;
}
fseek(playlist, pos, SEEK_SET);
request_next_playlist_item = 1;
}
return 1;
case GF_EVENT_QUIT:
if (evt->message.error) {
fprintf(stderr, "A fatal error was encoutered: %s (%s) - exiting ...\n", evt->message.message ? evt->message.message : "no details", gf_error_to_string(evt->message.error) );
}
Run = 0;
break;
case GF_EVENT_DISCONNECT:
gf_term_disconnect(term);
break;
case GF_EVENT_MIGRATE:
{
}
break;
case GF_EVENT_NAVIGATE_INFO:
if (evt->navigate.to_url) fprintf(stderr, "Go to URL: \"%s\"\r", evt->navigate.to_url);
break;
case GF_EVENT_NAVIGATE:
if (gf_term_is_supported_url(term, evt->navigate.to_url, 1, no_mime_check)) {
strncpy(the_url, evt->navigate.to_url, sizeof(the_url)-1);
the_url[sizeof(the_url) - 1] = 0;
fprintf(stderr, "Navigating to URL %s\n", the_url);
gf_term_navigate_to(term, evt->navigate.to_url);
return 1;
} else {
fprintf(stderr, "Navigation destination not supported\nGo to URL: %s\n", evt->navigate.to_url);
}
break;
case GF_EVENT_SET_CAPTION:
gf_term_user_event(term, evt);
break;
case GF_EVENT_AUTHORIZATION:
{
int maxTries = 1;
assert( evt->type == GF_EVENT_AUTHORIZATION);
assert( evt->auth.user);
assert( evt->auth.password);
assert( evt->auth.site_url);
while ((!strlen(evt->auth.user) || !strlen(evt->auth.password)) && (maxTries--) >= 0) {
fprintf(stderr, "**** Authorization required for site %s ****\n", evt->auth.site_url);
fprintf(stderr, "login : ");
read_line_input(evt->auth.user, 50, 1);
fprintf(stderr, "\npassword: ");
read_line_input(evt->auth.password, 50, 0);
fprintf(stderr, "*********\n");
}
if (maxTries < 0) {
fprintf(stderr, "**** No User or password has been filled, aborting ***\n");
return 0;
}
return 1;
}
case GF_EVENT_ADDON_DETECTED:
if (enable_add_ons) {
fprintf(stderr, "Media Addon %s detected - enabling it\n", evt->addon_connect.addon_url);
addon_visible = 1;
}
return enable_add_ons;
}
return 0;
}
void list_modules(GF_ModuleManager *modules)
{
u32 i;
fprintf(stderr, "\rAvailable modules:\n");
for (i=0; i<gf_modules_get_count(modules); i++) {
char *str = (char *) gf_modules_get_file_name(modules, i);
if (str) fprintf(stderr, "\t%s\n", str);
}
fprintf(stderr, "\n");
}
void set_navigation()
{
GF_Err e;
char nav;
u32 type = gf_term_get_option(term, GF_OPT_NAVIGATION_TYPE);
e = GF_OK;
fflush(stdin);
if (!type) {
fprintf(stderr, "Content/compositor doesn't allow user-selectable navigation\n");
} else if (type==1) {
fprintf(stderr, "Select Navigation (\'N\'one, \'E\'xamine, \'S\'lide): ");
nav = getch();
if (nav=='N') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_NONE);
else if (nav=='E') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_EXAMINE);
else if (nav=='S') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_SLIDE);
else fprintf(stderr, "Unknown selector \'%c\' - only \'N\',\'E\',\'S\' allowed\n", nav);
} else if (type==2) {
fprintf(stderr, "Select Navigation (\'N\'one, \'W\'alk, \'F\'ly, \'E\'xamine, \'P\'an, \'S\'lide, \'G\'ame, \'V\'R, \'O\'rbit): ");
nav = getch();
if (nav=='N') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_NONE);
else if (nav=='W') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_WALK);
else if (nav=='F') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_FLY);
else if (nav=='E') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_EXAMINE);
else if (nav=='P') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_PAN);
else if (nav=='S') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_SLIDE);
else if (nav=='G') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_GAME);
else if (nav=='O') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_ORBIT);
else if (nav=='V') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_VR);
else fprintf(stderr, "Unknown selector %c - only \'N\',\'W\',\'F\',\'E\',\'P\',\'S\',\'G\', \'V\', \'O\' allowed\n", nav);
}
if (e) fprintf(stderr, "Error setting mode: %s\n", gf_error_to_string(e));
}
static Bool get_time_list(char *arg, u32 *times, u32 *nb_times)
{
char *str;
Float var;
Double sec;
u32 h, m, s, ms, f, fps;
if (!arg || (arg[0]=='-') || !isdigit(arg[0])) return 0;
/*SMPTE time code*/
if (strchr(arg, ':') && strchr(arg, ';') && strchr(arg, '/')) {
if (sscanf(arg, "%02ud:%02ud:%02ud;%02ud/%02ud", &h, &m, &s, &f, &fps)==5) {
sec = 0;
if (fps) sec = ((Double)f) / fps;
sec += 3600*h + 60*m + s;
times[*nb_times] = (u32) (1000*sec);
(*nb_times) ++;
return 1;
}
}
while (arg) {
str = strchr(arg, '-');
if (str) str[0] = 0;
/*HH:MM:SS:MS time code*/
if (strchr(arg, ':') && (sscanf(arg, "%u:%u:%u:%u", &h, &m, &s, &ms)==4)) {
sec = ms;
sec /= 1000;
sec += 3600*h + 60*m + s;
times[*nb_times] = (u32) (1000*sec);
(*nb_times) ++;
} else if (sscanf(arg, "%f", &var)==1) {
sec = atof(arg);
times[*nb_times] = (u32) (1000*sec);
(*nb_times) ++;
}
if (!str) break;
str[0] = '-';
arg = str+1;
}
return 1;
}
static u64 last_log_time=0;
static void on_gpac_log(void *cbk, GF_LOG_Level ll, GF_LOG_Tool lm, const char *fmt, va_list list)
{
FILE *logs = cbk ? cbk : stderr;
if (rti_logs && (lm & GF_LOG_RTI)) {
char szMsg[2048];
vsprintf(szMsg, fmt, list);
UpdateRTInfo(szMsg + 6 /*"[RTI] "*/);
} else {
if (log_time_start) {
u64 now = gf_sys_clock_high_res();
fprintf(logs, "At "LLD" (diff %d) - ", now - log_time_start, (u32) (now - last_log_time) );
last_log_time = now;
}
if (log_utc_time) {
u64 utc_clock = gf_net_get_utc() ;
time_t secs = utc_clock/1000;
struct tm t;
t = *gmtime(&secs);
fprintf(logs, "UTC %d-%02d-%02dT%02d:%02d:%02dZ (TS "LLU") - ", 1900+t.tm_year, t.tm_mon+1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, utc_clock);
}
vfprintf(logs, fmt, list);
fflush(logs);
}
}
static void init_rti_logs(char *rti_file, char *url, Bool use_rtix)
{
if (rti_logs) gf_fclose(rti_logs);
rti_logs = gf_fopen(rti_file, "wt");
if (rti_logs) {
fprintf(rti_logs, "!! GPAC RunTime Info ");
if (url) fprintf(rti_logs, "for file %s", url);
fprintf(rti_logs, " !!\n");
fprintf(rti_logs, "SysTime(ms)\tSceneTime(ms)\tCPU\tFPS\tMemory(kB)\tObservation\n");
/*turn on RTI loging*/
if (use_rtix) {
gf_log_set_callback(NULL, on_gpac_log);
gf_log_set_tool_level(GF_LOG_RTI, GF_LOG_DEBUG);
GF_LOG(GF_LOG_DEBUG, GF_LOG_RTI, ("[RTI] System state when enabling log\n"));
} else if (log_time_start) {
log_time_start = gf_sys_clock_high_res();
}
}
}
void set_cfg_option(char *opt_string)
{
char *sep, *sep2, szSec[1024], szKey[1024], szVal[1024];
sep = strchr(opt_string, ':');
if (!sep) {
fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string);
return;
}
{
const size_t sepIdx = sep - opt_string;
if (sepIdx >= sizeof(szSec)) {
fprintf(stderr, "Badly formatted option %s - Section name is too long\n", opt_string);
return;
}
strncpy(szSec, opt_string, sepIdx);
szSec[sepIdx] = 0;
}
sep ++;
sep2 = strchr(sep, '=');
if (!sep2) {
fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string);
return;
}
{
const size_t sepIdx = sep2 - sep;
if (sepIdx >= sizeof(szKey)) {
fprintf(stderr, "Badly formatted option %s - key name is too long\n", opt_string);
return;
}
strncpy(szKey, sep, sepIdx);
szKey[sepIdx] = 0;
if (strlen(sep2 + 1) >= sizeof(szVal)) {
fprintf(stderr, "Badly formatted option %s - value is too long\n", opt_string);
return;
}
strcpy(szVal, sep2+1);
}
if (!stricmp(szKey, "*")) {
if (stricmp(szVal, "null")) {
fprintf(stderr, "Badly formatted option %s - expected Section:*=null\n", opt_string);
return;
}
gf_cfg_del_section(cfg_file, szSec);
return;
}
if (!stricmp(szVal, "null")) {
szVal[0]=0;
}
gf_cfg_set_key(cfg_file, szSec, szKey, szVal[0] ? szVal : NULL);
}
Bool revert_cache_file(void *cbck, char *item_name, char *item_path, GF_FileEnumInfo *file_info)
{
const char *url;
char *sep;
GF_Config *cached;
if (strncmp(item_name, "gpac_cache_", 11)) return GF_FALSE;
cached = gf_cfg_new(NULL, item_path);
url = gf_cfg_get_key(cached, "cache", "url");
if (url) url = strstr(url, "://");
if (url) {
u32 i, len, dir_len=0, k=0;
char *dst_name;
sep = strstr(item_path, "gpac_cache_");
if (sep) {
sep[0] = 0;
dir_len = (u32) strlen(item_path);
sep[0] = 'g';
}
url+=3;
len = (u32) strlen(url);
dst_name = gf_malloc(len+dir_len+1);
memset(dst_name, 0, len+dir_len+1);
strncpy(dst_name, item_path, dir_len);
k=dir_len;
for (i=0; i<len; i++) {
dst_name[k] = url[i];
if (dst_name[k]==':') dst_name[k]='_';
else if (dst_name[k]=='/') {
if (!gf_dir_exists(dst_name))
gf_mkdir(dst_name);
}
k++;
}
sep = strrchr(item_path, '.');
if (sep) {
sep[0]=0;
if (gf_file_exists(item_path)) {
gf_move_file(item_path, dst_name);
}
sep[0]='.';
}
gf_free(dst_name);
}
gf_cfg_del(cached);
gf_delete_file(item_path);
return GF_FALSE;
}
void do_flatten_cache(const char *cache_dir)
{
gf_enum_directory(cache_dir, GF_FALSE, revert_cache_file, NULL, "*.txt");
}
#ifdef WIN32
#include <wincon.h>
#endif
static void progress_quiet(const void *cbck, const char *title, u64 done, u64 total) { }
int mp4client_main(int argc, char **argv)
{
char c;
const char *str;
int ret_val = 0;
u32 i, times[100], nb_times, dump_mode;
u32 simulation_time_in_ms = 0;
u32 initial_service_id = 0;
Bool auto_exit = GF_FALSE;
Bool logs_set = GF_FALSE;
Bool start_fs = GF_FALSE;
Bool use_rtix = GF_FALSE;
Bool pause_at_first = GF_FALSE;
Bool no_cfg_save = GF_FALSE;
Bool is_cfg_only = GF_FALSE;
Double play_from = 0;
#ifdef GPAC_MEMORY_TRACKING
GF_MemTrackerType mem_track = GF_MemTrackerNone;
#endif
Double fps = GF_IMPORT_DEFAULT_FPS;
Bool fill_ar, visible, do_uncache, has_command;
char *url_arg, *out_arg, *the_cfg, *rti_file, *views, *mosaic;
FILE *logfile = NULL;
Float scale = 1;
#ifndef WIN32
dlopen(NULL, RTLD_NOW|RTLD_GLOBAL);
#endif
/*by default use current dir*/
strcpy(the_url, ".");
memset(&user, 0, sizeof(GF_User));
dump_mode = DUMP_NONE;
fill_ar = visible = do_uncache = has_command = GF_FALSE;
url_arg = out_arg = the_cfg = rti_file = views = mosaic = NULL;
nb_times = 0;
times[0] = 0;
/*first locate config file if specified*/
for (i=1; i<(u32) argc; i++) {
char *arg = argv[i];
if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) {
the_cfg = argv[i+1];
i++;
}
else if (!strcmp(arg, "-mem-track") || !strcmp(arg, "-mem-track-stack")) {
#ifdef GPAC_MEMORY_TRACKING
mem_track = !strcmp(arg, "-mem-track-stack") ? GF_MemTrackerBackTrace : GF_MemTrackerSimple;
#else
fprintf(stderr, "WARNING - GPAC not compiled with Memory Tracker - ignoring \"%s\"\n", arg);
#endif
} else if (!strcmp(arg, "-gui")) {
gui_mode = 1;
} else if (!strcmp(arg, "-guid")) {
gui_mode = 2;
} else if (!strcmp(arg, "-h") || !strcmp(arg, "-help")) {
PrintUsage();
return 0;
}
}
#ifdef GPAC_MEMORY_TRACKING
gf_sys_init(mem_track);
#else
gf_sys_init(GF_MemTrackerNone);
#endif
gf_sys_set_args(argc, (const char **) argv);
cfg_file = gf_cfg_init(the_cfg, NULL);
if (!cfg_file) {
fprintf(stderr, "Error: Configuration File not found\n");
return 1;
}
/*if logs are specified, use them*/
if (gf_log_set_tools_levels( gf_cfg_get_key(cfg_file, "General", "Logs") ) != GF_OK) {
return 1;
}
if( gf_cfg_get_key(cfg_file, "General", "Logs") != NULL ) {
logs_set = GF_TRUE;
}
if (!gui_mode) {
str = gf_cfg_get_key(cfg_file, "General", "ForceGUI");
if (str && !strcmp(str, "yes")) gui_mode = 1;
}
for (i=1; i<(u32) argc; i++) {
char *arg = argv[i];
if (!strcmp(arg, "-rti")) {
rti_file = argv[i+1];
i++;
} else if (!strcmp(arg, "-rtix")) {
rti_file = argv[i+1];
i++;
use_rtix = GF_TRUE;
} else if (!stricmp(arg, "-size")) {
/*usage of %ud breaks sscanf on MSVC*/
if (sscanf(argv[i+1], "%dx%d", &forced_width, &forced_height) != 2) {
forced_width = forced_height = 0;
}
i++;
} else if (!strcmp(arg, "-quiet")) {
be_quiet = 1;
} else if (!strcmp(arg, "-strict-error")) {
gf_log_set_strict_error(1);
} else if (!strcmp(arg, "-log-file") || !strcmp(arg, "-lf")) {
logfile = gf_fopen(argv[i+1], "wt");
gf_log_set_callback(logfile, on_gpac_log);
i++;
} else if (!strcmp(arg, "-logs") ) {
if (gf_log_set_tools_levels(argv[i+1]) != GF_OK) {
return 1;
}
logs_set = GF_TRUE;
i++;
} else if (!strcmp(arg, "-log-clock") || !strcmp(arg, "-lc")) {
log_time_start = 1;
} else if (!strcmp(arg, "-log-utc") || !strcmp(arg, "-lu")) {
log_utc_time = 1;
}
#if defined(__DARWIN__) || defined(__APPLE__)
else if (!strcmp(arg, "-thread")) threading_flags = 0;
#else
else if (!strcmp(arg, "-no-thread")) threading_flags = GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_WINDOW_NO_THREAD;
#endif
else if (!strcmp(arg, "-no-cthread") || !strcmp(arg, "-no-compositor-thread")) threading_flags |= GF_TERM_NO_COMPOSITOR_THREAD;
else if (!strcmp(arg, "-no-audio")) no_audio = 1;
else if (!strcmp(arg, "-no-regulation")) no_regulation = 1;
else if (!strcmp(arg, "-fs")) start_fs = 1;
else if (!strcmp(arg, "-opt")) {
set_cfg_option(argv[i+1]);
i++;
} else if (!strcmp(arg, "-conf")) {
set_cfg_option(argv[i+1]);
is_cfg_only=GF_TRUE;
i++;
}
else if (!strcmp(arg, "-ifce")) {
gf_cfg_set_key(cfg_file, "Network", "DefaultMCastInterface", argv[i+1]);
i++;
}
else if (!stricmp(arg, "-help")) {
PrintUsage();
return 1;
}
else if (!stricmp(arg, "-noprog")) {
no_prog=1;
gf_set_progress_callback(NULL, progress_quiet);
}
else if (!stricmp(arg, "-no-save") || !stricmp(arg, "--no-save") /*old versions used --n-save ...*/) {
no_cfg_save=1;
}
else if (!stricmp(arg, "-ntp-shift")) {
s32 shift = atoi(argv[i+1]);
i++;
gf_net_set_ntp_shift(shift);
}
else if (!stricmp(arg, "-run-for")) {
simulation_time_in_ms = atoi(argv[i+1]) * 1000;
if (!simulation_time_in_ms)
simulation_time_in_ms = 1; /*1ms*/
i++;
}
else if (!strcmp(arg, "-out")) {
out_arg = argv[i+1];
i++;
}
else if (!stricmp(arg, "-fps")) {
fps = atof(argv[i+1]);
i++;
} else if (!strcmp(arg, "-avi") || !strcmp(arg, "-sha")) {
dump_mode &= 0xFFFF0000;
if (!strcmp(arg, "-sha")) dump_mode |= DUMP_SHA1;
else dump_mode |= DUMP_AVI;
if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) {
if (!strcmp(arg, "-avi") && (nb_times!=2) ) {
fprintf(stderr, "Only one time arg found for -avi - check usage\n");
return 1;
}
i++;
}
} else if (!strcmp(arg, "-rgbds")) { /*get dump in rgbds pixel format*/
dump_mode |= DUMP_RGB_DEPTH_SHAPE;
} else if (!strcmp(arg, "-rgbd")) { /*get dump in rgbd pixel format*/
dump_mode |= DUMP_RGB_DEPTH;
} else if (!strcmp(arg, "-depth")) {
dump_mode |= DUMP_DEPTH_ONLY;
} else if (!strcmp(arg, "-bmp")) {
dump_mode &= 0xFFFF0000;
dump_mode |= DUMP_BMP;
if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++;
} else if (!strcmp(arg, "-png")) {
dump_mode &= 0xFFFF0000;
dump_mode |= DUMP_PNG;
if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++;
} else if (!strcmp(arg, "-raw")) {
dump_mode &= 0xFFFF0000;
dump_mode |= DUMP_RAW;
if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++;
} else if (!stricmp(arg, "-scale")) {
sscanf(argv[i+1], "%f", &scale);
i++;
}
else if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) {
/* already parsed */
i++;
}
/*arguments only used in non-gui mode*/
if (!gui_mode) {
if (arg[0] != '-') {
if (url_arg) {
fprintf(stderr, "Several input URLs provided (\"%s\", \"%s\"). Check your command-line.\n", url_arg, arg);
return 1;
}
url_arg = arg;
}
else if (!strcmp(arg, "-loop")) loop_at_end = 1;
else if (!strcmp(arg, "-bench")) bench_mode = 1;
else if (!strcmp(arg, "-vbench")) bench_mode = 2;
else if (!strcmp(arg, "-sbench")) bench_mode = 3;
else if (!strcmp(arg, "-no-addon")) enable_add_ons = GF_FALSE;
else if (!strcmp(arg, "-pause")) pause_at_first = 1;
else if (!strcmp(arg, "-play-from")) {
play_from = atof((const char *) argv[i+1]);
i++;
}
else if (!strcmp(arg, "-speed")) {
playback_speed = FLT2FIX( atof((const char *) argv[i+1]) );
if (playback_speed <= 0) playback_speed = FIX_ONE;
i++;
}
else if (!strcmp(arg, "-no-wnd")) user.init_flags |= GF_TERM_WINDOWLESS;
else if (!strcmp(arg, "-no-back")) user.init_flags |= GF_TERM_WINDOW_TRANSPARENT;
else if (!strcmp(arg, "-align")) {
if (argv[i+1][0]=='m') align_mode = 1;
else if (argv[i+1][0]=='b') align_mode = 2;
align_mode <<= 8;
if (argv[i+1][1]=='m') align_mode |= 1;
else if (argv[i+1][1]=='r') align_mode |= 2;
i++;
} else if (!strcmp(arg, "-fill")) {
fill_ar = GF_TRUE;
} else if (!strcmp(arg, "-show")) {
visible = 1;
} else if (!strcmp(arg, "-uncache")) {
do_uncache = GF_TRUE;
}
else if (!strcmp(arg, "-exit")) auto_exit = GF_TRUE;
else if (!stricmp(arg, "-views")) {
views = argv[i+1];
i++;
}
else if (!stricmp(arg, "-mosaic")) {
mosaic = argv[i+1];
i++;
}
else if (!stricmp(arg, "-com")) {
has_command = GF_TRUE;
i++;
}
else if (!stricmp(arg, "-service")) {
initial_service_id = atoi(argv[i+1]);
i++;
}
}
}
if (is_cfg_only) {
gf_cfg_del(cfg_file);
fprintf(stderr, "GPAC Config updated\n");
return 0;
}
if (do_uncache) {
const char *cache_dir = gf_cfg_get_key(cfg_file, "General", "CacheDirectory");
do_flatten_cache(cache_dir);
fprintf(stderr, "GPAC Cache dir %s flattened\n", cache_dir);
gf_cfg_del(cfg_file);
return 0;
}
if (dump_mode && !url_arg ) {
FILE *test;
url_arg = (char *)gf_cfg_get_key(cfg_file, "General", "StartupFile");
test = url_arg ? gf_fopen(url_arg, "rt") : NULL;
if (!test) url_arg = NULL;
else gf_fclose(test);
if (!url_arg) {
fprintf(stderr, "Missing argument for dump\n");
PrintUsage();
if (logfile) gf_fclose(logfile);
return 1;
}
}
if (!gui_mode && !url_arg && (gf_cfg_get_key(cfg_file, "General", "StartupFile") != NULL)) {
gui_mode=1;
}
#ifdef WIN32
if (gui_mode==1) {
const char *opt;
TCHAR buffer[1024];
DWORD res = GetCurrentDirectory(1024, buffer);
buffer[res] = 0;
opt = gf_cfg_get_key(cfg_file, "General", "ModulesDirectory");
if (strstr(opt, buffer)) {
gui_mode=1;
} else {
gui_mode=2;
}
}
#endif
if (gui_mode==1) {
hide_shell(1);
}
if (gui_mode) {
no_prog=1;
gf_set_progress_callback(NULL, progress_quiet);
}
if (!url_arg && simulation_time_in_ms)
simulation_time_in_ms += gf_sys_clock();
#if defined(__DARWIN__) || defined(__APPLE__)
carbon_init();
#endif
if (dump_mode) rti_file = NULL;
if (!logs_set) {
gf_log_set_tool_level(GF_LOG_ALL, GF_LOG_WARNING);
}
//only override default log callback when needed
if (rti_file || logfile || log_utc_time || log_time_start)
gf_log_set_callback(NULL, on_gpac_log);
if (rti_file) init_rti_logs(rti_file, url_arg, use_rtix);
{
GF_SystemRTInfo rti;
if (gf_sys_get_rti(0, &rti, 0))
fprintf(stderr, "System info: %d MB RAM - %d cores\n", (u32) (rti.physical_memory/1024/1024), rti.nb_cores);
}
/*setup dumping options*/
if (dump_mode) {
user.init_flags |= GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_NO_REGULATION;
if (!visible)
user.init_flags |= GF_TERM_INIT_HIDE;
gf_cfg_set_key(cfg_file, "Audio", "DriverName", "Raw Audio Output");
no_cfg_save=GF_TRUE;
} else {
init_w = forced_width;
init_h = forced_height;
}
user.modules = gf_modules_new(NULL, cfg_file);
if (user.modules) i = gf_modules_get_count(user.modules);
if (!i || !user.modules) {
fprintf(stderr, "Error: no modules found - exiting\n");
if (user.modules) gf_modules_del(user.modules);
gf_cfg_del(cfg_file);
gf_sys_close();
if (logfile) gf_fclose(logfile);
return 1;
}
fprintf(stderr, "Modules Found : %d \n", i);
str = gf_cfg_get_key(cfg_file, "General", "GPACVersion");
if (!str || strcmp(str, GPAC_FULL_VERSION)) {
gf_cfg_del_section(cfg_file, "PluginsCache");
gf_cfg_set_key(cfg_file, "General", "GPACVersion", GPAC_FULL_VERSION);
}
user.config = cfg_file;
user.EventProc = GPAC_EventProc;
/*dummy in this case (global vars) but MUST be non-NULL*/
user.opaque = user.modules;
if (threading_flags) user.init_flags |= threading_flags;
if (no_audio) user.init_flags |= GF_TERM_NO_AUDIO;
if (no_regulation) user.init_flags |= GF_TERM_NO_REGULATION;
if (threading_flags & (GF_TERM_NO_DECODER_THREAD|GF_TERM_NO_COMPOSITOR_THREAD) ) term_step = GF_TRUE;
//in dump mode we don't want to rely on system clock but on the number of samples being consumed
if (dump_mode) user.init_flags |= GF_TERM_USE_AUDIO_HW_CLOCK;
if (bench_mode) {
gf_cfg_discard_changes(user.config);
auto_exit = GF_TRUE;
gf_cfg_set_key(user.config, "Audio", "DriverName", "Raw Audio Output");
if (bench_mode!=2) {
gf_cfg_set_key(user.config, "Video", "DriverName", "Raw Video Output");
gf_cfg_set_key(user.config, "RAWVideo", "RawOutput", "null");
gf_cfg_set_key(user.config, "Compositor", "OpenGLMode", "disable");
} else {
gf_cfg_set_key(user.config, "Video", "DisableVSync", "yes");
}
}
{
char dim[50];
sprintf(dim, "%d", forced_width);
gf_cfg_set_key(user.config, "Compositor", "DefaultWidth", forced_width ? dim : NULL);
sprintf(dim, "%d", forced_height);
gf_cfg_set_key(user.config, "Compositor", "DefaultHeight", forced_height ? dim : NULL);
}
fprintf(stderr, "Loading GPAC Terminal\n");
i = gf_sys_clock();
term = gf_term_new(&user);
if (!term) {
fprintf(stderr, "\nInit error - check you have at least one video out and one rasterizer...\nFound modules:\n");
list_modules(user.modules);
gf_modules_del(user.modules);
gf_cfg_discard_changes(cfg_file);
gf_cfg_del(cfg_file);
gf_sys_close();
if (logfile) gf_fclose(logfile);
return 1;
}
fprintf(stderr, "Terminal Loaded in %d ms\n", gf_sys_clock()-i);
if (bench_mode) {
display_rti = 2;
gf_term_set_option(term, GF_OPT_VIDEO_BENCH, (bench_mode==3) ? 2 : 1);
if (bench_mode==1) bench_mode=2;
}
if (dump_mode) {
// gf_term_set_option(term, GF_OPT_VISIBLE, 0);
if (fill_ar) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN);
} else {
/*check video output*/
str = gf_cfg_get_key(cfg_file, "Video", "DriverName");
if (!bench_mode && !strcmp(str, "Raw Video Output")) fprintf(stderr, "WARNING: using raw output video (memory only) - no display used\n");
/*check audio output*/
str = gf_cfg_get_key(cfg_file, "Audio", "DriverName");
if (!str || !strcmp(str, "No Audio Output Available")) fprintf(stderr, "WARNING: no audio output available - make sure no other program is locking the sound card\n");
str = gf_cfg_get_key(cfg_file, "General", "NoMIMETypeFetch");
no_mime_check = (str && !stricmp(str, "yes")) ? 1 : 0;
}
str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Enabled");
if (str && !strcmp(str, "yes")) {
str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Name");
if (str) fprintf(stderr, "HTTP Proxy %s enabled\n", str);
}
if (rti_file) {
str = gf_cfg_get_key(cfg_file, "General", "RTIRefreshPeriod");
if (str) {
rti_update_time_ms = atoi(str);
} else {
gf_cfg_set_key(cfg_file, "General", "RTIRefreshPeriod", "200");
}
UpdateRTInfo("At GPAC load time\n");
}
Run = 1;
if (dump_mode) {
if (!nb_times) {
times[0] = 0;
nb_times++;
}
ret_val = dump_file(url_arg, out_arg, dump_mode, fps, forced_width, forced_height, scale, times, nb_times);
Run = 0;
}
else if (views) {
}
/*connect if requested*/
else if (!gui_mode && url_arg) {
char *ext;
if (strlen(url_arg) >= sizeof(the_url)) {
fprintf(stderr, "Input url %s is too long, truncating to %d chars.\n", url_arg, (int)(sizeof(the_url) - 1));
strncpy(the_url, url_arg, sizeof(the_url)-1);
the_url[sizeof(the_url) - 1] = 0;
}
else {
strcpy(the_url, url_arg);
}
ext = strrchr(the_url, '.');
if (ext && (!stricmp(ext, ".m3u") || !stricmp(ext, ".pls"))) {
GF_Err e = GF_OK;
fprintf(stderr, "Opening Playlist %s\n", the_url);
strcpy(pl_path, the_url);
/*this is not clean, we need to have a plugin handle playlist for ourselves*/
if (!strncmp("http:", the_url, 5)) {
GF_DownloadSession *sess = gf_dm_sess_new(term->downloader, the_url, GF_NETIO_SESSION_NOT_THREADED, NULL, NULL, &e);
if (sess) {
e = gf_dm_sess_process(sess);
if (!e) {
strncpy(the_url, gf_dm_sess_get_cache_name(sess), sizeof(the_url) - 1);
the_url[sizeof(the_cfg) - 1] = 0;
}
gf_dm_sess_del(sess);
}
}
playlist = e ? NULL : gf_fopen(the_url, "rt");
readonly_playlist = 1;
if (playlist) {
request_next_playlist_item = GF_TRUE;
} else {
if (e)
fprintf(stderr, "Failed to open playlist %s: %s\n", the_url, gf_error_to_string(e) );
fprintf(stderr, "Hit 'h' for help\n\n");
}
} else {
fprintf(stderr, "Opening URL %s\n", the_url);
if (pause_at_first) fprintf(stderr, "[Status: Paused]\n");
gf_term_connect_from_time(term, the_url, (u64) (play_from*1000), pause_at_first);
}
} else {
fprintf(stderr, "Hit 'h' for help\n\n");
str = gf_cfg_get_key(cfg_file, "General", "StartupFile");
if (str) {
strncpy(the_url, "MP4Client "GPAC_FULL_VERSION , sizeof(the_url)-1);
the_url[sizeof(the_url) - 1] = 0;
gf_term_connect(term, str);
startup_file = 1;
is_connected = 1;
}
}
if (gui_mode==2) gui_mode=0;
if (start_fs) gf_term_set_option(term, GF_OPT_FULLSCREEN, 1);
if (views) {
char szTemp[4046];
sprintf(szTemp, "views://%s", views);
gf_term_connect(term, szTemp);
}
if (mosaic) {
char szTemp[4046];
sprintf(szTemp, "mosaic://%s", mosaic);
gf_term_connect(term, szTemp);
}
if (bench_mode) {
rti_update_time_ms = 500;
bench_mode_start = gf_sys_clock();
}
while (Run) {
/*we don't want getchar to block*/
if ((gui_mode==1) || !gf_prompt_has_input()) {
if (reload) {
reload = 0;
gf_term_disconnect(term);
gf_term_connect(term, startup_file ? gf_cfg_get_key(cfg_file, "General", "StartupFile") : the_url);
}
if (restart && gf_term_get_option(term, GF_OPT_IS_OVER)) {
restart = 0;
gf_term_play_from_time(term, 0, 0);
}
if (request_next_playlist_item) {
c = '\n';
request_next_playlist_item = 0;
goto force_input;
}
if (has_command && is_connected) {
has_command = GF_FALSE;
for (i=0; i<(u32)argc; i++) {
if (!strcmp(argv[i], "-com")) {
gf_term_scene_update(term, NULL, argv[i+1]);
i++;
}
}
}
if (initial_service_id && is_connected) {
GF_ObjectManager *root_od = gf_term_get_root_object(term);
if (root_od) {
gf_term_select_service(term, root_od, initial_service_id);
initial_service_id = 0;
}
}
if (!use_rtix || display_rti) UpdateRTInfo(NULL);
if (term_step) {
gf_term_process_step(term);
} else {
gf_sleep(rti_update_time_ms);
}
if (auto_exit && eos_seen && gf_term_get_option(term, GF_OPT_IS_OVER)) {
Run = GF_FALSE;
}
/*sim time*/
if (simulation_time_in_ms
&& ( (gf_term_get_elapsed_time_in_ms(term)>simulation_time_in_ms) || (!url_arg && gf_sys_clock()>simulation_time_in_ms))
) {
Run = GF_FALSE;
}
continue;
}
c = gf_prompt_get_char();
force_input:
switch (c) {
case 'q':
{
GF_Event evt;
memset(&evt, 0, sizeof(GF_Event));
evt.type = GF_EVENT_QUIT;
gf_term_send_event(term, &evt);
}
// Run = 0;
break;
case 'X':
exit(0);
break;
case 'Q':
break;
case 'o':
startup_file = 0;
gf_term_disconnect(term);
fprintf(stderr, "Enter the absolute URL\n");
if (1 > scanf("%s", the_url)) {
fprintf(stderr, "Cannot read absolute URL, aborting\n");
break;
}
if (rti_file) init_rti_logs(rti_file, the_url, use_rtix);
gf_term_connect(term, the_url);
break;
case 'O':
gf_term_disconnect(term);
fprintf(stderr, "Enter the absolute URL to the playlist\n");
if (1 > scanf("%s", the_url)) {
fprintf(stderr, "Cannot read the absolute URL, aborting.\n");
break;
}
playlist = gf_fopen(the_url, "rt");
if (playlist) {
if (1 > fscanf(playlist, "%s", the_url)) {
fprintf(stderr, "Cannot read any URL from playlist, aborting.\n");
gf_fclose( playlist);
break;
}
fprintf(stderr, "Opening URL %s\n", the_url);
gf_term_connect(term, the_url);
}
break;
case '\n':
case 'N':
if (playlist) {
int res;
gf_term_disconnect(term);
res = fscanf(playlist, "%s", the_url);
if ((res == EOF) && loop_at_end) {
fseek(playlist, 0, SEEK_SET);
res = fscanf(playlist, "%s", the_url);
}
if (res == EOF) {
fprintf(stderr, "No more items - exiting\n");
Run = 0;
} else if (the_url[0] == '#') {
request_next_playlist_item = GF_TRUE;
} else {
fprintf(stderr, "Opening URL %s\n", the_url);
gf_term_connect_with_path(term, the_url, pl_path);
}
}
break;
case 'P':
if (playlist) {
u32 count;
gf_term_disconnect(term);
if (1 > scanf("%u", &count)) {
fprintf(stderr, "Cannot read number, aborting.\n");
break;
}
while (count) {
if (fscanf(playlist, "%s", the_url)) {
fprintf(stderr, "Failed to read line, aborting\n");
break;
}
count--;
}
fprintf(stderr, "Opening URL %s\n", the_url);
gf_term_connect(term, the_url);
}
break;
case 'r':
if (is_connected)
reload = 1;
break;
case 'D':
if (is_connected) gf_term_disconnect(term);
break;
case 'p':
if (is_connected) {
Bool is_pause = gf_term_get_option(term, GF_OPT_PLAY_STATE);
fprintf(stderr, "[Status: %s]\n", is_pause ? "Playing" : "Paused");
gf_term_set_option(term, GF_OPT_PLAY_STATE, is_pause ? GF_STATE_PLAYING : GF_STATE_PAUSED);
}
break;
case 's':
if (is_connected) {
gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_STEP_PAUSE);
fprintf(stderr, "Step time: ");
PrintTime(gf_term_get_time_in_ms(term));
fprintf(stderr, "\n");
}
break;
case 'z':
case 'T':
if (!CanSeek || (Duration<=2000)) {
fprintf(stderr, "scene not seekable\n");
} else {
Double res;
s32 seekTo;
fprintf(stderr, "Duration: ");
PrintTime(Duration);
res = gf_term_get_time_in_ms(term);
if (c=='z') {
res *= 100;
res /= (s64)Duration;
fprintf(stderr, " (current %.2f %%)\nEnter Seek percentage:\n", res);
if (scanf("%d", &seekTo) == 1) {
if (seekTo > 100) seekTo = 100;
res = (Double)(s64)Duration;
res /= 100;
res *= seekTo;
gf_term_play_from_time(term, (u64) (s64) res, 0);
}
} else {
u32 r, h, m, s;
fprintf(stderr, " - Current Time: ");
PrintTime((u64) res);
fprintf(stderr, "\nEnter seek time (Format: s, m:s or h:m:s):\n");
h = m = s = 0;
r =scanf("%d:%d:%d", &h, &m, &s);
if (r==2) {
s = m;
m = h;
h = 0;
}
else if (r==1) {
s = h;
m = h = 0;
}
if (r && (r<=3)) {
u64 time = h*3600 + m*60 + s;
gf_term_play_from_time(term, time*1000, 0);
}
}
}
break;
case 't':
{
if (is_connected) {
fprintf(stderr, "Current Time: ");
PrintTime(gf_term_get_time_in_ms(term));
fprintf(stderr, " - Duration: ");
PrintTime(Duration);
fprintf(stderr, "\n");
}
}
break;
case 'w':
if (is_connected) PrintWorldInfo(term);
break;
case 'v':
if (is_connected) PrintODList(term, NULL, 0, 0, "Root");
break;
case 'i':
if (is_connected) {
u32 ID;
fprintf(stderr, "Enter OD ID (0 for main OD): ");
fflush(stderr);
if (scanf("%ud", &ID) == 1) {
ViewOD(term, ID, (u32)-1, NULL);
} else {
char str_url[GF_MAX_PATH];
if (scanf("%s", str_url) == 1)
ViewOD(term, 0, (u32)-1, str_url);
}
}
break;
case 'j':
if (is_connected) {
u32 num;
do {
fprintf(stderr, "Enter OD number (0 for main OD): ");
fflush(stderr);
} while( 1 > scanf("%ud", &num));
ViewOD(term, (u32)-1, num, NULL);
}
break;
case 'b':
if (is_connected) ViewODs(term, 1);
break;
case 'm':
if (is_connected) ViewODs(term, 0);
break;
case 'l':
list_modules(user.modules);
break;
case 'n':
if (is_connected) set_navigation();
break;
case 'x':
if (is_connected) gf_term_set_option(term, GF_OPT_NAVIGATION_TYPE, 0);
break;
case 'd':
if (is_connected) {
GF_ObjectManager *odm = NULL;
char radname[GF_MAX_PATH], *sExt;
GF_Err e;
u32 i, count, odid;
Bool xml_dump, std_out;
radname[0] = 0;
do {
fprintf(stderr, "Enter Inline OD ID if any or 0 : ");
fflush(stderr);
} while( 1 > scanf("%ud", &odid));
if (odid) {
GF_ObjectManager *root_odm = gf_term_get_root_object(term);
if (!root_odm) break;
count = gf_term_get_object_count(term, root_odm);
for (i=0; i<count; i++) {
GF_MediaInfo info;
odm = gf_term_get_object(term, root_odm, i);
if (gf_term_get_object_info(term, odm, &info) == GF_OK) {
if (info.od->objectDescriptorID==odid) break;
}
odm = NULL;
}
}
do {
fprintf(stderr, "Enter file radical name (+\'.x\' for XML dumping) - \"std\" for stderr: ");
fflush(stderr);
} while( 1 > scanf("%s", radname));
sExt = strrchr(radname, '.');
xml_dump = 0;
if (sExt) {
if (!stricmp(sExt, ".x")) xml_dump = 1;
sExt[0] = 0;
}
std_out = strnicmp(radname, "std", 3) ? 0 : 1;
e = gf_term_dump_scene(term, std_out ? NULL : radname, NULL, xml_dump, 0, odm);
fprintf(stderr, "Dump done (%s)\n", gf_error_to_string(e));
}
break;
case 'c':
PrintGPACConfig();
break;
case '3':
{
Bool use_3d = !gf_term_get_option(term, GF_OPT_USE_OPENGL);
if (gf_term_set_option(term, GF_OPT_USE_OPENGL, use_3d)==GF_OK) {
fprintf(stderr, "Using %s for 2D drawing\n", use_3d ? "OpenGL" : "2D rasterizer");
}
}
break;
case 'k':
{
Bool opt = gf_term_get_option(term, GF_OPT_STRESS_MODE);
opt = !opt;
fprintf(stderr, "Turning stress mode %s\n", opt ? "on" : "off");
gf_term_set_option(term, GF_OPT_STRESS_MODE, opt);
}
break;
case '4':
gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_4_3);
break;
case '5':
gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_16_9);
break;
case '6':
gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN);
break;
case '7':
gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_KEEP);
break;
case 'C':
switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) {
case GF_MEDIA_CACHE_DISABLED:
gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_ENABLED);
break;
case GF_MEDIA_CACHE_ENABLED:
gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_DISABLED);
break;
case GF_MEDIA_CACHE_RUNNING:
fprintf(stderr, "Streaming Cache is running - please stop it first\n");
continue;
}
switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) {
case GF_MEDIA_CACHE_ENABLED:
fprintf(stderr, "Streaming Cache Enabled\n");
break;
case GF_MEDIA_CACHE_DISABLED:
fprintf(stderr, "Streaming Cache Disabled\n");
break;
case GF_MEDIA_CACHE_RUNNING:
fprintf(stderr, "Streaming Cache Running\n");
break;
}
break;
case 'S':
case 'A':
if (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)==GF_MEDIA_CACHE_RUNNING) {
gf_term_set_option(term, GF_OPT_MEDIA_CACHE, (c=='S') ? GF_MEDIA_CACHE_DISABLED : GF_MEDIA_CACHE_DISCARD);
fprintf(stderr, "Streaming Cache stopped\n");
} else {
fprintf(stderr, "Streaming Cache not running\n");
}
break;
case 'R':
display_rti = !display_rti;
ResetCaption();
break;
case 'F':
if (display_rti) display_rti = 0;
else display_rti = 2;
ResetCaption();
break;
case 'u':
{
GF_Err e;
char szCom[8192];
fprintf(stderr, "Enter command to send:\n");
fflush(stdin);
szCom[0] = 0;
if (1 > scanf("%[^\t\n]", szCom)) {
fprintf(stderr, "Cannot read command to send, aborting.\n");
break;
}
e = gf_term_scene_update(term, NULL, szCom);
if (e) fprintf(stderr, "Processing command failed: %s\n", gf_error_to_string(e));
}
break;
case 'e':
{
GF_Err e;
char jsCode[8192];
fprintf(stderr, "Enter JavaScript code to evaluate:\n");
fflush(stdin);
jsCode[0] = 0;
if (1 > scanf("%[^\t\n]", jsCode)) {
fprintf(stderr, "Cannot read code to evaluate, aborting.\n");
break;
}
e = gf_term_scene_update(term, "application/ecmascript", jsCode);
if (e) fprintf(stderr, "Processing JS code failed: %s\n", gf_error_to_string(e));
}
break;
case 'L':
{
char szLog[1024], *cur_logs;
cur_logs = gf_log_get_tools_levels();
fprintf(stderr, "Enter new log level (current tools %s):\n", cur_logs);
gf_free(cur_logs);
if (scanf("%s", szLog) < 1) {
fprintf(stderr, "Cannot read new log level, aborting.\n");
break;
}
gf_log_modify_tools_levels(szLog);
}
break;
case 'g':
{
GF_SystemRTInfo rti;
gf_sys_get_rti(rti_update_time_ms, &rti, 0);
fprintf(stderr, "GPAC allocated memory "LLD"\n", rti.gpac_memory);
}
break;
case 'M':
{
u32 size;
do {
fprintf(stderr, "Enter new video cache memory in kBytes (current %ud):\n", gf_term_get_option(term, GF_OPT_VIDEO_CACHE_SIZE));
} while (1 > scanf("%ud", &size));
gf_term_set_option(term, GF_OPT_VIDEO_CACHE_SIZE, size);
}
break;
case 'H':
{
u32 http_bitrate = gf_term_get_option(term, GF_OPT_HTTP_MAX_RATE);
do {
fprintf(stderr, "Enter new http bitrate in bps (0 for none) - current limit: %d\n", http_bitrate);
} while (1 > scanf("%ud", &http_bitrate));
gf_term_set_option(term, GF_OPT_HTTP_MAX_RATE, http_bitrate);
}
break;
case 'E':
gf_term_set_option(term, GF_OPT_RELOAD_CONFIG, 1);
break;
case 'B':
switch_bench(!bench_mode);
break;
case 'Y':
{
char szOpt[8192];
fprintf(stderr, "Enter option to set (Section:Name=Value):\n");
fflush(stdin);
szOpt[0] = 0;
if (1 > scanf("%[^\t\n]", szOpt)) {
fprintf(stderr, "Cannot read option\n");
break;
}
set_cfg_option(szOpt);
}
break;
/*extract to PNG*/
case 'Z':
{
char szFileName[100];
u32 nb_pass, nb_views, offscreen_view = 0;
GF_VideoSurface fb;
GF_Err e;
nb_pass = 1;
nb_views = gf_term_get_option(term, GF_OPT_NUM_STEREO_VIEWS);
if (nb_views>1) {
fprintf(stderr, "Auto-stereo mode detected - type number of view to dump (0 is main output, 1 to %d offscreen view, %d for all offscreen, %d for all offscreen and main)\n", nb_views, nb_views+1, nb_views+2);
if (scanf("%d", &offscreen_view) != 1) {
offscreen_view = 0;
}
if (offscreen_view==nb_views+1) {
offscreen_view = 1;
nb_pass = nb_views;
}
else if (offscreen_view==nb_views+2) {
offscreen_view = 0;
nb_pass = nb_views+1;
}
}
while (nb_pass) {
nb_pass--;
if (offscreen_view) {
sprintf(szFileName, "view%d_dump.png", offscreen_view);
e = gf_term_get_offscreen_buffer(term, &fb, offscreen_view-1, 0);
} else {
sprintf(szFileName, "gpac_video_dump_"LLU".png", gf_net_get_utc() );
e = gf_term_get_screen_buffer(term, &fb);
}
offscreen_view++;
if (e) {
fprintf(stderr, "Error dumping screen buffer %s\n", gf_error_to_string(e) );
nb_pass = 0;
} else {
#ifndef GPAC_DISABLE_AV_PARSERS
u32 dst_size = fb.width*fb.height*4;
char *dst = (char*)gf_malloc(sizeof(char)*dst_size);
e = gf_img_png_enc(fb.video_buffer, fb.width, fb.height, fb.pitch_y, fb.pixel_format, dst, &dst_size);
if (e) {
fprintf(stderr, "Error encoding PNG %s\n", gf_error_to_string(e) );
nb_pass = 0;
} else {
FILE *png = gf_fopen(szFileName, "wb");
if (!png) {
fprintf(stderr, "Error writing file %s\n", szFileName);
nb_pass = 0;
} else {
gf_fwrite(dst, dst_size, 1, png);
gf_fclose(png);
fprintf(stderr, "Dump to %s\n", szFileName);
}
}
if (dst) gf_free(dst);
gf_term_release_screen_buffer(term, &fb);
#endif //GPAC_DISABLE_AV_PARSERS
}
}
fprintf(stderr, "Done: %s\n", szFileName);
}
break;
case 'G':
{
GF_ObjectManager *root_od, *odm;
u32 index;
char szOpt[8192];
fprintf(stderr, "Enter 0-based index of object to select or service ID:\n");
fflush(stdin);
szOpt[0] = 0;
if (1 > scanf("%[^\t\n]", szOpt)) {
fprintf(stderr, "Cannot read OD ID\n");
break;
}
index = atoi(szOpt);
odm = NULL;
root_od = gf_term_get_root_object(term);
if (root_od) {
if ( gf_term_find_service(term, root_od, index)) {
gf_term_select_service(term, root_od, index);
} else {
fprintf(stderr, "Cannot find service %d - trying with object index\n", index);
odm = gf_term_get_object(term, root_od, index);
if (odm) {
gf_term_select_object(term, odm);
} else {
fprintf(stderr, "Cannot find object at index %d\n", index);
}
}
}
}
break;
case 'h':
PrintHelp();
break;
default:
break;
}
}
if (bench_mode) {
PrintAVInfo(GF_TRUE);
}
/*FIXME: we have an issue in cleaning up after playing in bench mode and run-for 0 (buildbot tests). We for now disable error checks after run-for is done*/
if (simulation_time_in_ms) {
gf_log_set_strict_error(0);
}
i = gf_sys_clock();
gf_term_disconnect(term);
if (rti_file) UpdateRTInfo("Disconnected\n");
fprintf(stderr, "Deleting terminal... ");
if (playlist) gf_fclose(playlist);
#if defined(__DARWIN__) || defined(__APPLE__)
carbon_uninit();
#endif
gf_term_del(term);
fprintf(stderr, "done (in %d ms) - ran for %d ms\n", gf_sys_clock() - i, gf_sys_clock());
fprintf(stderr, "GPAC cleanup ...\n");
gf_modules_del(user.modules);
if (no_cfg_save)
gf_cfg_discard_changes(cfg_file);
gf_cfg_del(cfg_file);
gf_sys_close();
if (rti_logs) gf_fclose(rti_logs);
if (logfile) gf_fclose(logfile);
if (gui_mode) {
hide_shell(2);
}
#ifdef GPAC_MEMORY_TRACKING
if (mem_track && (gf_memory_size() || gf_file_handles_count() )) {
gf_log_set_tool_level(GF_LOG_MEMORY, GF_LOG_INFO);
gf_memory_print();
return 2;
}
#endif
return ret_val;
}
#if defined(WIN32) && !defined(NO_WMAIN)
int wmain(int argc, wchar_t** wargv)
{
int i;
int res;
size_t len;
size_t res_len;
char **argv;
argv = (char **)malloc(argc*sizeof(wchar_t *));
for (i = 0; i < argc; i++) {
wchar_t *src_str = wargv[i];
len = UTF8_MAX_BYTES_PER_CHAR * gf_utf8_wcslen(wargv[i]);
argv[i] = (char *)malloc(len + 1);
res_len = gf_utf8_wcstombs(argv[i], len, &src_str);
argv[i][res_len] = 0;
if (res_len > len) {
fprintf(stderr, "Length allocated for conversion of wide char to UTF-8 not sufficient\n");
return -1;
}
}
res = mp4client_main(argc, argv);
for (i = 0; i < argc; i++) {
free(argv[i]);
}
free(argv);
return res;
}
#else
int main(int argc, char** argv)
{
return mp4client_main(argc, argv);
}
#endif //win32
static GF_ObjectManager *video_odm = NULL;
static GF_ObjectManager *audio_odm = NULL;
static GF_ObjectManager *scene_odm = NULL;
static u32 last_odm_count = 0;
void PrintAVInfo(Bool final)
{
GF_MediaInfo a_odi, v_odi, s_odi;
Double avg_dec_time=0;
u32 tot_time=0;
Bool print_codecs = final;
if (scene_odm) {
GF_ObjectManager *root_odm = gf_term_get_root_object(term);
u32 count = gf_term_get_object_count(term, root_odm);
if (last_odm_count != count) {
last_odm_count = count;
scene_odm = NULL;
}
}
if (!video_odm && !audio_odm && !scene_odm) {
u32 count, i;
GF_ObjectManager *root_odm = root_odm = gf_term_get_root_object(term);
if (!root_odm) return;
if (gf_term_get_object_info(term, root_odm, &v_odi)==GF_OK) {
if (!scene_odm && (v_odi.generated_scene== 0)) {
scene_odm = root_odm;
}
}
count = gf_term_get_object_count(term, root_odm);
for (i=0; i<count; i++) {
GF_ObjectManager *odm = gf_term_get_object(term, root_odm, i);
if (!odm) break;
if (gf_term_get_object_info(term, odm, &v_odi) == GF_OK) {
if (!video_odm && (v_odi.od_type == GF_STREAM_VISUAL) && (v_odi.raw_media || (v_odi.cb_max_count>1) || v_odi.direct_video_memory || (bench_mode == 3) )) {
video_odm = odm;
}
else if (!audio_odm && (v_odi.od_type == GF_STREAM_AUDIO)) {
audio_odm = odm;
}
else if (!scene_odm && (v_odi.od_type == GF_STREAM_SCENE)) {
scene_odm = odm;
}
}
}
}
if (0 && bench_buffer) {
fprintf(stderr, "Buffering %d %% ", bench_buffer-1);
return;
}
if (video_odm) {
if (gf_term_get_object_info(term, video_odm, &v_odi)!= GF_OK) {
video_odm = NULL;
return;
}
} else {
memset(&v_odi, 0, sizeof(v_odi));
}
if (print_codecs && audio_odm) {
gf_term_get_object_info(term, audio_odm, &a_odi);
} else {
memset(&a_odi, 0, sizeof(a_odi));
}
if ((print_codecs || !video_odm) && scene_odm) {
gf_term_get_object_info(term, scene_odm, &s_odi);
} else {
memset(&s_odi, 0, sizeof(s_odi));
}
if (final) {
tot_time = gf_sys_clock() - bench_mode_start;
fprintf(stderr, " \r");
fprintf(stderr, "************** Bench Mode Done in %d ms ********************\n", tot_time);
if (bench_mode==3) fprintf(stderr, "** Systems layer only (no decoding) **\n");
if (!video_odm) {
u32 nb_frames_drawn;
Double FPS = gf_term_get_simulation_frame_rate(term, &nb_frames_drawn);
fprintf(stderr, "Drawn %d frames FPS %.2f (simulation FPS %.2f) - duration %d ms\n", nb_frames_drawn, ((Float)nb_frames_drawn*1000)/tot_time,(Float) FPS, gf_term_get_time_in_ms(term) );
}
}
if (print_codecs) {
if (video_odm) {
fprintf(stderr, "%s %dx%d sar=%d:%d duration %.2fs\n", v_odi.codec_name, v_odi.width, v_odi.height, v_odi.par ? (v_odi.par>>16)&0xFF : 1, v_odi.par ? (v_odi.par)&0xFF : 1, v_odi.duration);
if (final) {
u32 dec_run_time = v_odi.last_frame_time - v_odi.first_frame_time;
if (!dec_run_time) dec_run_time = 1;
if (v_odi.duration) fprintf(stderr, "%d%% ", (u32) (100*v_odi.current_time / v_odi.duration ) );
fprintf(stderr, "%d frames FPS %.2f (max %d us/f) rate avg %d max %d", v_odi.nb_dec_frames, ((Float)v_odi.nb_dec_frames*1000) / dec_run_time, v_odi.max_dec_time, (u32) v_odi.avg_bitrate/1000, (u32) v_odi.max_bitrate/1000);
if (v_odi.nb_dropped) {
fprintf(stderr, " (Error during bench: %d frames drop)", v_odi.nb_dropped);
}
fprintf(stderr, "\n");
}
}
if (audio_odm) {
fprintf(stderr, "%s SR %d num channels %d bpp %d duration %.2fs\n", a_odi.codec_name, a_odi.sample_rate, a_odi.num_channels, a_odi.bits_per_sample, a_odi.duration);
if (final) {
u32 dec_run_time = a_odi.last_frame_time - a_odi.first_frame_time;
if (!dec_run_time) dec_run_time = 1;
if (a_odi.duration) fprintf(stderr, "%d%% ", (u32) (100*a_odi.current_time / a_odi.duration ) );
fprintf(stderr, "%d frames (ms/f %.2f avg %.2f max) rate avg %d max %d", a_odi.nb_dec_frames, ((Float)dec_run_time)/a_odi.nb_dec_frames, a_odi.max_dec_time/1000.0, (u32) a_odi.avg_bitrate/1000, (u32) a_odi.max_bitrate/1000);
if (a_odi.nb_dropped) {
fprintf(stderr, " (Error during bench: %d frames drop)", a_odi.nb_dropped);
}
fprintf(stderr, "\n");
}
}
if (scene_odm) {
u32 w, h;
gf_term_get_visual_output_size(term, &w, &h);
fprintf(stderr, "%s scene size %dx%d rastered to %dx%d duration %.2fs\n", s_odi.codec_name ? s_odi.codec_name : "", s_odi.width, s_odi.height, w, h, s_odi.duration);
if (final) {
if (s_odi.nb_dec_frames>2 && s_odi.total_dec_time) {
u32 dec_run_time = s_odi.last_frame_time - s_odi.first_frame_time;
if (!dec_run_time) dec_run_time = 1;
fprintf(stderr, "%d frames FPS %.2f (max %d us/f) rate avg %d max %d", s_odi.nb_dec_frames, ((Float)s_odi.nb_dec_frames*1000) / dec_run_time, s_odi.max_dec_time, (u32) s_odi.avg_bitrate/1000, (u32) s_odi.max_bitrate/1000);
fprintf(stderr, "\n");
} else {
u32 nb_frames_drawn;
Double FPS;
gf_term_get_simulation_frame_rate(term, &nb_frames_drawn);
tot_time = gf_sys_clock() - bench_mode_start;
FPS = gf_term_get_framerate(term, 0);
fprintf(stderr, "%d frames FPS %.2f (abs %.2f)\n", nb_frames_drawn, (1000.0*nb_frames_drawn / tot_time), FPS);
}
}
}
if (final) {
fprintf(stderr, "**********************************************************\n\n");
return;
}
}
if (video_odm) {
tot_time = v_odi.last_frame_time - v_odi.first_frame_time;
if (!tot_time) tot_time=1;
if (v_odi.duration) fprintf(stderr, "%d%% ", (u32) (100*v_odi.current_time / v_odi.duration ) );
fprintf(stderr, "%d f FPS %.2f (%.2f ms max) rate %d ", v_odi.nb_dec_frames, ((Float)v_odi.nb_dec_frames*1000) / tot_time, v_odi.max_dec_time/1000.0, (u32) v_odi.instant_bitrate/1000);
}
else if (scene_odm) {
if (s_odi.nb_dec_frames>2 && s_odi.total_dec_time) {
avg_dec_time = (Float) 1000000 * s_odi.nb_dec_frames;
avg_dec_time /= s_odi.total_dec_time;
if (s_odi.duration) fprintf(stderr, "%d%% ", (u32) (100*s_odi.current_time / s_odi.duration ) );
fprintf(stderr, "%d f %.2f (%d us max) - rate %d ", s_odi.nb_dec_frames, avg_dec_time, s_odi.max_dec_time, (u32) s_odi.instant_bitrate/1000);
} else {
u32 nb_frames_drawn;
Double FPS;
gf_term_get_simulation_frame_rate(term, &nb_frames_drawn);
tot_time = gf_sys_clock() - bench_mode_start;
FPS = gf_term_get_framerate(term, 1);
fprintf(stderr, "%d f FPS %.2f (abs %.2f) ", nb_frames_drawn, (1000.0*nb_frames_drawn / tot_time), FPS);
}
}
else if (audio_odm) {
if (!print_codecs) {
gf_term_get_object_info(term, audio_odm, &a_odi);
}
tot_time = a_odi.last_frame_time - a_odi.first_frame_time;
if (!tot_time) tot_time=1;
if (a_odi.duration) fprintf(stderr, "%d%% ", (u32) (100*a_odi.current_time / a_odi.duration ) );
fprintf(stderr, "%d frames (ms/f %.2f avg %.2f max)", a_odi.nb_dec_frames, ((Float)tot_time)/a_odi.nb_dec_frames, a_odi.max_dec_time/1000.0);
}
}
void PrintWorldInfo(GF_Terminal *term)
{
u32 i;
const char *title;
GF_List *descs;
descs = gf_list_new();
title = gf_term_get_world_info(term, NULL, descs);
if (!title && !gf_list_count(descs)) {
fprintf(stderr, "No World Info available\n");
} else {
fprintf(stderr, "\t%s\n", title ? title : "No title available");
for (i=0; i<gf_list_count(descs); i++) {
char *str = gf_list_get(descs, i);
fprintf(stderr, "%s\n", str);
}
}
gf_list_del(descs);
}
void PrintODList(GF_Terminal *term, GF_ObjectManager *root_odm, u32 num, u32 indent, char *root_name)
{
GF_MediaInfo odi;
u32 i, count;
char szIndent[50];
GF_ObjectManager *odm;
if (!root_odm) {
fprintf(stderr, "Currently loaded objects:\n");
root_odm = gf_term_get_root_object(term);
}
if (!root_odm) return;
count = gf_term_get_current_service_id(term);
if (count)
fprintf(stderr, "Current service ID %d\n", count);
if (gf_term_get_object_info(term, root_odm, &odi) != GF_OK) return;
if (!odi.od) {
fprintf(stderr, "Service not attached\n");
return;
}
for (i=0; i<indent; i++) szIndent[i]=' ';
szIndent[indent]=0;
fprintf(stderr, "%s", szIndent);
fprintf(stderr, "#%d %s - ", num, root_name);
if (odi.od->ServiceID) fprintf(stderr, "Service ID %d ", odi.od->ServiceID);
if (odi.media_url) {
fprintf(stderr, "%s\n", odi.media_url);
} else {
fprintf(stderr, "OD ID %d\n", odi.od->objectDescriptorID);
}
szIndent[indent]=' ';
szIndent[indent+1]=0;
indent++;
count = gf_term_get_object_count(term, root_odm);
for (i=0; i<count; i++) {
odm = gf_term_get_object(term, root_odm, i);
if (!odm) break;
num++;
if (gf_term_get_object_info(term, odm, &odi) == GF_OK) {
switch (gf_term_object_subscene_type(term, odm)) {
case 1:
PrintODList(term, odm, num, indent, "Root");
break;
case 2:
PrintODList(term, odm, num, indent, "Inline Scene");
break;
case 3:
PrintODList(term, odm, num, indent, "EXTERNPROTO Library");
break;
default:
fprintf(stderr, "%s", szIndent);
fprintf(stderr, "#%d - ", num);
if (odi.media_url) {
fprintf(stderr, "%s", odi.media_url);
} else if (odi.od) {
if (odi.od->URLString) {
fprintf(stderr, "%s", odi.od->URLString);
} else {
fprintf(stderr, "ID %d", odi.od->objectDescriptorID);
}
} else if (odi.service_url) {
fprintf(stderr, "%s", odi.service_url);
} else {
fprintf(stderr, "unknown");
}
fprintf(stderr, " - %s", (odi.od_type==GF_STREAM_VISUAL) ? "Video" : (odi.od_type==GF_STREAM_AUDIO) ? "Audio" : "Systems");
if (odi.od && odi.od->ServiceID) fprintf(stderr, " - Service ID %d", odi.od->ServiceID);
fprintf(stderr, "\n");
break;
}
}
}
}
void ViewOD(GF_Terminal *term, u32 OD_ID, u32 number, const char *szURL)
{
GF_MediaInfo odi;
u32 i, j, count, d_enum,id;
GF_Err e;
NetStatCommand com;
GF_ObjectManager *odm, *root_odm = gf_term_get_root_object(term);
if (!root_odm) return;
odm = NULL;
if (!szURL && ((!OD_ID && (number == (u32)-1)) || ((OD_ID == (u32)(-1)) && !number))) {
odm = root_odm;
if ((gf_term_get_object_info(term, odm, &odi) != GF_OK)) odm=NULL;
} else {
count = gf_term_get_object_count(term, root_odm);
for (i=0; i<count; i++) {
odm = gf_term_get_object(term, root_odm, i);
if (!odm) break;
if (gf_term_get_object_info(term, odm, &odi) == GF_OK) {
if (szURL && strstr(odi.service_url, szURL)) break;
if ((number == (u32)(-1)) && odi.od && (odi.od->objectDescriptorID == OD_ID)) break;
else if (i == (u32)(number-1)) break;
}
odm = NULL;
}
}
if (!odm) {
if (szURL) fprintf(stderr, "cannot find OD for URL %s\n", szURL);
if (number == (u32)-1) fprintf(stderr, "cannot find OD with ID %d\n", OD_ID);
else fprintf(stderr, "cannot find OD with number %d\n", number);
return;
}
if (!odi.od) {
if (number == (u32)-1) fprintf(stderr, "Object %d not attached yet\n", OD_ID);
else fprintf(stderr, "Object #%d not attached yet\n", number);
return;
}
if (!odi.od) {
fprintf(stderr, "Service not attached\n");
return;
}
if (odi.od->tag==GF_ODF_IOD_TAG) {
fprintf(stderr, "InitialObjectDescriptor %d\n", odi.od->objectDescriptorID);
fprintf(stderr, "Profiles and Levels: Scene %x - Graphics %x - Visual %x - Audio %x - OD %x\n",
odi.scene_pl, odi.graphics_pl, odi.visual_pl, odi.audio_pl, odi.OD_pl);
fprintf(stderr, "Inline Profile Flag %d\n", odi.inline_pl);
} else {
fprintf(stderr, "ObjectDescriptor %d\n", odi.od->objectDescriptorID);
}
fprintf(stderr, "Object Duration: ");
if (odi.duration) {
PrintTime((u32) (odi.duration*1000));
} else {
fprintf(stderr, "unknown");
}
fprintf(stderr, "\n");
fprintf(stderr, "Service Handler: %s\n", odi.service_handler);
fprintf(stderr, "Service URL: %s\n", odi.service_url);
if (odi.codec_name) {
Float avg_dec_time;
switch (odi.od_type) {
case GF_STREAM_VISUAL:
fprintf(stderr, "Video Object: Width %d - Height %d\r\n", odi.width, odi.height);
fprintf(stderr, "Media Codec: %s\n", odi.codec_name);
if (odi.par) fprintf(stderr, "Pixel Aspect Ratio: %d:%d\n", (odi.par>>16)&0xFF, (odi.par)&0xFF);
break;
case GF_STREAM_AUDIO:
fprintf(stderr, "Audio Object: Sample Rate %d - %d channels\r\n", odi.sample_rate, odi.num_channels);
fprintf(stderr, "Media Codec: %s\n", odi.codec_name);
break;
case GF_STREAM_SCENE:
case GF_STREAM_PRIVATE_SCENE:
if (odi.width && odi.height) {
fprintf(stderr, "Scene Description - Width %d - Height %d\n", odi.width, odi.height);
} else {
fprintf(stderr, "Scene Description - no size specified\n");
}
fprintf(stderr, "Scene Codec: %s\n", odi.codec_name);
break;
case GF_STREAM_TEXT:
if (odi.width && odi.height) {
fprintf(stderr, "Text Object: Width %d - Height %d\n", odi.width, odi.height);
} else {
fprintf(stderr, "Text Object: No size specified\n");
}
fprintf(stderr, "Text Codec %s\n", odi.codec_name);
break;
}
avg_dec_time = 0;
if (odi.nb_dec_frames) {
avg_dec_time = (Float) odi.total_dec_time;
avg_dec_time /= odi.nb_dec_frames;
}
fprintf(stderr, "\tBitrate over last second: %d kbps\n\tMax bitrate over one second: %d kbps\n\tAverage Decoding Time %.2f us %d max)\n\tTotal decoded frames %d\n",
(u32) odi.avg_bitrate/1024, odi.max_bitrate/1024, avg_dec_time, odi.max_dec_time, odi.nb_dec_frames);
}
if (odi.protection) fprintf(stderr, "Encrypted Media%s\n", (odi.protection==2) ? " NOT UNLOCKED" : "");
count = gf_list_count(odi.od->ESDescriptors);
fprintf(stderr, "%d streams in OD\n", count);
for (i=0; i<count; i++) {
GF_ESD *esd = (GF_ESD *) gf_list_get(odi.od->ESDescriptors, i);
fprintf(stderr, "\nStream ID %d - Clock ID %d\n", esd->ESID, esd->OCRESID);
if (esd->dependsOnESID) fprintf(stderr, "\tDepends on Stream ID %d for decoding\n", esd->dependsOnESID);
switch (esd->decoderConfig->streamType) {
case GF_STREAM_OD:
fprintf(stderr, "\tOD Stream - version %d\n", esd->decoderConfig->objectTypeIndication);
break;
case GF_STREAM_OCR:
fprintf(stderr, "\tOCR Stream\n");
break;
case GF_STREAM_SCENE:
fprintf(stderr, "\tScene Description Stream - version %d\n", esd->decoderConfig->objectTypeIndication);
break;
case GF_STREAM_VISUAL:
fprintf(stderr, "\tVisual Stream - media type: %s", gf_esd_get_textual_description(esd));
break;
case GF_STREAM_AUDIO:
fprintf(stderr, "\tAudio Stream - media type: %s", gf_esd_get_textual_description(esd));
break;
case GF_STREAM_MPEG7:
fprintf(stderr, "\tMPEG-7 Stream - version %d\n", esd->decoderConfig->objectTypeIndication);
break;
case GF_STREAM_IPMP:
fprintf(stderr, "\tIPMP Stream - version %d\n", esd->decoderConfig->objectTypeIndication);
break;
case GF_STREAM_OCI:
fprintf(stderr, "\tOCI Stream - version %d\n", esd->decoderConfig->objectTypeIndication);
break;
case GF_STREAM_MPEGJ:
fprintf(stderr, "\tMPEGJ Stream - version %d\n", esd->decoderConfig->objectTypeIndication);
break;
case GF_STREAM_INTERACT:
fprintf(stderr, "\tUser Interaction Stream - version %d\n", esd->decoderConfig->objectTypeIndication);
break;
case GF_STREAM_TEXT:
fprintf(stderr, "\tStreaming Text Stream - version %d\n", esd->decoderConfig->objectTypeIndication);
break;
default:
fprintf(stderr, "\tUnknown Stream\n");
break;
}
fprintf(stderr, "\tBuffer Size %d\n\tAverage Bitrate %d bps\n\tMaximum Bitrate %d bps\n", esd->decoderConfig->bufferSizeDB, esd->decoderConfig->avgBitrate, esd->decoderConfig->maxBitrate);
if (esd->slConfig->predefined==SLPredef_SkipSL) {
fprintf(stderr, "\tNot using MPEG-4 Synchronization Layer\n");
} else {
fprintf(stderr, "\tStream Clock Resolution %d\n", esd->slConfig->timestampResolution);
}
if (esd->URLString) fprintf(stderr, "\tStream Location: %s\n", esd->URLString);
/*check language*/
if (esd->langDesc) {
s32 lang_idx;
char lan[4];
lan[0] = esd->langDesc->langCode>>16;
lan[1] = (esd->langDesc->langCode>>8)&0xFF;
lan[2] = (esd->langDesc->langCode)&0xFF;
lan[3] = 0;
lang_idx = gf_lang_find(lan);
if (lang_idx>=0) {
fprintf(stderr, "\tStream Language: %s\n", gf_lang_get_name(lang_idx));
}
}
}
fprintf(stderr, "\n");
/*check OCI (not everything interests us) - FIXME: support for unicode*/
count = gf_list_count(odi.od->OCIDescriptors);
if (count) {
fprintf(stderr, "%d Object Content Information descriptors in OD\n", count);
for (i=0; i<count; i++) {
GF_Descriptor *desc = (GF_Descriptor *) gf_list_get(odi.od->OCIDescriptors, i);
switch (desc->tag) {
case GF_ODF_SEGMENT_TAG:
{
GF_Segment *sd = (GF_Segment *) desc;
fprintf(stderr, "Segment Descriptor: Name: %s - start time %g sec - duration %g sec\n", sd->SegmentName, sd->startTime, sd->Duration);
}
break;
case GF_ODF_CC_NAME_TAG:
{
GF_CC_Name *ccn = (GF_CC_Name *)desc;
fprintf(stderr, "Content Creators:\n");
for (j=0; j<gf_list_count(ccn->ContentCreators); j++) {
GF_ContentCreatorInfo *ci = (GF_ContentCreatorInfo *) gf_list_get(ccn->ContentCreators, j);
if (!ci->isUTF8) continue;
fprintf(stderr, "\t%s\n", ci->contentCreatorName);
}
}
break;
case GF_ODF_SHORT_TEXT_TAG:
{
GF_ShortTextual *std = (GF_ShortTextual *)desc;
fprintf(stderr, "Description:\n\tEvent: %s\n\t%s\n", std->eventName, std->eventText);
}
break;
default:
break;
}
}
fprintf(stderr, "\n");
}
switch (odi.status) {
case 0:
fprintf(stderr, "Stopped - ");
break;
case 1:
fprintf(stderr, "Playing - ");
break;
case 2:
fprintf(stderr, "Paused - ");
break;
case 3:
fprintf(stderr, "Not setup yet\n");
return;
default:
fprintf(stderr, "Setup Failed\n");
return;
}
if (odi.buffer>=0) fprintf(stderr, "Buffer: %d ms - ", odi.buffer);
else fprintf(stderr, "Not buffering - ");
fprintf(stderr, "Clock drift: %d ms\n", odi.clock_drift);
if (odi.db_unit_count) fprintf(stderr, "%d AU in DB\n", odi.db_unit_count);
if (odi.cb_max_count) fprintf(stderr, "Composition Buffer: %d CU (%d max)\n", odi.cb_unit_count, odi.cb_max_count);
fprintf(stderr, "\n");
if (odi.owns_service) {
const char *url;
u32 done, total, bps;
d_enum = 0;
while (gf_term_get_download_info(term, odm, &d_enum, &url, NULL, &done, &total, &bps)) {
if (d_enum==1) fprintf(stderr, "Current Downloads in service:\n");
if (done && total) {
fprintf(stderr, "%s: %d / %d bytes (%.2f %%) - %.2f kBps\n", url, done, total, (100.0f*done)/total, ((Float)bps)/1024.0f);
} else {
fprintf(stderr, "%s: %.2f kbps\n", url, ((Float)8*bps)/1024.0f);
}
}
if (!d_enum) fprintf(stderr, "No Downloads in service\n");
fprintf(stderr, "\n");
}
d_enum = 0;
while (gf_term_get_channel_net_info(term, odm, &d_enum, &id, &com, &e)) {
if (e) continue;
if (!com.bw_down && !com.bw_up) continue;
fprintf(stderr, "Stream ID %d statistics:\n", id);
if (com.multiplex_port) {
fprintf(stderr, "\tMultiplex Port %d - multiplex ID %d\n", com.multiplex_port, com.port);
} else {
fprintf(stderr, "\tPort %d\n", com.port);
}
fprintf(stderr, "\tPacket Loss Percentage: %.4f\n", com.pck_loss_percentage);
fprintf(stderr, "\tDown Bandwidth: %d bps\n", com.bw_down);
if (com.bw_up) fprintf(stderr, "\tUp Bandwidth: %d bps\n", com.bw_up);
if (com.ctrl_port) {
if (com.multiplex_port) {
fprintf(stderr, "\tControl Multiplex Port: %d - Control Multiplex ID %d\n", com.multiplex_port, com.ctrl_port);
} else {
fprintf(stderr, "\tControl Port: %d\n", com.ctrl_port);
}
fprintf(stderr, "\tDown Bandwidth: %d bps\n", com.ctrl_bw_down);
fprintf(stderr, "\tUp Bandwidth: %d bps\n", com.ctrl_bw_up);
}
fprintf(stderr, "\n");
}
}
void PrintODTiming(GF_Terminal *term, GF_ObjectManager *odm, u32 indent)
{
GF_MediaInfo odi;
u32 ind = indent;
u32 i, count;
if (!odm) return;
if (gf_term_get_object_info(term, odm, &odi) != GF_OK) return;
if (!odi.od) {
fprintf(stderr, "Service not attached\n");
return;
}
while (ind) {
fprintf(stderr, " ");
ind--;
}
if (! odi.generated_scene) {
fprintf(stderr, "- OD %d: ", odi.od->objectDescriptorID);
switch (odi.status) {
case 1:
fprintf(stderr, "Playing - ");
break;
case 2:
fprintf(stderr, "Paused - ");
break;
default:
fprintf(stderr, "Stopped - ");
break;
}
if (odi.buffer>=0) fprintf(stderr, "Buffer: %d ms - ", odi.buffer);
else fprintf(stderr, "Not buffering - ");
fprintf(stderr, "Clock drift: %d ms", odi.clock_drift);
fprintf(stderr, " - time: ");
PrintTime((u32) (odi.current_time*1000));
fprintf(stderr, "\n");
} else {
fprintf(stderr, "+ Service %s:\n", odi.service_url);
}
count = gf_term_get_object_count(term, odm);
for (i=0; i<count; i++) {
GF_ObjectManager *an_odm = gf_term_get_object(term, odm, i);
PrintODTiming(term, an_odm, indent+1);
}
return;
}
void PrintODBuffer(GF_Terminal *term, GF_ObjectManager *odm, u32 indent)
{
Float avg_dec_time;
GF_MediaInfo odi;
u32 ind, i, count;
if (!odm) return;
if (gf_term_get_object_info(term, odm, &odi) != GF_OK) return;
if (!odi.od) {
fprintf(stderr, "Service not attached\n");
return;
}
ind = indent;
while (ind) {
fprintf(stderr, " ");
ind--;
}
if (odi.generated_scene) {
fprintf(stderr, "+ Service %s:\n", odi.service_url);
} else {
fprintf(stderr, "- OD %d: ", odi.od->objectDescriptorID);
switch (odi.status) {
case 1:
fprintf(stderr, "Playing");
break;
case 2:
fprintf(stderr, "Paused");
break;
default:
fprintf(stderr, "Stopped");
break;
}
if (odi.buffer>=0) fprintf(stderr, " - Buffer: %d ms", odi.buffer);
if (odi.db_unit_count) fprintf(stderr, " - DB: %d AU", odi.db_unit_count);
if (odi.cb_max_count) fprintf(stderr, " - CB: %d/%d CUs", odi.cb_unit_count, odi.cb_max_count);
fprintf(stderr, "\n");
ind = indent;
while (ind) {
fprintf(stderr, " ");
ind--;
}
fprintf(stderr, " %d decoded frames - %d dropped frames\n", odi.nb_dec_frames, odi.nb_dropped);
ind = indent;
while (ind) {
fprintf(stderr, " ");
ind--;
}
avg_dec_time = 0;
if (odi.nb_dec_frames) {
avg_dec_time = (Float) odi.total_dec_time;
avg_dec_time /= odi.nb_dec_frames;
}
fprintf(stderr, " Avg Bitrate %d kbps (%d max) - Avg Decoding Time %.2f us (%d max)\n",
(u32) odi.avg_bitrate/1024, odi.max_bitrate/1024, avg_dec_time, odi.max_dec_time);
}
count = gf_term_get_object_count(term, odm);
for (i=0; i<count; i++) {
GF_ObjectManager *an_odm = gf_term_get_object(term, odm, i);
PrintODBuffer(term, an_odm, indent+1);
}
}
void ViewODs(GF_Terminal *term, Bool show_timing)
{
GF_ObjectManager *root_odm = gf_term_get_root_object(term);
if (!root_odm) return;
if (show_timing) {
PrintODTiming(term, root_odm, 0);
} else {
PrintODBuffer(term, root_odm, 0);
}
fprintf(stderr, "\n");
}
void PrintGPACConfig()
{
u32 i, j, cfg_count, key_count;
char szName[200];
char *secName = NULL;
fprintf(stderr, "Enter section name (\"*\" for complete dump):\n");
if (1 > scanf("%s", szName)) {
fprintf(stderr, "No section name, aborting.\n");
return;
}
if (strcmp(szName, "*")) secName = szName;
fprintf(stderr, "\n\n*** GPAC Configuration ***\n\n");
cfg_count = gf_cfg_get_section_count(cfg_file);
for (i=0; i<cfg_count; i++) {
const char *sec = gf_cfg_get_section_name(cfg_file, i);
if (secName) {
if (stricmp(sec, secName)) continue;
} else {
if (!stricmp(sec, "General")) continue;
if (!stricmp(sec, "MimeTypes")) continue;
if (!stricmp(sec, "RecentFiles")) continue;
}
fprintf(stderr, "[%s]\n", sec);
key_count = gf_cfg_get_key_count(cfg_file, sec);
for (j=0; j<key_count; j++) {
const char *key = gf_cfg_get_key_name(cfg_file, sec, j);
const char *val = gf_cfg_get_key(cfg_file, sec, key);
fprintf(stderr, "%s=%s\n", key, val);
}
fprintf(stderr, "\n");
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_525_1 |
crossvul-cpp_data_bad_4807_0 | /*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common.h"
#include "git2/types.h"
#include "git2/errors.h"
#include "git2/refs.h"
#include "git2/revwalk.h"
#include "smart.h"
#include "util.h"
#include "netops.h"
#include "posix.h"
#include "buffer.h"
#include <ctype.h>
#define PKT_LEN_SIZE 4
static const char pkt_done_str[] = "0009done\n";
static const char pkt_flush_str[] = "0000";
static const char pkt_have_prefix[] = "0032have ";
static const char pkt_want_prefix[] = "0032want ";
static int flush_pkt(git_pkt **out)
{
git_pkt *pkt;
pkt = git__malloc(sizeof(git_pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_FLUSH;
*out = pkt;
return 0;
}
/* the rest of the line will be useful for multi_ack and multi_ack_detailed */
static int ack_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_ack *pkt;
GIT_UNUSED(line);
GIT_UNUSED(len);
pkt = git__calloc(1, sizeof(git_pkt_ack));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_ACK;
line += 3;
len -= 3;
if (len >= GIT_OID_HEXSZ) {
git_oid_fromstr(&pkt->oid, line + 1);
line += GIT_OID_HEXSZ + 1;
len -= GIT_OID_HEXSZ + 1;
}
if (len >= 7) {
if (!git__prefixcmp(line + 1, "continue"))
pkt->status = GIT_ACK_CONTINUE;
if (!git__prefixcmp(line + 1, "common"))
pkt->status = GIT_ACK_COMMON;
if (!git__prefixcmp(line + 1, "ready"))
pkt->status = GIT_ACK_READY;
}
*out = (git_pkt *) pkt;
return 0;
}
static int nak_pkt(git_pkt **out)
{
git_pkt *pkt;
pkt = git__malloc(sizeof(git_pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_NAK;
*out = pkt;
return 0;
}
static int pack_pkt(git_pkt **out)
{
git_pkt *pkt;
pkt = git__malloc(sizeof(git_pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_PACK;
*out = pkt;
return 0;
}
static int comment_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_comment *pkt;
size_t alloclen;
GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_comment), len);
GITERR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1);
pkt = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_COMMENT;
memcpy(pkt->comment, line, len);
pkt->comment[len] = '\0';
*out = (git_pkt *) pkt;
return 0;
}
static int err_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_err *pkt;
size_t alloclen;
/* Remove "ERR " from the line */
line += 4;
len -= 4;
GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_progress), len);
GITERR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1);
pkt = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_ERR;
pkt->len = (int)len;
memcpy(pkt->error, line, len);
pkt->error[len] = '\0';
*out = (git_pkt *) pkt;
return 0;
}
static int data_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_data *pkt;
size_t alloclen;
line++;
len--;
GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_progress), len);
pkt = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_DATA;
pkt->len = (int) len;
memcpy(pkt->data, line, len);
*out = (git_pkt *) pkt;
return 0;
}
static int sideband_progress_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_progress *pkt;
size_t alloclen;
line++;
len--;
GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_progress), len);
pkt = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_PROGRESS;
pkt->len = (int) len;
memcpy(pkt->data, line, len);
*out = (git_pkt *) pkt;
return 0;
}
static int sideband_error_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_err *pkt;
size_t alloc_len;
line++;
len--;
GITERR_CHECK_ALLOC_ADD(&alloc_len, sizeof(git_pkt_err), len);
GITERR_CHECK_ALLOC_ADD(&alloc_len, alloc_len, 1);
pkt = git__malloc(alloc_len);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_ERR;
pkt->len = (int)len;
memcpy(pkt->error, line, len);
pkt->error[len] = '\0';
*out = (git_pkt *)pkt;
return 0;
}
/*
* Parse an other-ref line.
*/
static int ref_pkt(git_pkt **out, const char *line, size_t len)
{
int error;
git_pkt_ref *pkt;
size_t alloclen;
pkt = git__malloc(sizeof(git_pkt_ref));
GITERR_CHECK_ALLOC(pkt);
memset(pkt, 0x0, sizeof(git_pkt_ref));
pkt->type = GIT_PKT_REF;
if ((error = git_oid_fromstr(&pkt->head.oid, line)) < 0)
goto error_out;
/* Check for a bit of consistency */
if (line[GIT_OID_HEXSZ] != ' ') {
giterr_set(GITERR_NET, "Error parsing pkt-line");
error = -1;
goto error_out;
}
/* Jump from the name */
line += GIT_OID_HEXSZ + 1;
len -= (GIT_OID_HEXSZ + 1);
if (line[len - 1] == '\n')
--len;
GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);
pkt->head.name = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt->head.name);
memcpy(pkt->head.name, line, len);
pkt->head.name[len] = '\0';
if (strlen(pkt->head.name) < len) {
pkt->capabilities = strchr(pkt->head.name, '\0') + 1;
}
*out = (git_pkt *)pkt;
return 0;
error_out:
git__free(pkt);
return error;
}
static int ok_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_ok *pkt;
const char *ptr;
size_t alloc_len;
pkt = git__malloc(sizeof(*pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_OK;
line += 3; /* skip "ok " */
if (!(ptr = strchr(line, '\n'))) {
giterr_set(GITERR_NET, "Invalid packet line");
git__free(pkt);
return -1;
}
len = ptr - line;
GITERR_CHECK_ALLOC_ADD(&alloc_len, len, 1);
pkt->ref = git__malloc(alloc_len);
GITERR_CHECK_ALLOC(pkt->ref);
memcpy(pkt->ref, line, len);
pkt->ref[len] = '\0';
*out = (git_pkt *)pkt;
return 0;
}
static int ng_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_ng *pkt;
const char *ptr;
size_t alloclen;
pkt = git__malloc(sizeof(*pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->ref = NULL;
pkt->type = GIT_PKT_NG;
line += 3; /* skip "ng " */
if (!(ptr = strchr(line, ' ')))
goto out_err;
len = ptr - line;
GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);
pkt->ref = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt->ref);
memcpy(pkt->ref, line, len);
pkt->ref[len] = '\0';
line = ptr + 1;
if (!(ptr = strchr(line, '\n')))
goto out_err;
len = ptr - line;
GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);
pkt->msg = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt->msg);
memcpy(pkt->msg, line, len);
pkt->msg[len] = '\0';
*out = (git_pkt *)pkt;
return 0;
out_err:
giterr_set(GITERR_NET, "Invalid packet line");
git__free(pkt->ref);
git__free(pkt);
return -1;
}
static int unpack_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_unpack *pkt;
GIT_UNUSED(len);
pkt = git__malloc(sizeof(*pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_UNPACK;
if (!git__prefixcmp(line, "unpack ok"))
pkt->unpack_ok = 1;
else
pkt->unpack_ok = 0;
*out = (git_pkt *)pkt;
return 0;
}
static int32_t parse_len(const char *line)
{
char num[PKT_LEN_SIZE + 1];
int i, k, error;
int32_t len;
const char *num_end;
memcpy(num, line, PKT_LEN_SIZE);
num[PKT_LEN_SIZE] = '\0';
for (i = 0; i < PKT_LEN_SIZE; ++i) {
if (!isxdigit(num[i])) {
/* Make sure there are no special characters before passing to error message */
for (k = 0; k < PKT_LEN_SIZE; ++k) {
if(!isprint(num[k])) {
num[k] = '.';
}
}
giterr_set(GITERR_NET, "invalid hex digit in length: '%s'", num);
return -1;
}
}
if ((error = git__strtol32(&len, num, &num_end, 16)) < 0)
return error;
return len;
}
/*
* As per the documentation, the syntax is:
*
* pkt-line = data-pkt / flush-pkt
* data-pkt = pkt-len pkt-payload
* pkt-len = 4*(HEXDIG)
* pkt-payload = (pkt-len -4)*(OCTET)
* flush-pkt = "0000"
*
* Which means that the first four bytes are the length of the line,
* in ASCII hexadecimal (including itself)
*/
int git_pkt_parse_line(
git_pkt **head, const char *line, const char **out, size_t bufflen)
{
int ret;
int32_t len;
/* Not even enough for the length */
if (bufflen > 0 && bufflen < PKT_LEN_SIZE)
return GIT_EBUFS;
len = parse_len(line);
if (len < 0) {
/*
* If we fail to parse the length, it might be because the
* server is trying to send us the packfile already.
*/
if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) {
giterr_clear();
*out = line;
return pack_pkt(head);
}
return (int)len;
}
/*
* If we were given a buffer length, then make sure there is
* enough in the buffer to satisfy this line
*/
if (bufflen > 0 && bufflen < (size_t)len)
return GIT_EBUFS;
line += PKT_LEN_SIZE;
/*
* TODO: How do we deal with empty lines? Try again? with the next
* line?
*/
if (len == PKT_LEN_SIZE) {
*head = NULL;
*out = line;
return 0;
}
if (len == 0) { /* Flush pkt */
*out = line;
return flush_pkt(head);
}
len -= PKT_LEN_SIZE; /* the encoded length includes its own size */
if (*line == GIT_SIDE_BAND_DATA)
ret = data_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_PROGRESS)
ret = sideband_progress_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_ERROR)
ret = sideband_error_pkt(head, line, len);
else if (!git__prefixcmp(line, "ACK"))
ret = ack_pkt(head, line, len);
else if (!git__prefixcmp(line, "NAK"))
ret = nak_pkt(head);
else if (!git__prefixcmp(line, "ERR "))
ret = err_pkt(head, line, len);
else if (*line == '#')
ret = comment_pkt(head, line, len);
else if (!git__prefixcmp(line, "ok"))
ret = ok_pkt(head, line, len);
else if (!git__prefixcmp(line, "ng"))
ret = ng_pkt(head, line, len);
else if (!git__prefixcmp(line, "unpack"))
ret = unpack_pkt(head, line, len);
else
ret = ref_pkt(head, line, len);
*out = line + len;
return ret;
}
void git_pkt_free(git_pkt *pkt)
{
if (pkt->type == GIT_PKT_REF) {
git_pkt_ref *p = (git_pkt_ref *) pkt;
git__free(p->head.name);
git__free(p->head.symref_target);
}
if (pkt->type == GIT_PKT_OK) {
git_pkt_ok *p = (git_pkt_ok *) pkt;
git__free(p->ref);
}
if (pkt->type == GIT_PKT_NG) {
git_pkt_ng *p = (git_pkt_ng *) pkt;
git__free(p->ref);
git__free(p->msg);
}
git__free(pkt);
}
int git_pkt_buffer_flush(git_buf *buf)
{
return git_buf_put(buf, pkt_flush_str, strlen(pkt_flush_str));
}
static int buffer_want_with_caps(const git_remote_head *head, transport_smart_caps *caps, git_buf *buf)
{
git_buf str = GIT_BUF_INIT;
char oid[GIT_OID_HEXSZ +1] = {0};
size_t len;
/* Prefer multi_ack_detailed */
if (caps->multi_ack_detailed)
git_buf_puts(&str, GIT_CAP_MULTI_ACK_DETAILED " ");
else if (caps->multi_ack)
git_buf_puts(&str, GIT_CAP_MULTI_ACK " ");
/* Prefer side-band-64k if the server supports both */
if (caps->side_band_64k)
git_buf_printf(&str, "%s ", GIT_CAP_SIDE_BAND_64K);
else if (caps->side_band)
git_buf_printf(&str, "%s ", GIT_CAP_SIDE_BAND);
if (caps->include_tag)
git_buf_puts(&str, GIT_CAP_INCLUDE_TAG " ");
if (caps->thin_pack)
git_buf_puts(&str, GIT_CAP_THIN_PACK " ");
if (caps->ofs_delta)
git_buf_puts(&str, GIT_CAP_OFS_DELTA " ");
if (git_buf_oom(&str))
return -1;
len = strlen("XXXXwant ") + GIT_OID_HEXSZ + 1 /* NUL */ +
git_buf_len(&str) + 1 /* LF */;
if (len > 0xffff) {
giterr_set(GITERR_NET,
"Tried to produce packet with invalid length %" PRIuZ, len);
return -1;
}
git_buf_grow_by(buf, len);
git_oid_fmt(oid, &head->oid);
git_buf_printf(buf,
"%04xwant %s %s\n", (unsigned int)len, oid, git_buf_cstr(&str));
git_buf_free(&str);
GITERR_CHECK_ALLOC_BUF(buf);
return 0;
}
/*
* All "want" packets have the same length and format, so what we do
* is overwrite the OID each time.
*/
int git_pkt_buffer_wants(
const git_remote_head * const *refs,
size_t count,
transport_smart_caps *caps,
git_buf *buf)
{
size_t i = 0;
const git_remote_head *head;
if (caps->common) {
for (; i < count; ++i) {
head = refs[i];
if (!head->local)
break;
}
if (buffer_want_with_caps(refs[i], caps, buf) < 0)
return -1;
i++;
}
for (; i < count; ++i) {
char oid[GIT_OID_HEXSZ];
head = refs[i];
if (head->local)
continue;
git_oid_fmt(oid, &head->oid);
git_buf_put(buf, pkt_want_prefix, strlen(pkt_want_prefix));
git_buf_put(buf, oid, GIT_OID_HEXSZ);
git_buf_putc(buf, '\n');
if (git_buf_oom(buf))
return -1;
}
return git_pkt_buffer_flush(buf);
}
int git_pkt_buffer_have(git_oid *oid, git_buf *buf)
{
char oidhex[GIT_OID_HEXSZ + 1];
memset(oidhex, 0x0, sizeof(oidhex));
git_oid_fmt(oidhex, oid);
return git_buf_printf(buf, "%s%s\n", pkt_have_prefix, oidhex);
}
int git_pkt_buffer_done(git_buf *buf)
{
return git_buf_puts(buf, pkt_done_str);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4807_0 |
crossvul-cpp_data_good_5421_0 | /* $Id: Str.c,v 1.8 2002/12/24 17:20:46 ukai Exp $ */
/*
* String manipulation library for Boehm GC
*
* (C) Copyright 1998-1999 by Akinori Ito
*
* This software may be redistributed freely for this purpose, in full
* or in part, provided that this entire copyright notice is included
* on any copies of this software and applications and derivations thereof.
*
* This software is provided on an "as is" basis, without warranty of any
* kind, either expressed or implied, as to any matter including, but not
* limited to warranty of fitness of purpose, or merchantability, or
* results obtained from use of this software.
*/
#include <stdio.h>
#include <stdlib.h>
#include <gc.h>
#include <stdarg.h>
#include <string.h>
#ifdef __EMX__ /* or include "fm.h" for HAVE_BCOPY? */
#include <strings.h>
#endif
#include "Str.h"
#include "myctype.h"
#define INITIAL_STR_SIZE 32
#ifdef STR_DEBUG
/* This is obsolete, because "Str" can handle a '\0' character now. */
#define STR_LENGTH_CHECK(x) if (((x)->ptr==0&&(x)->length!=0)||(strlen((x)->ptr)!=(x)->length))abort();
#else /* not STR_DEBUG */
#define STR_LENGTH_CHECK(x)
#endif /* not STR_DEBUG */
Str
Strnew()
{
Str x = GC_MALLOC(sizeof(struct _Str));
x->ptr = GC_MALLOC_ATOMIC(INITIAL_STR_SIZE);
x->ptr[0] = '\0';
x->area_size = INITIAL_STR_SIZE;
x->length = 0;
return x;
}
Str
Strnew_size(int n)
{
Str x = GC_MALLOC(sizeof(struct _Str));
x->ptr = GC_MALLOC_ATOMIC(n + 1);
x->ptr[0] = '\0';
x->area_size = n + 1;
x->length = 0;
return x;
}
Str
Strnew_charp(const char *p)
{
Str x;
int n;
if (p == NULL)
return Strnew();
x = GC_MALLOC(sizeof(struct _Str));
n = strlen(p) + 1;
x->ptr = GC_MALLOC_ATOMIC(n);
x->area_size = n;
x->length = n - 1;
bcopy((void *)p, (void *)x->ptr, n);
return x;
}
Str
Strnew_m_charp(const char *p, ...)
{
va_list ap;
Str r = Strnew();
va_start(ap, p);
while (p != NULL) {
Strcat_charp(r, p);
p = va_arg(ap, char *);
}
return r;
}
Str
Strnew_charp_n(const char *p, int n)
{
Str x;
if (p == NULL)
return Strnew_size(n);
x = GC_MALLOC(sizeof(struct _Str));
x->ptr = GC_MALLOC_ATOMIC(n + 1);
x->area_size = n + 1;
x->length = n;
bcopy((void *)p, (void *)x->ptr, n);
x->ptr[n] = '\0';
return x;
}
Str
Strdup(Str s)
{
Str n = Strnew_size(s->length);
STR_LENGTH_CHECK(s);
Strcopy(n, s);
return n;
}
void
Strclear(Str s)
{
s->length = 0;
s->ptr[0] = '\0';
}
void
Strfree(Str x)
{
GC_free(x->ptr);
GC_free(x);
}
void
Strcopy(Str x, Str y)
{
STR_LENGTH_CHECK(x);
STR_LENGTH_CHECK(y);
if (x->area_size < y->length + 1) {
GC_free(x->ptr);
x->ptr = GC_MALLOC_ATOMIC(y->length + 1);
x->area_size = y->length + 1;
}
bcopy((void *)y->ptr, (void *)x->ptr, y->length + 1);
x->length = y->length;
}
void
Strcopy_charp(Str x, const char *y)
{
int len;
STR_LENGTH_CHECK(x);
if (y == NULL) {
x->length = 0;
return;
}
len = strlen(y);
if (x->area_size < len + 1) {
GC_free(x->ptr);
x->ptr = GC_MALLOC_ATOMIC(len + 1);
x->area_size = len + 1;
}
bcopy((void *)y, (void *)x->ptr, len + 1);
x->length = len;
}
void
Strcopy_charp_n(Str x, const char *y, int n)
{
int len = n;
STR_LENGTH_CHECK(x);
if (y == NULL) {
x->length = 0;
return;
}
if (x->area_size < len + 1) {
GC_free(x->ptr);
x->ptr = GC_MALLOC_ATOMIC(len + 1);
x->area_size = len + 1;
}
bcopy((void *)y, (void *)x->ptr, n);
x->ptr[n] = '\0';
x->length = n;
}
void
Strcat_charp_n(Str x, const char *y, int n)
{
int newlen;
STR_LENGTH_CHECK(x);
if (y == NULL)
return;
newlen = x->length + n + 1;
if (x->area_size < newlen) {
char *old = x->ptr;
newlen = newlen * 3 / 2;
x->ptr = GC_MALLOC_ATOMIC(newlen);
x->area_size = newlen;
bcopy((void *)old, (void *)x->ptr, x->length);
GC_free(old);
}
bcopy((void *)y, (void *)&x->ptr[x->length], n);
x->length += n;
x->ptr[x->length] = '\0';
}
void
Strcat(Str x, Str y)
{
STR_LENGTH_CHECK(y);
Strcat_charp_n(x, y->ptr, y->length);
}
void
Strcat_charp(Str x, const char *y)
{
if (y == NULL)
return;
Strcat_charp_n(x, y, strlen(y));
}
void
Strcat_m_charp(Str x, ...)
{
va_list ap;
char *p;
va_start(ap, x);
while ((p = va_arg(ap, char *)) != NULL)
Strcat_charp_n(x, p, strlen(p));
}
void
Strgrow(Str x)
{
char *old = x->ptr;
int newlen;
newlen = x->area_size * 6 / 5;
if (newlen == x->area_size)
newlen += 2;
x->ptr = GC_MALLOC_ATOMIC(newlen);
x->area_size = newlen;
bcopy((void *)old, (void *)x->ptr, x->length);
GC_free(old);
}
Str
Strsubstr(Str s, int beg, int len)
{
Str new_s;
int i;
STR_LENGTH_CHECK(s);
new_s = Strnew();
if (beg >= s->length)
return new_s;
for (i = 0; i < len && beg + i < s->length; i++)
Strcat_char(new_s, s->ptr[beg + i]);
return new_s;
}
void
Strlower(Str s)
{
int i;
STR_LENGTH_CHECK(s);
for (i = 0; i < s->length; i++)
s->ptr[i] = TOLOWER(s->ptr[i]);
}
void
Strupper(Str s)
{
int i;
STR_LENGTH_CHECK(s);
for (i = 0; i < s->length; i++)
s->ptr[i] = TOUPPER(s->ptr[i]);
}
void
Strchop(Str s)
{
STR_LENGTH_CHECK(s);
while (s->length > 0 &&
(s->ptr[s->length - 1] == '\n' || s->ptr[s->length - 1] == '\r')) {
s->length--;
}
s->ptr[s->length] = '\0';
}
void
Strinsert_char(Str s, int pos, char c)
{
int i;
STR_LENGTH_CHECK(s);
if (pos < 0 || s->length < pos)
return;
if (s->length + 2 > s->area_size)
Strgrow(s);
for (i = s->length; i > pos; i--)
s->ptr[i] = s->ptr[i - 1];
s->ptr[++s->length] = '\0';
s->ptr[pos] = c;
}
void
Strinsert_charp(Str s, int pos, const char *p)
{
STR_LENGTH_CHECK(s);
while (*p)
Strinsert_char(s, pos++, *(p++));
}
void
Strdelete(Str s, int pos, int n)
{
int i;
STR_LENGTH_CHECK(s);
if (s->length <= pos + n) {
s->ptr[pos] = '\0';
s->length = pos;
return;
}
for (i = pos; i < s->length - n; i++)
s->ptr[i] = s->ptr[i + n];
s->ptr[i] = '\0';
s->length = i;
}
void
Strtruncate(Str s, int pos)
{
STR_LENGTH_CHECK(s);
s->ptr[pos] = '\0';
s->length = pos;
}
void
Strshrink(Str s, int n)
{
STR_LENGTH_CHECK(s);
if (n >= s->length) {
s->length = 0;
s->ptr[0] = '\0';
}
else {
s->length -= n;
s->ptr[s->length] = '\0';
}
}
void
Strremovefirstspaces(Str s)
{
int i;
STR_LENGTH_CHECK(s);
for (i = 0; i < s->length && IS_SPACE(s->ptr[i]); i++) ;
if (i == 0)
return;
Strdelete(s, 0, i);
}
void
Strremovetrailingspaces(Str s)
{
int i;
STR_LENGTH_CHECK(s);
for (i = s->length - 1; i >= 0 && IS_SPACE(s->ptr[i]); i--) ;
s->length = i + 1;
s->ptr[i + 1] = '\0';
}
Str
Stralign_left(Str s, int width)
{
Str n;
int i;
STR_LENGTH_CHECK(s);
if (s->length >= width)
return Strdup(s);
n = Strnew_size(width);
Strcopy(n, s);
for (i = s->length; i < width; i++)
Strcat_char(n, ' ');
return n;
}
Str
Stralign_right(Str s, int width)
{
Str n;
int i;
STR_LENGTH_CHECK(s);
if (s->length >= width)
return Strdup(s);
n = Strnew_size(width);
for (i = s->length; i < width; i++)
Strcat_char(n, ' ');
Strcat(n, s);
return n;
}
Str
Stralign_center(Str s, int width)
{
Str n;
int i, w;
STR_LENGTH_CHECK(s);
if (s->length >= width)
return Strdup(s);
n = Strnew_size(width);
w = (width - s->length) / 2;
for (i = 0; i < w; i++)
Strcat_char(n, ' ');
Strcat(n, s);
for (i = w + s->length; i < width; i++)
Strcat_char(n, ' ');
return n;
}
#define SP_NORMAL 0
#define SP_PREC 1
#define SP_PREC2 2
Str
Sprintf(char *fmt, ...)
{
int len = 0;
int status = SP_NORMAL;
int p = 0;
char *f;
Str s;
va_list ap;
va_start(ap, fmt);
for (f = fmt; *f; f++) {
redo:
switch (status) {
case SP_NORMAL:
if (*f == '%') {
status = SP_PREC;
p = 0;
}
else
len++;
break;
case SP_PREC:
if (IS_ALPHA(*f)) {
/* conversion char. */
double vd;
int vi;
char *vs;
void *vp;
switch (*f) {
case 'l':
case 'h':
case 'L':
case 'w':
continue;
case 'd':
case 'i':
case 'o':
case 'x':
case 'X':
case 'u':
vi = va_arg(ap, int);
len += (p > 0) ? p : 10;
break;
case 'f':
case 'g':
case 'e':
case 'G':
case 'E':
vd = va_arg(ap, double);
len += (p > 0) ? p : 15;
break;
case 'c':
len += 1;
vi = va_arg(ap, int);
break;
case 's':
vs = va_arg(ap, char *);
vi = strlen(vs);
len += (p > vi) ? p : vi;
break;
case 'p':
vp = va_arg(ap, void *);
len += 10;
break;
case 'n':
vp = va_arg(ap, void *);
break;
}
status = SP_NORMAL;
}
else if (IS_DIGIT(*f))
p = p * 10 + *f - '0';
else if (*f == '.')
status = SP_PREC2;
else if (*f == '%') {
status = SP_NORMAL;
len++;
}
break;
case SP_PREC2:
if (IS_ALPHA(*f)) {
status = SP_PREC;
goto redo;
}
break;
}
}
va_end(ap);
s = Strnew_size(len * 2);
va_start(ap, fmt);
vsprintf(s->ptr, fmt, ap);
va_end(ap);
s->length = strlen(s->ptr);
if (s->length > len * 2) {
fprintf(stderr, "Sprintf: string too long\n");
exit(1);
}
return s;
}
Str
Strfgets(FILE * f)
{
Str s = Strnew();
int c;
while ((c = fgetc(f)) != EOF) {
Strcat_char(s, c);
if (c == '\n')
break;
}
return s;
}
Str
Strfgetall(FILE * f)
{
Str s = Strnew();
int c;
while ((c = fgetc(f)) != EOF) {
Strcat_char(s, c);
}
return s;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5421_0 |
crossvul-cpp_data_good_342_7 | /*
* sc.c: General functions
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
#ifdef ENABLE_OPENSSL
#include <openssl/crypto.h> /* for OPENSSL_cleanse */
#endif
#include "internal.h"
#ifdef PACKAGE_VERSION
static const char *sc_version = PACKAGE_VERSION;
#else
static const char *sc_version = "(undef)";
#endif
const char *sc_get_version(void)
{
return sc_version;
}
int sc_hex_to_bin(const char *in, u8 *out, size_t *outlen)
{
int err = SC_SUCCESS;
size_t left, count = 0, in_len;
if (in == NULL || out == NULL || outlen == NULL) {
return SC_ERROR_INVALID_ARGUMENTS;
}
left = *outlen;
in_len = strlen(in);
while (*in != '\0') {
int byte = 0, nybbles = 2;
while (nybbles-- && *in && *in != ':' && *in != ' ') {
char c;
byte <<= 4;
c = *in++;
if ('0' <= c && c <= '9')
c -= '0';
else
if ('a' <= c && c <= 'f')
c = c - 'a' + 10;
else
if ('A' <= c && c <= 'F')
c = c - 'A' + 10;
else {
err = SC_ERROR_INVALID_ARGUMENTS;
goto out;
}
byte |= c;
}
/* Detect premature end of string before byte is complete */
if (in_len > 1 && *in == '\0' && nybbles >= 0) {
err = SC_ERROR_INVALID_ARGUMENTS;
break;
}
if (*in == ':' || *in == ' ')
in++;
if (left <= 0) {
err = SC_ERROR_BUFFER_TOO_SMALL;
break;
}
out[count++] = (u8) byte;
left--;
}
out:
*outlen = count;
return err;
}
int sc_bin_to_hex(const u8 *in, size_t in_len, char *out, size_t out_len,
int in_sep)
{
unsigned int n, sep_len;
char *pos, *end, sep;
sep = (char)in_sep;
sep_len = sep > 0 ? 1 : 0;
pos = out;
end = out + out_len;
for (n = 0; n < in_len; n++) {
if (pos + 3 + sep_len >= end)
return SC_ERROR_BUFFER_TOO_SMALL;
if (n && sep_len)
*pos++ = sep;
sprintf(pos, "%02x", in[n]);
pos += 2;
}
*pos = '\0';
return SC_SUCCESS;
}
/*
* Right trim all non-printable characters
*/
size_t sc_right_trim(u8 *buf, size_t len) {
size_t i;
if (!buf)
return 0;
if (len > 0) {
for(i = len-1; i > 0; i--) {
if(!isprint(buf[i])) {
buf[i] = '\0';
len--;
continue;
}
break;
}
}
return len;
}
u8 *ulong2bebytes(u8 *buf, unsigned long x)
{
if (buf != NULL) {
buf[3] = (u8) (x & 0xff);
buf[2] = (u8) ((x >> 8) & 0xff);
buf[1] = (u8) ((x >> 16) & 0xff);
buf[0] = (u8) ((x >> 24) & 0xff);
}
return buf;
}
u8 *ushort2bebytes(u8 *buf, unsigned short x)
{
if (buf != NULL) {
buf[1] = (u8) (x & 0xff);
buf[0] = (u8) ((x >> 8) & 0xff);
}
return buf;
}
unsigned long bebytes2ulong(const u8 *buf)
{
if (buf == NULL)
return 0UL;
return (unsigned long) (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]);
}
unsigned short bebytes2ushort(const u8 *buf)
{
if (buf == NULL)
return 0U;
return (unsigned short) (buf[0] << 8 | buf[1]);
}
unsigned short lebytes2ushort(const u8 *buf)
{
if (buf == NULL)
return 0U;
return (unsigned short)buf[1] << 8 | (unsigned short)buf[0];
}
void sc_init_oid(struct sc_object_id *oid)
{
int ii;
if (!oid)
return;
for (ii=0; ii<SC_MAX_OBJECT_ID_OCTETS; ii++)
oid->value[ii] = -1;
}
int sc_format_oid(struct sc_object_id *oid, const char *in)
{
int ii, ret = SC_ERROR_INVALID_ARGUMENTS;
const char *p;
char *q;
if (oid == NULL || in == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
sc_init_oid(oid);
p = in;
for (ii=0; ii < SC_MAX_OBJECT_ID_OCTETS; ii++) {
oid->value[ii] = strtol(p, &q, 10);
if (!*q)
break;
if (!(q[0] == '.' && isdigit(q[1])))
goto out;
p = q + 1;
}
if (!sc_valid_oid(oid))
goto out;
ret = SC_SUCCESS;
out:
if (ret)
sc_init_oid(oid);
return ret;
}
int sc_compare_oid(const struct sc_object_id *oid1, const struct sc_object_id *oid2)
{
int i;
if (oid1 == NULL || oid2 == NULL) {
return SC_ERROR_INVALID_ARGUMENTS;
}
for (i = 0; i < SC_MAX_OBJECT_ID_OCTETS; i++) {
if (oid1->value[i] != oid2->value[i])
return 0;
if (oid1->value[i] == -1)
break;
}
return 1;
}
int sc_valid_oid(const struct sc_object_id *oid)
{
int ii;
if (!oid)
return 0;
if (oid->value[0] == -1 || oid->value[1] == -1)
return 0;
if (oid->value[0] > 2 || oid->value[1] > 39)
return 0;
for (ii=0;ii<SC_MAX_OBJECT_ID_OCTETS;ii++)
if (oid->value[ii])
break;
if (ii==SC_MAX_OBJECT_ID_OCTETS)
return 0;
return 1;
}
int sc_detect_card_presence(sc_reader_t *reader)
{
int r;
LOG_FUNC_CALLED(reader->ctx);
if (reader->ops->detect_card_presence == NULL)
LOG_FUNC_RETURN(reader->ctx, SC_ERROR_NOT_SUPPORTED);
r = reader->ops->detect_card_presence(reader);
LOG_FUNC_RETURN(reader->ctx, r);
}
int sc_path_set(sc_path_t *path, int type, const u8 *id, size_t id_len,
int idx, int count)
{
if (path == NULL || id == NULL || id_len == 0 || id_len > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memset(path, 0, sizeof(*path));
memcpy(path->value, id, id_len);
path->len = id_len;
path->type = type;
path->index = idx;
path->count = count;
return SC_SUCCESS;
}
void sc_format_path(const char *str, sc_path_t *path)
{
int type = SC_PATH_TYPE_PATH;
if (path) {
memset(path, 0, sizeof(*path));
if (*str == 'i' || *str == 'I') {
type = SC_PATH_TYPE_FILE_ID;
str++;
}
path->len = sizeof(path->value);
if (sc_hex_to_bin(str, path->value, &path->len) >= 0) {
path->type = type;
}
path->count = -1;
}
}
int sc_append_path(sc_path_t *dest, const sc_path_t *src)
{
return sc_concatenate_path(dest, dest, src);
}
int sc_append_path_id(sc_path_t *dest, const u8 *id, size_t idlen)
{
if (dest->len + idlen > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memcpy(dest->value + dest->len, id, idlen);
dest->len += idlen;
return SC_SUCCESS;
}
int sc_append_file_id(sc_path_t *dest, unsigned int fid)
{
u8 id[2] = { fid >> 8, fid & 0xff };
return sc_append_path_id(dest, id, 2);
}
int sc_concatenate_path(sc_path_t *d, const sc_path_t *p1, const sc_path_t *p2)
{
sc_path_t tpath;
if (d == NULL || p1 == NULL || p2 == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (p1->type == SC_PATH_TYPE_DF_NAME || p2->type == SC_PATH_TYPE_DF_NAME)
/* we do not support concatenation of AIDs at the moment */
return SC_ERROR_NOT_SUPPORTED;
if (p1->len + p2->len > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memset(&tpath, 0, sizeof(sc_path_t));
memcpy(tpath.value, p1->value, p1->len);
memcpy(tpath.value + p1->len, p2->value, p2->len);
tpath.len = p1->len + p2->len;
tpath.type = SC_PATH_TYPE_PATH;
/* use 'index' and 'count' entry of the second path object */
tpath.index = p2->index;
tpath.count = p2->count;
/* the result is currently always as path */
tpath.type = SC_PATH_TYPE_PATH;
*d = tpath;
return SC_SUCCESS;
}
const char *sc_print_path(const sc_path_t *path)
{
static char buffer[SC_MAX_PATH_STRING_SIZE + SC_MAX_AID_STRING_SIZE];
if (sc_path_print(buffer, sizeof(buffer), path) != SC_SUCCESS)
buffer[0] = '\0';
return buffer;
}
int sc_path_print(char *buf, size_t buflen, const sc_path_t *path)
{
size_t i;
if (buf == NULL || path == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (buflen < path->len * 2 + path->aid.len * 2 + 1)
return SC_ERROR_BUFFER_TOO_SMALL;
buf[0] = '\0';
if (path->aid.len) {
for (i = 0; i < path->aid.len; i++)
snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->aid.value[i]);
snprintf(buf + strlen(buf), buflen - strlen(buf), "::");
}
for (i = 0; i < path->len; i++)
snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->value[i]);
if (!path->aid.len && path->type == SC_PATH_TYPE_DF_NAME)
snprintf(buf + strlen(buf), buflen - strlen(buf), "::");
return SC_SUCCESS;
}
int sc_compare_path(const sc_path_t *path1, const sc_path_t *path2)
{
return path1->len == path2->len
&& !memcmp(path1->value, path2->value, path1->len);
}
int sc_compare_path_prefix(const sc_path_t *prefix, const sc_path_t *path)
{
sc_path_t tpath;
if (prefix->len > path->len)
return 0;
tpath = *path;
tpath.len = prefix->len;
return sc_compare_path(&tpath, prefix);
}
const sc_path_t *sc_get_mf_path(void)
{
static const sc_path_t mf_path = {
{0x3f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 2,
0,
0,
SC_PATH_TYPE_PATH,
{{0},0}
};
return &mf_path;
}
int sc_file_add_acl_entry(sc_file_t *file, unsigned int operation,
unsigned int method, unsigned long key_ref)
{
sc_acl_entry_t *p, *_new;
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return SC_ERROR_INVALID_ARGUMENTS;
}
switch (method) {
case SC_AC_NEVER:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 1;
return SC_SUCCESS;
case SC_AC_NONE:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 2;
return SC_SUCCESS;
case SC_AC_UNKNOWN:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 3;
return SC_SUCCESS;
default:
/* NONE and UNKNOWN get zapped when a new AC is added.
* If the ACL is NEVER, additional entries will be
* dropped silently. */
if (file->acl[operation] == (sc_acl_entry_t *) 1)
return SC_SUCCESS;
if (file->acl[operation] == (sc_acl_entry_t *) 2
|| file->acl[operation] == (sc_acl_entry_t *) 3)
file->acl[operation] = NULL;
}
/* If the entry is already present (e.g. due to the mapping)
* of the card's AC with OpenSC's), don't add it again. */
for (p = file->acl[operation]; p != NULL; p = p->next) {
if ((p->method == method) && (p->key_ref == key_ref))
return SC_SUCCESS;
}
_new = malloc(sizeof(sc_acl_entry_t));
if (_new == NULL)
return SC_ERROR_OUT_OF_MEMORY;
_new->method = method;
_new->key_ref = key_ref;
_new->next = NULL;
p = file->acl[operation];
if (p == NULL) {
file->acl[operation] = _new;
return SC_SUCCESS;
}
while (p->next != NULL)
p = p->next;
p->next = _new;
return SC_SUCCESS;
}
const sc_acl_entry_t * sc_file_get_acl_entry(const sc_file_t *file,
unsigned int operation)
{
sc_acl_entry_t *p;
static const sc_acl_entry_t e_never = {
SC_AC_NEVER, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
static const sc_acl_entry_t e_none = {
SC_AC_NONE, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
static const sc_acl_entry_t e_unknown = {
SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return NULL;
}
p = file->acl[operation];
if (p == (sc_acl_entry_t *) 1)
return &e_never;
if (p == (sc_acl_entry_t *) 2)
return &e_none;
if (p == (sc_acl_entry_t *) 3)
return &e_unknown;
return file->acl[operation];
}
void sc_file_clear_acl_entries(sc_file_t *file, unsigned int operation)
{
sc_acl_entry_t *e;
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return;
}
e = file->acl[operation];
if (e == (sc_acl_entry_t *) 1 ||
e == (sc_acl_entry_t *) 2 ||
e == (sc_acl_entry_t *) 3) {
file->acl[operation] = NULL;
return;
}
while (e != NULL) {
sc_acl_entry_t *tmp = e->next;
free(e);
e = tmp;
}
file->acl[operation] = NULL;
}
sc_file_t * sc_file_new(void)
{
sc_file_t *file = (sc_file_t *)calloc(1, sizeof(sc_file_t));
if (file == NULL)
return NULL;
file->magic = SC_FILE_MAGIC;
return file;
}
void sc_file_free(sc_file_t *file)
{
unsigned int i;
if (file == NULL || !sc_file_valid(file))
return;
file->magic = 0;
for (i = 0; i < SC_MAX_AC_OPS; i++)
sc_file_clear_acl_entries(file, i);
if (file->sec_attr)
free(file->sec_attr);
if (file->prop_attr)
free(file->prop_attr);
if (file->type_attr)
free(file->type_attr);
if (file->encoded_content)
free(file->encoded_content);
free(file);
}
void sc_file_dup(sc_file_t **dest, const sc_file_t *src)
{
sc_file_t *newf;
const sc_acl_entry_t *e;
unsigned int op;
*dest = NULL;
if (!sc_file_valid(src))
return;
newf = sc_file_new();
if (newf == NULL)
return;
*dest = newf;
memcpy(&newf->path, &src->path, sizeof(struct sc_path));
memcpy(&newf->name, &src->name, sizeof(src->name));
newf->namelen = src->namelen;
newf->type = src->type;
newf->shareable = src->shareable;
newf->ef_structure = src->ef_structure;
newf->size = src->size;
newf->id = src->id;
newf->status = src->status;
for (op = 0; op < SC_MAX_AC_OPS; op++) {
newf->acl[op] = NULL;
e = sc_file_get_acl_entry(src, op);
if (e != NULL) {
if (sc_file_add_acl_entry(newf, op, e->method, e->key_ref) < 0)
goto err;
}
}
newf->record_length = src->record_length;
newf->record_count = src->record_count;
if (sc_file_set_sec_attr(newf, src->sec_attr, src->sec_attr_len) < 0)
goto err;
if (sc_file_set_prop_attr(newf, src->prop_attr, src->prop_attr_len) < 0)
goto err;
if (sc_file_set_type_attr(newf, src->type_attr, src->type_attr_len) < 0)
goto err;
if (sc_file_set_content(newf, src->encoded_content, src->encoded_content_len) < 0)
goto err;
return;
err:
sc_file_free(newf);
*dest = NULL;
}
int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,
size_t sec_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (sec_attr == NULL || sec_attr_len) {
if (file->sec_attr != NULL)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return 0;
}
tmp = (u8 *) realloc(file->sec_attr, sec_attr_len);
if (!tmp) {
if (file->sec_attr)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->sec_attr = tmp;
memcpy(file->sec_attr, sec_attr, sec_attr_len);
file->sec_attr_len = sec_attr_len;
return 0;
}
int sc_file_set_prop_attr(sc_file_t *file, const u8 *prop_attr,
size_t prop_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (prop_attr == NULL) {
if (file->prop_attr != NULL)
free(file->prop_attr);
file->prop_attr = NULL;
file->prop_attr_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->prop_attr, prop_attr_len);
if (!tmp) {
if (file->prop_attr)
free(file->prop_attr);
file->prop_attr = NULL;
file->prop_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->prop_attr = tmp;
memcpy(file->prop_attr, prop_attr, prop_attr_len);
file->prop_attr_len = prop_attr_len;
return SC_SUCCESS;
}
int sc_file_set_type_attr(sc_file_t *file, const u8 *type_attr,
size_t type_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (type_attr == NULL) {
if (file->type_attr != NULL)
free(file->type_attr);
file->type_attr = NULL;
file->type_attr_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->type_attr, type_attr_len);
if (!tmp) {
if (file->type_attr)
free(file->type_attr);
file->type_attr = NULL;
file->type_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->type_attr = tmp;
memcpy(file->type_attr, type_attr, type_attr_len);
file->type_attr_len = type_attr_len;
return SC_SUCCESS;
}
int sc_file_set_content(sc_file_t *file, const u8 *content,
size_t content_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (content == NULL) {
if (file->encoded_content != NULL)
free(file->encoded_content);
file->encoded_content = NULL;
file->encoded_content_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->encoded_content, content_len);
if (!tmp) {
if (file->encoded_content)
free(file->encoded_content);
file->encoded_content = NULL;
file->encoded_content_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->encoded_content = tmp;
memcpy(file->encoded_content, content, content_len);
file->encoded_content_len = content_len;
return SC_SUCCESS;
}
int sc_file_valid(const sc_file_t *file) {
if (file == NULL)
return 0;
return file->magic == SC_FILE_MAGIC;
}
int _sc_parse_atr(sc_reader_t *reader)
{
u8 *p = reader->atr.value;
int atr_len = (int) reader->atr.len;
int n_hist, x;
int tx[4] = {-1, -1, -1, -1};
int i, FI, DI;
const int Fi_table[] = {
372, 372, 558, 744, 1116, 1488, 1860, -1,
-1, 512, 768, 1024, 1536, 2048, -1, -1 };
const int f_table[] = {
40, 50, 60, 80, 120, 160, 200, -1,
-1, 50, 75, 100, 150, 200, -1, -1 };
const int Di_table[] = {
-1, 1, 2, 4, 8, 16, 32, -1,
12, 20, -1, -1, -1, -1, -1, -1 };
reader->atr_info.hist_bytes_len = 0;
reader->atr_info.hist_bytes = NULL;
if (atr_len == 0) {
sc_log(reader->ctx, "empty ATR - card not present?\n");
return SC_ERROR_INTERNAL;
}
if (p[0] != 0x3B && p[0] != 0x3F) {
sc_log(reader->ctx, "invalid sync byte in ATR: 0x%02X\n", p[0]);
return SC_ERROR_INTERNAL;
}
n_hist = p[1] & 0x0F;
x = p[1] >> 4;
p += 2;
atr_len -= 2;
for (i = 0; i < 4 && atr_len > 0; i++) {
if (x & (1 << i)) {
tx[i] = *p;
p++;
atr_len--;
} else
tx[i] = -1;
}
if (tx[0] >= 0) {
reader->atr_info.FI = FI = tx[0] >> 4;
reader->atr_info.DI = DI = tx[0] & 0x0F;
reader->atr_info.Fi = Fi_table[FI];
reader->atr_info.f = f_table[FI];
reader->atr_info.Di = Di_table[DI];
} else {
reader->atr_info.Fi = -1;
reader->atr_info.f = -1;
reader->atr_info.Di = -1;
}
if (tx[2] >= 0)
reader->atr_info.N = tx[3];
else
reader->atr_info.N = -1;
while (tx[3] > 0 && tx[3] & 0xF0 && atr_len > 0) {
x = tx[3] >> 4;
for (i = 0; i < 4 && atr_len > 0; i++) {
if (x & (1 << i)) {
tx[i] = *p;
p++;
atr_len--;
} else
tx[i] = -1;
}
}
if (atr_len <= 0)
return SC_SUCCESS;
if (n_hist > atr_len)
n_hist = atr_len;
reader->atr_info.hist_bytes_len = n_hist;
reader->atr_info.hist_bytes = p;
return SC_SUCCESS;
}
void sc_mem_clear(void *ptr, size_t len)
{
if (len > 0) {
#ifdef ENABLE_OPENSSL
OPENSSL_cleanse(ptr, len);
#else
memset(ptr, 0, len);
#endif
}
}
int sc_mem_reverse(unsigned char *buf, size_t len)
{
unsigned char ch;
size_t ii;
if (!buf || !len)
return SC_ERROR_INVALID_ARGUMENTS;
for (ii = 0; ii < len / 2; ii++) {
ch = *(buf + ii);
*(buf + ii) = *(buf + len - 1 - ii);
*(buf + len - 1 - ii) = ch;
}
return SC_SUCCESS;
}
static int
sc_remote_apdu_allocate(struct sc_remote_data *rdata,
struct sc_remote_apdu **new_rapdu)
{
struct sc_remote_apdu *rapdu = NULL, *rr;
if (!rdata)
return SC_ERROR_INVALID_ARGUMENTS;
rapdu = calloc(1, sizeof(struct sc_remote_apdu));
if (rapdu == NULL)
return SC_ERROR_OUT_OF_MEMORY;
rapdu->apdu.data = &rapdu->sbuf[0];
rapdu->apdu.resp = &rapdu->rbuf[0];
rapdu->apdu.resplen = sizeof(rapdu->rbuf);
if (new_rapdu)
*new_rapdu = rapdu;
if (rdata->data == NULL) {
rdata->data = rapdu;
rdata->length = 1;
return SC_SUCCESS;
}
for (rr = rdata->data; rr->next; rr = rr->next)
;
rr->next = rapdu;
rdata->length++;
return SC_SUCCESS;
}
static void
sc_remote_apdu_free (struct sc_remote_data *rdata)
{
struct sc_remote_apdu *rapdu = NULL;
if (!rdata)
return;
rapdu = rdata->data;
while(rapdu) {
struct sc_remote_apdu *rr = rapdu->next;
free(rapdu);
rapdu = rr;
}
}
void sc_remote_data_init(struct sc_remote_data *rdata)
{
if (!rdata)
return;
memset(rdata, 0, sizeof(struct sc_remote_data));
rdata->alloc = sc_remote_apdu_allocate;
rdata->free = sc_remote_apdu_free;
}
static unsigned long sc_CRC_tab32[256];
static int sc_CRC_tab32_initialized = 0;
unsigned sc_crc32(const unsigned char *value, size_t len)
{
size_t ii, jj;
unsigned long crc;
unsigned long index, long_c;
if (!sc_CRC_tab32_initialized) {
for (ii=0; ii<256; ii++) {
crc = (unsigned long) ii;
for (jj=0; jj<8; jj++) {
if ( crc & 0x00000001L )
crc = ( crc >> 1 ) ^ 0xEDB88320l;
else
crc = crc >> 1;
}
sc_CRC_tab32[ii] = crc;
}
sc_CRC_tab32_initialized = 1;
}
crc = 0xffffffffL;
for (ii=0; ii<len; ii++) {
long_c = 0x000000ffL & (unsigned long) (*(value + ii));
index = crc ^ long_c;
crc = (crc >> 8) ^ sc_CRC_tab32[ index & 0xff ];
}
crc ^= 0xffffffff;
return crc%0xffff;
}
const u8 *sc_compacttlv_find_tag(const u8 *buf, size_t len, u8 tag, size_t *outlen)
{
if (buf != NULL) {
size_t idx;
u8 plain_tag = tag & 0xF0;
size_t expected_len = tag & 0x0F;
for (idx = 0; idx < len; idx++) {
if ((buf[idx] & 0xF0) == plain_tag && idx + expected_len < len &&
(expected_len == 0 || expected_len == (buf[idx] & 0x0F))) {
if (outlen != NULL)
*outlen = buf[idx] & 0x0F;
return buf + (idx + 1);
}
idx += (buf[idx] & 0x0F);
}
}
return NULL;
}
/**************************** mutex functions ************************/
int sc_mutex_create(const sc_context_t *ctx, void **mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->create_mutex != NULL)
return ctx->thread_ctx->create_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_lock(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->lock_mutex != NULL)
return ctx->thread_ctx->lock_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_unlock(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->unlock_mutex != NULL)
return ctx->thread_ctx->unlock_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_destroy(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->destroy_mutex != NULL)
return ctx->thread_ctx->destroy_mutex(mutex);
else
return SC_SUCCESS;
}
unsigned long sc_thread_id(const sc_context_t *ctx)
{
if (ctx == NULL || ctx->thread_ctx == NULL ||
ctx->thread_ctx->thread_id == NULL)
return 0UL;
else
return ctx->thread_ctx->thread_id();
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_342_7 |
crossvul-cpp_data_bad_927_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% EEEEE N N H H AAA N N CCCC EEEEE %
% E NN N H H A A NN N C E %
% EEE N N N HHHHH AAAAA N N N C EEE %
% E N NN H H A A N NN C E %
% EEEEE N N H H A A N N CCCC EEEEE %
% %
% %
% MagickCore Image Enhancement Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/accelerate-private.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/fx.h"
#include "MagickCore/gem.h"
#include "MagickCore/gem-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/histogram.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resample.h"
#include "MagickCore/resample-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/threshold.h"
#include "MagickCore/token.h"
#include "MagickCore/xml-tree.h"
#include "MagickCore/xml-tree-private.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A u t o G a m m a I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AutoGammaImage() extract the 'mean' from the image and adjust the image
% to try make set its gamma appropriatally.
%
% The format of the AutoGammaImage method is:
%
% MagickBooleanType AutoGammaImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: The image to auto-level
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType AutoGammaImage(Image *image,
ExceptionInfo *exception)
{
double
gamma,
log_mean,
mean,
sans;
MagickStatusType
status;
register ssize_t
i;
log_mean=log(0.5);
if (image->channel_mask == DefaultChannels)
{
/*
Apply gamma correction equally across all given channels.
*/
(void) GetImageMean(image,&mean,&sans,exception);
gamma=log(mean*QuantumScale)/log_mean;
return(LevelImage(image,0.0,(double) QuantumRange,gamma,exception));
}
/*
Auto-gamma each channel separately.
*/
status=MagickTrue;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
ChannelType
channel_mask;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
channel_mask=SetImageChannelMask(image,(ChannelType) (1UL << i));
status=GetImageMean(image,&mean,&sans,exception);
gamma=log(mean*QuantumScale)/log_mean;
status&=LevelImage(image,0.0,(double) QuantumRange,gamma,exception);
(void) SetImageChannelMask(image,channel_mask);
if (status == MagickFalse)
break;
}
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A u t o L e v e l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AutoLevelImage() adjusts the levels of a particular image channel by
% scaling the minimum and maximum values to the full quantum range.
%
% The format of the LevelImage method is:
%
% MagickBooleanType AutoLevelImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: The image to auto-level
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType AutoLevelImage(Image *image,
ExceptionInfo *exception)
{
return(MinMaxStretchImage(image,0.0,0.0,1.0,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B r i g h t n e s s C o n t r a s t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BrightnessContrastImage() changes the brightness and/or contrast of an
% image. It converts the brightness and contrast parameters into slope and
% intercept and calls a polynomical function to apply to the image.
%
% The format of the BrightnessContrastImage method is:
%
% MagickBooleanType BrightnessContrastImage(Image *image,
% const double brightness,const double contrast,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o brightness: the brightness percent (-100 .. 100).
%
% o contrast: the contrast percent (-100 .. 100).
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType BrightnessContrastImage(Image *image,
const double brightness,const double contrast,ExceptionInfo *exception)
{
#define BrightnessContastImageTag "BrightnessContast/Image"
double
alpha,
coefficients[2],
intercept,
slope;
MagickBooleanType
status;
/*
Compute slope and intercept.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
alpha=contrast;
slope=tan((double) (MagickPI*(alpha/100.0+1.0)/4.0));
if (slope < 0.0)
slope=0.0;
intercept=brightness/100.0+((100-brightness)/200.0)*(1.0-slope);
coefficients[0]=slope;
coefficients[1]=intercept;
status=FunctionImage(image,PolynomialFunction,2,coefficients,exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C L A H E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CLAHEImage() is a variant of adaptive histogram equalization in which the
% contrast amplification is limited, so as to reduce this problem of noise
% amplification.
%
% Adapted from implementation by Karel Zuiderveld, karel@cv.ruu.nl in
% "Graphics Gems IV", Academic Press, 1994.
%
% The format of the CLAHEImage method is:
%
% MagickBooleanType CLAHEImage(Image *image,const size_t width,
% const size_t height,const size_t number_bins,const double clip_limit,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o width: the width of the tile divisions to use in horizontal direction.
%
% o height: the height of the tile divisions to use in vertical direction.
%
% o number_bins: number of bins for histogram ("dynamic range").
%
% o clip_limit: contrast limit for localised changes in contrast. A limit
% less than 1 results in standard non-contrast limited AHE.
%
% o exception: return any errors or warnings in this structure.
%
*/
typedef struct _RangeInfo
{
unsigned short
min,
max;
} RangeInfo;
static void ClipCLAHEHistogram(const double clip_limit,const size_t number_bins,
size_t *histogram)
{
#define NumberCLAHEGrays (65536)
register ssize_t
i;
size_t
cumulative_excess,
previous_excess,
step;
ssize_t
excess;
/*
Compute total number of excess pixels.
*/
cumulative_excess=0;
for (i=0; i < (ssize_t) number_bins; i++)
{
excess=(ssize_t) histogram[i]-(ssize_t) clip_limit;
if (excess > 0)
cumulative_excess+=excess;
}
/*
Clip histogram and redistribute excess pixels across all bins.
*/
step=cumulative_excess/number_bins;
excess=(ssize_t) (clip_limit-step);
for (i=0; i < (ssize_t) number_bins; i++)
{
if ((double) histogram[i] > clip_limit)
histogram[i]=(size_t) clip_limit;
else
if ((ssize_t) histogram[i] > excess)
{
cumulative_excess-=histogram[i]-excess;
histogram[i]=(size_t) clip_limit;
}
else
{
cumulative_excess-=step;
histogram[i]+=step;
}
}
/*
Redistribute remaining excess.
*/
do
{
register size_t
*p;
size_t
*q;
previous_excess=cumulative_excess;
p=histogram;
q=histogram+number_bins;
while ((cumulative_excess != 0) && (p < q))
{
step=number_bins/cumulative_excess;
if (step < 1)
step=1;
for (p=histogram; (p < q) && (cumulative_excess != 0); p+=step)
if ((double) *p < clip_limit)
{
(*p)++;
cumulative_excess--;
}
p++;
}
} while ((cumulative_excess != 0) && (cumulative_excess < previous_excess));
}
static void GenerateCLAHEHistogram(const RectangleInfo *clahe_info,
const RectangleInfo *tile_info,const size_t number_bins,
const unsigned short *lut,const unsigned short *pixels,size_t *histogram)
{
register const unsigned short
*p;
register ssize_t
i;
/*
Classify the pixels into a gray histogram.
*/
for (i=0; i < (ssize_t) number_bins; i++)
histogram[i]=0L;
p=pixels;
for (i=0; i < (ssize_t) tile_info->height; i++)
{
const unsigned short
*q;
q=p+tile_info->width;
while (p < q)
histogram[lut[*p++]]++;
q+=clahe_info->width;
p=q-tile_info->width;
}
}
static void InterpolateCLAHE(const RectangleInfo *clahe_info,const size_t *Q12,
const size_t *Q22,const size_t *Q11,const size_t *Q21,
const RectangleInfo *tile,const unsigned short *lut,unsigned short *pixels)
{
ssize_t
y;
unsigned short
intensity;
/*
Bilinear interpolate four tiles to eliminate boundary artifacts.
*/
for (y=(ssize_t) tile->height; y > 0; y--)
{
register ssize_t
x;
for (x=(ssize_t) tile->width; x > 0; x--)
{
intensity=lut[*pixels];
*pixels++=(unsigned short ) (PerceptibleReciprocal((double) tile->width*
tile->height)*(y*(x*Q12[intensity]+(tile->width-x)*Q22[intensity])+
(tile->height-y)*(x*Q11[intensity]+(tile->width-x)*Q21[intensity])));
}
pixels+=(clahe_info->width-tile->width);
}
}
static void GenerateCLAHELut(const RangeInfo *range_info,
const size_t number_bins,unsigned short *lut)
{
ssize_t
i;
unsigned short
delta;
/*
Scale input image [intensity min,max] to [0,number_bins-1].
*/
delta=(unsigned short) ((range_info->max-range_info->min)/number_bins+1);
for (i=(ssize_t) range_info->min; i <= (ssize_t) range_info->max; i++)
lut[i]=(unsigned short) ((i-range_info->min)/delta);
}
static void MapCLAHEHistogram(const RangeInfo *range_info,
const size_t number_bins,const size_t number_pixels,size_t *histogram)
{
double
scale,
sum;
register ssize_t
i;
/*
Rescale histogram to range [min-intensity .. max-intensity].
*/
scale=(double) (range_info->max-range_info->min)/number_pixels;
sum=0.0;
for (i=0; i < (ssize_t) number_bins; i++)
{
sum+=histogram[i];
histogram[i]=(size_t) (range_info->min+scale*sum);
if (histogram[i] > range_info->max)
histogram[i]=range_info->max;
}
}
static MagickBooleanType CLAHE(const RectangleInfo *clahe_info,
const RectangleInfo *tile_info,const RangeInfo *range_info,
const size_t number_bins,const double clip_limit,unsigned short *pixels)
{
MemoryInfo
*tile_cache;
register unsigned short
*p;
size_t
limit,
*tiles;
ssize_t
y;
unsigned short
lut[NumberCLAHEGrays];
/*
Constrast limited adapted histogram equalization.
*/
if (clip_limit == 1.0)
return(MagickTrue);
tile_cache=AcquireVirtualMemory((size_t) clahe_info->x*clahe_info->y,
number_bins*sizeof(*tiles));
if (tile_cache == (MemoryInfo *) NULL)
return(MagickFalse);
tiles=(size_t *) GetVirtualMemoryBlob(tile_cache);
limit=(size_t) (clip_limit*(tile_info->width*tile_info->height)/number_bins);
if (limit < 1UL)
limit=1UL;
/*
Generate greylevel mappings for each tile.
*/
GenerateCLAHELut(range_info,number_bins,lut);
p=pixels;
for (y=0; y < (ssize_t) clahe_info->y; y++)
{
register ssize_t
x;
for (x=0; x < (ssize_t) clahe_info->x; x++)
{
size_t
*histogram;
histogram=tiles+(number_bins*(y*clahe_info->x+x));
GenerateCLAHEHistogram(clahe_info,tile_info,number_bins,lut,p,histogram);
ClipCLAHEHistogram((double) limit,number_bins,histogram);
MapCLAHEHistogram(range_info,number_bins,tile_info->width*
tile_info->height,histogram);
p+=tile_info->width;
}
p+=clahe_info->width*(tile_info->height-1);
}
/*
Interpolate greylevel mappings to get CLAHE image.
*/
p=pixels;
for (y=0; y <= (ssize_t) clahe_info->y; y++)
{
OffsetInfo
offset;
RectangleInfo
tile;
register ssize_t
x;
tile.height=tile_info->height;
tile.y=y-1;
offset.y=tile.y+1;
if (y == 0)
{
/*
Top row.
*/
tile.height=tile_info->height >> 1;
tile.y=0;
offset.y=0;
}
else
if (y == (ssize_t) clahe_info->y)
{
/*
Bottom row.
*/
tile.height=(tile_info->height+1) >> 1;
tile.y=clahe_info->y-1;
offset.y=tile.y;
}
for (x=0; x <= (ssize_t) clahe_info->x; x++)
{
tile.width=tile_info->width;
tile.x=x-1;
offset.x=tile.x+1;
if (x == 0)
{
/*
Left column.
*/
tile.width=tile_info->width >> 1;
tile.x=0;
offset.x=0;
}
else
if (x == (ssize_t) clahe_info->x)
{
/*
Right column.
*/
tile.width=(tile_info->width+1) >> 1;
tile.x=clahe_info->x-1;
offset.x=tile.x;
}
InterpolateCLAHE(clahe_info,
tiles+(number_bins*(tile.y*clahe_info->x+tile.x)), /* Q12 */
tiles+(number_bins*(tile.y*clahe_info->x+offset.x)), /* Q22 */
tiles+(number_bins*(offset.y*clahe_info->x+tile.x)), /* Q11 */
tiles+(number_bins*(offset.y*clahe_info->x+offset.x)), /* Q21 */
&tile,lut,p);
p+=tile.width;
}
p+=clahe_info->width*(tile.height-1);
}
tile_cache=RelinquishVirtualMemory(tile_cache);
return(MagickTrue);
}
MagickExport MagickBooleanType CLAHEImage(Image *image,const size_t width,
const size_t height,const size_t number_bins,const double clip_limit,
ExceptionInfo *exception)
{
#define CLAHEImageTag "CLAHE/Image"
CacheView
*image_view;
ColorspaceType
colorspace;
MagickBooleanType
status;
MagickOffsetType
progress;
MemoryInfo
*pixel_cache;
RangeInfo
range_info;
RectangleInfo
clahe_info,
tile_info;
size_t
n;
ssize_t
y;
unsigned short
*pixels;
/*
Configure CLAHE parameters.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
range_info.min=0;
range_info.max=NumberCLAHEGrays-1;
tile_info.width=width;
if (tile_info.width == 0)
tile_info.width=image->columns >> 3;
tile_info.height=height;
if (tile_info.height == 0)
tile_info.height=image->rows >> 3;
tile_info.x=0;
if ((image->columns % tile_info.width) != 0)
tile_info.x=(ssize_t) tile_info.width-(image->columns % tile_info.width);
tile_info.y=0;
if ((image->rows % tile_info.height) != 0)
tile_info.y=(ssize_t) tile_info.height-(image->rows % tile_info.height);
clahe_info.width=image->columns+tile_info.x;
clahe_info.height=image->rows+tile_info.y;
clahe_info.x=(ssize_t) clahe_info.width/tile_info.width;
clahe_info.y=(ssize_t) clahe_info.height/tile_info.height;
pixel_cache=AcquireVirtualMemory(clahe_info.width,clahe_info.height*
sizeof(*pixels));
if (pixel_cache == (MemoryInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
pixels=(unsigned short *) GetVirtualMemoryBlob(pixel_cache);
colorspace=image->colorspace;
if (TransformImageColorspace(image,LabColorspace,exception) == MagickFalse)
{
pixel_cache=RelinquishVirtualMemory(pixel_cache);
return(MagickFalse);
}
/*
Initialize CLAHE pixels.
*/
image_view=AcquireVirtualCacheView(image,exception);
progress=0;
status=MagickTrue;
n=0;
for (y=0; y < (ssize_t) clahe_info.height; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-(tile_info.x >> 1),y-
(tile_info.y >> 1),clahe_info.width,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) clahe_info.width; x++)
{
pixels[n++]=ScaleQuantumToShort(p[0]);
p+=GetPixelChannels(image);
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,CLAHEImageTag,progress,2*
GetPixelChannels(image));
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
status=CLAHE(&clahe_info,&tile_info,&range_info,number_bins == 0 ?
(size_t) 128 : MagickMin(number_bins,256),clip_limit,pixels);
if (status == MagickFalse)
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
/*
Push CLAHE pixels to CLAHE image.
*/
image_view=AcquireAuthenticCacheView(image,exception);
n=clahe_info.width*(tile_info.y >> 1);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
n+=tile_info.x >> 1;
for (x=0; x < (ssize_t) image->columns; x++)
{
q[0]=ScaleShortToQuantum(pixels[n++]);
q+=GetPixelChannels(image);
}
n+=(clahe_info.width-image->columns-(tile_info.x >> 1));
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,CLAHEImageTag,progress,2*
GetPixelChannels(image));
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
pixel_cache=RelinquishVirtualMemory(pixel_cache);
if (TransformImageColorspace(image,colorspace,exception) == MagickFalse)
status=MagickFalse;
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l u t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClutImage() replaces each color value in the given image, by using it as an
% index to lookup a replacement color value in a Color Look UP Table in the
% form of an image. The values are extracted along a diagonal of the CLUT
% image so either a horizontal or vertial gradient image can be used.
%
% Typically this is used to either re-color a gray-scale image according to a
% color gradient in the CLUT image, or to perform a freeform histogram
% (level) adjustment according to the (typically gray-scale) gradient in the
% CLUT image.
%
% When the 'channel' mask includes the matte/alpha transparency channel but
% one image has no such channel it is assumed that that image is a simple
% gray-scale image that will effect the alpha channel values, either for
% gray-scale coloring (with transparent or semi-transparent colors), or
% a histogram adjustment of existing alpha channel values. If both images
% have matte channels, direct and normal indexing is applied, which is rarely
% used.
%
% The format of the ClutImage method is:
%
% MagickBooleanType ClutImage(Image *image,Image *clut_image,
% const PixelInterpolateMethod method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image, which is replaced by indexed CLUT values
%
% o clut_image: the color lookup table image for replacement color values.
%
% o method: the pixel interpolation method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ClutImage(Image *image,const Image *clut_image,
const PixelInterpolateMethod method,ExceptionInfo *exception)
{
#define ClutImageTag "Clut/Image"
CacheView
*clut_view,
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
*clut_map;
register ssize_t
i;
ssize_t adjust,
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(clut_image != (Image *) NULL);
assert(clut_image->signature == MagickCoreSignature);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
(IsGrayColorspace(clut_image->colorspace) == MagickFalse))
(void) SetImageColorspace(image,sRGBColorspace,exception);
clut_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*clut_map));
if (clut_map == (PixelInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
/*
Clut image.
*/
status=MagickTrue;
progress=0;
adjust=(ssize_t) (clut_image->interpolate == IntegerInterpolatePixel ? 0 : 1);
clut_view=AcquireVirtualCacheView(clut_image,exception);
for (i=0; i <= (ssize_t) MaxMap; i++)
{
GetPixelInfo(clut_image,clut_map+i);
status=InterpolatePixelInfo(clut_image,clut_view,method,
(double) i*(clut_image->columns-adjust)/MaxMap,(double) i*
(clut_image->rows-adjust)/MaxMap,clut_map+i,exception);
if (status == MagickFalse)
break;
}
clut_view=DestroyCacheView(clut_view);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelInfo
pixel;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
GetPixelInfo(image,&pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
PixelTrait
traits;
GetPixelInfoPixel(image,q,&pixel);
traits=GetPixelChannelTraits(image,RedPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
pixel.red=clut_map[ScaleQuantumToMap(ClampToQuantum(
pixel.red))].red;
traits=GetPixelChannelTraits(image,GreenPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
pixel.green=clut_map[ScaleQuantumToMap(ClampToQuantum(
pixel.green))].green;
traits=GetPixelChannelTraits(image,BluePixelChannel);
if ((traits & UpdatePixelTrait) != 0)
pixel.blue=clut_map[ScaleQuantumToMap(ClampToQuantum(
pixel.blue))].blue;
traits=GetPixelChannelTraits(image,BlackPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
pixel.black=clut_map[ScaleQuantumToMap(ClampToQuantum(
pixel.black))].black;
traits=GetPixelChannelTraits(image,AlphaPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
pixel.alpha=clut_map[ScaleQuantumToMap(ClampToQuantum(
pixel.alpha))].alpha;
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ClutImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
clut_map=(PixelInfo *) RelinquishMagickMemory(clut_map);
if ((clut_image->alpha_trait != UndefinedPixelTrait) &&
((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0))
(void) SetImageAlphaChannel(image,ActivateAlphaChannel,exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o l o r D e c i s i o n L i s t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ColorDecisionListImage() accepts a lightweight Color Correction Collection
% (CCC) file which solely contains one or more color corrections and applies
% the correction to the image. Here is a sample CCC file:
%
% <ColorCorrectionCollection xmlns="urn:ASC:CDL:v1.2">
% <ColorCorrection id="cc03345">
% <SOPNode>
% <Slope> 0.9 1.2 0.5 </Slope>
% <Offset> 0.4 -0.5 0.6 </Offset>
% <Power> 1.0 0.8 1.5 </Power>
% </SOPNode>
% <SATNode>
% <Saturation> 0.85 </Saturation>
% </SATNode>
% </ColorCorrection>
% </ColorCorrectionCollection>
%
% which includes the slop, offset, and power for each of the RGB channels
% as well as the saturation.
%
% The format of the ColorDecisionListImage method is:
%
% MagickBooleanType ColorDecisionListImage(Image *image,
% const char *color_correction_collection,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o color_correction_collection: the color correction collection in XML.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ColorDecisionListImage(Image *image,
const char *color_correction_collection,ExceptionInfo *exception)
{
#define ColorDecisionListCorrectImageTag "ColorDecisionList/Image"
typedef struct _Correction
{
double
slope,
offset,
power;
} Correction;
typedef struct _ColorCorrection
{
Correction
red,
green,
blue;
double
saturation;
} ColorCorrection;
CacheView
*image_view;
char
token[MagickPathExtent];
ColorCorrection
color_correction;
const char
*content,
*p;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
*cdl_map;
register ssize_t
i;
ssize_t
y;
XMLTreeInfo
*cc,
*ccc,
*sat,
*sop;
/*
Allocate and initialize cdl maps.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (color_correction_collection == (const char *) NULL)
return(MagickFalse);
ccc=NewXMLTree((const char *) color_correction_collection,exception);
if (ccc == (XMLTreeInfo *) NULL)
return(MagickFalse);
cc=GetXMLTreeChild(ccc,"ColorCorrection");
if (cc == (XMLTreeInfo *) NULL)
{
ccc=DestroyXMLTree(ccc);
return(MagickFalse);
}
color_correction.red.slope=1.0;
color_correction.red.offset=0.0;
color_correction.red.power=1.0;
color_correction.green.slope=1.0;
color_correction.green.offset=0.0;
color_correction.green.power=1.0;
color_correction.blue.slope=1.0;
color_correction.blue.offset=0.0;
color_correction.blue.power=1.0;
color_correction.saturation=0.0;
sop=GetXMLTreeChild(cc,"SOPNode");
if (sop != (XMLTreeInfo *) NULL)
{
XMLTreeInfo
*offset,
*power,
*slope;
slope=GetXMLTreeChild(sop,"Slope");
if (slope != (XMLTreeInfo *) NULL)
{
content=GetXMLTreeContent(slope);
p=(const char *) content;
for (i=0; (*p != '\0') && (i < 3); i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
switch (i)
{
case 0:
{
color_correction.red.slope=StringToDouble(token,(char **) NULL);
break;
}
case 1:
{
color_correction.green.slope=StringToDouble(token,
(char **) NULL);
break;
}
case 2:
{
color_correction.blue.slope=StringToDouble(token,
(char **) NULL);
break;
}
}
}
}
offset=GetXMLTreeChild(sop,"Offset");
if (offset != (XMLTreeInfo *) NULL)
{
content=GetXMLTreeContent(offset);
p=(const char *) content;
for (i=0; (*p != '\0') && (i < 3); i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
switch (i)
{
case 0:
{
color_correction.red.offset=StringToDouble(token,
(char **) NULL);
break;
}
case 1:
{
color_correction.green.offset=StringToDouble(token,
(char **) NULL);
break;
}
case 2:
{
color_correction.blue.offset=StringToDouble(token,
(char **) NULL);
break;
}
}
}
}
power=GetXMLTreeChild(sop,"Power");
if (power != (XMLTreeInfo *) NULL)
{
content=GetXMLTreeContent(power);
p=(const char *) content;
for (i=0; (*p != '\0') && (i < 3); i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
switch (i)
{
case 0:
{
color_correction.red.power=StringToDouble(token,(char **) NULL);
break;
}
case 1:
{
color_correction.green.power=StringToDouble(token,
(char **) NULL);
break;
}
case 2:
{
color_correction.blue.power=StringToDouble(token,
(char **) NULL);
break;
}
}
}
}
}
sat=GetXMLTreeChild(cc,"SATNode");
if (sat != (XMLTreeInfo *) NULL)
{
XMLTreeInfo
*saturation;
saturation=GetXMLTreeChild(sat,"Saturation");
if (saturation != (XMLTreeInfo *) NULL)
{
content=GetXMLTreeContent(saturation);
p=(const char *) content;
GetNextToken(p,&p,MagickPathExtent,token);
color_correction.saturation=StringToDouble(token,(char **) NULL);
}
}
ccc=DestroyXMLTree(ccc);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" Color Correction Collection:");
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.red.slope: %g",color_correction.red.slope);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.red.offset: %g",color_correction.red.offset);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.red.power: %g",color_correction.red.power);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.green.slope: %g",color_correction.green.slope);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.green.offset: %g",color_correction.green.offset);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.green.power: %g",color_correction.green.power);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.blue.slope: %g",color_correction.blue.slope);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.blue.offset: %g",color_correction.blue.offset);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.blue.power: %g",color_correction.blue.power);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.saturation: %g",color_correction.saturation);
}
cdl_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*cdl_map));
if (cdl_map == (PixelInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
for (i=0; i <= (ssize_t) MaxMap; i++)
{
cdl_map[i].red=(double) ScaleMapToQuantum((double)
(MaxMap*(pow(color_correction.red.slope*i/MaxMap+
color_correction.red.offset,color_correction.red.power))));
cdl_map[i].green=(double) ScaleMapToQuantum((double)
(MaxMap*(pow(color_correction.green.slope*i/MaxMap+
color_correction.green.offset,color_correction.green.power))));
cdl_map[i].blue=(double) ScaleMapToQuantum((double)
(MaxMap*(pow(color_correction.blue.slope*i/MaxMap+
color_correction.blue.offset,color_correction.blue.power))));
}
if (image->storage_class == PseudoClass)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Apply transfer function to colormap.
*/
double
luma;
luma=0.21267f*image->colormap[i].red+0.71526*image->colormap[i].green+
0.07217f*image->colormap[i].blue;
image->colormap[i].red=luma+color_correction.saturation*cdl_map[
ScaleQuantumToMap(ClampToQuantum(image->colormap[i].red))].red-luma;
image->colormap[i].green=luma+color_correction.saturation*cdl_map[
ScaleQuantumToMap(ClampToQuantum(image->colormap[i].green))].green-luma;
image->colormap[i].blue=luma+color_correction.saturation*cdl_map[
ScaleQuantumToMap(ClampToQuantum(image->colormap[i].blue))].blue-luma;
}
/*
Apply transfer function to image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
luma;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
luma=0.21267f*GetPixelRed(image,q)+0.71526*GetPixelGreen(image,q)+
0.07217f*GetPixelBlue(image,q);
SetPixelRed(image,ClampToQuantum(luma+color_correction.saturation*
(cdl_map[ScaleQuantumToMap(GetPixelRed(image,q))].red-luma)),q);
SetPixelGreen(image,ClampToQuantum(luma+color_correction.saturation*
(cdl_map[ScaleQuantumToMap(GetPixelGreen(image,q))].green-luma)),q);
SetPixelBlue(image,ClampToQuantum(luma+color_correction.saturation*
(cdl_map[ScaleQuantumToMap(GetPixelBlue(image,q))].blue-luma)),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ColorDecisionListCorrectImageTag,
progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
cdl_map=(PixelInfo *) RelinquishMagickMemory(cdl_map);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o n t r a s t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ContrastImage() enhances the intensity differences between the lighter and
% darker elements of the image. Set sharpen to a MagickTrue to increase the
% image contrast otherwise the contrast is reduced.
%
% The format of the ContrastImage method is:
%
% MagickBooleanType ContrastImage(Image *image,
% const MagickBooleanType sharpen,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o sharpen: Increase or decrease image contrast.
%
% o exception: return any errors or warnings in this structure.
%
*/
static void Contrast(const int sign,double *red,double *green,double *blue)
{
double
brightness,
hue,
saturation;
/*
Enhance contrast: dark color become darker, light color become lighter.
*/
assert(red != (double *) NULL);
assert(green != (double *) NULL);
assert(blue != (double *) NULL);
hue=0.0;
saturation=0.0;
brightness=0.0;
ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness);
brightness+=0.5*sign*(0.5*(sin((double) (MagickPI*(brightness-0.5)))+1.0)-
brightness);
if (brightness > 1.0)
brightness=1.0;
else
if (brightness < 0.0)
brightness=0.0;
ConvertHSBToRGB(hue,saturation,brightness,red,green,blue);
}
MagickExport MagickBooleanType ContrastImage(Image *image,
const MagickBooleanType sharpen,ExceptionInfo *exception)
{
#define ContrastImageTag "Contrast/Image"
CacheView
*image_view;
int
sign;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
if (AccelerateContrastImage(image,sharpen,exception) != MagickFalse)
return(MagickTrue);
#endif
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
sign=sharpen != MagickFalse ? 1 : -1;
if (image->storage_class == PseudoClass)
{
/*
Contrast enhance colormap.
*/
for (i=0; i < (ssize_t) image->colors; i++)
{
double
blue,
green,
red;
red=(double) image->colormap[i].red;
green=(double) image->colormap[i].green;
blue=(double) image->colormap[i].blue;
Contrast(sign,&red,&green,&blue);
image->colormap[i].red=(MagickRealType) red;
image->colormap[i].green=(MagickRealType) green;
image->colormap[i].blue=(MagickRealType) blue;
}
}
/*
Contrast enhance image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
blue,
green,
red;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
red=(double) GetPixelRed(image,q);
green=(double) GetPixelGreen(image,q);
blue=(double) GetPixelBlue(image,q);
Contrast(sign,&red,&green,&blue);
SetPixelRed(image,ClampToQuantum(red),q);
SetPixelGreen(image,ClampToQuantum(green),q);
SetPixelBlue(image,ClampToQuantum(blue),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ContrastImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o n t r a s t S t r e t c h I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ContrastStretchImage() is a simple image enhancement technique that attempts
% to improve the contrast in an image by 'stretching' the range of intensity
% values it contains to span a desired range of values. It differs from the
% more sophisticated histogram equalization in that it can only apply a
% linear scaling function to the image pixel values. As a result the
% 'enhancement' is less harsh.
%
% The format of the ContrastStretchImage method is:
%
% MagickBooleanType ContrastStretchImage(Image *image,
% const char *levels,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o black_point: the black point.
%
% o white_point: the white point.
%
% o levels: Specify the levels where the black and white points have the
% range of 0 to number-of-pixels (e.g. 1%, 10x90%, etc.).
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ContrastStretchImage(Image *image,
const double black_point,const double white_point,ExceptionInfo *exception)
{
#define MaxRange(color) ((double) ScaleQuantumToMap((Quantum) (color)))
#define ContrastStretchImageTag "ContrastStretch/Image"
CacheView
*image_view;
double
*black,
*histogram,
*stretch_map,
*white;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
/*
Allocate histogram and stretch map.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageGray(image,exception) != MagickFalse)
(void) SetImageColorspace(image,GRAYColorspace,exception);
black=(double *) AcquireQuantumMemory(MaxPixelChannels,sizeof(*black));
white=(double *) AcquireQuantumMemory(MaxPixelChannels,sizeof(*white));
histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*
sizeof(*histogram));
stretch_map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*
sizeof(*stretch_map));
if ((black == (double *) NULL) || (white == (double *) NULL) ||
(histogram == (double *) NULL) || (stretch_map == (double *) NULL))
{
if (stretch_map != (double *) NULL)
stretch_map=(double *) RelinquishMagickMemory(stretch_map);
if (histogram != (double *) NULL)
histogram=(double *) RelinquishMagickMemory(histogram);
if (white != (double *) NULL)
white=(double *) RelinquishMagickMemory(white);
if (black != (double *) NULL)
black=(double *) RelinquishMagickMemory(black);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
/*
Form histogram.
*/
status=MagickTrue;
(void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*histogram));
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
pixel;
pixel=GetPixelIntensity(image,p);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
if (image->channel_mask != DefaultChannels)
pixel=(double) p[i];
histogram[GetPixelChannels(image)*ScaleQuantumToMap(
ClampToQuantum(pixel))+i]++;
}
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
/*
Find the histogram boundaries by locating the black/white levels.
*/
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
intensity;
register ssize_t
j;
black[i]=0.0;
white[i]=MaxRange(QuantumRange);
intensity=0.0;
for (j=0; j <= (ssize_t) MaxMap; j++)
{
intensity+=histogram[GetPixelChannels(image)*j+i];
if (intensity > black_point)
break;
}
black[i]=(double) j;
intensity=0.0;
for (j=(ssize_t) MaxMap; j != 0; j--)
{
intensity+=histogram[GetPixelChannels(image)*j+i];
if (intensity > ((double) image->columns*image->rows-white_point))
break;
}
white[i]=(double) j;
}
histogram=(double *) RelinquishMagickMemory(histogram);
/*
Stretch the histogram to create the stretched image mapping.
*/
(void) memset(stretch_map,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*stretch_map));
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
register ssize_t
j;
for (j=0; j <= (ssize_t) MaxMap; j++)
{
double
gamma;
gamma=PerceptibleReciprocal(white[i]-black[i]);
if (j < (ssize_t) black[i])
stretch_map[GetPixelChannels(image)*j+i]=0.0;
else
if (j > (ssize_t) white[i])
stretch_map[GetPixelChannels(image)*j+i]=(double) QuantumRange;
else
if (black[i] != white[i])
stretch_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum(
(double) (MaxMap*gamma*(j-black[i])));
}
}
if (image->storage_class == PseudoClass)
{
register ssize_t
j;
/*
Stretch-contrast colormap.
*/
for (j=0; j < (ssize_t) image->colors; j++)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,RedPixelChannel);
image->colormap[j].red=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+i];
}
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,GreenPixelChannel);
image->colormap[j].green=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+i];
}
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,BluePixelChannel);
image->colormap[j].blue=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+i];
}
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,AlphaPixelChannel);
image->colormap[j].alpha=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+i];
}
}
}
/*
Stretch-contrast image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel = GetPixelChannelChannel(image,j);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (black[j] == white[j])
continue;
q[j]=ClampToQuantum(stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(q[j])+j]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ContrastStretchImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
stretch_map=(double *) RelinquishMagickMemory(stretch_map);
white=(double *) RelinquishMagickMemory(white);
black=(double *) RelinquishMagickMemory(black);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E n h a n c e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% EnhanceImage() applies a digital filter that improves the quality of a
% noisy image.
%
% The format of the EnhanceImage method is:
%
% Image *EnhanceImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *EnhanceImage(const Image *image,ExceptionInfo *exception)
{
#define EnhanceImageTag "Enhance/Image"
#define EnhancePixel(weight) \
mean=QuantumScale*((double) GetPixelRed(image,r)+pixel.red)/2.0; \
distance=QuantumScale*((double) GetPixelRed(image,r)-pixel.red); \
distance_squared=(4.0+mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelGreen(image,r)+pixel.green)/2.0; \
distance=QuantumScale*((double) GetPixelGreen(image,r)-pixel.green); \
distance_squared+=(7.0-mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelBlue(image,r)+pixel.blue)/2.0; \
distance=QuantumScale*((double) GetPixelBlue(image,r)-pixel.blue); \
distance_squared+=(5.0-mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelBlack(image,r)+pixel.black)/2.0; \
distance=QuantumScale*((double) GetPixelBlack(image,r)-pixel.black); \
distance_squared+=(5.0-mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelAlpha(image,r)+pixel.alpha)/2.0; \
distance=QuantumScale*((double) GetPixelAlpha(image,r)-pixel.alpha); \
distance_squared+=(5.0-mean)*distance*distance; \
if (distance_squared < 0.069) \
{ \
aggregate.red+=(weight)*GetPixelRed(image,r); \
aggregate.green+=(weight)*GetPixelGreen(image,r); \
aggregate.blue+=(weight)*GetPixelBlue(image,r); \
aggregate.black+=(weight)*GetPixelBlack(image,r); \
aggregate.alpha+=(weight)*GetPixelAlpha(image,r); \
total_weight+=(weight); \
} \
r+=GetPixelChannels(image);
CacheView
*enhance_view,
*image_view;
Image
*enhance_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Initialize enhanced image attributes.
*/
assert(image != (const 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);
enhance_image=CloneImage(image,0,0,MagickTrue,
exception);
if (enhance_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(enhance_image,DirectClass,exception) == MagickFalse)
{
enhance_image=DestroyImage(enhance_image);
return((Image *) NULL);
}
/*
Enhance image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
enhance_view=AcquireAuthenticCacheView(enhance_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,enhance_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelInfo
pixel;
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
ssize_t
center;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-2,y-2,image->columns+4,5,exception);
q=QueueCacheViewAuthenticPixels(enhance_view,0,y,enhance_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
center=(ssize_t) GetPixelChannels(image)*(2*(image->columns+4)+2);
GetPixelInfo(image,&pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
double
distance,
distance_squared,
mean,
total_weight;
PixelInfo
aggregate;
register const Quantum
*magick_restrict r;
GetPixelInfo(image,&aggregate);
total_weight=0.0;
GetPixelInfoPixel(image,p+center,&pixel);
r=p;
EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0);
EnhancePixel(8.0); EnhancePixel(5.0);
r=p+GetPixelChannels(image)*(image->columns+4);
EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0);
EnhancePixel(20.0); EnhancePixel(8.0);
r=p+2*GetPixelChannels(image)*(image->columns+4);
EnhancePixel(10.0); EnhancePixel(40.0); EnhancePixel(80.0);
EnhancePixel(40.0); EnhancePixel(10.0);
r=p+3*GetPixelChannels(image)*(image->columns+4);
EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0);
EnhancePixel(20.0); EnhancePixel(8.0);
r=p+4*GetPixelChannels(image)*(image->columns+4);
EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0);
EnhancePixel(8.0); EnhancePixel(5.0);
if (total_weight > MagickEpsilon)
{
pixel.red=((aggregate.red+total_weight/2.0)/total_weight);
pixel.green=((aggregate.green+total_weight/2.0)/total_weight);
pixel.blue=((aggregate.blue+total_weight/2.0)/total_weight);
pixel.black=((aggregate.black+total_weight/2.0)/total_weight);
pixel.alpha=((aggregate.alpha+total_weight/2.0)/total_weight);
}
SetPixelViaPixelInfo(image,&pixel,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(enhance_image);
}
if (SyncCacheViewAuthenticPixels(enhance_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,EnhanceImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
enhance_view=DestroyCacheView(enhance_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
enhance_image=DestroyImage(enhance_image);
return(enhance_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E q u a l i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% EqualizeImage() applies a histogram equalization to the image.
%
% The format of the EqualizeImage method is:
%
% MagickBooleanType EqualizeImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType EqualizeImage(Image *image,
ExceptionInfo *exception)
{
#define EqualizeImageTag "Equalize/Image"
CacheView
*image_view;
double
black[CompositePixelChannel+1],
*equalize_map,
*histogram,
*map,
white[CompositePixelChannel+1];
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
/*
Allocate and initialize histogram arrays.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
if (AccelerateEqualizeImage(image,exception) != MagickFalse)
return(MagickTrue);
#endif
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
equalize_map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*
sizeof(*equalize_map));
histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*
sizeof(*histogram));
map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*sizeof(*map));
if ((equalize_map == (double *) NULL) || (histogram == (double *) NULL) ||
(map == (double *) NULL))
{
if (map != (double *) NULL)
map=(double *) RelinquishMagickMemory(map);
if (histogram != (double *) NULL)
histogram=(double *) RelinquishMagickMemory(histogram);
if (equalize_map != (double *) NULL)
equalize_map=(double *) RelinquishMagickMemory(equalize_map);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
/*
Form histogram.
*/
status=MagickTrue;
(void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*histogram));
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
intensity;
intensity=(double) p[i];
if ((image->channel_mask & SyncChannels) != 0)
intensity=GetPixelIntensity(image,p);
histogram[GetPixelChannels(image)*ScaleQuantumToMap(
ClampToQuantum(intensity))+i]++;
}
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
/*
Integrate the histogram to get the equalization map.
*/
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
intensity;
register ssize_t
j;
intensity=0.0;
for (j=0; j <= (ssize_t) MaxMap; j++)
{
intensity+=histogram[GetPixelChannels(image)*j+i];
map[GetPixelChannels(image)*j+i]=intensity;
}
}
(void) memset(equalize_map,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*equalize_map));
(void) memset(black,0,sizeof(*black));
(void) memset(white,0,sizeof(*white));
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
register ssize_t
j;
black[i]=map[i];
white[i]=map[GetPixelChannels(image)*MaxMap+i];
if (black[i] != white[i])
for (j=0; j <= (ssize_t) MaxMap; j++)
equalize_map[GetPixelChannels(image)*j+i]=(double)
ScaleMapToQuantum((double) ((MaxMap*(map[
GetPixelChannels(image)*j+i]-black[i]))/(white[i]-black[i])));
}
histogram=(double *) RelinquishMagickMemory(histogram);
map=(double *) RelinquishMagickMemory(map);
if (image->storage_class == PseudoClass)
{
register ssize_t
j;
/*
Equalize colormap.
*/
for (j=0; j < (ssize_t) image->colors; j++)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
{
PixelChannel channel = GetPixelChannelChannel(image,
RedPixelChannel);
if (black[channel] != white[channel])
image->colormap[j].red=equalize_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+
channel];
}
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
{
PixelChannel channel = GetPixelChannelChannel(image,
GreenPixelChannel);
if (black[channel] != white[channel])
image->colormap[j].green=equalize_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+
channel];
}
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
{
PixelChannel channel = GetPixelChannelChannel(image,
BluePixelChannel);
if (black[channel] != white[channel])
image->colormap[j].blue=equalize_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+
channel];
}
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
{
PixelChannel channel = GetPixelChannelChannel(image,
AlphaPixelChannel);
if (black[channel] != white[channel])
image->colormap[j].alpha=equalize_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+
channel];
}
}
}
/*
Equalize image.
*/
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel = GetPixelChannelChannel(image,j);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (((traits & UpdatePixelTrait) == 0) || (black[j] == white[j]))
continue;
q[j]=ClampToQuantum(equalize_map[GetPixelChannels(image)*
ScaleQuantumToMap(q[j])+j]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,EqualizeImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
equalize_map=(double *) RelinquishMagickMemory(equalize_map);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G a m m a I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GammaImage() gamma-corrects a particular image channel. The same
% image viewed on different devices will have perceptual differences in the
% way the image's intensities are represented on the screen. Specify
% individual gamma levels for the red, green, and blue channels, or adjust
% all three with the gamma parameter. Values typically range from 0.8 to 2.3.
%
% You can also reduce the influence of a particular channel with a gamma
% value of 0.
%
% The format of the GammaImage method is:
%
% MagickBooleanType GammaImage(Image *image,const double gamma,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o level: the image gamma as a string (e.g. 1.6,1.2,1.0).
%
% o gamma: the image gamma.
%
*/
static inline double gamma_pow(const double value,const double gamma)
{
return(value < 0.0 ? value : pow(value,gamma));
}
MagickExport MagickBooleanType GammaImage(Image *image,const double gamma,
ExceptionInfo *exception)
{
#define GammaImageTag "Gamma/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
Quantum
*gamma_map;
register ssize_t
i;
ssize_t
y;
/*
Allocate and initialize gamma maps.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (gamma == 1.0)
return(MagickTrue);
gamma_map=(Quantum *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*gamma_map));
if (gamma_map == (Quantum *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
(void) memset(gamma_map,0,(MaxMap+1)*sizeof(*gamma_map));
if (gamma != 0.0)
for (i=0; i <= (ssize_t) MaxMap; i++)
gamma_map[i]=ScaleMapToQuantum((double) (MaxMap*pow((double) i/
MaxMap,1.0/gamma)));
if (image->storage_class == PseudoClass)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Gamma-correct colormap.
*/
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=(double) gamma_map[ScaleQuantumToMap(
ClampToQuantum(image->colormap[i].red))];
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=(double) gamma_map[ScaleQuantumToMap(
ClampToQuantum(image->colormap[i].green))];
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=(double) gamma_map[ScaleQuantumToMap(
ClampToQuantum(image->colormap[i].blue))];
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].alpha=(double) gamma_map[ScaleQuantumToMap(
ClampToQuantum(image->colormap[i].alpha))];
}
/*
Gamma-correct image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel = GetPixelChannelChannel(image,j);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[j]=gamma_map[ScaleQuantumToMap(ClampToQuantum((MagickRealType)
q[j]))];
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,GammaImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
gamma_map=(Quantum *) RelinquishMagickMemory(gamma_map);
if (image->gamma != 0.0)
image->gamma*=gamma;
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G r a y s c a l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GrayscaleImage() converts the image to grayscale.
%
% The format of the GrayscaleImage method is:
%
% MagickBooleanType GrayscaleImage(Image *image,
% const PixelIntensityMethod method ,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o method: the pixel intensity method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GrayscaleImage(Image *image,
const PixelIntensityMethod method,ExceptionInfo *exception)
{
#define GrayscaleImageTag "Grayscale/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
{
if (SyncImage(image,exception) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
}
#if defined(MAGICKCORE_OPENCL_SUPPORT)
if (AccelerateGrayscaleImage(image,method,exception) != MagickFalse)
{
image->intensity=method;
image->type=GrayscaleType;
if ((method == Rec601LuminancePixelIntensityMethod) ||
(method == Rec709LuminancePixelIntensityMethod))
return(SetImageColorspace(image,LinearGRAYColorspace,exception));
return(SetImageColorspace(image,GRAYColorspace,exception));
}
#endif
/*
Grayscale image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickRealType
blue,
green,
red,
intensity;
red=(MagickRealType) GetPixelRed(image,q);
green=(MagickRealType) GetPixelGreen(image,q);
blue=(MagickRealType) GetPixelBlue(image,q);
intensity=0.0;
switch (method)
{
case AveragePixelIntensityMethod:
{
intensity=(red+green+blue)/3.0;
break;
}
case BrightnessPixelIntensityMethod:
{
intensity=MagickMax(MagickMax(red,green),blue);
break;
}
case LightnessPixelIntensityMethod:
{
intensity=(MagickMin(MagickMin(red,green),blue)+
MagickMax(MagickMax(red,green),blue))/2.0;
break;
}
case MSPixelIntensityMethod:
{
intensity=(MagickRealType) (((double) red*red+green*green+
blue*blue)/3.0);
break;
}
case Rec601LumaPixelIntensityMethod:
{
if (image->colorspace == RGBColorspace)
{
red=EncodePixelGamma(red);
green=EncodePixelGamma(green);
blue=EncodePixelGamma(blue);
}
intensity=0.298839*red+0.586811*green+0.114350*blue;
break;
}
case Rec601LuminancePixelIntensityMethod:
{
if (image->colorspace == sRGBColorspace)
{
red=DecodePixelGamma(red);
green=DecodePixelGamma(green);
blue=DecodePixelGamma(blue);
}
intensity=0.298839*red+0.586811*green+0.114350*blue;
break;
}
case Rec709LumaPixelIntensityMethod:
default:
{
if (image->colorspace == RGBColorspace)
{
red=EncodePixelGamma(red);
green=EncodePixelGamma(green);
blue=EncodePixelGamma(blue);
}
intensity=0.212656*red+0.715158*green+0.072186*blue;
break;
}
case Rec709LuminancePixelIntensityMethod:
{
if (image->colorspace == sRGBColorspace)
{
red=DecodePixelGamma(red);
green=DecodePixelGamma(green);
blue=DecodePixelGamma(blue);
}
intensity=0.212656*red+0.715158*green+0.072186*blue;
break;
}
case RMSPixelIntensityMethod:
{
intensity=(MagickRealType) (sqrt((double) red*red+green*green+
blue*blue)/sqrt(3.0));
break;
}
}
SetPixelGray(image,ClampToQuantum(intensity),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,GrayscaleImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
image->intensity=method;
image->type=GrayscaleType;
if ((method == Rec601LuminancePixelIntensityMethod) ||
(method == Rec709LuminancePixelIntensityMethod))
return(SetImageColorspace(image,LinearGRAYColorspace,exception));
return(SetImageColorspace(image,GRAYColorspace,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% H a l d C l u t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% HaldClutImage() applies a Hald color lookup table to the image. A Hald
% color lookup table is a 3-dimensional color cube mapped to 2 dimensions.
% Create it with the HALD coder. You can apply any color transformation to
% the Hald image and then use this method to apply the transform to the
% image.
%
% The format of the HaldClutImage method is:
%
% MagickBooleanType HaldClutImage(Image *image,Image *hald_image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image, which is replaced by indexed CLUT values
%
% o hald_image: the color lookup table image for replacement color values.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType HaldClutImage(Image *image,
const Image *hald_image,ExceptionInfo *exception)
{
#define HaldClutImageTag "Clut/Image"
typedef struct _HaldInfo
{
double
x,
y,
z;
} HaldInfo;
CacheView
*hald_view,
*image_view;
double
width;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
zero;
size_t
cube_size,
length,
level;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(hald_image != (Image *) NULL);
assert(hald_image->signature == MagickCoreSignature);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
/*
Hald clut image.
*/
status=MagickTrue;
progress=0;
length=(size_t) MagickMin((MagickRealType) hald_image->columns,
(MagickRealType) hald_image->rows);
for (level=2; (level*level*level) < length; level++) ;
level*=level;
cube_size=level*level;
width=(double) hald_image->columns;
GetPixelInfo(hald_image,&zero);
hald_view=AcquireVirtualCacheView(hald_image,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
offset;
HaldInfo
point;
PixelInfo
pixel,
pixel1,
pixel2,
pixel3,
pixel4;
point.x=QuantumScale*(level-1.0)*GetPixelRed(image,q);
point.y=QuantumScale*(level-1.0)*GetPixelGreen(image,q);
point.z=QuantumScale*(level-1.0)*GetPixelBlue(image,q);
offset=point.x+level*floor(point.y)+cube_size*floor(point.z);
point.x-=floor(point.x);
point.y-=floor(point.y);
point.z-=floor(point.z);
pixel1=zero;
status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate,
fmod(offset,width),floor(offset/width),&pixel1,exception);
if (status == MagickFalse)
break;
pixel2=zero;
status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate,
fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception);
if (status == MagickFalse)
break;
pixel3=zero;
CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha,
point.y,&pixel3);
offset+=cube_size;
status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate,
fmod(offset,width),floor(offset/width),&pixel1,exception);
if (status == MagickFalse)
break;
status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate,
fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception);
if (status == MagickFalse)
break;
pixel4=zero;
CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha,
point.y,&pixel4);
pixel=zero;
CompositePixelInfoAreaBlend(&pixel3,pixel3.alpha,&pixel4,pixel4.alpha,
point.z,&pixel);
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
SetPixelRed(image,ClampToQuantum(pixel.red),q);
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
SetPixelGreen(image,ClampToQuantum(pixel.green),q);
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
SetPixelBlue(image,ClampToQuantum(pixel.blue),q);
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelBlack(image,ClampToQuantum(pixel.black),q);
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,HaldClutImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
hald_view=DestroyCacheView(hald_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L e v e l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LevelImage() adjusts the levels of a particular image channel by
% scaling the colors falling between specified white and black points to
% the full available quantum range.
%
% The parameters provided represent the black, and white points. The black
% point specifies the darkest color in the image. Colors darker than the
% black point are set to zero. White point specifies the lightest color in
% the image. Colors brighter than the white point are set to the maximum
% quantum value.
%
% If a '!' flag is given, map black and white colors to the given levels
% rather than mapping those levels to black and white. See
% LevelizeImage() below.
%
% Gamma specifies a gamma correction to apply to the image.
%
% The format of the LevelImage method is:
%
% MagickBooleanType LevelImage(Image *image,const double black_point,
% const double white_point,const double gamma,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o black_point: The level to map zero (black) to.
%
% o white_point: The level to map QuantumRange (white) to.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double LevelPixel(const double black_point,
const double white_point,const double gamma,const double pixel)
{
double
level_pixel,
scale;
scale=PerceptibleReciprocal(white_point-black_point);
level_pixel=QuantumRange*gamma_pow(scale*((double) pixel-black_point),
1.0/gamma);
return(level_pixel);
}
MagickExport MagickBooleanType LevelImage(Image *image,const double black_point,
const double white_point,const double gamma,ExceptionInfo *exception)
{
#define LevelImageTag "Level/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
/*
Allocate and initialize levels map.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Level colormap.
*/
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=(double) ClampToQuantum(LevelPixel(black_point,
white_point,gamma,image->colormap[i].red));
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=(double) ClampToQuantum(LevelPixel(black_point,
white_point,gamma,image->colormap[i].green));
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=(double) ClampToQuantum(LevelPixel(black_point,
white_point,gamma,image->colormap[i].blue));
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].alpha=(double) ClampToQuantum(LevelPixel(black_point,
white_point,gamma,image->colormap[i].alpha));
}
/*
Level image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel = GetPixelChannelChannel(image,j);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[j]=ClampToQuantum(LevelPixel(black_point,white_point,gamma,
(double) q[j]));
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,LevelImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
(void) ClampImage(image,exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L e v e l i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LevelizeImage() applies the reversed LevelImage() operation to just
% the specific channels specified. It compresses the full range of color
% values, so that they lie between the given black and white points. Gamma is
% applied before the values are mapped.
%
% LevelizeImage() can be called with by using a +level command line
% API option, or using a '!' on a -level or LevelImage() geometry string.
%
% It can be used to de-contrast a greyscale image to the exact levels
% specified. Or by using specific levels for each channel of an image you
% can convert a gray-scale image to any linear color gradient, according to
% those levels.
%
% The format of the LevelizeImage method is:
%
% MagickBooleanType LevelizeImage(Image *image,const double black_point,
% const double white_point,const double gamma,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o black_point: The level to map zero (black) to.
%
% o white_point: The level to map QuantumRange (white) to.
%
% o gamma: adjust gamma by this factor before mapping values.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType LevelizeImage(Image *image,
const double black_point,const double white_point,const double gamma,
ExceptionInfo *exception)
{
#define LevelizeImageTag "Levelize/Image"
#define LevelizeValue(x) ClampToQuantum(((MagickRealType) gamma_pow((double) \
(QuantumScale*(x)),gamma))*(white_point-black_point)+black_point)
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
/*
Allocate and initialize levels map.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Level colormap.
*/
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=(double) LevelizeValue(image->colormap[i].red);
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=(double) LevelizeValue(
image->colormap[i].green);
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=(double) LevelizeValue(image->colormap[i].blue);
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].alpha=(double) LevelizeValue(
image->colormap[i].alpha);
}
/*
Level image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel = GetPixelChannelChannel(image,j);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[j]=LevelizeValue(q[j]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,LevelizeImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L e v e l I m a g e C o l o r s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LevelImageColors() maps the given color to "black" and "white" values,
% linearly spreading out the colors, and level values on a channel by channel
% bases, as per LevelImage(). The given colors allows you to specify
% different level ranges for each of the color channels separately.
%
% If the boolean 'invert' is set true the image values will modifyed in the
% reverse direction. That is any existing "black" and "white" colors in the
% image will become the color values given, with all other values compressed
% appropriatally. This effectivally maps a greyscale gradient into the given
% color gradient.
%
% The format of the LevelImageColors method is:
%
% MagickBooleanType LevelImageColors(Image *image,
% const PixelInfo *black_color,const PixelInfo *white_color,
% const MagickBooleanType invert,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o black_color: The color to map black to/from
%
% o white_point: The color to map white to/from
%
% o invert: if true map the colors (levelize), rather than from (level)
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType LevelImageColors(Image *image,
const PixelInfo *black_color,const PixelInfo *white_color,
const MagickBooleanType invert,ExceptionInfo *exception)
{
ChannelType
channel_mask;
MagickStatusType
status;
/*
Allocate and initialize levels map.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
((IsGrayColorspace(black_color->colorspace) == MagickFalse) ||
(IsGrayColorspace(white_color->colorspace) == MagickFalse)))
(void) SetImageColorspace(image,sRGBColorspace,exception);
status=MagickTrue;
if (invert == MagickFalse)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
{
channel_mask=SetImageChannelMask(image,RedChannel);
status&=LevelImage(image,black_color->red,white_color->red,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
{
channel_mask=SetImageChannelMask(image,GreenChannel);
status&=LevelImage(image,black_color->green,white_color->green,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
{
channel_mask=SetImageChannelMask(image,BlueChannel);
status&=LevelImage(image,black_color->blue,white_color->blue,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
{
channel_mask=SetImageChannelMask(image,BlackChannel);
status&=LevelImage(image,black_color->black,white_color->black,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
{
channel_mask=SetImageChannelMask(image,AlphaChannel);
status&=LevelImage(image,black_color->alpha,white_color->alpha,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
}
else
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
{
channel_mask=SetImageChannelMask(image,RedChannel);
status&=LevelizeImage(image,black_color->red,white_color->red,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
{
channel_mask=SetImageChannelMask(image,GreenChannel);
status&=LevelizeImage(image,black_color->green,white_color->green,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
{
channel_mask=SetImageChannelMask(image,BlueChannel);
status&=LevelizeImage(image,black_color->blue,white_color->blue,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
{
channel_mask=SetImageChannelMask(image,BlackChannel);
status&=LevelizeImage(image,black_color->black,white_color->black,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
{
channel_mask=SetImageChannelMask(image,AlphaChannel);
status&=LevelizeImage(image,black_color->alpha,white_color->alpha,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
}
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L i n e a r S t r e t c h I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LinearStretchImage() discards any pixels below the black point and above
% the white point and levels the remaining pixels.
%
% The format of the LinearStretchImage method is:
%
% MagickBooleanType LinearStretchImage(Image *image,
% const double black_point,const double white_point,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o black_point: the black point.
%
% o white_point: the white point.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType LinearStretchImage(Image *image,
const double black_point,const double white_point,ExceptionInfo *exception)
{
#define LinearStretchImageTag "LinearStretch/Image"
CacheView
*image_view;
double
*histogram,
intensity;
MagickBooleanType
status;
ssize_t
black,
white,
y;
/*
Allocate histogram and linear map.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*histogram));
if (histogram == (double *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
/*
Form histogram.
*/
(void) memset(histogram,0,(MaxMap+1)*sizeof(*histogram));
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
intensity=GetPixelIntensity(image,p);
histogram[ScaleQuantumToMap(ClampToQuantum(intensity))]++;
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
/*
Find the histogram boundaries by locating the black and white point levels.
*/
intensity=0.0;
for (black=0; black < (ssize_t) MaxMap; black++)
{
intensity+=histogram[black];
if (intensity >= black_point)
break;
}
intensity=0.0;
for (white=(ssize_t) MaxMap; white != 0; white--)
{
intensity+=histogram[white];
if (intensity >= white_point)
break;
}
histogram=(double *) RelinquishMagickMemory(histogram);
status=LevelImage(image,(double) ScaleMapToQuantum((MagickRealType) black),
(double) ScaleMapToQuantum((MagickRealType) white),1.0,exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M o d u l a t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ModulateImage() lets you control the brightness, saturation, and hue
% of an image. Modulate represents the brightness, saturation, and hue
% as one parameter (e.g. 90,150,100). If the image colorspace is HSL, the
% modulation is lightness, saturation, and hue. For HWB, use blackness,
% whiteness, and hue. And for HCL, use chrome, luma, and hue.
%
% The format of the ModulateImage method is:
%
% MagickBooleanType ModulateImage(Image *image,const char *modulate,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o modulate: Define the percent change in brightness, saturation, and hue.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline void ModulateHCL(const double percent_hue,
const double percent_chroma,const double percent_luma,double *red,
double *green,double *blue)
{
double
hue,
luma,
chroma;
/*
Increase or decrease color luma, chroma, or hue.
*/
ConvertRGBToHCL(*red,*green,*blue,&hue,&chroma,&luma);
hue+=fmod((percent_hue-100.0),200.0)/200.0;
chroma*=0.01*percent_chroma;
luma*=0.01*percent_luma;
ConvertHCLToRGB(hue,chroma,luma,red,green,blue);
}
static inline void ModulateHCLp(const double percent_hue,
const double percent_chroma,const double percent_luma,double *red,
double *green,double *blue)
{
double
hue,
luma,
chroma;
/*
Increase or decrease color luma, chroma, or hue.
*/
ConvertRGBToHCLp(*red,*green,*blue,&hue,&chroma,&luma);
hue+=fmod((percent_hue-100.0),200.0)/200.0;
chroma*=0.01*percent_chroma;
luma*=0.01*percent_luma;
ConvertHCLpToRGB(hue,chroma,luma,red,green,blue);
}
static inline void ModulateHSB(const double percent_hue,
const double percent_saturation,const double percent_brightness,double *red,
double *green,double *blue)
{
double
brightness,
hue,
saturation;
/*
Increase or decrease color brightness, saturation, or hue.
*/
ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness);
hue+=fmod((percent_hue-100.0),200.0)/200.0;
saturation*=0.01*percent_saturation;
brightness*=0.01*percent_brightness;
ConvertHSBToRGB(hue,saturation,brightness,red,green,blue);
}
static inline void ModulateHSI(const double percent_hue,
const double percent_saturation,const double percent_intensity,double *red,
double *green,double *blue)
{
double
intensity,
hue,
saturation;
/*
Increase or decrease color intensity, saturation, or hue.
*/
ConvertRGBToHSI(*red,*green,*blue,&hue,&saturation,&intensity);
hue+=fmod((percent_hue-100.0),200.0)/200.0;
saturation*=0.01*percent_saturation;
intensity*=0.01*percent_intensity;
ConvertHSIToRGB(hue,saturation,intensity,red,green,blue);
}
static inline void ModulateHSL(const double percent_hue,
const double percent_saturation,const double percent_lightness,double *red,
double *green,double *blue)
{
double
hue,
lightness,
saturation;
/*
Increase or decrease color lightness, saturation, or hue.
*/
ConvertRGBToHSL(*red,*green,*blue,&hue,&saturation,&lightness);
hue+=fmod((percent_hue-100.0),200.0)/200.0;
saturation*=0.01*percent_saturation;
lightness*=0.01*percent_lightness;
ConvertHSLToRGB(hue,saturation,lightness,red,green,blue);
}
static inline void ModulateHSV(const double percent_hue,
const double percent_saturation,const double percent_value,double *red,
double *green,double *blue)
{
double
hue,
saturation,
value;
/*
Increase or decrease color value, saturation, or hue.
*/
ConvertRGBToHSV(*red,*green,*blue,&hue,&saturation,&value);
hue+=fmod((percent_hue-100.0),200.0)/200.0;
saturation*=0.01*percent_saturation;
value*=0.01*percent_value;
ConvertHSVToRGB(hue,saturation,value,red,green,blue);
}
static inline void ModulateHWB(const double percent_hue,
const double percent_whiteness,const double percent_blackness,double *red,
double *green,double *blue)
{
double
blackness,
hue,
whiteness;
/*
Increase or decrease color blackness, whiteness, or hue.
*/
ConvertRGBToHWB(*red,*green,*blue,&hue,&whiteness,&blackness);
hue+=fmod((percent_hue-100.0),200.0)/200.0;
blackness*=0.01*percent_blackness;
whiteness*=0.01*percent_whiteness;
ConvertHWBToRGB(hue,whiteness,blackness,red,green,blue);
}
static inline void ModulateLCHab(const double percent_luma,
const double percent_chroma,const double percent_hue,double *red,
double *green,double *blue)
{
double
hue,
luma,
chroma;
/*
Increase or decrease color luma, chroma, or hue.
*/
ConvertRGBToLCHab(*red,*green,*blue,&luma,&chroma,&hue);
luma*=0.01*percent_luma;
chroma*=0.01*percent_chroma;
hue+=fmod((percent_hue-100.0),200.0)/200.0;
ConvertLCHabToRGB(luma,chroma,hue,red,green,blue);
}
static inline void ModulateLCHuv(const double percent_luma,
const double percent_chroma,const double percent_hue,double *red,
double *green,double *blue)
{
double
hue,
luma,
chroma;
/*
Increase or decrease color luma, chroma, or hue.
*/
ConvertRGBToLCHuv(*red,*green,*blue,&luma,&chroma,&hue);
luma*=0.01*percent_luma;
chroma*=0.01*percent_chroma;
hue+=fmod((percent_hue-100.0),200.0)/200.0;
ConvertLCHuvToRGB(luma,chroma,hue,red,green,blue);
}
MagickExport MagickBooleanType ModulateImage(Image *image,const char *modulate,
ExceptionInfo *exception)
{
#define ModulateImageTag "Modulate/Image"
CacheView
*image_view;
ColorspaceType
colorspace;
const char
*artifact;
double
percent_brightness,
percent_hue,
percent_saturation;
GeometryInfo
geometry_info;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickStatusType
flags;
register ssize_t
i;
ssize_t
y;
/*
Initialize modulate table.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (modulate == (char *) NULL)
return(MagickFalse);
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
flags=ParseGeometry(modulate,&geometry_info);
percent_brightness=geometry_info.rho;
percent_saturation=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
percent_saturation=100.0;
percent_hue=geometry_info.xi;
if ((flags & XiValue) == 0)
percent_hue=100.0;
colorspace=UndefinedColorspace;
artifact=GetImageArtifact(image,"modulate:colorspace");
if (artifact != (const char *) NULL)
colorspace=(ColorspaceType) ParseCommandOption(MagickColorspaceOptions,
MagickFalse,artifact);
if (image->storage_class == PseudoClass)
for (i=0; i < (ssize_t) image->colors; i++)
{
double
blue,
green,
red;
/*
Modulate image colormap.
*/
red=(double) image->colormap[i].red;
green=(double) image->colormap[i].green;
blue=(double) image->colormap[i].blue;
switch (colorspace)
{
case HCLColorspace:
{
ModulateHCL(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HCLpColorspace:
{
ModulateHCLp(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSBColorspace:
{
ModulateHSB(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSIColorspace:
{
ModulateHSI(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSLColorspace:
default:
{
ModulateHSL(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSVColorspace:
{
ModulateHSV(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HWBColorspace:
{
ModulateHWB(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case LCHColorspace:
case LCHabColorspace:
{
ModulateLCHab(percent_brightness,percent_saturation,percent_hue,
&red,&green,&blue);
break;
}
case LCHuvColorspace:
{
ModulateLCHuv(percent_brightness,percent_saturation,percent_hue,
&red,&green,&blue);
break;
}
}
image->colormap[i].red=red;
image->colormap[i].green=green;
image->colormap[i].blue=blue;
}
/*
Modulate image.
*/
#if defined(MAGICKCORE_OPENCL_SUPPORT)
if (AccelerateModulateImage(image,percent_brightness,percent_hue,
percent_saturation,colorspace,exception) != MagickFalse)
return(MagickTrue);
#endif
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
blue,
green,
red;
red=(double) GetPixelRed(image,q);
green=(double) GetPixelGreen(image,q);
blue=(double) GetPixelBlue(image,q);
switch (colorspace)
{
case HCLColorspace:
{
ModulateHCL(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HCLpColorspace:
{
ModulateHCLp(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSBColorspace:
{
ModulateHSB(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSLColorspace:
default:
{
ModulateHSL(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSVColorspace:
{
ModulateHSV(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HWBColorspace:
{
ModulateHWB(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case LCHabColorspace:
{
ModulateLCHab(percent_brightness,percent_saturation,percent_hue,
&red,&green,&blue);
break;
}
case LCHColorspace:
case LCHuvColorspace:
{
ModulateLCHuv(percent_brightness,percent_saturation,percent_hue,
&red,&green,&blue);
break;
}
}
SetPixelRed(image,ClampToQuantum(red),q);
SetPixelGreen(image,ClampToQuantum(green),q);
SetPixelBlue(image,ClampToQuantum(blue),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ModulateImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% N e g a t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% NegateImage() negates the colors in the reference image. The grayscale
% option means that only grayscale values within the image are negated.
%
% The format of the NegateImage method is:
%
% MagickBooleanType NegateImage(Image *image,
% const MagickBooleanType grayscale,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o grayscale: If MagickTrue, only negate grayscale pixels within the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType NegateImage(Image *image,
const MagickBooleanType grayscale,ExceptionInfo *exception)
{
#define NegateImageTag "Negate/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Negate colormap.
*/
if( grayscale != MagickFalse )
if ((image->colormap[i].red != image->colormap[i].green) ||
(image->colormap[i].green != image->colormap[i].blue))
continue;
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=QuantumRange-image->colormap[i].red;
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=QuantumRange-image->colormap[i].green;
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=QuantumRange-image->colormap[i].blue;
}
/*
Negate image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
if( grayscale != MagickFalse )
{
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
if (IsPixelGray(image,q) != MagickFalse)
{
q+=GetPixelChannels(image);
continue;
}
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel = GetPixelChannelChannel(image,j);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[j]=QuantumRange-q[j];
}
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,NegateImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(MagickTrue);
}
/*
Negate image.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel = GetPixelChannelChannel(image,j);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[j]=QuantumRange-q[j];
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,NegateImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% N o r m a l i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% The NormalizeImage() method enhances the contrast of a color image by
% mapping the darkest 2 percent of all pixel to black and the brightest
% 1 percent to white.
%
% The format of the NormalizeImage method is:
%
% MagickBooleanType NormalizeImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType NormalizeImage(Image *image,
ExceptionInfo *exception)
{
double
black_point,
white_point;
black_point=(double) image->columns*image->rows*0.0015;
white_point=(double) image->columns*image->rows*0.9995;
return(ContrastStretchImage(image,black_point,white_point,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S i g m o i d a l C o n t r a s t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SigmoidalContrastImage() adjusts the contrast of an image with a non-linear
% sigmoidal contrast algorithm. Increase the contrast of the image using a
% sigmoidal transfer function without saturating highlights or shadows.
% Contrast indicates how much to increase the contrast (0 is none; 3 is
% typical; 20 is pushing it); mid-point indicates where midtones fall in the
% resultant image (0 is white; 50% is middle-gray; 100% is black). Set
% sharpen to MagickTrue to increase the image contrast otherwise the contrast
% is reduced.
%
% The format of the SigmoidalContrastImage method is:
%
% MagickBooleanType SigmoidalContrastImage(Image *image,
% const MagickBooleanType sharpen,const char *levels,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o sharpen: Increase or decrease image contrast.
%
% o contrast: strength of the contrast, the larger the number the more
% 'threshold-like' it becomes.
%
% o midpoint: midpoint of the function as a color value 0 to QuantumRange.
%
% o exception: return any errors or warnings in this structure.
%
*/
/*
ImageMagick 6 has a version of this function which uses LUTs.
*/
/*
Sigmoidal function Sigmoidal with inflexion point moved to b and "slope
constant" set to a.
The first version, based on the hyperbolic tangent tanh, when combined with
the scaling step, is an exact arithmetic clone of the the sigmoid function
based on the logistic curve. The equivalence is based on the identity
1/(1+exp(-t)) = (1+tanh(t/2))/2
(http://de.wikipedia.org/wiki/Sigmoidfunktion) and the fact that the
scaled sigmoidal derivation is invariant under affine transformations of
the ordinate.
The tanh version is almost certainly more accurate and cheaper. The 0.5
factor in the argument is to clone the legacy ImageMagick behavior. The
reason for making the define depend on atanh even though it only uses tanh
has to do with the construction of the inverse of the scaled sigmoidal.
*/
#if defined(MAGICKCORE_HAVE_ATANH)
#define Sigmoidal(a,b,x) ( tanh((0.5*(a))*((x)-(b))) )
#else
#define Sigmoidal(a,b,x) ( 1.0/(1.0+exp((a)*((b)-(x)))) )
#endif
/*
Scaled sigmoidal function:
( Sigmoidal(a,b,x) - Sigmoidal(a,b,0) ) /
( Sigmoidal(a,b,1) - Sigmoidal(a,b,0) )
See http://osdir.com/ml/video.image-magick.devel/2005-04/msg00006.html and
http://www.cs.dartmouth.edu/farid/downloads/tutorials/fip.pdf. The limit
of ScaledSigmoidal as a->0 is the identity, but a=0 gives a division by
zero. This is fixed below by exiting immediately when contrast is small,
leaving the image (or colormap) unmodified. This appears to be safe because
the series expansion of the logistic sigmoidal function around x=b is
1/2-a*(b-x)/4+...
so that the key denominator s(1)-s(0) is about a/4 (a/2 with tanh).
*/
#define ScaledSigmoidal(a,b,x) ( \
(Sigmoidal((a),(b),(x))-Sigmoidal((a),(b),0.0)) / \
(Sigmoidal((a),(b),1.0)-Sigmoidal((a),(b),0.0)) )
/*
Inverse of ScaledSigmoidal, used for +sigmoidal-contrast. Because b
may be 0 or 1, the argument of the hyperbolic tangent (resp. logistic
sigmoidal) may be outside of the interval (-1,1) (resp. (0,1)), even
when creating a LUT from in gamut values, hence the branching. In
addition, HDRI may have out of gamut values.
InverseScaledSigmoidal is not a two-sided inverse of ScaledSigmoidal:
It is only a right inverse. This is unavoidable.
*/
static inline double InverseScaledSigmoidal(const double a,const double b,
const double x)
{
const double sig0=Sigmoidal(a,b,0.0);
const double sig1=Sigmoidal(a,b,1.0);
const double argument=(sig1-sig0)*x+sig0;
const double clamped=
(
#if defined(MAGICKCORE_HAVE_ATANH)
argument < -1+MagickEpsilon
?
-1+MagickEpsilon
:
( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument )
);
return(b+(2.0/a)*atanh(clamped));
#else
argument < MagickEpsilon
?
MagickEpsilon
:
( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument )
);
return(b-log(1.0/clamped-1.0)/a);
#endif
}
MagickExport MagickBooleanType SigmoidalContrastImage(Image *image,
const MagickBooleanType sharpen,const double contrast,const double midpoint,
ExceptionInfo *exception)
{
#define SigmoidalContrastImageTag "SigmoidalContrast/Image"
#define ScaledSig(x) ( ClampToQuantum(QuantumRange* \
ScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) )
#define InverseScaledSig(x) ( ClampToQuantum(QuantumRange* \
InverseScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) )
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Convenience macros.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
/*
Side effect: may clamp values unless contrast<MagickEpsilon, in which
case nothing is done.
*/
if (contrast < MagickEpsilon)
return(MagickTrue);
/*
Sigmoidal-contrast enhance colormap.
*/
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
if( sharpen != MagickFalse )
for (i=0; i < (ssize_t) image->colors; i++)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=(MagickRealType) ScaledSig(
image->colormap[i].red);
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=(MagickRealType) ScaledSig(
image->colormap[i].green);
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=(MagickRealType) ScaledSig(
image->colormap[i].blue);
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].alpha=(MagickRealType) ScaledSig(
image->colormap[i].alpha);
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=(MagickRealType) InverseScaledSig(
image->colormap[i].red);
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=(MagickRealType) InverseScaledSig(
image->colormap[i].green);
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=(MagickRealType) InverseScaledSig(
image->colormap[i].blue);
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].alpha=(MagickRealType) InverseScaledSig(
image->colormap[i].alpha);
}
}
/*
Sigmoidal-contrast enhance image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if( sharpen != MagickFalse )
q[i]=ScaledSig(q[i]);
else
q[i]=InverseScaledSig(q[i]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SigmoidalContrastImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_927_0 |
crossvul-cpp_data_good_4781_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% JJJJJ PPPP EEEEE GGGG %
% J P P E G %
% J PPPP EEE G GG %
% J J P E G G %
% JJJ P EEEEE GGG %
% %
% %
% Read/Write JPEG Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% This software is based in part on the work of the Independent JPEG Group.
% See ftp://ftp.uu.net/graphics/jpeg/jpegsrc.v6b.tar.gz for copyright and
% licensing restrictions. Blob support contributed by Glenn Randers-Pehrson.
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/colormap-private.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/constitute.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/geometry.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/option-private.h"
#include "magick/pixel-accessor.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/semaphore.h"
#include "magick/splay-tree.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/token.h"
#include "magick/utility.h"
#include "magick/xml-tree.h"
#include <setjmp.h>
#if defined(MAGICKCORE_JPEG_DELEGATE)
#define JPEG_INTERNAL_OPTIONS
#if defined(__MINGW32__) || defined(__MINGW64__)
# define XMD_H 1 /* Avoid conflicting typedef for INT32 */
#endif
#undef HAVE_STDLIB_H
#include "jpeglib.h"
#include "jerror.h"
#endif
/*
Define declarations.
*/
#define ICC_MARKER (JPEG_APP0+2)
#define ICC_PROFILE "ICC_PROFILE"
#define IPTC_MARKER (JPEG_APP0+13)
#define XML_MARKER (JPEG_APP0+1)
#define MaxBufferExtent 16384
/*
Typedef declarations.
*/
#if defined(MAGICKCORE_JPEG_DELEGATE)
typedef struct _DestinationManager
{
struct jpeg_destination_mgr
manager;
Image
*image;
JOCTET
*buffer;
} DestinationManager;
typedef struct _ErrorManager
{
Image
*image;
MagickBooleanType
finished;
StringInfo
*profile;
jmp_buf
error_recovery;
} ErrorManager;
typedef struct _SourceManager
{
struct jpeg_source_mgr
manager;
Image
*image;
JOCTET
*buffer;
boolean
start_of_blob;
} SourceManager;
#endif
typedef struct _QuantizationTable
{
char
*slot,
*description;
size_t
width,
height;
double
divisor;
unsigned int
*levels;
} QuantizationTable;
/*
Forward declarations.
*/
#if defined(MAGICKCORE_JPEG_DELEGATE)
static MagickBooleanType
WriteJPEGImage(const ImageInfo *,Image *);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s J P E G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsJPEG() returns MagickTrue if the image format type, identified by the
% magick string, is JPEG.
%
% The format of the IsJPEG method is:
%
% MagickBooleanType IsJPEG(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsJPEG(const unsigned char *magick,const size_t length)
{
if (length < 3)
return(MagickFalse);
if (memcmp(magick,"\377\330\377",3) == 0)
return(MagickTrue);
return(MagickFalse);
}
#if defined(MAGICKCORE_JPEG_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d J P E G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadJPEGImage() reads a JPEG image file and returns it. It allocates
% the memory necessary for the new Image structure and returns a pointer to
% the new image.
%
% The format of the ReadJPEGImage method is:
%
% Image *ReadJPEGImage(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static boolean FillInputBuffer(j_decompress_ptr cinfo)
{
SourceManager
*source;
source=(SourceManager *) cinfo->src;
source->manager.bytes_in_buffer=(size_t) ReadBlob(source->image,
MaxBufferExtent,source->buffer);
if (source->manager.bytes_in_buffer == 0)
{
if (source->start_of_blob != FALSE)
ERREXIT(cinfo,JERR_INPUT_EMPTY);
WARNMS(cinfo,JWRN_JPEG_EOF);
source->buffer[0]=(JOCTET) 0xff;
source->buffer[1]=(JOCTET) JPEG_EOI;
source->manager.bytes_in_buffer=2;
}
source->manager.next_input_byte=source->buffer;
source->start_of_blob=FALSE;
return(TRUE);
}
static int GetCharacter(j_decompress_ptr jpeg_info)
{
if (jpeg_info->src->bytes_in_buffer == 0)
(void) (*jpeg_info->src->fill_input_buffer)(jpeg_info);
jpeg_info->src->bytes_in_buffer--;
return((int) GETJOCTET(*jpeg_info->src->next_input_byte++));
}
static void InitializeSource(j_decompress_ptr cinfo)
{
SourceManager
*source;
source=(SourceManager *) cinfo->src;
source->start_of_blob=TRUE;
}
static MagickBooleanType IsITUFaxImage(const Image *image)
{
const StringInfo
*profile;
const unsigned char
*datum;
profile=GetImageProfile(image,"8bim");
if (profile == (const StringInfo *) NULL)
return(MagickFalse);
if (GetStringInfoLength(profile) < 5)
return(MagickFalse);
datum=GetStringInfoDatum(profile);
if ((datum[0] == 0x47) && (datum[1] == 0x33) && (datum[2] == 0x46) &&
(datum[3] == 0x41) && (datum[4] == 0x58))
return(MagickTrue);
return(MagickFalse);
}
static void JPEGErrorHandler(j_common_ptr jpeg_info)
{
char
message[JMSG_LENGTH_MAX];
ErrorManager
*error_manager;
Image
*image;
*message='\0';
error_manager=(ErrorManager *) jpeg_info->client_data;
image=error_manager->image;
(jpeg_info->err->format_message)(jpeg_info,message);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"[%s] JPEG Trace: \"%s\"",image->filename,message);
if (error_manager->finished != MagickFalse)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CorruptImageWarning,(char *) message,"`%s'",image->filename);
else
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CorruptImageError,(char *) message,"`%s'",image->filename);
longjmp(error_manager->error_recovery,1);
}
static MagickBooleanType JPEGWarningHandler(j_common_ptr jpeg_info,int level)
{
#define JPEGExcessiveWarnings 1000
char
message[JMSG_LENGTH_MAX];
ErrorManager
*error_manager;
Image
*image;
*message='\0';
error_manager=(ErrorManager *) jpeg_info->client_data;
image=error_manager->image;
if (level < 0)
{
/*
Process warning message.
*/
(jpeg_info->err->format_message)(jpeg_info,message);
if (jpeg_info->err->num_warnings++ > JPEGExcessiveWarnings)
JPEGErrorHandler(jpeg_info);
ThrowBinaryException(CorruptImageWarning,(char *) message,
image->filename);
}
else
if ((image->debug != MagickFalse) &&
(level >= jpeg_info->err->trace_level))
{
/*
Process trace message.
*/
(jpeg_info->err->format_message)(jpeg_info,message);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"[%s] JPEG Trace: \"%s\"",image->filename,message);
}
return(MagickTrue);
}
static boolean ReadComment(j_decompress_ptr jpeg_info)
{
ErrorManager
*error_manager;
Image
*image;
register unsigned char
*p;
register ssize_t
i;
size_t
length;
StringInfo
*comment;
/*
Determine length of comment.
*/
error_manager=(ErrorManager *) jpeg_info->client_data;
image=error_manager->image;
length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8);
length+=GetCharacter(jpeg_info);
if (length <= 2)
return(TRUE);
length-=2;
comment=BlobToStringInfo((const void *) NULL,length);
if (comment == (StringInfo *) NULL)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
/*
Read comment.
*/
error_manager->profile=comment;
p=GetStringInfoDatum(comment);
for (i=0; i < (ssize_t) GetStringInfoLength(comment); i++)
*p++=(unsigned char) GetCharacter(jpeg_info);
*p='\0';
error_manager->profile=NULL;
p=GetStringInfoDatum(comment);
(void) SetImageProperty(image,"comment",(const char *) p);
comment=DestroyStringInfo(comment);
return(TRUE);
}
static boolean ReadICCProfile(j_decompress_ptr jpeg_info)
{
char
magick[12];
ErrorManager
*error_manager;
Image
*image;
MagickBooleanType
status;
register ssize_t
i;
register unsigned char
*p;
size_t
length;
StringInfo
*icc_profile,
*profile;
/*
Read color profile.
*/
length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8);
length+=(size_t) GetCharacter(jpeg_info);
length-=2;
if (length <= 14)
{
while (length-- > 0)
(void) GetCharacter(jpeg_info);
return(TRUE);
}
for (i=0; i < 12; i++)
magick[i]=(char) GetCharacter(jpeg_info);
if (LocaleCompare(magick,ICC_PROFILE) != 0)
{
/*
Not a ICC profile, return.
*/
for (i=0; i < (ssize_t) (length-12); i++)
(void) GetCharacter(jpeg_info);
return(TRUE);
}
(void) GetCharacter(jpeg_info); /* id */
(void) GetCharacter(jpeg_info); /* markers */
length-=14;
error_manager=(ErrorManager *) jpeg_info->client_data;
image=error_manager->image;
profile=BlobToStringInfo((const void *) NULL,length);
if (profile == (StringInfo *) NULL)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
error_manager->profile=profile;
p=GetStringInfoDatum(profile);
for (i=(ssize_t) GetStringInfoLength(profile)-1; i >= 0; i--)
*p++=(unsigned char) GetCharacter(jpeg_info);
error_manager->profile=NULL;
icc_profile=(StringInfo *) GetImageProfile(image,"icc");
if (icc_profile != (StringInfo *) NULL)
{
ConcatenateStringInfo(icc_profile,profile);
profile=DestroyStringInfo(profile);
}
else
{
status=SetImageProfile(image,"icc",profile);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Profile: ICC, %.20g bytes",(double) length);
return(TRUE);
}
static boolean ReadIPTCProfile(j_decompress_ptr jpeg_info)
{
char
magick[MaxTextExtent];
ErrorManager
*error_manager;
Image
*image;
MagickBooleanType
status;
register ssize_t
i;
register unsigned char
*p;
size_t
length;
StringInfo
*iptc_profile,
*profile;
/*
Determine length of binary data stored here.
*/
length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8);
length+=(size_t) GetCharacter(jpeg_info);
length-=2;
if (length <= 14)
{
while (length-- > 0)
(void) GetCharacter(jpeg_info);
return(TRUE);
}
/*
Validate that this was written as a Photoshop resource format slug.
*/
for (i=0; i < 10; i++)
magick[i]=(char) GetCharacter(jpeg_info);
magick[10]='\0';
length-=10;
if (length <= 10)
return(TRUE);
if (LocaleCompare(magick,"Photoshop ") != 0)
{
/*
Not a IPTC profile, return.
*/
for (i=0; i < (ssize_t) length; i++)
(void) GetCharacter(jpeg_info);
return(TRUE);
}
/*
Remove the version number.
*/
for (i=0; i < 4; i++)
(void) GetCharacter(jpeg_info);
if (length <= 11)
return(TRUE);
length-=4;
error_manager=(ErrorManager *) jpeg_info->client_data;
image=error_manager->image;
profile=BlobToStringInfo((const void *) NULL,length);
if (profile == (StringInfo *) NULL)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
error_manager->profile=profile;
p=GetStringInfoDatum(profile);
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++)
*p++=(unsigned char) GetCharacter(jpeg_info);
error_manager->profile=NULL;
iptc_profile=(StringInfo *) GetImageProfile(image,"8bim");
if (iptc_profile != (StringInfo *) NULL)
{
ConcatenateStringInfo(iptc_profile,profile);
profile=DestroyStringInfo(profile);
}
else
{
status=SetImageProfile(image,"8bim",profile);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Profile: iptc, %.20g bytes",(double) length);
return(TRUE);
}
static boolean ReadProfile(j_decompress_ptr jpeg_info)
{
char
name[MaxTextExtent];
const StringInfo
*previous_profile;
ErrorManager
*error_manager;
Image
*image;
int
marker;
MagickBooleanType
status;
register ssize_t
i;
register unsigned char
*p;
size_t
length;
StringInfo
*profile;
/*
Read generic profile.
*/
length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8);
length+=(size_t) GetCharacter(jpeg_info);
if (length <= 2)
return(TRUE);
length-=2;
marker=jpeg_info->unread_marker-JPEG_APP0;
(void) FormatLocaleString(name,MaxTextExtent,"APP%d",marker);
error_manager=(ErrorManager *) jpeg_info->client_data;
image=error_manager->image;
profile=BlobToStringInfo((const void *) NULL,length);
if (profile == (StringInfo *) NULL)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
error_manager->profile=profile;
p=GetStringInfoDatum(profile);
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++)
*p++=(unsigned char) GetCharacter(jpeg_info);
error_manager->profile=NULL;
if (marker == 1)
{
p=GetStringInfoDatum(profile);
if ((length > 4) && (LocaleNCompare((char *) p,"exif",4) == 0))
(void) CopyMagickString(name,"exif",MaxTextExtent);
if ((length > 5) && (LocaleNCompare((char *) p,"http:",5) == 0))
{
ssize_t
j;
/*
Extract namespace from XMP profile.
*/
p=GetStringInfoDatum(profile);
for (j=0; j < (ssize_t) GetStringInfoLength(profile); j++)
{
if (*p == '\0')
break;
p++;
}
if (j < (ssize_t) GetStringInfoLength(profile))
(void) DestroyStringInfo(SplitStringInfo(profile,(size_t) (j+1)));
(void) CopyMagickString(name,"xmp",MaxTextExtent);
}
}
previous_profile=GetImageProfile(image,name);
if (previous_profile != (const StringInfo *) NULL)
{
size_t
length;
length=GetStringInfoLength(profile);
SetStringInfoLength(profile,GetStringInfoLength(profile)+
GetStringInfoLength(previous_profile));
(void) memmove(GetStringInfoDatum(profile)+
GetStringInfoLength(previous_profile),GetStringInfoDatum(profile),
length);
(void) memcpy(GetStringInfoDatum(profile),
GetStringInfoDatum(previous_profile),
GetStringInfoLength(previous_profile));
}
status=SetImageProfile(image,name,profile);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Profile: %s, %.20g bytes",name,(double) length);
return(TRUE);
}
static void SkipInputData(j_decompress_ptr cinfo,long number_bytes)
{
SourceManager
*source;
if (number_bytes <= 0)
return;
source=(SourceManager *) cinfo->src;
while (number_bytes > (long) source->manager.bytes_in_buffer)
{
number_bytes-=(long) source->manager.bytes_in_buffer;
(void) FillInputBuffer(cinfo);
}
source->manager.next_input_byte+=number_bytes;
source->manager.bytes_in_buffer-=number_bytes;
}
static void TerminateSource(j_decompress_ptr cinfo)
{
(void) cinfo;
}
static void JPEGSourceManager(j_decompress_ptr cinfo,Image *image)
{
SourceManager
*source;
cinfo->src=(struct jpeg_source_mgr *) (*cinfo->mem->alloc_small)
((j_common_ptr) cinfo,JPOOL_IMAGE,sizeof(SourceManager));
source=(SourceManager *) cinfo->src;
source->buffer=(JOCTET *) (*cinfo->mem->alloc_small)
((j_common_ptr) cinfo,JPOOL_IMAGE,MaxBufferExtent*sizeof(JOCTET));
source=(SourceManager *) cinfo->src;
source->manager.init_source=InitializeSource;
source->manager.fill_input_buffer=FillInputBuffer;
source->manager.skip_input_data=SkipInputData;
source->manager.resync_to_restart=jpeg_resync_to_restart;
source->manager.term_source=TerminateSource;
source->manager.bytes_in_buffer=0;
source->manager.next_input_byte=NULL;
source->image=image;
}
static void JPEGSetImageQuality(struct jpeg_decompress_struct *jpeg_info,
Image *image)
{
image->quality=UndefinedCompressionQuality;
#if defined(D_PROGRESSIVE_SUPPORTED)
if (image->compression == LosslessJPEGCompression)
{
image->quality=100;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Quality: 100 (lossless)");
}
else
#endif
{
ssize_t
j,
qvalue,
sum;
register ssize_t
i;
/*
Determine the JPEG compression quality from the quantization tables.
*/
sum=0;
for (i=0; i < NUM_QUANT_TBLS; i++)
{
if (jpeg_info->quant_tbl_ptrs[i] != NULL)
for (j=0; j < DCTSIZE2; j++)
sum+=jpeg_info->quant_tbl_ptrs[i]->quantval[j];
}
if ((jpeg_info->quant_tbl_ptrs[0] != NULL) &&
(jpeg_info->quant_tbl_ptrs[1] != NULL))
{
ssize_t
hash[101] =
{
1020, 1015, 932, 848, 780, 735, 702, 679, 660, 645,
632, 623, 613, 607, 600, 594, 589, 585, 581, 571,
555, 542, 529, 514, 494, 474, 457, 439, 424, 410,
397, 386, 373, 364, 351, 341, 334, 324, 317, 309,
299, 294, 287, 279, 274, 267, 262, 257, 251, 247,
243, 237, 232, 227, 222, 217, 213, 207, 202, 198,
192, 188, 183, 177, 173, 168, 163, 157, 153, 148,
143, 139, 132, 128, 125, 119, 115, 108, 104, 99,
94, 90, 84, 79, 74, 70, 64, 59, 55, 49,
45, 40, 34, 30, 25, 20, 15, 11, 6, 4,
0
},
sums[101] =
{
32640, 32635, 32266, 31495, 30665, 29804, 29146, 28599, 28104,
27670, 27225, 26725, 26210, 25716, 25240, 24789, 24373, 23946,
23572, 22846, 21801, 20842, 19949, 19121, 18386, 17651, 16998,
16349, 15800, 15247, 14783, 14321, 13859, 13535, 13081, 12702,
12423, 12056, 11779, 11513, 11135, 10955, 10676, 10392, 10208,
9928, 9747, 9564, 9369, 9193, 9017, 8822, 8639, 8458,
8270, 8084, 7896, 7710, 7527, 7347, 7156, 6977, 6788,
6607, 6422, 6236, 6054, 5867, 5684, 5495, 5305, 5128,
4945, 4751, 4638, 4442, 4248, 4065, 3888, 3698, 3509,
3326, 3139, 2957, 2775, 2586, 2405, 2216, 2037, 1846,
1666, 1483, 1297, 1109, 927, 735, 554, 375, 201,
128, 0
};
qvalue=(ssize_t) (jpeg_info->quant_tbl_ptrs[0]->quantval[2]+
jpeg_info->quant_tbl_ptrs[0]->quantval[53]+
jpeg_info->quant_tbl_ptrs[1]->quantval[0]+
jpeg_info->quant_tbl_ptrs[1]->quantval[DCTSIZE2-1]);
for (i=0; i < 100; i++)
{
if ((qvalue < hash[i]) && (sum < sums[i]))
continue;
if (((qvalue <= hash[i]) && (sum <= sums[i])) || (i >= 50))
image->quality=(size_t) i+1;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Quality: %.20g (%s)",(double) i+1,(qvalue <= hash[i]) &&
(sum <= sums[i]) ? "exact" : "approximate");
break;
}
}
else
if (jpeg_info->quant_tbl_ptrs[0] != NULL)
{
ssize_t
hash[101] =
{
510, 505, 422, 380, 355, 338, 326, 318, 311, 305,
300, 297, 293, 291, 288, 286, 284, 283, 281, 280,
279, 278, 277, 273, 262, 251, 243, 233, 225, 218,
211, 205, 198, 193, 186, 181, 177, 172, 168, 164,
158, 156, 152, 148, 145, 142, 139, 136, 133, 131,
129, 126, 123, 120, 118, 115, 113, 110, 107, 105,
102, 100, 97, 94, 92, 89, 87, 83, 81, 79,
76, 74, 70, 68, 66, 63, 61, 57, 55, 52,
50, 48, 44, 42, 39, 37, 34, 31, 29, 26,
24, 21, 18, 16, 13, 11, 8, 6, 3, 2,
0
},
sums[101] =
{
16320, 16315, 15946, 15277, 14655, 14073, 13623, 13230, 12859,
12560, 12240, 11861, 11456, 11081, 10714, 10360, 10027, 9679,
9368, 9056, 8680, 8331, 7995, 7668, 7376, 7084, 6823,
6562, 6345, 6125, 5939, 5756, 5571, 5421, 5240, 5086,
4976, 4829, 4719, 4616, 4463, 4393, 4280, 4166, 4092,
3980, 3909, 3835, 3755, 3688, 3621, 3541, 3467, 3396,
3323, 3247, 3170, 3096, 3021, 2952, 2874, 2804, 2727,
2657, 2583, 2509, 2437, 2362, 2290, 2211, 2136, 2068,
1996, 1915, 1858, 1773, 1692, 1620, 1552, 1477, 1398,
1326, 1251, 1179, 1109, 1031, 961, 884, 814, 736,
667, 592, 518, 441, 369, 292, 221, 151, 86,
64, 0
};
qvalue=(ssize_t) (jpeg_info->quant_tbl_ptrs[0]->quantval[2]+
jpeg_info->quant_tbl_ptrs[0]->quantval[53]);
for (i=0; i < 100; i++)
{
if ((qvalue < hash[i]) && (sum < sums[i]))
continue;
if (((qvalue <= hash[i]) && (sum <= sums[i])) || (i >= 50))
image->quality=(size_t) i+1;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Quality: %.20g (%s)",(double) i+1,(qvalue <= hash[i]) &&
(sum <= sums[i]) ? "exact" : "approximate");
break;
}
}
}
}
static void JPEGSetImageSamplingFactor(struct jpeg_decompress_struct *jpeg_info, Image *image)
{
char
sampling_factor[MaxTextExtent];
switch (jpeg_info->out_color_space)
{
case JCS_CMYK:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Colorspace: CMYK");
(void) FormatLocaleString(sampling_factor,MaxTextExtent,
"%dx%d,%dx%d,%dx%d,%dx%d",jpeg_info->comp_info[0].h_samp_factor,
jpeg_info->comp_info[0].v_samp_factor,
jpeg_info->comp_info[1].h_samp_factor,
jpeg_info->comp_info[1].v_samp_factor,
jpeg_info->comp_info[2].h_samp_factor,
jpeg_info->comp_info[2].v_samp_factor,
jpeg_info->comp_info[3].h_samp_factor,
jpeg_info->comp_info[3].v_samp_factor);
break;
}
case JCS_GRAYSCALE:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Colorspace: GRAYSCALE");
(void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d",
jpeg_info->comp_info[0].h_samp_factor,
jpeg_info->comp_info[0].v_samp_factor);
break;
}
case JCS_RGB:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Colorspace: RGB");
(void) FormatLocaleString(sampling_factor,MaxTextExtent,
"%dx%d,%dx%d,%dx%d",jpeg_info->comp_info[0].h_samp_factor,
jpeg_info->comp_info[0].v_samp_factor,
jpeg_info->comp_info[1].h_samp_factor,
jpeg_info->comp_info[1].v_samp_factor,
jpeg_info->comp_info[2].h_samp_factor,
jpeg_info->comp_info[2].v_samp_factor);
break;
}
default:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Colorspace: %d",
jpeg_info->out_color_space);
(void) FormatLocaleString(sampling_factor,MaxTextExtent,
"%dx%d,%dx%d,%dx%d,%dx%d",jpeg_info->comp_info[0].h_samp_factor,
jpeg_info->comp_info[0].v_samp_factor,
jpeg_info->comp_info[1].h_samp_factor,
jpeg_info->comp_info[1].v_samp_factor,
jpeg_info->comp_info[2].h_samp_factor,
jpeg_info->comp_info[2].v_samp_factor,
jpeg_info->comp_info[3].h_samp_factor,
jpeg_info->comp_info[3].v_samp_factor);
break;
}
}
(void) SetImageProperty(image,"jpeg:sampling-factor",sampling_factor);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Sampling Factors: %s",
sampling_factor);
}
static Image *ReadJPEGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
value[MaxTextExtent];
const char
*option;
ErrorManager
error_manager;
Image
*image;
IndexPacket
index;
JSAMPLE
*volatile jpeg_pixels;
JSAMPROW
scanline[1];
MagickBooleanType
debug,
status;
MagickSizeType
number_pixels;
MemoryInfo
*memory_info;
register ssize_t
i;
struct jpeg_decompress_struct
jpeg_info;
struct jpeg_error_mgr
jpeg_error;
register JSAMPLE
*p;
size_t
units;
ssize_t
y;
/*
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);
debug=IsEventLogging();
(void) debug;
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize JPEG parameters.
*/
(void) ResetMagickMemory(&error_manager,0,sizeof(error_manager));
(void) ResetMagickMemory(&jpeg_info,0,sizeof(jpeg_info));
(void) ResetMagickMemory(&jpeg_error,0,sizeof(jpeg_error));
jpeg_info.err=jpeg_std_error(&jpeg_error);
jpeg_info.err->emit_message=(void (*)(j_common_ptr,int)) JPEGWarningHandler;
jpeg_info.err->error_exit=(void (*)(j_common_ptr)) JPEGErrorHandler;
memory_info=(MemoryInfo *) NULL;
error_manager.image=image;
if (setjmp(error_manager.error_recovery) != 0)
{
jpeg_destroy_decompress(&jpeg_info);
if (error_manager.profile != (StringInfo *) NULL)
error_manager.profile=DestroyStringInfo(error_manager.profile);
(void) CloseBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
if (number_pixels != 0)
return(GetFirstImageInList(image));
InheritException(exception,&image->exception);
return(DestroyImage(image));
}
jpeg_info.client_data=(void *) &error_manager;
jpeg_create_decompress(&jpeg_info);
JPEGSourceManager(&jpeg_info,image);
jpeg_set_marker_processor(&jpeg_info,JPEG_COM,ReadComment);
option=GetImageOption(image_info,"profile:skip");
if (IsOptionMember("ICC",option) == MagickFalse)
jpeg_set_marker_processor(&jpeg_info,ICC_MARKER,ReadICCProfile);
if (IsOptionMember("IPTC",option) == MagickFalse)
jpeg_set_marker_processor(&jpeg_info,IPTC_MARKER,ReadIPTCProfile);
for (i=1; i < 16; i++)
if ((i != 2) && (i != 13) && (i != 14))
if (IsOptionMember("APP",option) == MagickFalse)
jpeg_set_marker_processor(&jpeg_info,(int) (JPEG_APP0+i),ReadProfile);
i=(ssize_t) jpeg_read_header(&jpeg_info,TRUE);
if ((image_info->colorspace == YCbCrColorspace) ||
(image_info->colorspace == Rec601YCbCrColorspace) ||
(image_info->colorspace == Rec709YCbCrColorspace))
jpeg_info.out_color_space=JCS_YCbCr;
/*
Set image resolution.
*/
units=0;
if ((jpeg_info.saw_JFIF_marker != 0) && (jpeg_info.X_density != 1) &&
(jpeg_info.Y_density != 1))
{
image->x_resolution=(double) jpeg_info.X_density;
image->y_resolution=(double) jpeg_info.Y_density;
units=(size_t) jpeg_info.density_unit;
}
if (units == 1)
image->units=PixelsPerInchResolution;
if (units == 2)
image->units=PixelsPerCentimeterResolution;
number_pixels=(MagickSizeType) image->columns*image->rows;
option=GetImageOption(image_info,"jpeg:size");
if ((option != (const char *) NULL) &&
(jpeg_info.out_color_space != JCS_YCbCr))
{
double
scale_factor;
GeometryInfo
geometry_info;
MagickStatusType
flags;
/*
Scale the image.
*/
flags=ParseGeometry(option,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
jpeg_calc_output_dimensions(&jpeg_info);
image->magick_columns=jpeg_info.output_width;
image->magick_rows=jpeg_info.output_height;
scale_factor=1.0;
if (geometry_info.rho != 0.0)
scale_factor=jpeg_info.output_width/geometry_info.rho;
if ((geometry_info.sigma != 0.0) &&
(scale_factor > (jpeg_info.output_height/geometry_info.sigma)))
scale_factor=jpeg_info.output_height/geometry_info.sigma;
jpeg_info.scale_num=1U;
jpeg_info.scale_denom=(unsigned int) scale_factor;
jpeg_calc_output_dimensions(&jpeg_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Scale factor: %.20g",(double) scale_factor);
}
#if (JPEG_LIB_VERSION >= 61) && defined(D_PROGRESSIVE_SUPPORTED)
#if defined(D_LOSSLESS_SUPPORTED)
image->interlace=jpeg_info.process == JPROC_PROGRESSIVE ?
JPEGInterlace : NoInterlace;
image->compression=jpeg_info.process == JPROC_LOSSLESS ?
LosslessJPEGCompression : JPEGCompression;
if (jpeg_info.data_precision > 8)
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"12-bit JPEG not supported. Reducing pixel data to 8 bits","`%s'",
image->filename);
if (jpeg_info.data_precision == 16)
jpeg_info.data_precision=12;
#else
image->interlace=jpeg_info.progressive_mode != 0 ? JPEGInterlace :
NoInterlace;
image->compression=JPEGCompression;
#endif
#else
image->compression=JPEGCompression;
image->interlace=JPEGInterlace;
#endif
option=GetImageOption(image_info,"jpeg:colors");
if (option != (const char *) NULL)
{
/*
Let the JPEG library quantize for us.
*/
jpeg_info.quantize_colors=TRUE;
jpeg_info.desired_number_of_colors=(int) StringToUnsignedLong(option);
}
option=GetImageOption(image_info,"jpeg:block-smoothing");
if (option != (const char *) NULL)
jpeg_info.do_block_smoothing=IsStringTrue(option) != MagickFalse ? TRUE :
FALSE;
jpeg_info.dct_method=JDCT_FLOAT;
option=GetImageOption(image_info,"jpeg:dct-method");
if (option != (const char *) NULL)
switch (*option)
{
case 'D':
case 'd':
{
if (LocaleCompare(option,"default") == 0)
jpeg_info.dct_method=JDCT_DEFAULT;
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(option,"fastest") == 0)
jpeg_info.dct_method=JDCT_FASTEST;
if (LocaleCompare(option,"float") == 0)
jpeg_info.dct_method=JDCT_FLOAT;
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(option,"ifast") == 0)
jpeg_info.dct_method=JDCT_IFAST;
if (LocaleCompare(option,"islow") == 0)
jpeg_info.dct_method=JDCT_ISLOW;
break;
}
}
option=GetImageOption(image_info,"jpeg:fancy-upsampling");
if (option != (const char *) NULL)
jpeg_info.do_fancy_upsampling=IsStringTrue(option) != MagickFalse ? TRUE :
FALSE;
(void) jpeg_start_decompress(&jpeg_info);
image->columns=jpeg_info.output_width;
image->rows=jpeg_info.output_height;
image->depth=(size_t) jpeg_info.data_precision;
switch (jpeg_info.out_color_space)
{
case JCS_RGB:
default:
{
(void) SetImageColorspace(image,sRGBColorspace);
break;
}
case JCS_GRAYSCALE:
{
(void) SetImageColorspace(image,GRAYColorspace);
break;
}
case JCS_YCbCr:
{
(void) SetImageColorspace(image,YCbCrColorspace);
break;
}
case JCS_CMYK:
{
(void) SetImageColorspace(image,CMYKColorspace);
break;
}
}
if (IsITUFaxImage(image) != MagickFalse)
{
(void) SetImageColorspace(image,LabColorspace);
jpeg_info.out_color_space=JCS_YCbCr;
}
if (option != (const char *) NULL)
if (AcquireImageColormap(image,StringToUnsignedLong(option)) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if ((jpeg_info.output_components == 1) && (jpeg_info.quantize_colors == 0))
{
size_t
colors;
colors=(size_t) GetQuantumRange(image->depth)+1;
if (AcquireImageColormap(image,colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
if (image->debug != MagickFalse)
{
if (image->interlace != NoInterlace)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: progressive");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: nonprogressive");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Data precision: %d",
(int) jpeg_info.data_precision);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %dx%d",
(int) jpeg_info.output_width,(int) jpeg_info.output_height);
}
JPEGSetImageQuality(&jpeg_info,image);
JPEGSetImageSamplingFactor(&jpeg_info,image);
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
jpeg_info.out_color_space);
(void) SetImageProperty(image,"jpeg:colorspace",value);
if (image_info->ping != MagickFalse)
{
jpeg_destroy_decompress(&jpeg_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
jpeg_destroy_decompress(&jpeg_info);
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if ((jpeg_info.output_components != 1) &&
(jpeg_info.output_components != 3) && (jpeg_info.output_components != 4))
{
jpeg_destroy_decompress(&jpeg_info);
ThrowReaderException(CorruptImageError,"ImageTypeNotSupported");
}
memory_info=AcquireVirtualMemory((size_t) image->columns,
jpeg_info.output_components*sizeof(*jpeg_pixels));
if (memory_info == (MemoryInfo *) NULL)
{
jpeg_destroy_decompress(&jpeg_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
jpeg_pixels=(JSAMPLE *) GetVirtualMemoryBlob(memory_info);
/*
Convert JPEG pixels to pixel packets.
*/
if (setjmp(error_manager.error_recovery) != 0)
{
if (memory_info != (MemoryInfo *) NULL)
memory_info=RelinquishVirtualMemory(memory_info);
jpeg_destroy_decompress(&jpeg_info);
(void) CloseBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
if (number_pixels != 0)
return(GetFirstImageInList(image));
return(DestroyImage(image));
}
if (jpeg_info.quantize_colors != 0)
{
image->colors=(size_t) jpeg_info.actual_number_of_colors;
if (jpeg_info.out_color_space == JCS_GRAYSCALE)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]);
image->colormap[i].green=image->colormap[i].red;
image->colormap[i].blue=image->colormap[i].red;
image->colormap[i].opacity=OpaqueOpacity;
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]);
image->colormap[i].green=ScaleCharToQuantum(jpeg_info.colormap[1][i]);
image->colormap[i].blue=ScaleCharToQuantum(jpeg_info.colormap[2][i]);
image->colormap[i].opacity=OpaqueOpacity;
}
}
scanline[0]=(JSAMPROW) jpeg_pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (jpeg_read_scanlines(&jpeg_info,scanline,1) != 1)
{
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageWarning,"SkipToSyncByte","`%s'",image->filename);
continue;
}
p=jpeg_pixels;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
if (jpeg_info.data_precision > 8)
{
unsigned short
scale;
scale=65535/(unsigned short) GetQuantumRange((size_t)
jpeg_info.data_precision);
if (jpeg_info.output_components == 1)
for (x=0; x < (ssize_t) image->columns; x++)
{
size_t
pixel;
pixel=(size_t) (scale*GETJSAMPLE(*p));
index=ConstrainColormapIndex(image,pixel);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
else
if (image->colorspace != CMYKColorspace)
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleShortToQuantum((unsigned short)
(scale*GETJSAMPLE(*p++))));
SetPixelGreen(q,ScaleShortToQuantum((unsigned short)
(scale*GETJSAMPLE(*p++))));
SetPixelBlue(q,ScaleShortToQuantum((unsigned short)
(scale*GETJSAMPLE(*p++))));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelCyan(q,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelMagenta(q,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelYellow(q,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelBlack(indexes+x,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
}
else
if (jpeg_info.output_components == 1)
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,(size_t) GETJSAMPLE(*p));
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
else
if (image->colorspace != CMYKColorspace)
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelCyan(q,QuantumRange-ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelMagenta(q,QuantumRange-ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelYellow(q,QuantumRange-ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelBlack(indexes+x,QuantumRange-ScaleCharToQuantum(
(unsigned char) GETJSAMPLE(*p++)));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
{
jpeg_abort_decompress(&jpeg_info);
break;
}
}
if (status != MagickFalse)
{
error_manager.finished=MagickTrue;
if (setjmp(error_manager.error_recovery) == 0)
(void) jpeg_finish_decompress(&jpeg_info);
}
/*
Free jpeg resources.
*/
jpeg_destroy_decompress(&jpeg_info);
memory_info=RelinquishVirtualMemory(memory_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r J P E G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterJPEGImage() adds properties for the JPEG image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterJPEGImage method is:
%
% size_t RegisterJPEGImage(void)
%
*/
ModuleExport size_t RegisterJPEGImage(void)
{
char
version[MaxTextExtent];
MagickInfo
*entry;
static const char
description[] = "Joint Photographic Experts Group JFIF format";
*version='\0';
#if defined(JPEG_LIB_VERSION)
(void) FormatLocaleString(version,MaxTextExtent,"%d",JPEG_LIB_VERSION);
#endif
entry=SetMagickInfo("JPE");
#if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION)
entry->thread_support=NoThreadSupport;
#endif
#if defined(MAGICKCORE_JPEG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJPEGImage;
entry->encoder=(EncodeImageHandler *) WriteJPEGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsJPEG;
entry->adjoin=MagickFalse;
entry->description=ConstantString(description);
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jpeg");
entry->module=ConstantString("JPEG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JPEG");
#if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION)
entry->thread_support=NoThreadSupport;
#endif
#if defined(MAGICKCORE_JPEG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJPEGImage;
entry->encoder=(EncodeImageHandler *) WriteJPEGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsJPEG;
entry->adjoin=MagickFalse;
entry->description=ConstantString(description);
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jpeg");
entry->module=ConstantString("JPEG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JPG");
#if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION)
entry->thread_support=NoThreadSupport;
#endif
#if defined(MAGICKCORE_JPEG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJPEGImage;
entry->encoder=(EncodeImageHandler *) WriteJPEGImage;
#endif
entry->adjoin=MagickFalse;
entry->description=ConstantString(description);
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jpeg");
entry->module=ConstantString("JPEG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JPS");
#if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION)
entry->thread_support=NoThreadSupport;
#endif
#if defined(MAGICKCORE_JPEG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJPEGImage;
entry->encoder=(EncodeImageHandler *) WriteJPEGImage;
#endif
entry->adjoin=MagickFalse;
entry->description=ConstantString(description);
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jpeg");
entry->module=ConstantString("JPEG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PJPEG");
#if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION)
entry->thread_support=NoThreadSupport;
#endif
#if defined(MAGICKCORE_JPEG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJPEGImage;
entry->encoder=(EncodeImageHandler *) WriteJPEGImage;
#endif
entry->adjoin=MagickFalse;
entry->description=ConstantString(description);
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jpeg");
entry->module=ConstantString("JPEG");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r J P E G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterJPEGImage() removes format registrations made by the
% JPEG module from the list of supported formats.
%
% The format of the UnregisterJPEGImage method is:
%
% UnregisterJPEGImage(void)
%
*/
ModuleExport void UnregisterJPEGImage(void)
{
(void) UnregisterMagickInfo("PJPG");
(void) UnregisterMagickInfo("JPS");
(void) UnregisterMagickInfo("JPG");
(void) UnregisterMagickInfo("JPG");
(void) UnregisterMagickInfo("JPEG");
(void) UnregisterMagickInfo("JPE");
}
#if defined(MAGICKCORE_JPEG_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e J P E G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteJPEGImage() writes a JPEG image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the WriteJPEGImage method is:
%
% MagickBooleanType WriteJPEGImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o jpeg_image: The image.
%
%
*/
static QuantizationTable *DestroyQuantizationTable(QuantizationTable *table)
{
assert(table != (QuantizationTable *) NULL);
if (table->slot != (char *) NULL)
table->slot=DestroyString(table->slot);
if (table->description != (char *) NULL)
table->description=DestroyString(table->description);
if (table->levels != (unsigned int *) NULL)
table->levels=(unsigned int *) RelinquishMagickMemory(table->levels);
table=(QuantizationTable *) RelinquishMagickMemory(table);
return(table);
}
static boolean EmptyOutputBuffer(j_compress_ptr cinfo)
{
DestinationManager
*destination;
destination=(DestinationManager *) cinfo->dest;
destination->manager.free_in_buffer=(size_t) WriteBlob(destination->image,
MaxBufferExtent,destination->buffer);
if (destination->manager.free_in_buffer != MaxBufferExtent)
ERREXIT(cinfo,JERR_FILE_WRITE);
destination->manager.next_output_byte=destination->buffer;
return(TRUE);
}
static QuantizationTable *GetQuantizationTable(const char *filename,
const char *slot,ExceptionInfo *exception)
{
char
*p,
*xml;
const char
*attribute,
*content;
double
value;
register ssize_t
i;
QuantizationTable
*table;
size_t
length;
ssize_t
j;
XMLTreeInfo
*description,
*levels,
*quantization_tables,
*table_iterator;
(void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
"Loading quantization tables \"%s\" ...",filename);
table=(QuantizationTable *) NULL;
xml=FileToString(filename,~0UL,exception);
if (xml == (char *) NULL)
return(table);
quantization_tables=NewXMLTree(xml,exception);
if (quantization_tables == (XMLTreeInfo *) NULL)
{
xml=DestroyString(xml);
return(table);
}
for (table_iterator=GetXMLTreeChild(quantization_tables,"table");
table_iterator != (XMLTreeInfo *) NULL;
table_iterator=GetNextXMLTreeTag(table_iterator))
{
attribute=GetXMLTreeAttribute(table_iterator,"slot");
if ((attribute != (char *) NULL) && (LocaleCompare(slot,attribute) == 0))
break;
attribute=GetXMLTreeAttribute(table_iterator,"alias");
if ((attribute != (char *) NULL) && (LocaleCompare(slot,attribute) == 0))
break;
}
if (table_iterator == (XMLTreeInfo *) NULL)
{
xml=DestroyString(xml);
return(table);
}
description=GetXMLTreeChild(table_iterator,"description");
if (description == (XMLTreeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement","<description>, slot \"%s\"",slot);
quantization_tables=DestroyXMLTree(quantization_tables);
xml=DestroyString(xml);
return(table);
}
levels=GetXMLTreeChild(table_iterator,"levels");
if (levels == (XMLTreeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement","<levels>, slot \"%s\"",slot);
quantization_tables=DestroyXMLTree(quantization_tables);
xml=DestroyString(xml);
return(table);
}
table=(QuantizationTable *) AcquireMagickMemory(sizeof(*table));
if (table == (QuantizationTable *) NULL)
ThrowFatalException(ResourceLimitFatalError,
"UnableToAcquireQuantizationTable");
table->slot=(char *) NULL;
table->description=(char *) NULL;
table->levels=(unsigned int *) NULL;
attribute=GetXMLTreeAttribute(table_iterator,"slot");
if (attribute != (char *) NULL)
table->slot=ConstantString(attribute);
content=GetXMLTreeContent(description);
if (content != (char *) NULL)
table->description=ConstantString(content);
attribute=GetXMLTreeAttribute(levels,"width");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute","<levels width>, slot \"%s\"",slot);
quantization_tables=DestroyXMLTree(quantization_tables);
table=DestroyQuantizationTable(table);
xml=DestroyString(xml);
return(table);
}
table->width=StringToUnsignedLong(attribute);
if (table->width == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute","<levels width>, table \"%s\"",slot);
quantization_tables=DestroyXMLTree(quantization_tables);
table=DestroyQuantizationTable(table);
xml=DestroyString(xml);
return(table);
}
attribute=GetXMLTreeAttribute(levels,"height");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute","<levels height>, table \"%s\"",slot);
quantization_tables=DestroyXMLTree(quantization_tables);
table=DestroyQuantizationTable(table);
xml=DestroyString(xml);
return(table);
}
table->height=StringToUnsignedLong(attribute);
if (table->height == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute","<levels height>, table \"%s\"",slot);
quantization_tables=DestroyXMLTree(quantization_tables);
table=DestroyQuantizationTable(table);
xml=DestroyString(xml);
return(table);
}
attribute=GetXMLTreeAttribute(levels,"divisor");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute","<levels divisor>, table \"%s\"",slot);
quantization_tables=DestroyXMLTree(quantization_tables);
table=DestroyQuantizationTable(table);
xml=DestroyString(xml);
return(table);
}
table->divisor=InterpretLocaleValue(attribute,(char **) NULL);
if (table->divisor == 0.0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute","<levels divisor>, table \"%s\"",slot);
quantization_tables=DestroyXMLTree(quantization_tables);
table=DestroyQuantizationTable(table);
xml=DestroyString(xml);
return(table);
}
content=GetXMLTreeContent(levels);
if (content == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingContent","<levels>, table \"%s\"",slot);
quantization_tables=DestroyXMLTree(quantization_tables);
table=DestroyQuantizationTable(table);
xml=DestroyString(xml);
return(table);
}
length=(size_t) table->width*table->height;
if (length < 64)
length=64;
table->levels=(unsigned int *) AcquireQuantumMemory(length,
sizeof(*table->levels));
if (table->levels == (unsigned int *) NULL)
ThrowFatalException(ResourceLimitFatalError,
"UnableToAcquireQuantizationTable");
for (i=0; i < (ssize_t) (table->width*table->height); i++)
{
table->levels[i]=(unsigned int) (InterpretLocaleValue(content,&p)/
table->divisor+0.5);
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
content=p;
}
value=InterpretLocaleValue(content,&p);
(void) value;
if (p != content)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent","<level> too many values, table \"%s\"",slot);
quantization_tables=DestroyXMLTree(quantization_tables);
table=DestroyQuantizationTable(table);
xml=DestroyString(xml);
return(table);
}
for (j=i; j < 64; j++)
table->levels[j]=table->levels[j-1];
quantization_tables=DestroyXMLTree(quantization_tables);
xml=DestroyString(xml);
return(table);
}
static void InitializeDestination(j_compress_ptr cinfo)
{
DestinationManager
*destination;
destination=(DestinationManager *) cinfo->dest;
destination->buffer=(JOCTET *) (*cinfo->mem->alloc_small)
((j_common_ptr) cinfo,JPOOL_IMAGE,MaxBufferExtent*sizeof(JOCTET));
destination->manager.next_output_byte=destination->buffer;
destination->manager.free_in_buffer=MaxBufferExtent;
}
static void TerminateDestination(j_compress_ptr cinfo)
{
DestinationManager
*destination;
destination=(DestinationManager *) cinfo->dest;
if ((MaxBufferExtent-(int) destination->manager.free_in_buffer) > 0)
{
ssize_t
count;
count=WriteBlob(destination->image,MaxBufferExtent-
destination->manager.free_in_buffer,destination->buffer);
if (count != (ssize_t)
(MaxBufferExtent-destination->manager.free_in_buffer))
ERREXIT(cinfo,JERR_FILE_WRITE);
}
}
static void WriteProfile(j_compress_ptr jpeg_info,Image *image)
{
const char
*name;
const StringInfo
*profile;
MagickBooleanType
iptc;
register ssize_t
i;
size_t
length,
tag_length;
StringInfo
*custom_profile;
/*
Save image profile as a APP marker.
*/
iptc=MagickFalse;
custom_profile=AcquireStringInfo(65535L);
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
register unsigned char
*p;
profile=GetImageProfile(image,name);
p=GetStringInfoDatum(custom_profile);
if (LocaleCompare(name,"EXIF") == 0)
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65533L)
{
length=MagickMin(GetStringInfoLength(profile)-i,65533L);
jpeg_write_marker(jpeg_info,XML_MARKER,GetStringInfoDatum(profile)+i,
(unsigned int) length);
}
if (LocaleCompare(name,"ICC") == 0)
{
register unsigned char
*p;
tag_length=strlen(ICC_PROFILE);
p=GetStringInfoDatum(custom_profile);
(void) CopyMagickMemory(p,ICC_PROFILE,tag_length);
p[tag_length]='\0';
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65519L)
{
length=MagickMin(GetStringInfoLength(profile)-i,65519L);
p[12]=(unsigned char) ((i/65519L)+1);
p[13]=(unsigned char) (GetStringInfoLength(profile)/65519L+1);
(void) CopyMagickMemory(p+tag_length+3,GetStringInfoDatum(profile)+i,
length);
jpeg_write_marker(jpeg_info,ICC_MARKER,GetStringInfoDatum(
custom_profile),(unsigned int) (length+tag_length+3));
}
}
if (((LocaleCompare(name,"IPTC") == 0) ||
(LocaleCompare(name,"8BIM") == 0)) && (iptc == MagickFalse))
{
size_t
roundup;
iptc=MagickTrue;
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65500L)
{
length=MagickMin(GetStringInfoLength(profile)-i,65500L);
roundup=(size_t) (length & 0x01);
if (LocaleNCompare((char *) GetStringInfoDatum(profile),"8BIM",4) == 0)
{
(void) memcpy(p,"Photoshop 3.0 ",14);
tag_length=14;
}
else
{
(void) CopyMagickMemory(p,"Photoshop 3.0 8BIM\04\04\0\0\0\0",24);
tag_length=26;
p[24]=(unsigned char) (length >> 8);
p[25]=(unsigned char) (length & 0xff);
}
p[13]=0x00;
(void) memcpy(p+tag_length,GetStringInfoDatum(profile)+i,length);
if (roundup != 0)
p[length+tag_length]='\0';
jpeg_write_marker(jpeg_info,IPTC_MARKER,GetStringInfoDatum(
custom_profile),(unsigned int) (length+tag_length+roundup));
}
}
if (LocaleCompare(name,"XMP") == 0)
{
StringInfo
*xmp_profile;
/*
Add namespace to XMP profile.
*/
xmp_profile=StringToStringInfo("http://ns.adobe.com/xap/1.0/ ");
if (xmp_profile != (StringInfo *) NULL)
{
if (profile != (StringInfo *) NULL)
ConcatenateStringInfo(xmp_profile,profile);
GetStringInfoDatum(xmp_profile)[28]='\0';
for (i=0; i < (ssize_t) GetStringInfoLength(xmp_profile); i+=65533L)
{
length=MagickMin(GetStringInfoLength(xmp_profile)-i,65533L);
jpeg_write_marker(jpeg_info,XML_MARKER,
GetStringInfoDatum(xmp_profile)+i,(unsigned int) length);
}
xmp_profile=DestroyStringInfo(xmp_profile);
}
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"%s profile: %.20g bytes",name,(double) GetStringInfoLength(profile));
name=GetNextImageProfile(image);
}
custom_profile=DestroyStringInfo(custom_profile);
}
static void JPEGDestinationManager(j_compress_ptr cinfo,Image * image)
{
DestinationManager
*destination;
cinfo->dest=(struct jpeg_destination_mgr *) (*cinfo->mem->alloc_small)
((j_common_ptr) cinfo,JPOOL_IMAGE,sizeof(DestinationManager));
destination=(DestinationManager *) cinfo->dest;
destination->manager.init_destination=InitializeDestination;
destination->manager.empty_output_buffer=EmptyOutputBuffer;
destination->manager.term_destination=TerminateDestination;
destination->image=image;
}
static char **SamplingFactorToList(const char *text)
{
char
**textlist;
register char
*q;
register const char
*p;
register ssize_t
i;
if (text == (char *) NULL)
return((char **) NULL);
/*
Convert string to an ASCII list.
*/
textlist=(char **) AcquireQuantumMemory((size_t) MAX_COMPONENTS,
sizeof(*textlist));
if (textlist == (char **) NULL)
ThrowFatalException(ResourceLimitFatalError,"UnableToConvertText");
p=text;
for (i=0; i < (ssize_t) MAX_COMPONENTS; i++)
{
for (q=(char *) p; *q != '\0'; q++)
if (*q == ',')
break;
textlist[i]=(char *) AcquireQuantumMemory((size_t) (q-p)+MaxTextExtent,
sizeof(*textlist[i]));
if (textlist[i] == (char *) NULL)
ThrowFatalException(ResourceLimitFatalError,"UnableToConvertText");
(void) CopyMagickString(textlist[i],p,(size_t) (q-p+1));
if (*q == '\r')
q++;
if (*q == '\0')
break;
p=q+1;
}
for (i++; i < (ssize_t) MAX_COMPONENTS; i++)
textlist[i]=ConstantString("1x1");
return(textlist);
}
static MagickBooleanType WriteJPEGImage(const ImageInfo *image_info,
Image *image)
{
const char
*option,
*sampling_factor,
*value;
ErrorManager
error_manager;
ExceptionInfo
*exception;
Image
*volatile volatile_image;
int
colorspace,
quality;
JSAMPLE
*volatile jpeg_pixels;
JSAMPROW
scanline[1];
MagickBooleanType
status;
MemoryInfo
*memory_info;
register JSAMPLE
*q;
register ssize_t
i;
ssize_t
y;
struct jpeg_compress_struct
jpeg_info;
struct jpeg_error_mgr
jpeg_error;
unsigned short
scale;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
exception=(&image->exception);
if ((LocaleCompare(image_info->magick,"JPS") == 0) &&
(image->next != (Image *) NULL))
image=AppendImages(image,MagickFalse,exception);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
/*
Initialize JPEG parameters.
*/
(void) ResetMagickMemory(&error_manager,0,sizeof(error_manager));
(void) ResetMagickMemory(&jpeg_info,0,sizeof(jpeg_info));
(void) ResetMagickMemory(&jpeg_error,0,sizeof(jpeg_error));
volatile_image=image;
jpeg_info.client_data=(void *) volatile_image;
jpeg_info.err=jpeg_std_error(&jpeg_error);
jpeg_info.err->emit_message=(void (*)(j_common_ptr,int)) JPEGWarningHandler;
jpeg_info.err->error_exit=(void (*)(j_common_ptr)) JPEGErrorHandler;
error_manager.image=volatile_image;
memory_info=(MemoryInfo *) NULL;
if (setjmp(error_manager.error_recovery) != 0)
{
jpeg_destroy_compress(&jpeg_info);
(void) CloseBlob(volatile_image);
return(MagickFalse);
}
jpeg_info.client_data=(void *) &error_manager;
jpeg_create_compress(&jpeg_info);
JPEGDestinationManager(&jpeg_info,image);
if ((image->columns != (unsigned int) image->columns) ||
(image->rows != (unsigned int) image->rows))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
jpeg_info.image_width=(unsigned int) image->columns;
jpeg_info.image_height=(unsigned int) image->rows;
jpeg_info.input_components=3;
jpeg_info.data_precision=8;
jpeg_info.in_color_space=JCS_RGB;
switch (image->colorspace)
{
case CMYKColorspace:
{
jpeg_info.input_components=4;
jpeg_info.in_color_space=JCS_CMYK;
break;
}
case YCbCrColorspace:
case Rec601YCbCrColorspace:
case Rec709YCbCrColorspace:
{
jpeg_info.in_color_space=JCS_YCbCr;
break;
}
case GRAYColorspace:
case Rec601LumaColorspace:
case Rec709LumaColorspace:
{
if (image_info->type == TrueColorType)
break;
jpeg_info.input_components=1;
jpeg_info.in_color_space=JCS_GRAYSCALE;
break;
}
default:
{
(void) TransformImageColorspace(image,sRGBColorspace);
if (image_info->type == TrueColorType)
break;
if (SetImageGray(image,&image->exception) != MagickFalse)
{
jpeg_info.input_components=1;
jpeg_info.in_color_space=JCS_GRAYSCALE;
}
break;
}
}
jpeg_set_defaults(&jpeg_info);
if (jpeg_info.in_color_space == JCS_CMYK)
jpeg_set_colorspace(&jpeg_info,JCS_YCCK);
if ((jpeg_info.data_precision != 12) && (image->depth <= 8))
jpeg_info.data_precision=8;
else
jpeg_info.data_precision=BITS_IN_JSAMPLE;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Image resolution: %.20g,%.20g",image->x_resolution,image->y_resolution);
if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0))
{
/*
Set image resolution.
*/
jpeg_info.write_JFIF_header=TRUE;
jpeg_info.X_density=(UINT16) image->x_resolution;
jpeg_info.Y_density=(UINT16) image->y_resolution;
/*
Set image resolution units.
*/
if (image->units == PixelsPerInchResolution)
jpeg_info.density_unit=(UINT8) 1;
if (image->units == PixelsPerCentimeterResolution)
jpeg_info.density_unit=(UINT8) 2;
}
jpeg_info.dct_method=JDCT_FLOAT;
option=GetImageOption(image_info,"jpeg:dct-method");
if (option != (const char *) NULL)
switch (*option)
{
case 'D':
case 'd':
{
if (LocaleCompare(option,"default") == 0)
jpeg_info.dct_method=JDCT_DEFAULT;
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(option,"fastest") == 0)
jpeg_info.dct_method=JDCT_FASTEST;
if (LocaleCompare(option,"float") == 0)
jpeg_info.dct_method=JDCT_FLOAT;
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(option,"ifast") == 0)
jpeg_info.dct_method=JDCT_IFAST;
if (LocaleCompare(option,"islow") == 0)
jpeg_info.dct_method=JDCT_ISLOW;
break;
}
}
option=GetImageOption(image_info,"jpeg:optimize-coding");
if (option != (const char *) NULL)
jpeg_info.optimize_coding=IsStringTrue(option) != MagickFalse ? TRUE :
FALSE;
else
{
MagickSizeType
length;
length=(MagickSizeType) jpeg_info.input_components*image->columns*
image->rows*sizeof(JSAMPLE);
if (length == (MagickSizeType) ((size_t) length))
{
/*
Perform optimization only if available memory resources permit it.
*/
status=AcquireMagickResource(MemoryResource,length);
RelinquishMagickResource(MemoryResource,length);
jpeg_info.optimize_coding=status == MagickFalse ? FALSE : TRUE;
}
}
#if (JPEG_LIB_VERSION >= 61) && defined(C_PROGRESSIVE_SUPPORTED)
if ((LocaleCompare(image_info->magick,"PJPEG") == 0) ||
(image_info->interlace != NoInterlace))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: progressive");
jpeg_simple_progression(&jpeg_info);
}
else
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: non-progressive");
#else
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: nonprogressive");
#endif
quality=92;
if ((image_info->compression != LosslessJPEGCompression) &&
(image->quality <= 100))
{
if (image->quality != UndefinedCompressionQuality)
quality=(int) image->quality;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Quality: %.20g",
(double) image->quality);
}
else
{
#if !defined(C_LOSSLESS_SUPPORTED)
quality=100;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Quality: 100");
#else
if (image->quality < 100)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderWarning,"LosslessToLossyJPEGConversion",image->filename);
else
{
int
point_transform,
predictor;
predictor=image->quality/100; /* range 1-7 */
point_transform=image->quality % 20; /* range 0-15 */
jpeg_simple_lossless(&jpeg_info,predictor,point_transform);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Compression: lossless");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Predictor: %d",predictor);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Point Transform: %d",point_transform);
}
}
#endif
}
option=GetImageOption(image_info,"jpeg:extent");
if (option != (const char *) NULL)
{
Image
*jpeg_image;
ImageInfo
*jpeg_info;
jpeg_info=CloneImageInfo(image_info);
jpeg_info->blob=NULL;
jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (jpeg_image != (Image *) NULL)
{
MagickSizeType
extent;
size_t
maximum,
minimum;
/*
Search for compression quality that does not exceed image extent.
*/
jpeg_image->quality=0;
extent=(MagickSizeType) SiPrefixToDoubleInterval(option,100.0);
(void) DeleteImageOption(jpeg_info,"jpeg:extent");
(void) DeleteImageArtifact(jpeg_image,"jpeg:extent");
maximum=image_info->quality;
if (maximum < 2)
maximum=101;
for (minimum=2; minimum < maximum; )
{
(void) AcquireUniqueFilename(jpeg_image->filename);
jpeg_image->quality=minimum+(maximum-minimum+1)/2;
(void) WriteJPEGImage(jpeg_info,jpeg_image);
if (GetBlobSize(jpeg_image) <= extent)
minimum=jpeg_image->quality+1;
else
maximum=jpeg_image->quality-1;
(void) RelinquishUniqueFileResource(jpeg_image->filename);
}
quality=(int) minimum-1;
jpeg_image=DestroyImage(jpeg_image);
}
jpeg_info=DestroyImageInfo(jpeg_info);
}
jpeg_set_quality(&jpeg_info,quality,TRUE);
#if (JPEG_LIB_VERSION >= 70)
option=GetImageOption(image_info,"quality");
if (option != (const char *) NULL)
{
GeometryInfo
geometry_info;
int
flags;
/*
Set quality scaling for luminance and chrominance separately.
*/
flags=ParseGeometry(option,&geometry_info);
if (((flags & RhoValue) != 0) && ((flags & SigmaValue) != 0))
{
jpeg_info.q_scale_factor[0]=jpeg_quality_scaling((int)
(geometry_info.rho+0.5));
jpeg_info.q_scale_factor[1]=jpeg_quality_scaling((int)
(geometry_info.sigma+0.5));
jpeg_default_qtables(&jpeg_info,TRUE);
}
}
#endif
colorspace=jpeg_info.in_color_space;
value=GetImageOption(image_info,"jpeg:colorspace");
if (value == (char *) NULL)
value=GetImageProperty(image,"jpeg:colorspace");
if (value != (char *) NULL)
colorspace=StringToInteger(value);
sampling_factor=(const char *) NULL;
if (colorspace == jpeg_info.in_color_space)
{
value=GetImageOption(image_info,"jpeg:sampling-factor");
if (value == (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)
{
if (quality >= 90)
for (i=0; i < MAX_COMPONENTS; i++)
{
jpeg_info.comp_info[i].h_samp_factor=1;
jpeg_info.comp_info[i].v_samp_factor=1;
}
}
else
{
char
**factors;
GeometryInfo
geometry_info;
MagickStatusType
flags;
/*
Set sampling factor.
*/
i=0;
factors=SamplingFactorToList(sampling_factor);
if (factors != (char **) NULL)
{
for (i=0; i < MAX_COMPONENTS; i++)
{
if (factors[i] == (char *) NULL)
break;
flags=ParseGeometry(factors[i],&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
jpeg_info.comp_info[i].h_samp_factor=(int) geometry_info.rho;
jpeg_info.comp_info[i].v_samp_factor=(int) geometry_info.sigma;
factors[i]=(char *) RelinquishMagickMemory(factors[i]);
}
factors=(char **) RelinquishMagickMemory(factors);
}
for ( ; i < MAX_COMPONENTS; i++)
{
jpeg_info.comp_info[i].h_samp_factor=1;
jpeg_info.comp_info[i].v_samp_factor=1;
}
}
option=GetImageOption(image_info,"jpeg:q-table");
if (option != (const char *) NULL)
{
QuantizationTable
*table;
/*
Custom quantization tables.
*/
table=GetQuantizationTable(option,"0",&image->exception);
if (table != (QuantizationTable *) NULL)
{
for (i=0; i < MAX_COMPONENTS; i++)
jpeg_info.comp_info[i].quant_tbl_no=0;
jpeg_add_quant_table(&jpeg_info,0,table->levels,
jpeg_quality_scaling(quality),0);
table=DestroyQuantizationTable(table);
}
table=GetQuantizationTable(option,"1",&image->exception);
if (table != (QuantizationTable *) NULL)
{
for (i=1; i < MAX_COMPONENTS; i++)
jpeg_info.comp_info[i].quant_tbl_no=1;
jpeg_add_quant_table(&jpeg_info,1,table->levels,
jpeg_quality_scaling(quality),0);
table=DestroyQuantizationTable(table);
}
table=GetQuantizationTable(option,"2",&image->exception);
if (table != (QuantizationTable *) NULL)
{
for (i=2; i < MAX_COMPONENTS; i++)
jpeg_info.comp_info[i].quant_tbl_no=2;
jpeg_add_quant_table(&jpeg_info,2,table->levels,
jpeg_quality_scaling(quality),0);
table=DestroyQuantizationTable(table);
}
table=GetQuantizationTable(option,"3",&image->exception);
if (table != (QuantizationTable *) NULL)
{
for (i=3; i < MAX_COMPONENTS; i++)
jpeg_info.comp_info[i].quant_tbl_no=3;
jpeg_add_quant_table(&jpeg_info,3,table->levels,
jpeg_quality_scaling(quality),0);
table=DestroyQuantizationTable(table);
}
}
jpeg_start_compress(&jpeg_info,TRUE);
if (image->debug != MagickFalse)
{
if (image->storage_class == PseudoClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Storage class: PseudoClass");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Storage class: DirectClass");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Depth: %.20g",
(double) image->depth);
if (image->colors != 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Number of colors: %.20g",(double) image->colors);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Number of colors: unspecified");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"JPEG data precision: %d",(int) jpeg_info.data_precision);
switch (image->colorspace)
{
case CMYKColorspace:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Storage class: DirectClass");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Colorspace: CMYK");
break;
}
case YCbCrColorspace:
case Rec601YCbCrColorspace:
case Rec709YCbCrColorspace:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Colorspace: YCbCr");
break;
}
default:
break;
}
switch (image->colorspace)
{
case CMYKColorspace:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Colorspace: CMYK");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling factors: %dx%d,%dx%d,%dx%d,%dx%d",
jpeg_info.comp_info[0].h_samp_factor,
jpeg_info.comp_info[0].v_samp_factor,
jpeg_info.comp_info[1].h_samp_factor,
jpeg_info.comp_info[1].v_samp_factor,
jpeg_info.comp_info[2].h_samp_factor,
jpeg_info.comp_info[2].v_samp_factor,
jpeg_info.comp_info[3].h_samp_factor,
jpeg_info.comp_info[3].v_samp_factor);
break;
}
case GRAYColorspace:
case Rec601LumaColorspace:
case Rec709LumaColorspace:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Colorspace: GRAY");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling factors: %dx%d",jpeg_info.comp_info[0].h_samp_factor,
jpeg_info.comp_info[0].v_samp_factor);
break;
}
case sRGBColorspace:
case RGBColorspace:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Image colorspace is RGB");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling factors: %dx%d,%dx%d,%dx%d",
jpeg_info.comp_info[0].h_samp_factor,
jpeg_info.comp_info[0].v_samp_factor,
jpeg_info.comp_info[1].h_samp_factor,
jpeg_info.comp_info[1].v_samp_factor,
jpeg_info.comp_info[2].h_samp_factor,
jpeg_info.comp_info[2].v_samp_factor);
break;
}
case YCbCrColorspace:
case Rec601YCbCrColorspace:
case Rec709YCbCrColorspace:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Colorspace: YCbCr");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling factors: %dx%d,%dx%d,%dx%d",
jpeg_info.comp_info[0].h_samp_factor,
jpeg_info.comp_info[0].v_samp_factor,
jpeg_info.comp_info[1].h_samp_factor,
jpeg_info.comp_info[1].v_samp_factor,
jpeg_info.comp_info[2].h_samp_factor,
jpeg_info.comp_info[2].v_samp_factor);
break;
}
default:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Colorspace: %d",
image->colorspace);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling factors: %dx%d,%dx%d,%dx%d,%dx%d",
jpeg_info.comp_info[0].h_samp_factor,
jpeg_info.comp_info[0].v_samp_factor,
jpeg_info.comp_info[1].h_samp_factor,
jpeg_info.comp_info[1].v_samp_factor,
jpeg_info.comp_info[2].h_samp_factor,
jpeg_info.comp_info[2].v_samp_factor,
jpeg_info.comp_info[3].h_samp_factor,
jpeg_info.comp_info[3].v_samp_factor);
break;
}
}
}
/*
Write JPEG profiles.
*/
value=GetImageProperty(image,"comment");
if (value != (char *) NULL)
for (i=0; i < (ssize_t) strlen(value); i+=65533L)
jpeg_write_marker(&jpeg_info,JPEG_COM,(unsigned char *) value+i,
(unsigned int) MagickMin((size_t) strlen(value+i),65533L));
if (image->profiles != (void *) NULL)
WriteProfile(&jpeg_info,image);
/*
Convert MIFF to JPEG raster pixels.
*/
memory_info=AcquireVirtualMemory((size_t) image->columns,
jpeg_info.input_components*sizeof(*jpeg_pixels));
if (memory_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
jpeg_pixels=(JSAMPLE *) GetVirtualMemoryBlob(memory_info);
if (setjmp(error_manager.error_recovery) != 0)
{
jpeg_destroy_compress(&jpeg_info);
if (memory_info != (MemoryInfo *) NULL)
memory_info=RelinquishVirtualMemory(memory_info);
(void) CloseBlob(image);
return(MagickFalse);
}
scanline[0]=(JSAMPROW) jpeg_pixels;
scale=65535/(unsigned short) GetQuantumRange((size_t)
jpeg_info.data_precision);
if (scale == 0)
scale=1;
if (jpeg_info.data_precision <= 8)
{
if ((jpeg_info.in_color_space == JCS_RGB) ||
(jpeg_info.in_color_space == JCS_YCbCr))
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=jpeg_pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(JSAMPLE) ScaleQuantumToChar(GetPixelRed(p));
*q++=(JSAMPLE) ScaleQuantumToChar(GetPixelGreen(p));
*q++=(JSAMPLE) ScaleQuantumToChar(GetPixelBlue(p));
p++;
}
(void) jpeg_write_scanlines(&jpeg_info,scanline,1);
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
else
if (jpeg_info.in_color_space == JCS_GRAYSCALE)
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=jpeg_pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(JSAMPLE) ScaleQuantumToChar(ClampToQuantum(
GetPixelLuma(image,p)));
p++;
}
(void) jpeg_write_scanlines(&jpeg_info,scanline,1);
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=jpeg_pixels;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
/*
Convert DirectClass packets to contiguous CMYK scanlines.
*/
*q++=(JSAMPLE) (ScaleQuantumToChar((Quantum) (QuantumRange-
GetPixelCyan(p))));
*q++=(JSAMPLE) (ScaleQuantumToChar((Quantum) (QuantumRange-
GetPixelMagenta(p))));
*q++=(JSAMPLE) (ScaleQuantumToChar((Quantum) (QuantumRange-
GetPixelYellow(p))));
*q++=(JSAMPLE) (ScaleQuantumToChar((Quantum) (QuantumRange-
GetPixelBlack(indexes+x))));
p++;
}
(void) jpeg_write_scanlines(&jpeg_info,scanline,1);
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
if (jpeg_info.in_color_space == JCS_GRAYSCALE)
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=jpeg_pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(JSAMPLE) (ScaleQuantumToShort(ClampToQuantum(
GetPixelLuma(image,p)))/scale);
p++;
}
(void) jpeg_write_scanlines(&jpeg_info,scanline,1);
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
else
if ((jpeg_info.in_color_space == JCS_RGB) ||
(jpeg_info.in_color_space == JCS_YCbCr))
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=jpeg_pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(JSAMPLE) (ScaleQuantumToShort(GetPixelRed(p))/scale);
*q++=(JSAMPLE) (ScaleQuantumToShort(GetPixelGreen(p))/scale);
*q++=(JSAMPLE) (ScaleQuantumToShort(GetPixelBlue(p))/scale);
p++;
}
(void) jpeg_write_scanlines(&jpeg_info,scanline,1);
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=jpeg_pixels;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
/*
Convert DirectClass packets to contiguous CMYK scanlines.
*/
*q++=(JSAMPLE) (ScaleQuantumToShort(QuantumRange-GetPixelRed(p))/
scale);
*q++=(JSAMPLE) (ScaleQuantumToShort(QuantumRange-GetPixelGreen(p))/
scale);
*q++=(JSAMPLE) (ScaleQuantumToShort(QuantumRange-GetPixelBlue(p))/
scale);
*q++=(JSAMPLE) (ScaleQuantumToShort(QuantumRange-
GetPixelIndex(indexes+x))/scale);
p++;
}
(void) jpeg_write_scanlines(&jpeg_info,scanline,1);
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (y == (ssize_t) image->rows)
jpeg_finish_compress(&jpeg_info);
/*
Relinquish resources.
*/
jpeg_destroy_compress(&jpeg_info);
memory_info=RelinquishVirtualMemory(memory_info);
(void) CloseBlob(image);
return(MagickTrue);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4781_0 |
crossvul-cpp_data_bad_5286_1 | /*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Andrei Zmievski <andrei@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if HAVE_WDDX
#include "ext/xml/expat_compat.h"
#include "php_wddx.h"
#include "php_wddx_api.h"
#define PHP_XML_INTERNAL
#include "ext/xml/php_xml.h"
#include "ext/standard/php_incomplete_class.h"
#include "ext/standard/base64.h"
#include "ext/standard/info.h"
#include "ext/standard/php_smart_str.h"
#include "ext/standard/html.h"
#include "ext/standard/php_string.h"
#include "ext/date/php_date.h"
#include "zend_globals.h"
#define WDDX_BUF_LEN 256
#define PHP_CLASS_NAME_VAR "php_class_name"
#define EL_ARRAY "array"
#define EL_BINARY "binary"
#define EL_BOOLEAN "boolean"
#define EL_CHAR "char"
#define EL_CHAR_CODE "code"
#define EL_NULL "null"
#define EL_NUMBER "number"
#define EL_PACKET "wddxPacket"
#define EL_STRING "string"
#define EL_STRUCT "struct"
#define EL_VALUE "value"
#define EL_VAR "var"
#define EL_NAME "name"
#define EL_VERSION "version"
#define EL_RECORDSET "recordset"
#define EL_FIELD "field"
#define EL_DATETIME "dateTime"
#define php_wddx_deserialize(a,b) \
php_wddx_deserialize_ex((a)->value.str.val, (a)->value.str.len, (b))
#define SET_STACK_VARNAME \
if (stack->varname) { \
ent.varname = estrdup(stack->varname); \
efree(stack->varname); \
stack->varname = NULL; \
} else \
ent.varname = NULL; \
static int le_wddx;
typedef struct {
zval *data;
enum {
ST_ARRAY,
ST_BOOLEAN,
ST_NULL,
ST_NUMBER,
ST_STRING,
ST_BINARY,
ST_STRUCT,
ST_RECORDSET,
ST_FIELD,
ST_DATETIME
} type;
char *varname;
} st_entry;
typedef struct {
int top, max;
char *varname;
zend_bool done;
void **elements;
} wddx_stack;
static void php_wddx_process_data(void *user_data, const XML_Char *s, int len);
/* {{{ arginfo */
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_value, 0, 0, 1)
ZEND_ARG_INFO(0, var)
ZEND_ARG_INFO(0, comment)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_vars, 0, 0, 1)
ZEND_ARG_VARIADIC_INFO(0, var_names)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_start, 0, 0, 0)
ZEND_ARG_INFO(0, comment)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_packet_end, 0, 0, 1)
ZEND_ARG_INFO(0, packet_id)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_add_vars, 0, 0, 2)
ZEND_ARG_INFO(0, packet_id)
ZEND_ARG_VARIADIC_INFO(0, var_names)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_deserialize, 0, 0, 1)
ZEND_ARG_INFO(0, packet)
ZEND_END_ARG_INFO()
/* }}} */
/* {{{ wddx_functions[]
*/
const zend_function_entry wddx_functions[] = {
PHP_FE(wddx_serialize_value, arginfo_wddx_serialize_value)
PHP_FE(wddx_serialize_vars, arginfo_wddx_serialize_vars)
PHP_FE(wddx_packet_start, arginfo_wddx_serialize_start)
PHP_FE(wddx_packet_end, arginfo_wddx_packet_end)
PHP_FE(wddx_add_vars, arginfo_wddx_add_vars)
PHP_FE(wddx_deserialize, arginfo_wddx_deserialize)
PHP_FE_END
};
/* }}} */
PHP_MINIT_FUNCTION(wddx);
PHP_MINFO_FUNCTION(wddx);
/* {{{ dynamically loadable module stuff */
#ifdef COMPILE_DL_WDDX
ZEND_GET_MODULE(wddx)
#endif /* COMPILE_DL_WDDX */
/* }}} */
/* {{{ wddx_module_entry
*/
zend_module_entry wddx_module_entry = {
STANDARD_MODULE_HEADER,
"wddx",
wddx_functions,
PHP_MINIT(wddx),
NULL,
NULL,
NULL,
PHP_MINFO(wddx),
NO_VERSION_YET,
STANDARD_MODULE_PROPERTIES
};
/* }}} */
/* {{{ wddx_stack_init
*/
static int wddx_stack_init(wddx_stack *stack)
{
stack->top = 0;
stack->elements = (void **) safe_emalloc(sizeof(void **), STACK_BLOCK_SIZE, 0);
stack->max = STACK_BLOCK_SIZE;
stack->varname = NULL;
stack->done = 0;
return SUCCESS;
}
/* }}} */
/* {{{ wddx_stack_push
*/
static int wddx_stack_push(wddx_stack *stack, void *element, int size)
{
if (stack->top >= stack->max) { /* we need to allocate more memory */
stack->elements = (void **) erealloc(stack->elements,
(sizeof(void **) * (stack->max += STACK_BLOCK_SIZE)));
}
stack->elements[stack->top] = (void *) emalloc(size);
memcpy(stack->elements[stack->top], element, size);
return stack->top++;
}
/* }}} */
/* {{{ wddx_stack_top
*/
static int wddx_stack_top(wddx_stack *stack, void **element)
{
if (stack->top > 0) {
*element = stack->elements[stack->top - 1];
return SUCCESS;
} else {
*element = NULL;
return FAILURE;
}
}
/* }}} */
/* {{{ wddx_stack_is_empty
*/
static int wddx_stack_is_empty(wddx_stack *stack)
{
if (stack->top == 0) {
return 1;
} else {
return 0;
}
}
/* }}} */
/* {{{ wddx_stack_destroy
*/
static int wddx_stack_destroy(wddx_stack *stack)
{
register int i;
if (stack->elements) {
for (i = 0; i < stack->top; i++) {
if (((st_entry *)stack->elements[i])->data
&& ((st_entry *)stack->elements[i])->type != ST_FIELD) {
zval_ptr_dtor(&((st_entry *)stack->elements[i])->data);
}
if (((st_entry *)stack->elements[i])->varname) {
efree(((st_entry *)stack->elements[i])->varname);
}
efree(stack->elements[i]);
}
efree(stack->elements);
}
return SUCCESS;
}
/* }}} */
/* {{{ release_wddx_packet_rsrc
*/
static void release_wddx_packet_rsrc(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
smart_str *str = (smart_str *)rsrc->ptr;
smart_str_free(str);
efree(str);
}
/* }}} */
#include "ext/session/php_session.h"
#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
/* {{{ PS_SERIALIZER_ENCODE_FUNC
*/
PS_SERIALIZER_ENCODE_FUNC(wddx)
{
wddx_packet *packet;
PS_ENCODE_VARS;
packet = php_wddx_constructor();
php_wddx_packet_start(packet, NULL, 0);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
PS_ENCODE_LOOP(
php_wddx_serialize_var(packet, *struc, key, key_length TSRMLS_CC);
);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
php_wddx_packet_end(packet);
*newstr = php_wddx_gather(packet);
php_wddx_destructor(packet);
if (newlen) {
*newlen = strlen(*newstr);
}
return SUCCESS;
}
/* }}} */
/* {{{ PS_SERIALIZER_DECODE_FUNC
*/
PS_SERIALIZER_DECODE_FUNC(wddx)
{
zval *retval;
zval **ent;
char *key;
uint key_length;
char tmp[128];
ulong idx;
int hash_type;
int ret;
if (vallen == 0) {
return SUCCESS;
}
MAKE_STD_ZVAL(retval);
if ((ret = php_wddx_deserialize_ex((char *)val, vallen, retval)) == SUCCESS) {
if (Z_TYPE_P(retval) != IS_ARRAY) {
zval_ptr_dtor(&retval);
return FAILURE;
}
for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(retval));
zend_hash_get_current_data(Z_ARRVAL_P(retval), (void **) &ent) == SUCCESS;
zend_hash_move_forward(Z_ARRVAL_P(retval))) {
hash_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(retval), &key, &key_length, &idx, 0, NULL);
switch (hash_type) {
case HASH_KEY_IS_LONG:
key_length = slprintf(tmp, sizeof(tmp), "%ld", idx) + 1;
key = tmp;
/* fallthru */
case HASH_KEY_IS_STRING:
php_set_session_var(key, key_length-1, *ent, NULL TSRMLS_CC);
PS_ADD_VAR(key);
}
}
}
zval_ptr_dtor(&retval);
return ret;
}
/* }}} */
#endif
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(wddx)
{
le_wddx = zend_register_list_destructors_ex(release_wddx_packet_rsrc, NULL, "wddx", module_number);
#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
php_session_register_serializer("wddx",
PS_SERIALIZER_ENCODE_NAME(wddx),
PS_SERIALIZER_DECODE_NAME(wddx));
#endif
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(wddx)
{
php_info_print_table_start();
#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
php_info_print_table_header(2, "WDDX Support", "enabled" );
php_info_print_table_row(2, "WDDX Session Serializer", "enabled" );
#else
php_info_print_table_row(2, "WDDX Support", "enabled" );
#endif
php_info_print_table_end();
}
/* }}} */
/* {{{ php_wddx_packet_start
*/
void php_wddx_packet_start(wddx_packet *packet, char *comment, int comment_len)
{
php_wddx_add_chunk_static(packet, WDDX_PACKET_S);
if (comment) {
char *escaped;
size_t escaped_len;
TSRMLS_FETCH();
escaped = php_escape_html_entities(
comment, comment_len, &escaped_len, 0, ENT_QUOTES, NULL TSRMLS_CC);
php_wddx_add_chunk_static(packet, WDDX_HEADER_S);
php_wddx_add_chunk_static(packet, WDDX_COMMENT_S);
php_wddx_add_chunk_ex(packet, escaped, escaped_len);
php_wddx_add_chunk_static(packet, WDDX_COMMENT_E);
php_wddx_add_chunk_static(packet, WDDX_HEADER_E);
str_efree(escaped);
} else {
php_wddx_add_chunk_static(packet, WDDX_HEADER);
}
php_wddx_add_chunk_static(packet, WDDX_DATA_S);
}
/* }}} */
/* {{{ php_wddx_packet_end
*/
void php_wddx_packet_end(wddx_packet *packet)
{
php_wddx_add_chunk_static(packet, WDDX_DATA_E);
php_wddx_add_chunk_static(packet, WDDX_PACKET_E);
}
/* }}} */
#define FLUSH_BUF() \
if (l > 0) { \
php_wddx_add_chunk_ex(packet, buf, l); \
l = 0; \
}
/* {{{ php_wddx_serialize_string
*/
static void php_wddx_serialize_string(wddx_packet *packet, zval *var TSRMLS_DC)
{
php_wddx_add_chunk_static(packet, WDDX_STRING_S);
if (Z_STRLEN_P(var) > 0) {
char *buf;
size_t buf_len;
buf = php_escape_html_entities(Z_STRVAL_P(var), Z_STRLEN_P(var), &buf_len, 0, ENT_QUOTES, NULL TSRMLS_CC);
php_wddx_add_chunk_ex(packet, buf, buf_len);
str_efree(buf);
}
php_wddx_add_chunk_static(packet, WDDX_STRING_E);
}
/* }}} */
/* {{{ php_wddx_serialize_number
*/
static void php_wddx_serialize_number(wddx_packet *packet, zval *var)
{
char tmp_buf[WDDX_BUF_LEN];
zval tmp;
tmp = *var;
zval_copy_ctor(&tmp);
convert_to_string(&tmp);
snprintf(tmp_buf, sizeof(tmp_buf), WDDX_NUMBER, Z_STRVAL(tmp));
zval_dtor(&tmp);
php_wddx_add_chunk(packet, tmp_buf);
}
/* }}} */
/* {{{ php_wddx_serialize_boolean
*/
static void php_wddx_serialize_boolean(wddx_packet *packet, zval *var)
{
php_wddx_add_chunk(packet, Z_LVAL_P(var) ? WDDX_BOOLEAN_TRUE : WDDX_BOOLEAN_FALSE);
}
/* }}} */
/* {{{ php_wddx_serialize_unset
*/
static void php_wddx_serialize_unset(wddx_packet *packet)
{
php_wddx_add_chunk_static(packet, WDDX_NULL);
}
/* }}} */
/* {{{ php_wddx_serialize_object
*/
static void php_wddx_serialize_object(wddx_packet *packet, zval *obj)
{
/* OBJECTS_FIXME */
zval **ent, *fname, **varname;
zval *retval = NULL;
const char *key;
ulong idx;
char tmp_buf[WDDX_BUF_LEN];
HashTable *objhash, *sleephash;
TSRMLS_FETCH();
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__sleep", 1);
/*
* We try to call __sleep() method on object. It's supposed to return an
* array of property names to be serialized.
*/
if (call_user_function_ex(CG(function_table), &obj, fname, &retval, 0, 0, 1, NULL TSRMLS_CC) == SUCCESS) {
if (retval && (sleephash = HASH_OF(retval))) {
PHP_CLASS_ATTRIBUTES;
PHP_SET_CLASS_ATTRIBUTES(obj);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR);
php_wddx_add_chunk(packet, tmp_buf);
php_wddx_add_chunk_static(packet, WDDX_STRING_S);
php_wddx_add_chunk_ex(packet, class_name, name_len);
php_wddx_add_chunk_static(packet, WDDX_STRING_E);
php_wddx_add_chunk_static(packet, WDDX_VAR_E);
PHP_CLEANUP_CLASS_ATTRIBUTES();
objhash = HASH_OF(obj);
for (zend_hash_internal_pointer_reset(sleephash);
zend_hash_get_current_data(sleephash, (void **)&varname) == SUCCESS;
zend_hash_move_forward(sleephash)) {
if (Z_TYPE_PP(varname) != IS_STRING) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize.");
continue;
}
if (zend_hash_find(objhash, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname)+1, (void **)&ent) == SUCCESS) {
php_wddx_serialize_var(packet, *ent, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname) TSRMLS_CC);
}
}
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
}
} else {
uint key_len;
PHP_CLASS_ATTRIBUTES;
PHP_SET_CLASS_ATTRIBUTES(obj);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR);
php_wddx_add_chunk(packet, tmp_buf);
php_wddx_add_chunk_static(packet, WDDX_STRING_S);
php_wddx_add_chunk_ex(packet, class_name, name_len);
php_wddx_add_chunk_static(packet, WDDX_STRING_E);
php_wddx_add_chunk_static(packet, WDDX_VAR_E);
PHP_CLEANUP_CLASS_ATTRIBUTES();
objhash = HASH_OF(obj);
for (zend_hash_internal_pointer_reset(objhash);
zend_hash_get_current_data(objhash, (void**)&ent) == SUCCESS;
zend_hash_move_forward(objhash)) {
if (*ent == obj) {
continue;
}
if (zend_hash_get_current_key_ex(objhash, &key, &key_len, &idx, 0, NULL) == HASH_KEY_IS_STRING) {
const char *class_name, *prop_name;
zend_unmangle_property_name(key, key_len-1, &class_name, &prop_name);
php_wddx_serialize_var(packet, *ent, prop_name, strlen(prop_name)+1 TSRMLS_CC);
} else {
key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx);
php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC);
}
}
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
}
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
/* }}} */
/* {{{ php_wddx_serialize_array
*/
static void php_wddx_serialize_array(wddx_packet *packet, zval *arr)
{
zval **ent;
char *key;
uint key_len;
int is_struct = 0, ent_type;
ulong idx;
HashTable *target_hash;
char tmp_buf[WDDX_BUF_LEN];
ulong ind = 0;
int type;
TSRMLS_FETCH();
target_hash = HASH_OF(arr);
for (zend_hash_internal_pointer_reset(target_hash);
zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS;
zend_hash_move_forward(target_hash)) {
type = zend_hash_get_current_key(target_hash, &key, &idx, 0);
if (type == HASH_KEY_IS_STRING) {
is_struct = 1;
break;
}
if (idx != ind) {
is_struct = 1;
break;
}
ind++;
}
if (is_struct) {
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
} else {
snprintf(tmp_buf, sizeof(tmp_buf), WDDX_ARRAY_S, zend_hash_num_elements(target_hash));
php_wddx_add_chunk(packet, tmp_buf);
}
for (zend_hash_internal_pointer_reset(target_hash);
zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS;
zend_hash_move_forward(target_hash)) {
if (*ent == arr) {
continue;
}
if (is_struct) {
ent_type = zend_hash_get_current_key_ex(target_hash, &key, &key_len, &idx, 0, NULL);
if (ent_type == HASH_KEY_IS_STRING) {
php_wddx_serialize_var(packet, *ent, key, key_len TSRMLS_CC);
} else {
key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx);
php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC);
}
} else {
php_wddx_serialize_var(packet, *ent, NULL, 0 TSRMLS_CC);
}
}
if (is_struct) {
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
} else {
php_wddx_add_chunk_static(packet, WDDX_ARRAY_E);
}
}
/* }}} */
/* {{{ php_wddx_serialize_var
*/
void php_wddx_serialize_var(wddx_packet *packet, zval *var, char *name, int name_len TSRMLS_DC)
{
HashTable *ht;
if (name) {
size_t name_esc_len;
char *tmp_buf, *name_esc;
name_esc = php_escape_html_entities(name, name_len, &name_esc_len, 0, ENT_QUOTES, NULL TSRMLS_CC);
tmp_buf = emalloc(name_esc_len + sizeof(WDDX_VAR_S));
snprintf(tmp_buf, name_esc_len + sizeof(WDDX_VAR_S), WDDX_VAR_S, name_esc);
php_wddx_add_chunk(packet, tmp_buf);
efree(tmp_buf);
str_efree(name_esc);
}
switch(Z_TYPE_P(var)) {
case IS_STRING:
php_wddx_serialize_string(packet, var TSRMLS_CC);
break;
case IS_LONG:
case IS_DOUBLE:
php_wddx_serialize_number(packet, var);
break;
case IS_BOOL:
php_wddx_serialize_boolean(packet, var);
break;
case IS_NULL:
php_wddx_serialize_unset(packet);
break;
case IS_ARRAY:
ht = Z_ARRVAL_P(var);
if (ht->nApplyCount > 1) {
php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references");
return;
}
ht->nApplyCount++;
php_wddx_serialize_array(packet, var);
ht->nApplyCount--;
break;
case IS_OBJECT:
ht = Z_OBJPROP_P(var);
if (ht->nApplyCount > 1) {
php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references");
return;
}
ht->nApplyCount++;
php_wddx_serialize_object(packet, var);
ht->nApplyCount--;
break;
}
if (name) {
php_wddx_add_chunk_static(packet, WDDX_VAR_E);
}
}
/* }}} */
/* {{{ php_wddx_add_var
*/
static void php_wddx_add_var(wddx_packet *packet, zval *name_var)
{
zval **val;
HashTable *target_hash;
TSRMLS_FETCH();
if (Z_TYPE_P(name_var) == IS_STRING) {
if (!EG(active_symbol_table)) {
zend_rebuild_symbol_table(TSRMLS_C);
}
if (zend_hash_find(EG(active_symbol_table), Z_STRVAL_P(name_var),
Z_STRLEN_P(name_var)+1, (void**)&val) != FAILURE) {
php_wddx_serialize_var(packet, *val, Z_STRVAL_P(name_var), Z_STRLEN_P(name_var) TSRMLS_CC);
}
} else if (Z_TYPE_P(name_var) == IS_ARRAY || Z_TYPE_P(name_var) == IS_OBJECT) {
int is_array = Z_TYPE_P(name_var) == IS_ARRAY;
target_hash = HASH_OF(name_var);
if (is_array && target_hash->nApplyCount > 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected");
return;
}
zend_hash_internal_pointer_reset(target_hash);
while(zend_hash_get_current_data(target_hash, (void**)&val) == SUCCESS) {
if (is_array) {
target_hash->nApplyCount++;
}
php_wddx_add_var(packet, *val);
if (is_array) {
target_hash->nApplyCount--;
}
zend_hash_move_forward(target_hash);
}
}
}
/* }}} */
/* {{{ php_wddx_push_element
*/
static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts)
{
st_entry ent;
wddx_stack *stack = (wddx_stack *)user_data;
if (!strcmp(name, EL_PACKET)) {
int i;
if (atts) for (i=0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VERSION)) {
/* nothing for now */
}
}
} else if (!strcmp(name, EL_STRING)) {
ent.type = ST_STRING;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BINARY)) {
ent.type = ST_BINARY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_CHAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_CHAR_CODE) && atts[++i] && atts[i][0]) {
char tmp_buf[2];
snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i], NULL, 16));
php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf));
break;
}
}
} else if (!strcmp(name, EL_NUMBER)) {
ent.type = ST_NUMBER;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
Z_LVAL_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BOOLEAN)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VALUE) && atts[++i] && atts[i][0]) {
ent.type = ST_BOOLEAN;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_BOOL;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
php_wddx_process_data(user_data, atts[i], strlen(atts[i]));
break;
}
}
} else if (!strcmp(name, EL_NULL)) {
ent.type = ST_NULL;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
ZVAL_NULL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_ARRAY)) {
ent.type = ST_ARRAY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_STRUCT)) {
ent.type = ST_STRUCT;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_VAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[++i] && atts[i][0]) {
if (stack->varname) efree(stack->varname);
stack->varname = estrdup(atts[i]);
break;
}
}
} else if (!strcmp(name, EL_RECORDSET)) {
int i;
ent.type = ST_RECORDSET;
SET_STACK_VARNAME;
MAKE_STD_ZVAL(ent.data);
array_init(ent.data);
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], "fieldNames") && atts[++i] && atts[i][0]) {
zval *tmp;
char *key;
char *p1, *p2, *endp;
endp = (char *)atts[i] + strlen(atts[i]);
p1 = (char *)atts[i];
while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) {
key = estrndup(p1, p2 - p1);
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp);
p1 = p2 + sizeof(",")-1;
efree(key);
}
if (p1 <= endp) {
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp);
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_FIELD)) {
int i;
st_entry ent;
ent.type = ST_FIELD;
ent.varname = NULL;
ent.data = NULL;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[++i] && atts[i][0]) {
st_entry *recordset;
zval **field;
if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS &&
recordset->type == ST_RECORDSET &&
zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i], strlen(atts[i])+1, (void**)&field) == SUCCESS) {
ent.data = *field;
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_DATETIME)) {
ent.type = ST_DATETIME;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
}
/* }}} */
/* {{{ php_wddx_pop_element
*/
static void php_wddx_pop_element(void *user_data, const XML_Char *name)
{
st_entry *ent1, *ent2;
wddx_stack *stack = (wddx_stack *)user_data;
HashTable *target_hash;
zend_class_entry **pce;
zval *obj;
zval *tmp;
TSRMLS_FETCH();
/* OBJECTS_FIXME */
if (stack->top == 0) {
return;
}
if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||
!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||
!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||
!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||
!strcmp(name, EL_DATETIME)) {
wddx_stack_top(stack, (void**)&ent1);
if (!ent1->data) {
if (stack->top > 1) {
stack->top--;
efree(ent1);
} else {
stack->done = 1;
}
return;
}
if (!strcmp(name, EL_BINARY)) {
int new_len=0;
unsigned char *new_str;
new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len);
STR_FREE(Z_STRVAL_P(ent1->data));
if (new_str) {
Z_STRVAL_P(ent1->data) = new_str;
Z_STRLEN_P(ent1->data) = new_len;
} else {
ZVAL_EMPTY_STRING(ent1->data);
}
}
/* Call __wakeup() method on the object. */
if (Z_TYPE_P(ent1->data) == IS_OBJECT) {
zval *fname, *retval = NULL;
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__wakeup", 1);
call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
if (stack->top > 1) {
stack->top--;
wddx_stack_top(stack, (void**)&ent2);
/* if non-existent field */
if (ent2->data == NULL) {
zval_ptr_dtor(&ent1->data);
efree(ent1);
return;
}
if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {
target_hash = HASH_OF(ent2->data);
if (ent1->varname) {
if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&
ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {
zend_bool incomplete_class = 0;
zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),
Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {
incomplete_class = 1;
pce = &PHP_IC_ENTRY;
}
/* Initialize target object */
MAKE_STD_ZVAL(obj);
object_init_ex(obj, *pce);
/* Merge current hashtable with object's default properties */
zend_hash_merge(Z_OBJPROP_P(obj),
Z_ARRVAL_P(ent2->data),
(void (*)(void *)) zval_add_ref,
(void *) &tmp, sizeof(zval *), 0);
if (incomplete_class) {
php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
}
/* Clean up old array entry */
zval_ptr_dtor(&ent2->data);
/* Set stack entry to point to the newly created object */
ent2->data = obj;
/* Clean up class name var entry */
zval_ptr_dtor(&ent1->data);
} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {
zend_class_entry *old_scope = EG(scope);
EG(scope) = Z_OBJCE_P(ent2->data);
Z_DELREF_P(ent1->data);
add_property_zval(ent2->data, ent1->varname, ent1->data);
EG(scope) = old_scope;
} else {
zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);
}
efree(ent1->varname);
} else {
zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);
}
}
efree(ent1);
} else {
stack->done = 1;
}
} else if (!strcmp(name, EL_VAR) && stack->varname) {
efree(stack->varname);
stack->varname = NULL;
} else if (!strcmp(name, EL_FIELD)) {
st_entry *ent;
wddx_stack_top(stack, (void **)&ent);
efree(ent);
stack->top--;
}
}
/* }}} */
/* {{{ php_wddx_process_data
*/
static void php_wddx_process_data(void *user_data, const XML_Char *s, int len)
{
st_entry *ent;
wddx_stack *stack = (wddx_stack *)user_data;
TSRMLS_FETCH();
if (!wddx_stack_is_empty(stack) && !stack->done) {
wddx_stack_top(stack, (void**)&ent);
switch (ent->type) {
case ST_STRING:
if (Z_STRLEN_P(ent->data) == 0) {
STR_FREE(Z_STRVAL_P(ent->data));
Z_STRVAL_P(ent->data) = estrndup(s, len);
Z_STRLEN_P(ent->data) = len;
} else {
Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1);
memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len);
Z_STRLEN_P(ent->data) += len;
Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0';
}
break;
case ST_BINARY:
if (Z_STRLEN_P(ent->data) == 0) {
STR_FREE(Z_STRVAL_P(ent->data));
Z_STRVAL_P(ent->data) = estrndup(s, len + 1);
} else {
Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1);
memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len);
}
Z_STRLEN_P(ent->data) += len;
Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0';
break;
case ST_NUMBER:
Z_TYPE_P(ent->data) = IS_STRING;
Z_STRLEN_P(ent->data) = len;
Z_STRVAL_P(ent->data) = estrndup(s, len);
convert_scalar_to_number(ent->data TSRMLS_CC);
break;
case ST_BOOLEAN:
if(!ent->data) {
break;
}
if (!strcmp(s, "true")) {
Z_LVAL_P(ent->data) = 1;
} else if (!strcmp(s, "false")) {
Z_LVAL_P(ent->data) = 0;
} else {
zval_ptr_dtor(&ent->data);
if (ent->varname) {
efree(ent->varname);
ent->varname = NULL;
}
ent->data = NULL;
}
break;
case ST_DATETIME: {
char *tmp;
if (Z_TYPE_P(ent->data) == IS_STRING) {
tmp = safe_emalloc(Z_STRLEN_P(ent->data), 1, (size_t)len + 1);
memcpy(tmp, Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data));
memcpy(tmp + Z_STRLEN_P(ent->data), s, len);
len += Z_STRLEN_P(ent->data);
efree(Z_STRVAL_P(ent->data));
Z_TYPE_P(ent->data) = IS_LONG;
} else {
tmp = emalloc(len + 1);
memcpy(tmp, s, len);
}
tmp[len] = '\0';
Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL);
/* date out of range < 1969 or > 2038 */
if (Z_LVAL_P(ent->data) == -1) {
ZVAL_STRINGL(ent->data, tmp, len, 0);
} else {
efree(tmp);
}
}
break;
default:
break;
}
}
}
/* }}} */
/* {{{ php_wddx_deserialize_ex
*/
int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value)
{
wddx_stack stack;
XML_Parser parser;
st_entry *ent;
int retval;
wddx_stack_init(&stack);
parser = XML_ParserCreate("UTF-8");
XML_SetUserData(parser, &stack);
XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element);
XML_SetCharacterDataHandler(parser, php_wddx_process_data);
XML_Parse(parser, value, vallen, 1);
XML_ParserFree(parser);
if (stack.top == 1) {
wddx_stack_top(&stack, (void**)&ent);
if(ent->data == NULL) {
retval = FAILURE;
} else {
*return_value = *(ent->data);
zval_copy_ctor(return_value);
retval = SUCCESS;
}
} else {
retval = FAILURE;
}
wddx_stack_destroy(&stack);
return retval;
}
/* }}} */
/* {{{ proto string wddx_serialize_value(mixed var [, string comment])
Creates a new packet and serializes the given value */
PHP_FUNCTION(wddx_serialize_value)
{
zval *var;
char *comment = NULL;
int comment_len = 0;
wddx_packet *packet;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|s", &var, &comment, &comment_len) == FAILURE) {
return;
}
packet = php_wddx_constructor();
php_wddx_packet_start(packet, comment, comment_len);
php_wddx_serialize_var(packet, var, NULL, 0 TSRMLS_CC);
php_wddx_packet_end(packet);
ZVAL_STRINGL(return_value, packet->c, packet->len, 1);
smart_str_free(packet);
efree(packet);
}
/* }}} */
/* {{{ proto string wddx_serialize_vars(mixed var_name [, mixed ...])
Creates a new packet and serializes given variables into a struct */
PHP_FUNCTION(wddx_serialize_vars)
{
int num_args, i;
wddx_packet *packet;
zval ***args = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &num_args) == FAILURE) {
return;
}
packet = php_wddx_constructor();
php_wddx_packet_start(packet, NULL, 0);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
for (i=0; i<num_args; i++) {
if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) {
convert_to_string_ex(args[i]);
}
php_wddx_add_var(packet, *args[i]);
}
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
php_wddx_packet_end(packet);
efree(args);
ZVAL_STRINGL(return_value, packet->c, packet->len, 1);
smart_str_free(packet);
efree(packet);
}
/* }}} */
/* {{{ php_wddx_constructor
*/
wddx_packet *php_wddx_constructor(void)
{
smart_str *packet;
packet = (smart_str *)emalloc(sizeof(smart_str));
packet->c = NULL;
return packet;
}
/* }}} */
/* {{{ php_wddx_destructor
*/
void php_wddx_destructor(wddx_packet *packet)
{
smart_str_free(packet);
efree(packet);
}
/* }}} */
/* {{{ proto resource wddx_packet_start([string comment])
Starts a WDDX packet with optional comment and returns the packet id */
PHP_FUNCTION(wddx_packet_start)
{
char *comment = NULL;
int comment_len = 0;
wddx_packet *packet;
comment = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &comment, &comment_len) == FAILURE) {
return;
}
packet = php_wddx_constructor();
php_wddx_packet_start(packet, comment, comment_len);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
ZEND_REGISTER_RESOURCE(return_value, packet, le_wddx);
}
/* }}} */
/* {{{ proto string wddx_packet_end(resource packet_id)
Ends specified WDDX packet and returns the string containing the packet */
PHP_FUNCTION(wddx_packet_end)
{
zval *packet_id;
wddx_packet *packet = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &packet_id) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
php_wddx_packet_end(packet);
ZVAL_STRINGL(return_value, packet->c, packet->len, 1);
zend_list_delete(Z_LVAL_P(packet_id));
}
/* }}} */
/* {{{ proto int wddx_add_vars(resource packet_id, mixed var_names [, mixed ...])
Serializes given variables and adds them to packet given by packet_id */
PHP_FUNCTION(wddx_add_vars)
{
int num_args, i;
zval ***args = NULL;
zval *packet_id;
wddx_packet *packet = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r+", &packet_id, &args, &num_args) == FAILURE) {
return;
}
if (!ZEND_FETCH_RESOURCE_NO_RETURN(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx)) {
efree(args);
RETURN_FALSE;
}
if (!packet) {
efree(args);
RETURN_FALSE;
}
for (i=0; i<num_args; i++) {
if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) {
convert_to_string_ex(args[i]);
}
php_wddx_add_var(packet, (*args[i]));
}
efree(args);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto mixed wddx_deserialize(mixed packet)
Deserializes given packet and returns a PHP value */
PHP_FUNCTION(wddx_deserialize)
{
zval *packet;
char *payload;
int payload_len;
php_stream *stream = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &packet) == FAILURE) {
return;
}
if (Z_TYPE_P(packet) == IS_STRING) {
payload = Z_STRVAL_P(packet);
payload_len = Z_STRLEN_P(packet);
} else if (Z_TYPE_P(packet) == IS_RESOURCE) {
php_stream_from_zval(stream, &packet);
if (stream) {
payload_len = php_stream_copy_to_mem(stream, &payload, PHP_STREAM_COPY_ALL, 0);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Expecting parameter 1 to be a string or a stream");
return;
}
if (payload_len == 0) {
return;
}
php_wddx_deserialize_ex(payload, payload_len, return_value);
if (stream) {
pefree(payload, 0);
}
}
/* }}} */
#endif /* HAVE_LIBEXPAT */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5286_1 |
crossvul-cpp_data_bad_4946_7 | #include "cache.h"
#include "tag.h"
#include "blob.h"
#include "tree.h"
#include "commit.h"
#include "diff.h"
#include "refs.h"
#include "revision.h"
#include "graph.h"
#include "grep.h"
#include "reflog-walk.h"
#include "patch-ids.h"
#include "decorate.h"
#include "log-tree.h"
#include "string-list.h"
#include "line-log.h"
#include "mailmap.h"
#include "commit-slab.h"
#include "dir.h"
#include "cache-tree.h"
#include "bisect.h"
volatile show_early_output_fn_t show_early_output;
static const char *term_bad;
static const char *term_good;
char *path_name(struct strbuf *path, const char *name)
{
struct strbuf ret = STRBUF_INIT;
if (path)
strbuf_addbuf(&ret, path);
strbuf_addstr(&ret, name);
return strbuf_detach(&ret, NULL);
}
void show_object_with_name(FILE *out, struct object *obj,
struct strbuf *path, const char *component)
{
char *name = path_name(path, component);
char *p;
fprintf(out, "%s ", oid_to_hex(&obj->oid));
for (p = name; *p && *p != '\n'; p++)
fputc(*p, out);
fputc('\n', out);
free(name);
}
static void mark_blob_uninteresting(struct blob *blob)
{
if (!blob)
return;
if (blob->object.flags & UNINTERESTING)
return;
blob->object.flags |= UNINTERESTING;
}
static void mark_tree_contents_uninteresting(struct tree *tree)
{
struct tree_desc desc;
struct name_entry entry;
struct object *obj = &tree->object;
if (!has_object_file(&obj->oid))
return;
if (parse_tree(tree) < 0)
die("bad tree %s", oid_to_hex(&obj->oid));
init_tree_desc(&desc, tree->buffer, tree->size);
while (tree_entry(&desc, &entry)) {
switch (object_type(entry.mode)) {
case OBJ_TREE:
mark_tree_uninteresting(lookup_tree(entry.sha1));
break;
case OBJ_BLOB:
mark_blob_uninteresting(lookup_blob(entry.sha1));
break;
default:
/* Subproject commit - not in this repository */
break;
}
}
/*
* We don't care about the tree any more
* after it has been marked uninteresting.
*/
free_tree_buffer(tree);
}
void mark_tree_uninteresting(struct tree *tree)
{
struct object *obj;
if (!tree)
return;
obj = &tree->object;
if (obj->flags & UNINTERESTING)
return;
obj->flags |= UNINTERESTING;
mark_tree_contents_uninteresting(tree);
}
void mark_parents_uninteresting(struct commit *commit)
{
struct commit_list *parents = NULL, *l;
for (l = commit->parents; l; l = l->next)
commit_list_insert(l->item, &parents);
while (parents) {
struct commit *commit = pop_commit(&parents);
while (commit) {
/*
* A missing commit is ok iff its parent is marked
* uninteresting.
*
* We just mark such a thing parsed, so that when
* it is popped next time around, we won't be trying
* to parse it and get an error.
*/
if (!has_object_file(&commit->object.oid))
commit->object.parsed = 1;
if (commit->object.flags & UNINTERESTING)
break;
commit->object.flags |= UNINTERESTING;
/*
* Normally we haven't parsed the parent
* yet, so we won't have a parent of a parent
* here. However, it may turn out that we've
* reached this commit some other way (where it
* wasn't uninteresting), in which case we need
* to mark its parents recursively too..
*/
if (!commit->parents)
break;
for (l = commit->parents->next; l; l = l->next)
commit_list_insert(l->item, &parents);
commit = commit->parents->item;
}
}
}
static void add_pending_object_with_path(struct rev_info *revs,
struct object *obj,
const char *name, unsigned mode,
const char *path)
{
if (!obj)
return;
if (revs->no_walk && (obj->flags & UNINTERESTING))
revs->no_walk = 0;
if (revs->reflog_info && obj->type == OBJ_COMMIT) {
struct strbuf buf = STRBUF_INIT;
int len = interpret_branch_name(name, 0, &buf);
int st;
if (0 < len && name[len] && buf.len)
strbuf_addstr(&buf, name + len);
st = add_reflog_for_walk(revs->reflog_info,
(struct commit *)obj,
buf.buf[0] ? buf.buf: name);
strbuf_release(&buf);
if (st)
return;
}
add_object_array_with_path(obj, name, &revs->pending, mode, path);
}
static void add_pending_object_with_mode(struct rev_info *revs,
struct object *obj,
const char *name, unsigned mode)
{
add_pending_object_with_path(revs, obj, name, mode, NULL);
}
void add_pending_object(struct rev_info *revs,
struct object *obj, const char *name)
{
add_pending_object_with_mode(revs, obj, name, S_IFINVALID);
}
void add_head_to_pending(struct rev_info *revs)
{
unsigned char sha1[20];
struct object *obj;
if (get_sha1("HEAD", sha1))
return;
obj = parse_object(sha1);
if (!obj)
return;
add_pending_object(revs, obj, "HEAD");
}
static struct object *get_reference(struct rev_info *revs, const char *name,
const unsigned char *sha1,
unsigned int flags)
{
struct object *object;
object = parse_object(sha1);
if (!object) {
if (revs->ignore_missing)
return object;
die("bad object %s", name);
}
object->flags |= flags;
return object;
}
void add_pending_sha1(struct rev_info *revs, const char *name,
const unsigned char *sha1, unsigned int flags)
{
struct object *object = get_reference(revs, name, sha1, flags);
add_pending_object(revs, object, name);
}
static struct commit *handle_commit(struct rev_info *revs,
struct object_array_entry *entry)
{
struct object *object = entry->item;
const char *name = entry->name;
const char *path = entry->path;
unsigned int mode = entry->mode;
unsigned long flags = object->flags;
/*
* Tag object? Look what it points to..
*/
while (object->type == OBJ_TAG) {
struct tag *tag = (struct tag *) object;
if (revs->tag_objects && !(flags & UNINTERESTING))
add_pending_object(revs, object, tag->tag);
if (!tag->tagged)
die("bad tag");
object = parse_object(tag->tagged->oid.hash);
if (!object) {
if (flags & UNINTERESTING)
return NULL;
die("bad object %s", oid_to_hex(&tag->tagged->oid));
}
object->flags |= flags;
/*
* We'll handle the tagged object by looping or dropping
* through to the non-tag handlers below. Do not
* propagate path data from the tag's pending entry.
*/
path = NULL;
mode = 0;
}
/*
* Commit object? Just return it, we'll do all the complex
* reachability crud.
*/
if (object->type == OBJ_COMMIT) {
struct commit *commit = (struct commit *)object;
if (parse_commit(commit) < 0)
die("unable to parse commit %s", name);
if (flags & UNINTERESTING) {
mark_parents_uninteresting(commit);
revs->limited = 1;
}
if (revs->show_source && !commit->util)
commit->util = xstrdup(name);
return commit;
}
/*
* Tree object? Either mark it uninteresting, or add it
* to the list of objects to look at later..
*/
if (object->type == OBJ_TREE) {
struct tree *tree = (struct tree *)object;
if (!revs->tree_objects)
return NULL;
if (flags & UNINTERESTING) {
mark_tree_contents_uninteresting(tree);
return NULL;
}
add_pending_object_with_path(revs, object, name, mode, path);
return NULL;
}
/*
* Blob object? You know the drill by now..
*/
if (object->type == OBJ_BLOB) {
if (!revs->blob_objects)
return NULL;
if (flags & UNINTERESTING)
return NULL;
add_pending_object_with_path(revs, object, name, mode, path);
return NULL;
}
die("%s is unknown object", name);
}
static int everybody_uninteresting(struct commit_list *orig,
struct commit **interesting_cache)
{
struct commit_list *list = orig;
if (*interesting_cache) {
struct commit *commit = *interesting_cache;
if (!(commit->object.flags & UNINTERESTING))
return 0;
}
while (list) {
struct commit *commit = list->item;
list = list->next;
if (commit->object.flags & UNINTERESTING)
continue;
*interesting_cache = commit;
return 0;
}
return 1;
}
/*
* A definition of "relevant" commit that we can use to simplify limited graphs
* by eliminating side branches.
*
* A "relevant" commit is one that is !UNINTERESTING (ie we are including it
* in our list), or that is a specified BOTTOM commit. Then after computing
* a limited list, during processing we can generally ignore boundary merges
* coming from outside the graph, (ie from irrelevant parents), and treat
* those merges as if they were single-parent. TREESAME is defined to consider
* only relevant parents, if any. If we are TREESAME to our on-graph parents,
* we don't care if we were !TREESAME to non-graph parents.
*
* Treating bottom commits as relevant ensures that a limited graph's
* connection to the actual bottom commit is not viewed as a side branch, but
* treated as part of the graph. For example:
*
* ....Z...A---X---o---o---B
* . /
* W---Y
*
* When computing "A..B", the A-X connection is at least as important as
* Y-X, despite A being flagged UNINTERESTING.
*
* And when computing --ancestry-path "A..B", the A-X connection is more
* important than Y-X, despite both A and Y being flagged UNINTERESTING.
*/
static inline int relevant_commit(struct commit *commit)
{
return (commit->object.flags & (UNINTERESTING | BOTTOM)) != UNINTERESTING;
}
/*
* Return a single relevant commit from a parent list. If we are a TREESAME
* commit, and this selects one of our parents, then we can safely simplify to
* that parent.
*/
static struct commit *one_relevant_parent(const struct rev_info *revs,
struct commit_list *orig)
{
struct commit_list *list = orig;
struct commit *relevant = NULL;
if (!orig)
return NULL;
/*
* For 1-parent commits, or if first-parent-only, then return that
* first parent (even if not "relevant" by the above definition).
* TREESAME will have been set purely on that parent.
*/
if (revs->first_parent_only || !orig->next)
return orig->item;
/*
* For multi-parent commits, identify a sole relevant parent, if any.
* If we have only one relevant parent, then TREESAME will be set purely
* with regard to that parent, and we can simplify accordingly.
*
* If we have more than one relevant parent, or no relevant parents
* (and multiple irrelevant ones), then we can't select a parent here
* and return NULL.
*/
while (list) {
struct commit *commit = list->item;
list = list->next;
if (relevant_commit(commit)) {
if (relevant)
return NULL;
relevant = commit;
}
}
return relevant;
}
/*
* The goal is to get REV_TREE_NEW as the result only if the
* diff consists of all '+' (and no other changes), REV_TREE_OLD
* if the whole diff is removal of old data, and otherwise
* REV_TREE_DIFFERENT (of course if the trees are the same we
* want REV_TREE_SAME).
* That means that once we get to REV_TREE_DIFFERENT, we do not
* have to look any further.
*/
static int tree_difference = REV_TREE_SAME;
static void file_add_remove(struct diff_options *options,
int addremove, unsigned mode,
const unsigned char *sha1,
int sha1_valid,
const char *fullpath, unsigned dirty_submodule)
{
int diff = addremove == '+' ? REV_TREE_NEW : REV_TREE_OLD;
tree_difference |= diff;
if (tree_difference == REV_TREE_DIFFERENT)
DIFF_OPT_SET(options, HAS_CHANGES);
}
static void file_change(struct diff_options *options,
unsigned old_mode, unsigned new_mode,
const unsigned char *old_sha1,
const unsigned char *new_sha1,
int old_sha1_valid, int new_sha1_valid,
const char *fullpath,
unsigned old_dirty_submodule, unsigned new_dirty_submodule)
{
tree_difference = REV_TREE_DIFFERENT;
DIFF_OPT_SET(options, HAS_CHANGES);
}
static int rev_compare_tree(struct rev_info *revs,
struct commit *parent, struct commit *commit)
{
struct tree *t1 = parent->tree;
struct tree *t2 = commit->tree;
if (!t1)
return REV_TREE_NEW;
if (!t2)
return REV_TREE_OLD;
if (revs->simplify_by_decoration) {
/*
* If we are simplifying by decoration, then the commit
* is worth showing if it has a tag pointing at it.
*/
if (get_name_decoration(&commit->object))
return REV_TREE_DIFFERENT;
/*
* A commit that is not pointed by a tag is uninteresting
* if we are not limited by path. This means that you will
* see the usual "commits that touch the paths" plus any
* tagged commit by specifying both --simplify-by-decoration
* and pathspec.
*/
if (!revs->prune_data.nr)
return REV_TREE_SAME;
}
tree_difference = REV_TREE_SAME;
DIFF_OPT_CLR(&revs->pruning, HAS_CHANGES);
if (diff_tree_sha1(t1->object.oid.hash, t2->object.oid.hash, "",
&revs->pruning) < 0)
return REV_TREE_DIFFERENT;
return tree_difference;
}
static int rev_same_tree_as_empty(struct rev_info *revs, struct commit *commit)
{
int retval;
struct tree *t1 = commit->tree;
if (!t1)
return 0;
tree_difference = REV_TREE_SAME;
DIFF_OPT_CLR(&revs->pruning, HAS_CHANGES);
retval = diff_tree_sha1(NULL, t1->object.oid.hash, "", &revs->pruning);
return retval >= 0 && (tree_difference == REV_TREE_SAME);
}
struct treesame_state {
unsigned int nparents;
unsigned char treesame[FLEX_ARRAY];
};
static struct treesame_state *initialise_treesame(struct rev_info *revs, struct commit *commit)
{
unsigned n = commit_list_count(commit->parents);
struct treesame_state *st = xcalloc(1, sizeof(*st) + n);
st->nparents = n;
add_decoration(&revs->treesame, &commit->object, st);
return st;
}
/*
* Must be called immediately after removing the nth_parent from a commit's
* parent list, if we are maintaining the per-parent treesame[] decoration.
* This does not recalculate the master TREESAME flag - update_treesame()
* should be called to update it after a sequence of treesame[] modifications
* that may have affected it.
*/
static int compact_treesame(struct rev_info *revs, struct commit *commit, unsigned nth_parent)
{
struct treesame_state *st;
int old_same;
if (!commit->parents) {
/*
* Have just removed the only parent from a non-merge.
* Different handling, as we lack decoration.
*/
if (nth_parent != 0)
die("compact_treesame %u", nth_parent);
old_same = !!(commit->object.flags & TREESAME);
if (rev_same_tree_as_empty(revs, commit))
commit->object.flags |= TREESAME;
else
commit->object.flags &= ~TREESAME;
return old_same;
}
st = lookup_decoration(&revs->treesame, &commit->object);
if (!st || nth_parent >= st->nparents)
die("compact_treesame %u", nth_parent);
old_same = st->treesame[nth_parent];
memmove(st->treesame + nth_parent,
st->treesame + nth_parent + 1,
st->nparents - nth_parent - 1);
/*
* If we've just become a non-merge commit, update TREESAME
* immediately, and remove the no-longer-needed decoration.
* If still a merge, defer update until update_treesame().
*/
if (--st->nparents == 1) {
if (commit->parents->next)
die("compact_treesame parents mismatch");
if (st->treesame[0] && revs->dense)
commit->object.flags |= TREESAME;
else
commit->object.flags &= ~TREESAME;
free(add_decoration(&revs->treesame, &commit->object, NULL));
}
return old_same;
}
static unsigned update_treesame(struct rev_info *revs, struct commit *commit)
{
if (commit->parents && commit->parents->next) {
unsigned n;
struct treesame_state *st;
struct commit_list *p;
unsigned relevant_parents;
unsigned relevant_change, irrelevant_change;
st = lookup_decoration(&revs->treesame, &commit->object);
if (!st)
die("update_treesame %s", oid_to_hex(&commit->object.oid));
relevant_parents = 0;
relevant_change = irrelevant_change = 0;
for (p = commit->parents, n = 0; p; n++, p = p->next) {
if (relevant_commit(p->item)) {
relevant_change |= !st->treesame[n];
relevant_parents++;
} else
irrelevant_change |= !st->treesame[n];
}
if (relevant_parents ? relevant_change : irrelevant_change)
commit->object.flags &= ~TREESAME;
else
commit->object.flags |= TREESAME;
}
return commit->object.flags & TREESAME;
}
static inline int limiting_can_increase_treesame(const struct rev_info *revs)
{
/*
* TREESAME is irrelevant unless prune && dense;
* if simplify_history is set, we can't have a mixture of TREESAME and
* !TREESAME INTERESTING parents (and we don't have treesame[]
* decoration anyway);
* if first_parent_only is set, then the TREESAME flag is locked
* against the first parent (and again we lack treesame[] decoration).
*/
return revs->prune && revs->dense &&
!revs->simplify_history &&
!revs->first_parent_only;
}
static void try_to_simplify_commit(struct rev_info *revs, struct commit *commit)
{
struct commit_list **pp, *parent;
struct treesame_state *ts = NULL;
int relevant_change = 0, irrelevant_change = 0;
int relevant_parents, nth_parent;
/*
* If we don't do pruning, everything is interesting
*/
if (!revs->prune)
return;
if (!commit->tree)
return;
if (!commit->parents) {
if (rev_same_tree_as_empty(revs, commit))
commit->object.flags |= TREESAME;
return;
}
/*
* Normal non-merge commit? If we don't want to make the
* history dense, we consider it always to be a change..
*/
if (!revs->dense && !commit->parents->next)
return;
for (pp = &commit->parents, nth_parent = 0, relevant_parents = 0;
(parent = *pp) != NULL;
pp = &parent->next, nth_parent++) {
struct commit *p = parent->item;
if (relevant_commit(p))
relevant_parents++;
if (nth_parent == 1) {
/*
* This our second loop iteration - so we now know
* we're dealing with a merge.
*
* Do not compare with later parents when we care only about
* the first parent chain, in order to avoid derailing the
* traversal to follow a side branch that brought everything
* in the path we are limited to by the pathspec.
*/
if (revs->first_parent_only)
break;
/*
* If this will remain a potentially-simplifiable
* merge, remember per-parent treesame if needed.
* Initialise the array with the comparison from our
* first iteration.
*/
if (revs->treesame.name &&
!revs->simplify_history &&
!(commit->object.flags & UNINTERESTING)) {
ts = initialise_treesame(revs, commit);
if (!(irrelevant_change || relevant_change))
ts->treesame[0] = 1;
}
}
if (parse_commit(p) < 0)
die("cannot simplify commit %s (because of %s)",
oid_to_hex(&commit->object.oid),
oid_to_hex(&p->object.oid));
switch (rev_compare_tree(revs, p, commit)) {
case REV_TREE_SAME:
if (!revs->simplify_history || !relevant_commit(p)) {
/* Even if a merge with an uninteresting
* side branch brought the entire change
* we are interested in, we do not want
* to lose the other branches of this
* merge, so we just keep going.
*/
if (ts)
ts->treesame[nth_parent] = 1;
continue;
}
parent->next = NULL;
commit->parents = parent;
commit->object.flags |= TREESAME;
return;
case REV_TREE_NEW:
if (revs->remove_empty_trees &&
rev_same_tree_as_empty(revs, p)) {
/* We are adding all the specified
* paths from this parent, so the
* history beyond this parent is not
* interesting. Remove its parents
* (they are grandparents for us).
* IOW, we pretend this parent is a
* "root" commit.
*/
if (parse_commit(p) < 0)
die("cannot simplify commit %s (invalid %s)",
oid_to_hex(&commit->object.oid),
oid_to_hex(&p->object.oid));
p->parents = NULL;
}
/* fallthrough */
case REV_TREE_OLD:
case REV_TREE_DIFFERENT:
if (relevant_commit(p))
relevant_change = 1;
else
irrelevant_change = 1;
continue;
}
die("bad tree compare for commit %s", oid_to_hex(&commit->object.oid));
}
/*
* TREESAME is straightforward for single-parent commits. For merge
* commits, it is most useful to define it so that "irrelevant"
* parents cannot make us !TREESAME - if we have any relevant
* parents, then we only consider TREESAMEness with respect to them,
* allowing irrelevant merges from uninteresting branches to be
* simplified away. Only if we have only irrelevant parents do we
* base TREESAME on them. Note that this logic is replicated in
* update_treesame, which should be kept in sync.
*/
if (relevant_parents ? !relevant_change : !irrelevant_change)
commit->object.flags |= TREESAME;
}
static void commit_list_insert_by_date_cached(struct commit *p, struct commit_list **head,
struct commit_list *cached_base, struct commit_list **cache)
{
struct commit_list *new_entry;
if (cached_base && p->date < cached_base->item->date)
new_entry = commit_list_insert_by_date(p, &cached_base->next);
else
new_entry = commit_list_insert_by_date(p, head);
if (cache && (!*cache || p->date < (*cache)->item->date))
*cache = new_entry;
}
static int add_parents_to_list(struct rev_info *revs, struct commit *commit,
struct commit_list **list, struct commit_list **cache_ptr)
{
struct commit_list *parent = commit->parents;
unsigned left_flag;
struct commit_list *cached_base = cache_ptr ? *cache_ptr : NULL;
if (commit->object.flags & ADDED)
return 0;
commit->object.flags |= ADDED;
if (revs->include_check &&
!revs->include_check(commit, revs->include_check_data))
return 0;
/*
* If the commit is uninteresting, don't try to
* prune parents - we want the maximal uninteresting
* set.
*
* Normally we haven't parsed the parent
* yet, so we won't have a parent of a parent
* here. However, it may turn out that we've
* reached this commit some other way (where it
* wasn't uninteresting), in which case we need
* to mark its parents recursively too..
*/
if (commit->object.flags & UNINTERESTING) {
while (parent) {
struct commit *p = parent->item;
parent = parent->next;
if (p)
p->object.flags |= UNINTERESTING;
if (parse_commit_gently(p, 1) < 0)
continue;
if (p->parents)
mark_parents_uninteresting(p);
if (p->object.flags & SEEN)
continue;
p->object.flags |= SEEN;
commit_list_insert_by_date_cached(p, list, cached_base, cache_ptr);
}
return 0;
}
/*
* Ok, the commit wasn't uninteresting. Try to
* simplify the commit history and find the parent
* that has no differences in the path set if one exists.
*/
try_to_simplify_commit(revs, commit);
if (revs->no_walk)
return 0;
left_flag = (commit->object.flags & SYMMETRIC_LEFT);
for (parent = commit->parents; parent; parent = parent->next) {
struct commit *p = parent->item;
if (parse_commit_gently(p, revs->ignore_missing_links) < 0)
return -1;
if (revs->show_source && !p->util)
p->util = commit->util;
p->object.flags |= left_flag;
if (!(p->object.flags & SEEN)) {
p->object.flags |= SEEN;
commit_list_insert_by_date_cached(p, list, cached_base, cache_ptr);
}
if (revs->first_parent_only)
break;
}
return 0;
}
static void cherry_pick_list(struct commit_list *list, struct rev_info *revs)
{
struct commit_list *p;
int left_count = 0, right_count = 0;
int left_first;
struct patch_ids ids;
unsigned cherry_flag;
/* First count the commits on the left and on the right */
for (p = list; p; p = p->next) {
struct commit *commit = p->item;
unsigned flags = commit->object.flags;
if (flags & BOUNDARY)
;
else if (flags & SYMMETRIC_LEFT)
left_count++;
else
right_count++;
}
if (!left_count || !right_count)
return;
left_first = left_count < right_count;
init_patch_ids(&ids);
ids.diffopts.pathspec = revs->diffopt.pathspec;
/* Compute patch-ids for one side */
for (p = list; p; p = p->next) {
struct commit *commit = p->item;
unsigned flags = commit->object.flags;
if (flags & BOUNDARY)
continue;
/*
* If we have fewer left, left_first is set and we omit
* commits on the right branch in this loop. If we have
* fewer right, we skip the left ones.
*/
if (left_first != !!(flags & SYMMETRIC_LEFT))
continue;
commit->util = add_commit_patch_id(commit, &ids);
}
/* either cherry_mark or cherry_pick are true */
cherry_flag = revs->cherry_mark ? PATCHSAME : SHOWN;
/* Check the other side */
for (p = list; p; p = p->next) {
struct commit *commit = p->item;
struct patch_id *id;
unsigned flags = commit->object.flags;
if (flags & BOUNDARY)
continue;
/*
* If we have fewer left, left_first is set and we omit
* commits on the left branch in this loop.
*/
if (left_first == !!(flags & SYMMETRIC_LEFT))
continue;
/*
* Have we seen the same patch id?
*/
id = has_commit_patch_id(commit, &ids);
if (!id)
continue;
id->seen = 1;
commit->object.flags |= cherry_flag;
}
/* Now check the original side for seen ones */
for (p = list; p; p = p->next) {
struct commit *commit = p->item;
struct patch_id *ent;
ent = commit->util;
if (!ent)
continue;
if (ent->seen)
commit->object.flags |= cherry_flag;
commit->util = NULL;
}
free_patch_ids(&ids);
}
/* How many extra uninteresting commits we want to see.. */
#define SLOP 5
static int still_interesting(struct commit_list *src, unsigned long date, int slop,
struct commit **interesting_cache)
{
/*
* No source list at all? We're definitely done..
*/
if (!src)
return 0;
/*
* Does the destination list contain entries with a date
* before the source list? Definitely _not_ done.
*/
if (date <= src->item->date)
return SLOP;
/*
* Does the source list still have interesting commits in
* it? Definitely not done..
*/
if (!everybody_uninteresting(src, interesting_cache))
return SLOP;
/* Ok, we're closing in.. */
return slop-1;
}
/*
* "rev-list --ancestry-path A..B" computes commits that are ancestors
* of B but not ancestors of A but further limits the result to those
* that are descendants of A. This takes the list of bottom commits and
* the result of "A..B" without --ancestry-path, and limits the latter
* further to the ones that can reach one of the commits in "bottom".
*/
static void limit_to_ancestry(struct commit_list *bottom, struct commit_list *list)
{
struct commit_list *p;
struct commit_list *rlist = NULL;
int made_progress;
/*
* Reverse the list so that it will be likely that we would
* process parents before children.
*/
for (p = list; p; p = p->next)
commit_list_insert(p->item, &rlist);
for (p = bottom; p; p = p->next)
p->item->object.flags |= TMP_MARK;
/*
* Mark the ones that can reach bottom commits in "list",
* in a bottom-up fashion.
*/
do {
made_progress = 0;
for (p = rlist; p; p = p->next) {
struct commit *c = p->item;
struct commit_list *parents;
if (c->object.flags & (TMP_MARK | UNINTERESTING))
continue;
for (parents = c->parents;
parents;
parents = parents->next) {
if (!(parents->item->object.flags & TMP_MARK))
continue;
c->object.flags |= TMP_MARK;
made_progress = 1;
break;
}
}
} while (made_progress);
/*
* NEEDSWORK: decide if we want to remove parents that are
* not marked with TMP_MARK from commit->parents for commits
* in the resulting list. We may not want to do that, though.
*/
/*
* The ones that are not marked with TMP_MARK are uninteresting
*/
for (p = list; p; p = p->next) {
struct commit *c = p->item;
if (c->object.flags & TMP_MARK)
continue;
c->object.flags |= UNINTERESTING;
}
/* We are done with the TMP_MARK */
for (p = list; p; p = p->next)
p->item->object.flags &= ~TMP_MARK;
for (p = bottom; p; p = p->next)
p->item->object.flags &= ~TMP_MARK;
free_commit_list(rlist);
}
/*
* Before walking the history, keep the set of "negative" refs the
* caller has asked to exclude.
*
* This is used to compute "rev-list --ancestry-path A..B", as we need
* to filter the result of "A..B" further to the ones that can actually
* reach A.
*/
static struct commit_list *collect_bottom_commits(struct commit_list *list)
{
struct commit_list *elem, *bottom = NULL;
for (elem = list; elem; elem = elem->next)
if (elem->item->object.flags & BOTTOM)
commit_list_insert(elem->item, &bottom);
return bottom;
}
/* Assumes either left_only or right_only is set */
static void limit_left_right(struct commit_list *list, struct rev_info *revs)
{
struct commit_list *p;
for (p = list; p; p = p->next) {
struct commit *commit = p->item;
if (revs->right_only) {
if (commit->object.flags & SYMMETRIC_LEFT)
commit->object.flags |= SHOWN;
} else /* revs->left_only is set */
if (!(commit->object.flags & SYMMETRIC_LEFT))
commit->object.flags |= SHOWN;
}
}
static int limit_list(struct rev_info *revs)
{
int slop = SLOP;
unsigned long date = ~0ul;
struct commit_list *list = revs->commits;
struct commit_list *newlist = NULL;
struct commit_list **p = &newlist;
struct commit_list *bottom = NULL;
struct commit *interesting_cache = NULL;
if (revs->ancestry_path) {
bottom = collect_bottom_commits(list);
if (!bottom)
die("--ancestry-path given but there are no bottom commits");
}
while (list) {
struct commit *commit = pop_commit(&list);
struct object *obj = &commit->object;
show_early_output_fn_t show;
if (commit == interesting_cache)
interesting_cache = NULL;
if (revs->max_age != -1 && (commit->date < revs->max_age))
obj->flags |= UNINTERESTING;
if (add_parents_to_list(revs, commit, &list, NULL) < 0)
return -1;
if (obj->flags & UNINTERESTING) {
mark_parents_uninteresting(commit);
if (revs->show_all)
p = &commit_list_insert(commit, p)->next;
slop = still_interesting(list, date, slop, &interesting_cache);
if (slop)
continue;
/* If showing all, add the whole pending list to the end */
if (revs->show_all)
*p = list;
break;
}
if (revs->min_age != -1 && (commit->date > revs->min_age))
continue;
date = commit->date;
p = &commit_list_insert(commit, p)->next;
show = show_early_output;
if (!show)
continue;
show(revs, newlist);
show_early_output = NULL;
}
if (revs->cherry_pick || revs->cherry_mark)
cherry_pick_list(newlist, revs);
if (revs->left_only || revs->right_only)
limit_left_right(newlist, revs);
if (bottom) {
limit_to_ancestry(bottom, newlist);
free_commit_list(bottom);
}
/*
* Check if any commits have become TREESAME by some of their parents
* becoming UNINTERESTING.
*/
if (limiting_can_increase_treesame(revs))
for (list = newlist; list; list = list->next) {
struct commit *c = list->item;
if (c->object.flags & (UNINTERESTING | TREESAME))
continue;
update_treesame(revs, c);
}
revs->commits = newlist;
return 0;
}
/*
* Add an entry to refs->cmdline with the specified information.
* *name is copied.
*/
static void add_rev_cmdline(struct rev_info *revs,
struct object *item,
const char *name,
int whence,
unsigned flags)
{
struct rev_cmdline_info *info = &revs->cmdline;
int nr = info->nr;
ALLOC_GROW(info->rev, nr + 1, info->alloc);
info->rev[nr].item = item;
info->rev[nr].name = xstrdup(name);
info->rev[nr].whence = whence;
info->rev[nr].flags = flags;
info->nr++;
}
static void add_rev_cmdline_list(struct rev_info *revs,
struct commit_list *commit_list,
int whence,
unsigned flags)
{
while (commit_list) {
struct object *object = &commit_list->item->object;
add_rev_cmdline(revs, object, oid_to_hex(&object->oid),
whence, flags);
commit_list = commit_list->next;
}
}
struct all_refs_cb {
int all_flags;
int warned_bad_reflog;
struct rev_info *all_revs;
const char *name_for_errormsg;
};
int ref_excluded(struct string_list *ref_excludes, const char *path)
{
struct string_list_item *item;
if (!ref_excludes)
return 0;
for_each_string_list_item(item, ref_excludes) {
if (!wildmatch(item->string, path, 0, NULL))
return 1;
}
return 0;
}
static int handle_one_ref(const char *path, const struct object_id *oid,
int flag, void *cb_data)
{
struct all_refs_cb *cb = cb_data;
struct object *object;
if (ref_excluded(cb->all_revs->ref_excludes, path))
return 0;
object = get_reference(cb->all_revs, path, oid->hash, cb->all_flags);
add_rev_cmdline(cb->all_revs, object, path, REV_CMD_REF, cb->all_flags);
add_pending_sha1(cb->all_revs, path, oid->hash, cb->all_flags);
return 0;
}
static void init_all_refs_cb(struct all_refs_cb *cb, struct rev_info *revs,
unsigned flags)
{
cb->all_revs = revs;
cb->all_flags = flags;
}
void clear_ref_exclusion(struct string_list **ref_excludes_p)
{
if (*ref_excludes_p) {
string_list_clear(*ref_excludes_p, 0);
free(*ref_excludes_p);
}
*ref_excludes_p = NULL;
}
void add_ref_exclusion(struct string_list **ref_excludes_p, const char *exclude)
{
if (!*ref_excludes_p) {
*ref_excludes_p = xcalloc(1, sizeof(**ref_excludes_p));
(*ref_excludes_p)->strdup_strings = 1;
}
string_list_append(*ref_excludes_p, exclude);
}
static void handle_refs(const char *submodule, struct rev_info *revs, unsigned flags,
int (*for_each)(const char *, each_ref_fn, void *))
{
struct all_refs_cb cb;
init_all_refs_cb(&cb, revs, flags);
for_each(submodule, handle_one_ref, &cb);
}
static void handle_one_reflog_commit(unsigned char *sha1, void *cb_data)
{
struct all_refs_cb *cb = cb_data;
if (!is_null_sha1(sha1)) {
struct object *o = parse_object(sha1);
if (o) {
o->flags |= cb->all_flags;
/* ??? CMDLINEFLAGS ??? */
add_pending_object(cb->all_revs, o, "");
}
else if (!cb->warned_bad_reflog) {
warning("reflog of '%s' references pruned commits",
cb->name_for_errormsg);
cb->warned_bad_reflog = 1;
}
}
}
static int handle_one_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
const char *email, unsigned long timestamp, int tz,
const char *message, void *cb_data)
{
handle_one_reflog_commit(osha1, cb_data);
handle_one_reflog_commit(nsha1, cb_data);
return 0;
}
static int handle_one_reflog(const char *path, const struct object_id *oid,
int flag, void *cb_data)
{
struct all_refs_cb *cb = cb_data;
cb->warned_bad_reflog = 0;
cb->name_for_errormsg = path;
for_each_reflog_ent(path, handle_one_reflog_ent, cb_data);
return 0;
}
void add_reflogs_to_pending(struct rev_info *revs, unsigned flags)
{
struct all_refs_cb cb;
cb.all_revs = revs;
cb.all_flags = flags;
for_each_reflog(handle_one_reflog, &cb);
}
static void add_cache_tree(struct cache_tree *it, struct rev_info *revs,
struct strbuf *path)
{
size_t baselen = path->len;
int i;
if (it->entry_count >= 0) {
struct tree *tree = lookup_tree(it->sha1);
add_pending_object_with_path(revs, &tree->object, "",
040000, path->buf);
}
for (i = 0; i < it->subtree_nr; i++) {
struct cache_tree_sub *sub = it->down[i];
strbuf_addf(path, "%s%s", baselen ? "/" : "", sub->name);
add_cache_tree(sub->cache_tree, revs, path);
strbuf_setlen(path, baselen);
}
}
void add_index_objects_to_pending(struct rev_info *revs, unsigned flags)
{
int i;
read_cache();
for (i = 0; i < active_nr; i++) {
struct cache_entry *ce = active_cache[i];
struct blob *blob;
if (S_ISGITLINK(ce->ce_mode))
continue;
blob = lookup_blob(ce->sha1);
if (!blob)
die("unable to add index blob to traversal");
add_pending_object_with_path(revs, &blob->object, "",
ce->ce_mode, ce->name);
}
if (active_cache_tree) {
struct strbuf path = STRBUF_INIT;
add_cache_tree(active_cache_tree, revs, &path);
strbuf_release(&path);
}
}
static int add_parents_only(struct rev_info *revs, const char *arg_, int flags)
{
unsigned char sha1[20];
struct object *it;
struct commit *commit;
struct commit_list *parents;
const char *arg = arg_;
if (*arg == '^') {
flags ^= UNINTERESTING | BOTTOM;
arg++;
}
if (get_sha1_committish(arg, sha1))
return 0;
while (1) {
it = get_reference(revs, arg, sha1, 0);
if (!it && revs->ignore_missing)
return 0;
if (it->type != OBJ_TAG)
break;
if (!((struct tag*)it)->tagged)
return 0;
hashcpy(sha1, ((struct tag*)it)->tagged->oid.hash);
}
if (it->type != OBJ_COMMIT)
return 0;
commit = (struct commit *)it;
for (parents = commit->parents; parents; parents = parents->next) {
it = &parents->item->object;
it->flags |= flags;
add_rev_cmdline(revs, it, arg_, REV_CMD_PARENTS_ONLY, flags);
add_pending_object(revs, it, arg);
}
return 1;
}
void init_revisions(struct rev_info *revs, const char *prefix)
{
memset(revs, 0, sizeof(*revs));
revs->abbrev = DEFAULT_ABBREV;
revs->ignore_merges = 1;
revs->simplify_history = 1;
DIFF_OPT_SET(&revs->pruning, RECURSIVE);
DIFF_OPT_SET(&revs->pruning, QUICK);
revs->pruning.add_remove = file_add_remove;
revs->pruning.change = file_change;
revs->sort_order = REV_SORT_IN_GRAPH_ORDER;
revs->dense = 1;
revs->prefix = prefix;
revs->max_age = -1;
revs->min_age = -1;
revs->skip_count = -1;
revs->max_count = -1;
revs->max_parents = -1;
revs->commit_format = CMIT_FMT_DEFAULT;
init_grep_defaults();
grep_init(&revs->grep_filter, prefix);
revs->grep_filter.status_only = 1;
revs->grep_filter.regflags = REG_NEWLINE;
diff_setup(&revs->diffopt);
if (prefix && !revs->diffopt.prefix) {
revs->diffopt.prefix = prefix;
revs->diffopt.prefix_length = strlen(prefix);
}
revs->notes_opt.use_default_notes = -1;
}
static void add_pending_commit_list(struct rev_info *revs,
struct commit_list *commit_list,
unsigned int flags)
{
while (commit_list) {
struct object *object = &commit_list->item->object;
object->flags |= flags;
add_pending_object(revs, object, oid_to_hex(&object->oid));
commit_list = commit_list->next;
}
}
static void prepare_show_merge(struct rev_info *revs)
{
struct commit_list *bases;
struct commit *head, *other;
unsigned char sha1[20];
const char **prune = NULL;
int i, prune_num = 1; /* counting terminating NULL */
if (get_sha1("HEAD", sha1))
die("--merge without HEAD?");
head = lookup_commit_or_die(sha1, "HEAD");
if (get_sha1("MERGE_HEAD", sha1))
die("--merge without MERGE_HEAD?");
other = lookup_commit_or_die(sha1, "MERGE_HEAD");
add_pending_object(revs, &head->object, "HEAD");
add_pending_object(revs, &other->object, "MERGE_HEAD");
bases = get_merge_bases(head, other);
add_rev_cmdline_list(revs, bases, REV_CMD_MERGE_BASE, UNINTERESTING | BOTTOM);
add_pending_commit_list(revs, bases, UNINTERESTING | BOTTOM);
free_commit_list(bases);
head->object.flags |= SYMMETRIC_LEFT;
if (!active_nr)
read_cache();
for (i = 0; i < active_nr; i++) {
const struct cache_entry *ce = active_cache[i];
if (!ce_stage(ce))
continue;
if (ce_path_match(ce, &revs->prune_data, NULL)) {
prune_num++;
REALLOC_ARRAY(prune, prune_num);
prune[prune_num-2] = ce->name;
prune[prune_num-1] = NULL;
}
while ((i+1 < active_nr) &&
ce_same_name(ce, active_cache[i+1]))
i++;
}
free_pathspec(&revs->prune_data);
parse_pathspec(&revs->prune_data, PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
PATHSPEC_PREFER_FULL | PATHSPEC_LITERAL_PATH, "", prune);
revs->limited = 1;
}
int handle_revision_arg(const char *arg_, struct rev_info *revs, int flags, unsigned revarg_opt)
{
struct object_context oc;
char *dotdot;
struct object *object;
unsigned char sha1[20];
int local_flags;
const char *arg = arg_;
int cant_be_filename = revarg_opt & REVARG_CANNOT_BE_FILENAME;
unsigned get_sha1_flags = 0;
flags = flags & UNINTERESTING ? flags | BOTTOM : flags & ~BOTTOM;
dotdot = strstr(arg, "..");
if (dotdot) {
unsigned char from_sha1[20];
const char *next = dotdot + 2;
const char *this = arg;
int symmetric = *next == '.';
unsigned int flags_exclude = flags ^ (UNINTERESTING | BOTTOM);
static const char head_by_default[] = "HEAD";
unsigned int a_flags;
*dotdot = 0;
next += symmetric;
if (!*next)
next = head_by_default;
if (dotdot == arg)
this = head_by_default;
if (this == head_by_default && next == head_by_default &&
!symmetric) {
/*
* Just ".."? That is not a range but the
* pathspec for the parent directory.
*/
if (!cant_be_filename) {
*dotdot = '.';
return -1;
}
}
if (!get_sha1_committish(this, from_sha1) &&
!get_sha1_committish(next, sha1)) {
struct object *a_obj, *b_obj;
if (!cant_be_filename) {
*dotdot = '.';
verify_non_filename(revs->prefix, arg);
}
a_obj = parse_object(from_sha1);
b_obj = parse_object(sha1);
if (!a_obj || !b_obj) {
missing:
if (revs->ignore_missing)
return 0;
die(symmetric
? "Invalid symmetric difference expression %s"
: "Invalid revision range %s", arg);
}
if (!symmetric) {
/* just A..B */
a_flags = flags_exclude;
} else {
/* A...B -- find merge bases between the two */
struct commit *a, *b;
struct commit_list *exclude;
a = (a_obj->type == OBJ_COMMIT
? (struct commit *)a_obj
: lookup_commit_reference(a_obj->oid.hash));
b = (b_obj->type == OBJ_COMMIT
? (struct commit *)b_obj
: lookup_commit_reference(b_obj->oid.hash));
if (!a || !b)
goto missing;
exclude = get_merge_bases(a, b);
add_rev_cmdline_list(revs, exclude,
REV_CMD_MERGE_BASE,
flags_exclude);
add_pending_commit_list(revs, exclude,
flags_exclude);
free_commit_list(exclude);
a_flags = flags | SYMMETRIC_LEFT;
}
a_obj->flags |= a_flags;
b_obj->flags |= flags;
add_rev_cmdline(revs, a_obj, this,
REV_CMD_LEFT, a_flags);
add_rev_cmdline(revs, b_obj, next,
REV_CMD_RIGHT, flags);
add_pending_object(revs, a_obj, this);
add_pending_object(revs, b_obj, next);
return 0;
}
*dotdot = '.';
}
dotdot = strstr(arg, "^@");
if (dotdot && !dotdot[2]) {
*dotdot = 0;
if (add_parents_only(revs, arg, flags))
return 0;
*dotdot = '^';
}
dotdot = strstr(arg, "^!");
if (dotdot && !dotdot[2]) {
*dotdot = 0;
if (!add_parents_only(revs, arg, flags ^ (UNINTERESTING | BOTTOM)))
*dotdot = '^';
}
local_flags = 0;
if (*arg == '^') {
local_flags = UNINTERESTING | BOTTOM;
arg++;
}
if (revarg_opt & REVARG_COMMITTISH)
get_sha1_flags = GET_SHA1_COMMITTISH;
if (get_sha1_with_context(arg, get_sha1_flags, sha1, &oc))
return revs->ignore_missing ? 0 : -1;
if (!cant_be_filename)
verify_non_filename(revs->prefix, arg);
object = get_reference(revs, arg, sha1, flags ^ local_flags);
add_rev_cmdline(revs, object, arg_, REV_CMD_REV, flags ^ local_flags);
add_pending_object_with_mode(revs, object, arg, oc.mode);
return 0;
}
struct cmdline_pathspec {
int alloc;
int nr;
const char **path;
};
static void append_prune_data(struct cmdline_pathspec *prune, const char **av)
{
while (*av) {
ALLOC_GROW(prune->path, prune->nr + 1, prune->alloc);
prune->path[prune->nr++] = *(av++);
}
}
static void read_pathspec_from_stdin(struct rev_info *revs, struct strbuf *sb,
struct cmdline_pathspec *prune)
{
while (strbuf_getline(sb, stdin) != EOF) {
ALLOC_GROW(prune->path, prune->nr + 1, prune->alloc);
prune->path[prune->nr++] = xstrdup(sb->buf);
}
}
static void read_revisions_from_stdin(struct rev_info *revs,
struct cmdline_pathspec *prune)
{
struct strbuf sb;
int seen_dashdash = 0;
int save_warning;
save_warning = warn_on_object_refname_ambiguity;
warn_on_object_refname_ambiguity = 0;
strbuf_init(&sb, 1000);
while (strbuf_getline(&sb, stdin) != EOF) {
int len = sb.len;
if (!len)
break;
if (sb.buf[0] == '-') {
if (len == 2 && sb.buf[1] == '-') {
seen_dashdash = 1;
break;
}
die("options not supported in --stdin mode");
}
if (handle_revision_arg(sb.buf, revs, 0,
REVARG_CANNOT_BE_FILENAME))
die("bad revision '%s'", sb.buf);
}
if (seen_dashdash)
read_pathspec_from_stdin(revs, &sb, prune);
strbuf_release(&sb);
warn_on_object_refname_ambiguity = save_warning;
}
static void add_grep(struct rev_info *revs, const char *ptn, enum grep_pat_token what)
{
append_grep_pattern(&revs->grep_filter, ptn, "command line", 0, what);
}
static void add_header_grep(struct rev_info *revs, enum grep_header_field field, const char *pattern)
{
append_header_grep_pattern(&revs->grep_filter, field, pattern);
}
static void add_message_grep(struct rev_info *revs, const char *pattern)
{
add_grep(revs, pattern, GREP_PATTERN_BODY);
}
static int handle_revision_opt(struct rev_info *revs, int argc, const char **argv,
int *unkc, const char **unkv)
{
const char *arg = argv[0];
const char *optarg;
int argcount;
/* pseudo revision arguments */
if (!strcmp(arg, "--all") || !strcmp(arg, "--branches") ||
!strcmp(arg, "--tags") || !strcmp(arg, "--remotes") ||
!strcmp(arg, "--reflog") || !strcmp(arg, "--not") ||
!strcmp(arg, "--no-walk") || !strcmp(arg, "--do-walk") ||
!strcmp(arg, "--bisect") || starts_with(arg, "--glob=") ||
!strcmp(arg, "--indexed-objects") ||
starts_with(arg, "--exclude=") ||
starts_with(arg, "--branches=") || starts_with(arg, "--tags=") ||
starts_with(arg, "--remotes=") || starts_with(arg, "--no-walk="))
{
unkv[(*unkc)++] = arg;
return 1;
}
if ((argcount = parse_long_opt("max-count", argv, &optarg))) {
revs->max_count = atoi(optarg);
revs->no_walk = 0;
return argcount;
} else if ((argcount = parse_long_opt("skip", argv, &optarg))) {
revs->skip_count = atoi(optarg);
return argcount;
} else if ((*arg == '-') && isdigit(arg[1])) {
/* accept -<digit>, like traditional "head" */
if (strtol_i(arg + 1, 10, &revs->max_count) < 0 ||
revs->max_count < 0)
die("'%s': not a non-negative integer", arg + 1);
revs->no_walk = 0;
} else if (!strcmp(arg, "-n")) {
if (argc <= 1)
return error("-n requires an argument");
revs->max_count = atoi(argv[1]);
revs->no_walk = 0;
return 2;
} else if (starts_with(arg, "-n")) {
revs->max_count = atoi(arg + 2);
revs->no_walk = 0;
} else if ((argcount = parse_long_opt("max-age", argv, &optarg))) {
revs->max_age = atoi(optarg);
return argcount;
} else if ((argcount = parse_long_opt("since", argv, &optarg))) {
revs->max_age = approxidate(optarg);
return argcount;
} else if ((argcount = parse_long_opt("after", argv, &optarg))) {
revs->max_age = approxidate(optarg);
return argcount;
} else if ((argcount = parse_long_opt("min-age", argv, &optarg))) {
revs->min_age = atoi(optarg);
return argcount;
} else if ((argcount = parse_long_opt("before", argv, &optarg))) {
revs->min_age = approxidate(optarg);
return argcount;
} else if ((argcount = parse_long_opt("until", argv, &optarg))) {
revs->min_age = approxidate(optarg);
return argcount;
} else if (!strcmp(arg, "--first-parent")) {
revs->first_parent_only = 1;
} else if (!strcmp(arg, "--ancestry-path")) {
revs->ancestry_path = 1;
revs->simplify_history = 0;
revs->limited = 1;
} else if (!strcmp(arg, "-g") || !strcmp(arg, "--walk-reflogs")) {
init_reflog_walk(&revs->reflog_info);
} else if (!strcmp(arg, "--default")) {
if (argc <= 1)
return error("bad --default argument");
revs->def = argv[1];
return 2;
} else if (!strcmp(arg, "--merge")) {
revs->show_merge = 1;
} else if (!strcmp(arg, "--topo-order")) {
revs->sort_order = REV_SORT_IN_GRAPH_ORDER;
revs->topo_order = 1;
} else if (!strcmp(arg, "--simplify-merges")) {
revs->simplify_merges = 1;
revs->topo_order = 1;
revs->rewrite_parents = 1;
revs->simplify_history = 0;
revs->limited = 1;
} else if (!strcmp(arg, "--simplify-by-decoration")) {
revs->simplify_merges = 1;
revs->topo_order = 1;
revs->rewrite_parents = 1;
revs->simplify_history = 0;
revs->simplify_by_decoration = 1;
revs->limited = 1;
revs->prune = 1;
load_ref_decorations(DECORATE_SHORT_REFS);
} else if (!strcmp(arg, "--date-order")) {
revs->sort_order = REV_SORT_BY_COMMIT_DATE;
revs->topo_order = 1;
} else if (!strcmp(arg, "--author-date-order")) {
revs->sort_order = REV_SORT_BY_AUTHOR_DATE;
revs->topo_order = 1;
} else if (starts_with(arg, "--early-output")) {
int count = 100;
switch (arg[14]) {
case '=':
count = atoi(arg+15);
/* Fallthrough */
case 0:
revs->topo_order = 1;
revs->early_output = count;
}
} else if (!strcmp(arg, "--parents")) {
revs->rewrite_parents = 1;
revs->print_parents = 1;
} else if (!strcmp(arg, "--dense")) {
revs->dense = 1;
} else if (!strcmp(arg, "--sparse")) {
revs->dense = 0;
} else if (!strcmp(arg, "--show-all")) {
revs->show_all = 1;
} else if (!strcmp(arg, "--remove-empty")) {
revs->remove_empty_trees = 1;
} else if (!strcmp(arg, "--merges")) {
revs->min_parents = 2;
} else if (!strcmp(arg, "--no-merges")) {
revs->max_parents = 1;
} else if (starts_with(arg, "--min-parents=")) {
revs->min_parents = atoi(arg+14);
} else if (starts_with(arg, "--no-min-parents")) {
revs->min_parents = 0;
} else if (starts_with(arg, "--max-parents=")) {
revs->max_parents = atoi(arg+14);
} else if (starts_with(arg, "--no-max-parents")) {
revs->max_parents = -1;
} else if (!strcmp(arg, "--boundary")) {
revs->boundary = 1;
} else if (!strcmp(arg, "--left-right")) {
revs->left_right = 1;
} else if (!strcmp(arg, "--left-only")) {
if (revs->right_only)
die("--left-only is incompatible with --right-only"
" or --cherry");
revs->left_only = 1;
} else if (!strcmp(arg, "--right-only")) {
if (revs->left_only)
die("--right-only is incompatible with --left-only");
revs->right_only = 1;
} else if (!strcmp(arg, "--cherry")) {
if (revs->left_only)
die("--cherry is incompatible with --left-only");
revs->cherry_mark = 1;
revs->right_only = 1;
revs->max_parents = 1;
revs->limited = 1;
} else if (!strcmp(arg, "--count")) {
revs->count = 1;
} else if (!strcmp(arg, "--cherry-mark")) {
if (revs->cherry_pick)
die("--cherry-mark is incompatible with --cherry-pick");
revs->cherry_mark = 1;
revs->limited = 1; /* needs limit_list() */
} else if (!strcmp(arg, "--cherry-pick")) {
if (revs->cherry_mark)
die("--cherry-pick is incompatible with --cherry-mark");
revs->cherry_pick = 1;
revs->limited = 1;
} else if (!strcmp(arg, "--objects")) {
revs->tag_objects = 1;
revs->tree_objects = 1;
revs->blob_objects = 1;
} else if (!strcmp(arg, "--objects-edge")) {
revs->tag_objects = 1;
revs->tree_objects = 1;
revs->blob_objects = 1;
revs->edge_hint = 1;
} else if (!strcmp(arg, "--objects-edge-aggressive")) {
revs->tag_objects = 1;
revs->tree_objects = 1;
revs->blob_objects = 1;
revs->edge_hint = 1;
revs->edge_hint_aggressive = 1;
} else if (!strcmp(arg, "--verify-objects")) {
revs->tag_objects = 1;
revs->tree_objects = 1;
revs->blob_objects = 1;
revs->verify_objects = 1;
} else if (!strcmp(arg, "--unpacked")) {
revs->unpacked = 1;
} else if (starts_with(arg, "--unpacked=")) {
die("--unpacked=<packfile> no longer supported.");
} else if (!strcmp(arg, "-r")) {
revs->diff = 1;
DIFF_OPT_SET(&revs->diffopt, RECURSIVE);
} else if (!strcmp(arg, "-t")) {
revs->diff = 1;
DIFF_OPT_SET(&revs->diffopt, RECURSIVE);
DIFF_OPT_SET(&revs->diffopt, TREE_IN_RECURSIVE);
} else if (!strcmp(arg, "-m")) {
revs->ignore_merges = 0;
} else if (!strcmp(arg, "-c")) {
revs->diff = 1;
revs->dense_combined_merges = 0;
revs->combine_merges = 1;
} else if (!strcmp(arg, "--cc")) {
revs->diff = 1;
revs->dense_combined_merges = 1;
revs->combine_merges = 1;
} else if (!strcmp(arg, "-v")) {
revs->verbose_header = 1;
} else if (!strcmp(arg, "--pretty")) {
revs->verbose_header = 1;
revs->pretty_given = 1;
get_commit_format(NULL, revs);
} else if (starts_with(arg, "--pretty=") || starts_with(arg, "--format=")) {
/*
* Detached form ("--pretty X" as opposed to "--pretty=X")
* not allowed, since the argument is optional.
*/
revs->verbose_header = 1;
revs->pretty_given = 1;
get_commit_format(arg+9, revs);
} else if (!strcmp(arg, "--show-notes") || !strcmp(arg, "--notes")) {
revs->show_notes = 1;
revs->show_notes_given = 1;
revs->notes_opt.use_default_notes = 1;
} else if (!strcmp(arg, "--show-signature")) {
revs->show_signature = 1;
} else if (!strcmp(arg, "--show-linear-break") ||
starts_with(arg, "--show-linear-break=")) {
if (starts_with(arg, "--show-linear-break="))
revs->break_bar = xstrdup(arg + 20);
else
revs->break_bar = " ..........";
revs->track_linear = 1;
revs->track_first_time = 1;
} else if (starts_with(arg, "--show-notes=") ||
starts_with(arg, "--notes=")) {
struct strbuf buf = STRBUF_INIT;
revs->show_notes = 1;
revs->show_notes_given = 1;
if (starts_with(arg, "--show-notes")) {
if (revs->notes_opt.use_default_notes < 0)
revs->notes_opt.use_default_notes = 1;
strbuf_addstr(&buf, arg+13);
}
else
strbuf_addstr(&buf, arg+8);
expand_notes_ref(&buf);
string_list_append(&revs->notes_opt.extra_notes_refs,
strbuf_detach(&buf, NULL));
} else if (!strcmp(arg, "--no-notes")) {
revs->show_notes = 0;
revs->show_notes_given = 1;
revs->notes_opt.use_default_notes = -1;
/* we have been strdup'ing ourselves, so trick
* string_list into free()ing strings */
revs->notes_opt.extra_notes_refs.strdup_strings = 1;
string_list_clear(&revs->notes_opt.extra_notes_refs, 0);
revs->notes_opt.extra_notes_refs.strdup_strings = 0;
} else if (!strcmp(arg, "--standard-notes")) {
revs->show_notes_given = 1;
revs->notes_opt.use_default_notes = 1;
} else if (!strcmp(arg, "--no-standard-notes")) {
revs->notes_opt.use_default_notes = 0;
} else if (!strcmp(arg, "--oneline")) {
revs->verbose_header = 1;
get_commit_format("oneline", revs);
revs->pretty_given = 1;
revs->abbrev_commit = 1;
} else if (!strcmp(arg, "--graph")) {
revs->topo_order = 1;
revs->rewrite_parents = 1;
revs->graph = graph_init(revs);
} else if (!strcmp(arg, "--root")) {
revs->show_root_diff = 1;
} else if (!strcmp(arg, "--no-commit-id")) {
revs->no_commit_id = 1;
} else if (!strcmp(arg, "--always")) {
revs->always_show_header = 1;
} else if (!strcmp(arg, "--no-abbrev")) {
revs->abbrev = 0;
} else if (!strcmp(arg, "--abbrev")) {
revs->abbrev = DEFAULT_ABBREV;
} else if (starts_with(arg, "--abbrev=")) {
revs->abbrev = strtoul(arg + 9, NULL, 10);
if (revs->abbrev < MINIMUM_ABBREV)
revs->abbrev = MINIMUM_ABBREV;
else if (revs->abbrev > 40)
revs->abbrev = 40;
} else if (!strcmp(arg, "--abbrev-commit")) {
revs->abbrev_commit = 1;
revs->abbrev_commit_given = 1;
} else if (!strcmp(arg, "--no-abbrev-commit")) {
revs->abbrev_commit = 0;
} else if (!strcmp(arg, "--full-diff")) {
revs->diff = 1;
revs->full_diff = 1;
} else if (!strcmp(arg, "--full-history")) {
revs->simplify_history = 0;
} else if (!strcmp(arg, "--relative-date")) {
revs->date_mode.type = DATE_RELATIVE;
revs->date_mode_explicit = 1;
} else if ((argcount = parse_long_opt("date", argv, &optarg))) {
parse_date_format(optarg, &revs->date_mode);
revs->date_mode_explicit = 1;
return argcount;
} else if (!strcmp(arg, "--log-size")) {
revs->show_log_size = 1;
}
/*
* Grepping the commit log
*/
else if ((argcount = parse_long_opt("author", argv, &optarg))) {
add_header_grep(revs, GREP_HEADER_AUTHOR, optarg);
return argcount;
} else if ((argcount = parse_long_opt("committer", argv, &optarg))) {
add_header_grep(revs, GREP_HEADER_COMMITTER, optarg);
return argcount;
} else if ((argcount = parse_long_opt("grep-reflog", argv, &optarg))) {
add_header_grep(revs, GREP_HEADER_REFLOG, optarg);
return argcount;
} else if ((argcount = parse_long_opt("grep", argv, &optarg))) {
add_message_grep(revs, optarg);
return argcount;
} else if (!strcmp(arg, "--grep-debug")) {
revs->grep_filter.debug = 1;
} else if (!strcmp(arg, "--basic-regexp")) {
grep_set_pattern_type_option(GREP_PATTERN_TYPE_BRE, &revs->grep_filter);
} else if (!strcmp(arg, "--extended-regexp") || !strcmp(arg, "-E")) {
grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, &revs->grep_filter);
} else if (!strcmp(arg, "--regexp-ignore-case") || !strcmp(arg, "-i")) {
revs->grep_filter.regflags |= REG_ICASE;
DIFF_OPT_SET(&revs->diffopt, PICKAXE_IGNORE_CASE);
} else if (!strcmp(arg, "--fixed-strings") || !strcmp(arg, "-F")) {
grep_set_pattern_type_option(GREP_PATTERN_TYPE_FIXED, &revs->grep_filter);
} else if (!strcmp(arg, "--perl-regexp")) {
grep_set_pattern_type_option(GREP_PATTERN_TYPE_PCRE, &revs->grep_filter);
} else if (!strcmp(arg, "--all-match")) {
revs->grep_filter.all_match = 1;
} else if (!strcmp(arg, "--invert-grep")) {
revs->invert_grep = 1;
} else if ((argcount = parse_long_opt("encoding", argv, &optarg))) {
if (strcmp(optarg, "none"))
git_log_output_encoding = xstrdup(optarg);
else
git_log_output_encoding = "";
return argcount;
} else if (!strcmp(arg, "--reverse")) {
revs->reverse ^= 1;
} else if (!strcmp(arg, "--children")) {
revs->children.name = "children";
revs->limited = 1;
} else if (!strcmp(arg, "--ignore-missing")) {
revs->ignore_missing = 1;
} else {
int opts = diff_opt_parse(&revs->diffopt, argv, argc, revs->prefix);
if (!opts)
unkv[(*unkc)++] = arg;
return opts;
}
if (revs->graph && revs->track_linear)
die("--show-linear-break and --graph are incompatible");
return 1;
}
void parse_revision_opt(struct rev_info *revs, struct parse_opt_ctx_t *ctx,
const struct option *options,
const char * const usagestr[])
{
int n = handle_revision_opt(revs, ctx->argc, ctx->argv,
&ctx->cpidx, ctx->out);
if (n <= 0) {
error("unknown option `%s'", ctx->argv[0]);
usage_with_options(usagestr, options);
}
ctx->argv += n;
ctx->argc -= n;
}
static int for_each_bisect_ref(const char *submodule, each_ref_fn fn, void *cb_data, const char *term) {
struct strbuf bisect_refs = STRBUF_INIT;
int status;
strbuf_addf(&bisect_refs, "refs/bisect/%s", term);
status = for_each_ref_in_submodule(submodule, bisect_refs.buf, fn, cb_data);
strbuf_release(&bisect_refs);
return status;
}
static int for_each_bad_bisect_ref(const char *submodule, each_ref_fn fn, void *cb_data)
{
return for_each_bisect_ref(submodule, fn, cb_data, term_bad);
}
static int for_each_good_bisect_ref(const char *submodule, each_ref_fn fn, void *cb_data)
{
return for_each_bisect_ref(submodule, fn, cb_data, term_good);
}
static int handle_revision_pseudo_opt(const char *submodule,
struct rev_info *revs,
int argc, const char **argv, int *flags)
{
const char *arg = argv[0];
const char *optarg;
int argcount;
/*
* NOTE!
*
* Commands like "git shortlog" will not accept the options below
* unless parse_revision_opt queues them (as opposed to erroring
* out).
*
* When implementing your new pseudo-option, remember to
* register it in the list at the top of handle_revision_opt.
*/
if (!strcmp(arg, "--all")) {
handle_refs(submodule, revs, *flags, for_each_ref_submodule);
handle_refs(submodule, revs, *flags, head_ref_submodule);
clear_ref_exclusion(&revs->ref_excludes);
} else if (!strcmp(arg, "--branches")) {
handle_refs(submodule, revs, *flags, for_each_branch_ref_submodule);
clear_ref_exclusion(&revs->ref_excludes);
} else if (!strcmp(arg, "--bisect")) {
read_bisect_terms(&term_bad, &term_good);
handle_refs(submodule, revs, *flags, for_each_bad_bisect_ref);
handle_refs(submodule, revs, *flags ^ (UNINTERESTING | BOTTOM), for_each_good_bisect_ref);
revs->bisect = 1;
} else if (!strcmp(arg, "--tags")) {
handle_refs(submodule, revs, *flags, for_each_tag_ref_submodule);
clear_ref_exclusion(&revs->ref_excludes);
} else if (!strcmp(arg, "--remotes")) {
handle_refs(submodule, revs, *flags, for_each_remote_ref_submodule);
clear_ref_exclusion(&revs->ref_excludes);
} else if ((argcount = parse_long_opt("glob", argv, &optarg))) {
struct all_refs_cb cb;
init_all_refs_cb(&cb, revs, *flags);
for_each_glob_ref(handle_one_ref, optarg, &cb);
clear_ref_exclusion(&revs->ref_excludes);
return argcount;
} else if ((argcount = parse_long_opt("exclude", argv, &optarg))) {
add_ref_exclusion(&revs->ref_excludes, optarg);
return argcount;
} else if (starts_with(arg, "--branches=")) {
struct all_refs_cb cb;
init_all_refs_cb(&cb, revs, *flags);
for_each_glob_ref_in(handle_one_ref, arg + 11, "refs/heads/", &cb);
clear_ref_exclusion(&revs->ref_excludes);
} else if (starts_with(arg, "--tags=")) {
struct all_refs_cb cb;
init_all_refs_cb(&cb, revs, *flags);
for_each_glob_ref_in(handle_one_ref, arg + 7, "refs/tags/", &cb);
clear_ref_exclusion(&revs->ref_excludes);
} else if (starts_with(arg, "--remotes=")) {
struct all_refs_cb cb;
init_all_refs_cb(&cb, revs, *flags);
for_each_glob_ref_in(handle_one_ref, arg + 10, "refs/remotes/", &cb);
clear_ref_exclusion(&revs->ref_excludes);
} else if (!strcmp(arg, "--reflog")) {
add_reflogs_to_pending(revs, *flags);
} else if (!strcmp(arg, "--indexed-objects")) {
add_index_objects_to_pending(revs, *flags);
} else if (!strcmp(arg, "--not")) {
*flags ^= UNINTERESTING | BOTTOM;
} else if (!strcmp(arg, "--no-walk")) {
revs->no_walk = REVISION_WALK_NO_WALK_SORTED;
} else if (starts_with(arg, "--no-walk=")) {
/*
* Detached form ("--no-walk X" as opposed to "--no-walk=X")
* not allowed, since the argument is optional.
*/
if (!strcmp(arg + 10, "sorted"))
revs->no_walk = REVISION_WALK_NO_WALK_SORTED;
else if (!strcmp(arg + 10, "unsorted"))
revs->no_walk = REVISION_WALK_NO_WALK_UNSORTED;
else
return error("invalid argument to --no-walk");
} else if (!strcmp(arg, "--do-walk")) {
revs->no_walk = 0;
} else {
return 0;
}
return 1;
}
static void NORETURN diagnose_missing_default(const char *def)
{
unsigned char sha1[20];
int flags;
const char *refname;
refname = resolve_ref_unsafe(def, 0, sha1, &flags);
if (!refname || !(flags & REF_ISSYMREF) || (flags & REF_ISBROKEN))
die(_("your current branch appears to be broken"));
skip_prefix(refname, "refs/heads/", &refname);
die(_("your current branch '%s' does not have any commits yet"),
refname);
}
/*
* Parse revision information, filling in the "rev_info" structure,
* and removing the used arguments from the argument list.
*
* Returns the number of arguments left that weren't recognized
* (which are also moved to the head of the argument list)
*/
int setup_revisions(int argc, const char **argv, struct rev_info *revs, struct setup_revision_opt *opt)
{
int i, flags, left, seen_dashdash, read_from_stdin, got_rev_arg = 0, revarg_opt;
struct cmdline_pathspec prune_data;
const char *submodule = NULL;
memset(&prune_data, 0, sizeof(prune_data));
if (opt)
submodule = opt->submodule;
/* First, search for "--" */
if (opt && opt->assume_dashdash) {
seen_dashdash = 1;
} else {
seen_dashdash = 0;
for (i = 1; i < argc; i++) {
const char *arg = argv[i];
if (strcmp(arg, "--"))
continue;
argv[i] = NULL;
argc = i;
if (argv[i + 1])
append_prune_data(&prune_data, argv + i + 1);
seen_dashdash = 1;
break;
}
}
/* Second, deal with arguments and options */
flags = 0;
revarg_opt = opt ? opt->revarg_opt : 0;
if (seen_dashdash)
revarg_opt |= REVARG_CANNOT_BE_FILENAME;
read_from_stdin = 0;
for (left = i = 1; i < argc; i++) {
const char *arg = argv[i];
if (*arg == '-') {
int opts;
opts = handle_revision_pseudo_opt(submodule,
revs, argc - i, argv + i,
&flags);
if (opts > 0) {
i += opts - 1;
continue;
}
if (!strcmp(arg, "--stdin")) {
if (revs->disable_stdin) {
argv[left++] = arg;
continue;
}
if (read_from_stdin++)
die("--stdin given twice?");
read_revisions_from_stdin(revs, &prune_data);
continue;
}
opts = handle_revision_opt(revs, argc - i, argv + i, &left, argv);
if (opts > 0) {
i += opts - 1;
continue;
}
if (opts < 0)
exit(128);
continue;
}
if (handle_revision_arg(arg, revs, flags, revarg_opt)) {
int j;
if (seen_dashdash || *arg == '^')
die("bad revision '%s'", arg);
/* If we didn't have a "--":
* (1) all filenames must exist;
* (2) all rev-args must not be interpretable
* as a valid filename.
* but the latter we have checked in the main loop.
*/
for (j = i; j < argc; j++)
verify_filename(revs->prefix, argv[j], j == i);
append_prune_data(&prune_data, argv + i);
break;
}
else
got_rev_arg = 1;
}
if (prune_data.nr) {
/*
* If we need to introduce the magic "a lone ':' means no
* pathspec whatsoever", here is the place to do so.
*
* if (prune_data.nr == 1 && !strcmp(prune_data[0], ":")) {
* prune_data.nr = 0;
* prune_data.alloc = 0;
* free(prune_data.path);
* prune_data.path = NULL;
* } else {
* terminate prune_data.alloc with NULL and
* call init_pathspec() to set revs->prune_data here.
* }
*/
ALLOC_GROW(prune_data.path, prune_data.nr + 1, prune_data.alloc);
prune_data.path[prune_data.nr++] = NULL;
parse_pathspec(&revs->prune_data, 0, 0,
revs->prefix, prune_data.path);
}
if (revs->def == NULL)
revs->def = opt ? opt->def : NULL;
if (opt && opt->tweak)
opt->tweak(revs, opt);
if (revs->show_merge)
prepare_show_merge(revs);
if (revs->def && !revs->pending.nr && !got_rev_arg) {
unsigned char sha1[20];
struct object *object;
struct object_context oc;
if (get_sha1_with_context(revs->def, 0, sha1, &oc))
diagnose_missing_default(revs->def);
object = get_reference(revs, revs->def, sha1, 0);
add_pending_object_with_mode(revs, object, revs->def, oc.mode);
}
/* Did the user ask for any diff output? Run the diff! */
if (revs->diffopt.output_format & ~DIFF_FORMAT_NO_OUTPUT)
revs->diff = 1;
/* Pickaxe, diff-filter and rename following need diffs */
if (revs->diffopt.pickaxe ||
revs->diffopt.filter ||
DIFF_OPT_TST(&revs->diffopt, FOLLOW_RENAMES))
revs->diff = 1;
if (revs->topo_order)
revs->limited = 1;
if (revs->prune_data.nr) {
copy_pathspec(&revs->pruning.pathspec, &revs->prune_data);
/* Can't prune commits with rename following: the paths change.. */
if (!DIFF_OPT_TST(&revs->diffopt, FOLLOW_RENAMES))
revs->prune = 1;
if (!revs->full_diff)
copy_pathspec(&revs->diffopt.pathspec,
&revs->prune_data);
}
if (revs->combine_merges)
revs->ignore_merges = 0;
revs->diffopt.abbrev = revs->abbrev;
if (revs->line_level_traverse) {
revs->limited = 1;
revs->topo_order = 1;
}
diff_setup_done(&revs->diffopt);
grep_commit_pattern_type(GREP_PATTERN_TYPE_UNSPECIFIED,
&revs->grep_filter);
compile_grep_patterns(&revs->grep_filter);
if (revs->reverse && revs->reflog_info)
die("cannot combine --reverse with --walk-reflogs");
if (revs->rewrite_parents && revs->children.name)
die("cannot combine --parents and --children");
/*
* Limitations on the graph functionality
*/
if (revs->reverse && revs->graph)
die("cannot combine --reverse with --graph");
if (revs->reflog_info && revs->graph)
die("cannot combine --walk-reflogs with --graph");
if (revs->no_walk && revs->graph)
die("cannot combine --no-walk with --graph");
if (!revs->reflog_info && revs->grep_filter.use_reflog_filter)
die("cannot use --grep-reflog without --walk-reflogs");
if (revs->first_parent_only && revs->bisect)
die(_("--first-parent is incompatible with --bisect"));
return left;
}
static void add_child(struct rev_info *revs, struct commit *parent, struct commit *child)
{
struct commit_list *l = xcalloc(1, sizeof(*l));
l->item = child;
l->next = add_decoration(&revs->children, &parent->object, l);
}
static int remove_duplicate_parents(struct rev_info *revs, struct commit *commit)
{
struct treesame_state *ts = lookup_decoration(&revs->treesame, &commit->object);
struct commit_list **pp, *p;
int surviving_parents;
/* Examine existing parents while marking ones we have seen... */
pp = &commit->parents;
surviving_parents = 0;
while ((p = *pp) != NULL) {
struct commit *parent = p->item;
if (parent->object.flags & TMP_MARK) {
*pp = p->next;
if (ts)
compact_treesame(revs, commit, surviving_parents);
continue;
}
parent->object.flags |= TMP_MARK;
surviving_parents++;
pp = &p->next;
}
/* clear the temporary mark */
for (p = commit->parents; p; p = p->next) {
p->item->object.flags &= ~TMP_MARK;
}
/* no update_treesame() - removing duplicates can't affect TREESAME */
return surviving_parents;
}
struct merge_simplify_state {
struct commit *simplified;
};
static struct merge_simplify_state *locate_simplify_state(struct rev_info *revs, struct commit *commit)
{
struct merge_simplify_state *st;
st = lookup_decoration(&revs->merge_simplification, &commit->object);
if (!st) {
st = xcalloc(1, sizeof(*st));
add_decoration(&revs->merge_simplification, &commit->object, st);
}
return st;
}
static int mark_redundant_parents(struct rev_info *revs, struct commit *commit)
{
struct commit_list *h = reduce_heads(commit->parents);
int i = 0, marked = 0;
struct commit_list *po, *pn;
/* Want these for sanity-checking only */
int orig_cnt = commit_list_count(commit->parents);
int cnt = commit_list_count(h);
/*
* Not ready to remove items yet, just mark them for now, based
* on the output of reduce_heads(). reduce_heads outputs the reduced
* set in its original order, so this isn't too hard.
*/
po = commit->parents;
pn = h;
while (po) {
if (pn && po->item == pn->item) {
pn = pn->next;
i++;
} else {
po->item->object.flags |= TMP_MARK;
marked++;
}
po=po->next;
}
if (i != cnt || cnt+marked != orig_cnt)
die("mark_redundant_parents %d %d %d %d", orig_cnt, cnt, i, marked);
free_commit_list(h);
return marked;
}
static int mark_treesame_root_parents(struct rev_info *revs, struct commit *commit)
{
struct commit_list *p;
int marked = 0;
for (p = commit->parents; p; p = p->next) {
struct commit *parent = p->item;
if (!parent->parents && (parent->object.flags & TREESAME)) {
parent->object.flags |= TMP_MARK;
marked++;
}
}
return marked;
}
/*
* Awkward naming - this means one parent we are TREESAME to.
* cf mark_treesame_root_parents: root parents that are TREESAME (to an
* empty tree). Better name suggestions?
*/
static int leave_one_treesame_to_parent(struct rev_info *revs, struct commit *commit)
{
struct treesame_state *ts = lookup_decoration(&revs->treesame, &commit->object);
struct commit *unmarked = NULL, *marked = NULL;
struct commit_list *p;
unsigned n;
for (p = commit->parents, n = 0; p; p = p->next, n++) {
if (ts->treesame[n]) {
if (p->item->object.flags & TMP_MARK) {
if (!marked)
marked = p->item;
} else {
if (!unmarked) {
unmarked = p->item;
break;
}
}
}
}
/*
* If we are TREESAME to a marked-for-deletion parent, but not to any
* unmarked parents, unmark the first TREESAME parent. This is the
* parent that the default simplify_history==1 scan would have followed,
* and it doesn't make sense to omit that path when asking for a
* simplified full history. Retaining it improves the chances of
* understanding odd missed merges that took an old version of a file.
*
* Example:
*
* I--------*X A modified the file, but mainline merge X used
* \ / "-s ours", so took the version from I. X is
* `-*A--' TREESAME to I and !TREESAME to A.
*
* Default log from X would produce "I". Without this check,
* --full-history --simplify-merges would produce "I-A-X", showing
* the merge commit X and that it changed A, but not making clear that
* it had just taken the I version. With this check, the topology above
* is retained.
*
* Note that it is possible that the simplification chooses a different
* TREESAME parent from the default, in which case this test doesn't
* activate, and we _do_ drop the default parent. Example:
*
* I------X A modified the file, but it was reverted in B,
* \ / meaning mainline merge X is TREESAME to both
* *A-*B parents.
*
* Default log would produce "I" by following the first parent;
* --full-history --simplify-merges will produce "I-A-B". But this is a
* reasonable result - it presents a logical full history leading from
* I to X, and X is not an important merge.
*/
if (!unmarked && marked) {
marked->object.flags &= ~TMP_MARK;
return 1;
}
return 0;
}
static int remove_marked_parents(struct rev_info *revs, struct commit *commit)
{
struct commit_list **pp, *p;
int nth_parent, removed = 0;
pp = &commit->parents;
nth_parent = 0;
while ((p = *pp) != NULL) {
struct commit *parent = p->item;
if (parent->object.flags & TMP_MARK) {
parent->object.flags &= ~TMP_MARK;
*pp = p->next;
free(p);
removed++;
compact_treesame(revs, commit, nth_parent);
continue;
}
pp = &p->next;
nth_parent++;
}
/* Removing parents can only increase TREESAMEness */
if (removed && !(commit->object.flags & TREESAME))
update_treesame(revs, commit);
return nth_parent;
}
static struct commit_list **simplify_one(struct rev_info *revs, struct commit *commit, struct commit_list **tail)
{
struct commit_list *p;
struct commit *parent;
struct merge_simplify_state *st, *pst;
int cnt;
st = locate_simplify_state(revs, commit);
/*
* Have we handled this one?
*/
if (st->simplified)
return tail;
/*
* An UNINTERESTING commit simplifies to itself, so does a
* root commit. We do not rewrite parents of such commit
* anyway.
*/
if ((commit->object.flags & UNINTERESTING) || !commit->parents) {
st->simplified = commit;
return tail;
}
/*
* Do we know what commit all of our parents that matter
* should be rewritten to? Otherwise we are not ready to
* rewrite this one yet.
*/
for (cnt = 0, p = commit->parents; p; p = p->next) {
pst = locate_simplify_state(revs, p->item);
if (!pst->simplified) {
tail = &commit_list_insert(p->item, tail)->next;
cnt++;
}
if (revs->first_parent_only)
break;
}
if (cnt) {
tail = &commit_list_insert(commit, tail)->next;
return tail;
}
/*
* Rewrite our list of parents. Note that this cannot
* affect our TREESAME flags in any way - a commit is
* always TREESAME to its simplification.
*/
for (p = commit->parents; p; p = p->next) {
pst = locate_simplify_state(revs, p->item);
p->item = pst->simplified;
if (revs->first_parent_only)
break;
}
if (revs->first_parent_only)
cnt = 1;
else
cnt = remove_duplicate_parents(revs, commit);
/*
* It is possible that we are a merge and one side branch
* does not have any commit that touches the given paths;
* in such a case, the immediate parent from that branch
* will be rewritten to be the merge base.
*
* o----X X: the commit we are looking at;
* / / o: a commit that touches the paths;
* ---o----'
*
* Further, a merge of an independent branch that doesn't
* touch the path will reduce to a treesame root parent:
*
* ----o----X X: the commit we are looking at;
* / o: a commit that touches the paths;
* r r: a root commit not touching the paths
*
* Detect and simplify both cases.
*/
if (1 < cnt) {
int marked = mark_redundant_parents(revs, commit);
marked += mark_treesame_root_parents(revs, commit);
if (marked)
marked -= leave_one_treesame_to_parent(revs, commit);
if (marked)
cnt = remove_marked_parents(revs, commit);
}
/*
* A commit simplifies to itself if it is a root, if it is
* UNINTERESTING, if it touches the given paths, or if it is a
* merge and its parents don't simplify to one relevant commit
* (the first two cases are already handled at the beginning of
* this function).
*
* Otherwise, it simplifies to what its sole relevant parent
* simplifies to.
*/
if (!cnt ||
(commit->object.flags & UNINTERESTING) ||
!(commit->object.flags & TREESAME) ||
(parent = one_relevant_parent(revs, commit->parents)) == NULL)
st->simplified = commit;
else {
pst = locate_simplify_state(revs, parent);
st->simplified = pst->simplified;
}
return tail;
}
static void simplify_merges(struct rev_info *revs)
{
struct commit_list *list, *next;
struct commit_list *yet_to_do, **tail;
struct commit *commit;
if (!revs->prune)
return;
/* feed the list reversed */
yet_to_do = NULL;
for (list = revs->commits; list; list = next) {
commit = list->item;
next = list->next;
/*
* Do not free(list) here yet; the original list
* is used later in this function.
*/
commit_list_insert(commit, &yet_to_do);
}
while (yet_to_do) {
list = yet_to_do;
yet_to_do = NULL;
tail = &yet_to_do;
while (list) {
commit = pop_commit(&list);
tail = simplify_one(revs, commit, tail);
}
}
/* clean up the result, removing the simplified ones */
list = revs->commits;
revs->commits = NULL;
tail = &revs->commits;
while (list) {
struct merge_simplify_state *st;
commit = pop_commit(&list);
st = locate_simplify_state(revs, commit);
if (st->simplified == commit)
tail = &commit_list_insert(commit, tail)->next;
}
}
static void set_children(struct rev_info *revs)
{
struct commit_list *l;
for (l = revs->commits; l; l = l->next) {
struct commit *commit = l->item;
struct commit_list *p;
for (p = commit->parents; p; p = p->next)
add_child(revs, p->item, commit);
}
}
void reset_revision_walk(void)
{
clear_object_flags(SEEN | ADDED | SHOWN);
}
int prepare_revision_walk(struct rev_info *revs)
{
int i;
struct object_array old_pending;
struct commit_list **next = &revs->commits;
memcpy(&old_pending, &revs->pending, sizeof(old_pending));
revs->pending.nr = 0;
revs->pending.alloc = 0;
revs->pending.objects = NULL;
for (i = 0; i < old_pending.nr; i++) {
struct object_array_entry *e = old_pending.objects + i;
struct commit *commit = handle_commit(revs, e);
if (commit) {
if (!(commit->object.flags & SEEN)) {
commit->object.flags |= SEEN;
next = commit_list_append(commit, next);
}
}
}
if (!revs->leak_pending)
object_array_clear(&old_pending);
/* Signal whether we need per-parent treesame decoration */
if (revs->simplify_merges ||
(revs->limited && limiting_can_increase_treesame(revs)))
revs->treesame.name = "treesame";
if (revs->no_walk != REVISION_WALK_NO_WALK_UNSORTED)
commit_list_sort_by_date(&revs->commits);
if (revs->no_walk)
return 0;
if (revs->limited)
if (limit_list(revs) < 0)
return -1;
if (revs->topo_order)
sort_in_topological_order(&revs->commits, revs->sort_order);
if (revs->line_level_traverse)
line_log_filter(revs);
if (revs->simplify_merges)
simplify_merges(revs);
if (revs->children.name)
set_children(revs);
return 0;
}
static enum rewrite_result rewrite_one(struct rev_info *revs, struct commit **pp)
{
struct commit_list *cache = NULL;
for (;;) {
struct commit *p = *pp;
if (!revs->limited)
if (add_parents_to_list(revs, p, &revs->commits, &cache) < 0)
return rewrite_one_error;
if (p->object.flags & UNINTERESTING)
return rewrite_one_ok;
if (!(p->object.flags & TREESAME))
return rewrite_one_ok;
if (!p->parents)
return rewrite_one_noparents;
if ((p = one_relevant_parent(revs, p->parents)) == NULL)
return rewrite_one_ok;
*pp = p;
}
}
int rewrite_parents(struct rev_info *revs, struct commit *commit,
rewrite_parent_fn_t rewrite_parent)
{
struct commit_list **pp = &commit->parents;
while (*pp) {
struct commit_list *parent = *pp;
switch (rewrite_parent(revs, &parent->item)) {
case rewrite_one_ok:
break;
case rewrite_one_noparents:
*pp = parent->next;
continue;
case rewrite_one_error:
return -1;
}
pp = &parent->next;
}
remove_duplicate_parents(revs, commit);
return 0;
}
static int commit_rewrite_person(struct strbuf *buf, const char *what, struct string_list *mailmap)
{
char *person, *endp;
size_t len, namelen, maillen;
const char *name;
const char *mail;
struct ident_split ident;
person = strstr(buf->buf, what);
if (!person)
return 0;
person += strlen(what);
endp = strchr(person, '\n');
if (!endp)
return 0;
len = endp - person;
if (split_ident_line(&ident, person, len))
return 0;
mail = ident.mail_begin;
maillen = ident.mail_end - ident.mail_begin;
name = ident.name_begin;
namelen = ident.name_end - ident.name_begin;
if (map_user(mailmap, &mail, &maillen, &name, &namelen)) {
struct strbuf namemail = STRBUF_INIT;
strbuf_addf(&namemail, "%.*s <%.*s>",
(int)namelen, name, (int)maillen, mail);
strbuf_splice(buf, ident.name_begin - buf->buf,
ident.mail_end - ident.name_begin + 1,
namemail.buf, namemail.len);
strbuf_release(&namemail);
return 1;
}
return 0;
}
static int commit_match(struct commit *commit, struct rev_info *opt)
{
int retval;
const char *encoding;
const char *message;
struct strbuf buf = STRBUF_INIT;
if (!opt->grep_filter.pattern_list && !opt->grep_filter.header_list)
return 1;
/* Prepend "fake" headers as needed */
if (opt->grep_filter.use_reflog_filter) {
strbuf_addstr(&buf, "reflog ");
get_reflog_message(&buf, opt->reflog_info);
strbuf_addch(&buf, '\n');
}
/*
* We grep in the user's output encoding, under the assumption that it
* is the encoding they are most likely to write their grep pattern
* for. In addition, it means we will match the "notes" encoding below,
* so we will not end up with a buffer that has two different encodings
* in it.
*/
encoding = get_log_output_encoding();
message = logmsg_reencode(commit, NULL, encoding);
/* Copy the commit to temporary if we are using "fake" headers */
if (buf.len)
strbuf_addstr(&buf, message);
if (opt->grep_filter.header_list && opt->mailmap) {
if (!buf.len)
strbuf_addstr(&buf, message);
commit_rewrite_person(&buf, "\nauthor ", opt->mailmap);
commit_rewrite_person(&buf, "\ncommitter ", opt->mailmap);
}
/* Append "fake" message parts as needed */
if (opt->show_notes) {
if (!buf.len)
strbuf_addstr(&buf, message);
format_display_notes(commit->object.oid.hash, &buf, encoding, 1);
}
/*
* Find either in the original commit message, or in the temporary.
* Note that we cast away the constness of "message" here. It is
* const because it may come from the cached commit buffer. That's OK,
* because we know that it is modifiable heap memory, and that while
* grep_buffer may modify it for speed, it will restore any
* changes before returning.
*/
if (buf.len)
retval = grep_buffer(&opt->grep_filter, buf.buf, buf.len);
else
retval = grep_buffer(&opt->grep_filter,
(char *)message, strlen(message));
strbuf_release(&buf);
unuse_commit_buffer(commit, message);
return opt->invert_grep ? !retval : retval;
}
static inline int want_ancestry(const struct rev_info *revs)
{
return (revs->rewrite_parents || revs->children.name);
}
enum commit_action get_commit_action(struct rev_info *revs, struct commit *commit)
{
if (commit->object.flags & SHOWN)
return commit_ignore;
if (revs->unpacked && has_sha1_pack(commit->object.oid.hash))
return commit_ignore;
if (revs->show_all)
return commit_show;
if (commit->object.flags & UNINTERESTING)
return commit_ignore;
if (revs->min_age != -1 && (commit->date > revs->min_age))
return commit_ignore;
if (revs->min_parents || (revs->max_parents >= 0)) {
int n = commit_list_count(commit->parents);
if ((n < revs->min_parents) ||
((revs->max_parents >= 0) && (n > revs->max_parents)))
return commit_ignore;
}
if (!commit_match(commit, revs))
return commit_ignore;
if (revs->prune && revs->dense) {
/* Commit without changes? */
if (commit->object.flags & TREESAME) {
int n;
struct commit_list *p;
/* drop merges unless we want parenthood */
if (!want_ancestry(revs))
return commit_ignore;
/*
* If we want ancestry, then need to keep any merges
* between relevant commits to tie together topology.
* For consistency with TREESAME and simplification
* use "relevant" here rather than just INTERESTING,
* to treat bottom commit(s) as part of the topology.
*/
for (n = 0, p = commit->parents; p; p = p->next)
if (relevant_commit(p->item))
if (++n >= 2)
return commit_show;
return commit_ignore;
}
}
return commit_show;
}
define_commit_slab(saved_parents, struct commit_list *);
#define EMPTY_PARENT_LIST ((struct commit_list *)-1)
/*
* You may only call save_parents() once per commit (this is checked
* for non-root commits).
*/
static void save_parents(struct rev_info *revs, struct commit *commit)
{
struct commit_list **pp;
if (!revs->saved_parents_slab) {
revs->saved_parents_slab = xmalloc(sizeof(struct saved_parents));
init_saved_parents(revs->saved_parents_slab);
}
pp = saved_parents_at(revs->saved_parents_slab, commit);
/*
* When walking with reflogs, we may visit the same commit
* several times: once for each appearance in the reflog.
*
* In this case, save_parents() will be called multiple times.
* We want to keep only the first set of parents. We need to
* store a sentinel value for an empty (i.e., NULL) parent
* list to distinguish it from a not-yet-saved list, however.
*/
if (*pp)
return;
if (commit->parents)
*pp = copy_commit_list(commit->parents);
else
*pp = EMPTY_PARENT_LIST;
}
static void free_saved_parents(struct rev_info *revs)
{
if (revs->saved_parents_slab)
clear_saved_parents(revs->saved_parents_slab);
}
struct commit_list *get_saved_parents(struct rev_info *revs, const struct commit *commit)
{
struct commit_list *parents;
if (!revs->saved_parents_slab)
return commit->parents;
parents = *saved_parents_at(revs->saved_parents_slab, commit);
if (parents == EMPTY_PARENT_LIST)
return NULL;
return parents;
}
enum commit_action simplify_commit(struct rev_info *revs, struct commit *commit)
{
enum commit_action action = get_commit_action(revs, commit);
if (action == commit_show &&
!revs->show_all &&
revs->prune && revs->dense && want_ancestry(revs)) {
/*
* --full-diff on simplified parents is no good: it
* will show spurious changes from the commits that
* were elided. So we save the parents on the side
* when --full-diff is in effect.
*/
if (revs->full_diff)
save_parents(revs, commit);
if (rewrite_parents(revs, commit, rewrite_one) < 0)
return commit_error;
}
return action;
}
static void track_linear(struct rev_info *revs, struct commit *commit)
{
if (revs->track_first_time) {
revs->linear = 1;
revs->track_first_time = 0;
} else {
struct commit_list *p;
for (p = revs->previous_parents; p; p = p->next)
if (p->item == NULL || /* first commit */
!oidcmp(&p->item->object.oid, &commit->object.oid))
break;
revs->linear = p != NULL;
}
if (revs->reverse) {
if (revs->linear)
commit->object.flags |= TRACK_LINEAR;
}
free_commit_list(revs->previous_parents);
revs->previous_parents = copy_commit_list(commit->parents);
}
static struct commit *get_revision_1(struct rev_info *revs)
{
if (!revs->commits)
return NULL;
do {
struct commit *commit = pop_commit(&revs->commits);
if (revs->reflog_info) {
save_parents(revs, commit);
fake_reflog_parent(revs->reflog_info, commit);
commit->object.flags &= ~(ADDED | SEEN | SHOWN);
}
/*
* If we haven't done the list limiting, we need to look at
* the parents here. We also need to do the date-based limiting
* that we'd otherwise have done in limit_list().
*/
if (!revs->limited) {
if (revs->max_age != -1 &&
(commit->date < revs->max_age))
continue;
if (add_parents_to_list(revs, commit, &revs->commits, NULL) < 0) {
if (!revs->ignore_missing_links)
die("Failed to traverse parents of commit %s",
oid_to_hex(&commit->object.oid));
}
}
switch (simplify_commit(revs, commit)) {
case commit_ignore:
continue;
case commit_error:
die("Failed to simplify parents of commit %s",
oid_to_hex(&commit->object.oid));
default:
if (revs->track_linear)
track_linear(revs, commit);
return commit;
}
} while (revs->commits);
return NULL;
}
/*
* Return true for entries that have not yet been shown. (This is an
* object_array_each_func_t.)
*/
static int entry_unshown(struct object_array_entry *entry, void *cb_data_unused)
{
return !(entry->item->flags & SHOWN);
}
/*
* If array is on the verge of a realloc, garbage-collect any entries
* that have already been shown to try to free up some space.
*/
static void gc_boundary(struct object_array *array)
{
if (array->nr == array->alloc)
object_array_filter(array, entry_unshown, NULL);
}
static void create_boundary_commit_list(struct rev_info *revs)
{
unsigned i;
struct commit *c;
struct object_array *array = &revs->boundary_commits;
struct object_array_entry *objects = array->objects;
/*
* If revs->commits is non-NULL at this point, an error occurred in
* get_revision_1(). Ignore the error and continue printing the
* boundary commits anyway. (This is what the code has always
* done.)
*/
if (revs->commits) {
free_commit_list(revs->commits);
revs->commits = NULL;
}
/*
* Put all of the actual boundary commits from revs->boundary_commits
* into revs->commits
*/
for (i = 0; i < array->nr; i++) {
c = (struct commit *)(objects[i].item);
if (!c)
continue;
if (!(c->object.flags & CHILD_SHOWN))
continue;
if (c->object.flags & (SHOWN | BOUNDARY))
continue;
c->object.flags |= BOUNDARY;
commit_list_insert(c, &revs->commits);
}
/*
* If revs->topo_order is set, sort the boundary commits
* in topological order
*/
sort_in_topological_order(&revs->commits, revs->sort_order);
}
static struct commit *get_revision_internal(struct rev_info *revs)
{
struct commit *c = NULL;
struct commit_list *l;
if (revs->boundary == 2) {
/*
* All of the normal commits have already been returned,
* and we are now returning boundary commits.
* create_boundary_commit_list() has populated
* revs->commits with the remaining commits to return.
*/
c = pop_commit(&revs->commits);
if (c)
c->object.flags |= SHOWN;
return c;
}
/*
* If our max_count counter has reached zero, then we are done. We
* don't simply return NULL because we still might need to show
* boundary commits. But we want to avoid calling get_revision_1, which
* might do a considerable amount of work finding the next commit only
* for us to throw it away.
*
* If it is non-zero, then either we don't have a max_count at all
* (-1), or it is still counting, in which case we decrement.
*/
if (revs->max_count) {
c = get_revision_1(revs);
if (c) {
while (revs->skip_count > 0) {
revs->skip_count--;
c = get_revision_1(revs);
if (!c)
break;
}
}
if (revs->max_count > 0)
revs->max_count--;
}
if (c)
c->object.flags |= SHOWN;
if (!revs->boundary)
return c;
if (!c) {
/*
* get_revision_1() runs out the commits, and
* we are done computing the boundaries.
* switch to boundary commits output mode.
*/
revs->boundary = 2;
/*
* Update revs->commits to contain the list of
* boundary commits.
*/
create_boundary_commit_list(revs);
return get_revision_internal(revs);
}
/*
* boundary commits are the commits that are parents of the
* ones we got from get_revision_1() but they themselves are
* not returned from get_revision_1(). Before returning
* 'c', we need to mark its parents that they could be boundaries.
*/
for (l = c->parents; l; l = l->next) {
struct object *p;
p = &(l->item->object);
if (p->flags & (CHILD_SHOWN | SHOWN))
continue;
p->flags |= CHILD_SHOWN;
gc_boundary(&revs->boundary_commits);
add_object_array(p, NULL, &revs->boundary_commits);
}
return c;
}
struct commit *get_revision(struct rev_info *revs)
{
struct commit *c;
struct commit_list *reversed;
if (revs->reverse) {
reversed = NULL;
while ((c = get_revision_internal(revs)))
commit_list_insert(c, &reversed);
revs->commits = reversed;
revs->reverse = 0;
revs->reverse_output_stage = 1;
}
if (revs->reverse_output_stage) {
c = pop_commit(&revs->commits);
if (revs->track_linear)
revs->linear = !!(c && c->object.flags & TRACK_LINEAR);
return c;
}
c = get_revision_internal(revs);
if (c && revs->graph)
graph_update(revs->graph, c);
if (!c) {
free_saved_parents(revs);
if (revs->previous_parents) {
free_commit_list(revs->previous_parents);
revs->previous_parents = NULL;
}
}
return c;
}
char *get_revision_mark(const struct rev_info *revs, const struct commit *commit)
{
if (commit->object.flags & BOUNDARY)
return "-";
else if (commit->object.flags & UNINTERESTING)
return "^";
else if (commit->object.flags & PATCHSAME)
return "=";
else if (!revs || revs->left_right) {
if (commit->object.flags & SYMMETRIC_LEFT)
return "<";
else
return ">";
} else if (revs->graph)
return "*";
else if (revs->cherry_mark)
return "+";
return "";
}
void put_revision_mark(const struct rev_info *revs, const struct commit *commit)
{
char *mark = get_revision_mark(revs, commit);
if (!strlen(mark))
return;
fputs(mark, stdout);
putchar(' ');
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4946_7 |
crossvul-cpp_data_good_3503_0 | /*
FUSE: Filesystem in Userspace
Copyright (C) 2001-2008 Miklos Szeredi <miklos@szeredi.hu>
This program can be distributed under the terms of the GNU GPL.
See the file COPYING.
*/
#include "fuse_i.h"
#include <linux/init.h>
#include <linux/module.h>
#include <linux/poll.h>
#include <linux/uio.h>
#include <linux/miscdevice.h>
#include <linux/pagemap.h>
#include <linux/file.h>
#include <linux/slab.h>
#include <linux/pipe_fs_i.h>
#include <linux/swap.h>
#include <linux/splice.h>
MODULE_ALIAS_MISCDEV(FUSE_MINOR);
MODULE_ALIAS("devname:fuse");
static struct kmem_cache *fuse_req_cachep;
static struct fuse_conn *fuse_get_conn(struct file *file)
{
/*
* Lockless access is OK, because file->private data is set
* once during mount and is valid until the file is released.
*/
return file->private_data;
}
static void fuse_request_init(struct fuse_req *req)
{
memset(req, 0, sizeof(*req));
INIT_LIST_HEAD(&req->list);
INIT_LIST_HEAD(&req->intr_entry);
init_waitqueue_head(&req->waitq);
atomic_set(&req->count, 1);
}
struct fuse_req *fuse_request_alloc(void)
{
struct fuse_req *req = kmem_cache_alloc(fuse_req_cachep, GFP_KERNEL);
if (req)
fuse_request_init(req);
return req;
}
EXPORT_SYMBOL_GPL(fuse_request_alloc);
struct fuse_req *fuse_request_alloc_nofs(void)
{
struct fuse_req *req = kmem_cache_alloc(fuse_req_cachep, GFP_NOFS);
if (req)
fuse_request_init(req);
return req;
}
void fuse_request_free(struct fuse_req *req)
{
kmem_cache_free(fuse_req_cachep, req);
}
static void block_sigs(sigset_t *oldset)
{
sigset_t mask;
siginitsetinv(&mask, sigmask(SIGKILL));
sigprocmask(SIG_BLOCK, &mask, oldset);
}
static void restore_sigs(sigset_t *oldset)
{
sigprocmask(SIG_SETMASK, oldset, NULL);
}
static void __fuse_get_request(struct fuse_req *req)
{
atomic_inc(&req->count);
}
/* Must be called with > 1 refcount */
static void __fuse_put_request(struct fuse_req *req)
{
BUG_ON(atomic_read(&req->count) < 2);
atomic_dec(&req->count);
}
static void fuse_req_init_context(struct fuse_req *req)
{
req->in.h.uid = current_fsuid();
req->in.h.gid = current_fsgid();
req->in.h.pid = current->pid;
}
struct fuse_req *fuse_get_req(struct fuse_conn *fc)
{
struct fuse_req *req;
sigset_t oldset;
int intr;
int err;
atomic_inc(&fc->num_waiting);
block_sigs(&oldset);
intr = wait_event_interruptible(fc->blocked_waitq, !fc->blocked);
restore_sigs(&oldset);
err = -EINTR;
if (intr)
goto out;
err = -ENOTCONN;
if (!fc->connected)
goto out;
req = fuse_request_alloc();
err = -ENOMEM;
if (!req)
goto out;
fuse_req_init_context(req);
req->waiting = 1;
return req;
out:
atomic_dec(&fc->num_waiting);
return ERR_PTR(err);
}
EXPORT_SYMBOL_GPL(fuse_get_req);
/*
* Return request in fuse_file->reserved_req. However that may
* currently be in use. If that is the case, wait for it to become
* available.
*/
static struct fuse_req *get_reserved_req(struct fuse_conn *fc,
struct file *file)
{
struct fuse_req *req = NULL;
struct fuse_file *ff = file->private_data;
do {
wait_event(fc->reserved_req_waitq, ff->reserved_req);
spin_lock(&fc->lock);
if (ff->reserved_req) {
req = ff->reserved_req;
ff->reserved_req = NULL;
get_file(file);
req->stolen_file = file;
}
spin_unlock(&fc->lock);
} while (!req);
return req;
}
/*
* Put stolen request back into fuse_file->reserved_req
*/
static void put_reserved_req(struct fuse_conn *fc, struct fuse_req *req)
{
struct file *file = req->stolen_file;
struct fuse_file *ff = file->private_data;
spin_lock(&fc->lock);
fuse_request_init(req);
BUG_ON(ff->reserved_req);
ff->reserved_req = req;
wake_up_all(&fc->reserved_req_waitq);
spin_unlock(&fc->lock);
fput(file);
}
/*
* Gets a requests for a file operation, always succeeds
*
* This is used for sending the FLUSH request, which must get to
* userspace, due to POSIX locks which may need to be unlocked.
*
* If allocation fails due to OOM, use the reserved request in
* fuse_file.
*
* This is very unlikely to deadlock accidentally, since the
* filesystem should not have it's own file open. If deadlock is
* intentional, it can still be broken by "aborting" the filesystem.
*/
struct fuse_req *fuse_get_req_nofail(struct fuse_conn *fc, struct file *file)
{
struct fuse_req *req;
atomic_inc(&fc->num_waiting);
wait_event(fc->blocked_waitq, !fc->blocked);
req = fuse_request_alloc();
if (!req)
req = get_reserved_req(fc, file);
fuse_req_init_context(req);
req->waiting = 1;
return req;
}
void fuse_put_request(struct fuse_conn *fc, struct fuse_req *req)
{
if (atomic_dec_and_test(&req->count)) {
if (req->waiting)
atomic_dec(&fc->num_waiting);
if (req->stolen_file)
put_reserved_req(fc, req);
else
fuse_request_free(req);
}
}
EXPORT_SYMBOL_GPL(fuse_put_request);
static unsigned len_args(unsigned numargs, struct fuse_arg *args)
{
unsigned nbytes = 0;
unsigned i;
for (i = 0; i < numargs; i++)
nbytes += args[i].size;
return nbytes;
}
static u64 fuse_get_unique(struct fuse_conn *fc)
{
fc->reqctr++;
/* zero is special */
if (fc->reqctr == 0)
fc->reqctr = 1;
return fc->reqctr;
}
static void queue_request(struct fuse_conn *fc, struct fuse_req *req)
{
req->in.h.len = sizeof(struct fuse_in_header) +
len_args(req->in.numargs, (struct fuse_arg *) req->in.args);
list_add_tail(&req->list, &fc->pending);
req->state = FUSE_REQ_PENDING;
if (!req->waiting) {
req->waiting = 1;
atomic_inc(&fc->num_waiting);
}
wake_up(&fc->waitq);
kill_fasync(&fc->fasync, SIGIO, POLL_IN);
}
void fuse_queue_forget(struct fuse_conn *fc, struct fuse_forget_link *forget,
u64 nodeid, u64 nlookup)
{
forget->forget_one.nodeid = nodeid;
forget->forget_one.nlookup = nlookup;
spin_lock(&fc->lock);
fc->forget_list_tail->next = forget;
fc->forget_list_tail = forget;
wake_up(&fc->waitq);
kill_fasync(&fc->fasync, SIGIO, POLL_IN);
spin_unlock(&fc->lock);
}
static void flush_bg_queue(struct fuse_conn *fc)
{
while (fc->active_background < fc->max_background &&
!list_empty(&fc->bg_queue)) {
struct fuse_req *req;
req = list_entry(fc->bg_queue.next, struct fuse_req, list);
list_del(&req->list);
fc->active_background++;
req->in.h.unique = fuse_get_unique(fc);
queue_request(fc, req);
}
}
/*
* This function is called when a request is finished. Either a reply
* has arrived or it was aborted (and not yet sent) or some error
* occurred during communication with userspace, or the device file
* was closed. The requester thread is woken up (if still waiting),
* the 'end' callback is called if given, else the reference to the
* request is released
*
* Called with fc->lock, unlocks it
*/
static void request_end(struct fuse_conn *fc, struct fuse_req *req)
__releases(fc->lock)
{
void (*end) (struct fuse_conn *, struct fuse_req *) = req->end;
req->end = NULL;
list_del(&req->list);
list_del(&req->intr_entry);
req->state = FUSE_REQ_FINISHED;
if (req->background) {
if (fc->num_background == fc->max_background) {
fc->blocked = 0;
wake_up_all(&fc->blocked_waitq);
}
if (fc->num_background == fc->congestion_threshold &&
fc->connected && fc->bdi_initialized) {
clear_bdi_congested(&fc->bdi, BLK_RW_SYNC);
clear_bdi_congested(&fc->bdi, BLK_RW_ASYNC);
}
fc->num_background--;
fc->active_background--;
flush_bg_queue(fc);
}
spin_unlock(&fc->lock);
wake_up(&req->waitq);
if (end)
end(fc, req);
fuse_put_request(fc, req);
}
static void wait_answer_interruptible(struct fuse_conn *fc,
struct fuse_req *req)
__releases(fc->lock)
__acquires(fc->lock)
{
if (signal_pending(current))
return;
spin_unlock(&fc->lock);
wait_event_interruptible(req->waitq, req->state == FUSE_REQ_FINISHED);
spin_lock(&fc->lock);
}
static void queue_interrupt(struct fuse_conn *fc, struct fuse_req *req)
{
list_add_tail(&req->intr_entry, &fc->interrupts);
wake_up(&fc->waitq);
kill_fasync(&fc->fasync, SIGIO, POLL_IN);
}
static void request_wait_answer(struct fuse_conn *fc, struct fuse_req *req)
__releases(fc->lock)
__acquires(fc->lock)
{
if (!fc->no_interrupt) {
/* Any signal may interrupt this */
wait_answer_interruptible(fc, req);
if (req->aborted)
goto aborted;
if (req->state == FUSE_REQ_FINISHED)
return;
req->interrupted = 1;
if (req->state == FUSE_REQ_SENT)
queue_interrupt(fc, req);
}
if (!req->force) {
sigset_t oldset;
/* Only fatal signals may interrupt this */
block_sigs(&oldset);
wait_answer_interruptible(fc, req);
restore_sigs(&oldset);
if (req->aborted)
goto aborted;
if (req->state == FUSE_REQ_FINISHED)
return;
/* Request is not yet in userspace, bail out */
if (req->state == FUSE_REQ_PENDING) {
list_del(&req->list);
__fuse_put_request(req);
req->out.h.error = -EINTR;
return;
}
}
/*
* Either request is already in userspace, or it was forced.
* Wait it out.
*/
spin_unlock(&fc->lock);
wait_event(req->waitq, req->state == FUSE_REQ_FINISHED);
spin_lock(&fc->lock);
if (!req->aborted)
return;
aborted:
BUG_ON(req->state != FUSE_REQ_FINISHED);
if (req->locked) {
/* This is uninterruptible sleep, because data is
being copied to/from the buffers of req. During
locked state, there mustn't be any filesystem
operation (e.g. page fault), since that could lead
to deadlock */
spin_unlock(&fc->lock);
wait_event(req->waitq, !req->locked);
spin_lock(&fc->lock);
}
}
void fuse_request_send(struct fuse_conn *fc, struct fuse_req *req)
{
req->isreply = 1;
spin_lock(&fc->lock);
if (!fc->connected)
req->out.h.error = -ENOTCONN;
else if (fc->conn_error)
req->out.h.error = -ECONNREFUSED;
else {
req->in.h.unique = fuse_get_unique(fc);
queue_request(fc, req);
/* acquire extra reference, since request is still needed
after request_end() */
__fuse_get_request(req);
request_wait_answer(fc, req);
}
spin_unlock(&fc->lock);
}
EXPORT_SYMBOL_GPL(fuse_request_send);
static void fuse_request_send_nowait_locked(struct fuse_conn *fc,
struct fuse_req *req)
{
req->background = 1;
fc->num_background++;
if (fc->num_background == fc->max_background)
fc->blocked = 1;
if (fc->num_background == fc->congestion_threshold &&
fc->bdi_initialized) {
set_bdi_congested(&fc->bdi, BLK_RW_SYNC);
set_bdi_congested(&fc->bdi, BLK_RW_ASYNC);
}
list_add_tail(&req->list, &fc->bg_queue);
flush_bg_queue(fc);
}
static void fuse_request_send_nowait(struct fuse_conn *fc, struct fuse_req *req)
{
spin_lock(&fc->lock);
if (fc->connected) {
fuse_request_send_nowait_locked(fc, req);
spin_unlock(&fc->lock);
} else {
req->out.h.error = -ENOTCONN;
request_end(fc, req);
}
}
void fuse_request_send_background(struct fuse_conn *fc, struct fuse_req *req)
{
req->isreply = 1;
fuse_request_send_nowait(fc, req);
}
EXPORT_SYMBOL_GPL(fuse_request_send_background);
static int fuse_request_send_notify_reply(struct fuse_conn *fc,
struct fuse_req *req, u64 unique)
{
int err = -ENODEV;
req->isreply = 0;
req->in.h.unique = unique;
spin_lock(&fc->lock);
if (fc->connected) {
queue_request(fc, req);
err = 0;
}
spin_unlock(&fc->lock);
return err;
}
/*
* Called under fc->lock
*
* fc->connected must have been checked previously
*/
void fuse_request_send_background_locked(struct fuse_conn *fc,
struct fuse_req *req)
{
req->isreply = 1;
fuse_request_send_nowait_locked(fc, req);
}
/*
* Lock the request. Up to the next unlock_request() there mustn't be
* anything that could cause a page-fault. If the request was already
* aborted bail out.
*/
static int lock_request(struct fuse_conn *fc, struct fuse_req *req)
{
int err = 0;
if (req) {
spin_lock(&fc->lock);
if (req->aborted)
err = -ENOENT;
else
req->locked = 1;
spin_unlock(&fc->lock);
}
return err;
}
/*
* Unlock request. If it was aborted during being locked, the
* requester thread is currently waiting for it to be unlocked, so
* wake it up.
*/
static void unlock_request(struct fuse_conn *fc, struct fuse_req *req)
{
if (req) {
spin_lock(&fc->lock);
req->locked = 0;
if (req->aborted)
wake_up(&req->waitq);
spin_unlock(&fc->lock);
}
}
struct fuse_copy_state {
struct fuse_conn *fc;
int write;
struct fuse_req *req;
const struct iovec *iov;
struct pipe_buffer *pipebufs;
struct pipe_buffer *currbuf;
struct pipe_inode_info *pipe;
unsigned long nr_segs;
unsigned long seglen;
unsigned long addr;
struct page *pg;
void *mapaddr;
void *buf;
unsigned len;
unsigned move_pages:1;
};
static void fuse_copy_init(struct fuse_copy_state *cs, struct fuse_conn *fc,
int write,
const struct iovec *iov, unsigned long nr_segs)
{
memset(cs, 0, sizeof(*cs));
cs->fc = fc;
cs->write = write;
cs->iov = iov;
cs->nr_segs = nr_segs;
}
/* Unmap and put previous page of userspace buffer */
static void fuse_copy_finish(struct fuse_copy_state *cs)
{
if (cs->currbuf) {
struct pipe_buffer *buf = cs->currbuf;
if (!cs->write) {
buf->ops->unmap(cs->pipe, buf, cs->mapaddr);
} else {
kunmap(buf->page);
buf->len = PAGE_SIZE - cs->len;
}
cs->currbuf = NULL;
cs->mapaddr = NULL;
} else if (cs->mapaddr) {
kunmap(cs->pg);
if (cs->write) {
flush_dcache_page(cs->pg);
set_page_dirty_lock(cs->pg);
}
put_page(cs->pg);
cs->mapaddr = NULL;
}
}
/*
* Get another pagefull of userspace buffer, and map it to kernel
* address space, and lock request
*/
static int fuse_copy_fill(struct fuse_copy_state *cs)
{
unsigned long offset;
int err;
unlock_request(cs->fc, cs->req);
fuse_copy_finish(cs);
if (cs->pipebufs) {
struct pipe_buffer *buf = cs->pipebufs;
if (!cs->write) {
err = buf->ops->confirm(cs->pipe, buf);
if (err)
return err;
BUG_ON(!cs->nr_segs);
cs->currbuf = buf;
cs->mapaddr = buf->ops->map(cs->pipe, buf, 0);
cs->len = buf->len;
cs->buf = cs->mapaddr + buf->offset;
cs->pipebufs++;
cs->nr_segs--;
} else {
struct page *page;
if (cs->nr_segs == cs->pipe->buffers)
return -EIO;
page = alloc_page(GFP_HIGHUSER);
if (!page)
return -ENOMEM;
buf->page = page;
buf->offset = 0;
buf->len = 0;
cs->currbuf = buf;
cs->mapaddr = kmap(page);
cs->buf = cs->mapaddr;
cs->len = PAGE_SIZE;
cs->pipebufs++;
cs->nr_segs++;
}
} else {
if (!cs->seglen) {
BUG_ON(!cs->nr_segs);
cs->seglen = cs->iov[0].iov_len;
cs->addr = (unsigned long) cs->iov[0].iov_base;
cs->iov++;
cs->nr_segs--;
}
err = get_user_pages_fast(cs->addr, 1, cs->write, &cs->pg);
if (err < 0)
return err;
BUG_ON(err != 1);
offset = cs->addr % PAGE_SIZE;
cs->mapaddr = kmap(cs->pg);
cs->buf = cs->mapaddr + offset;
cs->len = min(PAGE_SIZE - offset, cs->seglen);
cs->seglen -= cs->len;
cs->addr += cs->len;
}
return lock_request(cs->fc, cs->req);
}
/* Do as much copy to/from userspace buffer as we can */
static int fuse_copy_do(struct fuse_copy_state *cs, void **val, unsigned *size)
{
unsigned ncpy = min(*size, cs->len);
if (val) {
if (cs->write)
memcpy(cs->buf, *val, ncpy);
else
memcpy(*val, cs->buf, ncpy);
*val += ncpy;
}
*size -= ncpy;
cs->len -= ncpy;
cs->buf += ncpy;
return ncpy;
}
static int fuse_check_page(struct page *page)
{
if (page_mapcount(page) ||
page->mapping != NULL ||
page_count(page) != 1 ||
(page->flags & PAGE_FLAGS_CHECK_AT_PREP &
~(1 << PG_locked |
1 << PG_referenced |
1 << PG_uptodate |
1 << PG_lru |
1 << PG_active |
1 << PG_reclaim))) {
printk(KERN_WARNING "fuse: trying to steal weird page\n");
printk(KERN_WARNING " page=%p index=%li flags=%08lx, count=%i, mapcount=%i, mapping=%p\n", page, page->index, page->flags, page_count(page), page_mapcount(page), page->mapping);
return 1;
}
return 0;
}
static int fuse_try_move_page(struct fuse_copy_state *cs, struct page **pagep)
{
int err;
struct page *oldpage = *pagep;
struct page *newpage;
struct pipe_buffer *buf = cs->pipebufs;
struct address_space *mapping;
pgoff_t index;
unlock_request(cs->fc, cs->req);
fuse_copy_finish(cs);
err = buf->ops->confirm(cs->pipe, buf);
if (err)
return err;
BUG_ON(!cs->nr_segs);
cs->currbuf = buf;
cs->len = buf->len;
cs->pipebufs++;
cs->nr_segs--;
if (cs->len != PAGE_SIZE)
goto out_fallback;
if (buf->ops->steal(cs->pipe, buf) != 0)
goto out_fallback;
newpage = buf->page;
if (WARN_ON(!PageUptodate(newpage)))
return -EIO;
ClearPageMappedToDisk(newpage);
if (fuse_check_page(newpage) != 0)
goto out_fallback_unlock;
mapping = oldpage->mapping;
index = oldpage->index;
/*
* This is a new and locked page, it shouldn't be mapped or
* have any special flags on it
*/
if (WARN_ON(page_mapped(oldpage)))
goto out_fallback_unlock;
if (WARN_ON(page_has_private(oldpage)))
goto out_fallback_unlock;
if (WARN_ON(PageDirty(oldpage) || PageWriteback(oldpage)))
goto out_fallback_unlock;
if (WARN_ON(PageMlocked(oldpage)))
goto out_fallback_unlock;
err = replace_page_cache_page(oldpage, newpage, GFP_KERNEL);
if (err) {
unlock_page(newpage);
return err;
}
page_cache_get(newpage);
if (!(buf->flags & PIPE_BUF_FLAG_LRU))
lru_cache_add_file(newpage);
err = 0;
spin_lock(&cs->fc->lock);
if (cs->req->aborted)
err = -ENOENT;
else
*pagep = newpage;
spin_unlock(&cs->fc->lock);
if (err) {
unlock_page(newpage);
page_cache_release(newpage);
return err;
}
unlock_page(oldpage);
page_cache_release(oldpage);
cs->len = 0;
return 0;
out_fallback_unlock:
unlock_page(newpage);
out_fallback:
cs->mapaddr = buf->ops->map(cs->pipe, buf, 1);
cs->buf = cs->mapaddr + buf->offset;
err = lock_request(cs->fc, cs->req);
if (err)
return err;
return 1;
}
static int fuse_ref_page(struct fuse_copy_state *cs, struct page *page,
unsigned offset, unsigned count)
{
struct pipe_buffer *buf;
if (cs->nr_segs == cs->pipe->buffers)
return -EIO;
unlock_request(cs->fc, cs->req);
fuse_copy_finish(cs);
buf = cs->pipebufs;
page_cache_get(page);
buf->page = page;
buf->offset = offset;
buf->len = count;
cs->pipebufs++;
cs->nr_segs++;
cs->len = 0;
return 0;
}
/*
* Copy a page in the request to/from the userspace buffer. Must be
* done atomically
*/
static int fuse_copy_page(struct fuse_copy_state *cs, struct page **pagep,
unsigned offset, unsigned count, int zeroing)
{
int err;
struct page *page = *pagep;
if (page && zeroing && count < PAGE_SIZE)
clear_highpage(page);
while (count) {
if (cs->write && cs->pipebufs && page) {
return fuse_ref_page(cs, page, offset, count);
} else if (!cs->len) {
if (cs->move_pages && page &&
offset == 0 && count == PAGE_SIZE) {
err = fuse_try_move_page(cs, pagep);
if (err <= 0)
return err;
} else {
err = fuse_copy_fill(cs);
if (err)
return err;
}
}
if (page) {
void *mapaddr = kmap_atomic(page, KM_USER0);
void *buf = mapaddr + offset;
offset += fuse_copy_do(cs, &buf, &count);
kunmap_atomic(mapaddr, KM_USER0);
} else
offset += fuse_copy_do(cs, NULL, &count);
}
if (page && !cs->write)
flush_dcache_page(page);
return 0;
}
/* Copy pages in the request to/from userspace buffer */
static int fuse_copy_pages(struct fuse_copy_state *cs, unsigned nbytes,
int zeroing)
{
unsigned i;
struct fuse_req *req = cs->req;
unsigned offset = req->page_offset;
unsigned count = min(nbytes, (unsigned) PAGE_SIZE - offset);
for (i = 0; i < req->num_pages && (nbytes || zeroing); i++) {
int err;
err = fuse_copy_page(cs, &req->pages[i], offset, count,
zeroing);
if (err)
return err;
nbytes -= count;
count = min(nbytes, (unsigned) PAGE_SIZE);
offset = 0;
}
return 0;
}
/* Copy a single argument in the request to/from userspace buffer */
static int fuse_copy_one(struct fuse_copy_state *cs, void *val, unsigned size)
{
while (size) {
if (!cs->len) {
int err = fuse_copy_fill(cs);
if (err)
return err;
}
fuse_copy_do(cs, &val, &size);
}
return 0;
}
/* Copy request arguments to/from userspace buffer */
static int fuse_copy_args(struct fuse_copy_state *cs, unsigned numargs,
unsigned argpages, struct fuse_arg *args,
int zeroing)
{
int err = 0;
unsigned i;
for (i = 0; !err && i < numargs; i++) {
struct fuse_arg *arg = &args[i];
if (i == numargs - 1 && argpages)
err = fuse_copy_pages(cs, arg->size, zeroing);
else
err = fuse_copy_one(cs, arg->value, arg->size);
}
return err;
}
static int forget_pending(struct fuse_conn *fc)
{
return fc->forget_list_head.next != NULL;
}
static int request_pending(struct fuse_conn *fc)
{
return !list_empty(&fc->pending) || !list_empty(&fc->interrupts) ||
forget_pending(fc);
}
/* Wait until a request is available on the pending list */
static void request_wait(struct fuse_conn *fc)
__releases(fc->lock)
__acquires(fc->lock)
{
DECLARE_WAITQUEUE(wait, current);
add_wait_queue_exclusive(&fc->waitq, &wait);
while (fc->connected && !request_pending(fc)) {
set_current_state(TASK_INTERRUPTIBLE);
if (signal_pending(current))
break;
spin_unlock(&fc->lock);
schedule();
spin_lock(&fc->lock);
}
set_current_state(TASK_RUNNING);
remove_wait_queue(&fc->waitq, &wait);
}
/*
* Transfer an interrupt request to userspace
*
* Unlike other requests this is assembled on demand, without a need
* to allocate a separate fuse_req structure.
*
* Called with fc->lock held, releases it
*/
static int fuse_read_interrupt(struct fuse_conn *fc, struct fuse_copy_state *cs,
size_t nbytes, struct fuse_req *req)
__releases(fc->lock)
{
struct fuse_in_header ih;
struct fuse_interrupt_in arg;
unsigned reqsize = sizeof(ih) + sizeof(arg);
int err;
list_del_init(&req->intr_entry);
req->intr_unique = fuse_get_unique(fc);
memset(&ih, 0, sizeof(ih));
memset(&arg, 0, sizeof(arg));
ih.len = reqsize;
ih.opcode = FUSE_INTERRUPT;
ih.unique = req->intr_unique;
arg.unique = req->in.h.unique;
spin_unlock(&fc->lock);
if (nbytes < reqsize)
return -EINVAL;
err = fuse_copy_one(cs, &ih, sizeof(ih));
if (!err)
err = fuse_copy_one(cs, &arg, sizeof(arg));
fuse_copy_finish(cs);
return err ? err : reqsize;
}
static struct fuse_forget_link *dequeue_forget(struct fuse_conn *fc,
unsigned max,
unsigned *countp)
{
struct fuse_forget_link *head = fc->forget_list_head.next;
struct fuse_forget_link **newhead = &head;
unsigned count;
for (count = 0; *newhead != NULL && count < max; count++)
newhead = &(*newhead)->next;
fc->forget_list_head.next = *newhead;
*newhead = NULL;
if (fc->forget_list_head.next == NULL)
fc->forget_list_tail = &fc->forget_list_head;
if (countp != NULL)
*countp = count;
return head;
}
static int fuse_read_single_forget(struct fuse_conn *fc,
struct fuse_copy_state *cs,
size_t nbytes)
__releases(fc->lock)
{
int err;
struct fuse_forget_link *forget = dequeue_forget(fc, 1, NULL);
struct fuse_forget_in arg = {
.nlookup = forget->forget_one.nlookup,
};
struct fuse_in_header ih = {
.opcode = FUSE_FORGET,
.nodeid = forget->forget_one.nodeid,
.unique = fuse_get_unique(fc),
.len = sizeof(ih) + sizeof(arg),
};
spin_unlock(&fc->lock);
kfree(forget);
if (nbytes < ih.len)
return -EINVAL;
err = fuse_copy_one(cs, &ih, sizeof(ih));
if (!err)
err = fuse_copy_one(cs, &arg, sizeof(arg));
fuse_copy_finish(cs);
if (err)
return err;
return ih.len;
}
static int fuse_read_batch_forget(struct fuse_conn *fc,
struct fuse_copy_state *cs, size_t nbytes)
__releases(fc->lock)
{
int err;
unsigned max_forgets;
unsigned count;
struct fuse_forget_link *head;
struct fuse_batch_forget_in arg = { .count = 0 };
struct fuse_in_header ih = {
.opcode = FUSE_BATCH_FORGET,
.unique = fuse_get_unique(fc),
.len = sizeof(ih) + sizeof(arg),
};
if (nbytes < ih.len) {
spin_unlock(&fc->lock);
return -EINVAL;
}
max_forgets = (nbytes - ih.len) / sizeof(struct fuse_forget_one);
head = dequeue_forget(fc, max_forgets, &count);
spin_unlock(&fc->lock);
arg.count = count;
ih.len += count * sizeof(struct fuse_forget_one);
err = fuse_copy_one(cs, &ih, sizeof(ih));
if (!err)
err = fuse_copy_one(cs, &arg, sizeof(arg));
while (head) {
struct fuse_forget_link *forget = head;
if (!err) {
err = fuse_copy_one(cs, &forget->forget_one,
sizeof(forget->forget_one));
}
head = forget->next;
kfree(forget);
}
fuse_copy_finish(cs);
if (err)
return err;
return ih.len;
}
static int fuse_read_forget(struct fuse_conn *fc, struct fuse_copy_state *cs,
size_t nbytes)
__releases(fc->lock)
{
if (fc->minor < 16 || fc->forget_list_head.next->next == NULL)
return fuse_read_single_forget(fc, cs, nbytes);
else
return fuse_read_batch_forget(fc, cs, nbytes);
}
/*
* Read a single request into the userspace filesystem's buffer. This
* function waits until a request is available, then removes it from
* the pending list and copies request data to userspace buffer. If
* no reply is needed (FORGET) or request has been aborted or there
* was an error during the copying then it's finished by calling
* request_end(). Otherwise add it to the processing list, and set
* the 'sent' flag.
*/
static ssize_t fuse_dev_do_read(struct fuse_conn *fc, struct file *file,
struct fuse_copy_state *cs, size_t nbytes)
{
int err;
struct fuse_req *req;
struct fuse_in *in;
unsigned reqsize;
restart:
spin_lock(&fc->lock);
err = -EAGAIN;
if ((file->f_flags & O_NONBLOCK) && fc->connected &&
!request_pending(fc))
goto err_unlock;
request_wait(fc);
err = -ENODEV;
if (!fc->connected)
goto err_unlock;
err = -ERESTARTSYS;
if (!request_pending(fc))
goto err_unlock;
if (!list_empty(&fc->interrupts)) {
req = list_entry(fc->interrupts.next, struct fuse_req,
intr_entry);
return fuse_read_interrupt(fc, cs, nbytes, req);
}
if (forget_pending(fc)) {
if (list_empty(&fc->pending) || fc->forget_batch-- > 0)
return fuse_read_forget(fc, cs, nbytes);
if (fc->forget_batch <= -8)
fc->forget_batch = 16;
}
req = list_entry(fc->pending.next, struct fuse_req, list);
req->state = FUSE_REQ_READING;
list_move(&req->list, &fc->io);
in = &req->in;
reqsize = in->h.len;
/* If request is too large, reply with an error and restart the read */
if (nbytes < reqsize) {
req->out.h.error = -EIO;
/* SETXATTR is special, since it may contain too large data */
if (in->h.opcode == FUSE_SETXATTR)
req->out.h.error = -E2BIG;
request_end(fc, req);
goto restart;
}
spin_unlock(&fc->lock);
cs->req = req;
err = fuse_copy_one(cs, &in->h, sizeof(in->h));
if (!err)
err = fuse_copy_args(cs, in->numargs, in->argpages,
(struct fuse_arg *) in->args, 0);
fuse_copy_finish(cs);
spin_lock(&fc->lock);
req->locked = 0;
if (req->aborted) {
request_end(fc, req);
return -ENODEV;
}
if (err) {
req->out.h.error = -EIO;
request_end(fc, req);
return err;
}
if (!req->isreply)
request_end(fc, req);
else {
req->state = FUSE_REQ_SENT;
list_move_tail(&req->list, &fc->processing);
if (req->interrupted)
queue_interrupt(fc, req);
spin_unlock(&fc->lock);
}
return reqsize;
err_unlock:
spin_unlock(&fc->lock);
return err;
}
static ssize_t fuse_dev_read(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t pos)
{
struct fuse_copy_state cs;
struct file *file = iocb->ki_filp;
struct fuse_conn *fc = fuse_get_conn(file);
if (!fc)
return -EPERM;
fuse_copy_init(&cs, fc, 1, iov, nr_segs);
return fuse_dev_do_read(fc, file, &cs, iov_length(iov, nr_segs));
}
static int fuse_dev_pipe_buf_steal(struct pipe_inode_info *pipe,
struct pipe_buffer *buf)
{
return 1;
}
static const struct pipe_buf_operations fuse_dev_pipe_buf_ops = {
.can_merge = 0,
.map = generic_pipe_buf_map,
.unmap = generic_pipe_buf_unmap,
.confirm = generic_pipe_buf_confirm,
.release = generic_pipe_buf_release,
.steal = fuse_dev_pipe_buf_steal,
.get = generic_pipe_buf_get,
};
static ssize_t fuse_dev_splice_read(struct file *in, loff_t *ppos,
struct pipe_inode_info *pipe,
size_t len, unsigned int flags)
{
int ret;
int page_nr = 0;
int do_wakeup = 0;
struct pipe_buffer *bufs;
struct fuse_copy_state cs;
struct fuse_conn *fc = fuse_get_conn(in);
if (!fc)
return -EPERM;
bufs = kmalloc(pipe->buffers * sizeof(struct pipe_buffer), GFP_KERNEL);
if (!bufs)
return -ENOMEM;
fuse_copy_init(&cs, fc, 1, NULL, 0);
cs.pipebufs = bufs;
cs.pipe = pipe;
ret = fuse_dev_do_read(fc, in, &cs, len);
if (ret < 0)
goto out;
ret = 0;
pipe_lock(pipe);
if (!pipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
goto out_unlock;
}
if (pipe->nrbufs + cs.nr_segs > pipe->buffers) {
ret = -EIO;
goto out_unlock;
}
while (page_nr < cs.nr_segs) {
int newbuf = (pipe->curbuf + pipe->nrbufs) & (pipe->buffers - 1);
struct pipe_buffer *buf = pipe->bufs + newbuf;
buf->page = bufs[page_nr].page;
buf->offset = bufs[page_nr].offset;
buf->len = bufs[page_nr].len;
buf->ops = &fuse_dev_pipe_buf_ops;
pipe->nrbufs++;
page_nr++;
ret += buf->len;
if (pipe->inode)
do_wakeup = 1;
}
out_unlock:
pipe_unlock(pipe);
if (do_wakeup) {
smp_mb();
if (waitqueue_active(&pipe->wait))
wake_up_interruptible(&pipe->wait);
kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
}
out:
for (; page_nr < cs.nr_segs; page_nr++)
page_cache_release(bufs[page_nr].page);
kfree(bufs);
return ret;
}
static int fuse_notify_poll(struct fuse_conn *fc, unsigned int size,
struct fuse_copy_state *cs)
{
struct fuse_notify_poll_wakeup_out outarg;
int err = -EINVAL;
if (size != sizeof(outarg))
goto err;
err = fuse_copy_one(cs, &outarg, sizeof(outarg));
if (err)
goto err;
fuse_copy_finish(cs);
return fuse_notify_poll_wakeup(fc, &outarg);
err:
fuse_copy_finish(cs);
return err;
}
static int fuse_notify_inval_inode(struct fuse_conn *fc, unsigned int size,
struct fuse_copy_state *cs)
{
struct fuse_notify_inval_inode_out outarg;
int err = -EINVAL;
if (size != sizeof(outarg))
goto err;
err = fuse_copy_one(cs, &outarg, sizeof(outarg));
if (err)
goto err;
fuse_copy_finish(cs);
down_read(&fc->killsb);
err = -ENOENT;
if (fc->sb) {
err = fuse_reverse_inval_inode(fc->sb, outarg.ino,
outarg.off, outarg.len);
}
up_read(&fc->killsb);
return err;
err:
fuse_copy_finish(cs);
return err;
}
static int fuse_notify_inval_entry(struct fuse_conn *fc, unsigned int size,
struct fuse_copy_state *cs)
{
struct fuse_notify_inval_entry_out outarg;
int err = -ENOMEM;
char *buf;
struct qstr name;
buf = kzalloc(FUSE_NAME_MAX + 1, GFP_KERNEL);
if (!buf)
goto err;
err = -EINVAL;
if (size < sizeof(outarg))
goto err;
err = fuse_copy_one(cs, &outarg, sizeof(outarg));
if (err)
goto err;
err = -ENAMETOOLONG;
if (outarg.namelen > FUSE_NAME_MAX)
goto err;
err = -EINVAL;
if (size != sizeof(outarg) + outarg.namelen + 1)
goto err;
name.name = buf;
name.len = outarg.namelen;
err = fuse_copy_one(cs, buf, outarg.namelen + 1);
if (err)
goto err;
fuse_copy_finish(cs);
buf[outarg.namelen] = 0;
name.hash = full_name_hash(name.name, name.len);
down_read(&fc->killsb);
err = -ENOENT;
if (fc->sb)
err = fuse_reverse_inval_entry(fc->sb, outarg.parent, &name);
up_read(&fc->killsb);
kfree(buf);
return err;
err:
kfree(buf);
fuse_copy_finish(cs);
return err;
}
static int fuse_notify_store(struct fuse_conn *fc, unsigned int size,
struct fuse_copy_state *cs)
{
struct fuse_notify_store_out outarg;
struct inode *inode;
struct address_space *mapping;
u64 nodeid;
int err;
pgoff_t index;
unsigned int offset;
unsigned int num;
loff_t file_size;
loff_t end;
err = -EINVAL;
if (size < sizeof(outarg))
goto out_finish;
err = fuse_copy_one(cs, &outarg, sizeof(outarg));
if (err)
goto out_finish;
err = -EINVAL;
if (size - sizeof(outarg) != outarg.size)
goto out_finish;
nodeid = outarg.nodeid;
down_read(&fc->killsb);
err = -ENOENT;
if (!fc->sb)
goto out_up_killsb;
inode = ilookup5(fc->sb, nodeid, fuse_inode_eq, &nodeid);
if (!inode)
goto out_up_killsb;
mapping = inode->i_mapping;
index = outarg.offset >> PAGE_CACHE_SHIFT;
offset = outarg.offset & ~PAGE_CACHE_MASK;
file_size = i_size_read(inode);
end = outarg.offset + outarg.size;
if (end > file_size) {
file_size = end;
fuse_write_update_size(inode, file_size);
}
num = outarg.size;
while (num) {
struct page *page;
unsigned int this_num;
err = -ENOMEM;
page = find_or_create_page(mapping, index,
mapping_gfp_mask(mapping));
if (!page)
goto out_iput;
this_num = min_t(unsigned, num, PAGE_CACHE_SIZE - offset);
err = fuse_copy_page(cs, &page, offset, this_num, 0);
if (!err && offset == 0 && (num != 0 || file_size == end))
SetPageUptodate(page);
unlock_page(page);
page_cache_release(page);
if (err)
goto out_iput;
num -= this_num;
offset = 0;
index++;
}
err = 0;
out_iput:
iput(inode);
out_up_killsb:
up_read(&fc->killsb);
out_finish:
fuse_copy_finish(cs);
return err;
}
static void fuse_retrieve_end(struct fuse_conn *fc, struct fuse_req *req)
{
release_pages(req->pages, req->num_pages, 0);
}
static int fuse_retrieve(struct fuse_conn *fc, struct inode *inode,
struct fuse_notify_retrieve_out *outarg)
{
int err;
struct address_space *mapping = inode->i_mapping;
struct fuse_req *req;
pgoff_t index;
loff_t file_size;
unsigned int num;
unsigned int offset;
size_t total_len = 0;
req = fuse_get_req(fc);
if (IS_ERR(req))
return PTR_ERR(req);
offset = outarg->offset & ~PAGE_CACHE_MASK;
req->in.h.opcode = FUSE_NOTIFY_REPLY;
req->in.h.nodeid = outarg->nodeid;
req->in.numargs = 2;
req->in.argpages = 1;
req->page_offset = offset;
req->end = fuse_retrieve_end;
index = outarg->offset >> PAGE_CACHE_SHIFT;
file_size = i_size_read(inode);
num = outarg->size;
if (outarg->offset > file_size)
num = 0;
else if (outarg->offset + num > file_size)
num = file_size - outarg->offset;
while (num) {
struct page *page;
unsigned int this_num;
page = find_get_page(mapping, index);
if (!page)
break;
this_num = min_t(unsigned, num, PAGE_CACHE_SIZE - offset);
req->pages[req->num_pages] = page;
req->num_pages++;
num -= this_num;
total_len += this_num;
}
req->misc.retrieve_in.offset = outarg->offset;
req->misc.retrieve_in.size = total_len;
req->in.args[0].size = sizeof(req->misc.retrieve_in);
req->in.args[0].value = &req->misc.retrieve_in;
req->in.args[1].size = total_len;
err = fuse_request_send_notify_reply(fc, req, outarg->notify_unique);
if (err)
fuse_retrieve_end(fc, req);
return err;
}
static int fuse_notify_retrieve(struct fuse_conn *fc, unsigned int size,
struct fuse_copy_state *cs)
{
struct fuse_notify_retrieve_out outarg;
struct inode *inode;
int err;
err = -EINVAL;
if (size != sizeof(outarg))
goto copy_finish;
err = fuse_copy_one(cs, &outarg, sizeof(outarg));
if (err)
goto copy_finish;
fuse_copy_finish(cs);
down_read(&fc->killsb);
err = -ENOENT;
if (fc->sb) {
u64 nodeid = outarg.nodeid;
inode = ilookup5(fc->sb, nodeid, fuse_inode_eq, &nodeid);
if (inode) {
err = fuse_retrieve(fc, inode, &outarg);
iput(inode);
}
}
up_read(&fc->killsb);
return err;
copy_finish:
fuse_copy_finish(cs);
return err;
}
static int fuse_notify(struct fuse_conn *fc, enum fuse_notify_code code,
unsigned int size, struct fuse_copy_state *cs)
{
switch (code) {
case FUSE_NOTIFY_POLL:
return fuse_notify_poll(fc, size, cs);
case FUSE_NOTIFY_INVAL_INODE:
return fuse_notify_inval_inode(fc, size, cs);
case FUSE_NOTIFY_INVAL_ENTRY:
return fuse_notify_inval_entry(fc, size, cs);
case FUSE_NOTIFY_STORE:
return fuse_notify_store(fc, size, cs);
case FUSE_NOTIFY_RETRIEVE:
return fuse_notify_retrieve(fc, size, cs);
default:
fuse_copy_finish(cs);
return -EINVAL;
}
}
/* Look up request on processing list by unique ID */
static struct fuse_req *request_find(struct fuse_conn *fc, u64 unique)
{
struct list_head *entry;
list_for_each(entry, &fc->processing) {
struct fuse_req *req;
req = list_entry(entry, struct fuse_req, list);
if (req->in.h.unique == unique || req->intr_unique == unique)
return req;
}
return NULL;
}
static int copy_out_args(struct fuse_copy_state *cs, struct fuse_out *out,
unsigned nbytes)
{
unsigned reqsize = sizeof(struct fuse_out_header);
if (out->h.error)
return nbytes != reqsize ? -EINVAL : 0;
reqsize += len_args(out->numargs, out->args);
if (reqsize < nbytes || (reqsize > nbytes && !out->argvar))
return -EINVAL;
else if (reqsize > nbytes) {
struct fuse_arg *lastarg = &out->args[out->numargs-1];
unsigned diffsize = reqsize - nbytes;
if (diffsize > lastarg->size)
return -EINVAL;
lastarg->size -= diffsize;
}
return fuse_copy_args(cs, out->numargs, out->argpages, out->args,
out->page_zeroing);
}
/*
* Write a single reply to a request. First the header is copied from
* the write buffer. The request is then searched on the processing
* list by the unique ID found in the header. If found, then remove
* it from the list and copy the rest of the buffer to the request.
* The request is finished by calling request_end()
*/
static ssize_t fuse_dev_do_write(struct fuse_conn *fc,
struct fuse_copy_state *cs, size_t nbytes)
{
int err;
struct fuse_req *req;
struct fuse_out_header oh;
if (nbytes < sizeof(struct fuse_out_header))
return -EINVAL;
err = fuse_copy_one(cs, &oh, sizeof(oh));
if (err)
goto err_finish;
err = -EINVAL;
if (oh.len != nbytes)
goto err_finish;
/*
* Zero oh.unique indicates unsolicited notification message
* and error contains notification code.
*/
if (!oh.unique) {
err = fuse_notify(fc, oh.error, nbytes - sizeof(oh), cs);
return err ? err : nbytes;
}
err = -EINVAL;
if (oh.error <= -1000 || oh.error > 0)
goto err_finish;
spin_lock(&fc->lock);
err = -ENOENT;
if (!fc->connected)
goto err_unlock;
req = request_find(fc, oh.unique);
if (!req)
goto err_unlock;
if (req->aborted) {
spin_unlock(&fc->lock);
fuse_copy_finish(cs);
spin_lock(&fc->lock);
request_end(fc, req);
return -ENOENT;
}
/* Is it an interrupt reply? */
if (req->intr_unique == oh.unique) {
err = -EINVAL;
if (nbytes != sizeof(struct fuse_out_header))
goto err_unlock;
if (oh.error == -ENOSYS)
fc->no_interrupt = 1;
else if (oh.error == -EAGAIN)
queue_interrupt(fc, req);
spin_unlock(&fc->lock);
fuse_copy_finish(cs);
return nbytes;
}
req->state = FUSE_REQ_WRITING;
list_move(&req->list, &fc->io);
req->out.h = oh;
req->locked = 1;
cs->req = req;
if (!req->out.page_replace)
cs->move_pages = 0;
spin_unlock(&fc->lock);
err = copy_out_args(cs, &req->out, nbytes);
fuse_copy_finish(cs);
spin_lock(&fc->lock);
req->locked = 0;
if (!err) {
if (req->aborted)
err = -ENOENT;
} else if (!req->aborted)
req->out.h.error = -EIO;
request_end(fc, req);
return err ? err : nbytes;
err_unlock:
spin_unlock(&fc->lock);
err_finish:
fuse_copy_finish(cs);
return err;
}
static ssize_t fuse_dev_write(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t pos)
{
struct fuse_copy_state cs;
struct fuse_conn *fc = fuse_get_conn(iocb->ki_filp);
if (!fc)
return -EPERM;
fuse_copy_init(&cs, fc, 0, iov, nr_segs);
return fuse_dev_do_write(fc, &cs, iov_length(iov, nr_segs));
}
static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe,
struct file *out, loff_t *ppos,
size_t len, unsigned int flags)
{
unsigned nbuf;
unsigned idx;
struct pipe_buffer *bufs;
struct fuse_copy_state cs;
struct fuse_conn *fc;
size_t rem;
ssize_t ret;
fc = fuse_get_conn(out);
if (!fc)
return -EPERM;
bufs = kmalloc(pipe->buffers * sizeof(struct pipe_buffer), GFP_KERNEL);
if (!bufs)
return -ENOMEM;
pipe_lock(pipe);
nbuf = 0;
rem = 0;
for (idx = 0; idx < pipe->nrbufs && rem < len; idx++)
rem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len;
ret = -EINVAL;
if (rem < len) {
pipe_unlock(pipe);
goto out;
}
rem = len;
while (rem) {
struct pipe_buffer *ibuf;
struct pipe_buffer *obuf;
BUG_ON(nbuf >= pipe->buffers);
BUG_ON(!pipe->nrbufs);
ibuf = &pipe->bufs[pipe->curbuf];
obuf = &bufs[nbuf];
if (rem >= ibuf->len) {
*obuf = *ibuf;
ibuf->ops = NULL;
pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);
pipe->nrbufs--;
} else {
ibuf->ops->get(pipe, ibuf);
*obuf = *ibuf;
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
obuf->len = rem;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
nbuf++;
rem -= obuf->len;
}
pipe_unlock(pipe);
fuse_copy_init(&cs, fc, 0, NULL, nbuf);
cs.pipebufs = bufs;
cs.pipe = pipe;
if (flags & SPLICE_F_MOVE)
cs.move_pages = 1;
ret = fuse_dev_do_write(fc, &cs, len);
for (idx = 0; idx < nbuf; idx++) {
struct pipe_buffer *buf = &bufs[idx];
buf->ops->release(pipe, buf);
}
out:
kfree(bufs);
return ret;
}
static unsigned fuse_dev_poll(struct file *file, poll_table *wait)
{
unsigned mask = POLLOUT | POLLWRNORM;
struct fuse_conn *fc = fuse_get_conn(file);
if (!fc)
return POLLERR;
poll_wait(file, &fc->waitq, wait);
spin_lock(&fc->lock);
if (!fc->connected)
mask = POLLERR;
else if (request_pending(fc))
mask |= POLLIN | POLLRDNORM;
spin_unlock(&fc->lock);
return mask;
}
/*
* Abort all requests on the given list (pending or processing)
*
* This function releases and reacquires fc->lock
*/
static void end_requests(struct fuse_conn *fc, struct list_head *head)
__releases(fc->lock)
__acquires(fc->lock)
{
while (!list_empty(head)) {
struct fuse_req *req;
req = list_entry(head->next, struct fuse_req, list);
req->out.h.error = -ECONNABORTED;
request_end(fc, req);
spin_lock(&fc->lock);
}
}
/*
* Abort requests under I/O
*
* The requests are set to aborted and finished, and the request
* waiter is woken up. This will make request_wait_answer() wait
* until the request is unlocked and then return.
*
* If the request is asynchronous, then the end function needs to be
* called after waiting for the request to be unlocked (if it was
* locked).
*/
static void end_io_requests(struct fuse_conn *fc)
__releases(fc->lock)
__acquires(fc->lock)
{
while (!list_empty(&fc->io)) {
struct fuse_req *req =
list_entry(fc->io.next, struct fuse_req, list);
void (*end) (struct fuse_conn *, struct fuse_req *) = req->end;
req->aborted = 1;
req->out.h.error = -ECONNABORTED;
req->state = FUSE_REQ_FINISHED;
list_del_init(&req->list);
wake_up(&req->waitq);
if (end) {
req->end = NULL;
__fuse_get_request(req);
spin_unlock(&fc->lock);
wait_event(req->waitq, !req->locked);
end(fc, req);
fuse_put_request(fc, req);
spin_lock(&fc->lock);
}
}
}
static void end_queued_requests(struct fuse_conn *fc)
__releases(fc->lock)
__acquires(fc->lock)
{
fc->max_background = UINT_MAX;
flush_bg_queue(fc);
end_requests(fc, &fc->pending);
end_requests(fc, &fc->processing);
while (forget_pending(fc))
kfree(dequeue_forget(fc, 1, NULL));
}
static void end_polls(struct fuse_conn *fc)
{
struct rb_node *p;
p = rb_first(&fc->polled_files);
while (p) {
struct fuse_file *ff;
ff = rb_entry(p, struct fuse_file, polled_node);
wake_up_interruptible_all(&ff->poll_wait);
p = rb_next(p);
}
}
/*
* Abort all requests.
*
* Emergency exit in case of a malicious or accidental deadlock, or
* just a hung filesystem.
*
* The same effect is usually achievable through killing the
* filesystem daemon and all users of the filesystem. The exception
* is the combination of an asynchronous request and the tricky
* deadlock (see Documentation/filesystems/fuse.txt).
*
* During the aborting, progression of requests from the pending and
* processing lists onto the io list, and progression of new requests
* onto the pending list is prevented by req->connected being false.
*
* Progression of requests under I/O to the processing list is
* prevented by the req->aborted flag being true for these requests.
* For this reason requests on the io list must be aborted first.
*/
void fuse_abort_conn(struct fuse_conn *fc)
{
spin_lock(&fc->lock);
if (fc->connected) {
fc->connected = 0;
fc->blocked = 0;
end_io_requests(fc);
end_queued_requests(fc);
end_polls(fc);
wake_up_all(&fc->waitq);
wake_up_all(&fc->blocked_waitq);
kill_fasync(&fc->fasync, SIGIO, POLL_IN);
}
spin_unlock(&fc->lock);
}
EXPORT_SYMBOL_GPL(fuse_abort_conn);
int fuse_dev_release(struct inode *inode, struct file *file)
{
struct fuse_conn *fc = fuse_get_conn(file);
if (fc) {
spin_lock(&fc->lock);
fc->connected = 0;
fc->blocked = 0;
end_queued_requests(fc);
end_polls(fc);
wake_up_all(&fc->blocked_waitq);
spin_unlock(&fc->lock);
fuse_conn_put(fc);
}
return 0;
}
EXPORT_SYMBOL_GPL(fuse_dev_release);
static int fuse_dev_fasync(int fd, struct file *file, int on)
{
struct fuse_conn *fc = fuse_get_conn(file);
if (!fc)
return -EPERM;
/* No locking - fasync_helper does its own locking */
return fasync_helper(fd, file, on, &fc->fasync);
}
const struct file_operations fuse_dev_operations = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.read = do_sync_read,
.aio_read = fuse_dev_read,
.splice_read = fuse_dev_splice_read,
.write = do_sync_write,
.aio_write = fuse_dev_write,
.splice_write = fuse_dev_splice_write,
.poll = fuse_dev_poll,
.release = fuse_dev_release,
.fasync = fuse_dev_fasync,
};
EXPORT_SYMBOL_GPL(fuse_dev_operations);
static struct miscdevice fuse_miscdevice = {
.minor = FUSE_MINOR,
.name = "fuse",
.fops = &fuse_dev_operations,
};
int __init fuse_dev_init(void)
{
int err = -ENOMEM;
fuse_req_cachep = kmem_cache_create("fuse_request",
sizeof(struct fuse_req),
0, 0, NULL);
if (!fuse_req_cachep)
goto out;
err = misc_register(&fuse_miscdevice);
if (err)
goto out_cache_clean;
return 0;
out_cache_clean:
kmem_cache_destroy(fuse_req_cachep);
out:
return err;
}
void fuse_dev_cleanup(void)
{
misc_deregister(&fuse_miscdevice);
kmem_cache_destroy(fuse_req_cachep);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3503_0 |
crossvul-cpp_data_bad_4835_0 | /*
* HTTP protocol for ffmpeg client
* Copyright (c) 2000, 2001 Fabrice Bellard
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "config.h"
#if CONFIG_ZLIB
#include <zlib.h>
#endif /* CONFIG_ZLIB */
#include "libavutil/avassert.h"
#include "libavutil/avstring.h"
#include "libavutil/opt.h"
#include "libavutil/time.h"
#include "avformat.h"
#include "http.h"
#include "httpauth.h"
#include "internal.h"
#include "network.h"
#include "os_support.h"
#include "url.h"
/* XXX: POST protocol is not completely implemented because ffmpeg uses
* only a subset of it. */
/* The IO buffer size is unrelated to the max URL size in itself, but needs
* to be large enough to fit the full request headers (including long
* path names). */
#define BUFFER_SIZE MAX_URL_SIZE
#define MAX_REDIRECTS 8
#define HTTP_SINGLE 1
#define HTTP_MUTLI 2
typedef enum {
LOWER_PROTO,
READ_HEADERS,
WRITE_REPLY_HEADERS,
FINISH
}HandshakeState;
typedef struct HTTPContext {
const AVClass *class;
URLContext *hd;
unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
int line_count;
int http_code;
/* Used if "Transfer-Encoding: chunked" otherwise -1. */
int64_t chunksize;
int64_t off, end_off, filesize;
char *location;
HTTPAuthState auth_state;
HTTPAuthState proxy_auth_state;
char *http_proxy;
char *headers;
char *mime_type;
char *user_agent;
#if FF_API_HTTP_USER_AGENT
char *user_agent_deprecated;
#endif
char *content_type;
/* Set if the server correctly handles Connection: close and will close
* the connection after feeding us the content. */
int willclose;
int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
int chunked_post;
/* A flag which indicates if the end of chunked encoding has been sent. */
int end_chunked_post;
/* A flag which indicates we have finished to read POST reply. */
int end_header;
/* A flag which indicates if we use persistent connections. */
int multiple_requests;
uint8_t *post_data;
int post_datalen;
int is_akamai;
int is_mediagateway;
char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
/* A dictionary containing cookies keyed by cookie name */
AVDictionary *cookie_dict;
int icy;
/* how much data was read since the last ICY metadata packet */
int icy_data_read;
/* after how many bytes of read data a new metadata packet will be found */
int icy_metaint;
char *icy_metadata_headers;
char *icy_metadata_packet;
AVDictionary *metadata;
#if CONFIG_ZLIB
int compressed;
z_stream inflate_stream;
uint8_t *inflate_buffer;
#endif /* CONFIG_ZLIB */
AVDictionary *chained_options;
int send_expect_100;
char *method;
int reconnect;
int reconnect_at_eof;
int reconnect_streamed;
int reconnect_delay;
int reconnect_delay_max;
int listen;
char *resource;
int reply_code;
int is_multi_client;
HandshakeState handshake_step;
int is_connected_server;
} HTTPContext;
#define OFFSET(x) offsetof(HTTPContext, x)
#define D AV_OPT_FLAG_DECODING_PARAM
#define E AV_OPT_FLAG_ENCODING_PARAM
#define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
static const AVOption options[] = {
{ "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, D },
{ "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
{ "http_proxy", "set HTTP proxy to tunnel through", OFFSET(http_proxy), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
{ "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
{ "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
{ "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
#if FF_API_HTTP_USER_AGENT
{ "user-agent", "override User-Agent header", OFFSET(user_agent_deprecated), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
#endif
{ "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D | E },
{ "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
{ "mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
{ "cookies", "set cookies to be sent in applicable future requests, use newline delimited Set-Cookie HTTP field value syntax", OFFSET(cookies), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D },
{ "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
{ "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
{ "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
{ "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
{ "auth_type", "HTTP authentication type", OFFSET(auth_state.auth_type), AV_OPT_TYPE_INT, { .i64 = HTTP_AUTH_NONE }, HTTP_AUTH_NONE, HTTP_AUTH_BASIC, D | E, "auth_type"},
{ "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
{ "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
{ "send_expect_100", "Force sending an Expect: 100-continue header for POST", OFFSET(send_expect_100), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
{ "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
{ "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
{ "end_offset", "try to limit the request to bytes preceding this offset", OFFSET(end_off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
{ "method", "Override the HTTP method or set the expected HTTP method from a client", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
{ "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
{ "reconnect_at_eof", "auto reconnect at EOF", OFFSET(reconnect_at_eof), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
{ "reconnect_streamed", "auto reconnect streamed / non seekable streams", OFFSET(reconnect_streamed), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
{ "reconnect_delay_max", "max reconnect delay in seconds after which to give up", OFFSET(reconnect_delay_max), AV_OPT_TYPE_INT, { .i64 = 120 }, 0, UINT_MAX/1000/1000, D },
{ "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, D | E },
{ "resource", "The resource requested by a client", OFFSET(resource), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
{ "reply_code", "The http status code to return to a client", OFFSET(reply_code), AV_OPT_TYPE_INT, { .i64 = 200}, INT_MIN, 599, E},
{ NULL }
};
static int http_connect(URLContext *h, const char *path, const char *local_path,
const char *hoststr, const char *auth,
const char *proxyauth, int *new_location);
static int http_read_header(URLContext *h, int *new_location);
void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
{
memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
&((HTTPContext *)src->priv_data)->auth_state,
sizeof(HTTPAuthState));
memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
&((HTTPContext *)src->priv_data)->proxy_auth_state,
sizeof(HTTPAuthState));
}
static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
{
const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
char hostname[1024], hoststr[1024], proto[10];
char auth[1024], proxyauth[1024] = "";
char path1[MAX_URL_SIZE];
char buf[1024], urlbuf[MAX_URL_SIZE];
int port, use_proxy, err, location_changed = 0;
HTTPContext *s = h->priv_data;
av_url_split(proto, sizeof(proto), auth, sizeof(auth),
hostname, sizeof(hostname), &port,
path1, sizeof(path1), s->location);
ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
proxy_path = s->http_proxy ? s->http_proxy : getenv("http_proxy");
use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
proxy_path && av_strstart(proxy_path, "http://", NULL);
if (!strcmp(proto, "https")) {
lower_proto = "tls";
use_proxy = 0;
if (port < 0)
port = 443;
}
if (port < 0)
port = 80;
if (path1[0] == '\0')
path = "/";
else
path = path1;
local_path = path;
if (use_proxy) {
/* Reassemble the request URL without auth string - we don't
* want to leak the auth to the proxy. */
ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
path1);
path = urlbuf;
av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
}
ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
if (!s->hd) {
err = ffurl_open_whitelist(&s->hd, buf, AVIO_FLAG_READ_WRITE,
&h->interrupt_callback, options,
h->protocol_whitelist, h->protocol_blacklist, h);
if (err < 0)
return err;
}
err = http_connect(h, path, local_path, hoststr,
auth, proxyauth, &location_changed);
if (err < 0)
return err;
return location_changed;
}
/* return non zero if error */
static int http_open_cnx(URLContext *h, AVDictionary **options)
{
HTTPAuthType cur_auth_type, cur_proxy_auth_type;
HTTPContext *s = h->priv_data;
int location_changed, attempts = 0, redirects = 0;
redo:
av_dict_copy(options, s->chained_options, 0);
cur_auth_type = s->auth_state.auth_type;
cur_proxy_auth_type = s->auth_state.auth_type;
location_changed = http_open_cnx_internal(h, options);
if (location_changed < 0)
goto fail;
attempts++;
if (s->http_code == 401) {
if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
ffurl_closep(&s->hd);
goto redo;
} else
goto fail;
}
if (s->http_code == 407) {
if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
ffurl_closep(&s->hd);
goto redo;
} else
goto fail;
}
if ((s->http_code == 301 || s->http_code == 302 ||
s->http_code == 303 || s->http_code == 307) &&
location_changed == 1) {
/* url moved, get next */
ffurl_closep(&s->hd);
if (redirects++ >= MAX_REDIRECTS)
return AVERROR(EIO);
/* Restart the authentication process with the new target, which
* might use a different auth mechanism. */
memset(&s->auth_state, 0, sizeof(s->auth_state));
attempts = 0;
location_changed = 0;
goto redo;
}
return 0;
fail:
if (s->hd)
ffurl_closep(&s->hd);
if (location_changed < 0)
return location_changed;
return ff_http_averror(s->http_code, AVERROR(EIO));
}
int ff_http_do_new_request(URLContext *h, const char *uri)
{
HTTPContext *s = h->priv_data;
AVDictionary *options = NULL;
int ret;
s->off = 0;
s->icy_data_read = 0;
av_free(s->location);
s->location = av_strdup(uri);
if (!s->location)
return AVERROR(ENOMEM);
ret = http_open_cnx(h, &options);
av_dict_free(&options);
return ret;
}
int ff_http_averror(int status_code, int default_averror)
{
switch (status_code) {
case 400: return AVERROR_HTTP_BAD_REQUEST;
case 401: return AVERROR_HTTP_UNAUTHORIZED;
case 403: return AVERROR_HTTP_FORBIDDEN;
case 404: return AVERROR_HTTP_NOT_FOUND;
default: break;
}
if (status_code >= 400 && status_code <= 499)
return AVERROR_HTTP_OTHER_4XX;
else if (status_code >= 500)
return AVERROR_HTTP_SERVER_ERROR;
else
return default_averror;
}
static int http_write_reply(URLContext* h, int status_code)
{
int ret, body = 0, reply_code, message_len;
const char *reply_text, *content_type;
HTTPContext *s = h->priv_data;
char message[BUFFER_SIZE];
content_type = "text/plain";
if (status_code < 0)
body = 1;
switch (status_code) {
case AVERROR_HTTP_BAD_REQUEST:
case 400:
reply_code = 400;
reply_text = "Bad Request";
break;
case AVERROR_HTTP_FORBIDDEN:
case 403:
reply_code = 403;
reply_text = "Forbidden";
break;
case AVERROR_HTTP_NOT_FOUND:
case 404:
reply_code = 404;
reply_text = "Not Found";
break;
case 200:
reply_code = 200;
reply_text = "OK";
content_type = s->content_type ? s->content_type : "application/octet-stream";
break;
case AVERROR_HTTP_SERVER_ERROR:
case 500:
reply_code = 500;
reply_text = "Internal server error";
break;
default:
return AVERROR(EINVAL);
}
if (body) {
s->chunked_post = 0;
message_len = snprintf(message, sizeof(message),
"HTTP/1.1 %03d %s\r\n"
"Content-Type: %s\r\n"
"Content-Length: %"SIZE_SPECIFIER"\r\n"
"%s"
"\r\n"
"%03d %s\r\n",
reply_code,
reply_text,
content_type,
strlen(reply_text) + 6, // 3 digit status code + space + \r\n
s->headers ? s->headers : "",
reply_code,
reply_text);
} else {
s->chunked_post = 1;
message_len = snprintf(message, sizeof(message),
"HTTP/1.1 %03d %s\r\n"
"Content-Type: %s\r\n"
"Transfer-Encoding: chunked\r\n"
"%s"
"\r\n",
reply_code,
reply_text,
content_type,
s->headers ? s->headers : "");
}
av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message);
if ((ret = ffurl_write(s->hd, message, message_len)) < 0)
return ret;
return 0;
}
static void handle_http_errors(URLContext *h, int error)
{
av_assert0(error < 0);
http_write_reply(h, error);
}
static int http_handshake(URLContext *c)
{
int ret, err, new_location;
HTTPContext *ch = c->priv_data;
URLContext *cl = ch->hd;
switch (ch->handshake_step) {
case LOWER_PROTO:
av_log(c, AV_LOG_TRACE, "Lower protocol\n");
if ((ret = ffurl_handshake(cl)) > 0)
return 2 + ret;
if (ret < 0)
return ret;
ch->handshake_step = READ_HEADERS;
ch->is_connected_server = 1;
return 2;
case READ_HEADERS:
av_log(c, AV_LOG_TRACE, "Read headers\n");
if ((err = http_read_header(c, &new_location)) < 0) {
handle_http_errors(c, err);
return err;
}
ch->handshake_step = WRITE_REPLY_HEADERS;
return 1;
case WRITE_REPLY_HEADERS:
av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code);
if ((err = http_write_reply(c, ch->reply_code)) < 0)
return err;
ch->handshake_step = FINISH;
return 1;
case FINISH:
return 0;
}
// this should never be reached.
return AVERROR(EINVAL);
}
static int http_listen(URLContext *h, const char *uri, int flags,
AVDictionary **options) {
HTTPContext *s = h->priv_data;
int ret;
char hostname[1024], proto[10];
char lower_url[100];
const char *lower_proto = "tcp";
int port;
av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
NULL, 0, uri);
if (!strcmp(proto, "https"))
lower_proto = "tls";
ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
NULL);
if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0)
goto fail;
if ((ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
&h->interrupt_callback, options,
h->protocol_whitelist, h->protocol_blacklist, h
)) < 0)
goto fail;
s->handshake_step = LOWER_PROTO;
if (s->listen == HTTP_SINGLE) { /* single client */
s->reply_code = 200;
while ((ret = http_handshake(h)) > 0);
}
fail:
av_dict_free(&s->chained_options);
return ret;
}
static int http_open(URLContext *h, const char *uri, int flags,
AVDictionary **options)
{
HTTPContext *s = h->priv_data;
int ret;
if( s->seekable == 1 )
h->is_streamed = 0;
else
h->is_streamed = 1;
s->filesize = -1;
s->location = av_strdup(uri);
if (!s->location)
return AVERROR(ENOMEM);
if (options)
av_dict_copy(&s->chained_options, *options, 0);
if (s->headers) {
int len = strlen(s->headers);
if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
av_log(h, AV_LOG_WARNING,
"No trailing CRLF found in HTTP header.\n");
ret = av_reallocp(&s->headers, len + 3);
if (ret < 0)
return ret;
s->headers[len] = '\r';
s->headers[len + 1] = '\n';
s->headers[len + 2] = '\0';
}
}
if (s->listen) {
return http_listen(h, uri, flags, options);
}
ret = http_open_cnx(h, options);
if (ret < 0)
av_dict_free(&s->chained_options);
return ret;
}
static int http_accept(URLContext *s, URLContext **c)
{
int ret;
HTTPContext *sc = s->priv_data;
HTTPContext *cc;
URLContext *sl = sc->hd;
URLContext *cl = NULL;
av_assert0(sc->listen);
if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0)
goto fail;
cc = (*c)->priv_data;
if ((ret = ffurl_accept(sl, &cl)) < 0)
goto fail;
cc->hd = cl;
cc->is_multi_client = 1;
fail:
return ret;
}
static int http_getc(HTTPContext *s)
{
int len;
if (s->buf_ptr >= s->buf_end) {
len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
if (len < 0) {
return len;
} else if (len == 0) {
return AVERROR_EOF;
} else {
s->buf_ptr = s->buffer;
s->buf_end = s->buffer + len;
}
}
return *s->buf_ptr++;
}
static int http_get_line(HTTPContext *s, char *line, int line_size)
{
int ch;
char *q;
q = line;
for (;;) {
ch = http_getc(s);
if (ch < 0)
return ch;
if (ch == '\n') {
/* process line */
if (q > line && q[-1] == '\r')
q--;
*q = '\0';
return 0;
} else {
if ((q - line) < line_size - 1)
*q++ = ch;
}
}
}
static int check_http_code(URLContext *h, int http_code, const char *end)
{
HTTPContext *s = h->priv_data;
/* error codes are 4xx and 5xx, but regard 401 as a success, so we
* don't abort until all headers have been parsed. */
if (http_code >= 400 && http_code < 600 &&
(http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
(http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
end += strspn(end, SPACE_CHARS);
av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
return ff_http_averror(http_code, AVERROR(EIO));
}
return 0;
}
static int parse_location(HTTPContext *s, const char *p)
{
char redirected_location[MAX_URL_SIZE], *new_loc;
ff_make_absolute_url(redirected_location, sizeof(redirected_location),
s->location, p);
new_loc = av_strdup(redirected_location);
if (!new_loc)
return AVERROR(ENOMEM);
av_free(s->location);
s->location = new_loc;
return 0;
}
/* "bytes $from-$to/$document_size" */
static void parse_content_range(URLContext *h, const char *p)
{
HTTPContext *s = h->priv_data;
const char *slash;
if (!strncmp(p, "bytes ", 6)) {
p += 6;
s->off = strtoll(p, NULL, 10);
if ((slash = strchr(p, '/')) && strlen(slash) > 0)
s->filesize = strtoll(slash + 1, NULL, 10);
}
if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
h->is_streamed = 0; /* we _can_ in fact seek */
}
static int parse_content_encoding(URLContext *h, const char *p)
{
if (!av_strncasecmp(p, "gzip", 4) ||
!av_strncasecmp(p, "deflate", 7)) {
#if CONFIG_ZLIB
HTTPContext *s = h->priv_data;
s->compressed = 1;
inflateEnd(&s->inflate_stream);
if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
s->inflate_stream.msg);
return AVERROR(ENOSYS);
}
if (zlibCompileFlags() & (1 << 17)) {
av_log(h, AV_LOG_WARNING,
"Your zlib was compiled without gzip support.\n");
return AVERROR(ENOSYS);
}
#else
av_log(h, AV_LOG_WARNING,
"Compressed (%s) content, need zlib with gzip support\n", p);
return AVERROR(ENOSYS);
#endif /* CONFIG_ZLIB */
} else if (!av_strncasecmp(p, "identity", 8)) {
// The normal, no-encoding case (although servers shouldn't include
// the header at all if this is the case).
} else {
av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
}
return 0;
}
// Concat all Icy- header lines
static int parse_icy(HTTPContext *s, const char *tag, const char *p)
{
int len = 4 + strlen(p) + strlen(tag);
int is_first = !s->icy_metadata_headers;
int ret;
av_dict_set(&s->metadata, tag, p, 0);
if (s->icy_metadata_headers)
len += strlen(s->icy_metadata_headers);
if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
return ret;
if (is_first)
*s->icy_metadata_headers = '\0';
av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
return 0;
}
static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
{
char *eql, *name;
// duplicate the cookie name (dict will dupe the value)
if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
// add the cookie to the dictionary
av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
return 0;
}
static int cookie_string(AVDictionary *dict, char **cookies)
{
AVDictionaryEntry *e = NULL;
int len = 1;
// determine how much memory is needed for the cookies string
while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
len += strlen(e->key) + strlen(e->value) + 1;
// reallocate the cookies
e = NULL;
if (*cookies) av_free(*cookies);
*cookies = av_malloc(len);
if (!*cookies) return AVERROR(ENOMEM);
*cookies[0] = '\0';
// write out the cookies
while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
return 0;
}
static int process_line(URLContext *h, char *line, int line_count,
int *new_location)
{
HTTPContext *s = h->priv_data;
const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
char *tag, *p, *end, *method, *resource, *version;
int ret;
/* end of header */
if (line[0] == '\0') {
s->end_header = 1;
return 0;
}
p = line;
if (line_count == 0) {
if (s->is_connected_server) {
// HTTP method
method = p;
while (*p && !av_isspace(*p))
p++;
*(p++) = '\0';
av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
if (s->method) {
if (av_strcasecmp(s->method, method)) {
av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
s->method, method);
return ff_http_averror(400, AVERROR(EIO));
}
} else {
// use autodetected HTTP method to expect
av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
if (av_strcasecmp(auto_method, method)) {
av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
"(%s autodetected %s received)\n", auto_method, method);
return ff_http_averror(400, AVERROR(EIO));
}
if (!(s->method = av_strdup(method)))
return AVERROR(ENOMEM);
}
// HTTP resource
while (av_isspace(*p))
p++;
resource = p;
while (!av_isspace(*p))
p++;
*(p++) = '\0';
av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
if (!(s->resource = av_strdup(resource)))
return AVERROR(ENOMEM);
// HTTP version
while (av_isspace(*p))
p++;
version = p;
while (*p && !av_isspace(*p))
p++;
*p = '\0';
if (av_strncasecmp(version, "HTTP/", 5)) {
av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
return ff_http_averror(400, AVERROR(EIO));
}
av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
} else {
while (!av_isspace(*p) && *p != '\0')
p++;
while (av_isspace(*p))
p++;
s->http_code = strtol(p, &end, 10);
av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
if ((ret = check_http_code(h, s->http_code, end)) < 0)
return ret;
}
} else {
while (*p != '\0' && *p != ':')
p++;
if (*p != ':')
return 1;
*p = '\0';
tag = line;
p++;
while (av_isspace(*p))
p++;
if (!av_strcasecmp(tag, "Location")) {
if ((ret = parse_location(s, p)) < 0)
return ret;
*new_location = 1;
} else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
s->filesize = strtoll(p, NULL, 10);
} else if (!av_strcasecmp(tag, "Content-Range")) {
parse_content_range(h, p);
} else if (!av_strcasecmp(tag, "Accept-Ranges") &&
!strncmp(p, "bytes", 5) &&
s->seekable == -1) {
h->is_streamed = 0;
} else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
!av_strncasecmp(p, "chunked", 7)) {
s->filesize = -1;
s->chunksize = 0;
} else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
ff_http_auth_handle_header(&s->auth_state, tag, p);
} else if (!av_strcasecmp(tag, "Authentication-Info")) {
ff_http_auth_handle_header(&s->auth_state, tag, p);
} else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
} else if (!av_strcasecmp(tag, "Connection")) {
if (!strcmp(p, "close"))
s->willclose = 1;
} else if (!av_strcasecmp(tag, "Server")) {
if (!av_strcasecmp(p, "AkamaiGHost")) {
s->is_akamai = 1;
} else if (!av_strncasecmp(p, "MediaGateway", 12)) {
s->is_mediagateway = 1;
}
} else if (!av_strcasecmp(tag, "Content-Type")) {
av_free(s->mime_type);
s->mime_type = av_strdup(p);
} else if (!av_strcasecmp(tag, "Set-Cookie")) {
if (parse_cookie(s, p, &s->cookie_dict))
av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
} else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
s->icy_metaint = strtoll(p, NULL, 10);
} else if (!av_strncasecmp(tag, "Icy-", 4)) {
if ((ret = parse_icy(s, tag, p)) < 0)
return ret;
} else if (!av_strcasecmp(tag, "Content-Encoding")) {
if ((ret = parse_content_encoding(h, p)) < 0)
return ret;
}
}
return 1;
}
/**
* Create a string containing cookie values for use as a HTTP cookie header
* field value for a particular path and domain from the cookie values stored in
* the HTTP protocol context. The cookie string is stored in *cookies.
*
* @return a negative value if an error condition occurred, 0 otherwise
*/
static int get_cookies(HTTPContext *s, char **cookies, const char *path,
const char *domain)
{
// cookie strings will look like Set-Cookie header field values. Multiple
// Set-Cookie fields will result in multiple values delimited by a newline
int ret = 0;
char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
if (!set_cookies) return AVERROR(EINVAL);
// destroy any cookies in the dictionary.
av_dict_free(&s->cookie_dict);
*cookies = NULL;
while ((cookie = av_strtok(set_cookies, "\n", &next))) {
int domain_offset = 0;
char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
set_cookies = NULL;
// store the cookie in a dict in case it is updated in the response
if (parse_cookie(s, cookie, &s->cookie_dict))
av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
while ((param = av_strtok(cookie, "; ", &next_param))) {
if (cookie) {
// first key-value pair is the actual cookie value
cvalue = av_strdup(param);
cookie = NULL;
} else if (!av_strncasecmp("path=", param, 5)) {
av_free(cpath);
cpath = av_strdup(¶m[5]);
} else if (!av_strncasecmp("domain=", param, 7)) {
// if the cookie specifies a sub-domain, skip the leading dot thereby
// supporting URLs that point to sub-domains and the master domain
int leading_dot = (param[7] == '.');
av_free(cdomain);
cdomain = av_strdup(¶m[7+leading_dot]);
} else {
// ignore unknown attributes
}
}
if (!cdomain)
cdomain = av_strdup(domain);
// ensure all of the necessary values are valid
if (!cdomain || !cpath || !cvalue) {
av_log(s, AV_LOG_WARNING,
"Invalid cookie found, no value, path or domain specified\n");
goto done_cookie;
}
// check if the request path matches the cookie path
if (av_strncasecmp(path, cpath, strlen(cpath)))
goto done_cookie;
// the domain should be at least the size of our cookie domain
domain_offset = strlen(domain) - strlen(cdomain);
if (domain_offset < 0)
goto done_cookie;
// match the cookie domain
if (av_strcasecmp(&domain[domain_offset], cdomain))
goto done_cookie;
// cookie parameters match, so copy the value
if (!*cookies) {
if (!(*cookies = av_strdup(cvalue))) {
ret = AVERROR(ENOMEM);
goto done_cookie;
}
} else {
char *tmp = *cookies;
size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
if (!(*cookies = av_malloc(str_size))) {
ret = AVERROR(ENOMEM);
goto done_cookie;
}
snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
av_free(tmp);
}
done_cookie:
av_freep(&cdomain);
av_freep(&cpath);
av_freep(&cvalue);
if (ret < 0) {
if (*cookies) av_freep(cookies);
av_free(cset_cookies);
return ret;
}
}
av_free(cset_cookies);
return 0;
}
static inline int has_header(const char *str, const char *header)
{
/* header + 2 to skip over CRLF prefix. (make sure you have one!) */
if (!str)
return 0;
return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
}
static int http_read_header(URLContext *h, int *new_location)
{
HTTPContext *s = h->priv_data;
char line[MAX_URL_SIZE];
int err = 0;
s->chunksize = -1;
for (;;) {
if ((err = http_get_line(s, line, sizeof(line))) < 0)
return err;
av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
err = process_line(h, line, s->line_count, new_location);
if (err < 0)
return err;
if (err == 0)
break;
s->line_count++;
}
if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
h->is_streamed = 1; /* we can in fact _not_ seek */
// add any new cookies into the existing cookie string
cookie_string(s->cookie_dict, &s->cookies);
av_dict_free(&s->cookie_dict);
return err;
}
static int http_connect(URLContext *h, const char *path, const char *local_path,
const char *hoststr, const char *auth,
const char *proxyauth, int *new_location)
{
HTTPContext *s = h->priv_data;
int post, err;
char headers[HTTP_HEADERS_SIZE] = "";
char *authstr = NULL, *proxyauthstr = NULL;
int64_t off = s->off;
int len = 0;
const char *method;
int send_expect_100 = 0;
/* send http header */
post = h->flags & AVIO_FLAG_WRITE;
if (s->post_data) {
/* force POST method and disable chunked encoding when
* custom HTTP post data is set */
post = 1;
s->chunked_post = 0;
}
if (s->method)
method = s->method;
else
method = post ? "POST" : "GET";
authstr = ff_http_auth_create_response(&s->auth_state, auth,
local_path, method);
proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
local_path, method);
if (post && !s->post_data) {
send_expect_100 = s->send_expect_100;
/* The user has supplied authentication but we don't know the auth type,
* send Expect: 100-continue to get the 401 response including the
* WWW-Authenticate header, or an 100 continue if no auth actually
* is needed. */
if (auth && *auth &&
s->auth_state.auth_type == HTTP_AUTH_NONE &&
s->http_code != 401)
send_expect_100 = 1;
}
#if FF_API_HTTP_USER_AGENT
if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {
av_log(s, AV_LOG_WARNING, "the user-agent option is deprecated, please use user_agent option\n");
s->user_agent = av_strdup(s->user_agent_deprecated);
}
#endif
/* set default headers if needed */
if (!has_header(s->headers, "\r\nUser-Agent: "))
len += av_strlcatf(headers + len, sizeof(headers) - len,
"User-Agent: %s\r\n", s->user_agent);
if (!has_header(s->headers, "\r\nAccept: "))
len += av_strlcpy(headers + len, "Accept: */*\r\n",
sizeof(headers) - len);
// Note: we send this on purpose even when s->off is 0 when we're probing,
// since it allows us to detect more reliably if a (non-conforming)
// server supports seeking by analysing the reply headers.
if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Range: bytes=%"PRId64"-", s->off);
if (s->end_off)
len += av_strlcatf(headers + len, sizeof(headers) - len,
"%"PRId64, s->end_off - 1);
len += av_strlcpy(headers + len, "\r\n",
sizeof(headers) - len);
}
if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Expect: 100-continue\r\n");
if (!has_header(s->headers, "\r\nConnection: ")) {
if (s->multiple_requests)
len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
sizeof(headers) - len);
else
len += av_strlcpy(headers + len, "Connection: close\r\n",
sizeof(headers) - len);
}
if (!has_header(s->headers, "\r\nHost: "))
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Host: %s\r\n", hoststr);
if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Content-Length: %d\r\n", s->post_datalen);
if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Content-Type: %s\r\n", s->content_type);
if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
char *cookies = NULL;
if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Cookie: %s\r\n", cookies);
av_free(cookies);
}
}
if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Icy-MetaData: %d\r\n", 1);
/* now add in custom headers */
if (s->headers)
av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
snprintf(s->buffer, sizeof(s->buffer),
"%s %s HTTP/1.1\r\n"
"%s"
"%s"
"%s"
"%s%s"
"\r\n",
method,
path,
post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
headers,
authstr ? authstr : "",
proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
goto done;
if (s->post_data)
if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
goto done;
/* init input buffer */
s->buf_ptr = s->buffer;
s->buf_end = s->buffer;
s->line_count = 0;
s->off = 0;
s->icy_data_read = 0;
s->filesize = -1;
s->willclose = 0;
s->end_chunked_post = 0;
s->end_header = 0;
if (post && !s->post_data && !send_expect_100) {
/* Pretend that it did work. We didn't read any header yet, since
* we've still to send the POST data, but the code calling this
* function will check http_code after we return. */
s->http_code = 200;
err = 0;
goto done;
}
/* wait for header */
err = http_read_header(h, new_location);
if (err < 0)
goto done;
if (*new_location)
s->off = off;
err = (off == s->off) ? 0 : -1;
done:
av_freep(&authstr);
av_freep(&proxyauthstr);
return err;
}
static int http_buf_read(URLContext *h, uint8_t *buf, int size)
{
HTTPContext *s = h->priv_data;
int len;
/* read bytes from input buffer first */
len = s->buf_end - s->buf_ptr;
if (len > 0) {
if (len > size)
len = size;
memcpy(buf, s->buf_ptr, len);
s->buf_ptr += len;
} else {
int64_t target_end = s->end_off ? s->end_off : s->filesize;
if ((!s->willclose || s->chunksize < 0) &&
target_end >= 0 && s->off >= target_end)
return AVERROR_EOF;
len = ffurl_read(s->hd, buf, size);
if (!len && (!s->willclose || s->chunksize < 0) &&
target_end >= 0 && s->off < target_end) {
av_log(h, AV_LOG_ERROR,
"Stream ends prematurely at %"PRId64", should be %"PRId64"\n",
s->off, target_end
);
return AVERROR(EIO);
}
}
if (len > 0) {
s->off += len;
if (s->chunksize > 0)
s->chunksize -= len;
}
return len;
}
#if CONFIG_ZLIB
#define DECOMPRESS_BUF_SIZE (256 * 1024)
static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
{
HTTPContext *s = h->priv_data;
int ret;
if (!s->inflate_buffer) {
s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
if (!s->inflate_buffer)
return AVERROR(ENOMEM);
}
if (s->inflate_stream.avail_in == 0) {
int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
if (read <= 0)
return read;
s->inflate_stream.next_in = s->inflate_buffer;
s->inflate_stream.avail_in = read;
}
s->inflate_stream.avail_out = size;
s->inflate_stream.next_out = buf;
ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END)
av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
ret, s->inflate_stream.msg);
return size - s->inflate_stream.avail_out;
}
#endif /* CONFIG_ZLIB */
static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
static int http_read_stream(URLContext *h, uint8_t *buf, int size)
{
HTTPContext *s = h->priv_data;
int err, new_location, read_ret;
int64_t seek_ret;
if (!s->hd)
return AVERROR_EOF;
if (s->end_chunked_post && !s->end_header) {
err = http_read_header(h, &new_location);
if (err < 0)
return err;
}
if (s->chunksize >= 0) {
if (!s->chunksize) {
char line[32];
do {
if ((err = http_get_line(s, line, sizeof(line))) < 0)
return err;
} while (!*line); /* skip CR LF from last chunk */
s->chunksize = strtoll(line, NULL, 16);
av_log(NULL, AV_LOG_TRACE, "Chunked encoding data size: %"PRId64"'\n",
s->chunksize);
if (!s->chunksize)
return 0;
}
size = FFMIN(size, s->chunksize);
}
#if CONFIG_ZLIB
if (s->compressed)
return http_buf_read_compressed(h, buf, size);
#endif /* CONFIG_ZLIB */
read_ret = http_buf_read(h, buf, size);
if ( (read_ret < 0 && s->reconnect && (!h->is_streamed || s->reconnect_streamed) && s->filesize > 0 && s->off < s->filesize)
|| (read_ret == 0 && s->reconnect_at_eof && (!h->is_streamed || s->reconnect_streamed))) {
int64_t target = h->is_streamed ? 0 : s->off;
if (s->reconnect_delay > s->reconnect_delay_max)
return AVERROR(EIO);
av_log(h, AV_LOG_INFO, "Will reconnect at %"PRId64" error=%s.\n", s->off, av_err2str(read_ret));
av_usleep(1000U*1000*s->reconnect_delay);
s->reconnect_delay = 1 + 2*s->reconnect_delay;
seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
if (seek_ret != target) {
av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRId64".\n", target);
return read_ret;
}
read_ret = http_buf_read(h, buf, size);
} else
s->reconnect_delay = 0;
return read_ret;
}
// Like http_read_stream(), but no short reads.
// Assumes partial reads are an error.
static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
{
int pos = 0;
while (pos < size) {
int len = http_read_stream(h, buf + pos, size - pos);
if (len < 0)
return len;
pos += len;
}
return pos;
}
static void update_metadata(HTTPContext *s, char *data)
{
char *key;
char *val;
char *end;
char *next = data;
while (*next) {
key = next;
val = strstr(key, "='");
if (!val)
break;
end = strstr(val, "';");
if (!end)
break;
*val = '\0';
*end = '\0';
val += 2;
av_dict_set(&s->metadata, key, val, 0);
next = end + 2;
}
}
static int store_icy(URLContext *h, int size)
{
HTTPContext *s = h->priv_data;
/* until next metadata packet */
int remaining = s->icy_metaint - s->icy_data_read;
if (remaining < 0)
return AVERROR_INVALIDDATA;
if (!remaining) {
/* The metadata packet is variable sized. It has a 1 byte header
* which sets the length of the packet (divided by 16). If it's 0,
* the metadata doesn't change. After the packet, icy_metaint bytes
* of normal data follows. */
uint8_t ch;
int len = http_read_stream_all(h, &ch, 1);
if (len < 0)
return len;
if (ch > 0) {
char data[255 * 16 + 1];
int ret;
len = ch * 16;
ret = http_read_stream_all(h, data, len);
if (ret < 0)
return ret;
data[len + 1] = 0;
if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
return ret;
update_metadata(s, data);
}
s->icy_data_read = 0;
remaining = s->icy_metaint;
}
return FFMIN(size, remaining);
}
static int http_read(URLContext *h, uint8_t *buf, int size)
{
HTTPContext *s = h->priv_data;
if (s->icy_metaint > 0) {
size = store_icy(h, size);
if (size < 0)
return size;
}
size = http_read_stream(h, buf, size);
if (size > 0)
s->icy_data_read += size;
return size;
}
/* used only when posting data */
static int http_write(URLContext *h, const uint8_t *buf, int size)
{
char temp[11] = ""; /* 32-bit hex + CRLF + nul */
int ret;
char crlf[] = "\r\n";
HTTPContext *s = h->priv_data;
if (!s->chunked_post) {
/* non-chunked data is sent without any special encoding */
return ffurl_write(s->hd, buf, size);
}
/* silently ignore zero-size data since chunk encoding that would
* signal EOF */
if (size > 0) {
/* upload data using chunked encoding */
snprintf(temp, sizeof(temp), "%x\r\n", size);
if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
(ret = ffurl_write(s->hd, buf, size)) < 0 ||
(ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
return ret;
}
return size;
}
static int http_shutdown(URLContext *h, int flags)
{
int ret = 0;
char footer[] = "0\r\n\r\n";
HTTPContext *s = h->priv_data;
/* signal end of chunked encoding if used */
if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
ret = ret > 0 ? 0 : ret;
s->end_chunked_post = 1;
}
return ret;
}
static int http_close(URLContext *h)
{
int ret = 0;
HTTPContext *s = h->priv_data;
#if CONFIG_ZLIB
inflateEnd(&s->inflate_stream);
av_freep(&s->inflate_buffer);
#endif /* CONFIG_ZLIB */
if (!s->end_chunked_post)
/* Close the write direction by sending the end of chunked encoding. */
ret = http_shutdown(h, h->flags);
if (s->hd)
ffurl_closep(&s->hd);
av_dict_free(&s->chained_options);
return ret;
}
static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
{
HTTPContext *s = h->priv_data;
URLContext *old_hd = s->hd;
int64_t old_off = s->off;
uint8_t old_buf[BUFFER_SIZE];
int old_buf_size, ret;
AVDictionary *options = NULL;
if (whence == AVSEEK_SIZE)
return s->filesize;
else if (!force_reconnect &&
((whence == SEEK_CUR && off == 0) ||
(whence == SEEK_SET && off == s->off)))
return s->off;
else if ((s->filesize == -1 && whence == SEEK_END))
return AVERROR(ENOSYS);
if (whence == SEEK_CUR)
off += s->off;
else if (whence == SEEK_END)
off += s->filesize;
else if (whence != SEEK_SET)
return AVERROR(EINVAL);
if (off < 0)
return AVERROR(EINVAL);
s->off = off;
if (s->off && h->is_streamed)
return AVERROR(ENOSYS);
/* we save the old context in case the seek fails */
old_buf_size = s->buf_end - s->buf_ptr;
memcpy(old_buf, s->buf_ptr, old_buf_size);
s->hd = NULL;
/* if it fails, continue on old connection */
if ((ret = http_open_cnx(h, &options)) < 0) {
av_dict_free(&options);
memcpy(s->buffer, old_buf, old_buf_size);
s->buf_ptr = s->buffer;
s->buf_end = s->buffer + old_buf_size;
s->hd = old_hd;
s->off = old_off;
return ret;
}
av_dict_free(&options);
ffurl_close(old_hd);
return off;
}
static int64_t http_seek(URLContext *h, int64_t off, int whence)
{
return http_seek_internal(h, off, whence, 0);
}
static int http_get_file_handle(URLContext *h)
{
HTTPContext *s = h->priv_data;
return ffurl_get_file_handle(s->hd);
}
#define HTTP_CLASS(flavor) \
static const AVClass flavor ## _context_class = { \
.class_name = # flavor, \
.item_name = av_default_item_name, \
.option = options, \
.version = LIBAVUTIL_VERSION_INT, \
}
#if CONFIG_HTTP_PROTOCOL
HTTP_CLASS(http);
const URLProtocol ff_http_protocol = {
.name = "http",
.url_open2 = http_open,
.url_accept = http_accept,
.url_handshake = http_handshake,
.url_read = http_read,
.url_write = http_write,
.url_seek = http_seek,
.url_close = http_close,
.url_get_file_handle = http_get_file_handle,
.url_shutdown = http_shutdown,
.priv_data_size = sizeof(HTTPContext),
.priv_data_class = &http_context_class,
.flags = URL_PROTOCOL_FLAG_NETWORK,
.default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
};
#endif /* CONFIG_HTTP_PROTOCOL */
#if CONFIG_HTTPS_PROTOCOL
HTTP_CLASS(https);
const URLProtocol ff_https_protocol = {
.name = "https",
.url_open2 = http_open,
.url_read = http_read,
.url_write = http_write,
.url_seek = http_seek,
.url_close = http_close,
.url_get_file_handle = http_get_file_handle,
.url_shutdown = http_shutdown,
.priv_data_size = sizeof(HTTPContext),
.priv_data_class = &https_context_class,
.flags = URL_PROTOCOL_FLAG_NETWORK,
.default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
};
#endif /* CONFIG_HTTPS_PROTOCOL */
#if CONFIG_HTTPPROXY_PROTOCOL
static int http_proxy_close(URLContext *h)
{
HTTPContext *s = h->priv_data;
if (s->hd)
ffurl_closep(&s->hd);
return 0;
}
static int http_proxy_open(URLContext *h, const char *uri, int flags)
{
HTTPContext *s = h->priv_data;
char hostname[1024], hoststr[1024];
char auth[1024], pathbuf[1024], *path;
char lower_url[100];
int port, ret = 0, attempts = 0;
HTTPAuthType cur_auth_type;
char *authstr;
int new_loc;
if( s->seekable == 1 )
h->is_streamed = 0;
else
h->is_streamed = 1;
av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
pathbuf, sizeof(pathbuf), uri);
ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
path = pathbuf;
if (*path == '/')
path++;
ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
NULL);
redo:
ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
&h->interrupt_callback, NULL,
h->protocol_whitelist, h->protocol_blacklist, h);
if (ret < 0)
return ret;
authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
path, "CONNECT");
snprintf(s->buffer, sizeof(s->buffer),
"CONNECT %s HTTP/1.1\r\n"
"Host: %s\r\n"
"Connection: close\r\n"
"%s%s"
"\r\n",
path,
hoststr,
authstr ? "Proxy-" : "", authstr ? authstr : "");
av_freep(&authstr);
if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
goto fail;
s->buf_ptr = s->buffer;
s->buf_end = s->buffer;
s->line_count = 0;
s->filesize = -1;
cur_auth_type = s->proxy_auth_state.auth_type;
/* Note: This uses buffering, potentially reading more than the
* HTTP header. If tunneling a protocol where the server starts
* the conversation, we might buffer part of that here, too.
* Reading that requires using the proper ffurl_read() function
* on this URLContext, not using the fd directly (as the tls
* protocol does). This shouldn't be an issue for tls though,
* since the client starts the conversation there, so there
* is no extra data that we might buffer up here.
*/
ret = http_read_header(h, &new_loc);
if (ret < 0)
goto fail;
attempts++;
if (s->http_code == 407 &&
(cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
ffurl_closep(&s->hd);
goto redo;
}
if (s->http_code < 400)
return 0;
ret = ff_http_averror(s->http_code, AVERROR(EIO));
fail:
http_proxy_close(h);
return ret;
}
static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
{
HTTPContext *s = h->priv_data;
return ffurl_write(s->hd, buf, size);
}
const URLProtocol ff_httpproxy_protocol = {
.name = "httpproxy",
.url_open = http_proxy_open,
.url_read = http_buf_read,
.url_write = http_proxy_write,
.url_close = http_proxy_close,
.url_get_file_handle = http_get_file_handle,
.priv_data_size = sizeof(HTTPContext),
.flags = URL_PROTOCOL_FLAG_NETWORK,
};
#endif /* CONFIG_HTTPPROXY_PROTOCOL */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4835_0 |
crossvul-cpp_data_good_1537_2 | /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2009 by the Massachusetts Institute of Technology.
* All Rights Reserved.
*
* Export of this software from the United States of America may
* require a specific license from the United States Government.
* It is the responsibility of any person or organization contemplating
* export to obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of M.I.T. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. Furthermore if you modify this software you must label
* your software as modified software and not distribute it in such a
* fashion that it might be confused with the original M.I.T. software.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*/
#include "k5-int.h"
#include "gssapiP_krb5.h"
/*
* IAKERB implementation
*/
extern int gssint_get_der_length(unsigned char **, OM_uint32, unsigned int*);
enum iakerb_state {
IAKERB_AS_REQ, /* acquiring ticket with initial creds */
IAKERB_TGS_REQ, /* acquiring ticket with TGT */
IAKERB_AP_REQ /* hand-off to normal GSS AP-REQ exchange */
};
struct _iakerb_ctx_id_rec {
krb5_magic magic; /* KG_IAKERB_CONTEXT */
krb5_context k5c;
gss_cred_id_t defcred; /* Initiator only */
enum iakerb_state state; /* Initiator only */
krb5_init_creds_context icc; /* Initiator only */
krb5_tkt_creds_context tcc; /* Initiator only */
gss_ctx_id_t gssc;
krb5_data conv; /* conversation for checksumming */
unsigned int count; /* number of round trips */
int initiate;
int established;
krb5_get_init_creds_opt *gic_opts;
};
#define IAKERB_MAX_HOPS ( 16 /* MAX_IN_TKT_LOOPS */ + KRB5_REFERRAL_MAXHOPS )
typedef struct _iakerb_ctx_id_rec iakerb_ctx_id_rec;
typedef iakerb_ctx_id_rec *iakerb_ctx_id_t;
/*
* Release an IAKERB context
*/
static void
iakerb_release_context(iakerb_ctx_id_t ctx)
{
OM_uint32 tmp;
if (ctx == NULL)
return;
krb5_gss_release_cred(&tmp, &ctx->defcred);
krb5_init_creds_free(ctx->k5c, ctx->icc);
krb5_tkt_creds_free(ctx->k5c, ctx->tcc);
krb5_gss_delete_sec_context(&tmp, &ctx->gssc, NULL);
krb5_free_data_contents(ctx->k5c, &ctx->conv);
krb5_get_init_creds_opt_free(ctx->k5c, ctx->gic_opts);
krb5_free_context(ctx->k5c);
free(ctx);
}
/*
* Create a IAKERB-FINISHED structure containing a checksum of
* the entire IAKERB exchange.
*/
krb5_error_code
iakerb_make_finished(krb5_context context,
krb5_key key,
const krb5_data *conv,
krb5_data **finished)
{
krb5_error_code code;
krb5_iakerb_finished iaf;
*finished = NULL;
memset(&iaf, 0, sizeof(iaf));
if (key == NULL)
return KRB5KDC_ERR_NULL_KEY;
code = krb5_k_make_checksum(context, 0, key, KRB5_KEYUSAGE_IAKERB_FINISHED,
conv, &iaf.checksum);
if (code != 0)
return code;
code = encode_krb5_iakerb_finished(&iaf, finished);
krb5_free_checksum_contents(context, &iaf.checksum);
return code;
}
/*
* Verify a IAKERB-FINISHED structure submitted by the initiator
*/
krb5_error_code
iakerb_verify_finished(krb5_context context,
krb5_key key,
const krb5_data *conv,
const krb5_data *finished)
{
krb5_error_code code;
krb5_iakerb_finished *iaf;
krb5_boolean valid = FALSE;
if (key == NULL)
return KRB5KDC_ERR_NULL_KEY;
code = decode_krb5_iakerb_finished(finished, &iaf);
if (code != 0)
return code;
code = krb5_k_verify_checksum(context, key, KRB5_KEYUSAGE_IAKERB_FINISHED,
conv, &iaf->checksum, &valid);
if (code == 0 && valid == FALSE)
code = KRB5KRB_AP_ERR_BAD_INTEGRITY;
krb5_free_iakerb_finished(context, iaf);
return code;
}
/*
* Save a token for future checksumming.
*/
static krb5_error_code
iakerb_save_token(iakerb_ctx_id_t ctx, const gss_buffer_t token)
{
char *p;
p = realloc(ctx->conv.data, ctx->conv.length + token->length);
if (p == NULL)
return ENOMEM;
memcpy(p + ctx->conv.length, token->value, token->length);
ctx->conv.data = p;
ctx->conv.length += token->length;
return 0;
}
/*
* Parse a token into IAKERB-HEADER and KRB-KDC-REQ/REP
*/
static krb5_error_code
iakerb_parse_token(iakerb_ctx_id_t ctx,
int initialContextToken,
const gss_buffer_t token,
krb5_data *realm,
krb5_data **cookie,
krb5_data *request)
{
krb5_error_code code;
krb5_iakerb_header *iah = NULL;
unsigned int bodysize, lenlen;
int length;
unsigned char *ptr;
int flags = 0;
krb5_data data;
if (token == GSS_C_NO_BUFFER || token->length == 0) {
code = KRB5_BAD_MSIZE;
goto cleanup;
}
if (initialContextToken)
flags |= G_VFY_TOKEN_HDR_WRAPPER_REQUIRED;
ptr = token->value;
code = g_verify_token_header(gss_mech_iakerb,
&bodysize, &ptr,
IAKERB_TOK_PROXY,
token->length, flags);
if (code != 0)
goto cleanup;
data.data = (char *)ptr;
if (bodysize-- == 0 || *ptr++ != 0x30 /* SEQUENCE */) {
code = ASN1_BAD_ID;
goto cleanup;
}
length = gssint_get_der_length(&ptr, bodysize, &lenlen);
if (length < 0 || bodysize - lenlen < (unsigned int)length) {
code = KRB5_BAD_MSIZE;
goto cleanup;
}
data.length = 1 /* SEQUENCE */ + lenlen + length;
ptr += length;
bodysize -= (lenlen + length);
code = decode_krb5_iakerb_header(&data, &iah);
if (code != 0)
goto cleanup;
if (realm != NULL) {
*realm = iah->target_realm;
iah->target_realm.data = NULL;
}
if (cookie != NULL) {
*cookie = iah->cookie;
iah->cookie = NULL;
}
request->data = (char *)ptr;
request->length = bodysize;
assert(request->data + request->length ==
(char *)token->value + token->length);
cleanup:
krb5_free_iakerb_header(ctx->k5c, iah);
return code;
}
/*
* Create a token from IAKERB-HEADER and KRB-KDC-REQ/REP
*/
static krb5_error_code
iakerb_make_token(iakerb_ctx_id_t ctx,
krb5_data *realm,
krb5_data *cookie,
krb5_data *request,
int initialContextToken,
gss_buffer_t token)
{
krb5_error_code code;
krb5_iakerb_header iah;
krb5_data *data = NULL;
char *p;
unsigned int tokenSize;
unsigned char *q;
token->value = NULL;
token->length = 0;
/*
* Assemble the IAKERB-HEADER from the realm and cookie
*/
memset(&iah, 0, sizeof(iah));
iah.target_realm = *realm;
iah.cookie = cookie;
code = encode_krb5_iakerb_header(&iah, &data);
if (code != 0)
goto cleanup;
/*
* Concatenate Kerberos request.
*/
p = realloc(data->data, data->length + request->length);
if (p == NULL) {
code = ENOMEM;
goto cleanup;
}
data->data = p;
if (request->length > 0)
memcpy(data->data + data->length, request->data, request->length);
data->length += request->length;
if (initialContextToken)
tokenSize = g_token_size(gss_mech_iakerb, data->length);
else
tokenSize = 2 + data->length;
token->value = q = gssalloc_malloc(tokenSize);
if (q == NULL) {
code = ENOMEM;
goto cleanup;
}
token->length = tokenSize;
if (initialContextToken) {
g_make_token_header(gss_mech_iakerb, data->length, &q,
IAKERB_TOK_PROXY);
} else {
store_16_be(IAKERB_TOK_PROXY, q);
q += 2;
}
memcpy(q, data->data, data->length);
q += data->length;
assert(q == (unsigned char *)token->value + token->length);
cleanup:
krb5_free_data(ctx->k5c, data);
return code;
}
/*
* Parse the IAKERB token in input_token and send the contained KDC
* request to the KDC for the realm.
*
* Wrap the KDC reply in output_token.
*/
static krb5_error_code
iakerb_acceptor_step(iakerb_ctx_id_t ctx,
int initialContextToken,
const gss_buffer_t input_token,
gss_buffer_t output_token)
{
krb5_error_code code;
krb5_data request = empty_data(), reply = empty_data();
krb5_data realm = empty_data();
OM_uint32 tmp;
int tcp_only, use_master;
krb5_ui_4 kdc_code;
output_token->length = 0;
output_token->value = NULL;
if (ctx->count >= IAKERB_MAX_HOPS) {
code = KRB5_KDC_UNREACH;
goto cleanup;
}
code = iakerb_parse_token(ctx, initialContextToken, input_token, &realm,
NULL, &request);
if (code != 0)
goto cleanup;
if (realm.length == 0 || request.length == 0) {
code = KRB5_BAD_MSIZE;
goto cleanup;
}
code = iakerb_save_token(ctx, input_token);
if (code != 0)
goto cleanup;
for (tcp_only = 0; tcp_only <= 1; tcp_only++) {
use_master = 0;
code = krb5_sendto_kdc(ctx->k5c, &request, &realm,
&reply, &use_master, tcp_only);
if (code == 0 && krb5_is_krb_error(&reply)) {
krb5_error *error;
code = decode_krb5_error(&reply, &error);
if (code != 0)
goto cleanup;
kdc_code = error->error;
krb5_free_error(ctx->k5c, error);
if (kdc_code == KRB_ERR_RESPONSE_TOO_BIG) {
krb5_free_data_contents(ctx->k5c, &reply);
reply = empty_data();
continue;
}
}
break;
}
if (code == KRB5_KDC_UNREACH || code == KRB5_REALM_UNKNOWN) {
krb5_error error;
memset(&error, 0, sizeof(error));
if (code == KRB5_KDC_UNREACH)
error.error = KRB_AP_ERR_IAKERB_KDC_NO_RESPONSE;
else if (code == KRB5_REALM_UNKNOWN)
error.error = KRB_AP_ERR_IAKERB_KDC_NOT_FOUND;
code = krb5_mk_error(ctx->k5c, &error, &reply);
if (code != 0)
goto cleanup;
} else if (code != 0)
goto cleanup;
code = iakerb_make_token(ctx, &realm, NULL, &reply, 0, output_token);
if (code != 0)
goto cleanup;
code = iakerb_save_token(ctx, output_token);
if (code != 0)
goto cleanup;
ctx->count++;
cleanup:
if (code != 0)
gss_release_buffer(&tmp, output_token);
/* request is a pointer into input_token, no need to free */
krb5_free_data_contents(ctx->k5c, &realm);
krb5_free_data_contents(ctx->k5c, &reply);
return code;
}
/*
* Initialise the krb5_init_creds context for the IAKERB context
*/
static krb5_error_code
iakerb_init_creds_ctx(iakerb_ctx_id_t ctx,
krb5_gss_cred_id_t cred,
OM_uint32 time_req)
{
krb5_error_code code;
if (cred->iakerb_mech == 0) {
code = EINVAL;
goto cleanup;
}
assert(cred->name != NULL);
assert(cred->name->princ != NULL);
code = krb5_get_init_creds_opt_alloc(ctx->k5c, &ctx->gic_opts);
if (code != 0)
goto cleanup;
if (time_req != 0 && time_req != GSS_C_INDEFINITE)
krb5_get_init_creds_opt_set_tkt_life(ctx->gic_opts, time_req);
code = krb5_get_init_creds_opt_set_out_ccache(ctx->k5c, ctx->gic_opts,
cred->ccache);
if (code != 0)
goto cleanup;
code = krb5_init_creds_init(ctx->k5c,
cred->name->princ,
NULL, /* prompter */
NULL, /* data */
0, /* start_time */
ctx->gic_opts,
&ctx->icc);
if (code != 0)
goto cleanup;
if (cred->password != NULL) {
code = krb5_init_creds_set_password(ctx->k5c, ctx->icc,
cred->password);
} else {
code = krb5_init_creds_set_keytab(ctx->k5c, ctx->icc,
cred->client_keytab);
}
if (code != 0)
goto cleanup;
cleanup:
return code;
}
/*
* Initialise the krb5_tkt_creds context for the IAKERB context
*/
static krb5_error_code
iakerb_tkt_creds_ctx(iakerb_ctx_id_t ctx,
krb5_gss_cred_id_t cred,
krb5_gss_name_t name,
OM_uint32 time_req)
{
krb5_error_code code;
krb5_creds creds;
krb5_timestamp now;
assert(cred->name != NULL);
assert(cred->name->princ != NULL);
memset(&creds, 0, sizeof(creds));
creds.client = cred->name->princ;
creds.server = name->princ;
if (time_req != 0 && time_req != GSS_C_INDEFINITE) {
code = krb5_timeofday(ctx->k5c, &now);
if (code != 0)
goto cleanup;
creds.times.endtime = now + time_req;
}
if (cred->name->ad_context != NULL) {
code = krb5_authdata_export_authdata(ctx->k5c,
cred->name->ad_context,
AD_USAGE_TGS_REQ,
&creds.authdata);
if (code != 0)
goto cleanup;
}
code = krb5_tkt_creds_init(ctx->k5c, cred->ccache, &creds, 0, &ctx->tcc);
if (code != 0)
goto cleanup;
cleanup:
krb5_free_authdata(ctx->k5c, creds.authdata);
return code;
}
/*
* Parse the IAKERB token in input_token and process the KDC
* response.
*
* Emit the next KDC request, if any, in output_token.
*/
static krb5_error_code
iakerb_initiator_step(iakerb_ctx_id_t ctx,
krb5_gss_cred_id_t cred,
krb5_gss_name_t name,
OM_uint32 time_req,
const gss_buffer_t input_token,
gss_buffer_t output_token)
{
krb5_error_code code = 0;
krb5_data in = empty_data(), out = empty_data(), realm = empty_data();
krb5_data *cookie = NULL;
OM_uint32 tmp;
unsigned int flags = 0;
krb5_ticket_times times;
output_token->length = 0;
output_token->value = NULL;
if (input_token != GSS_C_NO_BUFFER) {
code = iakerb_parse_token(ctx, 0, input_token, NULL, &cookie, &in);
if (code != 0)
goto cleanup;
code = iakerb_save_token(ctx, input_token);
if (code != 0)
goto cleanup;
}
switch (ctx->state) {
case IAKERB_AS_REQ:
if (ctx->icc == NULL) {
code = iakerb_init_creds_ctx(ctx, cred, time_req);
if (code != 0)
goto cleanup;
}
code = krb5_init_creds_step(ctx->k5c, ctx->icc, &in, &out, &realm,
&flags);
if (code != 0) {
if (cred->have_tgt) {
/* We were trying to refresh; keep going with current creds. */
ctx->state = IAKERB_TGS_REQ;
krb5_clear_error_message(ctx->k5c);
} else {
goto cleanup;
}
} else if (!(flags & KRB5_INIT_CREDS_STEP_FLAG_CONTINUE)) {
krb5_init_creds_get_times(ctx->k5c, ctx->icc, ×);
kg_cred_set_initial_refresh(ctx->k5c, cred, ×);
cred->expire = times.endtime;
krb5_init_creds_free(ctx->k5c, ctx->icc);
ctx->icc = NULL;
ctx->state = IAKERB_TGS_REQ;
} else
break;
in = empty_data();
/* Done with AS request; fall through to TGS request. */
case IAKERB_TGS_REQ:
if (ctx->tcc == NULL) {
code = iakerb_tkt_creds_ctx(ctx, cred, name, time_req);
if (code != 0)
goto cleanup;
}
code = krb5_tkt_creds_step(ctx->k5c, ctx->tcc, &in, &out, &realm,
&flags);
if (code != 0)
goto cleanup;
if (!(flags & KRB5_TKT_CREDS_STEP_FLAG_CONTINUE)) {
krb5_tkt_creds_get_times(ctx->k5c, ctx->tcc, ×);
cred->expire = times.endtime;
krb5_tkt_creds_free(ctx->k5c, ctx->tcc);
ctx->tcc = NULL;
ctx->state = IAKERB_AP_REQ;
} else
break;
/* Done with TGS request; fall through to AP request. */
case IAKERB_AP_REQ:
break;
}
if (out.length != 0) {
assert(ctx->state != IAKERB_AP_REQ);
code = iakerb_make_token(ctx, &realm, cookie, &out,
(input_token == GSS_C_NO_BUFFER),
output_token);
if (code != 0)
goto cleanup;
/* Save the token for generating a future checksum */
code = iakerb_save_token(ctx, output_token);
if (code != 0)
goto cleanup;
ctx->count++;
}
cleanup:
if (code != 0)
gss_release_buffer(&tmp, output_token);
krb5_free_data(ctx->k5c, cookie);
krb5_free_data_contents(ctx->k5c, &out);
krb5_free_data_contents(ctx->k5c, &realm);
return code;
}
/*
* Determine the starting IAKERB state for a context. If we already
* have a ticket, we may not need to do IAKERB at all.
*/
static krb5_error_code
iakerb_get_initial_state(iakerb_ctx_id_t ctx,
krb5_gss_cred_id_t cred,
krb5_gss_name_t target,
OM_uint32 time_req,
enum iakerb_state *state)
{
krb5_creds in_creds, *out_creds = NULL;
krb5_error_code code;
memset(&in_creds, 0, sizeof(in_creds));
in_creds.client = cred->name->princ;
in_creds.server = target->princ;
if (cred->name->ad_context != NULL) {
code = krb5_authdata_export_authdata(ctx->k5c,
cred->name->ad_context,
AD_USAGE_TGS_REQ,
&in_creds.authdata);
if (code != 0)
goto cleanup;
}
if (time_req != 0 && time_req != GSS_C_INDEFINITE) {
krb5_timestamp now;
code = krb5_timeofday(ctx->k5c, &now);
if (code != 0)
goto cleanup;
in_creds.times.endtime = now + time_req;
}
/* Make an AS request if we have no creds or it's time to refresh them. */
if (cred->expire == 0 || kg_cred_time_to_refresh(ctx->k5c, cred)) {
*state = IAKERB_AS_REQ;
code = 0;
goto cleanup;
}
code = krb5_get_credentials(ctx->k5c, KRB5_GC_CACHED, cred->ccache,
&in_creds, &out_creds);
if (code == KRB5_CC_NOTFOUND || code == KRB5_CC_NOT_KTYPE) {
*state = cred->have_tgt ? IAKERB_TGS_REQ : IAKERB_AS_REQ;
code = 0;
} else if (code == 0) {
*state = IAKERB_AP_REQ;
krb5_free_creds(ctx->k5c, out_creds);
}
cleanup:
krb5_free_authdata(ctx->k5c, in_creds.authdata);
return code;
}
/*
* Allocate and initialise an IAKERB context
*/
static krb5_error_code
iakerb_alloc_context(iakerb_ctx_id_t *pctx, int initiate)
{
iakerb_ctx_id_t ctx;
krb5_error_code code;
*pctx = NULL;
ctx = k5alloc(sizeof(*ctx), &code);
if (ctx == NULL)
goto cleanup;
ctx->defcred = GSS_C_NO_CREDENTIAL;
ctx->magic = KG_IAKERB_CONTEXT;
ctx->state = IAKERB_AS_REQ;
ctx->count = 0;
ctx->initiate = initiate;
ctx->established = 0;
code = krb5_gss_init_context(&ctx->k5c);
if (code != 0)
goto cleanup;
*pctx = ctx;
cleanup:
if (code != 0)
iakerb_release_context(ctx);
return code;
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_delete_sec_context(OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
gss_buffer_t output_token)
{
iakerb_ctx_id_t iakerb_ctx = (iakerb_ctx_id_t)*context_handle;
if (output_token != GSS_C_NO_BUFFER) {
output_token->length = 0;
output_token->value = NULL;
}
*minor_status = 0;
*context_handle = GSS_C_NO_CONTEXT;
iakerb_release_context(iakerb_ctx);
return GSS_S_COMPLETE;
}
static krb5_boolean
iakerb_is_iakerb_token(const gss_buffer_t token)
{
krb5_error_code code;
unsigned int bodysize = token->length;
unsigned char *ptr = token->value;
code = g_verify_token_header(gss_mech_iakerb,
&bodysize, &ptr,
IAKERB_TOK_PROXY,
token->length, 0);
return (code == 0);
}
static void
iakerb_make_exts(iakerb_ctx_id_t ctx, krb5_gss_ctx_ext_rec *exts)
{
memset(exts, 0, sizeof(*exts));
if (ctx->conv.length != 0)
exts->iakerb.conv = &ctx->conv;
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_accept_sec_context(OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
gss_cred_id_t verifier_cred_handle,
gss_buffer_t input_token,
gss_channel_bindings_t input_chan_bindings,
gss_name_t *src_name,
gss_OID *mech_type,
gss_buffer_t output_token,
OM_uint32 *ret_flags,
OM_uint32 *time_rec,
gss_cred_id_t *delegated_cred_handle)
{
OM_uint32 major_status = GSS_S_FAILURE;
OM_uint32 code;
iakerb_ctx_id_t ctx;
int initialContextToken = (*context_handle == GSS_C_NO_CONTEXT);
if (initialContextToken) {
code = iakerb_alloc_context(&ctx, 0);
if (code != 0)
goto cleanup;
} else
ctx = (iakerb_ctx_id_t)*context_handle;
if (iakerb_is_iakerb_token(input_token)) {
if (ctx->gssc != GSS_C_NO_CONTEXT) {
/* We shouldn't get an IAKERB token now. */
code = G_WRONG_TOKID;
major_status = GSS_S_DEFECTIVE_TOKEN;
goto cleanup;
}
code = iakerb_acceptor_step(ctx, initialContextToken,
input_token, output_token);
if (code == (OM_uint32)KRB5_BAD_MSIZE)
major_status = GSS_S_DEFECTIVE_TOKEN;
if (code != 0)
goto cleanup;
if (initialContextToken) {
*context_handle = (gss_ctx_id_t)ctx;
ctx = NULL;
}
if (src_name != NULL)
*src_name = GSS_C_NO_NAME;
if (mech_type != NULL)
*mech_type = (gss_OID)gss_mech_iakerb;
if (ret_flags != NULL)
*ret_flags = 0;
if (time_rec != NULL)
*time_rec = 0;
if (delegated_cred_handle != NULL)
*delegated_cred_handle = GSS_C_NO_CREDENTIAL;
major_status = GSS_S_CONTINUE_NEEDED;
} else {
krb5_gss_ctx_ext_rec exts;
iakerb_make_exts(ctx, &exts);
major_status = krb5_gss_accept_sec_context_ext(&code,
&ctx->gssc,
verifier_cred_handle,
input_token,
input_chan_bindings,
src_name,
NULL,
output_token,
ret_flags,
time_rec,
delegated_cred_handle,
&exts);
if (major_status == GSS_S_COMPLETE)
ctx->established = 1;
if (mech_type != NULL)
*mech_type = (gss_OID)gss_mech_krb5;
}
cleanup:
if (initialContextToken && GSS_ERROR(major_status)) {
iakerb_release_context(ctx);
*context_handle = GSS_C_NO_CONTEXT;
}
*minor_status = code;
return major_status;
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_init_sec_context(OM_uint32 *minor_status,
gss_cred_id_t claimant_cred_handle,
gss_ctx_id_t *context_handle,
gss_name_t target_name,
gss_OID mech_type,
OM_uint32 req_flags,
OM_uint32 time_req,
gss_channel_bindings_t input_chan_bindings,
gss_buffer_t input_token,
gss_OID *actual_mech_type,
gss_buffer_t output_token,
OM_uint32 *ret_flags,
OM_uint32 *time_rec)
{
OM_uint32 major_status = GSS_S_FAILURE;
krb5_error_code code;
iakerb_ctx_id_t ctx;
krb5_gss_cred_id_t kcred;
krb5_gss_name_t kname;
krb5_boolean cred_locked = FALSE;
int initialContextToken = (*context_handle == GSS_C_NO_CONTEXT);
if (initialContextToken) {
code = iakerb_alloc_context(&ctx, 1);
if (code != 0) {
*minor_status = code;
goto cleanup;
}
if (claimant_cred_handle == GSS_C_NO_CREDENTIAL) {
major_status = iakerb_gss_acquire_cred(minor_status, NULL,
GSS_C_INDEFINITE,
GSS_C_NULL_OID_SET,
GSS_C_INITIATE,
&ctx->defcred, NULL, NULL);
if (GSS_ERROR(major_status))
goto cleanup;
claimant_cred_handle = ctx->defcred;
}
} else {
ctx = (iakerb_ctx_id_t)*context_handle;
if (claimant_cred_handle == GSS_C_NO_CREDENTIAL)
claimant_cred_handle = ctx->defcred;
}
kname = (krb5_gss_name_t)target_name;
major_status = kg_cred_resolve(minor_status, ctx->k5c,
claimant_cred_handle, target_name);
if (GSS_ERROR(major_status))
goto cleanup;
cred_locked = TRUE;
kcred = (krb5_gss_cred_id_t)claimant_cred_handle;
major_status = GSS_S_FAILURE;
if (initialContextToken) {
code = iakerb_get_initial_state(ctx, kcred, kname, time_req,
&ctx->state);
if (code != 0) {
*minor_status = code;
goto cleanup;
}
*context_handle = (gss_ctx_id_t)ctx;
}
if (ctx->state != IAKERB_AP_REQ) {
/* We need to do IAKERB. */
code = iakerb_initiator_step(ctx,
kcred,
kname,
time_req,
input_token,
output_token);
if (code == KRB5_BAD_MSIZE)
major_status = GSS_S_DEFECTIVE_TOKEN;
if (code != 0) {
*minor_status = code;
goto cleanup;
}
}
if (ctx->state == IAKERB_AP_REQ) {
krb5_gss_ctx_ext_rec exts;
if (cred_locked) {
k5_mutex_unlock(&kcred->lock);
cred_locked = FALSE;
}
iakerb_make_exts(ctx, &exts);
if (ctx->gssc == GSS_C_NO_CONTEXT)
input_token = GSS_C_NO_BUFFER;
/* IAKERB is finished, or we skipped to Kerberos directly. */
major_status = krb5_gss_init_sec_context_ext(minor_status,
(gss_cred_id_t) kcred,
&ctx->gssc,
target_name,
(gss_OID)gss_mech_iakerb,
req_flags,
time_req,
input_chan_bindings,
input_token,
NULL,
output_token,
ret_flags,
time_rec,
&exts);
if (major_status == GSS_S_COMPLETE)
ctx->established = 1;
if (actual_mech_type != NULL)
*actual_mech_type = (gss_OID)gss_mech_krb5;
} else {
if (actual_mech_type != NULL)
*actual_mech_type = (gss_OID)gss_mech_iakerb;
if (ret_flags != NULL)
*ret_flags = 0;
if (time_rec != NULL)
*time_rec = 0;
major_status = GSS_S_CONTINUE_NEEDED;
}
cleanup:
if (cred_locked)
k5_mutex_unlock(&kcred->lock);
if (initialContextToken && GSS_ERROR(major_status)) {
iakerb_release_context(ctx);
*context_handle = GSS_C_NO_CONTEXT;
}
return major_status;
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_unwrap(OM_uint32 *minor_status, gss_ctx_id_t context_handle,
gss_buffer_t input_message_buffer,
gss_buffer_t output_message_buffer, int *conf_state,
gss_qop_t *qop_state)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
if (ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_NO_CONTEXT;
return krb5_gss_unwrap(minor_status, ctx->gssc, input_message_buffer,
output_message_buffer, conf_state, qop_state);
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_wrap(OM_uint32 *minor_status, gss_ctx_id_t context_handle,
int conf_req_flag, gss_qop_t qop_req,
gss_buffer_t input_message_buffer, int *conf_state,
gss_buffer_t output_message_buffer)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
if (ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_NO_CONTEXT;
return krb5_gss_wrap(minor_status, ctx->gssc, conf_req_flag, qop_req,
input_message_buffer, conf_state,
output_message_buffer);
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_process_context_token(OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_buffer_t token_buffer)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
if (ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_DEFECTIVE_TOKEN;
return krb5_gss_process_context_token(minor_status, ctx->gssc,
token_buffer);
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_context_time(OM_uint32 *minor_status, gss_ctx_id_t context_handle,
OM_uint32 *time_rec)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
if (ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_NO_CONTEXT;
return krb5_gss_context_time(minor_status, ctx->gssc, time_rec);
}
#ifndef LEAN_CLIENT
OM_uint32 KRB5_CALLCONV
iakerb_gss_export_sec_context(OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
gss_buffer_t interprocess_token)
{
OM_uint32 maj;
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)*context_handle;
/* We don't currently support exporting partially established contexts. */
if (!ctx->established)
return GSS_S_UNAVAILABLE;
maj = krb5_gss_export_sec_context(minor_status, &ctx->gssc,
interprocess_token);
if (ctx->gssc == GSS_C_NO_CONTEXT) {
iakerb_release_context(ctx);
*context_handle = GSS_C_NO_CONTEXT;
}
return maj;
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_import_sec_context(OM_uint32 *minor_status,
gss_buffer_t interprocess_token,
gss_ctx_id_t *context_handle)
{
OM_uint32 maj, tmpmin;
krb5_error_code code;
gss_ctx_id_t gssc;
krb5_gss_ctx_id_t kctx;
iakerb_ctx_id_t ctx;
maj = krb5_gss_import_sec_context(minor_status, interprocess_token, &gssc);
if (maj != GSS_S_COMPLETE)
return maj;
kctx = (krb5_gss_ctx_id_t)gssc;
if (!kctx->established) {
/* We don't currently support importing partially established
* contexts. */
krb5_gss_delete_sec_context(&tmpmin, &gssc, GSS_C_NO_BUFFER);
return GSS_S_FAILURE;
}
code = iakerb_alloc_context(&ctx, kctx->initiate);
if (code != 0) {
krb5_gss_delete_sec_context(&tmpmin, &gssc, GSS_C_NO_BUFFER);
*minor_status = code;
return GSS_S_FAILURE;
}
ctx->gssc = gssc;
ctx->established = 1;
*context_handle = (gss_ctx_id_t)ctx;
return GSS_S_COMPLETE;
}
#endif /* LEAN_CLIENT */
OM_uint32 KRB5_CALLCONV
iakerb_gss_inquire_context(OM_uint32 *minor_status,
gss_ctx_id_t context_handle, gss_name_t *src_name,
gss_name_t *targ_name, OM_uint32 *lifetime_rec,
gss_OID *mech_type, OM_uint32 *ctx_flags,
int *initiate, int *opened)
{
OM_uint32 ret;
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
if (src_name != NULL)
*src_name = GSS_C_NO_NAME;
if (targ_name != NULL)
*targ_name = GSS_C_NO_NAME;
if (lifetime_rec != NULL)
*lifetime_rec = 0;
if (mech_type != NULL)
*mech_type = (gss_OID)gss_mech_iakerb;
if (ctx_flags != NULL)
*ctx_flags = 0;
if (initiate != NULL)
*initiate = ctx->initiate;
if (opened != NULL)
*opened = ctx->established;
if (ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_COMPLETE;
ret = krb5_gss_inquire_context(minor_status, ctx->gssc, src_name,
targ_name, lifetime_rec, mech_type,
ctx_flags, initiate, opened);
if (!ctx->established) {
/* Report IAKERB as the mech OID until the context is established. */
if (mech_type != NULL)
*mech_type = (gss_OID)gss_mech_iakerb;
/* We don't support exporting partially-established contexts. */
if (ctx_flags != NULL)
*ctx_flags &= ~GSS_C_TRANS_FLAG;
}
return ret;
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_wrap_size_limit(OM_uint32 *minor_status,
gss_ctx_id_t context_handle, int conf_req_flag,
gss_qop_t qop_req, OM_uint32 req_output_size,
OM_uint32 *max_input_size)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
if (ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_NO_CONTEXT;
return krb5_gss_wrap_size_limit(minor_status, ctx->gssc, conf_req_flag,
qop_req, req_output_size, max_input_size);
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_get_mic(OM_uint32 *minor_status, gss_ctx_id_t context_handle,
gss_qop_t qop_req, gss_buffer_t message_buffer,
gss_buffer_t message_token)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
if (ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_NO_CONTEXT;
return krb5_gss_get_mic(minor_status, ctx->gssc, qop_req, message_buffer,
message_token);
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_verify_mic(OM_uint32 *minor_status, gss_ctx_id_t context_handle,
gss_buffer_t msg_buffer, gss_buffer_t token_buffer,
gss_qop_t *qop_state)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
if (ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_NO_CONTEXT;
return krb5_gss_verify_mic(minor_status, ctx->gssc, msg_buffer,
token_buffer, qop_state);
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_inquire_sec_context_by_oid(OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_OID desired_object,
gss_buffer_set_t *data_set)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
if (ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_UNAVAILABLE;
return krb5_gss_inquire_sec_context_by_oid(minor_status, ctx->gssc,
desired_object, data_set);
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_set_sec_context_option(OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
const gss_OID desired_object,
const gss_buffer_t value)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)*context_handle;
if (ctx == NULL || ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_UNAVAILABLE;
return krb5_gss_set_sec_context_option(minor_status, &ctx->gssc,
desired_object, value);
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_wrap_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle,
int conf_req_flag, gss_qop_t qop_req, int *conf_state,
gss_iov_buffer_desc *iov, int iov_count)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
if (ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_NO_CONTEXT;
return krb5_gss_wrap_iov(minor_status, ctx->gssc, conf_req_flag, qop_req,
conf_state, iov, iov_count);
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_unwrap_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle,
int *conf_state, gss_qop_t *qop_state,
gss_iov_buffer_desc *iov, int iov_count)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
if (ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_NO_CONTEXT;
return krb5_gss_unwrap_iov(minor_status, ctx->gssc, conf_state, qop_state,
iov, iov_count);
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_wrap_iov_length(OM_uint32 *minor_status,
gss_ctx_id_t context_handle, int conf_req_flag,
gss_qop_t qop_req, int *conf_state,
gss_iov_buffer_desc *iov, int iov_count)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
if (ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_NO_CONTEXT;
return krb5_gss_wrap_iov_length(minor_status, ctx->gssc, conf_req_flag,
qop_req, conf_state, iov, iov_count);
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_pseudo_random(OM_uint32 *minor_status, gss_ctx_id_t context_handle,
int prf_key, const gss_buffer_t prf_in,
ssize_t desired_output_len, gss_buffer_t prf_out)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
if (ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_NO_CONTEXT;
return krb5_gss_pseudo_random(minor_status, ctx->gssc, prf_key, prf_in,
desired_output_len, prf_out);
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_get_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle,
gss_qop_t qop_req, gss_iov_buffer_desc *iov,
int iov_count)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
if (ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_NO_CONTEXT;
return krb5_gss_get_mic_iov(minor_status, ctx->gssc, qop_req, iov,
iov_count);
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_verify_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle,
gss_qop_t *qop_state, gss_iov_buffer_desc *iov,
int iov_count)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
if (ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_NO_CONTEXT;
return krb5_gss_verify_mic_iov(minor_status, ctx->gssc, qop_state, iov,
iov_count);
}
OM_uint32 KRB5_CALLCONV
iakerb_gss_get_mic_iov_length(OM_uint32 *minor_status,
gss_ctx_id_t context_handle, gss_qop_t qop_req,
gss_iov_buffer_desc *iov, int iov_count)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
if (ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_NO_CONTEXT;
return krb5_gss_get_mic_iov_length(minor_status, ctx->gssc, qop_req, iov,
iov_count);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_1537_2 |
crossvul-cpp_data_good_2183_1 | /* $Id: miniwget.c,v 1.60 2013/10/07 10:03:16 nanard Exp $ */
/* Project : miniupnp
* Website : http://miniupnp.free.fr/
* Author : Thomas Bernard
* Copyright (c) 2005-2013 Thomas Bernard
* This software is subject to the conditions detailed in the
* LICENCE file provided in this distribution. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#include <io.h>
#define MAXHOSTNAMELEN 64
#define MIN(x,y) (((x)<(y))?(x):(y))
#define snprintf _snprintf
#define socklen_t int
#ifndef strncasecmp
#if defined(_MSC_VER) && (_MSC_VER >= 1400)
#define strncasecmp _memicmp
#else /* defined(_MSC_VER) && (_MSC_VER >= 1400) */
#define strncasecmp memicmp
#endif /* defined(_MSC_VER) && (_MSC_VER >= 1400) */
#endif /* #ifndef strncasecmp */
#else /* #ifdef _WIN32 */
#include <unistd.h>
#include <sys/param.h>
#if defined(__amigaos__) && !defined(__amigaos4__)
#define socklen_t int
#else /* #if defined(__amigaos__) && !defined(__amigaos4__) */
#include <sys/select.h>
#endif /* #else defined(__amigaos__) && !defined(__amigaos4__) */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netdb.h>
#define closesocket close
/* defining MINIUPNPC_IGNORE_EINTR enable the ignore of interruptions
* during the connect() call */
#define MINIUPNPC_IGNORE_EINTR
#endif /* #else _WIN32 */
#if defined(__sun) || defined(sun)
#define MIN(x,y) (((x)<(y))?(x):(y))
#endif
#include "miniupnpcstrings.h"
#include "miniwget.h"
#include "connecthostport.h"
#include "receivedata.h"
#ifndef MAXHOSTNAMELEN
#define MAXHOSTNAMELEN 64
#endif
/*
* Read a HTTP response from a socket.
* Process Content-Length and Transfer-encoding headers.
* return a pointer to the content buffer, which length is saved
* to the length parameter.
*/
void *
getHTTPResponse(int s, int * size)
{
char buf[2048];
int n;
int endofheaders = 0;
int chunked = 0;
int content_length = -1;
unsigned int chunksize = 0;
unsigned int bytestocopy = 0;
/* buffers : */
char * header_buf;
unsigned int header_buf_len = 2048;
unsigned int header_buf_used = 0;
char * content_buf;
unsigned int content_buf_len = 2048;
unsigned int content_buf_used = 0;
char chunksize_buf[32];
unsigned int chunksize_buf_index;
header_buf = malloc(header_buf_len);
content_buf = malloc(content_buf_len);
chunksize_buf[0] = '\0';
chunksize_buf_index = 0;
while((n = receivedata(s, buf, 2048, 5000, NULL)) > 0)
{
if(endofheaders == 0)
{
int i;
int linestart=0;
int colon=0;
int valuestart=0;
if(header_buf_used + n > header_buf_len) {
header_buf = realloc(header_buf, header_buf_used + n);
header_buf_len = header_buf_used + n;
}
memcpy(header_buf + header_buf_used, buf, n);
header_buf_used += n;
/* search for CR LF CR LF (end of headers)
* recognize also LF LF */
i = 0;
while(i < ((int)header_buf_used-1) && (endofheaders == 0)) {
if(header_buf[i] == '\r') {
i++;
if(header_buf[i] == '\n') {
i++;
if(i < (int)header_buf_used && header_buf[i] == '\r') {
i++;
if(i < (int)header_buf_used && header_buf[i] == '\n') {
endofheaders = i+1;
}
}
}
} else if(header_buf[i] == '\n') {
i++;
if(header_buf[i] == '\n') {
endofheaders = i+1;
}
}
i++;
}
if(endofheaders == 0)
continue;
/* parse header lines */
for(i = 0; i < endofheaders - 1; i++) {
if(colon <= linestart && header_buf[i]==':')
{
colon = i;
while(i < (endofheaders-1)
&& (header_buf[i+1] == ' ' || header_buf[i+1] == '\t'))
i++;
valuestart = i + 1;
}
/* detecting end of line */
else if(header_buf[i]=='\r' || header_buf[i]=='\n')
{
if(colon > linestart && valuestart > colon)
{
#ifdef DEBUG
printf("header='%.*s', value='%.*s'\n",
colon-linestart, header_buf+linestart,
i-valuestart, header_buf+valuestart);
#endif
if(0==strncasecmp(header_buf+linestart, "content-length", colon-linestart))
{
content_length = atoi(header_buf+valuestart);
#ifdef DEBUG
printf("Content-Length: %d\n", content_length);
#endif
}
else if(0==strncasecmp(header_buf+linestart, "transfer-encoding", colon-linestart)
&& 0==strncasecmp(header_buf+valuestart, "chunked", 7))
{
#ifdef DEBUG
printf("chunked transfer-encoding!\n");
#endif
chunked = 1;
}
}
while((i < (int)header_buf_used) && (header_buf[i]=='\r' || header_buf[i] == '\n'))
i++;
linestart = i;
colon = linestart;
valuestart = 0;
}
}
/* copy the remaining of the received data back to buf */
n = header_buf_used - endofheaders;
memcpy(buf, header_buf + endofheaders, n);
/* if(headers) */
}
if(endofheaders)
{
/* content */
if(chunked)
{
int i = 0;
while(i < n)
{
if(chunksize == 0)
{
/* reading chunk size */
if(chunksize_buf_index == 0) {
/* skipping any leading CR LF */
if(i<n && buf[i] == '\r') i++;
if(i<n && buf[i] == '\n') i++;
}
while(i<n && isxdigit(buf[i])
&& chunksize_buf_index < (sizeof(chunksize_buf)-1))
{
chunksize_buf[chunksize_buf_index++] = buf[i];
chunksize_buf[chunksize_buf_index] = '\0';
i++;
}
while(i<n && buf[i] != '\r' && buf[i] != '\n')
i++; /* discarding chunk-extension */
if(i<n && buf[i] == '\r') i++;
if(i<n && buf[i] == '\n') {
unsigned int j;
for(j = 0; j < chunksize_buf_index; j++) {
if(chunksize_buf[j] >= '0'
&& chunksize_buf[j] <= '9')
chunksize = (chunksize << 4) + (chunksize_buf[j] - '0');
else
chunksize = (chunksize << 4) + ((chunksize_buf[j] | 32) - 'a' + 10);
}
chunksize_buf[0] = '\0';
chunksize_buf_index = 0;
i++;
} else {
/* not finished to get chunksize */
continue;
}
#ifdef DEBUG
printf("chunksize = %u (%x)\n", chunksize, chunksize);
#endif
if(chunksize == 0)
{
#ifdef DEBUG
printf("end of HTTP content - %d %d\n", i, n);
/*printf("'%.*s'\n", n-i, buf+i);*/
#endif
goto end_of_stream;
}
}
bytestocopy = ((int)chunksize < (n - i))?chunksize:(unsigned int)(n - i);
if((content_buf_used + bytestocopy) > content_buf_len)
{
if(content_length >= (int)(content_buf_used + bytestocopy)) {
content_buf_len = content_length;
} else {
content_buf_len = content_buf_used + bytestocopy;
}
content_buf = (char *)realloc((void *)content_buf,
content_buf_len);
}
memcpy(content_buf + content_buf_used, buf + i, bytestocopy);
content_buf_used += bytestocopy;
i += bytestocopy;
chunksize -= bytestocopy;
}
}
else
{
/* not chunked */
if(content_length > 0
&& (int)(content_buf_used + n) > content_length) {
/* skipping additional bytes */
n = content_length - content_buf_used;
}
if(content_buf_used + n > content_buf_len)
{
if(content_length >= (int)(content_buf_used + n)) {
content_buf_len = content_length;
} else {
content_buf_len = content_buf_used + n;
}
content_buf = (char *)realloc((void *)content_buf,
content_buf_len);
}
memcpy(content_buf + content_buf_used, buf, n);
content_buf_used += n;
}
}
/* use the Content-Length header value if available */
if(content_length > 0 && (int)content_buf_used >= content_length)
{
#ifdef DEBUG
printf("End of HTTP content\n");
#endif
break;
}
}
end_of_stream:
free(header_buf); header_buf = NULL;
*size = content_buf_used;
if(content_buf_used == 0)
{
free(content_buf);
content_buf = NULL;
}
return content_buf;
}
/* miniwget3() :
* do all the work.
* Return NULL if something failed. */
static void *
miniwget3(const char * host,
unsigned short port, const char * path,
int * size, char * addr_str, int addr_str_len,
const char * httpversion, unsigned int scope_id)
{
char buf[2048];
int s;
int n;
int len;
int sent;
void * content;
*size = 0;
s = connecthostport(host, port, scope_id);
if(s < 0)
return NULL;
/* get address for caller ! */
if(addr_str)
{
struct sockaddr_storage saddr;
socklen_t saddrlen;
saddrlen = sizeof(saddr);
if(getsockname(s, (struct sockaddr *)&saddr, &saddrlen) < 0)
{
perror("getsockname");
}
else
{
#if defined(__amigaos__) && !defined(__amigaos4__)
/* using INT WINAPI WSAAddressToStringA(LPSOCKADDR, DWORD, LPWSAPROTOCOL_INFOA, LPSTR, LPDWORD);
* But his function make a string with the port : nn.nn.nn.nn:port */
/* if(WSAAddressToStringA((SOCKADDR *)&saddr, sizeof(saddr),
NULL, addr_str, (DWORD *)&addr_str_len))
{
printf("WSAAddressToStringA() failed : %d\n", WSAGetLastError());
}*/
/* the following code is only compatible with ip v4 addresses */
strncpy(addr_str, inet_ntoa(((struct sockaddr_in *)&saddr)->sin_addr), addr_str_len);
#else
#if 0
if(saddr.sa_family == AF_INET6) {
inet_ntop(AF_INET6,
&(((struct sockaddr_in6 *)&saddr)->sin6_addr),
addr_str, addr_str_len);
} else {
inet_ntop(AF_INET,
&(((struct sockaddr_in *)&saddr)->sin_addr),
addr_str, addr_str_len);
}
#endif
/* getnameinfo return ip v6 address with the scope identifier
* such as : 2a01:e35:8b2b:7330::%4281128194 */
n = getnameinfo((const struct sockaddr *)&saddr, saddrlen,
addr_str, addr_str_len,
NULL, 0,
NI_NUMERICHOST | NI_NUMERICSERV);
if(n != 0) {
#ifdef _WIN32
fprintf(stderr, "getnameinfo() failed : %d\n", n);
#else
fprintf(stderr, "getnameinfo() failed : %s\n", gai_strerror(n));
#endif
}
#endif
}
#ifdef DEBUG
printf("address miniwget : %s\n", addr_str);
#endif
}
len = snprintf(buf, sizeof(buf),
"GET %s HTTP/%s\r\n"
"Host: %s:%d\r\n"
"Connection: Close\r\n"
"User-Agent: " OS_STRING ", UPnP/1.0, MiniUPnPc/" MINIUPNPC_VERSION_STRING "\r\n"
"\r\n",
path, httpversion, host, port);
sent = 0;
/* sending the HTTP request */
while(sent < len)
{
n = send(s, buf+sent, len-sent, 0);
if(n < 0)
{
perror("send");
closesocket(s);
return NULL;
}
else
{
sent += n;
}
}
content = getHTTPResponse(s, size);
closesocket(s);
return content;
}
/* miniwget2() :
* Call miniwget3(); retry with HTTP/1.1 if 1.0 fails. */
static void *
miniwget2(const char * host,
unsigned short port, const char * path,
int * size, char * addr_str, int addr_str_len,
unsigned int scope_id)
{
char * respbuffer;
#if 1
respbuffer = miniwget3(host, port, path, size,
addr_str, addr_str_len, "1.1", scope_id);
#else
respbuffer = miniwget3(host, port, path, size,
addr_str, addr_str_len, "1.0", scope_id);
if (*size == 0)
{
#ifdef DEBUG
printf("Retrying with HTTP/1.1\n");
#endif
free(respbuffer);
respbuffer = miniwget3(host, port, path, size,
addr_str, addr_str_len, "1.1", scope_id);
}
#endif
return respbuffer;
}
/* parseURL()
* arguments :
* url : source string not modified
* hostname : hostname destination string (size of MAXHOSTNAMELEN+1)
* port : port (destination)
* path : pointer to the path part of the URL
*
* Return values :
* 0 - Failure
* 1 - Success */
int
parseURL(const char * url,
char * hostname, unsigned short * port,
char * * path, unsigned int * scope_id)
{
char * p1, *p2, *p3;
if(!url)
return 0;
p1 = strstr(url, "://");
if(!p1)
return 0;
p1 += 3;
if( (url[0]!='h') || (url[1]!='t')
||(url[2]!='t') || (url[3]!='p'))
return 0;
memset(hostname, 0, MAXHOSTNAMELEN + 1);
if(*p1 == '[')
{
/* IP v6 : http://[2a00:1450:8002::6a]/path/abc */
char * scope;
scope = strchr(p1, '%');
p2 = strchr(p1, ']');
if(p2 && scope && scope < p2 && scope_id) {
/* parse scope */
#ifdef IF_NAMESIZE
char tmp[IF_NAMESIZE];
int l;
scope++;
/* "%25" is just '%' in URL encoding */
if(scope[0] == '2' && scope[1] == '5')
scope += 2; /* skip "25" */
l = p2 - scope;
if(l >= IF_NAMESIZE)
l = IF_NAMESIZE - 1;
memcpy(tmp, scope, l);
tmp[l] = '\0';
*scope_id = if_nametoindex(tmp);
if(*scope_id == 0) {
*scope_id = (unsigned int)strtoul(tmp, NULL, 10);
}
#else
/* under windows, scope is numerical */
char tmp[8];
int l;
scope++;
/* "%25" is just '%' in URL encoding */
if(scope[0] == '2' && scope[1] == '5')
scope += 2; /* skip "25" */
l = p2 - scope;
if(l >= sizeof(tmp))
l = sizeof(tmp) - 1;
memcpy(tmp, scope, l);
tmp[l] = '\0';
*scope_id = (unsigned int)strtoul(tmp, NULL, 10);
#endif
}
p3 = strchr(p1, '/');
if(p2 && p3)
{
p2++;
strncpy(hostname, p1, MIN(MAXHOSTNAMELEN, (int)(p2-p1)));
if(*p2 == ':')
{
*port = 0;
p2++;
while( (*p2 >= '0') && (*p2 <= '9'))
{
*port *= 10;
*port += (unsigned short)(*p2 - '0');
p2++;
}
}
else
{
*port = 80;
}
*path = p3;
return 1;
}
}
p2 = strchr(p1, ':');
p3 = strchr(p1, '/');
if(!p3)
return 0;
if(!p2 || (p2>p3))
{
strncpy(hostname, p1, MIN(MAXHOSTNAMELEN, (int)(p3-p1)));
*port = 80;
}
else
{
strncpy(hostname, p1, MIN(MAXHOSTNAMELEN, (int)(p2-p1)));
*port = 0;
p2++;
while( (*p2 >= '0') && (*p2 <= '9'))
{
*port *= 10;
*port += (unsigned short)(*p2 - '0');
p2++;
}
}
*path = p3;
return 1;
}
void *
miniwget(const char * url, int * size, unsigned int scope_id)
{
unsigned short port;
char * path;
/* protocol://host:port/chemin */
char hostname[MAXHOSTNAMELEN+1];
*size = 0;
if(!parseURL(url, hostname, &port, &path, &scope_id))
return NULL;
#ifdef DEBUG
printf("parsed url : hostname='%s' port=%hu path='%s' scope_id=%u\n",
hostname, port, path, scope_id);
#endif
return miniwget2(hostname, port, path, size, 0, 0, scope_id);
}
void *
miniwget_getaddr(const char * url, int * size,
char * addr, int addrlen, unsigned int scope_id)
{
unsigned short port;
char * path;
/* protocol://host:port/path */
char hostname[MAXHOSTNAMELEN+1];
*size = 0;
if(addr)
addr[0] = '\0';
if(!parseURL(url, hostname, &port, &path, &scope_id))
return NULL;
#ifdef DEBUG
printf("parsed url : hostname='%s' port=%hu path='%s' scope_id=%u\n",
hostname, port, path, scope_id);
#endif
return miniwget2(hostname, port, path, size, addr, addrlen, scope_id);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2183_1 |
crossvul-cpp_data_bad_5111_0 | /* cosine.c
*
* CoSine IPNOS L2 debug output parsing
* Copyright (c) 2002 by Motonori Shindo <motonori@shin.do>
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <gram@alumni.rice.edu>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include "wtap-int.h"
#include "cosine.h"
#include "file_wrappers.h"
#include <stdlib.h>
#include <string.h>
/*
IPNOS: CONFIG VPN(100) VR(1.1.1.1)# diags
ipnos diags: Control (1/0) :: layer-2 ?
Registered commands for area "layer-2"
apply-pkt-log-profile Configure packet logging on an interface
create-pkt-log-profile Set packet-log-profile to be used for packet logging (see layer-2 pkt-log)
detail Get Layer 2 low-level details
ipnos diags: Control (1/0) :: layer-2 create ?
create-pkt-log-profile <pkt-log-profile-id ctl-tx-trace-length ctl-rx-trace-length data-tx-trace-length data-rx-trace-length pe-logging-or-control-blade>
ipnos diags: Control (1/0) :: layer-2 create 1 32 32 0 0 0
ipnos diags: Control (1/0) :: layer-2 create 2 32 32 100 100 0
ipnos diags: Control (1/0) :: layer-2 apply ?
apply-pkt-log-profile <slot port channel subif pkt-log-profile-id>
ipnos diags: Control (1/0) :: layer-2 apply 3 0x0701 100 0 1
Successfully applied packet-log-profile on LI
-- Note that only the control packets are logged because the data packet size parameters are 0 in profile 1
IPNOS: CONFIG VPN(200) VR(3.3.3.3)# ping 20.20.20.43
vpn 200 : [max tries 4, timeout 5 seconds, data length 64 bytes, ttl 255]
ping #1 ok, RTT 0.000 seconds
ping #2 ok, RTT 0.000 seconds
ping #3 ok, RTT 0.000 seconds
ping #4 ok, RTT 0.000 seconds
[finished]
IPNOS: CONFIG VPN(200) VR(3.3.3.3)# 2000-2-1,18:19:46.8: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
2000-2-1,18:19:46.8: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x30000]
2000-2-1,18:19:46.8: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
2000-2-1,18:19:46.8: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x8030000]
ipnos diags: Control (1/0) :: layer-2 apply 3 0x0701 100 0 0
Successfully applied packet-log-profile on LI
ipnos diags: Control (1/0) :: layer-2 apply 3 0x0701 100 0 2
Successfully applied packet-log-profile on LI
-- Note that both control and data packets are logged because the data packet size parameter is 100 in profile 2
Please ignore the event-log messages getting mixed up with the ping command
ping 20.20.20.43 cou2000-2-1,18:20:17.0: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
00 D0 D8 D2 FF 03 C0 21 09 29 00 08 6B 60 84 AA
2000-2-1,18:20:17.0: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x30000]
00 D0 D8 D2 FF 03 C0 21 09 29 00 08 6D FE FA AA
2000-2-1,18:20:17.0: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
00 D0 D8 D2 FF 03 C0 21 0A 29 00 08 6B 60 84 AA
2000-2-1,18:20:17.0: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x8030000]
00 D0 D8 D2 FF 03 C0 21 0A 29 00 08 6D FE FA AA
nt 1 length 500
vpn 200 : [max tries 1, timeout 5 seconds, data length 500 bytes, ttl 255]
2000-2-1,18:20:24.1: l2-tx (PPP:3/7/1:100), Length:536, Pro:1, Off:8, Pri:7, RM:0, Err:0 [0x4070, 0x801]
00 D0 D8 D2 FF 03 00 21 45 00 02 10 00 27 00 00
FF 01 69 51 14 14 14 22 14 14 14 2B 08 00 AD B8
00 03 00 01 10 11 12 13 14 15 16 17 18 19 1A 1B
1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B
2C 2D 2E 2F 30 31 32 33 34 35 36 37 38 39 3A 3B
3C 3D 3E 3F 40 41 42 43 44 45 46 47 48 49 4A 4B
4C 4D 4E 4F
ping #1 ok, RTT 0.010 seconds
2000-2-1,18:20:24.1: l2-rx (PPP:3/7/1:100), Length:536, Pro:1, Off:8, Pri:7, RM:0, Err:0 [0x4071, 0x30801]
00 D0 D8 D2 FF 03 00 21 45 00 02 10 00 23 00 00
FF 01 69 55 14 14 14 2B 14 14 14 22 00 00 B5 B8
00 03 00 01 10 11 12 13 14 15 16 17 18 19 1A 1B
1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B
2C 2D 2E 2F 30 31 32 33 34 35 36 37 38 39 3A 3B
3C 3D 3E 3F 40 41 42 43 44 45 46 47 48 49 4A 4B
4C 4D 4E 4F
[finished]
IPNOS: CONFIG VPN(200) VR(3.3.3.3)# 2000-2-1,18:20:27.0: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
00 D0 D8 D2 FF 03 C0 21 09 2A 00 08 6B 60 84 AA
2000-2-1,18:20:27.0: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x30000]
00 D0 D8 D2 FF 03 C0 21 09 2A 00 08 6D FE FA AA
2000-2-1,18:20:27.0: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
00 D0 D8 D2 FF 03 C0 21 0A 2A 00 08 6B 60 84 AA
2000-2-1,18:20:27.0: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x30000]
00 D0 D8 D2 FF 03 C0 21 0A 2A 00 08 6D FE FA AA
ipnos diags: Control (1/0) :: layer-2 apply 3 0x0701 100 0 0
Successfully applied packet-log-profile on LI
ipnos diags: Control (1/0) ::
*/
/* XXX TODO:
o Handle a case where an empty line doesn't exists as a delimiter of
each packet. If the output is sent to a control blade and
displayed as an event log, there's always an empty line between
each packet output, but it may not be true when it is an PE
output.
o Some telnet client on Windows may put in a line break at 80
columns when it save the session to a text file ("CRT" is such an
example). I don't think it's a good idea for the telnet client to
do so, but CRT is widely used in Windows community, I should
take care of that in the future.
*/
/* Magic text to check for CoSine L2 debug output */
#define COSINE_HDR_MAGIC_STR1 "l2-tx"
#define COSINE_HDR_MAGIC_STR2 "l2-rx"
/* Magic text for start of packet */
#define COSINE_REC_MAGIC_STR1 COSINE_HDR_MAGIC_STR1
#define COSINE_REC_MAGIC_STR2 COSINE_HDR_MAGIC_STR2
#define COSINE_HEADER_LINES_TO_CHECK 200
#define COSINE_LINE_LENGTH 240
static gboolean empty_line(const gchar *line);
static gint64 cosine_seek_next_packet(wtap *wth, int *err, gchar **err_info,
char *hdr);
static gboolean cosine_check_file_type(wtap *wth, int *err, gchar **err_info);
static gboolean cosine_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset);
static gboolean cosine_seek_read(wtap *wth, gint64 seek_off,
struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info);
static int parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer* buf,
char *line, int *err, gchar **err_info);
static int parse_single_hex_dump_line(char* rec, guint8 *buf,
guint byte_offset);
/* Returns TRUE if the line appears to be an empty line. Otherwise it
returns FALSE. */
static gboolean empty_line(const gchar *line)
{
while (*line) {
if (g_ascii_isspace(*line)) {
line++;
continue;
} else {
break;
}
}
if (*line == '\0')
return TRUE;
else
return FALSE;
}
/* Seeks to the beginning of the next packet, and returns the
byte offset. Copy the header line to hdr. Returns -1 on failure,
and sets "*err" to the error and sets "*err_info" to null or an
additional error string. */
static gint64 cosine_seek_next_packet(wtap *wth, int *err, gchar **err_info,
char *hdr)
{
gint64 cur_off;
char buf[COSINE_LINE_LENGTH];
while (1) {
cur_off = file_tell(wth->fh);
if (cur_off == -1) {
/* Error */
*err = file_error(wth->fh, err_info);
return -1;
}
if (file_gets(buf, sizeof(buf), wth->fh) == NULL) {
*err = file_error(wth->fh, err_info);
return -1;
}
if (strstr(buf, COSINE_REC_MAGIC_STR1) ||
strstr(buf, COSINE_REC_MAGIC_STR2)) {
g_strlcpy(hdr, buf, COSINE_LINE_LENGTH);
return cur_off;
}
}
return -1;
}
/* Look through the first part of a file to see if this is
* a CoSine L2 debug output.
*
* Returns TRUE if it is, FALSE if it isn't or if we get an I/O error;
* if we get an I/O error, "*err" will be set to a non-zero value and
* "*err_info" will be set to null or an additional error string.
*/
static gboolean cosine_check_file_type(wtap *wth, int *err, gchar **err_info)
{
char buf[COSINE_LINE_LENGTH];
gsize reclen;
guint line;
buf[COSINE_LINE_LENGTH-1] = '\0';
for (line = 0; line < COSINE_HEADER_LINES_TO_CHECK; line++) {
if (file_gets(buf, COSINE_LINE_LENGTH, wth->fh) == NULL) {
/* EOF or error. */
*err = file_error(wth->fh, err_info);
return FALSE;
}
reclen = strlen(buf);
if (reclen < strlen(COSINE_HDR_MAGIC_STR1) ||
reclen < strlen(COSINE_HDR_MAGIC_STR2)) {
continue;
}
if (strstr(buf, COSINE_HDR_MAGIC_STR1) ||
strstr(buf, COSINE_HDR_MAGIC_STR2)) {
return TRUE;
}
}
*err = 0;
return FALSE;
}
wtap_open_return_val cosine_open(wtap *wth, int *err, gchar **err_info)
{
/* Look for CoSine header */
if (!cosine_check_file_type(wth, err, err_info)) {
if (*err != 0 && *err != WTAP_ERR_SHORT_READ)
return WTAP_OPEN_ERROR;
return WTAP_OPEN_NOT_MINE;
}
if (file_seek(wth->fh, 0L, SEEK_SET, err) == -1) /* rewind */
return WTAP_OPEN_ERROR;
wth->file_encap = WTAP_ENCAP_COSINE;
wth->file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_COSINE;
wth->snapshot_length = 0; /* not known */
wth->subtype_read = cosine_read;
wth->subtype_seek_read = cosine_seek_read;
wth->file_tsprec = WTAP_TSPREC_CSEC;
return WTAP_OPEN_MINE;
}
/* Find the next packet and parse it; called from wtap_read(). */
static gboolean cosine_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset)
{
gint64 offset;
char line[COSINE_LINE_LENGTH];
/* Find the next packet */
offset = cosine_seek_next_packet(wth, err, err_info, line);
if (offset < 0)
return FALSE;
*data_offset = offset;
/* Parse the header and convert the ASCII hex dump to binary data */
return parse_cosine_packet(wth->fh, &wth->phdr, wth->frame_buffer,
line, err, err_info);
}
/* Used to read packets in random-access fashion */
static gboolean
cosine_seek_read(wtap *wth, gint64 seek_off, struct wtap_pkthdr *phdr,
Buffer *buf, int *err, gchar **err_info)
{
char line[COSINE_LINE_LENGTH];
if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)
return FALSE;
if (file_gets(line, COSINE_LINE_LENGTH, wth->random_fh) == NULL) {
*err = file_error(wth->random_fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Parse the header and convert the ASCII hex dump to binary data */
return parse_cosine_packet(wth->random_fh, phdr, buf, line, err,
err_info);
}
/* Parses a packet record header. There are two possible formats:
1) output to a control blade with date and time
2002-5-10,20:1:31.4: l2-tx (FR:3/7/1:1), Length:18, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
2) output to PE without date and time
l2-tx (FR:3/7/1:1), Length:18, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0] */
static gboolean
parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,
char *line, int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
int num_items_scanned;
int yy, mm, dd, hr, min, sec, csec;
guint pkt_len;
int pro, off, pri, rm, error;
guint code1, code2;
char if_name[COSINE_MAX_IF_NAME_LEN] = "", direction[6] = "";
struct tm tm;
guint8 *pd;
int i, hex_lines, n, caplen = 0;
if (sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d:",
&yy, &mm, &dd, &hr, &min, &sec, &csec) == 7) {
/* appears to be output to a control blade */
num_items_scanned = sscanf(line,
"%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]",
&yy, &mm, &dd, &hr, &min, &sec, &csec,
direction, if_name, &pkt_len,
&pro, &off, &pri, &rm, &error,
&code1, &code2);
if (num_items_scanned != 17) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: purported control blade line doesn't have code values");
return FALSE;
}
} else {
/* appears to be output to PE */
num_items_scanned = sscanf(line,
"%5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]",
direction, if_name, &pkt_len,
&pro, &off, &pri, &rm, &error,
&code1, &code2);
if (num_items_scanned != 10) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: header line is neither control blade nor PE output");
return FALSE;
}
yy = mm = dd = hr = min = sec = csec = 0;
}
if (pkt_len > WTAP_MAX_PACKET_SIZE) {
/*
* Probably a corrupt capture file; don't blow up trying
* to allocate space for an immensely-large packet.
*/
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup_printf("cosine: File has %u-byte packet, bigger than maximum of %u",
pkt_len, WTAP_MAX_PACKET_SIZE);
return FALSE;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
tm.tm_year = yy - 1900;
tm.tm_mon = mm - 1;
tm.tm_mday = dd;
tm.tm_hour = hr;
tm.tm_min = min;
tm.tm_sec = sec;
tm.tm_isdst = -1;
phdr->ts.secs = mktime(&tm);
phdr->ts.nsecs = csec * 10000000;
phdr->len = pkt_len;
/* XXX need to handle other encapsulations like Cisco HDLC,
Frame Relay and ATM */
if (strncmp(if_name, "TEST:", 5) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_TEST;
} else if (strncmp(if_name, "PPoATM:", 7) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPoATM;
} else if (strncmp(if_name, "PPoFR:", 6) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPoFR;
} else if (strncmp(if_name, "ATM:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_ATM;
} else if (strncmp(if_name, "FR:", 3) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_FR;
} else if (strncmp(if_name, "HDLC:", 5) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_HDLC;
} else if (strncmp(if_name, "PPP:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPP;
} else if (strncmp(if_name, "ETH:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_ETH;
} else {
pseudo_header->cosine.encap = COSINE_ENCAP_UNKNOWN;
}
if (strncmp(direction, "l2-tx", 5) == 0) {
pseudo_header->cosine.direction = COSINE_DIR_TX;
} else if (strncmp(direction, "l2-rx", 5) == 0) {
pseudo_header->cosine.direction = COSINE_DIR_RX;
}
g_strlcpy(pseudo_header->cosine.if_name, if_name,
COSINE_MAX_IF_NAME_LEN);
pseudo_header->cosine.pro = pro;
pseudo_header->cosine.off = off;
pseudo_header->cosine.pri = pri;
pseudo_header->cosine.rm = rm;
pseudo_header->cosine.err = error;
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, pkt_len);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (empty_line(line)) {
break;
}
if ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: hex dump line doesn't have 16 numbers");
return FALSE;
}
caplen += n;
}
phdr->caplen = caplen;
return TRUE;
}
/* Take a string representing one line from a hex dump and converts
* the text to binary data. We place the bytes in the buffer at the
* specified offset.
*
* Returns number of bytes successfully read, -1 if bad. */
static int
parse_single_hex_dump_line(char* rec, guint8 *buf, guint byte_offset)
{
int num_items_scanned, i;
unsigned int bytes[16];
num_items_scanned = sscanf(rec, "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
&bytes[0], &bytes[1], &bytes[2], &bytes[3],
&bytes[4], &bytes[5], &bytes[6], &bytes[7],
&bytes[8], &bytes[9], &bytes[10], &bytes[11],
&bytes[12], &bytes[13], &bytes[14], &bytes[15]);
if (num_items_scanned == 0)
return -1;
if (num_items_scanned > 16)
num_items_scanned = 16;
for (i=0; i<num_items_scanned; i++) {
buf[byte_offset + i] = (guint8)bytes[i];
}
return num_items_scanned;
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: t
* End:
*
* vi: set shiftwidth=8 tabstop=8 noexpandtab:
* :indentSize=8:tabSize=8:noTabs=false:
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5111_0 |
crossvul-cpp_data_good_2107_0 | /*
* Copyright (c) Ian F. Darwin 1986-1995.
* Software written by Ian F. Darwin and others;
* maintained 1995-present by Christos Zoulas and others.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice immediately at the beginning of the file, without modification,
* this list of conditions, and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* softmagic - interpret variable magic from MAGIC
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: softmagic.c,v 1.171 2014/01/08 22:02:06 christos Exp $")
#endif /* lint */
#include "magic.h"
#ifdef HAVE_FMTCHECK
#include <stdio.h>
#define F(a, b) fmtcheck((a), (b))
#else
#define F(a, b) (a)
#endif
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <time.h>
#if defined(HAVE_LOCALE_H)
#include <locale.h>
#endif
private int match(struct magic_set *, struct magic *, uint32_t,
const unsigned char *, size_t, size_t, int, int, int, int, int *, int *,
int *);
private int mget(struct magic_set *, const unsigned char *,
struct magic *, size_t, size_t, unsigned int, int, int, int, int, int *,
int *, int *);
private int magiccheck(struct magic_set *, struct magic *);
private int32_t mprint(struct magic_set *, struct magic *);
private int32_t moffset(struct magic_set *, struct magic *);
private void mdebug(uint32_t, const char *, size_t);
private int mcopy(struct magic_set *, union VALUETYPE *, int, int,
const unsigned char *, uint32_t, size_t, size_t);
private int mconvert(struct magic_set *, struct magic *, int);
private int print_sep(struct magic_set *, int);
private int handle_annotation(struct magic_set *, struct magic *);
private void cvt_8(union VALUETYPE *, const struct magic *);
private void cvt_16(union VALUETYPE *, const struct magic *);
private void cvt_32(union VALUETYPE *, const struct magic *);
private void cvt_64(union VALUETYPE *, const struct magic *);
#define OFFSET_OOB(n, o, i) ((n) < (o) || (i) >= ((n) - (o)))
/*
* softmagic - lookup one file in parsed, in-memory copy of database
* Passed the name and FILE * of one file to be typed.
*/
/*ARGSUSED1*/ /* nbytes passed for regularity, maybe need later */
protected int
file_softmagic(struct magic_set *ms, const unsigned char *buf, size_t nbytes,
int mode, int text)
{
struct mlist *ml;
int rv, printed_something = 0, need_separator = 0;
for (ml = ms->mlist[0]->next; ml != ms->mlist[0]; ml = ml->next)
if ((rv = match(ms, ml->magic, ml->nmagic, buf, nbytes, 0, mode,
text, 0, 0, &printed_something, &need_separator,
NULL)) != 0)
return rv;
return 0;
}
/*
* Go through the whole list, stopping if you find a match. Process all
* the continuations of that match before returning.
*
* We support multi-level continuations:
*
* At any time when processing a successful top-level match, there is a
* current continuation level; it represents the level of the last
* successfully matched continuation.
*
* Continuations above that level are skipped as, if we see one, it
* means that the continuation that controls them - i.e, the
* lower-level continuation preceding them - failed to match.
*
* Continuations below that level are processed as, if we see one,
* it means we've finished processing or skipping higher-level
* continuations under the control of a successful or unsuccessful
* lower-level continuation, and are now seeing the next lower-level
* continuation and should process it. The current continuation
* level reverts to the level of the one we're seeing.
*
* Continuations at the current level are processed as, if we see
* one, there's no lower-level continuation that may have failed.
*
* If a continuation matches, we bump the current continuation level
* so that higher-level continuations are processed.
*/
private int
match(struct magic_set *ms, struct magic *magic, uint32_t nmagic,
const unsigned char *s, size_t nbytes, size_t offset, int mode, int text,
int flip, int recursion_level, int *printed_something, int *need_separator,
int *returnval)
{
uint32_t magindex = 0;
unsigned int cont_level = 0;
int returnvalv = 0, e; /* if a match is found it is set to 1*/
int firstline = 1; /* a flag to print X\n X\n- X */
int print = (ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0;
if (returnval == NULL)
returnval = &returnvalv;
if (file_check_mem(ms, cont_level) == -1)
return -1;
for (magindex = 0; magindex < nmagic; magindex++) {
int flush = 0;
struct magic *m = &magic[magindex];
if (m->type != FILE_NAME)
if ((IS_STRING(m->type) &&
#define FLT (STRING_BINTEST | STRING_TEXTTEST)
((text && (m->str_flags & FLT) == STRING_BINTEST) ||
(!text && (m->str_flags & FLT) == STRING_TEXTTEST))) ||
(m->flag & mode) != mode) {
/* Skip sub-tests */
while (magindex + 1 < nmagic &&
magic[magindex + 1].cont_level != 0 &&
++magindex)
continue;
continue; /* Skip to next top-level test*/
}
ms->offset = m->offset;
ms->line = m->lineno;
/* if main entry matches, print it... */
switch (mget(ms, s, m, nbytes, offset, cont_level, mode, text,
flip, recursion_level + 1, printed_something,
need_separator, returnval)) {
case -1:
return -1;
case 0:
flush = m->reln != '!';
break;
default:
if (m->type == FILE_INDIRECT)
*returnval = 1;
switch (magiccheck(ms, m)) {
case -1:
return -1;
case 0:
flush++;
break;
default:
flush = 0;
break;
}
break;
}
if (flush) {
/*
* main entry didn't match,
* flush its continuations
*/
while (magindex < nmagic - 1 &&
magic[magindex + 1].cont_level != 0)
magindex++;
continue;
}
if ((e = handle_annotation(ms, m)) != 0) {
*need_separator = 1;
*printed_something = 1;
*returnval = 1;
return e;
}
/*
* If we are going to print something, we'll need to print
* a blank before we print something else.
*/
if (*m->desc) {
*need_separator = 1;
*printed_something = 1;
if (print_sep(ms, firstline) == -1)
return -1;
}
if (print && mprint(ms, m) == -1)
return -1;
ms->c.li[cont_level].off = moffset(ms, m);
/* and any continuations that match */
if (file_check_mem(ms, ++cont_level) == -1)
return -1;
while (magic[magindex+1].cont_level != 0 &&
++magindex < nmagic) {
m = &magic[magindex];
ms->line = m->lineno; /* for messages */
if (cont_level < m->cont_level)
continue;
if (cont_level > m->cont_level) {
/*
* We're at the end of the level
* "cont_level" continuations.
*/
cont_level = m->cont_level;
}
ms->offset = m->offset;
if (m->flag & OFFADD) {
ms->offset +=
ms->c.li[cont_level - 1].off;
}
#ifdef ENABLE_CONDITIONALS
if (m->cond == COND_ELSE ||
m->cond == COND_ELIF) {
if (ms->c.li[cont_level].last_match == 1)
continue;
}
#endif
switch (mget(ms, s, m, nbytes, offset, cont_level, mode,
text, flip, recursion_level + 1, printed_something,
need_separator, returnval)) {
case -1:
return -1;
case 0:
if (m->reln != '!')
continue;
flush = 1;
break;
default:
if (m->type == FILE_INDIRECT)
*returnval = 1;
flush = 0;
break;
}
switch (flush ? 1 : magiccheck(ms, m)) {
case -1:
return -1;
case 0:
#ifdef ENABLE_CONDITIONALS
ms->c.li[cont_level].last_match = 0;
#endif
break;
default:
#ifdef ENABLE_CONDITIONALS
ms->c.li[cont_level].last_match = 1;
#endif
if (m->type == FILE_CLEAR)
ms->c.li[cont_level].got_match = 0;
else if (ms->c.li[cont_level].got_match) {
if (m->type == FILE_DEFAULT)
break;
} else
ms->c.li[cont_level].got_match = 1;
if ((e = handle_annotation(ms, m)) != 0) {
*need_separator = 1;
*printed_something = 1;
*returnval = 1;
return e;
}
/*
* If we are going to print something,
* make sure that we have a separator first.
*/
if (*m->desc) {
if (!*printed_something) {
*printed_something = 1;
if (print_sep(ms, firstline)
== -1)
return -1;
}
}
/*
* This continuation matched. Print
* its message, with a blank before it
* if the previous item printed and
* this item isn't empty.
*/
/* space if previous printed */
if (*need_separator
&& ((m->flag & NOSPACE) == 0)
&& *m->desc) {
if (print &&
file_printf(ms, " ") == -1)
return -1;
*need_separator = 0;
}
if (print && mprint(ms, m) == -1)
return -1;
ms->c.li[cont_level].off = moffset(ms, m);
if (*m->desc)
*need_separator = 1;
/*
* If we see any continuations
* at a higher level,
* process them.
*/
if (file_check_mem(ms, ++cont_level) == -1)
return -1;
break;
}
}
if (*printed_something) {
firstline = 0;
if (print)
*returnval = 1;
}
if ((ms->flags & MAGIC_CONTINUE) == 0 && *printed_something) {
return *returnval; /* don't keep searching */
}
}
return *returnval; /* This is hit if -k is set or there is no match */
}
private int
check_fmt(struct magic_set *ms, struct magic *m)
{
regex_t rx;
int rc, rv = -1;
if (strchr(m->desc, '%') == NULL)
return 0;
(void)setlocale(LC_CTYPE, "C");
rc = regcomp(&rx, "%[-0-9\\.]*s", REG_EXTENDED|REG_NOSUB);
if (rc) {
char errmsg[512];
(void)regerror(rc, &rx, errmsg, sizeof(errmsg));
file_magerror(ms, "regex error %d, (%s)", rc, errmsg);
} else {
rc = regexec(&rx, m->desc, 0, 0, 0);
regfree(&rx);
rv = !rc;
}
(void)setlocale(LC_CTYPE, "");
return rv;
}
#ifndef HAVE_STRNDUP
char * strndup(const char *, size_t);
char *
strndup(const char *str, size_t n)
{
size_t len;
char *copy;
for (len = 0; len < n && str[len]; len++)
continue;
if ((copy = malloc(len + 1)) == NULL)
return NULL;
(void)memcpy(copy, str, len);
copy[len] = '\0';
return copy;
}
#endif /* HAVE_STRNDUP */
private int32_t
mprint(struct magic_set *ms, struct magic *m)
{
uint64_t v;
float vf;
double vd;
int64_t t = 0;
char buf[128], tbuf[26];
union VALUETYPE *p = &ms->ms_value;
switch (m->type) {
case FILE_BYTE:
v = file_signextend(ms, m, (uint64_t)p->b);
switch (check_fmt(ms, m)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%c",
(unsigned char)v);
if (file_printf(ms, F(m->desc, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(m->desc, "%c"),
(unsigned char) v) == -1)
return -1;
break;
}
t = ms->offset + sizeof(char);
break;
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
v = file_signextend(ms, m, (uint64_t)p->h);
switch (check_fmt(ms, m)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%hu",
(unsigned short)v);
if (file_printf(ms, F(m->desc, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(m->desc, "%hu"),
(unsigned short) v) == -1)
return -1;
break;
}
t = ms->offset + sizeof(short);
break;
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
v = file_signextend(ms, m, (uint64_t)p->l);
switch (check_fmt(ms, m)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%u", (uint32_t)v);
if (file_printf(ms, F(m->desc, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(m->desc, "%u"),
(uint32_t) v) == -1)
return -1;
break;
}
t = ms->offset + sizeof(int32_t);
break;
case FILE_QUAD:
case FILE_BEQUAD:
case FILE_LEQUAD:
v = file_signextend(ms, m, p->q);
switch (check_fmt(ms, m)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%llu",
(unsigned long long)v);
if (file_printf(ms, F(m->desc, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(m->desc, "%llu"),
(unsigned long long) v) == -1)
return -1;
break;
}
t = ms->offset + sizeof(int64_t);
break;
case FILE_STRING:
case FILE_PSTRING:
case FILE_BESTRING16:
case FILE_LESTRING16:
if (m->reln == '=' || m->reln == '!') {
if (file_printf(ms, F(m->desc, "%s"), m->value.s) == -1)
return -1;
t = ms->offset + m->vallen;
}
else {
char *str = p->s;
/* compute t before we mangle the string? */
t = ms->offset + strlen(str);
if (*m->value.s == '\0')
str[strcspn(str, "\n")] = '\0';
if (m->str_flags & STRING_TRIM) {
char *last;
while (isspace((unsigned char)*str))
str++;
last = str;
while (*last)
last++;
--last;
while (isspace((unsigned char)*last))
last--;
*++last = '\0';
}
if (file_printf(ms, F(m->desc, "%s"), str) == -1)
return -1;
if (m->type == FILE_PSTRING)
t += file_pstring_length_size(m);
}
break;
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
if (file_printf(ms, F(m->desc, "%s"),
file_fmttime(p->l, FILE_T_LOCAL,
tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint32_t);
break;
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
if (file_printf(ms, F(m->desc, "%s"),
file_fmttime(p->l, 0, tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint32_t);
break;
case FILE_QDATE:
case FILE_BEQDATE:
case FILE_LEQDATE:
if (file_printf(ms, F(m->desc, "%s"),
file_fmttime(p->q, FILE_T_LOCAL, tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint64_t);
break;
case FILE_QLDATE:
case FILE_BEQLDATE:
case FILE_LEQLDATE:
if (file_printf(ms, F(m->desc, "%s"),
file_fmttime(p->q, 0, tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint64_t);
break;
case FILE_QWDATE:
case FILE_BEQWDATE:
case FILE_LEQWDATE:
if (file_printf(ms, F(m->desc, "%s"),
file_fmttime(p->q, FILE_T_WINDOWS, tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint64_t);
break;
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
vf = p->f;
switch (check_fmt(ms, m)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%g", vf);
if (file_printf(ms, F(m->desc, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(m->desc, "%g"), vf) == -1)
return -1;
break;
}
t = ms->offset + sizeof(float);
break;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
vd = p->d;
switch (check_fmt(ms, m)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%g", vd);
if (file_printf(ms, F(m->desc, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(m->desc, "%g"), vd) == -1)
return -1;
break;
}
t = ms->offset + sizeof(double);
break;
case FILE_REGEX: {
char *cp;
int rval;
cp = strndup((const char *)ms->search.s, ms->search.rm_len);
if (cp == NULL) {
file_oomem(ms, ms->search.rm_len);
return -1;
}
rval = file_printf(ms, F(m->desc, "%s"), cp);
free(cp);
if (rval == -1)
return -1;
if ((m->str_flags & REGEX_OFFSET_START))
t = ms->search.offset;
else
t = ms->search.offset + ms->search.rm_len;
break;
}
case FILE_SEARCH:
if (file_printf(ms, F(m->desc, "%s"), m->value.s) == -1)
return -1;
if ((m->str_flags & REGEX_OFFSET_START))
t = ms->search.offset;
else
t = ms->search.offset + m->vallen;
break;
case FILE_DEFAULT:
case FILE_CLEAR:
if (file_printf(ms, "%s", m->desc) == -1)
return -1;
t = ms->offset;
break;
case FILE_INDIRECT:
case FILE_USE:
case FILE_NAME:
t = ms->offset;
break;
default:
file_magerror(ms, "invalid m->type (%d) in mprint()", m->type);
return -1;
}
return (int32_t)t;
}
private int32_t
moffset(struct magic_set *ms, struct magic *m)
{
switch (m->type) {
case FILE_BYTE:
return CAST(int32_t, (ms->offset + sizeof(char)));
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
return CAST(int32_t, (ms->offset + sizeof(short)));
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
return CAST(int32_t, (ms->offset + sizeof(int32_t)));
case FILE_QUAD:
case FILE_BEQUAD:
case FILE_LEQUAD:
return CAST(int32_t, (ms->offset + sizeof(int64_t)));
case FILE_STRING:
case FILE_PSTRING:
case FILE_BESTRING16:
case FILE_LESTRING16:
if (m->reln == '=' || m->reln == '!')
return ms->offset + m->vallen;
else {
union VALUETYPE *p = &ms->ms_value;
uint32_t t;
if (*m->value.s == '\0')
p->s[strcspn(p->s, "\n")] = '\0';
t = CAST(uint32_t, (ms->offset + strlen(p->s)));
if (m->type == FILE_PSTRING)
t += (uint32_t)file_pstring_length_size(m);
return t;
}
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
return CAST(int32_t, (ms->offset + sizeof(uint32_t)));
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
return CAST(int32_t, (ms->offset + sizeof(uint32_t)));
case FILE_QDATE:
case FILE_BEQDATE:
case FILE_LEQDATE:
return CAST(int32_t, (ms->offset + sizeof(uint64_t)));
case FILE_QLDATE:
case FILE_BEQLDATE:
case FILE_LEQLDATE:
return CAST(int32_t, (ms->offset + sizeof(uint64_t)));
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
return CAST(int32_t, (ms->offset + sizeof(float)));
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
return CAST(int32_t, (ms->offset + sizeof(double)));
case FILE_REGEX:
if ((m->str_flags & REGEX_OFFSET_START) != 0)
return CAST(int32_t, ms->search.offset);
else
return CAST(int32_t, (ms->search.offset +
ms->search.rm_len));
case FILE_SEARCH:
if ((m->str_flags & REGEX_OFFSET_START) != 0)
return CAST(int32_t, ms->search.offset);
else
return CAST(int32_t, (ms->search.offset + m->vallen));
case FILE_CLEAR:
case FILE_DEFAULT:
case FILE_INDIRECT:
return ms->offset;
default:
return 0;
}
}
private int
cvt_flip(int type, int flip)
{
if (flip == 0)
return type;
switch (type) {
case FILE_BESHORT:
return FILE_LESHORT;
case FILE_BELONG:
return FILE_LELONG;
case FILE_BEDATE:
return FILE_LEDATE;
case FILE_BELDATE:
return FILE_LELDATE;
case FILE_BEQUAD:
return FILE_LEQUAD;
case FILE_BEQDATE:
return FILE_LEQDATE;
case FILE_BEQLDATE:
return FILE_LEQLDATE;
case FILE_BEQWDATE:
return FILE_LEQWDATE;
case FILE_LESHORT:
return FILE_BESHORT;
case FILE_LELONG:
return FILE_BELONG;
case FILE_LEDATE:
return FILE_BEDATE;
case FILE_LELDATE:
return FILE_BELDATE;
case FILE_LEQUAD:
return FILE_BEQUAD;
case FILE_LEQDATE:
return FILE_BEQDATE;
case FILE_LEQLDATE:
return FILE_BEQLDATE;
case FILE_LEQWDATE:
return FILE_BEQWDATE;
case FILE_BEFLOAT:
return FILE_LEFLOAT;
case FILE_LEFLOAT:
return FILE_BEFLOAT;
case FILE_BEDOUBLE:
return FILE_LEDOUBLE;
case FILE_LEDOUBLE:
return FILE_BEDOUBLE;
default:
return type;
}
}
#define DO_CVT(fld, cast) \
if (m->num_mask) \
switch (m->mask_op & FILE_OPS_MASK) { \
case FILE_OPAND: \
p->fld &= cast m->num_mask; \
break; \
case FILE_OPOR: \
p->fld |= cast m->num_mask; \
break; \
case FILE_OPXOR: \
p->fld ^= cast m->num_mask; \
break; \
case FILE_OPADD: \
p->fld += cast m->num_mask; \
break; \
case FILE_OPMINUS: \
p->fld -= cast m->num_mask; \
break; \
case FILE_OPMULTIPLY: \
p->fld *= cast m->num_mask; \
break; \
case FILE_OPDIVIDE: \
p->fld /= cast m->num_mask; \
break; \
case FILE_OPMODULO: \
p->fld %= cast m->num_mask; \
break; \
} \
if (m->mask_op & FILE_OPINVERSE) \
p->fld = ~p->fld \
private void
cvt_8(union VALUETYPE *p, const struct magic *m)
{
DO_CVT(b, (uint8_t));
}
private void
cvt_16(union VALUETYPE *p, const struct magic *m)
{
DO_CVT(h, (uint16_t));
}
private void
cvt_32(union VALUETYPE *p, const struct magic *m)
{
DO_CVT(l, (uint32_t));
}
private void
cvt_64(union VALUETYPE *p, const struct magic *m)
{
DO_CVT(q, (uint64_t));
}
#define DO_CVT2(fld, cast) \
if (m->num_mask) \
switch (m->mask_op & FILE_OPS_MASK) { \
case FILE_OPADD: \
p->fld += cast m->num_mask; \
break; \
case FILE_OPMINUS: \
p->fld -= cast m->num_mask; \
break; \
case FILE_OPMULTIPLY: \
p->fld *= cast m->num_mask; \
break; \
case FILE_OPDIVIDE: \
p->fld /= cast m->num_mask; \
break; \
} \
private void
cvt_float(union VALUETYPE *p, const struct magic *m)
{
DO_CVT2(f, (float));
}
private void
cvt_double(union VALUETYPE *p, const struct magic *m)
{
DO_CVT2(d, (double));
}
/*
* Convert the byte order of the data we are looking at
* While we're here, let's apply the mask operation
* (unless you have a better idea)
*/
private int
mconvert(struct magic_set *ms, struct magic *m, int flip)
{
union VALUETYPE *p = &ms->ms_value;
switch (cvt_flip(m->type, flip)) {
case FILE_BYTE:
cvt_8(p, m);
return 1;
case FILE_SHORT:
cvt_16(p, m);
return 1;
case FILE_LONG:
case FILE_DATE:
case FILE_LDATE:
cvt_32(p, m);
return 1;
case FILE_QUAD:
case FILE_QDATE:
case FILE_QLDATE:
case FILE_QWDATE:
cvt_64(p, m);
return 1;
case FILE_STRING:
case FILE_BESTRING16:
case FILE_LESTRING16: {
/* Null terminate and eat *trailing* return */
p->s[sizeof(p->s) - 1] = '\0';
return 1;
}
case FILE_PSTRING: {
char *ptr1 = p->s, *ptr2 = ptr1 + file_pstring_length_size(m);
size_t len = file_pstring_get_length(m, ptr1);
if (len >= sizeof(p->s))
len = sizeof(p->s) - 1;
while (len--)
*ptr1++ = *ptr2++;
*ptr1 = '\0';
return 1;
}
case FILE_BESHORT:
p->h = (short)((p->hs[0]<<8)|(p->hs[1]));
cvt_16(p, m);
return 1;
case FILE_BELONG:
case FILE_BEDATE:
case FILE_BELDATE:
p->l = (int32_t)
((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3]));
cvt_32(p, m);
return 1;
case FILE_BEQUAD:
case FILE_BEQDATE:
case FILE_BEQLDATE:
case FILE_BEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7]));
cvt_64(p, m);
return 1;
case FILE_LESHORT:
p->h = (short)((p->hs[1]<<8)|(p->hs[0]));
cvt_16(p, m);
return 1;
case FILE_LELONG:
case FILE_LEDATE:
case FILE_LELDATE:
p->l = (int32_t)
((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0]));
cvt_32(p, m);
return 1;
case FILE_LEQUAD:
case FILE_LEQDATE:
case FILE_LEQLDATE:
case FILE_LEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0]));
cvt_64(p, m);
return 1;
case FILE_MELONG:
case FILE_MEDATE:
case FILE_MELDATE:
p->l = (int32_t)
((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2]));
cvt_32(p, m);
return 1;
case FILE_FLOAT:
cvt_float(p, m);
return 1;
case FILE_BEFLOAT:
p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)|
((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]);
cvt_float(p, m);
return 1;
case FILE_LEFLOAT:
p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)|
((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]);
cvt_float(p, m);
return 1;
case FILE_DOUBLE:
cvt_double(p, m);
return 1;
case FILE_BEDOUBLE:
p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]);
cvt_double(p, m);
return 1;
case FILE_LEDOUBLE:
p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]);
cvt_double(p, m);
return 1;
case FILE_REGEX:
case FILE_SEARCH:
case FILE_DEFAULT:
case FILE_CLEAR:
case FILE_NAME:
case FILE_USE:
return 1;
default:
file_magerror(ms, "invalid type %d in mconvert()", m->type);
return 0;
}
}
private void
mdebug(uint32_t offset, const char *str, size_t len)
{
(void) fprintf(stderr, "mget/%zu @%d: ", len, offset);
file_showstr(stderr, str, len);
(void) fputc('\n', stderr);
(void) fputc('\n', stderr);
}
private int
mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir,
const unsigned char *s, uint32_t offset, size_t nbytes, size_t linecnt)
{
/*
* Note: FILE_SEARCH and FILE_REGEX do not actually copy
* anything, but setup pointers into the source
*/
if (indir == 0) {
switch (type) {
case FILE_SEARCH:
ms->search.s = RCAST(const char *, s) + offset;
ms->search.s_len = nbytes - offset;
ms->search.offset = offset;
return 0;
case FILE_REGEX: {
const char *b;
const char *c;
const char *last; /* end of search region */
const char *buf; /* start of search region */
const char *end;
size_t lines;
if (s == NULL) {
ms->search.s_len = 0;
ms->search.s = NULL;
return 0;
}
buf = RCAST(const char *, s) + offset;
end = last = RCAST(const char *, s) + nbytes;
/* mget() guarantees buf <= last */
for (lines = linecnt, b = buf; lines && b < end &&
((b = CAST(const char *,
memchr(c = b, '\n', CAST(size_t, (end - b)))))
|| (b = CAST(const char *,
memchr(c, '\r', CAST(size_t, (end - c))))));
lines--, b++) {
last = b;
if (b[0] == '\r' && b[1] == '\n')
b++;
}
if (lines)
last = RCAST(const char *, s) + nbytes;
ms->search.s = buf;
ms->search.s_len = last - buf;
ms->search.offset = offset;
ms->search.rm_len = 0;
return 0;
}
case FILE_BESTRING16:
case FILE_LESTRING16: {
const unsigned char *src = s + offset;
const unsigned char *esrc = s + nbytes;
char *dst = p->s;
char *edst = &p->s[sizeof(p->s) - 1];
if (type == FILE_BESTRING16)
src++;
/* check that offset is within range */
if (offset >= nbytes)
break;
for (/*EMPTY*/; src < esrc; src += 2, dst++) {
if (dst < edst)
*dst = *src;
else
break;
if (*dst == '\0') {
if (type == FILE_BESTRING16 ?
*(src - 1) != '\0' :
*(src + 1) != '\0')
*dst = ' ';
}
}
*edst = '\0';
return 0;
}
case FILE_STRING: /* XXX - these two should not need */
case FILE_PSTRING: /* to copy anything, but do anyway. */
default:
break;
}
}
if (offset >= nbytes) {
(void)memset(p, '\0', sizeof(*p));
return 0;
}
if (nbytes - offset < sizeof(*p))
nbytes = nbytes - offset;
else
nbytes = sizeof(*p);
(void)memcpy(p, s + offset, nbytes);
/*
* the usefulness of padding with zeroes eludes me, it
* might even cause problems
*/
if (nbytes < sizeof(*p))
(void)memset(((char *)(void *)p) + nbytes, '\0',
sizeof(*p) - nbytes);
return 0;
}
private int
mget(struct magic_set *ms, const unsigned char *s, struct magic *m,
size_t nbytes, size_t o, unsigned int cont_level, int mode, int text,
int flip, int recursion_level, int *printed_something,
int *need_separator, int *returnval)
{
uint32_t soffset, offset = ms->offset;
uint32_t count = m->str_range;
int rv, oneed_separator, in_type;
char *sbuf, *rbuf;
union VALUETYPE *p = &ms->ms_value;
struct mlist ml;
if (recursion_level >= 20) {
file_error(ms, 0, "recursion nesting exceeded");
return -1;
}
if (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o),
(uint32_t)nbytes, count) == -1)
return -1;
if ((ms->flags & MAGIC_DEBUG) != 0) {
fprintf(stderr, "mget(type=%d, flag=%x, offset=%u, o=%zu, "
"nbytes=%zu, count=%u)\n", m->type, m->flag, offset, o,
nbytes, count);
mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE));
#ifndef COMPILE_ONLY
file_mdump(m);
#endif
}
if (m->flag & INDIR) {
int off = m->in_offset;
if (m->in_op & FILE_OPINDIRECT) {
const union VALUETYPE *q = CAST(const union VALUETYPE *,
((const void *)(s + offset + off)));
switch (cvt_flip(m->in_type, flip)) {
case FILE_BYTE:
off = q->b;
break;
case FILE_SHORT:
off = q->h;
break;
case FILE_BESHORT:
off = (short)((q->hs[0]<<8)|(q->hs[1]));
break;
case FILE_LESHORT:
off = (short)((q->hs[1]<<8)|(q->hs[0]));
break;
case FILE_LONG:
off = q->l;
break;
case FILE_BELONG:
case FILE_BEID3:
off = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)|
(q->hl[2]<<8)|(q->hl[3]));
break;
case FILE_LEID3:
case FILE_LELONG:
off = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)|
(q->hl[1]<<8)|(q->hl[0]));
break;
case FILE_MELONG:
off = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)|
(q->hl[3]<<8)|(q->hl[2]));
break;
}
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect offs=%u\n", off);
}
switch (in_type = cvt_flip(m->in_type, flip)) {
case FILE_BYTE:
if (OFFSET_OOB(nbytes, offset, 1))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->b & off;
break;
case FILE_OPOR:
offset = p->b | off;
break;
case FILE_OPXOR:
offset = p->b ^ off;
break;
case FILE_OPADD:
offset = p->b + off;
break;
case FILE_OPMINUS:
offset = p->b - off;
break;
case FILE_OPMULTIPLY:
offset = p->b * off;
break;
case FILE_OPDIVIDE:
offset = p->b / off;
break;
case FILE_OPMODULO:
offset = p->b % off;
break;
}
} else
offset = p->b;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_BESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) &
off;
break;
case FILE_OPOR:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) |
off;
break;
case FILE_OPXOR:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) ^
off;
break;
case FILE_OPADD:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) +
off;
break;
case FILE_OPMINUS:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) *
off;
break;
case FILE_OPDIVIDE:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) /
off;
break;
case FILE_OPMODULO:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) %
off;
break;
}
} else
offset = (short)((p->hs[0]<<8)|
(p->hs[1]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) &
off;
break;
case FILE_OPOR:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) |
off;
break;
case FILE_OPXOR:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) ^
off;
break;
case FILE_OPADD:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) +
off;
break;
case FILE_OPMINUS:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) *
off;
break;
case FILE_OPDIVIDE:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) /
off;
break;
case FILE_OPMODULO:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) %
off;
break;
}
} else
offset = (short)((p->hs[1]<<8)|
(p->hs[0]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_SHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->h & off;
break;
case FILE_OPOR:
offset = p->h | off;
break;
case FILE_OPXOR:
offset = p->h ^ off;
break;
case FILE_OPADD:
offset = p->h + off;
break;
case FILE_OPMINUS:
offset = p->h - off;
break;
case FILE_OPMULTIPLY:
offset = p->h * off;
break;
case FILE_OPDIVIDE:
offset = p->h / off;
break;
case FILE_OPMODULO:
offset = p->h % off;
break;
}
}
else
offset = p->h;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_BELONG:
case FILE_BEID3:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) &
off;
break;
case FILE_OPOR:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) |
off;
break;
case FILE_OPXOR:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) ^
off;
break;
case FILE_OPADD:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) +
off;
break;
case FILE_OPMINUS:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) *
off;
break;
case FILE_OPDIVIDE:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) /
off;
break;
case FILE_OPMODULO:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) %
off;
break;
}
} else
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LELONG:
case FILE_LEID3:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) &
off;
break;
case FILE_OPOR:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) |
off;
break;
case FILE_OPXOR:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) ^
off;
break;
case FILE_OPADD:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) +
off;
break;
case FILE_OPMINUS:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) *
off;
break;
case FILE_OPDIVIDE:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) /
off;
break;
case FILE_OPMODULO:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) %
off;
break;
}
} else
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_MELONG:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) &
off;
break;
case FILE_OPOR:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) |
off;
break;
case FILE_OPXOR:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) ^
off;
break;
case FILE_OPADD:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) +
off;
break;
case FILE_OPMINUS:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) *
off;
break;
case FILE_OPDIVIDE:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) /
off;
break;
case FILE_OPMODULO:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) %
off;
break;
}
} else
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LONG:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->l & off;
break;
case FILE_OPOR:
offset = p->l | off;
break;
case FILE_OPXOR:
offset = p->l ^ off;
break;
case FILE_OPADD:
offset = p->l + off;
break;
case FILE_OPMINUS:
offset = p->l - off;
break;
case FILE_OPMULTIPLY:
offset = p->l * off;
break;
case FILE_OPDIVIDE:
offset = p->l / off;
break;
case FILE_OPMODULO:
offset = p->l % off;
break;
}
} else
offset = p->l;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
default:
break;
}
switch (in_type) {
case FILE_LEID3:
case FILE_BEID3:
offset = ((((offset >> 0) & 0x7f) << 0) |
(((offset >> 8) & 0x7f) << 7) |
(((offset >> 16) & 0x7f) << 14) |
(((offset >> 24) & 0x7f) << 21)) + 10;
break;
default:
break;
}
if (m->flag & INDIROFFADD) {
offset += ms->c.li[cont_level-1].off;
if (offset == 0) {
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr,
"indirect *zero* offset\n");
return 0;
}
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect +offs=%u\n", offset);
}
if (mcopy(ms, p, m->type, 0, s, offset, nbytes, count) == -1)
return -1;
ms->offset = offset;
if ((ms->flags & MAGIC_DEBUG) != 0) {
mdebug(offset, (char *)(void *)p,
sizeof(union VALUETYPE));
#ifndef COMPILE_ONLY
file_mdump(m);
#endif
}
}
/* Verify we have enough data to match magic type */
switch (m->type) {
case FILE_BYTE:
if (OFFSET_OOB(nbytes, offset, 1))
return 0;
break;
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
break;
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
break;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
if (OFFSET_OOB(nbytes, offset, 8))
return 0;
break;
case FILE_STRING:
case FILE_PSTRING:
case FILE_SEARCH:
if (OFFSET_OOB(nbytes, offset, m->vallen))
return 0;
break;
case FILE_REGEX:
if (OFFSET_OOB(nbytes, offset, 0))
return 0;
break;
case FILE_INDIRECT:
if (OFFSET_OOB(nbytes, offset, 0))
return 0;
sbuf = ms->o.buf;
soffset = ms->offset;
ms->o.buf = NULL;
ms->offset = 0;
rv = file_softmagic(ms, s + offset, nbytes - offset,
BINTEST, text);
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect @offs=%u[%d]\n", offset, rv);
rbuf = ms->o.buf;
ms->o.buf = sbuf;
ms->offset = soffset;
if (rv == 1) {
if ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 &&
file_printf(ms, F(m->desc, "%u"), offset) == -1)
return -1;
if (file_printf(ms, "%s", rbuf) == -1)
return -1;
free(rbuf);
}
return rv;
case FILE_USE:
if (OFFSET_OOB(nbytes, offset, 0))
return 0;
sbuf = m->value.s;
if (*sbuf == '^') {
sbuf++;
flip = !flip;
}
if (file_magicfind(ms, sbuf, &ml) == -1) {
file_error(ms, 0, "cannot find entry `%s'", sbuf);
return -1;
}
oneed_separator = *need_separator;
if (m->flag & NOSPACE)
*need_separator = 0;
rv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o,
mode, text, flip, recursion_level, printed_something,
need_separator, returnval);
if (rv != 1)
*need_separator = oneed_separator;
return rv;
case FILE_NAME:
if (file_printf(ms, "%s", m->desc) == -1)
return -1;
return 1;
case FILE_DEFAULT: /* nothing to check */
case FILE_CLEAR:
default:
break;
}
if (!mconvert(ms, m, flip))
return 0;
return 1;
}
private uint64_t
file_strncmp(const char *s1, const char *s2, size_t len, uint32_t flags)
{
/*
* Convert the source args to unsigned here so that (1) the
* compare will be unsigned as it is in strncmp() and (2) so
* the ctype functions will work correctly without extra
* casting.
*/
const unsigned char *a = (const unsigned char *)s1;
const unsigned char *b = (const unsigned char *)s2;
uint64_t v;
/*
* What we want here is v = strncmp(s1, s2, len),
* but ignoring any nulls.
*/
v = 0;
if (0L == flags) { /* normal string: do it fast */
while (len-- > 0)
if ((v = *b++ - *a++) != '\0')
break;
}
else { /* combine the others */
while (len-- > 0) {
if ((flags & STRING_IGNORE_LOWERCASE) &&
islower(*a)) {
if ((v = tolower(*b++) - *a++) != '\0')
break;
}
else if ((flags & STRING_IGNORE_UPPERCASE) &&
isupper(*a)) {
if ((v = toupper(*b++) - *a++) != '\0')
break;
}
else if ((flags & STRING_COMPACT_WHITESPACE) &&
isspace(*a)) {
a++;
if (isspace(*b++)) {
if (!isspace(*a))
while (isspace(*b))
b++;
}
else {
v = 1;
break;
}
}
else if ((flags & STRING_COMPACT_OPTIONAL_WHITESPACE) &&
isspace(*a)) {
a++;
while (isspace(*b))
b++;
}
else {
if ((v = *b++ - *a++) != '\0')
break;
}
}
}
return v;
}
private uint64_t
file_strncmp16(const char *a, const char *b, size_t len, uint32_t flags)
{
/*
* XXX - The 16-bit string compare probably needs to be done
* differently, especially if the flags are to be supported.
* At the moment, I am unsure.
*/
flags = 0;
return file_strncmp(a, b, len, flags);
}
private int
magiccheck(struct magic_set *ms, struct magic *m)
{
uint64_t l = m->value.q;
uint64_t v;
float fl, fv;
double dl, dv;
int matched;
union VALUETYPE *p = &ms->ms_value;
switch (m->type) {
case FILE_BYTE:
v = p->b;
break;
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
v = p->h;
break;
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
v = p->l;
break;
case FILE_QUAD:
case FILE_LEQUAD:
case FILE_BEQUAD:
case FILE_QDATE:
case FILE_BEQDATE:
case FILE_LEQDATE:
case FILE_QLDATE:
case FILE_BEQLDATE:
case FILE_LEQLDATE:
case FILE_QWDATE:
case FILE_BEQWDATE:
case FILE_LEQWDATE:
v = p->q;
break;
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
fl = m->value.f;
fv = p->f;
switch (m->reln) {
case 'x':
matched = 1;
break;
case '!':
matched = fv != fl;
break;
case '=':
matched = fv == fl;
break;
case '>':
matched = fv > fl;
break;
case '<':
matched = fv < fl;
break;
default:
matched = 0;
file_magerror(ms, "cannot happen with float: invalid relation `%c'",
m->reln);
return -1;
}
return matched;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
dl = m->value.d;
dv = p->d;
switch (m->reln) {
case 'x':
matched = 1;
break;
case '!':
matched = dv != dl;
break;
case '=':
matched = dv == dl;
break;
case '>':
matched = dv > dl;
break;
case '<':
matched = dv < dl;
break;
default:
matched = 0;
file_magerror(ms, "cannot happen with double: invalid relation `%c'", m->reln);
return -1;
}
return matched;
case FILE_DEFAULT:
case FILE_CLEAR:
l = 0;
v = 0;
break;
case FILE_STRING:
case FILE_PSTRING:
l = 0;
v = file_strncmp(m->value.s, p->s, (size_t)m->vallen, m->str_flags);
break;
case FILE_BESTRING16:
case FILE_LESTRING16:
l = 0;
v = file_strncmp16(m->value.s, p->s, (size_t)m->vallen, m->str_flags);
break;
case FILE_SEARCH: { /* search ms->search.s for the string m->value.s */
size_t slen;
size_t idx;
if (ms->search.s == NULL)
return 0;
slen = MIN(m->vallen, sizeof(m->value.s));
l = 0;
v = 0;
for (idx = 0; m->str_range == 0 || idx < m->str_range; idx++) {
if (slen + idx > ms->search.s_len)
break;
v = file_strncmp(m->value.s, ms->search.s + idx, slen, m->str_flags);
if (v == 0) { /* found match */
ms->search.offset += idx;
break;
}
}
break;
}
case FILE_REGEX: {
int rc;
regex_t rx;
char errmsg[512];
if (ms->search.s == NULL)
return 0;
l = 0;
rc = regcomp(&rx, m->value.s,
REG_EXTENDED|REG_NEWLINE|
((m->str_flags & STRING_IGNORE_CASE) ? REG_ICASE : 0));
if (rc) {
(void)regerror(rc, &rx, errmsg, sizeof(errmsg));
file_magerror(ms, "regex error %d, (%s)",
rc, errmsg);
v = (uint64_t)-1;
}
else {
regmatch_t pmatch[1];
#ifndef REG_STARTEND
#define REG_STARTEND 0
size_t l = ms->search.s_len - 1;
char c = ms->search.s[l];
((char *)(intptr_t)ms->search.s)[l] = '\0';
#else
pmatch[0].rm_so = 0;
pmatch[0].rm_eo = ms->search.s_len;
#endif
rc = regexec(&rx, (const char *)ms->search.s,
1, pmatch, REG_STARTEND);
#if REG_STARTEND == 0
((char *)(intptr_t)ms->search.s)[l] = c;
#endif
switch (rc) {
case 0:
ms->search.s += (int)pmatch[0].rm_so;
ms->search.offset += (size_t)pmatch[0].rm_so;
ms->search.rm_len =
(size_t)(pmatch[0].rm_eo - pmatch[0].rm_so);
v = 0;
break;
case REG_NOMATCH:
v = 1;
break;
default:
(void)regerror(rc, &rx, errmsg, sizeof(errmsg));
file_magerror(ms, "regexec error %d, (%s)",
rc, errmsg);
v = (uint64_t)-1;
break;
}
regfree(&rx);
}
if (v == (uint64_t)-1)
return -1;
break;
}
case FILE_INDIRECT:
case FILE_USE:
case FILE_NAME:
return 1;
default:
file_magerror(ms, "invalid type %d in magiccheck()", m->type);
return -1;
}
v = file_signextend(ms, m, v);
switch (m->reln) {
case 'x':
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"u == *any* = 1\n", (unsigned long long)v);
matched = 1;
break;
case '!':
matched = v != l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT "u != %"
INT64_T_FORMAT "u = %d\n", (unsigned long long)v,
(unsigned long long)l, matched);
break;
case '=':
matched = v == l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT "u == %"
INT64_T_FORMAT "u = %d\n", (unsigned long long)v,
(unsigned long long)l, matched);
break;
case '>':
if (m->flag & UNSIGNED) {
matched = v > l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"u > %" INT64_T_FORMAT "u = %d\n",
(unsigned long long)v,
(unsigned long long)l, matched);
}
else {
matched = (int64_t) v > (int64_t) l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"d > %" INT64_T_FORMAT "d = %d\n",
(long long)v, (long long)l, matched);
}
break;
case '<':
if (m->flag & UNSIGNED) {
matched = v < l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"u < %" INT64_T_FORMAT "u = %d\n",
(unsigned long long)v,
(unsigned long long)l, matched);
}
else {
matched = (int64_t) v < (int64_t) l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"d < %" INT64_T_FORMAT "d = %d\n",
(long long)v, (long long)l, matched);
}
break;
case '&':
matched = (v & l) == l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "((%" INT64_T_FORMAT "x & %"
INT64_T_FORMAT "x) == %" INT64_T_FORMAT
"x) = %d\n", (unsigned long long)v,
(unsigned long long)l, (unsigned long long)l,
matched);
break;
case '^':
matched = (v & l) != l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "((%" INT64_T_FORMAT "x & %"
INT64_T_FORMAT "x) != %" INT64_T_FORMAT
"x) = %d\n", (unsigned long long)v,
(unsigned long long)l, (unsigned long long)l,
matched);
break;
default:
matched = 0;
file_magerror(ms, "cannot happen: invalid relation `%c'",
m->reln);
return -1;
}
return matched;
}
private int
handle_annotation(struct magic_set *ms, struct magic *m)
{
if (ms->flags & MAGIC_APPLE) {
if (file_printf(ms, "%.8s", m->apple) == -1)
return -1;
return 1;
}
if ((ms->flags & MAGIC_MIME_TYPE) && m->mimetype[0]) {
if (file_printf(ms, "%s", m->mimetype) == -1)
return -1;
return 1;
}
return 0;
}
private int
print_sep(struct magic_set *ms, int firstline)
{
if (ms->flags & MAGIC_MIME)
return 0;
if (firstline)
return 0;
/*
* we found another match
* put a newline and '-' to do some simple formatting
*/
return file_printf(ms, "\n- ");
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2107_0 |
crossvul-cpp_data_bad_3716_0 | /*
* Copyright (C) 2005-2012 Gilles Darold
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* Some part of the code of squidclamav are learn or simply copy/paste
* from the srv_clamav c-icap service written by Christos Tsantilas.
*
* Copyright (C) 2004 Christos Tsantilas
*
* Thanks to him for his great work.
*/
#include "c-icap.h"
#include "service.h"
#include "header.h"
#include "body.h"
#include "simple_api.h"
#include "debug.h"
#include "cfg_param.h"
#include "squidclamav.h"
#include "filetype.h"
#include "ci_threads.h"
#include "mem.h"
#include "commands.h"
#include <errno.h>
#include <signal.h>
/* Structure used to store information passed throught the module methods */
typedef struct av_req_data{
ci_simple_file_t *body;
ci_request_t *req;
ci_membuf_t *error_page;
int blocked;
int no_more_scan;
int virus;
char *url;
char *user;
char *clientip;
} av_req_data_t;
static int SEND_PERCENT_BYTES = 0;
static ci_off_t START_SEND_AFTER = 1;
/*squidclamav service extra data ... */
ci_service_xdata_t *squidclamav_xdata = NULL;
int AVREQDATA_POOL = -1;
int squidclamav_init_service(ci_service_xdata_t * srv_xdata, struct ci_server_conf *server_conf);
int squidclamav_post_init_service(ci_service_xdata_t * srv_xdata, struct ci_server_conf *server_conf);
void squidclamav_close_service();
int squidclamav_check_preview_handler(char *preview_data, int preview_data_len, ci_request_t *);
int squidclamav_end_of_data_handler(ci_request_t *);
void *squidclamav_init_request_data(ci_request_t * req);
void squidclamav_release_request_data(void *data);
int squidclamav_io(char *wbuf, int *wlen, char *rbuf, int *rlen, int iseof, ci_request_t * req);
/* General functions */
void set_istag(ci_service_xdata_t * srv_xdata);
/* Declare SquidClamav C-ICAP service */
CI_DECLARE_MOD_DATA ci_service_module_t service = {
"squidclamav", /*Module name */
"SquidClamav/Antivirus service", /* Module short description */
ICAP_RESPMOD | ICAP_REQMOD, /* Service type modification */
squidclamav_init_service, /* init_service. */
squidclamav_post_init_service, /* post_init_service. */
squidclamav_close_service, /* close_service */
squidclamav_init_request_data, /* init_request_data. */
squidclamav_release_request_data, /* release request data */
squidclamav_check_preview_handler, /* Preview data */
squidclamav_end_of_data_handler, /* when all data has been received */
squidclamav_io,
NULL,
NULL
};
int debug = 0;
int statit = 0;
int timeout = 1;
char *redirect_url = NULL;
char *squidguard = NULL;
char *clamd_local = NULL;
char *clamd_ip = NULL;
char *clamd_port = NULL;
char *clamd_curr_ip = NULL;
SCPattern *patterns = NULL;
int pattc = 0;
int current_pattern_size = 0;
ci_off_t maxsize = 0;
int logredir = 0;
int dnslookup = 1;
/* Used by pipe to squidGuard */
int usepipe = 0;
pid_t pid;
FILE *sgfpw = NULL;
FILE *sgfpr = NULL;
/* --------------- URL CHECK --------------------------- */
#define MAX_URL_SIZE 8192
#define MAX_METHOD_SIZE 16
#define SMALL_BUFF 1024
struct http_info {
char method[MAX_METHOD_SIZE];
char url[MAX_URL_SIZE];
};
int extract_http_info(ci_request_t *, ci_headers_list_t *, struct http_info *);
char *http_content_type(ci_request_t *);
void free_global ();
void free_pipe ();
void generate_redirect_page(char *, ci_request_t *, av_req_data_t *);
void cfgreload_command(char *, int, char **);
int create_pipe(char *command);
int dconnect (void);
int connectINET(char *serverHost, uint16_t serverPort);
/* ----------------------------------------------------- */
int squidclamav_init_service(ci_service_xdata_t * srv_xdata,
struct ci_server_conf *server_conf)
{
unsigned int xops;
ci_debug_printf(1, "DEBUG squidclamav_init_service: Going to initialize squidclamav\n");
squidclamav_xdata = srv_xdata;
set_istag(squidclamav_xdata);
ci_service_set_preview(srv_xdata, 1024);
ci_service_enable_204(srv_xdata);
ci_service_set_transfer_preview(srv_xdata, "*");
xops = CI_XCLIENTIP | CI_XSERVERIP;
xops |= CI_XAUTHENTICATEDUSER | CI_XAUTHENTICATEDGROUPS;
ci_service_set_xopts(srv_xdata, xops);
/*Initialize object pools*/
AVREQDATA_POOL = ci_object_pool_register("av_req_data_t", sizeof(av_req_data_t));
if(AVREQDATA_POOL < 0) {
ci_debug_printf(0, "FATAL squidclamav_init_service: error registering object_pool av_req_data_t\n");
return 0;
}
/* Reload configuration command */
register_command("squidclamav:cfgreload", MONITOR_PROC_CMD | CHILDS_PROC_CMD, cfgreload_command);
/*********************
read config files
********************/
clamd_curr_ip = (char *) malloc (sizeof (char) * 128);
memset(clamd_curr_ip, 0, sizeof(clamd_curr_ip));
if (load_patterns() == 0) {
return 0;
}
return 1;
}
void cfgreload_command(char *name, int type, char **argv)
{
ci_debug_printf(1, "DEBUG cfgreload_command: reload configuration command received\n");
free_global();
free_pipe();
debug = 0;
statit = 0;
pattc = 0;
current_pattern_size = 0;
maxsize = 0;
logredir = 0;
dnslookup = 1;
clamd_curr_ip = (char *) malloc (sizeof (char) * 128);
memset(clamd_curr_ip, 0, sizeof(clamd_curr_ip));
if (load_patterns() == 0)
ci_debug_printf(0, "FATAL cfgreload_command: reload configuration command failed!\n");
if (squidclamav_xdata)
set_istag(squidclamav_xdata);
if (squidguard != NULL) {
ci_debug_printf(1, "DEBUG cfgreload_command: reopening pipe to %s\n", squidguard);
create_pipe(squidguard);
}
}
int squidclamav_post_init_service(ci_service_xdata_t * srv_xdata, struct ci_server_conf *server_conf)
{
if (squidguard == NULL) return 0;
ci_debug_printf(1, "DEBUG squidclamav_post_init_service: opening pipe to %s\n", squidguard);
if (create_pipe(squidguard) == 1) {
return 0;
}
return 1;
}
void squidclamav_close_service()
{
ci_debug_printf(1, "DEBUG squidclamav_close_service: clean all memory!\n");
free_global();
free_pipe();
ci_object_pool_unregister(AVREQDATA_POOL);
}
void *squidclamav_init_request_data(ci_request_t * req)
{
int preview_size;
av_req_data_t *data;
preview_size = ci_req_preview_size(req);
ci_debug_printf(1, "DEBUG squidclamav_init_request_data: initializing request data handler.\n");
if (!(data = ci_object_pool_alloc(AVREQDATA_POOL))) {
ci_debug_printf(0, "FATAL squidclamav_init_request_data: Error allocation memory for service data!!!");
return NULL;
}
data->body = NULL;
data->error_page = NULL;
data->req = req;
data->blocked = 0;
data->no_more_scan = 0;
data->virus = 0;
return data;
}
void squidclamav_release_request_data(void *data)
{
if (data) {
ci_debug_printf(1, "DEBUG squidclamav_release_request_data: Releasing request data.\n");
if (((av_req_data_t *) data)->body) {
ci_simple_file_destroy(((av_req_data_t *) data)->body);
if (((av_req_data_t *) data)->url)
ci_buffer_free(((av_req_data_t *) data)->url);
if (((av_req_data_t *) data)->user)
ci_buffer_free(((av_req_data_t *) data)->user);
if (((av_req_data_t *) data)->clientip)
ci_buffer_free(((av_req_data_t *) data)->clientip);
}
if (((av_req_data_t *) data)->error_page)
ci_membuf_free(((av_req_data_t *) data)->error_page);
ci_object_pool_free(data);
}
}
int squidclamav_check_preview_handler(char *preview_data, int preview_data_len, ci_request_t * req)
{
ci_headers_list_t *req_header;
struct http_info httpinf;
av_req_data_t *data = ci_service_data(req);
char *clientip;
struct hostent *clientname;
unsigned long ip;
char *username;
char *content_type;
ci_off_t content_length;
char *chain_ret = NULL;
char *ret = NULL;
int chkipdone = 0;
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: processing preview header.\n");
if (preview_data_len)
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: preview data size is %d\n", preview_data_len);
/* Extract the HTTP header from the request */
if ((req_header = ci_http_request_headers(req)) == NULL) {
ci_debug_printf(0, "ERROR squidclamav_check_preview_handler: bad http header, aborting.\n");
return CI_ERROR;
}
/* Get the Authenticated user */
if ((username = ci_headers_value(req->request_header, "X-Authenticated-User")) != NULL) {
ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: X-Authenticated-User: %s\n", username);
/* if a TRUSTUSER match => no squidguard and no virus scan */
if (simple_pattern_compare(username, TRUSTUSER) == 1) {
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No squidguard and antivir check (TRUSTUSER match) for user: %s\n", username);
return CI_MOD_ALLOW204;
}
} else {
/* set null client to - */
username = (char *)malloc(sizeof(char)*2);
strcpy(username, "-");
}
/* Check client Ip against SquidClamav trustclient */
if ((clientip = ci_headers_value(req->request_header, "X-Client-IP")) != NULL) {
ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: X-Client-IP: %s\n", clientip);
ip = inet_addr(clientip);
chkipdone = 0;
if (dnslookup == 1) {
if ( (clientname = gethostbyaddr((char *)&ip, sizeof(ip), AF_INET)) != NULL) {
if (clientname->h_name != NULL) {
/* if a TRUSTCLIENT match => no squidguard and no virus scan */
if (client_pattern_compare(clientip, clientname->h_name) > 0) {
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No squidguard and antivir check (TRUSTCLIENT match) for client: %s(%s)\n", clientname->h_name, clientip);
return CI_MOD_ALLOW204;
}
chkipdone = 1;
}
}
}
if (chkipdone == 0) {
/* if a TRUSTCLIENT match => no squidguard and no virus scan */
if (client_pattern_compare(clientip, NULL) > 0) {
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No squidguard and antivir check (TRUSTCLIENT match) for client: %s\n", clientip);
return CI_MOD_ALLOW204;
}
}
} else {
/* set null client to - */
clientip = (char *)malloc(sizeof(char)*2);
strcpy(clientip, "-");
}
/* Get the requested URL */
if (!extract_http_info(req, req_header, &httpinf)) {
/* Something wrong in the header or unknow method */
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: bad http header, aborting.\n");
return CI_MOD_ALLOW204;
}
ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: URL requested: %s\n", httpinf.url);
/* Check the URL against SquidClamav Whitelist */
if (simple_pattern_compare(httpinf.url, WHITELIST) == 1) {
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No squidguard and antivir check (WHITELIST match) for url: %s\n", httpinf.url);
return CI_MOD_ALLOW204;
}
/* Check URL header against squidGuard */
if (usepipe == 1) {
ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: Sending request to chained program: %s\n", squidguard);
ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: Request: %s %s %s %s\n", httpinf.url,clientip,username,httpinf.method);
fprintf(sgfpw,"%s %s %s %s\n",httpinf.url,clientip,username,httpinf.method);
fflush(sgfpw);
/* the chained redirector must return empty line if ok or the redirection url */
chain_ret = (char *)malloc(sizeof(char)*MAX_URL_SIZE);
if (chain_ret != NULL) {
ret = fgets(chain_ret,MAX_URL_SIZE,sgfpr);
if ((ret != NULL) && (strlen(chain_ret) > 1)) {
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: Chained program redirection received: %s\n", chain_ret);
if (logredir)
ci_debug_printf(0, "INFO Chained program redirection received: %s\n", chain_ret);
/* Create the redirection url to squid */
data->blocked = 1;
generate_redirect_page(strtok(chain_ret, " "), req, data);
xfree(chain_ret);
chain_ret = NULL;
return CI_MOD_CONTINUE;
}
xfree(chain_ret);
chain_ret = NULL;
}
}
/* CONNECT method (https) can not be scanned so abort */
if (strcmp(httpinf.method, "CONNECT") == 0) {
ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: method %s can't be scanned.\n", httpinf.method);
return CI_MOD_ALLOW204;
}
/* Check the URL against SquidClamav abort */
if (simple_pattern_compare(httpinf.url, ABORT) == 1) {
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No antivir check (ABORT match) for url: %s\n", httpinf.url);
return CI_MOD_ALLOW204;
}
/* Get the content length header */
content_length = ci_http_content_length(req);
ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: Content-Length: %d\n", (int)content_length);
if ((content_length > 0) && (maxsize > 0) && (content_length >= maxsize)) {
ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: No antivir check, content-length upper than maxsize (%d > %d)\n", content_length, (int)maxsize);
return CI_MOD_ALLOW204;
}
/* Get the content type header */
if ((content_type = http_content_type(req)) != NULL) {
ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: Content-Type: %s\n", content_type);
/* Check the Content-Type against SquidClamav abortcontent */
if (simple_pattern_compare(content_type, ABORTCONTENT)) {
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No antivir check (ABORTCONTENT match) for content-type: %s\n", content_type);
return CI_MOD_ALLOW204;
}
}
/* No data, so nothing to scan */
if (!data || !ci_req_hasbody(req)) {
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No body data, allow 204\n");
return CI_MOD_ALLOW204;
}
if (preview_data_len == 0) {
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: can not begin to scan url: No preview data.\n");
return CI_MOD_ALLOW204;
}
data->url = ci_buffer_alloc(strlen(httpinf.url)+1);
strcpy(data->url, httpinf.url);
if (username != NULL) {
data->user = ci_buffer_alloc(strlen(username)+1);
strcpy(data->user, username);
} else {
data->user = NULL;
}
if (clientip != NULL) {
data->clientip = ci_buffer_alloc(strlen(clientip)+1);
strcpy(data->clientip, clientip);
} else {
ci_debug_printf(0, "ERROR squidclamav_check_preview_handler: clientip is null, you must set 'icap_send_client_ip on' into squid.conf\n");
data->clientip = NULL;
}
data->body = ci_simple_file_new(0);
if ((SEND_PERCENT_BYTES >= 0) && (START_SEND_AFTER == 0)) {
ci_req_unlock_data(req);
ci_simple_file_lock_all(data->body);
}
if (!data->body)
return CI_ERROR;
if (preview_data_len) {
if (ci_simple_file_write(data->body, preview_data, preview_data_len, ci_req_hasalldata(req)) == CI_ERROR)
return CI_ERROR;
}
return CI_MOD_CONTINUE;
}
int squidclamav_read_from_net(char *buf, int len, int iseof, ci_request_t * req)
{
av_req_data_t *data = ci_service_data(req);
int allow_transfer;
if (!data)
return CI_ERROR;
if (!data->body)
return len;
if (data->no_more_scan == 1) {
return ci_simple_file_write(data->body, buf, len, iseof);
}
if ((maxsize > 0) && (data->body->bytes_in >= maxsize)) {
data->no_more_scan = 1;
ci_req_unlock_data(req);
ci_simple_file_unlock_all(data->body);
ci_debug_printf(1, "DEBUG squidclamav_read_from_net: No more antivir check, downloaded stream is upper than maxsize (%d>%d)\n", data->body->bytes_in, (int)maxsize);
} else if (SEND_PERCENT_BYTES && (START_SEND_AFTER < data->body->bytes_in)) {
ci_req_unlock_data(req);
allow_transfer = (SEND_PERCENT_BYTES * (data->body->endpos + len)) / 100;
ci_simple_file_unlock(data->body, allow_transfer);
}
return ci_simple_file_write(data->body, buf, len, iseof);
}
int squidclamav_write_to_net(char *buf, int len, ci_request_t * req)
{
int bytes;
av_req_data_t *data = ci_service_data(req);
if (!data)
return CI_ERROR;
if (data->blocked == 1 && data->error_page == 0) {
ci_debug_printf(2, "DEBUG squidclamav_write_to_net: ending here, content was blocked\n");
return CI_EOF;
}
if (data->virus == 1 && data->error_page == 0) {
ci_debug_printf(2, "DEBUG squidclamav_write_to_net: ending here, virus was found\n");
return CI_EOF;
}
/* if a virus was found or the page has been blocked, a warning page
has already been generated */
if (data->error_page)
return ci_membuf_read(data->error_page, buf, len);
if (data->body)
bytes = ci_simple_file_read(data->body, buf, len);
else
bytes =0;
return bytes;
}
int squidclamav_io(char *wbuf, int *wlen, char *rbuf, int *rlen, int iseof, ci_request_t * req)
{
int ret = CI_OK;
if (rbuf && rlen) {
*rlen = squidclamav_read_from_net(rbuf, *rlen, iseof, req);
if (*rlen == CI_ERROR)
return CI_ERROR;
else if (*rlen < 0)
ret = CI_OK;
} else if (iseof) {
if (squidclamav_read_from_net(NULL, 0, iseof, req) == CI_ERROR)
return CI_ERROR;
}
if (wbuf && wlen) {
*wlen = squidclamav_write_to_net(wbuf, *wlen, req);
}
return CI_OK;
}
int squidclamav_end_of_data_handler(ci_request_t * req)
{
av_req_data_t *data = ci_service_data(req);
ci_simple_file_t *body;
char cbuff[MAX_URL_SIZE];
char clbuf[SMALL_BUFF];
ssize_t ret;
int nbread = 0;
int loopw = 60;
uint16_t port;
struct sockaddr_in server;
struct sockaddr_in peer;
size_t peer_size;
char *pt = NULL;
int sockd;
int wsockd;
unsigned long total_read;
ci_debug_printf(2, "DEBUG squidclamav_end_of_data_handler: ending request data handler.\n");
/* Nothing more to scan */
if (!data || !data->body)
return CI_MOD_DONE;
if (data->blocked == 1) {
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: blocked content, sending redirection header + error page.\n");
return CI_MOD_DONE;
}
body = data->body;
if (data->no_more_scan == 1) {
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: no more data to scan, sending content.\n");
ci_simple_file_unlock_all(body);
return CI_MOD_DONE;
}
/* SCAN DATA HERE */
if ((sockd = dconnect ()) < 0) {
ci_debug_printf(0, "ERROR squidclamav_end_of_data_handler: Can't connect to Clamd daemon.\n");
return CI_MOD_ALLOW204;
}
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: Sending STREAM command to clamd.\n");
if (write(sockd, "STREAM", 6) <= 0) {
ci_debug_printf(0, "ERROR squidclamav_end_of_data_handler: Can't write to Clamd socket.\n");
close(sockd);
return CI_MOD_ALLOW204;
}
while (loopw > 0) {
memset (cbuff, 0, sizeof(cbuff));
ret = read (sockd, cbuff, MAX_URL_SIZE);
if ((ret > -1) && (pt = strstr (cbuff, "PORT"))) {
pt += 5;
sscanf(pt, "%d", (int *) &port);
break;
}
loopw--;
}
if (loopw == 0) {
ci_debug_printf(0, "ERROR squidclamav_end_of_data_handler: Clamd daemon not ready for stream scanning.\n");
close(sockd);
return CI_MOD_ALLOW204;
}
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: Received port %d from clamd.\n", port);
/* connect to clamd given port */
if ((wsockd = socket (AF_INET, SOCK_STREAM, 0)) < 0) {
ci_debug_printf(0, "ERROR squidclamav_end_of_data_handler: Can't create the Clamd socket.\n");
close(sockd);
return CI_MOD_ALLOW204;
}
server.sin_family = AF_INET;
server.sin_port = htons (port);
peer_size = sizeof (peer);
if (getpeername(sockd, (struct sockaddr *) &peer, (socklen_t *) &peer_size) < 0) {
ci_debug_printf(0, "ERROR squidclamav_end_of_data_handler: Can't get socket peer name.\n");
close(sockd);
return CI_MOD_ALLOW204;
}
switch (peer.sin_family) {
case AF_UNIX:
server.sin_addr.s_addr = inet_addr ("127.0.0.1");
break;
case AF_INET:
server.sin_addr.s_addr = peer.sin_addr.s_addr;
break;
default:
ci_debug_printf(0, "ERROR squidclamav_end_of_data_handler: Unexpected socket type: %d.\n", peer.sin_family);
close(sockd);
return CI_MOD_ALLOW204;
}
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: Trying to connect to clamd [port: %d].\n", port);
if (connect (wsockd, (struct sockaddr *) &server, sizeof (struct sockaddr_in)) < 0) {
close(wsockd);
ci_debug_printf(0, "ERROR squidclamav_end_of_data_handler: Can't connect to clamd [port: %d].\n", port);
return CI_MOD_ALLOW204;
}
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: Ok connected to clamd on port: %d.\n", port);
/*-----------------------------------------------------*/
ci_debug_printf(1, "DEBUG: squidclamav_end_of_data_handler: Scanning data now\n");
lseek(body->fd, 0, SEEK_SET);
memset(cbuff, 0, sizeof(cbuff));
total_read = 0;
while (data->virus == 0 && (nbread = read(body->fd, cbuff, MAX_URL_SIZE)) > 0) {
total_read += nbread;
ret = write(wsockd, cbuff, nbread);
if ( (ret <= 0) && (total_read > 0) ) {
ci_debug_printf(3, "ERROR squidclamav_end_of_data_handler: Can't write to clamd socket (maybe we reach clamd StreamMaxLength, total read: %ld).\n", total_read);
break;
} else if ( ret <= 0 ) {
ci_debug_printf(0, "ERROR squidclamav_end_of_data_handler: Can't write to clamd socket.\n");
break;
} else {
ci_debug_printf(3, "DEBUG squidclamav_end_of_data_handler: Write %d bytes on %d to socket\n", (int)ret, nbread);
}
memset(cbuff, 0, sizeof(cbuff));
}
/* close socket to clamd */
if (wsockd > -1) {
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: End Clamd connection, attempting to read result.\n");
close(wsockd);
}
memset (clbuf, 0, sizeof(clbuf));
while ((nbread = read(sockd, clbuf, SMALL_BUFF)) > 0) {
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: received from Clamd: %s", clbuf);
if (strstr (clbuf, "FOUND\n")) {
data->virus = 1;
if (!ci_req_sent_data(req)) {
chomp(clbuf);
char *urlredir = (char *) malloc( sizeof(char)*MAX_URL_SIZE );
snprintf(urlredir, MAX_URL_SIZE, "%s?url=%s&source=%s&user=%s&virus=%s", redirect_url, data->url, data->clientip, data->user, clbuf);
if (logredir == 0)
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: Virus redirection: %s.\n", urlredir);
if (logredir)
ci_debug_printf(0, "INFO squidclamav_end_of_data_handler: Virus redirection: %s.\n", urlredir);
generate_redirect_page(urlredir, req, data);
xfree(urlredir);
}
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: Virus found, ending download.\n");
break;
}
memset(clbuf, 0, sizeof(clbuf));
}
/* close second socket to clamd */
if (sockd > -1) {
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: Closing Clamd connection.\n");
close(sockd);
}
if (data->virus) {
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: Virus found, sending redirection header + error page.\n");
return CI_MOD_DONE;
}
if (!ci_req_sent_data(req)) {
ci_debug_printf(2, "DEBUG squidclamav_end_of_data_handler: Responding with allow 204\n");
return CI_MOD_ALLOW204;
}
ci_debug_printf(3, "DEBUG squidclamav_end_of_data_handler: unlocking data to be sent.\n");
ci_simple_file_unlock_all(body);
return CI_MOD_DONE;
}
void set_istag(ci_service_xdata_t * srv_xdata)
{
char istag[SERVICE_ISTAG_SIZE + 1];
snprintf(istag, SERVICE_ISTAG_SIZE, "-%d-%s-%d%d",1, "squidclamav", 1, 0);
istag[SERVICE_ISTAG_SIZE] = '\0';
ci_service_set_istag(srv_xdata, istag);
ci_debug_printf(2, "DEBUG set_istag: setting istag to %s\n", istag);
}
/* util.c */
/* NUL-terminated version of strncpy() */
void
xstrncpy (char *dest, const char *src, size_t n) {
if ( (src == NULL) || (strcmp(src, "") == 0))
return;
strncpy(dest, src, n-1);
dest[n-1] = 0;
}
/* Emulate the Perl chomp() method: remove \r and \n from end of string */
void
chomp (char *str)
{
size_t len = 0;
if (str == NULL) return;
len = strlen(str);
if ((len > 0) && str[len - 1] == 10) {
str[len - 1] = 0;
len--;
}
if ((len > 0) && str[len - 1] == 13)
str[len - 1] = 0;
return;
}
/* return 0 if path exists, -1 otherwise */
int
isPathExists(const char *path)
{
struct stat sb;
if ( (path == NULL) || (strcmp(path, "") == 0) ) return -1;
if (lstat(path, &sb) != 0) {
return -1;
}
return 0;
}
/* return 0 if path is secure, -1 otherwise */
int
isPathSecure(const char *path)
{
struct stat sb;
/* no path => unreal, that's possible ! */
if (path == NULL) return -1;
/* file doesn't exist or access denied = secure */
/* fopen will fail */
if (lstat(path, &sb) != 0) return 0;
/* File is not a regular file => unsecure */
if ( S_ISLNK(sb.st_mode ) ) return -1;
if ( S_ISDIR(sb.st_mode ) ) return -1;
if ( S_ISCHR(sb.st_mode ) ) return -1;
if ( S_ISBLK(sb.st_mode ) ) return -1;
if ( S_ISFIFO(sb.st_mode ) ) return -1;
if ( S_ISSOCK(sb.st_mode ) ) return -1;
return 0;
}
/*
* xfree() - same as free(3). Will not call free(3) if s == NULL.
*/
void
xfree(void *s)
{
if (s != NULL)
free(s);
s = NULL;
}
/* Remove spaces and tabs from beginning and end of a string */
void
trim(char *str)
{
int i = 0;
int j = 0;
/* Remove spaces and tabs from beginning */
while ( (str[i] == ' ') || (str[i] == '\t') ) {
i++;
}
if (i > 0) {
for (j = i; j < strlen(str); j++) {
str[j-i] = str[j];
}
str[j-i] = '\0';
}
/* Now remove spaces and tabs from end */
i = strlen(str) - 1;
while ( (str[i] == ' ') || (str[i] == '\t')) {
i--;
}
if ( i < (strlen(str) - 1) ) {
str[i+1] = '\0';
}
}
/* Try to emulate the Perl split() method: str is splitted on the
all occurence of delim. Take care that empty fields are not returned */
char**
split( char* str, const char* delim)
{
int size = 0;
char** splitted = NULL;
char *tmp = NULL;
tmp = strtok(str, delim);
while (tmp != NULL) {
splitted = (char**) realloc(splitted, sizeof(char**) * (size+1));
if (splitted != NULL) {
splitted[size] = tmp;
} else {
return(NULL);
}
tmp = strtok(NULL, delim);
size++;
}
free(tmp);
tmp = NULL;
/* add null at end of array to help ptrarray_length */
splitted = (char**) realloc(splitted, sizeof(char**) * (size+1));
if (splitted != NULL) {
splitted[size] = NULL;
} else {
return(NULL);
}
return splitted;
}
/* Return the length of a pointer array. Must be ended by NULL */
int
ptrarray_length(char** arr)
{
int i = 0;
while(arr[i] != NULL) i++;
return i;
}
void *
xmallox (size_t len)
{
void *memres = malloc (len);
if (memres == NULL) {
fprintf(stderr, "Running Out of Memory!!!\n");
exit(EXIT_FAILURE);
}
return memres;
}
size_t
xstrnlen(const char *s, size_t n)
{
const char *p = (const char *)memchr(s, 0, n);
return(p ? p-s : n);
}
/* pattern.c */
int
isIpAddress(char *src_addr)
{
char *ptr;
int address;
int i;
char *s = (char *) malloc (sizeof (char) * LOW_CHAR);
xstrncpy(s, src_addr, LOW_CHAR);
/* make sure we have numbers and dots only! */
if(strspn(s, "0123456789.") != strlen(s)) {
xfree(s);
return 1;
}
/* split up each number from string */
ptr = strtok(s, ".");
if(ptr == NULL) {
xfree(s);
return 1;
}
address = atoi(ptr);
if(address < 0 || address > 255) {
xfree(s);
xfree(ptr);
return 1;
}
for(i = 2; i < 4; i++) {
ptr = strtok(NULL, ".");
if (ptr == NULL) {
xfree(s);
return 1;
}
address = atoi(ptr);
if (address < 0 || address > 255) {
xfree(ptr);
xfree(s);
return 1;
}
}
xfree(s);
return 0;
}
int
simple_pattern_compare(char *str, const int type)
{
int i = 0;
/* pass througth all regex pattern */
for (i = 0; i < pattc; i++) {
if ( (patterns[i].type == type) && (regexec(&patterns[i].regexv, str, 0, 0, 0) == 0) ) {
switch(type) {
/* return 1 if string matches whitelist pattern */
case WHITELIST:
if (debug > 0)
ci_debug_printf(2, "DEBUG simple_pattern_compare: whitelist (%s) matched: %s\n", patterns[i].pattern, str);
return 1;
/* return 1 if string matches abort pattern */
case ABORT:
if (debug > 0)
ci_debug_printf(2, "DEBUG simple_pattern_compare: abort (%s) matched: %s\n", patterns[i].pattern, str);
return 1;
/* return 1 if string matches trustuser pattern */
case TRUSTUSER:
if (debug > 0)
ci_debug_printf(2, "DEBUG simple_pattern_compare: trustuser (%s) matched: %s\n", patterns[i].pattern, str);
return 1;
/* return 1 if string matches abortcontent pattern */
case ABORTCONTENT:
if (debug > 0)
ci_debug_printf(2, "DEBUG simple_pattern_compare: abortcontent (%s) matched: %s\n", patterns[i].pattern, str);
return 1;
default:
ci_debug_printf(0, "ERROR simple_pattern_compare: unknown pattern match type: %s\n", str);
return -1;
}
}
}
/* return 0 otherwise */
return 0;
}
int
client_pattern_compare(char *ip, char *name)
{
int i = 0;
/* pass througth all regex pattern */
for (i = 0; i < pattc; i++) {
if (patterns[i].type == TRUSTCLIENT) {
/* Look at client ip pattern matching */
/* return 1 if string matches ip TRUSTCLIENT pattern */
if (regexec(&patterns[i].regexv, ip, 0, 0, 0) == 0) {
if (debug != 0)
ci_debug_printf(2, "DEBUG client_pattern_compare: trustclient (%s) matched: %s\n", patterns[i].pattern, ip);
return 1;
/* Look at client name pattern matching */
/* return 2 if string matches fqdn TRUSTCLIENT pattern */
} else if ((name != NULL) && (regexec(&patterns[i].regexv, name, 0, 0, 0) == 0)) {
if (debug != 0)
ci_debug_printf(2, "DEBUG client_pattern_compare: trustclient (%s) matched: %s\n", patterns[i].pattern, name);
return 2;
}
}
}
/* return 0 otherwise */
return 0;
}
/* scconfig.c */
/* load the squidclamav.conf */
int
load_patterns()
{
char *buf = NULL;
FILE *fp = NULL;
if (isPathExists(CONFIG_FILE) == 0) {
fp = fopen(CONFIG_FILE, "rt");
if (debug > 0)
ci_debug_printf(0, "LOG load_patterns: Reading configuration from %s\n", CONFIG_FILE);
}
if (fp == NULL) {
ci_debug_printf(0, "FATAL load_patterns: unable to open configuration file: %s\n", CONFIG_FILE);
return 0;
}
buf = (char *)malloc(sizeof(char)*LOW_BUFF*2);
if (buf == NULL) {
ci_debug_printf(0, "FATAL load_patterns: unable to allocate memory in load_patterns()\n");
fclose(fp);
return 0;
}
while ((fgets(buf, LOW_BUFF, fp) != NULL)) {
/* chop newline */
chomp(buf);
/* add to regex patterns array */
if (add_pattern(buf) == 0) {
xfree(buf);
fclose(fp);
return 0;
}
}
xfree(buf);
if (redirect_url == NULL) {
ci_debug_printf(0, "FATAL load_patterns: No redirection URL set, going to BRIDGE mode\n");
return 0;
}
if (squidguard != NULL) {
ci_debug_printf(0, "LOG load_patterns: Chaining with %s\n", squidguard);
}
if (fclose(fp) != 0)
ci_debug_printf(0, "ERROR load_patterns: Can't close configuration file\n");
/* Set default values */
if (clamd_local == NULL) {
if (clamd_ip == NULL) {
clamd_ip = (char *) malloc (sizeof (char) * SMALL_CHAR);
if(clamd_ip == NULL) {
ci_debug_printf(0, "FATAL load_patterns: unable to allocate memory in load_patterns()\n");
return 0;
}
xstrncpy(clamd_ip, CLAMD_SERVER, SMALL_CHAR);
}
if (clamd_port == NULL) {
clamd_port = (char *) malloc (sizeof (char) * LOW_CHAR);
if(clamd_port == NULL) {
ci_debug_printf(0, "FATAL load_patterns: unable to allocate memory in load_patterns()\n");
return 0;
}
xstrncpy(clamd_port, CLAMD_PORT, LOW_CHAR);
}
}
return 1;
}
int
growPatternArray (SCPattern item)
{
void *_tmp = NULL;
if (pattc == current_pattern_size) {
if (current_pattern_size == 0)
current_pattern_size = PATTERN_ARR_SIZE;
else
current_pattern_size += PATTERN_ARR_SIZE;
_tmp = realloc(patterns, (current_pattern_size * sizeof(SCPattern)));
if (!_tmp) {
return(-1);
}
patterns = (SCPattern*)_tmp;
}
patterns[pattc] = item;
pattc++;
return(pattc);
}
/* Add regexp expression to patterns array */
int
add_pattern(char *s)
{
char *first = NULL;
char *type = NULL;
int stored = 0;
int regex_flags = REG_NOSUB;
SCPattern currItem;
char *end = NULL;
/* skip empty and commented lines */
if ( (xstrnlen(s, LOW_BUFF) == 0) || (strncmp(s, "#", 1) == 0)) return 1;
/* Config file directives are construct as follow: name value */
type = (char *)malloc(sizeof(char)*LOW_CHAR);
first = (char *)malloc(sizeof(char)*LOW_BUFF);
stored = sscanf(s, "%31s %255[^#]", type, first);
if (stored < 2) {
ci_debug_printf(0, "FATAL add_patterns: Bad configuration line for [%s]\n", s);
xfree(type);
xfree(first);
return 0;
}
/* remove extra space or tabulation */
trim(first);
/* URl to redirect Squid on virus found */
if(strcmp(type, "redirect") == 0) {
redirect_url = (char *) malloc (sizeof (char) * LOW_BUFF);
if(redirect_url == NULL) {
fprintf(stderr, "unable to allocate memory in add_to_patterns()\n");
xfree(type);
xfree(first);
return 0;
} else {
xstrncpy(redirect_url, first, LOW_BUFF);
}
xfree(type);
xfree(first);
return 1;
}
/* Path to chained other Squid redirector, mostly SquidGuard */
if(strcmp(type, "squidguard") == 0) {
squidguard = (char *) malloc (sizeof (char) * LOW_BUFF);
if(squidguard == NULL) {
fprintf(stderr, "unable to allocate memory in add_to_patterns()\n");
xfree(type);
xfree(first);
return 0;
} else {
if (isPathExists(first) == 0) {
xstrncpy(squidguard, first, LOW_BUFF);
} else {
ci_debug_printf(0, "LOG add_patterns: Wrong path to SquidGuard, disabling.\n");
squidguard = NULL;
}
}
xfree(type);
xfree(first);
return 1;
}
if(strcmp(type, "debug") == 0) {
if (debug == 0)
debug = atoi(first);
xfree(type);
xfree(first);
return 1;
}
if(strcmp(type, "logredir") == 0) {
if (logredir == 0)
logredir = atoi(first);
xfree(type);
xfree(first);
return 1;
}
if(strcmp(type, "dnslookup") == 0) {
if (dnslookup == 1)
dnslookup = atoi(first);
xfree(type);
xfree(first);
return 1;
}
if(strcmp(type, "timeout") == 0) {
timeout = atoi(first);
if (timeout > 10)
timeout = 10;
xfree(type);
xfree(first);
return 1;
}
if(strcmp(type, "stat") == 0) {
statit = atoi(first);
xfree(type);
xfree(first);
return 1;
}
if(strcmp(type, "clamd_ip") == 0) {
clamd_ip = (char *) malloc (sizeof (char) * SMALL_CHAR);
if (clamd_ip == NULL) {
fprintf(stderr, "unable to allocate memory in add_to_patterns()\n");
xfree(type);
xfree(first);
return 0;
} else {
xstrncpy(clamd_ip, first, SMALL_CHAR);
}
xfree(type);
xfree(first);
return 1;
}
if(strcmp(type, "clamd_port") == 0) {
clamd_port = (char *) malloc (sizeof (char) * LOW_CHAR);
if(clamd_port == NULL) {
fprintf(stderr, "unable to allocate memory in add_to_patterns()\n");
xfree(type);
xfree(first);
return 0;
} else {
xstrncpy(clamd_port, first, LOW_CHAR);
}
xfree(type);
xfree(first);
return 1;
}
if(strcmp(type, "clamd_local") == 0) {
clamd_local = (char *) malloc (sizeof (char) * LOW_BUFF);
if(clamd_local == NULL) {
fprintf(stderr, "unable to allocate memory in add_to_patterns()\n");
xfree(type);
xfree(first);
return 0;
} else {
xstrncpy(clamd_local, first, LOW_BUFF);
}
xfree(type);
xfree(first);
return 1;
}
if (strcmp(type, "maxsize") == 0) {
maxsize = ci_strto_off_t(first, &end, 10);
if ((maxsize == 0 && errno != 0) || maxsize < 0)
maxsize = 0;
if (*end == 'k' || *end == 'K')
maxsize = maxsize * 1024;
else if (*end == 'm' || *end == 'M')
maxsize = maxsize * 1024 * 1024;
else if (*end == 'g' || *end == 'G')
maxsize = maxsize * 1024 * 1024 * 1024;
xfree(type);
xfree(first);
return 1;
}
/* force case insensitive pattern matching */
/* so aborti, contenti, regexi are now obsolete */
regex_flags |= REG_ICASE;
/* Add extended regex search */
regex_flags |= REG_EXTENDED;
/* Fill the pattern type */
if (strcmp(type, "abort") == 0) {
currItem.type = ABORT;
} else if (strcmp(type, "abortcontent") == 0) {
currItem.type = ABORTCONTENT;
} else if(strcmp(type, "whitelist") == 0) {
currItem.type = WHITELIST;
} else if(strcmp(type, "trustuser") == 0) {
currItem.type = TRUSTUSER;
} else if(strcmp(type, "trustclient") == 0) {
currItem.type = TRUSTCLIENT;
} else if ( (strcmp(type, "squid_ip") != 0) && (strcmp(type, "squid_port") != 0) && (strcmp(type, "maxredir") != 0) && (strcmp(type, "useragent") != 0) && (strcmp(type, "trust_cache") != 0) ) {
fprintf(stderr, "WARNING: Bad configuration keyword: %s\n", s);
xfree(type);
xfree(first);
return 1;
}
/* Fill the pattern flag */
currItem.flag = regex_flags;
/* Fill pattern array */
currItem.pattern = malloc(sizeof(char)*(strlen(first)+1));
if (currItem.pattern == NULL) {
fprintf(stderr, "unable to allocate new pattern in add_to_patterns()\n");
xfree(type);
xfree(first);
return 0;
}
strncpy(currItem.pattern, first, strlen(first) + 1);
if ((stored = regcomp(&currItem.regexv, currItem.pattern, currItem.flag)) != 0) {
ci_debug_printf(0, "ERROR add_pattern: Invalid regex pattern: %s\n", currItem.pattern);
} else {
if (growPatternArray(currItem) < 0) {
fprintf(stderr, "unable to allocate new pattern in add_to_patterns()\n");
xfree(type);
xfree(first);
return 0;
}
}
xfree(type);
xfree(first);
return 1;
}
int extract_http_info(ci_request_t * req, ci_headers_list_t * req_header,
struct http_info *httpinf)
{
char *str;
int i = 0;
/* Format of the HTTP header we want to parse:
GET http://www.squid-cache.org/Doc/config/icap_service HTTP/1.1
*/
httpinf->url[0]='\0';
httpinf->method[0] = '\0';
str = req_header->headers[0];
/* if we can't find a space character, there's somethings wrong */
if (strchr(str, ' ') == NULL) {
return 0;
}
/* extract the HTTP method */
while (*str != ' ' && i < MAX_METHOD_SIZE) {
httpinf->method[i] = *str;
str++;
i++;
}
httpinf->method[i] = '\0';
ci_debug_printf(3, "DEBUG extract_http_info: method %s\n", httpinf->method);
/* Extract the URL part of the header */
while (*str == ' ') str++;
i = 0;
while (*str != ' ' && i < MAX_URL_SIZE) {
httpinf->url[i] = *str;
i++;
str++;
}
httpinf->url[i] = '\0';
ci_debug_printf(3, "DEBUG extract_http_info: url %s\n", httpinf->url);
if (*str != ' ') {
return 0;
}
/* we must find the HTTP version after all */
while (*str == ' ')
str++;
if (*str != 'H' || *(str + 4) != '/') {
return 0;
}
return 1;
}
char *http_content_type(ci_request_t * req)
{
ci_headers_list_t *heads;
char *val;
if (!(heads = ci_http_response_headers(req))) {
/* Then maybe is a reqmod request, try to get request headers */
if (!(heads = ci_http_request_headers(req)))
return NULL;
}
if (!(val = ci_headers_value(heads, "Content-Type")))
return NULL;
return val;
}
void
free_global ()
{
xfree(clamd_local);
xfree(clamd_ip);
xfree(clamd_port);
xfree(clamd_curr_ip);
xfree(redirect_url);
if (patterns != NULL) {
while (pattc > 0) {
pattc--;
regfree(&patterns[pattc].regexv);
xfree(patterns[pattc].pattern);
}
free(patterns);
patterns = NULL;
}
}
void
free_pipe ()
{
xfree(squidguard);
if (sgfpw) fclose(sgfpw);
if (sgfpr) fclose(sgfpr);
}
static const char *blocked_header_message =
"<html>\n"
"<body>\n"
"<p>\n"
"You will be redirected in few seconds, if not use this <a href=\"";
static const char *blocked_footer_message =
"\">direct link</a>.\n"
"</p>\n"
"</body>\n"
"</html>\n";
void generate_redirect_page(char * redirect, ci_request_t * req, av_req_data_t * data)
{
int new_size = 0;
char buf[MAX_URL_SIZE];
ci_membuf_t *error_page;
new_size = strlen(blocked_header_message) + strlen(redirect) + strlen(blocked_footer_message) + 10;
if ( ci_http_response_headers(req))
ci_http_response_reset_headers(req);
else
ci_http_response_create(req, 1, 1);
ci_debug_printf(2, "DEBUG generate_redirect_page: creating redirection page\n");
snprintf(buf, MAX_URL_SIZE, "Location: %s", redirect);
/*strcat(buf, ";");*/
ci_debug_printf(3, "DEBUG generate_redirect_page: %s\n", buf);
ci_http_response_add_header(req, "HTTP/1.0 301 Moved Permanently");
ci_http_response_add_header(req, buf);
ci_http_response_add_header(req, "Server: C-ICAP");
ci_http_response_add_header(req, "Connection: close");
/*ci_http_response_add_header(req, "Content-Type: text/html;");*/
ci_http_response_add_header(req, "Content-Type: text/html");
ci_http_response_add_header(req, "Content-Language: en");
if (data->blocked == 1) {
error_page = ci_membuf_new_sized(new_size);
((av_req_data_t *) data)->error_page = error_page;
ci_membuf_write(error_page, (char *) blocked_header_message, strlen(blocked_header_message), 0);
ci_membuf_write(error_page, (char *) redirect, strlen(redirect), 0);
ci_membuf_write(error_page, (char *) blocked_footer_message, strlen(blocked_footer_message), 1);
}
ci_debug_printf(3, "DEBUG generate_redirect_page: done\n");
}
int create_pipe(char *command)
{
int pipe1[2];
int pipe2[2];
ci_debug_printf(1, "DEBUG create_pipe: Open pipe to squidGuard %s!\n", command);
if (command != NULL) {
if ( pipe(pipe1) < 0 || pipe(pipe2) < 0 ) {
ci_debug_printf(0, "ERROR create_pipe: unable to open pipe, disabling call to %s.\n", command);
perror("pipe");
usepipe = 0;
} else {
if ( (pid = fork()) == -1) {
ci_debug_printf(0, "ERROR create_pipe: unable to fork, disabling call to %s.\n", command);
usepipe = 0;
} else {
if(pid == 0) {
close(pipe1[1]);
dup2(pipe1[0],0);
close(pipe2[0]);
dup2(pipe2[1],1);
setsid();
/* Running chained program */
execlp(command,(char *)basename(command),(char *)0);
exit(EXIT_SUCCESS);
return(0);
} else {
close(pipe1[0]);
sgfpw = fdopen(pipe1[1], "w");
if (!sgfpw) {
ci_debug_printf(0, "ERROR create_pipe: unable to fopen command's child stdin, disabling it.\n");
usepipe = 0;
} else {
/* make pipe line buffered */
if (setvbuf (sgfpw, (char *)NULL, _IOLBF, 0) != 0)
ci_debug_printf(1, "DEBUG create_pipe: unable to line buffering pipe.\n");
sgfpr = fdopen(pipe2[0], "r");
if(!sgfpr) {
ci_debug_printf(0, "ERROR create_pipe: unable to fopen command's child stdout, disabling it.\n");
usepipe = 0;
} else {
ci_debug_printf(1, "DEBUG create_pipe: bidirectional pipe to %s childs ready...\n", command);
usepipe = 1;
}
}
}
}
}
}
return 1;
}
int
dconnect ()
{
struct sockaddr_un userver;
int asockd;
memset ((char *) &userver, 0, sizeof (userver));
ci_debug_printf(1, "dconnect: entering.\n");
if (clamd_local != NULL) {
userver.sun_family = AF_UNIX;
xstrncpy (userver.sun_path, clamd_local, sizeof(userver.sun_path));
if ((asockd = socket (AF_UNIX, SOCK_STREAM, 0)) < 0) {
ci_debug_printf(0, "ERROR dconnect: Can't bind local socket on %s.\n", clamd_local);
return -1;
}
if (connect (asockd, (struct sockaddr *) &userver, sizeof (struct sockaddr_un)) < 0) {
close (asockd);
ci_debug_printf(0, "ERROR dconnect: Can't connect to clamd on local socket %s.\n", clamd_local);
return -1;
}
return asockd;
} else {
if (clamd_curr_ip[0] != 0) {
asockd = connectINET(clamd_curr_ip, atoi(clamd_port));
if ( asockd != -1 ) {
ci_debug_printf(1, "DEBUG dconnect: Connected to Clamd (%s:%s)\n", clamd_curr_ip,clamd_port);
return asockd;
}
}
char *ptr;
char *s = (char *) malloc (sizeof (char) * SMALL_CHAR);
xstrncpy(s, clamd_ip, SMALL_CHAR);
ptr = strtok(s, ",");
while (ptr != NULL) {
asockd = connectINET(ptr, atoi(clamd_port));
if ( asockd != -1 ) {
ci_debug_printf(1, "DEBUG dconnect: Connected to Clamd (%s:%s)\n", ptr,clamd_port);
/* Store last working clamd */
xstrncpy(clamd_curr_ip, ptr, LOW_CHAR);
xfree(s);
break;
}
ptr = strtok(NULL, ",");
}
return asockd;
xfree(s);
}
return 0;
}
void connect_timeout() {
// doesn't actually need to do anything
}
int
connectINET(char *serverHost, uint16_t serverPort)
{
struct sockaddr_in server;
struct hostent *he;
int asockd;
struct sigaction action;
action.sa_handler = connect_timeout;
memset ((char *) &server, 0, sizeof (server));
server.sin_addr.s_addr = inet_addr(serverHost);
if ((asockd = socket (AF_INET, SOCK_STREAM, 0)) < 0) {
ci_debug_printf(0, "ERROR connectINET: Can't create a socket.\n");
return -1;
}
server.sin_family = AF_INET;
server.sin_port = htons(serverPort);
if ((he = gethostbyname(serverHost)) == 0)
{
close(asockd);
ci_debug_printf(0, "ERROR connectINET: Can't lookup hostname of %s\n", serverHost);
return -1;
}
server.sin_addr = *(struct in_addr *) he->h_addr_list[0];
sigaction(SIGALRM, &action, NULL);
alarm(timeout);
if (connect (asockd, (struct sockaddr *) &server, sizeof (struct sockaddr_in)) < 0) {
close (asockd);
ci_debug_printf(0, "ERROR connectINET: Can't connect on %s:%d.\n", serverHost,serverPort);
return -1;
}
int err = errno;
alarm(0);
if (err == EINTR) {
close(asockd);
ci_debug_printf(0, "ERROR connectINET: Timeout connecting to clamd on %s:%d.\n", serverHost,serverPort);
}
return asockd;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3716_0 |
crossvul-cpp_data_good_5795_5 | /*
* $Id: json_tokener.c,v 1.20 2006/07/25 03:24:50 mclark Exp $
*
* Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
* Michael Clark <michael@metaparadigm.com>
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See COPYING for details.
*
*
* Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved.
* The copyrights to the contents of this file are licensed under the MIT License
* (http://www.opensource.org/licenses/mit-license.php)
*/
#include "config.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <ctype.h>
#include <string.h>
#include <limits.h>
#include "bits.h"
#include "debug.h"
#include "printbuf.h"
#include "arraylist.h"
#include "json_inttypes.h"
#include "json_object.h"
#include "json_tokener.h"
#include "json_util.h"
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif /* HAVE_LOCALE_H */
#if !HAVE_STRDUP && defined(_MSC_VER)
/* MSC has the version as _strdup */
# define strdup _strdup
#elif !HAVE_STRDUP
# error You do not have strdup on your system.
#endif /* HAVE_STRDUP */
#if !HAVE_STRNCASECMP && defined(_MSC_VER)
/* MSC has the version as _strnicmp */
# define strncasecmp _strnicmp
#elif !HAVE_STRNCASECMP
# error You do not have strncasecmp on your system.
#endif /* HAVE_STRNCASECMP */
/* Use C99 NAN by default; if not available, nan("") should work too. */
#ifndef NAN
#define NAN nan("")
#endif /* !NAN */
static const char json_null_str[] = "null";
static const int json_null_str_len = sizeof(json_null_str) - 1;
static const char json_inf_str[] = "Infinity";
static const int json_inf_str_len = sizeof(json_inf_str) - 1;
static const char json_nan_str[] = "NaN";
static const int json_nan_str_len = sizeof(json_nan_str) - 1;
static const char json_true_str[] = "true";
static const int json_true_str_len = sizeof(json_true_str) - 1;
static const char json_false_str[] = "false";
static const int json_false_str_len = sizeof(json_false_str) - 1;
static const char* json_tokener_errors[] = {
"success",
"continue",
"nesting too deep",
"unexpected end of data",
"unexpected character",
"null expected",
"boolean expected",
"number expected",
"array value separator ',' expected",
"quoted object property name expected",
"object property name separator ':' expected",
"object value separator ',' expected",
"invalid string sequence",
"expected comment",
"buffer size overflow"
};
const char *json_tokener_error_desc(enum json_tokener_error jerr)
{
int jerr_int = (int)jerr;
if (jerr_int < 0 || jerr_int >= (int)(sizeof(json_tokener_errors) / sizeof(json_tokener_errors[0])))
return "Unknown error, invalid json_tokener_error value passed to json_tokener_error_desc()";
return json_tokener_errors[jerr];
}
enum json_tokener_error json_tokener_get_error(json_tokener *tok)
{
return tok->err;
}
/* Stuff for decoding unicode sequences */
#define IS_HIGH_SURROGATE(uc) (((uc) & 0xFC00) == 0xD800)
#define IS_LOW_SURROGATE(uc) (((uc) & 0xFC00) == 0xDC00)
#define DECODE_SURROGATE_PAIR(hi,lo) ((((hi) & 0x3FF) << 10) + ((lo) & 0x3FF) + 0x10000)
static unsigned char utf8_replacement_char[3] = { 0xEF, 0xBF, 0xBD };
struct json_tokener* json_tokener_new_ex(int depth)
{
struct json_tokener *tok;
tok = (struct json_tokener*)calloc(1, sizeof(struct json_tokener));
if (!tok) return NULL;
tok->stack = (struct json_tokener_srec *)calloc(depth, sizeof(struct json_tokener_srec));
if (!tok->stack) {
free(tok);
return NULL;
}
tok->pb = printbuf_new();
tok->max_depth = depth;
json_tokener_reset(tok);
return tok;
}
struct json_tokener* json_tokener_new(void)
{
return json_tokener_new_ex(JSON_TOKENER_DEFAULT_DEPTH);
}
void json_tokener_free(struct json_tokener *tok)
{
json_tokener_reset(tok);
if (tok->pb) printbuf_free(tok->pb);
if (tok->stack) free(tok->stack);
free(tok);
}
static void json_tokener_reset_level(struct json_tokener *tok, int depth)
{
tok->stack[depth].state = json_tokener_state_eatws;
tok->stack[depth].saved_state = json_tokener_state_start;
json_object_put(tok->stack[depth].current);
tok->stack[depth].current = NULL;
free(tok->stack[depth].obj_field_name);
tok->stack[depth].obj_field_name = NULL;
}
void json_tokener_reset(struct json_tokener *tok)
{
int i;
if (!tok)
return;
for(i = tok->depth; i >= 0; i--)
json_tokener_reset_level(tok, i);
tok->depth = 0;
tok->err = json_tokener_success;
}
struct json_object* json_tokener_parse(const char *str)
{
enum json_tokener_error jerr_ignored;
struct json_object* obj;
obj = json_tokener_parse_verbose(str, &jerr_ignored);
return obj;
}
struct json_object* json_tokener_parse_verbose(const char *str, enum json_tokener_error *error)
{
struct json_tokener* tok;
struct json_object* obj;
tok = json_tokener_new();
if (!tok)
return NULL;
obj = json_tokener_parse_ex(tok, str, -1);
*error = tok->err;
if(tok->err != json_tokener_success) {
if (obj != NULL)
json_object_put(obj);
obj = NULL;
}
json_tokener_free(tok);
return obj;
}
#define state tok->stack[tok->depth].state
#define saved_state tok->stack[tok->depth].saved_state
#define current tok->stack[tok->depth].current
#define obj_field_name tok->stack[tok->depth].obj_field_name
/* Optimization:
* json_tokener_parse_ex() consumed a lot of CPU in its main loop,
* iterating character-by character. A large performance boost is
* achieved by using tighter loops to locally handle units such as
* comments and strings. Loops that handle an entire token within
* their scope also gather entire strings and pass them to
* printbuf_memappend() in a single call, rather than calling
* printbuf_memappend() one char at a time.
*
* PEEK_CHAR() and ADVANCE_CHAR() macros are used for code that is
* common to both the main loop and the tighter loops.
*/
/* PEEK_CHAR(dest, tok) macro:
* Peeks at the current char and stores it in dest.
* Returns 1 on success, sets tok->err and returns 0 if no more chars.
* Implicit inputs: str, len vars
*/
#define PEEK_CHAR(dest, tok) \
(((tok)->char_offset == len) ? \
(((tok)->depth == 0 && state == json_tokener_state_eatws && saved_state == json_tokener_state_finish) ? \
(((tok)->err = json_tokener_success), 0) \
: \
(((tok)->err = json_tokener_continue), 0) \
) : \
(((dest) = *str), 1) \
)
/* ADVANCE_CHAR() macro:
* Incrementes str & tok->char_offset.
* For convenience of existing conditionals, returns the old value of c (0 on eof)
* Implicit inputs: c var
*/
#define ADVANCE_CHAR(str, tok) \
( ++(str), ((tok)->char_offset)++, c)
/* End optimization macro defs */
struct json_object* json_tokener_parse_ex(struct json_tokener *tok,
const char *str, int len)
{
struct json_object *obj = NULL;
char c = '\1';
#ifdef HAVE_SETLOCALE
char *oldlocale=NULL, *tmplocale;
tmplocale = setlocale(LC_NUMERIC, NULL);
if (tmplocale) oldlocale = strdup(tmplocale);
setlocale(LC_NUMERIC, "C");
#endif
tok->char_offset = 0;
tok->err = json_tokener_success;
/* this interface is presently not 64-bit clean due to the int len argument
and the internal printbuf interface that takes 32-bit int len arguments
so the function limits the maximum string size to INT32_MAX (2GB).
If the function is called with len == -1 then strlen is called to check
the string length is less than INT32_MAX (2GB) */
if ((len < -1) || (len == -1 && strlen(str) > INT32_MAX)) {
tok->err = json_tokener_error_size;
return NULL;
}
while (PEEK_CHAR(c, tok)) {
redo_char:
switch(state) {
case json_tokener_state_eatws:
/* Advance until we change state */
while (isspace((int)c)) {
if ((!ADVANCE_CHAR(str, tok)) || (!PEEK_CHAR(c, tok)))
goto out;
}
if(c == '/' && !(tok->flags & JSON_TOKENER_STRICT)) {
printbuf_reset(tok->pb);
printbuf_memappend_fast(tok->pb, &c, 1);
state = json_tokener_state_comment_start;
} else {
state = saved_state;
goto redo_char;
}
break;
case json_tokener_state_start:
switch(c) {
case '{':
state = json_tokener_state_eatws;
saved_state = json_tokener_state_object_field_start;
current = json_object_new_object();
break;
case '[':
state = json_tokener_state_eatws;
saved_state = json_tokener_state_array;
current = json_object_new_array();
break;
case 'I':
case 'i':
state = json_tokener_state_inf;
printbuf_reset(tok->pb);
tok->st_pos = 0;
goto redo_char;
case 'N':
case 'n':
state = json_tokener_state_null; // or NaN
printbuf_reset(tok->pb);
tok->st_pos = 0;
goto redo_char;
case '\'':
if (tok->flags & JSON_TOKENER_STRICT) {
/* in STRICT mode only double-quote are allowed */
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
case '"':
state = json_tokener_state_string;
printbuf_reset(tok->pb);
tok->quote_char = c;
break;
case 'T':
case 't':
case 'F':
case 'f':
state = json_tokener_state_boolean;
printbuf_reset(tok->pb);
tok->st_pos = 0;
goto redo_char;
#if defined(__GNUC__)
case '0' ... '9':
#else
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
#endif
case '-':
state = json_tokener_state_number;
printbuf_reset(tok->pb);
tok->is_double = 0;
goto redo_char;
default:
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
break;
case json_tokener_state_finish:
if(tok->depth == 0) goto out;
obj = json_object_get(current);
json_tokener_reset_level(tok, tok->depth);
tok->depth--;
goto redo_char;
case json_tokener_state_inf: /* aka starts with 'i' */
{
int size;
int size_inf;
int is_negative = 0;
printbuf_memappend_fast(tok->pb, &c, 1);
size = json_min(tok->st_pos+1, json_null_str_len);
size_inf = json_min(tok->st_pos+1, json_inf_str_len);
char *infbuf = tok->pb->buf;
if (*infbuf == '-')
{
infbuf++;
is_negative = 1;
}
if ((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_inf_str, infbuf, size_inf) == 0) ||
(strncmp(json_inf_str, infbuf, size_inf) == 0)
)
{
if (tok->st_pos == json_inf_str_len)
{
current = json_object_new_double(is_negative ? -INFINITY : INFINITY);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else {
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
tok->st_pos++;
}
break;
case json_tokener_state_null: /* aka starts with 'n' */
{
int size;
int size_nan;
printbuf_memappend_fast(tok->pb, &c, 1);
size = json_min(tok->st_pos+1, json_null_str_len);
size_nan = json_min(tok->st_pos+1, json_nan_str_len);
if((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_null_str, tok->pb->buf, size) == 0)
|| (strncmp(json_null_str, tok->pb->buf, size) == 0)
) {
if (tok->st_pos == json_null_str_len) {
current = NULL;
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
}
else if ((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_nan_str, tok->pb->buf, size_nan) == 0) ||
(strncmp(json_nan_str, tok->pb->buf, size_nan) == 0)
)
{
if (tok->st_pos == json_nan_str_len)
{
current = json_object_new_double(NAN);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else {
tok->err = json_tokener_error_parse_null;
goto out;
}
tok->st_pos++;
}
break;
case json_tokener_state_comment_start:
if(c == '*') {
state = json_tokener_state_comment;
} else if(c == '/') {
state = json_tokener_state_comment_eol;
} else {
tok->err = json_tokener_error_parse_comment;
goto out;
}
printbuf_memappend_fast(tok->pb, &c, 1);
break;
case json_tokener_state_comment:
{
/* Advance until we change state */
const char *case_start = str;
while(c != '*') {
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
printbuf_memappend_fast(tok->pb, case_start, 1+str-case_start);
state = json_tokener_state_comment_end;
}
break;
case json_tokener_state_comment_eol:
{
/* Advance until we change state */
const char *case_start = str;
while(c != '\n') {
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
MC_DEBUG("json_tokener_comment: %s\n", tok->pb->buf);
state = json_tokener_state_eatws;
}
break;
case json_tokener_state_comment_end:
printbuf_memappend_fast(tok->pb, &c, 1);
if(c == '/') {
MC_DEBUG("json_tokener_comment: %s\n", tok->pb->buf);
state = json_tokener_state_eatws;
} else {
state = json_tokener_state_comment;
}
break;
case json_tokener_state_string:
{
/* Advance until we change state */
const char *case_start = str;
while(1) {
if(c == tok->quote_char) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
current = json_object_new_string_len(tok->pb->buf, tok->pb->bpos);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
break;
} else if(c == '\\') {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
saved_state = json_tokener_state_string;
state = json_tokener_state_string_escape;
break;
}
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
}
break;
case json_tokener_state_string_escape:
switch(c) {
case '"':
case '\\':
case '/':
printbuf_memappend_fast(tok->pb, &c, 1);
state = saved_state;
break;
case 'b':
case 'n':
case 'r':
case 't':
case 'f':
if(c == 'b') printbuf_memappend_fast(tok->pb, "\b", 1);
else if(c == 'n') printbuf_memappend_fast(tok->pb, "\n", 1);
else if(c == 'r') printbuf_memappend_fast(tok->pb, "\r", 1);
else if(c == 't') printbuf_memappend_fast(tok->pb, "\t", 1);
else if(c == 'f') printbuf_memappend_fast(tok->pb, "\f", 1);
state = saved_state;
break;
case 'u':
tok->ucs_char = 0;
tok->st_pos = 0;
state = json_tokener_state_escape_unicode;
break;
default:
tok->err = json_tokener_error_parse_string;
goto out;
}
break;
case json_tokener_state_escape_unicode:
{
unsigned int got_hi_surrogate = 0;
/* Handle a 4-byte sequence, or two sequences if a surrogate pair */
while(1) {
if(strchr(json_hex_chars, c)) {
tok->ucs_char += ((unsigned int)hexdigit(c) << ((3-tok->st_pos++)*4));
if(tok->st_pos == 4) {
unsigned char unescaped_utf[4];
if (got_hi_surrogate) {
if (IS_LOW_SURROGATE(tok->ucs_char)) {
/* Recalculate the ucs_char, then fall thru to process normally */
tok->ucs_char = DECODE_SURROGATE_PAIR(got_hi_surrogate, tok->ucs_char);
} else {
/* Hi surrogate was not followed by a low surrogate */
/* Replace the hi and process the rest normally */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
got_hi_surrogate = 0;
}
if (tok->ucs_char < 0x80) {
unescaped_utf[0] = tok->ucs_char;
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 1);
} else if (tok->ucs_char < 0x800) {
unescaped_utf[0] = 0xc0 | (tok->ucs_char >> 6);
unescaped_utf[1] = 0x80 | (tok->ucs_char & 0x3f);
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 2);
} else if (IS_HIGH_SURROGATE(tok->ucs_char)) {
/* Got a high surrogate. Remember it and look for the
* the beginning of another sequence, which should be the
* low surrogate.
*/
got_hi_surrogate = tok->ucs_char;
/* Not at end, and the next two chars should be "\u" */
if ((tok->char_offset+1 != len) &&
(tok->char_offset+2 != len) &&
(str[1] == '\\') &&
(str[2] == 'u'))
{
/* Advance through the 16 bit surrogate, and move on to the
* next sequence. The next step is to process the following
* characters.
*/
if( !ADVANCE_CHAR(str, tok) || !ADVANCE_CHAR(str, tok) ) {
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
/* Advance to the first char of the next sequence and
* continue processing with the next sequence.
*/
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
goto out;
}
tok->ucs_char = 0;
tok->st_pos = 0;
continue; /* other json_tokener_state_escape_unicode */
} else {
/* Got a high surrogate without another sequence following
* it. Put a replacement char in for the hi surrogate
* and pretend we finished.
*/
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
} else if (IS_LOW_SURROGATE(tok->ucs_char)) {
/* Got a low surrogate not preceded by a high */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
} else if (tok->ucs_char < 0x10000) {
unescaped_utf[0] = 0xe0 | (tok->ucs_char >> 12);
unescaped_utf[1] = 0x80 | ((tok->ucs_char >> 6) & 0x3f);
unescaped_utf[2] = 0x80 | (tok->ucs_char & 0x3f);
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 3);
} else if (tok->ucs_char < 0x110000) {
unescaped_utf[0] = 0xf0 | ((tok->ucs_char >> 18) & 0x07);
unescaped_utf[1] = 0x80 | ((tok->ucs_char >> 12) & 0x3f);
unescaped_utf[2] = 0x80 | ((tok->ucs_char >> 6) & 0x3f);
unescaped_utf[3] = 0x80 | (tok->ucs_char & 0x3f);
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 4);
} else {
/* Don't know what we got--insert the replacement char */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
state = saved_state;
break;
}
} else {
tok->err = json_tokener_error_parse_string;
goto out;
}
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
if (got_hi_surrogate) /* Clean up any pending chars */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
goto out;
}
}
}
break;
case json_tokener_state_boolean:
{
int size1, size2;
printbuf_memappend_fast(tok->pb, &c, 1);
size1 = json_min(tok->st_pos+1, json_true_str_len);
size2 = json_min(tok->st_pos+1, json_false_str_len);
if((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_true_str, tok->pb->buf, size1) == 0)
|| (strncmp(json_true_str, tok->pb->buf, size1) == 0)
) {
if(tok->st_pos == json_true_str_len) {
current = json_object_new_boolean(1);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else if((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_false_str, tok->pb->buf, size2) == 0)
|| (strncmp(json_false_str, tok->pb->buf, size2) == 0)) {
if(tok->st_pos == json_false_str_len) {
current = json_object_new_boolean(0);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else {
tok->err = json_tokener_error_parse_boolean;
goto out;
}
tok->st_pos++;
}
break;
case json_tokener_state_number:
{
/* Advance until we change state */
const char *case_start = str;
int case_len=0;
while(c && strchr(json_number_chars, c)) {
++case_len;
if(c == '.' || c == 'e' || c == 'E')
tok->is_double = 1;
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, case_len);
goto out;
}
}
if (case_len>0)
printbuf_memappend_fast(tok->pb, case_start, case_len);
// Check for -Infinity
if (tok->pb->buf[0] == '-' && case_len == 1 &&
(c == 'i' || c == 'I'))
{
state = json_tokener_state_inf;
goto redo_char;
}
}
{
int64_t num64;
double numd;
if (!tok->is_double && json_parse_int64(tok->pb->buf, &num64) == 0) {
if (num64 && tok->pb->buf[0]=='0' && (tok->flags & JSON_TOKENER_STRICT)) {
/* in strict mode, number must not start with 0 */
tok->err = json_tokener_error_parse_number;
goto out;
}
current = json_object_new_int64(num64);
}
else if(tok->is_double && json_parse_double(tok->pb->buf, &numd) == 0)
{
current = json_object_new_double_s(numd, tok->pb->buf);
} else {
tok->err = json_tokener_error_parse_number;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
break;
case json_tokener_state_array_after_sep:
case json_tokener_state_array:
if(c == ']') {
if (state == json_tokener_state_array_after_sep &&
(tok->flags & JSON_TOKENER_STRICT))
{
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else {
if(tok->depth >= tok->max_depth-1) {
tok->err = json_tokener_error_depth;
goto out;
}
state = json_tokener_state_array_add;
tok->depth++;
json_tokener_reset_level(tok, tok->depth);
goto redo_char;
}
break;
case json_tokener_state_array_add:
json_object_array_add(current, obj);
saved_state = json_tokener_state_array_sep;
state = json_tokener_state_eatws;
goto redo_char;
case json_tokener_state_array_sep:
if(c == ']') {
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else if(c == ',') {
saved_state = json_tokener_state_array_after_sep;
state = json_tokener_state_eatws;
} else {
tok->err = json_tokener_error_parse_array;
goto out;
}
break;
case json_tokener_state_object_field_start:
case json_tokener_state_object_field_start_after_sep:
if(c == '}') {
if (state == json_tokener_state_object_field_start_after_sep &&
(tok->flags & JSON_TOKENER_STRICT))
{
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else if (c == '"' || c == '\'') {
tok->quote_char = c;
printbuf_reset(tok->pb);
state = json_tokener_state_object_field;
} else {
tok->err = json_tokener_error_parse_object_key_name;
goto out;
}
break;
case json_tokener_state_object_field:
{
/* Advance until we change state */
const char *case_start = str;
while(1) {
if(c == tok->quote_char) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
obj_field_name = strdup(tok->pb->buf);
saved_state = json_tokener_state_object_field_end;
state = json_tokener_state_eatws;
break;
} else if(c == '\\') {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
saved_state = json_tokener_state_object_field;
state = json_tokener_state_string_escape;
break;
}
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
}
break;
case json_tokener_state_object_field_end:
if(c == ':') {
saved_state = json_tokener_state_object_value;
state = json_tokener_state_eatws;
} else {
tok->err = json_tokener_error_parse_object_key_sep;
goto out;
}
break;
case json_tokener_state_object_value:
if(tok->depth >= tok->max_depth-1) {
tok->err = json_tokener_error_depth;
goto out;
}
state = json_tokener_state_object_value_add;
tok->depth++;
json_tokener_reset_level(tok, tok->depth);
goto redo_char;
case json_tokener_state_object_value_add:
json_object_object_add(current, obj_field_name, obj);
free(obj_field_name);
obj_field_name = NULL;
saved_state = json_tokener_state_object_sep;
state = json_tokener_state_eatws;
goto redo_char;
case json_tokener_state_object_sep:
if(c == '}') {
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else if(c == ',') {
saved_state = json_tokener_state_object_field_start_after_sep;
state = json_tokener_state_eatws;
} else {
tok->err = json_tokener_error_parse_object_value_sep;
goto out;
}
break;
}
if (!ADVANCE_CHAR(str, tok))
goto out;
} /* while(POP_CHAR) */
out:
if (c &&
(state == json_tokener_state_finish) &&
(tok->depth == 0) &&
(tok->flags & JSON_TOKENER_STRICT)) {
/* unexpected char after JSON data */
tok->err = json_tokener_error_parse_unexpected;
}
if (!c) { /* We hit an eof char (0) */
if(state != json_tokener_state_finish &&
saved_state != json_tokener_state_finish)
tok->err = json_tokener_error_parse_eof;
}
#ifdef HAVE_SETLOCALE
setlocale(LC_NUMERIC, oldlocale);
if (oldlocale) free(oldlocale);
#endif
if (tok->err == json_tokener_success)
{
json_object *ret = json_object_get(current);
int ii;
/* Partially reset, so we parse additional objects on subsequent calls. */
for(ii = tok->depth; ii >= 0; ii--)
json_tokener_reset_level(tok, ii);
return ret;
}
MC_DEBUG("json_tokener_parse_ex: error %s at offset %d\n",
json_tokener_errors[tok->err], tok->char_offset);
return NULL;
}
void json_tokener_set_flags(struct json_tokener *tok, int flags)
{
tok->flags = flags;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5795_5 |
crossvul-cpp_data_good_343_2 | /*
* card-muscle.c: Support for MuscleCard Applet from musclecard.com
*
* Copyright (C) 2006, Identity Alliance, Thomas Harning <support@identityalliance.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include "internal.h"
#include "cardctl.h"
#include "muscle.h"
#include "muscle-filesystem.h"
#include "types.h"
#include "opensc.h"
static struct sc_card_operations muscle_ops;
static const struct sc_card_operations *iso_ops = NULL;
static struct sc_card_driver muscle_drv = {
"MuscleApplet",
"muscle",
&muscle_ops,
NULL, 0, NULL
};
static struct sc_atr_table muscle_atrs[] = {
/* Tyfone JCOP 242R2 cards */
{ "3b:6d:00:00:ff:54:79:66:6f:6e:65:20:32:34:32:52:32", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU, 0, NULL },
/* Aladdin eToken PRO USB 72K Java */
{ "3b:d5:18:00:81:31:3a:7d:80:73:c8:21:10:30", NULL, NULL, SC_CARD_TYPE_MUSCLE_ETOKEN_72K, 0, NULL },
/* JCOP31 v2.4.1 contact interface */
{ "3b:f8:13:00:00:81:31:fe:45:4a:43:4f:50:76:32:34:31:b7", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL },
/* JCOP31 v2.4.1 RF interface */
{ "3b:88:80:01:4a:43:4f:50:76:32:34:31:5e", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
#define MUSCLE_DATA(card) ( (muscle_private_t*)card->drv_data )
#define MUSCLE_FS(card) ( ((muscle_private_t*)card->drv_data)->fs )
typedef struct muscle_private {
sc_security_env_t env;
unsigned short verifiedPins;
mscfs_t *fs;
int rsa_key_ref;
} muscle_private_t;
static int muscle_finish(sc_card_t *card)
{
muscle_private_t *priv = MUSCLE_DATA(card);
mscfs_free(priv->fs);
free(priv);
return 0;
}
static u8 muscleAppletId[] = { 0xA0, 0x00,0x00,0x00, 0x01, 0x01 };
static int muscle_match_card(sc_card_t *card)
{
sc_apdu_t apdu;
u8 response[64];
int r;
/* Since we send an APDU, the card's logout function may be called...
* however it's not always properly nulled out... */
card->ops->logout = NULL;
if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) == 1) {
/* Muscle applet is present, check the protocol version to be sure */
sc_format_apdu(card, &apdu, SC_APDU_CASE_2, 0x3C, 0x00, 0x00);
apdu.cla = 0xB0;
apdu.le = 64;
apdu.resplen = 64;
apdu.resp = response;
r = sc_transmit_apdu(card, &apdu);
if (r == SC_SUCCESS && response[0] == 0x01) {
card->type = SC_CARD_TYPE_MUSCLE_V1;
} else {
card->type = SC_CARD_TYPE_MUSCLE_GENERIC;
}
return 1;
}
return 0;
}
/* Since Musclecard has a different ACL system then PKCS15
* objects need to have their READ/UPDATE/DELETE permissions mapped for files
* and directory ACLS need to be set
* For keys.. they have different ACLS, but are accessed in different locations, so it shouldn't be an issue here
*/
static unsigned short muscle_parse_singleAcl(const sc_acl_entry_t* acl)
{
unsigned short acl_entry = 0;
while(acl) {
int key = acl->key_ref;
int method = acl->method;
switch(method) {
case SC_AC_NEVER:
return 0xFFFF;
/* Ignore... other items overwrite these */
case SC_AC_NONE:
case SC_AC_UNKNOWN:
break;
case SC_AC_CHV:
acl_entry |= (1 << key); /* Assuming key 0 == SO */
break;
case SC_AC_AUT:
case SC_AC_TERM:
case SC_AC_PRO:
default:
/* Ignored */
break;
}
acl = acl->next;
}
return acl_entry;
}
static void muscle_parse_acls(const sc_file_t* file, unsigned short* read_perm, unsigned short* write_perm, unsigned short* delete_perm)
{
assert(read_perm && write_perm && delete_perm);
*read_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_READ));
*write_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_UPDATE));
*delete_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_DELETE));
}
static int muscle_create_directory(sc_card_t *card, sc_file_t *file)
{
mscfs_t *fs = MUSCLE_FS(card);
msc_id objectId;
u8* oid = objectId.id;
unsigned id = file->id;
unsigned short read_perm = 0, write_perm = 0, delete_perm = 0;
int objectSize;
int r;
if(id == 0) /* No null name files */
return SC_ERROR_INVALID_ARGUMENTS;
/* No nesting directories */
if(fs->currentPath[0] != 0x3F || fs->currentPath[1] != 0x00)
return SC_ERROR_NOT_SUPPORTED;
oid[0] = ((id & 0xFF00) >> 8) & 0xFF;
oid[1] = id & 0xFF;
oid[2] = oid[3] = 0;
objectSize = file->size;
muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm);
r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm);
mscfs_clear_cache(fs);
if(r >= 0) return 0;
return r;
}
static int muscle_create_file(sc_card_t *card, sc_file_t *file)
{
mscfs_t *fs = MUSCLE_FS(card);
int objectSize = file->size;
unsigned short read_perm = 0, write_perm = 0, delete_perm = 0;
msc_id objectId;
int r;
if(file->type == SC_FILE_TYPE_DF)
return muscle_create_directory(card, file);
if(file->type != SC_FILE_TYPE_WORKING_EF)
return SC_ERROR_NOT_SUPPORTED;
if(file->id == 0) /* No null name files */
return SC_ERROR_INVALID_ARGUMENTS;
muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm);
mscfs_lookup_local(fs, file->id, &objectId);
r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm);
mscfs_clear_cache(fs);
if(r >= 0) return 0;
return r;
}
static int muscle_read_binary(sc_card_t *card, unsigned int idx, u8* buf, size_t count, unsigned long flags)
{
mscfs_t *fs = MUSCLE_FS(card);
int r;
msc_id objectId;
u8* oid = objectId.id;
mscfs_file_t *file;
r = mscfs_check_selection(fs, -1);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
file = &fs->cache.array[fs->currentFileIndex];
objectId = file->objectId;
/* memcpy(objectId.id, file->objectId.id, 4); */
if(!file->ef) {
oid[0] = oid[2];
oid[1] = oid[3];
oid[2] = oid[3] = 0;
}
r = msc_read_object(card, objectId, idx, buf, count);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
static int muscle_update_binary(sc_card_t *card, unsigned int idx, const u8* buf, size_t count, unsigned long flags)
{
mscfs_t *fs = MUSCLE_FS(card);
int r;
mscfs_file_t *file;
msc_id objectId;
u8* oid = objectId.id;
r = mscfs_check_selection(fs, -1);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
file = &fs->cache.array[fs->currentFileIndex];
objectId = file->objectId;
/* memcpy(objectId.id, file->objectId.id, 4); */
if(!file->ef) {
oid[0] = oid[2];
oid[1] = oid[3];
oid[2] = oid[3] = 0;
}
if(file->size < idx + count) {
int newFileSize = idx + count;
u8* buffer = malloc(newFileSize);
if(buffer == NULL) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
r = msc_read_object(card, objectId, 0, buffer, file->size);
/* TODO: RETRIEVE ACLS */
if(r < 0) goto update_bin_free_buffer;
r = msc_delete_object(card, objectId, 0);
if(r < 0) goto update_bin_free_buffer;
r = msc_create_object(card, objectId, newFileSize, 0,0,0);
if(r < 0) goto update_bin_free_buffer;
memcpy(buffer + idx, buf, count);
r = msc_update_object(card, objectId, 0, buffer, newFileSize);
if(r < 0) goto update_bin_free_buffer;
file->size = newFileSize;
update_bin_free_buffer:
free(buffer);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
} else {
r = msc_update_object(card, objectId, idx, buf, count);
}
/* mscfs_clear_cache(fs); */
return r;
}
/* TODO: Evaluate correctness */
static int muscle_delete_mscfs_file(sc_card_t *card, mscfs_file_t *file_data)
{
mscfs_t *fs = MUSCLE_FS(card);
msc_id id = file_data->objectId;
u8* oid = id.id;
int r;
if(!file_data->ef) {
int x;
mscfs_file_t *childFile;
/* Delete children */
mscfs_check_cache(fs);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"DELETING Children of: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
for(x = 0; x < fs->cache.size; x++) {
msc_id objectId;
childFile = &fs->cache.array[x];
objectId = childFile->objectId;
if(0 == memcmp(oid + 2, objectId.id, 2)) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"DELETING: %02X%02X%02X%02X\n",
objectId.id[0],objectId.id[1],
objectId.id[2],objectId.id[3]);
r = muscle_delete_mscfs_file(card, childFile);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
}
}
oid[0] = oid[2];
oid[1] = oid[3];
oid[2] = oid[3] = 0;
/* ??? objectId = objectId >> 16; */
}
if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4))
|| (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) {
}
r = msc_delete_object(card, id, 1);
/* Check if its the root... this file generally is virtual
* So don't return an error if it fails */
if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4))
|| (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4)))
return 0;
if(r < 0) {
printf("ID: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
}
return 0;
}
static int muscle_delete_file(sc_card_t *card, const sc_path_t *path_in)
{
mscfs_t *fs = MUSCLE_FS(card);
mscfs_file_t *file_data = NULL;
int r = 0;
r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, NULL);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
r = muscle_delete_mscfs_file(card, file_data);
mscfs_clear_cache(fs);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
return 0;
}
static void muscle_load_single_acl(sc_file_t* file, int operation, unsigned short acl)
{
int key;
/* Everybody by default.... */
sc_file_add_acl_entry(file, operation, SC_AC_NONE, 0);
if(acl == 0xFFFF) {
sc_file_add_acl_entry(file, operation, SC_AC_NEVER, 0);
return;
}
for(key = 0; key < 16; key++) {
if(acl >> key & 1) {
sc_file_add_acl_entry(file, operation, SC_AC_CHV, key);
}
}
}
static void muscle_load_file_acls(sc_file_t* file, mscfs_file_t *file_data)
{
muscle_load_single_acl(file, SC_AC_OP_READ, file_data->read);
muscle_load_single_acl(file, SC_AC_OP_WRITE, file_data->write);
muscle_load_single_acl(file, SC_AC_OP_UPDATE, file_data->write);
muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete);
}
static void muscle_load_dir_acls(sc_file_t* file, mscfs_file_t *file_data)
{
muscle_load_single_acl(file, SC_AC_OP_SELECT, 0);
muscle_load_single_acl(file, SC_AC_OP_LIST_FILES, 0);
muscle_load_single_acl(file, SC_AC_OP_LOCK, 0xFFFF);
muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete);
muscle_load_single_acl(file, SC_AC_OP_CREATE, file_data->write);
}
/* Required type = -1 for don't care, 1 for EF, 0 for DF */
static int select_item(sc_card_t *card, const sc_path_t *path_in, sc_file_t ** file_out, int requiredType)
{
mscfs_t *fs = MUSCLE_FS(card);
mscfs_file_t *file_data = NULL;
int pathlen = path_in->len;
int r = 0;
int objectIndex;
u8* oid;
mscfs_check_cache(fs);
r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, &objectIndex);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
/* Check if its the right type */
if(requiredType >= 0 && requiredType != file_data->ef) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
}
oid = file_data->objectId.id;
/* Is it a file or directory */
if(file_data->ef) {
fs->currentPath[0] = oid[0];
fs->currentPath[1] = oid[1];
fs->currentFile[0] = oid[2];
fs->currentFile[1] = oid[3];
} else {
fs->currentPath[0] = oid[pathlen - 2];
fs->currentPath[1] = oid[pathlen - 1];
fs->currentFile[0] = 0;
fs->currentFile[1] = 0;
}
fs->currentFileIndex = objectIndex;
if(file_out) {
sc_file_t *file;
file = sc_file_new();
file->path = *path_in;
file->size = file_data->size;
file->id = (oid[2] << 8) | oid[3];
if(!file_data->ef) {
file->type = SC_FILE_TYPE_DF;
} else {
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_TRANSPARENT;
}
/* Setup ACLS */
if(file_data->ef) {
muscle_load_file_acls(file, file_data);
} else {
muscle_load_dir_acls(file, file_data);
/* Setup directory acls... */
}
file->magic = SC_FILE_MAGIC;
*file_out = file;
}
return 0;
}
static int muscle_select_file(sc_card_t *card, const sc_path_t *path_in,
sc_file_t **file_out)
{
int r;
assert(card != NULL && path_in != NULL);
switch (path_in->type) {
case SC_PATH_TYPE_FILE_ID:
r = select_item(card, path_in, file_out, 1);
break;
case SC_PATH_TYPE_DF_NAME:
r = select_item(card, path_in, file_out, 0);
break;
case SC_PATH_TYPE_PATH:
r = select_item(card, path_in, file_out, -1);
break;
default:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
if(r > 0) r = 0;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
}
static int _listFile(mscfs_file_t *file, int reset, void *udata)
{
int next = reset ? 0x00 : 0x01;
return msc_list_objects( (sc_card_t*)udata, next, file);
}
static int muscle_init(sc_card_t *card)
{
muscle_private_t *priv;
card->name = "MuscleApplet";
card->drv_data = malloc(sizeof(muscle_private_t));
if(!card->drv_data) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
}
memset(card->drv_data, 0, sizeof(muscle_private_t));
priv = MUSCLE_DATA(card);
priv->verifiedPins = 0;
priv->fs = mscfs_new();
if(!priv->fs) {
free(card->drv_data);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
}
priv->fs->udata = card;
priv->fs->listFile = _listFile;
card->cla = 0xB0;
card->flags |= SC_CARD_FLAG_RNG;
card->caps |= SC_CARD_CAP_RNG;
/* Card type detection */
_sc_match_atr(card, muscle_atrs, &card->type);
if(card->type == SC_CARD_TYPE_MUSCLE_ETOKEN_72K) {
card->caps |= SC_CARD_CAP_APDU_EXT;
}
if(card->type == SC_CARD_TYPE_MUSCLE_JCOP241) {
card->caps |= SC_CARD_CAP_APDU_EXT;
}
if (!(card->caps & SC_CARD_CAP_APDU_EXT)) {
card->max_recv_size = 255;
card->max_send_size = 255;
}
if(card->type == SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU) {
/* Tyfone JCOP v242R2 card that doesn't support extended APDUs */
}
/* FIXME: Card type detection */
if (1) {
unsigned long flags;
flags = SC_ALGORITHM_RSA_RAW;
flags |= SC_ALGORITHM_RSA_HASH_NONE;
flags |= SC_ALGORITHM_ONBOARD_KEY_GEN;
_sc_card_add_rsa_alg(card, 1024, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
}
return SC_SUCCESS;
}
static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)
{
muscle_private_t* priv = MUSCLE_DATA(card);
mscfs_t *fs = priv->fs;
int x;
int count = 0;
mscfs_check_cache(priv->fs);
for(x = 0; x < fs->cache.size; x++) {
u8* oid = fs->cache.array[x].objectId.id;
if (bufLen < 2)
break;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"FILE: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
if(0 == memcmp(fs->currentPath, oid, 2)) {
buf[0] = oid[2];
buf[1] = oid[3];
if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */
buf += 2;
count += 2;
bufLen -= 2;
}
}
return count;
}
static int muscle_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *cmd,
int *tries_left)
{
muscle_private_t* priv = MUSCLE_DATA(card);
const int bufferLength = MSC_MAX_PIN_COMMAND_LENGTH;
u8 buffer[MSC_MAX_PIN_COMMAND_LENGTH];
switch(cmd->cmd) {
case SC_PIN_CMD_VERIFY:
switch(cmd->pin_type) {
case SC_AC_CHV: {
sc_apdu_t apdu;
int r;
msc_verify_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len);
cmd->apdu = &apdu;
cmd->pin1.offset = 5;
r = iso_ops->pin_cmd(card, cmd, tries_left);
if(r >= 0)
priv->verifiedPins |= (1 << cmd->pin_reference);
return r;
}
case SC_AC_TERM:
case SC_AC_PRO:
case SC_AC_AUT:
case SC_AC_NONE:
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n");
return SC_ERROR_NOT_SUPPORTED;
}
case SC_PIN_CMD_CHANGE:
switch(cmd->pin_type) {
case SC_AC_CHV: {
sc_apdu_t apdu;
msc_change_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len, cmd->pin2.data, cmd->pin2.len);
cmd->apdu = &apdu;
return iso_ops->pin_cmd(card, cmd, tries_left);
}
case SC_AC_TERM:
case SC_AC_PRO:
case SC_AC_AUT:
case SC_AC_NONE:
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n");
return SC_ERROR_NOT_SUPPORTED;
}
case SC_PIN_CMD_UNBLOCK:
switch(cmd->pin_type) {
case SC_AC_CHV: {
sc_apdu_t apdu;
msc_unblock_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len);
cmd->apdu = &apdu;
return iso_ops->pin_cmd(card, cmd, tries_left);
}
case SC_AC_TERM:
case SC_AC_PRO:
case SC_AC_AUT:
case SC_AC_NONE:
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n");
return SC_ERROR_NOT_SUPPORTED;
}
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported command\n");
return SC_ERROR_NOT_SUPPORTED;
}
}
static int muscle_card_extract_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info)
{
/* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */
switch(info->keyType) {
case 1: /* RSA */
return msc_extract_rsa_public_key(card,
info->keyLocation,
&info->modLength,
&info->modValue,
&info->expLength,
&info->expValue);
default:
return SC_ERROR_NOT_SUPPORTED;
}
}
static int muscle_card_import_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info)
{
/* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */
switch(info->keyType) {
case 0x02: /* RSA_PRIVATE */
case 0x03: /* RSA_PRIVATE_CRT */
return msc_import_key(card,
info->keyLocation,
info);
default:
return SC_ERROR_NOT_SUPPORTED;
}
}
static int muscle_card_generate_key(sc_card_t *card, sc_cardctl_muscle_gen_key_info_t *info)
{
return msc_generate_keypair(card,
info->privateKeyLocation,
info->publicKeyLocation,
info->keyType,
info->keySize,
0);
}
static int muscle_card_verified_pins(sc_card_t *card, sc_cardctl_muscle_verified_pins_info_t *info)
{
muscle_private_t* priv = MUSCLE_DATA(card);
info->verifiedPins = priv->verifiedPins;
return 0;
}
static int muscle_card_ctl(sc_card_t *card, unsigned long request, void *data)
{
switch(request) {
case SC_CARDCTL_MUSCLE_GENERATE_KEY:
return muscle_card_generate_key(card, (sc_cardctl_muscle_gen_key_info_t*) data);
case SC_CARDCTL_MUSCLE_EXTRACT_KEY:
return muscle_card_extract_key(card, (sc_cardctl_muscle_key_info_t*) data);
case SC_CARDCTL_MUSCLE_IMPORT_KEY:
return muscle_card_import_key(card, (sc_cardctl_muscle_key_info_t*) data);
case SC_CARDCTL_MUSCLE_VERIFIED_PINS:
return muscle_card_verified_pins(card, (sc_cardctl_muscle_verified_pins_info_t*) data);
default:
return SC_ERROR_NOT_SUPPORTED; /* Unsupported.. whatever it is */
}
}
static int muscle_set_security_env(sc_card_t *card,
const sc_security_env_t *env,
int se_num)
{
muscle_private_t* priv = MUSCLE_DATA(card);
if (env->operation != SC_SEC_OPERATION_SIGN &&
env->operation != SC_SEC_OPERATION_DECIPHER) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto operation supplied.\n");
return SC_ERROR_NOT_SUPPORTED;
}
if (env->algorithm != SC_ALGORITHM_RSA) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto algorithm supplied.\n");
return SC_ERROR_NOT_SUPPORTED;
}
/* ADJUST FOR PKCS1 padding support for decryption only */
if ((env->algorithm_flags & SC_ALGORITHM_RSA_PADS) ||
(env->algorithm_flags & SC_ALGORITHM_RSA_HASHES)) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card supports only raw RSA.\n");
return SC_ERROR_NOT_SUPPORTED;
}
if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) {
if (env->key_ref_len != 1 ||
(env->key_ref[0] > 0x0F)) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid key reference supplied.\n");
return SC_ERROR_NOT_SUPPORTED;
}
priv->rsa_key_ref = env->key_ref[0];
}
if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Algorithm reference not supported.\n");
return SC_ERROR_NOT_SUPPORTED;
}
/* if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT)
if (memcmp(env->file_ref.value, "\x00\x12", 2) != 0) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File reference is not 0012.\n");
return SC_ERROR_NOT_SUPPORTED;
} */
priv->env = *env;
return 0;
}
static int muscle_restore_security_env(sc_card_t *card, int se_num)
{
muscle_private_t* priv = MUSCLE_DATA(card);
memset(&priv->env, 0, sizeof(priv->env));
return 0;
}
static int muscle_decipher(sc_card_t * card,
const u8 * crgram, size_t crgram_len, u8 * out,
size_t out_len)
{
muscle_private_t* priv = MUSCLE_DATA(card);
u8 key_id;
int r;
/* sanity check */
if (priv->env.operation != SC_SEC_OPERATION_DECIPHER)
return SC_ERROR_INVALID_ARGUMENTS;
key_id = priv->rsa_key_ref * 2; /* Private key */
if (out_len < crgram_len) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small");
return SC_ERROR_BUFFER_TOO_SMALL;
}
r = msc_compute_crypt(card,
key_id,
0x00, /* RSA NO PADDING */
0x04, /* decrypt */
crgram,
out,
crgram_len,
out_len);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed");
return r;
}
static int muscle_compute_signature(sc_card_t *card, const u8 *data,
size_t data_len, u8 * out, size_t outlen)
{
muscle_private_t* priv = MUSCLE_DATA(card);
u8 key_id;
int r;
key_id = priv->rsa_key_ref * 2; /* Private key */
if (outlen < data_len) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small");
return SC_ERROR_BUFFER_TOO_SMALL;
}
r = msc_compute_crypt(card,
key_id,
0x00, /* RSA NO PADDING */
0x04, /* -- decrypt raw... will do what we need since signing isn't yet supported */
data,
out,
data_len,
outlen);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed");
return r;
}
static int muscle_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
{
if (len == 0)
return SC_SUCCESS;
else {
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL,
msc_get_challenge(card, len, 0, NULL, rnd),
"GET CHALLENGE cmd failed");
return (int) len;
}
}
static int muscle_check_sw(sc_card_t * card, unsigned int sw1, unsigned int sw2) {
if(sw1 == 0x9C) {
switch(sw2) {
case 0x01: /* SW_NO_MEMORY_LEFT */
return SC_ERROR_NOT_ENOUGH_MEMORY;
case 0x02: /* SW_AUTH_FAILED */
return SC_ERROR_PIN_CODE_INCORRECT;
case 0x03: /* SW_OPERATION_NOT_ALLOWED */
return SC_ERROR_NOT_ALLOWED;
case 0x05: /* SW_UNSUPPORTED_FEATURE */
return SC_ERROR_NO_CARD_SUPPORT;
case 0x06: /* SW_UNAUTHORIZED */
return SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;
case 0x07: /* SW_OBJECT_NOT_FOUND */
return SC_ERROR_FILE_NOT_FOUND;
case 0x08: /* SW_OBJECT_EXISTS */
return SC_ERROR_FILE_ALREADY_EXISTS;
case 0x09: /* SW_INCORRECT_ALG */
return SC_ERROR_INCORRECT_PARAMETERS;
case 0x0B: /* SW_SIGNATURE_INVALID */
return SC_ERROR_CARD_CMD_FAILED;
case 0x0C: /* SW_IDENTITY_BLOCKED */
return SC_ERROR_AUTH_METHOD_BLOCKED;
case 0x0F: /* SW_INVALID_PARAMETER */
case 0x10: /* SW_INCORRECT_P1 */
case 0x11: /* SW_INCORRECT_P2 */
return SC_ERROR_INCORRECT_PARAMETERS;
}
}
return iso_ops->check_sw(card, sw1, sw2);
}
static int muscle_card_reader_lock_obtained(sc_card_t *card, int was_reset)
{
int r = SC_SUCCESS;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (was_reset > 0) {
if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) != 1) {
r = SC_ERROR_INVALID_CARD;
}
}
LOG_FUNC_RETURN(card->ctx, r);
}
static struct sc_card_driver * sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (iso_ops == NULL)
iso_ops = iso_drv->ops;
muscle_ops = *iso_drv->ops;
muscle_ops.check_sw = muscle_check_sw;
muscle_ops.pin_cmd = muscle_pin_cmd;
muscle_ops.match_card = muscle_match_card;
muscle_ops.init = muscle_init;
muscle_ops.finish = muscle_finish;
muscle_ops.get_challenge = muscle_get_challenge;
muscle_ops.set_security_env = muscle_set_security_env;
muscle_ops.restore_security_env = muscle_restore_security_env;
muscle_ops.compute_signature = muscle_compute_signature;
muscle_ops.decipher = muscle_decipher;
muscle_ops.card_ctl = muscle_card_ctl;
muscle_ops.read_binary = muscle_read_binary;
muscle_ops.update_binary = muscle_update_binary;
muscle_ops.create_file = muscle_create_file;
muscle_ops.select_file = muscle_select_file;
muscle_ops.delete_file = muscle_delete_file;
muscle_ops.list_files = muscle_list_files;
muscle_ops.card_reader_lock_obtained = muscle_card_reader_lock_obtained;
return &muscle_drv;
}
struct sc_card_driver * sc_get_muscle_driver(void)
{
return sc_get_driver();
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_343_2 |
crossvul-cpp_data_bad_5740_1 | /*
* NET4: Implementation of BSD Unix domain sockets.
*
* Authors: Alan Cox, <alan@lxorguk.ukuu.org.uk>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Fixes:
* Linus Torvalds : Assorted bug cures.
* Niibe Yutaka : async I/O support.
* Carsten Paeth : PF_UNIX check, address fixes.
* Alan Cox : Limit size of allocated blocks.
* Alan Cox : Fixed the stupid socketpair bug.
* Alan Cox : BSD compatibility fine tuning.
* Alan Cox : Fixed a bug in connect when interrupted.
* Alan Cox : Sorted out a proper draft version of
* file descriptor passing hacked up from
* Mike Shaver's work.
* Marty Leisner : Fixes to fd passing
* Nick Nevin : recvmsg bugfix.
* Alan Cox : Started proper garbage collector
* Heiko EiBfeldt : Missing verify_area check
* Alan Cox : Started POSIXisms
* Andreas Schwab : Replace inode by dentry for proper
* reference counting
* Kirk Petersen : Made this a module
* Christoph Rohland : Elegant non-blocking accept/connect algorithm.
* Lots of bug fixes.
* Alexey Kuznetosv : Repaired (I hope) bugs introduces
* by above two patches.
* Andrea Arcangeli : If possible we block in connect(2)
* if the max backlog of the listen socket
* is been reached. This won't break
* old apps and it will avoid huge amount
* of socks hashed (this for unix_gc()
* performances reasons).
* Security fix that limits the max
* number of socks to 2*max_files and
* the number of skb queueable in the
* dgram receiver.
* Artur Skawina : Hash function optimizations
* Alexey Kuznetsov : Full scale SMP. Lot of bugs are introduced 8)
* Malcolm Beattie : Set peercred for socketpair
* Michal Ostrowski : Module initialization cleanup.
* Arnaldo C. Melo : Remove MOD_{INC,DEC}_USE_COUNT,
* the core infrastructure is doing that
* for all net proto families now (2.5.69+)
*
*
* Known differences from reference BSD that was tested:
*
* [TO FIX]
* ECONNREFUSED is not returned from one end of a connected() socket to the
* other the moment one end closes.
* fstat() doesn't return st_dev=0, and give the blksize as high water mark
* and a fake inode identifier (nor the BSD first socket fstat twice bug).
* [NOT TO FIX]
* accept() returns a path name even if the connecting socket has closed
* in the meantime (BSD loses the path and gives up).
* accept() returns 0 length path for an unbound connector. BSD returns 16
* and a null first byte in the path (but not for gethost/peername - BSD bug ??)
* socketpair(...SOCK_RAW..) doesn't panic the kernel.
* BSD af_unix apparently has connect forgetting to block properly.
* (need to check this with the POSIX spec in detail)
*
* Differences from 2.0.0-11-... (ANK)
* Bug fixes and improvements.
* - client shutdown killed server socket.
* - removed all useless cli/sti pairs.
*
* Semantic changes/extensions.
* - generic control message passing.
* - SCM_CREDENTIALS control message.
* - "Abstract" (not FS based) socket bindings.
* Abstract names are sequences of bytes (not zero terminated)
* started by 0, so that this name space does not intersect
* with BSD names.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/stat.h>
#include <linux/dcache.h>
#include <linux/namei.h>
#include <linux/socket.h>
#include <linux/un.h>
#include <linux/fcntl.h>
#include <linux/termios.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/in.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <net/af_unix.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <net/scm.h>
#include <linux/init.h>
#include <linux/poll.h>
#include <linux/rtnetlink.h>
#include <linux/mount.h>
#include <net/checksum.h>
#include <linux/security.h>
#include <linux/freezer.h>
struct hlist_head unix_socket_table[2 * UNIX_HASH_SIZE];
EXPORT_SYMBOL_GPL(unix_socket_table);
DEFINE_SPINLOCK(unix_table_lock);
EXPORT_SYMBOL_GPL(unix_table_lock);
static atomic_long_t unix_nr_socks;
static struct hlist_head *unix_sockets_unbound(void *addr)
{
unsigned long hash = (unsigned long)addr;
hash ^= hash >> 16;
hash ^= hash >> 8;
hash %= UNIX_HASH_SIZE;
return &unix_socket_table[UNIX_HASH_SIZE + hash];
}
#define UNIX_ABSTRACT(sk) (unix_sk(sk)->addr->hash < UNIX_HASH_SIZE)
#ifdef CONFIG_SECURITY_NETWORK
static void unix_get_secdata(struct scm_cookie *scm, struct sk_buff *skb)
{
UNIXCB(skb).secid = scm->secid;
}
static inline void unix_set_secdata(struct scm_cookie *scm, struct sk_buff *skb)
{
scm->secid = UNIXCB(skb).secid;
}
static inline bool unix_secdata_eq(struct scm_cookie *scm, struct sk_buff *skb)
{
return (scm->secid == UNIXCB(skb).secid);
}
#else
static inline void unix_get_secdata(struct scm_cookie *scm, struct sk_buff *skb)
{ }
static inline void unix_set_secdata(struct scm_cookie *scm, struct sk_buff *skb)
{ }
static inline bool unix_secdata_eq(struct scm_cookie *scm, struct sk_buff *skb)
{
return true;
}
#endif /* CONFIG_SECURITY_NETWORK */
/*
* SMP locking strategy:
* hash table is protected with spinlock unix_table_lock
* each socket state is protected by separate spin lock.
*/
static inline unsigned int unix_hash_fold(__wsum n)
{
unsigned int hash = (__force unsigned int)csum_fold(n);
hash ^= hash>>8;
return hash&(UNIX_HASH_SIZE-1);
}
#define unix_peer(sk) (unix_sk(sk)->peer)
static inline int unix_our_peer(struct sock *sk, struct sock *osk)
{
return unix_peer(osk) == sk;
}
static inline int unix_may_send(struct sock *sk, struct sock *osk)
{
return unix_peer(osk) == NULL || unix_our_peer(sk, osk);
}
static inline int unix_recvq_full(struct sock const *sk)
{
return skb_queue_len(&sk->sk_receive_queue) > sk->sk_max_ack_backlog;
}
struct sock *unix_peer_get(struct sock *s)
{
struct sock *peer;
unix_state_lock(s);
peer = unix_peer(s);
if (peer)
sock_hold(peer);
unix_state_unlock(s);
return peer;
}
EXPORT_SYMBOL_GPL(unix_peer_get);
static inline void unix_release_addr(struct unix_address *addr)
{
if (atomic_dec_and_test(&addr->refcnt))
kfree(addr);
}
/*
* Check unix socket name:
* - should be not zero length.
* - if started by not zero, should be NULL terminated (FS object)
* - if started by zero, it is abstract name.
*/
static int unix_mkname(struct sockaddr_un *sunaddr, int len, unsigned int *hashp)
{
if (len <= sizeof(short) || len > sizeof(*sunaddr))
return -EINVAL;
if (!sunaddr || sunaddr->sun_family != AF_UNIX)
return -EINVAL;
if (sunaddr->sun_path[0]) {
/*
* This may look like an off by one error but it is a bit more
* subtle. 108 is the longest valid AF_UNIX path for a binding.
* sun_path[108] doesn't as such exist. However in kernel space
* we are guaranteed that it is a valid memory location in our
* kernel address buffer.
*/
((char *)sunaddr)[len] = 0;
len = strlen(sunaddr->sun_path)+1+sizeof(short);
return len;
}
*hashp = unix_hash_fold(csum_partial(sunaddr, len, 0));
return len;
}
static void __unix_remove_socket(struct sock *sk)
{
sk_del_node_init(sk);
}
static void __unix_insert_socket(struct hlist_head *list, struct sock *sk)
{
WARN_ON(!sk_unhashed(sk));
sk_add_node(sk, list);
}
static inline void unix_remove_socket(struct sock *sk)
{
spin_lock(&unix_table_lock);
__unix_remove_socket(sk);
spin_unlock(&unix_table_lock);
}
static inline void unix_insert_socket(struct hlist_head *list, struct sock *sk)
{
spin_lock(&unix_table_lock);
__unix_insert_socket(list, sk);
spin_unlock(&unix_table_lock);
}
static struct sock *__unix_find_socket_byname(struct net *net,
struct sockaddr_un *sunname,
int len, int type, unsigned int hash)
{
struct sock *s;
sk_for_each(s, &unix_socket_table[hash ^ type]) {
struct unix_sock *u = unix_sk(s);
if (!net_eq(sock_net(s), net))
continue;
if (u->addr->len == len &&
!memcmp(u->addr->name, sunname, len))
goto found;
}
s = NULL;
found:
return s;
}
static inline struct sock *unix_find_socket_byname(struct net *net,
struct sockaddr_un *sunname,
int len, int type,
unsigned int hash)
{
struct sock *s;
spin_lock(&unix_table_lock);
s = __unix_find_socket_byname(net, sunname, len, type, hash);
if (s)
sock_hold(s);
spin_unlock(&unix_table_lock);
return s;
}
static struct sock *unix_find_socket_byinode(struct inode *i)
{
struct sock *s;
spin_lock(&unix_table_lock);
sk_for_each(s,
&unix_socket_table[i->i_ino & (UNIX_HASH_SIZE - 1)]) {
struct dentry *dentry = unix_sk(s)->path.dentry;
if (dentry && d_backing_inode(dentry) == i) {
sock_hold(s);
goto found;
}
}
s = NULL;
found:
spin_unlock(&unix_table_lock);
return s;
}
/* Support code for asymmetrically connected dgram sockets
*
* If a datagram socket is connected to a socket not itself connected
* to the first socket (eg, /dev/log), clients may only enqueue more
* messages if the present receive queue of the server socket is not
* "too large". This means there's a second writeability condition
* poll and sendmsg need to test. The dgram recv code will do a wake
* up on the peer_wait wait queue of a socket upon reception of a
* datagram which needs to be propagated to sleeping would-be writers
* since these might not have sent anything so far. This can't be
* accomplished via poll_wait because the lifetime of the server
* socket might be less than that of its clients if these break their
* association with it or if the server socket is closed while clients
* are still connected to it and there's no way to inform "a polling
* implementation" that it should let go of a certain wait queue
*
* In order to propagate a wake up, a wait_queue_t of the client
* socket is enqueued on the peer_wait queue of the server socket
* whose wake function does a wake_up on the ordinary client socket
* wait queue. This connection is established whenever a write (or
* poll for write) hit the flow control condition and broken when the
* association to the server socket is dissolved or after a wake up
* was relayed.
*/
static int unix_dgram_peer_wake_relay(wait_queue_t *q, unsigned mode, int flags,
void *key)
{
struct unix_sock *u;
wait_queue_head_t *u_sleep;
u = container_of(q, struct unix_sock, peer_wake);
__remove_wait_queue(&unix_sk(u->peer_wake.private)->peer_wait,
q);
u->peer_wake.private = NULL;
/* relaying can only happen while the wq still exists */
u_sleep = sk_sleep(&u->sk);
if (u_sleep)
wake_up_interruptible_poll(u_sleep, key);
return 0;
}
static int unix_dgram_peer_wake_connect(struct sock *sk, struct sock *other)
{
struct unix_sock *u, *u_other;
int rc;
u = unix_sk(sk);
u_other = unix_sk(other);
rc = 0;
spin_lock(&u_other->peer_wait.lock);
if (!u->peer_wake.private) {
u->peer_wake.private = other;
__add_wait_queue(&u_other->peer_wait, &u->peer_wake);
rc = 1;
}
spin_unlock(&u_other->peer_wait.lock);
return rc;
}
static void unix_dgram_peer_wake_disconnect(struct sock *sk,
struct sock *other)
{
struct unix_sock *u, *u_other;
u = unix_sk(sk);
u_other = unix_sk(other);
spin_lock(&u_other->peer_wait.lock);
if (u->peer_wake.private == other) {
__remove_wait_queue(&u_other->peer_wait, &u->peer_wake);
u->peer_wake.private = NULL;
}
spin_unlock(&u_other->peer_wait.lock);
}
static void unix_dgram_peer_wake_disconnect_wakeup(struct sock *sk,
struct sock *other)
{
unix_dgram_peer_wake_disconnect(sk, other);
wake_up_interruptible_poll(sk_sleep(sk),
POLLOUT |
POLLWRNORM |
POLLWRBAND);
}
/* preconditions:
* - unix_peer(sk) == other
* - association is stable
*/
static int unix_dgram_peer_wake_me(struct sock *sk, struct sock *other)
{
int connected;
connected = unix_dgram_peer_wake_connect(sk, other);
if (unix_recvq_full(other))
return 1;
if (connected)
unix_dgram_peer_wake_disconnect(sk, other);
return 0;
}
static int unix_writable(const struct sock *sk)
{
return sk->sk_state != TCP_LISTEN &&
(atomic_read(&sk->sk_wmem_alloc) << 2) <= sk->sk_sndbuf;
}
static void unix_write_space(struct sock *sk)
{
struct socket_wq *wq;
rcu_read_lock();
if (unix_writable(sk)) {
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait,
POLLOUT | POLLWRNORM | POLLWRBAND);
sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
}
rcu_read_unlock();
}
/* When dgram socket disconnects (or changes its peer), we clear its receive
* queue of packets arrived from previous peer. First, it allows to do
* flow control based only on wmem_alloc; second, sk connected to peer
* may receive messages only from that peer. */
static void unix_dgram_disconnected(struct sock *sk, struct sock *other)
{
if (!skb_queue_empty(&sk->sk_receive_queue)) {
skb_queue_purge(&sk->sk_receive_queue);
wake_up_interruptible_all(&unix_sk(sk)->peer_wait);
/* If one link of bidirectional dgram pipe is disconnected,
* we signal error. Messages are lost. Do not make this,
* when peer was not connected to us.
*/
if (!sock_flag(other, SOCK_DEAD) && unix_peer(other) == sk) {
other->sk_err = ECONNRESET;
other->sk_error_report(other);
}
}
}
static void unix_sock_destructor(struct sock *sk)
{
struct unix_sock *u = unix_sk(sk);
skb_queue_purge(&sk->sk_receive_queue);
WARN_ON(atomic_read(&sk->sk_wmem_alloc));
WARN_ON(!sk_unhashed(sk));
WARN_ON(sk->sk_socket);
if (!sock_flag(sk, SOCK_DEAD)) {
pr_info("Attempt to release alive unix socket: %p\n", sk);
return;
}
if (u->addr)
unix_release_addr(u->addr);
atomic_long_dec(&unix_nr_socks);
local_bh_disable();
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
local_bh_enable();
#ifdef UNIX_REFCNT_DEBUG
pr_debug("UNIX %p is destroyed, %ld are still alive.\n", sk,
atomic_long_read(&unix_nr_socks));
#endif
}
static void unix_release_sock(struct sock *sk, int embrion)
{
struct unix_sock *u = unix_sk(sk);
struct path path;
struct sock *skpair;
struct sk_buff *skb;
int state;
unix_remove_socket(sk);
/* Clear state */
unix_state_lock(sk);
sock_orphan(sk);
sk->sk_shutdown = SHUTDOWN_MASK;
path = u->path;
u->path.dentry = NULL;
u->path.mnt = NULL;
state = sk->sk_state;
sk->sk_state = TCP_CLOSE;
unix_state_unlock(sk);
wake_up_interruptible_all(&u->peer_wait);
skpair = unix_peer(sk);
if (skpair != NULL) {
if (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET) {
unix_state_lock(skpair);
/* No more writes */
skpair->sk_shutdown = SHUTDOWN_MASK;
if (!skb_queue_empty(&sk->sk_receive_queue) || embrion)
skpair->sk_err = ECONNRESET;
unix_state_unlock(skpair);
skpair->sk_state_change(skpair);
sk_wake_async(skpair, SOCK_WAKE_WAITD, POLL_HUP);
}
unix_dgram_peer_wake_disconnect(sk, skpair);
sock_put(skpair); /* It may now die */
unix_peer(sk) = NULL;
}
/* Try to flush out this socket. Throw out buffers at least */
while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) {
if (state == TCP_LISTEN)
unix_release_sock(skb->sk, 1);
/* passed fds are erased in the kfree_skb hook */
UNIXCB(skb).consumed = skb->len;
kfree_skb(skb);
}
if (path.dentry)
path_put(&path);
sock_put(sk);
/* ---- Socket is dead now and most probably destroyed ---- */
/*
* Fixme: BSD difference: In BSD all sockets connected to us get
* ECONNRESET and we die on the spot. In Linux we behave
* like files and pipes do and wait for the last
* dereference.
*
* Can't we simply set sock->err?
*
* What the above comment does talk about? --ANK(980817)
*/
if (unix_tot_inflight)
unix_gc(); /* Garbage collect fds */
}
static void init_peercred(struct sock *sk)
{
put_pid(sk->sk_peer_pid);
if (sk->sk_peer_cred)
put_cred(sk->sk_peer_cred);
sk->sk_peer_pid = get_pid(task_tgid(current));
sk->sk_peer_cred = get_current_cred();
}
static void copy_peercred(struct sock *sk, struct sock *peersk)
{
put_pid(sk->sk_peer_pid);
if (sk->sk_peer_cred)
put_cred(sk->sk_peer_cred);
sk->sk_peer_pid = get_pid(peersk->sk_peer_pid);
sk->sk_peer_cred = get_cred(peersk->sk_peer_cred);
}
static int unix_listen(struct socket *sock, int backlog)
{
int err;
struct sock *sk = sock->sk;
struct unix_sock *u = unix_sk(sk);
struct pid *old_pid = NULL;
err = -EOPNOTSUPP;
if (sock->type != SOCK_STREAM && sock->type != SOCK_SEQPACKET)
goto out; /* Only stream/seqpacket sockets accept */
err = -EINVAL;
if (!u->addr)
goto out; /* No listens on an unbound socket */
unix_state_lock(sk);
if (sk->sk_state != TCP_CLOSE && sk->sk_state != TCP_LISTEN)
goto out_unlock;
if (backlog > sk->sk_max_ack_backlog)
wake_up_interruptible_all(&u->peer_wait);
sk->sk_max_ack_backlog = backlog;
sk->sk_state = TCP_LISTEN;
/* set credentials so connect can copy them */
init_peercred(sk);
err = 0;
out_unlock:
unix_state_unlock(sk);
put_pid(old_pid);
out:
return err;
}
static int unix_release(struct socket *);
static int unix_bind(struct socket *, struct sockaddr *, int);
static int unix_stream_connect(struct socket *, struct sockaddr *,
int addr_len, int flags);
static int unix_socketpair(struct socket *, struct socket *);
static int unix_accept(struct socket *, struct socket *, int);
static int unix_getname(struct socket *, struct sockaddr *, int *, int);
static unsigned int unix_poll(struct file *, struct socket *, poll_table *);
static unsigned int unix_dgram_poll(struct file *, struct socket *,
poll_table *);
static int unix_ioctl(struct socket *, unsigned int, unsigned long);
static int unix_shutdown(struct socket *, int);
static int unix_stream_sendmsg(struct socket *, struct msghdr *, size_t);
static int unix_stream_recvmsg(struct socket *, struct msghdr *, size_t, int);
static ssize_t unix_stream_sendpage(struct socket *, struct page *, int offset,
size_t size, int flags);
static ssize_t unix_stream_splice_read(struct socket *, loff_t *ppos,
struct pipe_inode_info *, size_t size,
unsigned int flags);
static int unix_dgram_sendmsg(struct socket *, struct msghdr *, size_t);
static int unix_dgram_recvmsg(struct socket *, struct msghdr *, size_t, int);
static int unix_dgram_connect(struct socket *, struct sockaddr *,
int, int);
static int unix_seqpacket_sendmsg(struct socket *, struct msghdr *, size_t);
static int unix_seqpacket_recvmsg(struct socket *, struct msghdr *, size_t,
int);
static int unix_set_peek_off(struct sock *sk, int val)
{
struct unix_sock *u = unix_sk(sk);
if (mutex_lock_interruptible(&u->readlock))
return -EINTR;
sk->sk_peek_off = val;
mutex_unlock(&u->readlock);
return 0;
}
static const struct proto_ops unix_stream_ops = {
.family = PF_UNIX,
.owner = THIS_MODULE,
.release = unix_release,
.bind = unix_bind,
.connect = unix_stream_connect,
.socketpair = unix_socketpair,
.accept = unix_accept,
.getname = unix_getname,
.poll = unix_poll,
.ioctl = unix_ioctl,
.listen = unix_listen,
.shutdown = unix_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = unix_stream_sendmsg,
.recvmsg = unix_stream_recvmsg,
.mmap = sock_no_mmap,
.sendpage = unix_stream_sendpage,
.splice_read = unix_stream_splice_read,
.set_peek_off = unix_set_peek_off,
};
static const struct proto_ops unix_dgram_ops = {
.family = PF_UNIX,
.owner = THIS_MODULE,
.release = unix_release,
.bind = unix_bind,
.connect = unix_dgram_connect,
.socketpair = unix_socketpair,
.accept = sock_no_accept,
.getname = unix_getname,
.poll = unix_dgram_poll,
.ioctl = unix_ioctl,
.listen = sock_no_listen,
.shutdown = unix_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = unix_dgram_sendmsg,
.recvmsg = unix_dgram_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
.set_peek_off = unix_set_peek_off,
};
static const struct proto_ops unix_seqpacket_ops = {
.family = PF_UNIX,
.owner = THIS_MODULE,
.release = unix_release,
.bind = unix_bind,
.connect = unix_stream_connect,
.socketpair = unix_socketpair,
.accept = unix_accept,
.getname = unix_getname,
.poll = unix_dgram_poll,
.ioctl = unix_ioctl,
.listen = unix_listen,
.shutdown = unix_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = unix_seqpacket_sendmsg,
.recvmsg = unix_seqpacket_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
.set_peek_off = unix_set_peek_off,
};
static struct proto unix_proto = {
.name = "UNIX",
.owner = THIS_MODULE,
.obj_size = sizeof(struct unix_sock),
};
/*
* AF_UNIX sockets do not interact with hardware, hence they
* dont trigger interrupts - so it's safe for them to have
* bh-unsafe locking for their sk_receive_queue.lock. Split off
* this special lock-class by reinitializing the spinlock key:
*/
static struct lock_class_key af_unix_sk_receive_queue_lock_key;
static struct sock *unix_create1(struct net *net, struct socket *sock, int kern)
{
struct sock *sk = NULL;
struct unix_sock *u;
atomic_long_inc(&unix_nr_socks);
if (atomic_long_read(&unix_nr_socks) > 2 * get_max_files())
goto out;
sk = sk_alloc(net, PF_UNIX, GFP_KERNEL, &unix_proto, kern);
if (!sk)
goto out;
sock_init_data(sock, sk);
lockdep_set_class(&sk->sk_receive_queue.lock,
&af_unix_sk_receive_queue_lock_key);
sk->sk_write_space = unix_write_space;
sk->sk_max_ack_backlog = net->unx.sysctl_max_dgram_qlen;
sk->sk_destruct = unix_sock_destructor;
u = unix_sk(sk);
u->path.dentry = NULL;
u->path.mnt = NULL;
spin_lock_init(&u->lock);
atomic_long_set(&u->inflight, 0);
INIT_LIST_HEAD(&u->link);
mutex_init(&u->readlock); /* single task reading lock */
init_waitqueue_head(&u->peer_wait);
init_waitqueue_func_entry(&u->peer_wake, unix_dgram_peer_wake_relay);
unix_insert_socket(unix_sockets_unbound(sk), sk);
out:
if (sk == NULL)
atomic_long_dec(&unix_nr_socks);
else {
local_bh_disable();
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
local_bh_enable();
}
return sk;
}
static int unix_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
if (protocol && protocol != PF_UNIX)
return -EPROTONOSUPPORT;
sock->state = SS_UNCONNECTED;
switch (sock->type) {
case SOCK_STREAM:
sock->ops = &unix_stream_ops;
break;
/*
* Believe it or not BSD has AF_UNIX, SOCK_RAW though
* nothing uses it.
*/
case SOCK_RAW:
sock->type = SOCK_DGRAM;
case SOCK_DGRAM:
sock->ops = &unix_dgram_ops;
break;
case SOCK_SEQPACKET:
sock->ops = &unix_seqpacket_ops;
break;
default:
return -ESOCKTNOSUPPORT;
}
return unix_create1(net, sock, kern) ? 0 : -ENOMEM;
}
static int unix_release(struct socket *sock)
{
struct sock *sk = sock->sk;
if (!sk)
return 0;
unix_release_sock(sk, 0);
sock->sk = NULL;
return 0;
}
static int unix_autobind(struct socket *sock)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct unix_sock *u = unix_sk(sk);
static u32 ordernum = 1;
struct unix_address *addr;
int err;
unsigned int retries = 0;
err = mutex_lock_interruptible(&u->readlock);
if (err)
return err;
err = 0;
if (u->addr)
goto out;
err = -ENOMEM;
addr = kzalloc(sizeof(*addr) + sizeof(short) + 16, GFP_KERNEL);
if (!addr)
goto out;
addr->name->sun_family = AF_UNIX;
atomic_set(&addr->refcnt, 1);
retry:
addr->len = sprintf(addr->name->sun_path+1, "%05x", ordernum) + 1 + sizeof(short);
addr->hash = unix_hash_fold(csum_partial(addr->name, addr->len, 0));
spin_lock(&unix_table_lock);
ordernum = (ordernum+1)&0xFFFFF;
if (__unix_find_socket_byname(net, addr->name, addr->len, sock->type,
addr->hash)) {
spin_unlock(&unix_table_lock);
/*
* __unix_find_socket_byname() may take long time if many names
* are already in use.
*/
cond_resched();
/* Give up if all names seems to be in use. */
if (retries++ == 0xFFFFF) {
err = -ENOSPC;
kfree(addr);
goto out;
}
goto retry;
}
addr->hash ^= sk->sk_type;
__unix_remove_socket(sk);
u->addr = addr;
__unix_insert_socket(&unix_socket_table[addr->hash], sk);
spin_unlock(&unix_table_lock);
err = 0;
out: mutex_unlock(&u->readlock);
return err;
}
static struct sock *unix_find_other(struct net *net,
struct sockaddr_un *sunname, int len,
int type, unsigned int hash, int *error)
{
struct sock *u;
struct path path;
int err = 0;
if (sunname->sun_path[0]) {
struct inode *inode;
err = kern_path(sunname->sun_path, LOOKUP_FOLLOW, &path);
if (err)
goto fail;
inode = d_backing_inode(path.dentry);
err = inode_permission(inode, MAY_WRITE);
if (err)
goto put_fail;
err = -ECONNREFUSED;
if (!S_ISSOCK(inode->i_mode))
goto put_fail;
u = unix_find_socket_byinode(inode);
if (!u)
goto put_fail;
if (u->sk_type == type)
touch_atime(&path);
path_put(&path);
err = -EPROTOTYPE;
if (u->sk_type != type) {
sock_put(u);
goto fail;
}
} else {
err = -ECONNREFUSED;
u = unix_find_socket_byname(net, sunname, len, type, hash);
if (u) {
struct dentry *dentry;
dentry = unix_sk(u)->path.dentry;
if (dentry)
touch_atime(&unix_sk(u)->path);
} else
goto fail;
}
return u;
put_fail:
path_put(&path);
fail:
*error = err;
return NULL;
}
static int unix_mknod(struct dentry *dentry, struct path *path, umode_t mode,
struct path *res)
{
int err;
err = security_path_mknod(path, dentry, mode, 0);
if (!err) {
err = vfs_mknod(d_inode(path->dentry), dentry, mode, 0);
if (!err) {
res->mnt = mntget(path->mnt);
res->dentry = dget(dentry);
}
}
return err;
}
static int unix_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct unix_sock *u = unix_sk(sk);
struct sockaddr_un *sunaddr = (struct sockaddr_un *)uaddr;
char *sun_path = sunaddr->sun_path;
int err, name_err;
unsigned int hash;
struct unix_address *addr;
struct hlist_head *list;
struct path path;
struct dentry *dentry;
err = -EINVAL;
if (sunaddr->sun_family != AF_UNIX)
goto out;
if (addr_len == sizeof(short)) {
err = unix_autobind(sock);
goto out;
}
err = unix_mkname(sunaddr, addr_len, &hash);
if (err < 0)
goto out;
addr_len = err;
name_err = 0;
dentry = NULL;
if (sun_path[0]) {
/* Get the parent directory, calculate the hash for last
* component.
*/
dentry = kern_path_create(AT_FDCWD, sun_path, &path, 0);
if (IS_ERR(dentry)) {
/* delay report until after 'already bound' check */
name_err = PTR_ERR(dentry);
dentry = NULL;
}
}
err = mutex_lock_interruptible(&u->readlock);
if (err)
goto out_path;
err = -EINVAL;
if (u->addr)
goto out_up;
if (name_err) {
err = name_err == -EEXIST ? -EADDRINUSE : name_err;
goto out_up;
}
err = -ENOMEM;
addr = kmalloc(sizeof(*addr)+addr_len, GFP_KERNEL);
if (!addr)
goto out_up;
memcpy(addr->name, sunaddr, addr_len);
addr->len = addr_len;
addr->hash = hash ^ sk->sk_type;
atomic_set(&addr->refcnt, 1);
if (dentry) {
struct path u_path;
umode_t mode = S_IFSOCK |
(SOCK_INODE(sock)->i_mode & ~current_umask());
err = unix_mknod(dentry, &path, mode, &u_path);
if (err) {
if (err == -EEXIST)
err = -EADDRINUSE;
unix_release_addr(addr);
goto out_up;
}
addr->hash = UNIX_HASH_SIZE;
hash = d_backing_inode(dentry)->i_ino & (UNIX_HASH_SIZE - 1);
spin_lock(&unix_table_lock);
u->path = u_path;
list = &unix_socket_table[hash];
} else {
spin_lock(&unix_table_lock);
err = -EADDRINUSE;
if (__unix_find_socket_byname(net, sunaddr, addr_len,
sk->sk_type, hash)) {
unix_release_addr(addr);
goto out_unlock;
}
list = &unix_socket_table[addr->hash];
}
err = 0;
__unix_remove_socket(sk);
u->addr = addr;
__unix_insert_socket(list, sk);
out_unlock:
spin_unlock(&unix_table_lock);
out_up:
mutex_unlock(&u->readlock);
out_path:
if (dentry)
done_path_create(&path, dentry);
out:
return err;
}
static void unix_state_double_lock(struct sock *sk1, struct sock *sk2)
{
if (unlikely(sk1 == sk2) || !sk2) {
unix_state_lock(sk1);
return;
}
if (sk1 < sk2) {
unix_state_lock(sk1);
unix_state_lock_nested(sk2);
} else {
unix_state_lock(sk2);
unix_state_lock_nested(sk1);
}
}
static void unix_state_double_unlock(struct sock *sk1, struct sock *sk2)
{
if (unlikely(sk1 == sk2) || !sk2) {
unix_state_unlock(sk1);
return;
}
unix_state_unlock(sk1);
unix_state_unlock(sk2);
}
static int unix_dgram_connect(struct socket *sock, struct sockaddr *addr,
int alen, int flags)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct sockaddr_un *sunaddr = (struct sockaddr_un *)addr;
struct sock *other;
unsigned int hash;
int err;
if (addr->sa_family != AF_UNSPEC) {
err = unix_mkname(sunaddr, alen, &hash);
if (err < 0)
goto out;
alen = err;
if (test_bit(SOCK_PASSCRED, &sock->flags) &&
!unix_sk(sk)->addr && (err = unix_autobind(sock)) != 0)
goto out;
restart:
other = unix_find_other(net, sunaddr, alen, sock->type, hash, &err);
if (!other)
goto out;
unix_state_double_lock(sk, other);
/* Apparently VFS overslept socket death. Retry. */
if (sock_flag(other, SOCK_DEAD)) {
unix_state_double_unlock(sk, other);
sock_put(other);
goto restart;
}
err = -EPERM;
if (!unix_may_send(sk, other))
goto out_unlock;
err = security_unix_may_send(sk->sk_socket, other->sk_socket);
if (err)
goto out_unlock;
} else {
/*
* 1003.1g breaking connected state with AF_UNSPEC
*/
other = NULL;
unix_state_double_lock(sk, other);
}
/*
* If it was connected, reconnect.
*/
if (unix_peer(sk)) {
struct sock *old_peer = unix_peer(sk);
unix_peer(sk) = other;
unix_dgram_peer_wake_disconnect_wakeup(sk, old_peer);
unix_state_double_unlock(sk, other);
if (other != old_peer)
unix_dgram_disconnected(sk, old_peer);
sock_put(old_peer);
} else {
unix_peer(sk) = other;
unix_state_double_unlock(sk, other);
}
return 0;
out_unlock:
unix_state_double_unlock(sk, other);
sock_put(other);
out:
return err;
}
static long unix_wait_for_peer(struct sock *other, long timeo)
{
struct unix_sock *u = unix_sk(other);
int sched;
DEFINE_WAIT(wait);
prepare_to_wait_exclusive(&u->peer_wait, &wait, TASK_INTERRUPTIBLE);
sched = !sock_flag(other, SOCK_DEAD) &&
!(other->sk_shutdown & RCV_SHUTDOWN) &&
unix_recvq_full(other);
unix_state_unlock(other);
if (sched)
timeo = schedule_timeout(timeo);
finish_wait(&u->peer_wait, &wait);
return timeo;
}
static int unix_stream_connect(struct socket *sock, struct sockaddr *uaddr,
int addr_len, int flags)
{
struct sockaddr_un *sunaddr = (struct sockaddr_un *)uaddr;
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct unix_sock *u = unix_sk(sk), *newu, *otheru;
struct sock *newsk = NULL;
struct sock *other = NULL;
struct sk_buff *skb = NULL;
unsigned int hash;
int st;
int err;
long timeo;
err = unix_mkname(sunaddr, addr_len, &hash);
if (err < 0)
goto out;
addr_len = err;
if (test_bit(SOCK_PASSCRED, &sock->flags) && !u->addr &&
(err = unix_autobind(sock)) != 0)
goto out;
timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
/* First of all allocate resources.
If we will make it after state is locked,
we will have to recheck all again in any case.
*/
err = -ENOMEM;
/* create new sock for complete connection */
newsk = unix_create1(sock_net(sk), NULL, 0);
if (newsk == NULL)
goto out;
/* Allocate skb for sending to listening sock */
skb = sock_wmalloc(newsk, 1, 0, GFP_KERNEL);
if (skb == NULL)
goto out;
restart:
/* Find listening sock. */
other = unix_find_other(net, sunaddr, addr_len, sk->sk_type, hash, &err);
if (!other)
goto out;
/* Latch state of peer */
unix_state_lock(other);
/* Apparently VFS overslept socket death. Retry. */
if (sock_flag(other, SOCK_DEAD)) {
unix_state_unlock(other);
sock_put(other);
goto restart;
}
err = -ECONNREFUSED;
if (other->sk_state != TCP_LISTEN)
goto out_unlock;
if (other->sk_shutdown & RCV_SHUTDOWN)
goto out_unlock;
if (unix_recvq_full(other)) {
err = -EAGAIN;
if (!timeo)
goto out_unlock;
timeo = unix_wait_for_peer(other, timeo);
err = sock_intr_errno(timeo);
if (signal_pending(current))
goto out;
sock_put(other);
goto restart;
}
/* Latch our state.
It is tricky place. We need to grab our state lock and cannot
drop lock on peer. It is dangerous because deadlock is
possible. Connect to self case and simultaneous
attempt to connect are eliminated by checking socket
state. other is TCP_LISTEN, if sk is TCP_LISTEN we
check this before attempt to grab lock.
Well, and we have to recheck the state after socket locked.
*/
st = sk->sk_state;
switch (st) {
case TCP_CLOSE:
/* This is ok... continue with connect */
break;
case TCP_ESTABLISHED:
/* Socket is already connected */
err = -EISCONN;
goto out_unlock;
default:
err = -EINVAL;
goto out_unlock;
}
unix_state_lock_nested(sk);
if (sk->sk_state != st) {
unix_state_unlock(sk);
unix_state_unlock(other);
sock_put(other);
goto restart;
}
err = security_unix_stream_connect(sk, other, newsk);
if (err) {
unix_state_unlock(sk);
goto out_unlock;
}
/* The way is open! Fastly set all the necessary fields... */
sock_hold(sk);
unix_peer(newsk) = sk;
newsk->sk_state = TCP_ESTABLISHED;
newsk->sk_type = sk->sk_type;
init_peercred(newsk);
newu = unix_sk(newsk);
RCU_INIT_POINTER(newsk->sk_wq, &newu->peer_wq);
otheru = unix_sk(other);
/* copy address information from listening to new sock*/
if (otheru->addr) {
atomic_inc(&otheru->addr->refcnt);
newu->addr = otheru->addr;
}
if (otheru->path.dentry) {
path_get(&otheru->path);
newu->path = otheru->path;
}
/* Set credentials */
copy_peercred(sk, other);
sock->state = SS_CONNECTED;
sk->sk_state = TCP_ESTABLISHED;
sock_hold(newsk);
smp_mb__after_atomic(); /* sock_hold() does an atomic_inc() */
unix_peer(sk) = newsk;
unix_state_unlock(sk);
/* take ten and and send info to listening sock */
spin_lock(&other->sk_receive_queue.lock);
__skb_queue_tail(&other->sk_receive_queue, skb);
spin_unlock(&other->sk_receive_queue.lock);
unix_state_unlock(other);
other->sk_data_ready(other);
sock_put(other);
return 0;
out_unlock:
if (other)
unix_state_unlock(other);
out:
kfree_skb(skb);
if (newsk)
unix_release_sock(newsk, 0);
if (other)
sock_put(other);
return err;
}
static int unix_socketpair(struct socket *socka, struct socket *sockb)
{
struct sock *ska = socka->sk, *skb = sockb->sk;
/* Join our sockets back to back */
sock_hold(ska);
sock_hold(skb);
unix_peer(ska) = skb;
unix_peer(skb) = ska;
init_peercred(ska);
init_peercred(skb);
if (ska->sk_type != SOCK_DGRAM) {
ska->sk_state = TCP_ESTABLISHED;
skb->sk_state = TCP_ESTABLISHED;
socka->state = SS_CONNECTED;
sockb->state = SS_CONNECTED;
}
return 0;
}
static void unix_sock_inherit_flags(const struct socket *old,
struct socket *new)
{
if (test_bit(SOCK_PASSCRED, &old->flags))
set_bit(SOCK_PASSCRED, &new->flags);
if (test_bit(SOCK_PASSSEC, &old->flags))
set_bit(SOCK_PASSSEC, &new->flags);
}
static int unix_accept(struct socket *sock, struct socket *newsock, int flags)
{
struct sock *sk = sock->sk;
struct sock *tsk;
struct sk_buff *skb;
int err;
err = -EOPNOTSUPP;
if (sock->type != SOCK_STREAM && sock->type != SOCK_SEQPACKET)
goto out;
err = -EINVAL;
if (sk->sk_state != TCP_LISTEN)
goto out;
/* If socket state is TCP_LISTEN it cannot change (for now...),
* so that no locks are necessary.
*/
skb = skb_recv_datagram(sk, 0, flags&O_NONBLOCK, &err);
if (!skb) {
/* This means receive shutdown. */
if (err == 0)
err = -EINVAL;
goto out;
}
tsk = skb->sk;
skb_free_datagram(sk, skb);
wake_up_interruptible(&unix_sk(sk)->peer_wait);
/* attach accepted sock to socket */
unix_state_lock(tsk);
newsock->state = SS_CONNECTED;
unix_sock_inherit_flags(sock, newsock);
sock_graft(tsk, newsock);
unix_state_unlock(tsk);
return 0;
out:
return err;
}
static int unix_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer)
{
struct sock *sk = sock->sk;
struct unix_sock *u;
DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr, uaddr);
int err = 0;
if (peer) {
sk = unix_peer_get(sk);
err = -ENOTCONN;
if (!sk)
goto out;
err = 0;
} else {
sock_hold(sk);
}
u = unix_sk(sk);
unix_state_lock(sk);
if (!u->addr) {
sunaddr->sun_family = AF_UNIX;
sunaddr->sun_path[0] = 0;
*uaddr_len = sizeof(short);
} else {
struct unix_address *addr = u->addr;
*uaddr_len = addr->len;
memcpy(sunaddr, addr->name, *uaddr_len);
}
unix_state_unlock(sk);
sock_put(sk);
out:
return err;
}
static void unix_detach_fds(struct scm_cookie *scm, struct sk_buff *skb)
{
int i;
scm->fp = UNIXCB(skb).fp;
UNIXCB(skb).fp = NULL;
for (i = scm->fp->count-1; i >= 0; i--)
unix_notinflight(scm->fp->fp[i]);
}
static void unix_destruct_scm(struct sk_buff *skb)
{
struct scm_cookie scm;
memset(&scm, 0, sizeof(scm));
scm.pid = UNIXCB(skb).pid;
if (UNIXCB(skb).fp)
unix_detach_fds(&scm, skb);
/* Alas, it calls VFS */
/* So fscking what? fput() had been SMP-safe since the last Summer */
scm_destroy(&scm);
sock_wfree(skb);
}
#define MAX_RECURSION_LEVEL 4
static int unix_attach_fds(struct scm_cookie *scm, struct sk_buff *skb)
{
int i;
unsigned char max_level = 0;
int unix_sock_count = 0;
for (i = scm->fp->count - 1; i >= 0; i--) {
struct sock *sk = unix_get_socket(scm->fp->fp[i]);
if (sk) {
unix_sock_count++;
max_level = max(max_level,
unix_sk(sk)->recursion_level);
}
}
if (unlikely(max_level > MAX_RECURSION_LEVEL))
return -ETOOMANYREFS;
/*
* Need to duplicate file references for the sake of garbage
* collection. Otherwise a socket in the fps might become a
* candidate for GC while the skb is not yet queued.
*/
UNIXCB(skb).fp = scm_fp_dup(scm->fp);
if (!UNIXCB(skb).fp)
return -ENOMEM;
if (unix_sock_count) {
for (i = scm->fp->count - 1; i >= 0; i--)
unix_inflight(scm->fp->fp[i]);
}
return max_level;
}
static int unix_scm_to_skb(struct scm_cookie *scm, struct sk_buff *skb, bool send_fds)
{
int err = 0;
UNIXCB(skb).pid = get_pid(scm->pid);
UNIXCB(skb).uid = scm->creds.uid;
UNIXCB(skb).gid = scm->creds.gid;
UNIXCB(skb).fp = NULL;
unix_get_secdata(scm, skb);
if (scm->fp && send_fds)
err = unix_attach_fds(scm, skb);
skb->destructor = unix_destruct_scm;
return err;
}
static bool unix_passcred_enabled(const struct socket *sock,
const struct sock *other)
{
return test_bit(SOCK_PASSCRED, &sock->flags) ||
!other->sk_socket ||
test_bit(SOCK_PASSCRED, &other->sk_socket->flags);
}
/*
* Some apps rely on write() giving SCM_CREDENTIALS
* We include credentials if source or destination socket
* asserted SOCK_PASSCRED.
*/
static void maybe_add_creds(struct sk_buff *skb, const struct socket *sock,
const struct sock *other)
{
if (UNIXCB(skb).pid)
return;
if (unix_passcred_enabled(sock, other)) {
UNIXCB(skb).pid = get_pid(task_tgid(current));
current_uid_gid(&UNIXCB(skb).uid, &UNIXCB(skb).gid);
}
}
static int maybe_init_creds(struct scm_cookie *scm,
struct socket *socket,
const struct sock *other)
{
int err;
struct msghdr msg = { .msg_controllen = 0 };
err = scm_send(socket, &msg, scm, false);
if (err)
return err;
if (unix_passcred_enabled(socket, other)) {
scm->pid = get_pid(task_tgid(current));
current_uid_gid(&scm->creds.uid, &scm->creds.gid);
}
return err;
}
static bool unix_skb_scm_eq(struct sk_buff *skb,
struct scm_cookie *scm)
{
const struct unix_skb_parms *u = &UNIXCB(skb);
return u->pid == scm->pid &&
uid_eq(u->uid, scm->creds.uid) &&
gid_eq(u->gid, scm->creds.gid) &&
unix_secdata_eq(scm, skb);
}
/*
* Send AF_UNIX data.
*/
static int unix_dgram_sendmsg(struct socket *sock, struct msghdr *msg,
size_t len)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct unix_sock *u = unix_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr, msg->msg_name);
struct sock *other = NULL;
int namelen = 0; /* fake GCC */
int err;
unsigned int hash;
struct sk_buff *skb;
long timeo;
struct scm_cookie scm;
int max_level;
int data_len = 0;
int sk_locked;
wait_for_unix_gc();
err = scm_send(sock, msg, &scm, false);
if (err < 0)
return err;
err = -EOPNOTSUPP;
if (msg->msg_flags&MSG_OOB)
goto out;
if (msg->msg_namelen) {
err = unix_mkname(sunaddr, msg->msg_namelen, &hash);
if (err < 0)
goto out;
namelen = err;
} else {
sunaddr = NULL;
err = -ENOTCONN;
other = unix_peer_get(sk);
if (!other)
goto out;
}
if (test_bit(SOCK_PASSCRED, &sock->flags) && !u->addr
&& (err = unix_autobind(sock)) != 0)
goto out;
err = -EMSGSIZE;
if (len > sk->sk_sndbuf - 32)
goto out;
if (len > SKB_MAX_ALLOC) {
data_len = min_t(size_t,
len - SKB_MAX_ALLOC,
MAX_SKB_FRAGS * PAGE_SIZE);
data_len = PAGE_ALIGN(data_len);
BUILD_BUG_ON(SKB_MAX_ALLOC < PAGE_SIZE);
}
skb = sock_alloc_send_pskb(sk, len - data_len, data_len,
msg->msg_flags & MSG_DONTWAIT, &err,
PAGE_ALLOC_COSTLY_ORDER);
if (skb == NULL)
goto out;
err = unix_scm_to_skb(&scm, skb, true);
if (err < 0)
goto out_free;
max_level = err + 1;
skb_put(skb, len - data_len);
skb->data_len = data_len;
skb->len = len;
err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, len);
if (err)
goto out_free;
timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
restart:
if (!other) {
err = -ECONNRESET;
if (sunaddr == NULL)
goto out_free;
other = unix_find_other(net, sunaddr, namelen, sk->sk_type,
hash, &err);
if (other == NULL)
goto out_free;
}
if (sk_filter(other, skb) < 0) {
/* Toss the packet but do not return any error to the sender */
err = len;
goto out_free;
}
sk_locked = 0;
unix_state_lock(other);
restart_locked:
err = -EPERM;
if (!unix_may_send(sk, other))
goto out_unlock;
if (unlikely(sock_flag(other, SOCK_DEAD))) {
/*
* Check with 1003.1g - what should
* datagram error
*/
unix_state_unlock(other);
sock_put(other);
if (!sk_locked)
unix_state_lock(sk);
err = 0;
if (unix_peer(sk) == other) {
unix_peer(sk) = NULL;
unix_dgram_peer_wake_disconnect_wakeup(sk, other);
unix_state_unlock(sk);
unix_dgram_disconnected(sk, other);
sock_put(other);
err = -ECONNREFUSED;
} else {
unix_state_unlock(sk);
}
other = NULL;
if (err)
goto out_free;
goto restart;
}
err = -EPIPE;
if (other->sk_shutdown & RCV_SHUTDOWN)
goto out_unlock;
if (sk->sk_type != SOCK_SEQPACKET) {
err = security_unix_may_send(sk->sk_socket, other->sk_socket);
if (err)
goto out_unlock;
}
if (unlikely(unix_peer(other) != sk && unix_recvq_full(other))) {
if (timeo) {
timeo = unix_wait_for_peer(other, timeo);
err = sock_intr_errno(timeo);
if (signal_pending(current))
goto out_free;
goto restart;
}
if (!sk_locked) {
unix_state_unlock(other);
unix_state_double_lock(sk, other);
}
if (unix_peer(sk) != other ||
unix_dgram_peer_wake_me(sk, other)) {
err = -EAGAIN;
sk_locked = 1;
goto out_unlock;
}
if (!sk_locked) {
sk_locked = 1;
goto restart_locked;
}
}
if (unlikely(sk_locked))
unix_state_unlock(sk);
if (sock_flag(other, SOCK_RCVTSTAMP))
__net_timestamp(skb);
maybe_add_creds(skb, sock, other);
skb_queue_tail(&other->sk_receive_queue, skb);
if (max_level > unix_sk(other)->recursion_level)
unix_sk(other)->recursion_level = max_level;
unix_state_unlock(other);
other->sk_data_ready(other);
sock_put(other);
scm_destroy(&scm);
return len;
out_unlock:
if (sk_locked)
unix_state_unlock(sk);
unix_state_unlock(other);
out_free:
kfree_skb(skb);
out:
if (other)
sock_put(other);
scm_destroy(&scm);
return err;
}
/* We use paged skbs for stream sockets, and limit occupancy to 32768
* bytes, and a minimun of a full page.
*/
#define UNIX_SKB_FRAGS_SZ (PAGE_SIZE << get_order(32768))
static int unix_stream_sendmsg(struct socket *sock, struct msghdr *msg,
size_t len)
{
struct sock *sk = sock->sk;
struct sock *other = NULL;
int err, size;
struct sk_buff *skb;
int sent = 0;
struct scm_cookie scm;
bool fds_sent = false;
int max_level;
int data_len;
wait_for_unix_gc();
err = scm_send(sock, msg, &scm, false);
if (err < 0)
return err;
err = -EOPNOTSUPP;
if (msg->msg_flags&MSG_OOB)
goto out_err;
if (msg->msg_namelen) {
err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
goto out_err;
} else {
err = -ENOTCONN;
other = unix_peer(sk);
if (!other)
goto out_err;
}
if (sk->sk_shutdown & SEND_SHUTDOWN)
goto pipe_err;
while (sent < len) {
size = len - sent;
/* Keep two messages in the pipe so it schedules better */
size = min_t(int, size, (sk->sk_sndbuf >> 1) - 64);
/* allow fallback to order-0 allocations */
size = min_t(int, size, SKB_MAX_HEAD(0) + UNIX_SKB_FRAGS_SZ);
data_len = max_t(int, 0, size - SKB_MAX_HEAD(0));
data_len = min_t(size_t, size, PAGE_ALIGN(data_len));
skb = sock_alloc_send_pskb(sk, size - data_len, data_len,
msg->msg_flags & MSG_DONTWAIT, &err,
get_order(UNIX_SKB_FRAGS_SZ));
if (!skb)
goto out_err;
/* Only send the fds in the first buffer */
err = unix_scm_to_skb(&scm, skb, !fds_sent);
if (err < 0) {
kfree_skb(skb);
goto out_err;
}
max_level = err + 1;
fds_sent = true;
skb_put(skb, size - data_len);
skb->data_len = data_len;
skb->len = size;
err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, size);
if (err) {
kfree_skb(skb);
goto out_err;
}
unix_state_lock(other);
if (sock_flag(other, SOCK_DEAD) ||
(other->sk_shutdown & RCV_SHUTDOWN))
goto pipe_err_free;
maybe_add_creds(skb, sock, other);
skb_queue_tail(&other->sk_receive_queue, skb);
if (max_level > unix_sk(other)->recursion_level)
unix_sk(other)->recursion_level = max_level;
unix_state_unlock(other);
other->sk_data_ready(other);
sent += size;
}
scm_destroy(&scm);
return sent;
pipe_err_free:
unix_state_unlock(other);
kfree_skb(skb);
pipe_err:
if (sent == 0 && !(msg->msg_flags&MSG_NOSIGNAL))
send_sig(SIGPIPE, current, 0);
err = -EPIPE;
out_err:
scm_destroy(&scm);
return sent ? : err;
}
static ssize_t unix_stream_sendpage(struct socket *socket, struct page *page,
int offset, size_t size, int flags)
{
int err;
bool send_sigpipe = false;
bool init_scm = true;
struct scm_cookie scm;
struct sock *other, *sk = socket->sk;
struct sk_buff *skb, *newskb = NULL, *tail = NULL;
if (flags & MSG_OOB)
return -EOPNOTSUPP;
other = unix_peer(sk);
if (!other || sk->sk_state != TCP_ESTABLISHED)
return -ENOTCONN;
if (false) {
alloc_skb:
unix_state_unlock(other);
mutex_unlock(&unix_sk(other)->readlock);
newskb = sock_alloc_send_pskb(sk, 0, 0, flags & MSG_DONTWAIT,
&err, 0);
if (!newskb)
goto err;
}
/* we must acquire readlock as we modify already present
* skbs in the sk_receive_queue and mess with skb->len
*/
err = mutex_lock_interruptible(&unix_sk(other)->readlock);
if (err) {
err = flags & MSG_DONTWAIT ? -EAGAIN : -ERESTARTSYS;
goto err;
}
if (sk->sk_shutdown & SEND_SHUTDOWN) {
err = -EPIPE;
send_sigpipe = true;
goto err_unlock;
}
unix_state_lock(other);
if (sock_flag(other, SOCK_DEAD) ||
other->sk_shutdown & RCV_SHUTDOWN) {
err = -EPIPE;
send_sigpipe = true;
goto err_state_unlock;
}
if (init_scm) {
err = maybe_init_creds(&scm, socket, other);
if (err)
goto err_state_unlock;
init_scm = false;
}
skb = skb_peek_tail(&other->sk_receive_queue);
if (tail && tail == skb) {
skb = newskb;
} else if (!skb || !unix_skb_scm_eq(skb, &scm)) {
if (newskb) {
skb = newskb;
} else {
tail = skb;
goto alloc_skb;
}
} else if (newskb) {
/* this is fast path, we don't necessarily need to
* call to kfree_skb even though with newskb == NULL
* this - does no harm
*/
consume_skb(newskb);
newskb = NULL;
}
if (skb_append_pagefrags(skb, page, offset, size)) {
tail = skb;
goto alloc_skb;
}
skb->len += size;
skb->data_len += size;
skb->truesize += size;
atomic_add(size, &sk->sk_wmem_alloc);
if (newskb) {
err = unix_scm_to_skb(&scm, skb, false);
if (err)
goto err_state_unlock;
spin_lock(&other->sk_receive_queue.lock);
__skb_queue_tail(&other->sk_receive_queue, newskb);
spin_unlock(&other->sk_receive_queue.lock);
}
unix_state_unlock(other);
mutex_unlock(&unix_sk(other)->readlock);
other->sk_data_ready(other);
scm_destroy(&scm);
return size;
err_state_unlock:
unix_state_unlock(other);
err_unlock:
mutex_unlock(&unix_sk(other)->readlock);
err:
kfree_skb(newskb);
if (send_sigpipe && !(flags & MSG_NOSIGNAL))
send_sig(SIGPIPE, current, 0);
if (!init_scm)
scm_destroy(&scm);
return err;
}
static int unix_seqpacket_sendmsg(struct socket *sock, struct msghdr *msg,
size_t len)
{
int err;
struct sock *sk = sock->sk;
err = sock_error(sk);
if (err)
return err;
if (sk->sk_state != TCP_ESTABLISHED)
return -ENOTCONN;
if (msg->msg_namelen)
msg->msg_namelen = 0;
return unix_dgram_sendmsg(sock, msg, len);
}
static int unix_seqpacket_recvmsg(struct socket *sock, struct msghdr *msg,
size_t size, int flags)
{
struct sock *sk = sock->sk;
if (sk->sk_state != TCP_ESTABLISHED)
return -ENOTCONN;
return unix_dgram_recvmsg(sock, msg, size, flags);
}
static void unix_copy_addr(struct msghdr *msg, struct sock *sk)
{
struct unix_sock *u = unix_sk(sk);
if (u->addr) {
msg->msg_namelen = u->addr->len;
memcpy(msg->msg_name, u->addr->name, u->addr->len);
}
}
static int unix_dgram_recvmsg(struct socket *sock, struct msghdr *msg,
size_t size, int flags)
{
struct scm_cookie scm;
struct sock *sk = sock->sk;
struct unix_sock *u = unix_sk(sk);
int noblock = flags & MSG_DONTWAIT;
struct sk_buff *skb;
int err;
int peeked, skip;
err = -EOPNOTSUPP;
if (flags&MSG_OOB)
goto out;
err = mutex_lock_interruptible(&u->readlock);
if (unlikely(err)) {
/* recvmsg() in non blocking mode is supposed to return -EAGAIN
* sk_rcvtimeo is not honored by mutex_lock_interruptible()
*/
err = noblock ? -EAGAIN : -ERESTARTSYS;
goto out;
}
skip = sk_peek_offset(sk, flags);
skb = __skb_recv_datagram(sk, flags, &peeked, &skip, &err);
if (!skb) {
unix_state_lock(sk);
/* Signal EOF on disconnected non-blocking SEQPACKET socket. */
if (sk->sk_type == SOCK_SEQPACKET && err == -EAGAIN &&
(sk->sk_shutdown & RCV_SHUTDOWN))
err = 0;
unix_state_unlock(sk);
goto out_unlock;
}
wake_up_interruptible_sync_poll(&u->peer_wait,
POLLOUT | POLLWRNORM | POLLWRBAND);
if (msg->msg_name)
unix_copy_addr(msg, skb->sk);
if (size > skb->len - skip)
size = skb->len - skip;
else if (size < skb->len - skip)
msg->msg_flags |= MSG_TRUNC;
err = skb_copy_datagram_msg(skb, skip, msg, size);
if (err)
goto out_free;
if (sock_flag(sk, SOCK_RCVTSTAMP))
__sock_recv_timestamp(msg, sk, skb);
memset(&scm, 0, sizeof(scm));
scm_set_cred(&scm, UNIXCB(skb).pid, UNIXCB(skb).uid, UNIXCB(skb).gid);
unix_set_secdata(&scm, skb);
if (!(flags & MSG_PEEK)) {
if (UNIXCB(skb).fp)
unix_detach_fds(&scm, skb);
sk_peek_offset_bwd(sk, skb->len);
} else {
/* It is questionable: on PEEK we could:
- do not return fds - good, but too simple 8)
- return fds, and do not return them on read (old strategy,
apparently wrong)
- clone fds (I chose it for now, it is the most universal
solution)
POSIX 1003.1g does not actually define this clearly
at all. POSIX 1003.1g doesn't define a lot of things
clearly however!
*/
sk_peek_offset_fwd(sk, size);
if (UNIXCB(skb).fp)
scm.fp = scm_fp_dup(UNIXCB(skb).fp);
}
err = (flags & MSG_TRUNC) ? skb->len - skip : size;
scm_recv(sock, msg, &scm, flags);
out_free:
skb_free_datagram(sk, skb);
out_unlock:
mutex_unlock(&u->readlock);
out:
return err;
}
/*
* Sleep until more data has arrived. But check for races..
*/
static long unix_stream_data_wait(struct sock *sk, long timeo,
struct sk_buff *last, unsigned int last_len)
{
struct sk_buff *tail;
DEFINE_WAIT(wait);
unix_state_lock(sk);
for (;;) {
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
tail = skb_peek_tail(&sk->sk_receive_queue);
if (tail != last ||
(tail && tail->len != last_len) ||
sk->sk_err ||
(sk->sk_shutdown & RCV_SHUTDOWN) ||
signal_pending(current) ||
!timeo)
break;
sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
unix_state_unlock(sk);
timeo = freezable_schedule_timeout(timeo);
unix_state_lock(sk);
if (sock_flag(sk, SOCK_DEAD))
break;
sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
}
finish_wait(sk_sleep(sk), &wait);
unix_state_unlock(sk);
return timeo;
}
static unsigned int unix_skb_len(const struct sk_buff *skb)
{
return skb->len - UNIXCB(skb).consumed;
}
struct unix_stream_read_state {
int (*recv_actor)(struct sk_buff *, int, int,
struct unix_stream_read_state *);
struct socket *socket;
struct msghdr *msg;
struct pipe_inode_info *pipe;
size_t size;
int flags;
unsigned int splice_flags;
};
static int unix_stream_read_generic(struct unix_stream_read_state *state)
{
struct scm_cookie scm;
struct socket *sock = state->socket;
struct sock *sk = sock->sk;
struct unix_sock *u = unix_sk(sk);
int copied = 0;
int flags = state->flags;
int noblock = flags & MSG_DONTWAIT;
bool check_creds = false;
int target;
int err = 0;
long timeo;
int skip;
size_t size = state->size;
unsigned int last_len;
err = -EINVAL;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
err = -EOPNOTSUPP;
if (flags & MSG_OOB)
goto out;
target = sock_rcvlowat(sk, flags & MSG_WAITALL, size);
timeo = sock_rcvtimeo(sk, noblock);
memset(&scm, 0, sizeof(scm));
/* Lock the socket to prevent queue disordering
* while sleeps in memcpy_tomsg
*/
mutex_lock(&u->readlock);
if (flags & MSG_PEEK)
skip = sk_peek_offset(sk, flags);
else
skip = 0;
do {
int chunk;
bool drop_skb;
struct sk_buff *skb, *last;
unix_state_lock(sk);
if (sock_flag(sk, SOCK_DEAD)) {
err = -ECONNRESET;
goto unlock;
}
last = skb = skb_peek(&sk->sk_receive_queue);
last_len = last ? last->len : 0;
again:
if (skb == NULL) {
unix_sk(sk)->recursion_level = 0;
if (copied >= target)
goto unlock;
/*
* POSIX 1003.1g mandates this order.
*/
err = sock_error(sk);
if (err)
goto unlock;
if (sk->sk_shutdown & RCV_SHUTDOWN)
goto unlock;
unix_state_unlock(sk);
err = -EAGAIN;
if (!timeo)
break;
mutex_unlock(&u->readlock);
timeo = unix_stream_data_wait(sk, timeo, last,
last_len);
if (signal_pending(current)) {
err = sock_intr_errno(timeo);
goto out;
}
mutex_lock(&u->readlock);
continue;
unlock:
unix_state_unlock(sk);
break;
}
while (skip >= unix_skb_len(skb)) {
skip -= unix_skb_len(skb);
last = skb;
last_len = skb->len;
skb = skb_peek_next(skb, &sk->sk_receive_queue);
if (!skb)
goto again;
}
unix_state_unlock(sk);
if (check_creds) {
/* Never glue messages from different writers */
if (!unix_skb_scm_eq(skb, &scm))
break;
} else if (test_bit(SOCK_PASSCRED, &sock->flags)) {
/* Copy credentials */
scm_set_cred(&scm, UNIXCB(skb).pid, UNIXCB(skb).uid, UNIXCB(skb).gid);
unix_set_secdata(&scm, skb);
check_creds = true;
}
/* Copy address just once */
if (state->msg && state->msg->msg_name) {
DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr,
state->msg->msg_name);
unix_copy_addr(state->msg, skb->sk);
sunaddr = NULL;
}
chunk = min_t(unsigned int, unix_skb_len(skb) - skip, size);
skb_get(skb);
chunk = state->recv_actor(skb, skip, chunk, state);
drop_skb = !unix_skb_len(skb);
/* skb is only safe to use if !drop_skb */
consume_skb(skb);
if (chunk < 0) {
if (copied == 0)
copied = -EFAULT;
break;
}
copied += chunk;
size -= chunk;
if (drop_skb) {
/* the skb was touched by a concurrent reader;
* we should not expect anything from this skb
* anymore and assume it invalid - we can be
* sure it was dropped from the socket queue
*
* let's report a short read
*/
err = 0;
break;
}
/* Mark read part of skb as used */
if (!(flags & MSG_PEEK)) {
UNIXCB(skb).consumed += chunk;
sk_peek_offset_bwd(sk, chunk);
if (UNIXCB(skb).fp)
unix_detach_fds(&scm, skb);
if (unix_skb_len(skb))
break;
skb_unlink(skb, &sk->sk_receive_queue);
consume_skb(skb);
if (scm.fp)
break;
} else {
/* It is questionable, see note in unix_dgram_recvmsg.
*/
if (UNIXCB(skb).fp)
scm.fp = scm_fp_dup(UNIXCB(skb).fp);
sk_peek_offset_fwd(sk, chunk);
if (UNIXCB(skb).fp)
break;
skip = 0;
last = skb;
last_len = skb->len;
unix_state_lock(sk);
skb = skb_peek_next(skb, &sk->sk_receive_queue);
if (skb)
goto again;
unix_state_unlock(sk);
break;
}
} while (size);
mutex_unlock(&u->readlock);
if (state->msg)
scm_recv(sock, state->msg, &scm, flags);
else
scm_destroy(&scm);
out:
return copied ? : err;
}
static int unix_stream_read_actor(struct sk_buff *skb,
int skip, int chunk,
struct unix_stream_read_state *state)
{
int ret;
ret = skb_copy_datagram_msg(skb, UNIXCB(skb).consumed + skip,
state->msg, chunk);
return ret ?: chunk;
}
static int unix_stream_recvmsg(struct socket *sock, struct msghdr *msg,
size_t size, int flags)
{
struct unix_stream_read_state state = {
.recv_actor = unix_stream_read_actor,
.socket = sock,
.msg = msg,
.size = size,
.flags = flags
};
return unix_stream_read_generic(&state);
}
static ssize_t skb_unix_socket_splice(struct sock *sk,
struct pipe_inode_info *pipe,
struct splice_pipe_desc *spd)
{
int ret;
struct unix_sock *u = unix_sk(sk);
mutex_unlock(&u->readlock);
ret = splice_to_pipe(pipe, spd);
mutex_lock(&u->readlock);
return ret;
}
static int unix_stream_splice_actor(struct sk_buff *skb,
int skip, int chunk,
struct unix_stream_read_state *state)
{
return skb_splice_bits(skb, state->socket->sk,
UNIXCB(skb).consumed + skip,
state->pipe, chunk, state->splice_flags,
skb_unix_socket_splice);
}
static ssize_t unix_stream_splice_read(struct socket *sock, loff_t *ppos,
struct pipe_inode_info *pipe,
size_t size, unsigned int flags)
{
struct unix_stream_read_state state = {
.recv_actor = unix_stream_splice_actor,
.socket = sock,
.pipe = pipe,
.size = size,
.splice_flags = flags,
};
if (unlikely(*ppos))
return -ESPIPE;
if (sock->file->f_flags & O_NONBLOCK ||
flags & SPLICE_F_NONBLOCK)
state.flags = MSG_DONTWAIT;
return unix_stream_read_generic(&state);
}
static int unix_shutdown(struct socket *sock, int mode)
{
struct sock *sk = sock->sk;
struct sock *other;
if (mode < SHUT_RD || mode > SHUT_RDWR)
return -EINVAL;
/* This maps:
* SHUT_RD (0) -> RCV_SHUTDOWN (1)
* SHUT_WR (1) -> SEND_SHUTDOWN (2)
* SHUT_RDWR (2) -> SHUTDOWN_MASK (3)
*/
++mode;
unix_state_lock(sk);
sk->sk_shutdown |= mode;
other = unix_peer(sk);
if (other)
sock_hold(other);
unix_state_unlock(sk);
sk->sk_state_change(sk);
if (other &&
(sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET)) {
int peer_mode = 0;
if (mode&RCV_SHUTDOWN)
peer_mode |= SEND_SHUTDOWN;
if (mode&SEND_SHUTDOWN)
peer_mode |= RCV_SHUTDOWN;
unix_state_lock(other);
other->sk_shutdown |= peer_mode;
unix_state_unlock(other);
other->sk_state_change(other);
if (peer_mode == SHUTDOWN_MASK)
sk_wake_async(other, SOCK_WAKE_WAITD, POLL_HUP);
else if (peer_mode & RCV_SHUTDOWN)
sk_wake_async(other, SOCK_WAKE_WAITD, POLL_IN);
}
if (other)
sock_put(other);
return 0;
}
long unix_inq_len(struct sock *sk)
{
struct sk_buff *skb;
long amount = 0;
if (sk->sk_state == TCP_LISTEN)
return -EINVAL;
spin_lock(&sk->sk_receive_queue.lock);
if (sk->sk_type == SOCK_STREAM ||
sk->sk_type == SOCK_SEQPACKET) {
skb_queue_walk(&sk->sk_receive_queue, skb)
amount += unix_skb_len(skb);
} else {
skb = skb_peek(&sk->sk_receive_queue);
if (skb)
amount = skb->len;
}
spin_unlock(&sk->sk_receive_queue.lock);
return amount;
}
EXPORT_SYMBOL_GPL(unix_inq_len);
long unix_outq_len(struct sock *sk)
{
return sk_wmem_alloc_get(sk);
}
EXPORT_SYMBOL_GPL(unix_outq_len);
static int unix_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct sock *sk = sock->sk;
long amount = 0;
int err;
switch (cmd) {
case SIOCOUTQ:
amount = unix_outq_len(sk);
err = put_user(amount, (int __user *)arg);
break;
case SIOCINQ:
amount = unix_inq_len(sk);
if (amount < 0)
err = amount;
else
err = put_user(amount, (int __user *)arg);
break;
default:
err = -ENOIOCTLCMD;
break;
}
return err;
}
static unsigned int unix_poll(struct file *file, struct socket *sock, poll_table *wait)
{
struct sock *sk = sock->sk;
unsigned int mask;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
/* exceptional events? */
if (sk->sk_err)
mask |= POLLERR;
if (sk->sk_shutdown == SHUTDOWN_MASK)
mask |= POLLHUP;
if (sk->sk_shutdown & RCV_SHUTDOWN)
mask |= POLLRDHUP | POLLIN | POLLRDNORM;
/* readable? */
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
/* Connection-based need to check for termination and startup */
if ((sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET) &&
sk->sk_state == TCP_CLOSE)
mask |= POLLHUP;
/*
* we set writable also when the other side has shut down the
* connection. This prevents stuck sockets.
*/
if (unix_writable(sk))
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
return mask;
}
static unsigned int unix_dgram_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk, *other;
unsigned int mask, writable;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
/* exceptional events? */
if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
mask |= POLLERR |
(sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? POLLPRI : 0);
if (sk->sk_shutdown & RCV_SHUTDOWN)
mask |= POLLRDHUP | POLLIN | POLLRDNORM;
if (sk->sk_shutdown == SHUTDOWN_MASK)
mask |= POLLHUP;
/* readable? */
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
/* Connection-based need to check for termination and startup */
if (sk->sk_type == SOCK_SEQPACKET) {
if (sk->sk_state == TCP_CLOSE)
mask |= POLLHUP;
/* connection hasn't started yet? */
if (sk->sk_state == TCP_SYN_SENT)
return mask;
}
/* No write status requested, avoid expensive OUT tests. */
if (!(poll_requested_events(wait) & (POLLWRBAND|POLLWRNORM|POLLOUT)))
return mask;
writable = unix_writable(sk);
if (writable) {
unix_state_lock(sk);
other = unix_peer(sk);
if (other && unix_peer(other) != sk &&
unix_recvq_full(other) &&
unix_dgram_peer_wake_me(sk, other))
writable = 0;
unix_state_unlock(sk);
}
if (writable)
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
else
sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
return mask;
}
#ifdef CONFIG_PROC_FS
#define BUCKET_SPACE (BITS_PER_LONG - (UNIX_HASH_BITS + 1) - 1)
#define get_bucket(x) ((x) >> BUCKET_SPACE)
#define get_offset(x) ((x) & ((1L << BUCKET_SPACE) - 1))
#define set_bucket_offset(b, o) ((b) << BUCKET_SPACE | (o))
static struct sock *unix_from_bucket(struct seq_file *seq, loff_t *pos)
{
unsigned long offset = get_offset(*pos);
unsigned long bucket = get_bucket(*pos);
struct sock *sk;
unsigned long count = 0;
for (sk = sk_head(&unix_socket_table[bucket]); sk; sk = sk_next(sk)) {
if (sock_net(sk) != seq_file_net(seq))
continue;
if (++count == offset)
break;
}
return sk;
}
static struct sock *unix_next_socket(struct seq_file *seq,
struct sock *sk,
loff_t *pos)
{
unsigned long bucket;
while (sk > (struct sock *)SEQ_START_TOKEN) {
sk = sk_next(sk);
if (!sk)
goto next_bucket;
if (sock_net(sk) == seq_file_net(seq))
return sk;
}
do {
sk = unix_from_bucket(seq, pos);
if (sk)
return sk;
next_bucket:
bucket = get_bucket(*pos) + 1;
*pos = set_bucket_offset(bucket, 1);
} while (bucket < ARRAY_SIZE(unix_socket_table));
return NULL;
}
static void *unix_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(unix_table_lock)
{
spin_lock(&unix_table_lock);
if (!*pos)
return SEQ_START_TOKEN;
if (get_bucket(*pos) >= ARRAY_SIZE(unix_socket_table))
return NULL;
return unix_next_socket(seq, NULL, pos);
}
static void *unix_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
++*pos;
return unix_next_socket(seq, v, pos);
}
static void unix_seq_stop(struct seq_file *seq, void *v)
__releases(unix_table_lock)
{
spin_unlock(&unix_table_lock);
}
static int unix_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_puts(seq, "Num RefCount Protocol Flags Type St "
"Inode Path\n");
else {
struct sock *s = v;
struct unix_sock *u = unix_sk(s);
unix_state_lock(s);
seq_printf(seq, "%pK: %08X %08X %08X %04X %02X %5lu",
s,
atomic_read(&s->sk_refcnt),
0,
s->sk_state == TCP_LISTEN ? __SO_ACCEPTCON : 0,
s->sk_type,
s->sk_socket ?
(s->sk_state == TCP_ESTABLISHED ? SS_CONNECTED : SS_UNCONNECTED) :
(s->sk_state == TCP_ESTABLISHED ? SS_CONNECTING : SS_DISCONNECTING),
sock_i_ino(s));
if (u->addr) {
int i, len;
seq_putc(seq, ' ');
i = 0;
len = u->addr->len - sizeof(short);
if (!UNIX_ABSTRACT(s))
len--;
else {
seq_putc(seq, '@');
i++;
}
for ( ; i < len; i++)
seq_putc(seq, u->addr->name->sun_path[i]);
}
unix_state_unlock(s);
seq_putc(seq, '\n');
}
return 0;
}
static const struct seq_operations unix_seq_ops = {
.start = unix_seq_start,
.next = unix_seq_next,
.stop = unix_seq_stop,
.show = unix_seq_show,
};
static int unix_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &unix_seq_ops,
sizeof(struct seq_net_private));
}
static const struct file_operations unix_seq_fops = {
.owner = THIS_MODULE,
.open = unix_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif
static const struct net_proto_family unix_family_ops = {
.family = PF_UNIX,
.create = unix_create,
.owner = THIS_MODULE,
};
static int __net_init unix_net_init(struct net *net)
{
int error = -ENOMEM;
net->unx.sysctl_max_dgram_qlen = 10;
if (unix_sysctl_register(net))
goto out;
#ifdef CONFIG_PROC_FS
if (!proc_create("unix", 0, net->proc_net, &unix_seq_fops)) {
unix_sysctl_unregister(net);
goto out;
}
#endif
error = 0;
out:
return error;
}
static void __net_exit unix_net_exit(struct net *net)
{
unix_sysctl_unregister(net);
remove_proc_entry("unix", net->proc_net);
}
static struct pernet_operations unix_net_ops = {
.init = unix_net_init,
.exit = unix_net_exit,
};
static int __init af_unix_init(void)
{
int rc = -1;
BUILD_BUG_ON(sizeof(struct unix_skb_parms) > FIELD_SIZEOF(struct sk_buff, cb));
rc = proto_register(&unix_proto, 1);
if (rc != 0) {
pr_crit("%s: Cannot create unix_sock SLAB cache!\n", __func__);
goto out;
}
sock_register(&unix_family_ops);
register_pernet_subsys(&unix_net_ops);
out:
return rc;
}
static void __exit af_unix_exit(void)
{
sock_unregister(PF_UNIX);
proto_unregister(&unix_proto);
unregister_pernet_subsys(&unix_net_ops);
}
/* Earlier than device_initcall() so that other drivers invoking
request_module() don't end up in a loop when modprobe tries
to use a UNIX socket. But later than subsys_initcall() because
we depend on stuff initialised there */
fs_initcall(af_unix_init);
module_exit(af_unix_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_UNIX);
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5740_1 |
crossvul-cpp_data_bad_2987_0 | /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
* Copyright (c) 2016 Facebook
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/bpf.h>
#include <linux/bpf_verifier.h>
#include <linux/filter.h>
#include <net/netlink.h>
#include <linux/file.h>
#include <linux/vmalloc.h>
#include <linux/stringify.h>
#include "disasm.h"
static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
#define BPF_PROG_TYPE(_id, _name) \
[_id] = & _name ## _verifier_ops,
#define BPF_MAP_TYPE(_id, _ops)
#include <linux/bpf_types.h>
#undef BPF_PROG_TYPE
#undef BPF_MAP_TYPE
};
/* bpf_check() is a static code analyzer that walks eBPF program
* instruction by instruction and updates register/stack state.
* All paths of conditional branches are analyzed until 'bpf_exit' insn.
*
* The first pass is depth-first-search to check that the program is a DAG.
* It rejects the following programs:
* - larger than BPF_MAXINSNS insns
* - if loop is present (detected via back-edge)
* - unreachable insns exist (shouldn't be a forest. program = one function)
* - out of bounds or malformed jumps
* The second pass is all possible path descent from the 1st insn.
* Since it's analyzing all pathes through the program, the length of the
* analysis is limited to 64k insn, which may be hit even if total number of
* insn is less then 4K, but there are too many branches that change stack/regs.
* Number of 'branches to be analyzed' is limited to 1k
*
* On entry to each instruction, each register has a type, and the instruction
* changes the types of the registers depending on instruction semantics.
* If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
* copied to R1.
*
* All registers are 64-bit.
* R0 - return register
* R1-R5 argument passing registers
* R6-R9 callee saved registers
* R10 - frame pointer read-only
*
* At the start of BPF program the register R1 contains a pointer to bpf_context
* and has type PTR_TO_CTX.
*
* Verifier tracks arithmetic operations on pointers in case:
* BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
* BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
* 1st insn copies R10 (which has FRAME_PTR) type into R1
* and 2nd arithmetic instruction is pattern matched to recognize
* that it wants to construct a pointer to some element within stack.
* So after 2nd insn, the register R1 has type PTR_TO_STACK
* (and -20 constant is saved for further stack bounds checking).
* Meaning that this reg is a pointer to stack plus known immediate constant.
*
* Most of the time the registers have SCALAR_VALUE type, which
* means the register has some value, but it's not a valid pointer.
* (like pointer plus pointer becomes SCALAR_VALUE type)
*
* When verifier sees load or store instructions the type of base register
* can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer
* types recognized by check_mem_access() function.
*
* PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
* and the range of [ptr, ptr + map's value_size) is accessible.
*
* registers used to pass values to function calls are checked against
* function argument constraints.
*
* ARG_PTR_TO_MAP_KEY is one of such argument constraints.
* It means that the register type passed to this function must be
* PTR_TO_STACK and it will be used inside the function as
* 'pointer to map element key'
*
* For example the argument constraints for bpf_map_lookup_elem():
* .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
* .arg1_type = ARG_CONST_MAP_PTR,
* .arg2_type = ARG_PTR_TO_MAP_KEY,
*
* ret_type says that this function returns 'pointer to map elem value or null'
* function expects 1st argument to be a const pointer to 'struct bpf_map' and
* 2nd argument should be a pointer to stack, which will be used inside
* the helper function as a pointer to map element key.
*
* On the kernel side the helper function looks like:
* u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
* {
* struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
* void *key = (void *) (unsigned long) r2;
* void *value;
*
* here kernel can access 'key' and 'map' pointers safely, knowing that
* [key, key + map->key_size) bytes are valid and were initialized on
* the stack of eBPF program.
* }
*
* Corresponding eBPF program may look like:
* BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
* BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
* BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
* BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
* here verifier looks at prototype of map_lookup_elem() and sees:
* .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
* Now verifier knows that this map has key of R1->map_ptr->key_size bytes
*
* Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
* Now verifier checks that [R2, R2 + map's key_size) are within stack limits
* and were initialized prior to this call.
* If it's ok, then verifier allows this BPF_CALL insn and looks at
* .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
* R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
* returns ether pointer to map value or NULL.
*
* When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
* insn, the register holding that pointer in the true branch changes state to
* PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
* branch. See check_cond_jmp_op().
*
* After the call R0 is set to return type of the function and registers R1-R5
* are set to NOT_INIT to indicate that they are no longer readable.
*/
/* verifier_state + insn_idx are pushed to stack when branch is encountered */
struct bpf_verifier_stack_elem {
/* verifer state is 'st'
* before processing instruction 'insn_idx'
* and after processing instruction 'prev_insn_idx'
*/
struct bpf_verifier_state st;
int insn_idx;
int prev_insn_idx;
struct bpf_verifier_stack_elem *next;
};
#define BPF_COMPLEXITY_LIMIT_INSNS 131072
#define BPF_COMPLEXITY_LIMIT_STACK 1024
#define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA)
struct bpf_call_arg_meta {
struct bpf_map *map_ptr;
bool raw_mode;
bool pkt_access;
int regno;
int access_size;
};
static DEFINE_MUTEX(bpf_verifier_lock);
/* log_level controls verbosity level of eBPF verifier.
* verbose() is used to dump the verification trace to the log, so the user
* can figure out what's wrong with the program
*/
static __printf(2, 3) void verbose(struct bpf_verifier_env *env,
const char *fmt, ...)
{
struct bpf_verifer_log *log = &env->log;
unsigned int n;
va_list args;
if (!log->level || !log->ubuf || bpf_verifier_log_full(log))
return;
va_start(args, fmt);
n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
va_end(args);
WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
"verifier log line truncated - local buffer too short\n");
n = min(log->len_total - log->len_used - 1, n);
log->kbuf[n] = '\0';
if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
log->len_used += n;
else
log->ubuf = NULL;
}
static bool type_is_pkt_pointer(enum bpf_reg_type type)
{
return type == PTR_TO_PACKET ||
type == PTR_TO_PACKET_META;
}
/* string representation of 'enum bpf_reg_type' */
static const char * const reg_type_str[] = {
[NOT_INIT] = "?",
[SCALAR_VALUE] = "inv",
[PTR_TO_CTX] = "ctx",
[CONST_PTR_TO_MAP] = "map_ptr",
[PTR_TO_MAP_VALUE] = "map_value",
[PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
[PTR_TO_STACK] = "fp",
[PTR_TO_PACKET] = "pkt",
[PTR_TO_PACKET_META] = "pkt_meta",
[PTR_TO_PACKET_END] = "pkt_end",
};
static void print_verifier_state(struct bpf_verifier_env *env,
struct bpf_verifier_state *state)
{
struct bpf_reg_state *reg;
enum bpf_reg_type t;
int i;
for (i = 0; i < MAX_BPF_REG; i++) {
reg = &state->regs[i];
t = reg->type;
if (t == NOT_INIT)
continue;
verbose(env, " R%d=%s", i, reg_type_str[t]);
if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
tnum_is_const(reg->var_off)) {
/* reg->off should be 0 for SCALAR_VALUE */
verbose(env, "%lld", reg->var_off.value + reg->off);
} else {
verbose(env, "(id=%d", reg->id);
if (t != SCALAR_VALUE)
verbose(env, ",off=%d", reg->off);
if (type_is_pkt_pointer(t))
verbose(env, ",r=%d", reg->range);
else if (t == CONST_PTR_TO_MAP ||
t == PTR_TO_MAP_VALUE ||
t == PTR_TO_MAP_VALUE_OR_NULL)
verbose(env, ",ks=%d,vs=%d",
reg->map_ptr->key_size,
reg->map_ptr->value_size);
if (tnum_is_const(reg->var_off)) {
/* Typically an immediate SCALAR_VALUE, but
* could be a pointer whose offset is too big
* for reg->off
*/
verbose(env, ",imm=%llx", reg->var_off.value);
} else {
if (reg->smin_value != reg->umin_value &&
reg->smin_value != S64_MIN)
verbose(env, ",smin_value=%lld",
(long long)reg->smin_value);
if (reg->smax_value != reg->umax_value &&
reg->smax_value != S64_MAX)
verbose(env, ",smax_value=%lld",
(long long)reg->smax_value);
if (reg->umin_value != 0)
verbose(env, ",umin_value=%llu",
(unsigned long long)reg->umin_value);
if (reg->umax_value != U64_MAX)
verbose(env, ",umax_value=%llu",
(unsigned long long)reg->umax_value);
if (!tnum_is_unknown(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, ",var_off=%s", tn_buf);
}
}
verbose(env, ")");
}
}
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] == STACK_SPILL)
verbose(env, " fp%d=%s",
-MAX_BPF_STACK + i * BPF_REG_SIZE,
reg_type_str[state->stack[i].spilled_ptr.type]);
}
verbose(env, "\n");
}
static int copy_stack_state(struct bpf_verifier_state *dst,
const struct bpf_verifier_state *src)
{
if (!src->stack)
return 0;
if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) {
/* internal bug, make state invalid to reject the program */
memset(dst, 0, sizeof(*dst));
return -EFAULT;
}
memcpy(dst->stack, src->stack,
sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE));
return 0;
}
/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
* make it consume minimal amount of memory. check_stack_write() access from
* the program calls into realloc_verifier_state() to grow the stack size.
* Note there is a non-zero 'parent' pointer inside bpf_verifier_state
* which this function copies over. It points to previous bpf_verifier_state
* which is never reallocated
*/
static int realloc_verifier_state(struct bpf_verifier_state *state, int size,
bool copy_old)
{
u32 old_size = state->allocated_stack;
struct bpf_stack_state *new_stack;
int slot = size / BPF_REG_SIZE;
if (size <= old_size || !size) {
if (copy_old)
return 0;
state->allocated_stack = slot * BPF_REG_SIZE;
if (!size && old_size) {
kfree(state->stack);
state->stack = NULL;
}
return 0;
}
new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state),
GFP_KERNEL);
if (!new_stack)
return -ENOMEM;
if (copy_old) {
if (state->stack)
memcpy(new_stack, state->stack,
sizeof(*new_stack) * (old_size / BPF_REG_SIZE));
memset(new_stack + old_size / BPF_REG_SIZE, 0,
sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE);
}
state->allocated_stack = slot * BPF_REG_SIZE;
kfree(state->stack);
state->stack = new_stack;
return 0;
}
static void free_verifier_state(struct bpf_verifier_state *state,
bool free_self)
{
kfree(state->stack);
if (free_self)
kfree(state);
}
/* copy verifier state from src to dst growing dst stack space
* when necessary to accommodate larger src stack
*/
static int copy_verifier_state(struct bpf_verifier_state *dst,
const struct bpf_verifier_state *src)
{
int err;
err = realloc_verifier_state(dst, src->allocated_stack, false);
if (err)
return err;
memcpy(dst, src, offsetof(struct bpf_verifier_state, allocated_stack));
return copy_stack_state(dst, src);
}
static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
int *insn_idx)
{
struct bpf_verifier_state *cur = env->cur_state;
struct bpf_verifier_stack_elem *elem, *head = env->head;
int err;
if (env->head == NULL)
return -ENOENT;
if (cur) {
err = copy_verifier_state(cur, &head->st);
if (err)
return err;
}
if (insn_idx)
*insn_idx = head->insn_idx;
if (prev_insn_idx)
*prev_insn_idx = head->prev_insn_idx;
elem = head->next;
free_verifier_state(&head->st, false);
kfree(head);
env->head = elem;
env->stack_size--;
return 0;
}
static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
int insn_idx, int prev_insn_idx)
{
struct bpf_verifier_state *cur = env->cur_state;
struct bpf_verifier_stack_elem *elem;
int err;
elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
if (!elem)
goto err;
elem->insn_idx = insn_idx;
elem->prev_insn_idx = prev_insn_idx;
elem->next = env->head;
env->head = elem;
env->stack_size++;
err = copy_verifier_state(&elem->st, cur);
if (err)
goto err;
if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
verbose(env, "BPF program is too complex\n");
goto err;
}
return &elem->st;
err:
/* pop all elements and return */
while (!pop_stack(env, NULL, NULL));
return NULL;
}
#define CALLER_SAVED_REGS 6
static const int caller_saved[CALLER_SAVED_REGS] = {
BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
};
static void __mark_reg_not_init(struct bpf_reg_state *reg);
/* Mark the unknown part of a register (variable offset or scalar value) as
* known to have the value @imm.
*/
static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
{
reg->id = 0;
reg->var_off = tnum_const(imm);
reg->smin_value = (s64)imm;
reg->smax_value = (s64)imm;
reg->umin_value = imm;
reg->umax_value = imm;
}
/* Mark the 'variable offset' part of a register as zero. This should be
* used only on registers holding a pointer type.
*/
static void __mark_reg_known_zero(struct bpf_reg_state *reg)
{
__mark_reg_known(reg, 0);
}
static void mark_reg_known_zero(struct bpf_verifier_env *env,
struct bpf_reg_state *regs, u32 regno)
{
if (WARN_ON(regno >= MAX_BPF_REG)) {
verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
/* Something bad happened, let's kill all regs */
for (regno = 0; regno < MAX_BPF_REG; regno++)
__mark_reg_not_init(regs + regno);
return;
}
__mark_reg_known_zero(regs + regno);
}
static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
{
return type_is_pkt_pointer(reg->type);
}
static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
{
return reg_is_pkt_pointer(reg) ||
reg->type == PTR_TO_PACKET_END;
}
/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
enum bpf_reg_type which)
{
/* The register can already have a range from prior markings.
* This is fine as long as it hasn't been advanced from its
* origin.
*/
return reg->type == which &&
reg->id == 0 &&
reg->off == 0 &&
tnum_equals_const(reg->var_off, 0);
}
/* Attempts to improve min/max values based on var_off information */
static void __update_reg_bounds(struct bpf_reg_state *reg)
{
/* min signed is max(sign bit) | min(other bits) */
reg->smin_value = max_t(s64, reg->smin_value,
reg->var_off.value | (reg->var_off.mask & S64_MIN));
/* max signed is min(sign bit) | max(other bits) */
reg->smax_value = min_t(s64, reg->smax_value,
reg->var_off.value | (reg->var_off.mask & S64_MAX));
reg->umin_value = max(reg->umin_value, reg->var_off.value);
reg->umax_value = min(reg->umax_value,
reg->var_off.value | reg->var_off.mask);
}
/* Uses signed min/max values to inform unsigned, and vice-versa */
static void __reg_deduce_bounds(struct bpf_reg_state *reg)
{
/* Learn sign from signed bounds.
* If we cannot cross the sign boundary, then signed and unsigned bounds
* are the same, so combine. This works even in the negative case, e.g.
* -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
*/
if (reg->smin_value >= 0 || reg->smax_value < 0) {
reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
reg->umin_value);
reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
reg->umax_value);
return;
}
/* Learn sign from unsigned bounds. Signed bounds cross the sign
* boundary, so we must be careful.
*/
if ((s64)reg->umax_value >= 0) {
/* Positive. We can't learn anything from the smin, but smax
* is positive, hence safe.
*/
reg->smin_value = reg->umin_value;
reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
reg->umax_value);
} else if ((s64)reg->umin_value < 0) {
/* Negative. We can't learn anything from the smax, but smin
* is negative, hence safe.
*/
reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
reg->umin_value);
reg->smax_value = reg->umax_value;
}
}
/* Attempts to improve var_off based on unsigned min/max information */
static void __reg_bound_offset(struct bpf_reg_state *reg)
{
reg->var_off = tnum_intersect(reg->var_off,
tnum_range(reg->umin_value,
reg->umax_value));
}
/* Reset the min/max bounds of a register */
static void __mark_reg_unbounded(struct bpf_reg_state *reg)
{
reg->smin_value = S64_MIN;
reg->smax_value = S64_MAX;
reg->umin_value = 0;
reg->umax_value = U64_MAX;
}
/* Mark a register as having a completely unknown (scalar) value. */
static void __mark_reg_unknown(struct bpf_reg_state *reg)
{
reg->type = SCALAR_VALUE;
reg->id = 0;
reg->off = 0;
reg->var_off = tnum_unknown;
__mark_reg_unbounded(reg);
}
static void mark_reg_unknown(struct bpf_verifier_env *env,
struct bpf_reg_state *regs, u32 regno)
{
if (WARN_ON(regno >= MAX_BPF_REG)) {
verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
/* Something bad happened, let's kill all regs */
for (regno = 0; regno < MAX_BPF_REG; regno++)
__mark_reg_not_init(regs + regno);
return;
}
__mark_reg_unknown(regs + regno);
}
static void __mark_reg_not_init(struct bpf_reg_state *reg)
{
__mark_reg_unknown(reg);
reg->type = NOT_INIT;
}
static void mark_reg_not_init(struct bpf_verifier_env *env,
struct bpf_reg_state *regs, u32 regno)
{
if (WARN_ON(regno >= MAX_BPF_REG)) {
verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
/* Something bad happened, let's kill all regs */
for (regno = 0; regno < MAX_BPF_REG; regno++)
__mark_reg_not_init(regs + regno);
return;
}
__mark_reg_not_init(regs + regno);
}
static void init_reg_state(struct bpf_verifier_env *env,
struct bpf_reg_state *regs)
{
int i;
for (i = 0; i < MAX_BPF_REG; i++) {
mark_reg_not_init(env, regs, i);
regs[i].live = REG_LIVE_NONE;
}
/* frame pointer */
regs[BPF_REG_FP].type = PTR_TO_STACK;
mark_reg_known_zero(env, regs, BPF_REG_FP);
/* 1st arg to a function */
regs[BPF_REG_1].type = PTR_TO_CTX;
mark_reg_known_zero(env, regs, BPF_REG_1);
}
enum reg_arg_type {
SRC_OP, /* register is used as source operand */
DST_OP, /* register is used as destination operand */
DST_OP_NO_MARK /* same as above, check only, don't mark */
};
static void mark_reg_read(const struct bpf_verifier_state *state, u32 regno)
{
struct bpf_verifier_state *parent = state->parent;
if (regno == BPF_REG_FP)
/* We don't need to worry about FP liveness because it's read-only */
return;
while (parent) {
/* if read wasn't screened by an earlier write ... */
if (state->regs[regno].live & REG_LIVE_WRITTEN)
break;
/* ... then we depend on parent's value */
parent->regs[regno].live |= REG_LIVE_READ;
state = parent;
parent = state->parent;
}
}
static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
enum reg_arg_type t)
{
struct bpf_reg_state *regs = env->cur_state->regs;
if (regno >= MAX_BPF_REG) {
verbose(env, "R%d is invalid\n", regno);
return -EINVAL;
}
if (t == SRC_OP) {
/* check whether register used as source operand can be read */
if (regs[regno].type == NOT_INIT) {
verbose(env, "R%d !read_ok\n", regno);
return -EACCES;
}
mark_reg_read(env->cur_state, regno);
} else {
/* check whether register used as dest operand can be written to */
if (regno == BPF_REG_FP) {
verbose(env, "frame pointer is read only\n");
return -EACCES;
}
regs[regno].live |= REG_LIVE_WRITTEN;
if (t == DST_OP)
mark_reg_unknown(env, regs, regno);
}
return 0;
}
static bool is_spillable_regtype(enum bpf_reg_type type)
{
switch (type) {
case PTR_TO_MAP_VALUE:
case PTR_TO_MAP_VALUE_OR_NULL:
case PTR_TO_STACK:
case PTR_TO_CTX:
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
case PTR_TO_PACKET_END:
case CONST_PTR_TO_MAP:
return true;
default:
return false;
}
}
/* check_stack_read/write functions track spill/fill of registers,
* stack boundary and alignment are checked in check_mem_access()
*/
static int check_stack_write(struct bpf_verifier_env *env,
struct bpf_verifier_state *state, int off,
int size, int value_regno)
{
int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
err = realloc_verifier_state(state, round_up(slot + 1, BPF_REG_SIZE),
true);
if (err)
return err;
/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
* so it's aligned access and [off, off + size) are within stack limits
*/
if (!env->allow_ptr_leaks &&
state->stack[spi].slot_type[0] == STACK_SPILL &&
size != BPF_REG_SIZE) {
verbose(env, "attempt to corrupt spilled pointer on stack\n");
return -EACCES;
}
if (value_regno >= 0 &&
is_spillable_regtype(state->regs[value_regno].type)) {
/* register containing pointer is being spilled into stack */
if (size != BPF_REG_SIZE) {
verbose(env, "invalid size of register spill\n");
return -EACCES;
}
/* save register state */
state->stack[spi].spilled_ptr = state->regs[value_regno];
state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
for (i = 0; i < BPF_REG_SIZE; i++)
state->stack[spi].slot_type[i] = STACK_SPILL;
} else {
/* regular write of data into stack */
state->stack[spi].spilled_ptr = (struct bpf_reg_state) {};
for (i = 0; i < size; i++)
state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
STACK_MISC;
}
return 0;
}
static void mark_stack_slot_read(const struct bpf_verifier_state *state, int slot)
{
struct bpf_verifier_state *parent = state->parent;
while (parent) {
/* if read wasn't screened by an earlier write ... */
if (state->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN)
break;
/* ... then we depend on parent's value */
parent->stack[slot].spilled_ptr.live |= REG_LIVE_READ;
state = parent;
parent = state->parent;
}
}
static int check_stack_read(struct bpf_verifier_env *env,
struct bpf_verifier_state *state, int off, int size,
int value_regno)
{
int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
u8 *stype;
if (state->allocated_stack <= slot) {
verbose(env, "invalid read from stack off %d+0 size %d\n",
off, size);
return -EACCES;
}
stype = state->stack[spi].slot_type;
if (stype[0] == STACK_SPILL) {
if (size != BPF_REG_SIZE) {
verbose(env, "invalid size of register spill\n");
return -EACCES;
}
for (i = 1; i < BPF_REG_SIZE; i++) {
if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
verbose(env, "corrupted spill memory\n");
return -EACCES;
}
}
if (value_regno >= 0) {
/* restore register state from stack */
state->regs[value_regno] = state->stack[spi].spilled_ptr;
mark_stack_slot_read(state, spi);
}
return 0;
} else {
for (i = 0; i < size; i++) {
if (stype[(slot - i) % BPF_REG_SIZE] != STACK_MISC) {
verbose(env, "invalid read from stack off %d+%d size %d\n",
off, i, size);
return -EACCES;
}
}
if (value_regno >= 0)
/* have read misc data from the stack */
mark_reg_unknown(env, state->regs, value_regno);
return 0;
}
}
/* check read/write into map element returned by bpf_map_lookup_elem() */
static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
int size, bool zero_size_allowed)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_map *map = regs[regno].map_ptr;
if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
off + size > map->value_size) {
verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
map->value_size, off, size);
return -EACCES;
}
return 0;
}
/* check read/write into a map element with possible variable offset */
static int check_map_access(struct bpf_verifier_env *env, u32 regno,
int off, int size, bool zero_size_allowed)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_reg_state *reg = &state->regs[regno];
int err;
/* We may have adjusted the register to this map value, so we
* need to try adding each of min_value and max_value to off
* to make sure our theoretical access will be safe.
*/
if (env->log.level)
print_verifier_state(env, state);
/* The minimum value is only important with signed
* comparisons where we can't assume the floor of a
* value is 0. If we are using signed variables for our
* index'es we need to make sure that whatever we use
* will have a set floor within our range.
*/
if (reg->smin_value < 0) {
verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
regno);
return -EACCES;
}
err = __check_map_access(env, regno, reg->smin_value + off, size,
zero_size_allowed);
if (err) {
verbose(env, "R%d min value is outside of the array range\n",
regno);
return err;
}
/* If we haven't set a max value then we need to bail since we can't be
* sure we won't do bad things.
* If reg->umax_value + off could overflow, treat that as unbounded too.
*/
if (reg->umax_value >= BPF_MAX_VAR_OFF) {
verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
regno);
return -EACCES;
}
err = __check_map_access(env, regno, reg->umax_value + off, size,
zero_size_allowed);
if (err)
verbose(env, "R%d max value is outside of the array range\n",
regno);
return err;
}
#define MAX_PACKET_OFF 0xffff
static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
const struct bpf_call_arg_meta *meta,
enum bpf_access_type t)
{
switch (env->prog->type) {
case BPF_PROG_TYPE_LWT_IN:
case BPF_PROG_TYPE_LWT_OUT:
/* dst_input() and dst_output() can't write for now */
if (t == BPF_WRITE)
return false;
/* fallthrough */
case BPF_PROG_TYPE_SCHED_CLS:
case BPF_PROG_TYPE_SCHED_ACT:
case BPF_PROG_TYPE_XDP:
case BPF_PROG_TYPE_LWT_XMIT:
case BPF_PROG_TYPE_SK_SKB:
if (meta)
return meta->pkt_access;
env->seen_direct_write = true;
return true;
default:
return false;
}
}
static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
int off, int size, bool zero_size_allowed)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_reg_state *reg = ®s[regno];
if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
(u64)off + size > reg->range) {
verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
off, size, regno, reg->id, reg->off, reg->range);
return -EACCES;
}
return 0;
}
static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
int size, bool zero_size_allowed)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_reg_state *reg = ®s[regno];
int err;
/* We may have added a variable offset to the packet pointer; but any
* reg->range we have comes after that. We are only checking the fixed
* offset.
*/
/* We don't allow negative numbers, because we aren't tracking enough
* detail to prove they're safe.
*/
if (reg->smin_value < 0) {
verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
regno);
return -EACCES;
}
err = __check_packet_access(env, regno, off, size, zero_size_allowed);
if (err) {
verbose(env, "R%d offset is outside of the packet\n", regno);
return err;
}
return err;
}
/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
enum bpf_access_type t, enum bpf_reg_type *reg_type)
{
struct bpf_insn_access_aux info = {
.reg_type = *reg_type,
};
if (env->ops->is_valid_access &&
env->ops->is_valid_access(off, size, t, &info)) {
/* A non zero info.ctx_field_size indicates that this field is a
* candidate for later verifier transformation to load the whole
* field and then apply a mask when accessed with a narrower
* access than actual ctx access size. A zero info.ctx_field_size
* will only allow for whole field access and rejects any other
* type of narrower access.
*/
*reg_type = info.reg_type;
env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
/* remember the offset of last byte accessed in ctx */
if (env->prog->aux->max_ctx_offset < off + size)
env->prog->aux->max_ctx_offset = off + size;
return 0;
}
verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
return -EACCES;
}
static bool __is_pointer_value(bool allow_ptr_leaks,
const struct bpf_reg_state *reg)
{
if (allow_ptr_leaks)
return false;
return reg->type != SCALAR_VALUE;
}
static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
{
return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno);
}
static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
int off, int size, bool strict)
{
struct tnum reg_off;
int ip_align;
/* Byte size accesses are always allowed. */
if (!strict || size == 1)
return 0;
/* For platforms that do not have a Kconfig enabling
* CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
* NET_IP_ALIGN is universally set to '2'. And on platforms
* that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
* to this code only in strict mode where we want to emulate
* the NET_IP_ALIGN==2 checking. Therefore use an
* unconditional IP align value of '2'.
*/
ip_align = 2;
reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
if (!tnum_is_aligned(reg_off, size)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env,
"misaligned packet access off %d+%s+%d+%d size %d\n",
ip_align, tn_buf, reg->off, off, size);
return -EACCES;
}
return 0;
}
static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
const char *pointer_desc,
int off, int size, bool strict)
{
struct tnum reg_off;
/* Byte size accesses are always allowed. */
if (!strict || size == 1)
return 0;
reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
if (!tnum_is_aligned(reg_off, size)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
pointer_desc, tn_buf, reg->off, off, size);
return -EACCES;
}
return 0;
}
static int check_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
int off, int size)
{
bool strict = env->strict_alignment;
const char *pointer_desc = "";
switch (reg->type) {
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
/* Special case, because of NET_IP_ALIGN. Given metadata sits
* right in front, treat it the very same way.
*/
return check_pkt_ptr_alignment(env, reg, off, size, strict);
case PTR_TO_MAP_VALUE:
pointer_desc = "value ";
break;
case PTR_TO_CTX:
pointer_desc = "context ";
break;
case PTR_TO_STACK:
pointer_desc = "stack ";
break;
default:
break;
}
return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
strict);
}
/* truncate register to smaller size (in bytes)
* must be called with size < BPF_REG_SIZE
*/
static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
{
u64 mask;
/* clear high bits in bit representation */
reg->var_off = tnum_cast(reg->var_off, size);
/* fix arithmetic bounds */
mask = ((u64)1 << (size * 8)) - 1;
if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
reg->umin_value &= mask;
reg->umax_value &= mask;
} else {
reg->umin_value = 0;
reg->umax_value = mask;
}
reg->smin_value = reg->umin_value;
reg->smax_value = reg->umax_value;
}
/* check whether memory at (regno + off) is accessible for t = (read | write)
* if t==write, value_regno is a register which value is stored into memory
* if t==read, value_regno is a register which will receive the value from memory
* if t==write && value_regno==-1, some unknown value is stored into memory
* if t==read && value_regno==-1, don't care what we read from memory
*/
static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, int off,
int bpf_size, enum bpf_access_type t,
int value_regno)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_reg_state *reg = regs + regno;
int size, err = 0;
size = bpf_size_to_bytes(bpf_size);
if (size < 0)
return size;
/* alignment checks will add in reg->off themselves */
err = check_ptr_alignment(env, reg, off, size);
if (err)
return err;
/* for access checks, reg->off is just part of off */
off += reg->off;
if (reg->type == PTR_TO_MAP_VALUE) {
if (t == BPF_WRITE && value_regno >= 0 &&
is_pointer_value(env, value_regno)) {
verbose(env, "R%d leaks addr into map\n", value_regno);
return -EACCES;
}
err = check_map_access(env, regno, off, size, false);
if (!err && t == BPF_READ && value_regno >= 0)
mark_reg_unknown(env, regs, value_regno);
} else if (reg->type == PTR_TO_CTX) {
enum bpf_reg_type reg_type = SCALAR_VALUE;
if (t == BPF_WRITE && value_regno >= 0 &&
is_pointer_value(env, value_regno)) {
verbose(env, "R%d leaks addr into ctx\n", value_regno);
return -EACCES;
}
/* ctx accesses must be at a fixed offset, so that we can
* determine what type of data were returned.
*/
if (reg->off) {
verbose(env,
"dereference of modified ctx ptr R%d off=%d+%d, ctx+const is allowed, ctx+const+const is not\n",
regno, reg->off, off - reg->off);
return -EACCES;
}
if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env,
"variable ctx access var_off=%s off=%d size=%d",
tn_buf, off, size);
return -EACCES;
}
err = check_ctx_access(env, insn_idx, off, size, t, ®_type);
if (!err && t == BPF_READ && value_regno >= 0) {
/* ctx access returns either a scalar, or a
* PTR_TO_PACKET[_META,_END]. In the latter
* case, we know the offset is zero.
*/
if (reg_type == SCALAR_VALUE)
mark_reg_unknown(env, regs, value_regno);
else
mark_reg_known_zero(env, regs,
value_regno);
regs[value_regno].id = 0;
regs[value_regno].off = 0;
regs[value_regno].range = 0;
regs[value_regno].type = reg_type;
}
} else if (reg->type == PTR_TO_STACK) {
/* stack accesses must be at a fixed offset, so that we can
* determine what type of data were returned.
* See check_stack_read().
*/
if (!tnum_is_const(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "variable stack access var_off=%s off=%d size=%d",
tn_buf, off, size);
return -EACCES;
}
off += reg->var_off.value;
if (off >= 0 || off < -MAX_BPF_STACK) {
verbose(env, "invalid stack off=%d size=%d\n", off,
size);
return -EACCES;
}
if (env->prog->aux->stack_depth < -off)
env->prog->aux->stack_depth = -off;
if (t == BPF_WRITE)
err = check_stack_write(env, state, off, size,
value_regno);
else
err = check_stack_read(env, state, off, size,
value_regno);
} else if (reg_is_pkt_pointer(reg)) {
if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
verbose(env, "cannot write into packet\n");
return -EACCES;
}
if (t == BPF_WRITE && value_regno >= 0 &&
is_pointer_value(env, value_regno)) {
verbose(env, "R%d leaks addr into packet\n",
value_regno);
return -EACCES;
}
err = check_packet_access(env, regno, off, size, false);
if (!err && t == BPF_READ && value_regno >= 0)
mark_reg_unknown(env, regs, value_regno);
} else {
verbose(env, "R%d invalid mem access '%s'\n", regno,
reg_type_str[reg->type]);
return -EACCES;
}
if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
regs[value_regno].type == SCALAR_VALUE) {
/* b/h/w load zero-extends, mark upper bits as known 0 */
coerce_reg_to_size(®s[value_regno], size);
}
return err;
}
static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
{
int err;
if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
insn->imm != 0) {
verbose(env, "BPF_XADD uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->src_reg)) {
verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
return -EACCES;
}
/* check whether atomic_add can read the memory */
err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_READ, -1);
if (err)
return err;
/* check whether atomic_add can write into the same memory */
return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE, -1);
}
/* Does this register contain a constant zero? */
static bool register_is_null(struct bpf_reg_state reg)
{
return reg.type == SCALAR_VALUE && tnum_equals_const(reg.var_off, 0);
}
/* when register 'regno' is passed into function that will read 'access_size'
* bytes from that pointer, make sure that it's within stack boundary
* and all elements of stack are initialized.
* Unlike most pointer bounds-checking functions, this one doesn't take an
* 'off' argument, so it has to add in reg->off itself.
*/
static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
int access_size, bool zero_size_allowed,
struct bpf_call_arg_meta *meta)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_reg_state *regs = state->regs;
int off, i, slot, spi;
if (regs[regno].type != PTR_TO_STACK) {
/* Allow zero-byte read from NULL, regardless of pointer type */
if (zero_size_allowed && access_size == 0 &&
register_is_null(regs[regno]))
return 0;
verbose(env, "R%d type=%s expected=%s\n", regno,
reg_type_str[regs[regno].type],
reg_type_str[PTR_TO_STACK]);
return -EACCES;
}
/* Only allow fixed-offset stack reads */
if (!tnum_is_const(regs[regno].var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), regs[regno].var_off);
verbose(env, "invalid variable stack read R%d var_off=%s\n",
regno, tn_buf);
return -EACCES;
}
off = regs[regno].off + regs[regno].var_off.value;
if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
regno, off, access_size);
return -EACCES;
}
if (env->prog->aux->stack_depth < -off)
env->prog->aux->stack_depth = -off;
if (meta && meta->raw_mode) {
meta->access_size = access_size;
meta->regno = regno;
return 0;
}
for (i = 0; i < access_size; i++) {
slot = -(off + i) - 1;
spi = slot / BPF_REG_SIZE;
if (state->allocated_stack <= slot ||
state->stack[spi].slot_type[slot % BPF_REG_SIZE] !=
STACK_MISC) {
verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
off, i, access_size);
return -EACCES;
}
}
return 0;
}
static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
int access_size, bool zero_size_allowed,
struct bpf_call_arg_meta *meta)
{
struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
switch (reg->type) {
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
return check_packet_access(env, regno, reg->off, access_size,
zero_size_allowed);
case PTR_TO_MAP_VALUE:
return check_map_access(env, regno, reg->off, access_size,
zero_size_allowed);
default: /* scalar_value|ptr_to_stack or invalid ptr */
return check_stack_boundary(env, regno, access_size,
zero_size_allowed, meta);
}
}
static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
enum bpf_arg_type arg_type,
struct bpf_call_arg_meta *meta)
{
struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
enum bpf_reg_type expected_type, type = reg->type;
int err = 0;
if (arg_type == ARG_DONTCARE)
return 0;
err = check_reg_arg(env, regno, SRC_OP);
if (err)
return err;
if (arg_type == ARG_ANYTHING) {
if (is_pointer_value(env, regno)) {
verbose(env, "R%d leaks addr into helper function\n",
regno);
return -EACCES;
}
return 0;
}
if (type_is_pkt_pointer(type) &&
!may_access_direct_pkt_data(env, meta, BPF_READ)) {
verbose(env, "helper access to the packet is not allowed\n");
return -EACCES;
}
if (arg_type == ARG_PTR_TO_MAP_KEY ||
arg_type == ARG_PTR_TO_MAP_VALUE) {
expected_type = PTR_TO_STACK;
if (!type_is_pkt_pointer(type) &&
type != expected_type)
goto err_type;
} else if (arg_type == ARG_CONST_SIZE ||
arg_type == ARG_CONST_SIZE_OR_ZERO) {
expected_type = SCALAR_VALUE;
if (type != expected_type)
goto err_type;
} else if (arg_type == ARG_CONST_MAP_PTR) {
expected_type = CONST_PTR_TO_MAP;
if (type != expected_type)
goto err_type;
} else if (arg_type == ARG_PTR_TO_CTX) {
expected_type = PTR_TO_CTX;
if (type != expected_type)
goto err_type;
} else if (arg_type == ARG_PTR_TO_MEM ||
arg_type == ARG_PTR_TO_MEM_OR_NULL ||
arg_type == ARG_PTR_TO_UNINIT_MEM) {
expected_type = PTR_TO_STACK;
/* One exception here. In case function allows for NULL to be
* passed in as argument, it's a SCALAR_VALUE type. Final test
* happens during stack boundary checking.
*/
if (register_is_null(*reg) &&
arg_type == ARG_PTR_TO_MEM_OR_NULL)
/* final test in check_stack_boundary() */;
else if (!type_is_pkt_pointer(type) &&
type != PTR_TO_MAP_VALUE &&
type != expected_type)
goto err_type;
meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
} else {
verbose(env, "unsupported arg_type %d\n", arg_type);
return -EFAULT;
}
if (arg_type == ARG_CONST_MAP_PTR) {
/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
meta->map_ptr = reg->map_ptr;
} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
/* bpf_map_xxx(..., map_ptr, ..., key) call:
* check that [key, key + map->key_size) are within
* stack limits and initialized
*/
if (!meta->map_ptr) {
/* in function declaration map_ptr must come before
* map_key, so that it's verified and known before
* we have to check map_key here. Otherwise it means
* that kernel subsystem misconfigured verifier
*/
verbose(env, "invalid map_ptr to access map->key\n");
return -EACCES;
}
if (type_is_pkt_pointer(type))
err = check_packet_access(env, regno, reg->off,
meta->map_ptr->key_size,
false);
else
err = check_stack_boundary(env, regno,
meta->map_ptr->key_size,
false, NULL);
} else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
/* bpf_map_xxx(..., map_ptr, ..., value) call:
* check [value, value + map->value_size) validity
*/
if (!meta->map_ptr) {
/* kernel subsystem misconfigured verifier */
verbose(env, "invalid map_ptr to access map->value\n");
return -EACCES;
}
if (type_is_pkt_pointer(type))
err = check_packet_access(env, regno, reg->off,
meta->map_ptr->value_size,
false);
else
err = check_stack_boundary(env, regno,
meta->map_ptr->value_size,
false, NULL);
} else if (arg_type == ARG_CONST_SIZE ||
arg_type == ARG_CONST_SIZE_OR_ZERO) {
bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
/* bpf_xxx(..., buf, len) call will access 'len' bytes
* from stack pointer 'buf'. Check it
* note: regno == len, regno - 1 == buf
*/
if (regno == 0) {
/* kernel subsystem misconfigured verifier */
verbose(env,
"ARG_CONST_SIZE cannot be first argument\n");
return -EACCES;
}
/* The register is SCALAR_VALUE; the access check
* happens using its boundaries.
*/
if (!tnum_is_const(reg->var_off))
/* For unprivileged variable accesses, disable raw
* mode so that the program is required to
* initialize all the memory that the helper could
* just partially fill up.
*/
meta = NULL;
if (reg->smin_value < 0) {
verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
regno);
return -EACCES;
}
if (reg->umin_value == 0) {
err = check_helper_mem_access(env, regno - 1, 0,
zero_size_allowed,
meta);
if (err)
return err;
}
if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
regno);
return -EACCES;
}
err = check_helper_mem_access(env, regno - 1,
reg->umax_value,
zero_size_allowed, meta);
}
return err;
err_type:
verbose(env, "R%d type=%s expected=%s\n", regno,
reg_type_str[type], reg_type_str[expected_type]);
return -EACCES;
}
static int check_map_func_compatibility(struct bpf_verifier_env *env,
struct bpf_map *map, int func_id)
{
if (!map)
return 0;
/* We need a two way check, first is from map perspective ... */
switch (map->map_type) {
case BPF_MAP_TYPE_PROG_ARRAY:
if (func_id != BPF_FUNC_tail_call)
goto error;
break;
case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
if (func_id != BPF_FUNC_perf_event_read &&
func_id != BPF_FUNC_perf_event_output &&
func_id != BPF_FUNC_perf_event_read_value)
goto error;
break;
case BPF_MAP_TYPE_STACK_TRACE:
if (func_id != BPF_FUNC_get_stackid)
goto error;
break;
case BPF_MAP_TYPE_CGROUP_ARRAY:
if (func_id != BPF_FUNC_skb_under_cgroup &&
func_id != BPF_FUNC_current_task_under_cgroup)
goto error;
break;
/* devmap returns a pointer to a live net_device ifindex that we cannot
* allow to be modified from bpf side. So do not allow lookup elements
* for now.
*/
case BPF_MAP_TYPE_DEVMAP:
if (func_id != BPF_FUNC_redirect_map)
goto error;
break;
/* Restrict bpf side of cpumap, open when use-cases appear */
case BPF_MAP_TYPE_CPUMAP:
if (func_id != BPF_FUNC_redirect_map)
goto error;
break;
case BPF_MAP_TYPE_ARRAY_OF_MAPS:
case BPF_MAP_TYPE_HASH_OF_MAPS:
if (func_id != BPF_FUNC_map_lookup_elem)
goto error;
break;
case BPF_MAP_TYPE_SOCKMAP:
if (func_id != BPF_FUNC_sk_redirect_map &&
func_id != BPF_FUNC_sock_map_update &&
func_id != BPF_FUNC_map_delete_elem)
goto error;
break;
default:
break;
}
/* ... and second from the function itself. */
switch (func_id) {
case BPF_FUNC_tail_call:
if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
goto error;
break;
case BPF_FUNC_perf_event_read:
case BPF_FUNC_perf_event_output:
case BPF_FUNC_perf_event_read_value:
if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
goto error;
break;
case BPF_FUNC_get_stackid:
if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
goto error;
break;
case BPF_FUNC_current_task_under_cgroup:
case BPF_FUNC_skb_under_cgroup:
if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
goto error;
break;
case BPF_FUNC_redirect_map:
if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
map->map_type != BPF_MAP_TYPE_CPUMAP)
goto error;
break;
case BPF_FUNC_sk_redirect_map:
if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
goto error;
break;
case BPF_FUNC_sock_map_update:
if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
goto error;
break;
default:
break;
}
return 0;
error:
verbose(env, "cannot pass map_type %d into func %s#%d\n",
map->map_type, func_id_name(func_id), func_id);
return -EINVAL;
}
static int check_raw_mode(const struct bpf_func_proto *fn)
{
int count = 0;
if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
count++;
return count > 1 ? -EINVAL : 0;
}
/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
* are now invalid, so turn them into unknown SCALAR_VALUE.
*/
static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_reg_state *regs = state->regs, *reg;
int i;
for (i = 0; i < MAX_BPF_REG; i++)
if (reg_is_pkt_pointer_any(®s[i]))
mark_reg_unknown(env, regs, i);
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
reg = &state->stack[i].spilled_ptr;
if (reg_is_pkt_pointer_any(reg))
__mark_reg_unknown(reg);
}
}
static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
{
const struct bpf_func_proto *fn = NULL;
struct bpf_reg_state *regs;
struct bpf_call_arg_meta meta;
bool changes_data;
int i, err;
/* find function prototype */
if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
func_id);
return -EINVAL;
}
if (env->ops->get_func_proto)
fn = env->ops->get_func_proto(func_id);
if (!fn) {
verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
func_id);
return -EINVAL;
}
/* eBPF programs must be GPL compatible to use GPL-ed functions */
if (!env->prog->gpl_compatible && fn->gpl_only) {
verbose(env, "cannot call GPL only function from proprietary program\n");
return -EINVAL;
}
/* With LD_ABS/IND some JITs save/restore skb from r1. */
changes_data = bpf_helper_changes_pkt_data(fn->func);
if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
func_id_name(func_id), func_id);
return -EINVAL;
}
memset(&meta, 0, sizeof(meta));
meta.pkt_access = fn->pkt_access;
/* We only support one arg being in raw mode at the moment, which
* is sufficient for the helper functions we have right now.
*/
err = check_raw_mode(fn);
if (err) {
verbose(env, "kernel subsystem misconfigured func %s#%d\n",
func_id_name(func_id), func_id);
return err;
}
/* check args */
err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
if (err)
return err;
/* Mark slots with STACK_MISC in case of raw mode, stack offset
* is inferred from register state.
*/
for (i = 0; i < meta.access_size; i++) {
err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, BPF_WRITE, -1);
if (err)
return err;
}
regs = cur_regs(env);
/* reset caller saved regs */
for (i = 0; i < CALLER_SAVED_REGS; i++) {
mark_reg_not_init(env, regs, caller_saved[i]);
check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
}
/* update return register (already marked as written above) */
if (fn->ret_type == RET_INTEGER) {
/* sets type to SCALAR_VALUE */
mark_reg_unknown(env, regs, BPF_REG_0);
} else if (fn->ret_type == RET_VOID) {
regs[BPF_REG_0].type = NOT_INIT;
} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
struct bpf_insn_aux_data *insn_aux;
regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
/* There is no offset yet applied, variable or fixed */
mark_reg_known_zero(env, regs, BPF_REG_0);
regs[BPF_REG_0].off = 0;
/* remember map_ptr, so that check_map_access()
* can check 'value_size' boundary of memory access
* to map element returned from bpf_map_lookup_elem()
*/
if (meta.map_ptr == NULL) {
verbose(env,
"kernel subsystem misconfigured verifier\n");
return -EINVAL;
}
regs[BPF_REG_0].map_ptr = meta.map_ptr;
regs[BPF_REG_0].id = ++env->id_gen;
insn_aux = &env->insn_aux_data[insn_idx];
if (!insn_aux->map_ptr)
insn_aux->map_ptr = meta.map_ptr;
else if (insn_aux->map_ptr != meta.map_ptr)
insn_aux->map_ptr = BPF_MAP_PTR_POISON;
} else {
verbose(env, "unknown return type %d of func %s#%d\n",
fn->ret_type, func_id_name(func_id), func_id);
return -EINVAL;
}
err = check_map_func_compatibility(env, meta.map_ptr, func_id);
if (err)
return err;
if (changes_data)
clear_all_pkt_pointers(env);
return 0;
}
static bool signed_add_overflows(s64 a, s64 b)
{
/* Do the add in u64, where overflow is well-defined */
s64 res = (s64)((u64)a + (u64)b);
if (b < 0)
return res > a;
return res < a;
}
static bool signed_sub_overflows(s64 a, s64 b)
{
/* Do the sub in u64, where overflow is well-defined */
s64 res = (s64)((u64)a - (u64)b);
if (b < 0)
return res < a;
return res > a;
}
/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
* Caller should also handle BPF_MOV case separately.
* If we return -EACCES, caller may want to try again treating pointer as a
* scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
*/
static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn,
const struct bpf_reg_state *ptr_reg,
const struct bpf_reg_state *off_reg)
{
struct bpf_reg_state *regs = cur_regs(env), *dst_reg;
bool known = tnum_is_const(off_reg->var_off);
s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
u8 opcode = BPF_OP(insn->code);
u32 dst = insn->dst_reg;
dst_reg = ®s[dst];
if (WARN_ON_ONCE(known && (smin_val != smax_val))) {
print_verifier_state(env, env->cur_state);
verbose(env,
"verifier internal error: known but bad sbounds\n");
return -EINVAL;
}
if (WARN_ON_ONCE(known && (umin_val != umax_val))) {
print_verifier_state(env, env->cur_state);
verbose(env,
"verifier internal error: known but bad ubounds\n");
return -EINVAL;
}
if (BPF_CLASS(insn->code) != BPF_ALU64) {
/* 32-bit ALU ops on pointers produce (meaningless) scalars */
if (!env->allow_ptr_leaks)
verbose(env,
"R%d 32-bit pointer arithmetic prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
dst);
return -EACCES;
}
if (ptr_reg->type == CONST_PTR_TO_MAP) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_PACKET_END) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
dst);
return -EACCES;
}
/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
* The id may be overwritten later if we create a new variable offset.
*/
dst_reg->type = ptr_reg->type;
dst_reg->id = ptr_reg->id;
switch (opcode) {
case BPF_ADD:
/* We can take a fixed offset as long as it doesn't overflow
* the s32 'off' field
*/
if (known && (ptr_reg->off + smin_val ==
(s64)(s32)(ptr_reg->off + smin_val))) {
/* pointer += K. Accumulate it into fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->off = ptr_reg->off + smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. Note that off_reg->off
* == 0, since it's a scalar.
* dst_reg gets the pointer type and since some positive
* integer value was added to the pointer, give it a new 'id'
* if it's a PTR_TO_PACKET.
* this creates a new 'base' pointer, off_reg (variable) gets
* added into the variable offset, and we copy the fixed offset
* from ptr_reg.
*/
if (signed_add_overflows(smin_ptr, smin_val) ||
signed_add_overflows(smax_ptr, smax_val)) {
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr + smin_val;
dst_reg->smax_value = smax_ptr + smax_val;
}
if (umin_ptr + umin_val < umin_ptr ||
umax_ptr + umax_val < umax_ptr) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value = umin_ptr + umin_val;
dst_reg->umax_value = umax_ptr + umax_val;
}
dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
dst_reg->range = 0;
}
break;
case BPF_SUB:
if (dst_reg == off_reg) {
/* scalar -= pointer. Creates an unknown scalar */
if (!env->allow_ptr_leaks)
verbose(env, "R%d tried to subtract pointer from scalar\n",
dst);
return -EACCES;
}
/* We don't allow subtraction from FP, because (according to
* test_verifier.c test "invalid fp arithmetic", JITs might not
* be able to deal with it.
*/
if (ptr_reg->type == PTR_TO_STACK) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d subtraction from stack pointer prohibited\n",
dst);
return -EACCES;
}
if (known && (ptr_reg->off - smin_val ==
(s64)(s32)(ptr_reg->off - smin_val))) {
/* pointer -= K. Subtract it from fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->id = ptr_reg->id;
dst_reg->off = ptr_reg->off - smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. If the subtrahend is known
* nonnegative, then any reg->range we had before is still good.
*/
if (signed_sub_overflows(smin_ptr, smax_val) ||
signed_sub_overflows(smax_ptr, smin_val)) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr - smax_val;
dst_reg->smax_value = smax_ptr - smin_val;
}
if (umin_ptr < 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 = umin_ptr - umax_val;
dst_reg->umax_value = umax_ptr - umin_val;
}
dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
if (smin_val < 0)
dst_reg->range = 0;
}
break;
case BPF_AND:
case BPF_OR:
case BPF_XOR:
/* bitwise ops on pointers are troublesome, prohibit for now.
* (However, in principle we could allow some cases, e.g.
* ptr &= ~3 which would reduce min_value by 3.)
*/
if (!env->allow_ptr_leaks)
verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
default:
/* other operators (e.g. MUL,LSH) produce non-pointer results */
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
}
__update_reg_bounds(dst_reg);
__reg_deduce_bounds(dst_reg);
__reg_bound_offset(dst_reg);
return 0;
}
/* WARNING: This function does calculations on 64-bit values, but the actual
* execution may occur on 32-bit values. Therefore, things like bitshifts
* need extra checks in the 32-bit case.
*/
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);
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;
}
if (src_known)
dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
else
dst_reg->var_off = tnum_lshift(tnum_unknown, 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;
if (src_known)
dst_reg->var_off = tnum_rshift(dst_reg->var_off,
umin_val);
else
dst_reg->var_off = tnum_rshift(tnum_unknown, 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;
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;
}
/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
* and var_off.
*/
static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env), *dst_reg, *src_reg;
struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
u8 opcode = BPF_OP(insn->code);
int rc;
dst_reg = ®s[insn->dst_reg];
src_reg = NULL;
if (dst_reg->type != SCALAR_VALUE)
ptr_reg = dst_reg;
if (BPF_SRC(insn->code) == BPF_X) {
src_reg = ®s[insn->src_reg];
if (src_reg->type != SCALAR_VALUE) {
if (dst_reg->type != SCALAR_VALUE) {
/* Combining two pointers by any ALU op yields
* an arbitrary scalar.
*/
if (!env->allow_ptr_leaks) {
verbose(env, "R%d pointer %s pointer prohibited\n",
insn->dst_reg,
bpf_alu_string[opcode >> 4]);
return -EACCES;
}
mark_reg_unknown(env, regs, insn->dst_reg);
return 0;
} else {
/* scalar += pointer
* This is legal, but we have to reverse our
* src/dest handling in computing the range
*/
rc = adjust_ptr_min_max_vals(env, insn,
src_reg, dst_reg);
if (rc == -EACCES && env->allow_ptr_leaks) {
/* scalar += unknown scalar */
__mark_reg_unknown(&off_reg);
return adjust_scalar_min_max_vals(
env, insn,
dst_reg, off_reg);
}
return rc;
}
} else if (ptr_reg) {
/* pointer += scalar */
rc = adjust_ptr_min_max_vals(env, insn,
dst_reg, src_reg);
if (rc == -EACCES && env->allow_ptr_leaks) {
/* unknown scalar += scalar */
__mark_reg_unknown(dst_reg);
return adjust_scalar_min_max_vals(
env, insn, dst_reg, *src_reg);
}
return rc;
}
} else {
/* Pretend the src is a reg with a known value, since we only
* need to be able to read from this state.
*/
off_reg.type = SCALAR_VALUE;
__mark_reg_known(&off_reg, insn->imm);
src_reg = &off_reg;
if (ptr_reg) { /* pointer += K */
rc = adjust_ptr_min_max_vals(env, insn,
ptr_reg, src_reg);
if (rc == -EACCES && env->allow_ptr_leaks) {
/* unknown scalar += K */
__mark_reg_unknown(dst_reg);
return adjust_scalar_min_max_vals(
env, insn, dst_reg, off_reg);
}
return rc;
}
}
/* Got here implies adding two SCALAR_VALUEs */
if (WARN_ON_ONCE(ptr_reg)) {
print_verifier_state(env, env->cur_state);
verbose(env, "verifier internal error: unexpected ptr_reg\n");
return -EINVAL;
}
if (WARN_ON(!src_reg)) {
print_verifier_state(env, env->cur_state);
verbose(env, "verifier internal error: no src_reg\n");
return -EINVAL;
}
return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
}
/* check validity of 32-bit and 64-bit arithmetic operations */
static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 opcode = BPF_OP(insn->code);
int err;
if (opcode == BPF_END || opcode == BPF_NEG) {
if (opcode == BPF_NEG) {
if (BPF_SRC(insn->code) != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->off != 0 || insn->imm != 0) {
verbose(env, "BPF_NEG uses reserved fields\n");
return -EINVAL;
}
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
(insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
BPF_CLASS(insn->code) == BPF_ALU64) {
verbose(env, "BPF_END uses reserved fields\n");
return -EINVAL;
}
}
/* check src operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->dst_reg)) {
verbose(env, "R%d pointer arithmetic prohibited\n",
insn->dst_reg);
return -EACCES;
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
} else if (opcode == BPF_MOV) {
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
if (BPF_SRC(insn->code) == BPF_X) {
if (BPF_CLASS(insn->code) == BPF_ALU64) {
/* case: R1 = R2
* copy register state to dest reg
*/
regs[insn->dst_reg] = regs[insn->src_reg];
regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
} else {
/* R1 = (u32) R2 */
if (is_pointer_value(env, insn->src_reg)) {
verbose(env,
"R%d partial copy of pointer\n",
insn->src_reg);
return -EACCES;
}
mark_reg_unknown(env, regs, insn->dst_reg);
coerce_reg_to_size(®s[insn->dst_reg], 4);
}
} else {
/* case: R = imm
* remember the value we stored into this reg
*/
regs[insn->dst_reg].type = SCALAR_VALUE;
if (BPF_CLASS(insn->code) == BPF_ALU64) {
__mark_reg_known(regs + insn->dst_reg,
insn->imm);
} else {
__mark_reg_known(regs + insn->dst_reg,
(u32)insn->imm);
}
}
} else if (opcode > BPF_END) {
verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
return -EINVAL;
} else { /* all other ALU ops: and, sub, xor, add, ... */
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
}
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
verbose(env, "div by zero\n");
return -EINVAL;
}
if ((opcode == BPF_LSH || opcode == BPF_RSH ||
opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
if (insn->imm < 0 || insn->imm >= size) {
verbose(env, "invalid shift %d\n", insn->imm);
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
return adjust_reg_min_max_vals(env, insn);
}
return 0;
}
static void find_good_pkt_pointers(struct bpf_verifier_state *state,
struct bpf_reg_state *dst_reg,
enum bpf_reg_type type,
bool range_right_open)
{
struct bpf_reg_state *regs = state->regs, *reg;
u16 new_range;
int i;
if (dst_reg->off < 0 ||
(dst_reg->off == 0 && range_right_open))
/* This doesn't give us any range */
return;
if (dst_reg->umax_value > MAX_PACKET_OFF ||
dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
/* Risk of overflow. For instance, ptr + (1<<63) may be less
* than pkt_end, but that's because it's also less than pkt.
*/
return;
new_range = dst_reg->off;
if (range_right_open)
new_range--;
/* Examples for register markings:
*
* pkt_data in dst register:
*
* r2 = r3;
* r2 += 8;
* if (r2 > pkt_end) goto <handle exception>
* <access okay>
*
* r2 = r3;
* r2 += 8;
* if (r2 < pkt_end) goto <access okay>
* <handle exception>
*
* Where:
* r2 == dst_reg, pkt_end == src_reg
* r2=pkt(id=n,off=8,r=0)
* r3=pkt(id=n,off=0,r=0)
*
* pkt_data in src register:
*
* r2 = r3;
* r2 += 8;
* if (pkt_end >= r2) goto <access okay>
* <handle exception>
*
* r2 = r3;
* r2 += 8;
* if (pkt_end <= r2) goto <handle exception>
* <access okay>
*
* Where:
* pkt_end == dst_reg, r2 == src_reg
* r2=pkt(id=n,off=8,r=0)
* r3=pkt(id=n,off=0,r=0)
*
* Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
* or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
* and [r3, r3 + 8-1) respectively is safe to access depending on
* the check.
*/
/* If our ids match, then we must have the same max_value. And we
* don't care about the other reg's fixed offset, since if it's too big
* the range won't allow anything.
* dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
*/
for (i = 0; i < MAX_BPF_REG; i++)
if (regs[i].type == type && regs[i].id == dst_reg->id)
/* keep the maximum range already checked */
regs[i].range = max(regs[i].range, new_range);
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
reg = &state->stack[i].spilled_ptr;
if (reg->type == type && reg->id == dst_reg->id)
reg->range = max(reg->range, new_range);
}
}
/* Adjusts the register min/max values in the case that the dst_reg is the
* variable register that we are working on, and src_reg is a constant or we're
* simply doing a BPF_K check.
* In JEQ/JNE cases we also adjust the var_off values.
*/
static void reg_set_min_max(struct bpf_reg_state *true_reg,
struct bpf_reg_state *false_reg, u64 val,
u8 opcode)
{
/* If the dst_reg is a pointer, we can't learn anything about its
* variable offset from the compare (unless src_reg were a pointer into
* the same object, but we don't bother with that.
* Since false_reg and true_reg have the same type by construction, we
* only need to check one of them for pointerness.
*/
if (__is_pointer_value(false, false_reg))
return;
switch (opcode) {
case BPF_JEQ:
/* If this is false then we know nothing Jon Snow, but if it is
* true then we know for sure.
*/
__mark_reg_known(true_reg, val);
break;
case BPF_JNE:
/* If this is true we know nothing Jon Snow, but if it is false
* we know the value for sure;
*/
__mark_reg_known(false_reg, val);
break;
case BPF_JGT:
false_reg->umax_value = min(false_reg->umax_value, val);
true_reg->umin_value = max(true_reg->umin_value, val + 1);
break;
case BPF_JSGT:
false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
break;
case BPF_JLT:
false_reg->umin_value = max(false_reg->umin_value, val);
true_reg->umax_value = min(true_reg->umax_value, val - 1);
break;
case BPF_JSLT:
false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
break;
case BPF_JGE:
false_reg->umax_value = min(false_reg->umax_value, val - 1);
true_reg->umin_value = max(true_reg->umin_value, val);
break;
case BPF_JSGE:
false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
break;
case BPF_JLE:
false_reg->umin_value = max(false_reg->umin_value, val + 1);
true_reg->umax_value = min(true_reg->umax_value, val);
break;
case BPF_JSLE:
false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
break;
default:
break;
}
__reg_deduce_bounds(false_reg);
__reg_deduce_bounds(true_reg);
/* We might have learned some bits from the bounds. */
__reg_bound_offset(false_reg);
__reg_bound_offset(true_reg);
/* Intersecting with the old var_off might have improved our bounds
* slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
* then new var_off is (0; 0x7f...fc) which improves our umax.
*/
__update_reg_bounds(false_reg);
__update_reg_bounds(true_reg);
}
/* Same as above, but for the case that dst_reg holds a constant and src_reg is
* the variable reg.
*/
static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
struct bpf_reg_state *false_reg, u64 val,
u8 opcode)
{
if (__is_pointer_value(false, false_reg))
return;
switch (opcode) {
case BPF_JEQ:
/* If this is false then we know nothing Jon Snow, but if it is
* true then we know for sure.
*/
__mark_reg_known(true_reg, val);
break;
case BPF_JNE:
/* If this is true we know nothing Jon Snow, but if it is false
* we know the value for sure;
*/
__mark_reg_known(false_reg, val);
break;
case BPF_JGT:
true_reg->umax_value = min(true_reg->umax_value, val - 1);
false_reg->umin_value = max(false_reg->umin_value, val);
break;
case BPF_JSGT:
true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
break;
case BPF_JLT:
true_reg->umin_value = max(true_reg->umin_value, val + 1);
false_reg->umax_value = min(false_reg->umax_value, val);
break;
case BPF_JSLT:
true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
break;
case BPF_JGE:
true_reg->umax_value = min(true_reg->umax_value, val);
false_reg->umin_value = max(false_reg->umin_value, val + 1);
break;
case BPF_JSGE:
true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
break;
case BPF_JLE:
true_reg->umin_value = max(true_reg->umin_value, val);
false_reg->umax_value = min(false_reg->umax_value, val - 1);
break;
case BPF_JSLE:
true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
break;
default:
break;
}
__reg_deduce_bounds(false_reg);
__reg_deduce_bounds(true_reg);
/* We might have learned some bits from the bounds. */
__reg_bound_offset(false_reg);
__reg_bound_offset(true_reg);
/* Intersecting with the old var_off might have improved our bounds
* slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
* then new var_off is (0; 0x7f...fc) which improves our umax.
*/
__update_reg_bounds(false_reg);
__update_reg_bounds(true_reg);
}
/* Regs are known to be equal, so intersect their min/max/var_off */
static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
struct bpf_reg_state *dst_reg)
{
src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
dst_reg->umin_value);
src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
dst_reg->umax_value);
src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
dst_reg->smin_value);
src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
dst_reg->smax_value);
src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
dst_reg->var_off);
/* We might have learned new bounds from the var_off. */
__update_reg_bounds(src_reg);
__update_reg_bounds(dst_reg);
/* We might have learned something about the sign bit. */
__reg_deduce_bounds(src_reg);
__reg_deduce_bounds(dst_reg);
/* We might have learned some bits from the bounds. */
__reg_bound_offset(src_reg);
__reg_bound_offset(dst_reg);
/* Intersecting with the old var_off might have improved our bounds
* slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
* then new var_off is (0; 0x7f...fc) which improves our umax.
*/
__update_reg_bounds(src_reg);
__update_reg_bounds(dst_reg);
}
static void reg_combine_min_max(struct bpf_reg_state *true_src,
struct bpf_reg_state *true_dst,
struct bpf_reg_state *false_src,
struct bpf_reg_state *false_dst,
u8 opcode)
{
switch (opcode) {
case BPF_JEQ:
__reg_combine_min_max(true_src, true_dst);
break;
case BPF_JNE:
__reg_combine_min_max(false_src, false_dst);
break;
}
}
static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
bool is_null)
{
struct bpf_reg_state *reg = ®s[regno];
if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
/* Old offset (both fixed and variable parts) should
* have been known-zero, because we don't allow pointer
* arithmetic on pointers that might be NULL.
*/
if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
!tnum_equals_const(reg->var_off, 0) ||
reg->off)) {
__mark_reg_known_zero(reg);
reg->off = 0;
}
if (is_null) {
reg->type = SCALAR_VALUE;
} else if (reg->map_ptr->inner_map_meta) {
reg->type = CONST_PTR_TO_MAP;
reg->map_ptr = reg->map_ptr->inner_map_meta;
} else {
reg->type = PTR_TO_MAP_VALUE;
}
/* We don't need id from this point onwards anymore, thus we
* should better reset it, so that state pruning has chances
* to take effect.
*/
reg->id = 0;
}
}
/* The logic is similar to find_good_pkt_pointers(), both could eventually
* be folded together at some point.
*/
static void mark_map_regs(struct bpf_verifier_state *state, u32 regno,
bool is_null)
{
struct bpf_reg_state *regs = state->regs;
u32 id = regs[regno].id;
int i;
for (i = 0; i < MAX_BPF_REG; i++)
mark_map_reg(regs, i, id, is_null);
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
}
}
static bool try_match_pkt_pointers(const struct bpf_insn *insn,
struct bpf_reg_state *dst_reg,
struct bpf_reg_state *src_reg,
struct bpf_verifier_state *this_branch,
struct bpf_verifier_state *other_branch)
{
if (BPF_SRC(insn->code) != BPF_X)
return false;
switch (BPF_OP(insn->code)) {
case BPF_JGT:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
find_good_pkt_pointers(this_branch, dst_reg,
dst_reg->type, false);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end > pkt_data', pkt_data > pkt_meta' */
find_good_pkt_pointers(other_branch, src_reg,
src_reg->type, true);
} else {
return false;
}
break;
case BPF_JLT:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
find_good_pkt_pointers(other_branch, dst_reg,
dst_reg->type, true);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end < pkt_data', pkt_data > pkt_meta' */
find_good_pkt_pointers(this_branch, src_reg,
src_reg->type, false);
} else {
return false;
}
break;
case BPF_JGE:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
find_good_pkt_pointers(this_branch, dst_reg,
dst_reg->type, true);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
find_good_pkt_pointers(other_branch, src_reg,
src_reg->type, false);
} else {
return false;
}
break;
case BPF_JLE:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
find_good_pkt_pointers(other_branch, dst_reg,
dst_reg->type, false);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
find_good_pkt_pointers(this_branch, src_reg,
src_reg->type, true);
} else {
return false;
}
break;
default:
return false;
}
return true;
}
static int check_cond_jmp_op(struct bpf_verifier_env *env,
struct bpf_insn *insn, int *insn_idx)
{
struct bpf_verifier_state *other_branch, *this_branch = env->cur_state;
struct bpf_reg_state *regs = this_branch->regs, *dst_reg;
u8 opcode = BPF_OP(insn->code);
int err;
if (opcode > BPF_JSLE) {
verbose(env, "invalid BPF_JMP opcode %x\n", opcode);
return -EINVAL;
}
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0) {
verbose(env, "BPF_JMP uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->src_reg)) {
verbose(env, "R%d pointer comparison prohibited\n",
insn->src_reg);
return -EACCES;
}
} else {
if (insn->src_reg != BPF_REG_0) {
verbose(env, "BPF_JMP uses reserved fields\n");
return -EINVAL;
}
}
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
dst_reg = ®s[insn->dst_reg];
/* detect if R == 0 where R was initialized to zero earlier */
if (BPF_SRC(insn->code) == BPF_K &&
(opcode == BPF_JEQ || opcode == BPF_JNE) &&
dst_reg->type == SCALAR_VALUE &&
tnum_equals_const(dst_reg->var_off, insn->imm)) {
if (opcode == BPF_JEQ) {
/* if (imm == imm) goto pc+off;
* only follow the goto, ignore fall-through
*/
*insn_idx += insn->off;
return 0;
} else {
/* if (imm != imm) goto pc+off;
* only follow fall-through branch, since
* that's where the program will go
*/
return 0;
}
}
other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
if (!other_branch)
return -EFAULT;
/* detect if we are comparing against a constant value so we can adjust
* our min/max values for our dst register.
* this is only legit if both are scalars (or pointers to the same
* object, I suppose, but we don't support that right now), because
* otherwise the different base pointers mean the offsets aren't
* comparable.
*/
if (BPF_SRC(insn->code) == BPF_X) {
if (dst_reg->type == SCALAR_VALUE &&
regs[insn->src_reg].type == SCALAR_VALUE) {
if (tnum_is_const(regs[insn->src_reg].var_off))
reg_set_min_max(&other_branch->regs[insn->dst_reg],
dst_reg, regs[insn->src_reg].var_off.value,
opcode);
else if (tnum_is_const(dst_reg->var_off))
reg_set_min_max_inv(&other_branch->regs[insn->src_reg],
®s[insn->src_reg],
dst_reg->var_off.value, opcode);
else if (opcode == BPF_JEQ || opcode == BPF_JNE)
/* Comparing for equality, we can combine knowledge */
reg_combine_min_max(&other_branch->regs[insn->src_reg],
&other_branch->regs[insn->dst_reg],
®s[insn->src_reg],
®s[insn->dst_reg], opcode);
}
} else if (dst_reg->type == SCALAR_VALUE) {
reg_set_min_max(&other_branch->regs[insn->dst_reg],
dst_reg, insn->imm, opcode);
}
/* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
if (BPF_SRC(insn->code) == BPF_K &&
insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
/* Mark all identical map registers in each branch as either
* safe or unknown depending R == 0 or R != 0 conditional.
*/
mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
} else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
this_branch, other_branch) &&
is_pointer_value(env, insn->dst_reg)) {
verbose(env, "R%d pointer comparison prohibited\n",
insn->dst_reg);
return -EACCES;
}
if (env->log.level)
print_verifier_state(env, this_branch);
return 0;
}
/* return the map pointer stored inside BPF_LD_IMM64 instruction */
static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
{
u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
return (struct bpf_map *) (unsigned long) imm64;
}
/* verify BPF_LD_IMM64 instruction */
static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
int err;
if (BPF_SIZE(insn->code) != BPF_DW) {
verbose(env, "invalid BPF_LD_IMM insn\n");
return -EINVAL;
}
if (insn->off != 0) {
verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
return -EINVAL;
}
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
if (insn->src_reg == 0) {
u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
regs[insn->dst_reg].type = SCALAR_VALUE;
__mark_reg_known(®s[insn->dst_reg], imm);
return 0;
}
/* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
return 0;
}
static bool may_access_skb(enum bpf_prog_type type)
{
switch (type) {
case BPF_PROG_TYPE_SOCKET_FILTER:
case BPF_PROG_TYPE_SCHED_CLS:
case BPF_PROG_TYPE_SCHED_ACT:
return true;
default:
return false;
}
}
/* verify safety of LD_ABS|LD_IND instructions:
* - they can only appear in the programs where ctx == skb
* - since they are wrappers of function calls, they scratch R1-R5 registers,
* preserve R6-R9, and store return value into R0
*
* Implicit input:
* ctx == skb == R6 == CTX
*
* Explicit input:
* SRC == any register
* IMM == 32-bit immediate
*
* Output:
* R0 - 8/16/32-bit skb data converted to cpu endianness
*/
static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 mode = BPF_MODE(insn->code);
int i, err;
if (!may_access_skb(env->prog->type)) {
verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
return -EINVAL;
}
if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
BPF_SIZE(insn->code) == BPF_DW ||
(mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
return -EINVAL;
}
/* check whether implicit source operand (register R6) is readable */
err = check_reg_arg(env, BPF_REG_6, SRC_OP);
if (err)
return err;
if (regs[BPF_REG_6].type != PTR_TO_CTX) {
verbose(env,
"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
return -EINVAL;
}
if (mode == BPF_IND) {
/* check explicit source operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
}
/* reset caller saved regs to unreadable */
for (i = 0; i < CALLER_SAVED_REGS; i++) {
mark_reg_not_init(env, regs, caller_saved[i]);
check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
}
/* mark destination R0 register as readable, since it contains
* the value fetched from the packet.
* Already marked as written above.
*/
mark_reg_unknown(env, regs, BPF_REG_0);
return 0;
}
static int check_return_code(struct bpf_verifier_env *env)
{
struct bpf_reg_state *reg;
struct tnum range = tnum_range(0, 1);
switch (env->prog->type) {
case BPF_PROG_TYPE_CGROUP_SKB:
case BPF_PROG_TYPE_CGROUP_SOCK:
case BPF_PROG_TYPE_SOCK_OPS:
case BPF_PROG_TYPE_CGROUP_DEVICE:
break;
default:
return 0;
}
reg = cur_regs(env) + BPF_REG_0;
if (reg->type != SCALAR_VALUE) {
verbose(env, "At program exit the register R0 is not a known value (%s)\n",
reg_type_str[reg->type]);
return -EINVAL;
}
if (!tnum_in(range, reg->var_off)) {
verbose(env, "At program exit the register R0 ");
if (!tnum_is_unknown(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "has value %s", tn_buf);
} else {
verbose(env, "has unknown scalar value");
}
verbose(env, " should have been 0 or 1\n");
return -EINVAL;
}
return 0;
}
/* non-recursive DFS pseudo code
* 1 procedure DFS-iterative(G,v):
* 2 label v as discovered
* 3 let S be a stack
* 4 S.push(v)
* 5 while S is not empty
* 6 t <- S.pop()
* 7 if t is what we're looking for:
* 8 return t
* 9 for all edges e in G.adjacentEdges(t) do
* 10 if edge e is already labelled
* 11 continue with the next edge
* 12 w <- G.adjacentVertex(t,e)
* 13 if vertex w is not discovered and not explored
* 14 label e as tree-edge
* 15 label w as discovered
* 16 S.push(w)
* 17 continue at 5
* 18 else if vertex w is discovered
* 19 label e as back-edge
* 20 else
* 21 // vertex w is explored
* 22 label e as forward- or cross-edge
* 23 label t as explored
* 24 S.pop()
*
* convention:
* 0x10 - discovered
* 0x11 - discovered and fall-through edge labelled
* 0x12 - discovered and fall-through and branch edges labelled
* 0x20 - explored
*/
enum {
DISCOVERED = 0x10,
EXPLORED = 0x20,
FALLTHROUGH = 1,
BRANCH = 2,
};
#define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
static int *insn_stack; /* stack of insns to process */
static int cur_stack; /* current stack index */
static int *insn_state;
/* t, w, e - match pseudo-code above:
* t - index of current instruction
* w - next instruction
* e - edge
*/
static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
{
if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
return 0;
if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
return 0;
if (w < 0 || w >= env->prog->len) {
verbose(env, "jump out of range from insn %d to %d\n", t, w);
return -EINVAL;
}
if (e == BRANCH)
/* mark branch target for state pruning */
env->explored_states[w] = STATE_LIST_MARK;
if (insn_state[w] == 0) {
/* tree-edge */
insn_state[t] = DISCOVERED | e;
insn_state[w] = DISCOVERED;
if (cur_stack >= env->prog->len)
return -E2BIG;
insn_stack[cur_stack++] = w;
return 1;
} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
verbose(env, "back-edge from insn %d to %d\n", t, w);
return -EINVAL;
} else if (insn_state[w] == EXPLORED) {
/* forward- or cross-edge */
insn_state[t] = DISCOVERED | e;
} else {
verbose(env, "insn state internal bug\n");
return -EFAULT;
}
return 0;
}
/* non-recursive depth-first-search to detect loops in BPF program
* loop == back-edge in directed graph
*/
static int check_cfg(struct bpf_verifier_env *env)
{
struct bpf_insn *insns = env->prog->insnsi;
int insn_cnt = env->prog->len;
int ret = 0;
int i, t;
insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
if (!insn_state)
return -ENOMEM;
insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
if (!insn_stack) {
kfree(insn_state);
return -ENOMEM;
}
insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
insn_stack[0] = 0; /* 0 is the first instruction */
cur_stack = 1;
peek_stack:
if (cur_stack == 0)
goto check_state;
t = insn_stack[cur_stack - 1];
if (BPF_CLASS(insns[t].code) == BPF_JMP) {
u8 opcode = BPF_OP(insns[t].code);
if (opcode == BPF_EXIT) {
goto mark_explored;
} else if (opcode == BPF_CALL) {
ret = push_insn(t, t + 1, FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
if (t + 1 < insn_cnt)
env->explored_states[t + 1] = STATE_LIST_MARK;
} else if (opcode == BPF_JA) {
if (BPF_SRC(insns[t].code) != BPF_K) {
ret = -EINVAL;
goto err_free;
}
/* unconditional jump with single edge */
ret = push_insn(t, t + insns[t].off + 1,
FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
/* tell verifier to check for equivalent states
* after every call and jump
*/
if (t + 1 < insn_cnt)
env->explored_states[t + 1] = STATE_LIST_MARK;
} else {
/* conditional jump with two edges */
env->explored_states[t] = STATE_LIST_MARK;
ret = push_insn(t, t + 1, FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
}
} else {
/* all other non-branch instructions with single
* fall-through edge
*/
ret = push_insn(t, t + 1, FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
}
mark_explored:
insn_state[t] = EXPLORED;
if (cur_stack-- <= 0) {
verbose(env, "pop stack internal bug\n");
ret = -EFAULT;
goto err_free;
}
goto peek_stack;
check_state:
for (i = 0; i < insn_cnt; i++) {
if (insn_state[i] != EXPLORED) {
verbose(env, "unreachable insn %d\n", i);
ret = -EINVAL;
goto err_free;
}
}
ret = 0; /* cfg looks good */
err_free:
kfree(insn_state);
kfree(insn_stack);
return ret;
}
/* check %cur's range satisfies %old's */
static bool range_within(struct bpf_reg_state *old,
struct bpf_reg_state *cur)
{
return old->umin_value <= cur->umin_value &&
old->umax_value >= cur->umax_value &&
old->smin_value <= cur->smin_value &&
old->smax_value >= cur->smax_value;
}
/* Maximum number of register states that can exist at once */
#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
struct idpair {
u32 old;
u32 cur;
};
/* If in the old state two registers had the same id, then they need to have
* the same id in the new state as well. But that id could be different from
* the old state, so we need to track the mapping from old to new ids.
* Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
* regs with old id 5 must also have new id 9 for the new state to be safe. But
* regs with a different old id could still have new id 9, we don't care about
* that.
* So we look through our idmap to see if this old id has been seen before. If
* so, we require the new id to match; otherwise, we add the id pair to the map.
*/
static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
{
unsigned int i;
for (i = 0; i < ID_MAP_SIZE; i++) {
if (!idmap[i].old) {
/* Reached an empty slot; haven't seen this id before */
idmap[i].old = old_id;
idmap[i].cur = cur_id;
return true;
}
if (idmap[i].old == old_id)
return idmap[i].cur == cur_id;
}
/* We ran out of idmap slots, which should be impossible */
WARN_ON_ONCE(1);
return false;
}
/* Returns true if (rold safe implies rcur safe) */
static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
struct idpair *idmap)
{
if (!(rold->live & REG_LIVE_READ))
/* explored state didn't use this */
return true;
if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0)
return true;
if (rold->type == NOT_INIT)
/* explored state can't have used this */
return true;
if (rcur->type == NOT_INIT)
return false;
switch (rold->type) {
case SCALAR_VALUE:
if (rcur->type == SCALAR_VALUE) {
/* new val must satisfy old val knowledge */
return range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
} else {
/* if we knew anything about the old value, we're not
* equal, because we can't know anything about the
* scalar value of the pointer in the new value.
*/
return rold->umin_value == 0 &&
rold->umax_value == U64_MAX &&
rold->smin_value == S64_MIN &&
rold->smax_value == S64_MAX &&
tnum_is_unknown(rold->var_off);
}
case PTR_TO_MAP_VALUE:
/* If the new min/max/var_off satisfy the old ones and
* everything else matches, we are OK.
* We don't care about the 'id' value, because nothing
* uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
*/
return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_MAP_VALUE_OR_NULL:
/* a PTR_TO_MAP_VALUE could be safe to use as a
* PTR_TO_MAP_VALUE_OR_NULL into the same map.
* However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
* checked, doing so could have affected others with the same
* id, and we can't check for that because we lost the id when
* we converted to a PTR_TO_MAP_VALUE.
*/
if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
return false;
if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
return false;
/* Check our ids match any regs they're supposed to */
return check_ids(rold->id, rcur->id, idmap);
case PTR_TO_PACKET_META:
case PTR_TO_PACKET:
if (rcur->type != rold->type)
return false;
/* We must have at least as much range as the old ptr
* did, so that any accesses which were safe before are
* still safe. This is true even if old range < old off,
* since someone could have accessed through (ptr - k), or
* even done ptr -= k in a register, to get a safe access.
*/
if (rold->range > rcur->range)
return false;
/* If the offsets don't match, we can't trust our alignment;
* nor can we be sure that we won't fall out of range.
*/
if (rold->off != rcur->off)
return false;
/* id relations must be preserved */
if (rold->id && !check_ids(rold->id, rcur->id, idmap))
return false;
/* new val must satisfy old val knowledge */
return range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_CTX:
case CONST_PTR_TO_MAP:
case PTR_TO_STACK:
case PTR_TO_PACKET_END:
/* Only valid matches are exact, which memcmp() above
* would have accepted
*/
default:
/* Don't know what's going on, just say it's not safe */
return false;
}
/* Shouldn't get here; if we do, say it's not safe */
WARN_ON_ONCE(1);
return false;
}
static bool stacksafe(struct bpf_verifier_state *old,
struct bpf_verifier_state *cur,
struct idpair *idmap)
{
int i, spi;
/* if explored stack has more populated slots than current stack
* such stacks are not equivalent
*/
if (old->allocated_stack > cur->allocated_stack)
return false;
/* walk slots of the explored stack and ignore any additional
* slots in the current stack, since explored(safe) state
* didn't use them
*/
for (i = 0; i < old->allocated_stack; i++) {
spi = i / BPF_REG_SIZE;
if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
continue;
if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
cur->stack[spi].slot_type[i % BPF_REG_SIZE])
/* Ex: old explored (safe) state has STACK_SPILL in
* this stack slot, but current has has STACK_MISC ->
* this verifier states are not equivalent,
* return false to continue verification of this path
*/
return false;
if (i % BPF_REG_SIZE)
continue;
if (old->stack[spi].slot_type[0] != STACK_SPILL)
continue;
if (!regsafe(&old->stack[spi].spilled_ptr,
&cur->stack[spi].spilled_ptr,
idmap))
/* when explored and current stack slot are both storing
* spilled registers, check that stored pointers types
* are the same as well.
* Ex: explored safe path could have stored
* (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
* but current path has stored:
* (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
* such verifier states are not equivalent.
* return false to continue verification of this path
*/
return false;
}
return true;
}
/* compare two verifier states
*
* all states stored in state_list are known to be valid, since
* verifier reached 'bpf_exit' instruction through them
*
* this function is called when verifier exploring different branches of
* execution popped from the state stack. If it sees an old state that has
* more strict register state and more strict stack state then this execution
* branch doesn't need to be explored further, since verifier already
* concluded that more strict state leads to valid finish.
*
* Therefore two states are equivalent if register state is more conservative
* and explored stack state is more conservative than the current one.
* Example:
* explored current
* (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
* (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
*
* In other words if current stack state (one being explored) has more
* valid slots than old one that already passed validation, it means
* the verifier can stop exploring and conclude that current state is valid too
*
* Similarly with registers. If explored state has register type as invalid
* whereas register type in current state is meaningful, it means that
* the current state will reach 'bpf_exit' instruction safely
*/
static bool states_equal(struct bpf_verifier_env *env,
struct bpf_verifier_state *old,
struct bpf_verifier_state *cur)
{
struct idpair *idmap;
bool ret = false;
int i;
idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
/* If we failed to allocate the idmap, just say it's not safe */
if (!idmap)
return false;
for (i = 0; i < MAX_BPF_REG; i++) {
if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
goto out_free;
}
if (!stacksafe(old, cur, idmap))
goto out_free;
ret = true;
out_free:
kfree(idmap);
return ret;
}
/* A write screens off any subsequent reads; but write marks come from the
* straight-line code between a state and its parent. When we arrive at a
* jump target (in the first iteration of the propagate_liveness() loop),
* we didn't arrive by the straight-line code, so read marks in state must
* propagate to parent regardless of state's write marks.
*/
static bool do_propagate_liveness(const struct bpf_verifier_state *state,
struct bpf_verifier_state *parent)
{
bool writes = parent == state->parent; /* Observe write marks */
bool touched = false; /* any changes made? */
int i;
if (!parent)
return touched;
/* Propagate read liveness of registers... */
BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
/* We don't need to worry about FP liveness because it's read-only */
for (i = 0; i < BPF_REG_FP; i++) {
if (parent->regs[i].live & REG_LIVE_READ)
continue;
if (writes && (state->regs[i].live & REG_LIVE_WRITTEN))
continue;
if (state->regs[i].live & REG_LIVE_READ) {
parent->regs[i].live |= REG_LIVE_READ;
touched = true;
}
}
/* ... and stack slots */
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
i < parent->allocated_stack / BPF_REG_SIZE; i++) {
if (parent->stack[i].slot_type[0] != STACK_SPILL)
continue;
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
continue;
if (writes &&
(state->stack[i].spilled_ptr.live & REG_LIVE_WRITTEN))
continue;
if (state->stack[i].spilled_ptr.live & REG_LIVE_READ) {
parent->stack[i].spilled_ptr.live |= REG_LIVE_READ;
touched = true;
}
}
return touched;
}
/* "parent" is "a state from which we reach the current state", but initially
* it is not the state->parent (i.e. "the state whose straight-line code leads
* to the current state"), instead it is the state that happened to arrive at
* a (prunable) equivalent of the current state. See comment above
* do_propagate_liveness() for consequences of this.
* This function is just a more efficient way of calling mark_reg_read() or
* mark_stack_slot_read() on each reg in "parent" that is read in "state",
* though it requires that parent != state->parent in the call arguments.
*/
static void propagate_liveness(const struct bpf_verifier_state *state,
struct bpf_verifier_state *parent)
{
while (do_propagate_liveness(state, parent)) {
/* Something changed, so we need to feed those changes onward */
state = parent;
parent = state->parent;
}
}
static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
{
struct bpf_verifier_state_list *new_sl;
struct bpf_verifier_state_list *sl;
struct bpf_verifier_state *cur = env->cur_state;
int i, err;
sl = env->explored_states[insn_idx];
if (!sl)
/* this 'insn_idx' instruction wasn't marked, so we will not
* be doing state search here
*/
return 0;
while (sl != STATE_LIST_MARK) {
if (states_equal(env, &sl->state, cur)) {
/* reached equivalent register/stack state,
* prune the search.
* Registers read by the continuation are read by us.
* If we have any write marks in env->cur_state, they
* will prevent corresponding reads in the continuation
* from reaching our parent (an explored_state). Our
* own state will get the read marks recorded, but
* they'll be immediately forgotten as we're pruning
* this state and will pop a new one.
*/
propagate_liveness(&sl->state, cur);
return 1;
}
sl = sl->next;
}
/* there were no equivalent states, remember current one.
* technically the current state is not proven to be safe yet,
* but it will either reach bpf_exit (which means it's safe) or
* it will be rejected. Since there are no loops, we won't be
* seeing this 'insn_idx' instruction again on the way to bpf_exit
*/
new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
if (!new_sl)
return -ENOMEM;
/* add new state to the head of linked list */
err = copy_verifier_state(&new_sl->state, cur);
if (err) {
free_verifier_state(&new_sl->state, false);
kfree(new_sl);
return err;
}
new_sl->next = env->explored_states[insn_idx];
env->explored_states[insn_idx] = new_sl;
/* connect new state to parentage chain */
cur->parent = &new_sl->state;
/* clear write marks in current state: the writes we did are not writes
* our child did, so they don't screen off its reads from us.
* (There are no read marks in current state, because reads always mark
* their parent and current state never has children yet. Only
* explored_states can get read marks.)
*/
for (i = 0; i < BPF_REG_FP; i++)
cur->regs[i].live = REG_LIVE_NONE;
for (i = 0; i < cur->allocated_stack / BPF_REG_SIZE; i++)
if (cur->stack[i].slot_type[0] == STACK_SPILL)
cur->stack[i].spilled_ptr.live = REG_LIVE_NONE;
return 0;
}
static int ext_analyzer_insn_hook(struct bpf_verifier_env *env,
int insn_idx, int prev_insn_idx)
{
if (env->dev_ops && env->dev_ops->insn_hook)
return env->dev_ops->insn_hook(env, insn_idx, prev_insn_idx);
return 0;
}
static int do_check(struct bpf_verifier_env *env)
{
struct bpf_verifier_state *state;
struct bpf_insn *insns = env->prog->insnsi;
struct bpf_reg_state *regs;
int insn_cnt = env->prog->len;
int insn_idx, prev_insn_idx = 0;
int insn_processed = 0;
bool do_print_state = false;
state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
if (!state)
return -ENOMEM;
env->cur_state = state;
init_reg_state(env, state->regs);
state->parent = NULL;
insn_idx = 0;
for (;;) {
struct bpf_insn *insn;
u8 class;
int err;
if (insn_idx >= insn_cnt) {
verbose(env, "invalid insn idx %d insn_cnt %d\n",
insn_idx, insn_cnt);
return -EFAULT;
}
insn = &insns[insn_idx];
class = BPF_CLASS(insn->code);
if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
verbose(env,
"BPF program is too large. Processed %d insn\n",
insn_processed);
return -E2BIG;
}
err = is_state_visited(env, insn_idx);
if (err < 0)
return err;
if (err == 1) {
/* found equivalent state, can prune the search */
if (env->log.level) {
if (do_print_state)
verbose(env, "\nfrom %d to %d: safe\n",
prev_insn_idx, insn_idx);
else
verbose(env, "%d: safe\n", insn_idx);
}
goto process_bpf_exit;
}
if (need_resched())
cond_resched();
if (env->log.level > 1 || (env->log.level && do_print_state)) {
if (env->log.level > 1)
verbose(env, "%d:", insn_idx);
else
verbose(env, "\nfrom %d to %d:",
prev_insn_idx, insn_idx);
print_verifier_state(env, state);
do_print_state = false;
}
if (env->log.level) {
verbose(env, "%d: ", insn_idx);
print_bpf_insn(verbose, env, insn,
env->allow_ptr_leaks);
}
err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);
if (err)
return err;
regs = cur_regs(env);
env->insn_aux_data[insn_idx].seen = true;
if (class == BPF_ALU || class == BPF_ALU64) {
err = check_alu_op(env, insn);
if (err)
return err;
} else if (class == BPF_LDX) {
enum bpf_reg_type *prev_src_type, src_reg_type;
/* check for reserved fields is already done */
/* check src operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
src_reg_type = regs[insn->src_reg].type;
/* check that memory (src_reg + off) is readable,
* the state of dst_reg will be updated by this func
*/
err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
BPF_SIZE(insn->code), BPF_READ,
insn->dst_reg);
if (err)
return err;
prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
if (*prev_src_type == NOT_INIT) {
/* saw a valid insn
* dst_reg = *(u32 *)(src_reg + off)
* save type to validate intersecting paths
*/
*prev_src_type = src_reg_type;
} else if (src_reg_type != *prev_src_type &&
(src_reg_type == PTR_TO_CTX ||
*prev_src_type == PTR_TO_CTX)) {
/* ABuser program is trying to use the same insn
* dst_reg = *(u32*) (src_reg + off)
* with different pointer types:
* src_reg == ctx in one branch and
* src_reg == stack|map in some other branch.
* Reject it.
*/
verbose(env, "same insn cannot be used with different pointers\n");
return -EINVAL;
}
} else if (class == BPF_STX) {
enum bpf_reg_type *prev_dst_type, dst_reg_type;
if (BPF_MODE(insn->code) == BPF_XADD) {
err = check_xadd(env, insn_idx, insn);
if (err)
return err;
insn_idx++;
continue;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
dst_reg_type = regs[insn->dst_reg].type;
/* check that memory (dst_reg + off) is writeable */
err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE,
insn->src_reg);
if (err)
return err;
prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
if (*prev_dst_type == NOT_INIT) {
*prev_dst_type = dst_reg_type;
} else if (dst_reg_type != *prev_dst_type &&
(dst_reg_type == PTR_TO_CTX ||
*prev_dst_type == PTR_TO_CTX)) {
verbose(env, "same insn cannot be used with different pointers\n");
return -EINVAL;
}
} else if (class == BPF_ST) {
if (BPF_MODE(insn->code) != BPF_MEM ||
insn->src_reg != BPF_REG_0) {
verbose(env, "BPF_ST uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
/* check that memory (dst_reg + off) is writeable */
err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE,
-1);
if (err)
return err;
} else if (class == BPF_JMP) {
u8 opcode = BPF_OP(insn->code);
if (opcode == BPF_CALL) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->off != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_CALL uses reserved fields\n");
return -EINVAL;
}
err = check_call(env, insn->imm, insn_idx);
if (err)
return err;
} else if (opcode == BPF_JA) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->imm != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_JA uses reserved fields\n");
return -EINVAL;
}
insn_idx += insn->off + 1;
continue;
} else if (opcode == BPF_EXIT) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->imm != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_EXIT uses reserved fields\n");
return -EINVAL;
}
/* eBPF calling convetion is such that R0 is used
* to return the value from eBPF program.
* Make sure that it's readable at this time
* of bpf_exit, which means that program wrote
* something into it earlier
*/
err = check_reg_arg(env, BPF_REG_0, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, BPF_REG_0)) {
verbose(env, "R0 leaks addr as return value\n");
return -EACCES;
}
err = check_return_code(env);
if (err)
return err;
process_bpf_exit:
err = pop_stack(env, &prev_insn_idx, &insn_idx);
if (err < 0) {
if (err != -ENOENT)
return err;
break;
} else {
do_print_state = true;
continue;
}
} else {
err = check_cond_jmp_op(env, insn, &insn_idx);
if (err)
return err;
}
} else if (class == BPF_LD) {
u8 mode = BPF_MODE(insn->code);
if (mode == BPF_ABS || mode == BPF_IND) {
err = check_ld_abs(env, insn);
if (err)
return err;
} else if (mode == BPF_IMM) {
err = check_ld_imm(env, insn);
if (err)
return err;
insn_idx++;
env->insn_aux_data[insn_idx].seen = true;
} else {
verbose(env, "invalid BPF_LD mode\n");
return -EINVAL;
}
} else {
verbose(env, "unknown insn class %d\n", class);
return -EINVAL;
}
insn_idx++;
}
verbose(env, "processed %d insns, stack depth %d\n", insn_processed,
env->prog->aux->stack_depth);
return 0;
}
static int check_map_prealloc(struct bpf_map *map)
{
return (map->map_type != BPF_MAP_TYPE_HASH &&
map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
!(map->map_flags & BPF_F_NO_PREALLOC);
}
static int check_map_prog_compatibility(struct bpf_verifier_env *env,
struct bpf_map *map,
struct bpf_prog *prog)
{
/* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
* preallocated hash maps, since doing memory allocation
* in overflow_handler can crash depending on where nmi got
* triggered.
*/
if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
if (!check_map_prealloc(map)) {
verbose(env, "perf_event programs can only use preallocated hash map\n");
return -EINVAL;
}
if (map->inner_map_meta &&
!check_map_prealloc(map->inner_map_meta)) {
verbose(env, "perf_event programs can only use preallocated inner hash map\n");
return -EINVAL;
}
}
return 0;
}
/* look for pseudo eBPF instructions that access map FDs and
* replace them with actual map pointers
*/
static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
{
struct bpf_insn *insn = env->prog->insnsi;
int insn_cnt = env->prog->len;
int i, j, err;
err = bpf_prog_calc_tag(env->prog);
if (err)
return err;
for (i = 0; i < insn_cnt; i++, insn++) {
if (BPF_CLASS(insn->code) == BPF_LDX &&
(BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
verbose(env, "BPF_LDX uses reserved fields\n");
return -EINVAL;
}
if (BPF_CLASS(insn->code) == BPF_STX &&
((BPF_MODE(insn->code) != BPF_MEM &&
BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
verbose(env, "BPF_STX uses reserved fields\n");
return -EINVAL;
}
if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
struct bpf_map *map;
struct fd f;
if (i == insn_cnt - 1 || insn[1].code != 0 ||
insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
insn[1].off != 0) {
verbose(env, "invalid bpf_ld_imm64 insn\n");
return -EINVAL;
}
if (insn->src_reg == 0)
/* valid generic load 64-bit imm */
goto next_insn;
if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
verbose(env,
"unrecognized bpf_ld_imm64 insn\n");
return -EINVAL;
}
f = fdget(insn->imm);
map = __bpf_map_get(f);
if (IS_ERR(map)) {
verbose(env, "fd %d is not pointing to valid bpf_map\n",
insn->imm);
return PTR_ERR(map);
}
err = check_map_prog_compatibility(env, map, env->prog);
if (err) {
fdput(f);
return err;
}
/* store map pointer inside BPF_LD_IMM64 instruction */
insn[0].imm = (u32) (unsigned long) map;
insn[1].imm = ((u64) (unsigned long) map) >> 32;
/* check whether we recorded this map already */
for (j = 0; j < env->used_map_cnt; j++)
if (env->used_maps[j] == map) {
fdput(f);
goto next_insn;
}
if (env->used_map_cnt >= MAX_USED_MAPS) {
fdput(f);
return -E2BIG;
}
/* hold the map. If the program is rejected by verifier,
* the map will be released by release_maps() or it
* will be used by the valid program until it's unloaded
* and all maps are released in free_bpf_prog_info()
*/
map = bpf_map_inc(map, false);
if (IS_ERR(map)) {
fdput(f);
return PTR_ERR(map);
}
env->used_maps[env->used_map_cnt++] = map;
fdput(f);
next_insn:
insn++;
i++;
}
}
/* now all pseudo BPF_LD_IMM64 instructions load valid
* 'struct bpf_map *' into a register instead of user map_fd.
* These pointers will be used later by verifier to validate map access.
*/
return 0;
}
/* drop refcnt of maps used by the rejected program */
static void release_maps(struct bpf_verifier_env *env)
{
int i;
for (i = 0; i < env->used_map_cnt; i++)
bpf_map_put(env->used_maps[i]);
}
/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
{
struct bpf_insn *insn = env->prog->insnsi;
int insn_cnt = env->prog->len;
int i;
for (i = 0; i < insn_cnt; i++, insn++)
if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
insn->src_reg = 0;
}
/* single env->prog->insni[off] instruction was replaced with the range
* insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
* [0, off) and [off, end) to new locations, so the patched range stays zero
*/
static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
u32 off, u32 cnt)
{
struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
int i;
if (cnt == 1)
return 0;
new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
if (!new_data)
return -ENOMEM;
memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
memcpy(new_data + off + cnt - 1, old_data + off,
sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
for (i = off; i < off + cnt - 1; i++)
new_data[i].seen = true;
env->insn_aux_data = new_data;
vfree(old_data);
return 0;
}
static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
const struct bpf_insn *patch, u32 len)
{
struct bpf_prog *new_prog;
new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
if (!new_prog)
return NULL;
if (adjust_insn_aux_data(env, new_prog->len, off, len))
return NULL;
return new_prog;
}
/* The verifier does more data flow analysis than llvm and will not explore
* branches that are dead at run time. Malicious programs can have dead code
* too. Therefore replace all dead at-run-time code with nops.
*/
static void sanitize_dead_code(struct bpf_verifier_env *env)
{
struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
struct bpf_insn nop = BPF_MOV64_REG(BPF_REG_0, BPF_REG_0);
struct bpf_insn *insn = env->prog->insnsi;
const int insn_cnt = env->prog->len;
int i;
for (i = 0; i < insn_cnt; i++) {
if (aux_data[i].seen)
continue;
memcpy(insn + i, &nop, sizeof(nop));
}
}
/* convert load instructions that access fields of 'struct __sk_buff'
* into sequence of instructions that access fields of 'struct sk_buff'
*/
static int convert_ctx_accesses(struct bpf_verifier_env *env)
{
const struct bpf_verifier_ops *ops = env->ops;
int i, cnt, size, ctx_field_size, delta = 0;
const int insn_cnt = env->prog->len;
struct bpf_insn insn_buf[16], *insn;
struct bpf_prog *new_prog;
enum bpf_access_type type;
bool is_narrower_load;
u32 target_size;
if (ops->gen_prologue) {
cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
env->prog);
if (cnt >= ARRAY_SIZE(insn_buf)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
} else if (cnt) {
new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
env->prog = new_prog;
delta += cnt - 1;
}
}
if (!ops->convert_ctx_access)
return 0;
insn = env->prog->insnsi + delta;
for (i = 0; i < insn_cnt; i++, insn++) {
if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
type = BPF_READ;
else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
insn->code == (BPF_STX | BPF_MEM | BPF_DW))
type = BPF_WRITE;
else
continue;
if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
continue;
ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
size = BPF_LDST_BYTES(insn);
/* If the read access is a narrower load of the field,
* convert to a 4/8-byte load, to minimum program type specific
* convert_ctx_access changes. If conversion is successful,
* we will apply proper mask to the result.
*/
is_narrower_load = size < ctx_field_size;
if (is_narrower_load) {
u32 off = insn->off;
u8 size_code;
if (type == BPF_WRITE) {
verbose(env, "bpf verifier narrow ctx access misconfigured\n");
return -EINVAL;
}
size_code = BPF_H;
if (ctx_field_size == 4)
size_code = BPF_W;
else if (ctx_field_size == 8)
size_code = BPF_DW;
insn->off = off & ~(ctx_field_size - 1);
insn->code = BPF_LDX | BPF_MEM | size_code;
}
target_size = 0;
cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
&target_size);
if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
(ctx_field_size && !target_size)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
}
if (is_narrower_load && size < target_size) {
if (ctx_field_size <= 4)
insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
(1 << size * 8) - 1);
else
insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
(1 << size * 8) - 1);
}
new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
/* keep walking new program and skip insns we just inserted */
env->prog = new_prog;
insn = new_prog->insnsi + i + delta;
}
return 0;
}
/* fixup insn->imm field of bpf_call instructions
* and inline eligible helpers as explicit sequence of BPF instructions
*
* this function is called after eBPF program passed verification
*/
static int fixup_bpf_calls(struct bpf_verifier_env *env)
{
struct bpf_prog *prog = env->prog;
struct bpf_insn *insn = prog->insnsi;
const struct bpf_func_proto *fn;
const int insn_cnt = prog->len;
struct bpf_insn insn_buf[16];
struct bpf_prog *new_prog;
struct bpf_map *map_ptr;
int i, cnt, delta = 0;
for (i = 0; i < insn_cnt; i++, insn++) {
if (insn->code != (BPF_JMP | BPF_CALL))
continue;
if (insn->imm == BPF_FUNC_get_route_realm)
prog->dst_needed = 1;
if (insn->imm == BPF_FUNC_get_prandom_u32)
bpf_user_rnd_init_once();
if (insn->imm == BPF_FUNC_tail_call) {
/* If we tail call into other programs, we
* cannot make any assumptions since they can
* be replaced dynamically during runtime in
* the program array.
*/
prog->cb_access = 1;
env->prog->aux->stack_depth = MAX_BPF_STACK;
/* mark bpf_tail_call as different opcode to avoid
* conditional branch in the interpeter for every normal
* call and to prevent accidental JITing by JIT compiler
* that doesn't support bpf_tail_call yet
*/
insn->imm = 0;
insn->code = BPF_JMP | BPF_TAIL_CALL;
continue;
}
/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
* handlers are currently limited to 64 bit only.
*/
if (ebpf_jit_enabled() && BITS_PER_LONG == 64 &&
insn->imm == BPF_FUNC_map_lookup_elem) {
map_ptr = env->insn_aux_data[i + delta].map_ptr;
if (map_ptr == BPF_MAP_PTR_POISON ||
!map_ptr->ops->map_gen_lookup)
goto patch_call_imm;
cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf);
if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
}
new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
/* keep walking new program and skip insns we just inserted */
env->prog = prog = new_prog;
insn = new_prog->insnsi + i + delta;
continue;
}
if (insn->imm == BPF_FUNC_redirect_map) {
/* Note, we cannot use prog directly as imm as subsequent
* rewrites would still change the prog pointer. The only
* stable address we can use is aux, which also works with
* prog clones during blinding.
*/
u64 addr = (unsigned long)prog->aux;
struct bpf_insn r4_ld[] = {
BPF_LD_IMM64(BPF_REG_4, addr),
*insn,
};
cnt = ARRAY_SIZE(r4_ld);
new_prog = bpf_patch_insn_data(env, i + delta, r4_ld, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
env->prog = prog = new_prog;
insn = new_prog->insnsi + i + delta;
}
patch_call_imm:
fn = env->ops->get_func_proto(insn->imm);
/* all functions that have prototype and verifier allowed
* programs to call them, must be real in-kernel functions
*/
if (!fn->func) {
verbose(env,
"kernel subsystem misconfigured func %s#%d\n",
func_id_name(insn->imm), insn->imm);
return -EFAULT;
}
insn->imm = fn->func - __bpf_call_base;
}
return 0;
}
static void free_states(struct bpf_verifier_env *env)
{
struct bpf_verifier_state_list *sl, *sln;
int i;
if (!env->explored_states)
return;
for (i = 0; i < env->prog->len; i++) {
sl = env->explored_states[i];
if (sl)
while (sl != STATE_LIST_MARK) {
sln = sl->next;
free_verifier_state(&sl->state, false);
kfree(sl);
sl = sln;
}
}
kfree(env->explored_states);
}
int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
{
struct bpf_verifier_env *env;
struct bpf_verifer_log *log;
int ret = -EINVAL;
/* no program is valid */
if (ARRAY_SIZE(bpf_verifier_ops) == 0)
return -EINVAL;
/* 'struct bpf_verifier_env' can be global, but since it's not small,
* allocate/free it every time bpf_check() is called
*/
env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
if (!env)
return -ENOMEM;
log = &env->log;
env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
(*prog)->len);
ret = -ENOMEM;
if (!env->insn_aux_data)
goto err_free_env;
env->prog = *prog;
env->ops = bpf_verifier_ops[env->prog->type];
/* grab the mutex to protect few globals used by verifier */
mutex_lock(&bpf_verifier_lock);
if (attr->log_level || attr->log_buf || attr->log_size) {
/* user requested verbose verifier output
* and supplied buffer to store the verification trace
*/
log->level = attr->log_level;
log->ubuf = (char __user *) (unsigned long) attr->log_buf;
log->len_total = attr->log_size;
ret = -EINVAL;
/* log attributes have to be sane */
if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
!log->level || !log->ubuf)
goto err_unlock;
}
env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
env->strict_alignment = true;
if (env->prog->aux->offload) {
ret = bpf_prog_offload_verifier_prep(env);
if (ret)
goto err_unlock;
}
ret = replace_map_fd_with_map_ptr(env);
if (ret < 0)
goto skip_full_check;
env->explored_states = kcalloc(env->prog->len,
sizeof(struct bpf_verifier_state_list *),
GFP_USER);
ret = -ENOMEM;
if (!env->explored_states)
goto skip_full_check;
ret = check_cfg(env);
if (ret < 0)
goto skip_full_check;
env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
ret = do_check(env);
if (env->cur_state) {
free_verifier_state(env->cur_state, true);
env->cur_state = NULL;
}
skip_full_check:
while (!pop_stack(env, NULL, NULL));
free_states(env);
if (ret == 0)
sanitize_dead_code(env);
if (ret == 0)
/* program is valid, convert *(u32*)(ctx + off) accesses */
ret = convert_ctx_accesses(env);
if (ret == 0)
ret = fixup_bpf_calls(env);
if (log->level && bpf_verifier_log_full(log))
ret = -ENOSPC;
if (log->level && !log->ubuf) {
ret = -EFAULT;
goto err_release_maps;
}
if (ret == 0 && env->used_map_cnt) {
/* if program passed verifier, update used_maps in bpf_prog_info */
env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
sizeof(env->used_maps[0]),
GFP_KERNEL);
if (!env->prog->aux->used_maps) {
ret = -ENOMEM;
goto err_release_maps;
}
memcpy(env->prog->aux->used_maps, env->used_maps,
sizeof(env->used_maps[0]) * env->used_map_cnt);
env->prog->aux->used_map_cnt = env->used_map_cnt;
/* program is valid. Convert pseudo bpf_ld_imm64 into generic
* bpf_ld_imm64 instructions
*/
convert_pseudo_ld_imm64(env);
}
err_release_maps:
if (!env->prog->aux->used_maps)
/* if we didn't copy map pointers into bpf_prog_info, release
* them now. Otherwise free_bpf_prog_info() will release them.
*/
release_maps(env);
*prog = env->prog;
err_unlock:
mutex_unlock(&bpf_verifier_lock);
vfree(env->insn_aux_data);
err_free_env:
kfree(env);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2987_0 |
crossvul-cpp_data_good_939_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP N N M M %
% P P NN N MM MM %
% PPPP N N N M M M %
% P N NN M M %
% P N N M M %
% %
% %
% Read/Write PBMPlus Portable Anymap Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/pixel-private.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
/*
Typedef declarations.
*/
typedef struct _CommentInfo
{
char
*comment;
size_t
extent;
} CommentInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WritePNMImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P N M %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPNM() returns MagickTrue if the image format type, identified by the
% magick string, is PNM.
%
% The format of the IsPNM method is:
%
% MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o extent: Specifies the extent of the magick string.
%
*/
static MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent)
{
if (extent < 2)
return(MagickFalse);
if ((*magick == (unsigned char) 'P') &&
((magick[1] == '1') || (magick[1] == '2') || (magick[1] == '3') ||
(magick[1] == '4') || (magick[1] == '5') || (magick[1] == '6') ||
(magick[1] == '7') || (magick[1] == 'F') || (magick[1] == 'f')))
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPNMImage() reads a Portable Anymap image file and returns it.
% It allocates the memory necessary for the new Image structure and returns
% a pointer to the new image.
%
% The format of the ReadPNMImage method is:
%
% Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static int PNMComment(Image *image,CommentInfo *comment_info)
{
int
c;
register char
*p;
/*
Read comment.
*/
p=comment_info->comment+strlen(comment_info->comment);
for (c='#'; (c != EOF) && (c != (int) '\n') && (c != (int) '\r'); p++)
{
if ((size_t) (p-comment_info->comment+1) >= comment_info->extent)
{
comment_info->extent<<=1;
comment_info->comment=(char *) ResizeQuantumMemory(
comment_info->comment,comment_info->extent,
sizeof(*comment_info->comment));
if (comment_info->comment == (char *) NULL)
return(-1);
p=comment_info->comment+strlen(comment_info->comment);
}
c=ReadBlobByte(image);
if (c != EOF)
{
*p=(char) c;
*(p+1)='\0';
}
}
return(c);
}
static unsigned int PNMInteger(Image *image,CommentInfo *comment_info,
const unsigned int base)
{
int
c;
unsigned int
value;
/*
Skip any leading whitespace.
*/
do
{
c=ReadBlobByte(image);
if (c == EOF)
return(0);
if (c == (int) '#')
c=PNMComment(image,comment_info);
} while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r'));
if (base == 2)
return((unsigned int) (c-(int) '0'));
/*
Evaluate number.
*/
value=0;
while (isdigit(c) != 0)
{
if (value <= (unsigned int) (INT_MAX/10))
{
value*=10;
if (value <= (unsigned int) (INT_MAX-(c-(int) '0')))
value+=c-(int) '0';
}
c=ReadBlobByte(image);
if (c == EOF)
return(0);
}
if (c == (int) '#')
c=PNMComment(image,comment_info);
return(value);
}
static Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowPNMException(exception,message) \
{ \
if (comment_info.comment != (char *) NULL) \
comment_info.comment=DestroyString(comment_info.comment); \
ThrowReaderException((exception),(message)); \
}
char
format;
CommentInfo
comment_info;
double
quantum_scale;
Image
*image;
MagickBooleanType
status;
QuantumAny
max_value;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
size_t
depth,
extent,
packet_size;
ssize_t
count,
row,
y;
/*
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);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read PNM image.
*/
count=ReadBlob(image,1,(unsigned char *) &format);
do
{
/*
Initialize image structure.
*/
comment_info.comment=AcquireString(NULL);
comment_info.extent=MagickPathExtent;
if ((count != 1) || (format != 'P'))
ThrowPNMException(CorruptImageError,"ImproperImageHeader");
max_value=1;
quantum_type=RGBQuantum;
quantum_scale=1.0;
format=(char) ReadBlobByte(image);
if (format != '7')
{
/*
PBM, PGM, PPM, and PNM.
*/
image->columns=PNMInteger(image,&comment_info,10);
image->rows=PNMInteger(image,&comment_info,10);
if ((format == 'f') || (format == 'F'))
{
char
scale[MaxTextExtent];
if (ReadBlobString(image,scale) != (char *) NULL)
quantum_scale=StringToDouble(scale,(char **) NULL);
}
else
{
if ((format == '1') || (format == '4'))
max_value=1; /* bitmap */
else
max_value=PNMInteger(image,&comment_info,10);
}
}
else
{
char
keyword[MaxTextExtent],
value[MaxTextExtent];
int
c;
register char
*p;
/*
PAM.
*/
for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
{
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
if (c == '#')
{
/*
Comment.
*/
c=PNMComment(image,&comment_info);
c=ReadBlobByte(image);
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
p=keyword;
do
{
if ((size_t) (p-keyword) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
} while (isalnum(c));
*p='\0';
if (LocaleCompare(keyword,"endhdr") == 0)
break;
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
p=value;
while (isalnum(c) || (c == '_'))
{
if ((size_t) (p-value) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
}
*p='\0';
/*
Assign a value to the specified keyword.
*/
if (LocaleCompare(keyword,"depth") == 0)
packet_size=StringToUnsignedLong(value);
(void) packet_size;
if (LocaleCompare(keyword,"height") == 0)
image->rows=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"maxval") == 0)
max_value=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"TUPLTYPE") == 0)
{
if (LocaleCompare(value,"BLACKANDWHITE") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
}
if (LocaleCompare(value,"BLACKANDWHITE_ALPHA") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace);
image->matte=MagickTrue;
quantum_type=GrayAlphaQuantum;
}
if (LocaleCompare(value,"GRAYSCALE") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
}
if (LocaleCompare(value,"GRAYSCALE_ALPHA") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace);
image->matte=MagickTrue;
quantum_type=GrayAlphaQuantum;
}
if (LocaleCompare(value,"RGB_ALPHA") == 0)
{
quantum_type=RGBAQuantum;
image->matte=MagickTrue;
}
if (LocaleCompare(value,"CMYK") == 0)
{
(void) SetImageColorspace(image,CMYKColorspace);
quantum_type=CMYKQuantum;
}
if (LocaleCompare(value,"CMYK_ALPHA") == 0)
{
(void) SetImageColorspace(image,CMYKColorspace);
image->matte=MagickTrue;
quantum_type=CMYKAQuantum;
}
}
if (LocaleCompare(keyword,"width") == 0)
image->columns=StringToUnsignedLong(value);
}
}
if ((image->columns == 0) || (image->rows == 0))
ThrowPNMException(CorruptImageError,"NegativeOrZeroImageSize");
if ((max_value == 0) || (max_value > 4294967295U))
ThrowPNMException(CorruptImageError,"ImproperImageHeader");
for (depth=1; GetQuantumRange(depth) < max_value; depth++) ;
image->depth=depth;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((MagickSizeType) (image->columns*image->rows/8) > GetBlobSize(image))
ThrowPNMException(CorruptImageError,"InsufficientImageDataInFile");
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
(void) ResetImagePixels(image,exception);
/*
Convert PNM pixels.
*/
row=0;
switch (format)
{
case '1':
{
/*
Convert PBM image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace);
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
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,PNMInteger(image,&comment_info,2) == 0 ?
QuantumRange : 0);
if (EOFBlob(image) != MagickFalse)
break;
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
break;
}
image->type=BilevelType;
break;
}
case '2':
{
size_t
intensity;
/*
Convert PGM image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace);
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
intensity=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),
max_value);
if (EOFBlob(image) != MagickFalse)
break;
SetPixelRed(q,intensity);
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
break;
}
image->type=GrayscaleType;
break;
}
case '3':
{
/*
Convert PNM image to pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
QuantumAny
pixel;
pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),
max_value);
if (EOFBlob(image) != MagickFalse)
break;
SetPixelRed(q,pixel);
pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),
max_value);
SetPixelGreen(q,pixel);
pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),
max_value);
SetPixelBlue(q,pixel);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
break;
}
break;
}
case '4':
{
/*
Convert PBM raw image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
if (image->storage_class == PseudoClass)
quantum_type=IndexQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumMinIsWhite(quantum_info,MagickTrue);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register PixelPacket
*magick_restrict q;
ssize_t
count,
offset;
size_t
length;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (length != extent)
break;
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
case '5':
{
/*
Convert PGM raw image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
extent=(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*
image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
count,
offset;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
p=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
break;
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
case '6':
{
/*
Convert PNM raster image to pixel packets.
*/
quantum_type=RGBQuantum;
extent=3*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*
image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
count,
offset;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
p=pixels;
switch (image->depth)
{
case 8:
{
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
q->opacity=OpaqueOpacity;
q++;
}
break;
}
case 16:
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleShortToQuantum(pixel));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleShortToQuantum(pixel));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleShortToQuantum(pixel));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
case 32:
{
unsigned int
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleLongToQuantum(pixel));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleLongToQuantum(pixel));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleLongToQuantum(pixel));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
default:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
break;
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
register IndexPacket
*indexes;
size_t
channels;
/*
Convert PAM raster image to pixel packets.
*/
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
channels=1;
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
channels=4;
break;
}
default:
{
channels=3;
break;
}
}
if (image->matte != MagickFalse)
channels++;
extent=channels*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*
image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
ssize_t
count,
offset;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
p=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushCharPixel(p,&pixel);
if (image->depth != 1)
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
else
SetPixelOpacity(q,QuantumRange-ScaleAnyToQuantum(
pixel,max_value));
}
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value));
}
q++;
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel,
max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushCharPixel(p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel,
max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value));
}
q++;
}
break;
}
default:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushCharPixel(p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value));
}
q++;
}
break;
}
}
break;
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
case 'F':
case 'f':
{
/*
Convert PFM raster image to pixel packets.
*/
if (format == 'f')
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian;
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumDepth(image,quantum_info,32);
if (status == MagickFalse)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumScale(quantum_info,(MagickRealType) QuantumRange*
fabs(quantum_scale));
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register PixelPacket
*magick_restrict q;
ssize_t
count,
offset;
size_t
length;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if ((size_t) count != extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,(ssize_t) (image->rows-offset-1),
image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (length != extent)
break;
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
default:
ThrowPNMException(CorruptImageError,"ImproperImageHeader");
}
if (*comment_info.comment != '\0')
(void) SetImageProperty(image,"comment",comment_info.comment);
comment_info.comment=DestroyString(comment_info.comment);
if (y < (ssize_t) image->rows)
ThrowPNMException(CorruptImageError,"UnableToReadImageData");
if (EOFBlob(image) != MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"UnexpectedEndOfFile","`%s'",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;
if ((format == '1') || (format == '2') || (format == '3'))
do
{
/*
Skip to end of line.
*/
count=ReadBlob(image,1,(unsigned char *) &format);
if (count != 1)
break;
if (format == 'P')
break;
} while (format != '\n');
count=ReadBlob(image,1,(unsigned char *) &format);
if ((count == 1) && (format == 'P'))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
status=MagickFalse;
break;
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count == 1) && (format == 'P'));
(void) CloseBlob(image);
if (status == MagickFalse)
return(DestroyImageList(image));
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPNMImage() adds properties for the PNM image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterPNMImage method is:
%
% size_t RegisterPNMImage(void)
%
*/
ModuleExport size_t RegisterPNMImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("PAM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->description=ConstantString("Common 2-dimensional bitmap format");
entry->mime_type=ConstantString("image/x-portable-pixmap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PBM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->description=ConstantString("Portable bitmap format (black and white)");
entry->mime_type=ConstantString("image/x-portable-bitmap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PFM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->endian_support=MagickTrue;
entry->description=ConstantString("Portable float format");
entry->module=ConstantString("PFM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PGM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->description=ConstantString("Portable graymap format (gray scale)");
entry->mime_type=ConstantString("image/x-portable-greymap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->magick=(IsImageFormatHandler *) IsPNM;
entry->description=ConstantString("Portable anymap");
entry->mime_type=ConstantString("image/x-portable-pixmap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PPM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->description=ConstantString("Portable pixmap format (color)");
entry->mime_type=ConstantString("image/x-portable-pixmap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPNMImage() removes format registrations made by the
% PNM module from the list of supported formats.
%
% The format of the UnregisterPNMImage method is:
%
% UnregisterPNMImage(void)
%
*/
ModuleExport void UnregisterPNMImage(void)
{
(void) UnregisterMagickInfo("PAM");
(void) UnregisterMagickInfo("PBM");
(void) UnregisterMagickInfo("PGM");
(void) UnregisterMagickInfo("PNM");
(void) UnregisterMagickInfo("PPM");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePNMImage() writes an image to a file in the PNM rasterfile format.
%
% The format of the WritePNMImage method is:
%
% MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image)
{
char
buffer[MaxTextExtent],
format,
magick[MaxTextExtent];
const char
*value;
IndexPacket
index;
MagickBooleanType
status;
MagickOffsetType
scene;
QuantumAny
pixel;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register unsigned char
*pixels,
*q;
size_t
extent,
imageListLength,
packet_size;
ssize_t
count,
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
QuantumAny
max_value;
/*
Write PNM file header.
*/
max_value=GetQuantumRange(image->depth);
packet_size=3;
quantum_type=RGBQuantum;
(void) CopyMagickString(magick,image_info->magick,MaxTextExtent);
switch (magick[1])
{
case 'A':
case 'a':
{
format='7';
break;
}
case 'B':
case 'b':
{
format='4';
if (image_info->compression == NoCompression)
format='1';
break;
}
case 'F':
case 'f':
{
format='F';
if (SetImageGray(image,&image->exception) != MagickFalse)
format='f';
break;
}
case 'G':
case 'g':
{
format='5';
if (image_info->compression == NoCompression)
format='2';
break;
}
case 'N':
case 'n':
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
format='5';
if (image_info->compression == NoCompression)
format='2';
if (SetImageMonochrome(image,&image->exception) != MagickFalse)
{
format='4';
if (image_info->compression == NoCompression)
format='1';
}
break;
}
}
default:
{
format='6';
if (image_info->compression == NoCompression)
format='3';
break;
}
}
(void) FormatLocaleString(buffer,MaxTextExtent,"P%c\n",format);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,"comment");
if (value != (const char *) NULL)
{
register const char
*p;
/*
Write comments to file.
*/
(void) WriteBlobByte(image,'#');
for (p=value; *p != '\0'; p++)
{
(void) WriteBlobByte(image,(unsigned char) *p);
if ((*p == '\n') || (*p == '\r'))
(void) WriteBlobByte(image,'#');
}
(void) WriteBlobByte(image,'\n');
}
if (format != '7')
{
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n",
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,buffer);
}
else
{
char
type[MaxTextExtent];
/*
PAM header.
*/
(void) FormatLocaleString(buffer,MaxTextExtent,
"WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
quantum_type=GetQuantumType(image,&image->exception);
switch (quantum_type)
{
case CMYKQuantum:
case CMYKAQuantum:
{
packet_size=4;
(void) CopyMagickString(type,"CMYK",MaxTextExtent);
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
packet_size=1;
(void) CopyMagickString(type,"GRAYSCALE",MaxTextExtent);
if (IdentifyImageMonochrome(image,&image->exception) != MagickFalse)
(void) CopyMagickString(type,"BLACKANDWHITE",MaxTextExtent);
break;
}
default:
{
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
packet_size=3;
(void) CopyMagickString(type,"RGB",MaxTextExtent);
break;
}
}
if (image->matte != MagickFalse)
{
packet_size++;
(void) ConcatenateMagickString(type,"_ALPHA",MaxTextExtent);
}
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,
"DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"TUPLTYPE %s\nENDHDR\n",
type);
(void) WriteBlobString(image,buffer);
}
/*
Convert to PNM raster pixels.
*/
switch (format)
{
case '1':
{
unsigned char
pixels[2048];
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?
'0' : '1');
*q++=' ';
if ((q-pixels+1) >= (ssize_t) sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '2':
{
unsigned char
pixels[2048];
/*
Convert image to a PGM image.
*/
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ClampToQuantum(GetPixelLuma(image,p));
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToChar(index));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToShort(index));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToLong(index));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+2) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '3':
{
unsigned char
pixels[2048];
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToChar(GetPixelRed(p)),
ScaleQuantumToChar(GetPixelGreen(p)),
ScaleQuantumToChar(GetPixelBlue(p)));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToShort(GetPixelRed(p)),
ScaleQuantumToShort(GetPixelGreen(p)),
ScaleQuantumToShort(GetPixelBlue(p)));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToLong(GetPixelRed(p)),
ScaleQuantumToLong(GetPixelGreen(p)),
ScaleQuantumToLong(GetPixelBlue(p)));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+2) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '4':
{
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
image->depth=1;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '5':
{
/*
Convert image to a PGM image.
*/
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,GrayQuantum);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 8)
pixel=ScaleQuantumToChar(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToShort(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 32)
pixel=ScaleQuantumToLong(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '6':
{
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
/*
Convert image to a PAM.
*/
if (image->depth > 32)
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case 'F':
case 'f':
{
(void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" :
"1.0\n");
image->depth=32;
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
(void) WriteBlob(image,extent,pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_939_0 |
crossvul-cpp_data_good_3415_0 | /*
* Chronomaster DFA Video Decoder
* Copyright (c) 2011 Konstantin Shishkov
* based on work by Vladimir "VAG" Gneushev
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <inttypes.h>
#include "avcodec.h"
#include "bytestream.h"
#include "internal.h"
#include "libavutil/avassert.h"
#include "libavutil/imgutils.h"
#include "libavutil/mem.h"
typedef struct DfaContext {
uint32_t pal[256];
uint8_t *frame_buf;
} DfaContext;
static av_cold int dfa_decode_init(AVCodecContext *avctx)
{
DfaContext *s = avctx->priv_data;
avctx->pix_fmt = AV_PIX_FMT_PAL8;
if (!avctx->width || !avctx->height)
return AVERROR_INVALIDDATA;
av_assert0(av_image_check_size(avctx->width, avctx->height, 0, avctx) >= 0);
s->frame_buf = av_mallocz(avctx->width * avctx->height);
if (!s->frame_buf)
return AVERROR(ENOMEM);
return 0;
}
static int decode_copy(GetByteContext *gb, uint8_t *frame, int width, int height)
{
const int size = width * height;
if (bytestream2_get_buffer(gb, frame, size) != size)
return AVERROR_INVALIDDATA;
return 0;
}
static int decode_tsw1(GetByteContext *gb, uint8_t *frame, int width, int height)
{
const uint8_t *frame_start = frame;
const uint8_t *frame_end = frame + width * height;
int mask = 0x10000, bitbuf = 0;
int v, count, segments;
unsigned offset;
segments = bytestream2_get_le32(gb);
offset = bytestream2_get_le32(gb);
if (segments == 0 && offset == frame_end - frame)
return 0; // skip frame
if (frame_end - frame <= offset)
return AVERROR_INVALIDDATA;
frame += offset;
while (segments--) {
if (bytestream2_get_bytes_left(gb) < 2)
return AVERROR_INVALIDDATA;
if (mask == 0x10000) {
bitbuf = bytestream2_get_le16u(gb);
mask = 1;
}
if (frame_end - frame < 2)
return AVERROR_INVALIDDATA;
if (bitbuf & mask) {
v = bytestream2_get_le16(gb);
offset = (v & 0x1FFF) << 1;
count = ((v >> 13) + 2) << 1;
if (frame - frame_start < offset || frame_end - frame < count)
return AVERROR_INVALIDDATA;
av_memcpy_backptr(frame, offset, count);
frame += count;
} else {
*frame++ = bytestream2_get_byte(gb);
*frame++ = bytestream2_get_byte(gb);
}
mask <<= 1;
}
return 0;
}
static int decode_dsw1(GetByteContext *gb, uint8_t *frame, int width, int height)
{
const uint8_t *frame_start = frame;
const uint8_t *frame_end = frame + width * height;
int mask = 0x10000, bitbuf = 0;
int v, offset, count, segments;
segments = bytestream2_get_le16(gb);
while (segments--) {
if (bytestream2_get_bytes_left(gb) < 2)
return AVERROR_INVALIDDATA;
if (mask == 0x10000) {
bitbuf = bytestream2_get_le16u(gb);
mask = 1;
}
if (frame_end - frame < 2)
return AVERROR_INVALIDDATA;
if (bitbuf & mask) {
v = bytestream2_get_le16(gb);
offset = (v & 0x1FFF) << 1;
count = ((v >> 13) + 2) << 1;
if (frame - frame_start < offset || frame_end - frame < count)
return AVERROR_INVALIDDATA;
av_memcpy_backptr(frame, offset, count);
frame += count;
} else if (bitbuf & (mask << 1)) {
frame += bytestream2_get_le16(gb);
} else {
*frame++ = bytestream2_get_byte(gb);
*frame++ = bytestream2_get_byte(gb);
}
mask <<= 2;
}
return 0;
}
static int decode_dds1(GetByteContext *gb, uint8_t *frame, int width, int height)
{
const uint8_t *frame_start = frame;
const uint8_t *frame_end = frame + width * height;
int mask = 0x10000, bitbuf = 0;
int i, v, offset, count, segments;
segments = bytestream2_get_le16(gb);
while (segments--) {
if (bytestream2_get_bytes_left(gb) < 2)
return AVERROR_INVALIDDATA;
if (mask == 0x10000) {
bitbuf = bytestream2_get_le16u(gb);
mask = 1;
}
if (bitbuf & mask) {
v = bytestream2_get_le16(gb);
offset = (v & 0x1FFF) << 2;
count = ((v >> 13) + 2) << 1;
if (frame - frame_start < offset || frame_end - frame < count*2 + width)
return AVERROR_INVALIDDATA;
for (i = 0; i < count; i++) {
frame[0] = frame[1] =
frame[width] = frame[width + 1] = frame[-offset];
frame += 2;
}
} else if (bitbuf & (mask << 1)) {
v = bytestream2_get_le16(gb)*2;
if (frame - frame_end < v)
return AVERROR_INVALIDDATA;
frame += v;
} else {
if (frame_end - frame < width + 4)
return AVERROR_INVALIDDATA;
frame[0] = frame[1] =
frame[width] = frame[width + 1] = bytestream2_get_byte(gb);
frame += 2;
frame[0] = frame[1] =
frame[width] = frame[width + 1] = bytestream2_get_byte(gb);
frame += 2;
}
mask <<= 2;
}
return 0;
}
static int decode_bdlt(GetByteContext *gb, uint8_t *frame, int width, int height)
{
uint8_t *line_ptr;
int count, lines, segments;
count = bytestream2_get_le16(gb);
if (count >= height)
return AVERROR_INVALIDDATA;
frame += width * count;
lines = bytestream2_get_le16(gb);
if (count + lines > height)
return AVERROR_INVALIDDATA;
while (lines--) {
if (bytestream2_get_bytes_left(gb) < 1)
return AVERROR_INVALIDDATA;
line_ptr = frame;
frame += width;
segments = bytestream2_get_byteu(gb);
while (segments--) {
if (frame - line_ptr <= bytestream2_peek_byte(gb))
return AVERROR_INVALIDDATA;
line_ptr += bytestream2_get_byte(gb);
count = (int8_t)bytestream2_get_byte(gb);
if (count >= 0) {
if (frame - line_ptr < count)
return AVERROR_INVALIDDATA;
if (bytestream2_get_buffer(gb, line_ptr, count) != count)
return AVERROR_INVALIDDATA;
} else {
count = -count;
if (frame - line_ptr < count)
return AVERROR_INVALIDDATA;
memset(line_ptr, bytestream2_get_byte(gb), count);
}
line_ptr += count;
}
}
return 0;
}
static int decode_wdlt(GetByteContext *gb, uint8_t *frame, int width, int height)
{
const uint8_t *frame_end = frame + width * height;
uint8_t *line_ptr;
int count, i, v, lines, segments;
int y = 0;
lines = bytestream2_get_le16(gb);
if (lines > height)
return AVERROR_INVALIDDATA;
while (lines--) {
if (bytestream2_get_bytes_left(gb) < 2)
return AVERROR_INVALIDDATA;
segments = bytestream2_get_le16u(gb);
while ((segments & 0xC000) == 0xC000) {
unsigned skip_lines = -(int16_t)segments;
unsigned delta = -((int16_t)segments * width);
if (frame_end - frame <= delta || y + lines + skip_lines > height)
return AVERROR_INVALIDDATA;
frame += delta;
y += skip_lines;
segments = bytestream2_get_le16(gb);
}
if (frame_end <= frame)
return AVERROR_INVALIDDATA;
if (segments & 0x8000) {
frame[width - 1] = segments & 0xFF;
segments = bytestream2_get_le16(gb);
}
line_ptr = frame;
if (frame_end - frame < width)
return AVERROR_INVALIDDATA;
frame += width;
y++;
while (segments--) {
if (frame - line_ptr <= bytestream2_peek_byte(gb))
return AVERROR_INVALIDDATA;
line_ptr += bytestream2_get_byte(gb);
count = (int8_t)bytestream2_get_byte(gb);
if (count >= 0) {
if (frame - line_ptr < count * 2)
return AVERROR_INVALIDDATA;
if (bytestream2_get_buffer(gb, line_ptr, count * 2) != count * 2)
return AVERROR_INVALIDDATA;
line_ptr += count * 2;
} else {
count = -count;
if (frame - line_ptr < count * 2)
return AVERROR_INVALIDDATA;
v = bytestream2_get_le16(gb);
for (i = 0; i < count; i++)
bytestream_put_le16(&line_ptr, v);
}
}
}
return 0;
}
static int decode_tdlt(GetByteContext *gb, uint8_t *frame, int width, int height)
{
const uint8_t *frame_end = frame + width * height;
uint32_t segments = bytestream2_get_le32(gb);
int skip, copy;
while (segments--) {
if (bytestream2_get_bytes_left(gb) < 2)
return AVERROR_INVALIDDATA;
copy = bytestream2_get_byteu(gb) * 2;
skip = bytestream2_get_byteu(gb) * 2;
if (frame_end - frame < copy + skip ||
bytestream2_get_bytes_left(gb) < copy)
return AVERROR_INVALIDDATA;
frame += skip;
bytestream2_get_buffer(gb, frame, copy);
frame += copy;
}
return 0;
}
static int decode_blck(GetByteContext *gb, uint8_t *frame, int width, int height)
{
memset(frame, 0, width * height);
return 0;
}
typedef int (*chunk_decoder)(GetByteContext *gb, uint8_t *frame, int width, int height);
static const chunk_decoder decoder[8] = {
decode_copy, decode_tsw1, decode_bdlt, decode_wdlt,
decode_tdlt, decode_dsw1, decode_blck, decode_dds1,
};
static const char* chunk_name[8] = {
"COPY", "TSW1", "BDLT", "WDLT", "TDLT", "DSW1", "BLCK", "DDS1"
};
static int dfa_decode_frame(AVCodecContext *avctx,
void *data, int *got_frame,
AVPacket *avpkt)
{
AVFrame *frame = data;
DfaContext *s = avctx->priv_data;
GetByteContext gb;
const uint8_t *buf = avpkt->data;
uint32_t chunk_type, chunk_size;
uint8_t *dst;
int ret;
int i, pal_elems;
int version = avctx->extradata_size==2 ? AV_RL16(avctx->extradata) : 0;
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
return ret;
bytestream2_init(&gb, avpkt->data, avpkt->size);
while (bytestream2_get_bytes_left(&gb) > 0) {
bytestream2_skip(&gb, 4);
chunk_size = bytestream2_get_le32(&gb);
chunk_type = bytestream2_get_le32(&gb);
if (!chunk_type)
break;
if (chunk_type == 1) {
pal_elems = FFMIN(chunk_size / 3, 256);
for (i = 0; i < pal_elems; i++) {
s->pal[i] = bytestream2_get_be24(&gb) << 2;
s->pal[i] |= 0xFFU << 24 | (s->pal[i] >> 6) & 0x30303;
}
frame->palette_has_changed = 1;
} else if (chunk_type <= 9) {
if (decoder[chunk_type - 2](&gb, s->frame_buf, avctx->width, avctx->height)) {
av_log(avctx, AV_LOG_ERROR, "Error decoding %s chunk\n",
chunk_name[chunk_type - 2]);
return AVERROR_INVALIDDATA;
}
} else {
av_log(avctx, AV_LOG_WARNING,
"Ignoring unknown chunk type %"PRIu32"\n",
chunk_type);
}
buf += chunk_size;
}
buf = s->frame_buf;
dst = frame->data[0];
for (i = 0; i < avctx->height; i++) {
if(version == 0x100) {
int j;
for(j = 0; j < avctx->width; j++) {
dst[j] = buf[ (i&3)*(avctx->width /4) + (j/4) +
((j&3)*(avctx->height/4) + (i/4))*avctx->width];
}
} else {
memcpy(dst, buf, avctx->width);
buf += avctx->width;
}
dst += frame->linesize[0];
}
memcpy(frame->data[1], s->pal, sizeof(s->pal));
*got_frame = 1;
return avpkt->size;
}
static av_cold int dfa_decode_end(AVCodecContext *avctx)
{
DfaContext *s = avctx->priv_data;
av_freep(&s->frame_buf);
return 0;
}
AVCodec ff_dfa_decoder = {
.name = "dfa",
.long_name = NULL_IF_CONFIG_SMALL("Chronomaster DFA"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_DFA,
.priv_data_size = sizeof(DfaContext),
.init = dfa_decode_init,
.close = dfa_decode_end,
.decode = dfa_decode_frame,
.capabilities = AV_CODEC_CAP_DR1,
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3415_0 |
crossvul-cpp_data_bad_341_9 | /*
* Copyright (C) 2017 Frank Morgner <frankmorgner@gmail.com>
*
* This file is part of OpenSC.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "egk-tool-cmdline.h"
#include "libopensc/log.h"
#include "libopensc/opensc.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#endif
#ifdef ENABLE_ZLIB
#include <zlib.h>
int uncompress_gzip(void* uncompressed, size_t *uncompressed_len,
const void* compressed, size_t compressed_len)
{
z_stream stream;
memset(&stream, 0, sizeof stream);
stream.total_in = compressed_len;
stream.avail_in = compressed_len;
stream.total_out = *uncompressed_len;
stream.avail_out = *uncompressed_len;
stream.next_in = (Bytef *) compressed;
stream.next_out = (Bytef *) uncompressed;
/* 15 window bits, and the +32 tells zlib to to detect if using gzip or zlib */
if (Z_OK == inflateInit2(&stream, (15 + 32))
&& Z_STREAM_END == inflate(&stream, Z_FINISH)) {
*uncompressed_len = stream.total_out;
} else {
return SC_ERROR_INVALID_DATA;
}
inflateEnd(&stream);
return SC_SUCCESS;
}
#else
int uncompress_gzip(void* uncompressed, size_t *uncompressed_len,
const void* compressed, size_t compressed_len)
{
return SC_ERROR_NOT_SUPPORTED;
}
#endif
#define PRINT(c) (isprint(c) ? c : '?')
void dump_binary(void *buf, size_t buf_len)
{
#ifdef _WIN32
_setmode(fileno(stdout), _O_BINARY);
#endif
fwrite(buf, 1, buf_len, stdout);
#ifdef _WIN32
_setmode(fileno(stdout), _O_TEXT);
#endif
}
const unsigned char aid_hca[] = {0xD2, 0x76, 0x00, 0x00, 0x01, 0x02};
static int initialize(int reader_id, int verbose,
sc_context_t **ctx, sc_reader_t **reader)
{
unsigned int i, reader_count;
int r;
if (!ctx || !reader)
return SC_ERROR_INVALID_ARGUMENTS;
r = sc_establish_context(ctx, "");
if (r < 0 || !*ctx) {
fprintf(stderr, "Failed to create initial context: %s", sc_strerror(r));
return r;
}
(*ctx)->debug = verbose;
(*ctx)->flags |= SC_CTX_FLAG_ENABLE_DEFAULT_DRIVER;
reader_count = sc_ctx_get_reader_count(*ctx);
if (reader_count == 0) {
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "No reader not found.\n");
return SC_ERROR_NO_READERS_FOUND;
}
if (reader_id < 0) {
/* Automatically try to skip to a reader with a card if reader not specified */
for (i = 0; i < reader_count; i++) {
*reader = sc_ctx_get_reader(*ctx, i);
if (sc_detect_card_presence(*reader) & SC_READER_CARD_PRESENT) {
reader_id = i;
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "Using the first reader"
" with a card: %s", (*reader)->name);
break;
}
}
if ((unsigned int) reader_id >= reader_count) {
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "No card found, using the first reader.");
reader_id = 0;
}
}
if ((unsigned int) reader_id >= reader_count) {
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "Invalid reader number "
"(%d), only %d available.\n", reader_id, reader_count);
return SC_ERROR_NO_READERS_FOUND;
}
*reader = sc_ctx_get_reader(*ctx, reader_id);
return SC_SUCCESS;
}
int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len)
{
struct sc_path path;
struct sc_file *file;
unsigned char *p;
int ok = 0;
int r;
size_t len;
sc_format_path(str_path, &path);
if (SC_SUCCESS != sc_select_file(card, &path, &file)) {
goto err;
}
len = file ? file->size : 4096;
p = realloc(*data, len);
if (!p) {
goto err;
}
*data = p;
*data_len = len;
r = sc_read_binary(card, 0, p, len, 0);
if (r < 0)
goto err;
*data_len = r;
ok = 1;
err:
sc_file_free(file);
return ok;
}
void decode_version(unsigned char *bcd, unsigned int *major, unsigned int *minor, unsigned int *fix)
{
*major = 0;
*minor = 0;
*fix = 0;
/* decode BCD to decimal */
if ((bcd[0]>>4) < 10 && ((bcd[0]&0xF) < 10) && ((bcd[1]>>4) < 10)) {
*major = (bcd[0]>>4)*100 + (bcd[0]&0xF)*10 + (bcd[1]>>4);
}
if (((bcd[1]&0xF) < 10) && ((bcd[2]>>4) < 10) && ((bcd[2]&0xF) < 10)) {
*minor = (bcd[1]&0xF)*100 + (bcd[2]>>4)*10 + (bcd[2]&0xF);
}
if ((bcd[3]>>4) < 10 && ((bcd[3]&0xF) < 10)
&& (bcd[4]>>4) < 10 && ((bcd[4]&0xF) < 10)) {
*fix = (bcd[3]>>4)*1000 + (bcd[3]&0xF)*100
+ (bcd[4]>>4)*10 + (bcd[4]&0xF);
}
}
int
main (int argc, char **argv)
{
struct gengetopt_args_info cmdline;
struct sc_path path;
struct sc_context *ctx;
struct sc_reader *reader = NULL;
struct sc_card *card;
unsigned char *data = NULL;
size_t data_len = 0;
int r;
if (cmdline_parser(argc, argv, &cmdline) != 0)
exit(1);
r = initialize(cmdline.reader_arg, cmdline.verbose_given, &ctx, &reader);
if (r < 0) {
fprintf(stderr, "Can't initialize reader\n");
exit(1);
}
if (sc_connect_card(reader, &card) < 0) {
fprintf(stderr, "Could not connect to card\n");
sc_release_context(ctx);
exit(1);
}
sc_path_set(&path, SC_PATH_TYPE_DF_NAME, aid_hca, sizeof aid_hca, 0, 0);
if (SC_SUCCESS != sc_select_file(card, &path, NULL))
goto err;
if (cmdline.pd_flag
&& read_file(card, "D001", &data, &data_len)
&& data_len >= 2) {
size_t len_pd = (data[0] << 8) | data[1];
if (len_pd + 2 <= data_len) {
unsigned char uncompressed[1024];
size_t uncompressed_len = sizeof uncompressed;
if (uncompress_gzip(uncompressed, &uncompressed_len,
data + 2, len_pd) == SC_SUCCESS) {
dump_binary(uncompressed, uncompressed_len);
} else {
dump_binary(data + 2, len_pd);
}
}
}
if ((cmdline.vd_flag || cmdline.gvd_flag)
&& read_file(card, "D001", &data, &data_len)
&& data_len >= 8) {
size_t off_vd = (data[0] << 8) | data[1];
size_t end_vd = (data[2] << 8) | data[3];
size_t off_gvd = (data[4] << 8) | data[5];
size_t end_gvd = (data[6] << 8) | data[7];
size_t len_vd = end_vd - off_vd + 1;
size_t len_gvd = end_gvd - off_gvd + 1;
if (off_vd <= end_vd && end_vd < data_len
&& off_gvd <= end_gvd && end_gvd < data_len) {
unsigned char uncompressed[1024];
size_t uncompressed_len = sizeof uncompressed;
if (cmdline.vd_flag) {
if (uncompress_gzip(uncompressed, &uncompressed_len,
data + off_vd, len_vd) == SC_SUCCESS) {
dump_binary(uncompressed, uncompressed_len);
} else {
dump_binary(data + off_vd, len_vd);
}
}
if (cmdline.gvd_flag) {
if (uncompress_gzip(uncompressed, &uncompressed_len,
data + off_gvd, len_gvd) == SC_SUCCESS) {
dump_binary(uncompressed, uncompressed_len);
} else {
dump_binary(data + off_gvd, len_gvd);
}
}
}
}
if (cmdline.vsd_status_flag
&& read_file(card, "D00C", &data, &data_len)
&& data_len >= 25) {
char *status;
unsigned int major, minor, fix;
switch (data[0]) {
case '0':
status = "Transactions pending";
break;
case '1':
status = "No transactions pending";
break;
default:
status = "Unknown";
break;
}
decode_version(data+15, &major, &minor, &fix);
printf(
"Status %s\n"
"Timestamp %c%c.%c%c.%c%c%c%c at %c%c:%c%c:%c%c\n"
"Version %u.%u.%u\n",
status,
PRINT(data[7]), PRINT(data[8]),
PRINT(data[5]), PRINT(data[6]),
PRINT(data[1]), PRINT(data[2]), PRINT(data[3]), PRINT(data[4]),
PRINT(data[9]), PRINT(data[10]),
PRINT(data[11]), PRINT(data[12]),
PRINT(data[13]), PRINT(data[14]),
major, minor, fix);
}
err:
sc_disconnect_card(card);
sc_release_context(ctx);
cmdline_parser_free (&cmdline);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_341_9 |
crossvul-cpp_data_good_500_0 | /* Copyright (C) 2008-2018 - pancake, unlogic, emvivre */
#include <r_flag.h>
#include <r_core.h>
#include <r_asm.h>
#include <r_lib.h>
#include <r_types.h>
#include <stdio.h>
#include <string.h>
static ut64 getnum(RAsm *a, const char *s);
#define ENCODING_SHIFT 0
#define OPTYPE_SHIFT 6
#define REGMASK_SHIFT 16
#define OPSIZE_SHIFT 24
// How to encode the operand?
#define OT_REGMEM (1 << (ENCODING_SHIFT + 0))
#define OT_SPECIAL (1 << (ENCODING_SHIFT + 1))
#define OT_IMMEDIATE (1 << (ENCODING_SHIFT + 2))
#define OT_JMPADDRESS (1 << (ENCODING_SHIFT + 3))
// Register indices - by default, we allow all registers
#define OT_REGALL (0xff << REGMASK_SHIFT)
// Memory or register operands: how is the operand written in assembly code?
#define OT_MEMORY (1 << (OPTYPE_SHIFT + 0))
#define OT_CONSTANT (1 << (OPTYPE_SHIFT + 1))
#define OT_GPREG ((1 << (OPTYPE_SHIFT + 2)) | OT_REGALL)
#define OT_SEGMENTREG ((1 << (OPTYPE_SHIFT + 3)) | OT_REGALL)
#define OT_FPUREG ((1 << (OPTYPE_SHIFT + 4)) | OT_REGALL)
#define OT_MMXREG ((1 << (OPTYPE_SHIFT + 5)) | OT_REGALL)
#define OT_XMMREG ((1 << (OPTYPE_SHIFT + 6)) | OT_REGALL)
#define OT_CONTROLREG ((1 << (OPTYPE_SHIFT + 7)) | OT_REGALL)
#define OT_DEBUGREG ((1 << (OPTYPE_SHIFT + 8)) | OT_REGALL)
#define OT_SREG ((1 << (OPTYPE_SHIFT + 9)) | OT_REGALL)
// more?
#define OT_REGTYPE ((OT_GPREG | OT_SEGMENTREG | OT_FPUREG | OT_MMXREG | OT_XMMREG | OT_CONTROLREG | OT_DEBUGREG) & ~OT_REGALL)
// Register mask
#define OT_REG(num) ((1 << (REGMASK_SHIFT + (num))) | OT_REGTYPE)
#define OT_UNKNOWN (0 << OPSIZE_SHIFT)
#define OT_BYTE (1 << OPSIZE_SHIFT)
#define OT_WORD (2 << OPSIZE_SHIFT)
#define OT_DWORD (4 << OPSIZE_SHIFT)
#define OT_QWORD (8 << OPSIZE_SHIFT)
#define OT_OWORD (16 << OPSIZE_SHIFT)
#define OT_TBYTE (32 << OPSIZE_SHIFT)
#define ALL_SIZE (OT_BYTE | OT_WORD | OT_DWORD | OT_QWORD | OT_OWORD)
// For register operands, we mostl don't care about the size.
// So let's just set all relevant flags.
#define OT_FPUSIZE (OT_DWORD | OT_QWORD | OT_TBYTE)
#define OT_XMMSIZE (OT_DWORD | OT_QWORD | OT_OWORD)
// Macros for encoding
#define OT_REGMEMOP(type) (OT_##type##REG | OT_MEMORY | OT_REGMEM)
#define OT_REGONLYOP(type) (OT_##type##REG | OT_REGMEM)
#define OT_MEMONLYOP (OT_MEMORY | OT_REGMEM)
#define OT_MEMIMMOP (OT_MEMORY | OT_IMMEDIATE)
#define OT_REGSPECOP(type) (OT_##type##REG | OT_SPECIAL)
#define OT_IMMOP (OT_CONSTANT | OT_IMMEDIATE)
#define OT_MEMADDROP (OT_MEMORY | OT_IMMEDIATE)
// Some operations are encoded via opcode + spec field
#define SPECIAL_SPEC 0x00010000
#define SPECIAL_MASK 0x00000007
#define MAX_OPERANDS 3
#define MAX_REPOP_LENGTH 20
const ut8 SEG_REG_PREFIXES[] = {0x26, 0x2e, 0x36, 0x3e, 0x64, 0x65};
typedef enum tokentype_t {
TT_EOF,
TT_WORD,
TT_NUMBER,
TT_SPECIAL
} x86newTokenType;
typedef enum register_t {
X86R_UNDEFINED = -1,
X86R_EAX = 0, X86R_ECX, X86R_EDX, X86R_EBX, X86R_ESP, X86R_EBP, X86R_ESI, X86R_EDI, X86R_EIP,
X86R_AX = 0, X86R_CX, X86R_DX, X86R_BX, X86R_SP, X86R_BP, X86R_SI, X86R_DI,
X86R_AL = 0, X86R_CL, X86R_DL, X86R_BL, X86R_AH, X86R_CH, X86R_DH, X86R_BH,
X86R_RAX = 0, X86R_RCX, X86R_RDX, X86R_RBX, X86R_RSP, X86R_RBP, X86R_RSI, X86R_RDI, X86R_RIP,
X86R_R8 = 0, X86R_R9, X86R_R10, X86R_R11, X86R_R12, X86R_R13, X86R_R14, X86R_R15,
X86R_CS = 0, X86R_SS, X86R_DS, X86R_ES, X86R_FS, X86R_GS // Is this the right order?
} Register;
typedef struct operand_t {
ut32 type;
st8 sign;
struct {
Register reg;
bool extended;
};
union {
struct {
long offset;
st8 offset_sign;
Register regs[2];
int scale[2];
};
struct {
ut64 immediate;
bool is_good_flag;
};
struct {
char rep_op[MAX_REPOP_LENGTH];
};
};
bool explicit_size;
ut32 dest_size;
ut32 reg_size;
} Operand;
typedef struct Opcode_t {
char *mnemonic;
ut32 op[3];
size_t op_len;
bool is_short;
ut8 opcode[3];
int operands_count;
Operand operands[MAX_OPERANDS];
bool has_bnd;
} Opcode;
static ut8 getsib(const ut8 sib) {
if (!sib) {
return 0;
}
return (sib & 0x8) ? 3 : getsib ((sib << 1) | 1) - 1;
}
static int is_al_reg(const Operand *op) {
if (op->type & OT_MEMORY) {
return 0;
}
if (op->reg == X86R_AL && op->type & OT_BYTE) {
return 1;
}
return 0;
}
static int oprep(RAsm *a, ut8 *data, const Opcode *op);
static int process_16bit_group_1(RAsm *a, ut8 *data, const Opcode *op, int op1) {
int l = 0;
int immediate = op->operands[1].immediate * op->operands[1].sign;
data[l++] = 0x66;
if (op->operands[1].immediate < 128) {
data[l++] = 0x83;
data[l++] = op->operands[0].reg | (0xc0 + op1 + op->operands[0].reg);
} else {
if (op->operands[0].reg == X86R_AX) {
data[l++] = 0x05 + op1;
} else {
data[l++] = 0x81;
data[l++] = (0xc0 + op1) | op->operands[0].reg;
}
}
data[l++] = immediate;
if (op->operands[1].immediate > 127) {
data[l++] = immediate >> 8;
}
return l;
}
static int process_group_1(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int modrm = 0;
int mod_byte = 0;
int offset = 0;
int mem_ref = 0;
st32 immediate = 0;
if (!op->operands[1].is_good_flag) {
return -1;
}
if (a->bits == 64 && op->operands[0].type & OT_QWORD) {
data[l++] = 0x48;
}
if (!strcmp (op->mnemonic, "adc")) {
modrm = 2;
} else if (!strcmp (op->mnemonic, "add")) {
modrm = 0;
} else if (!strcmp (op->mnemonic, "or")) {
modrm = 1;
} else if (!strcmp (op->mnemonic, "and")) {
modrm = 4;
} else if (!strcmp (op->mnemonic, "xor")) {
modrm = 6;
} else if (!strcmp (op->mnemonic, "sbb")) {
modrm = 3;
} else if (!strcmp (op->mnemonic, "sub")) {
modrm = 5;
} else if (!strcmp (op->mnemonic, "cmp")) {
modrm = 7;
}
immediate = op->operands[1].immediate * op->operands[1].sign;
if (op->operands[0].type & OT_DWORD ||
op->operands[0].type & OT_QWORD) {
if (op->operands[1].immediate < 128) {
data[l++] = 0x83;
} else if (op->operands[0].reg != X86R_EAX ||
op->operands[0].type & OT_MEMORY) {
data[l++] = 0x81;
}
} else if (op->operands[0].type & OT_BYTE) {
if (op->operands[1].immediate > 255) {
eprintf ("Error: Immediate exceeds bounds\n");
return -1;
}
data[l++] = 0x80;
}
if (op->operands[0].type & OT_MEMORY) {
offset = op->operands[0].offset * op->operands[0].offset_sign;
if (op->operands[0].offset || op->operands[0].regs[0] == X86R_EBP) {
mod_byte = 1;
}
if (offset < ST8_MIN || offset > ST8_MAX) {
mod_byte = 2;
}
int reg0 = op->operands[0].regs[0];
if (reg0 == -1) {
mem_ref = 1;
reg0 = 5;
mod_byte = 0;
}
data[l++] = mod_byte << 6 | modrm << 3 | reg0;
if (op->operands[0].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
if (mod_byte || mem_ref) {
data[l++] = offset;
if (mod_byte == 2 || mem_ref) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
} else {
if (op->operands[1].immediate > 127 && op->operands[0].reg == X86R_EAX) {
data[l++] = 5 | modrm << 3 | op->operands[0].reg;
} else {
mod_byte = 3;
data[l++] = mod_byte << 6 | modrm << 3 | op->operands[0].reg;
}
}
data[l++] = immediate;
if ((immediate > 127 || immediate < -128) &&
((op->operands[0].type & OT_DWORD) || (op->operands[0].type & OT_QWORD))) {
data[l++] = immediate >> 8;
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
}
return l;
}
static int process_group_2(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int modrm = 0;
int mod_byte = 0;
int reg0 = 0;
if (a->bits == 64 && op->operands[0].type & OT_QWORD) { data[l++] = 0x48; }
if (!strcmp (op->mnemonic, "rol")) {
modrm = 0;
} else if (!strcmp (op->mnemonic, "ror")) {
modrm = 1;
} else if (!strcmp (op->mnemonic, "rcl")) {
modrm = 2;
} else if (!strcmp (op->mnemonic, "rcr")) {
modrm = 3;
} else if (!strcmp (op->mnemonic, "shl")) {
modrm = 4;
} else if (!strcmp (op->mnemonic, "shr")) {
modrm = 5;
} else if (!strcmp (op->mnemonic, "sal")) {
modrm = 6;
} else if (!strcmp (op->mnemonic, "sar")) {
modrm = 7;
}
st32 immediate = op->operands[1].immediate * op->operands[1].sign;
if (immediate > 255 || immediate < -128) {
eprintf ("Error: Immediate exceeds bounds\n");
return -1;
}
if (op->operands[0].type & (OT_DWORD | OT_QWORD)) {
if (op->operands[1].type & (OT_GPREG | OT_BYTE)) {
data[l++] = 0xd3;
} else if (immediate == 1) {
data[l++] = 0xd1;
} else {
data[l++] = 0xc1;
}
} else if (op->operands[0].type & OT_BYTE) {
const Operand *o = &op->operands[0];
if (o->regs[0] != -1 && o->regs[1] != -1) {
data[l++] = 0xc0;
data[l++] = 0x44;
data[l++] = o->regs[0]| (o->regs[1]<<3);
data[l++] = (ut8)((o->offset*o->offset_sign) & 0xff);
data[l++] = immediate;
return l;
} else if (op->operands[1].type & (OT_GPREG | OT_WORD)) {
data[l++] = 0xd2;
} else if (immediate == 1) {
data[l++] = 0xd0;
} else {
data[l++] = 0xc0;
}
}
if (op->operands[0].type & OT_MEMORY) {
reg0 = op->operands[0].regs[0];
mod_byte = 0;
} else {
reg0 = op->operands[0].reg;
mod_byte = 3;
}
data[l++] = mod_byte << 6 | modrm << 3 | reg0;
if (immediate != 1 && !(op->operands[1].type & OT_GPREG)) {
data[l++] = immediate;
}
return l;
}
static int process_1byte_op(RAsm *a, ut8 *data, const Opcode *op, int op1) {
int l = 0;
int mod_byte = 0;
int reg = 0;
int rm = 0;
int rex = 0;
int mem_ref = 0;
st32 offset = 0;
int ebp_reg = 0;
if (!op->operands[1].is_good_flag) {
return -1;
}
if (op->operands[0].reg == X86R_AL && op->operands[1].type & OT_CONSTANT) {
data[l++] = op1 + 4;
data[l++] = op->operands[1].immediate * op->operands[1].sign;
return l;
}
if (a->bits == 64) {
if (!(op->operands[0].type & op->operands[1].type)) {
return -1;
}
}
if (a->bits == 64 && ((op->operands[0].type & OT_QWORD) | (op->operands[1].type & OT_QWORD))) {
if (op->operands[0].extended) {
rex = 1;
}
if (op->operands[1].extended) {
rex += 4;
}
data[l++] = 0x48 | rex;
}
if (op->operands[0].type & OT_MEMORY && op->operands[1].type & OT_REGALL) {
if (a->bits == 64 && (op->operands[0].type & OT_DWORD) &&
(op->operands[1].type & OT_DWORD)) {
data[l++] = 0x67;
}
if (op->operands[0].type & OT_BYTE && op->operands[1].type & OT_BYTE) {
data[l++] = op1;
} else if (op->operands[0].type & (OT_DWORD | OT_QWORD) &&
op->operands[1].type & (OT_DWORD | OT_QWORD)) {
data[l++] = op1 + 0x1;
} else {
eprintf ("Error: mismatched operand sizes\n");
return -1;
}
reg = op->operands[1].reg;
rm = op->operands[0].regs[0];
offset = op->operands[0].offset * op->operands[0].offset_sign;
if (rm == -1) {
rm = 5;
mem_ref = 1;
} else {
if (offset) {
mod_byte = 1;
if (offset < ST8_MIN || offset > ST8_MAX) {
mod_byte = 2;
}
} else if (op->operands[0].regs[1] != X86R_UNDEFINED) {
rm = 4;
offset = op->operands[0].regs[1] << 3;
}
}
} else if (op->operands[0].type & OT_REGALL) {
if (op->operands[1].type & OT_MEMORY) {
if (op->operands[0].type & OT_BYTE && op->operands[1].type & OT_BYTE) {
data[l++] = op1 + 0x2;
} else if (op->operands[0].type & (OT_DWORD | OT_QWORD) &&
op->operands[1].type & (OT_DWORD | OT_QWORD)) {
data[l++] = op1 + 0x3;
} else {
eprintf ("Error: mismatched operand sizes\n");
return -1;
}
reg = op->operands[0].reg;
rm = op->operands[1].regs[0];
if (op->operands[1].scale[0] > 1) {
if (op->operands[1].regs[1] != X86R_UNDEFINED) {
data[l++] = op->operands[0].reg << 3 | 4;
data[l++] = getsib (op->operands[1].scale[0]) << 6 |
op->operands[1].regs[0] << 3 |
op->operands[1].regs[1];
return l;
}
data[l++] = op->operands[0].reg << 3 | 4; // 4 = SIB
data[l++] = getsib (op->operands[1].scale[0]) << 6 | op->operands[1].regs[0] << 3 | 5;
data[l++] = op->operands[1].offset * op->operands[1].offset_sign;
data[l++] = 0;
data[l++] = 0;
data[l++] = 0;
return l;
}
offset = op->operands[1].offset * op->operands[1].offset_sign;
if (offset) {
mod_byte = 1;
if (offset < ST8_MIN || offset > ST8_MAX) {
mod_byte = 2;
}
}
} else if (op->operands[1].type & OT_REGALL) {
if (op->operands[0].type & OT_BYTE && op->operands[1].type & OT_BYTE) {
data[l++] = op1;
} else if (op->operands[0].type & OT_DWORD && op->operands[1].type & OT_DWORD) {
data[l++] = op1 + 0x1;
}
if (a->bits == 64) {
if (op->operands[0].type & OT_QWORD &&
op->operands[1].type & OT_QWORD) {
data[l++] = op1 + 0x1;
}
}
mod_byte = 3;
reg = op->operands[1].reg;
rm = op->operands[0].reg;
}
}
if (op->operands[0].regs[0] == X86R_EBP ||
op->operands[1].regs[0] == X86R_EBP) {
//reg += 8;
ebp_reg = 1;
}
data[l++] = mod_byte << 6 | reg << 3 | rm;
if (op->operands[0].regs[0] == X86R_ESP ||
op->operands[1].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
if (offset || mem_ref || ebp_reg) {
//if ((mod_byte > 0 && mod_byte < 3) || mem_ref) {
data[l++] = offset;
if (mod_byte == 2 || mem_ref) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
return l;
}
static int opadc(RAsm *a, ut8 *data, const Opcode *op) {
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD) {
return process_16bit_group_1 (a, data, op, 0x10);
}
if (!is_al_reg (&op->operands[0])) {
return process_group_1 (a, data, op);
}
}
return process_1byte_op (a, data, op, 0x10);
}
static int opadd(RAsm *a, ut8 *data, const Opcode *op) {
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD) {
return process_16bit_group_1 (a, data, op, 0x00);
}
if (!is_al_reg (&op->operands[0])) {
return process_group_1 (a, data, op);
}
}
return process_1byte_op (a, data, op, 0x00);
}
static int opand(RAsm *a, ut8 *data, const Opcode *op) {
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD) {
return process_16bit_group_1 (a, data, op, 0x20);
}
if (!is_al_reg (&op->operands[0])) {
return process_group_1 (a, data, op);
}
}
return process_1byte_op (a, data, op, 0x20);
}
static int opcmp(RAsm *a, ut8 *data, const Opcode *op) {
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD) {
return process_16bit_group_1 (a, data, op, 0x38);
}
if (!is_al_reg (&op->operands[0])) {
return process_group_1 (a, data, op);
}
}
return process_1byte_op (a, data, op, 0x38);
}
static int opsub(RAsm *a, ut8 *data, const Opcode *op) {
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD) {
return process_16bit_group_1 (a, data, op, 0x28);
}
if (!is_al_reg (&op->operands[0])) {
return process_group_1 (a, data, op);
}
}
return process_1byte_op (a, data, op, 0x28);
}
static int opor(RAsm *a, ut8 * data, const Opcode *op) {
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD) {
return process_16bit_group_1 (a, data, op, 0x08);
}
if (!is_al_reg (&op->operands[0])) {
return process_group_1 (a, data, op);
}
}
return process_1byte_op (a, data, op, 0x08);
}
static int opxadd(RAsm *a, ut8 *data, const Opcode *op) {
int i = 0;
if (op->operands_count < 2 ) {
return -1;
}
if (a->bits == 64) {
data[i++] = 0x48;
};
data[i++] = 0x0f;
if (op->operands[0].type & OT_BYTE &&
op->operands[1].type & OT_BYTE) {
data[i++] = 0xc0;
} else {
data[i++] = 0xc1;
}
if (op->operands[0].type & OT_REGALL &&
op->operands[1].type & OT_REGALL) { // TODO memory modes
data[i] |= 0xc0;
data[i] |= (op->operands[1].reg << 3);
data[i++] |= op->operands[0].reg;
}
return i;
}
static int opxor(RAsm *a, ut8 * data, const Opcode *op) {
if (op->operands_count < 2) {
return -1;
}
if (op->operands[0].type == 0x80 && op->operands[0].reg == X86R_UNDEFINED) {
return -1;
}
if (op->operands[1].type == 0x80 && op->operands[0].reg == X86R_UNDEFINED) {
return -1;
}
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD) {
return process_16bit_group_1 (a, data, op, 0x30);
}
if (!is_al_reg (&op->operands[0])) {
return process_group_1 (a, data, op);
}
}
return process_1byte_op (a, data, op, 0x30);
}
static int opnot(RAsm *a, ut8 * data, const Opcode *op) {
int l = 0;
if (op->operands[0].reg == X86R_UNDEFINED) {
return -1;
}
int size = op->operands[0].type & ALL_SIZE;
if (op->operands[0].explicit_size) {
size = op->operands[0].dest_size;
}
//rex prefix
int rex = 1 << 6;
bool use_rex = false;
if (size & OT_QWORD) { //W field
use_rex = true;
rex |= 1 << 3;
}
if (op->operands[0].extended) { //B field
use_rex = true;
rex |= 1;
}
if (use_rex) {
data[l++] = rex;
}
data[l++] = 0xf7;
data[l++] = 0xd0 | op->operands[0].reg;
return l;
}
static int opsbb(RAsm *a, ut8 *data, const Opcode *op) {
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD) {
return process_16bit_group_1 (a, data, op, 0x18);
}
if (!is_al_reg (&op->operands[0])) {
return process_group_1 (a, data, op);
}
}
return process_1byte_op (a, data, op, 0x18);
}
static int opbswap(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
if (op->operands[0].type & OT_REGALL) {
if (op->operands[0].reg == X86R_UNDEFINED) {
return -1;
}
if (op->operands[0].type & OT_QWORD) {
data[l++] = 0x48;
data[l++] = 0x0f;
data[l++] = 0xc8 + op->operands[0].reg;
} else if (op->operands[0].type & OT_DWORD) {
data[l++] = 0x0f;
data[l++] = 0xc8 + op->operands[0].reg;
} else {
return -1;
}
}
return l;
}
static int opcall(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int immediate = 0;
int offset = 0;
int mod = 0;
if (op->operands[0].type & OT_GPREG) {
if (op->operands[0].reg == X86R_UNDEFINED) {
return -1;
}
if (a->bits == 64 && op->operands[0].extended) {
data[l++] = 0x41;
}
data[l++] = 0xff;
mod = 3;
data[l++] = mod << 6 | 2 << 3 | op->operands[0].reg;
} else if (op->operands[0].type & OT_MEMORY) {
if (op->operands[0].regs[0] == X86R_UNDEFINED) {
return -1;
}
data[l++] = 0xff;
offset = op->operands[0].offset * op->operands[0].offset_sign;
if (offset) {
mod = 1;
if (offset > 127 || offset < -128) {
mod = 2;
}
}
data[l++] = mod << 6 | 2 << 3 | op->operands[0].regs[0];
if (mod) {
data[l++] = offset;
if (mod == 2) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
} else {
ut64 instr_offset = a->pc;
data[l++] = 0xe8;
immediate = op->operands[0].immediate * op->operands[0].sign;
immediate -= instr_offset + 5;
data[l++] = immediate;
data[l++] = immediate >> 8;
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
}
return l;
}
static int opcmov(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int mod_byte = 0;
int offset = 0;
if (op->operands[0].type & OT_MEMORY ||
op->operands[1].type & OT_CONSTANT) {
return -1;
}
data[l++] = 0x0f;
char *cmov = op->mnemonic + 4;
if (!strcmp (cmov, "o")) {
data[l++] = 0x40;
} else if (!strcmp (cmov, "no")) {
data [l++] = 0x41;
} else if (!strcmp (cmov, "b") ||
!strcmp (cmov, "c") ||
!strcmp (cmov, "nae")) {
data [l++] = 0x42;
} else if (!strcmp (cmov, "ae") ||
!strcmp (cmov, "nb") ||
!strcmp (cmov, "nc")) {
data [l++] = 0x43;
} else if (!strcmp (cmov, "e") ||
!strcmp (cmov, "z")) {
data [l++] = 0x44;
} else if (!strcmp (cmov, "ne") ||
!strcmp (cmov, "nz")) {
data [l++] = 0x45;
} else if (!strcmp (cmov, "be") ||
!strcmp (cmov, "na")) {
data [l++] = 0x46;
} else if (!strcmp (cmov, "a") ||
!strcmp (cmov, "nbe")) {
data [l++] = 0x47;
} else if (!strcmp (cmov, "s")) {
data [l++] = 0x48;
} else if (!strcmp (cmov, "ns")) {
data [l++] = 0x49;
} else if (!strcmp (cmov, "p") ||
!strcmp (cmov, "pe")) {
data [l++] = 0x4a;
} else if (!strcmp (cmov, "np") ||
!strcmp (cmov, "po")) {
data [l++] = 0x4b;
} else if (!strcmp (cmov, "l") ||
!strcmp (cmov, "nge")) {
data [l++] = 0x4c;
} else if (!strcmp (cmov, "ge") ||
!strcmp (cmov, "nl")) {
data [l++] = 0x4d;
} else if (!strcmp (cmov, "le") ||
!strcmp (cmov, "ng")) {
data [l++] = 0x4e;
} else if (!strcmp (cmov, "g") ||
!strcmp (cmov, "nle")) {
data [l++] = 0x4f;
}
if (op->operands[0].type & OT_REGALL) {
if (op->operands[1].type & OT_MEMORY) {
if (op->operands[1].scale[0] > 1) {
if (op->operands[1].regs[1] != X86R_UNDEFINED) {
data[l++] = op->operands[0].reg << 3 | 4;
data[l++] = getsib (op->operands[1].scale[0]) << 6 |
op->operands[1].regs[0] << 3 |
op->operands[1].regs[1];
return l;
}
offset = op->operands[1].offset * op->operands[1].offset_sign;
if (op->operands[1].scale[0] == 2 && offset) {
data[l++] = 0x40 | op->operands[0].reg << 3 | 4; // 4 = SIB
} else {
data[l++] = op->operands[0].reg << 3 | 4; // 4 = SIB
}
if (op->operands[1].scale[0] == 2) {
data[l++] = op->operands[1].regs[0] << 3 | op->operands[1].regs[0];
} else {
data[l++] = getsib (op->operands[1].scale[0]) << 6 |
op->operands[1].regs[0] << 3 | 5;
}
if (offset) {
data[l++] = offset;
if (offset < ST8_MIN || offset > ST8_MAX) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
return l;
}
if (op->operands[1].regs[1] != X86R_UNDEFINED) {
data[l++] = op->operands[0].reg << 3 | 4;
data[l++] = op->operands[1].regs[1] << 3 | op->operands[1].regs[0];
return l;
}
offset = op->operands[1].offset * op->operands[1].offset_sign;
if (op->operands[1].offset || op->operands[1].regs[0] == X86R_EBP) {
mod_byte = 1;
}
if (offset < ST8_MIN || offset > ST8_MAX) {
mod_byte = 2;
}
data[l++] = mod_byte << 6 | op->operands[0].reg << 3 | op->operands[1].regs[0];
if (mod_byte) {
data[l++] = offset;
if (mod_byte == 2) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
} else {
data[l++] = 0xc0 | op->operands[0].reg << 3 | op->operands[1].reg;
}
}
return l;
}
static int opmovx(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int word = 0;
char *movx = op->mnemonic + 3;
if (!(op->operands[0].type & OT_REGTYPE && op->operands[1].type & OT_MEMORY)) {
return -1;
}
if (op->operands[1].type & OT_WORD) {
word = 1;
}
data[l++] = 0x0f;
if (!strcmp (movx, "zx")) {
data[l++] = 0xb6 + word;
} else if (!strcmp (movx, "sx")) {
data[l++] = 0xbe + word;
}
data[l++] = op->operands[0].reg << 3 | op->operands[1].regs[0];
if (op->operands[1].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
return l;
}
static int opaam(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int immediate = op->operands[0].immediate * op->operands[0].sign;
data[l++] = 0xd4;
if (immediate == 0) {
data[l++] = 0x0a;
} else if (immediate < 256 && immediate > -129) {
data[l++] = immediate;
}
return l;
}
static int opdec(RAsm *a, ut8 *data, const Opcode *op) {
if (op->operands[1].type) {
eprintf ("Error: Invalid operands\n");
return -1;
}
int l = 0;
int size = op->operands[0].type & ALL_SIZE;
if (op->operands[0].explicit_size) {
size = op->operands[0].dest_size;
}
if (size & OT_WORD) {
data[l++] = 0x66;
}
//rex prefix
int rex = 1 << 6;
bool use_rex = false;
if (size & OT_QWORD) { //W field
use_rex = true;
rex |= 1 << 3;
}
if (op->operands[0].extended) { //B field
use_rex = true;
rex |= 1;
}
//opcode selection
int opcode;
if (size & OT_BYTE) {
opcode = 0xfe;
} else {
opcode = 0xff;
}
if (!(op->operands[0].type & OT_MEMORY)) {
if (use_rex) {
data[l++] = rex;
}
if (a->bits > 32 || size & OT_BYTE) {
data[l++] = opcode;
}
if (a->bits == 32 && size & (OT_DWORD | OT_WORD)) {
data[l++] = 0x48 | op->operands[0].reg;
} else {
data[l++] = 0xc8 | op->operands[0].reg;
}
return l;
}
//modrm and SIB selection
bool rip_rel = op->operands[0].regs[0] == X86R_RIP;
int offset = op->operands[0].offset * op->operands[0].offset_sign;
int modrm = 0;
int mod;
int reg = 0;
int rm;
bool use_sib = false;
int sib = 0;
//mod
if (offset == 0) {
mod = 0;
} else if (offset < 128 && offset > -129) {
mod = 1;
} else {
mod = 2;
}
if (op->operands[0].regs[0] & OT_WORD) {
if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_SI) {
rm = B0000;
} else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_DI) {
rm = B0001;
} else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_SI) {
rm = B0010;
} else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_DI) {
rm = B0011;
} else if (op->operands[0].regs[0] == X86R_SI && op->operands[0].regs[1] == -1) {
rm = B0100;
} else if (op->operands[0].regs[0] == X86R_DI && op->operands[0].regs[1] == -1) {
rm = B0101;
} else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == -1) {
rm = B0111;
} else {
//TODO allow for displacement only when parser is reworked
return -1;
}
modrm = (mod << 6) | (reg << 3) | rm;
} else {
//rm
if (op->operands[0].extended) {
rm = op->operands[0].reg;
} else {
rm = op->operands[0].regs[0];
}
//[epb] alone is illegal, so we need to fake a [ebp+0]
if (rm == 5 && mod == 0) {
mod = 1;
}
//sib
int index = op->operands[0].regs[1];
int scale = getsib(op->operands[0].scale[1]);
if (index != -1) {
use_sib = true;
sib = (scale << 6) | (index << 3) | rm;
} else if (rm == 4) {
use_sib = true;
sib = 0x24;
}
if (use_sib) {
rm = B0100;
}
if (rip_rel) {
modrm = (B0000 << 6) | (reg << 3) | B0101;
sib = (scale << 6) | (B0100 << 3) | B0101;
} else {
modrm = (mod << 6) | (reg << 3) | rm;
}
modrm |= 1<<3;
}
if (use_rex) {
data[l++] = rex;
}
data[l++] = opcode;
data[l++] = modrm;
if (use_sib) {
data[l++] = sib;
}
//offset
if (mod == 1) {
data[l++] = offset;
} else if (op->operands[0].regs[0] & OT_WORD && mod == 2) {
data[l++] = offset;
data[l++] = offset >> 8;
} else if (mod == 2 || rip_rel) {
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
return l;
}
static int opidiv(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0x48;
}
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0x66;
}
if (op->operands[0].type & OT_BYTE) {
data[l++] = 0xf6;
} else {
data[l++] = 0xf7;
}
if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0x38 | op->operands[0].regs[0];
} else {
data[l++] = 0xf8 | op->operands[0].reg;
}
break;
default:
return -1;
}
return l;
}
static int opdiv(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0x48;
}
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0x66;
}
if (op->operands[0].type & OT_BYTE) {
data[l++] = 0xf6;
} else {
data[l++] = 0xf7;
}
if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
data[l++] = 0xf0 | op->operands[0].reg;
}
break;
default:
return -1;
}
return l;
}
static int opimul(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int offset = 0;
st64 immediate = 0;
if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0x48;
}
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0x66;
}
if (op->operands[0].type & OT_BYTE) {
data[l++] = 0xf6;
} else {
data[l++] = 0xf7;
}
if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0x28 | op->operands[0].regs[0];
} else {
data[l++] = 0xe8 | op->operands[0].reg;
}
break;
case 2:
if (op->operands[0].type & OT_GPREG) {
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[1].immediate == -1) {
eprintf ("Error: Immediate exceeds max\n");
return -1;
}
immediate = op->operands[1].immediate * op->operands[1].sign;
if (op->operands[0].type & OT_GPREG) {
if (immediate >= 128) {
data[l++] = 0x69;
} else {
data[l++] = 0x6b;
}
data[l++] = 0xc0 | op->operands[0].reg << 3 | op->operands[0].reg;
data[l++] = immediate;
if (immediate >= 128) {
data[l++] = immediate >> 8;
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
}
if (a->bits == 64 && immediate > UT32_MAX) {
data[l++] = immediate >> 32;
data[l++] = immediate >> 40;
data[l++] = immediate >> 48;
data[l++] = immediate >> 56;
}
}
} else if (op->operands[1].type & OT_MEMORY) {
data[l++] = 0x0f;
data[l++] = 0xaf;
if (op->operands[1].regs[0] != X86R_UNDEFINED) {
offset = op->operands[1].offset * op->operands[1].offset_sign;
if (offset != 0) {
if (offset >= 128 || offset <= -128) {
data[l] = 0x80;
} else {
data[l] = 0x40;
}
data[l++] |= op->operands[0].reg << 3 | op->operands[1].regs[0];
data[l++] = offset;
if (offset >= 128 || offset <= -128) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
} else {
if (op->operands[1].regs[1] != X86R_UNDEFINED) {
data[l++] = 0x04 | op->operands[0].reg << 3;
data[l++] = op->operands[1].regs[1] << 3 | op->operands[1].regs[0];
} else {
data[l++] = op->operands[0].reg << 3 | op->operands[1].regs[0];
}
}
} else {
immediate = op->operands[1].immediate * op->operands[1].sign;
data[l++] = op->operands[0].reg << 3 | 0x5;
data[l++] = immediate;
data[l++] = immediate >> 8;
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
}
} else if (op->operands[1].type & OT_GPREG) {
data[l++] = 0x0f;
data[l++] = 0xaf;
data[l++] = 0xc0 | op->operands[0].reg << 3 | op->operands[1].reg;
}
}
break;
case 3:
if (op->operands[0].type & OT_GPREG &&
(op->operands[1].type & OT_GPREG || op->operands[1].type & OT_MEMORY) &&
op->operands[2].type & OT_CONSTANT) {
data[l++] = 0x6b;
if (op->operands[1].type & OT_MEMORY) {
if (op->operands[1].regs[1] != X86R_UNDEFINED) {
data[l++] = 0x04 | op->operands[0].reg << 3;
data[l++] = op->operands[1].regs[0] | op->operands[1].regs[1] << 3;
} else {
offset = op->operands[1].offset * op->operands[1].offset_sign;
if (offset != 0) {
if (offset >= 128 || offset <= -128) {
data[l] = 0x80;
} else {
data[l] = 0x40;
}
data[l++] |= op->operands[0].reg << 3;
data[l++] = offset;
if (offset >= 128 || offset <= -128) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
} else {
data[l++] = 0x00 | op->operands[0].reg << 3 | op->operands[1].regs[0];
}
}
} else {
data[l++] = 0xc0 | op->operands[0].reg << 3 | op->operands[1].reg;
}
immediate = op->operands[2].immediate * op->operands[2].sign;
data[l++] = immediate;
if (immediate >= 128 || immediate <= -128) {
data[l++] = immediate >> 8;
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
}
}
break;
default:
return -1;
}
return l;
}
static int opin(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
st32 immediate = 0;
if (op->operands[1].reg == X86R_DX) {
if (op->operands[0].reg == X86R_AL &&
op->operands[0].type & OT_BYTE) {
data[l++] = 0xec;
return l;
}
if (op->operands[0].reg == X86R_AX &&
op->operands[0].type & OT_WORD) {
data[l++] = 0x66;
data[l++] = 0xed;
return l;
}
if (op->operands[0].reg == X86R_EAX &&
op->operands[0].type & OT_DWORD) {
data[l++] = 0xed;
return l;
}
} else if (op->operands[1].type & OT_CONSTANT) {
immediate = op->operands[1].immediate * op->operands[1].sign;
if (immediate > 255 || immediate < -128) {
return -1;
}
if (op->operands[0].reg == X86R_AL &&
op->operands[0].type & OT_BYTE) {
data[l++] = 0xe4;
} else if (op->operands[0].reg == X86R_AX &&
op->operands[0].type & OT_BYTE) {
data[l++] = 0x66;
data[l++] = 0xe5;
} else if (op->operands[0].reg == X86R_EAX &&
op->operands[0].type & OT_DWORD) {
data[l++] = 0xe5;
}
data[l++] = immediate;
}
return l;
}
static int opclflush(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int offset = 0;
int mod_byte = 0;
if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0x0f;
data[l++] = 0xae;
offset = op->operands[0].offset * op->operands[0].offset_sign;
if (offset) {
if (offset < ST8_MIN || offset > ST8_MAX) {
mod_byte = 2;
} else {
mod_byte = 1;
}
}
data[l++] = (mod_byte << 6) | (7 << 3) | op->operands[0].regs[0];
if (mod_byte) {
data[l++] = offset;
if (mod_byte == 2) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
}
return l;
}
static int opinc(RAsm *a, ut8 *data, const Opcode *op) {
if (op->operands[1].type) {
eprintf ("Error: Invalid operands\n");
return -1;
}
int l = 0;
int size = op->operands[0].type & ALL_SIZE;
if (op->operands[0].explicit_size) {
size = op->operands[0].dest_size;
}
if (size & OT_WORD) {
data[l++] = 0x66;
}
//rex prefix
int rex = 1 << 6;
bool use_rex = false;
if (size & OT_QWORD) { //W field
use_rex = true;
rex |= 1 << 3;
}
if (op->operands[0].extended) { //B field
use_rex = true;
rex |= 1;
}
//opcode selection
int opcode;
if (size & OT_BYTE) {
opcode = 0xfe;
} else {
opcode = 0xff;
}
if (!(op->operands[0].type & OT_MEMORY)) {
if (use_rex) {
data[l++] = rex;
}
if (a->bits > 32 || size & OT_BYTE) {
data[l++] = opcode;
}
if (a->bits == 32 && size & (OT_DWORD | OT_WORD)) {
data[l++] = 0x40 | op->operands[0].reg;
} else {
data[l++] = 0xc0 | op->operands[0].reg;
}
return l;
}
//modrm and SIB selection
bool rip_rel = op->operands[0].regs[0] == X86R_RIP;
int offset = op->operands[0].offset * op->operands[0].offset_sign;
int modrm = 0;
int mod;
int reg = 0;
int rm;
bool use_sib = false;
int sib = 0;
//mod
if (offset == 0) {
mod = 0;
} else if (offset < 128 && offset > -129) {
mod = 1;
} else {
mod = 2;
}
if (op->operands[0].regs[0] & OT_WORD) {
if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_SI) {
rm = B0000;
} else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_DI) {
rm = B0001;
} else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_SI) {
rm = B0010;
} else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_DI) {
rm = B0011;
} else if (op->operands[0].regs[0] == X86R_SI && op->operands[0].regs[1] == -1) {
rm = B0100;
} else if (op->operands[0].regs[0] == X86R_DI && op->operands[0].regs[1] == -1) {
rm = B0101;
} else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == -1) {
rm = B0111;
} else {
//TODO allow for displacement only when parser is reworked
return -1;
}
modrm = (mod << 6) | (reg << 3) | rm;
} else {
//rm
if (op->operands[0].extended) {
rm = op->operands[0].reg;
} else {
rm = op->operands[0].regs[0];
}
//[epb] alone is illegal, so we need to fake a [ebp+0]
if (rm == 5 && mod == 0) {
mod = 1;
}
//sib
int index = op->operands[0].regs[1];
int scale = getsib(op->operands[0].scale[1]);
if (index != -1) {
use_sib = true;
sib = (scale << 6) | (index << 3) | rm;
} else if (rm == 4) {
use_sib = true;
sib = 0x24;
}
if (use_sib) {
rm = B0100;
}
if (rip_rel) {
modrm = (B0000 << 6) | (reg << 3) | B0101;
sib = (scale << 6) | (B0100 << 3) | B0101;
} else {
modrm = (mod << 6) | (reg << 3) | rm;
}
}
if (use_rex) {
data[l++] = rex;
}
data[l++] = opcode;
data[l++] = modrm;
if (use_sib) {
data[l++] = sib;
}
//offset
if (mod == 1) {
data[l++] = offset;
} else if (op->operands[0].regs[0] & OT_WORD && mod == 2) {
data[l++] = offset;
data[l++] = offset >> 8;
} else if (mod == 2 || rip_rel) {
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
return l;
}
static int opint(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
if (op->operands[0].type & OT_CONSTANT) {
st32 immediate = op->operands[0].immediate * op->operands[0].sign;
if (immediate <= 255 && immediate >= -128) {
data[l++] = 0xcd;
data[l++] = immediate;
}
}
return l;
}
static int opjc(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
bool is_short = op->is_short;
// st64 bigimm = op->operands[0].immediate * op->operands[0].sign;
st64 immediate = op->operands[0].immediate * op->operands[0].sign;
if (is_short && (immediate > ST8_MAX || immediate < ST8_MIN)) {
return l;
}
immediate -= a->pc;
if (immediate > ST32_MAX || immediate < -ST32_MAX) {
return -1;
}
if (!strcmp (op->mnemonic, "jmp")) {
if (op->operands[0].type & OT_GPREG) {
data[l++] = 0xff;
if (op->operands[0].type & OT_MEMORY) {
if (op->operands[0].offset) {
int offset = op->operands[0].offset * op->operands[0].offset_sign;
if (offset >= 128 || offset <= -129) {
data[l] = 0xa0;
} else {
data[l] = 0x60;
}
data[l++] |= op->operands[0].regs[0];
data[l++] = offset;
if (op->operands[0].offset >= 0x80) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
} else {
data[l++] = 0x20 | op->operands[0].regs[0];
}
} else {
data[l++] = 0xe0 | op->operands[0].reg;
}
} else {
if (-0x80 <= (immediate - 2) && (immediate - 2) <= 0x7f) {
/* relative byte address */
data[l++] = 0xeb;
data[l++] = immediate - 2;
} else {
/* relative address */
immediate -= 5;
data[l++] = 0xe9;
data[l++] = immediate;
data[l++] = immediate >> 8;
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
}
}
return l;
}
if (immediate <= 0x81 && immediate > -0x7f) {
is_short = true;
}
if (a->bits == 16 && (immediate > 0x81 || immediate < -0x7e)) {
data[l++] = 0x66;
is_short = false;
immediate --;
}
if (!is_short) {data[l++] = 0x0f;}
if (!strcmp (op->mnemonic, "ja") ||
!strcmp (op->mnemonic, "jnbe")) {
data[l++] = 0x87;
} else if (!strcmp (op->mnemonic, "jae") ||
!strcmp (op->mnemonic, "jnb") ||
!strcmp (op->mnemonic, "jnc")) {
data[l++] = 0x83;
} else if (!strcmp (op->mnemonic, "jz") ||
!strcmp (op->mnemonic, "je")) {
data[l++] = 0x84;
} else if (!strcmp (op->mnemonic, "jb") ||
!strcmp (op->mnemonic, "jnae") ||
!strcmp (op->mnemonic, "jc")) {
data[l++] = 0x82;
} else if (!strcmp (op->mnemonic, "jbe") ||
!strcmp (op->mnemonic, "jna")) {
data[l++] = 0x86;
} else if (!strcmp (op->mnemonic, "jg") ||
!strcmp (op->mnemonic, "jnle")) {
data[l++] = 0x8f;
} else if (!strcmp (op->mnemonic, "jge") ||
!strcmp (op->mnemonic, "jnl")) {
data[l++] = 0x8d;
} else if (!strcmp (op->mnemonic, "jl") ||
!strcmp (op->mnemonic, "jnge")) {
data[l++] = 0x8c;
} else if (!strcmp (op->mnemonic, "jle") ||
!strcmp (op->mnemonic, "jng")) {
data[l++] = 0x8e;
} else if (!strcmp (op->mnemonic, "jne") ||
!strcmp (op->mnemonic, "jnz")) {
data[l++] = 0x85;
} else if (!strcmp (op->mnemonic, "jno")) {
data[l++] = 0x81;
} else if (!strcmp (op->mnemonic, "jnp") ||
!strcmp (op->mnemonic, "jpo")) {
data[l++] = 0x8b;
} else if (!strcmp (op->mnemonic, "jns")) {
data[l++] = 0x89;
} else if (!strcmp (op->mnemonic, "jo")) {
data[l++] = 0x80;
} else if (!strcmp (op->mnemonic, "jp") ||
!strcmp(op->mnemonic, "jpe")) {
data[l++] = 0x8a;
} else if (!strcmp (op->mnemonic, "js") ||
!strcmp (op->mnemonic, "jz")) {
data[l++] = 0x88;
}
if (is_short) {
data[l-1] -= 0x10;
}
immediate -= is_short ? 2 : 6;
data[l++] = immediate;
if (!is_short) {
data[l++] = immediate >> 8;
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
}
return l;
}
static int oplea(RAsm *a, ut8 *data, const Opcode *op){
int l = 0;
int mod = 0;
st32 offset = 0;
int reg = 0;
int rm = 0;
if (op->operands[0].type & OT_REGALL &&
op->operands[1].type & (OT_MEMORY | OT_CONSTANT)) {
if (a->bits == 64) {
data[l++] = 0x48;
}
data[l++] = 0x8d;
if (op->operands[1].regs[0] == X86R_UNDEFINED) {
int high = 0xff00 & op->operands[1].offset;
data[l++] = op->operands[0].reg << 3 | 5;
data[l++] = op->operands[1].offset;
data[l++] = high >> 8;
data[l++] = op->operands[1].offset >> 16;
data[l++] = op->operands[1].offset >> 24;
return l;
} else {
reg = op->operands[0].reg;
rm = op->operands[1].regs[0];
offset = op->operands[1].offset * op->operands[1].offset_sign;
if (offset != 0 || op->operands[1].regs[0] == X86R_EBP) {
mod = 1;
if (offset >= 128 || offset < -128) {
mod = 2;
}
data[l++] = mod << 6 | reg << 3 | rm;
if (op->operands[1].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
data[l++] = offset;
if (mod == 2) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
} else {
data[l++] = op->operands[0].reg << 3 | op->operands[1].regs[0];
if (op->operands[1].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
}
}
}
return l;
}
static int oples(RAsm *a, ut8* data, const Opcode *op) {
int l = 0;
int offset = 0;
int mod = 0;
if (op->operands[1].type & OT_MEMORY) {
data[l++] = 0xc4;
if (op->operands[1].type & OT_GPREG) {
offset = op->operands[1].offset * op->operands[1].offset_sign;
if (offset) {
mod = 1;
if (offset > 128 || offset < -128) {
mod = 2;
}
}
data[l++] = mod << 6 | op->operands[0].reg << 3 | op->operands[1].regs[0];
if (mod) {
data[l++] = offset;
if (mod > 1) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
} else {
offset = op->operands[1].offset * op->operands[1].offset_sign;
data[l++] = 0x05;
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
return l;
}
static int opmov(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
st64 offset = 0;
int mod = 0;
int base = 0;
int rex = 0;
ut64 immediate = 0;
if (op->operands[1].type & OT_CONSTANT) {
if (!op->operands[1].is_good_flag) {
return -1;
}
if (op->operands[1].immediate == -1) {
return -1;
}
immediate = op->operands[1].immediate * op->operands[1].sign;
if (op->operands[0].type & OT_GPREG && !(op->operands[0].type & OT_MEMORY)) {
if (a->bits == 64 && ((op->operands[0].type & OT_QWORD) | (op->operands[1].type & OT_QWORD))) {
if (!(op->operands[1].type & OT_CONSTANT) && op->operands[1].extended) {
data[l++] = 0x49;
} else {
data[l++] = 0x48;
}
} else if (op->operands[0].extended) {
data[l++] = 0x41;
}
if (op->operands[0].type & OT_WORD) {
if (a->bits > 16) {
data[l++] = 0x66;
}
}
if (op->operands[0].type & OT_BYTE) {
data[l++] = 0xb0 | op->operands[0].reg;
data[l++] = immediate;
} else {
if (a->bits == 64 &&
((op->operands[0].type & OT_QWORD) |
(op->operands[1].type & OT_QWORD)) &&
immediate < UT32_MAX) {
data[l++] = 0xc7;
data[l++] = 0xc0 | op->operands[0].reg;
} else {
data[l++] = 0xb8 | op->operands[0].reg;
}
data[l++] = immediate;
data[l++] = immediate >> 8;
if (!(op->operands[0].type & OT_WORD)) {
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
}
if (a->bits == 64 && immediate > UT32_MAX) {
data[l++] = immediate >> 32;
data[l++] = immediate >> 40;
data[l++] = immediate >> 48;
data[l++] = immediate >> 56;
}
}
} else if (op->operands[0].type & OT_MEMORY) {
if (!op->operands[0].explicit_size) {
if (op->operands[0].type & OT_GPREG) {
((Opcode *)op)->operands[0].dest_size = op->operands[0].reg_size;
} else {
return -1;
}
}
int dest_bits = 8 * ((op->operands[0].dest_size & ALL_SIZE) >> OPSIZE_SHIFT);
int reg_bits = 8 * ((op->operands[0].reg_size & ALL_SIZE) >> OPSIZE_SHIFT);
int offset = op->operands[0].offset * op->operands[0].offset_sign;
//addr_size_override prefix
bool use_aso = false;
if (reg_bits < a->bits) {
use_aso = true;
}
//op_size_override prefix
bool use_oso = false;
if (dest_bits == 16) {
use_oso = true;
}
bool rip_rel = op->operands[0].regs[0] == X86R_RIP;
//rex prefix
int rex = 1 << 6;
bool use_rex = false;
if (dest_bits == 64) { //W field
use_rex = true;
rex |= 1 << 3;
}
if (op->operands[0].extended) { //B field
use_rex = true;
rex |= 1;
}
//opcode selection
int opcode;
if (dest_bits == 8) {
opcode = 0xc6;
} else {
opcode = 0xc7;
}
//modrm and SIB selection
int modrm = 0;
int mod;
int reg = 0;
int rm;
bool use_sib = false;
int sib;
//mod
if (offset == 0) {
mod = 0;
} else if (offset < 128 && offset > -129) {
mod = 1;
} else {
mod = 2;
}
if (reg_bits == 16) {
if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_SI) {
rm = B0000;
} else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_DI) {
rm = B0001;
} else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_SI) {
rm = B0010;
} else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_DI) {
rm = B0011;
} else if (op->operands[0].regs[0] == X86R_SI && op->operands[0].regs[1] == -1) {
rm = B0100;
} else if (op->operands[0].regs[0] == X86R_DI && op->operands[0].regs[1] == -1) {
rm = B0101;
} else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == -1) {
rm = B0111;
} else {
//TODO allow for displacement only when parser is reworked
return -1;
}
modrm = (mod << 6) | (reg << 3) | rm;
} else {
//rm
if (op->operands[0].extended) {
rm = op->operands[0].reg;
} else {
rm = op->operands[0].regs[0];
}
//[epb] alone is illegal, so we need to fake a [ebp+0]
if (rm == 5 && mod == 0) {
mod = 1;
}
//sib
int index = op->operands[0].regs[1];
int scale = getsib(op->operands[0].scale[1]);
if (index != -1) {
use_sib = true;
sib = (scale << 6) | (index << 3) | rm;
} else if (rm == 4) {
use_sib = true;
sib = 0x24;
}
if (use_sib) {
rm = B0100;
}
if (rip_rel) {
modrm = (B0000 << 6) | (reg << 3) | B0101;
sib = (scale << 6) | (B0100 << 3) | B0101;
} else {
modrm = (mod << 6) | (reg << 3) | rm;
}
}
//build the final result
if (use_aso) {
data[l++] = 0x67;
}
if (use_oso) {
data[l++] = 0x66;
}
if (use_rex) {
data[l++] = rex;
}
data[l++] = opcode;
data[l++] = modrm;
if (use_sib) {
data[l++] = sib;
}
//offset
if (mod == 1) {
data[l++] = offset;
} else if (reg_bits == 16 && mod == 2) {
data[l++] = offset;
data[l++] = offset >> 8;
} else if (mod == 2 || rip_rel) {
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
//immediate
int byte;
for (byte = 0; byte < dest_bits && byte < 32; byte += 8) {
data[l++] = (immediate >> byte);
}
}
} else if (op->operands[1].type & OT_REGALL &&
!(op->operands[1].type & OT_MEMORY)) {
if (op->operands[0].type & OT_CONSTANT) {
return -1;
}
if (op->operands[0].type & OT_REGTYPE & OT_SEGMENTREG &&
op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) {
return -1;
}
// Check reg sizes match
if (op->operands[0].type & OT_REGTYPE && op->operands[1].type & OT_REGTYPE) {
if (!((op->operands[0].type & ALL_SIZE) &
(op->operands[1].type & ALL_SIZE))) {
return -1;
}
}
if (a->bits == 64) {
if (op->operands[0].extended) {
rex = 1;
}
if (op->operands[1].extended) {
rex += 4;
}
if (op->operands[1].type & OT_QWORD) {
if (!(op->operands[0].type & OT_QWORD)) {
data[l++] = 0x67;
data[l++] = 0x48;
}
}
if (op->operands[1].type & OT_QWORD &&
op->operands[0].type & OT_QWORD) {
data[l++] = 0x48 | rex;
}
if (op->operands[1].type & OT_DWORD &&
op->operands[0].type & OT_DWORD) {
data[l++] = 0x40 | rex;
}
} else if (op->operands[0].extended && op->operands[1].extended) {
data[l++] = 0x45;
}
offset = op->operands[0].offset * op->operands[0].offset_sign;
if (op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) {
data[l++] = 0x8c;
} else {
if (op->operands[0].type & OT_WORD) {
data[l++] = 0x66;
}
data[l++] = (op->operands[0].type & OT_BYTE) ? 0x88 : 0x89;
}
if (op->operands[0].scale[0] > 1) {
data[l++] = op->operands[1].reg << 3 | 4;
data[l++] = getsib (op->operands[0].scale[0]) << 6 |
op->operands[0].regs[0] << 3 | 5;
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
return l;
}
if (!(op->operands[0].type & OT_MEMORY)) {
if (op->operands[0].reg == X86R_UNDEFINED ||
op->operands[1].reg == X86R_UNDEFINED) {
return -1;
}
mod = 0x3;
data[l++] = mod << 6 | op->operands[1].reg << 3 | op->operands[0].reg;
} else if (op->operands[0].regs[0] == X86R_UNDEFINED) {
data[l++] = op->operands[1].reg << 3 | 0x5;
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
} else {
if (op->operands[0].type & OT_MEMORY) {
if (op->operands[0].regs[1] != X86R_UNDEFINED) {
data[l++] = op->operands[1].reg << 3 | 0x4;
data[l++] = op->operands[0].regs[1] << 3 | op->operands[0].regs[0];
return l;
}
if (offset) {
mod = (offset > 128 || offset < -129) ? 0x2 : 0x1;
}
if (op->operands[0].regs[0] == X86R_EBP) {
mod = 0x2;
}
data[l++] = mod << 6 | op->operands[1].reg << 3 | op->operands[0].regs[0];
if (op->operands[0].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
if (offset) {
data[l++] = offset;
}
if (mod == 2) {
// warning C4293: '>>': shift count negative or too big, undefined behavior
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
}
} else if (op->operands[1].type & OT_MEMORY) {
if (op->operands[0].type & OT_MEMORY) {
return -1;
}
offset = op->operands[1].offset * op->operands[1].offset_sign;
if (op->operands[0].reg == X86R_EAX && op->operands[1].regs[0] == X86R_UNDEFINED) {
if (a->bits == 64) {
data[l++] = 0x48;
}
if (op->operands[0].type & OT_BYTE) {
data[l++] = 0xa0;
} else {
data[l++] = 0xa1;
}
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
if (a->bits == 64) {
data[l++] = offset >> 32;
data[l++] = offset >> 40;
data[l++] = offset >> 48;
data[l++] = offset >> 54;
}
return l;
}
if (op->operands[0].type & OT_BYTE && a->bits == 64 && op->operands[1].regs[0]) {
if (op->operands[1].regs[0] >= X86R_R8 &&
op->operands[0].reg < 4) {
data[l++] = 0x41;
data[l++] = 0x8a;
data[l++] = op->operands[0].reg << 3 | (op->operands[1].regs[0] - 8);
return l;
}
return -1;
}
if (op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) {
if (op->operands[1].scale[0] == 0) {
return -1;
}
data[l++] = SEG_REG_PREFIXES[op->operands[1].regs[0] % 6];
data[l++] = 0x8b;
data[l++] = (((ut32)op->operands[0].reg) << 3) | 0x5;
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
return l;
}
if (a->bits == 64) {
if (op->operands[0].type & OT_QWORD) {
if (!(op->operands[1].type & OT_QWORD)) {
if (op->operands[1].regs[0] != -1) {
data[l++] = 0x67;
}
data[l++] = 0x48;
}
} else if (op->operands[1].type & OT_DWORD) {
data[l++] = 0x44;
} else if (!(op->operands[1].type & OT_QWORD)) {
data[l++] = 0x67;
}
if (op->operands[1].type & OT_QWORD &&
op->operands[0].type & OT_QWORD) {
data[l++] = 0x48;
}
}
if (op->operands[0].type & OT_WORD) {
data[l++] = 0x66;
data[l++] = op->operands[1].type & OT_BYTE ? 0x8a : 0x8b;
} else {
data[l++] = (op->operands[1].type & OT_BYTE ||
op->operands[0].type & OT_BYTE) ?
0x8a : 0x8b;
}
if (op->operands[1].regs[0] == X86R_UNDEFINED) {
if (a->bits == 64) {
data[l++] = op->operands[0].reg << 3 | 0x4;
data[l++] = 0x25;
} else {
data[l++] = op->operands[0].reg << 3 | 0x5;
}
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
} else {
if (op->operands[1].scale[0] > 1) {
data[l++] = op->operands[0].reg << 3 | 4;
if (op->operands[1].scale[0] >= 2) {
base = 5;
}
if (base) {
data[l++] = getsib (op->operands[1].scale[0]) << 6 | op->operands[1].regs[0] << 3 | base;
} else {
data[l++] = getsib (op->operands[1].scale[0]) << 3 | op->operands[1].regs[0];
}
if (offset || base) {
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
return l;
}
if (op->operands[1].regs[1] != X86R_UNDEFINED) {
data[l++] = op->operands[0].reg << 3 | 0x4;
data[l++] = op->operands[1].regs[1] << 3 | op->operands[1].regs[0];
return l;
}
if (offset || op->operands[1].regs[0] == X86R_EBP) {
mod = 0x2;
if (op->operands[1].offset > 127) {
mod = 0x4;
}
}
if (a->bits == 64 && offset && op->operands[0].type & OT_QWORD) {
if (op->operands[1].regs[0] == X86R_RIP) {
data[l++] = 0x5;
} else {
if (op->operands[1].offset > 127) {
data[l++] = 0x80 | op->operands[0].reg << 3 | op->operands[1].regs[0];
} else {
data[l++] = 0x40 | op->operands[1].regs[0];
}
}
if (op->operands[1].offset > 127) {
mod = 0x1;
}
} else {
if (op->operands[1].regs[0] == X86R_EIP && (op->operands[0].type & OT_DWORD)) {
data[l++] = 0x0d;
} else if (op->operands[1].regs[0] == X86R_RIP && (op->operands[0].type & OT_QWORD)) {
data[l++] = 0x05;
} else {
data[l++] = mod << 5 | op->operands[0].reg << 3 | op->operands[1].regs[0];
}
}
if (op->operands[1].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
if (mod >= 0x2) {
data[l++] = offset;
if (op->operands[1].offset > 128 || op->operands[1].regs[0] == X86R_EIP) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
} else if (a->bits == 64 && (offset || op->operands[1].regs[0] == X86R_RIP)) {
data[l++] = offset;
if (op->operands[1].offset > 127 || op->operands[1].regs[0] == X86R_RIP) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
}
}
return l;
}
static int opmul(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0x48;
}
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0x66;
}
if (op->operands[0].type & OT_BYTE) {
data[l++] = 0xf6;
} else {
data[l++] = 0xf7;
}
if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0x20 | op->operands[0].regs[0];
} else {
data[l++] = 0xe0 | op->operands[0].reg;
}
break;
default:
return -1;
}
return l;
}
static int oppop(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int offset = 0;
int mod = 0;
if (op->operands[0].type & OT_GPREG) {
if (op->operands[0].type & OT_MEMORY) {
return -1;
}
if (op->operands[0].type & OT_REGTYPE & OT_SEGMENTREG) {
ut8 base;
if (op->operands[0].reg & X86R_FS) {
data[l++] = 0x0f;
base = 0x81;
} else {
base = 0x7;
}
data[l++] = base + (8 * op->operands[0].reg);
} else {
ut8 base = 0x58;
data[l++] = base + op->operands[0].reg;
}
} else if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0x8f;
offset = op->operands[0].offset * op->operands[0].offset_sign;
if (offset != 0 || op->operands[0].regs[0] == X86R_EBP) {
mod = 1;
if (offset >= 128 || offset < -128) {
mod = 2;
}
data[l++] = mod << 6 | op->operands[0].regs[0];
if (op->operands[0].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
data[l++] = offset;
if (mod == 2) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
} else {
data[l++] = op->operands[0].regs[0];
if (op->operands[0].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
}
}
return l;
}
static int oppush(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int mod = 0;
st32 immediate = 0;;
st32 offset = 0;
if (op->operands[0].type & OT_GPREG &&
!(op->operands[0].type & OT_MEMORY)) {
if (op->operands[0].type & OT_REGTYPE & OT_SEGMENTREG) {
ut8 base;
if (op->operands[0].reg & X86R_FS) {
data[l++] = 0x0f;
base = 0x80;
} else {
base = 0x6;
}
data[l++] = base + (8 * op->operands[0].reg);
} else {
if (op->operands[0].extended && a->bits == 64) {
data[l++] = 0x41;
}
ut8 base = 0x50;
data[l++] = base + op->operands[0].reg;
}
} else if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0xff;
offset = op->operands[0].offset * op->operands[0].offset_sign;
mod = 0;
if (offset != 0 || op->operands[0].regs[0] == X86R_EBP) {
mod = 1;
if (offset >= 128 || offset < -128) {
mod = 2;
}
data[l++] = mod << 6 | 6 << 3 | op->operands[0].regs[0];
if (op->operands[0].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
data[l++] = offset;
if (mod == 2) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
} else {
mod = 3;
data[l++] = mod << 4 | op->operands[0].regs[0];
if (op->operands[0].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
}
} else {
immediate = op->operands[0].immediate * op->operands[0].sign;
if (immediate >= 128 || immediate < -128) {
data[l++] = 0x68;
data[l++] = immediate;
data[l++] = immediate >> 8;
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
} else {
data[l++] = 0x6a;
data[l++] = immediate;
}
}
return l;
}
static int opout(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
st32 immediate = 0;
if (op->operands[0].reg == X86R_DX) {
if (op->operands[1].reg == X86R_AL && op->operands[1].type & OT_BYTE) {
data[l++] = 0xee;
return l;
}
if (op->operands[1].reg == X86R_AX && op->operands[1].type & OT_WORD) {
data[l++] = 0x66;
data[l++] = 0xef;
return l;
}
if (op->operands[1].reg == X86R_EAX && op->operands[1].type & OT_DWORD) {
data[l++] = 0xef;
return l;
}
} else if (op->operands[0].type & OT_CONSTANT) {
immediate = op->operands[0].immediate * op->operands[0].sign;
if (immediate > 255 || immediate < -128) {
return -1;
}
if (op->operands[1].reg == X86R_AL && op->operands[1].type & OT_BYTE) {
data[l++] = 0xe6;
} else if (op->operands[1].reg == X86R_AX && op->operands[1].type & OT_WORD) {
data[l++] = 0x66;
data[l++] = 0xe7;
} else if (op->operands[1].reg == X86R_EAX && op->operands[1].type & OT_DWORD) {
data[l++] = 0xe7;
} else {
return -1;
}
data[l++] = immediate;
} else {
return -1;
}
return l;
}
static int oploop(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
data[l++] = 0xe2;
st8 delta = op->operands[0].immediate - a->pc - 2;
data[l++] = (ut8)delta;
return l;
}
static int opret(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int immediate = 0;
if (a->bits == 16) {
data[l++] = 0xc3;
return l;
}
if (op->operands[0].type == OT_UNKNOWN) {
data[l++] = 0xc3;
} else if (op->operands[0].type & (OT_CONSTANT | OT_WORD)) {
data[l++] = 0xc2;
immediate = op->operands[0].immediate * op->operands[0].sign;
data[l++] = immediate;
data[l++] = immediate << 8;
}
return l;
}
static int opretf(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
st32 immediate = 0;
if (op->operands[0].type & OT_CONSTANT) {
immediate = op->operands[0].immediate * op->operands[0].sign;
data[l++] = 0xca;
data[l++] = immediate;
data[l++] = immediate >> 8;
} else if (op->operands[0].type == OT_UNKNOWN) {
data[l++] = 0xcb;
}
return l;
}
static int opstos(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
if (!strcmp(op->mnemonic, "stosw")) {
data[l++] = 0x66;
}
if (!strcmp(op->mnemonic, "stosb")) {
data[l++] = 0xaa;
} else if (!strcmp(op->mnemonic, "stosw")) {
data[l++] = 0xab;
} else if (!strcmp(op->mnemonic, "stosd")) {
data[l++] = 0xab;
}
return l;
}
static int opset(RAsm *a, ut8 *data, const Opcode *op) {
if (!(op->operands[0].type & (OT_GPREG | OT_BYTE))) {return -1;}
int l = 0;
int mod = 0;
int reg = op->operands[0].regs[0];
data[l++] = 0x0f;
if (!strcmp (op->mnemonic, "seto")) {
data[l++] = 0x90;
} else if (!strcmp (op->mnemonic, "setno")) {
data[l++] = 0x91;
} else if (!strcmp (op->mnemonic, "setb") ||
!strcmp (op->mnemonic, "setnae") ||
!strcmp (op->mnemonic, "setc")) {
data[l++] = 0x92;
} else if (!strcmp (op->mnemonic, "setnb") ||
!strcmp (op->mnemonic, "setae") ||
!strcmp (op->mnemonic, "setnc")) {
data[l++] = 0x93;
} else if (!strcmp (op->mnemonic, "setz") ||
!strcmp (op->mnemonic, "sete")) {
data[l++] = 0x94;
} else if (!strcmp (op->mnemonic, "setnz") ||
!strcmp (op->mnemonic, "setne")) {
data[l++] = 0x95;
} else if (!strcmp (op->mnemonic, "setbe") ||
!strcmp (op->mnemonic, "setna")) {
data[l++] = 0x96;
} else if (!strcmp (op->mnemonic, "setnbe") ||
!strcmp (op->mnemonic, "seta")) {
data[l++] = 0x97;
} else if (!strcmp (op->mnemonic, "sets")) {
data[l++] = 0x98;
} else if (!strcmp (op->mnemonic, "setns")) {
data[l++] = 0x99;
} else if (!strcmp (op->mnemonic, "setp") ||
!strcmp (op->mnemonic, "setpe")) {
data[l++] = 0x9a;
} else if (!strcmp (op->mnemonic, "setnp") ||
!strcmp (op->mnemonic, "setpo")) {
data[l++] = 0x9b;
} else if (!strcmp (op->mnemonic, "setl") ||
!strcmp (op->mnemonic, "setnge")) {
data[l++] = 0x9c;
} else if (!strcmp (op->mnemonic, "setnl") ||
!strcmp (op->mnemonic, "setge")) {
data[l++] = 0x9d;
} else if (!strcmp (op->mnemonic, "setle") ||
!strcmp (op->mnemonic, "setng")) {
data[l++] = 0x9e;
} else if (!strcmp (op->mnemonic, "setnle") ||
!strcmp (op->mnemonic, "setg")) {
data[l++] = 0x9f;
} else {
return -1;
}
if (!(op->operands[0].type & OT_MEMORY)) {
mod = 3;
reg = op->operands[0].reg;
}
data[l++] = mod << 6 | reg;
return l;
}
static int optest(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
if (!op->operands[0].type || !op->operands[1].type) {
eprintf ("Error: Invalid operands\n");
return -1;
}
if (a->bits == 64) {
if (op->operands[0].type & OT_MEMORY ||
op->operands[1].type & OT_MEMORY) {
data[l++] = 0x67;
}
if (op->operands[0].type & OT_QWORD &&
op->operands[1].type & OT_QWORD) {
if (op->operands[0].extended &&
op->operands[1].extended) {
data[l++] = 0x4d;
} else {
data[l++] = 0x48;
}
}
}
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[0].type & OT_BYTE) {
data[l++] = 0xf6;
data[l++] = op->operands[0].regs[0];
data[l++] = op->operands[1].immediate;
return l;
}
data[l++] = 0xf7;
if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0x00 | op->operands[0].regs[0];
} else {
data[l++] = 0xc0 | op->operands[0].reg;
}
data[l++] = op->operands[1].immediate >> 0;
data[l++] = op->operands[1].immediate >> 8;
data[l++] = op->operands[1].immediate >> 16;
data[l++] = op->operands[1].immediate >> 24;
return l;
}
if (op->operands[0].type & OT_BYTE ||
op->operands[1].type & OT_BYTE) {
data[l++] = 0x84;
} else {
data[l++] = 0x85;
}
if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0x00 | op->operands[1].reg << 3 | op->operands[0].regs[0];
} else {
if (op->operands[1].type & OT_MEMORY) {
data[l++] = 0x00 | op->operands[0].reg << 3 | op->operands[1].regs[0];
} else {
data[l++] = 0xc0 | op->operands[1].reg << 3 | op->operands[0].reg;
}
}
return l;
}
static int opxchg(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int mod_byte = 0;
int reg = 0;
int rm = 0;
st32 offset = 0;
if (op->operands[0].type & OT_MEMORY || op->operands[1].type & OT_MEMORY) {
data[l++] = 0x87;
if (op->operands[0].type & OT_MEMORY) {
rm = op->operands[0].regs[0];
offset = op->operands[0].offset * op->operands[0].offset_sign;
reg = op->operands[1].reg;
} else if (op->operands[1].type & OT_MEMORY) {
rm = op->operands[1].regs[0];
offset = op->operands[1].offset * op->operands[1].offset_sign;
reg = op->operands[0].reg;
}
if (offset) {
mod_byte = 1;
if (offset < ST8_MIN || offset > ST8_MAX) {
mod_byte = 2;
}
}
} else {
if (op->operands[0].reg == X86R_EAX &&
op->operands[1].type & OT_GPREG) {
data[l++] = 0x90 + op->operands[1].reg;
return l;
} else if (op->operands[1].reg == X86R_EAX &&
op->operands[0].type & OT_GPREG) {
data[l++] = 0x90 + op->operands[0].reg;
return l;
} else if (op->operands[0].type & OT_GPREG &&
op->operands[1].type & OT_GPREG) {
mod_byte = 3;
data[l++] = 0x87;
reg = op->operands[1].reg;
rm = op->operands[0].reg;
}
}
data[l++] = mod_byte << 6 | reg << 3 | rm;
if (mod_byte > 0 && mod_byte < 3) {
data[l++] = offset;
if (mod_byte == 2) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
return l;
}
static int opcdqe(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
if (a->bits == 64) {
data[l++] = 0x48;
}
data[l++] = 0x98;
return l;
}
static int opfcmov(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
char* fcmov = op->mnemonic + strlen("fcmov");
switch (op->operands_count) {
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL ) {
if ( !strcmp( fcmov, "b" ) ) {
data[l++] = 0xda;
data[l++] = 0xc0 | op->operands[1].reg;
} else if ( !strcmp( fcmov, "e" ) ) {
data[l++] = 0xda;
data[l++] = 0xc8 | op->operands[1].reg;
} else if ( !strcmp( fcmov, "be" ) ) {
data[l++] = 0xda;
data[l++] = 0xd0 | op->operands[1].reg;
} else if ( !strcmp( fcmov, "u" ) ) {
data[l++] = 0xda;
data[l++] = 0xd8 | op->operands[1].reg;
} else if ( !strcmp( fcmov, "nb" ) ) {
data[l++] = 0xdb;
data[l++] = 0xc0 | op->operands[1].reg;
} else if ( !strcmp( fcmov, "ne" ) ) {
data[l++] = 0xdb;
data[l++] = 0xc8 | op->operands[1].reg;
} else if ( !strcmp( fcmov, "nbe" ) ) {
data[l++] = 0xdb;
data[l++] = 0xd0 | op->operands[1].reg;
} else if ( !strcmp( fcmov, "nu" ) ) {
data[l++] = 0xdb;
data[l++] = 0xd8 | op->operands[1].reg;
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opffree(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if (op->operands[0].type & OT_FPUREG & ~OT_REGALL) {
data[l++] = 0xdd;
data[l++] = 0xc0 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfrstor(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0xdd;
data[l++] = 0x20 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfxch(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 0:
data[l++] = 0xd9;
data[l++] = 0xc9;
break;
case 1:
if (op->operands[0].type & OT_FPUREG & ~OT_REGALL) {
data[l++] = 0xd9;
data[l++] = 0xc8 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfucom(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL ) {
data[l++] = 0xdd;
data[l++] = 0xe0 | op->operands[0].reg;
} else {
return -1;
}
break;
case 0:
data[l++] = 0xdd;
data[l++] = 0xe1;
break;
default:
return -1;
}
return l;
}
static int opfucomp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL ) {
data[l++] = 0xdd;
data[l++] = 0xe8 | op->operands[0].reg;
} else {
return -1;
}
break;
case 0:
data[l++] = 0xdd;
data[l++] = 0xe9;
break;
default:
return -1;
}
return l;
}
static int opfaddp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xde;
data[l++] = 0xc0 | op->operands[0].reg;
} else {
return -1;
}
break;
case 0:
data[l++] = 0xde;
data[l++] = 0xc1;
break;
default:
return -1;
}
return l;
}
static int opfiadd(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xde;
data[l++] = 0x00 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xda;
data[l++] = 0x00 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfadd(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0xdc;
data[l++] = 0x00 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xd8;
data[l++] = 0x00 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL ) {
data[l++] = 0xd8;
data[l++] = 0xc0 | op->operands[1].reg;
} else if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xdc;
data[l++] = 0xc0 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opficom(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xde;
data[l++] = 0x10 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xda;
data[l++] = 0x10 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opficomp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xde;
data[l++] = 0x18 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xda;
data[l++] = 0x18 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfild(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xdf;
data[l++] = 0x00 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xdb;
data[l++] = 0x00 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0xdf;
data[l++] = 0x28 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfldcw(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_WORD ) {
data[l++] = 0xd9;
data[l++] = 0x28 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfldenv(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0xd9;
data[l++] = 0x20 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfbld(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_TBYTE ) {
data[l++] = 0xdf;
data[l++] = 0x20 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfbstp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_TBYTE ) {
data[l++] = 0xdf;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfxrstor(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x0f;
data[l++] = 0xae;
data[l++] = 0x08 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfxsave(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x0f;
data[l++] = 0xae;
data[l++] = 0x00 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfist(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xdf;
data[l++] = 0x10 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xdb;
data[l++] = 0x10 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfistp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xdf;
data[l++] = 0x18 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xdb;
data[l++] = 0x18 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0xdf;
data[l++] = 0x38 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfisttp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xdf;
data[l++] = 0x08 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xdb;
data[l++] = 0x08 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0xdd;
data[l++] = 0x08 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfstenv(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x9b;
data[l++] = 0xd9;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfnstenv(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0xd9;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfdiv(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xd8;
data[l++] = 0x30 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0xdc;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL ) {
data[l++] = 0xd8;
data[l++] = 0xf0 | op->operands[1].reg;
} else if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xdc;
data[l++] = 0xf8 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfdivp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 0:
data[l++] = 0xde;
data[l++] = 0xf9;
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xde;
data[l++] = 0xf8 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfidiv(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xda;
data[l++] = 0x30 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xde;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfdivr(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xd8;
data[l++] = 0x38 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0xdc;
data[l++] = 0x38 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL ) {
data[l++] = 0xd8;
data[l++] = 0xf8 | op->operands[1].reg;
} else if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xdc;
data[l++] = 0xf0 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfdivrp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 0:
data[l++] = 0xde;
data[l++] = 0xf1;
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xde;
data[l++] = 0xf0 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfidivr(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xda;
data[l++] = 0x38 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xde;
data[l++] = 0x38 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfmul(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xd8;
data[l++] = 0x08 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0xdc;
data[l++] = 0x08 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL ) {
data[l++] = 0xd8;
data[l++] = 0xc8 | op->operands[1].reg;
} else if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xdc;
data[l++] = 0xc8 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfmulp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 0:
data[l++] = 0xde;
data[l++] = 0xc9;
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xde;
data[l++] = 0xc8 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfimul(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xda;
data[l++] = 0x08 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xde;
data[l++] = 0x08 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfsub(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xd8;
data[l++] = 0x20 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0xdc;
data[l++] = 0x20 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL ) {
data[l++] = 0xd8;
data[l++] = 0xe0 | op->operands[1].reg;
} else if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xdc;
data[l++] = 0xe8 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfsubp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 0:
data[l++] = 0xde;
data[l++] = 0xe9;
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xde;
data[l++] = 0xe8 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfisub(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xda;
data[l++] = 0x20 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xde;
data[l++] = 0x20 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfsubr(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xd8;
data[l++] = 0x28 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0xdc;
data[l++] = 0x28 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL ) {
data[l++] = 0xd8;
data[l++] = 0xe8 | op->operands[1].reg;
} else if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xdc;
data[l++] = 0xe0 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfsubrp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 0:
data[l++] = 0xde;
data[l++] = 0xe1;
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xde;
data[l++] = 0xe0 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfisubr(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xda;
data[l++] = 0x28 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xde;
data[l++] = 0x28 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfnstcw(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_WORD ) {
data[l++] = 0xd9;
data[l++] = 0x38 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfstcw(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_WORD ) {
data[l++] = 0x9b;
data[l++] = 0xd9;
data[l++] = 0x38 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfnstsw(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_WORD ) {
data[l++] = 0xdd;
data[l++] = 0x38 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD &&
op->operands[0].reg == X86R_AX ) {
data[l++] = 0xdf;
data[l++] = 0xe0;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfstsw(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_WORD ) {
data[l++] = 0x9b;
data[l++] = 0xdd;
data[l++] = 0x38 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD &&
op->operands[0].reg == X86R_AX ) {
data[l++] = 0x9b;
data[l++] = 0xdf;
data[l++] = 0xe0;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfnsave(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_DWORD ) {
data[l++] = 0xdd;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfsave(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_DWORD ) {
data[l++] = 0x9b;
data[l++] = 0xdd;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int oplldt(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0x0f;
data[l++] = 0x00;
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x10 | op->operands[0].regs[0];
} else {
data[l++] = 0xd0 | op->operands[0].reg;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int oplmsw(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0x0f;
data[l++] = 0x01;
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
data[l++] = 0xf0 | op->operands[0].reg;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int oplgdt(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x0f;
data[l++] = 0x01;
data[l++] = 0x10 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int oplidt(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x0f;
data[l++] = 0x01;
data[l++] = 0x18 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opsgdt(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x0f;
data[l++] = 0x01;
data[l++] = 0x00 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opstmxcsr(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_DWORD ) {
data[l++] = 0x0f;
data[l++] = 0xae;
data[l++] = 0x18 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opstr(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_WORD ) {
data[l++] = 0x0f;
data[l++] = 0x00;
data[l++] = 0x08 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_DWORD ) {
data[l++] = 0x0f;
data[l++] = 0x00;
data[l++] = 0xc8 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opsidt(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x0f;
data[l++] = 0x01;
data[l++] = 0x08 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opsldt(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( a->bits == 64 ) {
data[l++] = 0x48;
}
data[l++] = 0x0f;
data[l++] = 0x00;
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x00 | op->operands[0].regs[0];
} else {
data[l++] = 0xc0 | op->operands[0].reg;
}
break;
default:
return -1;
}
return l;
}
static int opsmsw(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( a->bits == 64 ) {
data[l++] = 0x48;
}
data[l++] = 0x0f;
data[l++] = 0x01;
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x20 | op->operands[0].regs[0];
} else {
data[l++] = 0xe0 | op->operands[0].reg;
}
break;
default:
return -1;
}
return l;
}
static int opverr(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0x0f;
data[l++] = 0x00;
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x20 | op->operands[0].regs[0];
} else {
data[l++] = 0xe0 | op->operands[0].reg;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opverw(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0x0f;
data[l++] = 0x00;
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x28 | op->operands[0].regs[0];
} else {
data[l++] = 0xe8 | op->operands[0].reg;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opvmclear(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_QWORD
) {
data[l++] = 0x66;
data[l++] = 0x0f;
data[l++] = 0xc7;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opvmon(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_QWORD
) {
data[l++] = 0xf3;
data[l++] = 0x0f;
data[l++] = 0xc7;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opvmptrld(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_QWORD
) {
data[l++] = 0x0f;
data[l++] = 0xc7;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opvmptrst(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_QWORD
) {
data[l++] = 0x0f;
data[l++] = 0xc7;
data[l++] = 0x38 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
typedef struct lookup_t {
char mnemonic[12];
int only_x32;
int (*opdo)(RAsm*, ut8*, const Opcode*);
ut64 opcode;
int size;
} LookupTable;
LookupTable oplookup[] = {
{"aaa", 0, NULL, 0x37, 1},
{"aad", 0, NULL, 0xd50a, 2},
{"aam", 0, opaam, 0},
{"aas", 0, NULL, 0x3f, 1},
{"adc", 0, &opadc, 0},
{"add", 0, &opadd, 0},
{"adx", 0, NULL, 0xd4, 1},
{"amx", 0, NULL, 0xd5, 1},
{"and", 0, &opand, 0},
{"bswap", 0, &opbswap, 0},
{"call", 0, &opcall, 0},
{"cbw", 0, NULL, 0x6698, 2},
{"cdq", 0, NULL, 0x99, 1},
{"cdqe", 0, &opcdqe, 0},
{"cwde", 0, &opcdqe, 0},
{"clc", 0, NULL, 0xf8, 1},
{"cld", 0, NULL, 0xfc, 1},
{"clflush", 0, &opclflush, 0},
{"clgi", 0, NULL, 0x0f01dd, 3},
{"cli", 0, NULL, 0xfa, 1},
{"clts", 0, NULL, 0x0f06, 2},
{"cmc", 0, NULL, 0xf5, 1},
{"cmovo", 0, &opcmov, 0},
{"cmovno", 0, &opcmov, 0},
{"cmovb", 0, &opcmov, 0},
{"cmovc", 0, &opcmov, 0},
{"cmovnae", 0, &opcmov, 0},
{"cmovae", 0, &opcmov, 0},
{"cmovnb", 0, &opcmov, 0},
{"cmovnc", 0, &opcmov, 0},
{"cmove", 0, &opcmov, 0},
{"cmovz", 0, &opcmov, 0},
{"cmovne", 0, &opcmov, 0},
{"cmovnz", 0, &opcmov, 0},
{"cmovbe", 0, &opcmov, 0},
{"cmovna", 0, &opcmov, 0},
{"cmova", 0, &opcmov, 0},
{"cmovnbe", 0, &opcmov, 0},
{"cmovne", 0, &opcmov, 0},
{"cmovnz", 0, &opcmov, 0},
{"cmovs", 0, &opcmov, 0},
{"cmovns", 0, &opcmov, 0},
{"cmovp", 0, &opcmov, 0},
{"cmovpe", 0, &opcmov, 0},
{"cmovnp", 0, &opcmov, 0},
{"cmovpo", 0, &opcmov, 0},
{"cmovl", 0, &opcmov, 0},
{"cmovnge", 0, &opcmov, 0},
{"cmovge", 0, &opcmov, 0},
{"cmovnl", 0, &opcmov, 0},
{"cmovle", 0, &opcmov, 0},
{"cmovng", 0, &opcmov, 0},
{"cmovg", 0, &opcmov, 0},
{"cmovnle", 0, &opcmov, 0},
{"cmp", 0, &opcmp, 0},
{"cmpsb", 0, NULL, 0xa6, 1},
{"cmpsd", 0, NULL, 0xa7, 1},
{"cmpsw", 0, NULL, 0x66a7, 2},
{"cpuid", 0, NULL, 0x0fa2, 2},
{"cwd", 0, NULL, 0x6699, 2},
{"cwde", 0, NULL, 0x98, 1},
{"daa", 0, NULL, 0x27, 1},
{"das", 0, NULL, 0x2f, 1},
{"dec", 0, &opdec, 0},
{"div", 0, &opdiv, 0},
{"emms", 0, NULL, 0x0f77, 2},
{"f2xm1", 0, NULL, 0xd9f0, 2},
{"fabs", 0, NULL, 0xd9e1, 2},
{"fadd", 0, &opfadd, 0},
{"faddp", 0, &opfaddp, 0},
{"fbld", 0, &opfbld, 0},
{"fbstp", 0, &opfbstp, 0},
{"fchs", 0, NULL, 0xd9e0, 2},
{"fclex", 0, NULL, 0x9bdbe2, 3},
{"fcmovb", 0, &opfcmov, 0},
{"fcmove", 0, &opfcmov, 0},
{"fcmovbe", 0, &opfcmov, 0},
{"fcmovu", 0, &opfcmov, 0},
{"fcmovnb", 0, &opfcmov, 0},
{"fcmovne", 0, &opfcmov, 0},
{"fcmovnbe", 0, &opfcmov, 0},
{"fcmovnu", 0, &opfcmov, 0},
{"fcos", 0, NULL, 0xd9ff, 2},
{"fdecstp", 0, NULL, 0xd9f6, 2},
{"fdiv", 0, &opfdiv, 0},
{"fdivp", 0, &opfdivp, 0},
{"fdivr", 0, &opfdivr, 0},
{"fdivrp", 0, &opfdivrp, 0},
{"femms", 0, NULL, 0x0f0e, 2},
{"ffree", 0, &opffree, 0},
{"fiadd", 0, &opfiadd, 0},
{"ficom", 0, &opficom, 0},
{"ficomp", 0, &opficomp, 0},
{"fidiv", 0, &opfidiv, 0},
{"fidivr", 0, &opfidivr, 0},
{"fild", 0, &opfild, 0},
{"fimul", 0, &opfimul, 0},
{"fincstp", 0, NULL, 0xd9f7, 2},
{"finit", 0, NULL, 0x9bdbe3, 3},
{"fist", 0, &opfist, 0},
{"fistp", 0, &opfistp, 0},
{"fisttp", 0, &opfisttp, 0},
{"fisub", 0, &opfisub, 0},
{"fisubr", 0, &opfisubr, 0},
{"fld1", 0, NULL, 0xd9e8, 2},
{"fldcw", 0, &opfldcw, 0},
{"fldenv", 0, &opfldenv, 0},
{"fldl2t", 0, NULL, 0xd9e9, 2},
{"fldl2e", 0, NULL, 0xd9ea, 2},
{"fldlg2", 0, NULL, 0xd9ec, 2},
{"fldln2", 0, NULL, 0xd9ed, 2},
{"fldpi", 0, NULL, 0xd9eb, 2},
{"fldz", 0, NULL, 0xd9ee, 2},
{"fmul", 0, &opfmul, 0},
{"fmulp", 0, &opfmulp, 0},
{"fnclex", 0, NULL, 0xdbe2, 2},
{"fninit", 0, NULL, 0xdbe3, 2},
{"fnop", 0, NULL, 0xd9d0, 2},
{"fnsave", 0, &opfnsave, 0},
{"fnstcw", 0, &opfnstcw, 0},
{"fnstenv", 0, &opfnstenv, 0},
{"fnstsw", 0, &opfnstsw, 0},
{"fpatan", 0, NULL, 0xd9f3, 2},
{"fprem", 0, NULL, 0xd9f8, 2},
{"fprem1", 0, NULL, 0xd9f5, 2},
{"fptan", 0, NULL, 0xd9f2, 2},
{"frndint", 0, NULL, 0xd9fc, 2},
{"frstor", 0, &opfrstor, 0},
{"fsave", 0, &opfsave, 0},
{"fscale", 0, NULL, 0xd9fd, 2},
{"fsin", 0, NULL, 0xd9fe, 2},
{"fsincos", 0, NULL, 0xd9fb, 2},
{"fsqrt", 0, NULL, 0xd9fa, 2},
{"fstcw", 0, &opfstcw, 0},
{"fstenv", 0, &opfstenv, 0},
{"fstsw", 0, &opfstsw, 0},
{"fsub", 0, &opfsub, 0},
{"fsubp", 0, &opfsubp, 0},
{"fsubr", 0, &opfsubr, 0},
{"fsubrp", 0, &opfsubrp, 0},
{"ftst", 0, NULL, 0xd9e4, 2},
{"fucom", 0, &opfucom, 0},
{"fucomp", 0, &opfucomp, 0},
{"fucompp", 0, NULL, 0xdae9, 2},
{"fwait", 0, NULL, 0x9b, 1},
{"fxam", 0, NULL, 0xd9e5, 2},
{"fxch", 0, &opfxch, 0},
{"fxrstor", 0, &opfxrstor, 0},
{"fxsave", 0, &opfxsave, 0},
{"fxtract", 0, NULL, 0xd9f4, 2},
{"fyl2x", 0, NULL, 0xd9f1, 2},
{"fyl2xp1", 0, NULL, 0xd9f9, 2},
{"getsec", 0, NULL, 0x0f37, 2},
{"hlt", 0, NULL, 0xf4, 1},
{"idiv", 0, &opidiv, 0},
{"imul", 0, &opimul, 0},
{"in", 0, &opin, 0},
{"inc", 0, &opinc, 0},
{"ins", 0, NULL, 0x6d, 1},
{"insb", 0, NULL, 0x6c, 1},
{"insd", 0, NULL, 0x6d, 1},
{"insw", 0, NULL, 0x666d, 2},
{"int", 0, &opint, 0},
{"int1", 0, NULL, 0xf1, 1},
{"int3", 0, NULL, 0xcc, 1},
{"into", 0, NULL, 0xce, 1},
{"invd", 0, NULL, 0x0f08, 2},
{"iret", 0, NULL, 0x66cf, 2},
{"iretd", 0, NULL, 0xcf, 1},
{"ja", 0, &opjc, 0},
{"jae", 0, &opjc, 0},
{"jb", 0, &opjc, 0},
{"jbe", 0, &opjc, 0},
{"jc", 0, &opjc, 0},
{"je", 0, &opjc, 0},
{"jg", 0, &opjc, 0},
{"jge", 0, &opjc, 0},
{"jl", 0, &opjc, 0},
{"jle", 0, &opjc, 0},
{"jmp", 0, &opjc, 0},
{"jna", 0, &opjc, 0},
{"jnae", 0, &opjc, 0},
{"jnb", 0, &opjc, 0},
{"jnbe", 0, &opjc, 0},
{"jnc", 0, &opjc, 0},
{"jne", 0, &opjc, 0},
{"jng", 0, &opjc, 0},
{"jnge", 0, &opjc, 0},
{"jnl", 0, &opjc, 0},
{"jnle", 0, &opjc, 0},
{"jno", 0, &opjc, 0},
{"jnp", 0, &opjc, 0},
{"jns", 0, &opjc, 0},
{"jnz", 0, &opjc, 0},
{"jo", 0, &opjc, 0},
{"jp", 0, &opjc, 0},
{"jpe", 0, &opjc, 0},
{"jpo", 0, &opjc, 0},
{"js", 0, &opjc, 0},
{"jz", 0, &opjc, 0},
{"lahf", 0, NULL, 0x9f},
{"lea", 0, &oplea, 0},
{"leave", 0, NULL, 0xc9, 1},
{"les", 0, &oples, 0},
{"lfence", 0, NULL, 0x0faee8, 3},
{"lgdt", 0, &oplgdt, 0},
{"lidt", 0, &oplidt, 0},
{"lldt", 0, &oplldt, 0},
{"lmsw", 0, &oplmsw, 0},
{"lodsb", 0, NULL, 0xac, 1},
{"lodsd", 0, NULL, 0xad, 1},
{"lodsw", 0, NULL, 0x66ad, 2},
{"loop", 0, &oploop, 0},
{"mfence", 0, NULL, 0x0faef0, 3},
{"monitor", 0, NULL, 0x0f01c8, 3},
{"mov", 0, &opmov, 0},
{"movsb", 0, NULL, 0xa4, 1},
{"movsd", 0, NULL, 0xa5, 1},
{"movsw", 0, NULL, 0x66a5, 2},
{"movzx", 0, &opmovx, 0},
{"movsx", 0, &opmovx, 0},
{"mul", 0, &opmul, 0},
{"mwait", 0, NULL, 0x0f01c9, 3},
{"nop", 0, NULL, 0x90, 1},
{"not", 0, &opnot, 0},
{"or", 0, &opor, 0},
{"out", 0, &opout, 0},
{"outsb", 0, NULL, 0x6e, 1},
{"outs", 0, NULL, 0x6f, 1},
{"outsd", 0, NULL, 0x6f, 1},
{"outsw", 0, NULL, 0x666f, 2},
{"pop", 0, &oppop, 0},
{"popa", 1, NULL, 0x61, 1},
{"popad", 1, NULL, 0x61, 1},
{"popal", 1, NULL, 0x61, 1},
{"popaw", 1, NULL, 0x6661, 2},
{"popfd", 1, NULL, 0x9d, 1},
{"prefetch", 0, NULL, 0x0f0d, 2},
{"push", 0, &oppush, 0},
{"pusha", 1, NULL, 0x60, 1},
{"pushad", 1, NULL, 0x60, 1},
{"pushal", 1, NULL, 0x60, 1},
{"pushfd", 0, NULL, 0x9c, 1},
{"rcl", 0, &process_group_2, 0},
{"rcr", 0, &process_group_2, 0},
{"rep", 0, &oprep, 0},
{"repe", 0, &oprep, 0},
{"repne", 0, &oprep, 0},
{"repz", 0, &oprep, 0},
{"repnz", 0, &oprep, 0},
{"rdmsr", 0, NULL, 0x0f32, 2},
{"rdpmc", 0, NULL, 0x0f33, 2},
{"rdtsc", 0, NULL, 0x0f31, 2},
{"rdtscp", 0, NULL, 0x0f01f9, 3},
{"ret", 0, &opret, 0},
{"retf", 0, &opretf, 0},
{"retw", 0, NULL, 0x66c3, 2},
{"rol", 0, &process_group_2, 0},
{"ror", 0, &process_group_2, 0},
{"rsm", 0, NULL, 0x0faa, 2},
{"sahf", 0, NULL, 0x9e, 1},
{"sal", 0, &process_group_2, 0},
{"salc", 0, NULL, 0xd6, 1},
{"sar", 0, &process_group_2, 0},
{"sbb", 0, &opsbb, 0},
{"scasb", 0, NULL, 0xae, 1},
{"scasd", 0, NULL, 0xaf, 1},
{"scasw", 0, NULL, 0x66af, 2},
{"seto", 0, &opset, 0},
{"setno", 0, &opset, 0},
{"setb", 0, &opset, 0},
{"setnae", 0, &opset, 0},
{"setc", 0, &opset, 0},
{"setnb", 0, &opset, 0},
{"setae", 0, &opset, 0},
{"setnc", 0, &opset, 0},
{"setz", 0, &opset, 0},
{"sete", 0, &opset, 0},
{"setnz", 0, &opset, 0},
{"setne", 0, &opset, 0},
{"setbe", 0, &opset, 0},
{"setna", 0, &opset, 0},
{"setnbe", 0, &opset, 0},
{"seta", 0, &opset, 0},
{"sets", 0, &opset, 0},
{"setns", 0, &opset, 0},
{"setp", 0, &opset, 0},
{"setpe", 0, &opset, 0},
{"setnp", 0, &opset, 0},
{"setpo", 0, &opset, 0},
{"setl", 0, &opset, 0},
{"setnge", 0, &opset, 0},
{"setnl", 0, &opset, 0},
{"setge", 0, &opset, 0},
{"setle", 0, &opset, 0},
{"setng", 0, &opset, 0},
{"setnle", 0, &opset, 0},
{"setg", 0, &opset, 0},
{"sfence", 0, NULL, 0x0faef8, 3},
{"sgdt", 0, &opsgdt, 0},
{"shl", 0, &process_group_2, 0},
{"shr", 0, &process_group_2, 0},
{"sidt", 0, &opsidt, 0},
{"sldt", 0, &opsldt, 0},
{"smsw", 0, &opsmsw, 0},
{"stc", 0, NULL, 0xf9, 1},
{"std", 0, NULL, 0xfd, 1},
{"stgi", 0, NULL, 0x0f01dc, 3},
{"sti", 0, NULL, 0xfb, 1},
{"stmxcsr", 0, &opstmxcsr, 0},
{"stosb", 0, &opstos, 0},
{"stosd", 0, &opstos, 0},
{"stosw", 0, &opstos, 0},
{"str", 0, &opstr, 0},
{"sub", 0, &opsub, 0},
{"swapgs", 0, NULL, 0x0f1ff8, 3},
{"syscall", 0, NULL, 0x0f05, 2},
{"sysenter", 0, NULL, 0x0f34, 2},
{"sysexit", 0, NULL, 0x0f35, 2},
{"sysret", 0, NULL, 0x0f07, 2},
{"ud2", 0, NULL, 0x0f0b, 2},
{"verr", 0, &opverr, 0},
{"verw", 0, &opverw, 0},
{"vmcall", 0, NULL, 0x0f01c1, 3},
{"vmclear", 0, &opvmclear, 0},
{"vmlaunch", 0, NULL, 0x0f01c2, 3},
{"vmload", 0, NULL, 0x0f01da, 3},
{"vmmcall", 0, NULL, 0x0f01d9, 3},
{"vmptrld", 0, &opvmptrld, 0},
{"vmptrst", 0, &opvmptrst, 0},
{"vmresume", 0, NULL, 0x0f01c3, 3},
{"vmrun", 0, NULL, 0x0f01d8, 3},
{"vmsave", 0, NULL, 0x0f01db, 3},
{"vmxoff", 0, NULL, 0x0f01c4, 3},
{"vmxon", 0, &opvmon, 0},
{"vzeroall", 0, NULL, 0xc5fc77, 3},
{"vzeroupper", 0, NULL, 0xc5f877, 3},
{"wait", 0, NULL, 0x9b, 1},
{"wbinvd", 0, NULL, 0x0f09, 2},
{"wrmsr", 0, NULL, 0x0f30, 2},
{"xadd", 0, &opxadd, 0},
{"xchg", 0, &opxchg, 0},
{"xgetbv", 0, NULL, 0x0f01d0, 3},
{"xlatb", 0, NULL, 0xd7, 1},
{"xor", 0, &opxor, 0},
{"xsetbv", 0, NULL, 0x0f01d1, 3},
{"test", 0, &optest, 0},
{"null", 0, NULL, 0, 0}
};
static x86newTokenType getToken(const char *str, size_t *begin, size_t *end) {
if (*begin > strlen (str)) {
return TT_EOF;
}
// Skip whitespace
while (begin && str[*begin] && isspace ((ut8)str[*begin])) {
++(*begin);
}
if (!str[*begin]) { // null byte
*end = *begin;
return TT_EOF;
}
if (isalpha ((ut8)str[*begin])) { // word token
*end = *begin;
while (end && str[*end] && isalnum ((ut8)str[*end])) {
++(*end);
}
return TT_WORD;
}
if (isdigit ((ut8)str[*begin])) { // number token
*end = *begin;
while (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex.
++(*end);
}
return TT_NUMBER;
} else { // special character: [, ], +, *, ...
*end = *begin + 1;
return TT_SPECIAL;
}
}
/**
* Get the register at position pos in str. Increase pos afterwards.
*/
static Register parseReg(RAsm *a, const char *str, size_t *pos, ut32 *type) {
int i;
// Must be the same order as in enum register_t
const char *regs[] = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "eip", NULL };
const char *regsext[] = { "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d", NULL };
const char *regs8[] = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh", NULL };
const char *regs16[] = { "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", NULL };
const char *regs64[] = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "rip", NULL};
const char *regs64ext[] = { "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", NULL };
const char *sregs[] = { "es", "cs", "ss", "ds", "fs", "gs", NULL};
// Get token (especially the length)
size_t nextpos, length;
const char *token;
getToken (str, pos, &nextpos);
token = str + *pos;
length = nextpos - *pos;
*pos = nextpos;
// General purpose registers
if (length == 3 && token[0] == 'e') {
for (i = 0; regs[i]; i++) {
if (!r_str_ncasecmp (regs[i], token, length)) {
*type = (OT_GPREG & OT_REG (i)) | OT_DWORD;
return i;
}
}
}
if (length == 2 && (token[1] == 'l' || token[1] == 'h')) {
for (i = 0; regs8[i]; i++) {
if (!r_str_ncasecmp (regs8[i], token, length)) {
*type = (OT_GPREG & OT_REG (i)) | OT_BYTE;
return i;
}
}
}
if (length == 2) {
for (i = 0; regs16[i]; i++) {
if (!r_str_ncasecmp (regs16[i], token, length)) {
*type = (OT_GPREG & OT_REG (i)) | OT_WORD;
return i;
}
}
// This isn't working properly yet
for (i = 0; sregs[i]; i++) {
if (!r_str_ncasecmp (sregs[i], token, length)) {
*type = (OT_SEGMENTREG & OT_REG (i)) | OT_WORD;
return i;
}
}
}
if (token[0] == 'r') {
for (i = 0; regs64[i]; i++) {
if (!r_str_ncasecmp (regs64[i], token, length)) {
*type = (OT_GPREG & OT_REG (i)) | OT_QWORD;
a->bits = 64;
return i;
}
}
for (i = 0; regs64ext[i]; i++) {
if (!r_str_ncasecmp (regs64ext[i], token, length)) {
*type = (OT_GPREG & OT_REG (i)) | OT_QWORD;
a->bits = 64;
return i + 9;
}
}
for (i = 0; regsext[i]; i++) {
if (!r_str_ncasecmp (regsext[i], token, length)) {
*type = (OT_GPREG & OT_REG (i)) | OT_DWORD;
if (a->bits < 32) {
a->bits = 32;
}
return i + 9;
}
}
}
// Extended registers
if (!r_str_ncasecmp ("st", token, 2)) {
*type = (OT_FPUREG & ~OT_REGALL);
*pos = 3;
}
if (!r_str_ncasecmp ("mm", token, 2)) {
*type = (OT_MMXREG & ~OT_REGALL);
*pos = 3;
}
if (!r_str_ncasecmp ("xmm", token, 3)) {
*type = (OT_XMMREG & ~OT_REGALL);
*pos = 4;
}
// Now read number, possibly with parantheses
if (*type & (OT_FPUREG | OT_MMXREG | OT_XMMREG) & ~OT_REGALL) {
Register reg = X86R_UNDEFINED;
// pass by '(',if there is one
if (getToken (str, pos, &nextpos) == TT_SPECIAL && str[*pos] == '(') {
*pos = nextpos;
}
// read number
// const int maxreg = (a->bits == 64) ? 15 : 7;
if (getToken (str, pos, &nextpos) != TT_NUMBER ||
(reg = getnum (a, str + *pos)) > 7) {
if ((int)reg > 15) {
eprintf ("Too large register index!\n");
return X86R_UNDEFINED;
} else {
reg -= 8;
}
}
*pos = nextpos;
// pass by ')'
if (getToken (str, pos, &nextpos) == TT_SPECIAL && str[*pos] == ')') {
*pos = nextpos;
}
// Safety to prevent a shift bigger than 31. Reg
// should never be > 8 anyway
if (reg > 7) {
eprintf ("Too large register index!\n");
return X86R_UNDEFINED;
}
*type |= (OT_REG (reg) & ~OT_REGTYPE);
return reg;
}
return X86R_UNDEFINED;
}
static void parse_segment_offset(RAsm *a, const char *str, size_t *pos,
Operand *op, int reg_index) {
int nextpos = *pos;
char *c = strchr (str + nextpos, ':');
if (c) {
nextpos ++; // Skip the ':'
c = strchr (str + nextpos, '[');
if (c) {nextpos ++;} // Skip the '['
// Assign registers to match behaviour of OT_MEMORY type
op->regs[reg_index] = op->reg;
op->type |= OT_MEMORY;
op->offset_sign = 1;
char *p = strchr (str + nextpos, '-');
if (p) {
op->offset_sign = -1;
nextpos ++;
}
op->scale[reg_index] = getnum (a, str + nextpos);
op->offset = op->scale[reg_index];
}
}
// Parse operand
static int parseOperand(RAsm *a, const char *str, Operand *op, bool isrepop) {
size_t pos, nextpos = 0;
x86newTokenType last_type;
int size_token = 1;
bool explicit_size = false;
int reg_index = 0;
// Reset type
op->type = 0;
// Consume tokens denoting the operand size
while (size_token) {
pos = nextpos;
last_type = getToken (str, &pos, &nextpos);
// Token may indicate size: then skip
if (!r_str_ncasecmp (str + pos, "ptr", 3)) {
continue;
} else if (!r_str_ncasecmp (str + pos, "byte", 4)) {
op->type |= OT_MEMORY | OT_BYTE;
op->dest_size = OT_BYTE;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "word", 4)) {
op->type |= OT_MEMORY | OT_WORD;
op->dest_size = OT_WORD;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "dword", 5)) {
op->type |= OT_MEMORY | OT_DWORD;
op->dest_size = OT_DWORD;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "qword", 5)) {
op->type |= OT_MEMORY | OT_QWORD;
op->dest_size = OT_QWORD;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "oword", 5)) {
op->type |= OT_MEMORY | OT_OWORD;
op->dest_size = OT_OWORD;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "tbyte", 5)) {
op->type |= OT_MEMORY | OT_TBYTE;
op->dest_size = OT_TBYTE;
explicit_size = true;
} else { // the current token doesn't denote a size
size_token = 0;
}
}
// Next token: register, immediate, or '['
if (str[pos] == '[') {
// Don't care about size, if none is given.
if (!op->type) {
op->type = OT_MEMORY;
}
// At the moment, we only accept plain linear combinations:
// part := address | [factor *] register
// address := part {+ part}*
op->offset = op->scale[0] = op->scale[1] = 0;
ut64 temp = 1;
Register reg = X86R_UNDEFINED;
bool first_reg = true;
while (str[pos] != ']') {
if (pos > nextpos) {
// eprintf ("Error parsing instruction\n");
break;
}
pos = nextpos;
if (!str[pos]) {
break;
}
last_type = getToken (str, &pos, &nextpos);
if (last_type == TT_SPECIAL) {
if (str[pos] == '+' || str[pos] == '-' || str[pos] == ']') {
if (reg != X86R_UNDEFINED) {
if (reg_index < 2) {
op->regs[reg_index] = reg;
op->scale[reg_index] = temp;
}
++reg_index;
} else {
op->offset += temp;
if (reg_index < 2) {
op->regs[reg_index] = X86R_UNDEFINED;
}
}
temp = 1;
reg = X86R_UNDEFINED;
} else if (str[pos] == '*') {
// go to ], + or - to get scale
// Something to do here?
// Seems we are just ignoring '*' or assuming it implicitly.
}
}
else if (last_type == TT_WORD) {
ut32 reg_type = 0;
// We can't multiply registers
if (reg != X86R_UNDEFINED) {
op->type = 0; // Make the result invalid
}
// Reset nextpos: parseReg wants to parse from the beginning
nextpos = pos;
reg = parseReg (a, str, &nextpos, ®_type);
if (first_reg) {
op->extended = false;
if (reg > 8) {
op->extended = true;
op->reg = reg - 9;
}
first_reg = false;
} else if (reg > 8) {
op->reg = reg - 9;
}
if (reg_type & OT_REGTYPE & OT_SEGMENTREG) {
op->reg = reg;
op->type = reg_type;
parse_segment_offset (a, str, &nextpos, op, reg_index);
return nextpos;
}
// Still going to need to know the size if not specified
if (!explicit_size) {
op->type |= reg_type;
}
op->reg_size = reg_type;
op->explicit_size = explicit_size;
// Addressing only via general purpose registers
if (!(reg_type & OT_GPREG)) {
op->type = 0; // Make the result invalid
}
}
else {
char *p = strchr (str, '+');
op->offset_sign = 1;
if (!p) {
p = strchr (str, '-');
if (p) {
op->offset_sign = -1;
}
}
//with SIB notation, we need to consider the right sign
char * plus = strchr (str, '+');
char * minus = strchr (str, '-');
char * closeB = strchr (str, ']');
if (plus && minus && plus < closeB && minus < closeB) {
op->offset_sign = -1;
}
// If there's a scale, we don't want to parse out the
// scale with the offset (scale + offset) otherwise the scale
// will be the sum of the two. This splits the numbers
char *tmp;
tmp = malloc (strlen (str + pos) + 1);
strcpy (tmp, str + pos);
strtok (tmp, "+-");
st64 read = getnum (a, tmp);
free (tmp);
temp *= read;
}
}
} else if (last_type == TT_WORD) { // register
nextpos = pos;
RFlagItem *flag;
if (isrepop) {
op->is_good_flag = false;
strncpy (op->rep_op, str, MAX_REPOP_LENGTH - 1);
op->rep_op[MAX_REPOP_LENGTH - 1] = '\0';
return nextpos;
}
op->reg = parseReg (a, str, &nextpos, &op->type);
op->extended = false;
if (op->reg > 8) {
op->extended = true;
op->reg -= 9;
}
if (op->type & OT_REGTYPE & OT_SEGMENTREG) {
parse_segment_offset (a, str, &nextpos, op, reg_index);
return nextpos;
}
if (op->reg == X86R_UNDEFINED) {
op->is_good_flag = false;
if (a->num && a->num->value == 0) {
return nextpos;
}
op->type = OT_CONSTANT;
RCore *core = a->num? (RCore *)(a->num->userptr): NULL;
if (core && (flag = r_flag_get (core->flags, str))) {
op->is_good_flag = true;
}
char *p = strchr (str, '-');
if (p) {
op->sign = -1;
str = ++p;
}
op->immediate = getnum (a, str);
} else if (op->reg < X86R_UNDEFINED) {
strncpy (op->rep_op, str, MAX_REPOP_LENGTH - 1);
op->rep_op[MAX_REPOP_LENGTH - 1] = '\0';
}
} else { // immediate
// We don't know the size, so let's just set no size flag.
op->type = OT_CONSTANT;
op->sign = 1;
char *p = strchr (str, '-');
if (p) {
op->sign = -1;
str = ++p;
}
op->immediate = getnum (a, str);
}
return nextpos;
}
static int parseOpcode(RAsm *a, const char *op, Opcode *out) {
out->has_bnd = false;
bool isrepop = false;
if (!strncmp (op, "bnd ", 4)) {
out->has_bnd = true;
op += 4;
}
char *args = strchr (op, ' ');
out->mnemonic = args ? r_str_ndup (op, args - op) : strdup (op);
out->operands[0].type = out->operands[1].type = 0;
out->operands[0].extended = out->operands[1].extended = false;
out->operands[0].reg = out->operands[0].regs[0] = out->operands[0].regs[1] = X86R_UNDEFINED;
out->operands[1].reg = out->operands[1].regs[0] = out->operands[1].regs[1] = X86R_UNDEFINED;
out->operands[0].immediate = out->operands[1].immediate = 0;
out->operands[0].sign = out->operands[1].sign = 1;
out->operands[0].is_good_flag = out->operands[1].is_good_flag = true;
out->is_short = false;
out->operands_count = 0;
if (args) {
args++;
} else {
return 1;
}
if (!r_str_ncasecmp (args, "short", 5)) {
out->is_short = true;
args += 5;
}
if (!strncmp (out->mnemonic, "rep", 3)) {
isrepop = true;
}
parseOperand (a, args, &(out->operands[0]), isrepop);
out->operands_count = 1;
while (out->operands_count < MAX_OPERANDS) {
args = strchr (args, ',');
if (!args) {
break;
}
args++;
parseOperand (a, args, &(out->operands[out->operands_count]), isrepop);
out->operands_count++;
}
return 0;
}
static ut64 getnum(RAsm *a, const char *s) {
if (!s) {
return 0;
}
if (*s == '$') {
s++;
}
return r_num_math (a->num, s);
}
static int oprep(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
LookupTable *lt_ptr;
int retval;
if (!strcmp (op->mnemonic, "rep") ||
!strcmp (op->mnemonic, "repe") ||
!strcmp (op->mnemonic, "repz")) {
data[l++] = 0xf3;
} else if (!strcmp (op->mnemonic, "repne") ||
!strcmp (op->mnemonic, "repnz")) {
data[l++] = 0xf2;
}
Opcode instr = {0};
parseOpcode (a, op->operands[0].rep_op, &instr);
for (lt_ptr = oplookup; strcmp (lt_ptr->mnemonic, "null"); lt_ptr++) {
if (!r_str_casecmp (instr.mnemonic, lt_ptr->mnemonic)) {
if (lt_ptr->opcode > 0) {
if (lt_ptr->only_x32 && a->bits == 64) {
free (instr.mnemonic);
return -1;
}
ut8 *ptr = (ut8 *)<_ptr->opcode;
int i = 0;
for (; i < lt_ptr->size; i++) {
data[i + l] = ptr[lt_ptr->size - (i + 1)];
}
free (instr.mnemonic);
return l + lt_ptr->size;
} else {
if (lt_ptr->opdo) {
data += l;
if (instr.has_bnd) {
data[l] = 0xf2;
data++;
}
retval = lt_ptr->opdo (a, data, &instr);
// if op supports bnd then the first byte will
// be 0xf2.
if (instr.has_bnd) {
retval++;
}
return l + retval;
}
break;
}
}
}
free (instr.mnemonic);
return -1;
}
static int assemble(RAsm *a, RAsmOp *ao, const char *str) {
ut8 __data[32] = {0};
ut8 *data = __data;
char op[128];
LookupTable *lt_ptr;
int retval = -1;
Opcode instr = {0};
strncpy (op, str, sizeof (op) - 1);
op[sizeof (op) - 1] = '\0';
parseOpcode (a, op, &instr);
for (lt_ptr = oplookup; strcmp (lt_ptr->mnemonic, "null"); lt_ptr++) {
if (!r_str_casecmp (instr.mnemonic, lt_ptr->mnemonic)) {
if (lt_ptr->opcode > 0) {
if (!lt_ptr->only_x32 || a->bits != 64) {
ut8 *ptr = (ut8 *)<_ptr->opcode;
int i = 0;
for (; i < lt_ptr->size; i++) {
data[i] = ptr[lt_ptr->size - (i + 1)];
}
retval = lt_ptr->size;
}
} else {
if (lt_ptr->opdo) {
if (instr.has_bnd) {
data[0] = 0xf2;
data ++;
}
retval = lt_ptr->opdo (a, data, &instr);
// if op supports bnd then the first byte will
// be 0xf2.
if (instr.has_bnd) {
retval++;
}
}
}
break;
}
}
r_asm_op_set_buf (ao, __data, retval);
free (instr.mnemonic);
return retval;
}
RAsmPlugin r_asm_plugin_x86_nz = {
.name = "x86.nz",
.desc = "x86 handmade assembler",
.license = "LGPL3",
.arch = "x86",
.bits = 16 | 32 | 64,
.endian = R_SYS_ENDIAN_LITTLE,
.assemble = &assemble
};
#ifndef CORELIB
R_API RLibStruct radare_plugin = {
.type = R_LIB_TYPE_ASM,
.data = &r_asm_plugin_x86_nz,
.version = R2_VERSION
};
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_500_0 |
crossvul-cpp_data_bad_3191_0 | /*
* bplist.c
* Binary plist implementation
*
* Copyright (c) 2011-2017 Nikias Bassen, All Rights Reserved.
* Copyright (c) 2008-2010 Jonathan Beck, All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <inttypes.h>
#include <plist/plist.h>
#include "plist.h"
#include "hashtable.h"
#include "bytearray.h"
#include "ptrarray.h"
#include <node.h>
#include <node_iterator.h>
/* Magic marker and size. */
#define BPLIST_MAGIC ((uint8_t*)"bplist")
#define BPLIST_MAGIC_SIZE 6
#define BPLIST_VERSION ((uint8_t*)"00")
#define BPLIST_VERSION_SIZE 2
typedef struct __attribute__((packed)) {
uint8_t unused[6];
uint8_t offset_size;
uint8_t ref_size;
uint64_t num_objects;
uint64_t root_object_index;
uint64_t offset_table_offset;
} bplist_trailer_t;
enum
{
BPLIST_NULL = 0x00,
BPLIST_FALSE = 0x08,
BPLIST_TRUE = 0x09,
BPLIST_FILL = 0x0F, /* will be used for length grabbing */
BPLIST_UINT = 0x10,
BPLIST_REAL = 0x20,
BPLIST_DATE = 0x30,
BPLIST_DATA = 0x40,
BPLIST_STRING = 0x50,
BPLIST_UNICODE = 0x60,
BPLIST_UNK_0x70 = 0x70,
BPLIST_UID = 0x80,
BPLIST_ARRAY = 0xA0,
BPLIST_SET = 0xC0,
BPLIST_DICT = 0xD0,
BPLIST_MASK = 0xF0
};
union plist_uint_ptr
{
const void *src;
uint8_t *u8ptr;
uint16_t *u16ptr;
uint32_t *u32ptr;
uint64_t *u64ptr;
};
#define get_unaligned(ptr) \
({ \
struct __attribute__((packed)) { \
typeof(*(ptr)) __v; \
} *__p = (void *) (ptr); \
__p->__v; \
})
#ifndef bswap16
#define bswap16(x) ((((x) & 0xFF00) >> 8) | (((x) & 0x00FF) << 8))
#endif
#ifndef bswap32
#define bswap32(x) ((((x) & 0xFF000000) >> 24) \
| (((x) & 0x00FF0000) >> 8) \
| (((x) & 0x0000FF00) << 8) \
| (((x) & 0x000000FF) << 24))
#endif
#ifndef bswap64
#define bswap64(x) ((((x) & 0xFF00000000000000ull) >> 56) \
| (((x) & 0x00FF000000000000ull) >> 40) \
| (((x) & 0x0000FF0000000000ull) >> 24) \
| (((x) & 0x000000FF00000000ull) >> 8) \
| (((x) & 0x00000000FF000000ull) << 8) \
| (((x) & 0x0000000000FF0000ull) << 24) \
| (((x) & 0x000000000000FF00ull) << 40) \
| (((x) & 0x00000000000000FFull) << 56))
#endif
#ifndef be16toh
#ifdef __BIG_ENDIAN__
#define be16toh(x) (x)
#else
#define be16toh(x) bswap16(x)
#endif
#endif
#ifndef be32toh
#ifdef __BIG_ENDIAN__
#define be32toh(x) (x)
#else
#define be32toh(x) bswap32(x)
#endif
#endif
#ifndef be64toh
#ifdef __BIG_ENDIAN__
#define be64toh(x) (x)
#else
#define be64toh(x) bswap64(x)
#endif
#endif
#ifdef __BIG_ENDIAN__
#define beNtoh(x,n) (x >> ((8-n) << 3))
#else
#define beNtoh(x,n) be64toh(x << ((8-n) << 3))
#endif
#define UINT_TO_HOST(x, n) \
({ \
union plist_uint_ptr __up; \
__up.src = (n > 8) ? x + (n - 8) : x; \
(n >= 8 ? be64toh( get_unaligned(__up.u64ptr) ) : \
(n == 4 ? be32toh( get_unaligned(__up.u32ptr) ) : \
(n == 2 ? be16toh( get_unaligned(__up.u16ptr) ) : \
(n == 1 ? *__up.u8ptr : \
beNtoh( get_unaligned(__up.u64ptr), n) \
)))); \
})
#define get_needed_bytes(x) \
( ((uint64_t)x) < (1ULL << 8) ? 1 : \
( ((uint64_t)x) < (1ULL << 16) ? 2 : \
( ((uint64_t)x) < (1ULL << 24) ? 3 : \
( ((uint64_t)x) < (1ULL << 32) ? 4 : 8))))
#define get_real_bytes(x) (x == (float) x ? sizeof(float) : sizeof(double))
#if (defined(__LITTLE_ENDIAN__) \
&& !defined(__FLOAT_WORD_ORDER__)) \
|| (defined(__FLOAT_WORD_ORDER__) \
&& __FLOAT_WORD_ORDER__ == __ORDER_LITTLE_ENDIAN__)
#define float_bswap64(x) bswap64(x)
#define float_bswap32(x) bswap32(x)
#else
#define float_bswap64(x) (x)
#define float_bswap32(x) (x)
#endif
#define NODE_IS_ROOT(x) (((node_t*)x)->isRoot)
struct bplist_data {
const char* data;
uint64_t size;
uint64_t num_objects;
uint8_t ref_size;
uint8_t offset_size;
const char* offset_table;
uint32_t level;
plist_t used_indexes;
};
#ifdef DEBUG
static int plist_bin_debug = 0;
#define PLIST_BIN_ERR(...) if (plist_bin_debug) { fprintf(stderr, "libplist[binparser] ERROR: " __VA_ARGS__); }
#else
#define PLIST_BIN_ERR(...)
#endif
void plist_bin_init(void)
{
/* init binary plist stuff */
#ifdef DEBUG
char *env_debug = getenv("PLIST_BIN_DEBUG");
if (env_debug && !strcmp(env_debug, "1")) {
plist_bin_debug = 1;
}
#endif
}
void plist_bin_deinit(void)
{
/* deinit binary plist stuff */
}
static plist_t parse_bin_node_at_index(struct bplist_data *bplist, uint32_t node_index);
static plist_t parse_uint_node(const char **bnode, uint8_t size)
{
plist_data_t data = plist_new_plist_data();
size = 1 << size; // make length less misleading
switch (size)
{
case sizeof(uint8_t):
case sizeof(uint16_t):
case sizeof(uint32_t):
case sizeof(uint64_t):
data->length = sizeof(uint64_t);
break;
case 16:
data->length = size;
break;
default:
free(data);
PLIST_BIN_ERR("%s: Invalid byte size for integer node\n", __func__);
return NULL;
};
data->intval = UINT_TO_HOST(*bnode, size);
(*bnode) += size;
data->type = PLIST_UINT;
return node_create(NULL, data);
}
static plist_t parse_real_node(const char **bnode, uint8_t size)
{
plist_data_t data = plist_new_plist_data();
uint8_t buf[8];
size = 1 << size; // make length less misleading
switch (size)
{
case sizeof(uint32_t):
*(uint32_t*)buf = float_bswap32(*(uint32_t*)*bnode);
data->realval = *(float *) buf;
break;
case sizeof(uint64_t):
*(uint64_t*)buf = float_bswap64(*(uint64_t*)*bnode);
data->realval = *(double *) buf;
break;
default:
free(data);
PLIST_BIN_ERR("%s: Invalid byte size for real node\n", __func__);
return NULL;
}
data->type = PLIST_REAL;
data->length = sizeof(double);
return node_create(NULL, data);
}
static plist_t parse_date_node(const char **bnode, uint8_t size)
{
plist_t node = parse_real_node(bnode, size);
plist_data_t data = plist_get_data(node);
data->type = PLIST_DATE;
return node;
}
static plist_t parse_string_node(const char **bnode, uint64_t size)
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_STRING;
data->strval = (char *) malloc(sizeof(char) * (size + 1));
memcpy(data->strval, *bnode, size);
data->strval[size] = '\0';
data->length = strlen(data->strval);
return node_create(NULL, data);
}
static char *plist_utf16_to_utf8(uint16_t *unistr, long len, long *items_read, long *items_written)
{
if (!unistr || (len <= 0)) return NULL;
char *outbuf = (char*)malloc(4*(len+1));
int p = 0;
long i = 0;
uint16_t wc;
uint32_t w;
int read_lead_surrogate = 0;
while (i < len) {
wc = unistr[i++];
if (wc >= 0xD800 && wc <= 0xDBFF) {
if (!read_lead_surrogate) {
read_lead_surrogate = 1;
w = 0x010000 + ((wc & 0x3FF) << 10);
} else {
// This is invalid, the next 16 bit char should be a trail surrogate.
// Handling error by skipping.
read_lead_surrogate = 0;
}
} else if (wc >= 0xDC00 && wc <= 0xDFFF) {
if (read_lead_surrogate) {
read_lead_surrogate = 0;
w = w | (wc & 0x3FF);
outbuf[p++] = (char)(0xF0 + ((w >> 18) & 0x7));
outbuf[p++] = (char)(0x80 + ((w >> 12) & 0x3F));
outbuf[p++] = (char)(0x80 + ((w >> 6) & 0x3F));
outbuf[p++] = (char)(0x80 + (w & 0x3F));
} else {
// This is invalid. A trail surrogate should always follow a lead surrogate.
// Handling error by skipping
}
} else if (wc >= 0x800) {
outbuf[p++] = (char)(0xE0 + ((wc >> 12) & 0xF));
outbuf[p++] = (char)(0x80 + ((wc >> 6) & 0x3F));
outbuf[p++] = (char)(0x80 + (wc & 0x3F));
} else if (wc >= 0x80) {
outbuf[p++] = (char)(0xC0 + ((wc >> 6) & 0x1F));
outbuf[p++] = (char)(0x80 + (wc & 0x3F));
} else {
outbuf[p++] = (char)(wc & 0x7F);
}
}
if (items_read) {
*items_read = i;
}
if (items_written) {
*items_written = p;
}
outbuf[p] = 0;
return outbuf;
}
static plist_t parse_unicode_node(const char **bnode, uint64_t size)
{
plist_data_t data = plist_new_plist_data();
uint64_t i = 0;
uint16_t *unicodestr = NULL;
char *tmpstr = NULL;
long items_read = 0;
long items_written = 0;
data->type = PLIST_STRING;
unicodestr = (uint16_t*) malloc(sizeof(uint16_t) * size);
for (i = 0; i < size; i++)
unicodestr[i] = be16toh(((uint16_t*)*bnode)[i]);
tmpstr = plist_utf16_to_utf8(unicodestr, size, &items_read, &items_written);
free(unicodestr);
if (!tmpstr) {
plist_free_data(data);
return NULL;
}
tmpstr[items_written] = '\0';
data->type = PLIST_STRING;
data->strval = realloc(tmpstr, items_written+1);
if (!data->strval)
data->strval = tmpstr;
data->length = items_written;
return node_create(NULL, data);
}
static plist_t parse_data_node(const char **bnode, uint64_t size)
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_DATA;
data->length = size;
data->buff = (uint8_t *) malloc(sizeof(uint8_t) * size);
memcpy(data->buff, *bnode, sizeof(uint8_t) * size);
return node_create(NULL, data);
}
static plist_t parse_dict_node(struct bplist_data *bplist, const char** bnode, uint64_t size)
{
uint64_t j;
uint64_t str_i = 0, str_j = 0;
uint64_t index1, index2;
plist_data_t data = plist_new_plist_data();
const char *index1_ptr = NULL;
const char *index2_ptr = NULL;
data->type = PLIST_DICT;
data->length = size;
plist_t node = node_create(NULL, data);
for (j = 0; j < data->length; j++) {
str_i = j * bplist->ref_size;
str_j = (j + size) * bplist->ref_size;
index1_ptr = (*bnode) + str_i;
index2_ptr = (*bnode) + str_j;
if ((index1_ptr < bplist->data || index1_ptr + bplist->ref_size > bplist->offset_table) ||
(index2_ptr < bplist->data || index2_ptr + bplist->ref_size > bplist->offset_table)) {
plist_free(node);
PLIST_BIN_ERR("%s: dict entry %" PRIu64 " is outside of valid range\n", __func__, j);
return NULL;
}
index1 = UINT_TO_HOST(index1_ptr, bplist->ref_size);
index2 = UINT_TO_HOST(index2_ptr, bplist->ref_size);
if (index1 >= bplist->num_objects) {
plist_free(node);
PLIST_BIN_ERR("%s: dict entry %" PRIu64 ": key index (%" PRIu64 ") must be smaller than the number of objects (%" PRIu64 ")\n", __func__, j, index1, bplist->num_objects);
return NULL;
}
if (index2 >= bplist->num_objects) {
plist_free(node);
PLIST_BIN_ERR("%s: dict entry %" PRIu64 ": value index (%" PRIu64 ") must be smaller than the number of objects (%" PRIu64 ")\n", __func__, j, index1, bplist->num_objects);
return NULL;
}
/* process key node */
plist_t key = parse_bin_node_at_index(bplist, index1);
if (!key) {
plist_free(node);
return NULL;
}
if (plist_get_data(key)->type != PLIST_STRING) {
PLIST_BIN_ERR("%s: dict entry %" PRIu64 ": invalid node type for key\n", __func__, j);
plist_free(key);
plist_free(node);
return NULL;
}
/* enforce key type */
plist_get_data(key)->type = PLIST_KEY;
if (!plist_get_data(key)->strval) {
PLIST_BIN_ERR("%s: dict entry %" PRIu64 ": key must not be NULL\n", __func__, j);
plist_free(key);
plist_free(node);
return NULL;
}
/* process value node */
plist_t val = parse_bin_node_at_index(bplist, index2);
if (!val) {
plist_free(key);
plist_free(node);
return NULL;
}
node_attach(node, key);
node_attach(node, val);
}
return node;
}
static plist_t parse_array_node(struct bplist_data *bplist, const char** bnode, uint64_t size)
{
uint64_t j;
uint64_t str_j = 0;
uint64_t index1;
plist_data_t data = plist_new_plist_data();
const char *index1_ptr = NULL;
data->type = PLIST_ARRAY;
data->length = size;
plist_t node = node_create(NULL, data);
for (j = 0; j < data->length; j++) {
str_j = j * bplist->ref_size;
index1_ptr = (*bnode) + str_j;
if (index1_ptr < bplist->data || index1_ptr + bplist->ref_size > bplist->offset_table) {
plist_free(node);
PLIST_BIN_ERR("%s: array item %" PRIu64 " is outside of valid range\n", __func__, j);
return NULL;
}
index1 = UINT_TO_HOST(index1_ptr, bplist->ref_size);
if (index1 >= bplist->num_objects) {
plist_free(node);
PLIST_BIN_ERR("%s: array item %" PRIu64 " object index (%" PRIu64 ") must be smaller than the number of objects (%" PRIu64 ")\n", __func__, j, index1, bplist->num_objects);
return NULL;
}
/* process value node */
plist_t val = parse_bin_node_at_index(bplist, index1);
if (!val) {
plist_free(node);
return NULL;
}
node_attach(node, val);
}
return node;
}
static plist_t parse_uid_node(const char **bnode, uint8_t size)
{
plist_data_t data = plist_new_plist_data();
size = size + 1;
data->intval = UINT_TO_HOST(*bnode, size);
if (data->intval > UINT32_MAX) {
PLIST_BIN_ERR("%s: value %" PRIu64 " too large for UID node (must be <= %u)\n", __func__, (uint64_t)data->intval, UINT32_MAX);
free(data);
return NULL;
}
(*bnode) += size;
data->type = PLIST_UID;
data->length = sizeof(uint64_t);
return node_create(NULL, data);
}
static plist_t parse_bin_node(struct bplist_data *bplist, const char** object)
{
uint16_t type = 0;
uint64_t size = 0;
if (!object)
return NULL;
type = (**object) & BPLIST_MASK;
size = (**object) & BPLIST_FILL;
(*object)++;
if (size == BPLIST_FILL) {
switch (type) {
case BPLIST_DATA:
case BPLIST_STRING:
case BPLIST_UNICODE:
case BPLIST_ARRAY:
case BPLIST_SET:
case BPLIST_DICT:
{
uint16_t next_size = **object & BPLIST_FILL;
if ((**object & BPLIST_MASK) != BPLIST_UINT) {
PLIST_BIN_ERR("%s: invalid size node type for node type 0x%02x: found 0x%02x, expected 0x%02x\n", __func__, type, **object & BPLIST_MASK, BPLIST_UINT);
return NULL;
}
(*object)++;
next_size = 1 << next_size;
if (*object + next_size > bplist->offset_table) {
PLIST_BIN_ERR("%s: size node data bytes for node type 0x%02x point outside of valid range\n", __func__, type);
return NULL;
}
size = UINT_TO_HOST(*object, next_size);
(*object) += next_size;
break;
}
default:
break;
}
}
switch (type)
{
case BPLIST_NULL:
switch (size)
{
case BPLIST_TRUE:
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_BOOLEAN;
data->boolval = TRUE;
data->length = 1;
return node_create(NULL, data);
}
case BPLIST_FALSE:
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_BOOLEAN;
data->boolval = FALSE;
data->length = 1;
return node_create(NULL, data);
}
case BPLIST_NULL:
default:
return NULL;
}
case BPLIST_UINT:
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UINT data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_uint_node(object, size);
case BPLIST_REAL:
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_REAL data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_real_node(object, size);
case BPLIST_DATE:
if (3 != size) {
PLIST_BIN_ERR("%s: invalid data size for BPLIST_DATE node\n", __func__);
return NULL;
}
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_DATE data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_date_node(object, size);
case BPLIST_DATA:
if (*object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_DATA data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_data_node(object, size);
case BPLIST_STRING:
if (*object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_STRING data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_string_node(object, size);
case BPLIST_UNICODE:
if (*object + size*2 > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UNICODE data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_unicode_node(object, size);
case BPLIST_SET:
case BPLIST_ARRAY:
if (*object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_ARRAY data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_array_node(bplist, object, size);
case BPLIST_UID:
if (*object + size+1 > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UID data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_uid_node(object, size);
case BPLIST_DICT:
if (*object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_REAL data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_dict_node(bplist, object, size);
default:
PLIST_BIN_ERR("%s: unexpected node type 0x%02x\n", __func__, type);
return NULL;
}
return NULL;
}
static plist_t parse_bin_node_at_index(struct bplist_data *bplist, uint32_t node_index)
{
int i = 0;
const char* ptr = NULL;
plist_t plist = NULL;
const char* idx_ptr = NULL;
if (node_index >= bplist->num_objects) {
PLIST_BIN_ERR("node index (%u) must be smaller than the number of objects (%" PRIu64 ")\n", node_index, bplist->num_objects);
return NULL;
}
idx_ptr = bplist->offset_table + node_index * bplist->offset_size;
if (idx_ptr < bplist->offset_table ||
idx_ptr >= bplist->offset_table + bplist->num_objects * bplist->offset_size) {
PLIST_BIN_ERR("node index %u points outside of valid range\n", node_index);
return NULL;
}
ptr = bplist->data + UINT_TO_HOST(idx_ptr, bplist->offset_size);
/* make sure the node offset is in a sane range */
if ((ptr < bplist->data) || (ptr >= bplist->offset_table)) {
PLIST_BIN_ERR("offset for node index %u points outside of valid range\n", node_index);
return NULL;
}
/* store node_index for current recursion level */
if (plist_array_get_size(bplist->used_indexes) < bplist->level+1) {
while (plist_array_get_size(bplist->used_indexes) < bplist->level+1) {
plist_array_append_item(bplist->used_indexes, plist_new_uint(node_index));
}
} else {
plist_array_set_item(bplist->used_indexes, plist_new_uint(node_index), bplist->level);
}
/* recursion check */
if (bplist->level > 0) {
for (i = bplist->level-1; i >= 0; i--) {
plist_t node_i = plist_array_get_item(bplist->used_indexes, i);
plist_t node_level = plist_array_get_item(bplist->used_indexes, bplist->level);
if (plist_compare_node_value(node_i, node_level)) {
PLIST_BIN_ERR("recursion detected in binary plist\n");
return NULL;
}
}
}
/* finally parse node */
bplist->level++;
plist = parse_bin_node(bplist, &ptr);
bplist->level--;
return plist;
}
PLIST_API void plist_from_bin(const char *plist_bin, uint32_t length, plist_t * plist)
{
bplist_trailer_t *trailer = NULL;
uint8_t offset_size = 0;
uint8_t ref_size = 0;
uint64_t num_objects = 0;
uint64_t root_object = 0;
const char *offset_table = NULL;
const char *start_data = NULL;
const char *end_data = NULL;
//first check we have enough data
if (!(length >= BPLIST_MAGIC_SIZE + BPLIST_VERSION_SIZE + sizeof(bplist_trailer_t))) {
PLIST_BIN_ERR("plist data is to small to hold a binary plist\n");
return;
}
//check that plist_bin in actually a plist
if (memcmp(plist_bin, BPLIST_MAGIC, BPLIST_MAGIC_SIZE) != 0) {
PLIST_BIN_ERR("bplist magic mismatch\n");
return;
}
//check for known version
if (memcmp(plist_bin + BPLIST_MAGIC_SIZE, BPLIST_VERSION, BPLIST_VERSION_SIZE) != 0) {
PLIST_BIN_ERR("unsupported binary plist version '%.2s\n", plist_bin+BPLIST_MAGIC_SIZE);
return;
}
start_data = plist_bin + BPLIST_MAGIC_SIZE + BPLIST_VERSION_SIZE;
end_data = plist_bin + length - sizeof(bplist_trailer_t);
//now parse trailer
trailer = (bplist_trailer_t*)end_data;
offset_size = trailer->offset_size;
ref_size = trailer->ref_size;
num_objects = be64toh(trailer->num_objects);
root_object = be64toh(trailer->root_object_index);
offset_table = (char *)(plist_bin + be64toh(trailer->offset_table_offset));
if (num_objects == 0) {
PLIST_BIN_ERR("number of objects must be larger than 0\n");
return;
}
if (offset_size == 0) {
PLIST_BIN_ERR("offset size in trailer must be larger than 0\n");
return;
}
if (ref_size == 0) {
PLIST_BIN_ERR("object reference size in trailer must be larger than 0\n");
return;
}
if (root_object >= num_objects) {
PLIST_BIN_ERR("root object index (%" PRIu64 ") must be smaller than number of objects (%" PRIu64 ")\n", root_object, num_objects);
return;
}
if (offset_table < start_data || offset_table >= end_data) {
PLIST_BIN_ERR("offset table offset points outside of valid range\n");
return;
}
if (offset_table + num_objects * offset_size > end_data) {
PLIST_BIN_ERR("offset table points outside of valid range\n");
return;
}
struct bplist_data bplist;
bplist.data = plist_bin;
bplist.size = length;
bplist.num_objects = num_objects;
bplist.ref_size = ref_size;
bplist.offset_size = offset_size;
bplist.offset_table = offset_table;
bplist.level = 0;
bplist.used_indexes = plist_new_array();
if (!bplist.used_indexes) {
PLIST_BIN_ERR("failed to create array to hold used node indexes. Out of memory?\n");
return;
}
*plist = parse_bin_node_at_index(&bplist, root_object);
plist_free(bplist.used_indexes);
}
static unsigned int plist_data_hash(const void* key)
{
plist_data_t data = plist_get_data((plist_t) key);
unsigned int hash = data->type;
unsigned int i = 0;
char *buff = NULL;
unsigned int size = 0;
switch (data->type)
{
case PLIST_BOOLEAN:
case PLIST_UINT:
case PLIST_REAL:
case PLIST_DATE:
case PLIST_UID:
buff = (char *) &data->intval; //works also for real as we use an union
size = 8;
break;
case PLIST_KEY:
case PLIST_STRING:
buff = data->strval;
size = data->length;
break;
case PLIST_DATA:
case PLIST_ARRAY:
case PLIST_DICT:
//for these types only hash pointer
buff = (char *) &key;
size = sizeof(const void*);
break;
default:
break;
}
// now perform hash using djb2 hashing algorithm
// see: http://www.cse.yorku.ca/~oz/hash.html
hash += 5381;
for (i = 0; i < size; buff++, i++) {
hash = ((hash << 5) + hash) + *buff;
}
return hash;
}
struct serialize_s
{
ptrarray_t* objects;
hashtable_t* ref_table;
};
static void serialize_plist(node_t* node, void* data)
{
uint64_t *index_val = NULL;
struct serialize_s *ser = (struct serialize_s *) data;
uint64_t current_index = ser->objects->len;
//first check that node is not yet in objects
void* val = hash_table_lookup(ser->ref_table, node);
if (val)
{
//data is already in table
return;
}
//insert new ref
index_val = (uint64_t *) malloc(sizeof(uint64_t));
*index_val = current_index;
hash_table_insert(ser->ref_table, node, index_val);
//now append current node to object array
ptr_array_add(ser->objects, node);
//now recurse on children
node_iterator_t *ni = node_iterator_create(node->children);
node_t *ch;
while ((ch = node_iterator_next(ni))) {
serialize_plist(ch, data);
}
node_iterator_destroy(ni);
return;
}
#define Log2(x) (x == 8 ? 3 : (x == 4 ? 2 : (x == 2 ? 1 : 0)))
static void write_int(bytearray_t * bplist, uint64_t val)
{
int size = get_needed_bytes(val);
uint8_t sz;
//do not write 3bytes int node
if (size == 3)
size++;
sz = BPLIST_UINT | Log2(size);
val = be64toh(val);
byte_array_append(bplist, &sz, 1);
byte_array_append(bplist, (uint8_t*)&val + (8-size), size);
}
static void write_uint(bytearray_t * bplist, uint64_t val)
{
uint8_t sz = BPLIST_UINT | 4;
uint64_t zero = 0;
val = be64toh(val);
byte_array_append(bplist, &sz, 1);
byte_array_append(bplist, &zero, sizeof(uint64_t));
byte_array_append(bplist, &val, sizeof(uint64_t));
}
static void write_real(bytearray_t * bplist, double val)
{
int size = get_real_bytes(val); //cheat to know used space
uint8_t buff[9];
buff[0] = BPLIST_REAL | Log2(size);
if (size == sizeof(float)) {
float floatval = (float)val;
*(uint32_t*)(buff+1) = float_bswap32(*(uint32_t*)&floatval);
} else {
*(uint64_t*)(buff+1) = float_bswap64(*(uint64_t*)&val);
}
byte_array_append(bplist, buff, size+1);
}
static void write_date(bytearray_t * bplist, double val)
{
uint8_t buff[9];
buff[0] = BPLIST_DATE | 3;
*(uint64_t*)(buff+1) = float_bswap64(*(uint64_t*)&val);
byte_array_append(bplist, buff, sizeof(buff));
}
static void write_raw_data(bytearray_t * bplist, uint8_t mark, uint8_t * val, uint64_t size)
{
uint8_t marker = mark | (size < 15 ? size : 0xf);
byte_array_append(bplist, &marker, sizeof(uint8_t));
if (size >= 15) {
write_int(bplist, size);
}
if (BPLIST_UNICODE==mark) size <<= 1;
byte_array_append(bplist, val, size);
}
static void write_data(bytearray_t * bplist, uint8_t * val, uint64_t size)
{
write_raw_data(bplist, BPLIST_DATA, val, size);
}
static void write_string(bytearray_t * bplist, char *val)
{
uint64_t size = strlen(val);
write_raw_data(bplist, BPLIST_STRING, (uint8_t *) val, size);
}
static void write_unicode(bytearray_t * bplist, uint16_t * val, uint64_t size)
{
uint64_t i = 0;
uint16_t *buff = (uint16_t*)malloc(size << 1);
for (i = 0; i < size; i++)
buff[i] = be16toh(val[i]);
write_raw_data(bplist, BPLIST_UNICODE, (uint8_t*)buff, size);
free(buff);
}
static void write_array(bytearray_t * bplist, node_t* node, hashtable_t* ref_table, uint8_t ref_size)
{
node_t* cur = NULL;
uint64_t i = 0;
uint64_t size = node_n_children(node);
uint8_t marker = BPLIST_ARRAY | (size < 15 ? size : 0xf);
byte_array_append(bplist, &marker, sizeof(uint8_t));
if (size >= 15) {
write_int(bplist, size);
}
for (i = 0, cur = node_first_child(node); cur && i < size; cur = node_next_sibling(cur), i++) {
uint64_t idx = *(uint64_t *) (hash_table_lookup(ref_table, cur));
idx = be64toh(idx);
byte_array_append(bplist, (uint8_t*)&idx + (sizeof(uint64_t) - ref_size), ref_size);
}
}
static void write_dict(bytearray_t * bplist, node_t* node, hashtable_t* ref_table, uint8_t ref_size)
{
node_t* cur = NULL;
uint64_t i = 0;
uint64_t size = node_n_children(node) / 2;
uint8_t marker = BPLIST_DICT | (size < 15 ? size : 0xf);
byte_array_append(bplist, &marker, sizeof(uint8_t));
if (size >= 15) {
write_int(bplist, size);
}
for (i = 0, cur = node_first_child(node); cur && i < size; cur = node_next_sibling(node_next_sibling(cur)), i++) {
uint64_t idx1 = *(uint64_t *) (hash_table_lookup(ref_table, cur));
idx1 = be64toh(idx1);
byte_array_append(bplist, (uint8_t*)&idx1 + (sizeof(uint64_t) - ref_size), ref_size);
}
for (i = 0, cur = node_first_child(node); cur && i < size; cur = node_next_sibling(node_next_sibling(cur)), i++) {
uint64_t idx2 = *(uint64_t *) (hash_table_lookup(ref_table, cur->next));
idx2 = be64toh(idx2);
byte_array_append(bplist, (uint8_t*)&idx2 + (sizeof(uint64_t) - ref_size), ref_size);
}
}
static void write_uid(bytearray_t * bplist, uint64_t val)
{
val = (uint32_t)val;
int size = get_needed_bytes(val);
uint8_t sz;
//do not write 3bytes int node
if (size == 3)
size++;
sz = BPLIST_UID | (size-1); // yes, this is what Apple does...
val = be64toh(val);
byte_array_append(bplist, &sz, 1);
byte_array_append(bplist, (uint8_t*)&val + (8-size), size);
}
static int is_ascii_string(char* s, int len)
{
int ret = 1, i = 0;
for(i = 0; i < len; i++)
{
if ( !isascii( s[i] ) )
{
ret = 0;
break;
}
}
return ret;
}
static uint16_t *plist_utf8_to_utf16(char *unistr, long size, long *items_read, long *items_written)
{
uint16_t *outbuf = (uint16_t*)malloc(((size*2)+1)*sizeof(uint16_t));
int p = 0;
long i = 0;
unsigned char c0;
unsigned char c1;
unsigned char c2;
unsigned char c3;
uint32_t w;
while (i < size) {
c0 = unistr[i];
c1 = (i < size-1) ? unistr[i+1] : 0;
c2 = (i < size-2) ? unistr[i+2] : 0;
c3 = (i < size-3) ? unistr[i+3] : 0;
if ((c0 >= 0xF0) && (i < size-3) && (c1 >= 0x80) && (c2 >= 0x80) && (c3 >= 0x80)) {
// 4 byte sequence. Need to generate UTF-16 surrogate pair
w = ((((c0 & 7) << 18) + ((c1 & 0x3F) << 12) + ((c2 & 0x3F) << 6) + (c3 & 0x3F)) & 0x1FFFFF) - 0x010000;
outbuf[p++] = 0xD800 + (w >> 10);
outbuf[p++] = 0xDC00 + (w & 0x3FF);
i+=4;
} else if ((c0 >= 0xE0) && (i < size-2) && (c1 >= 0x80) && (c2 >= 0x80)) {
// 3 byte sequence
outbuf[p++] = ((c2 & 0x3F) + ((c1 & 3) << 6)) + (((c1 >> 2) & 15) << 8) + ((c0 & 15) << 12);
i+=3;
} else if ((c0 >= 0xC0) && (i < size-1) && (c1 >= 0x80)) {
// 2 byte sequence
outbuf[p++] = ((c1 & 0x3F) + ((c0 & 3) << 6)) + (((c0 >> 2) & 7) << 8);
i+=2;
} else if (c0 < 0x80) {
// 1 byte sequence
outbuf[p++] = c0;
i+=1;
} else {
// invalid character
PLIST_BIN_ERR("%s: invalid utf8 sequence in string at index %lu\n", __func__, i);
break;
}
}
if (items_read) {
*items_read = i;
}
if (items_written) {
*items_written = p;
}
outbuf[p] = 0;
return outbuf;
}
PLIST_API void plist_to_bin(plist_t plist, char **plist_bin, uint32_t * length)
{
ptrarray_t* objects = NULL;
hashtable_t* ref_table = NULL;
struct serialize_s ser_s;
uint8_t offset_size = 0;
uint8_t ref_size = 0;
uint64_t num_objects = 0;
uint64_t root_object = 0;
uint64_t offset_table_index = 0;
bytearray_t *bplist_buff = NULL;
uint64_t i = 0;
uint8_t *buff = NULL;
uint64_t *offsets = NULL;
bplist_trailer_t trailer;
//for string
long len = 0;
long items_read = 0;
long items_written = 0;
uint16_t *unicodestr = NULL;
uint64_t objects_len = 0;
uint64_t buff_len = 0;
//check for valid input
if (!plist || !plist_bin || *plist_bin || !length)
return;
//list of objects
objects = ptr_array_new(256);
//hashtable to write only once same nodes
ref_table = hash_table_new(plist_data_hash, plist_data_compare, free);
//serialize plist
ser_s.objects = objects;
ser_s.ref_table = ref_table;
serialize_plist(plist, &ser_s);
//now stream to output buffer
offset_size = 0; //unknown yet
objects_len = objects->len;
ref_size = get_needed_bytes(objects_len);
num_objects = objects->len;
root_object = 0; //root is first in list
offset_table_index = 0; //unknown yet
//setup a dynamic bytes array to store bplist in
bplist_buff = byte_array_new();
//set magic number and version
byte_array_append(bplist_buff, BPLIST_MAGIC, BPLIST_MAGIC_SIZE);
byte_array_append(bplist_buff, BPLIST_VERSION, BPLIST_VERSION_SIZE);
//write objects and table
offsets = (uint64_t *) malloc(num_objects * sizeof(uint64_t));
for (i = 0; i < num_objects; i++)
{
plist_data_t data = plist_get_data(ptr_array_index(objects, i));
offsets[i] = bplist_buff->len;
switch (data->type)
{
case PLIST_BOOLEAN:
buff = (uint8_t *) malloc(sizeof(uint8_t));
buff[0] = data->boolval ? BPLIST_TRUE : BPLIST_FALSE;
byte_array_append(bplist_buff, buff, sizeof(uint8_t));
free(buff);
break;
case PLIST_UINT:
if (data->length == 16) {
write_uint(bplist_buff, data->intval);
} else {
write_int(bplist_buff, data->intval);
}
break;
case PLIST_REAL:
write_real(bplist_buff, data->realval);
break;
case PLIST_KEY:
case PLIST_STRING:
len = strlen(data->strval);
if ( is_ascii_string(data->strval, len) )
{
write_string(bplist_buff, data->strval);
}
else
{
unicodestr = plist_utf8_to_utf16(data->strval, len, &items_read, &items_written);
write_unicode(bplist_buff, unicodestr, items_written);
free(unicodestr);
}
break;
case PLIST_DATA:
write_data(bplist_buff, data->buff, data->length);
case PLIST_ARRAY:
write_array(bplist_buff, ptr_array_index(objects, i), ref_table, ref_size);
break;
case PLIST_DICT:
write_dict(bplist_buff, ptr_array_index(objects, i), ref_table, ref_size);
break;
case PLIST_DATE:
write_date(bplist_buff, data->realval);
break;
case PLIST_UID:
write_uid(bplist_buff, data->intval);
break;
default:
break;
}
}
//free intermediate objects
ptr_array_free(objects);
hash_table_destroy(ref_table);
//write offsets
buff_len = bplist_buff->len;
offset_size = get_needed_bytes(buff_len);
offset_table_index = bplist_buff->len;
for (i = 0; i < num_objects; i++) {
uint64_t offset = be64toh(offsets[i]);
byte_array_append(bplist_buff, (uint8_t*)&offset + (sizeof(uint64_t) - offset_size), offset_size);
}
free(offsets);
//setup trailer
memset(trailer.unused, '\0', sizeof(trailer.unused));
trailer.offset_size = offset_size;
trailer.ref_size = ref_size;
trailer.num_objects = be64toh(num_objects);
trailer.root_object_index = be64toh(root_object);
trailer.offset_table_offset = be64toh(offset_table_index);
byte_array_append(bplist_buff, &trailer, sizeof(bplist_trailer_t));
//set output buffer and size
*plist_bin = bplist_buff->data;
*length = bplist_buff->len;
bplist_buff->data = NULL; // make sure we don't free the output buffer
byte_array_free(bplist_buff);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3191_0 |
crossvul-cpp_data_bad_4233_0 | /* Copyright (C) 2001-2020 Artifex Software, Inc.
All Rights Reserved.
This software is provided AS-IS with no warranty, either express or
implied.
This software is distributed under license and may not be copied,
modified or distributed except as expressly authorized under the terms
of the license contained in the file LICENSE in this distribution.
Refer to licensing information at http://www.artifex.com or contact
Artifex Software, Inc., 1305 Grant Avenue - Suite 200, Novato,
CA 94945, U.S.A., +1(415)492-9861, for further information.
*/
/* String operators */
#include "memory_.h"
#include "ghost.h"
#include "gsutil.h"
#include "ialloc.h"
#include "iname.h"
#include "ivmspace.h"
#include "oper.h"
#include "store.h"
/* The generic operators (copy, get, put, getinterval, putinterval, */
/* length, and forall) are implemented in zgeneric.c. */
/* <int> .bytestring <bytestring> */
static int
zbytestring(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
byte *sbody;
uint size;
check_int_leu(*op, max_int);
size = (uint)op->value.intval;
sbody = ialloc_bytes(size, ".bytestring");
if (sbody == 0)
return_error(gs_error_VMerror);
make_astruct(op, a_all | icurrent_space, sbody);
memset(sbody, 0, size);
return 0;
}
/* <int> string <string> */
int
zstring(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
byte *sbody;
uint size;
check_type(*op, t_integer);
if (op->value.intval < 0 )
return_error(gs_error_rangecheck);
if (op->value.intval > max_string_size )
return_error(gs_error_limitcheck); /* to match Distiller */
size = op->value.intval;
sbody = ialloc_string(size, "string");
if (sbody == 0)
return_error(gs_error_VMerror);
make_string(op, a_all | icurrent_space, size, sbody);
memset(sbody, 0, size);
return 0;
}
/* <name> .namestring <string> */
static int
znamestring(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
check_type(*op, t_name);
name_string_ref(imemory, op, op);
return 0;
}
/* <string> <pattern> anchorsearch <post> <match> -true- */
/* <string> <pattern> anchorsearch <string> -false- */
static int
zanchorsearch(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
os_ptr op1 = op - 1;
uint size = r_size(op);
check_read_type(*op, t_string);
check_read_type(*op1, t_string);
if (size <= r_size(op1) && !memcmp(op1->value.bytes, op->value.bytes, size)) {
os_ptr op0 = op;
push(1);
*op0 = *op1;
r_set_size(op0, size);
op1->value.bytes += size;
r_dec_size(op1, size);
make_true(op);
} else
make_false(op);
return 0;
}
/* <string> <pattern> (r)search <post> <match> <pre> -true- */
/* <string> <pattern> (r)search <string> -false- */
static int
search_impl(i_ctx_t *i_ctx_p, bool forward)
{
os_ptr op = osp;
os_ptr op1 = op - 1;
uint size = r_size(op);
uint count;
byte *pat;
byte *ptr;
byte ch;
int incr = forward ? 1 : -1;
check_read_type(*op1, t_string);
check_read_type(*op, t_string);
if (size > r_size(op1)) { /* can't match */
make_false(op);
return 0;
}
count = r_size(op1) - size;
ptr = op1->value.bytes;
if (size == 0)
goto found;
if (!forward)
ptr += count;
pat = op->value.bytes;
ch = pat[0];
do {
if (*ptr == ch && (size == 1 || !memcmp(ptr, pat, size)))
goto found;
ptr += incr;
}
while (count--);
/* No match */
make_false(op);
return 0;
found:
op->tas.type_attrs = op1->tas.type_attrs;
op->value.bytes = ptr;
r_set_size(op, size);
push(2);
op[-1] = *op1;
r_set_size(op - 1, ptr - op[-1].value.bytes);
op1->value.bytes = ptr + size;
r_set_size(op1, count + (!forward ? (size - 1) : 0));
make_true(op);
return 0;
}
/* Search from the start of the string */
static int
zsearch(i_ctx_t *i_ctx_p)
{
return search_impl(i_ctx_p, true);
}
/* Search from the end of the string */
static int
zrsearch(i_ctx_t *i_ctx_p)
{
return search_impl(i_ctx_p, false);
}
/* <string> <charstring> .stringbreak <int|null> */
static int
zstringbreak(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
uint i, j;
check_read_type(op[-1], t_string);
check_read_type(*op, t_string);
/* We can't use strpbrk here, because C doesn't allow nulls in strings. */
for (i = 0; i < r_size(op - 1); ++i)
for (j = 0; j < r_size(op); ++j)
if (op[-1].value.const_bytes[i] == op->value.const_bytes[j]) {
make_int(op - 1, i);
goto done;
}
make_null(op - 1);
done:
pop(1);
return 0;
}
/* <obj> <pattern> .stringmatch <bool> */
static int
zstringmatch(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
os_ptr op1 = op - 1;
bool result;
check_read_type(*op, t_string);
switch (r_type(op1)) {
case t_string:
check_read(*op1);
goto cmp;
case t_name:
name_string_ref(imemory, op1, op1); /* can't fail */
cmp:
result = string_match(op1->value.const_bytes, r_size(op1),
op->value.const_bytes, r_size(op),
NULL);
break;
default:
result = (r_size(op) == 1 && *op->value.bytes == '*');
}
make_bool(op1, result);
pop(1);
return 0;
}
/* ------ Initialization procedure ------ */
const op_def zstring_op_defs[] =
{
{"1.bytestring", zbytestring},
{"2anchorsearch", zanchorsearch},
{"1.namestring", znamestring},
{"2search", zsearch},
{"2rsearch", zrsearch},
{"1string", zstring},
{"2.stringbreak", zstringbreak},
{"2.stringmatch", zstringmatch},
op_def_end(0)
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4233_0 |
crossvul-cpp_data_good_5409_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% FFFFF X X %
% F X X %
% FFF X %
% F X X %
% F X X %
% %
% %
% MagickCore Image Special Effects Methods %
% %
% Software Design %
% Cristy %
% October 1996 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/accelerate-private.h"
#include "MagickCore/annotate.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/decorate.h"
#include "MagickCore/distort.h"
#include "MagickCore/draw.h"
#include "MagickCore/effect.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/fx.h"
#include "MagickCore/fx-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/gem-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/layer.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/random_.h"
#include "MagickCore/random-private.h"
#include "MagickCore/resample.h"
#include "MagickCore/resample-private.h"
#include "MagickCore/resize.h"
#include "MagickCore/resource_.h"
#include "MagickCore/splay-tree.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/transform.h"
#include "MagickCore/transform-private.h"
#include "MagickCore/utility.h"
/*
Define declarations.
*/
#define LeftShiftOperator 0xf5U
#define RightShiftOperator 0xf6U
#define LessThanEqualOperator 0xf7U
#define GreaterThanEqualOperator 0xf8U
#define EqualOperator 0xf9U
#define NotEqualOperator 0xfaU
#define LogicalAndOperator 0xfbU
#define LogicalOrOperator 0xfcU
#define ExponentialNotation 0xfdU
struct _FxInfo
{
const Image
*images;
char
*expression;
FILE
*file;
SplayTreeInfo
*colors,
*symbols;
CacheView
**view;
RandomInfo
*random_info;
ExceptionInfo
*exception;
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A c q u i r e F x I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireFxInfo() allocates the FxInfo structure.
%
% The format of the AcquireFxInfo method is:
%
% FxInfo *AcquireFxInfo(Image *image,const char *expression,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o expression: the expression.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickPrivate FxInfo *AcquireFxInfo(const Image *image,const char *expression,
ExceptionInfo *exception)
{
char
fx_op[2];
const Image
*next;
FxInfo
*fx_info;
register ssize_t
i;
fx_info=(FxInfo *) AcquireMagickMemory(sizeof(*fx_info));
if (fx_info == (FxInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(fx_info,0,sizeof(*fx_info));
fx_info->exception=AcquireExceptionInfo();
fx_info->images=image;
fx_info->colors=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory,
RelinquishAlignedMemory);
fx_info->symbols=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory,
RelinquishMagickMemory);
fx_info->view=(CacheView **) AcquireQuantumMemory(GetImageListLength(
fx_info->images),sizeof(*fx_info->view));
if (fx_info->view == (CacheView **) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
i=0;
next=GetFirstImageInList(fx_info->images);
for ( ; next != (Image *) NULL; next=next->next)
{
fx_info->view[i]=AcquireVirtualCacheView(next,exception);
i++;
}
fx_info->random_info=AcquireRandomInfo();
fx_info->expression=ConstantString(expression);
fx_info->file=stderr;
(void) SubstituteString(&fx_info->expression," ",""); /* compact string */
/*
Force right-to-left associativity for unary negation.
*/
(void) SubstituteString(&fx_info->expression,"-","-1.0*");
(void) SubstituteString(&fx_info->expression,"^-1.0*","^-");
(void) SubstituteString(&fx_info->expression,"E-1.0*","E-");
(void) SubstituteString(&fx_info->expression,"e-1.0*","e-");
/*
Convert compound to simple operators.
*/
fx_op[1]='\0';
*fx_op=(char) LeftShiftOperator;
(void) SubstituteString(&fx_info->expression,"<<",fx_op);
*fx_op=(char) RightShiftOperator;
(void) SubstituteString(&fx_info->expression,">>",fx_op);
*fx_op=(char) LessThanEqualOperator;
(void) SubstituteString(&fx_info->expression,"<=",fx_op);
*fx_op=(char) GreaterThanEqualOperator;
(void) SubstituteString(&fx_info->expression,">=",fx_op);
*fx_op=(char) EqualOperator;
(void) SubstituteString(&fx_info->expression,"==",fx_op);
*fx_op=(char) NotEqualOperator;
(void) SubstituteString(&fx_info->expression,"!=",fx_op);
*fx_op=(char) LogicalAndOperator;
(void) SubstituteString(&fx_info->expression,"&&",fx_op);
*fx_op=(char) LogicalOrOperator;
(void) SubstituteString(&fx_info->expression,"||",fx_op);
*fx_op=(char) ExponentialNotation;
(void) SubstituteString(&fx_info->expression,"**",fx_op);
return(fx_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A d d N o i s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AddNoiseImage() adds random noise to the image.
%
% The format of the AddNoiseImage method is:
%
% Image *AddNoiseImage(const Image *image,const NoiseType noise_type,
% const double attenuate,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o noise_type: The type of noise: Uniform, Gaussian, Multiplicative,
% Impulse, Laplacian, or Poisson.
%
% o attenuate: attenuate the random distribution.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AddNoiseImage(const Image *image,const NoiseType noise_type,
const double attenuate,ExceptionInfo *exception)
{
#define AddNoiseImageTag "AddNoise/Image"
CacheView
*image_view,
*noise_view;
Image
*noise_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RandomInfo
**magick_restrict random_info;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
/*
Initialize noise image attributes.
*/
assert(image != (const 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);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
noise_image=AccelerateAddNoiseImage(image,noise_type,exception);
if (noise_image != (Image *) NULL)
return(noise_image);
#endif
noise_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if (noise_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(noise_image,DirectClass,exception) == MagickFalse)
{
noise_image=DestroyImage(noise_image);
return((Image *) NULL);
}
/*
Add noise in each row.
*/
status=MagickTrue;
progress=0;
random_info=AcquireRandomInfoThreadSet();
image_view=AcquireVirtualCacheView(image,exception);
noise_view=AcquireAuthenticCacheView(noise_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,noise_image,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait noise_traits=GetPixelChannelTraits(noise_image,channel);
if ((traits == UndefinedPixelTrait) ||
(noise_traits == UndefinedPixelTrait))
continue;
if (((noise_traits & CopyPixelTrait) != 0) ||
(GetPixelReadMask(image,p) == 0))
{
SetPixelChannel(noise_image,channel,p[i],q);
continue;
}
SetPixelChannel(noise_image,channel,ClampToQuantum(
GenerateDifferentialNoise(random_info[id],p[i],noise_type,attenuate)),
q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(noise_image);
}
sync=SyncCacheViewAuthenticPixels(noise_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_AddNoiseImage)
#endif
proceed=SetImageProgress(image,AddNoiseImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
noise_view=DestroyCacheView(noise_view);
image_view=DestroyCacheView(image_view);
random_info=DestroyRandomInfoThreadSet(random_info);
if (status == MagickFalse)
noise_image=DestroyImage(noise_image);
return(noise_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B l u e S h i f t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BlueShiftImage() mutes the colors of the image to simulate a scene at
% nighttime in the moonlight.
%
% The format of the BlueShiftImage method is:
%
% Image *BlueShiftImage(const Image *image,const double factor,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o factor: the shift factor.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *BlueShiftImage(const Image *image,const double factor,
ExceptionInfo *exception)
{
#define BlueShiftImageTag "BlueShift/Image"
CacheView
*image_view,
*shift_view;
Image
*shift_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Allocate blue shift image.
*/
assert(image != (const 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);
shift_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if (shift_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(shift_image,DirectClass,exception) == MagickFalse)
{
shift_image=DestroyImage(shift_image);
return((Image *) NULL);
}
/*
Blue-shift DirectClass image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
shift_view=AcquireAuthenticCacheView(shift_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,shift_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
PixelInfo
pixel;
Quantum
quantum;
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(shift_view,0,y,shift_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
quantum=GetPixelRed(image,p);
if (GetPixelGreen(image,p) < quantum)
quantum=GetPixelGreen(image,p);
if (GetPixelBlue(image,p) < quantum)
quantum=GetPixelBlue(image,p);
pixel.red=0.5*(GetPixelRed(image,p)+factor*quantum);
pixel.green=0.5*(GetPixelGreen(image,p)+factor*quantum);
pixel.blue=0.5*(GetPixelBlue(image,p)+factor*quantum);
quantum=GetPixelRed(image,p);
if (GetPixelGreen(image,p) > quantum)
quantum=GetPixelGreen(image,p);
if (GetPixelBlue(image,p) > quantum)
quantum=GetPixelBlue(image,p);
pixel.red=0.5*(pixel.red+factor*quantum);
pixel.green=0.5*(pixel.green+factor*quantum);
pixel.blue=0.5*(pixel.blue+factor*quantum);
SetPixelRed(shift_image,ClampToQuantum(pixel.red),q);
SetPixelGreen(shift_image,ClampToQuantum(pixel.green),q);
SetPixelBlue(shift_image,ClampToQuantum(pixel.blue),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(shift_image);
}
sync=SyncCacheViewAuthenticPixels(shift_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_BlueShiftImage)
#endif
proceed=SetImageProgress(image,BlueShiftImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
shift_view=DestroyCacheView(shift_view);
if (status == MagickFalse)
shift_image=DestroyImage(shift_image);
return(shift_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C h a r c o a l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CharcoalImage() creates a new image that is a copy of an existing one with
% the edge highlighted. It allocates the memory necessary for the new Image
% structure and returns a pointer to the new image.
%
% The format of the CharcoalImage method is:
%
% Image *CharcoalImage(const Image *image,const double radius,
% const double sigma,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the pixel neighborhood.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *CharcoalImage(const Image *image,const double radius,
const double sigma,ExceptionInfo *exception)
{
Image
*charcoal_image,
*clone_image,
*edge_image;
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);
clone_image=CloneImage(image,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
return((Image *) NULL);
edge_image=EdgeImage(clone_image,radius,exception);
clone_image=DestroyImage(clone_image);
if (edge_image == (Image *) NULL)
return((Image *) NULL);
charcoal_image=BlurImage(edge_image,radius,sigma,exception);
edge_image=DestroyImage(edge_image);
if (charcoal_image == (Image *) NULL)
return((Image *) NULL);
(void) NormalizeImage(charcoal_image,exception);
(void) NegateImage(charcoal_image,MagickFalse,exception);
(void) GrayscaleImage(charcoal_image,image->intensity,exception);
return(charcoal_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o l o r i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ColorizeImage() blends the fill color with each pixel in the image.
% A percentage blend is specified with opacity. Control the application
% of different color components by specifying a different percentage for
% each component (e.g. 90/100/10 is 90% red, 100% green, and 10% blue).
%
% The format of the ColorizeImage method is:
%
% Image *ColorizeImage(const Image *image,const char *blend,
% const PixelInfo *colorize,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o blend: A character string indicating the level of blending as a
% percentage.
%
% o colorize: A color value.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ColorizeImage(const Image *image,const char *blend,
const PixelInfo *colorize,ExceptionInfo *exception)
{
#define ColorizeImageTag "Colorize/Image"
#define Colorize(pixel,blend_percentage,colorize) \
(((pixel)*(100.0-(blend_percentage))+(colorize)*(blend_percentage))/100.0)
CacheView
*image_view;
GeometryInfo
geometry_info;
Image
*colorize_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickStatusType
flags;
PixelInfo
blend_percentage;
ssize_t
y;
/*
Allocate colorized image.
*/
assert(image != (const 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);
colorize_image=CloneImage(image,0,0,MagickTrue,exception);
if (colorize_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(colorize_image,DirectClass,exception) == MagickFalse)
{
colorize_image=DestroyImage(colorize_image);
return((Image *) NULL);
}
if ((IsGrayColorspace(colorize_image->colorspace) != MagickFalse) ||
(IsPixelInfoGray(colorize) != MagickFalse))
(void) SetImageColorspace(colorize_image,sRGBColorspace,exception);
if ((colorize_image->alpha_trait == UndefinedPixelTrait) &&
(colorize->alpha_trait != UndefinedPixelTrait))
(void) SetImageAlpha(colorize_image,OpaqueAlpha,exception);
if (blend == (const char *) NULL)
return(colorize_image);
GetPixelInfo(colorize_image,&blend_percentage);
flags=ParseGeometry(blend,&geometry_info);
blend_percentage.red=geometry_info.rho;
blend_percentage.green=geometry_info.rho;
blend_percentage.blue=geometry_info.rho;
blend_percentage.black=geometry_info.rho;
blend_percentage.alpha=(MagickRealType) TransparentAlpha;
if ((flags & SigmaValue) != 0)
blend_percentage.green=geometry_info.sigma;
if ((flags & XiValue) != 0)
blend_percentage.blue=geometry_info.xi;
if ((flags & PsiValue) != 0)
blend_percentage.alpha=geometry_info.psi;
if (blend_percentage.colorspace == CMYKColorspace)
{
if ((flags & PsiValue) != 0)
blend_percentage.black=geometry_info.psi;
if ((flags & ChiValue) != 0)
blend_percentage.alpha=geometry_info.chi;
}
/*
Colorize DirectClass image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(colorize_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(colorize_image,colorize_image,colorize_image->rows,1)
#endif
for (y=0; y < (ssize_t) colorize_image->rows; y++)
{
MagickBooleanType
sync;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,colorize_image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) colorize_image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(colorize_image); i++)
{
PixelTrait traits=GetPixelChannelTraits(colorize_image,
(PixelChannel) i);
if (traits == UndefinedPixelTrait)
continue;
if (((traits & CopyPixelTrait) != 0) ||
(GetPixelReadMask(colorize_image,q) == 0))
continue;
SetPixelChannel(colorize_image,(PixelChannel) i,ClampToQuantum(
Colorize(q[i],GetPixelInfoChannel(&blend_percentage,(PixelChannel) i),
GetPixelInfoChannel(colorize,(PixelChannel) i))),q);
}
q+=GetPixelChannels(colorize_image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ColorizeImage)
#endif
proceed=SetImageProgress(image,ColorizeImageTag,progress++,
colorize_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
colorize_image=DestroyImage(colorize_image);
return(colorize_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o l o r M a t r i x I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ColorMatrixImage() applies color transformation to an image. This method
% permits saturation changes, hue rotation, luminance to alpha, and various
% other effects. Although variable-sized transformation matrices can be used,
% typically one uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA
% (or RGBA with offsets). The matrix is similar to those used by Adobe Flash
% except offsets are in column 6 rather than 5 (in support of CMYKA images)
% and offsets are normalized (divide Flash offset by 255).
%
% The format of the ColorMatrixImage method is:
%
% Image *ColorMatrixImage(const Image *image,
% const KernelInfo *color_matrix,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o color_matrix: the color matrix.
%
% o exception: return any errors or warnings in this structure.
%
*/
/* FUTURE: modify to make use of a MagickMatrix Mutliply function
That should be provided in "matrix.c"
(ASIDE: actually distorts should do this too but currently doesn't)
*/
MagickExport Image *ColorMatrixImage(const Image *image,
const KernelInfo *color_matrix,ExceptionInfo *exception)
{
#define ColorMatrixImageTag "ColorMatrix/Image"
CacheView
*color_view,
*image_view;
double
ColorMatrix[6][6] =
{
{ 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 },
{ 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 },
{ 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 },
{ 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 },
{ 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 },
{ 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }
};
Image
*color_image;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
u,
v,
y;
/*
Map given color_matrix, into a 6x6 matrix RGBKA and a constant
*/
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);
i=0;
for (v=0; v < (ssize_t) color_matrix->height; v++)
for (u=0; u < (ssize_t) color_matrix->width; u++)
{
if ((v < 6) && (u < 6))
ColorMatrix[v][u]=color_matrix->values[i];
i++;
}
/*
Initialize color image.
*/
color_image=CloneImage(image,0,0,MagickTrue,exception);
if (color_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(color_image,DirectClass,exception) == MagickFalse)
{
color_image=DestroyImage(color_image);
return((Image *) NULL);
}
if (image->debug != MagickFalse)
{
char
format[MagickPathExtent],
*message;
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" ColorMatrix image with color matrix:");
message=AcquireString("");
for (v=0; v < 6; v++)
{
*message='\0';
(void) FormatLocaleString(format,MagickPathExtent,"%.20g: ",(double) v);
(void) ConcatenateString(&message,format);
for (u=0; u < 6; u++)
{
(void) FormatLocaleString(format,MagickPathExtent,"%+f ",
ColorMatrix[v][u]);
(void) ConcatenateString(&message,format);
}
(void) LogMagickEvent(TransformEvent,GetMagickModule(),"%s",message);
}
message=DestroyString(message);
}
/*
Apply the ColorMatrix to image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
color_view=AcquireAuthenticCacheView(color_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,color_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelInfo
pixel;
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(color_view,0,y,color_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
GetPixelInfo(image,&pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
v;
size_t
height;
GetPixelInfoPixel(image,p,&pixel);
height=color_matrix->height > 6 ? 6UL : color_matrix->height;
for (v=0; v < (ssize_t) height; v++)
{
double
sum;
sum=ColorMatrix[v][0]*GetPixelRed(image,p)+ColorMatrix[v][1]*
GetPixelGreen(image,p)+ColorMatrix[v][2]*GetPixelBlue(image,p);
if (image->colorspace == CMYKColorspace)
sum+=ColorMatrix[v][3]*GetPixelBlack(image,p);
if (image->alpha_trait != UndefinedPixelTrait)
sum+=ColorMatrix[v][4]*GetPixelAlpha(image,p);
sum+=QuantumRange*ColorMatrix[v][5];
switch (v)
{
case 0: pixel.red=sum; break;
case 1: pixel.green=sum; break;
case 2: pixel.blue=sum; break;
case 3: pixel.black=sum; break;
case 4: pixel.alpha=sum; break;
default: break;
}
}
SetPixelViaPixelInfo(color_image,&pixel,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(color_image);
}
if (SyncCacheViewAuthenticPixels(color_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ColorMatrixImage)
#endif
proceed=SetImageProgress(image,ColorMatrixImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
color_view=DestroyCacheView(color_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
color_image=DestroyImage(color_image);
return(color_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y F x I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyFxInfo() deallocates memory associated with an FxInfo structure.
%
% The format of the DestroyFxInfo method is:
%
% ImageInfo *DestroyFxInfo(ImageInfo *fx_info)
%
% A description of each parameter follows:
%
% o fx_info: the fx info.
%
*/
MagickPrivate FxInfo *DestroyFxInfo(FxInfo *fx_info)
{
register ssize_t
i;
fx_info->exception=DestroyExceptionInfo(fx_info->exception);
fx_info->expression=DestroyString(fx_info->expression);
fx_info->symbols=DestroySplayTree(fx_info->symbols);
fx_info->colors=DestroySplayTree(fx_info->colors);
for (i=(ssize_t) GetImageListLength(fx_info->images)-1; i >= 0; i--)
fx_info->view[i]=DestroyCacheView(fx_info->view[i]);
fx_info->view=(CacheView **) RelinquishMagickMemory(fx_info->view);
fx_info->random_info=DestroyRandomInfo(fx_info->random_info);
fx_info=(FxInfo *) RelinquishMagickMemory(fx_info);
return(fx_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ F x E v a l u a t e C h a n n e l E x p r e s s i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FxEvaluateChannelExpression() evaluates an expression and returns the
% results.
%
% The format of the FxEvaluateExpression method is:
%
% double FxEvaluateChannelExpression(FxInfo *fx_info,
% const PixelChannel channel,const ssize_t x,const ssize_t y,
% double *alpha,Exceptioninfo *exception)
% double FxEvaluateExpression(FxInfo *fx_info,
% double *alpha,Exceptioninfo *exception)
%
% A description of each parameter follows:
%
% o fx_info: the fx info.
%
% o channel: the channel.
%
% o x,y: the pixel position.
%
% o alpha: the result.
%
% o exception: return any errors or warnings in this structure.
%
*/
static double FxChannelStatistics(FxInfo *fx_info,Image *image,
PixelChannel channel,const char *symbol,ExceptionInfo *exception)
{
ChannelType
channel_mask;
char
key[MagickPathExtent],
statistic[MagickPathExtent];
const char
*value;
register const char
*p;
channel_mask=UndefinedChannel;
for (p=symbol; (*p != '.') && (*p != '\0'); p++) ;
if (*p == '.')
{
ssize_t
option;
option=ParseCommandOption(MagickPixelChannelOptions,MagickTrue,p+1);
if (option >= 0)
{
channel=(PixelChannel) option;
channel_mask=(ChannelType) (channel_mask | (1 << channel));
(void) SetPixelChannelMask(image,channel_mask);
}
}
(void) FormatLocaleString(key,MagickPathExtent,"%p.%.20g.%s",(void *) image,
(double) channel,symbol);
value=(const char *) GetValueFromSplayTree(fx_info->symbols,key);
if (value != (const char *) NULL)
{
if (channel_mask != UndefinedChannel)
(void) SetPixelChannelMask(image,channel_mask);
return(QuantumScale*StringToDouble(value,(char **) NULL));
}
(void) DeleteNodeFromSplayTree(fx_info->symbols,key);
if (LocaleNCompare(symbol,"depth",5) == 0)
{
size_t
depth;
depth=GetImageDepth(image,exception);
(void) FormatLocaleString(statistic,MagickPathExtent,"%.20g",(double)
depth);
}
if (LocaleNCompare(symbol,"kurtosis",8) == 0)
{
double
kurtosis,
skewness;
(void) GetImageKurtosis(image,&kurtosis,&skewness,exception);
(void) FormatLocaleString(statistic,MagickPathExtent,"%g",kurtosis);
}
if (LocaleNCompare(symbol,"maxima",6) == 0)
{
double
maxima,
minima;
(void) GetImageRange(image,&minima,&maxima,exception);
(void) FormatLocaleString(statistic,MagickPathExtent,"%g",maxima);
}
if (LocaleNCompare(symbol,"mean",4) == 0)
{
double
mean,
standard_deviation;
(void) GetImageMean(image,&mean,&standard_deviation,exception);
(void) FormatLocaleString(statistic,MagickPathExtent,"%g",mean);
}
if (LocaleNCompare(symbol,"minima",6) == 0)
{
double
maxima,
minima;
(void) GetImageRange(image,&minima,&maxima,exception);
(void) FormatLocaleString(statistic,MagickPathExtent,"%g",minima);
}
if (LocaleNCompare(symbol,"skewness",8) == 0)
{
double
kurtosis,
skewness;
(void) GetImageKurtosis(image,&kurtosis,&skewness,exception);
(void) FormatLocaleString(statistic,MagickPathExtent,"%g",skewness);
}
if (LocaleNCompare(symbol,"standard_deviation",18) == 0)
{
double
mean,
standard_deviation;
(void) GetImageMean(image,&mean,&standard_deviation,exception);
(void) FormatLocaleString(statistic,MagickPathExtent,"%g",
standard_deviation);
}
if (channel_mask != UndefinedChannel)
(void) SetPixelChannelMask(image,channel_mask);
(void) AddValueToSplayTree(fx_info->symbols,ConstantString(key),
ConstantString(statistic));
return(QuantumScale*StringToDouble(statistic,(char **) NULL));
}
static double
FxEvaluateSubexpression(FxInfo *,const PixelChannel,const ssize_t,
const ssize_t,const char *,size_t *,double *,ExceptionInfo *);
static MagickOffsetType FxGCD(MagickOffsetType alpha,MagickOffsetType beta)
{
if (beta != 0)
return(FxGCD(beta,alpha % beta));
return(alpha);
}
static inline const char *FxSubexpression(const char *expression,
ExceptionInfo *exception)
{
const char
*subexpression;
register ssize_t
level;
level=0;
subexpression=expression;
while ((*subexpression != '\0') &&
((level != 1) || (strchr(")",(int) *subexpression) == (char *) NULL)))
{
if (strchr("(",(int) *subexpression) != (char *) NULL)
level++;
else
if (strchr(")",(int) *subexpression) != (char *) NULL)
level--;
subexpression++;
}
if (*subexpression == '\0')
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnbalancedParenthesis","`%s'",expression);
return(subexpression);
}
static double FxGetSymbol(FxInfo *fx_info,const PixelChannel channel,
const ssize_t x,const ssize_t y,const char *expression,
ExceptionInfo *exception)
{
char
*q,
subexpression[MagickPathExtent],
symbol[MagickPathExtent];
const char
*p,
*value;
Image
*image;
PixelInfo
pixel;
double
alpha,
beta;
PointInfo
point;
register ssize_t
i;
size_t
depth,
length,
level;
p=expression;
i=GetImageIndexInList(fx_info->images);
depth=0;
level=0;
point.x=(double) x;
point.y=(double) y;
if (isalpha((int) ((unsigned char) *(p+1))) == 0)
{
if (strchr("suv",(int) *p) != (char *) NULL)
{
switch (*p)
{
case 's':
default:
{
i=GetImageIndexInList(fx_info->images);
break;
}
case 'u': i=0; break;
case 'v': i=1; break;
}
p++;
if (*p == '[')
{
level++;
q=subexpression;
for (p++; *p != '\0'; )
{
if (*p == '[')
level++;
else
if (*p == ']')
{
level--;
if (level == 0)
break;
}
*q++=(*p++);
}
*q='\0';
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,
&depth,&beta,exception);
i=(ssize_t) (alpha+0.5);
p++;
}
if (*p == '.')
p++;
}
if ((*p == 'p') && (isalpha((int) ((unsigned char) *(p+1))) == 0))
{
p++;
if (*p == '{')
{
level++;
q=subexpression;
for (p++; *p != '\0'; )
{
if (*p == '{')
level++;
else
if (*p == '}')
{
level--;
if (level == 0)
break;
}
*q++=(*p++);
}
*q='\0';
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,
&depth,&beta,exception);
point.x=alpha;
point.y=beta;
p++;
}
else
if (*p == '[')
{
level++;
q=subexpression;
for (p++; *p != '\0'; )
{
if (*p == '[')
level++;
else
if (*p == ']')
{
level--;
if (level == 0)
break;
}
*q++=(*p++);
}
*q='\0';
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,
&depth,&beta,exception);
point.x+=alpha;
point.y+=beta;
p++;
}
if (*p == '.')
p++;
}
}
length=GetImageListLength(fx_info->images);
while (i < 0)
i+=(ssize_t) length;
if (length != 0)
i%=length;
image=GetImageFromList(fx_info->images,i);
if (image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"NoSuchImage","`%s'",expression);
return(0.0);
}
GetPixelInfo(image,&pixel);
(void) InterpolatePixelInfo(image,fx_info->view[i],image->interpolate,
point.x,point.y,&pixel,exception);
if ((strlen(p) > 2) && (LocaleCompare(p,"intensity") != 0) &&
(LocaleCompare(p,"luma") != 0) && (LocaleCompare(p,"luminance") != 0) &&
(LocaleCompare(p,"hue") != 0) && (LocaleCompare(p,"saturation") != 0) &&
(LocaleCompare(p,"lightness") != 0))
{
char
name[MagickPathExtent];
(void) CopyMagickString(name,p,MagickPathExtent);
for (q=name+(strlen(name)-1); q > name; q--)
{
if (*q == ')')
break;
if (*q == '.')
{
*q='\0';
break;
}
}
if ((strlen(name) > 2) &&
(GetValueFromSplayTree(fx_info->symbols,name) == (const char *) NULL))
{
PixelInfo
*color;
color=(PixelInfo *) GetValueFromSplayTree(fx_info->colors,name);
if (color != (PixelInfo *) NULL)
{
pixel=(*color);
p+=strlen(name);
}
else
{
MagickBooleanType
status;
status=QueryColorCompliance(name,AllCompliance,&pixel,
fx_info->exception);
if (status != MagickFalse)
{
(void) AddValueToSplayTree(fx_info->colors,ConstantString(
name),ClonePixelInfo(&pixel));
p+=strlen(name);
}
}
}
}
(void) CopyMagickString(symbol,p,MagickPathExtent);
StripString(symbol);
if (*symbol == '\0')
{
switch (channel)
{
case RedPixelChannel: return(QuantumScale*pixel.red);
case GreenPixelChannel: return(QuantumScale*pixel.green);
case BluePixelChannel: return(QuantumScale*pixel.blue);
case BlackPixelChannel:
{
if (image->colorspace != CMYKColorspace)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ImageError,"ColorSeparatedImageRequired","`%s'",
image->filename);
return(0.0);
}
return(QuantumScale*pixel.black);
}
case AlphaPixelChannel:
{
if (pixel.alpha_trait == UndefinedPixelTrait)
return(1.0);
alpha=(double) (QuantumScale*pixel.alpha);
return(alpha);
}
case IndexPixelChannel:
return(0.0);
case IntensityPixelChannel:
{
Quantum
quantum_pixel[MaxPixelChannels];
SetPixelViaPixelInfo(image,&pixel,quantum_pixel);
return(QuantumScale*GetPixelIntensity(image,quantum_pixel));
}
default:
break;
}
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnableToParseExpression","`%s'",p);
return(0.0);
}
switch (*symbol)
{
case 'A':
case 'a':
{
if (LocaleCompare(symbol,"a") == 0)
return((QuantumScale*pixel.alpha));
break;
}
case 'B':
case 'b':
{
if (LocaleCompare(symbol,"b") == 0)
return(QuantumScale*pixel.blue);
break;
}
case 'C':
case 'c':
{
if (LocaleNCompare(symbol,"channel",7) == 0)
{
GeometryInfo
channel_info;
MagickStatusType
flags;
flags=ParseGeometry(symbol+7,&channel_info);
if (image->colorspace == CMYKColorspace)
switch (channel)
{
case CyanPixelChannel:
{
if ((flags & RhoValue) == 0)
return(0.0);
return(channel_info.rho);
}
case MagentaPixelChannel:
{
if ((flags & SigmaValue) == 0)
return(0.0);
return(channel_info.sigma);
}
case YellowPixelChannel:
{
if ((flags & XiValue) == 0)
return(0.0);
return(channel_info.xi);
}
case BlackPixelChannel:
{
if ((flags & PsiValue) == 0)
return(0.0);
return(channel_info.psi);
}
case AlphaPixelChannel:
{
if ((flags & ChiValue) == 0)
return(0.0);
return(channel_info.chi);
}
default:
return(0.0);
}
switch (channel)
{
case RedPixelChannel:
{
if ((flags & RhoValue) == 0)
return(0.0);
return(channel_info.rho);
}
case GreenPixelChannel:
{
if ((flags & SigmaValue) == 0)
return(0.0);
return(channel_info.sigma);
}
case BluePixelChannel:
{
if ((flags & XiValue) == 0)
return(0.0);
return(channel_info.xi);
}
case BlackPixelChannel:
{
if ((flags & ChiValue) == 0)
return(0.0);
return(channel_info.chi);
}
case AlphaPixelChannel:
{
if ((flags & PsiValue) == 0)
return(0.0);
return(channel_info.psi);
}
default:
return(0.0);
}
}
if (LocaleCompare(symbol,"c") == 0)
return(QuantumScale*pixel.red);
break;
}
case 'D':
case 'd':
{
if (LocaleNCompare(symbol,"depth",5) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(symbol,"g") == 0)
return(QuantumScale*pixel.green);
break;
}
case 'K':
case 'k':
{
if (LocaleNCompare(symbol,"kurtosis",8) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleCompare(symbol,"k") == 0)
{
if (image->colorspace != CMYKColorspace)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"ColorSeparatedImageRequired","`%s'",
image->filename);
return(0.0);
}
return(QuantumScale*pixel.black);
}
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(symbol,"h") == 0)
return(image->rows);
if (LocaleCompare(symbol,"hue") == 0)
{
double
hue,
lightness,
saturation;
ConvertRGBToHSL(pixel.red,pixel.green,pixel.blue,&hue,&saturation,
&lightness);
return(hue);
}
break;
}
case 'I':
case 'i':
{
if ((LocaleCompare(symbol,"image.depth") == 0) ||
(LocaleCompare(symbol,"image.minima") == 0) ||
(LocaleCompare(symbol,"image.maxima") == 0) ||
(LocaleCompare(symbol,"image.mean") == 0) ||
(LocaleCompare(symbol,"image.kurtosis") == 0) ||
(LocaleCompare(symbol,"image.skewness") == 0) ||
(LocaleCompare(symbol,"image.standard_deviation") == 0))
return(FxChannelStatistics(fx_info,image,channel,symbol+6,exception));
if (LocaleCompare(symbol,"image.resolution.x") == 0)
return(image->resolution.x);
if (LocaleCompare(symbol,"image.resolution.y") == 0)
return(image->resolution.y);
if (LocaleCompare(symbol,"intensity") == 0)
{
Quantum
quantum_pixel[MaxPixelChannels];
SetPixelViaPixelInfo(image,&pixel,quantum_pixel);
return(QuantumScale*GetPixelIntensity(image,quantum_pixel));
}
if (LocaleCompare(symbol,"i") == 0)
return(x);
break;
}
case 'J':
case 'j':
{
if (LocaleCompare(symbol,"j") == 0)
return(y);
break;
}
case 'L':
case 'l':
{
if (LocaleCompare(symbol,"lightness") == 0)
{
double
hue,
lightness,
saturation;
ConvertRGBToHSL(pixel.red,pixel.green,pixel.blue,&hue,&saturation,
&lightness);
return(lightness);
}
if (LocaleCompare(symbol,"luma") == 0)
{
double
luma;
luma=0.212656*pixel.red+0.715158*pixel.green+0.072186*pixel.blue;
return(QuantumScale*luma);
}
if (LocaleCompare(symbol,"luminance") == 0)
{
double
luminence;
luminence=0.212656*pixel.red+0.715158*pixel.green+0.072186*pixel.blue;
return(QuantumScale*luminence);
}
break;
}
case 'M':
case 'm':
{
if (LocaleNCompare(symbol,"maxima",6) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleNCompare(symbol,"mean",4) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleNCompare(symbol,"minima",6) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleCompare(symbol,"m") == 0)
return(QuantumScale*pixel.green);
break;
}
case 'N':
case 'n':
{
if (LocaleCompare(symbol,"n") == 0)
return(GetImageListLength(fx_info->images));
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(symbol,"o") == 0)
return(QuantumScale*pixel.alpha);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(symbol,"page.height") == 0)
return(image->page.height);
if (LocaleCompare(symbol,"page.width") == 0)
return(image->page.width);
if (LocaleCompare(symbol,"page.x") == 0)
return(image->page.x);
if (LocaleCompare(symbol,"page.y") == 0)
return(image->page.y);
break;
}
case 'Q':
case 'q':
{
if (LocaleCompare(symbol,"quality") == 0)
return(image->quality);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(symbol,"resolution.x") == 0)
return(image->resolution.x);
if (LocaleCompare(symbol,"resolution.y") == 0)
return(image->resolution.y);
if (LocaleCompare(symbol,"r") == 0)
return(QuantumScale*pixel.red);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(symbol,"saturation") == 0)
{
double
hue,
lightness,
saturation;
ConvertRGBToHSL(pixel.red,pixel.green,pixel.blue,&hue,&saturation,
&lightness);
return(saturation);
}
if (LocaleNCompare(symbol,"skewness",8) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleNCompare(symbol,"standard_deviation",18) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
break;
}
case 'T':
case 't':
{
if (LocaleCompare(symbol,"t") == 0)
return(GetImageIndexInList(fx_info->images));
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(symbol,"w") == 0)
return(image->columns);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(symbol,"y") == 0)
return(QuantumScale*pixel.blue);
break;
}
case 'Z':
case 'z':
{
if (LocaleCompare(symbol,"z") == 0)
return((double)GetImageDepth(image, fx_info->exception));
break;
}
default:
break;
}
value=(const char *) GetValueFromSplayTree(fx_info->symbols,symbol);
if (value != (const char *) NULL)
return(StringToDouble(value,(char **) NULL));
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnableToParseExpression","`%s'",symbol);
return(0.0);
}
static const char *FxOperatorPrecedence(const char *expression,
ExceptionInfo *exception)
{
typedef enum
{
UndefinedPrecedence,
NullPrecedence,
BitwiseComplementPrecedence,
ExponentPrecedence,
ExponentialNotationPrecedence,
MultiplyPrecedence,
AdditionPrecedence,
ShiftPrecedence,
RelationalPrecedence,
EquivalencyPrecedence,
BitwiseAndPrecedence,
BitwiseOrPrecedence,
LogicalAndPrecedence,
LogicalOrPrecedence,
TernaryPrecedence,
AssignmentPrecedence,
CommaPrecedence,
SeparatorPrecedence
} FxPrecedence;
FxPrecedence
precedence,
target;
register const char
*subexpression;
register int
c;
size_t
level;
c=0;
level=0;
subexpression=(const char *) NULL;
target=NullPrecedence;
while (*expression != '\0')
{
precedence=UndefinedPrecedence;
if ((isspace((int) ((unsigned char) *expression)) != 0) || (c == (int) '@'))
{
expression++;
continue;
}
switch (*expression)
{
case 'A':
case 'a':
{
#if defined(MAGICKCORE_HAVE_ACOSH)
if (LocaleNCompare(expression,"acosh",5) == 0)
{
expression+=5;
break;
}
#endif
#if defined(MAGICKCORE_HAVE_ASINH)
if (LocaleNCompare(expression,"asinh",5) == 0)
{
expression+=5;
break;
}
#endif
#if defined(MAGICKCORE_HAVE_ATANH)
if (LocaleNCompare(expression,"atanh",5) == 0)
{
expression+=5;
break;
}
#endif
if (LocaleNCompare(expression,"atan2",5) == 0)
{
expression+=5;
break;
}
break;
}
case 'E':
case 'e':
{
if ((isdigit((int) ((unsigned char) c)) != 0) &&
((LocaleNCompare(expression,"E+",2) == 0) ||
(LocaleNCompare(expression,"E-",2) == 0)))
{
expression+=2; /* scientific notation */
break;
}
}
case 'J':
case 'j':
{
if ((LocaleNCompare(expression,"j0",2) == 0) ||
(LocaleNCompare(expression,"j1",2) == 0))
{
expression+=2;
break;
}
break;
}
case '#':
{
while (isxdigit((int) ((unsigned char) *(expression+1))) != 0)
expression++;
break;
}
default:
break;
}
if ((c == (int) '{') || (c == (int) '['))
level++;
else
if ((c == (int) '}') || (c == (int) ']'))
level--;
if (level == 0)
switch ((unsigned char) *expression)
{
case '~':
case '!':
{
precedence=BitwiseComplementPrecedence;
break;
}
case '^':
case '@':
{
precedence=ExponentPrecedence;
break;
}
default:
{
if (((c != 0) && ((isdigit((int) ((unsigned char) c)) != 0) ||
(strchr(")",(int) ((unsigned char) c)) != (char *) NULL))) &&
(((islower((int) ((unsigned char) *expression)) != 0) ||
(strchr("(",(int) ((unsigned char) *expression)) != (char *) NULL)) ||
((isdigit((int) ((unsigned char) c)) == 0) &&
(isdigit((int) ((unsigned char) *expression)) != 0))) &&
(strchr("xy",(int) ((unsigned char) *expression)) == (char *) NULL))
precedence=MultiplyPrecedence;
break;
}
case '*':
case '/':
case '%':
{
precedence=MultiplyPrecedence;
break;
}
case '+':
case '-':
{
if ((strchr("(+-/*%:&^|<>~,",c) == (char *) NULL) ||
(isalpha(c) != 0))
precedence=AdditionPrecedence;
break;
}
case LeftShiftOperator:
case RightShiftOperator:
{
precedence=ShiftPrecedence;
break;
}
case '<':
case LessThanEqualOperator:
case GreaterThanEqualOperator:
case '>':
{
precedence=RelationalPrecedence;
break;
}
case EqualOperator:
case NotEqualOperator:
{
precedence=EquivalencyPrecedence;
break;
}
case '&':
{
precedence=BitwiseAndPrecedence;
break;
}
case '|':
{
precedence=BitwiseOrPrecedence;
break;
}
case LogicalAndOperator:
{
precedence=LogicalAndPrecedence;
break;
}
case LogicalOrOperator:
{
precedence=LogicalOrPrecedence;
break;
}
case ExponentialNotation:
{
precedence=ExponentialNotationPrecedence;
break;
}
case ':':
case '?':
{
precedence=TernaryPrecedence;
break;
}
case '=':
{
precedence=AssignmentPrecedence;
break;
}
case ',':
{
precedence=CommaPrecedence;
break;
}
case ';':
{
precedence=SeparatorPrecedence;
break;
}
}
if ((precedence == BitwiseComplementPrecedence) ||
(precedence == TernaryPrecedence) ||
(precedence == AssignmentPrecedence))
{
if (precedence > target)
{
/*
Right-to-left associativity.
*/
target=precedence;
subexpression=expression;
}
}
else
if (precedence >= target)
{
/*
Left-to-right associativity.
*/
target=precedence;
subexpression=expression;
}
if (strchr("(",(int) *expression) != (char *) NULL)
expression=FxSubexpression(expression,exception);
c=(int) (*expression++);
}
return(subexpression);
}
static double FxEvaluateSubexpression(FxInfo *fx_info,
const PixelChannel channel,const ssize_t x,const ssize_t y,
const char *expression,size_t *depth,double *beta,ExceptionInfo *exception)
{
#define FxMaxParenthesisDepth 58
char
*q,
subexpression[MagickPathExtent];
double
alpha,
gamma;
register const char
*p;
*beta=0.0;
if (exception->severity >= ErrorException)
return(0.0);
while (isspace((int) ((unsigned char) *expression)) != 0)
expression++;
if (*expression == '\0')
return(0.0);
*subexpression='\0';
p=FxOperatorPrecedence(expression,exception);
if (p != (const char *) NULL)
{
(void) CopyMagickString(subexpression,expression,(size_t)
(p-expression+1));
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,depth,
beta,exception);
switch ((unsigned char) *p)
{
case '~':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
*beta=(double) (~(size_t) *beta);
return(*beta);
}
case '!':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
return(*beta == 0.0 ? 1.0 : 0.0);
}
case '^':
{
*beta=pow(alpha,FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,
beta,exception));
return(*beta);
}
case '*':
case ExponentialNotation:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
return(alpha*(*beta));
}
case '/':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
if (*beta == 0.0)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"DivideByZero","`%s'",expression);
return(0.0);
}
return(alpha/(*beta));
}
case '%':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
*beta=fabs(floor((*beta)+0.5));
if (*beta == 0.0)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"DivideByZero","`%s'",expression);
return(0.0);
}
return(fmod(alpha,*beta));
}
case '+':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
return(alpha+(*beta));
}
case '-':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
return(alpha-(*beta));
}
case LeftShiftOperator:
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
*beta=(double) ((size_t) (alpha+0.5) << (size_t) (gamma+0.5));
return(*beta);
}
case RightShiftOperator:
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
*beta=(double) ((size_t) (alpha+0.5) >> (size_t) (gamma+0.5));
return(*beta);
}
case '<':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
return(alpha < *beta ? 1.0 : 0.0);
}
case LessThanEqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
return(alpha <= *beta ? 1.0 : 0.0);
}
case '>':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
return(alpha > *beta ? 1.0 : 0.0);
}
case GreaterThanEqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
return(alpha >= *beta ? 1.0 : 0.0);
}
case EqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
return(fabs(alpha-(*beta)) < MagickEpsilon ? 1.0 : 0.0);
}
case NotEqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
return(fabs(alpha-(*beta)) >= MagickEpsilon ? 1.0 : 0.0);
}
case '&':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
*beta=(double) ((size_t) (alpha+0.5) & (size_t) (gamma+0.5));
return(*beta);
}
case '|':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
*beta=(double) ((size_t) (alpha+0.5) | (size_t) (gamma+0.5));
return(*beta);
}
case LogicalAndOperator:
{
p++;
if (alpha <= 0.0)
{
*beta=0.0;
return(*beta);
}
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth,beta,
exception);
*beta=(gamma > 0.0) ? 1.0 : 0.0;
return(*beta);
}
case LogicalOrOperator:
{
p++;
if (alpha > 0.0)
{
*beta=1.0;
return(*beta);
}
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth,beta,
exception);
*beta=(gamma > 0.0) ? 1.0 : 0.0;
return(*beta);
}
case '?':
{
(void) CopyMagickString(subexpression,++p,MagickPathExtent);
q=subexpression;
p=StringToken(":",&q);
if (q == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",subexpression);
return(0.0);
}
if (fabs(alpha) >= MagickEpsilon)
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth,beta,
exception);
else
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,q,depth,beta,
exception);
return(gamma);
}
case '=':
{
char
numeric[MagickPathExtent];
q=subexpression;
while (isalpha((int) ((unsigned char) *q)) != 0)
q++;
if (*q != '\0')
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",subexpression);
return(0.0);
}
ClearMagickException(exception);
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
(void) FormatLocaleString(numeric,MagickPathExtent,"%g",*beta);
(void) DeleteNodeFromSplayTree(fx_info->symbols,subexpression);
(void) AddValueToSplayTree(fx_info->symbols,ConstantString(
subexpression),ConstantString(numeric));
return(*beta);
}
case ',':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
return(alpha);
}
case ';':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta,
exception);
return(*beta);
}
default:
{
gamma=alpha*FxEvaluateSubexpression(fx_info,channel,x,y,p,depth,beta,
exception);
return(gamma);
}
}
}
if (strchr("(",(int) *expression) != (char *) NULL)
{
(*depth)++;
if (*depth >= FxMaxParenthesisDepth)
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"ParenthesisNestedTooDeeply","`%s'",expression);
(void) CopyMagickString(subexpression,expression+1,MagickPathExtent);
subexpression[strlen(subexpression)-1]='\0';
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,depth,
beta,exception);
(*depth)--;
return(gamma);
}
switch (*expression)
{
case '+':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth,beta,
exception);
return(1.0*gamma);
}
case '-':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth,beta,
exception);
return(-1.0*gamma);
}
case '~':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth,beta,
exception);
return((~(size_t) (gamma+0.5)));
}
case 'A':
case 'a':
{
if (LocaleNCompare(expression,"abs",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth,
beta,exception);
return(fabs(alpha));
}
#if defined(MAGICKCORE_HAVE_ACOSH)
if (LocaleNCompare(expression,"acosh",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth,
beta,exception);
return(acosh(alpha));
}
#endif
if (LocaleNCompare(expression,"acos",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth,
beta,exception);
return(acos(alpha));
}
#if defined(MAGICKCORE_HAVE_J1)
if (LocaleNCompare(expression,"airy",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth,
beta,exception);
if (alpha == 0.0)
return(1.0);
gamma=2.0*j1((MagickPI*alpha))/(MagickPI*alpha);
return(gamma*gamma);
}
#endif
#if defined(MAGICKCORE_HAVE_ASINH)
if (LocaleNCompare(expression,"asinh",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth,
beta,exception);
return(asinh(alpha));
}
#endif
if (LocaleNCompare(expression,"asin",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth,
beta,exception);
return(asin(alpha));
}
if (LocaleNCompare(expression,"alt",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth,
beta,exception);
return(((ssize_t) alpha) & 0x01 ? -1.0 : 1.0);
}
if (LocaleNCompare(expression,"atan2",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth,
beta,exception);
return(atan2(alpha,*beta));
}
#if defined(MAGICKCORE_HAVE_ATANH)
if (LocaleNCompare(expression,"atanh",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth,
beta,exception);
return(atanh(alpha));
}
#endif
if (LocaleNCompare(expression,"atan",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth,
beta,exception);
return(atan(alpha));
}
if (LocaleCompare(expression,"a") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
break;
}
case 'B':
case 'b':
{
if (LocaleCompare(expression,"b") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
break;
}
case 'C':
case 'c':
{
if (LocaleNCompare(expression,"ceil",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth,
beta,exception);
return(ceil(alpha));
}
if (LocaleNCompare(expression,"clamp",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth,
beta,exception);
if (alpha < 0.0)
return(0.0);
if (alpha > 1.0)
return(1.0);
return(alpha);
}
if (LocaleNCompare(expression,"cosh",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth,
beta,exception);
return(cosh(alpha));
}
if (LocaleNCompare(expression,"cos",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth,
beta,exception);
return(cos(alpha));
}
if (LocaleCompare(expression,"c") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
break;
}
case 'D':
case 'd':
{
if (LocaleNCompare(expression,"debug",5) == 0)
{
const char
*type;
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth,
beta,exception);
if (fx_info->images->colorspace == CMYKColorspace)
switch (channel)
{
case CyanPixelChannel: type="cyan"; break;
case MagentaPixelChannel: type="magenta"; break;
case YellowPixelChannel: type="yellow"; break;
case AlphaPixelChannel: type="opacity"; break;
case BlackPixelChannel: type="black"; break;
default: type="unknown"; break;
}
else
switch (channel)
{
case RedPixelChannel: type="red"; break;
case GreenPixelChannel: type="green"; break;
case BluePixelChannel: type="blue"; break;
case AlphaPixelChannel: type="opacity"; break;
default: type="unknown"; break;
}
(void) CopyMagickString(subexpression,expression+6,MagickPathExtent);
if (strlen(subexpression) > 1)
subexpression[strlen(subexpression)-1]='\0';
if (fx_info->file != (FILE *) NULL)
(void) FormatLocaleFile(fx_info->file,"%s[%.20g,%.20g].%s: "
"%s=%.*g\n",fx_info->images->filename,(double) x,(double) y,type,
subexpression,GetMagickPrecision(),alpha);
return(0.0);
}
if (LocaleNCompare(expression,"drc",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth,
beta,exception);
return((alpha/(*beta*(alpha-1.0)+1.0)));
}
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(expression,"epsilon") == 0)
return(MagickEpsilon);
#if defined(MAGICKCORE_HAVE_ERF)
if (LocaleNCompare(expression,"erf",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth,
beta,exception);
return(erf(alpha));
}
#endif
if (LocaleNCompare(expression,"exp",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth,
beta,exception);
return(exp(alpha));
}
if (LocaleCompare(expression,"e") == 0)
return(2.7182818284590452354);
break;
}
case 'F':
case 'f':
{
if (LocaleNCompare(expression,"floor",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth,
beta,exception);
return(floor(alpha));
}
break;
}
case 'G':
case 'g':
{
if (LocaleNCompare(expression,"gauss",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth,
beta,exception);
gamma=exp((-alpha*alpha/2.0))/sqrt(2.0*MagickPI);
return(gamma);
}
if (LocaleNCompare(expression,"gcd",3) == 0)
{
MagickOffsetType
gcd;
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth,
beta,exception);
gcd=FxGCD((MagickOffsetType) (alpha+0.5),(MagickOffsetType) (*beta+
0.5));
return(gcd);
}
if (LocaleCompare(expression,"g") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(expression,"h") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
if (LocaleCompare(expression,"hue") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
if (LocaleNCompare(expression,"hypot",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth,
beta,exception);
return(hypot(alpha,*beta));
}
break;
}
case 'K':
case 'k':
{
if (LocaleCompare(expression,"k") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(expression,"intensity") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
if (LocaleNCompare(expression,"int",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth,
beta,exception);
return(floor(alpha));
}
if (LocaleNCompare(expression,"isnan",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth,
beta,exception);
return(!!IsNaN(alpha));
}
if (LocaleCompare(expression,"i") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
break;
}
case 'J':
case 'j':
{
if (LocaleCompare(expression,"j") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
#if defined(MAGICKCORE_HAVE_J0)
if (LocaleNCompare(expression,"j0",2) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,depth,
beta,exception);
return(j0(alpha));
}
#endif
#if defined(MAGICKCORE_HAVE_J1)
if (LocaleNCompare(expression,"j1",2) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,depth,
beta,exception);
return(j1(alpha));
}
#endif
#if defined(MAGICKCORE_HAVE_J1)
if (LocaleNCompare(expression,"jinc",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth,
beta,exception);
if (alpha == 0.0)
return(1.0);
gamma=(2.0*j1((MagickPI*alpha))/(MagickPI*alpha));
return(gamma);
}
#endif
break;
}
case 'L':
case 'l':
{
if (LocaleNCompare(expression,"ln",2) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,depth,
beta,exception);
return(log(alpha));
}
if (LocaleNCompare(expression,"logtwo",6) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+6,depth,
beta,exception);
return(log10(alpha))/log10(2.0);
}
if (LocaleNCompare(expression,"log",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth,
beta,exception);
return(log10(alpha));
}
if (LocaleCompare(expression,"lightness") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
break;
}
case 'M':
case 'm':
{
if (LocaleCompare(expression,"MaxRGB") == 0)
return(QuantumRange);
if (LocaleNCompare(expression,"maxima",6) == 0)
break;
if (LocaleNCompare(expression,"max",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth,
beta,exception);
return(alpha > *beta ? alpha : *beta);
}
if (LocaleNCompare(expression,"minima",6) == 0)
break;
if (LocaleNCompare(expression,"min",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth,
beta,exception);
return(alpha < *beta ? alpha : *beta);
}
if (LocaleNCompare(expression,"mod",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth,
beta,exception);
gamma=alpha-floor((alpha/(*beta)))*(*beta);
return(gamma);
}
if (LocaleCompare(expression,"m") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
break;
}
case 'N':
case 'n':
{
if (LocaleNCompare(expression,"not",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth,
beta,exception);
return((alpha < MagickEpsilon));
}
if (LocaleCompare(expression,"n") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(expression,"Opaque") == 0)
return(1.0);
if (LocaleCompare(expression,"o") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(expression,"phi") == 0)
return(MagickPHI);
if (LocaleCompare(expression,"pi") == 0)
return(MagickPI);
if (LocaleNCompare(expression,"pow",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth,
beta,exception);
return(pow(alpha,*beta));
}
if (LocaleCompare(expression,"p") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
break;
}
case 'Q':
case 'q':
{
if (LocaleCompare(expression,"QuantumRange") == 0)
return(QuantumRange);
if (LocaleCompare(expression,"QuantumScale") == 0)
return(QuantumScale);
break;
}
case 'R':
case 'r':
{
if (LocaleNCompare(expression,"rand",4) == 0)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_FxEvaluateSubexpression)
#endif
alpha=GetPseudoRandomValue(fx_info->random_info);
return(alpha);
}
if (LocaleNCompare(expression,"round",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth,
beta,exception);
return(floor(alpha+0.5));
}
if (LocaleCompare(expression,"r") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
break;
}
case 'S':
case 's':
{
if (LocaleCompare(expression,"saturation") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
if (LocaleNCompare(expression,"sign",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth,
beta,exception);
return(alpha < 0.0 ? -1.0 : 1.0);
}
if (LocaleNCompare(expression,"sinc",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth,
beta,exception);
if (alpha == 0)
return(1.0);
gamma=sin((MagickPI*alpha))/(MagickPI*alpha);
return(gamma);
}
if (LocaleNCompare(expression,"sinh",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth,
beta,exception);
return(sinh(alpha));
}
if (LocaleNCompare(expression,"sin",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth,
beta,exception);
return(sin(alpha));
}
if (LocaleNCompare(expression,"sqrt",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth,
beta,exception);
return(sqrt(alpha));
}
if (LocaleNCompare(expression,"squish",6) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+6,depth,
beta,exception);
return((1.0/(1.0+exp(-alpha))));
}
if (LocaleCompare(expression,"s") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
break;
}
case 'T':
case 't':
{
if (LocaleNCompare(expression,"tanh",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth,
beta,exception);
return(tanh(alpha));
}
if (LocaleNCompare(expression,"tan",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth,
beta,exception);
return(tan(alpha));
}
if (LocaleCompare(expression,"Transparent") == 0)
return(0.0);
if (LocaleNCompare(expression,"trunc",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth,
beta,exception);
if (alpha >= 0.0)
return(floor(alpha));
return(ceil(alpha));
}
if (LocaleCompare(expression,"t") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
break;
}
case 'U':
case 'u':
{
if (LocaleCompare(expression,"u") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
break;
}
case 'V':
case 'v':
{
if (LocaleCompare(expression,"v") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
break;
}
case 'W':
case 'w':
{
if (LocaleNCompare(expression,"while",5) == 0)
{
do
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth,beta,exception);
} while (fabs(alpha) >= MagickEpsilon);
return(*beta);
}
if (LocaleCompare(expression,"w") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(expression,"y") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
break;
}
case 'Z':
case 'z':
{
if (LocaleCompare(expression,"z") == 0)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
break;
}
default:
break;
}
q=(char *) expression;
alpha=InterpretSiPrefixValue(expression,&q);
if (q == expression)
return(FxGetSymbol(fx_info,channel,x,y,expression,exception));
return(alpha);
}
MagickPrivate MagickBooleanType FxEvaluateExpression(FxInfo *fx_info,
double *alpha,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=FxEvaluateChannelExpression(fx_info,GrayPixelChannel,0,0,alpha,
exception);
return(status);
}
MagickExport MagickBooleanType FxPreprocessExpression(FxInfo *fx_info,
double *alpha,ExceptionInfo *exception)
{
FILE
*file;
MagickBooleanType
status;
file=fx_info->file;
fx_info->file=(FILE *) NULL;
status=FxEvaluateChannelExpression(fx_info,GrayPixelChannel,0,0,alpha,
exception);
fx_info->file=file;
return(status);
}
MagickPrivate MagickBooleanType FxEvaluateChannelExpression(FxInfo *fx_info,
const PixelChannel channel,const ssize_t x,const ssize_t y,
double *alpha,ExceptionInfo *exception)
{
double
beta;
size_t
depth;
depth=0;
beta=0.0;
*alpha=FxEvaluateSubexpression(fx_info,channel,x,y,fx_info->expression,&depth,
&beta,exception);
return(exception->severity == OptionError ? MagickFalse : MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F x I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FxImage() applies a mathematical expression to the specified image.
%
% The format of the FxImage method is:
%
% Image *FxImage(const Image *image,const char *expression,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o expression: A mathematical expression.
%
% o exception: return any errors or warnings in this structure.
%
*/
static FxInfo **DestroyFxThreadSet(FxInfo **fx_info)
{
register ssize_t
i;
assert(fx_info != (FxInfo **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (fx_info[i] != (FxInfo *) NULL)
fx_info[i]=DestroyFxInfo(fx_info[i]);
fx_info=(FxInfo **) RelinquishMagickMemory(fx_info);
return(fx_info);
}
static FxInfo **AcquireFxThreadSet(const Image *image,const char *expression,
ExceptionInfo *exception)
{
char
*fx_expression;
FxInfo
**fx_info;
double
alpha;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
fx_info=(FxInfo **) AcquireQuantumMemory(number_threads,sizeof(*fx_info));
if (fx_info == (FxInfo **) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return((FxInfo **) NULL);
}
(void) ResetMagickMemory(fx_info,0,number_threads*sizeof(*fx_info));
if (*expression != '@')
fx_expression=ConstantString(expression);
else
fx_expression=FileToString(expression+1,~0UL,exception);
for (i=0; i < (ssize_t) number_threads; i++)
{
MagickBooleanType
status;
fx_info[i]=AcquireFxInfo(image,fx_expression,exception);
if (fx_info[i] == (FxInfo *) NULL)
break;
status=FxPreprocessExpression(fx_info[i],&alpha,exception);
if (status == MagickFalse)
break;
}
fx_expression=DestroyString(fx_expression);
if (i < (ssize_t) number_threads)
fx_info=DestroyFxThreadSet(fx_info);
return(fx_info);
}
MagickExport Image *FxImage(const Image *image,const char *expression,
ExceptionInfo *exception)
{
#define FxImageTag "Fx/Image"
CacheView
*fx_view,
*image_view;
FxInfo
**magick_restrict fx_info;
Image
*fx_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
fx_info=AcquireFxThreadSet(image,expression,exception);
if (fx_info == (FxInfo **) NULL)
return((Image *) NULL);
fx_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if (fx_image == (Image *) NULL)
{
fx_info=DestroyFxThreadSet(fx_info);
return((Image *) NULL);
}
if (SetImageStorageClass(fx_image,DirectClass,exception) == MagickFalse)
{
fx_info=DestroyFxThreadSet(fx_info);
fx_image=DestroyImage(fx_image);
return((Image *) NULL);
}
/*
Fx image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
fx_view=AcquireAuthenticCacheView(fx_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,fx_image,fx_image->rows,1)
#endif
for (y=0; y < (ssize_t) fx_image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(fx_view,0,y,fx_image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) fx_image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
alpha;
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait fx_traits=GetPixelChannelTraits(fx_image,channel);
if ((traits == UndefinedPixelTrait) ||
(fx_traits == UndefinedPixelTrait))
continue;
if (((fx_traits & CopyPixelTrait) != 0) ||
(GetPixelReadMask(image,p) == 0))
{
SetPixelChannel(fx_image,channel,p[i],q);
continue;
}
alpha=0.0;
(void) FxEvaluateChannelExpression(fx_info[id],channel,x,y,&alpha,
exception);
q[i]=ClampToQuantum(QuantumRange*alpha);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(fx_image);
}
if (SyncCacheViewAuthenticPixels(fx_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_FxImage)
#endif
proceed=SetImageProgress(image,FxImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
fx_view=DestroyCacheView(fx_view);
image_view=DestroyCacheView(image_view);
fx_info=DestroyFxThreadSet(fx_info);
if (status == MagickFalse)
fx_image=DestroyImage(fx_image);
return(fx_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I m p l o d e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ImplodeImage() creates a new image that is a copy of an existing
% one with the image pixels "implode" by the specified percentage. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ImplodeImage method is:
%
% Image *ImplodeImage(const Image *image,const double amount,
% const PixelInterpolateMethod method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o implode_image: Method ImplodeImage returns a pointer to the image
% after it is implode. A null image is returned if there is a memory
% shortage.
%
% o image: the image.
%
% o amount: Define the extent of the implosion.
%
% o method: the pixel interpolation method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ImplodeImage(const Image *image,const double amount,
const PixelInterpolateMethod method,ExceptionInfo *exception)
{
#define ImplodeImageTag "Implode/Image"
CacheView
*image_view,
*implode_view,
*interpolate_view;
Image
*implode_image;
MagickBooleanType
status;
MagickOffsetType
progress;
double
radius;
PointInfo
center,
scale;
ssize_t
y;
/*
Initialize implode image attributes.
*/
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);
implode_image=CloneImage(image,image->columns,image->rows,MagickTrue,
exception);
if (implode_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(implode_image,DirectClass,exception) == MagickFalse)
{
implode_image=DestroyImage(implode_image);
return((Image *) NULL);
}
if (implode_image->background_color.alpha != OpaqueAlpha)
implode_image->alpha_trait=BlendPixelTrait;
/*
Compute scaling factor.
*/
scale.x=1.0;
scale.y=1.0;
center.x=0.5*image->columns;
center.y=0.5*image->rows;
radius=center.x;
if (image->columns > image->rows)
scale.y=(double) image->columns/(double) image->rows;
else
if (image->columns < image->rows)
{
scale.x=(double) image->rows/(double) image->columns;
radius=center.y;
}
/*
Implode image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
interpolate_view=AcquireVirtualCacheView(image,exception);
implode_view=AcquireAuthenticCacheView(implode_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,implode_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
distance;
PointInfo
delta;
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(implode_view,0,y,implode_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
delta.y=scale.y*(double) (y-center.y);
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
/*
Determine if the pixel is within an ellipse.
*/
if (GetPixelReadMask(image,p) == 0)
{
SetPixelBackgoundColor(implode_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(implode_image);
continue;
}
delta.x=scale.x*(double) (x-center.x);
distance=delta.x*delta.x+delta.y*delta.y;
if (distance >= (radius*radius))
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait implode_traits=GetPixelChannelTraits(implode_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(implode_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(implode_image,channel,p[i],q);
}
else
{
double
factor;
/*
Implode the pixel.
*/
factor=1.0;
if (distance > 0.0)
factor=pow(sin(MagickPI*sqrt((double) distance)/radius/2),-amount);
status=InterpolatePixelChannels(image,interpolate_view,implode_image,
method,(double) (factor*delta.x/scale.x+center.x),(double) (factor*
delta.y/scale.y+center.y),q,exception);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(implode_image);
}
if (SyncCacheViewAuthenticPixels(implode_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ImplodeImage)
#endif
proceed=SetImageProgress(image,ImplodeImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
implode_view=DestroyCacheView(implode_view);
interpolate_view=DestroyCacheView(interpolate_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
implode_image=DestroyImage(implode_image);
return(implode_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M o r p h I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% The MorphImages() method requires a minimum of two images. The first
% image is transformed into the second by a number of intervening images
% as specified by frames.
%
% The format of the MorphImage method is:
%
% Image *MorphImages(const Image *image,const size_t number_frames,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o number_frames: Define the number of in-between image to generate.
% The more in-between frames, the smoother the morph.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *MorphImages(const Image *image,const size_t number_frames,
ExceptionInfo *exception)
{
#define MorphImageTag "Morph/Image"
double
alpha,
beta;
Image
*morph_image,
*morph_images;
MagickBooleanType
status;
MagickOffsetType
scene;
register const Image
*next;
register ssize_t
n;
ssize_t
y;
/*
Clone first frame in sequence.
*/
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);
morph_images=CloneImage(image,0,0,MagickTrue,exception);
if (morph_images == (Image *) NULL)
return((Image *) NULL);
if (GetNextImageInList(image) == (Image *) NULL)
{
/*
Morph single image.
*/
for (n=1; n < (ssize_t) number_frames; n++)
{
morph_image=CloneImage(image,0,0,MagickTrue,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
AppendImageToList(&morph_images,morph_image);
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,MorphImageTag,(MagickOffsetType) n,
number_frames);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
return(GetFirstImageInList(morph_images));
}
/*
Morph image sequence.
*/
status=MagickTrue;
scene=0;
next=image;
for ( ; GetNextImageInList(next) != (Image *) NULL; next=GetNextImageInList(next))
{
for (n=0; n < (ssize_t) number_frames; n++)
{
CacheView
*image_view,
*morph_view;
beta=(double) (n+1.0)/(double) (number_frames+1.0);
alpha=1.0-beta;
morph_image=ResizeImage(next,(size_t) (alpha*next->columns+beta*
GetNextImageInList(next)->columns+0.5),(size_t) (alpha*next->rows+beta*
GetNextImageInList(next)->rows+0.5),next->filter,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
status=SetImageStorageClass(morph_image,DirectClass,exception);
if (status == MagickFalse)
{
morph_image=DestroyImage(morph_image);
return((Image *) NULL);
}
AppendImageToList(&morph_images,morph_image);
morph_images=GetLastImageInList(morph_images);
morph_image=ResizeImage(GetNextImageInList(next),morph_images->columns,
morph_images->rows,GetNextImageInList(next)->filter,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
image_view=AcquireVirtualCacheView(morph_image,exception);
morph_view=AcquireAuthenticCacheView(morph_images,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(morph_image,morph_image,morph_image->rows,1)
#endif
for (y=0; y < (ssize_t) morph_images->rows; y++)
{
MagickBooleanType
sync;
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,morph_image->columns,1,
exception);
q=GetCacheViewAuthenticPixels(morph_view,0,y,morph_images->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) morph_images->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(morph_image); i++)
{
PixelChannel channel=GetPixelChannelChannel(morph_image,i);
PixelTrait traits=GetPixelChannelTraits(morph_image,channel);
PixelTrait morph_traits=GetPixelChannelTraits(morph_images,channel);
if ((traits == UndefinedPixelTrait) ||
(morph_traits == UndefinedPixelTrait))
continue;
if (((morph_traits & CopyPixelTrait) != 0) ||
(GetPixelReadMask(morph_images,p) == 0))
{
SetPixelChannel(morph_image,channel,p[i],q);
continue;
}
SetPixelChannel(morph_image,channel,ClampToQuantum(alpha*
GetPixelChannel(morph_images,channel,q)+beta*p[i]),q);
}
p+=GetPixelChannels(morph_image);
q+=GetPixelChannels(morph_images);
}
sync=SyncCacheViewAuthenticPixels(morph_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
morph_view=DestroyCacheView(morph_view);
image_view=DestroyCacheView(image_view);
morph_image=DestroyImage(morph_image);
}
if (n < (ssize_t) number_frames)
break;
/*
Clone last frame in sequence.
*/
morph_image=CloneImage(GetNextImageInList(next),0,0,MagickTrue,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
AppendImageToList(&morph_images,morph_image);
morph_images=GetLastImageInList(morph_images);
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_MorphImages)
#endif
proceed=SetImageProgress(image,MorphImageTag,scene,
GetImageListLength(image));
if (proceed == MagickFalse)
status=MagickFalse;
}
scene++;
}
if (GetNextImageInList(next) != (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
return(GetFirstImageInList(morph_images));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P l a s m a I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PlasmaImage() initializes an image with plasma fractal values. The image
% must be initialized with a base color and the random number generator
% seeded before this method is called.
%
% The format of the PlasmaImage method is:
%
% MagickBooleanType PlasmaImage(Image *image,const SegmentInfo *segment,
% size_t attenuate,size_t depth,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o segment: Define the region to apply plasma fractals values.
%
% o attenuate: Define the plasma attenuation factor.
%
% o depth: Limit the plasma recursion depth.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline Quantum PlasmaPixel(RandomInfo *random_info,
const double pixel,const double noise)
{
Quantum
plasma;
plasma=ClampToQuantum(pixel+noise*GetPseudoRandomValue(random_info)-
noise/2.0);
if (plasma <= 0)
return((Quantum) 0);
if (plasma >= QuantumRange)
return(QuantumRange);
return(plasma);
}
static MagickBooleanType PlasmaImageProxy(Image *image,CacheView *image_view,
CacheView *u_view,CacheView *v_view,RandomInfo *random_info,
const SegmentInfo *segment,size_t attenuate,size_t depth,
ExceptionInfo *exception)
{
double
plasma;
register const Quantum
*magick_restrict u,
*magick_restrict v;
register Quantum
*magick_restrict q;
register ssize_t
i;
ssize_t
x,
x_mid,
y,
y_mid;
if ((fabs(segment->x2-segment->x1) <= MagickEpsilon) &&
(fabs(segment->y2-segment->y1) <= MagickEpsilon))
return(MagickTrue);
if (depth != 0)
{
MagickBooleanType
status;
SegmentInfo
local_info;
/*
Divide the area into quadrants and recurse.
*/
depth--;
attenuate++;
x_mid=(ssize_t) ceil((segment->x1+segment->x2)/2-0.5);
y_mid=(ssize_t) ceil((segment->y1+segment->y2)/2-0.5);
local_info=(*segment);
local_info.x2=(double) x_mid;
local_info.y2=(double) y_mid;
(void) PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth,exception);
local_info=(*segment);
local_info.y1=(double) y_mid;
local_info.x2=(double) x_mid;
(void) PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth,exception);
local_info=(*segment);
local_info.x1=(double) x_mid;
local_info.y2=(double) y_mid;
(void) PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth,exception);
local_info=(*segment);
local_info.x1=(double) x_mid;
local_info.y1=(double) y_mid;
status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth,exception);
return(status);
}
x_mid=(ssize_t) ceil((segment->x1+segment->x2)/2-0.5);
y_mid=(ssize_t) ceil((segment->y1+segment->y2)/2-0.5);
if ((fabs(segment->x1-x_mid) < MagickEpsilon) &&
(fabs(segment->x2-x_mid) < MagickEpsilon) &&
(fabs(segment->y1-y_mid) < MagickEpsilon) &&
(fabs(segment->y2-y_mid) < MagickEpsilon))
return(MagickFalse);
/*
Average pixels and apply plasma.
*/
plasma=(double) QuantumRange/(2.0*attenuate);
if ((fabs(segment->x1-x_mid) > MagickEpsilon) ||
(fabs(segment->x2-x_mid) > MagickEpsilon))
{
/*
Left pixel.
*/
x=(ssize_t) ceil(segment->x1-0.5);
u=GetCacheViewVirtualPixels(u_view,x,(ssize_t) ceil(segment->y1-0.5),1,1,
exception);
v=GetCacheViewVirtualPixels(v_view,x,(ssize_t) ceil(segment->y2-0.5),1,1,
exception);
q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception);
if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) ||
(q == (Quantum *) NULL))
return(MagickTrue);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=PlasmaPixel(random_info,(u[i]+v[i])/2.0,plasma);
}
(void) SyncCacheViewAuthenticPixels(image_view,exception);
if (fabs(segment->x1-segment->x2) > MagickEpsilon)
{
/*
Right pixel.
*/
x=(ssize_t) ceil(segment->x2-0.5);
u=GetCacheViewVirtualPixels(u_view,x,(ssize_t) ceil(segment->y1-0.5),
1,1,exception);
v=GetCacheViewVirtualPixels(v_view,x,(ssize_t) ceil(segment->y2-0.5),
1,1,exception);
q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception);
if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) ||
(q == (Quantum *) NULL))
return(MagickTrue);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=PlasmaPixel(random_info,(u[i]+v[i])/2.0,plasma);
}
(void) SyncCacheViewAuthenticPixels(image_view,exception);
}
}
if ((fabs(segment->y1-y_mid) > MagickEpsilon) ||
(fabs(segment->y2-y_mid) > MagickEpsilon))
{
if ((fabs(segment->x1-x_mid) > MagickEpsilon) ||
(fabs(segment->y2-y_mid) > MagickEpsilon))
{
/*
Bottom pixel.
*/
y=(ssize_t) ceil(segment->y2-0.5);
u=GetCacheViewVirtualPixels(u_view,(ssize_t) ceil(segment->x1-0.5),y,
1,1,exception);
v=GetCacheViewVirtualPixels(v_view,(ssize_t) ceil(segment->x2-0.5),y,
1,1,exception);
q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception);
if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) ||
(q == (Quantum *) NULL))
return(MagickTrue);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=PlasmaPixel(random_info,(u[i]+v[i])/2.0,plasma);
}
(void) SyncCacheViewAuthenticPixels(image_view,exception);
}
if (fabs(segment->y1-segment->y2) > MagickEpsilon)
{
/*
Top pixel.
*/
y=(ssize_t) ceil(segment->y1-0.5);
u=GetCacheViewVirtualPixels(u_view,(ssize_t) ceil(segment->x1-0.5),y,
1,1,exception);
v=GetCacheViewVirtualPixels(v_view,(ssize_t) ceil(segment->x2-0.5),y,
1,1,exception);
q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception);
if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) ||
(q == (Quantum *) NULL))
return(MagickTrue);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=PlasmaPixel(random_info,(u[i]+v[i])/2.0,plasma);
}
(void) SyncCacheViewAuthenticPixels(image_view,exception);
}
}
if ((fabs(segment->x1-segment->x2) > MagickEpsilon) ||
(fabs(segment->y1-segment->y2) > MagickEpsilon))
{
/*
Middle pixel.
*/
x=(ssize_t) ceil(segment->x1-0.5);
y=(ssize_t) ceil(segment->y1-0.5);
u=GetCacheViewVirtualPixels(u_view,x,y,1,1,exception);
x=(ssize_t) ceil(segment->x2-0.5);
y=(ssize_t) ceil(segment->y2-0.5);
v=GetCacheViewVirtualPixels(v_view,x,y,1,1,exception);
q=QueueCacheViewAuthenticPixels(image_view,x_mid,y_mid,1,1,exception);
if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) ||
(q == (Quantum *) NULL))
return(MagickTrue);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=PlasmaPixel(random_info,(u[i]+v[i])/2.0,plasma);
}
(void) SyncCacheViewAuthenticPixels(image_view,exception);
}
if ((fabs(segment->x2-segment->x1) < 3.0) &&
(fabs(segment->y2-segment->y1) < 3.0))
return(MagickTrue);
return(MagickFalse);
}
MagickExport MagickBooleanType PlasmaImage(Image *image,
const SegmentInfo *segment,size_t attenuate,size_t depth,
ExceptionInfo *exception)
{
CacheView
*image_view,
*u_view,
*v_view;
MagickBooleanType
status;
RandomInfo
*random_info;
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
image_view=AcquireAuthenticCacheView(image,exception);
u_view=AcquireVirtualCacheView(image,exception);
v_view=AcquireVirtualCacheView(image,exception);
random_info=AcquireRandomInfo();
status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info,segment,
attenuate,depth,exception);
random_info=DestroyRandomInfo(random_info);
v_view=DestroyCacheView(v_view);
u_view=DestroyCacheView(u_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P o l a r o i d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PolaroidImage() simulates a Polaroid picture.
%
% The format of the PolaroidImage method is:
%
% Image *PolaroidImage(const Image *image,const DrawInfo *draw_info,
% const char *caption,const double angle,
% const PixelInterpolateMethod method,ExceptionInfo exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o caption: the Polaroid caption.
%
% o angle: Apply the effect along this angle.
%
% o method: the pixel interpolation method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *PolaroidImage(const Image *image,const DrawInfo *draw_info,
const char *caption,const double angle,const PixelInterpolateMethod method,
ExceptionInfo *exception)
{
Image
*bend_image,
*caption_image,
*flop_image,
*picture_image,
*polaroid_image,
*rotate_image,
*trim_image;
size_t
height;
ssize_t
quantum;
/*
Simulate a Polaroid picture.
*/
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);
quantum=(ssize_t) MagickMax(MagickMax((double) image->columns,(double)
image->rows)/25.0,10.0);
height=image->rows+2*quantum;
caption_image=(Image *) NULL;
if (caption != (const char *) NULL)
{
char
geometry[MagickPathExtent],
*text;
DrawInfo
*annotate_info;
ImageInfo
*image_info;
MagickBooleanType
status;
ssize_t
count;
TypeMetric
metrics;
/*
Generate caption image.
*/
caption_image=CloneImage(image,image->columns,1,MagickTrue,exception);
if (caption_image == (Image *) NULL)
return((Image *) NULL);
image_info=AcquireImageInfo();
annotate_info=CloneDrawInfo((const ImageInfo *) NULL,draw_info);
text=InterpretImageProperties(image_info,(Image *) image,caption,
exception);
image_info=DestroyImageInfo(image_info);
(void) CloneString(&annotate_info->text,text);
count=FormatMagickCaption(caption_image,annotate_info,MagickTrue,&metrics,
&text,exception);
status=SetImageExtent(caption_image,image->columns,(size_t) ((count+1)*
(metrics.ascent-metrics.descent)+0.5),exception);
if (status == MagickFalse)
caption_image=DestroyImage(caption_image);
else
{
caption_image->background_color=image->border_color;
(void) SetImageBackgroundColor(caption_image,exception);
(void) CloneString(&annotate_info->text,text);
(void) FormatLocaleString(geometry,MagickPathExtent,"+0+%g",
metrics.ascent);
if (annotate_info->gravity == UndefinedGravity)
(void) CloneString(&annotate_info->geometry,AcquireString(
geometry));
(void) AnnotateImage(caption_image,annotate_info,exception);
height+=caption_image->rows;
}
annotate_info=DestroyDrawInfo(annotate_info);
text=DestroyString(text);
}
picture_image=CloneImage(image,image->columns+2*quantum,height,MagickTrue,
exception);
if (picture_image == (Image *) NULL)
{
if (caption_image != (Image *) NULL)
caption_image=DestroyImage(caption_image);
return((Image *) NULL);
}
picture_image->background_color=image->border_color;
(void) SetImageBackgroundColor(picture_image,exception);
(void) CompositeImage(picture_image,image,OverCompositeOp,MagickTrue,quantum,
quantum,exception);
if (caption_image != (Image *) NULL)
{
(void) CompositeImage(picture_image,caption_image,OverCompositeOp,
MagickTrue,quantum,(ssize_t) (image->rows+3*quantum/2),exception);
caption_image=DestroyImage(caption_image);
}
(void) QueryColorCompliance("none",AllCompliance,
&picture_image->background_color,exception);
(void) SetImageAlphaChannel(picture_image,OpaqueAlphaChannel,exception);
rotate_image=RotateImage(picture_image,90.0,exception);
picture_image=DestroyImage(picture_image);
if (rotate_image == (Image *) NULL)
return((Image *) NULL);
picture_image=rotate_image;
bend_image=WaveImage(picture_image,0.01*picture_image->rows,2.0*
picture_image->columns,method,exception);
picture_image=DestroyImage(picture_image);
if (bend_image == (Image *) NULL)
return((Image *) NULL);
picture_image=bend_image;
rotate_image=RotateImage(picture_image,-90.0,exception);
picture_image=DestroyImage(picture_image);
if (rotate_image == (Image *) NULL)
return((Image *) NULL);
picture_image=rotate_image;
picture_image->background_color=image->background_color;
polaroid_image=ShadowImage(picture_image,80.0,2.0,quantum/3,quantum/3,
exception);
if (polaroid_image == (Image *) NULL)
{
picture_image=DestroyImage(picture_image);
return(picture_image);
}
flop_image=FlopImage(polaroid_image,exception);
polaroid_image=DestroyImage(polaroid_image);
if (flop_image == (Image *) NULL)
{
picture_image=DestroyImage(picture_image);
return(picture_image);
}
polaroid_image=flop_image;
(void) CompositeImage(polaroid_image,picture_image,OverCompositeOp,
MagickTrue,(ssize_t) (-0.01*picture_image->columns/2.0),0L,exception);
picture_image=DestroyImage(picture_image);
(void) QueryColorCompliance("none",AllCompliance,
&polaroid_image->background_color,exception);
rotate_image=RotateImage(polaroid_image,angle,exception);
polaroid_image=DestroyImage(polaroid_image);
if (rotate_image == (Image *) NULL)
return((Image *) NULL);
polaroid_image=rotate_image;
trim_image=TrimImage(polaroid_image,exception);
polaroid_image=DestroyImage(polaroid_image);
if (trim_image == (Image *) NULL)
return((Image *) NULL);
polaroid_image=trim_image;
return(polaroid_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e p i a T o n e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MagickSepiaToneImage() applies a special effect to the image, similar to the
% effect achieved in a photo darkroom by sepia toning. Threshold ranges from
% 0 to QuantumRange and is a measure of the extent of the sepia toning. A
% threshold of 80% is a good starting point for a reasonable tone.
%
% The format of the SepiaToneImage method is:
%
% Image *SepiaToneImage(const Image *image,const double threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: the tone threshold.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SepiaToneImage(const Image *image,const double threshold,
ExceptionInfo *exception)
{
#define SepiaToneImageTag "SepiaTone/Image"
CacheView
*image_view,
*sepia_view;
Image
*sepia_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Initialize sepia-toned image attributes.
*/
assert(image != (const 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);
sepia_image=CloneImage(image,0,0,MagickTrue,exception);
if (sepia_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(sepia_image,DirectClass,exception) == MagickFalse)
{
sepia_image=DestroyImage(sepia_image);
return((Image *) NULL);
}
/*
Tone each row of the image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
sepia_view=AcquireAuthenticCacheView(sepia_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,sepia_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(sepia_view,0,y,sepia_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
intensity,
tone;
intensity=GetPixelIntensity(image,p);
tone=intensity > threshold ? (double) QuantumRange : intensity+
(double) QuantumRange-threshold;
SetPixelRed(sepia_image,ClampToQuantum(tone),q);
tone=intensity > (7.0*threshold/6.0) ? (double) QuantumRange :
intensity+(double) QuantumRange-7.0*threshold/6.0;
SetPixelGreen(sepia_image,ClampToQuantum(tone),q);
tone=intensity < (threshold/6.0) ? 0 : intensity-threshold/6.0;
SetPixelBlue(sepia_image,ClampToQuantum(tone),q);
tone=threshold/7.0;
if ((double) GetPixelGreen(image,q) < tone)
SetPixelGreen(sepia_image,ClampToQuantum(tone),q);
if ((double) GetPixelBlue(image,q) < tone)
SetPixelBlue(sepia_image,ClampToQuantum(tone),q);
SetPixelAlpha(sepia_image,GetPixelAlpha(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(sepia_image);
}
if (SyncCacheViewAuthenticPixels(sepia_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_SepiaToneImage)
#endif
proceed=SetImageProgress(image,SepiaToneImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
sepia_view=DestroyCacheView(sepia_view);
image_view=DestroyCacheView(image_view);
(void) NormalizeImage(sepia_image,exception);
(void) ContrastImage(sepia_image,MagickTrue,exception);
if (status == MagickFalse)
sepia_image=DestroyImage(sepia_image);
return(sepia_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S h a d o w I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ShadowImage() simulates a shadow from the specified image and returns it.
%
% The format of the ShadowImage method is:
%
% Image *ShadowImage(const Image *image,const double alpha,
% const double sigma,const ssize_t x_offset,const ssize_t y_offset,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o alpha: percentage transparency.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o x_offset: the shadow x-offset.
%
% o y_offset: the shadow y-offset.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ShadowImage(const Image *image,const double alpha,
const double sigma,const ssize_t x_offset,const ssize_t y_offset,
ExceptionInfo *exception)
{
#define ShadowImageTag "Shadow/Image"
CacheView
*image_view;
ChannelType
channel_mask;
Image
*border_image,
*clone_image,
*shadow_image;
MagickBooleanType
status;
PixelInfo
background_color;
RectangleInfo
border_info;
ssize_t
y;
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);
clone_image=CloneImage(image,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
return((Image *) NULL);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(clone_image,sRGBColorspace,exception);
(void) SetImageVirtualPixelMethod(clone_image,EdgeVirtualPixelMethod,
exception);
border_info.width=(size_t) floor(2.0*sigma+0.5);
border_info.height=(size_t) floor(2.0*sigma+0.5);
border_info.x=0;
border_info.y=0;
(void) QueryColorCompliance("none",AllCompliance,&clone_image->border_color,
exception);
clone_image->alpha_trait=BlendPixelTrait;
border_image=BorderImage(clone_image,&border_info,OverCompositeOp,exception);
clone_image=DestroyImage(clone_image);
if (border_image == (Image *) NULL)
return((Image *) NULL);
if (border_image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(border_image,OpaqueAlphaChannel,exception);
/*
Shadow image.
*/
status=MagickTrue;
background_color=border_image->background_color;
background_color.alpha_trait=BlendPixelTrait;
image_view=AcquireAuthenticCacheView(border_image,exception);
for (y=0; y < (ssize_t) border_image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(image_view,0,y,border_image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) border_image->columns; x++)
{
if (border_image->alpha_trait != UndefinedPixelTrait)
background_color.alpha=GetPixelAlpha(border_image,q)*alpha/100.0;
SetPixelViaPixelInfo(border_image,&background_color,q);
q+=GetPixelChannels(border_image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
{
border_image=DestroyImage(border_image);
return((Image *) NULL);
}
channel_mask=SetImageChannelMask(border_image,AlphaChannel);
shadow_image=BlurImage(border_image,0.0,sigma,exception);
border_image=DestroyImage(border_image);
if (shadow_image == (Image *) NULL)
return((Image *) NULL);
(void) SetPixelChannelMask(shadow_image,channel_mask);
if (shadow_image->page.width == 0)
shadow_image->page.width=shadow_image->columns;
if (shadow_image->page.height == 0)
shadow_image->page.height=shadow_image->rows;
shadow_image->page.width+=x_offset-(ssize_t) border_info.width;
shadow_image->page.height+=y_offset-(ssize_t) border_info.height;
shadow_image->page.x+=x_offset-(ssize_t) border_info.width;
shadow_image->page.y+=y_offset-(ssize_t) border_info.height;
return(shadow_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S k e t c h I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SketchImage() simulates a pencil sketch. We convolve the image with a
% Gaussian operator of the given radius and standard deviation (sigma). For
% reasonable results, radius should be larger than sigma. Use a radius of 0
% and SketchImage() selects a suitable radius for you. Angle gives the angle
% of the sketch.
%
% The format of the SketchImage method is:
%
% Image *SketchImage(const Image *image,const double radius,
% const double sigma,const double angle,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the Gaussian, in pixels, not counting the
% center pixel.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o angle: apply the effect along this angle.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SketchImage(const Image *image,const double radius,
const double sigma,const double angle,ExceptionInfo *exception)
{
CacheView
*random_view;
Image
*blend_image,
*blur_image,
*dodge_image,
*random_image,
*sketch_image;
MagickBooleanType
status;
RandomInfo
**magick_restrict random_info;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
/*
Sketch image.
*/
random_image=CloneImage(image,image->columns << 1,image->rows << 1,
MagickTrue,exception);
if (random_image == (Image *) NULL)
return((Image *) NULL);
status=MagickTrue;
random_info=AcquireRandomInfoThreadSet();
random_view=AcquireAuthenticCacheView(random_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(random_image,random_image,random_image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) random_image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(random_view,0,y,random_image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) random_image->columns; x++)
{
double
value;
register ssize_t
i;
if (GetPixelReadMask(random_image,q) == 0)
{
q+=GetPixelChannels(random_image);
continue;
}
value=GetPseudoRandomValue(random_info[id]);
for (i=0; i < (ssize_t) GetPixelChannels(random_image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=ClampToQuantum(QuantumRange*value);
}
q+=GetPixelChannels(random_image);
}
if (SyncCacheViewAuthenticPixels(random_view,exception) == MagickFalse)
status=MagickFalse;
}
random_view=DestroyCacheView(random_view);
random_info=DestroyRandomInfoThreadSet(random_info);
if (status == MagickFalse)
{
random_image=DestroyImage(random_image);
return(random_image);
}
blur_image=MotionBlurImage(random_image,radius,sigma,angle,exception);
random_image=DestroyImage(random_image);
if (blur_image == (Image *) NULL)
return((Image *) NULL);
dodge_image=EdgeImage(blur_image,radius,exception);
blur_image=DestroyImage(blur_image);
if (dodge_image == (Image *) NULL)
return((Image *) NULL);
(void) NormalizeImage(dodge_image,exception);
(void) NegateImage(dodge_image,MagickFalse,exception);
(void) TransformImage(&dodge_image,(char *) NULL,"50%",exception);
sketch_image=CloneImage(image,0,0,MagickTrue,exception);
if (sketch_image == (Image *) NULL)
{
dodge_image=DestroyImage(dodge_image);
return((Image *) NULL);
}
(void) CompositeImage(sketch_image,dodge_image,ColorDodgeCompositeOp,
MagickTrue,0,0,exception);
dodge_image=DestroyImage(dodge_image);
blend_image=CloneImage(image,0,0,MagickTrue,exception);
if (blend_image == (Image *) NULL)
{
sketch_image=DestroyImage(sketch_image);
return((Image *) NULL);
}
if (blend_image->alpha_trait != BlendPixelTrait)
(void) SetImageAlpha(blend_image,TransparentAlpha,exception);
(void) SetImageArtifact(blend_image,"compose:args","20x80");
(void) CompositeImage(sketch_image,blend_image,BlendCompositeOp,MagickTrue,
0,0,exception);
blend_image=DestroyImage(blend_image);
return(sketch_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S o l a r i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SolarizeImage() applies a special effect to the image, similar to the effect
% achieved in a photo darkroom by selectively exposing areas of photo
% sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a
% measure of the extent of the solarization.
%
% The format of the SolarizeImage method is:
%
% MagickBooleanType SolarizeImage(Image *image,const double threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: Define the extent of the solarization.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SolarizeImage(Image *image,
const double threshold,ExceptionInfo *exception)
{
#define SolarizeImageTag "Solarize/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
/*
Solarize colormap.
*/
for (i=0; i < (ssize_t) image->colors; i++)
{
if ((double) image->colormap[i].red > threshold)
image->colormap[i].red=QuantumRange-image->colormap[i].red;
if ((double) image->colormap[i].green > threshold)
image->colormap[i].green=QuantumRange-image->colormap[i].green;
if ((double) image->colormap[i].blue > threshold)
image->colormap[i].blue=QuantumRange-image->colormap[i].blue;
}
}
/*
Solarize image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if ((double) q[i] > threshold)
q[i]=QuantumRange-q[i];
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_SolarizeImage)
#endif
proceed=SetImageProgress(image,SolarizeImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S t e g a n o I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SteganoImage() hides a digital watermark within the image. Recover
% the hidden watermark later to prove that the authenticity of an image.
% Offset defines the start position within the image to hide the watermark.
%
% The format of the SteganoImage method is:
%
% Image *SteganoImage(const Image *image,Image *watermark,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o watermark: the watermark image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SteganoImage(const Image *image,const Image *watermark,
ExceptionInfo *exception)
{
#define GetBit(alpha,i) ((((size_t) (alpha) >> (size_t) (i)) & 0x01) != 0)
#define SetBit(alpha,i,set) (Quantum) ((set) != 0 ? (size_t) (alpha) \
| (one << (size_t) (i)) : (size_t) (alpha) & ~(one << (size_t) (i)))
#define SteganoImageTag "Stegano/Image"
CacheView
*stegano_view,
*watermark_view;
Image
*stegano_image;
int
c;
MagickBooleanType
status;
PixelInfo
pixel;
register Quantum
*q;
register ssize_t
x;
size_t
depth,
one;
ssize_t
i,
j,
k,
y;
/*
Initialize steganographic image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(watermark != (const Image *) NULL);
assert(watermark->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
one=1UL;
stegano_image=CloneImage(image,0,0,MagickTrue,exception);
if (stegano_image == (Image *) NULL)
return((Image *) NULL);
stegano_image->depth=MAGICKCORE_QUANTUM_DEPTH;
if (SetImageStorageClass(stegano_image,DirectClass,exception) == MagickFalse)
{
stegano_image=DestroyImage(stegano_image);
return((Image *) NULL);
}
/*
Hide watermark in low-order bits of image.
*/
c=0;
i=0;
j=0;
depth=stegano_image->depth;
k=stegano_image->offset;
status=MagickTrue;
watermark_view=AcquireVirtualCacheView(watermark,exception);
stegano_view=AcquireAuthenticCacheView(stegano_image,exception);
for (i=(ssize_t) depth-1; (i >= 0) && (j < (ssize_t) depth); i--)
{
for (y=0; (y < (ssize_t) watermark->rows) && (j < (ssize_t) depth); y++)
{
for (x=0; (x < (ssize_t) watermark->columns) && (j < (ssize_t) depth); x++)
{
ssize_t
offset;
(void) GetOneCacheViewVirtualPixelInfo(watermark_view,x,y,&pixel,
exception);
offset=k/(ssize_t) stegano_image->columns;
if (offset >= (ssize_t) stegano_image->rows)
break;
q=GetCacheViewAuthenticPixels(stegano_view,k % (ssize_t)
stegano_image->columns,k/(ssize_t) stegano_image->columns,1,1,
exception);
if (q == (Quantum *) NULL)
break;
switch (c)
{
case 0:
{
SetPixelRed(stegano_image,SetBit(GetPixelRed(stegano_image,q),j,
GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q);
break;
}
case 1:
{
SetPixelGreen(stegano_image,SetBit(GetPixelGreen(stegano_image,q),j,
GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q);
break;
}
case 2:
{
SetPixelBlue(stegano_image,SetBit(GetPixelBlue(stegano_image,q),j,
GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q);
break;
}
}
if (SyncCacheViewAuthenticPixels(stegano_view,exception) == MagickFalse)
break;
c++;
if (c == 3)
c=0;
k++;
if (k == (ssize_t) (stegano_image->columns*stegano_image->columns))
k=0;
if (k == stegano_image->offset)
j++;
}
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,SteganoImageTag,(MagickOffsetType)
(depth-i),depth);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
stegano_view=DestroyCacheView(stegano_view);
watermark_view=DestroyCacheView(watermark_view);
if (status == MagickFalse)
stegano_image=DestroyImage(stegano_image);
return(stegano_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S t e r e o A n a g l y p h I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% StereoAnaglyphImage() combines two images and produces a single image that
% is the composite of a left and right image of a stereo pair. Special
% red-green stereo glasses are required to view this effect.
%
% The format of the StereoAnaglyphImage method is:
%
% Image *StereoImage(const Image *left_image,const Image *right_image,
% ExceptionInfo *exception)
% Image *StereoAnaglyphImage(const Image *left_image,
% const Image *right_image,const ssize_t x_offset,const ssize_t y_offset,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o left_image: the left image.
%
% o right_image: the right image.
%
% o exception: return any errors or warnings in this structure.
%
% o x_offset: amount, in pixels, by which the left image is offset to the
% right of the right image.
%
% o y_offset: amount, in pixels, by which the left image is offset to the
% bottom of the right image.
%
%
*/
MagickExport Image *StereoImage(const Image *left_image,
const Image *right_image,ExceptionInfo *exception)
{
return(StereoAnaglyphImage(left_image,right_image,0,0,exception));
}
MagickExport Image *StereoAnaglyphImage(const Image *left_image,
const Image *right_image,const ssize_t x_offset,const ssize_t y_offset,
ExceptionInfo *exception)
{
#define StereoImageTag "Stereo/Image"
const Image
*image;
Image
*stereo_image;
MagickBooleanType
status;
ssize_t
y;
assert(left_image != (const Image *) NULL);
assert(left_image->signature == MagickCoreSignature);
if (left_image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
left_image->filename);
assert(right_image != (const Image *) NULL);
assert(right_image->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
assert(right_image != (const Image *) NULL);
image=left_image;
if ((left_image->columns != right_image->columns) ||
(left_image->rows != right_image->rows))
ThrowImageException(ImageError,"LeftAndRightImageSizesDiffer");
/*
Initialize stereo image attributes.
*/
stereo_image=CloneImage(left_image,left_image->columns,left_image->rows,
MagickTrue,exception);
if (stereo_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(stereo_image,DirectClass,exception) == MagickFalse)
{
stereo_image=DestroyImage(stereo_image);
return((Image *) NULL);
}
(void) SetImageColorspace(stereo_image,sRGBColorspace,exception);
/*
Copy left image to red channel and right image to blue channel.
*/
status=MagickTrue;
for (y=0; y < (ssize_t) stereo_image->rows; y++)
{
register const Quantum
*magick_restrict p,
*magick_restrict q;
register ssize_t
x;
register Quantum
*magick_restrict r;
p=GetVirtualPixels(left_image,-x_offset,y-y_offset,image->columns,1,
exception);
q=GetVirtualPixels(right_image,0,y,right_image->columns,1,exception);
r=QueueAuthenticPixels(stereo_image,0,y,stereo_image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL) ||
(r == (Quantum *) NULL))
break;
for (x=0; x < (ssize_t) stereo_image->columns; x++)
{
SetPixelRed(image,GetPixelRed(left_image,p),r);
SetPixelGreen(image,GetPixelGreen(right_image,q),r);
SetPixelBlue(image,GetPixelBlue(right_image,q),r);
if ((GetPixelAlphaTraits(stereo_image) & CopyPixelTrait) != 0)
SetPixelAlpha(image,(GetPixelAlpha(left_image,p)+
GetPixelAlpha(right_image,q))/2,r);
p+=GetPixelChannels(left_image);
q+=GetPixelChannels(right_image);
r+=GetPixelChannels(stereo_image);
}
if (SyncAuthenticPixels(stereo_image,exception) == MagickFalse)
break;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,StereoImageTag,(MagickOffsetType) y,
stereo_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
if (status == MagickFalse)
stereo_image=DestroyImage(stereo_image);
return(stereo_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S w i r l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SwirlImage() swirls the pixels about the center of the image, where
% degrees indicates the sweep of the arc through which each pixel is moved.
% You get a more dramatic effect as the degrees move from 1 to 360.
%
% The format of the SwirlImage method is:
%
% Image *SwirlImage(const Image *image,double degrees,
% const PixelInterpolateMethod method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o degrees: Define the tightness of the swirling effect.
%
% o method: the pixel interpolation method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SwirlImage(const Image *image,double degrees,
const PixelInterpolateMethod method,ExceptionInfo *exception)
{
#define SwirlImageTag "Swirl/Image"
CacheView
*image_view,
*interpolate_view,
*swirl_view;
Image
*swirl_image;
MagickBooleanType
status;
MagickOffsetType
progress;
double
radius;
PointInfo
center,
scale;
ssize_t
y;
/*
Initialize swirl image attributes.
*/
assert(image != (const 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);
swirl_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if (swirl_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(swirl_image,DirectClass,exception) == MagickFalse)
{
swirl_image=DestroyImage(swirl_image);
return((Image *) NULL);
}
if (swirl_image->background_color.alpha != OpaqueAlpha)
swirl_image->alpha_trait=BlendPixelTrait;
/*
Compute scaling factor.
*/
center.x=(double) image->columns/2.0;
center.y=(double) image->rows/2.0;
radius=MagickMax(center.x,center.y);
scale.x=1.0;
scale.y=1.0;
if (image->columns > image->rows)
scale.y=(double) image->columns/(double) image->rows;
else
if (image->columns < image->rows)
scale.x=(double) image->rows/(double) image->columns;
degrees=(double) DegreesToRadians(degrees);
/*
Swirl image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
interpolate_view=AcquireVirtualCacheView(image,exception);
swirl_view=AcquireAuthenticCacheView(swirl_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,swirl_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
distance;
PointInfo
delta;
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(swirl_view,0,y,swirl_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
delta.y=scale.y*(double) (y-center.y);
for (x=0; x < (ssize_t) image->columns; x++)
{
/*
Determine if the pixel is within an ellipse.
*/
if (GetPixelReadMask(image,p) == 0)
{
SetPixelBackgoundColor(swirl_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(swirl_image);
continue;
}
delta.x=scale.x*(double) (x-center.x);
distance=delta.x*delta.x+delta.y*delta.y;
if (distance >= (radius*radius))
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait swirl_traits=GetPixelChannelTraits(swirl_image,channel);
if ((traits == UndefinedPixelTrait) ||
(swirl_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(swirl_image,channel,p[i],q);
}
}
else
{
double
cosine,
factor,
sine;
/*
Swirl the pixel.
*/
factor=1.0-sqrt((double) distance)/radius;
sine=sin((double) (degrees*factor*factor));
cosine=cos((double) (degrees*factor*factor));
status=InterpolatePixelChannels(image,interpolate_view,swirl_image,
method,((cosine*delta.x-sine*delta.y)/scale.x+center.x),(double)
((sine*delta.x+cosine*delta.y)/scale.y+center.y),q,exception);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(swirl_image);
}
if (SyncCacheViewAuthenticPixels(swirl_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_SwirlImage)
#endif
proceed=SetImageProgress(image,SwirlImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
swirl_view=DestroyCacheView(swirl_view);
interpolate_view=DestroyCacheView(interpolate_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
swirl_image=DestroyImage(swirl_image);
return(swirl_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TintImage() applies a color vector to each pixel in the image. The length
% of the vector is 0 for black and white and at its maximum for the midtones.
% The vector weighting function is f(x)=(1-(4.0*((x-0.5)*(x-0.5))))
%
% The format of the TintImage method is:
%
% Image *TintImage(const Image *image,const char *blend,
% const PixelInfo *tint,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o blend: A color value used for tinting.
%
% o tint: A color value used for tinting.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *TintImage(const Image *image,const char *blend,
const PixelInfo *tint,ExceptionInfo *exception)
{
#define TintImageTag "Tint/Image"
CacheView
*image_view,
*tint_view;
double
intensity;
GeometryInfo
geometry_info;
Image
*tint_image;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
color_vector;
MagickStatusType
flags;
ssize_t
y;
/*
Allocate tint image.
*/
assert(image != (const 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);
tint_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if (tint_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(tint_image,DirectClass,exception) == MagickFalse)
{
tint_image=DestroyImage(tint_image);
return((Image *) NULL);
}
if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
(IsPixelInfoGray(tint) == MagickFalse))
(void) SetImageColorspace(tint_image,sRGBColorspace,exception);
if (blend == (const char *) NULL)
return(tint_image);
/*
Determine RGB values of the color.
*/
GetPixelInfo(image,&color_vector);
flags=ParseGeometry(blend,&geometry_info);
color_vector.red=geometry_info.rho;
color_vector.green=geometry_info.rho;
color_vector.blue=geometry_info.rho;
color_vector.alpha=(MagickRealType) OpaqueAlpha;
if ((flags & SigmaValue) != 0)
color_vector.green=geometry_info.sigma;
if ((flags & XiValue) != 0)
color_vector.blue=geometry_info.xi;
if ((flags & PsiValue) != 0)
color_vector.alpha=geometry_info.psi;
if (image->colorspace == CMYKColorspace)
{
color_vector.black=geometry_info.rho;
if ((flags & PsiValue) != 0)
color_vector.black=geometry_info.psi;
if ((flags & ChiValue) != 0)
color_vector.alpha=geometry_info.chi;
}
intensity=(double) GetPixelInfoIntensity((const Image *) NULL,tint);
color_vector.red=(double) (color_vector.red*tint->red/100.0-intensity);
color_vector.green=(double) (color_vector.green*tint->green/100.0-intensity);
color_vector.blue=(double) (color_vector.blue*tint->blue/100.0-intensity);
color_vector.black=(double) (color_vector.black*tint->black/100.0-intensity);
color_vector.alpha=(double) (color_vector.alpha*tint->alpha/100.0-intensity);
/*
Tint image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
tint_view=AcquireAuthenticCacheView(tint_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,tint_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(tint_view,0,y,tint_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
PixelInfo
pixel;
double
weight;
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait tint_traits=GetPixelChannelTraits(tint_image,channel);
if ((traits == UndefinedPixelTrait) ||
(tint_traits == UndefinedPixelTrait))
continue;
if (((tint_traits & CopyPixelTrait) != 0) ||
(GetPixelReadMask(image,p) == 0))
{
SetPixelChannel(tint_image,channel,p[i],q);
continue;
}
}
GetPixelInfo(image,&pixel);
weight=QuantumScale*GetPixelRed(image,p)-0.5;
pixel.red=(double) GetPixelRed(image,p)+color_vector.red*(1.0-(4.0*
(weight*weight)));
weight=QuantumScale*GetPixelGreen(image,p)-0.5;
pixel.green=(double) GetPixelGreen(image,p)+color_vector.green*(1.0-(4.0*
(weight*weight)));
weight=QuantumScale*GetPixelBlue(image,p)-0.5;
pixel.blue=(double) GetPixelBlue(image,p)+color_vector.blue*(1.0-(4.0*
(weight*weight)));
weight=QuantumScale*GetPixelBlack(image,p)-0.5;
pixel.black=(double) GetPixelBlack(image,p)+color_vector.black*(1.0-(4.0*
(weight*weight)));
SetPixelViaPixelInfo(tint_image,&pixel,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(tint_image);
}
if (SyncCacheViewAuthenticPixels(tint_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_TintImage)
#endif
proceed=SetImageProgress(image,TintImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
tint_view=DestroyCacheView(tint_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
tint_image=DestroyImage(tint_image);
return(tint_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% V i g n e t t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% VignetteImage() softens the edges of the image in vignette style.
%
% The format of the VignetteImage method is:
%
% Image *VignetteImage(const Image *image,const double radius,
% const double sigma,const ssize_t x,const ssize_t y,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the pixel neighborhood.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o x, y: Define the x and y ellipse offset.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *VignetteImage(const Image *image,const double radius,
const double sigma,const ssize_t x,const ssize_t y,ExceptionInfo *exception)
{
char
ellipse[MagickPathExtent];
DrawInfo
*draw_info;
Image
*canvas_image,
*blur_image,
*oval_image,
*vignette_image;
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);
canvas_image=CloneImage(image,0,0,MagickTrue,exception);
if (canvas_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(canvas_image,DirectClass,exception) == MagickFalse)
{
canvas_image=DestroyImage(canvas_image);
return((Image *) NULL);
}
canvas_image->alpha_trait=BlendPixelTrait;
oval_image=CloneImage(canvas_image,canvas_image->columns,canvas_image->rows,
MagickTrue,exception);
if (oval_image == (Image *) NULL)
{
canvas_image=DestroyImage(canvas_image);
return((Image *) NULL);
}
(void) QueryColorCompliance("#000000",AllCompliance,
&oval_image->background_color,exception);
(void) SetImageBackgroundColor(oval_image,exception);
draw_info=CloneDrawInfo((const ImageInfo *) NULL,(const DrawInfo *) NULL);
(void) QueryColorCompliance("#ffffff",AllCompliance,&draw_info->fill,
exception);
(void) QueryColorCompliance("#ffffff",AllCompliance,&draw_info->stroke,
exception);
(void) FormatLocaleString(ellipse,MagickPathExtent,"ellipse %g,%g,%g,%g,"
"0.0,360.0",image->columns/2.0,image->rows/2.0,image->columns/2.0-x,
image->rows/2.0-y);
draw_info->primitive=AcquireString(ellipse);
(void) DrawImage(oval_image,draw_info,exception);
draw_info=DestroyDrawInfo(draw_info);
blur_image=BlurImage(oval_image,radius,sigma,exception);
oval_image=DestroyImage(oval_image);
if (blur_image == (Image *) NULL)
{
canvas_image=DestroyImage(canvas_image);
return((Image *) NULL);
}
blur_image->alpha_trait=UndefinedPixelTrait;
(void) CompositeImage(canvas_image,blur_image,IntensityCompositeOp,MagickTrue,
0,0,exception);
blur_image=DestroyImage(blur_image);
vignette_image=MergeImageLayers(canvas_image,FlattenLayer,exception);
canvas_image=DestroyImage(canvas_image);
if (vignette_image != (Image *) NULL)
(void) TransformImageColorspace(vignette_image,image->colorspace,exception);
return(vignette_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W a v e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WaveImage() creates a "ripple" effect in the image by shifting the pixels
% vertically along a sine wave whose amplitude and wavelength is specified
% by the given parameters.
%
% The format of the WaveImage method is:
%
% Image *WaveImage(const Image *image,const double amplitude,
% const double wave_length,const PixelInterpolateMethod method,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o amplitude, wave_length: Define the amplitude and wave length of the
% sine wave.
%
% o interpolate: the pixel interpolation method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *WaveImage(const Image *image,const double amplitude,
const double wave_length,const PixelInterpolateMethod method,
ExceptionInfo *exception)
{
#define WaveImageTag "Wave/Image"
CacheView
*image_view,
*wave_view;
Image
*wave_image;
MagickBooleanType
status;
MagickOffsetType
progress;
double
*sine_map;
register ssize_t
i;
ssize_t
y;
/*
Initialize wave image attributes.
*/
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);
wave_image=CloneImage(image,image->columns,(size_t) (image->rows+2.0*
fabs(amplitude)),MagickTrue,exception);
if (wave_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(wave_image,DirectClass,exception) == MagickFalse)
{
wave_image=DestroyImage(wave_image);
return((Image *) NULL);
}
if (wave_image->background_color.alpha != OpaqueAlpha)
wave_image->alpha_trait=BlendPixelTrait;
/*
Allocate sine map.
*/
sine_map=(double *) AcquireQuantumMemory((size_t) wave_image->columns,
sizeof(*sine_map));
if (sine_map == (double *) NULL)
{
wave_image=DestroyImage(wave_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t) wave_image->columns; i++)
sine_map[i]=fabs(amplitude)+amplitude*sin((double) ((2.0*MagickPI*i)/
wave_length));
/*
Wave image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
wave_view=AcquireAuthenticCacheView(wave_image,exception);
(void) SetCacheViewVirtualPixelMethod(image_view,
BackgroundVirtualPixelMethod);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,wave_image,wave_image->rows,1)
#endif
for (y=0; y < (ssize_t) wave_image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) wave_image->columns; x++)
{
status=InterpolatePixelChannels(image,image_view,wave_image,method,
(double) x,(double) (y-sine_map[x]),q,exception);
q+=GetPixelChannels(wave_image);
}
if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_WaveImage)
#endif
proceed=SetImageProgress(image,WaveImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
wave_view=DestroyCacheView(wave_view);
image_view=DestroyCacheView(image_view);
sine_map=(double *) RelinquishMagickMemory(sine_map);
if (status == MagickFalse)
wave_image=DestroyImage(wave_image);
return(wave_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W a v e l e t D e n o i s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WaveletDenoiseImage() removes noise from the image using a wavelet
% transform. The wavelet transform is a fast hierarchical scheme for
% processing an image using a set of consecutive lowpass and high_pass filters,
% followed by a decimation. This results in a decomposition into different
% scales which can be regarded as different “frequency bands”, determined by
% the mother wavelet. Adapted from dcraw.c by David Coffin.
%
% The format of the WaveletDenoiseImage method is:
%
% Image *WaveletDenoiseImage(const Image *image,const double threshold,
% const double softness,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: set the threshold for smoothing.
%
% o softness: attenuate the smoothing threshold.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline void HatTransform(const float *magick_restrict pixels,
const size_t stride,const size_t extent,const size_t scale,float *kernel)
{
const float
*magick_restrict p,
*magick_restrict q,
*magick_restrict r;
register ssize_t
i;
p=pixels;
q=pixels+scale*stride;
r=pixels+scale*stride;
for (i=0; i < (ssize_t) scale; i++)
{
kernel[i]=0.25f*(*p+(*p)+(*q)+(*r));
p+=stride;
q-=stride;
r+=stride;
}
for ( ; i < (ssize_t) (extent-scale); i++)
{
kernel[i]=0.25f*(2.0f*(*p)+*(p-scale*stride)+*(p+scale*stride));
p+=stride;
}
q=p-scale*stride;
r=pixels+stride*(extent-2);
for ( ; i < (ssize_t) extent; i++)
{
kernel[i]=0.25f*(*p+(*p)+(*q)+(*r));
p+=stride;
q+=stride;
r-=stride;
}
}
MagickExport Image *WaveletDenoiseImage(const Image *image,
const double threshold,const double softness,ExceptionInfo *exception)
{
CacheView
*image_view,
*noise_view;
float
*kernel,
*pixels;
Image
*noise_image;
MagickBooleanType
status;
MagickSizeType
number_pixels;
MemoryInfo
*pixels_info;
ssize_t
channel;
static const float
noise_levels[] = { 0.8002f, 0.2735f, 0.1202f, 0.0585f, 0.0291f, 0.0152f,
0.0080f, 0.0044f };
/*
Initialize noise image attributes.
*/
assert(image != (const 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);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
noise_image=AccelerateWaveletDenoiseImage(image,threshold,exception);
if (noise_image != (Image *) NULL)
return(noise_image);
#endif
noise_image=CloneImage(image,0,0,MagickTrue,exception);
if (noise_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(noise_image,DirectClass,exception) == MagickFalse)
{
noise_image=DestroyImage(noise_image);
return((Image *) NULL);
}
if (AcquireMagickResource(WidthResource,4*image->columns) == MagickFalse)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
pixels_info=AcquireVirtualMemory(3*image->columns,image->rows*
sizeof(*pixels));
kernel=(float *) AcquireQuantumMemory(MagickMax(image->rows,image->columns)+1,
GetOpenMPMaximumThreads()*sizeof(*kernel));
if ((pixels_info == (MemoryInfo *) NULL) || (kernel == (float *) NULL))
{
if (kernel != (float *) NULL)
kernel=(float *) RelinquishMagickMemory(kernel);
if (pixels_info != (MemoryInfo *) NULL)
pixels_info=RelinquishVirtualMemory(pixels_info);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(float *) GetVirtualMemoryBlob(pixels_info);
status=MagickTrue;
number_pixels=(MagickSizeType) image->columns*image->rows;
image_view=AcquireAuthenticCacheView(image,exception);
noise_view=AcquireAuthenticCacheView(noise_image,exception);
for (channel=0; channel < (ssize_t) GetPixelChannels(image); channel++)
{
register ssize_t
i;
size_t
high_pass,
low_pass;
ssize_t
level,
y;
PixelChannel
pixel_channel;
PixelTrait
traits;
if (status == MagickFalse)
continue;
traits=GetPixelChannelTraits(image,(PixelChannel) channel);
if (traits == UndefinedPixelTrait)
continue;
pixel_channel=GetPixelChannelChannel(image,channel);
if ((pixel_channel != RedPixelChannel) &&
(pixel_channel != GreenPixelChannel) &&
(pixel_channel != BluePixelChannel))
continue;
/*
Copy channel from image to wavelet pixel array.
*/
i=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
ssize_t
x;
p=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixels[i++]=(float) p[channel];
p+=GetPixelChannels(image);
}
}
/*
Low pass filter outputs are called approximation kernel & high pass
filters are referred to as detail kernel. The detail kernel
have high values in the noisy parts of the signal.
*/
high_pass=0;
for (level=0; level < 5; level++)
{
double
magnitude;
ssize_t
x,
y;
low_pass=(size_t) (number_pixels*((level & 0x01)+1));
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,1) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register float
*magick_restrict p,
*magick_restrict q;
register ssize_t
x;
p=kernel+id*image->columns;
q=pixels+y*image->columns;
HatTransform(q+high_pass,1,image->columns,(size_t) (1 << level),p);
q+=low_pass;
for (x=0; x < (ssize_t) image->columns; x++)
*q++=(*p++);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,1) \
magick_threads(image,image,image->columns,1)
#endif
for (x=0; x < (ssize_t) image->columns; x++)
{
const int
id = GetOpenMPThreadId();
register float
*magick_restrict p,
*magick_restrict q;
register ssize_t
y;
p=kernel+id*image->rows;
q=pixels+x+low_pass;
HatTransform(q,image->columns,image->rows,(size_t) (1 << level),p);
for (y=0; y < (ssize_t) image->rows; y++)
{
*q=(*p++);
q+=image->columns;
}
}
/*
To threshold, each coefficient is compared to a threshold value and
attenuated / shrunk by some factor.
*/
magnitude=threshold*noise_levels[level];
for (i=0; i < (ssize_t) number_pixels; ++i)
{
pixels[high_pass+i]-=pixels[low_pass+i];
if (pixels[high_pass+i] < -magnitude)
pixels[high_pass+i]+=magnitude-softness*magnitude;
else
if (pixels[high_pass+i] > magnitude)
pixels[high_pass+i]-=magnitude-softness*magnitude;
else
pixels[high_pass+i]*=softness;
if (high_pass != 0)
pixels[i]+=pixels[high_pass+i];
}
high_pass=low_pass;
}
/*
Reconstruct image from the thresholded wavelet kernel.
*/
i=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register Quantum
*magick_restrict q;
register ssize_t
x;
ssize_t
offset;
q=GetCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
break;
}
offset=GetPixelChannelOffset(noise_image,pixel_channel);
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickRealType
pixel;
pixel=(MagickRealType) pixels[i]+pixels[low_pass+i];
q[offset]=ClampToQuantum(pixel);
i++;
q+=GetPixelChannels(noise_image);
}
sync=SyncCacheViewAuthenticPixels(noise_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,AddNoiseImageTag,(MagickOffsetType)
channel,GetPixelChannels(image));
if (proceed == MagickFalse)
status=MagickFalse;
}
}
noise_view=DestroyCacheView(noise_view);
image_view=DestroyCacheView(image_view);
kernel=(float *) RelinquishMagickMemory(kernel);
pixels_info=RelinquishVirtualMemory(pixels_info);
if (status == MagickFalse)
noise_image=DestroyImage(noise_image);
return(noise_image);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5409_0 |
crossvul-cpp_data_good_5025_0 | /*
* Copyright (C) 2003-2008 Takahiro Hirofuchi
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
#include <asm/byteorder.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/stat.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <net/sock.h>
#include "usbip_common.h"
#define DRIVER_AUTHOR "Takahiro Hirofuchi <hirofuchi@users.sourceforge.net>"
#define DRIVER_DESC "USB/IP Core"
#ifdef CONFIG_USBIP_DEBUG
unsigned long usbip_debug_flag = 0xffffffff;
#else
unsigned long usbip_debug_flag;
#endif
EXPORT_SYMBOL_GPL(usbip_debug_flag);
module_param(usbip_debug_flag, ulong, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(usbip_debug_flag, "debug flags (defined in usbip_common.h)");
/* FIXME */
struct device_attribute dev_attr_usbip_debug;
EXPORT_SYMBOL_GPL(dev_attr_usbip_debug);
static ssize_t usbip_debug_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%lx\n", usbip_debug_flag);
}
static ssize_t usbip_debug_store(struct device *dev,
struct device_attribute *attr, const char *buf,
size_t count)
{
if (sscanf(buf, "%lx", &usbip_debug_flag) != 1)
return -EINVAL;
return count;
}
DEVICE_ATTR_RW(usbip_debug);
static void usbip_dump_buffer(char *buff, int bufflen)
{
print_hex_dump(KERN_DEBUG, "usbip-core", DUMP_PREFIX_OFFSET, 16, 4,
buff, bufflen, false);
}
static void usbip_dump_pipe(unsigned int p)
{
unsigned char type = usb_pipetype(p);
unsigned char ep = usb_pipeendpoint(p);
unsigned char dev = usb_pipedevice(p);
unsigned char dir = usb_pipein(p);
pr_debug("dev(%d) ep(%d) [%s] ", dev, ep, dir ? "IN" : "OUT");
switch (type) {
case PIPE_ISOCHRONOUS:
pr_debug("ISO\n");
break;
case PIPE_INTERRUPT:
pr_debug("INT\n");
break;
case PIPE_CONTROL:
pr_debug("CTRL\n");
break;
case PIPE_BULK:
pr_debug("BULK\n");
break;
default:
pr_debug("ERR\n");
break;
}
}
static void usbip_dump_usb_device(struct usb_device *udev)
{
struct device *dev = &udev->dev;
int i;
dev_dbg(dev, " devnum(%d) devpath(%s) usb speed(%s)",
udev->devnum, udev->devpath, usb_speed_string(udev->speed));
pr_debug("tt %p, ttport %d\n", udev->tt, udev->ttport);
dev_dbg(dev, " ");
for (i = 0; i < 16; i++)
pr_debug(" %2u", i);
pr_debug("\n");
dev_dbg(dev, " toggle0(IN) :");
for (i = 0; i < 16; i++)
pr_debug(" %2u", (udev->toggle[0] & (1 << i)) ? 1 : 0);
pr_debug("\n");
dev_dbg(dev, " toggle1(OUT):");
for (i = 0; i < 16; i++)
pr_debug(" %2u", (udev->toggle[1] & (1 << i)) ? 1 : 0);
pr_debug("\n");
dev_dbg(dev, " epmaxp_in :");
for (i = 0; i < 16; i++) {
if (udev->ep_in[i])
pr_debug(" %2u",
le16_to_cpu(udev->ep_in[i]->desc.wMaxPacketSize));
}
pr_debug("\n");
dev_dbg(dev, " epmaxp_out :");
for (i = 0; i < 16; i++) {
if (udev->ep_out[i])
pr_debug(" %2u",
le16_to_cpu(udev->ep_out[i]->desc.wMaxPacketSize));
}
pr_debug("\n");
dev_dbg(dev, "parent %p, bus %p\n", udev->parent, udev->bus);
dev_dbg(dev,
"descriptor %p, config %p, actconfig %p, rawdescriptors %p\n",
&udev->descriptor, udev->config,
udev->actconfig, udev->rawdescriptors);
dev_dbg(dev, "have_langid %d, string_langid %d\n",
udev->have_langid, udev->string_langid);
dev_dbg(dev, "maxchild %d\n", udev->maxchild);
}
static void usbip_dump_request_type(__u8 rt)
{
switch (rt & USB_RECIP_MASK) {
case USB_RECIP_DEVICE:
pr_debug("DEVICE");
break;
case USB_RECIP_INTERFACE:
pr_debug("INTERF");
break;
case USB_RECIP_ENDPOINT:
pr_debug("ENDPOI");
break;
case USB_RECIP_OTHER:
pr_debug("OTHER ");
break;
default:
pr_debug("------");
break;
}
}
static void usbip_dump_usb_ctrlrequest(struct usb_ctrlrequest *cmd)
{
if (!cmd) {
pr_debug(" : null pointer\n");
return;
}
pr_debug(" ");
pr_debug("bRequestType(%02X) bRequest(%02X) wValue(%04X) wIndex(%04X) wLength(%04X) ",
cmd->bRequestType, cmd->bRequest,
cmd->wValue, cmd->wIndex, cmd->wLength);
pr_debug("\n ");
if ((cmd->bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD) {
pr_debug("STANDARD ");
switch (cmd->bRequest) {
case USB_REQ_GET_STATUS:
pr_debug("GET_STATUS\n");
break;
case USB_REQ_CLEAR_FEATURE:
pr_debug("CLEAR_FEAT\n");
break;
case USB_REQ_SET_FEATURE:
pr_debug("SET_FEAT\n");
break;
case USB_REQ_SET_ADDRESS:
pr_debug("SET_ADDRRS\n");
break;
case USB_REQ_GET_DESCRIPTOR:
pr_debug("GET_DESCRI\n");
break;
case USB_REQ_SET_DESCRIPTOR:
pr_debug("SET_DESCRI\n");
break;
case USB_REQ_GET_CONFIGURATION:
pr_debug("GET_CONFIG\n");
break;
case USB_REQ_SET_CONFIGURATION:
pr_debug("SET_CONFIG\n");
break;
case USB_REQ_GET_INTERFACE:
pr_debug("GET_INTERF\n");
break;
case USB_REQ_SET_INTERFACE:
pr_debug("SET_INTERF\n");
break;
case USB_REQ_SYNCH_FRAME:
pr_debug("SYNC_FRAME\n");
break;
default:
pr_debug("REQ(%02X)\n", cmd->bRequest);
break;
}
usbip_dump_request_type(cmd->bRequestType);
} else if ((cmd->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS) {
pr_debug("CLASS\n");
} else if ((cmd->bRequestType & USB_TYPE_MASK) == USB_TYPE_VENDOR) {
pr_debug("VENDOR\n");
} else if ((cmd->bRequestType & USB_TYPE_MASK) == USB_TYPE_RESERVED) {
pr_debug("RESERVED\n");
}
}
void usbip_dump_urb(struct urb *urb)
{
struct device *dev;
if (!urb) {
pr_debug("urb: null pointer!!\n");
return;
}
if (!urb->dev) {
pr_debug("urb->dev: null pointer!!\n");
return;
}
dev = &urb->dev->dev;
dev_dbg(dev, " urb :%p\n", urb);
dev_dbg(dev, " dev :%p\n", urb->dev);
usbip_dump_usb_device(urb->dev);
dev_dbg(dev, " pipe :%08x ", urb->pipe);
usbip_dump_pipe(urb->pipe);
dev_dbg(dev, " status :%d\n", urb->status);
dev_dbg(dev, " transfer_flags :%08X\n", urb->transfer_flags);
dev_dbg(dev, " transfer_buffer :%p\n", urb->transfer_buffer);
dev_dbg(dev, " transfer_buffer_length:%d\n",
urb->transfer_buffer_length);
dev_dbg(dev, " actual_length :%d\n", urb->actual_length);
dev_dbg(dev, " setup_packet :%p\n", urb->setup_packet);
if (urb->setup_packet && usb_pipetype(urb->pipe) == PIPE_CONTROL)
usbip_dump_usb_ctrlrequest(
(struct usb_ctrlrequest *)urb->setup_packet);
dev_dbg(dev, " start_frame :%d\n", urb->start_frame);
dev_dbg(dev, " number_of_packets :%d\n", urb->number_of_packets);
dev_dbg(dev, " interval :%d\n", urb->interval);
dev_dbg(dev, " error_count :%d\n", urb->error_count);
dev_dbg(dev, " context :%p\n", urb->context);
dev_dbg(dev, " complete :%p\n", urb->complete);
}
EXPORT_SYMBOL_GPL(usbip_dump_urb);
void usbip_dump_header(struct usbip_header *pdu)
{
pr_debug("BASE: cmd %u seq %u devid %u dir %u ep %u\n",
pdu->base.command,
pdu->base.seqnum,
pdu->base.devid,
pdu->base.direction,
pdu->base.ep);
switch (pdu->base.command) {
case USBIP_CMD_SUBMIT:
pr_debug("USBIP_CMD_SUBMIT: x_flags %u x_len %u sf %u #p %d iv %d\n",
pdu->u.cmd_submit.transfer_flags,
pdu->u.cmd_submit.transfer_buffer_length,
pdu->u.cmd_submit.start_frame,
pdu->u.cmd_submit.number_of_packets,
pdu->u.cmd_submit.interval);
break;
case USBIP_CMD_UNLINK:
pr_debug("USBIP_CMD_UNLINK: seq %u\n",
pdu->u.cmd_unlink.seqnum);
break;
case USBIP_RET_SUBMIT:
pr_debug("USBIP_RET_SUBMIT: st %d al %u sf %d #p %d ec %d\n",
pdu->u.ret_submit.status,
pdu->u.ret_submit.actual_length,
pdu->u.ret_submit.start_frame,
pdu->u.ret_submit.number_of_packets,
pdu->u.ret_submit.error_count);
break;
case USBIP_RET_UNLINK:
pr_debug("USBIP_RET_UNLINK: status %d\n",
pdu->u.ret_unlink.status);
break;
default:
/* NOT REACHED */
pr_err("unknown command\n");
break;
}
}
EXPORT_SYMBOL_GPL(usbip_dump_header);
/* Receive data over TCP/IP. */
int usbip_recv(struct socket *sock, void *buf, int size)
{
int result;
struct msghdr msg;
struct kvec iov;
int total = 0;
/* for blocks of if (usbip_dbg_flag_xmit) */
char *bp = buf;
int osize = size;
usbip_dbg_xmit("enter\n");
if (!sock || !buf || !size) {
pr_err("invalid arg, sock %p buff %p size %d\n", sock, buf,
size);
return -EINVAL;
}
do {
sock->sk->sk_allocation = GFP_NOIO;
iov.iov_base = buf;
iov.iov_len = size;
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_flags = MSG_NOSIGNAL;
result = kernel_recvmsg(sock, &msg, &iov, 1, size, MSG_WAITALL);
if (result <= 0) {
pr_debug("receive sock %p buf %p size %u ret %d total %d\n",
sock, buf, size, result, total);
goto err;
}
size -= result;
buf += result;
total += result;
} while (size > 0);
if (usbip_dbg_flag_xmit) {
if (!in_interrupt())
pr_debug("%-10s:", current->comm);
else
pr_debug("interrupt :");
pr_debug("receiving....\n");
usbip_dump_buffer(bp, osize);
pr_debug("received, osize %d ret %d size %d total %d\n",
osize, result, size, total);
}
return total;
err:
return result;
}
EXPORT_SYMBOL_GPL(usbip_recv);
/* there may be more cases to tweak the flags. */
static unsigned int tweak_transfer_flags(unsigned int flags)
{
flags &= ~URB_NO_TRANSFER_DMA_MAP;
return flags;
}
static void usbip_pack_cmd_submit(struct usbip_header *pdu, struct urb *urb,
int pack)
{
struct usbip_header_cmd_submit *spdu = &pdu->u.cmd_submit;
/*
* Some members are not still implemented in usbip. I hope this issue
* will be discussed when usbip is ported to other operating systems.
*/
if (pack) {
spdu->transfer_flags =
tweak_transfer_flags(urb->transfer_flags);
spdu->transfer_buffer_length = urb->transfer_buffer_length;
spdu->start_frame = urb->start_frame;
spdu->number_of_packets = urb->number_of_packets;
spdu->interval = urb->interval;
} else {
urb->transfer_flags = spdu->transfer_flags;
urb->transfer_buffer_length = spdu->transfer_buffer_length;
urb->start_frame = spdu->start_frame;
urb->number_of_packets = spdu->number_of_packets;
urb->interval = spdu->interval;
}
}
static void usbip_pack_ret_submit(struct usbip_header *pdu, struct urb *urb,
int pack)
{
struct usbip_header_ret_submit *rpdu = &pdu->u.ret_submit;
if (pack) {
rpdu->status = urb->status;
rpdu->actual_length = urb->actual_length;
rpdu->start_frame = urb->start_frame;
rpdu->number_of_packets = urb->number_of_packets;
rpdu->error_count = urb->error_count;
} else {
urb->status = rpdu->status;
urb->actual_length = rpdu->actual_length;
urb->start_frame = rpdu->start_frame;
urb->number_of_packets = rpdu->number_of_packets;
urb->error_count = rpdu->error_count;
}
}
void usbip_pack_pdu(struct usbip_header *pdu, struct urb *urb, int cmd,
int pack)
{
switch (cmd) {
case USBIP_CMD_SUBMIT:
usbip_pack_cmd_submit(pdu, urb, pack);
break;
case USBIP_RET_SUBMIT:
usbip_pack_ret_submit(pdu, urb, pack);
break;
default:
/* NOT REACHED */
pr_err("unknown command\n");
break;
}
}
EXPORT_SYMBOL_GPL(usbip_pack_pdu);
static void correct_endian_basic(struct usbip_header_basic *base, int send)
{
if (send) {
base->command = cpu_to_be32(base->command);
base->seqnum = cpu_to_be32(base->seqnum);
base->devid = cpu_to_be32(base->devid);
base->direction = cpu_to_be32(base->direction);
base->ep = cpu_to_be32(base->ep);
} else {
base->command = be32_to_cpu(base->command);
base->seqnum = be32_to_cpu(base->seqnum);
base->devid = be32_to_cpu(base->devid);
base->direction = be32_to_cpu(base->direction);
base->ep = be32_to_cpu(base->ep);
}
}
static void correct_endian_cmd_submit(struct usbip_header_cmd_submit *pdu,
int send)
{
if (send) {
pdu->transfer_flags = cpu_to_be32(pdu->transfer_flags);
cpu_to_be32s(&pdu->transfer_buffer_length);
cpu_to_be32s(&pdu->start_frame);
cpu_to_be32s(&pdu->number_of_packets);
cpu_to_be32s(&pdu->interval);
} else {
pdu->transfer_flags = be32_to_cpu(pdu->transfer_flags);
be32_to_cpus(&pdu->transfer_buffer_length);
be32_to_cpus(&pdu->start_frame);
be32_to_cpus(&pdu->number_of_packets);
be32_to_cpus(&pdu->interval);
}
}
static void correct_endian_ret_submit(struct usbip_header_ret_submit *pdu,
int send)
{
if (send) {
cpu_to_be32s(&pdu->status);
cpu_to_be32s(&pdu->actual_length);
cpu_to_be32s(&pdu->start_frame);
cpu_to_be32s(&pdu->number_of_packets);
cpu_to_be32s(&pdu->error_count);
} else {
be32_to_cpus(&pdu->status);
be32_to_cpus(&pdu->actual_length);
be32_to_cpus(&pdu->start_frame);
be32_to_cpus(&pdu->number_of_packets);
be32_to_cpus(&pdu->error_count);
}
}
static void correct_endian_cmd_unlink(struct usbip_header_cmd_unlink *pdu,
int send)
{
if (send)
pdu->seqnum = cpu_to_be32(pdu->seqnum);
else
pdu->seqnum = be32_to_cpu(pdu->seqnum);
}
static void correct_endian_ret_unlink(struct usbip_header_ret_unlink *pdu,
int send)
{
if (send)
cpu_to_be32s(&pdu->status);
else
be32_to_cpus(&pdu->status);
}
void usbip_header_correct_endian(struct usbip_header *pdu, int send)
{
__u32 cmd = 0;
if (send)
cmd = pdu->base.command;
correct_endian_basic(&pdu->base, send);
if (!send)
cmd = pdu->base.command;
switch (cmd) {
case USBIP_CMD_SUBMIT:
correct_endian_cmd_submit(&pdu->u.cmd_submit, send);
break;
case USBIP_RET_SUBMIT:
correct_endian_ret_submit(&pdu->u.ret_submit, send);
break;
case USBIP_CMD_UNLINK:
correct_endian_cmd_unlink(&pdu->u.cmd_unlink, send);
break;
case USBIP_RET_UNLINK:
correct_endian_ret_unlink(&pdu->u.ret_unlink, send);
break;
default:
/* NOT REACHED */
pr_err("unknown command\n");
break;
}
}
EXPORT_SYMBOL_GPL(usbip_header_correct_endian);
static void usbip_iso_packet_correct_endian(
struct usbip_iso_packet_descriptor *iso, int send)
{
/* does not need all members. but copy all simply. */
if (send) {
iso->offset = cpu_to_be32(iso->offset);
iso->length = cpu_to_be32(iso->length);
iso->status = cpu_to_be32(iso->status);
iso->actual_length = cpu_to_be32(iso->actual_length);
} else {
iso->offset = be32_to_cpu(iso->offset);
iso->length = be32_to_cpu(iso->length);
iso->status = be32_to_cpu(iso->status);
iso->actual_length = be32_to_cpu(iso->actual_length);
}
}
static void usbip_pack_iso(struct usbip_iso_packet_descriptor *iso,
struct usb_iso_packet_descriptor *uiso, int pack)
{
if (pack) {
iso->offset = uiso->offset;
iso->length = uiso->length;
iso->status = uiso->status;
iso->actual_length = uiso->actual_length;
} else {
uiso->offset = iso->offset;
uiso->length = iso->length;
uiso->status = iso->status;
uiso->actual_length = iso->actual_length;
}
}
/* must free buffer */
struct usbip_iso_packet_descriptor*
usbip_alloc_iso_desc_pdu(struct urb *urb, ssize_t *bufflen)
{
struct usbip_iso_packet_descriptor *iso;
int np = urb->number_of_packets;
ssize_t size = np * sizeof(*iso);
int i;
iso = kzalloc(size, GFP_KERNEL);
if (!iso)
return NULL;
for (i = 0; i < np; i++) {
usbip_pack_iso(&iso[i], &urb->iso_frame_desc[i], 1);
usbip_iso_packet_correct_endian(&iso[i], 1);
}
*bufflen = size;
return iso;
}
EXPORT_SYMBOL_GPL(usbip_alloc_iso_desc_pdu);
/* some members of urb must be substituted before. */
int usbip_recv_iso(struct usbip_device *ud, struct urb *urb)
{
void *buff;
struct usbip_iso_packet_descriptor *iso;
int np = urb->number_of_packets;
int size = np * sizeof(*iso);
int i;
int ret;
int total_length = 0;
if (!usb_pipeisoc(urb->pipe))
return 0;
/* my Bluetooth dongle gets ISO URBs which are np = 0 */
if (np == 0)
return 0;
buff = kzalloc(size, GFP_KERNEL);
if (!buff)
return -ENOMEM;
ret = usbip_recv(ud->tcp_socket, buff, size);
if (ret != size) {
dev_err(&urb->dev->dev, "recv iso_frame_descriptor, %d\n",
ret);
kfree(buff);
if (ud->side == USBIP_STUB)
usbip_event_add(ud, SDEV_EVENT_ERROR_TCP);
else
usbip_event_add(ud, VDEV_EVENT_ERROR_TCP);
return -EPIPE;
}
iso = (struct usbip_iso_packet_descriptor *) buff;
for (i = 0; i < np; i++) {
usbip_iso_packet_correct_endian(&iso[i], 0);
usbip_pack_iso(&iso[i], &urb->iso_frame_desc[i], 0);
total_length += urb->iso_frame_desc[i].actual_length;
}
kfree(buff);
if (total_length != urb->actual_length) {
dev_err(&urb->dev->dev,
"total length of iso packets %d not equal to actual length of buffer %d\n",
total_length, urb->actual_length);
if (ud->side == USBIP_STUB)
usbip_event_add(ud, SDEV_EVENT_ERROR_TCP);
else
usbip_event_add(ud, VDEV_EVENT_ERROR_TCP);
return -EPIPE;
}
return ret;
}
EXPORT_SYMBOL_GPL(usbip_recv_iso);
/*
* This functions restores the padding which was removed for optimizing
* the bandwidth during transfer over tcp/ip
*
* buffer and iso packets need to be stored and be in propeper endian in urb
* before calling this function
*/
void usbip_pad_iso(struct usbip_device *ud, struct urb *urb)
{
int np = urb->number_of_packets;
int i;
int actualoffset = urb->actual_length;
if (!usb_pipeisoc(urb->pipe))
return;
/* if no packets or length of data is 0, then nothing to unpack */
if (np == 0 || urb->actual_length == 0)
return;
/*
* if actual_length is transfer_buffer_length then no padding is
* present.
*/
if (urb->actual_length == urb->transfer_buffer_length)
return;
/*
* loop over all packets from last to first (to prevent overwritting
* memory when padding) and move them into the proper place
*/
for (i = np-1; i > 0; i--) {
actualoffset -= urb->iso_frame_desc[i].actual_length;
memmove(urb->transfer_buffer + urb->iso_frame_desc[i].offset,
urb->transfer_buffer + actualoffset,
urb->iso_frame_desc[i].actual_length);
}
}
EXPORT_SYMBOL_GPL(usbip_pad_iso);
/* some members of urb must be substituted before. */
int usbip_recv_xbuff(struct usbip_device *ud, struct urb *urb)
{
int ret;
int size;
if (ud->side == USBIP_STUB) {
/* the direction of urb must be OUT. */
if (usb_pipein(urb->pipe))
return 0;
size = urb->transfer_buffer_length;
} else {
/* the direction of urb must be IN. */
if (usb_pipeout(urb->pipe))
return 0;
size = urb->actual_length;
}
/* no need to recv xbuff */
if (!(size > 0))
return 0;
if (size > urb->transfer_buffer_length) {
/* should not happen, probably malicious packet */
if (ud->side == USBIP_STUB) {
usbip_event_add(ud, SDEV_EVENT_ERROR_TCP);
return 0;
} else {
usbip_event_add(ud, VDEV_EVENT_ERROR_TCP);
return -EPIPE;
}
}
ret = usbip_recv(ud->tcp_socket, urb->transfer_buffer, size);
if (ret != size) {
dev_err(&urb->dev->dev, "recv xbuf, %d\n", ret);
if (ud->side == USBIP_STUB) {
usbip_event_add(ud, SDEV_EVENT_ERROR_TCP);
} else {
usbip_event_add(ud, VDEV_EVENT_ERROR_TCP);
return -EPIPE;
}
}
return ret;
}
EXPORT_SYMBOL_GPL(usbip_recv_xbuff);
static int __init usbip_core_init(void)
{
pr_info(DRIVER_DESC " v" USBIP_VERSION "\n");
return 0;
}
static void __exit usbip_core_exit(void)
{
return;
}
module_init(usbip_core_init);
module_exit(usbip_core_exit);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
MODULE_VERSION(USBIP_VERSION);
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5025_0 |
crossvul-cpp_data_bad_1543_0 | /*
Kjetil Matheussen 2006.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
// Only necessary with old 2.6 kernel (before jan 2006 or thereabout).
// 2.4 and newer 2.6 works fine.
#define TIMERCHECKS 0
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <stdarg.h>
#include <sys/types.h>
#include <pthread.h>
#include <pwd.h>
#include <sched.h>
#include <sys/mman.h>
#include <syslog.h>
#include <glibtop.h>
#include <glibtop/proclist.h>
#include <glibtop/procstate.h>
#if LIBGTOP_MAJOR_VERSION<2
# include <glibtop/xmalloc.h>
#endif
#include <glibtop/procuid.h>
#include <glibtop/proctime.h>
#if LIBGTOP_MAJOR_VERSION<2
typedef u_int64_t ui64;
#else
typedef guint64 ui64;
#endif
#define OPTARGS_BEGIN(das_usage) {int lokke;const char *usage=das_usage;for(lokke=1;lokke<argc;lokke++){char *a=argv[lokke];if(!strcmp("--help",a)||!strcmp("-h",a)){printf(usage);return 0;
#define OPTARG(name,name2) }}else if(!strcmp(name,a)||!strcmp(name2,a)){{
#define OPTARG_GETINT() atoi(argv[++lokke])
#define OPTARG_GETFLOAT() atof(argv[++lokke])
#define OPTARG_GETSTRING() argv[++lokke]
#define OPTARG_LAST() }}else if(lokke==argc-1){lokke--;{
#define OPTARGS_ELSE() }else if(1){
#define OPTARGS_END }else{fprintf(stderr,usage);return(-1);}}}
static int increasetime=1; // Seconds between each time the SCHED_OTHER thread is increasing the counter.
static int checktime=4; // Seconds between each time the SCHED_FIFO thread checks that the counter is increased.
static int waittime=8; // Seconds the SCHED_FIFO thread waits before setting the processes back to SCHED_FIFO.
struct das_proclist{
pid_t pid;
int policy; //SCHED_OTHER, SCHED_FIFO, SHED_RR
int priority;
ui64 start_time; // Creation time of the process.
};
struct proclistlist{
struct das_proclist *proclist;
int length;
};
static int verbose=0;
int counter=0; // Make non-static in case the c compiler does a whole-program optimization. :-)
#if TIMERCHECKS
static int checkirq=0;
#endif
static int xmessage_found=1;
static void print_error(FILE *where,char *fmt, ...) {
char temp[10000];
va_list ap;
va_start(ap, fmt);{
vsnprintf (temp, 9998, fmt, ap);
}va_end(ap);
syslog(LOG_INFO,temp);
if(where!=NULL)
fprintf(where,"Das_Watchdog: %s\n",temp);
}
static ui64 get_pid_start_time(pid_t pid){
glibtop_proc_time buf={0};
glibtop_get_proc_time(&buf,pid);
return buf.start_time;
}
static int get_pid_priority(pid_t pid){
struct sched_param par;
sched_getparam(pid,&par);
return par.sched_priority;
}
static int set_pid_priority(pid_t pid,int policy,int priority,char *message,char *name){
struct sched_param par={0};
par.sched_priority=priority;
if((sched_setscheduler(pid,policy,&par)!=0)){
print_error(stderr,message,pid,name,strerror(errno));
return 0;
}
return 1;
}
struct das_proclist *get_proclist(int *num_procs){
int lokke=0;
glibtop_proclist proclist_def={0};
pid_t *proclist=glibtop_get_proclist(&proclist_def,GLIBTOP_KERN_PROC_ALL,0); //|GLIBTOP_EXCLUDE_SYSTEM,0);
struct das_proclist *ret=calloc(sizeof(struct das_proclist),proclist_def.number);
*num_procs=proclist_def.number;
for(lokke=0;lokke<proclist_def.number;lokke++){
pid_t pid=proclist[lokke];
ret[lokke].pid=pid;
ret[lokke].policy=sched_getscheduler(pid);
ret[lokke].priority=get_pid_priority(pid);
ret[lokke].start_time=get_pid_start_time(pid);
}
#if LIBGTOP_MAJOR_VERSION<2
glibtop_free(proclist);
#else
g_free(proclist);
#endif
return ret;
}
struct proclistlist *pll_create(void){
struct proclistlist *pll=calloc(1,sizeof(struct proclistlist));
pll->proclist=get_proclist(&pll->length);
return pll;
}
static void pll_delete(struct proclistlist *pll){
free(pll->proclist);
free(pll);
}
static pid_t name2pid(char *name){
pid_t pid=-1;
int lokke;
int num_procs=0;
struct das_proclist *proclist=get_proclist(&num_procs);
for(lokke=0;lokke<num_procs;lokke++){
glibtop_proc_state state;
glibtop_get_proc_state(&state,proclist[lokke].pid);
if(!strcmp(state.cmd,name)){
pid=proclist[lokke].pid;
break;
}
}
free(proclist);
return pid;
}
static int is_a_member(int val,int *vals,int num_vals){
int lokke;
for(lokke=0;lokke<num_vals;lokke++)
if(val==vals[lokke])
return 1;
return 0;
}
// Returns a list of users that might be the one owning the proper .Xauthority file.
static int *get_userlist(struct proclistlist *pll, int *num_users){
int *ret=calloc(sizeof(int),pll->length);
int lokke;
*num_users=0;
for(lokke=0;lokke<pll->length;lokke++){
glibtop_proc_uid uid;
glibtop_get_proc_uid(&uid,pll->proclist[lokke].pid);
if( ! is_a_member(uid.uid,ret,*num_users)){ // ???
ret[*num_users]=uid.uid;
(*num_users)++;
}
}
return ret;
}
static int gettimerpid(char *name,int cpu){
pid_t pid;
char temp[500];
if(name==NULL)
name=&temp[0];
sprintf(name,"softirq-timer/%d",cpu);
pid=name2pid(name);
if(pid==-1){
sprintf(name,"ksoftirqd/%d",cpu);
pid=name2pid(name);
}
return pid;
}
#if TIMERCHECKS
static int checksoftirq2(int force,int cpu){
char name[500];
pid_t pid=gettimerpid(&name[0],cpu);
if(pid==-1) return 0;
{
int policy=sched_getscheduler(pid);
int priority=get_pid_priority(pid);
if(priority<sched_get_priority_max(SCHED_FIFO)
|| policy==SCHED_OTHER
)
{
if(force){
print_error(stdout,"Forcing %s to SCHED_FIFO priority %d",name,sched_get_priority_max(SCHED_FIFO));
set_pid_priority(pid,SCHED_FIFO,sched_get_priority_max(SCHED_FIFO),"Could not set %d (\"%s\") to SCHED_FIFO (%s).\n\n",name);
return checksoftirq2(0,cpu);
}
if(priority<sched_get_priority_max(SCHED_FIFO))
print_error(stderr,
"\n\nWarning. The priority of the \"%s\" process is only %d, and not %d. Unless you are using the High Res Timer,\n"
"the watchdog will probably not work. If you are using the High Res Timer, please continue doing so and ignore this message.\n",
name,
priority,
sched_get_priority_max(SCHED_FIFO)
);
if(policy==SCHED_OTHER)
print_error(stderr,
"\n\nWarning The \"%s\" process is running SCHED_OTHER. Unless you are using the High Res Timer,\n"
"the watchdog will probably not work, and the timing on your machine is probably horrible.\n",
name
);
if(checkirq){
print_error(stdout,"\n\nUnless you are using the High Res Timer, you need to add the \"--force\" flag to run das_watchdog reliably.\n");
print_error(stdout,"(Things might change though, so it could work despite all warnings above. To test the watchdog, run the \"test_rt\" program.)\n\n");
}
return -1;
}
//printf("name: -%s-\n",state.cmd);
return 1;
}
}
static int checksoftirq(int force){
int cpu=0;
for(;;){
switch(checksoftirq2(force,cpu)){
case -1:
return -1;
case 1:
cpu++;
break;
case 0:
default:
return 0;
}
}
return 0;
}
#endif
static char *get_pid_environ_val(pid_t pid,char *val){
char temp[500];
int i=0;
int foundit=0;
FILE *fp;
sprintf(temp,"/proc/%d/environ",pid);
fp=fopen(temp,"r");
if(fp==NULL)
return NULL;
for(;;){
temp[i]=fgetc(fp);
if(foundit==1 && (temp[i]==0 || temp[i]=='\0' || temp[i]==EOF)){
char *ret;
temp[i]=0;
ret=malloc(strlen(temp)+10);
sprintf(ret,"%s",temp);
fclose(fp);
return ret;
}
switch(temp[i]){
case EOF:
fclose(fp);
return NULL;
case '=':
temp[i]=0;
if(!strcmp(temp,val)){
foundit=1;
}
i=0;
break;
case '\0':
i=0;
break;
default:
i++;
}
}
}
// Returns 1 in case a message was sent.
static int send_xmessage(char *xa_filename,char *message){
if(access(xa_filename,R_OK)==0){
setenv("XAUTHORITY",xa_filename,1);
if(verbose)
print_error(stdout,"Trying xauth file \"%s\"",xa_filename);
if(system(message)==0)
return 1;
}
return 0;
}
// Returns 1 in case a message was sent.
static int send_xmessage_using_XAUTHORITY(struct proclistlist *pll,int lokke,char *message){
if(lokke==pll->length)
return 0;
{
char *xa_filename=get_pid_environ_val(pll->proclist[lokke].pid,"XAUTHORITY");
if(xa_filename!=NULL){
if(send_xmessage(xa_filename,message)==1){
free(xa_filename);
return 1;
}
}
free(xa_filename);
}
return send_xmessage_using_XAUTHORITY(pll,lokke+1,message);
}
int send_xmessage_using_uids(struct proclistlist *pll, char *message){
int num_users;
int lokke;
int *uids=get_userlist(pll,&num_users);
for(lokke=0;lokke<num_users;lokke++){
char xauthpath[5000];
struct passwd *pass=getpwuid(uids[lokke]);
sprintf(xauthpath,"%s/.Xauthority",pass->pw_dir);
if(send_xmessage(xauthpath,message)==1){
free(uids);
return 1;
}
}
free(uids);
return 0;
}
static void xmessage_fork(struct proclistlist *pll){
char message[5000];
set_pid_priority(0,SCHED_FIFO,sched_get_priority_min(SCHED_FIFO),"Unable to set SCHED_FIFO for %d (\"%s\"). (%s)", "the xmessage fork");
setenv("DISPLAY",":0.0",1);
if( ! xmessage_found)
sprintf(message,"xmessage \"WARNING! das_watchdog pauses realtime operations for %d seconds.\"",waittime);
else
sprintf(message,"%s \"WARNING! das_watchdog pauses realtime operations for %d seconds.\"",WHICH_XMESSAGE,waittime);
if(send_xmessage_using_uids(pll,message)==0){
set_pid_priority(0,SCHED_OTHER,0,"Unable to set SCHED_OTHER for %d (\"%s\"). (%s)", "the xmessage fork"); // send_xmessage_using_XAUTHRITY is too heavy to run in realtime.
send_xmessage_using_XAUTHORITY(pll,0,message);
}
pll_delete(pll);
}
// The SCHED_OTHER thread.
static void *counter_func(void *arg){
{
set_pid_priority(0,SCHED_FIFO,sched_get_priority_min(SCHED_FIFO),"Unable to set SCHED_FIFO for %d (\"%s\"). (%s)", "the counter_func");
}
for(;;){
counter++;
if(verbose)
print_error(stderr,"counter set to %d",counter);
sleep(increasetime);
}
return NULL;
}
int main(int argc,char **argv){
pid_t mypid=getpid();
pthread_t counter_thread={0};
int num_cpus=0;
int *timerpids;
#if TIMERCHECKS
int force=0;
#endif
int testing=0;
// Get timer pids
{
// Find number of timer processes.
while(gettimerpid(NULL,num_cpus)!=-1)
num_cpus++;
timerpids=malloc(sizeof(int)*num_cpus);
{
int cpu=0;
for(cpu=0;cpu<num_cpus;cpu++)
timerpids[cpu]=gettimerpid(NULL,cpu);
}
}
// Options.
OPTARGS_BEGIN("Usage: das_watchdog [--force] [--verbose] [--checkirq] [--increasetime n] [--checktime n] [--waittime n]\n"
" [ -f] [ -v] [ -c] [ -it n] [ -ct n] [ -wt n]\n"
"\n"
"Additional arguments:\n"
"[--version] or [-ve] -> Prints out version.\n"
"[--test] or [-te] -> Run a test to see if xmessage is working.\n")
{
OPTARG("--verbose","-v") verbose=1;
#if TIMERCHECKS
OPTARG("--force","-f") force=1;
OPTARG("--checkirq","-c") checkirq=1; return(checksoftirq(0));
#endif
OPTARG("--increasetime","-it") increasetime=OPTARG_GETINT();
OPTARG("--checktime","-ct") checktime=OPTARG_GETINT();
OPTARG("--waittime","-wt") waittime=OPTARG_GETINT();
OPTARG("--test","-te") testing=1; verbose=1;
OPTARG("--version","-ve") printf("Das Version die Uhr Hund %s nach sein bist.\n",VERSION);exit(0);
}OPTARGS_END;
// Logging to /var/log/messages
{
openlog("das_watchdog", 0, LOG_DAEMON);
syslog(LOG_INFO, "started");
}
// Check various.
{
#if TIMERCHECKS
if(force && checksoftirq(force)<0)
return -2;
checksoftirq(force);
#endif
if(getuid()!=0){
print_error(stdout,"Warning, you are not running as root. das_watchdog should be run as an init-script at startup, and not as a normal user.\n");
}
if(access(WHICH_XMESSAGE,X_OK)!=0){
print_error(stderr,"Warning, \"xmessage\" is not found or is not an executable. I will try to use the $PATH instead. Hopefully that'll work,");
print_error(stderr,"but you might not receive messages to the screen in case das_watchdog has to take action.");
xmessage_found=0;
}
}
// Set priority
if(1) {
if( ! set_pid_priority(0,SCHED_FIFO,sched_get_priority_max(SCHED_FIFO),
"Unable to set SCHED_FIFO realtime priority for %d (\"%s\"). (%s). Exiting.",
"Der Gewinde nach die Uhr Hund"))
return 0;
if(mlockall(MCL_CURRENT|MCL_FUTURE)==-1)
print_error(stderr,"Could not call mlockalll(MCL_CURRENT|MCL_FUTURE) (%s)",strerror(errno));
}
// Start child thread.
{
pthread_create(&counter_thread,NULL,counter_func,NULL);
}
// Main loop. (We are never supposed to exit from this one.)
for(;;){
int lastcounter=counter;
sleep(checktime);
if(verbose)
print_error(stderr," counter read to be %d (lastcounter=%d)",counter,lastcounter);
if(lastcounter==counter || testing==1){
int changedsched=0;
struct proclistlist *pll=pll_create();
int lokke;
if(verbose)
print_error(stdout,"Die Uhr Hund stossen sein!");
for(lokke=0;lokke<pll->length;lokke++){
if(pll->proclist[lokke].policy!=SCHED_OTHER
&& pll->proclist[lokke].pid!=mypid
&& (!is_a_member(pll->proclist[lokke].pid,timerpids,num_cpus))
)
{
struct sched_param par={0};
par.sched_priority=0;
if(verbose)
print_error(stdout,"Setting pid %d temporarily to SCHED_OTHER.",pll->proclist[lokke].pid);
if(set_pid_priority(pll->proclist[lokke].pid,SCHED_OTHER,0,"Could not set pid %d (\"%s\") to SCHED_OTHER (%s).\n","no name"))
changedsched++;
}
}
if(changedsched>0 || testing==1){
print_error(NULL,"realtime operations paused for %d seconds.",waittime);
if(fork()==0){
xmessage_fork(pll);
return 0;
}
sleep(waittime);
for(lokke=0;lokke<pll->length;lokke++){
if(pll->proclist[lokke].policy != SCHED_OTHER
&& pll->proclist[lokke].pid != mypid
&& (!is_a_member(pll->proclist[lokke].pid,timerpids,num_cpus))
&& pll->proclist[lokke].start_time == get_pid_start_time(pll->proclist[lokke].pid)
)
{
if(get_pid_priority(pll->proclist[lokke].pid) != 0
|| sched_getscheduler(pll->proclist[lokke].pid) != SCHED_OTHER){
print_error(stderr,
"Seems like someone else has changed priority and/or scheduling policy for %d in the mean time. I'm not going to do anything.",
pll->proclist[lokke].pid);
}else{
struct sched_param par={0};
par.sched_priority=pll->proclist[lokke].priority;
if(verbose)
print_error(stdout,"Setting pid %d back to realtime priority.",pll->proclist[lokke].pid);
set_pid_priority(pll->proclist[lokke].pid,pll->proclist[lokke].policy,pll->proclist[lokke].priority,"Could not set pid %d (\"%s\") to SCHED_FIFO/SCHED_RR (%s).\n\n", "no name");
}
}
}
}
pll_delete(pll);
}
if(testing==1) break;
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1543_0 |
crossvul-cpp_data_bad_5767_0 | /*
* fs/nfs/nfs4proc.c
*
* Client-side procedure declarations for NFSv4.
*
* Copyright (c) 2002 The Regents of the University of Michigan.
* All rights reserved.
*
* Kendrick Smith <kmsmith@umich.edu>
* Andy Adamson <andros@umich.edu>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <linux/mm.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/ratelimit.h>
#include <linux/printk.h>
#include <linux/slab.h>
#include <linux/sunrpc/clnt.h>
#include <linux/nfs.h>
#include <linux/nfs4.h>
#include <linux/nfs_fs.h>
#include <linux/nfs_page.h>
#include <linux/nfs_mount.h>
#include <linux/namei.h>
#include <linux/mount.h>
#include <linux/module.h>
#include <linux/nfs_idmap.h>
#include <linux/sunrpc/bc_xprt.h>
#include <linux/xattr.h>
#include <linux/utsname.h>
#include <linux/freezer.h>
#include "nfs4_fs.h"
#include "delegation.h"
#include "internal.h"
#include "iostat.h"
#include "callback.h"
#include "pnfs.h"
#include "netns.h"
#define NFSDBG_FACILITY NFSDBG_PROC
#define NFS4_POLL_RETRY_MIN (HZ/10)
#define NFS4_POLL_RETRY_MAX (15*HZ)
#define NFS4_MAX_LOOP_ON_RECOVER (10)
struct nfs4_opendata;
static int _nfs4_proc_open(struct nfs4_opendata *data);
static int _nfs4_recover_proc_open(struct nfs4_opendata *data);
static int nfs4_do_fsinfo(struct nfs_server *, struct nfs_fh *, struct nfs_fsinfo *);
static int nfs4_async_handle_error(struct rpc_task *, const struct nfs_server *, struct nfs4_state *);
static void nfs_fixup_referral_attributes(struct nfs_fattr *fattr);
static int nfs4_proc_getattr(struct nfs_server *, struct nfs_fh *, struct nfs_fattr *);
static int _nfs4_proc_getattr(struct nfs_server *server, struct nfs_fh *fhandle, struct nfs_fattr *fattr);
static int nfs4_do_setattr(struct inode *inode, struct rpc_cred *cred,
struct nfs_fattr *fattr, struct iattr *sattr,
struct nfs4_state *state);
#ifdef CONFIG_NFS_V4_1
static int nfs41_test_stateid(struct nfs_server *, nfs4_stateid *);
static int nfs41_free_stateid(struct nfs_server *, nfs4_stateid *);
#endif
/* Prevent leaks of NFSv4 errors into userland */
static int nfs4_map_errors(int err)
{
if (err >= -1000)
return err;
switch (err) {
case -NFS4ERR_RESOURCE:
return -EREMOTEIO;
case -NFS4ERR_WRONGSEC:
return -EPERM;
case -NFS4ERR_BADOWNER:
case -NFS4ERR_BADNAME:
return -EINVAL;
case -NFS4ERR_SHARE_DENIED:
return -EACCES;
case -NFS4ERR_MINOR_VERS_MISMATCH:
return -EPROTONOSUPPORT;
case -NFS4ERR_ACCESS:
return -EACCES;
default:
dprintk("%s could not handle NFSv4 error %d\n",
__func__, -err);
break;
}
return -EIO;
}
/*
* This is our standard bitmap for GETATTR requests.
*/
const u32 nfs4_fattr_bitmap[3] = {
FATTR4_WORD0_TYPE
| FATTR4_WORD0_CHANGE
| FATTR4_WORD0_SIZE
| FATTR4_WORD0_FSID
| FATTR4_WORD0_FILEID,
FATTR4_WORD1_MODE
| FATTR4_WORD1_NUMLINKS
| FATTR4_WORD1_OWNER
| FATTR4_WORD1_OWNER_GROUP
| FATTR4_WORD1_RAWDEV
| FATTR4_WORD1_SPACE_USED
| FATTR4_WORD1_TIME_ACCESS
| FATTR4_WORD1_TIME_METADATA
| FATTR4_WORD1_TIME_MODIFY
};
static const u32 nfs4_pnfs_open_bitmap[3] = {
FATTR4_WORD0_TYPE
| FATTR4_WORD0_CHANGE
| FATTR4_WORD0_SIZE
| FATTR4_WORD0_FSID
| FATTR4_WORD0_FILEID,
FATTR4_WORD1_MODE
| FATTR4_WORD1_NUMLINKS
| FATTR4_WORD1_OWNER
| FATTR4_WORD1_OWNER_GROUP
| FATTR4_WORD1_RAWDEV
| FATTR4_WORD1_SPACE_USED
| FATTR4_WORD1_TIME_ACCESS
| FATTR4_WORD1_TIME_METADATA
| FATTR4_WORD1_TIME_MODIFY,
FATTR4_WORD2_MDSTHRESHOLD
};
static const u32 nfs4_open_noattr_bitmap[3] = {
FATTR4_WORD0_TYPE
| FATTR4_WORD0_CHANGE
| FATTR4_WORD0_FILEID,
};
const u32 nfs4_statfs_bitmap[2] = {
FATTR4_WORD0_FILES_AVAIL
| FATTR4_WORD0_FILES_FREE
| FATTR4_WORD0_FILES_TOTAL,
FATTR4_WORD1_SPACE_AVAIL
| FATTR4_WORD1_SPACE_FREE
| FATTR4_WORD1_SPACE_TOTAL
};
const u32 nfs4_pathconf_bitmap[2] = {
FATTR4_WORD0_MAXLINK
| FATTR4_WORD0_MAXNAME,
0
};
const u32 nfs4_fsinfo_bitmap[3] = { FATTR4_WORD0_MAXFILESIZE
| FATTR4_WORD0_MAXREAD
| FATTR4_WORD0_MAXWRITE
| FATTR4_WORD0_LEASE_TIME,
FATTR4_WORD1_TIME_DELTA
| FATTR4_WORD1_FS_LAYOUT_TYPES,
FATTR4_WORD2_LAYOUT_BLKSIZE
};
const u32 nfs4_fs_locations_bitmap[2] = {
FATTR4_WORD0_TYPE
| FATTR4_WORD0_CHANGE
| FATTR4_WORD0_SIZE
| FATTR4_WORD0_FSID
| FATTR4_WORD0_FILEID
| FATTR4_WORD0_FS_LOCATIONS,
FATTR4_WORD1_MODE
| FATTR4_WORD1_NUMLINKS
| FATTR4_WORD1_OWNER
| FATTR4_WORD1_OWNER_GROUP
| FATTR4_WORD1_RAWDEV
| FATTR4_WORD1_SPACE_USED
| FATTR4_WORD1_TIME_ACCESS
| FATTR4_WORD1_TIME_METADATA
| FATTR4_WORD1_TIME_MODIFY
| FATTR4_WORD1_MOUNTED_ON_FILEID
};
static void nfs4_setup_readdir(u64 cookie, __be32 *verifier, struct dentry *dentry,
struct nfs4_readdir_arg *readdir)
{
__be32 *start, *p;
BUG_ON(readdir->count < 80);
if (cookie > 2) {
readdir->cookie = cookie;
memcpy(&readdir->verifier, verifier, sizeof(readdir->verifier));
return;
}
readdir->cookie = 0;
memset(&readdir->verifier, 0, sizeof(readdir->verifier));
if (cookie == 2)
return;
/*
* NFSv4 servers do not return entries for '.' and '..'
* Therefore, we fake these entries here. We let '.'
* have cookie 0 and '..' have cookie 1. Note that
* when talking to the server, we always send cookie 0
* instead of 1 or 2.
*/
start = p = kmap_atomic(*readdir->pages);
if (cookie == 0) {
*p++ = xdr_one; /* next */
*p++ = xdr_zero; /* cookie, first word */
*p++ = xdr_one; /* cookie, second word */
*p++ = xdr_one; /* entry len */
memcpy(p, ".\0\0\0", 4); /* entry */
p++;
*p++ = xdr_one; /* bitmap length */
*p++ = htonl(FATTR4_WORD0_FILEID); /* bitmap */
*p++ = htonl(8); /* attribute buffer length */
p = xdr_encode_hyper(p, NFS_FILEID(dentry->d_inode));
}
*p++ = xdr_one; /* next */
*p++ = xdr_zero; /* cookie, first word */
*p++ = xdr_two; /* cookie, second word */
*p++ = xdr_two; /* entry len */
memcpy(p, "..\0\0", 4); /* entry */
p++;
*p++ = xdr_one; /* bitmap length */
*p++ = htonl(FATTR4_WORD0_FILEID); /* bitmap */
*p++ = htonl(8); /* attribute buffer length */
p = xdr_encode_hyper(p, NFS_FILEID(dentry->d_parent->d_inode));
readdir->pgbase = (char *)p - (char *)start;
readdir->count -= readdir->pgbase;
kunmap_atomic(start);
}
static int nfs4_wait_clnt_recover(struct nfs_client *clp)
{
int res;
might_sleep();
res = wait_on_bit(&clp->cl_state, NFS4CLNT_MANAGER_RUNNING,
nfs_wait_bit_killable, TASK_KILLABLE);
if (res)
return res;
if (clp->cl_cons_state < 0)
return clp->cl_cons_state;
return 0;
}
static int nfs4_delay(struct rpc_clnt *clnt, long *timeout)
{
int res = 0;
might_sleep();
if (*timeout <= 0)
*timeout = NFS4_POLL_RETRY_MIN;
if (*timeout > NFS4_POLL_RETRY_MAX)
*timeout = NFS4_POLL_RETRY_MAX;
freezable_schedule_timeout_killable(*timeout);
if (fatal_signal_pending(current))
res = -ERESTARTSYS;
*timeout <<= 1;
return res;
}
/* This is the error handling routine for processes that are allowed
* to sleep.
*/
static int nfs4_handle_exception(struct nfs_server *server, int errorcode, struct nfs4_exception *exception)
{
struct nfs_client *clp = server->nfs_client;
struct nfs4_state *state = exception->state;
struct inode *inode = exception->inode;
int ret = errorcode;
exception->retry = 0;
switch(errorcode) {
case 0:
return 0;
case -NFS4ERR_OPENMODE:
if (inode && nfs4_have_delegation(inode, FMODE_READ)) {
nfs4_inode_return_delegation(inode);
exception->retry = 1;
return 0;
}
if (state == NULL)
break;
nfs4_schedule_stateid_recovery(server, state);
goto wait_on_recovery;
case -NFS4ERR_DELEG_REVOKED:
case -NFS4ERR_ADMIN_REVOKED:
case -NFS4ERR_BAD_STATEID:
if (state == NULL)
break;
nfs_remove_bad_delegation(state->inode);
nfs4_schedule_stateid_recovery(server, state);
goto wait_on_recovery;
case -NFS4ERR_EXPIRED:
if (state != NULL)
nfs4_schedule_stateid_recovery(server, state);
case -NFS4ERR_STALE_STATEID:
case -NFS4ERR_STALE_CLIENTID:
nfs4_schedule_lease_recovery(clp);
goto wait_on_recovery;
#if defined(CONFIG_NFS_V4_1)
case -NFS4ERR_BADSESSION:
case -NFS4ERR_BADSLOT:
case -NFS4ERR_BAD_HIGH_SLOT:
case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION:
case -NFS4ERR_DEADSESSION:
case -NFS4ERR_SEQ_FALSE_RETRY:
case -NFS4ERR_SEQ_MISORDERED:
dprintk("%s ERROR: %d Reset session\n", __func__,
errorcode);
nfs4_schedule_session_recovery(clp->cl_session, errorcode);
goto wait_on_recovery;
#endif /* defined(CONFIG_NFS_V4_1) */
case -NFS4ERR_FILE_OPEN:
if (exception->timeout > HZ) {
/* We have retried a decent amount, time to
* fail
*/
ret = -EBUSY;
break;
}
case -NFS4ERR_GRACE:
case -NFS4ERR_DELAY:
case -EKEYEXPIRED:
ret = nfs4_delay(server->client, &exception->timeout);
if (ret != 0)
break;
case -NFS4ERR_RETRY_UNCACHED_REP:
case -NFS4ERR_OLD_STATEID:
exception->retry = 1;
break;
case -NFS4ERR_BADOWNER:
/* The following works around a Linux server bug! */
case -NFS4ERR_BADNAME:
if (server->caps & NFS_CAP_UIDGID_NOMAP) {
server->caps &= ~NFS_CAP_UIDGID_NOMAP;
exception->retry = 1;
printk(KERN_WARNING "NFS: v4 server %s "
"does not accept raw "
"uid/gids. "
"Reenabling the idmapper.\n",
server->nfs_client->cl_hostname);
}
}
/* We failed to handle the error */
return nfs4_map_errors(ret);
wait_on_recovery:
ret = nfs4_wait_clnt_recover(clp);
if (ret == 0)
exception->retry = 1;
return ret;
}
static void do_renew_lease(struct nfs_client *clp, unsigned long timestamp)
{
spin_lock(&clp->cl_lock);
if (time_before(clp->cl_last_renewal,timestamp))
clp->cl_last_renewal = timestamp;
spin_unlock(&clp->cl_lock);
}
static void renew_lease(const struct nfs_server *server, unsigned long timestamp)
{
do_renew_lease(server->nfs_client, timestamp);
}
#if defined(CONFIG_NFS_V4_1)
/*
* nfs4_free_slot - free a slot and efficiently update slot table.
*
* freeing a slot is trivially done by clearing its respective bit
* in the bitmap.
* If the freed slotid equals highest_used_slotid we want to update it
* so that the server would be able to size down the slot table if needed,
* otherwise we know that the highest_used_slotid is still in use.
* When updating highest_used_slotid there may be "holes" in the bitmap
* so we need to scan down from highest_used_slotid to 0 looking for the now
* highest slotid in use.
* If none found, highest_used_slotid is set to NFS4_NO_SLOT.
*
* Must be called while holding tbl->slot_tbl_lock
*/
static void
nfs4_free_slot(struct nfs4_slot_table *tbl, u32 slotid)
{
BUG_ON(slotid >= NFS4_MAX_SLOT_TABLE);
/* clear used bit in bitmap */
__clear_bit(slotid, tbl->used_slots);
/* update highest_used_slotid when it is freed */
if (slotid == tbl->highest_used_slotid) {
slotid = find_last_bit(tbl->used_slots, tbl->max_slots);
if (slotid < tbl->max_slots)
tbl->highest_used_slotid = slotid;
else
tbl->highest_used_slotid = NFS4_NO_SLOT;
}
dprintk("%s: slotid %u highest_used_slotid %d\n", __func__,
slotid, tbl->highest_used_slotid);
}
bool nfs4_set_task_privileged(struct rpc_task *task, void *dummy)
{
rpc_task_set_priority(task, RPC_PRIORITY_PRIVILEGED);
return true;
}
/*
* Signal state manager thread if session fore channel is drained
*/
static void nfs4_check_drain_fc_complete(struct nfs4_session *ses)
{
if (!test_bit(NFS4_SESSION_DRAINING, &ses->session_state)) {
rpc_wake_up_first(&ses->fc_slot_table.slot_tbl_waitq,
nfs4_set_task_privileged, NULL);
return;
}
if (ses->fc_slot_table.highest_used_slotid != NFS4_NO_SLOT)
return;
dprintk("%s COMPLETE: Session Fore Channel Drained\n", __func__);
complete(&ses->fc_slot_table.complete);
}
/*
* Signal state manager thread if session back channel is drained
*/
void nfs4_check_drain_bc_complete(struct nfs4_session *ses)
{
if (!test_bit(NFS4_SESSION_DRAINING, &ses->session_state) ||
ses->bc_slot_table.highest_used_slotid != NFS4_NO_SLOT)
return;
dprintk("%s COMPLETE: Session Back Channel Drained\n", __func__);
complete(&ses->bc_slot_table.complete);
}
static void nfs41_sequence_free_slot(struct nfs4_sequence_res *res)
{
struct nfs4_slot_table *tbl;
tbl = &res->sr_session->fc_slot_table;
if (!res->sr_slot) {
/* just wake up the next guy waiting since
* we may have not consumed a slot after all */
dprintk("%s: No slot\n", __func__);
return;
}
spin_lock(&tbl->slot_tbl_lock);
nfs4_free_slot(tbl, res->sr_slot - tbl->slots);
nfs4_check_drain_fc_complete(res->sr_session);
spin_unlock(&tbl->slot_tbl_lock);
res->sr_slot = NULL;
}
static int nfs41_sequence_done(struct rpc_task *task, struct nfs4_sequence_res *res)
{
unsigned long timestamp;
struct nfs_client *clp;
/*
* sr_status remains 1 if an RPC level error occurred. The server
* may or may not have processed the sequence operation..
* Proceed as if the server received and processed the sequence
* operation.
*/
if (res->sr_status == 1)
res->sr_status = NFS_OK;
/* don't increment the sequence number if the task wasn't sent */
if (!RPC_WAS_SENT(task))
goto out;
/* Check the SEQUENCE operation status */
switch (res->sr_status) {
case 0:
/* Update the slot's sequence and clientid lease timer */
++res->sr_slot->seq_nr;
timestamp = res->sr_renewal_time;
clp = res->sr_session->clp;
do_renew_lease(clp, timestamp);
/* Check sequence flags */
if (res->sr_status_flags != 0)
nfs4_schedule_lease_recovery(clp);
break;
case -NFS4ERR_DELAY:
/* The server detected a resend of the RPC call and
* returned NFS4ERR_DELAY as per Section 2.10.6.2
* of RFC5661.
*/
dprintk("%s: slot=%td seq=%d: Operation in progress\n",
__func__,
res->sr_slot - res->sr_session->fc_slot_table.slots,
res->sr_slot->seq_nr);
goto out_retry;
default:
/* Just update the slot sequence no. */
++res->sr_slot->seq_nr;
}
out:
/* The session may be reset by one of the error handlers. */
dprintk("%s: Error %d free the slot \n", __func__, res->sr_status);
nfs41_sequence_free_slot(res);
return 1;
out_retry:
if (!rpc_restart_call(task))
goto out;
rpc_delay(task, NFS4_POLL_RETRY_MAX);
return 0;
}
static int nfs4_sequence_done(struct rpc_task *task,
struct nfs4_sequence_res *res)
{
if (res->sr_session == NULL)
return 1;
return nfs41_sequence_done(task, res);
}
/*
* nfs4_find_slot - efficiently look for a free slot
*
* nfs4_find_slot looks for an unset bit in the used_slots bitmap.
* If found, we mark the slot as used, update the highest_used_slotid,
* and respectively set up the sequence operation args.
* The slot number is returned if found, or NFS4_NO_SLOT otherwise.
*
* Note: must be called with under the slot_tbl_lock.
*/
static u32
nfs4_find_slot(struct nfs4_slot_table *tbl)
{
u32 slotid;
u32 ret_id = NFS4_NO_SLOT;
dprintk("--> %s used_slots=%04lx highest_used=%u max_slots=%u\n",
__func__, tbl->used_slots[0], tbl->highest_used_slotid,
tbl->max_slots);
slotid = find_first_zero_bit(tbl->used_slots, tbl->max_slots);
if (slotid >= tbl->max_slots)
goto out;
__set_bit(slotid, tbl->used_slots);
if (slotid > tbl->highest_used_slotid ||
tbl->highest_used_slotid == NFS4_NO_SLOT)
tbl->highest_used_slotid = slotid;
ret_id = slotid;
out:
dprintk("<-- %s used_slots=%04lx highest_used=%d slotid=%d \n",
__func__, tbl->used_slots[0], tbl->highest_used_slotid, ret_id);
return ret_id;
}
static void nfs41_init_sequence(struct nfs4_sequence_args *args,
struct nfs4_sequence_res *res, int cache_reply)
{
args->sa_session = NULL;
args->sa_cache_this = 0;
if (cache_reply)
args->sa_cache_this = 1;
res->sr_session = NULL;
res->sr_slot = NULL;
}
int nfs41_setup_sequence(struct nfs4_session *session,
struct nfs4_sequence_args *args,
struct nfs4_sequence_res *res,
struct rpc_task *task)
{
struct nfs4_slot *slot;
struct nfs4_slot_table *tbl;
u32 slotid;
dprintk("--> %s\n", __func__);
/* slot already allocated? */
if (res->sr_slot != NULL)
return 0;
tbl = &session->fc_slot_table;
spin_lock(&tbl->slot_tbl_lock);
if (test_bit(NFS4_SESSION_DRAINING, &session->session_state) &&
!rpc_task_has_priority(task, RPC_PRIORITY_PRIVILEGED)) {
/* The state manager will wait until the slot table is empty */
rpc_sleep_on(&tbl->slot_tbl_waitq, task, NULL);
spin_unlock(&tbl->slot_tbl_lock);
dprintk("%s session is draining\n", __func__);
return -EAGAIN;
}
if (!rpc_queue_empty(&tbl->slot_tbl_waitq) &&
!rpc_task_has_priority(task, RPC_PRIORITY_PRIVILEGED)) {
rpc_sleep_on(&tbl->slot_tbl_waitq, task, NULL);
spin_unlock(&tbl->slot_tbl_lock);
dprintk("%s enforce FIFO order\n", __func__);
return -EAGAIN;
}
slotid = nfs4_find_slot(tbl);
if (slotid == NFS4_NO_SLOT) {
rpc_sleep_on(&tbl->slot_tbl_waitq, task, NULL);
spin_unlock(&tbl->slot_tbl_lock);
dprintk("<-- %s: no free slots\n", __func__);
return -EAGAIN;
}
spin_unlock(&tbl->slot_tbl_lock);
rpc_task_set_priority(task, RPC_PRIORITY_NORMAL);
slot = tbl->slots + slotid;
args->sa_session = session;
args->sa_slotid = slotid;
dprintk("<-- %s slotid=%d seqid=%d\n", __func__, slotid, slot->seq_nr);
res->sr_session = session;
res->sr_slot = slot;
res->sr_renewal_time = jiffies;
res->sr_status_flags = 0;
/*
* sr_status is only set in decode_sequence, and so will remain
* set to 1 if an rpc level failure occurs.
*/
res->sr_status = 1;
return 0;
}
EXPORT_SYMBOL_GPL(nfs41_setup_sequence);
int nfs4_setup_sequence(const struct nfs_server *server,
struct nfs4_sequence_args *args,
struct nfs4_sequence_res *res,
struct rpc_task *task)
{
struct nfs4_session *session = nfs4_get_session(server);
int ret = 0;
if (session == NULL)
goto out;
dprintk("--> %s clp %p session %p sr_slot %td\n",
__func__, session->clp, session, res->sr_slot ?
res->sr_slot - session->fc_slot_table.slots : -1);
ret = nfs41_setup_sequence(session, args, res, task);
out:
dprintk("<-- %s status=%d\n", __func__, ret);
return ret;
}
struct nfs41_call_sync_data {
const struct nfs_server *seq_server;
struct nfs4_sequence_args *seq_args;
struct nfs4_sequence_res *seq_res;
};
static void nfs41_call_sync_prepare(struct rpc_task *task, void *calldata)
{
struct nfs41_call_sync_data *data = calldata;
dprintk("--> %s data->seq_server %p\n", __func__, data->seq_server);
if (nfs4_setup_sequence(data->seq_server, data->seq_args,
data->seq_res, task))
return;
rpc_call_start(task);
}
static void nfs41_call_priv_sync_prepare(struct rpc_task *task, void *calldata)
{
rpc_task_set_priority(task, RPC_PRIORITY_PRIVILEGED);
nfs41_call_sync_prepare(task, calldata);
}
static void nfs41_call_sync_done(struct rpc_task *task, void *calldata)
{
struct nfs41_call_sync_data *data = calldata;
nfs41_sequence_done(task, data->seq_res);
}
static const struct rpc_call_ops nfs41_call_sync_ops = {
.rpc_call_prepare = nfs41_call_sync_prepare,
.rpc_call_done = nfs41_call_sync_done,
};
static const struct rpc_call_ops nfs41_call_priv_sync_ops = {
.rpc_call_prepare = nfs41_call_priv_sync_prepare,
.rpc_call_done = nfs41_call_sync_done,
};
static int nfs4_call_sync_sequence(struct rpc_clnt *clnt,
struct nfs_server *server,
struct rpc_message *msg,
struct nfs4_sequence_args *args,
struct nfs4_sequence_res *res,
int privileged)
{
int ret;
struct rpc_task *task;
struct nfs41_call_sync_data data = {
.seq_server = server,
.seq_args = args,
.seq_res = res,
};
struct rpc_task_setup task_setup = {
.rpc_client = clnt,
.rpc_message = msg,
.callback_ops = &nfs41_call_sync_ops,
.callback_data = &data
};
if (privileged)
task_setup.callback_ops = &nfs41_call_priv_sync_ops;
task = rpc_run_task(&task_setup);
if (IS_ERR(task))
ret = PTR_ERR(task);
else {
ret = task->tk_status;
rpc_put_task(task);
}
return ret;
}
int _nfs4_call_sync_session(struct rpc_clnt *clnt,
struct nfs_server *server,
struct rpc_message *msg,
struct nfs4_sequence_args *args,
struct nfs4_sequence_res *res,
int cache_reply)
{
nfs41_init_sequence(args, res, cache_reply);
return nfs4_call_sync_sequence(clnt, server, msg, args, res, 0);
}
#else
static inline
void nfs41_init_sequence(struct nfs4_sequence_args *args,
struct nfs4_sequence_res *res, int cache_reply)
{
}
static int nfs4_sequence_done(struct rpc_task *task,
struct nfs4_sequence_res *res)
{
return 1;
}
#endif /* CONFIG_NFS_V4_1 */
int _nfs4_call_sync(struct rpc_clnt *clnt,
struct nfs_server *server,
struct rpc_message *msg,
struct nfs4_sequence_args *args,
struct nfs4_sequence_res *res,
int cache_reply)
{
nfs41_init_sequence(args, res, cache_reply);
return rpc_call_sync(clnt, msg, 0);
}
static inline
int nfs4_call_sync(struct rpc_clnt *clnt,
struct nfs_server *server,
struct rpc_message *msg,
struct nfs4_sequence_args *args,
struct nfs4_sequence_res *res,
int cache_reply)
{
return server->nfs_client->cl_mvops->call_sync(clnt, server, msg,
args, res, cache_reply);
}
static void update_changeattr(struct inode *dir, struct nfs4_change_info *cinfo)
{
struct nfs_inode *nfsi = NFS_I(dir);
spin_lock(&dir->i_lock);
nfsi->cache_validity |= NFS_INO_INVALID_ATTR|NFS_INO_INVALID_DATA;
if (!cinfo->atomic || cinfo->before != dir->i_version)
nfs_force_lookup_revalidate(dir);
dir->i_version = cinfo->after;
spin_unlock(&dir->i_lock);
}
struct nfs4_opendata {
struct kref kref;
struct nfs_openargs o_arg;
struct nfs_openres o_res;
struct nfs_open_confirmargs c_arg;
struct nfs_open_confirmres c_res;
struct nfs4_string owner_name;
struct nfs4_string group_name;
struct nfs_fattr f_attr;
struct dentry *dir;
struct dentry *dentry;
struct nfs4_state_owner *owner;
struct nfs4_state *state;
struct iattr attrs;
unsigned long timestamp;
unsigned int rpc_done : 1;
int rpc_status;
int cancelled;
};
static void nfs4_init_opendata_res(struct nfs4_opendata *p)
{
p->o_res.f_attr = &p->f_attr;
p->o_res.seqid = p->o_arg.seqid;
p->c_res.seqid = p->c_arg.seqid;
p->o_res.server = p->o_arg.server;
p->o_res.access_request = p->o_arg.access;
nfs_fattr_init(&p->f_attr);
nfs_fattr_init_names(&p->f_attr, &p->owner_name, &p->group_name);
}
static struct nfs4_opendata *nfs4_opendata_alloc(struct dentry *dentry,
struct nfs4_state_owner *sp, fmode_t fmode, int flags,
const struct iattr *attrs,
gfp_t gfp_mask)
{
struct dentry *parent = dget_parent(dentry);
struct inode *dir = parent->d_inode;
struct nfs_server *server = NFS_SERVER(dir);
struct nfs4_opendata *p;
p = kzalloc(sizeof(*p), gfp_mask);
if (p == NULL)
goto err;
p->o_arg.seqid = nfs_alloc_seqid(&sp->so_seqid, gfp_mask);
if (p->o_arg.seqid == NULL)
goto err_free;
nfs_sb_active(dentry->d_sb);
p->dentry = dget(dentry);
p->dir = parent;
p->owner = sp;
atomic_inc(&sp->so_count);
p->o_arg.fh = NFS_FH(dir);
p->o_arg.open_flags = flags;
p->o_arg.fmode = fmode & (FMODE_READ|FMODE_WRITE);
/* don't put an ACCESS op in OPEN compound if O_EXCL, because ACCESS
* will return permission denied for all bits until close */
if (!(flags & O_EXCL)) {
/* ask server to check for all possible rights as results
* are cached */
p->o_arg.access = NFS4_ACCESS_READ | NFS4_ACCESS_MODIFY |
NFS4_ACCESS_EXTEND | NFS4_ACCESS_EXECUTE;
}
p->o_arg.clientid = server->nfs_client->cl_clientid;
p->o_arg.id.create_time = ktime_to_ns(sp->so_seqid.create_time);
p->o_arg.id.uniquifier = sp->so_seqid.owner_id;
p->o_arg.name = &dentry->d_name;
p->o_arg.server = server;
p->o_arg.bitmask = server->attr_bitmask;
p->o_arg.open_bitmap = &nfs4_fattr_bitmap[0];
p->o_arg.claim = NFS4_OPEN_CLAIM_NULL;
if (attrs != NULL && attrs->ia_valid != 0) {
__be32 verf[2];
p->o_arg.u.attrs = &p->attrs;
memcpy(&p->attrs, attrs, sizeof(p->attrs));
verf[0] = jiffies;
verf[1] = current->pid;
memcpy(p->o_arg.u.verifier.data, verf,
sizeof(p->o_arg.u.verifier.data));
}
p->c_arg.fh = &p->o_res.fh;
p->c_arg.stateid = &p->o_res.stateid;
p->c_arg.seqid = p->o_arg.seqid;
nfs4_init_opendata_res(p);
kref_init(&p->kref);
return p;
err_free:
kfree(p);
err:
dput(parent);
return NULL;
}
static void nfs4_opendata_free(struct kref *kref)
{
struct nfs4_opendata *p = container_of(kref,
struct nfs4_opendata, kref);
struct super_block *sb = p->dentry->d_sb;
nfs_free_seqid(p->o_arg.seqid);
if (p->state != NULL)
nfs4_put_open_state(p->state);
nfs4_put_state_owner(p->owner);
dput(p->dir);
dput(p->dentry);
nfs_sb_deactive(sb);
nfs_fattr_free_names(&p->f_attr);
kfree(p);
}
static void nfs4_opendata_put(struct nfs4_opendata *p)
{
if (p != NULL)
kref_put(&p->kref, nfs4_opendata_free);
}
static int nfs4_wait_for_completion_rpc_task(struct rpc_task *task)
{
int ret;
ret = rpc_wait_for_completion_task(task);
return ret;
}
static int can_open_cached(struct nfs4_state *state, fmode_t mode, int open_mode)
{
int ret = 0;
if (open_mode & (O_EXCL|O_TRUNC))
goto out;
switch (mode & (FMODE_READ|FMODE_WRITE)) {
case FMODE_READ:
ret |= test_bit(NFS_O_RDONLY_STATE, &state->flags) != 0
&& state->n_rdonly != 0;
break;
case FMODE_WRITE:
ret |= test_bit(NFS_O_WRONLY_STATE, &state->flags) != 0
&& state->n_wronly != 0;
break;
case FMODE_READ|FMODE_WRITE:
ret |= test_bit(NFS_O_RDWR_STATE, &state->flags) != 0
&& state->n_rdwr != 0;
}
out:
return ret;
}
static int can_open_delegated(struct nfs_delegation *delegation, fmode_t fmode)
{
if (delegation == NULL)
return 0;
if ((delegation->type & fmode) != fmode)
return 0;
if (test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags))
return 0;
nfs_mark_delegation_referenced(delegation);
return 1;
}
static void update_open_stateflags(struct nfs4_state *state, fmode_t fmode)
{
switch (fmode) {
case FMODE_WRITE:
state->n_wronly++;
break;
case FMODE_READ:
state->n_rdonly++;
break;
case FMODE_READ|FMODE_WRITE:
state->n_rdwr++;
}
nfs4_state_set_mode_locked(state, state->state | fmode);
}
static void nfs_set_open_stateid_locked(struct nfs4_state *state, nfs4_stateid *stateid, fmode_t fmode)
{
if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0)
nfs4_stateid_copy(&state->stateid, stateid);
nfs4_stateid_copy(&state->open_stateid, stateid);
switch (fmode) {
case FMODE_READ:
set_bit(NFS_O_RDONLY_STATE, &state->flags);
break;
case FMODE_WRITE:
set_bit(NFS_O_WRONLY_STATE, &state->flags);
break;
case FMODE_READ|FMODE_WRITE:
set_bit(NFS_O_RDWR_STATE, &state->flags);
}
}
static void nfs_set_open_stateid(struct nfs4_state *state, nfs4_stateid *stateid, fmode_t fmode)
{
write_seqlock(&state->seqlock);
nfs_set_open_stateid_locked(state, stateid, fmode);
write_sequnlock(&state->seqlock);
}
static void __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, fmode_t fmode)
{
/*
* Protect the call to nfs4_state_set_mode_locked and
* serialise the stateid update
*/
write_seqlock(&state->seqlock);
if (deleg_stateid != NULL) {
nfs4_stateid_copy(&state->stateid, deleg_stateid);
set_bit(NFS_DELEGATED_STATE, &state->flags);
}
if (open_stateid != NULL)
nfs_set_open_stateid_locked(state, open_stateid, fmode);
write_sequnlock(&state->seqlock);
spin_lock(&state->owner->so_lock);
update_open_stateflags(state, fmode);
spin_unlock(&state->owner->so_lock);
}
static int update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, nfs4_stateid *delegation, fmode_t fmode)
{
struct nfs_inode *nfsi = NFS_I(state->inode);
struct nfs_delegation *deleg_cur;
int ret = 0;
fmode &= (FMODE_READ|FMODE_WRITE);
rcu_read_lock();
deleg_cur = rcu_dereference(nfsi->delegation);
if (deleg_cur == NULL)
goto no_delegation;
spin_lock(&deleg_cur->lock);
if (nfsi->delegation != deleg_cur ||
(deleg_cur->type & fmode) != fmode)
goto no_delegation_unlock;
if (delegation == NULL)
delegation = &deleg_cur->stateid;
else if (!nfs4_stateid_match(&deleg_cur->stateid, delegation))
goto no_delegation_unlock;
nfs_mark_delegation_referenced(deleg_cur);
__update_open_stateid(state, open_stateid, &deleg_cur->stateid, fmode);
ret = 1;
no_delegation_unlock:
spin_unlock(&deleg_cur->lock);
no_delegation:
rcu_read_unlock();
if (!ret && open_stateid != NULL) {
__update_open_stateid(state, open_stateid, NULL, fmode);
ret = 1;
}
return ret;
}
static void nfs4_return_incompatible_delegation(struct inode *inode, fmode_t fmode)
{
struct nfs_delegation *delegation;
rcu_read_lock();
delegation = rcu_dereference(NFS_I(inode)->delegation);
if (delegation == NULL || (delegation->type & fmode) == fmode) {
rcu_read_unlock();
return;
}
rcu_read_unlock();
nfs4_inode_return_delegation(inode);
}
static struct nfs4_state *nfs4_try_open_cached(struct nfs4_opendata *opendata)
{
struct nfs4_state *state = opendata->state;
struct nfs_inode *nfsi = NFS_I(state->inode);
struct nfs_delegation *delegation;
int open_mode = opendata->o_arg.open_flags & (O_EXCL|O_TRUNC);
fmode_t fmode = opendata->o_arg.fmode;
nfs4_stateid stateid;
int ret = -EAGAIN;
for (;;) {
if (can_open_cached(state, fmode, open_mode)) {
spin_lock(&state->owner->so_lock);
if (can_open_cached(state, fmode, open_mode)) {
update_open_stateflags(state, fmode);
spin_unlock(&state->owner->so_lock);
goto out_return_state;
}
spin_unlock(&state->owner->so_lock);
}
rcu_read_lock();
delegation = rcu_dereference(nfsi->delegation);
if (!can_open_delegated(delegation, fmode)) {
rcu_read_unlock();
break;
}
/* Save the delegation */
nfs4_stateid_copy(&stateid, &delegation->stateid);
rcu_read_unlock();
ret = nfs_may_open(state->inode, state->owner->so_cred, open_mode);
if (ret != 0)
goto out;
ret = -EAGAIN;
/* Try to update the stateid using the delegation */
if (update_open_stateid(state, NULL, &stateid, fmode))
goto out_return_state;
}
out:
return ERR_PTR(ret);
out_return_state:
atomic_inc(&state->count);
return state;
}
static void
nfs4_opendata_check_deleg(struct nfs4_opendata *data, struct nfs4_state *state)
{
struct nfs_client *clp = NFS_SERVER(state->inode)->nfs_client;
struct nfs_delegation *delegation;
int delegation_flags = 0;
rcu_read_lock();
delegation = rcu_dereference(NFS_I(state->inode)->delegation);
if (delegation)
delegation_flags = delegation->flags;
rcu_read_unlock();
if (data->o_arg.claim == NFS4_OPEN_CLAIM_DELEGATE_CUR) {
pr_err_ratelimited("NFS: Broken NFSv4 server %s is "
"returning a delegation for "
"OPEN(CLAIM_DELEGATE_CUR)\n",
clp->cl_hostname);
} else if ((delegation_flags & 1UL<<NFS_DELEGATION_NEED_RECLAIM) == 0)
nfs_inode_set_delegation(state->inode,
data->owner->so_cred,
&data->o_res);
else
nfs_inode_reclaim_delegation(state->inode,
data->owner->so_cred,
&data->o_res);
}
/*
* Check the inode attributes against the CLAIM_PREVIOUS returned attributes
* and update the nfs4_state.
*/
static struct nfs4_state *
_nfs4_opendata_reclaim_to_nfs4_state(struct nfs4_opendata *data)
{
struct inode *inode = data->state->inode;
struct nfs4_state *state = data->state;
int ret;
if (!data->rpc_done) {
ret = data->rpc_status;
goto err;
}
ret = -ESTALE;
if (!(data->f_attr.valid & NFS_ATTR_FATTR_TYPE) ||
!(data->f_attr.valid & NFS_ATTR_FATTR_FILEID) ||
!(data->f_attr.valid & NFS_ATTR_FATTR_CHANGE))
goto err;
ret = -ENOMEM;
state = nfs4_get_open_state(inode, data->owner);
if (state == NULL)
goto err;
ret = nfs_refresh_inode(inode, &data->f_attr);
if (ret)
goto err;
if (data->o_res.delegation_type != 0)
nfs4_opendata_check_deleg(data, state);
update_open_stateid(state, &data->o_res.stateid, NULL,
data->o_arg.fmode);
return state;
err:
return ERR_PTR(ret);
}
static struct nfs4_state *
_nfs4_opendata_to_nfs4_state(struct nfs4_opendata *data)
{
struct inode *inode;
struct nfs4_state *state = NULL;
int ret;
if (!data->rpc_done) {
state = nfs4_try_open_cached(data);
goto out;
}
ret = -EAGAIN;
if (!(data->f_attr.valid & NFS_ATTR_FATTR))
goto err;
inode = nfs_fhget(data->dir->d_sb, &data->o_res.fh, &data->f_attr);
ret = PTR_ERR(inode);
if (IS_ERR(inode))
goto err;
ret = -ENOMEM;
state = nfs4_get_open_state(inode, data->owner);
if (state == NULL)
goto err_put_inode;
if (data->o_res.delegation_type != 0)
nfs4_opendata_check_deleg(data, state);
update_open_stateid(state, &data->o_res.stateid, NULL,
data->o_arg.fmode);
iput(inode);
out:
return state;
err_put_inode:
iput(inode);
err:
return ERR_PTR(ret);
}
static struct nfs4_state *
nfs4_opendata_to_nfs4_state(struct nfs4_opendata *data)
{
if (data->o_arg.claim == NFS4_OPEN_CLAIM_PREVIOUS)
return _nfs4_opendata_reclaim_to_nfs4_state(data);
return _nfs4_opendata_to_nfs4_state(data);
}
static struct nfs_open_context *nfs4_state_find_open_context(struct nfs4_state *state)
{
struct nfs_inode *nfsi = NFS_I(state->inode);
struct nfs_open_context *ctx;
spin_lock(&state->inode->i_lock);
list_for_each_entry(ctx, &nfsi->open_files, list) {
if (ctx->state != state)
continue;
get_nfs_open_context(ctx);
spin_unlock(&state->inode->i_lock);
return ctx;
}
spin_unlock(&state->inode->i_lock);
return ERR_PTR(-ENOENT);
}
static struct nfs4_opendata *nfs4_open_recoverdata_alloc(struct nfs_open_context *ctx, struct nfs4_state *state)
{
struct nfs4_opendata *opendata;
opendata = nfs4_opendata_alloc(ctx->dentry, state->owner, 0, 0, NULL, GFP_NOFS);
if (opendata == NULL)
return ERR_PTR(-ENOMEM);
opendata->state = state;
atomic_inc(&state->count);
return opendata;
}
static int nfs4_open_recover_helper(struct nfs4_opendata *opendata, fmode_t fmode, struct nfs4_state **res)
{
struct nfs4_state *newstate;
int ret;
opendata->o_arg.open_flags = 0;
opendata->o_arg.fmode = fmode;
memset(&opendata->o_res, 0, sizeof(opendata->o_res));
memset(&opendata->c_res, 0, sizeof(opendata->c_res));
nfs4_init_opendata_res(opendata);
ret = _nfs4_recover_proc_open(opendata);
if (ret != 0)
return ret;
newstate = nfs4_opendata_to_nfs4_state(opendata);
if (IS_ERR(newstate))
return PTR_ERR(newstate);
nfs4_close_state(newstate, fmode);
*res = newstate;
return 0;
}
static int nfs4_open_recover(struct nfs4_opendata *opendata, struct nfs4_state *state)
{
struct nfs4_state *newstate;
int ret;
/* memory barrier prior to reading state->n_* */
clear_bit(NFS_DELEGATED_STATE, &state->flags);
smp_rmb();
if (state->n_rdwr != 0) {
clear_bit(NFS_O_RDWR_STATE, &state->flags);
ret = nfs4_open_recover_helper(opendata, FMODE_READ|FMODE_WRITE, &newstate);
if (ret != 0)
return ret;
if (newstate != state)
return -ESTALE;
}
if (state->n_wronly != 0) {
clear_bit(NFS_O_WRONLY_STATE, &state->flags);
ret = nfs4_open_recover_helper(opendata, FMODE_WRITE, &newstate);
if (ret != 0)
return ret;
if (newstate != state)
return -ESTALE;
}
if (state->n_rdonly != 0) {
clear_bit(NFS_O_RDONLY_STATE, &state->flags);
ret = nfs4_open_recover_helper(opendata, FMODE_READ, &newstate);
if (ret != 0)
return ret;
if (newstate != state)
return -ESTALE;
}
/*
* We may have performed cached opens for all three recoveries.
* Check if we need to update the current stateid.
*/
if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0 &&
!nfs4_stateid_match(&state->stateid, &state->open_stateid)) {
write_seqlock(&state->seqlock);
if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0)
nfs4_stateid_copy(&state->stateid, &state->open_stateid);
write_sequnlock(&state->seqlock);
}
return 0;
}
/*
* OPEN_RECLAIM:
* reclaim state on the server after a reboot.
*/
static int _nfs4_do_open_reclaim(struct nfs_open_context *ctx, struct nfs4_state *state)
{
struct nfs_delegation *delegation;
struct nfs4_opendata *opendata;
fmode_t delegation_type = 0;
int status;
opendata = nfs4_open_recoverdata_alloc(ctx, state);
if (IS_ERR(opendata))
return PTR_ERR(opendata);
opendata->o_arg.claim = NFS4_OPEN_CLAIM_PREVIOUS;
opendata->o_arg.fh = NFS_FH(state->inode);
rcu_read_lock();
delegation = rcu_dereference(NFS_I(state->inode)->delegation);
if (delegation != NULL && test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) != 0)
delegation_type = delegation->type;
rcu_read_unlock();
opendata->o_arg.u.delegation_type = delegation_type;
status = nfs4_open_recover(opendata, state);
nfs4_opendata_put(opendata);
return status;
}
static int nfs4_do_open_reclaim(struct nfs_open_context *ctx, struct nfs4_state *state)
{
struct nfs_server *server = NFS_SERVER(state->inode);
struct nfs4_exception exception = { };
int err;
do {
err = _nfs4_do_open_reclaim(ctx, state);
if (err != -NFS4ERR_DELAY)
break;
nfs4_handle_exception(server, err, &exception);
} while (exception.retry);
return err;
}
static int nfs4_open_reclaim(struct nfs4_state_owner *sp, struct nfs4_state *state)
{
struct nfs_open_context *ctx;
int ret;
ctx = nfs4_state_find_open_context(state);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
ret = nfs4_do_open_reclaim(ctx, state);
put_nfs_open_context(ctx);
return ret;
}
static int _nfs4_open_delegation_recall(struct nfs_open_context *ctx, struct nfs4_state *state, const nfs4_stateid *stateid)
{
struct nfs4_opendata *opendata;
int ret;
opendata = nfs4_open_recoverdata_alloc(ctx, state);
if (IS_ERR(opendata))
return PTR_ERR(opendata);
opendata->o_arg.claim = NFS4_OPEN_CLAIM_DELEGATE_CUR;
nfs4_stateid_copy(&opendata->o_arg.u.delegation, stateid);
ret = nfs4_open_recover(opendata, state);
nfs4_opendata_put(opendata);
return ret;
}
int nfs4_open_delegation_recall(struct nfs_open_context *ctx, struct nfs4_state *state, const nfs4_stateid *stateid)
{
struct nfs4_exception exception = { };
struct nfs_server *server = NFS_SERVER(state->inode);
int err;
do {
err = _nfs4_open_delegation_recall(ctx, state, stateid);
switch (err) {
case 0:
case -ENOENT:
case -ESTALE:
goto out;
case -NFS4ERR_BADSESSION:
case -NFS4ERR_BADSLOT:
case -NFS4ERR_BAD_HIGH_SLOT:
case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION:
case -NFS4ERR_DEADSESSION:
nfs4_schedule_session_recovery(server->nfs_client->cl_session, err);
goto out;
case -NFS4ERR_STALE_CLIENTID:
case -NFS4ERR_STALE_STATEID:
case -NFS4ERR_EXPIRED:
/* Don't recall a delegation if it was lost */
nfs4_schedule_lease_recovery(server->nfs_client);
goto out;
case -ERESTARTSYS:
/*
* The show must go on: exit, but mark the
* stateid as needing recovery.
*/
case -NFS4ERR_DELEG_REVOKED:
case -NFS4ERR_ADMIN_REVOKED:
case -NFS4ERR_BAD_STATEID:
nfs_inode_find_state_and_recover(state->inode,
stateid);
nfs4_schedule_stateid_recovery(server, state);
case -EKEYEXPIRED:
/*
* User RPCSEC_GSS context has expired.
* We cannot recover this stateid now, so
* skip it and allow recovery thread to
* proceed.
*/
case -ENOMEM:
err = 0;
goto out;
}
err = nfs4_handle_exception(server, err, &exception);
} while (exception.retry);
out:
return err;
}
static void nfs4_open_confirm_done(struct rpc_task *task, void *calldata)
{
struct nfs4_opendata *data = calldata;
data->rpc_status = task->tk_status;
if (data->rpc_status == 0) {
nfs4_stateid_copy(&data->o_res.stateid, &data->c_res.stateid);
nfs_confirm_seqid(&data->owner->so_seqid, 0);
renew_lease(data->o_res.server, data->timestamp);
data->rpc_done = 1;
}
}
static void nfs4_open_confirm_release(void *calldata)
{
struct nfs4_opendata *data = calldata;
struct nfs4_state *state = NULL;
/* If this request hasn't been cancelled, do nothing */
if (data->cancelled == 0)
goto out_free;
/* In case of error, no cleanup! */
if (!data->rpc_done)
goto out_free;
state = nfs4_opendata_to_nfs4_state(data);
if (!IS_ERR(state))
nfs4_close_state(state, data->o_arg.fmode);
out_free:
nfs4_opendata_put(data);
}
static const struct rpc_call_ops nfs4_open_confirm_ops = {
.rpc_call_done = nfs4_open_confirm_done,
.rpc_release = nfs4_open_confirm_release,
};
/*
* Note: On error, nfs4_proc_open_confirm will free the struct nfs4_opendata
*/
static int _nfs4_proc_open_confirm(struct nfs4_opendata *data)
{
struct nfs_server *server = NFS_SERVER(data->dir->d_inode);
struct rpc_task *task;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_CONFIRM],
.rpc_argp = &data->c_arg,
.rpc_resp = &data->c_res,
.rpc_cred = data->owner->so_cred,
};
struct rpc_task_setup task_setup_data = {
.rpc_client = server->client,
.rpc_message = &msg,
.callback_ops = &nfs4_open_confirm_ops,
.callback_data = data,
.workqueue = nfsiod_workqueue,
.flags = RPC_TASK_ASYNC,
};
int status;
kref_get(&data->kref);
data->rpc_done = 0;
data->rpc_status = 0;
data->timestamp = jiffies;
task = rpc_run_task(&task_setup_data);
if (IS_ERR(task))
return PTR_ERR(task);
status = nfs4_wait_for_completion_rpc_task(task);
if (status != 0) {
data->cancelled = 1;
smp_wmb();
} else
status = data->rpc_status;
rpc_put_task(task);
return status;
}
static void nfs4_open_prepare(struct rpc_task *task, void *calldata)
{
struct nfs4_opendata *data = calldata;
struct nfs4_state_owner *sp = data->owner;
if (nfs_wait_on_sequence(data->o_arg.seqid, task) != 0)
return;
/*
* Check if we still need to send an OPEN call, or if we can use
* a delegation instead.
*/
if (data->state != NULL) {
struct nfs_delegation *delegation;
if (can_open_cached(data->state, data->o_arg.fmode, data->o_arg.open_flags))
goto out_no_action;
rcu_read_lock();
delegation = rcu_dereference(NFS_I(data->state->inode)->delegation);
if (data->o_arg.claim != NFS4_OPEN_CLAIM_DELEGATE_CUR &&
can_open_delegated(delegation, data->o_arg.fmode))
goto unlock_no_action;
rcu_read_unlock();
}
/* Update client id. */
data->o_arg.clientid = sp->so_server->nfs_client->cl_clientid;
if (data->o_arg.claim == NFS4_OPEN_CLAIM_PREVIOUS) {
task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_NOATTR];
data->o_arg.open_bitmap = &nfs4_open_noattr_bitmap[0];
nfs_copy_fh(&data->o_res.fh, data->o_arg.fh);
}
data->timestamp = jiffies;
if (nfs4_setup_sequence(data->o_arg.server,
&data->o_arg.seq_args,
&data->o_res.seq_res,
task) != 0)
nfs_release_seqid(data->o_arg.seqid);
else
rpc_call_start(task);
return;
unlock_no_action:
rcu_read_unlock();
out_no_action:
task->tk_action = NULL;
}
static void nfs4_recover_open_prepare(struct rpc_task *task, void *calldata)
{
rpc_task_set_priority(task, RPC_PRIORITY_PRIVILEGED);
nfs4_open_prepare(task, calldata);
}
static void nfs4_open_done(struct rpc_task *task, void *calldata)
{
struct nfs4_opendata *data = calldata;
data->rpc_status = task->tk_status;
if (!nfs4_sequence_done(task, &data->o_res.seq_res))
return;
if (task->tk_status == 0) {
if (data->o_res.f_attr->valid & NFS_ATTR_FATTR_TYPE) {
switch (data->o_res.f_attr->mode & S_IFMT) {
case S_IFREG:
break;
case S_IFLNK:
data->rpc_status = -ELOOP;
break;
case S_IFDIR:
data->rpc_status = -EISDIR;
break;
default:
data->rpc_status = -ENOTDIR;
}
}
renew_lease(data->o_res.server, data->timestamp);
if (!(data->o_res.rflags & NFS4_OPEN_RESULT_CONFIRM))
nfs_confirm_seqid(&data->owner->so_seqid, 0);
}
data->rpc_done = 1;
}
static void nfs4_open_release(void *calldata)
{
struct nfs4_opendata *data = calldata;
struct nfs4_state *state = NULL;
/* If this request hasn't been cancelled, do nothing */
if (data->cancelled == 0)
goto out_free;
/* In case of error, no cleanup! */
if (data->rpc_status != 0 || !data->rpc_done)
goto out_free;
/* In case we need an open_confirm, no cleanup! */
if (data->o_res.rflags & NFS4_OPEN_RESULT_CONFIRM)
goto out_free;
state = nfs4_opendata_to_nfs4_state(data);
if (!IS_ERR(state))
nfs4_close_state(state, data->o_arg.fmode);
out_free:
nfs4_opendata_put(data);
}
static const struct rpc_call_ops nfs4_open_ops = {
.rpc_call_prepare = nfs4_open_prepare,
.rpc_call_done = nfs4_open_done,
.rpc_release = nfs4_open_release,
};
static const struct rpc_call_ops nfs4_recover_open_ops = {
.rpc_call_prepare = nfs4_recover_open_prepare,
.rpc_call_done = nfs4_open_done,
.rpc_release = nfs4_open_release,
};
static int nfs4_run_open_task(struct nfs4_opendata *data, int isrecover)
{
struct inode *dir = data->dir->d_inode;
struct nfs_server *server = NFS_SERVER(dir);
struct nfs_openargs *o_arg = &data->o_arg;
struct nfs_openres *o_res = &data->o_res;
struct rpc_task *task;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN],
.rpc_argp = o_arg,
.rpc_resp = o_res,
.rpc_cred = data->owner->so_cred,
};
struct rpc_task_setup task_setup_data = {
.rpc_client = server->client,
.rpc_message = &msg,
.callback_ops = &nfs4_open_ops,
.callback_data = data,
.workqueue = nfsiod_workqueue,
.flags = RPC_TASK_ASYNC,
};
int status;
nfs41_init_sequence(&o_arg->seq_args, &o_res->seq_res, 1);
kref_get(&data->kref);
data->rpc_done = 0;
data->rpc_status = 0;
data->cancelled = 0;
if (isrecover)
task_setup_data.callback_ops = &nfs4_recover_open_ops;
task = rpc_run_task(&task_setup_data);
if (IS_ERR(task))
return PTR_ERR(task);
status = nfs4_wait_for_completion_rpc_task(task);
if (status != 0) {
data->cancelled = 1;
smp_wmb();
} else
status = data->rpc_status;
rpc_put_task(task);
return status;
}
static int _nfs4_recover_proc_open(struct nfs4_opendata *data)
{
struct inode *dir = data->dir->d_inode;
struct nfs_openres *o_res = &data->o_res;
int status;
status = nfs4_run_open_task(data, 1);
if (status != 0 || !data->rpc_done)
return status;
nfs_fattr_map_and_free_names(NFS_SERVER(dir), &data->f_attr);
if (o_res->rflags & NFS4_OPEN_RESULT_CONFIRM) {
status = _nfs4_proc_open_confirm(data);
if (status != 0)
return status;
}
return status;
}
static int nfs4_opendata_access(struct rpc_cred *cred,
struct nfs4_opendata *opendata,
struct nfs4_state *state, fmode_t fmode)
{
struct nfs_access_entry cache;
u32 mask;
/* access call failed or for some reason the server doesn't
* support any access modes -- defer access call until later */
if (opendata->o_res.access_supported == 0)
return 0;
mask = 0;
/* don't check MAY_WRITE - a newly created file may not have
* write mode bits, but POSIX allows the creating process to write */
if (fmode & FMODE_READ)
mask |= MAY_READ;
if (fmode & FMODE_EXEC)
mask |= MAY_EXEC;
cache.cred = cred;
cache.jiffies = jiffies;
nfs_access_set_mask(&cache, opendata->o_res.access_result);
nfs_access_add_cache(state->inode, &cache);
if ((mask & ~cache.mask & (MAY_READ | MAY_EXEC)) == 0)
return 0;
/* even though OPEN succeeded, access is denied. Close the file */
nfs4_close_state(state, fmode);
return -EACCES;
}
/*
* Note: On error, nfs4_proc_open will free the struct nfs4_opendata
*/
static int _nfs4_proc_open(struct nfs4_opendata *data)
{
struct inode *dir = data->dir->d_inode;
struct nfs_server *server = NFS_SERVER(dir);
struct nfs_openargs *o_arg = &data->o_arg;
struct nfs_openres *o_res = &data->o_res;
int status;
status = nfs4_run_open_task(data, 0);
if (!data->rpc_done)
return status;
if (status != 0) {
if (status == -NFS4ERR_BADNAME &&
!(o_arg->open_flags & O_CREAT))
return -ENOENT;
return status;
}
nfs_fattr_map_and_free_names(server, &data->f_attr);
if (o_arg->open_flags & O_CREAT)
update_changeattr(dir, &o_res->cinfo);
if ((o_res->rflags & NFS4_OPEN_RESULT_LOCKTYPE_POSIX) == 0)
server->caps &= ~NFS_CAP_POSIX_LOCK;
if(o_res->rflags & NFS4_OPEN_RESULT_CONFIRM) {
status = _nfs4_proc_open_confirm(data);
if (status != 0)
return status;
}
if (!(o_res->f_attr->valid & NFS_ATTR_FATTR))
_nfs4_proc_getattr(server, &o_res->fh, o_res->f_attr);
return 0;
}
static int nfs4_client_recover_expired_lease(struct nfs_client *clp)
{
unsigned int loop;
int ret;
for (loop = NFS4_MAX_LOOP_ON_RECOVER; loop != 0; loop--) {
ret = nfs4_wait_clnt_recover(clp);
if (ret != 0)
break;
if (!test_bit(NFS4CLNT_LEASE_EXPIRED, &clp->cl_state) &&
!test_bit(NFS4CLNT_CHECK_LEASE,&clp->cl_state))
break;
nfs4_schedule_state_manager(clp);
ret = -EIO;
}
return ret;
}
static int nfs4_recover_expired_lease(struct nfs_server *server)
{
return nfs4_client_recover_expired_lease(server->nfs_client);
}
/*
* OPEN_EXPIRED:
* reclaim state on the server after a network partition.
* Assumes caller holds the appropriate lock
*/
static int _nfs4_open_expired(struct nfs_open_context *ctx, struct nfs4_state *state)
{
struct nfs4_opendata *opendata;
int ret;
opendata = nfs4_open_recoverdata_alloc(ctx, state);
if (IS_ERR(opendata))
return PTR_ERR(opendata);
ret = nfs4_open_recover(opendata, state);
if (ret == -ESTALE)
d_drop(ctx->dentry);
nfs4_opendata_put(opendata);
return ret;
}
static int nfs4_do_open_expired(struct nfs_open_context *ctx, struct nfs4_state *state)
{
struct nfs_server *server = NFS_SERVER(state->inode);
struct nfs4_exception exception = { };
int err;
do {
err = _nfs4_open_expired(ctx, state);
switch (err) {
default:
goto out;
case -NFS4ERR_GRACE:
case -NFS4ERR_DELAY:
nfs4_handle_exception(server, err, &exception);
err = 0;
}
} while (exception.retry);
out:
return err;
}
static int nfs4_open_expired(struct nfs4_state_owner *sp, struct nfs4_state *state)
{
struct nfs_open_context *ctx;
int ret;
ctx = nfs4_state_find_open_context(state);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
ret = nfs4_do_open_expired(ctx, state);
put_nfs_open_context(ctx);
return ret;
}
#if defined(CONFIG_NFS_V4_1)
static void nfs41_clear_delegation_stateid(struct nfs4_state *state)
{
struct nfs_server *server = NFS_SERVER(state->inode);
nfs4_stateid *stateid = &state->stateid;
int status;
/* If a state reset has been done, test_stateid is unneeded */
if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0)
return;
status = nfs41_test_stateid(server, stateid);
if (status != NFS_OK) {
/* Free the stateid unless the server explicitly
* informs us the stateid is unrecognized. */
if (status != -NFS4ERR_BAD_STATEID)
nfs41_free_stateid(server, stateid);
nfs_remove_bad_delegation(state->inode);
write_seqlock(&state->seqlock);
nfs4_stateid_copy(&state->stateid, &state->open_stateid);
write_sequnlock(&state->seqlock);
clear_bit(NFS_DELEGATED_STATE, &state->flags);
}
}
/**
* nfs41_check_open_stateid - possibly free an open stateid
*
* @state: NFSv4 state for an inode
*
* Returns NFS_OK if recovery for this stateid is now finished.
* Otherwise a negative NFS4ERR value is returned.
*/
static int nfs41_check_open_stateid(struct nfs4_state *state)
{
struct nfs_server *server = NFS_SERVER(state->inode);
nfs4_stateid *stateid = &state->open_stateid;
int status;
/* If a state reset has been done, test_stateid is unneeded */
if ((test_bit(NFS_O_RDONLY_STATE, &state->flags) == 0) &&
(test_bit(NFS_O_WRONLY_STATE, &state->flags) == 0) &&
(test_bit(NFS_O_RDWR_STATE, &state->flags) == 0))
return -NFS4ERR_BAD_STATEID;
status = nfs41_test_stateid(server, stateid);
if (status != NFS_OK) {
/* Free the stateid unless the server explicitly
* informs us the stateid is unrecognized. */
if (status != -NFS4ERR_BAD_STATEID)
nfs41_free_stateid(server, stateid);
clear_bit(NFS_O_RDONLY_STATE, &state->flags);
clear_bit(NFS_O_WRONLY_STATE, &state->flags);
clear_bit(NFS_O_RDWR_STATE, &state->flags);
}
return status;
}
static int nfs41_open_expired(struct nfs4_state_owner *sp, struct nfs4_state *state)
{
int status;
nfs41_clear_delegation_stateid(state);
status = nfs41_check_open_stateid(state);
if (status != NFS_OK)
status = nfs4_open_expired(sp, state);
return status;
}
#endif
/*
* on an EXCLUSIVE create, the server should send back a bitmask with FATTR4-*
* fields corresponding to attributes that were used to store the verifier.
* Make sure we clobber those fields in the later setattr call
*/
static inline void nfs4_exclusive_attrset(struct nfs4_opendata *opendata, struct iattr *sattr)
{
if ((opendata->o_res.attrset[1] & FATTR4_WORD1_TIME_ACCESS) &&
!(sattr->ia_valid & ATTR_ATIME_SET))
sattr->ia_valid |= ATTR_ATIME;
if ((opendata->o_res.attrset[1] & FATTR4_WORD1_TIME_MODIFY) &&
!(sattr->ia_valid & ATTR_MTIME_SET))
sattr->ia_valid |= ATTR_MTIME;
}
/*
* Returns a referenced nfs4_state
*/
static int _nfs4_do_open(struct inode *dir,
struct dentry *dentry,
fmode_t fmode,
int flags,
struct iattr *sattr,
struct rpc_cred *cred,
struct nfs4_state **res,
struct nfs4_threshold **ctx_th)
{
struct nfs4_state_owner *sp;
struct nfs4_state *state = NULL;
struct nfs_server *server = NFS_SERVER(dir);
struct nfs4_opendata *opendata;
int status;
/* Protect against reboot recovery conflicts */
status = -ENOMEM;
sp = nfs4_get_state_owner(server, cred, GFP_KERNEL);
if (sp == NULL) {
dprintk("nfs4_do_open: nfs4_get_state_owner failed!\n");
goto out_err;
}
status = nfs4_recover_expired_lease(server);
if (status != 0)
goto err_put_state_owner;
if (dentry->d_inode != NULL)
nfs4_return_incompatible_delegation(dentry->d_inode, fmode);
status = -ENOMEM;
opendata = nfs4_opendata_alloc(dentry, sp, fmode, flags, sattr, GFP_KERNEL);
if (opendata == NULL)
goto err_put_state_owner;
if (ctx_th && server->attr_bitmask[2] & FATTR4_WORD2_MDSTHRESHOLD) {
opendata->f_attr.mdsthreshold = pnfs_mdsthreshold_alloc();
if (!opendata->f_attr.mdsthreshold)
goto err_opendata_put;
opendata->o_arg.open_bitmap = &nfs4_pnfs_open_bitmap[0];
}
if (dentry->d_inode != NULL)
opendata->state = nfs4_get_open_state(dentry->d_inode, sp);
status = _nfs4_proc_open(opendata);
if (status != 0)
goto err_opendata_put;
state = nfs4_opendata_to_nfs4_state(opendata);
status = PTR_ERR(state);
if (IS_ERR(state))
goto err_opendata_put;
if (server->caps & NFS_CAP_POSIX_LOCK)
set_bit(NFS_STATE_POSIX_LOCKS, &state->flags);
status = nfs4_opendata_access(cred, opendata, state, fmode);
if (status != 0)
goto err_opendata_put;
if (opendata->o_arg.open_flags & O_EXCL) {
nfs4_exclusive_attrset(opendata, sattr);
nfs_fattr_init(opendata->o_res.f_attr);
status = nfs4_do_setattr(state->inode, cred,
opendata->o_res.f_attr, sattr,
state);
if (status == 0)
nfs_setattr_update_inode(state->inode, sattr);
nfs_post_op_update_inode(state->inode, opendata->o_res.f_attr);
}
if (pnfs_use_threshold(ctx_th, opendata->f_attr.mdsthreshold, server))
*ctx_th = opendata->f_attr.mdsthreshold;
else
kfree(opendata->f_attr.mdsthreshold);
opendata->f_attr.mdsthreshold = NULL;
nfs4_opendata_put(opendata);
nfs4_put_state_owner(sp);
*res = state;
return 0;
err_opendata_put:
kfree(opendata->f_attr.mdsthreshold);
nfs4_opendata_put(opendata);
err_put_state_owner:
nfs4_put_state_owner(sp);
out_err:
*res = NULL;
return status;
}
static struct nfs4_state *nfs4_do_open(struct inode *dir,
struct dentry *dentry,
fmode_t fmode,
int flags,
struct iattr *sattr,
struct rpc_cred *cred,
struct nfs4_threshold **ctx_th)
{
struct nfs4_exception exception = { };
struct nfs4_state *res;
int status;
fmode &= FMODE_READ|FMODE_WRITE|FMODE_EXEC;
do {
status = _nfs4_do_open(dir, dentry, fmode, flags, sattr, cred,
&res, ctx_th);
if (status == 0)
break;
/* NOTE: BAD_SEQID means the server and client disagree about the
* book-keeping w.r.t. state-changing operations
* (OPEN/CLOSE/LOCK/LOCKU...)
* It is actually a sign of a bug on the client or on the server.
*
* If we receive a BAD_SEQID error in the particular case of
* doing an OPEN, we assume that nfs_increment_open_seqid() will
* have unhashed the old state_owner for us, and that we can
* therefore safely retry using a new one. We should still warn
* the user though...
*/
if (status == -NFS4ERR_BAD_SEQID) {
pr_warn_ratelimited("NFS: v4 server %s "
" returned a bad sequence-id error!\n",
NFS_SERVER(dir)->nfs_client->cl_hostname);
exception.retry = 1;
continue;
}
/*
* BAD_STATEID on OPEN means that the server cancelled our
* state before it received the OPEN_CONFIRM.
* Recover by retrying the request as per the discussion
* on Page 181 of RFC3530.
*/
if (status == -NFS4ERR_BAD_STATEID) {
exception.retry = 1;
continue;
}
if (status == -EAGAIN) {
/* We must have found a delegation */
exception.retry = 1;
continue;
}
res = ERR_PTR(nfs4_handle_exception(NFS_SERVER(dir),
status, &exception));
} while (exception.retry);
return res;
}
static int _nfs4_do_setattr(struct inode *inode, struct rpc_cred *cred,
struct nfs_fattr *fattr, struct iattr *sattr,
struct nfs4_state *state)
{
struct nfs_server *server = NFS_SERVER(inode);
struct nfs_setattrargs arg = {
.fh = NFS_FH(inode),
.iap = sattr,
.server = server,
.bitmask = server->attr_bitmask,
};
struct nfs_setattrres res = {
.fattr = fattr,
.server = server,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SETATTR],
.rpc_argp = &arg,
.rpc_resp = &res,
.rpc_cred = cred,
};
unsigned long timestamp = jiffies;
int status;
nfs_fattr_init(fattr);
if (state != NULL) {
struct nfs_lockowner lockowner = {
.l_owner = current->files,
.l_pid = current->tgid,
};
nfs4_select_rw_stateid(&arg.stateid, state, FMODE_WRITE,
&lockowner);
} else if (nfs4_copy_delegation_stateid(&arg.stateid, inode,
FMODE_WRITE)) {
/* Use that stateid */
} else
nfs4_stateid_copy(&arg.stateid, &zero_stateid);
status = nfs4_call_sync(server->client, server, &msg, &arg.seq_args, &res.seq_res, 1);
if (status == 0 && state != NULL)
renew_lease(server, timestamp);
return status;
}
static int nfs4_do_setattr(struct inode *inode, struct rpc_cred *cred,
struct nfs_fattr *fattr, struct iattr *sattr,
struct nfs4_state *state)
{
struct nfs_server *server = NFS_SERVER(inode);
struct nfs4_exception exception = {
.state = state,
.inode = inode,
};
int err;
do {
err = _nfs4_do_setattr(inode, cred, fattr, sattr, state);
switch (err) {
case -NFS4ERR_OPENMODE:
if (state && !(state->state & FMODE_WRITE)) {
err = -EBADF;
if (sattr->ia_valid & ATTR_OPEN)
err = -EACCES;
goto out;
}
}
err = nfs4_handle_exception(server, err, &exception);
} while (exception.retry);
out:
return err;
}
struct nfs4_closedata {
struct inode *inode;
struct nfs4_state *state;
struct nfs_closeargs arg;
struct nfs_closeres res;
struct nfs_fattr fattr;
unsigned long timestamp;
bool roc;
u32 roc_barrier;
};
static void nfs4_free_closedata(void *data)
{
struct nfs4_closedata *calldata = data;
struct nfs4_state_owner *sp = calldata->state->owner;
struct super_block *sb = calldata->state->inode->i_sb;
if (calldata->roc)
pnfs_roc_release(calldata->state->inode);
nfs4_put_open_state(calldata->state);
nfs_free_seqid(calldata->arg.seqid);
nfs4_put_state_owner(sp);
nfs_sb_deactive_async(sb);
kfree(calldata);
}
static void nfs4_close_clear_stateid_flags(struct nfs4_state *state,
fmode_t fmode)
{
spin_lock(&state->owner->so_lock);
if (!(fmode & FMODE_READ))
clear_bit(NFS_O_RDONLY_STATE, &state->flags);
if (!(fmode & FMODE_WRITE))
clear_bit(NFS_O_WRONLY_STATE, &state->flags);
clear_bit(NFS_O_RDWR_STATE, &state->flags);
spin_unlock(&state->owner->so_lock);
}
static void nfs4_close_done(struct rpc_task *task, void *data)
{
struct nfs4_closedata *calldata = data;
struct nfs4_state *state = calldata->state;
struct nfs_server *server = NFS_SERVER(calldata->inode);
dprintk("%s: begin!\n", __func__);
if (!nfs4_sequence_done(task, &calldata->res.seq_res))
return;
/* hmm. we are done with the inode, and in the process of freeing
* the state_owner. we keep this around to process errors
*/
switch (task->tk_status) {
case 0:
if (calldata->roc)
pnfs_roc_set_barrier(state->inode,
calldata->roc_barrier);
nfs_set_open_stateid(state, &calldata->res.stateid, 0);
renew_lease(server, calldata->timestamp);
nfs4_close_clear_stateid_flags(state,
calldata->arg.fmode);
break;
case -NFS4ERR_STALE_STATEID:
case -NFS4ERR_OLD_STATEID:
case -NFS4ERR_BAD_STATEID:
case -NFS4ERR_EXPIRED:
if (calldata->arg.fmode == 0)
break;
default:
if (nfs4_async_handle_error(task, server, state) == -EAGAIN)
rpc_restart_call_prepare(task);
}
nfs_release_seqid(calldata->arg.seqid);
nfs_refresh_inode(calldata->inode, calldata->res.fattr);
dprintk("%s: done, ret = %d!\n", __func__, task->tk_status);
}
static void nfs4_close_prepare(struct rpc_task *task, void *data)
{
struct nfs4_closedata *calldata = data;
struct nfs4_state *state = calldata->state;
struct inode *inode = calldata->inode;
int call_close = 0;
dprintk("%s: begin!\n", __func__);
if (nfs_wait_on_sequence(calldata->arg.seqid, task) != 0)
return;
task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_DOWNGRADE];
calldata->arg.fmode = FMODE_READ|FMODE_WRITE;
spin_lock(&state->owner->so_lock);
/* Calculate the change in open mode */
if (state->n_rdwr == 0) {
if (state->n_rdonly == 0) {
call_close |= test_bit(NFS_O_RDONLY_STATE, &state->flags);
call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags);
calldata->arg.fmode &= ~FMODE_READ;
}
if (state->n_wronly == 0) {
call_close |= test_bit(NFS_O_WRONLY_STATE, &state->flags);
call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags);
calldata->arg.fmode &= ~FMODE_WRITE;
}
}
spin_unlock(&state->owner->so_lock);
if (!call_close) {
/* Note: exit _without_ calling nfs4_close_done */
task->tk_action = NULL;
goto out;
}
if (calldata->arg.fmode == 0) {
task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_CLOSE];
if (calldata->roc &&
pnfs_roc_drain(inode, &calldata->roc_barrier, task))
goto out;
}
nfs_fattr_init(calldata->res.fattr);
calldata->timestamp = jiffies;
if (nfs4_setup_sequence(NFS_SERVER(inode),
&calldata->arg.seq_args,
&calldata->res.seq_res,
task) != 0)
nfs_release_seqid(calldata->arg.seqid);
else
rpc_call_start(task);
out:
dprintk("%s: done!\n", __func__);
}
static const struct rpc_call_ops nfs4_close_ops = {
.rpc_call_prepare = nfs4_close_prepare,
.rpc_call_done = nfs4_close_done,
.rpc_release = nfs4_free_closedata,
};
/*
* It is possible for data to be read/written from a mem-mapped file
* after the sys_close call (which hits the vfs layer as a flush).
* This means that we can't safely call nfsv4 close on a file until
* the inode is cleared. This in turn means that we are not good
* NFSv4 citizens - we do not indicate to the server to update the file's
* share state even when we are done with one of the three share
* stateid's in the inode.
*
* NOTE: Caller must be holding the sp->so_owner semaphore!
*/
int nfs4_do_close(struct nfs4_state *state, gfp_t gfp_mask, int wait)
{
struct nfs_server *server = NFS_SERVER(state->inode);
struct nfs4_closedata *calldata;
struct nfs4_state_owner *sp = state->owner;
struct rpc_task *task;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_CLOSE],
.rpc_cred = state->owner->so_cred,
};
struct rpc_task_setup task_setup_data = {
.rpc_client = server->client,
.rpc_message = &msg,
.callback_ops = &nfs4_close_ops,
.workqueue = nfsiod_workqueue,
.flags = RPC_TASK_ASYNC,
};
int status = -ENOMEM;
calldata = kzalloc(sizeof(*calldata), gfp_mask);
if (calldata == NULL)
goto out;
nfs41_init_sequence(&calldata->arg.seq_args, &calldata->res.seq_res, 1);
calldata->inode = state->inode;
calldata->state = state;
calldata->arg.fh = NFS_FH(state->inode);
calldata->arg.stateid = &state->open_stateid;
/* Serialization for the sequence id */
calldata->arg.seqid = nfs_alloc_seqid(&state->owner->so_seqid, gfp_mask);
if (calldata->arg.seqid == NULL)
goto out_free_calldata;
calldata->arg.fmode = 0;
calldata->arg.bitmask = server->cache_consistency_bitmask;
calldata->res.fattr = &calldata->fattr;
calldata->res.seqid = calldata->arg.seqid;
calldata->res.server = server;
calldata->roc = pnfs_roc(state->inode);
nfs_sb_active(calldata->inode->i_sb);
msg.rpc_argp = &calldata->arg;
msg.rpc_resp = &calldata->res;
task_setup_data.callback_data = calldata;
task = rpc_run_task(&task_setup_data);
if (IS_ERR(task))
return PTR_ERR(task);
status = 0;
if (wait)
status = rpc_wait_for_completion_task(task);
rpc_put_task(task);
return status;
out_free_calldata:
kfree(calldata);
out:
nfs4_put_open_state(state);
nfs4_put_state_owner(sp);
return status;
}
static struct inode *
nfs4_atomic_open(struct inode *dir, struct nfs_open_context *ctx, int open_flags, struct iattr *attr)
{
struct nfs4_state *state;
/* Protect against concurrent sillydeletes */
state = nfs4_do_open(dir, ctx->dentry, ctx->mode, open_flags, attr,
ctx->cred, &ctx->mdsthreshold);
if (IS_ERR(state))
return ERR_CAST(state);
ctx->state = state;
return igrab(state->inode);
}
static void nfs4_close_context(struct nfs_open_context *ctx, int is_sync)
{
if (ctx->state == NULL)
return;
if (is_sync)
nfs4_close_sync(ctx->state, ctx->mode);
else
nfs4_close_state(ctx->state, ctx->mode);
}
static int _nfs4_server_capabilities(struct nfs_server *server, struct nfs_fh *fhandle)
{
struct nfs4_server_caps_arg args = {
.fhandle = fhandle,
};
struct nfs4_server_caps_res res = {};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SERVER_CAPS],
.rpc_argp = &args,
.rpc_resp = &res,
};
int status;
status = nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
if (status == 0) {
memcpy(server->attr_bitmask, res.attr_bitmask, sizeof(server->attr_bitmask));
server->caps &= ~(NFS_CAP_ACLS|NFS_CAP_HARDLINKS|
NFS_CAP_SYMLINKS|NFS_CAP_FILEID|
NFS_CAP_MODE|NFS_CAP_NLINK|NFS_CAP_OWNER|
NFS_CAP_OWNER_GROUP|NFS_CAP_ATIME|
NFS_CAP_CTIME|NFS_CAP_MTIME);
if (res.attr_bitmask[0] & FATTR4_WORD0_ACL)
server->caps |= NFS_CAP_ACLS;
if (res.has_links != 0)
server->caps |= NFS_CAP_HARDLINKS;
if (res.has_symlinks != 0)
server->caps |= NFS_CAP_SYMLINKS;
if (res.attr_bitmask[0] & FATTR4_WORD0_FILEID)
server->caps |= NFS_CAP_FILEID;
if (res.attr_bitmask[1] & FATTR4_WORD1_MODE)
server->caps |= NFS_CAP_MODE;
if (res.attr_bitmask[1] & FATTR4_WORD1_NUMLINKS)
server->caps |= NFS_CAP_NLINK;
if (res.attr_bitmask[1] & FATTR4_WORD1_OWNER)
server->caps |= NFS_CAP_OWNER;
if (res.attr_bitmask[1] & FATTR4_WORD1_OWNER_GROUP)
server->caps |= NFS_CAP_OWNER_GROUP;
if (res.attr_bitmask[1] & FATTR4_WORD1_TIME_ACCESS)
server->caps |= NFS_CAP_ATIME;
if (res.attr_bitmask[1] & FATTR4_WORD1_TIME_METADATA)
server->caps |= NFS_CAP_CTIME;
if (res.attr_bitmask[1] & FATTR4_WORD1_TIME_MODIFY)
server->caps |= NFS_CAP_MTIME;
memcpy(server->cache_consistency_bitmask, res.attr_bitmask, sizeof(server->cache_consistency_bitmask));
server->cache_consistency_bitmask[0] &= FATTR4_WORD0_CHANGE|FATTR4_WORD0_SIZE;
server->cache_consistency_bitmask[1] &= FATTR4_WORD1_TIME_METADATA|FATTR4_WORD1_TIME_MODIFY;
server->acl_bitmask = res.acl_bitmask;
server->fh_expire_type = res.fh_expire_type;
}
return status;
}
int nfs4_server_capabilities(struct nfs_server *server, struct nfs_fh *fhandle)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(server,
_nfs4_server_capabilities(server, fhandle),
&exception);
} while (exception.retry);
return err;
}
static int _nfs4_lookup_root(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fsinfo *info)
{
struct nfs4_lookup_root_arg args = {
.bitmask = nfs4_fattr_bitmap,
};
struct nfs4_lookup_res res = {
.server = server,
.fattr = info->fattr,
.fh = fhandle,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LOOKUP_ROOT],
.rpc_argp = &args,
.rpc_resp = &res,
};
nfs_fattr_init(info->fattr);
return nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
}
static int nfs4_lookup_root(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fsinfo *info)
{
struct nfs4_exception exception = { };
int err;
do {
err = _nfs4_lookup_root(server, fhandle, info);
switch (err) {
case 0:
case -NFS4ERR_WRONGSEC:
goto out;
default:
err = nfs4_handle_exception(server, err, &exception);
}
} while (exception.retry);
out:
return err;
}
static int nfs4_lookup_root_sec(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fsinfo *info, rpc_authflavor_t flavor)
{
struct rpc_auth *auth;
int ret;
auth = rpcauth_create(flavor, server->client);
if (IS_ERR(auth)) {
ret = -EIO;
goto out;
}
ret = nfs4_lookup_root(server, fhandle, info);
out:
return ret;
}
static int nfs4_find_root_sec(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fsinfo *info)
{
int i, len, status = 0;
rpc_authflavor_t flav_array[NFS_MAX_SECFLAVORS];
len = rpcauth_list_flavors(flav_array, ARRAY_SIZE(flav_array));
BUG_ON(len < 0);
for (i = 0; i < len; i++) {
/* AUTH_UNIX is the default flavor if none was specified,
* thus has already been tried. */
if (flav_array[i] == RPC_AUTH_UNIX)
continue;
status = nfs4_lookup_root_sec(server, fhandle, info, flav_array[i]);
if (status == -NFS4ERR_WRONGSEC || status == -EACCES)
continue;
break;
}
/*
* -EACCESS could mean that the user doesn't have correct permissions
* to access the mount. It could also mean that we tried to mount
* with a gss auth flavor, but rpc.gssd isn't running. Either way,
* existing mount programs don't handle -EACCES very well so it should
* be mapped to -EPERM instead.
*/
if (status == -EACCES)
status = -EPERM;
return status;
}
/*
* get the file handle for the "/" directory on the server
*/
int nfs4_proc_get_rootfh(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fsinfo *info)
{
int minor_version = server->nfs_client->cl_minorversion;
int status = nfs4_lookup_root(server, fhandle, info);
if ((status == -NFS4ERR_WRONGSEC) && !(server->flags & NFS_MOUNT_SECFLAVOUR))
/*
* A status of -NFS4ERR_WRONGSEC will be mapped to -EPERM
* by nfs4_map_errors() as this function exits.
*/
status = nfs_v4_minor_ops[minor_version]->find_root_sec(server, fhandle, info);
if (status == 0)
status = nfs4_server_capabilities(server, fhandle);
if (status == 0)
status = nfs4_do_fsinfo(server, fhandle, info);
return nfs4_map_errors(status);
}
static int nfs4_proc_get_root(struct nfs_server *server, struct nfs_fh *mntfh,
struct nfs_fsinfo *info)
{
int error;
struct nfs_fattr *fattr = info->fattr;
error = nfs4_server_capabilities(server, mntfh);
if (error < 0) {
dprintk("nfs4_get_root: getcaps error = %d\n", -error);
return error;
}
error = nfs4_proc_getattr(server, mntfh, fattr);
if (error < 0) {
dprintk("nfs4_get_root: getattr error = %d\n", -error);
return error;
}
if (fattr->valid & NFS_ATTR_FATTR_FSID &&
!nfs_fsid_equal(&server->fsid, &fattr->fsid))
memcpy(&server->fsid, &fattr->fsid, sizeof(server->fsid));
return error;
}
/*
* Get locations and (maybe) other attributes of a referral.
* Note that we'll actually follow the referral later when
* we detect fsid mismatch in inode revalidation
*/
static int nfs4_get_referral(struct rpc_clnt *client, struct inode *dir,
const struct qstr *name, struct nfs_fattr *fattr,
struct nfs_fh *fhandle)
{
int status = -ENOMEM;
struct page *page = NULL;
struct nfs4_fs_locations *locations = NULL;
page = alloc_page(GFP_KERNEL);
if (page == NULL)
goto out;
locations = kmalloc(sizeof(struct nfs4_fs_locations), GFP_KERNEL);
if (locations == NULL)
goto out;
status = nfs4_proc_fs_locations(client, dir, name, locations, page);
if (status != 0)
goto out;
/* Make sure server returned a different fsid for the referral */
if (nfs_fsid_equal(&NFS_SERVER(dir)->fsid, &locations->fattr.fsid)) {
dprintk("%s: server did not return a different fsid for"
" a referral at %s\n", __func__, name->name);
status = -EIO;
goto out;
}
/* Fixup attributes for the nfs_lookup() call to nfs_fhget() */
nfs_fixup_referral_attributes(&locations->fattr);
/* replace the lookup nfs_fattr with the locations nfs_fattr */
memcpy(fattr, &locations->fattr, sizeof(struct nfs_fattr));
memset(fhandle, 0, sizeof(struct nfs_fh));
out:
if (page)
__free_page(page);
kfree(locations);
return status;
}
static int _nfs4_proc_getattr(struct nfs_server *server, struct nfs_fh *fhandle, struct nfs_fattr *fattr)
{
struct nfs4_getattr_arg args = {
.fh = fhandle,
.bitmask = server->attr_bitmask,
};
struct nfs4_getattr_res res = {
.fattr = fattr,
.server = server,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETATTR],
.rpc_argp = &args,
.rpc_resp = &res,
};
nfs_fattr_init(fattr);
return nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
}
static int nfs4_proc_getattr(struct nfs_server *server, struct nfs_fh *fhandle, struct nfs_fattr *fattr)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(server,
_nfs4_proc_getattr(server, fhandle, fattr),
&exception);
} while (exception.retry);
return err;
}
/*
* The file is not closed if it is opened due to the a request to change
* the size of the file. The open call will not be needed once the
* VFS layer lookup-intents are implemented.
*
* Close is called when the inode is destroyed.
* If we haven't opened the file for O_WRONLY, we
* need to in the size_change case to obtain a stateid.
*
* Got race?
* Because OPEN is always done by name in nfsv4, it is
* possible that we opened a different file by the same
* name. We can recognize this race condition, but we
* can't do anything about it besides returning an error.
*
* This will be fixed with VFS changes (lookup-intent).
*/
static int
nfs4_proc_setattr(struct dentry *dentry, struct nfs_fattr *fattr,
struct iattr *sattr)
{
struct inode *inode = dentry->d_inode;
struct rpc_cred *cred = NULL;
struct nfs4_state *state = NULL;
int status;
if (pnfs_ld_layoutret_on_setattr(inode))
pnfs_return_layout(inode);
nfs_fattr_init(fattr);
/* Deal with open(O_TRUNC) */
if (sattr->ia_valid & ATTR_OPEN)
sattr->ia_valid &= ~(ATTR_MTIME|ATTR_CTIME|ATTR_OPEN);
/* Optimization: if the end result is no change, don't RPC */
if ((sattr->ia_valid & ~(ATTR_FILE)) == 0)
return 0;
/* Search for an existing open(O_WRITE) file */
if (sattr->ia_valid & ATTR_FILE) {
struct nfs_open_context *ctx;
ctx = nfs_file_open_context(sattr->ia_file);
if (ctx) {
cred = ctx->cred;
state = ctx->state;
}
}
status = nfs4_do_setattr(inode, cred, fattr, sattr, state);
if (status == 0)
nfs_setattr_update_inode(inode, sattr);
return status;
}
static int _nfs4_proc_lookup(struct rpc_clnt *clnt, struct inode *dir,
const struct qstr *name, struct nfs_fh *fhandle,
struct nfs_fattr *fattr)
{
struct nfs_server *server = NFS_SERVER(dir);
int status;
struct nfs4_lookup_arg args = {
.bitmask = server->attr_bitmask,
.dir_fh = NFS_FH(dir),
.name = name,
};
struct nfs4_lookup_res res = {
.server = server,
.fattr = fattr,
.fh = fhandle,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LOOKUP],
.rpc_argp = &args,
.rpc_resp = &res,
};
nfs_fattr_init(fattr);
dprintk("NFS call lookup %s\n", name->name);
status = nfs4_call_sync(clnt, server, &msg, &args.seq_args, &res.seq_res, 0);
dprintk("NFS reply lookup: %d\n", status);
return status;
}
static void nfs_fixup_secinfo_attributes(struct nfs_fattr *fattr)
{
fattr->valid |= NFS_ATTR_FATTR_TYPE | NFS_ATTR_FATTR_MODE |
NFS_ATTR_FATTR_NLINK | NFS_ATTR_FATTR_MOUNTPOINT;
fattr->mode = S_IFDIR | S_IRUGO | S_IXUGO;
fattr->nlink = 2;
}
static int nfs4_proc_lookup_common(struct rpc_clnt **clnt, struct inode *dir,
struct qstr *name, struct nfs_fh *fhandle,
struct nfs_fattr *fattr)
{
struct nfs4_exception exception = { };
struct rpc_clnt *client = *clnt;
int err;
do {
err = _nfs4_proc_lookup(client, dir, name, fhandle, fattr);
switch (err) {
case -NFS4ERR_BADNAME:
err = -ENOENT;
goto out;
case -NFS4ERR_MOVED:
err = nfs4_get_referral(client, dir, name, fattr, fhandle);
goto out;
case -NFS4ERR_WRONGSEC:
err = -EPERM;
if (client != *clnt)
goto out;
client = nfs4_create_sec_client(client, dir, name);
if (IS_ERR(client))
return PTR_ERR(client);
exception.retry = 1;
break;
default:
err = nfs4_handle_exception(NFS_SERVER(dir), err, &exception);
}
} while (exception.retry);
out:
if (err == 0)
*clnt = client;
else if (client != *clnt)
rpc_shutdown_client(client);
return err;
}
static int nfs4_proc_lookup(struct inode *dir, struct qstr *name,
struct nfs_fh *fhandle, struct nfs_fattr *fattr)
{
int status;
struct rpc_clnt *client = NFS_CLIENT(dir);
status = nfs4_proc_lookup_common(&client, dir, name, fhandle, fattr);
if (client != NFS_CLIENT(dir)) {
rpc_shutdown_client(client);
nfs_fixup_secinfo_attributes(fattr);
}
return status;
}
struct rpc_clnt *
nfs4_proc_lookup_mountpoint(struct inode *dir, struct qstr *name,
struct nfs_fh *fhandle, struct nfs_fattr *fattr)
{
int status;
struct rpc_clnt *client = rpc_clone_client(NFS_CLIENT(dir));
status = nfs4_proc_lookup_common(&client, dir, name, fhandle, fattr);
if (status < 0) {
rpc_shutdown_client(client);
return ERR_PTR(status);
}
return client;
}
static int _nfs4_proc_access(struct inode *inode, struct nfs_access_entry *entry)
{
struct nfs_server *server = NFS_SERVER(inode);
struct nfs4_accessargs args = {
.fh = NFS_FH(inode),
.bitmask = server->cache_consistency_bitmask,
};
struct nfs4_accessres res = {
.server = server,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_ACCESS],
.rpc_argp = &args,
.rpc_resp = &res,
.rpc_cred = entry->cred,
};
int mode = entry->mask;
int status;
/*
* Determine which access bits we want to ask for...
*/
if (mode & MAY_READ)
args.access |= NFS4_ACCESS_READ;
if (S_ISDIR(inode->i_mode)) {
if (mode & MAY_WRITE)
args.access |= NFS4_ACCESS_MODIFY | NFS4_ACCESS_EXTEND | NFS4_ACCESS_DELETE;
if (mode & MAY_EXEC)
args.access |= NFS4_ACCESS_LOOKUP;
} else {
if (mode & MAY_WRITE)
args.access |= NFS4_ACCESS_MODIFY | NFS4_ACCESS_EXTEND;
if (mode & MAY_EXEC)
args.access |= NFS4_ACCESS_EXECUTE;
}
res.fattr = nfs_alloc_fattr();
if (res.fattr == NULL)
return -ENOMEM;
status = nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
if (!status) {
nfs_access_set_mask(entry, res.access);
nfs_refresh_inode(inode, res.fattr);
}
nfs_free_fattr(res.fattr);
return status;
}
static int nfs4_proc_access(struct inode *inode, struct nfs_access_entry *entry)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(NFS_SERVER(inode),
_nfs4_proc_access(inode, entry),
&exception);
} while (exception.retry);
return err;
}
/*
* TODO: For the time being, we don't try to get any attributes
* along with any of the zero-copy operations READ, READDIR,
* READLINK, WRITE.
*
* In the case of the first three, we want to put the GETATTR
* after the read-type operation -- this is because it is hard
* to predict the length of a GETATTR response in v4, and thus
* align the READ data correctly. This means that the GETATTR
* may end up partially falling into the page cache, and we should
* shift it into the 'tail' of the xdr_buf before processing.
* To do this efficiently, we need to know the total length
* of data received, which doesn't seem to be available outside
* of the RPC layer.
*
* In the case of WRITE, we also want to put the GETATTR after
* the operation -- in this case because we want to make sure
* we get the post-operation mtime and size.
*
* Both of these changes to the XDR layer would in fact be quite
* minor, but I decided to leave them for a subsequent patch.
*/
static int _nfs4_proc_readlink(struct inode *inode, struct page *page,
unsigned int pgbase, unsigned int pglen)
{
struct nfs4_readlink args = {
.fh = NFS_FH(inode),
.pgbase = pgbase,
.pglen = pglen,
.pages = &page,
};
struct nfs4_readlink_res res;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_READLINK],
.rpc_argp = &args,
.rpc_resp = &res,
};
return nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode), &msg, &args.seq_args, &res.seq_res, 0);
}
static int nfs4_proc_readlink(struct inode *inode, struct page *page,
unsigned int pgbase, unsigned int pglen)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(NFS_SERVER(inode),
_nfs4_proc_readlink(inode, page, pgbase, pglen),
&exception);
} while (exception.retry);
return err;
}
/*
* This is just for mknod. open(O_CREAT) will always do ->open_context().
*/
static int
nfs4_proc_create(struct inode *dir, struct dentry *dentry, struct iattr *sattr,
int flags)
{
struct nfs_open_context *ctx;
struct nfs4_state *state;
int status = 0;
ctx = alloc_nfs_open_context(dentry, FMODE_READ);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
sattr->ia_mode &= ~current_umask();
state = nfs4_do_open(dir, dentry, ctx->mode,
flags, sattr, ctx->cred,
&ctx->mdsthreshold);
d_drop(dentry);
if (IS_ERR(state)) {
status = PTR_ERR(state);
goto out;
}
d_add(dentry, igrab(state->inode));
nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
ctx->state = state;
out:
put_nfs_open_context(ctx);
return status;
}
static int _nfs4_proc_remove(struct inode *dir, struct qstr *name)
{
struct nfs_server *server = NFS_SERVER(dir);
struct nfs_removeargs args = {
.fh = NFS_FH(dir),
.name = *name,
};
struct nfs_removeres res = {
.server = server,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_REMOVE],
.rpc_argp = &args,
.rpc_resp = &res,
};
int status;
status = nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 1);
if (status == 0)
update_changeattr(dir, &res.cinfo);
return status;
}
static int nfs4_proc_remove(struct inode *dir, struct qstr *name)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(NFS_SERVER(dir),
_nfs4_proc_remove(dir, name),
&exception);
} while (exception.retry);
return err;
}
static void nfs4_proc_unlink_setup(struct rpc_message *msg, struct inode *dir)
{
struct nfs_server *server = NFS_SERVER(dir);
struct nfs_removeargs *args = msg->rpc_argp;
struct nfs_removeres *res = msg->rpc_resp;
res->server = server;
msg->rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_REMOVE];
nfs41_init_sequence(&args->seq_args, &res->seq_res, 1);
}
static void nfs4_proc_unlink_rpc_prepare(struct rpc_task *task, struct nfs_unlinkdata *data)
{
if (nfs4_setup_sequence(NFS_SERVER(data->dir),
&data->args.seq_args,
&data->res.seq_res,
task))
return;
rpc_call_start(task);
}
static int nfs4_proc_unlink_done(struct rpc_task *task, struct inode *dir)
{
struct nfs_removeres *res = task->tk_msg.rpc_resp;
if (!nfs4_sequence_done(task, &res->seq_res))
return 0;
if (nfs4_async_handle_error(task, res->server, NULL) == -EAGAIN)
return 0;
update_changeattr(dir, &res->cinfo);
return 1;
}
static void nfs4_proc_rename_setup(struct rpc_message *msg, struct inode *dir)
{
struct nfs_server *server = NFS_SERVER(dir);
struct nfs_renameargs *arg = msg->rpc_argp;
struct nfs_renameres *res = msg->rpc_resp;
msg->rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_RENAME];
res->server = server;
nfs41_init_sequence(&arg->seq_args, &res->seq_res, 1);
}
static void nfs4_proc_rename_rpc_prepare(struct rpc_task *task, struct nfs_renamedata *data)
{
if (nfs4_setup_sequence(NFS_SERVER(data->old_dir),
&data->args.seq_args,
&data->res.seq_res,
task))
return;
rpc_call_start(task);
}
static int nfs4_proc_rename_done(struct rpc_task *task, struct inode *old_dir,
struct inode *new_dir)
{
struct nfs_renameres *res = task->tk_msg.rpc_resp;
if (!nfs4_sequence_done(task, &res->seq_res))
return 0;
if (nfs4_async_handle_error(task, res->server, NULL) == -EAGAIN)
return 0;
update_changeattr(old_dir, &res->old_cinfo);
update_changeattr(new_dir, &res->new_cinfo);
return 1;
}
static int _nfs4_proc_rename(struct inode *old_dir, struct qstr *old_name,
struct inode *new_dir, struct qstr *new_name)
{
struct nfs_server *server = NFS_SERVER(old_dir);
struct nfs_renameargs arg = {
.old_dir = NFS_FH(old_dir),
.new_dir = NFS_FH(new_dir),
.old_name = old_name,
.new_name = new_name,
};
struct nfs_renameres res = {
.server = server,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_RENAME],
.rpc_argp = &arg,
.rpc_resp = &res,
};
int status = -ENOMEM;
status = nfs4_call_sync(server->client, server, &msg, &arg.seq_args, &res.seq_res, 1);
if (!status) {
update_changeattr(old_dir, &res.old_cinfo);
update_changeattr(new_dir, &res.new_cinfo);
}
return status;
}
static int nfs4_proc_rename(struct inode *old_dir, struct qstr *old_name,
struct inode *new_dir, struct qstr *new_name)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(NFS_SERVER(old_dir),
_nfs4_proc_rename(old_dir, old_name,
new_dir, new_name),
&exception);
} while (exception.retry);
return err;
}
static int _nfs4_proc_link(struct inode *inode, struct inode *dir, struct qstr *name)
{
struct nfs_server *server = NFS_SERVER(inode);
struct nfs4_link_arg arg = {
.fh = NFS_FH(inode),
.dir_fh = NFS_FH(dir),
.name = name,
.bitmask = server->attr_bitmask,
};
struct nfs4_link_res res = {
.server = server,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LINK],
.rpc_argp = &arg,
.rpc_resp = &res,
};
int status = -ENOMEM;
res.fattr = nfs_alloc_fattr();
if (res.fattr == NULL)
goto out;
status = nfs4_call_sync(server->client, server, &msg, &arg.seq_args, &res.seq_res, 1);
if (!status) {
update_changeattr(dir, &res.cinfo);
nfs_post_op_update_inode(inode, res.fattr);
}
out:
nfs_free_fattr(res.fattr);
return status;
}
static int nfs4_proc_link(struct inode *inode, struct inode *dir, struct qstr *name)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(NFS_SERVER(inode),
_nfs4_proc_link(inode, dir, name),
&exception);
} while (exception.retry);
return err;
}
struct nfs4_createdata {
struct rpc_message msg;
struct nfs4_create_arg arg;
struct nfs4_create_res res;
struct nfs_fh fh;
struct nfs_fattr fattr;
};
static struct nfs4_createdata *nfs4_alloc_createdata(struct inode *dir,
struct qstr *name, struct iattr *sattr, u32 ftype)
{
struct nfs4_createdata *data;
data = kzalloc(sizeof(*data), GFP_KERNEL);
if (data != NULL) {
struct nfs_server *server = NFS_SERVER(dir);
data->msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_CREATE];
data->msg.rpc_argp = &data->arg;
data->msg.rpc_resp = &data->res;
data->arg.dir_fh = NFS_FH(dir);
data->arg.server = server;
data->arg.name = name;
data->arg.attrs = sattr;
data->arg.ftype = ftype;
data->arg.bitmask = server->attr_bitmask;
data->res.server = server;
data->res.fh = &data->fh;
data->res.fattr = &data->fattr;
nfs_fattr_init(data->res.fattr);
}
return data;
}
static int nfs4_do_create(struct inode *dir, struct dentry *dentry, struct nfs4_createdata *data)
{
int status = nfs4_call_sync(NFS_SERVER(dir)->client, NFS_SERVER(dir), &data->msg,
&data->arg.seq_args, &data->res.seq_res, 1);
if (status == 0) {
update_changeattr(dir, &data->res.dir_cinfo);
status = nfs_instantiate(dentry, data->res.fh, data->res.fattr);
}
return status;
}
static void nfs4_free_createdata(struct nfs4_createdata *data)
{
kfree(data);
}
static int _nfs4_proc_symlink(struct inode *dir, struct dentry *dentry,
struct page *page, unsigned int len, struct iattr *sattr)
{
struct nfs4_createdata *data;
int status = -ENAMETOOLONG;
if (len > NFS4_MAXPATHLEN)
goto out;
status = -ENOMEM;
data = nfs4_alloc_createdata(dir, &dentry->d_name, sattr, NF4LNK);
if (data == NULL)
goto out;
data->msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SYMLINK];
data->arg.u.symlink.pages = &page;
data->arg.u.symlink.len = len;
status = nfs4_do_create(dir, dentry, data);
nfs4_free_createdata(data);
out:
return status;
}
static int nfs4_proc_symlink(struct inode *dir, struct dentry *dentry,
struct page *page, unsigned int len, struct iattr *sattr)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(NFS_SERVER(dir),
_nfs4_proc_symlink(dir, dentry, page,
len, sattr),
&exception);
} while (exception.retry);
return err;
}
static int _nfs4_proc_mkdir(struct inode *dir, struct dentry *dentry,
struct iattr *sattr)
{
struct nfs4_createdata *data;
int status = -ENOMEM;
data = nfs4_alloc_createdata(dir, &dentry->d_name, sattr, NF4DIR);
if (data == NULL)
goto out;
status = nfs4_do_create(dir, dentry, data);
nfs4_free_createdata(data);
out:
return status;
}
static int nfs4_proc_mkdir(struct inode *dir, struct dentry *dentry,
struct iattr *sattr)
{
struct nfs4_exception exception = { };
int err;
sattr->ia_mode &= ~current_umask();
do {
err = nfs4_handle_exception(NFS_SERVER(dir),
_nfs4_proc_mkdir(dir, dentry, sattr),
&exception);
} while (exception.retry);
return err;
}
static int _nfs4_proc_readdir(struct dentry *dentry, struct rpc_cred *cred,
u64 cookie, struct page **pages, unsigned int count, int plus)
{
struct inode *dir = dentry->d_inode;
struct nfs4_readdir_arg args = {
.fh = NFS_FH(dir),
.pages = pages,
.pgbase = 0,
.count = count,
.bitmask = NFS_SERVER(dentry->d_inode)->attr_bitmask,
.plus = plus,
};
struct nfs4_readdir_res res;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_READDIR],
.rpc_argp = &args,
.rpc_resp = &res,
.rpc_cred = cred,
};
int status;
dprintk("%s: dentry = %s/%s, cookie = %Lu\n", __func__,
dentry->d_parent->d_name.name,
dentry->d_name.name,
(unsigned long long)cookie);
nfs4_setup_readdir(cookie, NFS_I(dir)->cookieverf, dentry, &args);
res.pgbase = args.pgbase;
status = nfs4_call_sync(NFS_SERVER(dir)->client, NFS_SERVER(dir), &msg, &args.seq_args, &res.seq_res, 0);
if (status >= 0) {
memcpy(NFS_I(dir)->cookieverf, res.verifier.data, NFS4_VERIFIER_SIZE);
status += args.pgbase;
}
nfs_invalidate_atime(dir);
dprintk("%s: returns %d\n", __func__, status);
return status;
}
static int nfs4_proc_readdir(struct dentry *dentry, struct rpc_cred *cred,
u64 cookie, struct page **pages, unsigned int count, int plus)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(NFS_SERVER(dentry->d_inode),
_nfs4_proc_readdir(dentry, cred, cookie,
pages, count, plus),
&exception);
} while (exception.retry);
return err;
}
static int _nfs4_proc_mknod(struct inode *dir, struct dentry *dentry,
struct iattr *sattr, dev_t rdev)
{
struct nfs4_createdata *data;
int mode = sattr->ia_mode;
int status = -ENOMEM;
BUG_ON(!(sattr->ia_valid & ATTR_MODE));
BUG_ON(!S_ISFIFO(mode) && !S_ISBLK(mode) && !S_ISCHR(mode) && !S_ISSOCK(mode));
data = nfs4_alloc_createdata(dir, &dentry->d_name, sattr, NF4SOCK);
if (data == NULL)
goto out;
if (S_ISFIFO(mode))
data->arg.ftype = NF4FIFO;
else if (S_ISBLK(mode)) {
data->arg.ftype = NF4BLK;
data->arg.u.device.specdata1 = MAJOR(rdev);
data->arg.u.device.specdata2 = MINOR(rdev);
}
else if (S_ISCHR(mode)) {
data->arg.ftype = NF4CHR;
data->arg.u.device.specdata1 = MAJOR(rdev);
data->arg.u.device.specdata2 = MINOR(rdev);
}
status = nfs4_do_create(dir, dentry, data);
nfs4_free_createdata(data);
out:
return status;
}
static int nfs4_proc_mknod(struct inode *dir, struct dentry *dentry,
struct iattr *sattr, dev_t rdev)
{
struct nfs4_exception exception = { };
int err;
sattr->ia_mode &= ~current_umask();
do {
err = nfs4_handle_exception(NFS_SERVER(dir),
_nfs4_proc_mknod(dir, dentry, sattr, rdev),
&exception);
} while (exception.retry);
return err;
}
static int _nfs4_proc_statfs(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fsstat *fsstat)
{
struct nfs4_statfs_arg args = {
.fh = fhandle,
.bitmask = server->attr_bitmask,
};
struct nfs4_statfs_res res = {
.fsstat = fsstat,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_STATFS],
.rpc_argp = &args,
.rpc_resp = &res,
};
nfs_fattr_init(fsstat->fattr);
return nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
}
static int nfs4_proc_statfs(struct nfs_server *server, struct nfs_fh *fhandle, struct nfs_fsstat *fsstat)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(server,
_nfs4_proc_statfs(server, fhandle, fsstat),
&exception);
} while (exception.retry);
return err;
}
static int _nfs4_do_fsinfo(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fsinfo *fsinfo)
{
struct nfs4_fsinfo_arg args = {
.fh = fhandle,
.bitmask = server->attr_bitmask,
};
struct nfs4_fsinfo_res res = {
.fsinfo = fsinfo,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_FSINFO],
.rpc_argp = &args,
.rpc_resp = &res,
};
return nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
}
static int nfs4_do_fsinfo(struct nfs_server *server, struct nfs_fh *fhandle, struct nfs_fsinfo *fsinfo)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(server,
_nfs4_do_fsinfo(server, fhandle, fsinfo),
&exception);
} while (exception.retry);
return err;
}
static int nfs4_proc_fsinfo(struct nfs_server *server, struct nfs_fh *fhandle, struct nfs_fsinfo *fsinfo)
{
int error;
nfs_fattr_init(fsinfo->fattr);
error = nfs4_do_fsinfo(server, fhandle, fsinfo);
if (error == 0) {
/* block layout checks this! */
server->pnfs_blksize = fsinfo->blksize;
set_pnfs_layoutdriver(server, fhandle, fsinfo->layouttype);
}
return error;
}
static int _nfs4_proc_pathconf(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_pathconf *pathconf)
{
struct nfs4_pathconf_arg args = {
.fh = fhandle,
.bitmask = server->attr_bitmask,
};
struct nfs4_pathconf_res res = {
.pathconf = pathconf,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_PATHCONF],
.rpc_argp = &args,
.rpc_resp = &res,
};
/* None of the pathconf attributes are mandatory to implement */
if ((args.bitmask[0] & nfs4_pathconf_bitmap[0]) == 0) {
memset(pathconf, 0, sizeof(*pathconf));
return 0;
}
nfs_fattr_init(pathconf->fattr);
return nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
}
static int nfs4_proc_pathconf(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_pathconf *pathconf)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(server,
_nfs4_proc_pathconf(server, fhandle, pathconf),
&exception);
} while (exception.retry);
return err;
}
void __nfs4_read_done_cb(struct nfs_read_data *data)
{
nfs_invalidate_atime(data->header->inode);
}
static int nfs4_read_done_cb(struct rpc_task *task, struct nfs_read_data *data)
{
struct nfs_server *server = NFS_SERVER(data->header->inode);
if (nfs4_async_handle_error(task, server, data->args.context->state) == -EAGAIN) {
rpc_restart_call_prepare(task);
return -EAGAIN;
}
__nfs4_read_done_cb(data);
if (task->tk_status > 0)
renew_lease(server, data->timestamp);
return 0;
}
static int nfs4_read_done(struct rpc_task *task, struct nfs_read_data *data)
{
dprintk("--> %s\n", __func__);
if (!nfs4_sequence_done(task, &data->res.seq_res))
return -EAGAIN;
return data->read_done_cb ? data->read_done_cb(task, data) :
nfs4_read_done_cb(task, data);
}
static void nfs4_proc_read_setup(struct nfs_read_data *data, struct rpc_message *msg)
{
data->timestamp = jiffies;
data->read_done_cb = nfs4_read_done_cb;
msg->rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_READ];
nfs41_init_sequence(&data->args.seq_args, &data->res.seq_res, 0);
}
static void nfs4_proc_read_rpc_prepare(struct rpc_task *task, struct nfs_read_data *data)
{
if (nfs4_setup_sequence(NFS_SERVER(data->header->inode),
&data->args.seq_args,
&data->res.seq_res,
task))
return;
rpc_call_start(task);
}
static int nfs4_write_done_cb(struct rpc_task *task, struct nfs_write_data *data)
{
struct inode *inode = data->header->inode;
if (nfs4_async_handle_error(task, NFS_SERVER(inode), data->args.context->state) == -EAGAIN) {
rpc_restart_call_prepare(task);
return -EAGAIN;
}
if (task->tk_status >= 0) {
renew_lease(NFS_SERVER(inode), data->timestamp);
nfs_post_op_update_inode_force_wcc(inode, &data->fattr);
}
return 0;
}
static int nfs4_write_done(struct rpc_task *task, struct nfs_write_data *data)
{
if (!nfs4_sequence_done(task, &data->res.seq_res))
return -EAGAIN;
return data->write_done_cb ? data->write_done_cb(task, data) :
nfs4_write_done_cb(task, data);
}
static
bool nfs4_write_need_cache_consistency_data(const struct nfs_write_data *data)
{
const struct nfs_pgio_header *hdr = data->header;
/* Don't request attributes for pNFS or O_DIRECT writes */
if (data->ds_clp != NULL || hdr->dreq != NULL)
return false;
/* Otherwise, request attributes if and only if we don't hold
* a delegation
*/
return nfs4_have_delegation(hdr->inode, FMODE_READ) == 0;
}
static void nfs4_proc_write_setup(struct nfs_write_data *data, struct rpc_message *msg)
{
struct nfs_server *server = NFS_SERVER(data->header->inode);
if (!nfs4_write_need_cache_consistency_data(data)) {
data->args.bitmask = NULL;
data->res.fattr = NULL;
} else
data->args.bitmask = server->cache_consistency_bitmask;
if (!data->write_done_cb)
data->write_done_cb = nfs4_write_done_cb;
data->res.server = server;
data->timestamp = jiffies;
msg->rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_WRITE];
nfs41_init_sequence(&data->args.seq_args, &data->res.seq_res, 1);
}
static void nfs4_proc_write_rpc_prepare(struct rpc_task *task, struct nfs_write_data *data)
{
if (nfs4_setup_sequence(NFS_SERVER(data->header->inode),
&data->args.seq_args,
&data->res.seq_res,
task))
return;
rpc_call_start(task);
}
static void nfs4_proc_commit_rpc_prepare(struct rpc_task *task, struct nfs_commit_data *data)
{
if (nfs4_setup_sequence(NFS_SERVER(data->inode),
&data->args.seq_args,
&data->res.seq_res,
task))
return;
rpc_call_start(task);
}
static int nfs4_commit_done_cb(struct rpc_task *task, struct nfs_commit_data *data)
{
struct inode *inode = data->inode;
if (nfs4_async_handle_error(task, NFS_SERVER(inode), NULL) == -EAGAIN) {
rpc_restart_call_prepare(task);
return -EAGAIN;
}
return 0;
}
static int nfs4_commit_done(struct rpc_task *task, struct nfs_commit_data *data)
{
if (!nfs4_sequence_done(task, &data->res.seq_res))
return -EAGAIN;
return data->commit_done_cb(task, data);
}
static void nfs4_proc_commit_setup(struct nfs_commit_data *data, struct rpc_message *msg)
{
struct nfs_server *server = NFS_SERVER(data->inode);
if (data->commit_done_cb == NULL)
data->commit_done_cb = nfs4_commit_done_cb;
data->res.server = server;
msg->rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_COMMIT];
nfs41_init_sequence(&data->args.seq_args, &data->res.seq_res, 1);
}
struct nfs4_renewdata {
struct nfs_client *client;
unsigned long timestamp;
};
/*
* nfs4_proc_async_renew(): This is not one of the nfs_rpc_ops; it is a special
* standalone procedure for queueing an asynchronous RENEW.
*/
static void nfs4_renew_release(void *calldata)
{
struct nfs4_renewdata *data = calldata;
struct nfs_client *clp = data->client;
if (atomic_read(&clp->cl_count) > 1)
nfs4_schedule_state_renewal(clp);
nfs_put_client(clp);
kfree(data);
}
static void nfs4_renew_done(struct rpc_task *task, void *calldata)
{
struct nfs4_renewdata *data = calldata;
struct nfs_client *clp = data->client;
unsigned long timestamp = data->timestamp;
if (task->tk_status < 0) {
/* Unless we're shutting down, schedule state recovery! */
if (test_bit(NFS_CS_RENEWD, &clp->cl_res_state) == 0)
return;
if (task->tk_status != NFS4ERR_CB_PATH_DOWN) {
nfs4_schedule_lease_recovery(clp);
return;
}
nfs4_schedule_path_down_recovery(clp);
}
do_renew_lease(clp, timestamp);
}
static const struct rpc_call_ops nfs4_renew_ops = {
.rpc_call_done = nfs4_renew_done,
.rpc_release = nfs4_renew_release,
};
static int nfs4_proc_async_renew(struct nfs_client *clp, struct rpc_cred *cred, unsigned renew_flags)
{
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_RENEW],
.rpc_argp = clp,
.rpc_cred = cred,
};
struct nfs4_renewdata *data;
if (renew_flags == 0)
return 0;
if (!atomic_inc_not_zero(&clp->cl_count))
return -EIO;
data = kmalloc(sizeof(*data), GFP_NOFS);
if (data == NULL)
return -ENOMEM;
data->client = clp;
data->timestamp = jiffies;
return rpc_call_async(clp->cl_rpcclient, &msg, RPC_TASK_SOFT,
&nfs4_renew_ops, data);
}
static int nfs4_proc_renew(struct nfs_client *clp, struct rpc_cred *cred)
{
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_RENEW],
.rpc_argp = clp,
.rpc_cred = cred,
};
unsigned long now = jiffies;
int status;
status = rpc_call_sync(clp->cl_rpcclient, &msg, 0);
if (status < 0)
return status;
do_renew_lease(clp, now);
return 0;
}
static inline int nfs4_server_supports_acls(struct nfs_server *server)
{
return (server->caps & NFS_CAP_ACLS)
&& (server->acl_bitmask & ACL4_SUPPORT_ALLOW_ACL)
&& (server->acl_bitmask & ACL4_SUPPORT_DENY_ACL);
}
/* Assuming that XATTR_SIZE_MAX is a multiple of PAGE_SIZE, and that
* it's OK to put sizeof(void) * (XATTR_SIZE_MAX/PAGE_SIZE) bytes on
* the stack.
*/
#define NFS4ACL_MAXPAGES DIV_ROUND_UP(XATTR_SIZE_MAX, PAGE_SIZE)
static int buf_to_pages_noslab(const void *buf, size_t buflen,
struct page **pages, unsigned int *pgbase)
{
struct page *newpage, **spages;
int rc = 0;
size_t len;
spages = pages;
do {
len = min_t(size_t, PAGE_SIZE, buflen);
newpage = alloc_page(GFP_KERNEL);
if (newpage == NULL)
goto unwind;
memcpy(page_address(newpage), buf, len);
buf += len;
buflen -= len;
*pages++ = newpage;
rc++;
} while (buflen != 0);
return rc;
unwind:
for(; rc > 0; rc--)
__free_page(spages[rc-1]);
return -ENOMEM;
}
struct nfs4_cached_acl {
int cached;
size_t len;
char data[0];
};
static void nfs4_set_cached_acl(struct inode *inode, struct nfs4_cached_acl *acl)
{
struct nfs_inode *nfsi = NFS_I(inode);
spin_lock(&inode->i_lock);
kfree(nfsi->nfs4_acl);
nfsi->nfs4_acl = acl;
spin_unlock(&inode->i_lock);
}
static void nfs4_zap_acl_attr(struct inode *inode)
{
nfs4_set_cached_acl(inode, NULL);
}
static inline ssize_t nfs4_read_cached_acl(struct inode *inode, char *buf, size_t buflen)
{
struct nfs_inode *nfsi = NFS_I(inode);
struct nfs4_cached_acl *acl;
int ret = -ENOENT;
spin_lock(&inode->i_lock);
acl = nfsi->nfs4_acl;
if (acl == NULL)
goto out;
if (buf == NULL) /* user is just asking for length */
goto out_len;
if (acl->cached == 0)
goto out;
ret = -ERANGE; /* see getxattr(2) man page */
if (acl->len > buflen)
goto out;
memcpy(buf, acl->data, acl->len);
out_len:
ret = acl->len;
out:
spin_unlock(&inode->i_lock);
return ret;
}
static void nfs4_write_cached_acl(struct inode *inode, struct page **pages, size_t pgbase, size_t acl_len)
{
struct nfs4_cached_acl *acl;
size_t buflen = sizeof(*acl) + acl_len;
if (buflen <= PAGE_SIZE) {
acl = kmalloc(buflen, GFP_KERNEL);
if (acl == NULL)
goto out;
acl->cached = 1;
_copy_from_pages(acl->data, pages, pgbase, acl_len);
} else {
acl = kmalloc(sizeof(*acl), GFP_KERNEL);
if (acl == NULL)
goto out;
acl->cached = 0;
}
acl->len = acl_len;
out:
nfs4_set_cached_acl(inode, acl);
}
/*
* The getxattr API returns the required buffer length when called with a
* NULL buf. The NFSv4 acl tool then calls getxattr again after allocating
* the required buf. On a NULL buf, we send a page of data to the server
* guessing that the ACL request can be serviced by a page. If so, we cache
* up to the page of ACL data, and the 2nd call to getxattr is serviced by
* the cache. If not so, we throw away the page, and cache the required
* length. The next getxattr call will then produce another round trip to
* the server, this time with the input buf of the required size.
*/
static ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen)
{
struct page *pages[NFS4ACL_MAXPAGES] = {NULL, };
struct nfs_getaclargs args = {
.fh = NFS_FH(inode),
.acl_pages = pages,
.acl_len = buflen,
};
struct nfs_getaclres res = {
.acl_len = buflen,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL],
.rpc_argp = &args,
.rpc_resp = &res,
};
unsigned int npages = DIV_ROUND_UP(buflen, PAGE_SIZE);
int ret = -ENOMEM, i;
/* As long as we're doing a round trip to the server anyway,
* let's be prepared for a page of acl data. */
if (npages == 0)
npages = 1;
if (npages > ARRAY_SIZE(pages))
return -ERANGE;
for (i = 0; i < npages; i++) {
pages[i] = alloc_page(GFP_KERNEL);
if (!pages[i])
goto out_free;
}
/* for decoding across pages */
res.acl_scratch = alloc_page(GFP_KERNEL);
if (!res.acl_scratch)
goto out_free;
args.acl_len = npages * PAGE_SIZE;
args.acl_pgbase = 0;
dprintk("%s buf %p buflen %zu npages %d args.acl_len %zu\n",
__func__, buf, buflen, npages, args.acl_len);
ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode),
&msg, &args.seq_args, &res.seq_res, 0);
if (ret)
goto out_free;
/* Handle the case where the passed-in buffer is too short */
if (res.acl_flags & NFS4_ACL_TRUNC) {
/* Did the user only issue a request for the acl length? */
if (buf == NULL)
goto out_ok;
ret = -ERANGE;
goto out_free;
}
nfs4_write_cached_acl(inode, pages, res.acl_data_offset, res.acl_len);
if (buf)
_copy_from_pages(buf, pages, res.acl_data_offset, res.acl_len);
out_ok:
ret = res.acl_len;
out_free:
for (i = 0; i < npages; i++)
if (pages[i])
__free_page(pages[i]);
if (res.acl_scratch)
__free_page(res.acl_scratch);
return ret;
}
static ssize_t nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen)
{
struct nfs4_exception exception = { };
ssize_t ret;
do {
ret = __nfs4_get_acl_uncached(inode, buf, buflen);
if (ret >= 0)
break;
ret = nfs4_handle_exception(NFS_SERVER(inode), ret, &exception);
} while (exception.retry);
return ret;
}
static ssize_t nfs4_proc_get_acl(struct inode *inode, void *buf, size_t buflen)
{
struct nfs_server *server = NFS_SERVER(inode);
int ret;
if (!nfs4_server_supports_acls(server))
return -EOPNOTSUPP;
ret = nfs_revalidate_inode(server, inode);
if (ret < 0)
return ret;
if (NFS_I(inode)->cache_validity & NFS_INO_INVALID_ACL)
nfs_zap_acl_cache(inode);
ret = nfs4_read_cached_acl(inode, buf, buflen);
if (ret != -ENOENT)
/* -ENOENT is returned if there is no ACL or if there is an ACL
* but no cached acl data, just the acl length */
return ret;
return nfs4_get_acl_uncached(inode, buf, buflen);
}
static int __nfs4_proc_set_acl(struct inode *inode, const void *buf, size_t buflen)
{
struct nfs_server *server = NFS_SERVER(inode);
struct page *pages[NFS4ACL_MAXPAGES];
struct nfs_setaclargs arg = {
.fh = NFS_FH(inode),
.acl_pages = pages,
.acl_len = buflen,
};
struct nfs_setaclres res;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SETACL],
.rpc_argp = &arg,
.rpc_resp = &res,
};
unsigned int npages = DIV_ROUND_UP(buflen, PAGE_SIZE);
int ret, i;
if (!nfs4_server_supports_acls(server))
return -EOPNOTSUPP;
if (npages > ARRAY_SIZE(pages))
return -ERANGE;
i = buf_to_pages_noslab(buf, buflen, arg.acl_pages, &arg.acl_pgbase);
if (i < 0)
return i;
nfs4_inode_return_delegation(inode);
ret = nfs4_call_sync(server->client, server, &msg, &arg.seq_args, &res.seq_res, 1);
/*
* Free each page after tx, so the only ref left is
* held by the network stack
*/
for (; i > 0; i--)
put_page(pages[i-1]);
/*
* Acl update can result in inode attribute update.
* so mark the attribute cache invalid.
*/
spin_lock(&inode->i_lock);
NFS_I(inode)->cache_validity |= NFS_INO_INVALID_ATTR;
spin_unlock(&inode->i_lock);
nfs_access_zap_cache(inode);
nfs_zap_acl_cache(inode);
return ret;
}
static int nfs4_proc_set_acl(struct inode *inode, const void *buf, size_t buflen)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(NFS_SERVER(inode),
__nfs4_proc_set_acl(inode, buf, buflen),
&exception);
} while (exception.retry);
return err;
}
static int
nfs4_async_handle_error(struct rpc_task *task, const struct nfs_server *server, struct nfs4_state *state)
{
struct nfs_client *clp = server->nfs_client;
if (task->tk_status >= 0)
return 0;
switch(task->tk_status) {
case -NFS4ERR_DELEG_REVOKED:
case -NFS4ERR_ADMIN_REVOKED:
case -NFS4ERR_BAD_STATEID:
if (state == NULL)
break;
nfs_remove_bad_delegation(state->inode);
case -NFS4ERR_OPENMODE:
if (state == NULL)
break;
nfs4_schedule_stateid_recovery(server, state);
goto wait_on_recovery;
case -NFS4ERR_EXPIRED:
if (state != NULL)
nfs4_schedule_stateid_recovery(server, state);
case -NFS4ERR_STALE_STATEID:
case -NFS4ERR_STALE_CLIENTID:
nfs4_schedule_lease_recovery(clp);
goto wait_on_recovery;
#if defined(CONFIG_NFS_V4_1)
case -NFS4ERR_BADSESSION:
case -NFS4ERR_BADSLOT:
case -NFS4ERR_BAD_HIGH_SLOT:
case -NFS4ERR_DEADSESSION:
case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION:
case -NFS4ERR_SEQ_FALSE_RETRY:
case -NFS4ERR_SEQ_MISORDERED:
dprintk("%s ERROR %d, Reset session\n", __func__,
task->tk_status);
nfs4_schedule_session_recovery(clp->cl_session, task->tk_status);
task->tk_status = 0;
return -EAGAIN;
#endif /* CONFIG_NFS_V4_1 */
case -NFS4ERR_DELAY:
nfs_inc_server_stats(server, NFSIOS_DELAY);
case -NFS4ERR_GRACE:
case -EKEYEXPIRED:
rpc_delay(task, NFS4_POLL_RETRY_MAX);
task->tk_status = 0;
return -EAGAIN;
case -NFS4ERR_RETRY_UNCACHED_REP:
case -NFS4ERR_OLD_STATEID:
task->tk_status = 0;
return -EAGAIN;
}
task->tk_status = nfs4_map_errors(task->tk_status);
return 0;
wait_on_recovery:
rpc_sleep_on(&clp->cl_rpcwaitq, task, NULL);
if (test_bit(NFS4CLNT_MANAGER_RUNNING, &clp->cl_state) == 0)
rpc_wake_up_queued_task(&clp->cl_rpcwaitq, task);
task->tk_status = 0;
return -EAGAIN;
}
static void nfs4_init_boot_verifier(const struct nfs_client *clp,
nfs4_verifier *bootverf)
{
__be32 verf[2];
if (test_bit(NFS4CLNT_PURGE_STATE, &clp->cl_state)) {
/* An impossible timestamp guarantees this value
* will never match a generated boot time. */
verf[0] = 0;
verf[1] = (__be32)(NSEC_PER_SEC + 1);
} else {
struct nfs_net *nn = net_generic(clp->cl_net, nfs_net_id);
verf[0] = (__be32)nn->boot_time.tv_sec;
verf[1] = (__be32)nn->boot_time.tv_nsec;
}
memcpy(bootverf->data, verf, sizeof(bootverf->data));
}
static unsigned int
nfs4_init_nonuniform_client_string(const struct nfs_client *clp,
char *buf, size_t len)
{
unsigned int result;
rcu_read_lock();
result = scnprintf(buf, len, "Linux NFSv4.0 %s/%s %s",
clp->cl_ipaddr,
rpc_peeraddr2str(clp->cl_rpcclient,
RPC_DISPLAY_ADDR),
rpc_peeraddr2str(clp->cl_rpcclient,
RPC_DISPLAY_PROTO));
rcu_read_unlock();
return result;
}
static unsigned int
nfs4_init_uniform_client_string(const struct nfs_client *clp,
char *buf, size_t len)
{
char *nodename = clp->cl_rpcclient->cl_nodename;
if (nfs4_client_id_uniquifier[0] != '\0')
nodename = nfs4_client_id_uniquifier;
return scnprintf(buf, len, "Linux NFSv%u.%u %s",
clp->rpc_ops->version, clp->cl_minorversion,
nodename);
}
/**
* nfs4_proc_setclientid - Negotiate client ID
* @clp: state data structure
* @program: RPC program for NFSv4 callback service
* @port: IP port number for NFS4 callback service
* @cred: RPC credential to use for this call
* @res: where to place the result
*
* Returns zero, a negative errno, or a negative NFS4ERR status code.
*/
int nfs4_proc_setclientid(struct nfs_client *clp, u32 program,
unsigned short port, struct rpc_cred *cred,
struct nfs4_setclientid_res *res)
{
nfs4_verifier sc_verifier;
struct nfs4_setclientid setclientid = {
.sc_verifier = &sc_verifier,
.sc_prog = program,
.sc_cb_ident = clp->cl_cb_ident,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SETCLIENTID],
.rpc_argp = &setclientid,
.rpc_resp = res,
.rpc_cred = cred,
};
int status;
/* nfs_client_id4 */
nfs4_init_boot_verifier(clp, &sc_verifier);
if (test_bit(NFS_CS_MIGRATION, &clp->cl_flags))
setclientid.sc_name_len =
nfs4_init_uniform_client_string(clp,
setclientid.sc_name,
sizeof(setclientid.sc_name));
else
setclientid.sc_name_len =
nfs4_init_nonuniform_client_string(clp,
setclientid.sc_name,
sizeof(setclientid.sc_name));
/* cb_client4 */
rcu_read_lock();
setclientid.sc_netid_len = scnprintf(setclientid.sc_netid,
sizeof(setclientid.sc_netid),
rpc_peeraddr2str(clp->cl_rpcclient,
RPC_DISPLAY_NETID));
rcu_read_unlock();
setclientid.sc_uaddr_len = scnprintf(setclientid.sc_uaddr,
sizeof(setclientid.sc_uaddr), "%s.%u.%u",
clp->cl_ipaddr, port >> 8, port & 255);
dprintk("NFS call setclientid auth=%s, '%.*s'\n",
clp->cl_rpcclient->cl_auth->au_ops->au_name,
setclientid.sc_name_len, setclientid.sc_name);
status = rpc_call_sync(clp->cl_rpcclient, &msg, RPC_TASK_TIMEOUT);
dprintk("NFS reply setclientid: %d\n", status);
return status;
}
/**
* nfs4_proc_setclientid_confirm - Confirm client ID
* @clp: state data structure
* @res: result of a previous SETCLIENTID
* @cred: RPC credential to use for this call
*
* Returns zero, a negative errno, or a negative NFS4ERR status code.
*/
int nfs4_proc_setclientid_confirm(struct nfs_client *clp,
struct nfs4_setclientid_res *arg,
struct rpc_cred *cred)
{
struct nfs_fsinfo fsinfo;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SETCLIENTID_CONFIRM],
.rpc_argp = arg,
.rpc_resp = &fsinfo,
.rpc_cred = cred,
};
unsigned long now;
int status;
dprintk("NFS call setclientid_confirm auth=%s, (client ID %llx)\n",
clp->cl_rpcclient->cl_auth->au_ops->au_name,
clp->cl_clientid);
now = jiffies;
status = rpc_call_sync(clp->cl_rpcclient, &msg, RPC_TASK_TIMEOUT);
if (status == 0) {
spin_lock(&clp->cl_lock);
clp->cl_lease_time = fsinfo.lease_time * HZ;
clp->cl_last_renewal = now;
spin_unlock(&clp->cl_lock);
}
dprintk("NFS reply setclientid_confirm: %d\n", status);
return status;
}
struct nfs4_delegreturndata {
struct nfs4_delegreturnargs args;
struct nfs4_delegreturnres res;
struct nfs_fh fh;
nfs4_stateid stateid;
unsigned long timestamp;
struct nfs_fattr fattr;
int rpc_status;
};
static void nfs4_delegreturn_done(struct rpc_task *task, void *calldata)
{
struct nfs4_delegreturndata *data = calldata;
if (!nfs4_sequence_done(task, &data->res.seq_res))
return;
switch (task->tk_status) {
case -NFS4ERR_STALE_STATEID:
case -NFS4ERR_EXPIRED:
case 0:
renew_lease(data->res.server, data->timestamp);
break;
default:
if (nfs4_async_handle_error(task, data->res.server, NULL) ==
-EAGAIN) {
rpc_restart_call_prepare(task);
return;
}
}
data->rpc_status = task->tk_status;
}
static void nfs4_delegreturn_release(void *calldata)
{
kfree(calldata);
}
#if defined(CONFIG_NFS_V4_1)
static void nfs4_delegreturn_prepare(struct rpc_task *task, void *data)
{
struct nfs4_delegreturndata *d_data;
d_data = (struct nfs4_delegreturndata *)data;
if (nfs4_setup_sequence(d_data->res.server,
&d_data->args.seq_args,
&d_data->res.seq_res, task))
return;
rpc_call_start(task);
}
#endif /* CONFIG_NFS_V4_1 */
static const struct rpc_call_ops nfs4_delegreturn_ops = {
#if defined(CONFIG_NFS_V4_1)
.rpc_call_prepare = nfs4_delegreturn_prepare,
#endif /* CONFIG_NFS_V4_1 */
.rpc_call_done = nfs4_delegreturn_done,
.rpc_release = nfs4_delegreturn_release,
};
static int _nfs4_proc_delegreturn(struct inode *inode, struct rpc_cred *cred, const nfs4_stateid *stateid, int issync)
{
struct nfs4_delegreturndata *data;
struct nfs_server *server = NFS_SERVER(inode);
struct rpc_task *task;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_DELEGRETURN],
.rpc_cred = cred,
};
struct rpc_task_setup task_setup_data = {
.rpc_client = server->client,
.rpc_message = &msg,
.callback_ops = &nfs4_delegreturn_ops,
.flags = RPC_TASK_ASYNC,
};
int status = 0;
data = kzalloc(sizeof(*data), GFP_NOFS);
if (data == NULL)
return -ENOMEM;
nfs41_init_sequence(&data->args.seq_args, &data->res.seq_res, 1);
data->args.fhandle = &data->fh;
data->args.stateid = &data->stateid;
data->args.bitmask = server->cache_consistency_bitmask;
nfs_copy_fh(&data->fh, NFS_FH(inode));
nfs4_stateid_copy(&data->stateid, stateid);
data->res.fattr = &data->fattr;
data->res.server = server;
nfs_fattr_init(data->res.fattr);
data->timestamp = jiffies;
data->rpc_status = 0;
task_setup_data.callback_data = data;
msg.rpc_argp = &data->args;
msg.rpc_resp = &data->res;
task = rpc_run_task(&task_setup_data);
if (IS_ERR(task))
return PTR_ERR(task);
if (!issync)
goto out;
status = nfs4_wait_for_completion_rpc_task(task);
if (status != 0)
goto out;
status = data->rpc_status;
if (status == 0)
nfs_post_op_update_inode_force_wcc(inode, &data->fattr);
else
nfs_refresh_inode(inode, &data->fattr);
out:
rpc_put_task(task);
return status;
}
int nfs4_proc_delegreturn(struct inode *inode, struct rpc_cred *cred, const nfs4_stateid *stateid, int issync)
{
struct nfs_server *server = NFS_SERVER(inode);
struct nfs4_exception exception = { };
int err;
do {
err = _nfs4_proc_delegreturn(inode, cred, stateid, issync);
switch (err) {
case -NFS4ERR_STALE_STATEID:
case -NFS4ERR_EXPIRED:
case 0:
return 0;
}
err = nfs4_handle_exception(server, err, &exception);
} while (exception.retry);
return err;
}
#define NFS4_LOCK_MINTIMEOUT (1 * HZ)
#define NFS4_LOCK_MAXTIMEOUT (30 * HZ)
/*
* sleep, with exponential backoff, and retry the LOCK operation.
*/
static unsigned long
nfs4_set_lock_task_retry(unsigned long timeout)
{
freezable_schedule_timeout_killable(timeout);
timeout <<= 1;
if (timeout > NFS4_LOCK_MAXTIMEOUT)
return NFS4_LOCK_MAXTIMEOUT;
return timeout;
}
static int _nfs4_proc_getlk(struct nfs4_state *state, int cmd, struct file_lock *request)
{
struct inode *inode = state->inode;
struct nfs_server *server = NFS_SERVER(inode);
struct nfs_client *clp = server->nfs_client;
struct nfs_lockt_args arg = {
.fh = NFS_FH(inode),
.fl = request,
};
struct nfs_lockt_res res = {
.denied = request,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LOCKT],
.rpc_argp = &arg,
.rpc_resp = &res,
.rpc_cred = state->owner->so_cred,
};
struct nfs4_lock_state *lsp;
int status;
arg.lock_owner.clientid = clp->cl_clientid;
status = nfs4_set_lock_state(state, request);
if (status != 0)
goto out;
lsp = request->fl_u.nfs4_fl.owner;
arg.lock_owner.id = lsp->ls_seqid.owner_id;
arg.lock_owner.s_dev = server->s_dev;
status = nfs4_call_sync(server->client, server, &msg, &arg.seq_args, &res.seq_res, 1);
switch (status) {
case 0:
request->fl_type = F_UNLCK;
break;
case -NFS4ERR_DENIED:
status = 0;
}
request->fl_ops->fl_release_private(request);
out:
return status;
}
static int nfs4_proc_getlk(struct nfs4_state *state, int cmd, struct file_lock *request)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(NFS_SERVER(state->inode),
_nfs4_proc_getlk(state, cmd, request),
&exception);
} while (exception.retry);
return err;
}
static int do_vfs_lock(struct file *file, struct file_lock *fl)
{
int res = 0;
switch (fl->fl_flags & (FL_POSIX|FL_FLOCK)) {
case FL_POSIX:
res = posix_lock_file_wait(file, fl);
break;
case FL_FLOCK:
res = flock_lock_file_wait(file, fl);
break;
default:
BUG();
}
return res;
}
struct nfs4_unlockdata {
struct nfs_locku_args arg;
struct nfs_locku_res res;
struct nfs4_lock_state *lsp;
struct nfs_open_context *ctx;
struct file_lock fl;
const struct nfs_server *server;
unsigned long timestamp;
};
static struct nfs4_unlockdata *nfs4_alloc_unlockdata(struct file_lock *fl,
struct nfs_open_context *ctx,
struct nfs4_lock_state *lsp,
struct nfs_seqid *seqid)
{
struct nfs4_unlockdata *p;
struct inode *inode = lsp->ls_state->inode;
p = kzalloc(sizeof(*p), GFP_NOFS);
if (p == NULL)
return NULL;
p->arg.fh = NFS_FH(inode);
p->arg.fl = &p->fl;
p->arg.seqid = seqid;
p->res.seqid = seqid;
p->arg.stateid = &lsp->ls_stateid;
p->lsp = lsp;
atomic_inc(&lsp->ls_count);
/* Ensure we don't close file until we're done freeing locks! */
p->ctx = get_nfs_open_context(ctx);
memcpy(&p->fl, fl, sizeof(p->fl));
p->server = NFS_SERVER(inode);
return p;
}
static void nfs4_locku_release_calldata(void *data)
{
struct nfs4_unlockdata *calldata = data;
nfs_free_seqid(calldata->arg.seqid);
nfs4_put_lock_state(calldata->lsp);
put_nfs_open_context(calldata->ctx);
kfree(calldata);
}
static void nfs4_locku_done(struct rpc_task *task, void *data)
{
struct nfs4_unlockdata *calldata = data;
if (!nfs4_sequence_done(task, &calldata->res.seq_res))
return;
switch (task->tk_status) {
case 0:
nfs4_stateid_copy(&calldata->lsp->ls_stateid,
&calldata->res.stateid);
renew_lease(calldata->server, calldata->timestamp);
break;
case -NFS4ERR_BAD_STATEID:
case -NFS4ERR_OLD_STATEID:
case -NFS4ERR_STALE_STATEID:
case -NFS4ERR_EXPIRED:
break;
default:
if (nfs4_async_handle_error(task, calldata->server, NULL) == -EAGAIN)
rpc_restart_call_prepare(task);
}
nfs_release_seqid(calldata->arg.seqid);
}
static void nfs4_locku_prepare(struct rpc_task *task, void *data)
{
struct nfs4_unlockdata *calldata = data;
if (nfs_wait_on_sequence(calldata->arg.seqid, task) != 0)
return;
if (test_bit(NFS_LOCK_INITIALIZED, &calldata->lsp->ls_flags) == 0) {
/* Note: exit _without_ running nfs4_locku_done */
task->tk_action = NULL;
return;
}
calldata->timestamp = jiffies;
if (nfs4_setup_sequence(calldata->server,
&calldata->arg.seq_args,
&calldata->res.seq_res,
task) != 0)
nfs_release_seqid(calldata->arg.seqid);
else
rpc_call_start(task);
}
static const struct rpc_call_ops nfs4_locku_ops = {
.rpc_call_prepare = nfs4_locku_prepare,
.rpc_call_done = nfs4_locku_done,
.rpc_release = nfs4_locku_release_calldata,
};
static struct rpc_task *nfs4_do_unlck(struct file_lock *fl,
struct nfs_open_context *ctx,
struct nfs4_lock_state *lsp,
struct nfs_seqid *seqid)
{
struct nfs4_unlockdata *data;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LOCKU],
.rpc_cred = ctx->cred,
};
struct rpc_task_setup task_setup_data = {
.rpc_client = NFS_CLIENT(lsp->ls_state->inode),
.rpc_message = &msg,
.callback_ops = &nfs4_locku_ops,
.workqueue = nfsiod_workqueue,
.flags = RPC_TASK_ASYNC,
};
/* Ensure this is an unlock - when canceling a lock, the
* canceled lock is passed in, and it won't be an unlock.
*/
fl->fl_type = F_UNLCK;
data = nfs4_alloc_unlockdata(fl, ctx, lsp, seqid);
if (data == NULL) {
nfs_free_seqid(seqid);
return ERR_PTR(-ENOMEM);
}
nfs41_init_sequence(&data->arg.seq_args, &data->res.seq_res, 1);
msg.rpc_argp = &data->arg;
msg.rpc_resp = &data->res;
task_setup_data.callback_data = data;
return rpc_run_task(&task_setup_data);
}
static int nfs4_proc_unlck(struct nfs4_state *state, int cmd, struct file_lock *request)
{
struct nfs_inode *nfsi = NFS_I(state->inode);
struct nfs_seqid *seqid;
struct nfs4_lock_state *lsp;
struct rpc_task *task;
int status = 0;
unsigned char fl_flags = request->fl_flags;
status = nfs4_set_lock_state(state, request);
/* Unlock _before_ we do the RPC call */
request->fl_flags |= FL_EXISTS;
down_read(&nfsi->rwsem);
if (do_vfs_lock(request->fl_file, request) == -ENOENT) {
up_read(&nfsi->rwsem);
goto out;
}
up_read(&nfsi->rwsem);
if (status != 0)
goto out;
/* Is this a delegated lock? */
if (test_bit(NFS_DELEGATED_STATE, &state->flags))
goto out;
lsp = request->fl_u.nfs4_fl.owner;
seqid = nfs_alloc_seqid(&lsp->ls_seqid, GFP_KERNEL);
status = -ENOMEM;
if (seqid == NULL)
goto out;
task = nfs4_do_unlck(request, nfs_file_open_context(request->fl_file), lsp, seqid);
status = PTR_ERR(task);
if (IS_ERR(task))
goto out;
status = nfs4_wait_for_completion_rpc_task(task);
rpc_put_task(task);
out:
request->fl_flags = fl_flags;
return status;
}
struct nfs4_lockdata {
struct nfs_lock_args arg;
struct nfs_lock_res res;
struct nfs4_lock_state *lsp;
struct nfs_open_context *ctx;
struct file_lock fl;
unsigned long timestamp;
int rpc_status;
int cancelled;
struct nfs_server *server;
};
static struct nfs4_lockdata *nfs4_alloc_lockdata(struct file_lock *fl,
struct nfs_open_context *ctx, struct nfs4_lock_state *lsp,
gfp_t gfp_mask)
{
struct nfs4_lockdata *p;
struct inode *inode = lsp->ls_state->inode;
struct nfs_server *server = NFS_SERVER(inode);
p = kzalloc(sizeof(*p), gfp_mask);
if (p == NULL)
return NULL;
p->arg.fh = NFS_FH(inode);
p->arg.fl = &p->fl;
p->arg.open_seqid = nfs_alloc_seqid(&lsp->ls_state->owner->so_seqid, gfp_mask);
if (p->arg.open_seqid == NULL)
goto out_free;
p->arg.lock_seqid = nfs_alloc_seqid(&lsp->ls_seqid, gfp_mask);
if (p->arg.lock_seqid == NULL)
goto out_free_seqid;
p->arg.lock_stateid = &lsp->ls_stateid;
p->arg.lock_owner.clientid = server->nfs_client->cl_clientid;
p->arg.lock_owner.id = lsp->ls_seqid.owner_id;
p->arg.lock_owner.s_dev = server->s_dev;
p->res.lock_seqid = p->arg.lock_seqid;
p->lsp = lsp;
p->server = server;
atomic_inc(&lsp->ls_count);
p->ctx = get_nfs_open_context(ctx);
memcpy(&p->fl, fl, sizeof(p->fl));
return p;
out_free_seqid:
nfs_free_seqid(p->arg.open_seqid);
out_free:
kfree(p);
return NULL;
}
static void nfs4_lock_prepare(struct rpc_task *task, void *calldata)
{
struct nfs4_lockdata *data = calldata;
struct nfs4_state *state = data->lsp->ls_state;
dprintk("%s: begin!\n", __func__);
if (nfs_wait_on_sequence(data->arg.lock_seqid, task) != 0)
return;
/* Do we need to do an open_to_lock_owner? */
if (!(data->arg.lock_seqid->sequence->flags & NFS_SEQID_CONFIRMED)) {
if (nfs_wait_on_sequence(data->arg.open_seqid, task) != 0)
goto out_release_lock_seqid;
data->arg.open_stateid = &state->stateid;
data->arg.new_lock_owner = 1;
data->res.open_seqid = data->arg.open_seqid;
} else
data->arg.new_lock_owner = 0;
data->timestamp = jiffies;
if (nfs4_setup_sequence(data->server,
&data->arg.seq_args,
&data->res.seq_res,
task) == 0) {
rpc_call_start(task);
return;
}
nfs_release_seqid(data->arg.open_seqid);
out_release_lock_seqid:
nfs_release_seqid(data->arg.lock_seqid);
dprintk("%s: done!, ret = %d\n", __func__, task->tk_status);
}
static void nfs4_recover_lock_prepare(struct rpc_task *task, void *calldata)
{
rpc_task_set_priority(task, RPC_PRIORITY_PRIVILEGED);
nfs4_lock_prepare(task, calldata);
}
static void nfs4_lock_done(struct rpc_task *task, void *calldata)
{
struct nfs4_lockdata *data = calldata;
dprintk("%s: begin!\n", __func__);
if (!nfs4_sequence_done(task, &data->res.seq_res))
return;
data->rpc_status = task->tk_status;
if (data->arg.new_lock_owner != 0) {
if (data->rpc_status == 0)
nfs_confirm_seqid(&data->lsp->ls_seqid, 0);
else
goto out;
}
if (data->rpc_status == 0) {
nfs4_stateid_copy(&data->lsp->ls_stateid, &data->res.stateid);
set_bit(NFS_LOCK_INITIALIZED, &data->lsp->ls_flags);
renew_lease(NFS_SERVER(data->ctx->dentry->d_inode), data->timestamp);
}
out:
dprintk("%s: done, ret = %d!\n", __func__, data->rpc_status);
}
static void nfs4_lock_release(void *calldata)
{
struct nfs4_lockdata *data = calldata;
dprintk("%s: begin!\n", __func__);
nfs_free_seqid(data->arg.open_seqid);
if (data->cancelled != 0) {
struct rpc_task *task;
task = nfs4_do_unlck(&data->fl, data->ctx, data->lsp,
data->arg.lock_seqid);
if (!IS_ERR(task))
rpc_put_task_async(task);
dprintk("%s: cancelling lock!\n", __func__);
} else
nfs_free_seqid(data->arg.lock_seqid);
nfs4_put_lock_state(data->lsp);
put_nfs_open_context(data->ctx);
kfree(data);
dprintk("%s: done!\n", __func__);
}
static const struct rpc_call_ops nfs4_lock_ops = {
.rpc_call_prepare = nfs4_lock_prepare,
.rpc_call_done = nfs4_lock_done,
.rpc_release = nfs4_lock_release,
};
static const struct rpc_call_ops nfs4_recover_lock_ops = {
.rpc_call_prepare = nfs4_recover_lock_prepare,
.rpc_call_done = nfs4_lock_done,
.rpc_release = nfs4_lock_release,
};
static void nfs4_handle_setlk_error(struct nfs_server *server, struct nfs4_lock_state *lsp, int new_lock_owner, int error)
{
switch (error) {
case -NFS4ERR_ADMIN_REVOKED:
case -NFS4ERR_BAD_STATEID:
lsp->ls_seqid.flags &= ~NFS_SEQID_CONFIRMED;
if (new_lock_owner != 0 ||
test_bit(NFS_LOCK_INITIALIZED, &lsp->ls_flags) != 0)
nfs4_schedule_stateid_recovery(server, lsp->ls_state);
break;
case -NFS4ERR_STALE_STATEID:
lsp->ls_seqid.flags &= ~NFS_SEQID_CONFIRMED;
case -NFS4ERR_EXPIRED:
nfs4_schedule_lease_recovery(server->nfs_client);
};
}
static int _nfs4_do_setlk(struct nfs4_state *state, int cmd, struct file_lock *fl, int recovery_type)
{
struct nfs4_lockdata *data;
struct rpc_task *task;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LOCK],
.rpc_cred = state->owner->so_cred,
};
struct rpc_task_setup task_setup_data = {
.rpc_client = NFS_CLIENT(state->inode),
.rpc_message = &msg,
.callback_ops = &nfs4_lock_ops,
.workqueue = nfsiod_workqueue,
.flags = RPC_TASK_ASYNC,
};
int ret;
dprintk("%s: begin!\n", __func__);
data = nfs4_alloc_lockdata(fl, nfs_file_open_context(fl->fl_file),
fl->fl_u.nfs4_fl.owner,
recovery_type == NFS_LOCK_NEW ? GFP_KERNEL : GFP_NOFS);
if (data == NULL)
return -ENOMEM;
if (IS_SETLKW(cmd))
data->arg.block = 1;
if (recovery_type > NFS_LOCK_NEW) {
if (recovery_type == NFS_LOCK_RECLAIM)
data->arg.reclaim = NFS_LOCK_RECLAIM;
task_setup_data.callback_ops = &nfs4_recover_lock_ops;
}
nfs41_init_sequence(&data->arg.seq_args, &data->res.seq_res, 1);
msg.rpc_argp = &data->arg;
msg.rpc_resp = &data->res;
task_setup_data.callback_data = data;
task = rpc_run_task(&task_setup_data);
if (IS_ERR(task))
return PTR_ERR(task);
ret = nfs4_wait_for_completion_rpc_task(task);
if (ret == 0) {
ret = data->rpc_status;
if (ret)
nfs4_handle_setlk_error(data->server, data->lsp,
data->arg.new_lock_owner, ret);
} else
data->cancelled = 1;
rpc_put_task(task);
dprintk("%s: done, ret = %d!\n", __func__, ret);
return ret;
}
static int nfs4_lock_reclaim(struct nfs4_state *state, struct file_lock *request)
{
struct nfs_server *server = NFS_SERVER(state->inode);
struct nfs4_exception exception = {
.inode = state->inode,
};
int err;
do {
/* Cache the lock if possible... */
if (test_bit(NFS_DELEGATED_STATE, &state->flags) != 0)
return 0;
err = _nfs4_do_setlk(state, F_SETLK, request, NFS_LOCK_RECLAIM);
if (err != -NFS4ERR_DELAY)
break;
nfs4_handle_exception(server, err, &exception);
} while (exception.retry);
return err;
}
static int nfs4_lock_expired(struct nfs4_state *state, struct file_lock *request)
{
struct nfs_server *server = NFS_SERVER(state->inode);
struct nfs4_exception exception = {
.inode = state->inode,
};
int err;
err = nfs4_set_lock_state(state, request);
if (err != 0)
return err;
do {
if (test_bit(NFS_DELEGATED_STATE, &state->flags) != 0)
return 0;
err = _nfs4_do_setlk(state, F_SETLK, request, NFS_LOCK_EXPIRED);
switch (err) {
default:
goto out;
case -NFS4ERR_GRACE:
case -NFS4ERR_DELAY:
nfs4_handle_exception(server, err, &exception);
err = 0;
}
} while (exception.retry);
out:
return err;
}
#if defined(CONFIG_NFS_V4_1)
/**
* nfs41_check_expired_locks - possibly free a lock stateid
*
* @state: NFSv4 state for an inode
*
* Returns NFS_OK if recovery for this stateid is now finished.
* Otherwise a negative NFS4ERR value is returned.
*/
static int nfs41_check_expired_locks(struct nfs4_state *state)
{
int status, ret = -NFS4ERR_BAD_STATEID;
struct nfs4_lock_state *lsp;
struct nfs_server *server = NFS_SERVER(state->inode);
list_for_each_entry(lsp, &state->lock_states, ls_locks) {
if (test_bit(NFS_LOCK_INITIALIZED, &lsp->ls_flags)) {
status = nfs41_test_stateid(server, &lsp->ls_stateid);
if (status != NFS_OK) {
/* Free the stateid unless the server
* informs us the stateid is unrecognized. */
if (status != -NFS4ERR_BAD_STATEID)
nfs41_free_stateid(server,
&lsp->ls_stateid);
clear_bit(NFS_LOCK_INITIALIZED, &lsp->ls_flags);
ret = status;
}
}
};
return ret;
}
static int nfs41_lock_expired(struct nfs4_state *state, struct file_lock *request)
{
int status = NFS_OK;
if (test_bit(LK_STATE_IN_USE, &state->flags))
status = nfs41_check_expired_locks(state);
if (status != NFS_OK)
status = nfs4_lock_expired(state, request);
return status;
}
#endif
static int _nfs4_proc_setlk(struct nfs4_state *state, int cmd, struct file_lock *request)
{
struct nfs_inode *nfsi = NFS_I(state->inode);
unsigned char fl_flags = request->fl_flags;
int status = -ENOLCK;
if ((fl_flags & FL_POSIX) &&
!test_bit(NFS_STATE_POSIX_LOCKS, &state->flags))
goto out;
/* Is this a delegated open? */
status = nfs4_set_lock_state(state, request);
if (status != 0)
goto out;
request->fl_flags |= FL_ACCESS;
status = do_vfs_lock(request->fl_file, request);
if (status < 0)
goto out;
down_read(&nfsi->rwsem);
if (test_bit(NFS_DELEGATED_STATE, &state->flags)) {
/* Yes: cache locks! */
/* ...but avoid races with delegation recall... */
request->fl_flags = fl_flags & ~FL_SLEEP;
status = do_vfs_lock(request->fl_file, request);
goto out_unlock;
}
status = _nfs4_do_setlk(state, cmd, request, NFS_LOCK_NEW);
if (status != 0)
goto out_unlock;
/* Note: we always want to sleep here! */
request->fl_flags = fl_flags | FL_SLEEP;
if (do_vfs_lock(request->fl_file, request) < 0)
printk(KERN_WARNING "NFS: %s: VFS is out of sync with lock "
"manager!\n", __func__);
out_unlock:
up_read(&nfsi->rwsem);
out:
request->fl_flags = fl_flags;
return status;
}
static int nfs4_proc_setlk(struct nfs4_state *state, int cmd, struct file_lock *request)
{
struct nfs4_exception exception = {
.state = state,
.inode = state->inode,
};
int err;
do {
err = _nfs4_proc_setlk(state, cmd, request);
if (err == -NFS4ERR_DENIED)
err = -EAGAIN;
err = nfs4_handle_exception(NFS_SERVER(state->inode),
err, &exception);
} while (exception.retry);
return err;
}
static int
nfs4_proc_lock(struct file *filp, int cmd, struct file_lock *request)
{
struct nfs_open_context *ctx;
struct nfs4_state *state;
unsigned long timeout = NFS4_LOCK_MINTIMEOUT;
int status;
/* verify open state */
ctx = nfs_file_open_context(filp);
state = ctx->state;
if (request->fl_start < 0 || request->fl_end < 0)
return -EINVAL;
if (IS_GETLK(cmd)) {
if (state != NULL)
return nfs4_proc_getlk(state, F_GETLK, request);
return 0;
}
if (!(IS_SETLK(cmd) || IS_SETLKW(cmd)))
return -EINVAL;
if (request->fl_type == F_UNLCK) {
if (state != NULL)
return nfs4_proc_unlck(state, cmd, request);
return 0;
}
if (state == NULL)
return -ENOLCK;
/*
* Don't rely on the VFS having checked the file open mode,
* since it won't do this for flock() locks.
*/
switch (request->fl_type) {
case F_RDLCK:
if (!(filp->f_mode & FMODE_READ))
return -EBADF;
break;
case F_WRLCK:
if (!(filp->f_mode & FMODE_WRITE))
return -EBADF;
}
do {
status = nfs4_proc_setlk(state, cmd, request);
if ((status != -EAGAIN) || IS_SETLK(cmd))
break;
timeout = nfs4_set_lock_task_retry(timeout);
status = -ERESTARTSYS;
if (signalled())
break;
} while(status < 0);
return status;
}
int nfs4_lock_delegation_recall(struct nfs4_state *state, struct file_lock *fl)
{
struct nfs_server *server = NFS_SERVER(state->inode);
struct nfs4_exception exception = { };
int err;
err = nfs4_set_lock_state(state, fl);
if (err != 0)
goto out;
do {
err = _nfs4_do_setlk(state, F_SETLK, fl, NFS_LOCK_NEW);
switch (err) {
default:
printk(KERN_ERR "NFS: %s: unhandled error "
"%d.\n", __func__, err);
case 0:
case -ESTALE:
goto out;
case -NFS4ERR_EXPIRED:
nfs4_schedule_stateid_recovery(server, state);
case -NFS4ERR_STALE_CLIENTID:
case -NFS4ERR_STALE_STATEID:
nfs4_schedule_lease_recovery(server->nfs_client);
goto out;
case -NFS4ERR_BADSESSION:
case -NFS4ERR_BADSLOT:
case -NFS4ERR_BAD_HIGH_SLOT:
case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION:
case -NFS4ERR_DEADSESSION:
nfs4_schedule_session_recovery(server->nfs_client->cl_session, err);
goto out;
case -ERESTARTSYS:
/*
* The show must go on: exit, but mark the
* stateid as needing recovery.
*/
case -NFS4ERR_DELEG_REVOKED:
case -NFS4ERR_ADMIN_REVOKED:
case -NFS4ERR_BAD_STATEID:
case -NFS4ERR_OPENMODE:
nfs4_schedule_stateid_recovery(server, state);
err = 0;
goto out;
case -EKEYEXPIRED:
/*
* User RPCSEC_GSS context has expired.
* We cannot recover this stateid now, so
* skip it and allow recovery thread to
* proceed.
*/
err = 0;
goto out;
case -ENOMEM:
case -NFS4ERR_DENIED:
/* kill_proc(fl->fl_pid, SIGLOST, 1); */
err = 0;
goto out;
case -NFS4ERR_DELAY:
break;
}
err = nfs4_handle_exception(server, err, &exception);
} while (exception.retry);
out:
return err;
}
struct nfs_release_lockowner_data {
struct nfs4_lock_state *lsp;
struct nfs_server *server;
struct nfs_release_lockowner_args args;
};
static void nfs4_release_lockowner_release(void *calldata)
{
struct nfs_release_lockowner_data *data = calldata;
nfs4_free_lock_state(data->server, data->lsp);
kfree(calldata);
}
static const struct rpc_call_ops nfs4_release_lockowner_ops = {
.rpc_release = nfs4_release_lockowner_release,
};
int nfs4_release_lockowner(struct nfs4_lock_state *lsp)
{
struct nfs_server *server = lsp->ls_state->owner->so_server;
struct nfs_release_lockowner_data *data;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_RELEASE_LOCKOWNER],
};
if (server->nfs_client->cl_mvops->minor_version != 0)
return -EINVAL;
data = kmalloc(sizeof(*data), GFP_NOFS);
if (!data)
return -ENOMEM;
data->lsp = lsp;
data->server = server;
data->args.lock_owner.clientid = server->nfs_client->cl_clientid;
data->args.lock_owner.id = lsp->ls_seqid.owner_id;
data->args.lock_owner.s_dev = server->s_dev;
msg.rpc_argp = &data->args;
rpc_call_async(server->client, &msg, 0, &nfs4_release_lockowner_ops, data);
return 0;
}
#define XATTR_NAME_NFSV4_ACL "system.nfs4_acl"
static int nfs4_xattr_set_nfs4_acl(struct dentry *dentry, const char *key,
const void *buf, size_t buflen,
int flags, int type)
{
if (strcmp(key, "") != 0)
return -EINVAL;
return nfs4_proc_set_acl(dentry->d_inode, buf, buflen);
}
static int nfs4_xattr_get_nfs4_acl(struct dentry *dentry, const char *key,
void *buf, size_t buflen, int type)
{
if (strcmp(key, "") != 0)
return -EINVAL;
return nfs4_proc_get_acl(dentry->d_inode, buf, buflen);
}
static size_t nfs4_xattr_list_nfs4_acl(struct dentry *dentry, char *list,
size_t list_len, const char *name,
size_t name_len, int type)
{
size_t len = sizeof(XATTR_NAME_NFSV4_ACL);
if (!nfs4_server_supports_acls(NFS_SERVER(dentry->d_inode)))
return 0;
if (list && len <= list_len)
memcpy(list, XATTR_NAME_NFSV4_ACL, len);
return len;
}
/*
* nfs_fhget will use either the mounted_on_fileid or the fileid
*/
static void nfs_fixup_referral_attributes(struct nfs_fattr *fattr)
{
if (!(((fattr->valid & NFS_ATTR_FATTR_MOUNTED_ON_FILEID) ||
(fattr->valid & NFS_ATTR_FATTR_FILEID)) &&
(fattr->valid & NFS_ATTR_FATTR_FSID) &&
(fattr->valid & NFS_ATTR_FATTR_V4_LOCATIONS)))
return;
fattr->valid |= NFS_ATTR_FATTR_TYPE | NFS_ATTR_FATTR_MODE |
NFS_ATTR_FATTR_NLINK | NFS_ATTR_FATTR_V4_REFERRAL;
fattr->mode = S_IFDIR | S_IRUGO | S_IXUGO;
fattr->nlink = 2;
}
static int _nfs4_proc_fs_locations(struct rpc_clnt *client, struct inode *dir,
const struct qstr *name,
struct nfs4_fs_locations *fs_locations,
struct page *page)
{
struct nfs_server *server = NFS_SERVER(dir);
u32 bitmask[2] = {
[0] = FATTR4_WORD0_FSID | FATTR4_WORD0_FS_LOCATIONS,
};
struct nfs4_fs_locations_arg args = {
.dir_fh = NFS_FH(dir),
.name = name,
.page = page,
.bitmask = bitmask,
};
struct nfs4_fs_locations_res res = {
.fs_locations = fs_locations,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_FS_LOCATIONS],
.rpc_argp = &args,
.rpc_resp = &res,
};
int status;
dprintk("%s: start\n", __func__);
/* Ask for the fileid of the absent filesystem if mounted_on_fileid
* is not supported */
if (NFS_SERVER(dir)->attr_bitmask[1] & FATTR4_WORD1_MOUNTED_ON_FILEID)
bitmask[1] |= FATTR4_WORD1_MOUNTED_ON_FILEID;
else
bitmask[0] |= FATTR4_WORD0_FILEID;
nfs_fattr_init(&fs_locations->fattr);
fs_locations->server = server;
fs_locations->nlocations = 0;
status = nfs4_call_sync(client, server, &msg, &args.seq_args, &res.seq_res, 0);
dprintk("%s: returned status = %d\n", __func__, status);
return status;
}
int nfs4_proc_fs_locations(struct rpc_clnt *client, struct inode *dir,
const struct qstr *name,
struct nfs4_fs_locations *fs_locations,
struct page *page)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(NFS_SERVER(dir),
_nfs4_proc_fs_locations(client, dir, name, fs_locations, page),
&exception);
} while (exception.retry);
return err;
}
static int _nfs4_proc_secinfo(struct inode *dir, const struct qstr *name, struct nfs4_secinfo_flavors *flavors)
{
int status;
struct nfs4_secinfo_arg args = {
.dir_fh = NFS_FH(dir),
.name = name,
};
struct nfs4_secinfo_res res = {
.flavors = flavors,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SECINFO],
.rpc_argp = &args,
.rpc_resp = &res,
};
dprintk("NFS call secinfo %s\n", name->name);
status = nfs4_call_sync(NFS_SERVER(dir)->client, NFS_SERVER(dir), &msg, &args.seq_args, &res.seq_res, 0);
dprintk("NFS reply secinfo: %d\n", status);
return status;
}
int nfs4_proc_secinfo(struct inode *dir, const struct qstr *name,
struct nfs4_secinfo_flavors *flavors)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(NFS_SERVER(dir),
_nfs4_proc_secinfo(dir, name, flavors),
&exception);
} while (exception.retry);
return err;
}
#ifdef CONFIG_NFS_V4_1
/*
* Check the exchange flags returned by the server for invalid flags, having
* both PNFS and NON_PNFS flags set, and not having one of NON_PNFS, PNFS, or
* DS flags set.
*/
static int nfs4_check_cl_exchange_flags(u32 flags)
{
if (flags & ~EXCHGID4_FLAG_MASK_R)
goto out_inval;
if ((flags & EXCHGID4_FLAG_USE_PNFS_MDS) &&
(flags & EXCHGID4_FLAG_USE_NON_PNFS))
goto out_inval;
if (!(flags & (EXCHGID4_FLAG_MASK_PNFS)))
goto out_inval;
return NFS_OK;
out_inval:
return -NFS4ERR_INVAL;
}
static bool
nfs41_same_server_scope(struct nfs41_server_scope *a,
struct nfs41_server_scope *b)
{
if (a->server_scope_sz == b->server_scope_sz &&
memcmp(a->server_scope, b->server_scope, a->server_scope_sz) == 0)
return true;
return false;
}
/*
* nfs4_proc_bind_conn_to_session()
*
* The 4.1 client currently uses the same TCP connection for the
* fore and backchannel.
*/
int nfs4_proc_bind_conn_to_session(struct nfs_client *clp, struct rpc_cred *cred)
{
int status;
struct nfs41_bind_conn_to_session_res res;
struct rpc_message msg = {
.rpc_proc =
&nfs4_procedures[NFSPROC4_CLNT_BIND_CONN_TO_SESSION],
.rpc_argp = clp,
.rpc_resp = &res,
.rpc_cred = cred,
};
dprintk("--> %s\n", __func__);
BUG_ON(clp == NULL);
res.session = kzalloc(sizeof(struct nfs4_session), GFP_NOFS);
if (unlikely(res.session == NULL)) {
status = -ENOMEM;
goto out;
}
status = rpc_call_sync(clp->cl_rpcclient, &msg, RPC_TASK_TIMEOUT);
if (status == 0) {
if (memcmp(res.session->sess_id.data,
clp->cl_session->sess_id.data, NFS4_MAX_SESSIONID_LEN)) {
dprintk("NFS: %s: Session ID mismatch\n", __func__);
status = -EIO;
goto out_session;
}
if (res.dir != NFS4_CDFS4_BOTH) {
dprintk("NFS: %s: Unexpected direction from server\n",
__func__);
status = -EIO;
goto out_session;
}
if (res.use_conn_in_rdma_mode) {
dprintk("NFS: %s: Server returned RDMA mode = true\n",
__func__);
status = -EIO;
goto out_session;
}
}
out_session:
kfree(res.session);
out:
dprintk("<-- %s status= %d\n", __func__, status);
return status;
}
/*
* nfs4_proc_exchange_id()
*
* Returns zero, a negative errno, or a negative NFS4ERR status code.
*
* Since the clientid has expired, all compounds using sessions
* associated with the stale clientid will be returning
* NFS4ERR_BADSESSION in the sequence operation, and will therefore
* be in some phase of session reset.
*/
int nfs4_proc_exchange_id(struct nfs_client *clp, struct rpc_cred *cred)
{
nfs4_verifier verifier;
struct nfs41_exchange_id_args args = {
.verifier = &verifier,
.client = clp,
.flags = EXCHGID4_FLAG_SUPP_MOVED_REFER,
};
struct nfs41_exchange_id_res res = {
0
};
int status;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_EXCHANGE_ID],
.rpc_argp = &args,
.rpc_resp = &res,
.rpc_cred = cred,
};
nfs4_init_boot_verifier(clp, &verifier);
args.id_len = nfs4_init_uniform_client_string(clp, args.id,
sizeof(args.id));
dprintk("NFS call exchange_id auth=%s, '%.*s'\n",
clp->cl_rpcclient->cl_auth->au_ops->au_name,
args.id_len, args.id);
res.server_owner = kzalloc(sizeof(struct nfs41_server_owner),
GFP_NOFS);
if (unlikely(res.server_owner == NULL)) {
status = -ENOMEM;
goto out;
}
res.server_scope = kzalloc(sizeof(struct nfs41_server_scope),
GFP_NOFS);
if (unlikely(res.server_scope == NULL)) {
status = -ENOMEM;
goto out_server_owner;
}
res.impl_id = kzalloc(sizeof(struct nfs41_impl_id), GFP_NOFS);
if (unlikely(res.impl_id == NULL)) {
status = -ENOMEM;
goto out_server_scope;
}
status = rpc_call_sync(clp->cl_rpcclient, &msg, RPC_TASK_TIMEOUT);
if (status == 0)
status = nfs4_check_cl_exchange_flags(res.flags);
if (status == 0) {
clp->cl_clientid = res.clientid;
clp->cl_exchange_flags = (res.flags & ~EXCHGID4_FLAG_CONFIRMED_R);
if (!(res.flags & EXCHGID4_FLAG_CONFIRMED_R))
clp->cl_seqid = res.seqid;
kfree(clp->cl_serverowner);
clp->cl_serverowner = res.server_owner;
res.server_owner = NULL;
/* use the most recent implementation id */
kfree(clp->cl_implid);
clp->cl_implid = res.impl_id;
if (clp->cl_serverscope != NULL &&
!nfs41_same_server_scope(clp->cl_serverscope,
res.server_scope)) {
dprintk("%s: server_scope mismatch detected\n",
__func__);
set_bit(NFS4CLNT_SERVER_SCOPE_MISMATCH, &clp->cl_state);
kfree(clp->cl_serverscope);
clp->cl_serverscope = NULL;
}
if (clp->cl_serverscope == NULL) {
clp->cl_serverscope = res.server_scope;
goto out;
}
} else
kfree(res.impl_id);
out_server_owner:
kfree(res.server_owner);
out_server_scope:
kfree(res.server_scope);
out:
if (clp->cl_implid != NULL)
dprintk("NFS reply exchange_id: Server Implementation ID: "
"domain: %s, name: %s, date: %llu,%u\n",
clp->cl_implid->domain, clp->cl_implid->name,
clp->cl_implid->date.seconds,
clp->cl_implid->date.nseconds);
dprintk("NFS reply exchange_id: %d\n", status);
return status;
}
static int _nfs4_proc_destroy_clientid(struct nfs_client *clp,
struct rpc_cred *cred)
{
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_DESTROY_CLIENTID],
.rpc_argp = clp,
.rpc_cred = cred,
};
int status;
status = rpc_call_sync(clp->cl_rpcclient, &msg, RPC_TASK_TIMEOUT);
if (status)
dprintk("NFS: Got error %d from the server %s on "
"DESTROY_CLIENTID.", status, clp->cl_hostname);
return status;
}
static int nfs4_proc_destroy_clientid(struct nfs_client *clp,
struct rpc_cred *cred)
{
unsigned int loop;
int ret;
for (loop = NFS4_MAX_LOOP_ON_RECOVER; loop != 0; loop--) {
ret = _nfs4_proc_destroy_clientid(clp, cred);
switch (ret) {
case -NFS4ERR_DELAY:
case -NFS4ERR_CLIENTID_BUSY:
ssleep(1);
break;
default:
return ret;
}
}
return 0;
}
int nfs4_destroy_clientid(struct nfs_client *clp)
{
struct rpc_cred *cred;
int ret = 0;
if (clp->cl_mvops->minor_version < 1)
goto out;
if (clp->cl_exchange_flags == 0)
goto out;
if (clp->cl_preserve_clid)
goto out;
cred = nfs4_get_exchange_id_cred(clp);
ret = nfs4_proc_destroy_clientid(clp, cred);
if (cred)
put_rpccred(cred);
switch (ret) {
case 0:
case -NFS4ERR_STALE_CLIENTID:
clp->cl_exchange_flags = 0;
}
out:
return ret;
}
struct nfs4_get_lease_time_data {
struct nfs4_get_lease_time_args *args;
struct nfs4_get_lease_time_res *res;
struct nfs_client *clp;
};
static void nfs4_get_lease_time_prepare(struct rpc_task *task,
void *calldata)
{
int ret;
struct nfs4_get_lease_time_data *data =
(struct nfs4_get_lease_time_data *)calldata;
dprintk("--> %s\n", __func__);
rpc_task_set_priority(task, RPC_PRIORITY_PRIVILEGED);
/* just setup sequence, do not trigger session recovery
since we're invoked within one */
ret = nfs41_setup_sequence(data->clp->cl_session,
&data->args->la_seq_args,
&data->res->lr_seq_res, task);
BUG_ON(ret == -EAGAIN);
rpc_call_start(task);
dprintk("<-- %s\n", __func__);
}
/*
* Called from nfs4_state_manager thread for session setup, so don't recover
* from sequence operation or clientid errors.
*/
static void nfs4_get_lease_time_done(struct rpc_task *task, void *calldata)
{
struct nfs4_get_lease_time_data *data =
(struct nfs4_get_lease_time_data *)calldata;
dprintk("--> %s\n", __func__);
if (!nfs41_sequence_done(task, &data->res->lr_seq_res))
return;
switch (task->tk_status) {
case -NFS4ERR_DELAY:
case -NFS4ERR_GRACE:
dprintk("%s Retry: tk_status %d\n", __func__, task->tk_status);
rpc_delay(task, NFS4_POLL_RETRY_MIN);
task->tk_status = 0;
/* fall through */
case -NFS4ERR_RETRY_UNCACHED_REP:
rpc_restart_call_prepare(task);
return;
}
dprintk("<-- %s\n", __func__);
}
static const struct rpc_call_ops nfs4_get_lease_time_ops = {
.rpc_call_prepare = nfs4_get_lease_time_prepare,
.rpc_call_done = nfs4_get_lease_time_done,
};
int nfs4_proc_get_lease_time(struct nfs_client *clp, struct nfs_fsinfo *fsinfo)
{
struct rpc_task *task;
struct nfs4_get_lease_time_args args;
struct nfs4_get_lease_time_res res = {
.lr_fsinfo = fsinfo,
};
struct nfs4_get_lease_time_data data = {
.args = &args,
.res = &res,
.clp = clp,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GET_LEASE_TIME],
.rpc_argp = &args,
.rpc_resp = &res,
};
struct rpc_task_setup task_setup = {
.rpc_client = clp->cl_rpcclient,
.rpc_message = &msg,
.callback_ops = &nfs4_get_lease_time_ops,
.callback_data = &data,
.flags = RPC_TASK_TIMEOUT,
};
int status;
nfs41_init_sequence(&args.la_seq_args, &res.lr_seq_res, 0);
dprintk("--> %s\n", __func__);
task = rpc_run_task(&task_setup);
if (IS_ERR(task))
status = PTR_ERR(task);
else {
status = task->tk_status;
rpc_put_task(task);
}
dprintk("<-- %s return %d\n", __func__, status);
return status;
}
static struct nfs4_slot *nfs4_alloc_slots(u32 max_slots, gfp_t gfp_flags)
{
return kcalloc(max_slots, sizeof(struct nfs4_slot), gfp_flags);
}
static void nfs4_add_and_init_slots(struct nfs4_slot_table *tbl,
struct nfs4_slot *new,
u32 max_slots,
u32 ivalue)
{
struct nfs4_slot *old = NULL;
u32 i;
spin_lock(&tbl->slot_tbl_lock);
if (new) {
old = tbl->slots;
tbl->slots = new;
tbl->max_slots = max_slots;
}
tbl->highest_used_slotid = NFS4_NO_SLOT;
for (i = 0; i < tbl->max_slots; i++)
tbl->slots[i].seq_nr = ivalue;
spin_unlock(&tbl->slot_tbl_lock);
kfree(old);
}
/*
* (re)Initialise a slot table
*/
static int nfs4_realloc_slot_table(struct nfs4_slot_table *tbl, u32 max_reqs,
u32 ivalue)
{
struct nfs4_slot *new = NULL;
int ret = -ENOMEM;
dprintk("--> %s: max_reqs=%u, tbl->max_slots %d\n", __func__,
max_reqs, tbl->max_slots);
/* Does the newly negotiated max_reqs match the existing slot table? */
if (max_reqs != tbl->max_slots) {
new = nfs4_alloc_slots(max_reqs, GFP_NOFS);
if (!new)
goto out;
}
ret = 0;
nfs4_add_and_init_slots(tbl, new, max_reqs, ivalue);
dprintk("%s: tbl=%p slots=%p max_slots=%d\n", __func__,
tbl, tbl->slots, tbl->max_slots);
out:
dprintk("<-- %s: return %d\n", __func__, ret);
return ret;
}
/* Destroy the slot table */
static void nfs4_destroy_slot_tables(struct nfs4_session *session)
{
if (session->fc_slot_table.slots != NULL) {
kfree(session->fc_slot_table.slots);
session->fc_slot_table.slots = NULL;
}
if (session->bc_slot_table.slots != NULL) {
kfree(session->bc_slot_table.slots);
session->bc_slot_table.slots = NULL;
}
return;
}
/*
* Initialize or reset the forechannel and backchannel tables
*/
static int nfs4_setup_session_slot_tables(struct nfs4_session *ses)
{
struct nfs4_slot_table *tbl;
int status;
dprintk("--> %s\n", __func__);
/* Fore channel */
tbl = &ses->fc_slot_table;
status = nfs4_realloc_slot_table(tbl, ses->fc_attrs.max_reqs, 1);
if (status) /* -ENOMEM */
return status;
/* Back channel */
tbl = &ses->bc_slot_table;
status = nfs4_realloc_slot_table(tbl, ses->bc_attrs.max_reqs, 0);
if (status && tbl->slots == NULL)
/* Fore and back channel share a connection so get
* both slot tables or neither */
nfs4_destroy_slot_tables(ses);
return status;
}
struct nfs4_session *nfs4_alloc_session(struct nfs_client *clp)
{
struct nfs4_session *session;
struct nfs4_slot_table *tbl;
session = kzalloc(sizeof(struct nfs4_session), GFP_NOFS);
if (!session)
return NULL;
tbl = &session->fc_slot_table;
tbl->highest_used_slotid = NFS4_NO_SLOT;
spin_lock_init(&tbl->slot_tbl_lock);
rpc_init_priority_wait_queue(&tbl->slot_tbl_waitq, "ForeChannel Slot table");
init_completion(&tbl->complete);
tbl = &session->bc_slot_table;
tbl->highest_used_slotid = NFS4_NO_SLOT;
spin_lock_init(&tbl->slot_tbl_lock);
rpc_init_wait_queue(&tbl->slot_tbl_waitq, "BackChannel Slot table");
init_completion(&tbl->complete);
session->session_state = 1<<NFS4_SESSION_INITING;
session->clp = clp;
return session;
}
void nfs4_destroy_session(struct nfs4_session *session)
{
struct rpc_xprt *xprt;
struct rpc_cred *cred;
cred = nfs4_get_exchange_id_cred(session->clp);
nfs4_proc_destroy_session(session, cred);
if (cred)
put_rpccred(cred);
rcu_read_lock();
xprt = rcu_dereference(session->clp->cl_rpcclient->cl_xprt);
rcu_read_unlock();
dprintk("%s Destroy backchannel for xprt %p\n",
__func__, xprt);
xprt_destroy_backchannel(xprt, NFS41_BC_MIN_CALLBACKS);
nfs4_destroy_slot_tables(session);
kfree(session);
}
/*
* Initialize the values to be used by the client in CREATE_SESSION
* If nfs4_init_session set the fore channel request and response sizes,
* use them.
*
* Set the back channel max_resp_sz_cached to zero to force the client to
* always set csa_cachethis to FALSE because the current implementation
* of the back channel DRC only supports caching the CB_SEQUENCE operation.
*/
static void nfs4_init_channel_attrs(struct nfs41_create_session_args *args)
{
struct nfs4_session *session = args->client->cl_session;
unsigned int mxrqst_sz = session->fc_attrs.max_rqst_sz,
mxresp_sz = session->fc_attrs.max_resp_sz;
if (mxrqst_sz == 0)
mxrqst_sz = NFS_MAX_FILE_IO_SIZE;
if (mxresp_sz == 0)
mxresp_sz = NFS_MAX_FILE_IO_SIZE;
/* Fore channel attributes */
args->fc_attrs.max_rqst_sz = mxrqst_sz;
args->fc_attrs.max_resp_sz = mxresp_sz;
args->fc_attrs.max_ops = NFS4_MAX_OPS;
args->fc_attrs.max_reqs = max_session_slots;
dprintk("%s: Fore Channel : max_rqst_sz=%u max_resp_sz=%u "
"max_ops=%u max_reqs=%u\n",
__func__,
args->fc_attrs.max_rqst_sz, args->fc_attrs.max_resp_sz,
args->fc_attrs.max_ops, args->fc_attrs.max_reqs);
/* Back channel attributes */
args->bc_attrs.max_rqst_sz = PAGE_SIZE;
args->bc_attrs.max_resp_sz = PAGE_SIZE;
args->bc_attrs.max_resp_sz_cached = 0;
args->bc_attrs.max_ops = NFS4_MAX_BACK_CHANNEL_OPS;
args->bc_attrs.max_reqs = 1;
dprintk("%s: Back Channel : max_rqst_sz=%u max_resp_sz=%u "
"max_resp_sz_cached=%u max_ops=%u max_reqs=%u\n",
__func__,
args->bc_attrs.max_rqst_sz, args->bc_attrs.max_resp_sz,
args->bc_attrs.max_resp_sz_cached, args->bc_attrs.max_ops,
args->bc_attrs.max_reqs);
}
static int nfs4_verify_fore_channel_attrs(struct nfs41_create_session_args *args, struct nfs4_session *session)
{
struct nfs4_channel_attrs *sent = &args->fc_attrs;
struct nfs4_channel_attrs *rcvd = &session->fc_attrs;
if (rcvd->max_resp_sz > sent->max_resp_sz)
return -EINVAL;
/*
* Our requested max_ops is the minimum we need; we're not
* prepared to break up compounds into smaller pieces than that.
* So, no point even trying to continue if the server won't
* cooperate:
*/
if (rcvd->max_ops < sent->max_ops)
return -EINVAL;
if (rcvd->max_reqs == 0)
return -EINVAL;
if (rcvd->max_reqs > NFS4_MAX_SLOT_TABLE)
rcvd->max_reqs = NFS4_MAX_SLOT_TABLE;
return 0;
}
static int nfs4_verify_back_channel_attrs(struct nfs41_create_session_args *args, struct nfs4_session *session)
{
struct nfs4_channel_attrs *sent = &args->bc_attrs;
struct nfs4_channel_attrs *rcvd = &session->bc_attrs;
if (rcvd->max_rqst_sz > sent->max_rqst_sz)
return -EINVAL;
if (rcvd->max_resp_sz < sent->max_resp_sz)
return -EINVAL;
if (rcvd->max_resp_sz_cached > sent->max_resp_sz_cached)
return -EINVAL;
/* These would render the backchannel useless: */
if (rcvd->max_ops != sent->max_ops)
return -EINVAL;
if (rcvd->max_reqs != sent->max_reqs)
return -EINVAL;
return 0;
}
static int nfs4_verify_channel_attrs(struct nfs41_create_session_args *args,
struct nfs4_session *session)
{
int ret;
ret = nfs4_verify_fore_channel_attrs(args, session);
if (ret)
return ret;
return nfs4_verify_back_channel_attrs(args, session);
}
static int _nfs4_proc_create_session(struct nfs_client *clp,
struct rpc_cred *cred)
{
struct nfs4_session *session = clp->cl_session;
struct nfs41_create_session_args args = {
.client = clp,
.cb_program = NFS4_CALLBACK,
};
struct nfs41_create_session_res res = {
.client = clp,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_CREATE_SESSION],
.rpc_argp = &args,
.rpc_resp = &res,
.rpc_cred = cred,
};
int status;
nfs4_init_channel_attrs(&args);
args.flags = (SESSION4_PERSIST | SESSION4_BACK_CHAN);
status = rpc_call_sync(session->clp->cl_rpcclient, &msg, RPC_TASK_TIMEOUT);
if (!status)
/* Verify the session's negotiated channel_attrs values */
status = nfs4_verify_channel_attrs(&args, session);
if (!status) {
/* Increment the clientid slot sequence id */
clp->cl_seqid++;
}
return status;
}
/*
* Issues a CREATE_SESSION operation to the server.
* It is the responsibility of the caller to verify the session is
* expired before calling this routine.
*/
int nfs4_proc_create_session(struct nfs_client *clp, struct rpc_cred *cred)
{
int status;
unsigned *ptr;
struct nfs4_session *session = clp->cl_session;
dprintk("--> %s clp=%p session=%p\n", __func__, clp, session);
status = _nfs4_proc_create_session(clp, cred);
if (status)
goto out;
/* Init or reset the session slot tables */
status = nfs4_setup_session_slot_tables(session);
dprintk("slot table setup returned %d\n", status);
if (status)
goto out;
ptr = (unsigned *)&session->sess_id.data[0];
dprintk("%s client>seqid %d sessionid %u:%u:%u:%u\n", __func__,
clp->cl_seqid, ptr[0], ptr[1], ptr[2], ptr[3]);
out:
dprintk("<-- %s\n", __func__);
return status;
}
/*
* Issue the over-the-wire RPC DESTROY_SESSION.
* The caller must serialize access to this routine.
*/
int nfs4_proc_destroy_session(struct nfs4_session *session,
struct rpc_cred *cred)
{
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_DESTROY_SESSION],
.rpc_argp = session,
.rpc_cred = cred,
};
int status = 0;
dprintk("--> nfs4_proc_destroy_session\n");
/* session is still being setup */
if (session->clp->cl_cons_state != NFS_CS_READY)
return status;
status = rpc_call_sync(session->clp->cl_rpcclient, &msg, RPC_TASK_TIMEOUT);
if (status)
dprintk("NFS: Got error %d from the server on DESTROY_SESSION. "
"Session has been destroyed regardless...\n", status);
dprintk("<-- nfs4_proc_destroy_session\n");
return status;
}
/*
* With sessions, the client is not marked ready until after a
* successful EXCHANGE_ID and CREATE_SESSION.
*
* Map errors cl_cons_state errors to EPROTONOSUPPORT to indicate
* other versions of NFS can be tried.
*/
static int nfs41_check_session_ready(struct nfs_client *clp)
{
int ret;
if (clp->cl_cons_state == NFS_CS_SESSION_INITING) {
ret = nfs4_client_recover_expired_lease(clp);
if (ret)
return ret;
}
if (clp->cl_cons_state < NFS_CS_READY)
return -EPROTONOSUPPORT;
smp_rmb();
return 0;
}
int nfs4_init_session(struct nfs_server *server)
{
struct nfs_client *clp = server->nfs_client;
struct nfs4_session *session;
unsigned int rsize, wsize;
if (!nfs4_has_session(clp))
return 0;
session = clp->cl_session;
spin_lock(&clp->cl_lock);
if (test_and_clear_bit(NFS4_SESSION_INITING, &session->session_state)) {
rsize = server->rsize;
if (rsize == 0)
rsize = NFS_MAX_FILE_IO_SIZE;
wsize = server->wsize;
if (wsize == 0)
wsize = NFS_MAX_FILE_IO_SIZE;
session->fc_attrs.max_rqst_sz = wsize + nfs41_maxwrite_overhead;
session->fc_attrs.max_resp_sz = rsize + nfs41_maxread_overhead;
}
spin_unlock(&clp->cl_lock);
return nfs41_check_session_ready(clp);
}
int nfs4_init_ds_session(struct nfs_client *clp, unsigned long lease_time)
{
struct nfs4_session *session = clp->cl_session;
int ret;
spin_lock(&clp->cl_lock);
if (test_and_clear_bit(NFS4_SESSION_INITING, &session->session_state)) {
/*
* Do not set NFS_CS_CHECK_LEASE_TIME instead set the
* DS lease to be equal to the MDS lease.
*/
clp->cl_lease_time = lease_time;
clp->cl_last_renewal = jiffies;
}
spin_unlock(&clp->cl_lock);
ret = nfs41_check_session_ready(clp);
if (ret)
return ret;
/* Test for the DS role */
if (!is_ds_client(clp))
return -ENODEV;
return 0;
}
EXPORT_SYMBOL_GPL(nfs4_init_ds_session);
/*
* Renew the cl_session lease.
*/
struct nfs4_sequence_data {
struct nfs_client *clp;
struct nfs4_sequence_args args;
struct nfs4_sequence_res res;
};
static void nfs41_sequence_release(void *data)
{
struct nfs4_sequence_data *calldata = data;
struct nfs_client *clp = calldata->clp;
if (atomic_read(&clp->cl_count) > 1)
nfs4_schedule_state_renewal(clp);
nfs_put_client(clp);
kfree(calldata);
}
static int nfs41_sequence_handle_errors(struct rpc_task *task, struct nfs_client *clp)
{
switch(task->tk_status) {
case -NFS4ERR_DELAY:
rpc_delay(task, NFS4_POLL_RETRY_MAX);
return -EAGAIN;
default:
nfs4_schedule_lease_recovery(clp);
}
return 0;
}
static void nfs41_sequence_call_done(struct rpc_task *task, void *data)
{
struct nfs4_sequence_data *calldata = data;
struct nfs_client *clp = calldata->clp;
if (!nfs41_sequence_done(task, task->tk_msg.rpc_resp))
return;
if (task->tk_status < 0) {
dprintk("%s ERROR %d\n", __func__, task->tk_status);
if (atomic_read(&clp->cl_count) == 1)
goto out;
if (nfs41_sequence_handle_errors(task, clp) == -EAGAIN) {
rpc_restart_call_prepare(task);
return;
}
}
dprintk("%s rpc_cred %p\n", __func__, task->tk_msg.rpc_cred);
out:
dprintk("<-- %s\n", __func__);
}
static void nfs41_sequence_prepare(struct rpc_task *task, void *data)
{
struct nfs4_sequence_data *calldata = data;
struct nfs_client *clp = calldata->clp;
struct nfs4_sequence_args *args;
struct nfs4_sequence_res *res;
args = task->tk_msg.rpc_argp;
res = task->tk_msg.rpc_resp;
if (nfs41_setup_sequence(clp->cl_session, args, res, task))
return;
rpc_call_start(task);
}
static const struct rpc_call_ops nfs41_sequence_ops = {
.rpc_call_done = nfs41_sequence_call_done,
.rpc_call_prepare = nfs41_sequence_prepare,
.rpc_release = nfs41_sequence_release,
};
static struct rpc_task *_nfs41_proc_sequence(struct nfs_client *clp, struct rpc_cred *cred)
{
struct nfs4_sequence_data *calldata;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SEQUENCE],
.rpc_cred = cred,
};
struct rpc_task_setup task_setup_data = {
.rpc_client = clp->cl_rpcclient,
.rpc_message = &msg,
.callback_ops = &nfs41_sequence_ops,
.flags = RPC_TASK_ASYNC | RPC_TASK_SOFT,
};
if (!atomic_inc_not_zero(&clp->cl_count))
return ERR_PTR(-EIO);
calldata = kzalloc(sizeof(*calldata), GFP_NOFS);
if (calldata == NULL) {
nfs_put_client(clp);
return ERR_PTR(-ENOMEM);
}
nfs41_init_sequence(&calldata->args, &calldata->res, 0);
msg.rpc_argp = &calldata->args;
msg.rpc_resp = &calldata->res;
calldata->clp = clp;
task_setup_data.callback_data = calldata;
return rpc_run_task(&task_setup_data);
}
static int nfs41_proc_async_sequence(struct nfs_client *clp, struct rpc_cred *cred, unsigned renew_flags)
{
struct rpc_task *task;
int ret = 0;
if ((renew_flags & NFS4_RENEW_TIMEOUT) == 0)
return 0;
task = _nfs41_proc_sequence(clp, cred);
if (IS_ERR(task))
ret = PTR_ERR(task);
else
rpc_put_task_async(task);
dprintk("<-- %s status=%d\n", __func__, ret);
return ret;
}
static int nfs4_proc_sequence(struct nfs_client *clp, struct rpc_cred *cred)
{
struct rpc_task *task;
int ret;
task = _nfs41_proc_sequence(clp, cred);
if (IS_ERR(task)) {
ret = PTR_ERR(task);
goto out;
}
ret = rpc_wait_for_completion_task(task);
if (!ret) {
struct nfs4_sequence_res *res = task->tk_msg.rpc_resp;
if (task->tk_status == 0)
nfs41_handle_sequence_flag_errors(clp, res->sr_status_flags);
ret = task->tk_status;
}
rpc_put_task(task);
out:
dprintk("<-- %s status=%d\n", __func__, ret);
return ret;
}
struct nfs4_reclaim_complete_data {
struct nfs_client *clp;
struct nfs41_reclaim_complete_args arg;
struct nfs41_reclaim_complete_res res;
};
static void nfs4_reclaim_complete_prepare(struct rpc_task *task, void *data)
{
struct nfs4_reclaim_complete_data *calldata = data;
rpc_task_set_priority(task, RPC_PRIORITY_PRIVILEGED);
if (nfs41_setup_sequence(calldata->clp->cl_session,
&calldata->arg.seq_args,
&calldata->res.seq_res, task))
return;
rpc_call_start(task);
}
static int nfs41_reclaim_complete_handle_errors(struct rpc_task *task, struct nfs_client *clp)
{
switch(task->tk_status) {
case 0:
case -NFS4ERR_COMPLETE_ALREADY:
case -NFS4ERR_WRONG_CRED: /* What to do here? */
break;
case -NFS4ERR_DELAY:
rpc_delay(task, NFS4_POLL_RETRY_MAX);
/* fall through */
case -NFS4ERR_RETRY_UNCACHED_REP:
return -EAGAIN;
default:
nfs4_schedule_lease_recovery(clp);
}
return 0;
}
static void nfs4_reclaim_complete_done(struct rpc_task *task, void *data)
{
struct nfs4_reclaim_complete_data *calldata = data;
struct nfs_client *clp = calldata->clp;
struct nfs4_sequence_res *res = &calldata->res.seq_res;
dprintk("--> %s\n", __func__);
if (!nfs41_sequence_done(task, res))
return;
if (nfs41_reclaim_complete_handle_errors(task, clp) == -EAGAIN) {
rpc_restart_call_prepare(task);
return;
}
dprintk("<-- %s\n", __func__);
}
static void nfs4_free_reclaim_complete_data(void *data)
{
struct nfs4_reclaim_complete_data *calldata = data;
kfree(calldata);
}
static const struct rpc_call_ops nfs4_reclaim_complete_call_ops = {
.rpc_call_prepare = nfs4_reclaim_complete_prepare,
.rpc_call_done = nfs4_reclaim_complete_done,
.rpc_release = nfs4_free_reclaim_complete_data,
};
/*
* Issue a global reclaim complete.
*/
static int nfs41_proc_reclaim_complete(struct nfs_client *clp)
{
struct nfs4_reclaim_complete_data *calldata;
struct rpc_task *task;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_RECLAIM_COMPLETE],
};
struct rpc_task_setup task_setup_data = {
.rpc_client = clp->cl_rpcclient,
.rpc_message = &msg,
.callback_ops = &nfs4_reclaim_complete_call_ops,
.flags = RPC_TASK_ASYNC,
};
int status = -ENOMEM;
dprintk("--> %s\n", __func__);
calldata = kzalloc(sizeof(*calldata), GFP_NOFS);
if (calldata == NULL)
goto out;
calldata->clp = clp;
calldata->arg.one_fs = 0;
nfs41_init_sequence(&calldata->arg.seq_args, &calldata->res.seq_res, 0);
msg.rpc_argp = &calldata->arg;
msg.rpc_resp = &calldata->res;
task_setup_data.callback_data = calldata;
task = rpc_run_task(&task_setup_data);
if (IS_ERR(task)) {
status = PTR_ERR(task);
goto out;
}
status = nfs4_wait_for_completion_rpc_task(task);
if (status == 0)
status = task->tk_status;
rpc_put_task(task);
return 0;
out:
dprintk("<-- %s status=%d\n", __func__, status);
return status;
}
static void
nfs4_layoutget_prepare(struct rpc_task *task, void *calldata)
{
struct nfs4_layoutget *lgp = calldata;
struct nfs_server *server = NFS_SERVER(lgp->args.inode);
dprintk("--> %s\n", __func__);
/* Note the is a race here, where a CB_LAYOUTRECALL can come in
* right now covering the LAYOUTGET we are about to send.
* However, that is not so catastrophic, and there seems
* to be no way to prevent it completely.
*/
if (nfs4_setup_sequence(server, &lgp->args.seq_args,
&lgp->res.seq_res, task))
return;
if (pnfs_choose_layoutget_stateid(&lgp->args.stateid,
NFS_I(lgp->args.inode)->layout,
lgp->args.ctx->state)) {
rpc_exit(task, NFS4_OK);
return;
}
rpc_call_start(task);
}
static void nfs4_layoutget_done(struct rpc_task *task, void *calldata)
{
struct nfs4_layoutget *lgp = calldata;
struct inode *inode = lgp->args.inode;
struct nfs_server *server = NFS_SERVER(inode);
struct pnfs_layout_hdr *lo;
struct nfs4_state *state = NULL;
dprintk("--> %s\n", __func__);
if (!nfs4_sequence_done(task, &lgp->res.seq_res))
goto out;
switch (task->tk_status) {
case 0:
goto out;
case -NFS4ERR_LAYOUTTRYLATER:
case -NFS4ERR_RECALLCONFLICT:
task->tk_status = -NFS4ERR_DELAY;
break;
case -NFS4ERR_EXPIRED:
case -NFS4ERR_BAD_STATEID:
spin_lock(&inode->i_lock);
lo = NFS_I(inode)->layout;
if (!lo || list_empty(&lo->plh_segs)) {
spin_unlock(&inode->i_lock);
/* If the open stateid was bad, then recover it. */
state = lgp->args.ctx->state;
} else {
LIST_HEAD(head);
pnfs_mark_matching_lsegs_invalid(lo, &head, NULL);
spin_unlock(&inode->i_lock);
/* Mark the bad layout state as invalid, then
* retry using the open stateid. */
pnfs_free_lseg_list(&head);
}
}
if (nfs4_async_handle_error(task, server, state) == -EAGAIN)
rpc_restart_call_prepare(task);
out:
dprintk("<-- %s\n", __func__);
}
static size_t max_response_pages(struct nfs_server *server)
{
u32 max_resp_sz = server->nfs_client->cl_session->fc_attrs.max_resp_sz;
return nfs_page_array_len(0, max_resp_sz);
}
static void nfs4_free_pages(struct page **pages, size_t size)
{
int i;
if (!pages)
return;
for (i = 0; i < size; i++) {
if (!pages[i])
break;
__free_page(pages[i]);
}
kfree(pages);
}
static struct page **nfs4_alloc_pages(size_t size, gfp_t gfp_flags)
{
struct page **pages;
int i;
pages = kcalloc(size, sizeof(struct page *), gfp_flags);
if (!pages) {
dprintk("%s: can't alloc array of %zu pages\n", __func__, size);
return NULL;
}
for (i = 0; i < size; i++) {
pages[i] = alloc_page(gfp_flags);
if (!pages[i]) {
dprintk("%s: failed to allocate page\n", __func__);
nfs4_free_pages(pages, size);
return NULL;
}
}
return pages;
}
static void nfs4_layoutget_release(void *calldata)
{
struct nfs4_layoutget *lgp = calldata;
struct nfs_server *server = NFS_SERVER(lgp->args.inode);
size_t max_pages = max_response_pages(server);
dprintk("--> %s\n", __func__);
nfs4_free_pages(lgp->args.layout.pages, max_pages);
put_nfs_open_context(lgp->args.ctx);
kfree(calldata);
dprintk("<-- %s\n", __func__);
}
static const struct rpc_call_ops nfs4_layoutget_call_ops = {
.rpc_call_prepare = nfs4_layoutget_prepare,
.rpc_call_done = nfs4_layoutget_done,
.rpc_release = nfs4_layoutget_release,
};
struct pnfs_layout_segment *
nfs4_proc_layoutget(struct nfs4_layoutget *lgp, gfp_t gfp_flags)
{
struct nfs_server *server = NFS_SERVER(lgp->args.inode);
size_t max_pages = max_response_pages(server);
struct rpc_task *task;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LAYOUTGET],
.rpc_argp = &lgp->args,
.rpc_resp = &lgp->res,
};
struct rpc_task_setup task_setup_data = {
.rpc_client = server->client,
.rpc_message = &msg,
.callback_ops = &nfs4_layoutget_call_ops,
.callback_data = lgp,
.flags = RPC_TASK_ASYNC,
};
struct pnfs_layout_segment *lseg = NULL;
int status = 0;
dprintk("--> %s\n", __func__);
lgp->args.layout.pages = nfs4_alloc_pages(max_pages, gfp_flags);
if (!lgp->args.layout.pages) {
nfs4_layoutget_release(lgp);
return ERR_PTR(-ENOMEM);
}
lgp->args.layout.pglen = max_pages * PAGE_SIZE;
lgp->res.layoutp = &lgp->args.layout;
lgp->res.seq_res.sr_slot = NULL;
nfs41_init_sequence(&lgp->args.seq_args, &lgp->res.seq_res, 0);
task = rpc_run_task(&task_setup_data);
if (IS_ERR(task))
return ERR_CAST(task);
status = nfs4_wait_for_completion_rpc_task(task);
if (status == 0)
status = task->tk_status;
if (status == 0)
lseg = pnfs_layout_process(lgp);
rpc_put_task(task);
dprintk("<-- %s status=%d\n", __func__, status);
if (status)
return ERR_PTR(status);
return lseg;
}
static void
nfs4_layoutreturn_prepare(struct rpc_task *task, void *calldata)
{
struct nfs4_layoutreturn *lrp = calldata;
dprintk("--> %s\n", __func__);
if (nfs41_setup_sequence(lrp->clp->cl_session, &lrp->args.seq_args,
&lrp->res.seq_res, task))
return;
rpc_call_start(task);
}
static void nfs4_layoutreturn_done(struct rpc_task *task, void *calldata)
{
struct nfs4_layoutreturn *lrp = calldata;
struct nfs_server *server;
dprintk("--> %s\n", __func__);
if (!nfs4_sequence_done(task, &lrp->res.seq_res))
return;
server = NFS_SERVER(lrp->args.inode);
if (nfs4_async_handle_error(task, server, NULL) == -EAGAIN) {
rpc_restart_call_prepare(task);
return;
}
dprintk("<-- %s\n", __func__);
}
static void nfs4_layoutreturn_release(void *calldata)
{
struct nfs4_layoutreturn *lrp = calldata;
struct pnfs_layout_hdr *lo = lrp->args.layout;
dprintk("--> %s\n", __func__);
spin_lock(&lo->plh_inode->i_lock);
if (lrp->res.lrs_present)
pnfs_set_layout_stateid(lo, &lrp->res.stateid, true);
lo->plh_block_lgets--;
spin_unlock(&lo->plh_inode->i_lock);
pnfs_put_layout_hdr(lrp->args.layout);
kfree(calldata);
dprintk("<-- %s\n", __func__);
}
static const struct rpc_call_ops nfs4_layoutreturn_call_ops = {
.rpc_call_prepare = nfs4_layoutreturn_prepare,
.rpc_call_done = nfs4_layoutreturn_done,
.rpc_release = nfs4_layoutreturn_release,
};
int nfs4_proc_layoutreturn(struct nfs4_layoutreturn *lrp)
{
struct rpc_task *task;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LAYOUTRETURN],
.rpc_argp = &lrp->args,
.rpc_resp = &lrp->res,
};
struct rpc_task_setup task_setup_data = {
.rpc_client = lrp->clp->cl_rpcclient,
.rpc_message = &msg,
.callback_ops = &nfs4_layoutreturn_call_ops,
.callback_data = lrp,
};
int status;
dprintk("--> %s\n", __func__);
nfs41_init_sequence(&lrp->args.seq_args, &lrp->res.seq_res, 1);
task = rpc_run_task(&task_setup_data);
if (IS_ERR(task))
return PTR_ERR(task);
status = task->tk_status;
dprintk("<-- %s status=%d\n", __func__, status);
rpc_put_task(task);
return status;
}
/*
* Retrieve the list of Data Server devices from the MDS.
*/
static int _nfs4_getdevicelist(struct nfs_server *server,
const struct nfs_fh *fh,
struct pnfs_devicelist *devlist)
{
struct nfs4_getdevicelist_args args = {
.fh = fh,
.layoutclass = server->pnfs_curr_ld->id,
};
struct nfs4_getdevicelist_res res = {
.devlist = devlist,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETDEVICELIST],
.rpc_argp = &args,
.rpc_resp = &res,
};
int status;
dprintk("--> %s\n", __func__);
status = nfs4_call_sync(server->client, server, &msg, &args.seq_args,
&res.seq_res, 0);
dprintk("<-- %s status=%d\n", __func__, status);
return status;
}
int nfs4_proc_getdevicelist(struct nfs_server *server,
const struct nfs_fh *fh,
struct pnfs_devicelist *devlist)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(server,
_nfs4_getdevicelist(server, fh, devlist),
&exception);
} while (exception.retry);
dprintk("%s: err=%d, num_devs=%u\n", __func__,
err, devlist->num_devs);
return err;
}
EXPORT_SYMBOL_GPL(nfs4_proc_getdevicelist);
static int
_nfs4_proc_getdeviceinfo(struct nfs_server *server, struct pnfs_device *pdev)
{
struct nfs4_getdeviceinfo_args args = {
.pdev = pdev,
};
struct nfs4_getdeviceinfo_res res = {
.pdev = pdev,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETDEVICEINFO],
.rpc_argp = &args,
.rpc_resp = &res,
};
int status;
dprintk("--> %s\n", __func__);
status = nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
dprintk("<-- %s status=%d\n", __func__, status);
return status;
}
int nfs4_proc_getdeviceinfo(struct nfs_server *server, struct pnfs_device *pdev)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(server,
_nfs4_proc_getdeviceinfo(server, pdev),
&exception);
} while (exception.retry);
return err;
}
EXPORT_SYMBOL_GPL(nfs4_proc_getdeviceinfo);
static void nfs4_layoutcommit_prepare(struct rpc_task *task, void *calldata)
{
struct nfs4_layoutcommit_data *data = calldata;
struct nfs_server *server = NFS_SERVER(data->args.inode);
if (nfs4_setup_sequence(server, &data->args.seq_args,
&data->res.seq_res, task))
return;
rpc_call_start(task);
}
static void
nfs4_layoutcommit_done(struct rpc_task *task, void *calldata)
{
struct nfs4_layoutcommit_data *data = calldata;
struct nfs_server *server = NFS_SERVER(data->args.inode);
if (!nfs4_sequence_done(task, &data->res.seq_res))
return;
switch (task->tk_status) { /* Just ignore these failures */
case -NFS4ERR_DELEG_REVOKED: /* layout was recalled */
case -NFS4ERR_BADIOMODE: /* no IOMODE_RW layout for range */
case -NFS4ERR_BADLAYOUT: /* no layout */
case -NFS4ERR_GRACE: /* loca_recalim always false */
task->tk_status = 0;
break;
case 0:
nfs_post_op_update_inode_force_wcc(data->args.inode,
data->res.fattr);
break;
default:
if (nfs4_async_handle_error(task, server, NULL) == -EAGAIN) {
rpc_restart_call_prepare(task);
return;
}
}
}
static void nfs4_layoutcommit_release(void *calldata)
{
struct nfs4_layoutcommit_data *data = calldata;
struct pnfs_layout_segment *lseg, *tmp;
unsigned long *bitlock = &NFS_I(data->args.inode)->flags;
pnfs_cleanup_layoutcommit(data);
/* Matched by references in pnfs_set_layoutcommit */
list_for_each_entry_safe(lseg, tmp, &data->lseg_list, pls_lc_list) {
list_del_init(&lseg->pls_lc_list);
if (test_and_clear_bit(NFS_LSEG_LAYOUTCOMMIT,
&lseg->pls_flags))
pnfs_put_lseg(lseg);
}
clear_bit_unlock(NFS_INO_LAYOUTCOMMITTING, bitlock);
smp_mb__after_clear_bit();
wake_up_bit(bitlock, NFS_INO_LAYOUTCOMMITTING);
put_rpccred(data->cred);
kfree(data);
}
static const struct rpc_call_ops nfs4_layoutcommit_ops = {
.rpc_call_prepare = nfs4_layoutcommit_prepare,
.rpc_call_done = nfs4_layoutcommit_done,
.rpc_release = nfs4_layoutcommit_release,
};
int
nfs4_proc_layoutcommit(struct nfs4_layoutcommit_data *data, bool sync)
{
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LAYOUTCOMMIT],
.rpc_argp = &data->args,
.rpc_resp = &data->res,
.rpc_cred = data->cred,
};
struct rpc_task_setup task_setup_data = {
.task = &data->task,
.rpc_client = NFS_CLIENT(data->args.inode),
.rpc_message = &msg,
.callback_ops = &nfs4_layoutcommit_ops,
.callback_data = data,
.flags = RPC_TASK_ASYNC,
};
struct rpc_task *task;
int status = 0;
dprintk("NFS: %4d initiating layoutcommit call. sync %d "
"lbw: %llu inode %lu\n",
data->task.tk_pid, sync,
data->args.lastbytewritten,
data->args.inode->i_ino);
nfs41_init_sequence(&data->args.seq_args, &data->res.seq_res, 1);
task = rpc_run_task(&task_setup_data);
if (IS_ERR(task))
return PTR_ERR(task);
if (sync == false)
goto out;
status = nfs4_wait_for_completion_rpc_task(task);
if (status != 0)
goto out;
status = task->tk_status;
out:
dprintk("%s: status %d\n", __func__, status);
rpc_put_task(task);
return status;
}
static int
_nfs41_proc_secinfo_no_name(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fsinfo *info, struct nfs4_secinfo_flavors *flavors)
{
struct nfs41_secinfo_no_name_args args = {
.style = SECINFO_STYLE_CURRENT_FH,
};
struct nfs4_secinfo_res res = {
.flavors = flavors,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SECINFO_NO_NAME],
.rpc_argp = &args,
.rpc_resp = &res,
};
return nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
}
static int
nfs41_proc_secinfo_no_name(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fsinfo *info, struct nfs4_secinfo_flavors *flavors)
{
struct nfs4_exception exception = { };
int err;
do {
err = _nfs41_proc_secinfo_no_name(server, fhandle, info, flavors);
switch (err) {
case 0:
case -NFS4ERR_WRONGSEC:
case -NFS4ERR_NOTSUPP:
goto out;
default:
err = nfs4_handle_exception(server, err, &exception);
}
} while (exception.retry);
out:
return err;
}
static int
nfs41_find_root_sec(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fsinfo *info)
{
int err;
struct page *page;
rpc_authflavor_t flavor;
struct nfs4_secinfo_flavors *flavors;
page = alloc_page(GFP_KERNEL);
if (!page) {
err = -ENOMEM;
goto out;
}
flavors = page_address(page);
err = nfs41_proc_secinfo_no_name(server, fhandle, info, flavors);
/*
* Fall back on "guess and check" method if
* the server doesn't support SECINFO_NO_NAME
*/
if (err == -NFS4ERR_WRONGSEC || err == -NFS4ERR_NOTSUPP) {
err = nfs4_find_root_sec(server, fhandle, info);
goto out_freepage;
}
if (err)
goto out_freepage;
flavor = nfs_find_best_sec(flavors);
if (err == 0)
err = nfs4_lookup_root_sec(server, fhandle, info, flavor);
out_freepage:
put_page(page);
if (err == -EACCES)
return -EPERM;
out:
return err;
}
static int _nfs41_test_stateid(struct nfs_server *server, nfs4_stateid *stateid)
{
int status;
struct nfs41_test_stateid_args args = {
.stateid = stateid,
};
struct nfs41_test_stateid_res res;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_TEST_STATEID],
.rpc_argp = &args,
.rpc_resp = &res,
};
dprintk("NFS call test_stateid %p\n", stateid);
nfs41_init_sequence(&args.seq_args, &res.seq_res, 0);
status = nfs4_call_sync_sequence(server->client, server, &msg, &args.seq_args, &res.seq_res, 1);
if (status != NFS_OK) {
dprintk("NFS reply test_stateid: failed, %d\n", status);
return status;
}
dprintk("NFS reply test_stateid: succeeded, %d\n", -res.status);
return -res.status;
}
/**
* nfs41_test_stateid - perform a TEST_STATEID operation
*
* @server: server / transport on which to perform the operation
* @stateid: state ID to test
*
* Returns NFS_OK if the server recognizes that "stateid" is valid.
* Otherwise a negative NFS4ERR value is returned if the operation
* failed or the state ID is not currently valid.
*/
static int nfs41_test_stateid(struct nfs_server *server, nfs4_stateid *stateid)
{
struct nfs4_exception exception = { };
int err;
do {
err = _nfs41_test_stateid(server, stateid);
if (err != -NFS4ERR_DELAY)
break;
nfs4_handle_exception(server, err, &exception);
} while (exception.retry);
return err;
}
static int _nfs4_free_stateid(struct nfs_server *server, nfs4_stateid *stateid)
{
struct nfs41_free_stateid_args args = {
.stateid = stateid,
};
struct nfs41_free_stateid_res res;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_FREE_STATEID],
.rpc_argp = &args,
.rpc_resp = &res,
};
int status;
dprintk("NFS call free_stateid %p\n", stateid);
nfs41_init_sequence(&args.seq_args, &res.seq_res, 0);
status = nfs4_call_sync_sequence(server->client, server, &msg,
&args.seq_args, &res.seq_res, 1);
dprintk("NFS reply free_stateid: %d\n", status);
return status;
}
/**
* nfs41_free_stateid - perform a FREE_STATEID operation
*
* @server: server / transport on which to perform the operation
* @stateid: state ID to release
*
* Returns NFS_OK if the server freed "stateid". Otherwise a
* negative NFS4ERR value is returned.
*/
static int nfs41_free_stateid(struct nfs_server *server, nfs4_stateid *stateid)
{
struct nfs4_exception exception = { };
int err;
do {
err = _nfs4_free_stateid(server, stateid);
if (err != -NFS4ERR_DELAY)
break;
nfs4_handle_exception(server, err, &exception);
} while (exception.retry);
return err;
}
static bool nfs41_match_stateid(const nfs4_stateid *s1,
const nfs4_stateid *s2)
{
if (memcmp(s1->other, s2->other, sizeof(s1->other)) != 0)
return false;
if (s1->seqid == s2->seqid)
return true;
if (s1->seqid == 0 || s2->seqid == 0)
return true;
return false;
}
#endif /* CONFIG_NFS_V4_1 */
static bool nfs4_match_stateid(const nfs4_stateid *s1,
const nfs4_stateid *s2)
{
return nfs4_stateid_match(s1, s2);
}
static const struct nfs4_state_recovery_ops nfs40_reboot_recovery_ops = {
.owner_flag_bit = NFS_OWNER_RECLAIM_REBOOT,
.state_flag_bit = NFS_STATE_RECLAIM_REBOOT,
.recover_open = nfs4_open_reclaim,
.recover_lock = nfs4_lock_reclaim,
.establish_clid = nfs4_init_clientid,
.get_clid_cred = nfs4_get_setclientid_cred,
.detect_trunking = nfs40_discover_server_trunking,
};
#if defined(CONFIG_NFS_V4_1)
static const struct nfs4_state_recovery_ops nfs41_reboot_recovery_ops = {
.owner_flag_bit = NFS_OWNER_RECLAIM_REBOOT,
.state_flag_bit = NFS_STATE_RECLAIM_REBOOT,
.recover_open = nfs4_open_reclaim,
.recover_lock = nfs4_lock_reclaim,
.establish_clid = nfs41_init_clientid,
.get_clid_cred = nfs4_get_exchange_id_cred,
.reclaim_complete = nfs41_proc_reclaim_complete,
.detect_trunking = nfs41_discover_server_trunking,
};
#endif /* CONFIG_NFS_V4_1 */
static const struct nfs4_state_recovery_ops nfs40_nograce_recovery_ops = {
.owner_flag_bit = NFS_OWNER_RECLAIM_NOGRACE,
.state_flag_bit = NFS_STATE_RECLAIM_NOGRACE,
.recover_open = nfs4_open_expired,
.recover_lock = nfs4_lock_expired,
.establish_clid = nfs4_init_clientid,
.get_clid_cred = nfs4_get_setclientid_cred,
};
#if defined(CONFIG_NFS_V4_1)
static const struct nfs4_state_recovery_ops nfs41_nograce_recovery_ops = {
.owner_flag_bit = NFS_OWNER_RECLAIM_NOGRACE,
.state_flag_bit = NFS_STATE_RECLAIM_NOGRACE,
.recover_open = nfs41_open_expired,
.recover_lock = nfs41_lock_expired,
.establish_clid = nfs41_init_clientid,
.get_clid_cred = nfs4_get_exchange_id_cred,
};
#endif /* CONFIG_NFS_V4_1 */
static const struct nfs4_state_maintenance_ops nfs40_state_renewal_ops = {
.sched_state_renewal = nfs4_proc_async_renew,
.get_state_renewal_cred_locked = nfs4_get_renew_cred_locked,
.renew_lease = nfs4_proc_renew,
};
#if defined(CONFIG_NFS_V4_1)
static const struct nfs4_state_maintenance_ops nfs41_state_renewal_ops = {
.sched_state_renewal = nfs41_proc_async_sequence,
.get_state_renewal_cred_locked = nfs4_get_machine_cred_locked,
.renew_lease = nfs4_proc_sequence,
};
#endif
static const struct nfs4_minor_version_ops nfs_v4_0_minor_ops = {
.minor_version = 0,
.call_sync = _nfs4_call_sync,
.match_stateid = nfs4_match_stateid,
.find_root_sec = nfs4_find_root_sec,
.reboot_recovery_ops = &nfs40_reboot_recovery_ops,
.nograce_recovery_ops = &nfs40_nograce_recovery_ops,
.state_renewal_ops = &nfs40_state_renewal_ops,
};
#if defined(CONFIG_NFS_V4_1)
static const struct nfs4_minor_version_ops nfs_v4_1_minor_ops = {
.minor_version = 1,
.call_sync = _nfs4_call_sync_session,
.match_stateid = nfs41_match_stateid,
.find_root_sec = nfs41_find_root_sec,
.reboot_recovery_ops = &nfs41_reboot_recovery_ops,
.nograce_recovery_ops = &nfs41_nograce_recovery_ops,
.state_renewal_ops = &nfs41_state_renewal_ops,
};
#endif
const struct nfs4_minor_version_ops *nfs_v4_minor_ops[] = {
[0] = &nfs_v4_0_minor_ops,
#if defined(CONFIG_NFS_V4_1)
[1] = &nfs_v4_1_minor_ops,
#endif
};
const struct inode_operations nfs4_dir_inode_operations = {
.create = nfs_create,
.lookup = nfs_lookup,
.atomic_open = nfs_atomic_open,
.link = nfs_link,
.unlink = nfs_unlink,
.symlink = nfs_symlink,
.mkdir = nfs_mkdir,
.rmdir = nfs_rmdir,
.mknod = nfs_mknod,
.rename = nfs_rename,
.permission = nfs_permission,
.getattr = nfs_getattr,
.setattr = nfs_setattr,
.getxattr = generic_getxattr,
.setxattr = generic_setxattr,
.listxattr = generic_listxattr,
.removexattr = generic_removexattr,
};
static const struct inode_operations nfs4_file_inode_operations = {
.permission = nfs_permission,
.getattr = nfs_getattr,
.setattr = nfs_setattr,
.getxattr = generic_getxattr,
.setxattr = generic_setxattr,
.listxattr = generic_listxattr,
.removexattr = generic_removexattr,
};
const struct nfs_rpc_ops nfs_v4_clientops = {
.version = 4, /* protocol version */
.dentry_ops = &nfs4_dentry_operations,
.dir_inode_ops = &nfs4_dir_inode_operations,
.file_inode_ops = &nfs4_file_inode_operations,
.file_ops = &nfs4_file_operations,
.getroot = nfs4_proc_get_root,
.submount = nfs4_submount,
.try_mount = nfs4_try_mount,
.getattr = nfs4_proc_getattr,
.setattr = nfs4_proc_setattr,
.lookup = nfs4_proc_lookup,
.access = nfs4_proc_access,
.readlink = nfs4_proc_readlink,
.create = nfs4_proc_create,
.remove = nfs4_proc_remove,
.unlink_setup = nfs4_proc_unlink_setup,
.unlink_rpc_prepare = nfs4_proc_unlink_rpc_prepare,
.unlink_done = nfs4_proc_unlink_done,
.rename = nfs4_proc_rename,
.rename_setup = nfs4_proc_rename_setup,
.rename_rpc_prepare = nfs4_proc_rename_rpc_prepare,
.rename_done = nfs4_proc_rename_done,
.link = nfs4_proc_link,
.symlink = nfs4_proc_symlink,
.mkdir = nfs4_proc_mkdir,
.rmdir = nfs4_proc_remove,
.readdir = nfs4_proc_readdir,
.mknod = nfs4_proc_mknod,
.statfs = nfs4_proc_statfs,
.fsinfo = nfs4_proc_fsinfo,
.pathconf = nfs4_proc_pathconf,
.set_capabilities = nfs4_server_capabilities,
.decode_dirent = nfs4_decode_dirent,
.read_setup = nfs4_proc_read_setup,
.read_pageio_init = pnfs_pageio_init_read,
.read_rpc_prepare = nfs4_proc_read_rpc_prepare,
.read_done = nfs4_read_done,
.write_setup = nfs4_proc_write_setup,
.write_pageio_init = pnfs_pageio_init_write,
.write_rpc_prepare = nfs4_proc_write_rpc_prepare,
.write_done = nfs4_write_done,
.commit_setup = nfs4_proc_commit_setup,
.commit_rpc_prepare = nfs4_proc_commit_rpc_prepare,
.commit_done = nfs4_commit_done,
.lock = nfs4_proc_lock,
.clear_acl_cache = nfs4_zap_acl_attr,
.close_context = nfs4_close_context,
.open_context = nfs4_atomic_open,
.have_delegation = nfs4_have_delegation,
.return_delegation = nfs4_inode_return_delegation,
.alloc_client = nfs4_alloc_client,
.init_client = nfs4_init_client,
.free_client = nfs4_free_client,
.create_server = nfs4_create_server,
.clone_server = nfs_clone_server,
};
static const struct xattr_handler nfs4_xattr_nfs4_acl_handler = {
.prefix = XATTR_NAME_NFSV4_ACL,
.list = nfs4_xattr_list_nfs4_acl,
.get = nfs4_xattr_get_nfs4_acl,
.set = nfs4_xattr_set_nfs4_acl,
};
const struct xattr_handler *nfs4_xattr_handlers[] = {
&nfs4_xattr_nfs4_acl_handler,
NULL
};
/*
* Local variables:
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5767_0 |
crossvul-cpp_data_bad_550_0 | /*
* The copyright in this software is being made available under the 2-clauses
* BSD License, included below. This software may be subject to other third
* party and contributor rights, including patent rights, and no such rights
* are granted under this license.
*
* Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
* Copyright (c) 2002-2014, Professor Benoit Macq
* Copyright (c) 2001-2003, David Janssens
* Copyright (c) 2002-2003, Yannick Verschueren
* Copyright (c) 2003-2007, Francois-Olivier Devaux
* Copyright (c) 2003-2014, Antonin Descampe
* Copyright (c) 2005, Herve Drolon, FreeImage Team
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include "opj_apps_config.h"
#include "openjpeg.h"
#include "color.h"
#ifdef OPJ_HAVE_LIBLCMS2
#include <lcms2.h>
#endif
#ifdef OPJ_HAVE_LIBLCMS1
#include <lcms.h>
#endif
#ifdef OPJ_USE_LEGACY
#define OPJ_CLRSPC_GRAY CLRSPC_GRAY
#define OPJ_CLRSPC_SRGB CLRSPC_SRGB
#endif
/*--------------------------------------------------------
Matrix for sYCC, Amendment 1 to IEC 61966-2-1
Y : 0.299 0.587 0.114 :R
Cb: -0.1687 -0.3312 0.5 :G
Cr: 0.5 -0.4187 -0.0812 :B
Inverse:
R: 1 -3.68213e-05 1.40199 :Y
G: 1.00003 -0.344125 -0.714128 :Cb - 2^(prec - 1)
B: 0.999823 1.77204 -8.04142e-06 :Cr - 2^(prec - 1)
-----------------------------------------------------------*/
static void sycc_to_rgb(int offset, int upb, int y, int cb, int cr,
int *out_r, int *out_g, int *out_b)
{
int r, g, b;
cb -= offset;
cr -= offset;
r = y + (int)(1.402 * (float)cr);
if (r < 0) {
r = 0;
} else if (r > upb) {
r = upb;
}
*out_r = r;
g = y - (int)(0.344 * (float)cb + 0.714 * (float)cr);
if (g < 0) {
g = 0;
} else if (g > upb) {
g = upb;
}
*out_g = g;
b = y + (int)(1.772 * (float)cb);
if (b < 0) {
b = 0;
} else if (b > upb) {
b = upb;
}
*out_b = b;
}
static void sycc444_to_rgb(opj_image_t *img)
{
int *d0, *d1, *d2, *r, *g, *b;
const int *y, *cb, *cr;
size_t maxw, maxh, max, i;
int offset, upb;
upb = (int)img->comps[0].prec;
offset = 1 << (upb - 1);
upb = (1 << upb) - 1;
maxw = (size_t)img->comps[0].w;
maxh = (size_t)img->comps[0].h;
max = maxw * maxh;
y = img->comps[0].data;
cb = img->comps[1].data;
cr = img->comps[2].data;
d0 = r = (int*)opj_image_data_alloc(sizeof(int) * max);
d1 = g = (int*)opj_image_data_alloc(sizeof(int) * max);
d2 = b = (int*)opj_image_data_alloc(sizeof(int) * max);
if (r == NULL || g == NULL || b == NULL) {
goto fails;
}
for (i = 0U; i < max; ++i) {
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y;
++cb;
++cr;
++r;
++g;
++b;
}
opj_image_data_free(img->comps[0].data);
img->comps[0].data = d0;
opj_image_data_free(img->comps[1].data);
img->comps[1].data = d1;
opj_image_data_free(img->comps[2].data);
img->comps[2].data = d2;
img->color_space = OPJ_CLRSPC_SRGB;
return;
fails:
opj_image_data_free(r);
opj_image_data_free(g);
opj_image_data_free(b);
}/* sycc444_to_rgb() */
static void sycc422_to_rgb(opj_image_t *img)
{
int *d0, *d1, *d2, *r, *g, *b;
const int *y, *cb, *cr;
size_t maxw, maxh, max, offx, loopmaxw;
int offset, upb;
size_t i;
upb = (int)img->comps[0].prec;
offset = 1 << (upb - 1);
upb = (1 << upb) - 1;
maxw = (size_t)img->comps[0].w;
maxh = (size_t)img->comps[0].h;
max = maxw * maxh;
y = img->comps[0].data;
cb = img->comps[1].data;
cr = img->comps[2].data;
d0 = r = (int*)opj_image_data_alloc(sizeof(int) * max);
d1 = g = (int*)opj_image_data_alloc(sizeof(int) * max);
d2 = b = (int*)opj_image_data_alloc(sizeof(int) * max);
if (r == NULL || g == NULL || b == NULL) {
goto fails;
}
/* if img->x0 is odd, then first column shall use Cb/Cr = 0 */
offx = img->x0 & 1U;
loopmaxw = maxw - offx;
for (i = 0U; i < maxh; ++i) {
size_t j;
if (offx > 0U) {
sycc_to_rgb(offset, upb, *y, 0, 0, r, g, b);
++y;
++r;
++g;
++b;
}
for (j = 0U; j < (loopmaxw & ~(size_t)1U); j += 2U) {
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y;
++r;
++g;
++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y;
++r;
++g;
++b;
++cb;
++cr;
}
if (j < loopmaxw) {
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y;
++r;
++g;
++b;
++cb;
++cr;
}
}
opj_image_data_free(img->comps[0].data);
img->comps[0].data = d0;
opj_image_data_free(img->comps[1].data);
img->comps[1].data = d1;
opj_image_data_free(img->comps[2].data);
img->comps[2].data = d2;
img->comps[1].w = img->comps[2].w = img->comps[0].w;
img->comps[1].h = img->comps[2].h = img->comps[0].h;
img->comps[1].dx = img->comps[2].dx = img->comps[0].dx;
img->comps[1].dy = img->comps[2].dy = img->comps[0].dy;
img->color_space = OPJ_CLRSPC_SRGB;
return;
fails:
opj_image_data_free(r);
opj_image_data_free(g);
opj_image_data_free(b);
}/* sycc422_to_rgb() */
static void sycc420_to_rgb(opj_image_t *img)
{
int *d0, *d1, *d2, *r, *g, *b, *nr, *ng, *nb;
const int *y, *cb, *cr, *ny;
size_t maxw, maxh, max, offx, loopmaxw, offy, loopmaxh;
int offset, upb;
size_t i;
upb = (int)img->comps[0].prec;
offset = 1 << (upb - 1);
upb = (1 << upb) - 1;
maxw = (size_t)img->comps[0].w;
maxh = (size_t)img->comps[0].h;
max = maxw * maxh;
y = img->comps[0].data;
cb = img->comps[1].data;
cr = img->comps[2].data;
d0 = r = (int*)opj_image_data_alloc(sizeof(int) * max);
d1 = g = (int*)opj_image_data_alloc(sizeof(int) * max);
d2 = b = (int*)opj_image_data_alloc(sizeof(int) * max);
if (r == NULL || g == NULL || b == NULL) {
goto fails;
}
/* if img->x0 is odd, then first column shall use Cb/Cr = 0 */
offx = img->x0 & 1U;
loopmaxw = maxw - offx;
/* if img->y0 is odd, then first line shall use Cb/Cr = 0 */
offy = img->y0 & 1U;
loopmaxh = maxh - offy;
if (offy > 0U) {
size_t j;
for (j = 0; j < maxw; ++j) {
sycc_to_rgb(offset, upb, *y, 0, 0, r, g, b);
++y;
++r;
++g;
++b;
}
}
for (i = 0U; i < (loopmaxh & ~(size_t)1U); i += 2U) {
size_t j;
ny = y + maxw;
nr = r + maxw;
ng = g + maxw;
nb = b + maxw;
if (offx > 0U) {
sycc_to_rgb(offset, upb, *y, 0, 0, r, g, b);
++y;
++r;
++g;
++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny;
++nr;
++ng;
++nb;
}
for (j = 0; j < (loopmaxw & ~(size_t)1U); j += 2U) {
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y;
++r;
++g;
++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y;
++r;
++g;
++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny;
++nr;
++ng;
++nb;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny;
++nr;
++ng;
++nb;
++cb;
++cr;
}
if (j < loopmaxw) {
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y;
++r;
++g;
++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny;
++nr;
++ng;
++nb;
++cb;
++cr;
}
y += maxw;
r += maxw;
g += maxw;
b += maxw;
}
if (i < loopmaxh) {
size_t j;
for (j = 0U; j < (maxw & ~(size_t)1U); j += 2U) {
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y;
++r;
++g;
++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y;
++r;
++g;
++b;
++cb;
++cr;
}
if (j < maxw) {
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
}
}
opj_image_data_free(img->comps[0].data);
img->comps[0].data = d0;
opj_image_data_free(img->comps[1].data);
img->comps[1].data = d1;
opj_image_data_free(img->comps[2].data);
img->comps[2].data = d2;
img->comps[1].w = img->comps[2].w = img->comps[0].w;
img->comps[1].h = img->comps[2].h = img->comps[0].h;
img->comps[1].dx = img->comps[2].dx = img->comps[0].dx;
img->comps[1].dy = img->comps[2].dy = img->comps[0].dy;
img->color_space = OPJ_CLRSPC_SRGB;
return;
fails:
opj_image_data_free(r);
opj_image_data_free(g);
opj_image_data_free(b);
}/* sycc420_to_rgb() */
void color_sycc_to_rgb(opj_image_t *img)
{
if (img->numcomps < 3) {
img->color_space = OPJ_CLRSPC_GRAY;
return;
}
if ((img->comps[0].dx == 1)
&& (img->comps[1].dx == 2)
&& (img->comps[2].dx == 2)
&& (img->comps[0].dy == 1)
&& (img->comps[1].dy == 2)
&& (img->comps[2].dy == 2)) { /* horizontal and vertical sub-sample */
sycc420_to_rgb(img);
} else if ((img->comps[0].dx == 1)
&& (img->comps[1].dx == 2)
&& (img->comps[2].dx == 2)
&& (img->comps[0].dy == 1)
&& (img->comps[1].dy == 1)
&& (img->comps[2].dy == 1)) { /* horizontal sub-sample only */
sycc422_to_rgb(img);
} else if ((img->comps[0].dx == 1)
&& (img->comps[1].dx == 1)
&& (img->comps[2].dx == 1)
&& (img->comps[0].dy == 1)
&& (img->comps[1].dy == 1)
&& (img->comps[2].dy == 1)) { /* no sub-sample */
sycc444_to_rgb(img);
} else {
fprintf(stderr, "%s:%d:color_sycc_to_rgb\n\tCAN NOT CONVERT\n", __FILE__,
__LINE__);
return;
}
}/* color_sycc_to_rgb() */
#if defined(OPJ_HAVE_LIBLCMS2) || defined(OPJ_HAVE_LIBLCMS1)
#ifdef OPJ_HAVE_LIBLCMS1
/* Bob Friesenhahn proposed:*/
#define cmsSigXYZData icSigXYZData
#define cmsSigLabData icSigLabData
#define cmsSigCmykData icSigCmykData
#define cmsSigYCbCrData icSigYCbCrData
#define cmsSigLuvData icSigLuvData
#define cmsSigGrayData icSigGrayData
#define cmsSigRgbData icSigRgbData
#define cmsUInt32Number DWORD
#define cmsColorSpaceSignature icColorSpaceSignature
#define cmsGetHeaderRenderingIntent cmsTakeRenderingIntent
#endif /* OPJ_HAVE_LIBLCMS1 */
/*#define DEBUG_PROFILE*/
void color_apply_icc_profile(opj_image_t *image)
{
cmsHPROFILE in_prof, out_prof;
cmsHTRANSFORM transform;
cmsColorSpaceSignature in_space, out_space;
cmsUInt32Number intent, in_type, out_type;
int *r, *g, *b;
size_t nr_samples, i, max, max_w, max_h;
int prec, ok = 0;
OPJ_COLOR_SPACE new_space;
in_prof = cmsOpenProfileFromMem(image->icc_profile_buf, image->icc_profile_len);
#ifdef DEBUG_PROFILE
FILE *icm = fopen("debug.icm", "wb");
fwrite(image->icc_profile_buf, 1, image->icc_profile_len, icm);
fclose(icm);
#endif
if (in_prof == NULL) {
return;
}
in_space = cmsGetPCS(in_prof);
out_space = cmsGetColorSpace(in_prof);
intent = cmsGetHeaderRenderingIntent(in_prof);
max_w = image->comps[0].w;
max_h = image->comps[0].h;
prec = (int)image->comps[0].prec;
if (out_space == cmsSigRgbData) { /* enumCS 16 */
unsigned int i, nr_comp = image->numcomps;
if (nr_comp > 4) {
nr_comp = 4;
}
for (i = 1; i < nr_comp; ++i) { /* AFL test */
if (image->comps[0].dx != image->comps[i].dx) {
break;
}
if (image->comps[0].dy != image->comps[i].dy) {
break;
}
if (image->comps[0].prec != image->comps[i].prec) {
break;
}
if (image->comps[0].sgnd != image->comps[i].sgnd) {
break;
}
}
if (i != nr_comp) {
cmsCloseProfile(in_prof);
return;
}
if (prec <= 8) {
in_type = TYPE_RGB_8;
out_type = TYPE_RGB_8;
} else {
in_type = TYPE_RGB_16;
out_type = TYPE_RGB_16;
}
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
} else if (out_space == cmsSigGrayData) { /* enumCS 17 */
in_type = TYPE_GRAY_8;
out_type = TYPE_RGB_8;
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
} else if (out_space == cmsSigYCbCrData) { /* enumCS 18 */
in_type = TYPE_YCbCr_16;
out_type = TYPE_RGB_16;
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
} else {
#ifdef DEBUG_PROFILE
fprintf(stderr, "%s:%d: color_apply_icc_profile\n\tICC Profile has unknown "
"output colorspace(%#x)(%c%c%c%c)\n\tICC Profile ignored.\n",
__FILE__, __LINE__, out_space,
(out_space >> 24) & 0xff, (out_space >> 16) & 0xff,
(out_space >> 8) & 0xff, out_space & 0xff);
#endif
cmsCloseProfile(in_prof);
return;
}
if (out_prof == NULL) {
cmsCloseProfile(in_prof);
return;
}
#ifdef DEBUG_PROFILE
fprintf(stderr,
"%s:%d:color_apply_icc_profile\n\tchannels(%d) prec(%d) w(%d) h(%d)"
"\n\tprofile: in(%p) out(%p)\n", __FILE__, __LINE__, image->numcomps, prec,
max_w, max_h, (void*)in_prof, (void*)out_prof);
fprintf(stderr, "\trender_intent (%u)\n\t"
"color_space: in(%#x)(%c%c%c%c) out:(%#x)(%c%c%c%c)\n\t"
" type: in(%u) out:(%u)\n",
intent,
in_space,
(in_space >> 24) & 0xff, (in_space >> 16) & 0xff,
(in_space >> 8) & 0xff, in_space & 0xff,
out_space,
(out_space >> 24) & 0xff, (out_space >> 16) & 0xff,
(out_space >> 8) & 0xff, out_space & 0xff,
in_type, out_type
);
#else
(void)prec;
(void)in_space;
#endif /* DEBUG_PROFILE */
transform = cmsCreateTransform(in_prof, in_type, out_prof, out_type, intent, 0);
#ifdef OPJ_HAVE_LIBLCMS2
/* Possible for: LCMS_VERSION >= 2000 :*/
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
if (transform == NULL) {
#ifdef DEBUG_PROFILE
fprintf(stderr, "%s:%d:color_apply_icc_profile\n\tcmsCreateTransform failed. "
"ICC Profile ignored.\n", __FILE__, __LINE__);
#endif
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
return;
}
if (image->numcomps > 2) { /* RGB, RGBA */
if (prec <= 8) {
unsigned char *inbuf, *outbuf, *in, *out;
max = max_w * max_h;
nr_samples = (size_t)(max * 3U * sizeof(unsigned char));
in = inbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
if (inbuf == NULL || outbuf == NULL) {
goto fails0;
}
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U; i < max; ++i) {
*in++ = (unsigned char) * r++;
*in++ = (unsigned char) * g++;
*in++ = (unsigned char) * b++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
ok = 1;
fails0:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
} else { /* prec > 8 */
unsigned short *inbuf, *outbuf, *in, *out;
max = max_w * max_h;
nr_samples = (size_t)(max * 3U * sizeof(unsigned short));
in = inbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
if (inbuf == NULL || outbuf == NULL) {
goto fails1;
}
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U ; i < max; ++i) {
*in++ = (unsigned short) * r++;
*in++ = (unsigned short) * g++;
*in++ = (unsigned short) * b++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
ok = 1;
fails1:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
}
} else { /* image->numcomps <= 2 : GRAY, GRAYA */
if (prec <= 8) {
unsigned char *in, *inbuf, *out, *outbuf;
opj_image_comp_t *new_comps;
max = max_w * max_h;
nr_samples = (size_t)(max * 3 * sizeof(unsigned char));
in = inbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
g = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
b = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
if (inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) {
goto fails2;
}
new_comps = (opj_image_comp_t*)realloc(image->comps,
(image->numcomps + 2) * sizeof(opj_image_comp_t));
if (new_comps == NULL) {
goto fails2;
}
image->comps = new_comps;
if (image->numcomps == 2) {
image->comps[3] = image->comps[1];
}
image->comps[1] = image->comps[0];
image->comps[2] = image->comps[0];
image->comps[1].data = g;
image->comps[2].data = b;
image->numcomps += 2;
r = image->comps[0].data;
for (i = 0U; i < max; ++i) {
*in++ = (unsigned char) * r++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
r = g = b = NULL;
ok = 1;
fails2:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
opj_image_data_free(g);
opj_image_data_free(b);
} else { /* prec > 8 */
unsigned short *in, *inbuf, *out, *outbuf;
opj_image_comp_t *new_comps;
max = max_w * max_h;
nr_samples = (size_t)(max * 3U * sizeof(unsigned short));
in = inbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
g = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
b = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
if (inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) {
goto fails3;
}
new_comps = (opj_image_comp_t*)realloc(image->comps,
(image->numcomps + 2) * sizeof(opj_image_comp_t));
if (new_comps == NULL) {
goto fails3;
}
image->comps = new_comps;
if (image->numcomps == 2) {
image->comps[3] = image->comps[1];
}
image->comps[1] = image->comps[0];
image->comps[2] = image->comps[0];
image->comps[1].data = g;
image->comps[2].data = b;
image->numcomps += 2;
r = image->comps[0].data;
for (i = 0U; i < max; ++i) {
*in++ = (unsigned short) * r++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
r = g = b = NULL;
ok = 1;
fails3:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
opj_image_data_free(g);
opj_image_data_free(b);
}
}/* if(image->numcomps > 2) */
cmsDeleteTransform(transform);
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
if (ok) {
image->color_space = new_space;
}
}/* color_apply_icc_profile() */
static int are_comps_same_dimensions(opj_image_t * image)
{
unsigned int i;
for (i = 1; i < image->numcomps; i++) {
if (image->comps[0].dx != image->comps[i].dx ||
image->comps[0].dy != image->comps[i].dy) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
void color_cielab_to_rgb(opj_image_t *image)
{
int *row;
int enumcs, numcomps;
OPJ_COLOR_SPACE new_space;
numcomps = (int)image->numcomps;
if (numcomps != 3) {
fprintf(stderr, "%s:%d:\n\tnumcomps %d not handled. Quitting.\n",
__FILE__, __LINE__, numcomps);
return;
}
if (!are_comps_same_dimensions(image)) {
fprintf(stderr,
"%s:%d:\n\tcomponents are not all of the same dimension. Quitting.\n",
__FILE__, __LINE__);
return;
}
row = (int*)image->icc_profile_buf;
enumcs = row[0];
if (enumcs == 14) { /* CIELab */
int *L, *a, *b, *red, *green, *blue;
int *src0, *src1, *src2, *dst0, *dst1, *dst2;
double rl, ol, ra, oa, rb, ob, prec0, prec1, prec2;
double minL, maxL, mina, maxa, minb, maxb;
unsigned int default_type;
unsigned int i, max;
cmsHPROFILE in, out;
cmsHTRANSFORM transform;
cmsUInt16Number RGB[3];
cmsCIELab Lab;
in = cmsCreateLab4Profile(NULL);
if (in == NULL) {
return;
}
out = cmsCreate_sRGBProfile();
if (out == NULL) {
cmsCloseProfile(in);
return;
}
transform = cmsCreateTransform(in, TYPE_Lab_DBL, out, TYPE_RGB_16,
INTENT_PERCEPTUAL, 0);
#ifdef OPJ_HAVE_LIBLCMS2
cmsCloseProfile(in);
cmsCloseProfile(out);
#endif
if (transform == NULL) {
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in);
cmsCloseProfile(out);
#endif
return;
}
new_space = OPJ_CLRSPC_SRGB;
prec0 = (double)image->comps[0].prec;
prec1 = (double)image->comps[1].prec;
prec2 = (double)image->comps[2].prec;
default_type = (unsigned int)row[1];
if (default_type == 0x44454600) { /* DEF : default */
rl = 100;
ra = 170;
rb = 200;
ol = 0;
oa = pow(2, prec1 - 1);
ob = pow(2, prec2 - 2) + pow(2, prec2 - 3);
} else {
rl = row[2];
ra = row[4];
rb = row[6];
ol = row[3];
oa = row[5];
ob = row[7];
}
L = src0 = image->comps[0].data;
a = src1 = image->comps[1].data;
b = src2 = image->comps[2].data;
max = image->comps[0].w * image->comps[0].h;
red = dst0 = (int*)opj_image_data_alloc(max * sizeof(int));
green = dst1 = (int*)opj_image_data_alloc(max * sizeof(int));
blue = dst2 = (int*)opj_image_data_alloc(max * sizeof(int));
if (red == NULL || green == NULL || blue == NULL) {
goto fails;
}
minL = -(rl * ol) / (pow(2, prec0) - 1);
maxL = minL + rl;
mina = -(ra * oa) / (pow(2, prec1) - 1);
maxa = mina + ra;
minb = -(rb * ob) / (pow(2, prec2) - 1);
maxb = minb + rb;
for (i = 0; i < max; ++i) {
Lab.L = minL + (double)(*L) * (maxL - minL) / (pow(2, prec0) - 1);
++L;
Lab.a = mina + (double)(*a) * (maxa - mina) / (pow(2, prec1) - 1);
++a;
Lab.b = minb + (double)(*b) * (maxb - minb) / (pow(2, prec2) - 1);
++b;
cmsDoTransform(transform, &Lab, RGB, 1);
*red++ = RGB[0];
*green++ = RGB[1];
*blue++ = RGB[2];
}
cmsDeleteTransform(transform);
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in);
cmsCloseProfile(out);
#endif
opj_image_data_free(src0);
image->comps[0].data = dst0;
opj_image_data_free(src1);
image->comps[1].data = dst1;
opj_image_data_free(src2);
image->comps[2].data = dst2;
image->color_space = new_space;
image->comps[0].prec = 16;
image->comps[1].prec = 16;
image->comps[2].prec = 16;
return;
fails:
cmsDeleteTransform(transform);
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in);
cmsCloseProfile(out);
#endif
if (red) {
opj_image_data_free(red);
}
if (green) {
opj_image_data_free(green);
}
if (blue) {
opj_image_data_free(blue);
}
return;
}
fprintf(stderr, "%s:%d:\n\tenumCS %d not handled. Ignoring.\n", __FILE__,
__LINE__, enumcs);
}/* color_cielab_to_rgb() */
#endif /* OPJ_HAVE_LIBLCMS2 || OPJ_HAVE_LIBLCMS1 */
void color_cmyk_to_rgb(opj_image_t *image)
{
float C, M, Y, K;
float sC, sM, sY, sK;
unsigned int w, h, max, i;
w = image->comps[0].w;
h = image->comps[0].h;
if (
(image->numcomps < 4)
|| (image->comps[0].dx != image->comps[1].dx) ||
(image->comps[0].dx != image->comps[2].dx) ||
(image->comps[0].dx != image->comps[3].dx)
|| (image->comps[0].dy != image->comps[1].dy) ||
(image->comps[0].dy != image->comps[2].dy) ||
(image->comps[0].dy != image->comps[3].dy)
) {
fprintf(stderr, "%s:%d:color_cmyk_to_rgb\n\tCAN NOT CONVERT\n", __FILE__,
__LINE__);
return;
}
max = w * h;
sC = 1.0F / (float)((1 << image->comps[0].prec) - 1);
sM = 1.0F / (float)((1 << image->comps[1].prec) - 1);
sY = 1.0F / (float)((1 << image->comps[2].prec) - 1);
sK = 1.0F / (float)((1 << image->comps[3].prec) - 1);
for (i = 0; i < max; ++i) {
/* CMYK values from 0 to 1 */
C = (float)(image->comps[0].data[i]) * sC;
M = (float)(image->comps[1].data[i]) * sM;
Y = (float)(image->comps[2].data[i]) * sY;
K = (float)(image->comps[3].data[i]) * sK;
/* Invert all CMYK values */
C = 1.0F - C;
M = 1.0F - M;
Y = 1.0F - Y;
K = 1.0F - K;
/* CMYK -> RGB : RGB results from 0 to 255 */
image->comps[0].data[i] = (int)(255.0F * C * K); /* R */
image->comps[1].data[i] = (int)(255.0F * M * K); /* G */
image->comps[2].data[i] = (int)(255.0F * Y * K); /* B */
}
opj_image_data_free(image->comps[3].data);
image->comps[3].data = NULL;
image->comps[0].prec = 8;
image->comps[1].prec = 8;
image->comps[2].prec = 8;
image->numcomps -= 1;
image->color_space = OPJ_CLRSPC_SRGB;
for (i = 3; i < image->numcomps; ++i) {
memcpy(&(image->comps[i]), &(image->comps[i + 1]), sizeof(image->comps[i]));
}
}/* color_cmyk_to_rgb() */
/*
* This code has been adopted from sjpx_openjpeg.c of ghostscript
*/
void color_esycc_to_rgb(opj_image_t *image)
{
int y, cb, cr, sign1, sign2, val;
unsigned int w, h, max, i;
int flip_value = (1 << (image->comps[0].prec - 1));
int max_value = (1 << image->comps[0].prec) - 1;
if (
(image->numcomps < 3)
|| (image->comps[0].dx != image->comps[1].dx) ||
(image->comps[0].dx != image->comps[2].dx)
|| (image->comps[0].dy != image->comps[1].dy) ||
(image->comps[0].dy != image->comps[2].dy)
) {
fprintf(stderr, "%s:%d:color_esycc_to_rgb\n\tCAN NOT CONVERT\n", __FILE__,
__LINE__);
return;
}
w = image->comps[0].w;
h = image->comps[0].h;
sign1 = (int)image->comps[1].sgnd;
sign2 = (int)image->comps[2].sgnd;
max = w * h;
for (i = 0; i < max; ++i) {
y = image->comps[0].data[i];
cb = image->comps[1].data[i];
cr = image->comps[2].data[i];
if (!sign1) {
cb -= flip_value;
}
if (!sign2) {
cr -= flip_value;
}
val = (int)
((float)y - (float)0.0000368 * (float)cb
+ (float)1.40199 * (float)cr + (float)0.5);
if (val > max_value) {
val = max_value;
} else if (val < 0) {
val = 0;
}
image->comps[0].data[i] = val;
val = (int)
((float)1.0003 * (float)y - (float)0.344125 * (float)cb
- (float)0.7141128 * (float)cr + (float)0.5);
if (val > max_value) {
val = max_value;
} else if (val < 0) {
val = 0;
}
image->comps[1].data[i] = val;
val = (int)
((float)0.999823 * (float)y + (float)1.77204 * (float)cb
- (float)0.000008 * (float)cr + (float)0.5);
if (val > max_value) {
val = max_value;
} else if (val < 0) {
val = 0;
}
image->comps[2].data[i] = val;
}
image->color_space = OPJ_CLRSPC_SRGB;
}/* color_esycc_to_rgb() */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_550_0 |
crossvul-cpp_data_good_2986_0 | /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
* Copyright (c) 2016 Facebook
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/bpf.h>
#include <linux/bpf_verifier.h>
#include <linux/filter.h>
#include <net/netlink.h>
#include <linux/file.h>
#include <linux/vmalloc.h>
#include <linux/stringify.h>
#include "disasm.h"
static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
#define BPF_PROG_TYPE(_id, _name) \
[_id] = & _name ## _verifier_ops,
#define BPF_MAP_TYPE(_id, _ops)
#include <linux/bpf_types.h>
#undef BPF_PROG_TYPE
#undef BPF_MAP_TYPE
};
/* bpf_check() is a static code analyzer that walks eBPF program
* instruction by instruction and updates register/stack state.
* All paths of conditional branches are analyzed until 'bpf_exit' insn.
*
* The first pass is depth-first-search to check that the program is a DAG.
* It rejects the following programs:
* - larger than BPF_MAXINSNS insns
* - if loop is present (detected via back-edge)
* - unreachable insns exist (shouldn't be a forest. program = one function)
* - out of bounds or malformed jumps
* The second pass is all possible path descent from the 1st insn.
* Since it's analyzing all pathes through the program, the length of the
* analysis is limited to 64k insn, which may be hit even if total number of
* insn is less then 4K, but there are too many branches that change stack/regs.
* Number of 'branches to be analyzed' is limited to 1k
*
* On entry to each instruction, each register has a type, and the instruction
* changes the types of the registers depending on instruction semantics.
* If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
* copied to R1.
*
* All registers are 64-bit.
* R0 - return register
* R1-R5 argument passing registers
* R6-R9 callee saved registers
* R10 - frame pointer read-only
*
* At the start of BPF program the register R1 contains a pointer to bpf_context
* and has type PTR_TO_CTX.
*
* Verifier tracks arithmetic operations on pointers in case:
* BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
* BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
* 1st insn copies R10 (which has FRAME_PTR) type into R1
* and 2nd arithmetic instruction is pattern matched to recognize
* that it wants to construct a pointer to some element within stack.
* So after 2nd insn, the register R1 has type PTR_TO_STACK
* (and -20 constant is saved for further stack bounds checking).
* Meaning that this reg is a pointer to stack plus known immediate constant.
*
* Most of the time the registers have SCALAR_VALUE type, which
* means the register has some value, but it's not a valid pointer.
* (like pointer plus pointer becomes SCALAR_VALUE type)
*
* When verifier sees load or store instructions the type of base register
* can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer
* types recognized by check_mem_access() function.
*
* PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
* and the range of [ptr, ptr + map's value_size) is accessible.
*
* registers used to pass values to function calls are checked against
* function argument constraints.
*
* ARG_PTR_TO_MAP_KEY is one of such argument constraints.
* It means that the register type passed to this function must be
* PTR_TO_STACK and it will be used inside the function as
* 'pointer to map element key'
*
* For example the argument constraints for bpf_map_lookup_elem():
* .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
* .arg1_type = ARG_CONST_MAP_PTR,
* .arg2_type = ARG_PTR_TO_MAP_KEY,
*
* ret_type says that this function returns 'pointer to map elem value or null'
* function expects 1st argument to be a const pointer to 'struct bpf_map' and
* 2nd argument should be a pointer to stack, which will be used inside
* the helper function as a pointer to map element key.
*
* On the kernel side the helper function looks like:
* u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
* {
* struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
* void *key = (void *) (unsigned long) r2;
* void *value;
*
* here kernel can access 'key' and 'map' pointers safely, knowing that
* [key, key + map->key_size) bytes are valid and were initialized on
* the stack of eBPF program.
* }
*
* Corresponding eBPF program may look like:
* BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
* BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
* BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
* BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
* here verifier looks at prototype of map_lookup_elem() and sees:
* .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
* Now verifier knows that this map has key of R1->map_ptr->key_size bytes
*
* Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
* Now verifier checks that [R2, R2 + map's key_size) are within stack limits
* and were initialized prior to this call.
* If it's ok, then verifier allows this BPF_CALL insn and looks at
* .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
* R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
* returns ether pointer to map value or NULL.
*
* When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
* insn, the register holding that pointer in the true branch changes state to
* PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
* branch. See check_cond_jmp_op().
*
* After the call R0 is set to return type of the function and registers R1-R5
* are set to NOT_INIT to indicate that they are no longer readable.
*/
/* verifier_state + insn_idx are pushed to stack when branch is encountered */
struct bpf_verifier_stack_elem {
/* verifer state is 'st'
* before processing instruction 'insn_idx'
* and after processing instruction 'prev_insn_idx'
*/
struct bpf_verifier_state st;
int insn_idx;
int prev_insn_idx;
struct bpf_verifier_stack_elem *next;
};
#define BPF_COMPLEXITY_LIMIT_INSNS 131072
#define BPF_COMPLEXITY_LIMIT_STACK 1024
#define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA)
struct bpf_call_arg_meta {
struct bpf_map *map_ptr;
bool raw_mode;
bool pkt_access;
int regno;
int access_size;
};
static DEFINE_MUTEX(bpf_verifier_lock);
/* log_level controls verbosity level of eBPF verifier.
* verbose() is used to dump the verification trace to the log, so the user
* can figure out what's wrong with the program
*/
static __printf(2, 3) void verbose(struct bpf_verifier_env *env,
const char *fmt, ...)
{
struct bpf_verifer_log *log = &env->log;
unsigned int n;
va_list args;
if (!log->level || !log->ubuf || bpf_verifier_log_full(log))
return;
va_start(args, fmt);
n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
va_end(args);
WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
"verifier log line truncated - local buffer too short\n");
n = min(log->len_total - log->len_used - 1, n);
log->kbuf[n] = '\0';
if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
log->len_used += n;
else
log->ubuf = NULL;
}
static bool type_is_pkt_pointer(enum bpf_reg_type type)
{
return type == PTR_TO_PACKET ||
type == PTR_TO_PACKET_META;
}
/* string representation of 'enum bpf_reg_type' */
static const char * const reg_type_str[] = {
[NOT_INIT] = "?",
[SCALAR_VALUE] = "inv",
[PTR_TO_CTX] = "ctx",
[CONST_PTR_TO_MAP] = "map_ptr",
[PTR_TO_MAP_VALUE] = "map_value",
[PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
[PTR_TO_STACK] = "fp",
[PTR_TO_PACKET] = "pkt",
[PTR_TO_PACKET_META] = "pkt_meta",
[PTR_TO_PACKET_END] = "pkt_end",
};
static void print_verifier_state(struct bpf_verifier_env *env,
struct bpf_verifier_state *state)
{
struct bpf_reg_state *reg;
enum bpf_reg_type t;
int i;
for (i = 0; i < MAX_BPF_REG; i++) {
reg = &state->regs[i];
t = reg->type;
if (t == NOT_INIT)
continue;
verbose(env, " R%d=%s", i, reg_type_str[t]);
if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
tnum_is_const(reg->var_off)) {
/* reg->off should be 0 for SCALAR_VALUE */
verbose(env, "%lld", reg->var_off.value + reg->off);
} else {
verbose(env, "(id=%d", reg->id);
if (t != SCALAR_VALUE)
verbose(env, ",off=%d", reg->off);
if (type_is_pkt_pointer(t))
verbose(env, ",r=%d", reg->range);
else if (t == CONST_PTR_TO_MAP ||
t == PTR_TO_MAP_VALUE ||
t == PTR_TO_MAP_VALUE_OR_NULL)
verbose(env, ",ks=%d,vs=%d",
reg->map_ptr->key_size,
reg->map_ptr->value_size);
if (tnum_is_const(reg->var_off)) {
/* Typically an immediate SCALAR_VALUE, but
* could be a pointer whose offset is too big
* for reg->off
*/
verbose(env, ",imm=%llx", reg->var_off.value);
} else {
if (reg->smin_value != reg->umin_value &&
reg->smin_value != S64_MIN)
verbose(env, ",smin_value=%lld",
(long long)reg->smin_value);
if (reg->smax_value != reg->umax_value &&
reg->smax_value != S64_MAX)
verbose(env, ",smax_value=%lld",
(long long)reg->smax_value);
if (reg->umin_value != 0)
verbose(env, ",umin_value=%llu",
(unsigned long long)reg->umin_value);
if (reg->umax_value != U64_MAX)
verbose(env, ",umax_value=%llu",
(unsigned long long)reg->umax_value);
if (!tnum_is_unknown(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, ",var_off=%s", tn_buf);
}
}
verbose(env, ")");
}
}
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] == STACK_SPILL)
verbose(env, " fp%d=%s",
-MAX_BPF_STACK + i * BPF_REG_SIZE,
reg_type_str[state->stack[i].spilled_ptr.type]);
}
verbose(env, "\n");
}
static int copy_stack_state(struct bpf_verifier_state *dst,
const struct bpf_verifier_state *src)
{
if (!src->stack)
return 0;
if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) {
/* internal bug, make state invalid to reject the program */
memset(dst, 0, sizeof(*dst));
return -EFAULT;
}
memcpy(dst->stack, src->stack,
sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE));
return 0;
}
/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
* make it consume minimal amount of memory. check_stack_write() access from
* the program calls into realloc_verifier_state() to grow the stack size.
* Note there is a non-zero 'parent' pointer inside bpf_verifier_state
* which this function copies over. It points to previous bpf_verifier_state
* which is never reallocated
*/
static int realloc_verifier_state(struct bpf_verifier_state *state, int size,
bool copy_old)
{
u32 old_size = state->allocated_stack;
struct bpf_stack_state *new_stack;
int slot = size / BPF_REG_SIZE;
if (size <= old_size || !size) {
if (copy_old)
return 0;
state->allocated_stack = slot * BPF_REG_SIZE;
if (!size && old_size) {
kfree(state->stack);
state->stack = NULL;
}
return 0;
}
new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state),
GFP_KERNEL);
if (!new_stack)
return -ENOMEM;
if (copy_old) {
if (state->stack)
memcpy(new_stack, state->stack,
sizeof(*new_stack) * (old_size / BPF_REG_SIZE));
memset(new_stack + old_size / BPF_REG_SIZE, 0,
sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE);
}
state->allocated_stack = slot * BPF_REG_SIZE;
kfree(state->stack);
state->stack = new_stack;
return 0;
}
static void free_verifier_state(struct bpf_verifier_state *state,
bool free_self)
{
kfree(state->stack);
if (free_self)
kfree(state);
}
/* copy verifier state from src to dst growing dst stack space
* when necessary to accommodate larger src stack
*/
static int copy_verifier_state(struct bpf_verifier_state *dst,
const struct bpf_verifier_state *src)
{
int err;
err = realloc_verifier_state(dst, src->allocated_stack, false);
if (err)
return err;
memcpy(dst, src, offsetof(struct bpf_verifier_state, allocated_stack));
return copy_stack_state(dst, src);
}
static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
int *insn_idx)
{
struct bpf_verifier_state *cur = env->cur_state;
struct bpf_verifier_stack_elem *elem, *head = env->head;
int err;
if (env->head == NULL)
return -ENOENT;
if (cur) {
err = copy_verifier_state(cur, &head->st);
if (err)
return err;
}
if (insn_idx)
*insn_idx = head->insn_idx;
if (prev_insn_idx)
*prev_insn_idx = head->prev_insn_idx;
elem = head->next;
free_verifier_state(&head->st, false);
kfree(head);
env->head = elem;
env->stack_size--;
return 0;
}
static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
int insn_idx, int prev_insn_idx)
{
struct bpf_verifier_state *cur = env->cur_state;
struct bpf_verifier_stack_elem *elem;
int err;
elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
if (!elem)
goto err;
elem->insn_idx = insn_idx;
elem->prev_insn_idx = prev_insn_idx;
elem->next = env->head;
env->head = elem;
env->stack_size++;
err = copy_verifier_state(&elem->st, cur);
if (err)
goto err;
if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
verbose(env, "BPF program is too complex\n");
goto err;
}
return &elem->st;
err:
/* pop all elements and return */
while (!pop_stack(env, NULL, NULL));
return NULL;
}
#define CALLER_SAVED_REGS 6
static const int caller_saved[CALLER_SAVED_REGS] = {
BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
};
static void __mark_reg_not_init(struct bpf_reg_state *reg);
/* Mark the unknown part of a register (variable offset or scalar value) as
* known to have the value @imm.
*/
static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
{
reg->id = 0;
reg->var_off = tnum_const(imm);
reg->smin_value = (s64)imm;
reg->smax_value = (s64)imm;
reg->umin_value = imm;
reg->umax_value = imm;
}
/* Mark the 'variable offset' part of a register as zero. This should be
* used only on registers holding a pointer type.
*/
static void __mark_reg_known_zero(struct bpf_reg_state *reg)
{
__mark_reg_known(reg, 0);
}
static void mark_reg_known_zero(struct bpf_verifier_env *env,
struct bpf_reg_state *regs, u32 regno)
{
if (WARN_ON(regno >= MAX_BPF_REG)) {
verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
/* Something bad happened, let's kill all regs */
for (regno = 0; regno < MAX_BPF_REG; regno++)
__mark_reg_not_init(regs + regno);
return;
}
__mark_reg_known_zero(regs + regno);
}
static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
{
return type_is_pkt_pointer(reg->type);
}
static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
{
return reg_is_pkt_pointer(reg) ||
reg->type == PTR_TO_PACKET_END;
}
/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
enum bpf_reg_type which)
{
/* The register can already have a range from prior markings.
* This is fine as long as it hasn't been advanced from its
* origin.
*/
return reg->type == which &&
reg->id == 0 &&
reg->off == 0 &&
tnum_equals_const(reg->var_off, 0);
}
/* Attempts to improve min/max values based on var_off information */
static void __update_reg_bounds(struct bpf_reg_state *reg)
{
/* min signed is max(sign bit) | min(other bits) */
reg->smin_value = max_t(s64, reg->smin_value,
reg->var_off.value | (reg->var_off.mask & S64_MIN));
/* max signed is min(sign bit) | max(other bits) */
reg->smax_value = min_t(s64, reg->smax_value,
reg->var_off.value | (reg->var_off.mask & S64_MAX));
reg->umin_value = max(reg->umin_value, reg->var_off.value);
reg->umax_value = min(reg->umax_value,
reg->var_off.value | reg->var_off.mask);
}
/* Uses signed min/max values to inform unsigned, and vice-versa */
static void __reg_deduce_bounds(struct bpf_reg_state *reg)
{
/* Learn sign from signed bounds.
* If we cannot cross the sign boundary, then signed and unsigned bounds
* are the same, so combine. This works even in the negative case, e.g.
* -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
*/
if (reg->smin_value >= 0 || reg->smax_value < 0) {
reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
reg->umin_value);
reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
reg->umax_value);
return;
}
/* Learn sign from unsigned bounds. Signed bounds cross the sign
* boundary, so we must be careful.
*/
if ((s64)reg->umax_value >= 0) {
/* Positive. We can't learn anything from the smin, but smax
* is positive, hence safe.
*/
reg->smin_value = reg->umin_value;
reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
reg->umax_value);
} else if ((s64)reg->umin_value < 0) {
/* Negative. We can't learn anything from the smax, but smin
* is negative, hence safe.
*/
reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
reg->umin_value);
reg->smax_value = reg->umax_value;
}
}
/* Attempts to improve var_off based on unsigned min/max information */
static void __reg_bound_offset(struct bpf_reg_state *reg)
{
reg->var_off = tnum_intersect(reg->var_off,
tnum_range(reg->umin_value,
reg->umax_value));
}
/* Reset the min/max bounds of a register */
static void __mark_reg_unbounded(struct bpf_reg_state *reg)
{
reg->smin_value = S64_MIN;
reg->smax_value = S64_MAX;
reg->umin_value = 0;
reg->umax_value = U64_MAX;
}
/* Mark a register as having a completely unknown (scalar) value. */
static void __mark_reg_unknown(struct bpf_reg_state *reg)
{
reg->type = SCALAR_VALUE;
reg->id = 0;
reg->off = 0;
reg->var_off = tnum_unknown;
__mark_reg_unbounded(reg);
}
static void mark_reg_unknown(struct bpf_verifier_env *env,
struct bpf_reg_state *regs, u32 regno)
{
if (WARN_ON(regno >= MAX_BPF_REG)) {
verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
/* Something bad happened, let's kill all regs */
for (regno = 0; regno < MAX_BPF_REG; regno++)
__mark_reg_not_init(regs + regno);
return;
}
__mark_reg_unknown(regs + regno);
}
static void __mark_reg_not_init(struct bpf_reg_state *reg)
{
__mark_reg_unknown(reg);
reg->type = NOT_INIT;
}
static void mark_reg_not_init(struct bpf_verifier_env *env,
struct bpf_reg_state *regs, u32 regno)
{
if (WARN_ON(regno >= MAX_BPF_REG)) {
verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
/* Something bad happened, let's kill all regs */
for (regno = 0; regno < MAX_BPF_REG; regno++)
__mark_reg_not_init(regs + regno);
return;
}
__mark_reg_not_init(regs + regno);
}
static void init_reg_state(struct bpf_verifier_env *env,
struct bpf_reg_state *regs)
{
int i;
for (i = 0; i < MAX_BPF_REG; i++) {
mark_reg_not_init(env, regs, i);
regs[i].live = REG_LIVE_NONE;
}
/* frame pointer */
regs[BPF_REG_FP].type = PTR_TO_STACK;
mark_reg_known_zero(env, regs, BPF_REG_FP);
/* 1st arg to a function */
regs[BPF_REG_1].type = PTR_TO_CTX;
mark_reg_known_zero(env, regs, BPF_REG_1);
}
enum reg_arg_type {
SRC_OP, /* register is used as source operand */
DST_OP, /* register is used as destination operand */
DST_OP_NO_MARK /* same as above, check only, don't mark */
};
static void mark_reg_read(const struct bpf_verifier_state *state, u32 regno)
{
struct bpf_verifier_state *parent = state->parent;
if (regno == BPF_REG_FP)
/* We don't need to worry about FP liveness because it's read-only */
return;
while (parent) {
/* if read wasn't screened by an earlier write ... */
if (state->regs[regno].live & REG_LIVE_WRITTEN)
break;
/* ... then we depend on parent's value */
parent->regs[regno].live |= REG_LIVE_READ;
state = parent;
parent = state->parent;
}
}
static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
enum reg_arg_type t)
{
struct bpf_reg_state *regs = env->cur_state->regs;
if (regno >= MAX_BPF_REG) {
verbose(env, "R%d is invalid\n", regno);
return -EINVAL;
}
if (t == SRC_OP) {
/* check whether register used as source operand can be read */
if (regs[regno].type == NOT_INIT) {
verbose(env, "R%d !read_ok\n", regno);
return -EACCES;
}
mark_reg_read(env->cur_state, regno);
} else {
/* check whether register used as dest operand can be written to */
if (regno == BPF_REG_FP) {
verbose(env, "frame pointer is read only\n");
return -EACCES;
}
regs[regno].live |= REG_LIVE_WRITTEN;
if (t == DST_OP)
mark_reg_unknown(env, regs, regno);
}
return 0;
}
static bool is_spillable_regtype(enum bpf_reg_type type)
{
switch (type) {
case PTR_TO_MAP_VALUE:
case PTR_TO_MAP_VALUE_OR_NULL:
case PTR_TO_STACK:
case PTR_TO_CTX:
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
case PTR_TO_PACKET_END:
case CONST_PTR_TO_MAP:
return true;
default:
return false;
}
}
/* check_stack_read/write functions track spill/fill of registers,
* stack boundary and alignment are checked in check_mem_access()
*/
static int check_stack_write(struct bpf_verifier_env *env,
struct bpf_verifier_state *state, int off,
int size, int value_regno)
{
int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
err = realloc_verifier_state(state, round_up(slot + 1, BPF_REG_SIZE),
true);
if (err)
return err;
/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
* so it's aligned access and [off, off + size) are within stack limits
*/
if (!env->allow_ptr_leaks &&
state->stack[spi].slot_type[0] == STACK_SPILL &&
size != BPF_REG_SIZE) {
verbose(env, "attempt to corrupt spilled pointer on stack\n");
return -EACCES;
}
if (value_regno >= 0 &&
is_spillable_regtype(state->regs[value_regno].type)) {
/* register containing pointer is being spilled into stack */
if (size != BPF_REG_SIZE) {
verbose(env, "invalid size of register spill\n");
return -EACCES;
}
/* save register state */
state->stack[spi].spilled_ptr = state->regs[value_regno];
state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
for (i = 0; i < BPF_REG_SIZE; i++)
state->stack[spi].slot_type[i] = STACK_SPILL;
} else {
/* regular write of data into stack */
state->stack[spi].spilled_ptr = (struct bpf_reg_state) {};
for (i = 0; i < size; i++)
state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
STACK_MISC;
}
return 0;
}
static void mark_stack_slot_read(const struct bpf_verifier_state *state, int slot)
{
struct bpf_verifier_state *parent = state->parent;
while (parent) {
/* if read wasn't screened by an earlier write ... */
if (state->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN)
break;
/* ... then we depend on parent's value */
parent->stack[slot].spilled_ptr.live |= REG_LIVE_READ;
state = parent;
parent = state->parent;
}
}
static int check_stack_read(struct bpf_verifier_env *env,
struct bpf_verifier_state *state, int off, int size,
int value_regno)
{
int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
u8 *stype;
if (state->allocated_stack <= slot) {
verbose(env, "invalid read from stack off %d+0 size %d\n",
off, size);
return -EACCES;
}
stype = state->stack[spi].slot_type;
if (stype[0] == STACK_SPILL) {
if (size != BPF_REG_SIZE) {
verbose(env, "invalid size of register spill\n");
return -EACCES;
}
for (i = 1; i < BPF_REG_SIZE; i++) {
if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
verbose(env, "corrupted spill memory\n");
return -EACCES;
}
}
if (value_regno >= 0) {
/* restore register state from stack */
state->regs[value_regno] = state->stack[spi].spilled_ptr;
mark_stack_slot_read(state, spi);
}
return 0;
} else {
for (i = 0; i < size; i++) {
if (stype[(slot - i) % BPF_REG_SIZE] != STACK_MISC) {
verbose(env, "invalid read from stack off %d+%d size %d\n",
off, i, size);
return -EACCES;
}
}
if (value_regno >= 0)
/* have read misc data from the stack */
mark_reg_unknown(env, state->regs, value_regno);
return 0;
}
}
/* check read/write into map element returned by bpf_map_lookup_elem() */
static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
int size, bool zero_size_allowed)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_map *map = regs[regno].map_ptr;
if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
off + size > map->value_size) {
verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
map->value_size, off, size);
return -EACCES;
}
return 0;
}
/* check read/write into a map element with possible variable offset */
static int check_map_access(struct bpf_verifier_env *env, u32 regno,
int off, int size, bool zero_size_allowed)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_reg_state *reg = &state->regs[regno];
int err;
/* We may have adjusted the register to this map value, so we
* need to try adding each of min_value and max_value to off
* to make sure our theoretical access will be safe.
*/
if (env->log.level)
print_verifier_state(env, state);
/* The minimum value is only important with signed
* comparisons where we can't assume the floor of a
* value is 0. If we are using signed variables for our
* index'es we need to make sure that whatever we use
* will have a set floor within our range.
*/
if (reg->smin_value < 0) {
verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
regno);
return -EACCES;
}
err = __check_map_access(env, regno, reg->smin_value + off, size,
zero_size_allowed);
if (err) {
verbose(env, "R%d min value is outside of the array range\n",
regno);
return err;
}
/* If we haven't set a max value then we need to bail since we can't be
* sure we won't do bad things.
* If reg->umax_value + off could overflow, treat that as unbounded too.
*/
if (reg->umax_value >= BPF_MAX_VAR_OFF) {
verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
regno);
return -EACCES;
}
err = __check_map_access(env, regno, reg->umax_value + off, size,
zero_size_allowed);
if (err)
verbose(env, "R%d max value is outside of the array range\n",
regno);
return err;
}
#define MAX_PACKET_OFF 0xffff
static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
const struct bpf_call_arg_meta *meta,
enum bpf_access_type t)
{
switch (env->prog->type) {
case BPF_PROG_TYPE_LWT_IN:
case BPF_PROG_TYPE_LWT_OUT:
/* dst_input() and dst_output() can't write for now */
if (t == BPF_WRITE)
return false;
/* fallthrough */
case BPF_PROG_TYPE_SCHED_CLS:
case BPF_PROG_TYPE_SCHED_ACT:
case BPF_PROG_TYPE_XDP:
case BPF_PROG_TYPE_LWT_XMIT:
case BPF_PROG_TYPE_SK_SKB:
if (meta)
return meta->pkt_access;
env->seen_direct_write = true;
return true;
default:
return false;
}
}
static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
int off, int size, bool zero_size_allowed)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_reg_state *reg = ®s[regno];
if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
(u64)off + size > reg->range) {
verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
off, size, regno, reg->id, reg->off, reg->range);
return -EACCES;
}
return 0;
}
static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
int size, bool zero_size_allowed)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_reg_state *reg = ®s[regno];
int err;
/* We may have added a variable offset to the packet pointer; but any
* reg->range we have comes after that. We are only checking the fixed
* offset.
*/
/* We don't allow negative numbers, because we aren't tracking enough
* detail to prove they're safe.
*/
if (reg->smin_value < 0) {
verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
regno);
return -EACCES;
}
err = __check_packet_access(env, regno, off, size, zero_size_allowed);
if (err) {
verbose(env, "R%d offset is outside of the packet\n", regno);
return err;
}
return err;
}
/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
enum bpf_access_type t, enum bpf_reg_type *reg_type)
{
struct bpf_insn_access_aux info = {
.reg_type = *reg_type,
};
if (env->ops->is_valid_access &&
env->ops->is_valid_access(off, size, t, &info)) {
/* A non zero info.ctx_field_size indicates that this field is a
* candidate for later verifier transformation to load the whole
* field and then apply a mask when accessed with a narrower
* access than actual ctx access size. A zero info.ctx_field_size
* will only allow for whole field access and rejects any other
* type of narrower access.
*/
*reg_type = info.reg_type;
env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
/* remember the offset of last byte accessed in ctx */
if (env->prog->aux->max_ctx_offset < off + size)
env->prog->aux->max_ctx_offset = off + size;
return 0;
}
verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
return -EACCES;
}
static bool __is_pointer_value(bool allow_ptr_leaks,
const struct bpf_reg_state *reg)
{
if (allow_ptr_leaks)
return false;
return reg->type != SCALAR_VALUE;
}
static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
{
return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno);
}
static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
int off, int size, bool strict)
{
struct tnum reg_off;
int ip_align;
/* Byte size accesses are always allowed. */
if (!strict || size == 1)
return 0;
/* For platforms that do not have a Kconfig enabling
* CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
* NET_IP_ALIGN is universally set to '2'. And on platforms
* that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
* to this code only in strict mode where we want to emulate
* the NET_IP_ALIGN==2 checking. Therefore use an
* unconditional IP align value of '2'.
*/
ip_align = 2;
reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
if (!tnum_is_aligned(reg_off, size)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env,
"misaligned packet access off %d+%s+%d+%d size %d\n",
ip_align, tn_buf, reg->off, off, size);
return -EACCES;
}
return 0;
}
static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
const char *pointer_desc,
int off, int size, bool strict)
{
struct tnum reg_off;
/* Byte size accesses are always allowed. */
if (!strict || size == 1)
return 0;
reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
if (!tnum_is_aligned(reg_off, size)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
pointer_desc, tn_buf, reg->off, off, size);
return -EACCES;
}
return 0;
}
static int check_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
int off, int size)
{
bool strict = env->strict_alignment;
const char *pointer_desc = "";
switch (reg->type) {
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
/* Special case, because of NET_IP_ALIGN. Given metadata sits
* right in front, treat it the very same way.
*/
return check_pkt_ptr_alignment(env, reg, off, size, strict);
case PTR_TO_MAP_VALUE:
pointer_desc = "value ";
break;
case PTR_TO_CTX:
pointer_desc = "context ";
break;
case PTR_TO_STACK:
pointer_desc = "stack ";
/* The stack spill tracking logic in check_stack_write()
* and check_stack_read() relies on stack accesses being
* aligned.
*/
strict = true;
break;
default:
break;
}
return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
strict);
}
/* truncate register to smaller size (in bytes)
* must be called with size < BPF_REG_SIZE
*/
static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
{
u64 mask;
/* clear high bits in bit representation */
reg->var_off = tnum_cast(reg->var_off, size);
/* fix arithmetic bounds */
mask = ((u64)1 << (size * 8)) - 1;
if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
reg->umin_value &= mask;
reg->umax_value &= mask;
} else {
reg->umin_value = 0;
reg->umax_value = mask;
}
reg->smin_value = reg->umin_value;
reg->smax_value = reg->umax_value;
}
/* check whether memory at (regno + off) is accessible for t = (read | write)
* if t==write, value_regno is a register which value is stored into memory
* if t==read, value_regno is a register which will receive the value from memory
* if t==write && value_regno==-1, some unknown value is stored into memory
* if t==read && value_regno==-1, don't care what we read from memory
*/
static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, int off,
int bpf_size, enum bpf_access_type t,
int value_regno)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_reg_state *reg = regs + regno;
int size, err = 0;
size = bpf_size_to_bytes(bpf_size);
if (size < 0)
return size;
/* alignment checks will add in reg->off themselves */
err = check_ptr_alignment(env, reg, off, size);
if (err)
return err;
/* for access checks, reg->off is just part of off */
off += reg->off;
if (reg->type == PTR_TO_MAP_VALUE) {
if (t == BPF_WRITE && value_regno >= 0 &&
is_pointer_value(env, value_regno)) {
verbose(env, "R%d leaks addr into map\n", value_regno);
return -EACCES;
}
err = check_map_access(env, regno, off, size, false);
if (!err && t == BPF_READ && value_regno >= 0)
mark_reg_unknown(env, regs, value_regno);
} else if (reg->type == PTR_TO_CTX) {
enum bpf_reg_type reg_type = SCALAR_VALUE;
if (t == BPF_WRITE && value_regno >= 0 &&
is_pointer_value(env, value_regno)) {
verbose(env, "R%d leaks addr into ctx\n", value_regno);
return -EACCES;
}
/* ctx accesses must be at a fixed offset, so that we can
* determine what type of data were returned.
*/
if (reg->off) {
verbose(env,
"dereference of modified ctx ptr R%d off=%d+%d, ctx+const is allowed, ctx+const+const is not\n",
regno, reg->off, off - reg->off);
return -EACCES;
}
if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env,
"variable ctx access var_off=%s off=%d size=%d",
tn_buf, off, size);
return -EACCES;
}
err = check_ctx_access(env, insn_idx, off, size, t, ®_type);
if (!err && t == BPF_READ && value_regno >= 0) {
/* ctx access returns either a scalar, or a
* PTR_TO_PACKET[_META,_END]. In the latter
* case, we know the offset is zero.
*/
if (reg_type == SCALAR_VALUE)
mark_reg_unknown(env, regs, value_regno);
else
mark_reg_known_zero(env, regs,
value_regno);
regs[value_regno].id = 0;
regs[value_regno].off = 0;
regs[value_regno].range = 0;
regs[value_regno].type = reg_type;
}
} else if (reg->type == PTR_TO_STACK) {
/* stack accesses must be at a fixed offset, so that we can
* determine what type of data were returned.
* See check_stack_read().
*/
if (!tnum_is_const(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "variable stack access var_off=%s off=%d size=%d",
tn_buf, off, size);
return -EACCES;
}
off += reg->var_off.value;
if (off >= 0 || off < -MAX_BPF_STACK) {
verbose(env, "invalid stack off=%d size=%d\n", off,
size);
return -EACCES;
}
if (env->prog->aux->stack_depth < -off)
env->prog->aux->stack_depth = -off;
if (t == BPF_WRITE)
err = check_stack_write(env, state, off, size,
value_regno);
else
err = check_stack_read(env, state, off, size,
value_regno);
} else if (reg_is_pkt_pointer(reg)) {
if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
verbose(env, "cannot write into packet\n");
return -EACCES;
}
if (t == BPF_WRITE && value_regno >= 0 &&
is_pointer_value(env, value_regno)) {
verbose(env, "R%d leaks addr into packet\n",
value_regno);
return -EACCES;
}
err = check_packet_access(env, regno, off, size, false);
if (!err && t == BPF_READ && value_regno >= 0)
mark_reg_unknown(env, regs, value_regno);
} else {
verbose(env, "R%d invalid mem access '%s'\n", regno,
reg_type_str[reg->type]);
return -EACCES;
}
if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
regs[value_regno].type == SCALAR_VALUE) {
/* b/h/w load zero-extends, mark upper bits as known 0 */
coerce_reg_to_size(®s[value_regno], size);
}
return err;
}
static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
{
int err;
if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
insn->imm != 0) {
verbose(env, "BPF_XADD uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->src_reg)) {
verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
return -EACCES;
}
/* check whether atomic_add can read the memory */
err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_READ, -1);
if (err)
return err;
/* check whether atomic_add can write into the same memory */
return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE, -1);
}
/* Does this register contain a constant zero? */
static bool register_is_null(struct bpf_reg_state reg)
{
return reg.type == SCALAR_VALUE && tnum_equals_const(reg.var_off, 0);
}
/* when register 'regno' is passed into function that will read 'access_size'
* bytes from that pointer, make sure that it's within stack boundary
* and all elements of stack are initialized.
* Unlike most pointer bounds-checking functions, this one doesn't take an
* 'off' argument, so it has to add in reg->off itself.
*/
static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
int access_size, bool zero_size_allowed,
struct bpf_call_arg_meta *meta)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_reg_state *regs = state->regs;
int off, i, slot, spi;
if (regs[regno].type != PTR_TO_STACK) {
/* Allow zero-byte read from NULL, regardless of pointer type */
if (zero_size_allowed && access_size == 0 &&
register_is_null(regs[regno]))
return 0;
verbose(env, "R%d type=%s expected=%s\n", regno,
reg_type_str[regs[regno].type],
reg_type_str[PTR_TO_STACK]);
return -EACCES;
}
/* Only allow fixed-offset stack reads */
if (!tnum_is_const(regs[regno].var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), regs[regno].var_off);
verbose(env, "invalid variable stack read R%d var_off=%s\n",
regno, tn_buf);
return -EACCES;
}
off = regs[regno].off + regs[regno].var_off.value;
if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
regno, off, access_size);
return -EACCES;
}
if (env->prog->aux->stack_depth < -off)
env->prog->aux->stack_depth = -off;
if (meta && meta->raw_mode) {
meta->access_size = access_size;
meta->regno = regno;
return 0;
}
for (i = 0; i < access_size; i++) {
slot = -(off + i) - 1;
spi = slot / BPF_REG_SIZE;
if (state->allocated_stack <= slot ||
state->stack[spi].slot_type[slot % BPF_REG_SIZE] !=
STACK_MISC) {
verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
off, i, access_size);
return -EACCES;
}
}
return 0;
}
static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
int access_size, bool zero_size_allowed,
struct bpf_call_arg_meta *meta)
{
struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
switch (reg->type) {
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
return check_packet_access(env, regno, reg->off, access_size,
zero_size_allowed);
case PTR_TO_MAP_VALUE:
return check_map_access(env, regno, reg->off, access_size,
zero_size_allowed);
default: /* scalar_value|ptr_to_stack or invalid ptr */
return check_stack_boundary(env, regno, access_size,
zero_size_allowed, meta);
}
}
static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
enum bpf_arg_type arg_type,
struct bpf_call_arg_meta *meta)
{
struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
enum bpf_reg_type expected_type, type = reg->type;
int err = 0;
if (arg_type == ARG_DONTCARE)
return 0;
err = check_reg_arg(env, regno, SRC_OP);
if (err)
return err;
if (arg_type == ARG_ANYTHING) {
if (is_pointer_value(env, regno)) {
verbose(env, "R%d leaks addr into helper function\n",
regno);
return -EACCES;
}
return 0;
}
if (type_is_pkt_pointer(type) &&
!may_access_direct_pkt_data(env, meta, BPF_READ)) {
verbose(env, "helper access to the packet is not allowed\n");
return -EACCES;
}
if (arg_type == ARG_PTR_TO_MAP_KEY ||
arg_type == ARG_PTR_TO_MAP_VALUE) {
expected_type = PTR_TO_STACK;
if (!type_is_pkt_pointer(type) &&
type != expected_type)
goto err_type;
} else if (arg_type == ARG_CONST_SIZE ||
arg_type == ARG_CONST_SIZE_OR_ZERO) {
expected_type = SCALAR_VALUE;
if (type != expected_type)
goto err_type;
} else if (arg_type == ARG_CONST_MAP_PTR) {
expected_type = CONST_PTR_TO_MAP;
if (type != expected_type)
goto err_type;
} else if (arg_type == ARG_PTR_TO_CTX) {
expected_type = PTR_TO_CTX;
if (type != expected_type)
goto err_type;
} else if (arg_type == ARG_PTR_TO_MEM ||
arg_type == ARG_PTR_TO_MEM_OR_NULL ||
arg_type == ARG_PTR_TO_UNINIT_MEM) {
expected_type = PTR_TO_STACK;
/* One exception here. In case function allows for NULL to be
* passed in as argument, it's a SCALAR_VALUE type. Final test
* happens during stack boundary checking.
*/
if (register_is_null(*reg) &&
arg_type == ARG_PTR_TO_MEM_OR_NULL)
/* final test in check_stack_boundary() */;
else if (!type_is_pkt_pointer(type) &&
type != PTR_TO_MAP_VALUE &&
type != expected_type)
goto err_type;
meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
} else {
verbose(env, "unsupported arg_type %d\n", arg_type);
return -EFAULT;
}
if (arg_type == ARG_CONST_MAP_PTR) {
/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
meta->map_ptr = reg->map_ptr;
} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
/* bpf_map_xxx(..., map_ptr, ..., key) call:
* check that [key, key + map->key_size) are within
* stack limits and initialized
*/
if (!meta->map_ptr) {
/* in function declaration map_ptr must come before
* map_key, so that it's verified and known before
* we have to check map_key here. Otherwise it means
* that kernel subsystem misconfigured verifier
*/
verbose(env, "invalid map_ptr to access map->key\n");
return -EACCES;
}
if (type_is_pkt_pointer(type))
err = check_packet_access(env, regno, reg->off,
meta->map_ptr->key_size,
false);
else
err = check_stack_boundary(env, regno,
meta->map_ptr->key_size,
false, NULL);
} else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
/* bpf_map_xxx(..., map_ptr, ..., value) call:
* check [value, value + map->value_size) validity
*/
if (!meta->map_ptr) {
/* kernel subsystem misconfigured verifier */
verbose(env, "invalid map_ptr to access map->value\n");
return -EACCES;
}
if (type_is_pkt_pointer(type))
err = check_packet_access(env, regno, reg->off,
meta->map_ptr->value_size,
false);
else
err = check_stack_boundary(env, regno,
meta->map_ptr->value_size,
false, NULL);
} else if (arg_type == ARG_CONST_SIZE ||
arg_type == ARG_CONST_SIZE_OR_ZERO) {
bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
/* bpf_xxx(..., buf, len) call will access 'len' bytes
* from stack pointer 'buf'. Check it
* note: regno == len, regno - 1 == buf
*/
if (regno == 0) {
/* kernel subsystem misconfigured verifier */
verbose(env,
"ARG_CONST_SIZE cannot be first argument\n");
return -EACCES;
}
/* The register is SCALAR_VALUE; the access check
* happens using its boundaries.
*/
if (!tnum_is_const(reg->var_off))
/* For unprivileged variable accesses, disable raw
* mode so that the program is required to
* initialize all the memory that the helper could
* just partially fill up.
*/
meta = NULL;
if (reg->smin_value < 0) {
verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
regno);
return -EACCES;
}
if (reg->umin_value == 0) {
err = check_helper_mem_access(env, regno - 1, 0,
zero_size_allowed,
meta);
if (err)
return err;
}
if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
regno);
return -EACCES;
}
err = check_helper_mem_access(env, regno - 1,
reg->umax_value,
zero_size_allowed, meta);
}
return err;
err_type:
verbose(env, "R%d type=%s expected=%s\n", regno,
reg_type_str[type], reg_type_str[expected_type]);
return -EACCES;
}
static int check_map_func_compatibility(struct bpf_verifier_env *env,
struct bpf_map *map, int func_id)
{
if (!map)
return 0;
/* We need a two way check, first is from map perspective ... */
switch (map->map_type) {
case BPF_MAP_TYPE_PROG_ARRAY:
if (func_id != BPF_FUNC_tail_call)
goto error;
break;
case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
if (func_id != BPF_FUNC_perf_event_read &&
func_id != BPF_FUNC_perf_event_output &&
func_id != BPF_FUNC_perf_event_read_value)
goto error;
break;
case BPF_MAP_TYPE_STACK_TRACE:
if (func_id != BPF_FUNC_get_stackid)
goto error;
break;
case BPF_MAP_TYPE_CGROUP_ARRAY:
if (func_id != BPF_FUNC_skb_under_cgroup &&
func_id != BPF_FUNC_current_task_under_cgroup)
goto error;
break;
/* devmap returns a pointer to a live net_device ifindex that we cannot
* allow to be modified from bpf side. So do not allow lookup elements
* for now.
*/
case BPF_MAP_TYPE_DEVMAP:
if (func_id != BPF_FUNC_redirect_map)
goto error;
break;
/* Restrict bpf side of cpumap, open when use-cases appear */
case BPF_MAP_TYPE_CPUMAP:
if (func_id != BPF_FUNC_redirect_map)
goto error;
break;
case BPF_MAP_TYPE_ARRAY_OF_MAPS:
case BPF_MAP_TYPE_HASH_OF_MAPS:
if (func_id != BPF_FUNC_map_lookup_elem)
goto error;
break;
case BPF_MAP_TYPE_SOCKMAP:
if (func_id != BPF_FUNC_sk_redirect_map &&
func_id != BPF_FUNC_sock_map_update &&
func_id != BPF_FUNC_map_delete_elem)
goto error;
break;
default:
break;
}
/* ... and second from the function itself. */
switch (func_id) {
case BPF_FUNC_tail_call:
if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
goto error;
break;
case BPF_FUNC_perf_event_read:
case BPF_FUNC_perf_event_output:
case BPF_FUNC_perf_event_read_value:
if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
goto error;
break;
case BPF_FUNC_get_stackid:
if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
goto error;
break;
case BPF_FUNC_current_task_under_cgroup:
case BPF_FUNC_skb_under_cgroup:
if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
goto error;
break;
case BPF_FUNC_redirect_map:
if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
map->map_type != BPF_MAP_TYPE_CPUMAP)
goto error;
break;
case BPF_FUNC_sk_redirect_map:
if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
goto error;
break;
case BPF_FUNC_sock_map_update:
if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
goto error;
break;
default:
break;
}
return 0;
error:
verbose(env, "cannot pass map_type %d into func %s#%d\n",
map->map_type, func_id_name(func_id), func_id);
return -EINVAL;
}
static int check_raw_mode(const struct bpf_func_proto *fn)
{
int count = 0;
if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
count++;
return count > 1 ? -EINVAL : 0;
}
/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
* are now invalid, so turn them into unknown SCALAR_VALUE.
*/
static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_reg_state *regs = state->regs, *reg;
int i;
for (i = 0; i < MAX_BPF_REG; i++)
if (reg_is_pkt_pointer_any(®s[i]))
mark_reg_unknown(env, regs, i);
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
reg = &state->stack[i].spilled_ptr;
if (reg_is_pkt_pointer_any(reg))
__mark_reg_unknown(reg);
}
}
static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
{
const struct bpf_func_proto *fn = NULL;
struct bpf_reg_state *regs;
struct bpf_call_arg_meta meta;
bool changes_data;
int i, err;
/* find function prototype */
if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
func_id);
return -EINVAL;
}
if (env->ops->get_func_proto)
fn = env->ops->get_func_proto(func_id);
if (!fn) {
verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
func_id);
return -EINVAL;
}
/* eBPF programs must be GPL compatible to use GPL-ed functions */
if (!env->prog->gpl_compatible && fn->gpl_only) {
verbose(env, "cannot call GPL only function from proprietary program\n");
return -EINVAL;
}
/* With LD_ABS/IND some JITs save/restore skb from r1. */
changes_data = bpf_helper_changes_pkt_data(fn->func);
if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
func_id_name(func_id), func_id);
return -EINVAL;
}
memset(&meta, 0, sizeof(meta));
meta.pkt_access = fn->pkt_access;
/* We only support one arg being in raw mode at the moment, which
* is sufficient for the helper functions we have right now.
*/
err = check_raw_mode(fn);
if (err) {
verbose(env, "kernel subsystem misconfigured func %s#%d\n",
func_id_name(func_id), func_id);
return err;
}
/* check args */
err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
if (err)
return err;
/* Mark slots with STACK_MISC in case of raw mode, stack offset
* is inferred from register state.
*/
for (i = 0; i < meta.access_size; i++) {
err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, BPF_WRITE, -1);
if (err)
return err;
}
regs = cur_regs(env);
/* reset caller saved regs */
for (i = 0; i < CALLER_SAVED_REGS; i++) {
mark_reg_not_init(env, regs, caller_saved[i]);
check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
}
/* update return register (already marked as written above) */
if (fn->ret_type == RET_INTEGER) {
/* sets type to SCALAR_VALUE */
mark_reg_unknown(env, regs, BPF_REG_0);
} else if (fn->ret_type == RET_VOID) {
regs[BPF_REG_0].type = NOT_INIT;
} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
struct bpf_insn_aux_data *insn_aux;
regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
/* There is no offset yet applied, variable or fixed */
mark_reg_known_zero(env, regs, BPF_REG_0);
regs[BPF_REG_0].off = 0;
/* remember map_ptr, so that check_map_access()
* can check 'value_size' boundary of memory access
* to map element returned from bpf_map_lookup_elem()
*/
if (meta.map_ptr == NULL) {
verbose(env,
"kernel subsystem misconfigured verifier\n");
return -EINVAL;
}
regs[BPF_REG_0].map_ptr = meta.map_ptr;
regs[BPF_REG_0].id = ++env->id_gen;
insn_aux = &env->insn_aux_data[insn_idx];
if (!insn_aux->map_ptr)
insn_aux->map_ptr = meta.map_ptr;
else if (insn_aux->map_ptr != meta.map_ptr)
insn_aux->map_ptr = BPF_MAP_PTR_POISON;
} else {
verbose(env, "unknown return type %d of func %s#%d\n",
fn->ret_type, func_id_name(func_id), func_id);
return -EINVAL;
}
err = check_map_func_compatibility(env, meta.map_ptr, func_id);
if (err)
return err;
if (changes_data)
clear_all_pkt_pointers(env);
return 0;
}
static bool signed_add_overflows(s64 a, s64 b)
{
/* Do the add in u64, where overflow is well-defined */
s64 res = (s64)((u64)a + (u64)b);
if (b < 0)
return res > a;
return res < a;
}
static bool signed_sub_overflows(s64 a, s64 b)
{
/* Do the sub in u64, where overflow is well-defined */
s64 res = (s64)((u64)a - (u64)b);
if (b < 0)
return res < a;
return res > a;
}
/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
* Caller should also handle BPF_MOV case separately.
* If we return -EACCES, caller may want to try again treating pointer as a
* scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
*/
static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn,
const struct bpf_reg_state *ptr_reg,
const struct bpf_reg_state *off_reg)
{
struct bpf_reg_state *regs = cur_regs(env), *dst_reg;
bool known = tnum_is_const(off_reg->var_off);
s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
u8 opcode = BPF_OP(insn->code);
u32 dst = insn->dst_reg;
dst_reg = ®s[dst];
if (WARN_ON_ONCE(known && (smin_val != smax_val))) {
print_verifier_state(env, env->cur_state);
verbose(env,
"verifier internal error: known but bad sbounds\n");
return -EINVAL;
}
if (WARN_ON_ONCE(known && (umin_val != umax_val))) {
print_verifier_state(env, env->cur_state);
verbose(env,
"verifier internal error: known but bad ubounds\n");
return -EINVAL;
}
if (BPF_CLASS(insn->code) != BPF_ALU64) {
/* 32-bit ALU ops on pointers produce (meaningless) scalars */
if (!env->allow_ptr_leaks)
verbose(env,
"R%d 32-bit pointer arithmetic prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
dst);
return -EACCES;
}
if (ptr_reg->type == CONST_PTR_TO_MAP) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_PACKET_END) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
dst);
return -EACCES;
}
/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
* The id may be overwritten later if we create a new variable offset.
*/
dst_reg->type = ptr_reg->type;
dst_reg->id = ptr_reg->id;
switch (opcode) {
case BPF_ADD:
/* We can take a fixed offset as long as it doesn't overflow
* the s32 'off' field
*/
if (known && (ptr_reg->off + smin_val ==
(s64)(s32)(ptr_reg->off + smin_val))) {
/* pointer += K. Accumulate it into fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->off = ptr_reg->off + smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. Note that off_reg->off
* == 0, since it's a scalar.
* dst_reg gets the pointer type and since some positive
* integer value was added to the pointer, give it a new 'id'
* if it's a PTR_TO_PACKET.
* this creates a new 'base' pointer, off_reg (variable) gets
* added into the variable offset, and we copy the fixed offset
* from ptr_reg.
*/
if (signed_add_overflows(smin_ptr, smin_val) ||
signed_add_overflows(smax_ptr, smax_val)) {
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr + smin_val;
dst_reg->smax_value = smax_ptr + smax_val;
}
if (umin_ptr + umin_val < umin_ptr ||
umax_ptr + umax_val < umax_ptr) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value = umin_ptr + umin_val;
dst_reg->umax_value = umax_ptr + umax_val;
}
dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
dst_reg->range = 0;
}
break;
case BPF_SUB:
if (dst_reg == off_reg) {
/* scalar -= pointer. Creates an unknown scalar */
if (!env->allow_ptr_leaks)
verbose(env, "R%d tried to subtract pointer from scalar\n",
dst);
return -EACCES;
}
/* We don't allow subtraction from FP, because (according to
* test_verifier.c test "invalid fp arithmetic", JITs might not
* be able to deal with it.
*/
if (ptr_reg->type == PTR_TO_STACK) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d subtraction from stack pointer prohibited\n",
dst);
return -EACCES;
}
if (known && (ptr_reg->off - smin_val ==
(s64)(s32)(ptr_reg->off - smin_val))) {
/* pointer -= K. Subtract it from fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->id = ptr_reg->id;
dst_reg->off = ptr_reg->off - smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. If the subtrahend is known
* nonnegative, then any reg->range we had before is still good.
*/
if (signed_sub_overflows(smin_ptr, smax_val) ||
signed_sub_overflows(smax_ptr, smin_val)) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr - smax_val;
dst_reg->smax_value = smax_ptr - smin_val;
}
if (umin_ptr < 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 = umin_ptr - umax_val;
dst_reg->umax_value = umax_ptr - umin_val;
}
dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
if (smin_val < 0)
dst_reg->range = 0;
}
break;
case BPF_AND:
case BPF_OR:
case BPF_XOR:
/* bitwise ops on pointers are troublesome, prohibit for now.
* (However, in principle we could allow some cases, e.g.
* ptr &= ~3 which would reduce min_value by 3.)
*/
if (!env->allow_ptr_leaks)
verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
default:
/* other operators (e.g. MUL,LSH) produce non-pointer results */
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
}
__update_reg_bounds(dst_reg);
__reg_deduce_bounds(dst_reg);
__reg_bound_offset(dst_reg);
return 0;
}
/* WARNING: This function does calculations on 64-bit values, but the actual
* execution may occur on 32-bit values. Therefore, things like bitshifts
* need extra checks in the 32-bit case.
*/
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);
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;
}
if (src_known)
dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
else
dst_reg->var_off = tnum_lshift(tnum_unknown, 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;
if (src_known)
dst_reg->var_off = tnum_rshift(dst_reg->var_off,
umin_val);
else
dst_reg->var_off = tnum_rshift(tnum_unknown, 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;
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;
}
/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
* and var_off.
*/
static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env), *dst_reg, *src_reg;
struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
u8 opcode = BPF_OP(insn->code);
int rc;
dst_reg = ®s[insn->dst_reg];
src_reg = NULL;
if (dst_reg->type != SCALAR_VALUE)
ptr_reg = dst_reg;
if (BPF_SRC(insn->code) == BPF_X) {
src_reg = ®s[insn->src_reg];
if (src_reg->type != SCALAR_VALUE) {
if (dst_reg->type != SCALAR_VALUE) {
/* Combining two pointers by any ALU op yields
* an arbitrary scalar.
*/
if (!env->allow_ptr_leaks) {
verbose(env, "R%d pointer %s pointer prohibited\n",
insn->dst_reg,
bpf_alu_string[opcode >> 4]);
return -EACCES;
}
mark_reg_unknown(env, regs, insn->dst_reg);
return 0;
} else {
/* scalar += pointer
* This is legal, but we have to reverse our
* src/dest handling in computing the range
*/
rc = adjust_ptr_min_max_vals(env, insn,
src_reg, dst_reg);
if (rc == -EACCES && env->allow_ptr_leaks) {
/* scalar += unknown scalar */
__mark_reg_unknown(&off_reg);
return adjust_scalar_min_max_vals(
env, insn,
dst_reg, off_reg);
}
return rc;
}
} else if (ptr_reg) {
/* pointer += scalar */
rc = adjust_ptr_min_max_vals(env, insn,
dst_reg, src_reg);
if (rc == -EACCES && env->allow_ptr_leaks) {
/* unknown scalar += scalar */
__mark_reg_unknown(dst_reg);
return adjust_scalar_min_max_vals(
env, insn, dst_reg, *src_reg);
}
return rc;
}
} else {
/* Pretend the src is a reg with a known value, since we only
* need to be able to read from this state.
*/
off_reg.type = SCALAR_VALUE;
__mark_reg_known(&off_reg, insn->imm);
src_reg = &off_reg;
if (ptr_reg) { /* pointer += K */
rc = adjust_ptr_min_max_vals(env, insn,
ptr_reg, src_reg);
if (rc == -EACCES && env->allow_ptr_leaks) {
/* unknown scalar += K */
__mark_reg_unknown(dst_reg);
return adjust_scalar_min_max_vals(
env, insn, dst_reg, off_reg);
}
return rc;
}
}
/* Got here implies adding two SCALAR_VALUEs */
if (WARN_ON_ONCE(ptr_reg)) {
print_verifier_state(env, env->cur_state);
verbose(env, "verifier internal error: unexpected ptr_reg\n");
return -EINVAL;
}
if (WARN_ON(!src_reg)) {
print_verifier_state(env, env->cur_state);
verbose(env, "verifier internal error: no src_reg\n");
return -EINVAL;
}
return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
}
/* check validity of 32-bit and 64-bit arithmetic operations */
static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 opcode = BPF_OP(insn->code);
int err;
if (opcode == BPF_END || opcode == BPF_NEG) {
if (opcode == BPF_NEG) {
if (BPF_SRC(insn->code) != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->off != 0 || insn->imm != 0) {
verbose(env, "BPF_NEG uses reserved fields\n");
return -EINVAL;
}
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
(insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
BPF_CLASS(insn->code) == BPF_ALU64) {
verbose(env, "BPF_END uses reserved fields\n");
return -EINVAL;
}
}
/* check src operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->dst_reg)) {
verbose(env, "R%d pointer arithmetic prohibited\n",
insn->dst_reg);
return -EACCES;
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
} else if (opcode == BPF_MOV) {
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
if (BPF_SRC(insn->code) == BPF_X) {
if (BPF_CLASS(insn->code) == BPF_ALU64) {
/* case: R1 = R2
* copy register state to dest reg
*/
regs[insn->dst_reg] = regs[insn->src_reg];
regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
} else {
/* R1 = (u32) R2 */
if (is_pointer_value(env, insn->src_reg)) {
verbose(env,
"R%d partial copy of pointer\n",
insn->src_reg);
return -EACCES;
}
mark_reg_unknown(env, regs, insn->dst_reg);
coerce_reg_to_size(®s[insn->dst_reg], 4);
}
} else {
/* case: R = imm
* remember the value we stored into this reg
*/
regs[insn->dst_reg].type = SCALAR_VALUE;
if (BPF_CLASS(insn->code) == BPF_ALU64) {
__mark_reg_known(regs + insn->dst_reg,
insn->imm);
} else {
__mark_reg_known(regs + insn->dst_reg,
(u32)insn->imm);
}
}
} else if (opcode > BPF_END) {
verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
return -EINVAL;
} else { /* all other ALU ops: and, sub, xor, add, ... */
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
}
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
verbose(env, "div by zero\n");
return -EINVAL;
}
if ((opcode == BPF_LSH || opcode == BPF_RSH ||
opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
if (insn->imm < 0 || insn->imm >= size) {
verbose(env, "invalid shift %d\n", insn->imm);
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
return adjust_reg_min_max_vals(env, insn);
}
return 0;
}
static void find_good_pkt_pointers(struct bpf_verifier_state *state,
struct bpf_reg_state *dst_reg,
enum bpf_reg_type type,
bool range_right_open)
{
struct bpf_reg_state *regs = state->regs, *reg;
u16 new_range;
int i;
if (dst_reg->off < 0 ||
(dst_reg->off == 0 && range_right_open))
/* This doesn't give us any range */
return;
if (dst_reg->umax_value > MAX_PACKET_OFF ||
dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
/* Risk of overflow. For instance, ptr + (1<<63) may be less
* than pkt_end, but that's because it's also less than pkt.
*/
return;
new_range = dst_reg->off;
if (range_right_open)
new_range--;
/* Examples for register markings:
*
* pkt_data in dst register:
*
* r2 = r3;
* r2 += 8;
* if (r2 > pkt_end) goto <handle exception>
* <access okay>
*
* r2 = r3;
* r2 += 8;
* if (r2 < pkt_end) goto <access okay>
* <handle exception>
*
* Where:
* r2 == dst_reg, pkt_end == src_reg
* r2=pkt(id=n,off=8,r=0)
* r3=pkt(id=n,off=0,r=0)
*
* pkt_data in src register:
*
* r2 = r3;
* r2 += 8;
* if (pkt_end >= r2) goto <access okay>
* <handle exception>
*
* r2 = r3;
* r2 += 8;
* if (pkt_end <= r2) goto <handle exception>
* <access okay>
*
* Where:
* pkt_end == dst_reg, r2 == src_reg
* r2=pkt(id=n,off=8,r=0)
* r3=pkt(id=n,off=0,r=0)
*
* Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
* or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
* and [r3, r3 + 8-1) respectively is safe to access depending on
* the check.
*/
/* If our ids match, then we must have the same max_value. And we
* don't care about the other reg's fixed offset, since if it's too big
* the range won't allow anything.
* dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
*/
for (i = 0; i < MAX_BPF_REG; i++)
if (regs[i].type == type && regs[i].id == dst_reg->id)
/* keep the maximum range already checked */
regs[i].range = max(regs[i].range, new_range);
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
reg = &state->stack[i].spilled_ptr;
if (reg->type == type && reg->id == dst_reg->id)
reg->range = max(reg->range, new_range);
}
}
/* Adjusts the register min/max values in the case that the dst_reg is the
* variable register that we are working on, and src_reg is a constant or we're
* simply doing a BPF_K check.
* In JEQ/JNE cases we also adjust the var_off values.
*/
static void reg_set_min_max(struct bpf_reg_state *true_reg,
struct bpf_reg_state *false_reg, u64 val,
u8 opcode)
{
/* If the dst_reg is a pointer, we can't learn anything about its
* variable offset from the compare (unless src_reg were a pointer into
* the same object, but we don't bother with that.
* Since false_reg and true_reg have the same type by construction, we
* only need to check one of them for pointerness.
*/
if (__is_pointer_value(false, false_reg))
return;
switch (opcode) {
case BPF_JEQ:
/* If this is false then we know nothing Jon Snow, but if it is
* true then we know for sure.
*/
__mark_reg_known(true_reg, val);
break;
case BPF_JNE:
/* If this is true we know nothing Jon Snow, but if it is false
* we know the value for sure;
*/
__mark_reg_known(false_reg, val);
break;
case BPF_JGT:
false_reg->umax_value = min(false_reg->umax_value, val);
true_reg->umin_value = max(true_reg->umin_value, val + 1);
break;
case BPF_JSGT:
false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
break;
case BPF_JLT:
false_reg->umin_value = max(false_reg->umin_value, val);
true_reg->umax_value = min(true_reg->umax_value, val - 1);
break;
case BPF_JSLT:
false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
break;
case BPF_JGE:
false_reg->umax_value = min(false_reg->umax_value, val - 1);
true_reg->umin_value = max(true_reg->umin_value, val);
break;
case BPF_JSGE:
false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
break;
case BPF_JLE:
false_reg->umin_value = max(false_reg->umin_value, val + 1);
true_reg->umax_value = min(true_reg->umax_value, val);
break;
case BPF_JSLE:
false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
break;
default:
break;
}
__reg_deduce_bounds(false_reg);
__reg_deduce_bounds(true_reg);
/* We might have learned some bits from the bounds. */
__reg_bound_offset(false_reg);
__reg_bound_offset(true_reg);
/* Intersecting with the old var_off might have improved our bounds
* slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
* then new var_off is (0; 0x7f...fc) which improves our umax.
*/
__update_reg_bounds(false_reg);
__update_reg_bounds(true_reg);
}
/* Same as above, but for the case that dst_reg holds a constant and src_reg is
* the variable reg.
*/
static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
struct bpf_reg_state *false_reg, u64 val,
u8 opcode)
{
if (__is_pointer_value(false, false_reg))
return;
switch (opcode) {
case BPF_JEQ:
/* If this is false then we know nothing Jon Snow, but if it is
* true then we know for sure.
*/
__mark_reg_known(true_reg, val);
break;
case BPF_JNE:
/* If this is true we know nothing Jon Snow, but if it is false
* we know the value for sure;
*/
__mark_reg_known(false_reg, val);
break;
case BPF_JGT:
true_reg->umax_value = min(true_reg->umax_value, val - 1);
false_reg->umin_value = max(false_reg->umin_value, val);
break;
case BPF_JSGT:
true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
break;
case BPF_JLT:
true_reg->umin_value = max(true_reg->umin_value, val + 1);
false_reg->umax_value = min(false_reg->umax_value, val);
break;
case BPF_JSLT:
true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
break;
case BPF_JGE:
true_reg->umax_value = min(true_reg->umax_value, val);
false_reg->umin_value = max(false_reg->umin_value, val + 1);
break;
case BPF_JSGE:
true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
break;
case BPF_JLE:
true_reg->umin_value = max(true_reg->umin_value, val);
false_reg->umax_value = min(false_reg->umax_value, val - 1);
break;
case BPF_JSLE:
true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
break;
default:
break;
}
__reg_deduce_bounds(false_reg);
__reg_deduce_bounds(true_reg);
/* We might have learned some bits from the bounds. */
__reg_bound_offset(false_reg);
__reg_bound_offset(true_reg);
/* Intersecting with the old var_off might have improved our bounds
* slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
* then new var_off is (0; 0x7f...fc) which improves our umax.
*/
__update_reg_bounds(false_reg);
__update_reg_bounds(true_reg);
}
/* Regs are known to be equal, so intersect their min/max/var_off */
static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
struct bpf_reg_state *dst_reg)
{
src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
dst_reg->umin_value);
src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
dst_reg->umax_value);
src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
dst_reg->smin_value);
src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
dst_reg->smax_value);
src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
dst_reg->var_off);
/* We might have learned new bounds from the var_off. */
__update_reg_bounds(src_reg);
__update_reg_bounds(dst_reg);
/* We might have learned something about the sign bit. */
__reg_deduce_bounds(src_reg);
__reg_deduce_bounds(dst_reg);
/* We might have learned some bits from the bounds. */
__reg_bound_offset(src_reg);
__reg_bound_offset(dst_reg);
/* Intersecting with the old var_off might have improved our bounds
* slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
* then new var_off is (0; 0x7f...fc) which improves our umax.
*/
__update_reg_bounds(src_reg);
__update_reg_bounds(dst_reg);
}
static void reg_combine_min_max(struct bpf_reg_state *true_src,
struct bpf_reg_state *true_dst,
struct bpf_reg_state *false_src,
struct bpf_reg_state *false_dst,
u8 opcode)
{
switch (opcode) {
case BPF_JEQ:
__reg_combine_min_max(true_src, true_dst);
break;
case BPF_JNE:
__reg_combine_min_max(false_src, false_dst);
break;
}
}
static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
bool is_null)
{
struct bpf_reg_state *reg = ®s[regno];
if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
/* Old offset (both fixed and variable parts) should
* have been known-zero, because we don't allow pointer
* arithmetic on pointers that might be NULL.
*/
if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
!tnum_equals_const(reg->var_off, 0) ||
reg->off)) {
__mark_reg_known_zero(reg);
reg->off = 0;
}
if (is_null) {
reg->type = SCALAR_VALUE;
} else if (reg->map_ptr->inner_map_meta) {
reg->type = CONST_PTR_TO_MAP;
reg->map_ptr = reg->map_ptr->inner_map_meta;
} else {
reg->type = PTR_TO_MAP_VALUE;
}
/* We don't need id from this point onwards anymore, thus we
* should better reset it, so that state pruning has chances
* to take effect.
*/
reg->id = 0;
}
}
/* The logic is similar to find_good_pkt_pointers(), both could eventually
* be folded together at some point.
*/
static void mark_map_regs(struct bpf_verifier_state *state, u32 regno,
bool is_null)
{
struct bpf_reg_state *regs = state->regs;
u32 id = regs[regno].id;
int i;
for (i = 0; i < MAX_BPF_REG; i++)
mark_map_reg(regs, i, id, is_null);
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
}
}
static bool try_match_pkt_pointers(const struct bpf_insn *insn,
struct bpf_reg_state *dst_reg,
struct bpf_reg_state *src_reg,
struct bpf_verifier_state *this_branch,
struct bpf_verifier_state *other_branch)
{
if (BPF_SRC(insn->code) != BPF_X)
return false;
switch (BPF_OP(insn->code)) {
case BPF_JGT:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
find_good_pkt_pointers(this_branch, dst_reg,
dst_reg->type, false);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end > pkt_data', pkt_data > pkt_meta' */
find_good_pkt_pointers(other_branch, src_reg,
src_reg->type, true);
} else {
return false;
}
break;
case BPF_JLT:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
find_good_pkt_pointers(other_branch, dst_reg,
dst_reg->type, true);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end < pkt_data', pkt_data > pkt_meta' */
find_good_pkt_pointers(this_branch, src_reg,
src_reg->type, false);
} else {
return false;
}
break;
case BPF_JGE:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
find_good_pkt_pointers(this_branch, dst_reg,
dst_reg->type, true);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
find_good_pkt_pointers(other_branch, src_reg,
src_reg->type, false);
} else {
return false;
}
break;
case BPF_JLE:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
find_good_pkt_pointers(other_branch, dst_reg,
dst_reg->type, false);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
find_good_pkt_pointers(this_branch, src_reg,
src_reg->type, true);
} else {
return false;
}
break;
default:
return false;
}
return true;
}
static int check_cond_jmp_op(struct bpf_verifier_env *env,
struct bpf_insn *insn, int *insn_idx)
{
struct bpf_verifier_state *other_branch, *this_branch = env->cur_state;
struct bpf_reg_state *regs = this_branch->regs, *dst_reg;
u8 opcode = BPF_OP(insn->code);
int err;
if (opcode > BPF_JSLE) {
verbose(env, "invalid BPF_JMP opcode %x\n", opcode);
return -EINVAL;
}
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0) {
verbose(env, "BPF_JMP uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->src_reg)) {
verbose(env, "R%d pointer comparison prohibited\n",
insn->src_reg);
return -EACCES;
}
} else {
if (insn->src_reg != BPF_REG_0) {
verbose(env, "BPF_JMP uses reserved fields\n");
return -EINVAL;
}
}
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
dst_reg = ®s[insn->dst_reg];
/* detect if R == 0 where R was initialized to zero earlier */
if (BPF_SRC(insn->code) == BPF_K &&
(opcode == BPF_JEQ || opcode == BPF_JNE) &&
dst_reg->type == SCALAR_VALUE &&
tnum_equals_const(dst_reg->var_off, insn->imm)) {
if (opcode == BPF_JEQ) {
/* if (imm == imm) goto pc+off;
* only follow the goto, ignore fall-through
*/
*insn_idx += insn->off;
return 0;
} else {
/* if (imm != imm) goto pc+off;
* only follow fall-through branch, since
* that's where the program will go
*/
return 0;
}
}
other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
if (!other_branch)
return -EFAULT;
/* detect if we are comparing against a constant value so we can adjust
* our min/max values for our dst register.
* this is only legit if both are scalars (or pointers to the same
* object, I suppose, but we don't support that right now), because
* otherwise the different base pointers mean the offsets aren't
* comparable.
*/
if (BPF_SRC(insn->code) == BPF_X) {
if (dst_reg->type == SCALAR_VALUE &&
regs[insn->src_reg].type == SCALAR_VALUE) {
if (tnum_is_const(regs[insn->src_reg].var_off))
reg_set_min_max(&other_branch->regs[insn->dst_reg],
dst_reg, regs[insn->src_reg].var_off.value,
opcode);
else if (tnum_is_const(dst_reg->var_off))
reg_set_min_max_inv(&other_branch->regs[insn->src_reg],
®s[insn->src_reg],
dst_reg->var_off.value, opcode);
else if (opcode == BPF_JEQ || opcode == BPF_JNE)
/* Comparing for equality, we can combine knowledge */
reg_combine_min_max(&other_branch->regs[insn->src_reg],
&other_branch->regs[insn->dst_reg],
®s[insn->src_reg],
®s[insn->dst_reg], opcode);
}
} else if (dst_reg->type == SCALAR_VALUE) {
reg_set_min_max(&other_branch->regs[insn->dst_reg],
dst_reg, insn->imm, opcode);
}
/* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
if (BPF_SRC(insn->code) == BPF_K &&
insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
/* Mark all identical map registers in each branch as either
* safe or unknown depending R == 0 or R != 0 conditional.
*/
mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
} else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
this_branch, other_branch) &&
is_pointer_value(env, insn->dst_reg)) {
verbose(env, "R%d pointer comparison prohibited\n",
insn->dst_reg);
return -EACCES;
}
if (env->log.level)
print_verifier_state(env, this_branch);
return 0;
}
/* return the map pointer stored inside BPF_LD_IMM64 instruction */
static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
{
u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
return (struct bpf_map *) (unsigned long) imm64;
}
/* verify BPF_LD_IMM64 instruction */
static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
int err;
if (BPF_SIZE(insn->code) != BPF_DW) {
verbose(env, "invalid BPF_LD_IMM insn\n");
return -EINVAL;
}
if (insn->off != 0) {
verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
return -EINVAL;
}
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
if (insn->src_reg == 0) {
u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
regs[insn->dst_reg].type = SCALAR_VALUE;
__mark_reg_known(®s[insn->dst_reg], imm);
return 0;
}
/* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
return 0;
}
static bool may_access_skb(enum bpf_prog_type type)
{
switch (type) {
case BPF_PROG_TYPE_SOCKET_FILTER:
case BPF_PROG_TYPE_SCHED_CLS:
case BPF_PROG_TYPE_SCHED_ACT:
return true;
default:
return false;
}
}
/* verify safety of LD_ABS|LD_IND instructions:
* - they can only appear in the programs where ctx == skb
* - since they are wrappers of function calls, they scratch R1-R5 registers,
* preserve R6-R9, and store return value into R0
*
* Implicit input:
* ctx == skb == R6 == CTX
*
* Explicit input:
* SRC == any register
* IMM == 32-bit immediate
*
* Output:
* R0 - 8/16/32-bit skb data converted to cpu endianness
*/
static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 mode = BPF_MODE(insn->code);
int i, err;
if (!may_access_skb(env->prog->type)) {
verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
return -EINVAL;
}
if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
BPF_SIZE(insn->code) == BPF_DW ||
(mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
return -EINVAL;
}
/* check whether implicit source operand (register R6) is readable */
err = check_reg_arg(env, BPF_REG_6, SRC_OP);
if (err)
return err;
if (regs[BPF_REG_6].type != PTR_TO_CTX) {
verbose(env,
"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
return -EINVAL;
}
if (mode == BPF_IND) {
/* check explicit source operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
}
/* reset caller saved regs to unreadable */
for (i = 0; i < CALLER_SAVED_REGS; i++) {
mark_reg_not_init(env, regs, caller_saved[i]);
check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
}
/* mark destination R0 register as readable, since it contains
* the value fetched from the packet.
* Already marked as written above.
*/
mark_reg_unknown(env, regs, BPF_REG_0);
return 0;
}
static int check_return_code(struct bpf_verifier_env *env)
{
struct bpf_reg_state *reg;
struct tnum range = tnum_range(0, 1);
switch (env->prog->type) {
case BPF_PROG_TYPE_CGROUP_SKB:
case BPF_PROG_TYPE_CGROUP_SOCK:
case BPF_PROG_TYPE_SOCK_OPS:
case BPF_PROG_TYPE_CGROUP_DEVICE:
break;
default:
return 0;
}
reg = cur_regs(env) + BPF_REG_0;
if (reg->type != SCALAR_VALUE) {
verbose(env, "At program exit the register R0 is not a known value (%s)\n",
reg_type_str[reg->type]);
return -EINVAL;
}
if (!tnum_in(range, reg->var_off)) {
verbose(env, "At program exit the register R0 ");
if (!tnum_is_unknown(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "has value %s", tn_buf);
} else {
verbose(env, "has unknown scalar value");
}
verbose(env, " should have been 0 or 1\n");
return -EINVAL;
}
return 0;
}
/* non-recursive DFS pseudo code
* 1 procedure DFS-iterative(G,v):
* 2 label v as discovered
* 3 let S be a stack
* 4 S.push(v)
* 5 while S is not empty
* 6 t <- S.pop()
* 7 if t is what we're looking for:
* 8 return t
* 9 for all edges e in G.adjacentEdges(t) do
* 10 if edge e is already labelled
* 11 continue with the next edge
* 12 w <- G.adjacentVertex(t,e)
* 13 if vertex w is not discovered and not explored
* 14 label e as tree-edge
* 15 label w as discovered
* 16 S.push(w)
* 17 continue at 5
* 18 else if vertex w is discovered
* 19 label e as back-edge
* 20 else
* 21 // vertex w is explored
* 22 label e as forward- or cross-edge
* 23 label t as explored
* 24 S.pop()
*
* convention:
* 0x10 - discovered
* 0x11 - discovered and fall-through edge labelled
* 0x12 - discovered and fall-through and branch edges labelled
* 0x20 - explored
*/
enum {
DISCOVERED = 0x10,
EXPLORED = 0x20,
FALLTHROUGH = 1,
BRANCH = 2,
};
#define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
static int *insn_stack; /* stack of insns to process */
static int cur_stack; /* current stack index */
static int *insn_state;
/* t, w, e - match pseudo-code above:
* t - index of current instruction
* w - next instruction
* e - edge
*/
static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
{
if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
return 0;
if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
return 0;
if (w < 0 || w >= env->prog->len) {
verbose(env, "jump out of range from insn %d to %d\n", t, w);
return -EINVAL;
}
if (e == BRANCH)
/* mark branch target for state pruning */
env->explored_states[w] = STATE_LIST_MARK;
if (insn_state[w] == 0) {
/* tree-edge */
insn_state[t] = DISCOVERED | e;
insn_state[w] = DISCOVERED;
if (cur_stack >= env->prog->len)
return -E2BIG;
insn_stack[cur_stack++] = w;
return 1;
} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
verbose(env, "back-edge from insn %d to %d\n", t, w);
return -EINVAL;
} else if (insn_state[w] == EXPLORED) {
/* forward- or cross-edge */
insn_state[t] = DISCOVERED | e;
} else {
verbose(env, "insn state internal bug\n");
return -EFAULT;
}
return 0;
}
/* non-recursive depth-first-search to detect loops in BPF program
* loop == back-edge in directed graph
*/
static int check_cfg(struct bpf_verifier_env *env)
{
struct bpf_insn *insns = env->prog->insnsi;
int insn_cnt = env->prog->len;
int ret = 0;
int i, t;
insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
if (!insn_state)
return -ENOMEM;
insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
if (!insn_stack) {
kfree(insn_state);
return -ENOMEM;
}
insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
insn_stack[0] = 0; /* 0 is the first instruction */
cur_stack = 1;
peek_stack:
if (cur_stack == 0)
goto check_state;
t = insn_stack[cur_stack - 1];
if (BPF_CLASS(insns[t].code) == BPF_JMP) {
u8 opcode = BPF_OP(insns[t].code);
if (opcode == BPF_EXIT) {
goto mark_explored;
} else if (opcode == BPF_CALL) {
ret = push_insn(t, t + 1, FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
if (t + 1 < insn_cnt)
env->explored_states[t + 1] = STATE_LIST_MARK;
} else if (opcode == BPF_JA) {
if (BPF_SRC(insns[t].code) != BPF_K) {
ret = -EINVAL;
goto err_free;
}
/* unconditional jump with single edge */
ret = push_insn(t, t + insns[t].off + 1,
FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
/* tell verifier to check for equivalent states
* after every call and jump
*/
if (t + 1 < insn_cnt)
env->explored_states[t + 1] = STATE_LIST_MARK;
} else {
/* conditional jump with two edges */
env->explored_states[t] = STATE_LIST_MARK;
ret = push_insn(t, t + 1, FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
}
} else {
/* all other non-branch instructions with single
* fall-through edge
*/
ret = push_insn(t, t + 1, FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
}
mark_explored:
insn_state[t] = EXPLORED;
if (cur_stack-- <= 0) {
verbose(env, "pop stack internal bug\n");
ret = -EFAULT;
goto err_free;
}
goto peek_stack;
check_state:
for (i = 0; i < insn_cnt; i++) {
if (insn_state[i] != EXPLORED) {
verbose(env, "unreachable insn %d\n", i);
ret = -EINVAL;
goto err_free;
}
}
ret = 0; /* cfg looks good */
err_free:
kfree(insn_state);
kfree(insn_stack);
return ret;
}
/* check %cur's range satisfies %old's */
static bool range_within(struct bpf_reg_state *old,
struct bpf_reg_state *cur)
{
return old->umin_value <= cur->umin_value &&
old->umax_value >= cur->umax_value &&
old->smin_value <= cur->smin_value &&
old->smax_value >= cur->smax_value;
}
/* Maximum number of register states that can exist at once */
#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
struct idpair {
u32 old;
u32 cur;
};
/* If in the old state two registers had the same id, then they need to have
* the same id in the new state as well. But that id could be different from
* the old state, so we need to track the mapping from old to new ids.
* Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
* regs with old id 5 must also have new id 9 for the new state to be safe. But
* regs with a different old id could still have new id 9, we don't care about
* that.
* So we look through our idmap to see if this old id has been seen before. If
* so, we require the new id to match; otherwise, we add the id pair to the map.
*/
static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
{
unsigned int i;
for (i = 0; i < ID_MAP_SIZE; i++) {
if (!idmap[i].old) {
/* Reached an empty slot; haven't seen this id before */
idmap[i].old = old_id;
idmap[i].cur = cur_id;
return true;
}
if (idmap[i].old == old_id)
return idmap[i].cur == cur_id;
}
/* We ran out of idmap slots, which should be impossible */
WARN_ON_ONCE(1);
return false;
}
/* Returns true if (rold safe implies rcur safe) */
static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
struct idpair *idmap)
{
if (!(rold->live & REG_LIVE_READ))
/* explored state didn't use this */
return true;
if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0)
return true;
if (rold->type == NOT_INIT)
/* explored state can't have used this */
return true;
if (rcur->type == NOT_INIT)
return false;
switch (rold->type) {
case SCALAR_VALUE:
if (rcur->type == SCALAR_VALUE) {
/* new val must satisfy old val knowledge */
return range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
} else {
/* We're trying to use a pointer in place of a scalar.
* Even if the scalar was unbounded, this could lead to
* pointer leaks because scalars are allowed to leak
* while pointers are not. We could make this safe in
* special cases if root is calling us, but it's
* probably not worth the hassle.
*/
return false;
}
case PTR_TO_MAP_VALUE:
/* If the new min/max/var_off satisfy the old ones and
* everything else matches, we are OK.
* We don't care about the 'id' value, because nothing
* uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
*/
return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_MAP_VALUE_OR_NULL:
/* a PTR_TO_MAP_VALUE could be safe to use as a
* PTR_TO_MAP_VALUE_OR_NULL into the same map.
* However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
* checked, doing so could have affected others with the same
* id, and we can't check for that because we lost the id when
* we converted to a PTR_TO_MAP_VALUE.
*/
if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
return false;
if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
return false;
/* Check our ids match any regs they're supposed to */
return check_ids(rold->id, rcur->id, idmap);
case PTR_TO_PACKET_META:
case PTR_TO_PACKET:
if (rcur->type != rold->type)
return false;
/* We must have at least as much range as the old ptr
* did, so that any accesses which were safe before are
* still safe. This is true even if old range < old off,
* since someone could have accessed through (ptr - k), or
* even done ptr -= k in a register, to get a safe access.
*/
if (rold->range > rcur->range)
return false;
/* If the offsets don't match, we can't trust our alignment;
* nor can we be sure that we won't fall out of range.
*/
if (rold->off != rcur->off)
return false;
/* id relations must be preserved */
if (rold->id && !check_ids(rold->id, rcur->id, idmap))
return false;
/* new val must satisfy old val knowledge */
return range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_CTX:
case CONST_PTR_TO_MAP:
case PTR_TO_STACK:
case PTR_TO_PACKET_END:
/* Only valid matches are exact, which memcmp() above
* would have accepted
*/
default:
/* Don't know what's going on, just say it's not safe */
return false;
}
/* Shouldn't get here; if we do, say it's not safe */
WARN_ON_ONCE(1);
return false;
}
static bool stacksafe(struct bpf_verifier_state *old,
struct bpf_verifier_state *cur,
struct idpair *idmap)
{
int i, spi;
/* if explored stack has more populated slots than current stack
* such stacks are not equivalent
*/
if (old->allocated_stack > cur->allocated_stack)
return false;
/* walk slots of the explored stack and ignore any additional
* slots in the current stack, since explored(safe) state
* didn't use them
*/
for (i = 0; i < old->allocated_stack; i++) {
spi = i / BPF_REG_SIZE;
if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
continue;
if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
cur->stack[spi].slot_type[i % BPF_REG_SIZE])
/* Ex: old explored (safe) state has STACK_SPILL in
* this stack slot, but current has has STACK_MISC ->
* this verifier states are not equivalent,
* return false to continue verification of this path
*/
return false;
if (i % BPF_REG_SIZE)
continue;
if (old->stack[spi].slot_type[0] != STACK_SPILL)
continue;
if (!regsafe(&old->stack[spi].spilled_ptr,
&cur->stack[spi].spilled_ptr,
idmap))
/* when explored and current stack slot are both storing
* spilled registers, check that stored pointers types
* are the same as well.
* Ex: explored safe path could have stored
* (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
* but current path has stored:
* (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
* such verifier states are not equivalent.
* return false to continue verification of this path
*/
return false;
}
return true;
}
/* compare two verifier states
*
* all states stored in state_list are known to be valid, since
* verifier reached 'bpf_exit' instruction through them
*
* this function is called when verifier exploring different branches of
* execution popped from the state stack. If it sees an old state that has
* more strict register state and more strict stack state then this execution
* branch doesn't need to be explored further, since verifier already
* concluded that more strict state leads to valid finish.
*
* Therefore two states are equivalent if register state is more conservative
* and explored stack state is more conservative than the current one.
* Example:
* explored current
* (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
* (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
*
* In other words if current stack state (one being explored) has more
* valid slots than old one that already passed validation, it means
* the verifier can stop exploring and conclude that current state is valid too
*
* Similarly with registers. If explored state has register type as invalid
* whereas register type in current state is meaningful, it means that
* the current state will reach 'bpf_exit' instruction safely
*/
static bool states_equal(struct bpf_verifier_env *env,
struct bpf_verifier_state *old,
struct bpf_verifier_state *cur)
{
struct idpair *idmap;
bool ret = false;
int i;
idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
/* If we failed to allocate the idmap, just say it's not safe */
if (!idmap)
return false;
for (i = 0; i < MAX_BPF_REG; i++) {
if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
goto out_free;
}
if (!stacksafe(old, cur, idmap))
goto out_free;
ret = true;
out_free:
kfree(idmap);
return ret;
}
/* A write screens off any subsequent reads; but write marks come from the
* straight-line code between a state and its parent. When we arrive at a
* jump target (in the first iteration of the propagate_liveness() loop),
* we didn't arrive by the straight-line code, so read marks in state must
* propagate to parent regardless of state's write marks.
*/
static bool do_propagate_liveness(const struct bpf_verifier_state *state,
struct bpf_verifier_state *parent)
{
bool writes = parent == state->parent; /* Observe write marks */
bool touched = false; /* any changes made? */
int i;
if (!parent)
return touched;
/* Propagate read liveness of registers... */
BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
/* We don't need to worry about FP liveness because it's read-only */
for (i = 0; i < BPF_REG_FP; i++) {
if (parent->regs[i].live & REG_LIVE_READ)
continue;
if (writes && (state->regs[i].live & REG_LIVE_WRITTEN))
continue;
if (state->regs[i].live & REG_LIVE_READ) {
parent->regs[i].live |= REG_LIVE_READ;
touched = true;
}
}
/* ... and stack slots */
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
i < parent->allocated_stack / BPF_REG_SIZE; i++) {
if (parent->stack[i].slot_type[0] != STACK_SPILL)
continue;
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
continue;
if (writes &&
(state->stack[i].spilled_ptr.live & REG_LIVE_WRITTEN))
continue;
if (state->stack[i].spilled_ptr.live & REG_LIVE_READ) {
parent->stack[i].spilled_ptr.live |= REG_LIVE_READ;
touched = true;
}
}
return touched;
}
/* "parent" is "a state from which we reach the current state", but initially
* it is not the state->parent (i.e. "the state whose straight-line code leads
* to the current state"), instead it is the state that happened to arrive at
* a (prunable) equivalent of the current state. See comment above
* do_propagate_liveness() for consequences of this.
* This function is just a more efficient way of calling mark_reg_read() or
* mark_stack_slot_read() on each reg in "parent" that is read in "state",
* though it requires that parent != state->parent in the call arguments.
*/
static void propagate_liveness(const struct bpf_verifier_state *state,
struct bpf_verifier_state *parent)
{
while (do_propagate_liveness(state, parent)) {
/* Something changed, so we need to feed those changes onward */
state = parent;
parent = state->parent;
}
}
static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
{
struct bpf_verifier_state_list *new_sl;
struct bpf_verifier_state_list *sl;
struct bpf_verifier_state *cur = env->cur_state;
int i, err;
sl = env->explored_states[insn_idx];
if (!sl)
/* this 'insn_idx' instruction wasn't marked, so we will not
* be doing state search here
*/
return 0;
while (sl != STATE_LIST_MARK) {
if (states_equal(env, &sl->state, cur)) {
/* reached equivalent register/stack state,
* prune the search.
* Registers read by the continuation are read by us.
* If we have any write marks in env->cur_state, they
* will prevent corresponding reads in the continuation
* from reaching our parent (an explored_state). Our
* own state will get the read marks recorded, but
* they'll be immediately forgotten as we're pruning
* this state and will pop a new one.
*/
propagate_liveness(&sl->state, cur);
return 1;
}
sl = sl->next;
}
/* there were no equivalent states, remember current one.
* technically the current state is not proven to be safe yet,
* but it will either reach bpf_exit (which means it's safe) or
* it will be rejected. Since there are no loops, we won't be
* seeing this 'insn_idx' instruction again on the way to bpf_exit
*/
new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
if (!new_sl)
return -ENOMEM;
/* add new state to the head of linked list */
err = copy_verifier_state(&new_sl->state, cur);
if (err) {
free_verifier_state(&new_sl->state, false);
kfree(new_sl);
return err;
}
new_sl->next = env->explored_states[insn_idx];
env->explored_states[insn_idx] = new_sl;
/* connect new state to parentage chain */
cur->parent = &new_sl->state;
/* clear write marks in current state: the writes we did are not writes
* our child did, so they don't screen off its reads from us.
* (There are no read marks in current state, because reads always mark
* their parent and current state never has children yet. Only
* explored_states can get read marks.)
*/
for (i = 0; i < BPF_REG_FP; i++)
cur->regs[i].live = REG_LIVE_NONE;
for (i = 0; i < cur->allocated_stack / BPF_REG_SIZE; i++)
if (cur->stack[i].slot_type[0] == STACK_SPILL)
cur->stack[i].spilled_ptr.live = REG_LIVE_NONE;
return 0;
}
static int ext_analyzer_insn_hook(struct bpf_verifier_env *env,
int insn_idx, int prev_insn_idx)
{
if (env->dev_ops && env->dev_ops->insn_hook)
return env->dev_ops->insn_hook(env, insn_idx, prev_insn_idx);
return 0;
}
static int do_check(struct bpf_verifier_env *env)
{
struct bpf_verifier_state *state;
struct bpf_insn *insns = env->prog->insnsi;
struct bpf_reg_state *regs;
int insn_cnt = env->prog->len;
int insn_idx, prev_insn_idx = 0;
int insn_processed = 0;
bool do_print_state = false;
state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
if (!state)
return -ENOMEM;
env->cur_state = state;
init_reg_state(env, state->regs);
state->parent = NULL;
insn_idx = 0;
for (;;) {
struct bpf_insn *insn;
u8 class;
int err;
if (insn_idx >= insn_cnt) {
verbose(env, "invalid insn idx %d insn_cnt %d\n",
insn_idx, insn_cnt);
return -EFAULT;
}
insn = &insns[insn_idx];
class = BPF_CLASS(insn->code);
if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
verbose(env,
"BPF program is too large. Processed %d insn\n",
insn_processed);
return -E2BIG;
}
err = is_state_visited(env, insn_idx);
if (err < 0)
return err;
if (err == 1) {
/* found equivalent state, can prune the search */
if (env->log.level) {
if (do_print_state)
verbose(env, "\nfrom %d to %d: safe\n",
prev_insn_idx, insn_idx);
else
verbose(env, "%d: safe\n", insn_idx);
}
goto process_bpf_exit;
}
if (need_resched())
cond_resched();
if (env->log.level > 1 || (env->log.level && do_print_state)) {
if (env->log.level > 1)
verbose(env, "%d:", insn_idx);
else
verbose(env, "\nfrom %d to %d:",
prev_insn_idx, insn_idx);
print_verifier_state(env, state);
do_print_state = false;
}
if (env->log.level) {
verbose(env, "%d: ", insn_idx);
print_bpf_insn(verbose, env, insn,
env->allow_ptr_leaks);
}
err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);
if (err)
return err;
regs = cur_regs(env);
env->insn_aux_data[insn_idx].seen = true;
if (class == BPF_ALU || class == BPF_ALU64) {
err = check_alu_op(env, insn);
if (err)
return err;
} else if (class == BPF_LDX) {
enum bpf_reg_type *prev_src_type, src_reg_type;
/* check for reserved fields is already done */
/* check src operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
src_reg_type = regs[insn->src_reg].type;
/* check that memory (src_reg + off) is readable,
* the state of dst_reg will be updated by this func
*/
err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
BPF_SIZE(insn->code), BPF_READ,
insn->dst_reg);
if (err)
return err;
prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
if (*prev_src_type == NOT_INIT) {
/* saw a valid insn
* dst_reg = *(u32 *)(src_reg + off)
* save type to validate intersecting paths
*/
*prev_src_type = src_reg_type;
} else if (src_reg_type != *prev_src_type &&
(src_reg_type == PTR_TO_CTX ||
*prev_src_type == PTR_TO_CTX)) {
/* ABuser program is trying to use the same insn
* dst_reg = *(u32*) (src_reg + off)
* with different pointer types:
* src_reg == ctx in one branch and
* src_reg == stack|map in some other branch.
* Reject it.
*/
verbose(env, "same insn cannot be used with different pointers\n");
return -EINVAL;
}
} else if (class == BPF_STX) {
enum bpf_reg_type *prev_dst_type, dst_reg_type;
if (BPF_MODE(insn->code) == BPF_XADD) {
err = check_xadd(env, insn_idx, insn);
if (err)
return err;
insn_idx++;
continue;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
dst_reg_type = regs[insn->dst_reg].type;
/* check that memory (dst_reg + off) is writeable */
err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE,
insn->src_reg);
if (err)
return err;
prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
if (*prev_dst_type == NOT_INIT) {
*prev_dst_type = dst_reg_type;
} else if (dst_reg_type != *prev_dst_type &&
(dst_reg_type == PTR_TO_CTX ||
*prev_dst_type == PTR_TO_CTX)) {
verbose(env, "same insn cannot be used with different pointers\n");
return -EINVAL;
}
} else if (class == BPF_ST) {
if (BPF_MODE(insn->code) != BPF_MEM ||
insn->src_reg != BPF_REG_0) {
verbose(env, "BPF_ST uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
/* check that memory (dst_reg + off) is writeable */
err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE,
-1);
if (err)
return err;
} else if (class == BPF_JMP) {
u8 opcode = BPF_OP(insn->code);
if (opcode == BPF_CALL) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->off != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_CALL uses reserved fields\n");
return -EINVAL;
}
err = check_call(env, insn->imm, insn_idx);
if (err)
return err;
} else if (opcode == BPF_JA) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->imm != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_JA uses reserved fields\n");
return -EINVAL;
}
insn_idx += insn->off + 1;
continue;
} else if (opcode == BPF_EXIT) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->imm != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_EXIT uses reserved fields\n");
return -EINVAL;
}
/* eBPF calling convetion is such that R0 is used
* to return the value from eBPF program.
* Make sure that it's readable at this time
* of bpf_exit, which means that program wrote
* something into it earlier
*/
err = check_reg_arg(env, BPF_REG_0, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, BPF_REG_0)) {
verbose(env, "R0 leaks addr as return value\n");
return -EACCES;
}
err = check_return_code(env);
if (err)
return err;
process_bpf_exit:
err = pop_stack(env, &prev_insn_idx, &insn_idx);
if (err < 0) {
if (err != -ENOENT)
return err;
break;
} else {
do_print_state = true;
continue;
}
} else {
err = check_cond_jmp_op(env, insn, &insn_idx);
if (err)
return err;
}
} else if (class == BPF_LD) {
u8 mode = BPF_MODE(insn->code);
if (mode == BPF_ABS || mode == BPF_IND) {
err = check_ld_abs(env, insn);
if (err)
return err;
} else if (mode == BPF_IMM) {
err = check_ld_imm(env, insn);
if (err)
return err;
insn_idx++;
env->insn_aux_data[insn_idx].seen = true;
} else {
verbose(env, "invalid BPF_LD mode\n");
return -EINVAL;
}
} else {
verbose(env, "unknown insn class %d\n", class);
return -EINVAL;
}
insn_idx++;
}
verbose(env, "processed %d insns, stack depth %d\n", insn_processed,
env->prog->aux->stack_depth);
return 0;
}
static int check_map_prealloc(struct bpf_map *map)
{
return (map->map_type != BPF_MAP_TYPE_HASH &&
map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
!(map->map_flags & BPF_F_NO_PREALLOC);
}
static int check_map_prog_compatibility(struct bpf_verifier_env *env,
struct bpf_map *map,
struct bpf_prog *prog)
{
/* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
* preallocated hash maps, since doing memory allocation
* in overflow_handler can crash depending on where nmi got
* triggered.
*/
if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
if (!check_map_prealloc(map)) {
verbose(env, "perf_event programs can only use preallocated hash map\n");
return -EINVAL;
}
if (map->inner_map_meta &&
!check_map_prealloc(map->inner_map_meta)) {
verbose(env, "perf_event programs can only use preallocated inner hash map\n");
return -EINVAL;
}
}
return 0;
}
/* look for pseudo eBPF instructions that access map FDs and
* replace them with actual map pointers
*/
static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
{
struct bpf_insn *insn = env->prog->insnsi;
int insn_cnt = env->prog->len;
int i, j, err;
err = bpf_prog_calc_tag(env->prog);
if (err)
return err;
for (i = 0; i < insn_cnt; i++, insn++) {
if (BPF_CLASS(insn->code) == BPF_LDX &&
(BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
verbose(env, "BPF_LDX uses reserved fields\n");
return -EINVAL;
}
if (BPF_CLASS(insn->code) == BPF_STX &&
((BPF_MODE(insn->code) != BPF_MEM &&
BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
verbose(env, "BPF_STX uses reserved fields\n");
return -EINVAL;
}
if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
struct bpf_map *map;
struct fd f;
if (i == insn_cnt - 1 || insn[1].code != 0 ||
insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
insn[1].off != 0) {
verbose(env, "invalid bpf_ld_imm64 insn\n");
return -EINVAL;
}
if (insn->src_reg == 0)
/* valid generic load 64-bit imm */
goto next_insn;
if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
verbose(env,
"unrecognized bpf_ld_imm64 insn\n");
return -EINVAL;
}
f = fdget(insn->imm);
map = __bpf_map_get(f);
if (IS_ERR(map)) {
verbose(env, "fd %d is not pointing to valid bpf_map\n",
insn->imm);
return PTR_ERR(map);
}
err = check_map_prog_compatibility(env, map, env->prog);
if (err) {
fdput(f);
return err;
}
/* store map pointer inside BPF_LD_IMM64 instruction */
insn[0].imm = (u32) (unsigned long) map;
insn[1].imm = ((u64) (unsigned long) map) >> 32;
/* check whether we recorded this map already */
for (j = 0; j < env->used_map_cnt; j++)
if (env->used_maps[j] == map) {
fdput(f);
goto next_insn;
}
if (env->used_map_cnt >= MAX_USED_MAPS) {
fdput(f);
return -E2BIG;
}
/* hold the map. If the program is rejected by verifier,
* the map will be released by release_maps() or it
* will be used by the valid program until it's unloaded
* and all maps are released in free_bpf_prog_info()
*/
map = bpf_map_inc(map, false);
if (IS_ERR(map)) {
fdput(f);
return PTR_ERR(map);
}
env->used_maps[env->used_map_cnt++] = map;
fdput(f);
next_insn:
insn++;
i++;
}
}
/* now all pseudo BPF_LD_IMM64 instructions load valid
* 'struct bpf_map *' into a register instead of user map_fd.
* These pointers will be used later by verifier to validate map access.
*/
return 0;
}
/* drop refcnt of maps used by the rejected program */
static void release_maps(struct bpf_verifier_env *env)
{
int i;
for (i = 0; i < env->used_map_cnt; i++)
bpf_map_put(env->used_maps[i]);
}
/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
{
struct bpf_insn *insn = env->prog->insnsi;
int insn_cnt = env->prog->len;
int i;
for (i = 0; i < insn_cnt; i++, insn++)
if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
insn->src_reg = 0;
}
/* single env->prog->insni[off] instruction was replaced with the range
* insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
* [0, off) and [off, end) to new locations, so the patched range stays zero
*/
static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
u32 off, u32 cnt)
{
struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
int i;
if (cnt == 1)
return 0;
new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
if (!new_data)
return -ENOMEM;
memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
memcpy(new_data + off + cnt - 1, old_data + off,
sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
for (i = off; i < off + cnt - 1; i++)
new_data[i].seen = true;
env->insn_aux_data = new_data;
vfree(old_data);
return 0;
}
static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
const struct bpf_insn *patch, u32 len)
{
struct bpf_prog *new_prog;
new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
if (!new_prog)
return NULL;
if (adjust_insn_aux_data(env, new_prog->len, off, len))
return NULL;
return new_prog;
}
/* The verifier does more data flow analysis than llvm and will not explore
* branches that are dead at run time. Malicious programs can have dead code
* too. Therefore replace all dead at-run-time code with nops.
*/
static void sanitize_dead_code(struct bpf_verifier_env *env)
{
struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
struct bpf_insn nop = BPF_MOV64_REG(BPF_REG_0, BPF_REG_0);
struct bpf_insn *insn = env->prog->insnsi;
const int insn_cnt = env->prog->len;
int i;
for (i = 0; i < insn_cnt; i++) {
if (aux_data[i].seen)
continue;
memcpy(insn + i, &nop, sizeof(nop));
}
}
/* convert load instructions that access fields of 'struct __sk_buff'
* into sequence of instructions that access fields of 'struct sk_buff'
*/
static int convert_ctx_accesses(struct bpf_verifier_env *env)
{
const struct bpf_verifier_ops *ops = env->ops;
int i, cnt, size, ctx_field_size, delta = 0;
const int insn_cnt = env->prog->len;
struct bpf_insn insn_buf[16], *insn;
struct bpf_prog *new_prog;
enum bpf_access_type type;
bool is_narrower_load;
u32 target_size;
if (ops->gen_prologue) {
cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
env->prog);
if (cnt >= ARRAY_SIZE(insn_buf)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
} else if (cnt) {
new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
env->prog = new_prog;
delta += cnt - 1;
}
}
if (!ops->convert_ctx_access)
return 0;
insn = env->prog->insnsi + delta;
for (i = 0; i < insn_cnt; i++, insn++) {
if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
type = BPF_READ;
else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
insn->code == (BPF_STX | BPF_MEM | BPF_DW))
type = BPF_WRITE;
else
continue;
if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
continue;
ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
size = BPF_LDST_BYTES(insn);
/* If the read access is a narrower load of the field,
* convert to a 4/8-byte load, to minimum program type specific
* convert_ctx_access changes. If conversion is successful,
* we will apply proper mask to the result.
*/
is_narrower_load = size < ctx_field_size;
if (is_narrower_load) {
u32 off = insn->off;
u8 size_code;
if (type == BPF_WRITE) {
verbose(env, "bpf verifier narrow ctx access misconfigured\n");
return -EINVAL;
}
size_code = BPF_H;
if (ctx_field_size == 4)
size_code = BPF_W;
else if (ctx_field_size == 8)
size_code = BPF_DW;
insn->off = off & ~(ctx_field_size - 1);
insn->code = BPF_LDX | BPF_MEM | size_code;
}
target_size = 0;
cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
&target_size);
if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
(ctx_field_size && !target_size)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
}
if (is_narrower_load && size < target_size) {
if (ctx_field_size <= 4)
insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
(1 << size * 8) - 1);
else
insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
(1 << size * 8) - 1);
}
new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
/* keep walking new program and skip insns we just inserted */
env->prog = new_prog;
insn = new_prog->insnsi + i + delta;
}
return 0;
}
/* fixup insn->imm field of bpf_call instructions
* and inline eligible helpers as explicit sequence of BPF instructions
*
* this function is called after eBPF program passed verification
*/
static int fixup_bpf_calls(struct bpf_verifier_env *env)
{
struct bpf_prog *prog = env->prog;
struct bpf_insn *insn = prog->insnsi;
const struct bpf_func_proto *fn;
const int insn_cnt = prog->len;
struct bpf_insn insn_buf[16];
struct bpf_prog *new_prog;
struct bpf_map *map_ptr;
int i, cnt, delta = 0;
for (i = 0; i < insn_cnt; i++, insn++) {
if (insn->code != (BPF_JMP | BPF_CALL))
continue;
if (insn->imm == BPF_FUNC_get_route_realm)
prog->dst_needed = 1;
if (insn->imm == BPF_FUNC_get_prandom_u32)
bpf_user_rnd_init_once();
if (insn->imm == BPF_FUNC_tail_call) {
/* If we tail call into other programs, we
* cannot make any assumptions since they can
* be replaced dynamically during runtime in
* the program array.
*/
prog->cb_access = 1;
env->prog->aux->stack_depth = MAX_BPF_STACK;
/* mark bpf_tail_call as different opcode to avoid
* conditional branch in the interpeter for every normal
* call and to prevent accidental JITing by JIT compiler
* that doesn't support bpf_tail_call yet
*/
insn->imm = 0;
insn->code = BPF_JMP | BPF_TAIL_CALL;
continue;
}
/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
* handlers are currently limited to 64 bit only.
*/
if (ebpf_jit_enabled() && BITS_PER_LONG == 64 &&
insn->imm == BPF_FUNC_map_lookup_elem) {
map_ptr = env->insn_aux_data[i + delta].map_ptr;
if (map_ptr == BPF_MAP_PTR_POISON ||
!map_ptr->ops->map_gen_lookup)
goto patch_call_imm;
cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf);
if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
}
new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
/* keep walking new program and skip insns we just inserted */
env->prog = prog = new_prog;
insn = new_prog->insnsi + i + delta;
continue;
}
if (insn->imm == BPF_FUNC_redirect_map) {
/* Note, we cannot use prog directly as imm as subsequent
* rewrites would still change the prog pointer. The only
* stable address we can use is aux, which also works with
* prog clones during blinding.
*/
u64 addr = (unsigned long)prog->aux;
struct bpf_insn r4_ld[] = {
BPF_LD_IMM64(BPF_REG_4, addr),
*insn,
};
cnt = ARRAY_SIZE(r4_ld);
new_prog = bpf_patch_insn_data(env, i + delta, r4_ld, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
env->prog = prog = new_prog;
insn = new_prog->insnsi + i + delta;
}
patch_call_imm:
fn = env->ops->get_func_proto(insn->imm);
/* all functions that have prototype and verifier allowed
* programs to call them, must be real in-kernel functions
*/
if (!fn->func) {
verbose(env,
"kernel subsystem misconfigured func %s#%d\n",
func_id_name(insn->imm), insn->imm);
return -EFAULT;
}
insn->imm = fn->func - __bpf_call_base;
}
return 0;
}
static void free_states(struct bpf_verifier_env *env)
{
struct bpf_verifier_state_list *sl, *sln;
int i;
if (!env->explored_states)
return;
for (i = 0; i < env->prog->len; i++) {
sl = env->explored_states[i];
if (sl)
while (sl != STATE_LIST_MARK) {
sln = sl->next;
free_verifier_state(&sl->state, false);
kfree(sl);
sl = sln;
}
}
kfree(env->explored_states);
}
int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
{
struct bpf_verifier_env *env;
struct bpf_verifer_log *log;
int ret = -EINVAL;
/* no program is valid */
if (ARRAY_SIZE(bpf_verifier_ops) == 0)
return -EINVAL;
/* 'struct bpf_verifier_env' can be global, but since it's not small,
* allocate/free it every time bpf_check() is called
*/
env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
if (!env)
return -ENOMEM;
log = &env->log;
env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
(*prog)->len);
ret = -ENOMEM;
if (!env->insn_aux_data)
goto err_free_env;
env->prog = *prog;
env->ops = bpf_verifier_ops[env->prog->type];
/* grab the mutex to protect few globals used by verifier */
mutex_lock(&bpf_verifier_lock);
if (attr->log_level || attr->log_buf || attr->log_size) {
/* user requested verbose verifier output
* and supplied buffer to store the verification trace
*/
log->level = attr->log_level;
log->ubuf = (char __user *) (unsigned long) attr->log_buf;
log->len_total = attr->log_size;
ret = -EINVAL;
/* log attributes have to be sane */
if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
!log->level || !log->ubuf)
goto err_unlock;
}
env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
env->strict_alignment = true;
if (env->prog->aux->offload) {
ret = bpf_prog_offload_verifier_prep(env);
if (ret)
goto err_unlock;
}
ret = replace_map_fd_with_map_ptr(env);
if (ret < 0)
goto skip_full_check;
env->explored_states = kcalloc(env->prog->len,
sizeof(struct bpf_verifier_state_list *),
GFP_USER);
ret = -ENOMEM;
if (!env->explored_states)
goto skip_full_check;
ret = check_cfg(env);
if (ret < 0)
goto skip_full_check;
env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
ret = do_check(env);
if (env->cur_state) {
free_verifier_state(env->cur_state, true);
env->cur_state = NULL;
}
skip_full_check:
while (!pop_stack(env, NULL, NULL));
free_states(env);
if (ret == 0)
sanitize_dead_code(env);
if (ret == 0)
/* program is valid, convert *(u32*)(ctx + off) accesses */
ret = convert_ctx_accesses(env);
if (ret == 0)
ret = fixup_bpf_calls(env);
if (log->level && bpf_verifier_log_full(log))
ret = -ENOSPC;
if (log->level && !log->ubuf) {
ret = -EFAULT;
goto err_release_maps;
}
if (ret == 0 && env->used_map_cnt) {
/* if program passed verifier, update used_maps in bpf_prog_info */
env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
sizeof(env->used_maps[0]),
GFP_KERNEL);
if (!env->prog->aux->used_maps) {
ret = -ENOMEM;
goto err_release_maps;
}
memcpy(env->prog->aux->used_maps, env->used_maps,
sizeof(env->used_maps[0]) * env->used_map_cnt);
env->prog->aux->used_map_cnt = env->used_map_cnt;
/* program is valid. Convert pseudo bpf_ld_imm64 into generic
* bpf_ld_imm64 instructions
*/
convert_pseudo_ld_imm64(env);
}
err_release_maps:
if (!env->prog->aux->used_maps)
/* if we didn't copy map pointers into bpf_prog_info, release
* them now. Otherwise free_bpf_prog_info() will release them.
*/
release_maps(env);
*prog = env->prog;
err_unlock:
mutex_unlock(&bpf_verifier_lock);
vfree(env->insn_aux_data);
err_free_env:
kfree(env);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2986_0 |
crossvul-cpp_data_bad_3319_0 | /*
* Copyright (c) 2001 Vojtech Pavlik
*
* CATC EL1210A NetMate USB Ethernet driver
*
* Sponsored by SuSE
*
* Based on the work of
* Donald Becker
*
* Old chipset support added by Simon Evans <spse@secret.org.uk> 2002
* - adds support for Belkin F5U011
*/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
* Should you need to contact me, the author, you can do so either by
* e-mail - mail your message to <vojtech@suse.cz>, or by paper mail:
* Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/spinlock.h>
#include <linux/ethtool.h>
#include <linux/crc32.h>
#include <linux/bitops.h>
#include <linux/gfp.h>
#include <linux/uaccess.h>
#undef DEBUG
#include <linux/usb.h>
/*
* Version information.
*/
#define DRIVER_VERSION "v2.8"
#define DRIVER_AUTHOR "Vojtech Pavlik <vojtech@suse.cz>"
#define DRIVER_DESC "CATC EL1210A NetMate USB Ethernet driver"
#define SHORT_DRIVER_DESC "EL1210A NetMate USB Ethernet"
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
static const char driver_name[] = "catc";
/*
* Some defines.
*/
#define STATS_UPDATE (HZ) /* Time between stats updates */
#define TX_TIMEOUT (5*HZ) /* Max time the queue can be stopped */
#define PKT_SZ 1536 /* Max Ethernet packet size */
#define RX_MAX_BURST 15 /* Max packets per rx buffer (> 0, < 16) */
#define TX_MAX_BURST 15 /* Max full sized packets per tx buffer (> 0) */
#define CTRL_QUEUE 16 /* Max control requests in flight (power of two) */
#define RX_PKT_SZ 1600 /* Max size of receive packet for F5U011 */
/*
* Control requests.
*/
enum control_requests {
ReadMem = 0xf1,
GetMac = 0xf2,
Reset = 0xf4,
SetMac = 0xf5,
SetRxMode = 0xf5, /* F5U011 only */
WriteROM = 0xf8,
SetReg = 0xfa,
GetReg = 0xfb,
WriteMem = 0xfc,
ReadROM = 0xfd,
};
/*
* Registers.
*/
enum register_offsets {
TxBufCount = 0x20,
RxBufCount = 0x21,
OpModes = 0x22,
TxQed = 0x23,
RxQed = 0x24,
MaxBurst = 0x25,
RxUnit = 0x60,
EthStatus = 0x61,
StationAddr0 = 0x67,
EthStats = 0x69,
LEDCtrl = 0x81,
};
enum eth_stats {
TxSingleColl = 0x00,
TxMultiColl = 0x02,
TxExcessColl = 0x04,
RxFramErr = 0x06,
};
enum op_mode_bits {
Op3MemWaits = 0x03,
OpLenInclude = 0x08,
OpRxMerge = 0x10,
OpTxMerge = 0x20,
OpWin95bugfix = 0x40,
OpLoopback = 0x80,
};
enum rx_filter_bits {
RxEnable = 0x01,
RxPolarity = 0x02,
RxForceOK = 0x04,
RxMultiCast = 0x08,
RxPromisc = 0x10,
AltRxPromisc = 0x20, /* F5U011 uses different bit */
};
enum led_values {
LEDFast = 0x01,
LEDSlow = 0x02,
LEDFlash = 0x03,
LEDPulse = 0x04,
LEDLink = 0x08,
};
enum link_status {
LinkNoChange = 0,
LinkGood = 1,
LinkBad = 2
};
/*
* The catc struct.
*/
#define CTRL_RUNNING 0
#define RX_RUNNING 1
#define TX_RUNNING 2
struct catc {
struct net_device *netdev;
struct usb_device *usbdev;
unsigned long flags;
unsigned int tx_ptr, tx_idx;
unsigned int ctrl_head, ctrl_tail;
spinlock_t tx_lock, ctrl_lock;
u8 tx_buf[2][TX_MAX_BURST * (PKT_SZ + 2)];
u8 rx_buf[RX_MAX_BURST * (PKT_SZ + 2)];
u8 irq_buf[2];
u8 ctrl_buf[64];
struct usb_ctrlrequest ctrl_dr;
struct timer_list timer;
u8 stats_buf[8];
u16 stats_vals[4];
unsigned long last_stats;
u8 multicast[64];
struct ctrl_queue {
u8 dir;
u8 request;
u16 value;
u16 index;
void *buf;
int len;
void (*callback)(struct catc *catc, struct ctrl_queue *q);
} ctrl_queue[CTRL_QUEUE];
struct urb *tx_urb, *rx_urb, *irq_urb, *ctrl_urb;
u8 is_f5u011; /* Set if device is an F5U011 */
u8 rxmode[2]; /* Used for F5U011 */
atomic_t recq_sz; /* Used for F5U011 - counter of waiting rx packets */
};
/*
* Useful macros.
*/
#define catc_get_mac(catc, mac) catc_ctrl_msg(catc, USB_DIR_IN, GetMac, 0, 0, mac, 6)
#define catc_reset(catc) catc_ctrl_msg(catc, USB_DIR_OUT, Reset, 0, 0, NULL, 0)
#define catc_set_reg(catc, reg, val) catc_ctrl_msg(catc, USB_DIR_OUT, SetReg, val, reg, NULL, 0)
#define catc_get_reg(catc, reg, buf) catc_ctrl_msg(catc, USB_DIR_IN, GetReg, 0, reg, buf, 1)
#define catc_write_mem(catc, addr, buf, size) catc_ctrl_msg(catc, USB_DIR_OUT, WriteMem, 0, addr, buf, size)
#define catc_read_mem(catc, addr, buf, size) catc_ctrl_msg(catc, USB_DIR_IN, ReadMem, 0, addr, buf, size)
#define f5u011_rxmode(catc, rxmode) catc_ctrl_msg(catc, USB_DIR_OUT, SetRxMode, 0, 1, rxmode, 2)
#define f5u011_rxmode_async(catc, rxmode) catc_ctrl_async(catc, USB_DIR_OUT, SetRxMode, 0, 1, &rxmode, 2, NULL)
#define f5u011_mchash_async(catc, hash) catc_ctrl_async(catc, USB_DIR_OUT, SetRxMode, 0, 2, &hash, 8, NULL)
#define catc_set_reg_async(catc, reg, val) catc_ctrl_async(catc, USB_DIR_OUT, SetReg, val, reg, NULL, 0, NULL)
#define catc_get_reg_async(catc, reg, cb) catc_ctrl_async(catc, USB_DIR_IN, GetReg, 0, reg, NULL, 1, cb)
#define catc_write_mem_async(catc, addr, buf, size) catc_ctrl_async(catc, USB_DIR_OUT, WriteMem, 0, addr, buf, size, NULL)
/*
* Receive routines.
*/
static void catc_rx_done(struct urb *urb)
{
struct catc *catc = urb->context;
u8 *pkt_start = urb->transfer_buffer;
struct sk_buff *skb;
int pkt_len, pkt_offset = 0;
int status = urb->status;
if (!catc->is_f5u011) {
clear_bit(RX_RUNNING, &catc->flags);
pkt_offset = 2;
}
if (status) {
dev_dbg(&urb->dev->dev, "rx_done, status %d, length %d\n",
status, urb->actual_length);
return;
}
do {
if(!catc->is_f5u011) {
pkt_len = le16_to_cpup((__le16*)pkt_start);
if (pkt_len > urb->actual_length) {
catc->netdev->stats.rx_length_errors++;
catc->netdev->stats.rx_errors++;
break;
}
} else {
pkt_len = urb->actual_length;
}
if (!(skb = dev_alloc_skb(pkt_len)))
return;
skb_copy_to_linear_data(skb, pkt_start + pkt_offset, pkt_len);
skb_put(skb, pkt_len);
skb->protocol = eth_type_trans(skb, catc->netdev);
netif_rx(skb);
catc->netdev->stats.rx_packets++;
catc->netdev->stats.rx_bytes += pkt_len;
/* F5U011 only does one packet per RX */
if (catc->is_f5u011)
break;
pkt_start += (((pkt_len + 1) >> 6) + 1) << 6;
} while (pkt_start - (u8 *) urb->transfer_buffer < urb->actual_length);
if (catc->is_f5u011) {
if (atomic_read(&catc->recq_sz)) {
int state;
atomic_dec(&catc->recq_sz);
netdev_dbg(catc->netdev, "getting extra packet\n");
urb->dev = catc->usbdev;
if ((state = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
netdev_dbg(catc->netdev,
"submit(rx_urb) status %d\n", state);
}
} else {
clear_bit(RX_RUNNING, &catc->flags);
}
}
}
static void catc_irq_done(struct urb *urb)
{
struct catc *catc = urb->context;
u8 *data = urb->transfer_buffer;
int status = urb->status;
unsigned int hasdata = 0, linksts = LinkNoChange;
int res;
if (!catc->is_f5u011) {
hasdata = data[1] & 0x80;
if (data[1] & 0x40)
linksts = LinkGood;
else if (data[1] & 0x20)
linksts = LinkBad;
} else {
hasdata = (unsigned int)(be16_to_cpup((__be16*)data) & 0x0fff);
if (data[0] == 0x90)
linksts = LinkGood;
else if (data[0] == 0xA0)
linksts = LinkBad;
}
switch (status) {
case 0: /* success */
break;
case -ECONNRESET: /* unlink */
case -ENOENT:
case -ESHUTDOWN:
return;
/* -EPIPE: should clear the halt */
default: /* error */
dev_dbg(&urb->dev->dev,
"irq_done, status %d, data %02x %02x.\n",
status, data[0], data[1]);
goto resubmit;
}
if (linksts == LinkGood) {
netif_carrier_on(catc->netdev);
netdev_dbg(catc->netdev, "link ok\n");
}
if (linksts == LinkBad) {
netif_carrier_off(catc->netdev);
netdev_dbg(catc->netdev, "link bad\n");
}
if (hasdata) {
if (test_and_set_bit(RX_RUNNING, &catc->flags)) {
if (catc->is_f5u011)
atomic_inc(&catc->recq_sz);
} else {
catc->rx_urb->dev = catc->usbdev;
if ((res = usb_submit_urb(catc->rx_urb, GFP_ATOMIC)) < 0) {
dev_err(&catc->usbdev->dev,
"submit(rx_urb) status %d\n", res);
}
}
}
resubmit:
res = usb_submit_urb (urb, GFP_ATOMIC);
if (res)
dev_err(&catc->usbdev->dev,
"can't resubmit intr, %s-%s, status %d\n",
catc->usbdev->bus->bus_name,
catc->usbdev->devpath, res);
}
/*
* Transmit routines.
*/
static int catc_tx_run(struct catc *catc)
{
int status;
if (catc->is_f5u011)
catc->tx_ptr = (catc->tx_ptr + 63) & ~63;
catc->tx_urb->transfer_buffer_length = catc->tx_ptr;
catc->tx_urb->transfer_buffer = catc->tx_buf[catc->tx_idx];
catc->tx_urb->dev = catc->usbdev;
if ((status = usb_submit_urb(catc->tx_urb, GFP_ATOMIC)) < 0)
dev_err(&catc->usbdev->dev, "submit(tx_urb), status %d\n",
status);
catc->tx_idx = !catc->tx_idx;
catc->tx_ptr = 0;
netif_trans_update(catc->netdev);
return status;
}
static void catc_tx_done(struct urb *urb)
{
struct catc *catc = urb->context;
unsigned long flags;
int r, status = urb->status;
if (status == -ECONNRESET) {
dev_dbg(&urb->dev->dev, "Tx Reset.\n");
urb->status = 0;
netif_trans_update(catc->netdev);
catc->netdev->stats.tx_errors++;
clear_bit(TX_RUNNING, &catc->flags);
netif_wake_queue(catc->netdev);
return;
}
if (status) {
dev_dbg(&urb->dev->dev, "tx_done, status %d, length %d\n",
status, urb->actual_length);
return;
}
spin_lock_irqsave(&catc->tx_lock, flags);
if (catc->tx_ptr) {
r = catc_tx_run(catc);
if (unlikely(r < 0))
clear_bit(TX_RUNNING, &catc->flags);
} else {
clear_bit(TX_RUNNING, &catc->flags);
}
netif_wake_queue(catc->netdev);
spin_unlock_irqrestore(&catc->tx_lock, flags);
}
static netdev_tx_t catc_start_xmit(struct sk_buff *skb,
struct net_device *netdev)
{
struct catc *catc = netdev_priv(netdev);
unsigned long flags;
int r = 0;
char *tx_buf;
spin_lock_irqsave(&catc->tx_lock, flags);
catc->tx_ptr = (((catc->tx_ptr - 1) >> 6) + 1) << 6;
tx_buf = catc->tx_buf[catc->tx_idx] + catc->tx_ptr;
if (catc->is_f5u011)
*(__be16 *)tx_buf = cpu_to_be16(skb->len);
else
*(__le16 *)tx_buf = cpu_to_le16(skb->len);
skb_copy_from_linear_data(skb, tx_buf + 2, skb->len);
catc->tx_ptr += skb->len + 2;
if (!test_and_set_bit(TX_RUNNING, &catc->flags)) {
r = catc_tx_run(catc);
if (r < 0)
clear_bit(TX_RUNNING, &catc->flags);
}
if ((catc->is_f5u011 && catc->tx_ptr) ||
(catc->tx_ptr >= ((TX_MAX_BURST - 1) * (PKT_SZ + 2))))
netif_stop_queue(netdev);
spin_unlock_irqrestore(&catc->tx_lock, flags);
if (r >= 0) {
catc->netdev->stats.tx_bytes += skb->len;
catc->netdev->stats.tx_packets++;
}
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
static void catc_tx_timeout(struct net_device *netdev)
{
struct catc *catc = netdev_priv(netdev);
dev_warn(&netdev->dev, "Transmit timed out.\n");
usb_unlink_urb(catc->tx_urb);
}
/*
* Control messages.
*/
static int catc_ctrl_msg(struct catc *catc, u8 dir, u8 request, u16 value, u16 index, void *buf, int len)
{
int retval = usb_control_msg(catc->usbdev,
dir ? usb_rcvctrlpipe(catc->usbdev, 0) : usb_sndctrlpipe(catc->usbdev, 0),
request, 0x40 | dir, value, index, buf, len, 1000);
return retval < 0 ? retval : 0;
}
static void catc_ctrl_run(struct catc *catc)
{
struct ctrl_queue *q = catc->ctrl_queue + catc->ctrl_tail;
struct usb_device *usbdev = catc->usbdev;
struct urb *urb = catc->ctrl_urb;
struct usb_ctrlrequest *dr = &catc->ctrl_dr;
int status;
dr->bRequest = q->request;
dr->bRequestType = 0x40 | q->dir;
dr->wValue = cpu_to_le16(q->value);
dr->wIndex = cpu_to_le16(q->index);
dr->wLength = cpu_to_le16(q->len);
urb->pipe = q->dir ? usb_rcvctrlpipe(usbdev, 0) : usb_sndctrlpipe(usbdev, 0);
urb->transfer_buffer_length = q->len;
urb->transfer_buffer = catc->ctrl_buf;
urb->setup_packet = (void *) dr;
urb->dev = usbdev;
if (!q->dir && q->buf && q->len)
memcpy(catc->ctrl_buf, q->buf, q->len);
if ((status = usb_submit_urb(catc->ctrl_urb, GFP_ATOMIC)))
dev_err(&catc->usbdev->dev, "submit(ctrl_urb) status %d\n",
status);
}
static void catc_ctrl_done(struct urb *urb)
{
struct catc *catc = urb->context;
struct ctrl_queue *q;
unsigned long flags;
int status = urb->status;
if (status)
dev_dbg(&urb->dev->dev, "ctrl_done, status %d, len %d.\n",
status, urb->actual_length);
spin_lock_irqsave(&catc->ctrl_lock, flags);
q = catc->ctrl_queue + catc->ctrl_tail;
if (q->dir) {
if (q->buf && q->len)
memcpy(q->buf, catc->ctrl_buf, q->len);
else
q->buf = catc->ctrl_buf;
}
if (q->callback)
q->callback(catc, q);
catc->ctrl_tail = (catc->ctrl_tail + 1) & (CTRL_QUEUE - 1);
if (catc->ctrl_head != catc->ctrl_tail)
catc_ctrl_run(catc);
else
clear_bit(CTRL_RUNNING, &catc->flags);
spin_unlock_irqrestore(&catc->ctrl_lock, flags);
}
static int catc_ctrl_async(struct catc *catc, u8 dir, u8 request, u16 value,
u16 index, void *buf, int len, void (*callback)(struct catc *catc, struct ctrl_queue *q))
{
struct ctrl_queue *q;
int retval = 0;
unsigned long flags;
spin_lock_irqsave(&catc->ctrl_lock, flags);
q = catc->ctrl_queue + catc->ctrl_head;
q->dir = dir;
q->request = request;
q->value = value;
q->index = index;
q->buf = buf;
q->len = len;
q->callback = callback;
catc->ctrl_head = (catc->ctrl_head + 1) & (CTRL_QUEUE - 1);
if (catc->ctrl_head == catc->ctrl_tail) {
dev_err(&catc->usbdev->dev, "ctrl queue full\n");
catc->ctrl_tail = (catc->ctrl_tail + 1) & (CTRL_QUEUE - 1);
retval = -1;
}
if (!test_and_set_bit(CTRL_RUNNING, &catc->flags))
catc_ctrl_run(catc);
spin_unlock_irqrestore(&catc->ctrl_lock, flags);
return retval;
}
/*
* Statistics.
*/
static void catc_stats_done(struct catc *catc, struct ctrl_queue *q)
{
int index = q->index - EthStats;
u16 data, last;
catc->stats_buf[index] = *((char *)q->buf);
if (index & 1)
return;
data = ((u16)catc->stats_buf[index] << 8) | catc->stats_buf[index + 1];
last = catc->stats_vals[index >> 1];
switch (index) {
case TxSingleColl:
case TxMultiColl:
catc->netdev->stats.collisions += data - last;
break;
case TxExcessColl:
catc->netdev->stats.tx_aborted_errors += data - last;
catc->netdev->stats.tx_errors += data - last;
break;
case RxFramErr:
catc->netdev->stats.rx_frame_errors += data - last;
catc->netdev->stats.rx_errors += data - last;
break;
}
catc->stats_vals[index >> 1] = data;
}
static void catc_stats_timer(unsigned long data)
{
struct catc *catc = (void *) data;
int i;
for (i = 0; i < 8; i++)
catc_get_reg_async(catc, EthStats + 7 - i, catc_stats_done);
mod_timer(&catc->timer, jiffies + STATS_UPDATE);
}
/*
* Receive modes. Broadcast, Multicast, Promisc.
*/
static void catc_multicast(unsigned char *addr, u8 *multicast)
{
u32 crc;
crc = ether_crc_le(6, addr);
multicast[(crc >> 3) & 0x3f] |= 1 << (crc & 7);
}
static void catc_set_multicast_list(struct net_device *netdev)
{
struct catc *catc = netdev_priv(netdev);
struct netdev_hw_addr *ha;
u8 broadcast[ETH_ALEN];
u8 rx = RxEnable | RxPolarity | RxMultiCast;
eth_broadcast_addr(broadcast);
memset(catc->multicast, 0, 64);
catc_multicast(broadcast, catc->multicast);
catc_multicast(netdev->dev_addr, catc->multicast);
if (netdev->flags & IFF_PROMISC) {
memset(catc->multicast, 0xff, 64);
rx |= (!catc->is_f5u011) ? RxPromisc : AltRxPromisc;
}
if (netdev->flags & IFF_ALLMULTI) {
memset(catc->multicast, 0xff, 64);
} else {
netdev_for_each_mc_addr(ha, netdev) {
u32 crc = ether_crc_le(6, ha->addr);
if (!catc->is_f5u011) {
catc->multicast[(crc >> 3) & 0x3f] |= 1 << (crc & 7);
} else {
catc->multicast[7-(crc >> 29)] |= 1 << ((crc >> 26) & 7);
}
}
}
if (!catc->is_f5u011) {
catc_set_reg_async(catc, RxUnit, rx);
catc_write_mem_async(catc, 0xfa80, catc->multicast, 64);
} else {
f5u011_mchash_async(catc, catc->multicast);
if (catc->rxmode[0] != rx) {
catc->rxmode[0] = rx;
netdev_dbg(catc->netdev,
"Setting RX mode to %2.2X %2.2X\n",
catc->rxmode[0], catc->rxmode[1]);
f5u011_rxmode_async(catc, catc->rxmode);
}
}
}
static void catc_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
struct catc *catc = netdev_priv(dev);
strlcpy(info->driver, driver_name, sizeof(info->driver));
strlcpy(info->version, DRIVER_VERSION, sizeof(info->version));
usb_make_path(catc->usbdev, info->bus_info, sizeof(info->bus_info));
}
static int catc_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct catc *catc = netdev_priv(dev);
if (!catc->is_f5u011)
return -EOPNOTSUPP;
cmd->supported = SUPPORTED_10baseT_Half | SUPPORTED_TP;
cmd->advertising = ADVERTISED_10baseT_Half | ADVERTISED_TP;
ethtool_cmd_speed_set(cmd, SPEED_10);
cmd->duplex = DUPLEX_HALF;
cmd->port = PORT_TP;
cmd->phy_address = 0;
cmd->transceiver = XCVR_INTERNAL;
cmd->autoneg = AUTONEG_DISABLE;
cmd->maxtxpkt = 1;
cmd->maxrxpkt = 1;
return 0;
}
static const struct ethtool_ops ops = {
.get_drvinfo = catc_get_drvinfo,
.get_settings = catc_get_settings,
.get_link = ethtool_op_get_link
};
/*
* Open, close.
*/
static int catc_open(struct net_device *netdev)
{
struct catc *catc = netdev_priv(netdev);
int status;
catc->irq_urb->dev = catc->usbdev;
if ((status = usb_submit_urb(catc->irq_urb, GFP_KERNEL)) < 0) {
dev_err(&catc->usbdev->dev, "submit(irq_urb) status %d\n",
status);
return -1;
}
netif_start_queue(netdev);
if (!catc->is_f5u011)
mod_timer(&catc->timer, jiffies + STATS_UPDATE);
return 0;
}
static int catc_stop(struct net_device *netdev)
{
struct catc *catc = netdev_priv(netdev);
netif_stop_queue(netdev);
if (!catc->is_f5u011)
del_timer_sync(&catc->timer);
usb_kill_urb(catc->rx_urb);
usb_kill_urb(catc->tx_urb);
usb_kill_urb(catc->irq_urb);
usb_kill_urb(catc->ctrl_urb);
return 0;
}
static const struct net_device_ops catc_netdev_ops = {
.ndo_open = catc_open,
.ndo_stop = catc_stop,
.ndo_start_xmit = catc_start_xmit,
.ndo_tx_timeout = catc_tx_timeout,
.ndo_set_rx_mode = catc_set_multicast_list,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
/*
* USB probe, disconnect.
*/
static int catc_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct device *dev = &intf->dev;
struct usb_device *usbdev = interface_to_usbdev(intf);
struct net_device *netdev;
struct catc *catc;
u8 broadcast[ETH_ALEN];
int i, pktsz, ret;
if (usb_set_interface(usbdev,
intf->altsetting->desc.bInterfaceNumber, 1)) {
dev_err(dev, "Can't set altsetting 1.\n");
return -EIO;
}
netdev = alloc_etherdev(sizeof(struct catc));
if (!netdev)
return -ENOMEM;
catc = netdev_priv(netdev);
netdev->netdev_ops = &catc_netdev_ops;
netdev->watchdog_timeo = TX_TIMEOUT;
netdev->ethtool_ops = &ops;
catc->usbdev = usbdev;
catc->netdev = netdev;
spin_lock_init(&catc->tx_lock);
spin_lock_init(&catc->ctrl_lock);
init_timer(&catc->timer);
catc->timer.data = (long) catc;
catc->timer.function = catc_stats_timer;
catc->ctrl_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->rx_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->irq_urb = usb_alloc_urb(0, GFP_KERNEL);
if ((!catc->ctrl_urb) || (!catc->tx_urb) ||
(!catc->rx_urb) || (!catc->irq_urb)) {
dev_err(&intf->dev, "No free urbs available.\n");
ret = -ENOMEM;
goto fail_free;
}
/* The F5U011 has the same vendor/product as the netmate but a device version of 0x130 */
if (le16_to_cpu(usbdev->descriptor.idVendor) == 0x0423 &&
le16_to_cpu(usbdev->descriptor.idProduct) == 0xa &&
le16_to_cpu(catc->usbdev->descriptor.bcdDevice) == 0x0130) {
dev_dbg(dev, "Testing for f5u011\n");
catc->is_f5u011 = 1;
atomic_set(&catc->recq_sz, 0);
pktsz = RX_PKT_SZ;
} else {
pktsz = RX_MAX_BURST * (PKT_SZ + 2);
}
usb_fill_control_urb(catc->ctrl_urb, usbdev, usb_sndctrlpipe(usbdev, 0),
NULL, NULL, 0, catc_ctrl_done, catc);
usb_fill_bulk_urb(catc->tx_urb, usbdev, usb_sndbulkpipe(usbdev, 1),
NULL, 0, catc_tx_done, catc);
usb_fill_bulk_urb(catc->rx_urb, usbdev, usb_rcvbulkpipe(usbdev, 1),
catc->rx_buf, pktsz, catc_rx_done, catc);
usb_fill_int_urb(catc->irq_urb, usbdev, usb_rcvintpipe(usbdev, 2),
catc->irq_buf, 2, catc_irq_done, catc, 1);
if (!catc->is_f5u011) {
dev_dbg(dev, "Checking memory size\n");
i = 0x12345678;
catc_write_mem(catc, 0x7a80, &i, 4);
i = 0x87654321;
catc_write_mem(catc, 0xfa80, &i, 4);
catc_read_mem(catc, 0x7a80, &i, 4);
switch (i) {
case 0x12345678:
catc_set_reg(catc, TxBufCount, 8);
catc_set_reg(catc, RxBufCount, 32);
dev_dbg(dev, "64k Memory\n");
break;
default:
dev_warn(&intf->dev,
"Couldn't detect memory size, assuming 32k\n");
case 0x87654321:
catc_set_reg(catc, TxBufCount, 4);
catc_set_reg(catc, RxBufCount, 16);
dev_dbg(dev, "32k Memory\n");
break;
}
dev_dbg(dev, "Getting MAC from SEEROM.\n");
catc_get_mac(catc, netdev->dev_addr);
dev_dbg(dev, "Setting MAC into registers.\n");
for (i = 0; i < 6; i++)
catc_set_reg(catc, StationAddr0 - i, netdev->dev_addr[i]);
dev_dbg(dev, "Filling the multicast list.\n");
eth_broadcast_addr(broadcast);
catc_multicast(broadcast, catc->multicast);
catc_multicast(netdev->dev_addr, catc->multicast);
catc_write_mem(catc, 0xfa80, catc->multicast, 64);
dev_dbg(dev, "Clearing error counters.\n");
for (i = 0; i < 8; i++)
catc_set_reg(catc, EthStats + i, 0);
catc->last_stats = jiffies;
dev_dbg(dev, "Enabling.\n");
catc_set_reg(catc, MaxBurst, RX_MAX_BURST);
catc_set_reg(catc, OpModes, OpTxMerge | OpRxMerge | OpLenInclude | Op3MemWaits);
catc_set_reg(catc, LEDCtrl, LEDLink);
catc_set_reg(catc, RxUnit, RxEnable | RxPolarity | RxMultiCast);
} else {
dev_dbg(dev, "Performing reset\n");
catc_reset(catc);
catc_get_mac(catc, netdev->dev_addr);
dev_dbg(dev, "Setting RX Mode\n");
catc->rxmode[0] = RxEnable | RxPolarity | RxMultiCast;
catc->rxmode[1] = 0;
f5u011_rxmode(catc, catc->rxmode);
}
dev_dbg(dev, "Init done.\n");
printk(KERN_INFO "%s: %s USB Ethernet at usb-%s-%s, %pM.\n",
netdev->name, (catc->is_f5u011) ? "Belkin F5U011" : "CATC EL1210A NetMate",
usbdev->bus->bus_name, usbdev->devpath, netdev->dev_addr);
usb_set_intfdata(intf, catc);
SET_NETDEV_DEV(netdev, &intf->dev);
ret = register_netdev(netdev);
if (ret)
goto fail_clear_intfdata;
return 0;
fail_clear_intfdata:
usb_set_intfdata(intf, NULL);
fail_free:
usb_free_urb(catc->ctrl_urb);
usb_free_urb(catc->tx_urb);
usb_free_urb(catc->rx_urb);
usb_free_urb(catc->irq_urb);
free_netdev(netdev);
return ret;
}
static void catc_disconnect(struct usb_interface *intf)
{
struct catc *catc = usb_get_intfdata(intf);
usb_set_intfdata(intf, NULL);
if (catc) {
unregister_netdev(catc->netdev);
usb_free_urb(catc->ctrl_urb);
usb_free_urb(catc->tx_urb);
usb_free_urb(catc->rx_urb);
usb_free_urb(catc->irq_urb);
free_netdev(catc->netdev);
}
}
/*
* Module functions and tables.
*/
static struct usb_device_id catc_id_table [] = {
{ USB_DEVICE(0x0423, 0xa) }, /* CATC Netmate, Belkin F5U011 */
{ USB_DEVICE(0x0423, 0xc) }, /* CATC Netmate II, Belkin F5U111 */
{ USB_DEVICE(0x08d1, 0x1) }, /* smartBridges smartNIC */
{ }
};
MODULE_DEVICE_TABLE(usb, catc_id_table);
static struct usb_driver catc_driver = {
.name = driver_name,
.probe = catc_probe,
.disconnect = catc_disconnect,
.id_table = catc_id_table,
.disable_hub_initiated_lpm = 1,
};
module_usb_driver(catc_driver);
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3319_0 |
crossvul-cpp_data_good_4888_0 | /*
* Driver for Cadence QSPI Controller
*
* Copyright Altera Corporation (C) 2012-2014. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/clk.h>
#include <linux/completion.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/spi-nor.h>
#include <linux/of_device.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/sched.h>
#include <linux/spi/spi.h>
#include <linux/timer.h>
#define CQSPI_NAME "cadence-qspi"
#define CQSPI_MAX_CHIPSELECT 16
struct cqspi_st;
struct cqspi_flash_pdata {
struct spi_nor nor;
struct cqspi_st *cqspi;
u32 clk_rate;
u32 read_delay;
u32 tshsl_ns;
u32 tsd2d_ns;
u32 tchsh_ns;
u32 tslch_ns;
u8 inst_width;
u8 addr_width;
u8 data_width;
u8 cs;
bool registered;
};
struct cqspi_st {
struct platform_device *pdev;
struct clk *clk;
unsigned int sclk;
void __iomem *iobase;
void __iomem *ahb_base;
struct completion transfer_complete;
struct mutex bus_mutex;
int current_cs;
int current_page_size;
int current_erase_size;
int current_addr_width;
unsigned long master_ref_clk_hz;
bool is_decoded_cs;
u32 fifo_depth;
u32 fifo_width;
u32 trigger_address;
struct cqspi_flash_pdata f_pdata[CQSPI_MAX_CHIPSELECT];
};
/* Operation timeout value */
#define CQSPI_TIMEOUT_MS 500
#define CQSPI_READ_TIMEOUT_MS 10
/* Instruction type */
#define CQSPI_INST_TYPE_SINGLE 0
#define CQSPI_INST_TYPE_DUAL 1
#define CQSPI_INST_TYPE_QUAD 2
#define CQSPI_DUMMY_CLKS_PER_BYTE 8
#define CQSPI_DUMMY_BYTES_MAX 4
#define CQSPI_DUMMY_CLKS_MAX 31
#define CQSPI_STIG_DATA_LEN_MAX 8
/* Register map */
#define CQSPI_REG_CONFIG 0x00
#define CQSPI_REG_CONFIG_ENABLE_MASK BIT(0)
#define CQSPI_REG_CONFIG_DECODE_MASK BIT(9)
#define CQSPI_REG_CONFIG_CHIPSELECT_LSB 10
#define CQSPI_REG_CONFIG_DMA_MASK BIT(15)
#define CQSPI_REG_CONFIG_BAUD_LSB 19
#define CQSPI_REG_CONFIG_IDLE_LSB 31
#define CQSPI_REG_CONFIG_CHIPSELECT_MASK 0xF
#define CQSPI_REG_CONFIG_BAUD_MASK 0xF
#define CQSPI_REG_RD_INSTR 0x04
#define CQSPI_REG_RD_INSTR_OPCODE_LSB 0
#define CQSPI_REG_RD_INSTR_TYPE_INSTR_LSB 8
#define CQSPI_REG_RD_INSTR_TYPE_ADDR_LSB 12
#define CQSPI_REG_RD_INSTR_TYPE_DATA_LSB 16
#define CQSPI_REG_RD_INSTR_MODE_EN_LSB 20
#define CQSPI_REG_RD_INSTR_DUMMY_LSB 24
#define CQSPI_REG_RD_INSTR_TYPE_INSTR_MASK 0x3
#define CQSPI_REG_RD_INSTR_TYPE_ADDR_MASK 0x3
#define CQSPI_REG_RD_INSTR_TYPE_DATA_MASK 0x3
#define CQSPI_REG_RD_INSTR_DUMMY_MASK 0x1F
#define CQSPI_REG_WR_INSTR 0x08
#define CQSPI_REG_WR_INSTR_OPCODE_LSB 0
#define CQSPI_REG_WR_INSTR_TYPE_ADDR_LSB 12
#define CQSPI_REG_WR_INSTR_TYPE_DATA_LSB 16
#define CQSPI_REG_DELAY 0x0C
#define CQSPI_REG_DELAY_TSLCH_LSB 0
#define CQSPI_REG_DELAY_TCHSH_LSB 8
#define CQSPI_REG_DELAY_TSD2D_LSB 16
#define CQSPI_REG_DELAY_TSHSL_LSB 24
#define CQSPI_REG_DELAY_TSLCH_MASK 0xFF
#define CQSPI_REG_DELAY_TCHSH_MASK 0xFF
#define CQSPI_REG_DELAY_TSD2D_MASK 0xFF
#define CQSPI_REG_DELAY_TSHSL_MASK 0xFF
#define CQSPI_REG_READCAPTURE 0x10
#define CQSPI_REG_READCAPTURE_BYPASS_LSB 0
#define CQSPI_REG_READCAPTURE_DELAY_LSB 1
#define CQSPI_REG_READCAPTURE_DELAY_MASK 0xF
#define CQSPI_REG_SIZE 0x14
#define CQSPI_REG_SIZE_ADDRESS_LSB 0
#define CQSPI_REG_SIZE_PAGE_LSB 4
#define CQSPI_REG_SIZE_BLOCK_LSB 16
#define CQSPI_REG_SIZE_ADDRESS_MASK 0xF
#define CQSPI_REG_SIZE_PAGE_MASK 0xFFF
#define CQSPI_REG_SIZE_BLOCK_MASK 0x3F
#define CQSPI_REG_SRAMPARTITION 0x18
#define CQSPI_REG_INDIRECTTRIGGER 0x1C
#define CQSPI_REG_DMA 0x20
#define CQSPI_REG_DMA_SINGLE_LSB 0
#define CQSPI_REG_DMA_BURST_LSB 8
#define CQSPI_REG_DMA_SINGLE_MASK 0xFF
#define CQSPI_REG_DMA_BURST_MASK 0xFF
#define CQSPI_REG_REMAP 0x24
#define CQSPI_REG_MODE_BIT 0x28
#define CQSPI_REG_SDRAMLEVEL 0x2C
#define CQSPI_REG_SDRAMLEVEL_RD_LSB 0
#define CQSPI_REG_SDRAMLEVEL_WR_LSB 16
#define CQSPI_REG_SDRAMLEVEL_RD_MASK 0xFFFF
#define CQSPI_REG_SDRAMLEVEL_WR_MASK 0xFFFF
#define CQSPI_REG_IRQSTATUS 0x40
#define CQSPI_REG_IRQMASK 0x44
#define CQSPI_REG_INDIRECTRD 0x60
#define CQSPI_REG_INDIRECTRD_START_MASK BIT(0)
#define CQSPI_REG_INDIRECTRD_CANCEL_MASK BIT(1)
#define CQSPI_REG_INDIRECTRD_DONE_MASK BIT(5)
#define CQSPI_REG_INDIRECTRDWATERMARK 0x64
#define CQSPI_REG_INDIRECTRDSTARTADDR 0x68
#define CQSPI_REG_INDIRECTRDBYTES 0x6C
#define CQSPI_REG_CMDCTRL 0x90
#define CQSPI_REG_CMDCTRL_EXECUTE_MASK BIT(0)
#define CQSPI_REG_CMDCTRL_INPROGRESS_MASK BIT(1)
#define CQSPI_REG_CMDCTRL_WR_BYTES_LSB 12
#define CQSPI_REG_CMDCTRL_WR_EN_LSB 15
#define CQSPI_REG_CMDCTRL_ADD_BYTES_LSB 16
#define CQSPI_REG_CMDCTRL_ADDR_EN_LSB 19
#define CQSPI_REG_CMDCTRL_RD_BYTES_LSB 20
#define CQSPI_REG_CMDCTRL_RD_EN_LSB 23
#define CQSPI_REG_CMDCTRL_OPCODE_LSB 24
#define CQSPI_REG_CMDCTRL_WR_BYTES_MASK 0x7
#define CQSPI_REG_CMDCTRL_ADD_BYTES_MASK 0x3
#define CQSPI_REG_CMDCTRL_RD_BYTES_MASK 0x7
#define CQSPI_REG_INDIRECTWR 0x70
#define CQSPI_REG_INDIRECTWR_START_MASK BIT(0)
#define CQSPI_REG_INDIRECTWR_CANCEL_MASK BIT(1)
#define CQSPI_REG_INDIRECTWR_DONE_MASK BIT(5)
#define CQSPI_REG_INDIRECTWRWATERMARK 0x74
#define CQSPI_REG_INDIRECTWRSTARTADDR 0x78
#define CQSPI_REG_INDIRECTWRBYTES 0x7C
#define CQSPI_REG_CMDADDRESS 0x94
#define CQSPI_REG_CMDREADDATALOWER 0xA0
#define CQSPI_REG_CMDREADDATAUPPER 0xA4
#define CQSPI_REG_CMDWRITEDATALOWER 0xA8
#define CQSPI_REG_CMDWRITEDATAUPPER 0xAC
/* Interrupt status bits */
#define CQSPI_REG_IRQ_MODE_ERR BIT(0)
#define CQSPI_REG_IRQ_UNDERFLOW BIT(1)
#define CQSPI_REG_IRQ_IND_COMP BIT(2)
#define CQSPI_REG_IRQ_IND_RD_REJECT BIT(3)
#define CQSPI_REG_IRQ_WR_PROTECTED_ERR BIT(4)
#define CQSPI_REG_IRQ_ILLEGAL_AHB_ERR BIT(5)
#define CQSPI_REG_IRQ_WATERMARK BIT(6)
#define CQSPI_REG_IRQ_IND_SRAM_FULL BIT(12)
#define CQSPI_IRQ_MASK_RD (CQSPI_REG_IRQ_WATERMARK | \
CQSPI_REG_IRQ_IND_SRAM_FULL | \
CQSPI_REG_IRQ_IND_COMP)
#define CQSPI_IRQ_MASK_WR (CQSPI_REG_IRQ_IND_COMP | \
CQSPI_REG_IRQ_WATERMARK | \
CQSPI_REG_IRQ_UNDERFLOW)
#define CQSPI_IRQ_STATUS_MASK 0x1FFFF
static int cqspi_wait_for_bit(void __iomem *reg, const u32 mask, bool clear)
{
unsigned long end = jiffies + msecs_to_jiffies(CQSPI_TIMEOUT_MS);
u32 val;
while (1) {
val = readl(reg);
if (clear)
val = ~val;
val &= mask;
if (val == mask)
return 0;
if (time_after(jiffies, end))
return -ETIMEDOUT;
}
}
static bool cqspi_is_idle(struct cqspi_st *cqspi)
{
u32 reg = readl(cqspi->iobase + CQSPI_REG_CONFIG);
return reg & (1 << CQSPI_REG_CONFIG_IDLE_LSB);
}
static u32 cqspi_get_rd_sram_level(struct cqspi_st *cqspi)
{
u32 reg = readl(cqspi->iobase + CQSPI_REG_SDRAMLEVEL);
reg >>= CQSPI_REG_SDRAMLEVEL_RD_LSB;
return reg & CQSPI_REG_SDRAMLEVEL_RD_MASK;
}
static irqreturn_t cqspi_irq_handler(int this_irq, void *dev)
{
struct cqspi_st *cqspi = dev;
unsigned int irq_status;
/* Read interrupt status */
irq_status = readl(cqspi->iobase + CQSPI_REG_IRQSTATUS);
/* Clear interrupt */
writel(irq_status, cqspi->iobase + CQSPI_REG_IRQSTATUS);
irq_status &= CQSPI_IRQ_MASK_RD | CQSPI_IRQ_MASK_WR;
if (irq_status)
complete(&cqspi->transfer_complete);
return IRQ_HANDLED;
}
static unsigned int cqspi_calc_rdreg(struct spi_nor *nor, const u8 opcode)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
u32 rdreg = 0;
rdreg |= f_pdata->inst_width << CQSPI_REG_RD_INSTR_TYPE_INSTR_LSB;
rdreg |= f_pdata->addr_width << CQSPI_REG_RD_INSTR_TYPE_ADDR_LSB;
rdreg |= f_pdata->data_width << CQSPI_REG_RD_INSTR_TYPE_DATA_LSB;
return rdreg;
}
static int cqspi_wait_idle(struct cqspi_st *cqspi)
{
const unsigned int poll_idle_retry = 3;
unsigned int count = 0;
unsigned long timeout;
timeout = jiffies + msecs_to_jiffies(CQSPI_TIMEOUT_MS);
while (1) {
/*
* Read few times in succession to ensure the controller
* is indeed idle, that is, the bit does not transition
* low again.
*/
if (cqspi_is_idle(cqspi))
count++;
else
count = 0;
if (count >= poll_idle_retry)
return 0;
if (time_after(jiffies, timeout)) {
/* Timeout, in busy mode. */
dev_err(&cqspi->pdev->dev,
"QSPI is still busy after %dms timeout.\n",
CQSPI_TIMEOUT_MS);
return -ETIMEDOUT;
}
cpu_relax();
}
}
static int cqspi_exec_flash_cmd(struct cqspi_st *cqspi, unsigned int reg)
{
void __iomem *reg_base = cqspi->iobase;
int ret;
/* Write the CMDCTRL without start execution. */
writel(reg, reg_base + CQSPI_REG_CMDCTRL);
/* Start execute */
reg |= CQSPI_REG_CMDCTRL_EXECUTE_MASK;
writel(reg, reg_base + CQSPI_REG_CMDCTRL);
/* Polling for completion. */
ret = cqspi_wait_for_bit(reg_base + CQSPI_REG_CMDCTRL,
CQSPI_REG_CMDCTRL_INPROGRESS_MASK, 1);
if (ret) {
dev_err(&cqspi->pdev->dev,
"Flash command execution timed out.\n");
return ret;
}
/* Polling QSPI idle status. */
return cqspi_wait_idle(cqspi);
}
static int cqspi_command_read(struct spi_nor *nor,
const u8 *txbuf, const unsigned n_tx,
u8 *rxbuf, const unsigned n_rx)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *reg_base = cqspi->iobase;
unsigned int rdreg;
unsigned int reg;
unsigned int read_len;
int status;
if (!n_rx || n_rx > CQSPI_STIG_DATA_LEN_MAX || !rxbuf) {
dev_err(nor->dev, "Invalid input argument, len %d rxbuf 0x%p\n",
n_rx, rxbuf);
return -EINVAL;
}
reg = txbuf[0] << CQSPI_REG_CMDCTRL_OPCODE_LSB;
rdreg = cqspi_calc_rdreg(nor, txbuf[0]);
writel(rdreg, reg_base + CQSPI_REG_RD_INSTR);
reg |= (0x1 << CQSPI_REG_CMDCTRL_RD_EN_LSB);
/* 0 means 1 byte. */
reg |= (((n_rx - 1) & CQSPI_REG_CMDCTRL_RD_BYTES_MASK)
<< CQSPI_REG_CMDCTRL_RD_BYTES_LSB);
status = cqspi_exec_flash_cmd(cqspi, reg);
if (status)
return status;
reg = readl(reg_base + CQSPI_REG_CMDREADDATALOWER);
/* Put the read value into rx_buf */
read_len = (n_rx > 4) ? 4 : n_rx;
memcpy(rxbuf, ®, read_len);
rxbuf += read_len;
if (n_rx > 4) {
reg = readl(reg_base + CQSPI_REG_CMDREADDATAUPPER);
read_len = n_rx - read_len;
memcpy(rxbuf, ®, read_len);
}
return 0;
}
static int cqspi_command_write(struct spi_nor *nor, const u8 opcode,
const u8 *txbuf, const unsigned n_tx)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *reg_base = cqspi->iobase;
unsigned int reg;
unsigned int data;
int ret;
if (n_tx > 4 || (n_tx && !txbuf)) {
dev_err(nor->dev,
"Invalid input argument, cmdlen %d txbuf 0x%p\n",
n_tx, txbuf);
return -EINVAL;
}
reg = opcode << CQSPI_REG_CMDCTRL_OPCODE_LSB;
if (n_tx) {
reg |= (0x1 << CQSPI_REG_CMDCTRL_WR_EN_LSB);
reg |= ((n_tx - 1) & CQSPI_REG_CMDCTRL_WR_BYTES_MASK)
<< CQSPI_REG_CMDCTRL_WR_BYTES_LSB;
data = 0;
memcpy(&data, txbuf, n_tx);
writel(data, reg_base + CQSPI_REG_CMDWRITEDATALOWER);
}
ret = cqspi_exec_flash_cmd(cqspi, reg);
return ret;
}
static int cqspi_command_write_addr(struct spi_nor *nor,
const u8 opcode, const unsigned int addr)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *reg_base = cqspi->iobase;
unsigned int reg;
reg = opcode << CQSPI_REG_CMDCTRL_OPCODE_LSB;
reg |= (0x1 << CQSPI_REG_CMDCTRL_ADDR_EN_LSB);
reg |= ((nor->addr_width - 1) & CQSPI_REG_CMDCTRL_ADD_BYTES_MASK)
<< CQSPI_REG_CMDCTRL_ADD_BYTES_LSB;
writel(addr, reg_base + CQSPI_REG_CMDADDRESS);
return cqspi_exec_flash_cmd(cqspi, reg);
}
static int cqspi_indirect_read_setup(struct spi_nor *nor,
const unsigned int from_addr)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *reg_base = cqspi->iobase;
unsigned int dummy_clk = 0;
unsigned int reg;
writel(from_addr, reg_base + CQSPI_REG_INDIRECTRDSTARTADDR);
reg = nor->read_opcode << CQSPI_REG_RD_INSTR_OPCODE_LSB;
reg |= cqspi_calc_rdreg(nor, nor->read_opcode);
/* Setup dummy clock cycles */
dummy_clk = nor->read_dummy;
if (dummy_clk > CQSPI_DUMMY_CLKS_MAX)
dummy_clk = CQSPI_DUMMY_CLKS_MAX;
if (dummy_clk / 8) {
reg |= (1 << CQSPI_REG_RD_INSTR_MODE_EN_LSB);
/* Set mode bits high to ensure chip doesn't enter XIP */
writel(0xFF, reg_base + CQSPI_REG_MODE_BIT);
/* Need to subtract the mode byte (8 clocks). */
if (f_pdata->inst_width != CQSPI_INST_TYPE_QUAD)
dummy_clk -= 8;
if (dummy_clk)
reg |= (dummy_clk & CQSPI_REG_RD_INSTR_DUMMY_MASK)
<< CQSPI_REG_RD_INSTR_DUMMY_LSB;
}
writel(reg, reg_base + CQSPI_REG_RD_INSTR);
/* Set address width */
reg = readl(reg_base + CQSPI_REG_SIZE);
reg &= ~CQSPI_REG_SIZE_ADDRESS_MASK;
reg |= (nor->addr_width - 1);
writel(reg, reg_base + CQSPI_REG_SIZE);
return 0;
}
static int cqspi_indirect_read_execute(struct spi_nor *nor,
u8 *rxbuf, const unsigned n_rx)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *reg_base = cqspi->iobase;
void __iomem *ahb_base = cqspi->ahb_base;
unsigned int remaining = n_rx;
unsigned int bytes_to_read = 0;
int ret = 0;
writel(remaining, reg_base + CQSPI_REG_INDIRECTRDBYTES);
/* Clear all interrupts. */
writel(CQSPI_IRQ_STATUS_MASK, reg_base + CQSPI_REG_IRQSTATUS);
writel(CQSPI_IRQ_MASK_RD, reg_base + CQSPI_REG_IRQMASK);
reinit_completion(&cqspi->transfer_complete);
writel(CQSPI_REG_INDIRECTRD_START_MASK,
reg_base + CQSPI_REG_INDIRECTRD);
while (remaining > 0) {
ret = wait_for_completion_timeout(&cqspi->transfer_complete,
msecs_to_jiffies
(CQSPI_READ_TIMEOUT_MS));
bytes_to_read = cqspi_get_rd_sram_level(cqspi);
if (!ret && bytes_to_read == 0) {
dev_err(nor->dev, "Indirect read timeout, no bytes\n");
ret = -ETIMEDOUT;
goto failrd;
}
while (bytes_to_read != 0) {
bytes_to_read *= cqspi->fifo_width;
bytes_to_read = bytes_to_read > remaining ?
remaining : bytes_to_read;
readsl(ahb_base, rxbuf, DIV_ROUND_UP(bytes_to_read, 4));
rxbuf += bytes_to_read;
remaining -= bytes_to_read;
bytes_to_read = cqspi_get_rd_sram_level(cqspi);
}
if (remaining > 0)
reinit_completion(&cqspi->transfer_complete);
}
/* Check indirect done status */
ret = cqspi_wait_for_bit(reg_base + CQSPI_REG_INDIRECTRD,
CQSPI_REG_INDIRECTRD_DONE_MASK, 0);
if (ret) {
dev_err(nor->dev,
"Indirect read completion error (%i)\n", ret);
goto failrd;
}
/* Disable interrupt */
writel(0, reg_base + CQSPI_REG_IRQMASK);
/* Clear indirect completion status */
writel(CQSPI_REG_INDIRECTRD_DONE_MASK, reg_base + CQSPI_REG_INDIRECTRD);
return 0;
failrd:
/* Disable interrupt */
writel(0, reg_base + CQSPI_REG_IRQMASK);
/* Cancel the indirect read */
writel(CQSPI_REG_INDIRECTWR_CANCEL_MASK,
reg_base + CQSPI_REG_INDIRECTRD);
return ret;
}
static int cqspi_indirect_write_setup(struct spi_nor *nor,
const unsigned int to_addr)
{
unsigned int reg;
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *reg_base = cqspi->iobase;
/* Set opcode. */
reg = nor->program_opcode << CQSPI_REG_WR_INSTR_OPCODE_LSB;
writel(reg, reg_base + CQSPI_REG_WR_INSTR);
reg = cqspi_calc_rdreg(nor, nor->program_opcode);
writel(reg, reg_base + CQSPI_REG_RD_INSTR);
writel(to_addr, reg_base + CQSPI_REG_INDIRECTWRSTARTADDR);
reg = readl(reg_base + CQSPI_REG_SIZE);
reg &= ~CQSPI_REG_SIZE_ADDRESS_MASK;
reg |= (nor->addr_width - 1);
writel(reg, reg_base + CQSPI_REG_SIZE);
return 0;
}
static int cqspi_indirect_write_execute(struct spi_nor *nor,
const u8 *txbuf, const unsigned n_tx)
{
const unsigned int page_size = nor->page_size;
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *reg_base = cqspi->iobase;
unsigned int remaining = n_tx;
unsigned int write_bytes;
int ret;
writel(remaining, reg_base + CQSPI_REG_INDIRECTWRBYTES);
/* Clear all interrupts. */
writel(CQSPI_IRQ_STATUS_MASK, reg_base + CQSPI_REG_IRQSTATUS);
writel(CQSPI_IRQ_MASK_WR, reg_base + CQSPI_REG_IRQMASK);
reinit_completion(&cqspi->transfer_complete);
writel(CQSPI_REG_INDIRECTWR_START_MASK,
reg_base + CQSPI_REG_INDIRECTWR);
while (remaining > 0) {
write_bytes = remaining > page_size ? page_size : remaining;
writesl(cqspi->ahb_base, txbuf, DIV_ROUND_UP(write_bytes, 4));
ret = wait_for_completion_timeout(&cqspi->transfer_complete,
msecs_to_jiffies
(CQSPI_TIMEOUT_MS));
if (!ret) {
dev_err(nor->dev, "Indirect write timeout\n");
ret = -ETIMEDOUT;
goto failwr;
}
txbuf += write_bytes;
remaining -= write_bytes;
if (remaining > 0)
reinit_completion(&cqspi->transfer_complete);
}
/* Check indirect done status */
ret = cqspi_wait_for_bit(reg_base + CQSPI_REG_INDIRECTWR,
CQSPI_REG_INDIRECTWR_DONE_MASK, 0);
if (ret) {
dev_err(nor->dev,
"Indirect write completion error (%i)\n", ret);
goto failwr;
}
/* Disable interrupt. */
writel(0, reg_base + CQSPI_REG_IRQMASK);
/* Clear indirect completion status */
writel(CQSPI_REG_INDIRECTWR_DONE_MASK, reg_base + CQSPI_REG_INDIRECTWR);
cqspi_wait_idle(cqspi);
return 0;
failwr:
/* Disable interrupt. */
writel(0, reg_base + CQSPI_REG_IRQMASK);
/* Cancel the indirect write */
writel(CQSPI_REG_INDIRECTWR_CANCEL_MASK,
reg_base + CQSPI_REG_INDIRECTWR);
return ret;
}
static void cqspi_chipselect(struct spi_nor *nor)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *reg_base = cqspi->iobase;
unsigned int chip_select = f_pdata->cs;
unsigned int reg;
reg = readl(reg_base + CQSPI_REG_CONFIG);
if (cqspi->is_decoded_cs) {
reg |= CQSPI_REG_CONFIG_DECODE_MASK;
} else {
reg &= ~CQSPI_REG_CONFIG_DECODE_MASK;
/* Convert CS if without decoder.
* CS0 to 4b'1110
* CS1 to 4b'1101
* CS2 to 4b'1011
* CS3 to 4b'0111
*/
chip_select = 0xF & ~(1 << chip_select);
}
reg &= ~(CQSPI_REG_CONFIG_CHIPSELECT_MASK
<< CQSPI_REG_CONFIG_CHIPSELECT_LSB);
reg |= (chip_select & CQSPI_REG_CONFIG_CHIPSELECT_MASK)
<< CQSPI_REG_CONFIG_CHIPSELECT_LSB;
writel(reg, reg_base + CQSPI_REG_CONFIG);
}
static void cqspi_configure_cs_and_sizes(struct spi_nor *nor)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *iobase = cqspi->iobase;
unsigned int reg;
/* configure page size and block size. */
reg = readl(iobase + CQSPI_REG_SIZE);
reg &= ~(CQSPI_REG_SIZE_PAGE_MASK << CQSPI_REG_SIZE_PAGE_LSB);
reg &= ~(CQSPI_REG_SIZE_BLOCK_MASK << CQSPI_REG_SIZE_BLOCK_LSB);
reg &= ~CQSPI_REG_SIZE_ADDRESS_MASK;
reg |= (nor->page_size << CQSPI_REG_SIZE_PAGE_LSB);
reg |= (ilog2(nor->mtd.erasesize) << CQSPI_REG_SIZE_BLOCK_LSB);
reg |= (nor->addr_width - 1);
writel(reg, iobase + CQSPI_REG_SIZE);
/* configure the chip select */
cqspi_chipselect(nor);
/* Store the new configuration of the controller */
cqspi->current_page_size = nor->page_size;
cqspi->current_erase_size = nor->mtd.erasesize;
cqspi->current_addr_width = nor->addr_width;
}
static unsigned int calculate_ticks_for_ns(const unsigned int ref_clk_hz,
const unsigned int ns_val)
{
unsigned int ticks;
ticks = ref_clk_hz / 1000; /* kHz */
ticks = DIV_ROUND_UP(ticks * ns_val, 1000000);
return ticks;
}
static void cqspi_delay(struct spi_nor *nor)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
void __iomem *iobase = cqspi->iobase;
const unsigned int ref_clk_hz = cqspi->master_ref_clk_hz;
unsigned int tshsl, tchsh, tslch, tsd2d;
unsigned int reg;
unsigned int tsclk;
/* calculate the number of ref ticks for one sclk tick */
tsclk = DIV_ROUND_UP(ref_clk_hz, cqspi->sclk);
tshsl = calculate_ticks_for_ns(ref_clk_hz, f_pdata->tshsl_ns);
/* this particular value must be at least one sclk */
if (tshsl < tsclk)
tshsl = tsclk;
tchsh = calculate_ticks_for_ns(ref_clk_hz, f_pdata->tchsh_ns);
tslch = calculate_ticks_for_ns(ref_clk_hz, f_pdata->tslch_ns);
tsd2d = calculate_ticks_for_ns(ref_clk_hz, f_pdata->tsd2d_ns);
reg = (tshsl & CQSPI_REG_DELAY_TSHSL_MASK)
<< CQSPI_REG_DELAY_TSHSL_LSB;
reg |= (tchsh & CQSPI_REG_DELAY_TCHSH_MASK)
<< CQSPI_REG_DELAY_TCHSH_LSB;
reg |= (tslch & CQSPI_REG_DELAY_TSLCH_MASK)
<< CQSPI_REG_DELAY_TSLCH_LSB;
reg |= (tsd2d & CQSPI_REG_DELAY_TSD2D_MASK)
<< CQSPI_REG_DELAY_TSD2D_LSB;
writel(reg, iobase + CQSPI_REG_DELAY);
}
static void cqspi_config_baudrate_div(struct cqspi_st *cqspi)
{
const unsigned int ref_clk_hz = cqspi->master_ref_clk_hz;
void __iomem *reg_base = cqspi->iobase;
u32 reg, div;
/* Recalculate the baudrate divisor based on QSPI specification. */
div = DIV_ROUND_UP(ref_clk_hz, 2 * cqspi->sclk) - 1;
reg = readl(reg_base + CQSPI_REG_CONFIG);
reg &= ~(CQSPI_REG_CONFIG_BAUD_MASK << CQSPI_REG_CONFIG_BAUD_LSB);
reg |= (div & CQSPI_REG_CONFIG_BAUD_MASK) << CQSPI_REG_CONFIG_BAUD_LSB;
writel(reg, reg_base + CQSPI_REG_CONFIG);
}
static void cqspi_readdata_capture(struct cqspi_st *cqspi,
const unsigned int bypass,
const unsigned int delay)
{
void __iomem *reg_base = cqspi->iobase;
unsigned int reg;
reg = readl(reg_base + CQSPI_REG_READCAPTURE);
if (bypass)
reg |= (1 << CQSPI_REG_READCAPTURE_BYPASS_LSB);
else
reg &= ~(1 << CQSPI_REG_READCAPTURE_BYPASS_LSB);
reg &= ~(CQSPI_REG_READCAPTURE_DELAY_MASK
<< CQSPI_REG_READCAPTURE_DELAY_LSB);
reg |= (delay & CQSPI_REG_READCAPTURE_DELAY_MASK)
<< CQSPI_REG_READCAPTURE_DELAY_LSB;
writel(reg, reg_base + CQSPI_REG_READCAPTURE);
}
static void cqspi_controller_enable(struct cqspi_st *cqspi, bool enable)
{
void __iomem *reg_base = cqspi->iobase;
unsigned int reg;
reg = readl(reg_base + CQSPI_REG_CONFIG);
if (enable)
reg |= CQSPI_REG_CONFIG_ENABLE_MASK;
else
reg &= ~CQSPI_REG_CONFIG_ENABLE_MASK;
writel(reg, reg_base + CQSPI_REG_CONFIG);
}
static void cqspi_configure(struct spi_nor *nor)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
const unsigned int sclk = f_pdata->clk_rate;
int switch_cs = (cqspi->current_cs != f_pdata->cs);
int switch_ck = (cqspi->sclk != sclk);
if ((cqspi->current_page_size != nor->page_size) ||
(cqspi->current_erase_size != nor->mtd.erasesize) ||
(cqspi->current_addr_width != nor->addr_width))
switch_cs = 1;
if (switch_cs || switch_ck)
cqspi_controller_enable(cqspi, 0);
/* Switch chip select. */
if (switch_cs) {
cqspi->current_cs = f_pdata->cs;
cqspi_configure_cs_and_sizes(nor);
}
/* Setup baudrate divisor and delays */
if (switch_ck) {
cqspi->sclk = sclk;
cqspi_config_baudrate_div(cqspi);
cqspi_delay(nor);
cqspi_readdata_capture(cqspi, 1, f_pdata->read_delay);
}
if (switch_cs || switch_ck)
cqspi_controller_enable(cqspi, 1);
}
static int cqspi_set_protocol(struct spi_nor *nor, const int read)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
f_pdata->inst_width = CQSPI_INST_TYPE_SINGLE;
f_pdata->addr_width = CQSPI_INST_TYPE_SINGLE;
f_pdata->data_width = CQSPI_INST_TYPE_SINGLE;
if (read) {
switch (nor->flash_read) {
case SPI_NOR_NORMAL:
case SPI_NOR_FAST:
f_pdata->data_width = CQSPI_INST_TYPE_SINGLE;
break;
case SPI_NOR_DUAL:
f_pdata->data_width = CQSPI_INST_TYPE_DUAL;
break;
case SPI_NOR_QUAD:
f_pdata->data_width = CQSPI_INST_TYPE_QUAD;
break;
default:
return -EINVAL;
}
}
cqspi_configure(nor);
return 0;
}
static ssize_t cqspi_write(struct spi_nor *nor, loff_t to,
size_t len, const u_char *buf)
{
int ret;
ret = cqspi_set_protocol(nor, 0);
if (ret)
return ret;
ret = cqspi_indirect_write_setup(nor, to);
if (ret)
return ret;
ret = cqspi_indirect_write_execute(nor, buf, len);
if (ret)
return ret;
return (ret < 0) ? ret : len;
}
static ssize_t cqspi_read(struct spi_nor *nor, loff_t from,
size_t len, u_char *buf)
{
int ret;
ret = cqspi_set_protocol(nor, 1);
if (ret)
return ret;
ret = cqspi_indirect_read_setup(nor, from);
if (ret)
return ret;
ret = cqspi_indirect_read_execute(nor, buf, len);
if (ret)
return ret;
return (ret < 0) ? ret : len;
}
static int cqspi_erase(struct spi_nor *nor, loff_t offs)
{
int ret;
ret = cqspi_set_protocol(nor, 0);
if (ret)
return ret;
/* Send write enable, then erase commands. */
ret = nor->write_reg(nor, SPINOR_OP_WREN, NULL, 0);
if (ret)
return ret;
/* Set up command buffer. */
ret = cqspi_command_write_addr(nor, nor->erase_opcode, offs);
if (ret)
return ret;
return 0;
}
static int cqspi_prep(struct spi_nor *nor, enum spi_nor_ops ops)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
mutex_lock(&cqspi->bus_mutex);
return 0;
}
static void cqspi_unprep(struct spi_nor *nor, enum spi_nor_ops ops)
{
struct cqspi_flash_pdata *f_pdata = nor->priv;
struct cqspi_st *cqspi = f_pdata->cqspi;
mutex_unlock(&cqspi->bus_mutex);
}
static int cqspi_read_reg(struct spi_nor *nor, u8 opcode, u8 *buf, int len)
{
int ret;
ret = cqspi_set_protocol(nor, 0);
if (!ret)
ret = cqspi_command_read(nor, &opcode, 1, buf, len);
return ret;
}
static int cqspi_write_reg(struct spi_nor *nor, u8 opcode, u8 *buf, int len)
{
int ret;
ret = cqspi_set_protocol(nor, 0);
if (!ret)
ret = cqspi_command_write(nor, opcode, buf, len);
return ret;
}
static int cqspi_of_get_flash_pdata(struct platform_device *pdev,
struct cqspi_flash_pdata *f_pdata,
struct device_node *np)
{
if (of_property_read_u32(np, "cdns,read-delay", &f_pdata->read_delay)) {
dev_err(&pdev->dev, "couldn't determine read-delay\n");
return -ENXIO;
}
if (of_property_read_u32(np, "cdns,tshsl-ns", &f_pdata->tshsl_ns)) {
dev_err(&pdev->dev, "couldn't determine tshsl-ns\n");
return -ENXIO;
}
if (of_property_read_u32(np, "cdns,tsd2d-ns", &f_pdata->tsd2d_ns)) {
dev_err(&pdev->dev, "couldn't determine tsd2d-ns\n");
return -ENXIO;
}
if (of_property_read_u32(np, "cdns,tchsh-ns", &f_pdata->tchsh_ns)) {
dev_err(&pdev->dev, "couldn't determine tchsh-ns\n");
return -ENXIO;
}
if (of_property_read_u32(np, "cdns,tslch-ns", &f_pdata->tslch_ns)) {
dev_err(&pdev->dev, "couldn't determine tslch-ns\n");
return -ENXIO;
}
if (of_property_read_u32(np, "spi-max-frequency", &f_pdata->clk_rate)) {
dev_err(&pdev->dev, "couldn't determine spi-max-frequency\n");
return -ENXIO;
}
return 0;
}
static int cqspi_of_get_pdata(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
struct cqspi_st *cqspi = platform_get_drvdata(pdev);
cqspi->is_decoded_cs = of_property_read_bool(np, "cdns,is-decoded-cs");
if (of_property_read_u32(np, "cdns,fifo-depth", &cqspi->fifo_depth)) {
dev_err(&pdev->dev, "couldn't determine fifo-depth\n");
return -ENXIO;
}
if (of_property_read_u32(np, "cdns,fifo-width", &cqspi->fifo_width)) {
dev_err(&pdev->dev, "couldn't determine fifo-width\n");
return -ENXIO;
}
if (of_property_read_u32(np, "cdns,trigger-address",
&cqspi->trigger_address)) {
dev_err(&pdev->dev, "couldn't determine trigger-address\n");
return -ENXIO;
}
return 0;
}
static void cqspi_controller_init(struct cqspi_st *cqspi)
{
cqspi_controller_enable(cqspi, 0);
/* Configure the remap address register, no remap */
writel(0, cqspi->iobase + CQSPI_REG_REMAP);
/* Disable all interrupts. */
writel(0, cqspi->iobase + CQSPI_REG_IRQMASK);
/* Configure the SRAM split to 1:1 . */
writel(cqspi->fifo_depth / 2, cqspi->iobase + CQSPI_REG_SRAMPARTITION);
/* Load indirect trigger address. */
writel(cqspi->trigger_address,
cqspi->iobase + CQSPI_REG_INDIRECTTRIGGER);
/* Program read watermark -- 1/2 of the FIFO. */
writel(cqspi->fifo_depth * cqspi->fifo_width / 2,
cqspi->iobase + CQSPI_REG_INDIRECTRDWATERMARK);
/* Program write watermark -- 1/8 of the FIFO. */
writel(cqspi->fifo_depth * cqspi->fifo_width / 8,
cqspi->iobase + CQSPI_REG_INDIRECTWRWATERMARK);
cqspi_controller_enable(cqspi, 1);
}
static int cqspi_setup_flash(struct cqspi_st *cqspi, struct device_node *np)
{
struct platform_device *pdev = cqspi->pdev;
struct device *dev = &pdev->dev;
struct cqspi_flash_pdata *f_pdata;
struct spi_nor *nor;
struct mtd_info *mtd;
unsigned int cs;
int i, ret;
/* Get flash device data */
for_each_available_child_of_node(dev->of_node, np) {
if (of_property_read_u32(np, "reg", &cs)) {
dev_err(dev, "Couldn't determine chip select.\n");
goto err;
}
if (cs >= CQSPI_MAX_CHIPSELECT) {
dev_err(dev, "Chip select %d out of range.\n", cs);
goto err;
}
f_pdata = &cqspi->f_pdata[cs];
f_pdata->cqspi = cqspi;
f_pdata->cs = cs;
ret = cqspi_of_get_flash_pdata(pdev, f_pdata, np);
if (ret)
goto err;
nor = &f_pdata->nor;
mtd = &nor->mtd;
mtd->priv = nor;
nor->dev = dev;
spi_nor_set_flash_node(nor, np);
nor->priv = f_pdata;
nor->read_reg = cqspi_read_reg;
nor->write_reg = cqspi_write_reg;
nor->read = cqspi_read;
nor->write = cqspi_write;
nor->erase = cqspi_erase;
nor->prepare = cqspi_prep;
nor->unprepare = cqspi_unprep;
mtd->name = devm_kasprintf(dev, GFP_KERNEL, "%s.%d",
dev_name(dev), cs);
if (!mtd->name) {
ret = -ENOMEM;
goto err;
}
ret = spi_nor_scan(nor, NULL, SPI_NOR_QUAD);
if (ret)
goto err;
ret = mtd_device_register(mtd, NULL, 0);
if (ret)
goto err;
f_pdata->registered = true;
}
return 0;
err:
for (i = 0; i < CQSPI_MAX_CHIPSELECT; i++)
if (cqspi->f_pdata[i].registered)
mtd_device_unregister(&cqspi->f_pdata[i].nor.mtd);
return ret;
}
static int cqspi_probe(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
struct device *dev = &pdev->dev;
struct cqspi_st *cqspi;
struct resource *res;
struct resource *res_ahb;
int ret;
int irq;
cqspi = devm_kzalloc(dev, sizeof(*cqspi), GFP_KERNEL);
if (!cqspi)
return -ENOMEM;
mutex_init(&cqspi->bus_mutex);
cqspi->pdev = pdev;
platform_set_drvdata(pdev, cqspi);
/* Obtain configuration from OF. */
ret = cqspi_of_get_pdata(pdev);
if (ret) {
dev_err(dev, "Cannot get mandatory OF data.\n");
return -ENODEV;
}
/* Obtain QSPI clock. */
cqspi->clk = devm_clk_get(dev, NULL);
if (IS_ERR(cqspi->clk)) {
dev_err(dev, "Cannot claim QSPI clock.\n");
return PTR_ERR(cqspi->clk);
}
/* Obtain and remap controller address. */
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
cqspi->iobase = devm_ioremap_resource(dev, res);
if (IS_ERR(cqspi->iobase)) {
dev_err(dev, "Cannot remap controller address.\n");
return PTR_ERR(cqspi->iobase);
}
/* Obtain and remap AHB address. */
res_ahb = platform_get_resource(pdev, IORESOURCE_MEM, 1);
cqspi->ahb_base = devm_ioremap_resource(dev, res_ahb);
if (IS_ERR(cqspi->ahb_base)) {
dev_err(dev, "Cannot remap AHB address.\n");
return PTR_ERR(cqspi->ahb_base);
}
init_completion(&cqspi->transfer_complete);
/* Obtain IRQ line. */
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
dev_err(dev, "Cannot obtain IRQ.\n");
return -ENXIO;
}
ret = clk_prepare_enable(cqspi->clk);
if (ret) {
dev_err(dev, "Cannot enable QSPI clock.\n");
return ret;
}
cqspi->master_ref_clk_hz = clk_get_rate(cqspi->clk);
ret = devm_request_irq(dev, irq, cqspi_irq_handler, 0,
pdev->name, cqspi);
if (ret) {
dev_err(dev, "Cannot request IRQ.\n");
goto probe_irq_failed;
}
cqspi_wait_idle(cqspi);
cqspi_controller_init(cqspi);
cqspi->current_cs = -1;
cqspi->sclk = 0;
ret = cqspi_setup_flash(cqspi, np);
if (ret) {
dev_err(dev, "Cadence QSPI NOR probe failed %d\n", ret);
goto probe_setup_failed;
}
return ret;
probe_irq_failed:
cqspi_controller_enable(cqspi, 0);
probe_setup_failed:
clk_disable_unprepare(cqspi->clk);
return ret;
}
static int cqspi_remove(struct platform_device *pdev)
{
struct cqspi_st *cqspi = platform_get_drvdata(pdev);
int i;
for (i = 0; i < CQSPI_MAX_CHIPSELECT; i++)
if (cqspi->f_pdata[i].registered)
mtd_device_unregister(&cqspi->f_pdata[i].nor.mtd);
cqspi_controller_enable(cqspi, 0);
clk_disable_unprepare(cqspi->clk);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int cqspi_suspend(struct device *dev)
{
struct cqspi_st *cqspi = dev_get_drvdata(dev);
cqspi_controller_enable(cqspi, 0);
return 0;
}
static int cqspi_resume(struct device *dev)
{
struct cqspi_st *cqspi = dev_get_drvdata(dev);
cqspi_controller_enable(cqspi, 1);
return 0;
}
static const struct dev_pm_ops cqspi__dev_pm_ops = {
.suspend = cqspi_suspend,
.resume = cqspi_resume,
};
#define CQSPI_DEV_PM_OPS (&cqspi__dev_pm_ops)
#else
#define CQSPI_DEV_PM_OPS NULL
#endif
static struct of_device_id const cqspi_dt_ids[] = {
{.compatible = "cdns,qspi-nor",},
{ /* end of table */ }
};
MODULE_DEVICE_TABLE(of, cqspi_dt_ids);
static struct platform_driver cqspi_platform_driver = {
.probe = cqspi_probe,
.remove = cqspi_remove,
.driver = {
.name = CQSPI_NAME,
.pm = CQSPI_DEV_PM_OPS,
.of_match_table = cqspi_dt_ids,
},
};
module_platform_driver(cqspi_platform_driver);
MODULE_DESCRIPTION("Cadence QSPI Controller Driver");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:" CQSPI_NAME);
MODULE_AUTHOR("Ley Foon Tan <lftan@altera.com>");
MODULE_AUTHOR("Graham Moore <grmoore@opensource.altera.com>");
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4888_0 |
crossvul-cpp_data_bad_2540_1 | /* $Id: upnpreplyparse.c,v 1.19 2015/07/15 10:29:11 nanard Exp $ */
/* MiniUPnP project
* http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/
* (c) 2006-2015 Thomas Bernard
* This software is subject to the conditions detailed
* in the LICENCE file provided within the distribution */
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "upnpreplyparse.h"
#include "minixml.h"
static void
NameValueParserStartElt(void * d, const char * name, int l)
{
struct NameValueParserData * data = (struct NameValueParserData *)d;
data->topelt = 1;
if(l>63)
l = 63;
memcpy(data->curelt, name, l);
data->curelt[l] = '\0';
data->cdata = NULL;
data->cdatalen = 0;
}
static void
NameValueParserEndElt(void * d, const char * name, int l)
{
struct NameValueParserData * data = (struct NameValueParserData *)d;
struct NameValue * nv;
(void)name;
(void)l;
if(!data->topelt)
return;
if(strcmp(data->curelt, "NewPortListing") != 0)
{
int l;
/* standard case. Limited to n chars strings */
l = data->cdatalen;
nv = malloc(sizeof(struct NameValue));
if(nv == NULL)
{
/* malloc error */
#ifdef DEBUG
fprintf(stderr, "%s: error allocating memory",
"NameValueParserEndElt");
#endif /* DEBUG */
return;
}
if(l>=(int)sizeof(nv->value))
l = sizeof(nv->value) - 1;
strncpy(nv->name, data->curelt, 64);
nv->name[63] = '\0';
if(data->cdata != NULL)
{
memcpy(nv->value, data->cdata, l);
nv->value[l] = '\0';
}
else
{
nv->value[0] = '\0';
}
nv->l_next = data->l_head; /* insert in list */
data->l_head = nv;
}
data->cdata = NULL;
data->cdatalen = 0;
data->topelt = 0;
}
static void
NameValueParserGetData(void * d, const char * datas, int l)
{
struct NameValueParserData * data = (struct NameValueParserData *)d;
if(strcmp(data->curelt, "NewPortListing") == 0)
{
/* specific case for NewPortListing which is a XML Document */
data->portListing = malloc(l + 1);
if(!data->portListing)
{
/* malloc error */
#ifdef DEBUG
fprintf(stderr, "%s: error allocating memory",
"NameValueParserGetData");
#endif /* DEBUG */
return;
}
memcpy(data->portListing, datas, l);
data->portListing[l] = '\0';
data->portListingLength = l;
}
else
{
/* standard case. */
data->cdata = datas;
data->cdatalen = l;
}
}
void
ParseNameValue(const char * buffer, int bufsize,
struct NameValueParserData * data)
{
struct xmlparser parser;
data->l_head = NULL;
data->portListing = NULL;
data->portListingLength = 0;
/* init xmlparser object */
parser.xmlstart = buffer;
parser.xmlsize = bufsize;
parser.data = data;
parser.starteltfunc = NameValueParserStartElt;
parser.endeltfunc = NameValueParserEndElt;
parser.datafunc = NameValueParserGetData;
parser.attfunc = 0;
parsexml(&parser);
}
void
ClearNameValueList(struct NameValueParserData * pdata)
{
struct NameValue * nv;
if(pdata->portListing)
{
free(pdata->portListing);
pdata->portListing = NULL;
pdata->portListingLength = 0;
}
while((nv = pdata->l_head) != NULL)
{
pdata->l_head = nv->l_next;
free(nv);
}
}
char *
GetValueFromNameValueList(struct NameValueParserData * pdata,
const char * Name)
{
struct NameValue * nv;
char * p = NULL;
for(nv = pdata->l_head;
(nv != NULL) && (p == NULL);
nv = nv->l_next)
{
if(strcmp(nv->name, Name) == 0)
p = nv->value;
}
return p;
}
#if 0
/* useless now that minixml ignores namespaces by itself */
char *
GetValueFromNameValueListIgnoreNS(struct NameValueParserData * pdata,
const char * Name)
{
struct NameValue * nv;
char * p = NULL;
char * pname;
for(nv = pdata->head.lh_first;
(nv != NULL) && (p == NULL);
nv = nv->entries.le_next)
{
pname = strrchr(nv->name, ':');
if(pname)
pname++;
else
pname = nv->name;
if(strcmp(pname, Name)==0)
p = nv->value;
}
return p;
}
#endif
/* debug all-in-one function
* do parsing then display to stdout */
#ifdef DEBUG
void
DisplayNameValueList(char * buffer, int bufsize)
{
struct NameValueParserData pdata;
struct NameValue * nv;
ParseNameValue(buffer, bufsize, &pdata);
for(nv = pdata.l_head;
nv != NULL;
nv = nv->l_next)
{
printf("%s = %s\n", nv->name, nv->value);
}
ClearNameValueList(&pdata);
}
#endif /* DEBUG */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2540_1 |
crossvul-cpp_data_good_343_1 | /*
* Support for ePass2003 smart cards
*
* Copyright (C) 2008, Weitao Sun <weitao@ftsafe.com>
* Copyright (C) 2011, Xiaoshuo Wu <xiaoshuo@ftsafe.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef ENABLE_SM /* empty file without SM enabled */
#ifdef ENABLE_OPENSSL /* empty file without openssl */
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
#include "internal.h"
#include "asn1.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
static struct sc_atr_table epass2003_atrs[] = {
/* This is a FIPS certified card using SCP01 security messaging. */
{"3B:9F:95:81:31:FE:9F:00:66:46:53:05:10:00:11:71:df:00:00:00:6a:82:5e",
"FF:FF:FF:FF:FF:00:FF:FF:FF:FF:FF:FF:00:00:00:ff:00:ff:ff:00:00:00:00",
"FTCOS/ePass2003", SC_CARD_TYPE_ENTERSAFE_FTCOS_EPASS2003, 0, NULL },
{NULL, NULL, NULL, 0, 0, NULL}
};
static struct sc_card_operations *iso_ops = NULL;
static struct sc_card_operations epass2003_ops;
static struct sc_card_driver epass2003_drv = {
"epass2003",
"epass2003",
&epass2003_ops,
NULL, 0, NULL
};
#define KEY_TYPE_AES 0x01 /* FIPS mode */
#define KEY_TYPE_DES 0x02 /* Non-FIPS mode */
#define KEY_LEN_AES 16
#define KEY_LEN_DES 8
#define KEY_LEN_DES3 24
#define HASH_LEN 24
static unsigned char PIN_ID[2] = { ENTERSAFE_USER_PIN_ID, ENTERSAFE_SO_PIN_ID };
/*0x00:plain; 0x01:scp01 sm*/
#define SM_PLAIN 0x00
#define SM_SCP01 0x01
static unsigned char g_init_key_enc[16] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
0x0D, 0x0E, 0x0F, 0x10
};
static unsigned char g_init_key_mac[16] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
0x0D, 0x0E, 0x0F, 0x10
};
static unsigned char g_random[8] = {
0xBF, 0xC3, 0x29, 0x11, 0xC7, 0x18, 0xC3, 0x40
};
typedef struct epass2003_exdata_st {
unsigned char sm; /* SM_PLAIN or SM_SCP01 */
unsigned char smtype; /* KEY_TYPE_AES or KEY_TYPE_DES */
unsigned char sk_enc[16]; /* encrypt session key */
unsigned char sk_mac[16]; /* mac session key */
unsigned char icv_mac[16]; /* instruction counter vector(for sm) */
unsigned char currAlg; /* current Alg */
unsigned int ecAlgFlags; /* Ec Alg mechanism type*/
} epass2003_exdata;
#define REVERSE_ORDER4(x) ( \
((unsigned long)x & 0xFF000000)>> 24 | \
((unsigned long)x & 0x00FF0000)>> 8 | \
((unsigned long)x & 0x0000FF00)<< 8 | \
((unsigned long)x & 0x000000FF)<< 24)
static const struct sc_card_error epass2003_errors[] = {
{ 0x6200, SC_ERROR_CARD_CMD_FAILED, "Warning: no information given, non-volatile memory is unchanged" },
{ 0x6281, SC_ERROR_CORRUPTED_DATA, "Part of returned data may be corrupted" },
{ 0x6282, SC_ERROR_FILE_END_REACHED, "End of file/record reached before reading Le bytes" },
{ 0x6283, SC_ERROR_CARD_CMD_FAILED, "Selected file invalidated" },
{ 0x6284, SC_ERROR_CARD_CMD_FAILED, "FCI not formatted according to ISO 7816-4" },
{ 0x6300, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C1, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. One tries left"},
{ 0x63C2, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. Two tries left"},
{ 0x63C3, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C4, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C5, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C6, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C7, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C8, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C9, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63CA, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x6381, SC_ERROR_CARD_CMD_FAILED, "Warning: file filled up by last write" },
{ 0x6581, SC_ERROR_MEMORY_FAILURE, "Memory failure" },
{ 0x6700, SC_ERROR_WRONG_LENGTH, "Wrong length" },
{ 0x6800, SC_ERROR_NO_CARD_SUPPORT, "Functions in CLA not supported" },
{ 0x6881, SC_ERROR_NO_CARD_SUPPORT, "Logical channel not supported" },
{ 0x6882, SC_ERROR_NO_CARD_SUPPORT, "Secure messaging not supported" },
{ 0x6900, SC_ERROR_NOT_ALLOWED, "Command not allowed" },
{ 0x6981, SC_ERROR_CARD_CMD_FAILED, "Command incompatible with file structure" },
{ 0x6982, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Security status not satisfied" },
{ 0x6983, SC_ERROR_AUTH_METHOD_BLOCKED, "Authentication method blocked" },
{ 0x6984, SC_ERROR_REF_DATA_NOT_USABLE, "Referenced data not usable" },
{ 0x6985, SC_ERROR_NOT_ALLOWED, "Conditions of use not satisfied" },
{ 0x6986, SC_ERROR_NOT_ALLOWED, "Command not allowed (no current EF)" },
{ 0x6987, SC_ERROR_INCORRECT_PARAMETERS,"Expected SM data objects missing" },
{ 0x6988, SC_ERROR_INCORRECT_PARAMETERS,"SM data objects incorrect" },
{ 0x6A00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" },
{ 0x6A80, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters in the data field" },
{ 0x6A81, SC_ERROR_NO_CARD_SUPPORT, "Function not supported" },
{ 0x6A82, SC_ERROR_FILE_NOT_FOUND, "File not found" },
{ 0x6A83, SC_ERROR_RECORD_NOT_FOUND, "Record not found" },
{ 0x6A84, SC_ERROR_NOT_ENOUGH_MEMORY, "Not enough memory space in the file" },
{ 0x6A85, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with TLV structure" },
{ 0x6A86, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters P1-P2" },
{ 0x6A87, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with P1-P2" },
{ 0x6A88, SC_ERROR_DATA_OBJECT_NOT_FOUND,"Referenced data not found" },
{ 0x6A89, SC_ERROR_FILE_ALREADY_EXISTS, "File already exists"},
{ 0x6A8A, SC_ERROR_FILE_ALREADY_EXISTS, "DF name already exists"},
{ 0x6B00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" },
{ 0x6D00, SC_ERROR_INS_NOT_SUPPORTED, "Instruction code not supported or invalid" },
{ 0x6E00, SC_ERROR_CLASS_NOT_SUPPORTED, "Class not supported" },
{ 0x6F00, SC_ERROR_CARD_CMD_FAILED, "No precise diagnosis" },
{ 0x9000,SC_SUCCESS, NULL }
};
static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu);
static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out);
int epass2003_refresh(struct sc_card *card);
static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType);
static int
epass2003_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2)
{
const int err_count = sizeof(epass2003_errors)/sizeof(epass2003_errors[0]);
int i;
/* Handle special cases here */
if (sw1 == 0x6C) {
sc_log(card->ctx, "Wrong length; correct length is %d", sw2);
return SC_ERROR_WRONG_LENGTH;
}
for (i = 0; i < err_count; i++) {
if (epass2003_errors[i].SWs == ((sw1 << 8) | sw2)) {
sc_log(card->ctx, "%s", epass2003_errors[i].errorstr);
return epass2003_errors[i].errorno;
}
}
sc_log(card->ctx, "Unknown SWs; SW1=%02X, SW2=%02X", sw1, sw2);
return SC_ERROR_CARD_CMD_FAILED;
}
static int
sc_transmit_apdu_t(sc_card_t *card, sc_apdu_t *apdu)
{
int r = sc_transmit_apdu(card, apdu);
if ( ((0x69 == apdu->sw1) && (0x85 == apdu->sw2)) || ((0x69 == apdu->sw1) && (0x88 == apdu->sw2)))
{
epass2003_refresh(card);
r = sc_transmit_apdu(card, apdu);
}
return r;
}
static int
openssl_enc(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv,
const unsigned char *input, size_t length, unsigned char *output)
{
int r = SC_ERROR_INTERNAL;
EVP_CIPHER_CTX * ctx = NULL;
int outl = 0;
int outl_tmp = 0;
unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 };
memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH);
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
goto out;
EVP_EncryptInit_ex(ctx, cipher, NULL, key, iv_tmp);
EVP_CIPHER_CTX_set_padding(ctx, 0);
if (!EVP_EncryptUpdate(ctx, output, &outl, input, length))
goto out;
if (!EVP_EncryptFinal_ex(ctx, output + outl, &outl_tmp))
goto out;
r = SC_SUCCESS;
out:
if (ctx)
EVP_CIPHER_CTX_free(ctx);
return r;
}
static int
openssl_dec(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv,
const unsigned char *input, size_t length, unsigned char *output)
{
int r = SC_ERROR_INTERNAL;
EVP_CIPHER_CTX * ctx = NULL;
int outl = 0;
int outl_tmp = 0;
unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 };
memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH);
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
goto out;
EVP_DecryptInit_ex(ctx, cipher, NULL, key, iv_tmp);
EVP_CIPHER_CTX_set_padding(ctx, 0);
if (!EVP_DecryptUpdate(ctx, output, &outl, input, length))
goto out;
if (!EVP_DecryptFinal_ex(ctx, output + outl, &outl_tmp))
goto out;
r = SC_SUCCESS;
out:
if (ctx)
EVP_CIPHER_CTX_free(ctx);
return r;
}
static int
aes128_encrypt_ecb(const unsigned char *key, int keysize,
const unsigned char *input, size_t length, unsigned char *output)
{
unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 };
return openssl_enc(EVP_aes_128_ecb(), key, iv, input, length, output);
}
static int
aes128_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_enc(EVP_aes_128_cbc(), key, iv, input, length, output);
}
static int
aes128_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dec(EVP_aes_128_cbc(), key, iv, input, length, output);
}
static int
des3_encrypt_ecb(const unsigned char *key, int keysize,
const unsigned char *input, int length, unsigned char *output)
{
unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 };
unsigned char bKey[24] = { 0 };
if (keysize == 16) {
memcpy(&bKey[0], key, 16);
memcpy(&bKey[16], key, 8);
}
else {
memcpy(&bKey[0], key, 24);
}
return openssl_enc(EVP_des_ede3(), bKey, iv, input, length, output);
}
static int
des3_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
unsigned char bKey[24] = { 0 };
if (keysize == 16) {
memcpy(&bKey[0], key, 16);
memcpy(&bKey[16], key, 8);
}
else {
memcpy(&bKey[0], key, 24);
}
return openssl_enc(EVP_des_ede3_cbc(), bKey, iv, input, length, output);
}
static int
des3_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
unsigned char bKey[24] = { 0 };
if (keysize == 16) {
memcpy(&bKey[0], key, 16);
memcpy(&bKey[16], key, 8);
}
else {
memcpy(&bKey[0], key, 24);
}
return openssl_dec(EVP_des_ede3_cbc(), bKey, iv, input, length, output);
}
static int
des_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_enc(EVP_des_cbc(), key, iv, input, length, output);
}
static int
des_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dec(EVP_des_cbc(), key, iv, input, length, output);
}
static int
openssl_dig(const EVP_MD * digest, const unsigned char *input, size_t length,
unsigned char *output)
{
int r = 0;
EVP_MD_CTX *ctx = NULL;
unsigned outl = 0;
ctx = EVP_MD_CTX_create();
if (ctx == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
EVP_MD_CTX_init(ctx);
EVP_DigestInit_ex(ctx, digest, NULL);
if (!EVP_DigestUpdate(ctx, input, length)) {
r = SC_ERROR_INTERNAL;
goto err;
}
if (!EVP_DigestFinal_ex(ctx, output, &outl)) {
r = SC_ERROR_INTERNAL;
goto err;
}
r = SC_SUCCESS;
err:
if (ctx)
EVP_MD_CTX_destroy(ctx);
return r;
}
static int
sha1_digest(const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dig(EVP_sha1(), input, length, output);
}
static int
sha256_digest(const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dig(EVP_sha256(), input, length, output);
}
static int
gen_init_key(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac,
unsigned char *result, unsigned char key_type)
{
int r;
struct sc_apdu apdu;
unsigned char data[256] = { 0 };
unsigned char tmp_sm;
unsigned long blocksize = 0;
unsigned char cryptogram[256] = { 0 }; /* host cryptogram */
unsigned char iv[16] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x50, 0x00, 0x00);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = sizeof(g_random);
apdu.data = g_random; /* host random */
apdu.le = apdu.resplen = 28;
apdu.resp = result; /* card random is result[12~19] */
tmp_sm = exdata->sm;
exdata->sm = SM_PLAIN;
r = epass2003_transmit_apdu(card, &apdu);
exdata->sm = tmp_sm;
LOG_TEST_RET(card->ctx, r, "APDU gen_init_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "gen_init_key failed");
/* Step 1 - Generate Derivation data */
memcpy(data, &result[16], 4);
memcpy(&data[4], g_random, 4);
memcpy(&data[8], &result[12], 4);
memcpy(&data[12], &g_random[4], 4);
/* Step 2,3 - Create S-ENC/S-MAC Session Key */
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc);
aes128_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac);
}
else {
des3_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc);
des3_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac);
}
memcpy(data, g_random, 8);
memcpy(&data[8], &result[12], 8);
data[16] = 0x80;
blocksize = (key_type == KEY_TYPE_AES ? 16 : 8);
memset(&data[17], 0x00, blocksize - 1);
/* calculate host cryptogram */
if (KEY_TYPE_AES == key_type)
aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram);
else
des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram);
/* verify card cryptogram */
if (0 != memcmp(&cryptogram[16], &result[20], 8))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_CARD_CMD_FAILED);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
verify_init_key(struct sc_card *card, unsigned char *ran_key, unsigned char key_type)
{
int r;
struct sc_apdu apdu;
unsigned long blocksize = (key_type == KEY_TYPE_AES ? 16 : 8);
unsigned char data[256] = { 0 };
unsigned char cryptogram[256] = { 0 }; /* host cryptogram */
unsigned char iv[16] = { 0 };
unsigned char mac[256] = { 0 };
unsigned long i;
unsigned char tmp_sm;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
memcpy(data, ran_key, 8);
memcpy(&data[8], g_random, 8);
data[16] = 0x80;
memset(&data[17], 0x00, blocksize - 1);
memset(iv, 0, 16);
/* calculate host cryptogram */
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize,
cryptogram);
} else {
des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize,
cryptogram);
}
memset(data, 0, sizeof(data));
memcpy(data, "\x84\x82\x03\x00\x10", 5);
memcpy(&data[5], &cryptogram[16], 8);
memcpy(&data[13], "\x80\x00\x00", 3);
/* calculate mac icv */
memset(iv, 0x00, 16);
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac);
i = 0;
} else {
des3_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac);
i = 8;
}
/* save mac icv */
memset(exdata->icv_mac, 0x00, 16);
memcpy(exdata->icv_mac, &mac[i], 8);
/* verify host cryptogram */
memcpy(data, &cryptogram[16], 8);
memcpy(&data[8], &mac[i], 8);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x03, 0x00);
apdu.cla = 0x84;
apdu.lc = apdu.datalen = 16;
apdu.data = data;
tmp_sm = exdata->sm;
exdata->sm = SM_PLAIN;
r = epass2003_transmit_apdu(card, &apdu);
exdata->sm = tmp_sm;
LOG_TEST_RET(card->ctx, r,
"APDU verify_init_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r,
"verify_init_key failed");
return r;
}
static int
mutual_auth(struct sc_card *card, unsigned char *key_enc,
unsigned char *key_mac)
{
struct sc_context *ctx = card->ctx;
int r;
unsigned char result[256] = { 0 };
unsigned char ran_key[8] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(ctx);
r = gen_init_key(card, key_enc, key_mac, result, exdata->smtype);
LOG_TEST_RET(ctx, r, "gen_init_key failed");
memcpy(ran_key, &result[12], 8);
r = verify_init_key(card, ran_key, exdata->smtype);
LOG_TEST_RET(ctx, r, "verify_init_key failed");
LOG_FUNC_RETURN(ctx, r);
}
int
epass2003_refresh(struct sc_card *card)
{
int r = SC_SUCCESS;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if (exdata->sm) {
card->sm_ctx.sm_mode = 0;
r = mutual_auth(card, g_init_key_enc, g_init_key_mac);
card->sm_ctx.sm_mode = SM_MODE_TRANSMIT;
LOG_TEST_RET(card->ctx, r, "mutual_auth failed");
}
return r;
}
/* Data(TLV)=0x87|L|0x01+Cipher */
static int
construct_data_tlv(struct sc_card *card, struct sc_apdu *apdu, unsigned char *apdu_buf,
unsigned char *data_tlv, size_t * data_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
unsigned char pad[4096] = { 0 };
size_t pad_len;
size_t tlv_more; /* increased tlv length */
unsigned char iv[16] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
/* padding */
apdu_buf[block_size] = 0x87;
memcpy(pad, apdu->data, apdu->lc);
pad[apdu->lc] = 0x80;
if ((apdu->lc + 1) % block_size)
pad_len = ((apdu->lc + 1) / block_size + 1) * block_size;
else
pad_len = apdu->lc + 1;
/* encode Lc' */
if (pad_len > 0x7E) {
/* Lc' > 0x7E, use extended APDU */
apdu_buf[block_size + 1] = 0x82;
apdu_buf[block_size + 2] = (unsigned char)((pad_len + 1) / 0x100);
apdu_buf[block_size + 3] = (unsigned char)((pad_len + 1) % 0x100);
apdu_buf[block_size + 4] = 0x01;
tlv_more = 5;
}
else {
apdu_buf[block_size + 1] = (unsigned char)pad_len + 1;
apdu_buf[block_size + 2] = 0x01;
tlv_more = 3;
}
memcpy(data_tlv, &apdu_buf[block_size], tlv_more);
/* encrypt Data */
if (KEY_TYPE_AES == key_type)
aes128_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more);
else
des3_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more);
memcpy(data_tlv + tlv_more, apdu_buf + block_size + tlv_more, pad_len);
*data_tlv_len = tlv_more + pad_len;
return 0;
}
/* Le(TLV)=0x97|L|Le */
static int
construct_le_tlv(struct sc_apdu *apdu, unsigned char *apdu_buf, size_t data_tlv_len,
unsigned char *le_tlv, size_t * le_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
*(apdu_buf + block_size + data_tlv_len) = 0x97;
if (apdu->le > 0x7F) {
/* Le' > 0x7E, use extended APDU */
*(apdu_buf + block_size + data_tlv_len + 1) = 2;
*(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)(apdu->le / 0x100);
*(apdu_buf + block_size + data_tlv_len + 3) = (unsigned char)(apdu->le % 0x100);
memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 4);
*le_tlv_len = 4;
}
else {
*(apdu_buf + block_size + data_tlv_len + 1) = 1;
*(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)apdu->le;
memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 3);
*le_tlv_len = 3;
}
return 0;
}
/* MAC(TLV)=0x8e|0x08|MAC */
static int
construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len,
unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
unsigned char mac[4096] = { 0 };
size_t mac_len;
unsigned char icv[16] = { 0 };
int i = (KEY_TYPE_AES == key_type ? 15 : 7);
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if (0 == data_tlv_len && 0 == le_tlv_len) {
mac_len = block_size;
}
else {
/* padding */
*(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80;
if ((data_tlv_len + le_tlv_len + 1) % block_size)
mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) +
1) * block_size + block_size;
else
mac_len = data_tlv_len + le_tlv_len + 1 + block_size;
memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1),
0, (mac_len - (data_tlv_len + le_tlv_len + 1)));
}
/* increase icv */
for (; i >= 0; i--) {
if (exdata->icv_mac[i] == 0xff) {
exdata->icv_mac[i] = 0;
}
else {
exdata->icv_mac[i]++;
break;
}
}
/* calculate MAC */
memset(icv, 0, sizeof(icv));
memcpy(icv, exdata->icv_mac, 16);
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac);
memcpy(mac_tlv + 2, &mac[mac_len - 16], 8);
}
else {
unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 };
unsigned char tmp[8] = { 0 };
des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac);
des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp);
memset(iv, 0x00, sizeof iv);
des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2);
}
*mac_tlv_len = 2 + 8;
return 0;
}
/* According to GlobalPlatform Card Specification's SCP01
* encode APDU from
* CLA INS P1 P2 [Lc] Data [Le]
* to
* CLA INS P1 P2 Lc' Data' [Le]
* where
* Data'=Data(TLV)+Le(TLV)+MAC(TLV) */
static int
encode_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm,
unsigned char *apdu_buf, size_t * apdu_buf_len)
{
size_t block_size = 0;
unsigned char dataTLV[4096] = { 0 };
size_t data_tlv_len = 0;
unsigned char le_tlv[256] = { 0 };
size_t le_tlv_len = 0;
size_t mac_tlv_len = 10;
size_t tmp_lc = 0;
size_t tmp_le = 0;
unsigned char mac_tlv[256] = { 0 };
epass2003_exdata *exdata = NULL;
mac_tlv[0] = 0x8E;
mac_tlv[1] = 8;
/* size_t plain_le = 0; */
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata*)card->drv_data;
block_size = (KEY_TYPE_DES == exdata->smtype ? 16 : 8);
sm->cse = SC_APDU_CASE_4_SHORT;
apdu_buf[0] = (unsigned char)plain->cla;
apdu_buf[1] = (unsigned char)plain->ins;
apdu_buf[2] = (unsigned char)plain->p1;
apdu_buf[3] = (unsigned char)plain->p2;
/* plain_le = plain->le; */
/* padding */
apdu_buf[4] = 0x80;
memset(&apdu_buf[5], 0x00, block_size - 5);
/* Data -> Data' */
if (plain->lc != 0)
if (0 != construct_data_tlv(card, plain, apdu_buf, dataTLV, &data_tlv_len, exdata->smtype))
return -1;
if (plain->le != 0 || (plain->le == 0 && plain->resplen != 0))
if (0 != construct_le_tlv(plain, apdu_buf, data_tlv_len, le_tlv,
&le_tlv_len, exdata->smtype))
return -1;
if (0 != construct_mac_tlv(card, apdu_buf, data_tlv_len, le_tlv_len, mac_tlv, &mac_tlv_len, exdata->smtype))
return -1;
memset(apdu_buf + 4, 0, *apdu_buf_len - 4);
sm->lc = sm->datalen = data_tlv_len + le_tlv_len + mac_tlv_len;
if (sm->lc > 0xFF) {
sm->cse = SC_APDU_CASE_4_EXT;
apdu_buf[4] = (unsigned char)((sm->lc) / 0x10000);
apdu_buf[5] = (unsigned char)(((sm->lc) / 0x100) % 0x100);
apdu_buf[6] = (unsigned char)((sm->lc) % 0x100);
tmp_lc = 3;
}
else {
apdu_buf[4] = (unsigned char)sm->lc;
tmp_lc = 1;
}
memcpy(apdu_buf + 4 + tmp_lc, dataTLV, data_tlv_len);
memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len, le_tlv, le_tlv_len);
memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len + le_tlv_len, mac_tlv, mac_tlv_len);
memcpy((unsigned char *)sm->data, apdu_buf + 4 + tmp_lc, sm->datalen);
*apdu_buf_len = 0;
if (4 == le_tlv_len) {
sm->cse = SC_APDU_CASE_4_EXT;
*(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)(plain->le / 0x100);
*(apdu_buf + 4 + tmp_lc + sm->lc + 1) = (unsigned char)(plain->le % 0x100);
tmp_le = 2;
}
else if (3 == le_tlv_len) {
*(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)plain->le;
tmp_le = 1;
}
*apdu_buf_len += 4 + tmp_lc + data_tlv_len + le_tlv_len + mac_tlv_len + tmp_le;
/* sm->le = calc_le(plain_le); */
return 0;
}
static int
epass2003_sm_wrap_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm)
{
unsigned char buf[4096] = { 0 }; /* APDU buffer */
size_t buf_len = sizeof(buf);
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
if (exdata->sm)
plain->cla |= 0x0C;
sm->cse = plain->cse;
sm->cla = plain->cla;
sm->ins = plain->ins;
sm->p1 = plain->p1;
sm->p2 = plain->p2;
sm->lc = plain->lc;
sm->le = plain->le;
sm->control = plain->control;
sm->flags = plain->flags;
switch (sm->cla & 0x0C) {
case 0x00:
case 0x04:
sm->datalen = plain->datalen;
memcpy((void *)sm->data, plain->data, plain->datalen);
sm->resplen = plain->resplen;
memcpy(sm->resp, plain->resp, plain->resplen);
break;
case 0x0C:
memset(buf, 0, sizeof(buf));
if (0 != encode_apdu(card, plain, sm, buf, &buf_len))
return SC_ERROR_CARD_CMD_FAILED;
break;
default:
return SC_ERROR_INCORRECT_PARAMETERS;
}
return SC_SUCCESS;
}
/* According to GlobalPlatform Card Specification's SCP01
* decrypt APDU response from
* ResponseData' SW1 SW2
* to
* ResponseData SW1 SW2
* where
* ResponseData'=Data(TLV)+SW12(TLV)+MAC(TLV)
* where
* Data(TLV)=0x87|L|Cipher
* SW12(TLV)=0x99|0x02|SW1+SW2
* MAC(TLV)=0x8e|0x08|MAC */
static int
decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len)
{
size_t cipher_len;
size_t i;
unsigned char iv[16] = { 0 };
unsigned char plaintext[4096] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
/* no cipher */
if (in[0] == 0x99)
return 0;
/* parse cipher length */
if (0x01 == in[2] && 0x82 != in[1]) {
cipher_len = in[1];
i = 3;
}
else if (0x01 == in[3] && 0x81 == in[1]) {
cipher_len = in[2];
i = 4;
}
else if (0x01 == in[4] && 0x82 == in[1]) {
cipher_len = in[2] * 0x100;
cipher_len += in[3];
i = 5;
}
else {
return -1;
}
if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext)
return -1;
/* decrypt */
if (KEY_TYPE_AES == exdata->smtype)
aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);
else
des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);
/* unpadding */
while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0))
cipher_len--;
if (2 == cipher_len || *out_len < cipher_len - 2)
return -1;
memcpy(out, plaintext, cipher_len - 2);
*out_len = cipher_len - 2;
return 0;
}
static int
epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain)
{
int r;
size_t len = 0;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
r = sc_check_sw(card, sm->sw1, sm->sw2);
if (r == SC_SUCCESS) {
if (exdata->sm) {
len = plain->resplen;
if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len))
return SC_ERROR_CARD_CMD_FAILED;
}
else {
memcpy(plain->resp, sm->resp, sm->resplen);
len = sm->resplen;
}
}
plain->resplen = len;
plain->sw1 = sm->sw1;
plain->sw2 = sm->sw2;
sc_log(card->ctx,
"unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X",
plain->resplen, plain->sw1, plain->sw2);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_sm_free_wrapped_apdu(struct sc_card *card,
struct sc_apdu *plain, struct sc_apdu **sm_apdu)
{
struct sc_context *ctx = card->ctx;
int rv = SC_SUCCESS;
LOG_FUNC_CALLED(ctx);
if (!sm_apdu)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
if (!(*sm_apdu))
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
if (plain)
rv = epass2003_sm_unwrap_apdu(card, *sm_apdu, plain);
if ((*sm_apdu)->data) {
unsigned char * p = (unsigned char *)((*sm_apdu)->data);
free(p);
}
if ((*sm_apdu)->resp) {
free((*sm_apdu)->resp);
}
free(*sm_apdu);
*sm_apdu = NULL;
LOG_FUNC_RETURN(ctx, rv);
}
static int
epass2003_sm_get_wrapped_apdu(struct sc_card *card,
struct sc_apdu *plain, struct sc_apdu **sm_apdu)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu *apdu = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
if (!plain || !sm_apdu)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
*sm_apdu = NULL;
//construct new SM apdu from original apdu
apdu = calloc(1, sizeof(struct sc_apdu));
if (!apdu) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
apdu->data = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE);
if (!apdu->data) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
apdu->resp = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE);
if (!apdu->resp) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
apdu->datalen = SC_MAX_EXT_APDU_BUFFER_SIZE;
apdu->resplen = SC_MAX_EXT_APDU_BUFFER_SIZE;
rv = epass2003_sm_wrap_apdu(card, plain, apdu);
if (rv) {
rv = epass2003_sm_free_wrapped_apdu(card, NULL, &apdu);
if (rv < 0)
goto err;
}
*sm_apdu = apdu;
apdu = NULL;
err:
if (apdu) {
free((unsigned char *) apdu->data);
free(apdu->resp);
free(apdu);
apdu = NULL;
}
LOG_FUNC_RETURN(ctx, rv);
}
static int
epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu)
{
int r;
LOG_FUNC_CALLED(card->ctx);
r = sc_transmit_apdu_t(card, apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
return r;
}
static int
get_data(struct sc_card *card, unsigned char type, unsigned char *data, size_t datalen)
{
int r;
struct sc_apdu apdu;
unsigned char resp[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
size_t resplen = SC_MAX_APDU_BUFFER_SIZE;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, type);
apdu.resp = resp;
apdu.le = 0;
apdu.resplen = resplen;
if (0x86 == type) {
/* No SM temporarily */
unsigned char tmp_sm = exdata->sm;
exdata->sm = SM_PLAIN;
r = sc_transmit_apdu(card, &apdu);
exdata->sm = tmp_sm;
}
else {
r = sc_transmit_apdu_t(card, &apdu);
}
LOG_TEST_RET(card->ctx, r, "APDU get_data failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "get_data failed");
memcpy(data, resp, datalen);
return r;
}
/* card driver functions */
static int epass2003_match_card(struct sc_card *card)
{
int r;
LOG_FUNC_CALLED(card->ctx);
r = _sc_match_atr(card, epass2003_atrs, &card->type);
if (r < 0)
return 0;
return 1;
}
static int
epass2003_init(struct sc_card *card)
{
unsigned int flags;
unsigned int ext_flags;
unsigned char data[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
size_t datalen = SC_MAX_APDU_BUFFER_SIZE;
epass2003_exdata *exdata = NULL;
LOG_FUNC_CALLED(card->ctx);
card->name = "epass2003";
card->cla = 0x00;
exdata = (epass2003_exdata *)calloc(1, sizeof(epass2003_exdata));
if (!exdata)
return SC_ERROR_OUT_OF_MEMORY;
card->drv_data = exdata;
exdata->sm = SM_SCP01;
/* decide FIPS/Non-FIPS mode */
if (SC_SUCCESS != get_data(card, 0x86, data, datalen))
return SC_ERROR_INVALID_CARD;
if (0x01 == data[2])
exdata->smtype = KEY_TYPE_AES;
else
exdata->smtype = KEY_TYPE_DES;
if (0x84 == data[14]) {
if (0x00 == data[16]) {
exdata->sm = SM_PLAIN;
}
}
/* mutual authentication */
card->max_recv_size = 0xD8;
card->max_send_size = 0xE8;
card->sm_ctx.ops.open = epass2003_refresh;
card->sm_ctx.ops.get_sm_apdu = epass2003_sm_get_wrapped_apdu;
card->sm_ctx.ops.free_sm_apdu = epass2003_sm_free_wrapped_apdu;
/* FIXME (VT): rather then set/unset 'g_sm', better to implement filter for APDUs to be wrapped */
epass2003_refresh(card);
card->sm_ctx.sm_mode = SM_MODE_TRANSMIT;
flags = SC_ALGORITHM_ONBOARD_KEY_GEN | SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_HASH_NONE;
_sc_card_add_rsa_alg(card, 512, flags, 0);
_sc_card_add_rsa_alg(card, 768, flags, 0);
_sc_card_add_rsa_alg(card, 1024, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
//set EC Alg Flags
flags = SC_ALGORITHM_ONBOARD_KEY_GEN|SC_ALGORITHM_ECDSA_HASH_SHA1|SC_ALGORITHM_ECDSA_HASH_SHA256|SC_ALGORITHM_ECDSA_HASH_NONE|SC_ALGORITHM_ECDSA_RAW;
ext_flags = 0;
_sc_card_add_ec_alg(card, 256, flags, ext_flags, NULL);
card->caps = SC_CARD_CAP_RNG | SC_CARD_CAP_APDU_EXT;
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_finish(sc_card_t *card)
{
epass2003_exdata *exdata = (epass2003_exdata *)card->drv_data;
if (exdata)
free(exdata);
return SC_SUCCESS;
}
/* COS implement SFI as lower 5 bits of FID, and not allow same SFI at the
* same DF, so use hook functions to increase/decrease FID by 0x20 */
static int
epass2003_hook_path(struct sc_path *path, int inc)
{
u8 fid_h = path->value[path->len - 2];
u8 fid_l = path->value[path->len - 1];
switch (fid_h) {
case 0x29:
case 0x30:
case 0x31:
case 0x32:
case 0x33:
case 0x34:
if (inc)
fid_l = fid_l * FID_STEP;
else
fid_l = fid_l / FID_STEP;
path->value[path->len - 1] = fid_l;
return 1;
default:
break;
}
return 0;
}
static void
epass2003_hook_file(struct sc_file *file, int inc)
{
int fidl = file->id & 0xff;
int fidh = file->id & 0xff00;
if (epass2003_hook_path(&file->path, inc)) {
if (inc)
file->id = fidh + fidl * FID_STEP;
else
file->id = fidh + fidl / FID_STEP;
}
}
static int
epass2003_select_fid_(struct sc_card *card, sc_path_t * in_path, sc_file_t ** file_out)
{
struct sc_apdu apdu;
u8 buf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
u8 pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
int r, pathlen;
sc_file_t *file = NULL;
epass2003_hook_path(in_path, 1);
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
apdu.p1 = 0;
if (pathlen != 2)
return SC_ERROR_INVALID_ARGUMENTS;
break;
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
apdu.p2 = 0; /* first record, return FCI */
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
if (file_out != NULL) {
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = 0;
}
else {
apdu.cse = (apdu.lc == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT;
}
if (path[0] == 0x29) { /* TODO:0x29 accords with FID prefix in profile */
/* Not allowed to select private key file, so fake fci. */
/* 62 16 82 02 11 00 83 02 29 00 85 02 08 00 86 08 FF 90 90 90 FF FF FF FF */
apdu.resplen = 0x18;
memcpy(apdu.resp,
"\x6f\x16\x82\x02\x11\x00\x83\x02\x29\x00\x85\x02\x08\x00\x86\x08\xff\x90\x90\x90\xff\xff\xff\xff",
apdu.resplen);
apdu.resp[9] = path[1];
apdu.sw1 = 0x90;
apdu.sw2 = 0x00;
}
else {
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
}
if (file_out == NULL) {
if (apdu.sw1 == 0x61)
LOG_FUNC_RETURN(card->ctx, 0);
LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r)
LOG_FUNC_RETURN(card->ctx, r);
if (apdu.resplen < 2)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
switch (apdu.resp[0]) {
case 0x6F:
file = sc_file_new();
if (file == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
file->path = *in_path;
if (card->ops->process_fci == NULL) {
sc_file_free(file);
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
if ((size_t) apdu.resp[1] + 2 <= apdu.resplen)
card->ops->process_fci(card, file, apdu.resp + 2, apdu.resp[1]);
epass2003_hook_file(file, 0);
*file_out = file;
break;
case 0x00: /* proprietary coding */
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
break;
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
return 0;
}
static int
epass2003_select_fid(struct sc_card *card, unsigned int id_hi, unsigned int id_lo,
sc_file_t ** file_out)
{
int r;
sc_file_t *file = 0;
sc_path_t path;
memset(&path, 0, sizeof(path));
path.type = SC_PATH_TYPE_FILE_ID;
path.value[0] = id_hi;
path.value[1] = id_lo;
path.len = 2;
r = epass2003_select_fid_(card, &path, &file);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
/* update cache */
if (file && file->type == SC_FILE_TYPE_DF) {
card->cache.current_path.type = SC_PATH_TYPE_PATH;
card->cache.current_path.value[0] = 0x3f;
card->cache.current_path.value[1] = 0x00;
if (id_hi == 0x3f && id_lo == 0x00) {
card->cache.current_path.len = 2;
}
else {
card->cache.current_path.len = 4;
card->cache.current_path.value[2] = id_hi;
card->cache.current_path.value[3] = id_lo;
}
}
if (file_out)
*file_out = file;
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_select_aid(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out)
{
int r = 0;
if (card->cache.valid
&& card->cache.current_path.type == SC_PATH_TYPE_DF_NAME
&& card->cache.current_path.len == in_path->len
&& memcmp(card->cache.current_path.value, in_path->value, in_path->len) == 0) {
if (file_out) {
*file_out = sc_file_new();
if (!file_out)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
}
else {
r = iso_ops->select_file(card, in_path, file_out);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
/* update cache */
card->cache.current_path.type = SC_PATH_TYPE_DF_NAME;
card->cache.current_path.len = in_path->len;
memcpy(card->cache.current_path.value, in_path->value, in_path->len);
}
if (file_out) {
sc_file_t *file = *file_out;
file->type = SC_FILE_TYPE_DF;
file->ef_structure = SC_FILE_EF_UNKNOWN;
file->path.len = 0;
file->size = 0;
/* AID */
memcpy(file->name, in_path->value, in_path->len);
file->namelen = in_path->len;
file->id = 0x0000;
}
LOG_FUNC_RETURN(card->ctx, r);
}
static int
epass2003_select_path(struct sc_card *card, const u8 pathbuf[16], const size_t len,
sc_file_t ** file_out)
{
u8 n_pathbuf[SC_MAX_PATH_SIZE];
const u8 *path = pathbuf;
size_t pathlen = len;
int bMatch = -1;
unsigned int i;
int r;
if (pathlen % 2 != 0 || pathlen > 6 || pathlen <= 0)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
/* if pathlen == 6 then the first FID must be MF (== 3F00) */
if (pathlen == 6 && (path[0] != 0x3f || path[1] != 0x00))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
/* unify path (the first FID should be MF) */
if (path[0] != 0x3f || path[1] != 0x00) {
n_pathbuf[0] = 0x3f;
n_pathbuf[1] = 0x00;
for (i = 0; i < pathlen; i++)
n_pathbuf[i + 2] = pathbuf[i];
path = n_pathbuf;
pathlen += 2;
}
/* check current working directory */
if (card->cache.valid
&& card->cache.current_path.type == SC_PATH_TYPE_PATH
&& card->cache.current_path.len >= 2
&& card->cache.current_path.len <= pathlen) {
bMatch = 0;
for (i = 0; i < card->cache.current_path.len; i += 2)
if (card->cache.current_path.value[i] == path[i]
&& card->cache.current_path.value[i + 1] == path[i + 1])
bMatch += 2;
}
if (card->cache.valid && bMatch > 2) {
if (pathlen - bMatch == 2) {
/* we are in the right directory */
return epass2003_select_fid(card, path[bMatch], path[bMatch + 1], file_out);
}
else if (pathlen - bMatch > 2) {
/* two more steps to go */
sc_path_t new_path;
/* first step: change directory */
r = epass2003_select_fid(card, path[bMatch], path[bMatch + 1], NULL);
LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed");
new_path.type = SC_PATH_TYPE_PATH;
new_path.len = pathlen - bMatch - 2;
memcpy(new_path.value, &(path[bMatch + 2]), new_path.len);
/* final step: select file */
return epass2003_select_file(card, &new_path, file_out);
}
else { /* if (bMatch - pathlen == 0) */
/* done: we are already in the
* requested directory */
sc_log(card->ctx, "cache hit\n");
/* copy file info (if necessary) */
if (file_out) {
sc_file_t *file = sc_file_new();
if (!file)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
file->id = (path[pathlen - 2] << 8) + path[pathlen - 1];
file->path = card->cache.current_path;
file->type = SC_FILE_TYPE_DF;
file->ef_structure = SC_FILE_EF_UNKNOWN;
file->size = 0;
file->namelen = 0;
file->magic = SC_FILE_MAGIC;
*file_out = file;
}
/* nothing left to do */
return SC_SUCCESS;
}
}
else {
/* no usable cache */
for (i = 0; i < pathlen - 2; i += 2) {
r = epass2003_select_fid(card, path[i], path[i + 1], NULL);
LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed");
}
return epass2003_select_fid(card, path[pathlen - 2], path[pathlen - 1], file_out);
}
}
static int
epass2003_select_file(struct sc_card *card, const sc_path_t * in_path,
sc_file_t ** file_out)
{
int r;
char pbuf[SC_MAX_PATH_STRING_SIZE];
LOG_FUNC_CALLED(card->ctx);
r = sc_path_print(pbuf, sizeof(pbuf), &card->cache.current_path);
if (r != SC_SUCCESS)
pbuf[0] = '\0';
sc_log(card->ctx,
"current path (%s, %s): %s (len: %"SC_FORMAT_LEN_SIZE_T"u)\n",
card->cache.current_path.type == SC_PATH_TYPE_DF_NAME ?
"aid" : "path",
card->cache.valid ? "valid" : "invalid", pbuf,
card->cache.current_path.len);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
if (in_path->len != 2)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
return epass2003_select_fid(card, in_path->value[0], in_path->value[1], file_out);
case SC_PATH_TYPE_DF_NAME:
return epass2003_select_aid(card, in_path, file_out);
case SC_PATH_TYPE_PATH:
return epass2003_select_path(card, in_path->value, in_path->len, file_out);
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
}
static int
epass2003_set_security_env(struct sc_card *card, const sc_security_env_t * env, int se_num)
{
struct sc_apdu apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
u8 *p;
unsigned short fid = 0;
int r, locked = 0;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, 0);
p = sbuf;
*p++ = 0x80; /* algorithm reference */
*p++ = 0x01;
*p++ = 0x84;
*p++ = 0x81;
*p++ = 0x02;
fid = 0x2900;
fid += (unsigned short)(0x20 * (env->key_ref[0] & 0xff));
*p++ = fid >> 8;
*p++ = fid & 0xff;
r = p - sbuf;
apdu.lc = r;
apdu.datalen = r;
apdu.data = sbuf;
if (env->algorithm == SC_ALGORITHM_EC)
{
apdu.p2 = 0xB6;
exdata->currAlg = SC_ALGORITHM_EC;
if(env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA1)
{
sbuf[2] = 0x91;
exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA1;
}
else if (env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA256)
{
sbuf[2] = 0x92;
exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA256;
}
else
{
sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm_flags);
goto err;
}
}
else if(env->algorithm == SC_ALGORITHM_RSA)
{
exdata->currAlg = SC_ALGORITHM_RSA;
apdu.p2 = 0xB8;
sc_log(card->ctx, "setenv RSA Algorithm alg_flags = %0x\n",env->algorithm_flags);
}
else
{
sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm);
}
if (se_num > 0) {
r = sc_lock(card);
LOG_TEST_RET(card->ctx, r, "sc_lock() failed");
locked = 1;
}
if (apdu.datalen != 0) {
r = sc_transmit_apdu_t(card, &apdu);
if (r) {
sc_log(card->ctx, "%s: APDU transmit failed", sc_strerror(r));
goto err;
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r) {
sc_log(card->ctx, "%s: Card returned error", sc_strerror(r));
goto err;
}
}
if (se_num <= 0)
return 0;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0xF2, se_num);
r = sc_transmit_apdu_t(card, &apdu);
sc_unlock(card);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
err:
if (locked)
sc_unlock(card);
return r;
}
static int
epass2003_restore_security_env(struct sc_card *card, int se_num)
{
LOG_FUNC_CALLED(card->ctx);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int epass2003_decipher(struct sc_card *card, const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
int r;
struct sc_apdu apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
epass2003_exdata *exdata = NULL;
LOG_FUNC_CALLED(card->ctx);
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if(exdata->currAlg == SC_ALGORITHM_EC)
{
if(exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA1)
{
r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash_data failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A);
apdu.data = sbuf;
apdu.lc = 0x14;
apdu.datalen = 0x14;
}
else if (exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA256)
{
r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA256);
LOG_TEST_RET(card->ctx, r, "hash_data failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A);
apdu.data = sbuf;
apdu.lc = 0x20;
apdu.datalen = 0x20;
}
else
{
return SC_ERROR_NOT_SUPPORTED;
}
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) {
size_t len = apdu.resplen > outlen ? outlen : apdu.resplen;
memcpy(out, apdu.resp, len);
LOG_FUNC_RETURN(card->ctx, len);
}
LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
else if(exdata->currAlg == SC_ALGORITHM_RSA)
{
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0;
memcpy(sbuf, data, datalen);
apdu.data = sbuf;
apdu.lc = datalen;
apdu.datalen = datalen;
}
else
{
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
memcpy(sbuf, data, datalen);
apdu.data = sbuf;
apdu.lc = datalen;
apdu.datalen = datalen;
}
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) {
size_t len = apdu.resplen > outlen ? outlen : apdu.resplen;
memcpy(out, apdu.resp, len);
LOG_FUNC_RETURN(card->ctx, len);
}
LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int
acl_to_ac_byte(struct sc_card *card, const struct sc_acl_entry *e)
{
if (e == NULL)
return SC_ERROR_OBJECT_NOT_FOUND;
switch (e->method) {
case SC_AC_NONE:
LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE);
case SC_AC_NEVER:
LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_NOONE);
default:
LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_USER);
}
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
}
static int
epass2003_process_fci(struct sc_card *card, sc_file_t * file, const u8 * buf, size_t buflen)
{
sc_context_t *ctx = card->ctx;
size_t taglen, len = buflen;
const u8 *tag = NULL, *p = buf;
sc_log(ctx, "processing FCI bytes");
tag = sc_asn1_find_tag(ctx, p, len, 0x83, &taglen);
if (tag != NULL && taglen == 2) {
file->id = (tag[0] << 8) | tag[1];
sc_log(ctx, " file identifier: 0x%02X%02X", tag[0], tag[1]);
}
tag = sc_asn1_find_tag(ctx, p, len, 0x80, &taglen);
if (tag != NULL && taglen > 0 && taglen < 3) {
file->size = tag[0];
if (taglen == 2)
file->size = (file->size << 8) + tag[1];
sc_log(ctx, " bytes in file: %"SC_FORMAT_LEN_SIZE_T"u",
file->size);
}
if (tag == NULL) {
tag = sc_asn1_find_tag(ctx, p, len, 0x81, &taglen);
if (tag != NULL && taglen >= 2) {
int bytes = (tag[0] << 8) + tag[1];
sc_log(ctx, " bytes in file: %d", bytes);
file->size = bytes;
}
}
tag = sc_asn1_find_tag(ctx, p, len, 0x82, &taglen);
if (tag != NULL) {
if (taglen > 0) {
unsigned char byte = tag[0];
const char *type;
if (byte == 0x38) {
type = "DF";
file->type = SC_FILE_TYPE_DF;
}
else if (0x01 <= byte && byte <= 0x07) {
type = "working EF";
file->type = SC_FILE_TYPE_WORKING_EF;
switch (byte) {
case 0x01:
file->ef_structure = SC_FILE_EF_TRANSPARENT;
break;
case 0x02:
file->ef_structure = SC_FILE_EF_LINEAR_FIXED;
break;
case 0x04:
file->ef_structure = SC_FILE_EF_LINEAR_FIXED;
break;
case 0x03:
case 0x05:
case 0x06:
case 0x07:
break;
default:
break;
}
}
else if (0x10 == byte) {
type = "BSO";
file->type = SC_FILE_TYPE_BSO;
}
else if (0x11 <= byte) {
type = "internal EF";
file->type = SC_FILE_TYPE_INTERNAL_EF;
switch (byte) {
case 0x11:
break;
case 0x12:
break;
default:
break;
}
}
else {
type = "unknown";
file->type = SC_FILE_TYPE_INTERNAL_EF;
}
sc_log(ctx, "type %s, EF structure %d", type, byte);
}
}
tag = sc_asn1_find_tag(ctx, p, len, 0x84, &taglen);
if (tag != NULL && taglen > 0 && taglen <= 16) {
memcpy(file->name, tag, taglen);
file->namelen = taglen;
sc_log_hex(ctx, "File name", file->name, file->namelen);
if (!file->type)
file->type = SC_FILE_TYPE_DF;
}
tag = sc_asn1_find_tag(ctx, p, len, 0x85, &taglen);
if (tag != NULL && taglen)
sc_file_set_prop_attr(file, tag, taglen);
else
file->prop_attr_len = 0;
tag = sc_asn1_find_tag(ctx, p, len, 0xA5, &taglen);
if (tag != NULL && taglen)
sc_file_set_prop_attr(file, tag, taglen);
tag = sc_asn1_find_tag(ctx, p, len, 0x86, &taglen);
if (tag != NULL && taglen)
sc_file_set_sec_attr(file, tag, taglen);
tag = sc_asn1_find_tag(ctx, p, len, 0x8A, &taglen);
if (tag != NULL && taglen == 1) {
if (tag[0] == 0x01)
file->status = SC_FILE_STATUS_CREATION;
else if (tag[0] == 0x07 || tag[0] == 0x05)
file->status = SC_FILE_STATUS_ACTIVATED;
else if (tag[0] == 0x06 || tag[0] == 0x04)
file->status = SC_FILE_STATUS_INVALIDATED;
}
file->magic = SC_FILE_MAGIC;
return 0;
}
static int
epass2003_construct_fci(struct sc_card *card, const sc_file_t * file,
u8 * out, size_t * outlen)
{
u8 *p = out;
u8 buf[64];
unsigned char ops[8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
int rv;
unsigned ii;
if (*outlen < 2)
return SC_ERROR_BUFFER_TOO_SMALL;
*p++ = 0x62;
p++;
if (file->type == SC_FILE_TYPE_WORKING_EF) {
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
sc_asn1_put_tag(0x80, buf, 2, p, *outlen - (p - out), &p);
}
}
if (file->type == SC_FILE_TYPE_DF) {
buf[0] = 0x38;
buf[1] = 0x00;
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_WORKING_EF) {
buf[0] = file->ef_structure & 7;
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
buf[1] = 0x00;
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED
|| file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) {
buf[1] = 0x00;
buf[2] = 0x00;
buf[3] = 0x40; /* record length */
buf[4] = 0x00; /* record count */
sc_asn1_put_tag(0x82, buf, 5, p, *outlen - (p - out), &p);
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF) {
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) {
buf[0] = 0x11;
buf[1] = 0x00;
}
else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
buf[0] = 0x12;
buf[1] = 0x00;
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_BSO) {
buf[0] = 0x10;
buf[1] = 0x00;
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
buf[0] = (file->id >> 8) & 0xFF;
buf[1] = file->id & 0xFF;
sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p);
if (file->type == SC_FILE_TYPE_DF) {
if (file->namelen != 0) {
sc_asn1_put_tag(0x84, file->name, file->namelen, p, *outlen - (p - out), &p);
}
else {
return SC_ERROR_INVALID_ARGUMENTS;
}
}
if (file->type == SC_FILE_TYPE_DF) {
unsigned char data[2] = {0x00, 0x7F};
/* 127 files at most */
sc_asn1_put_tag(0x85, data, sizeof(data), p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_BSO) {
buf[0] = file->size & 0xff;
sc_asn1_put_tag(0x85, buf, 1, p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF) {
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
sc_asn1_put_tag(0x85, buf, 2, p, *outlen - (p - out), &p);
}
}
if (file->sec_attr_len) {
memcpy(buf, file->sec_attr, file->sec_attr_len);
sc_asn1_put_tag(0x86, buf, file->sec_attr_len, p, *outlen - (p - out), &p);
}
else {
sc_log(card->ctx, "SC_FILE_ACL");
if (file->type == SC_FILE_TYPE_DF) {
ops[0] = SC_AC_OP_LIST_FILES;
ops[1] = SC_AC_OP_CREATE;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->type == SC_FILE_TYPE_WORKING_EF) {
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
ops[0] = SC_AC_OP_READ;
ops[1] = SC_AC_OP_UPDATE;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED
|| file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) {
ops[0] = SC_AC_OP_READ;
ops[1] = SC_AC_OP_UPDATE;
ops[2] = SC_AC_OP_WRITE;
ops[3] = SC_AC_OP_DELETE;
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
}
else if (file->type == SC_FILE_TYPE_BSO) {
ops[0] = SC_AC_OP_UPDATE;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF) {
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) {
ops[1] = SC_AC_OP_UPDATE;
ops[2] = SC_AC_OP_CRYPTO;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
ops[0] = SC_AC_OP_READ;
ops[1] = SC_AC_OP_UPDATE;
ops[2] = SC_AC_OP_CRYPTO;
ops[3] = SC_AC_OP_DELETE;
}
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
for (ii = 0; ii < sizeof(ops); ii++) {
const struct sc_acl_entry *entry;
buf[ii] = 0xFF;
if (ops[ii] == 0xFF)
continue;
entry = sc_file_get_acl_entry(file, ops[ii]);
rv = acl_to_ac_byte(card, entry);
LOG_TEST_RET(card->ctx, rv, "Invalid ACL");
buf[ii] = rv;
}
sc_asn1_put_tag(0x86, buf, sizeof(ops), p, *outlen - (p - out), &p);
if(file->size == 256)
{
out[4]= 0x13;
}
}
/* VT ??? */
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
unsigned char data[2] = {0x00, 0x66};
sc_asn1_put_tag(0x87, data, sizeof(data), p, *outlen - (p - out), &p);
if(file->size == 256)
{
out[4]= 0x14;
}
}
out[1] = p - out - 2;
*outlen = p - out;
return 0;
}
static int
epass2003_create_file(struct sc_card *card, sc_file_t * file)
{
int r;
size_t len;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
struct sc_apdu apdu;
len = SC_MAX_APDU_BUFFER_SIZE;
epass2003_hook_file(file, 1);
if (card->ops->construct_fci == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
r = epass2003_construct_fci(card, file, sbuf, &len);
LOG_TEST_RET(card->ctx, r, "construct_fci() failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00);
apdu.lc = len;
apdu.datalen = len;
apdu.data = sbuf;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "APDU sw1/2 wrong");
epass2003_hook_file(file, 0);
return r;
}
static int
epass2003_delete_file(struct sc_card *card, const sc_path_t * path)
{
int r;
u8 sbuf[2];
struct sc_apdu apdu;
LOG_FUNC_CALLED(card->ctx);
r = sc_select_file(card, path, NULL);
epass2003_hook_path((struct sc_path *)path, 1);
if (r == SC_SUCCESS) {
sbuf[0] = path->value[path->len - 2];
sbuf[1] = path->value[path->len - 1];
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00);
apdu.lc = 2;
apdu.datalen = 2;
apdu.data = sbuf;
}
else {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "Delete file failed");
LOG_FUNC_RETURN(card->ctx, r);
}
static int
epass2003_list_files(struct sc_card *card, unsigned char *buf, size_t buflen)
{
struct sc_apdu apdu;
unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x34, 0x00, 0x00);
apdu.cla = 0x80;
apdu.le = 0;
apdu.resplen = sizeof(rbuf);
apdu.resp = rbuf;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "Card returned error");
if (apdu.resplen == 0x100 && rbuf[0] == 0 && rbuf[1] == 0)
LOG_FUNC_RETURN(card->ctx, 0);
buflen = buflen < apdu.resplen ? buflen : apdu.resplen;
memcpy(buf, rbuf, buflen);
LOG_FUNC_RETURN(card->ctx, buflen);
}
static int
internal_write_rsa_key_factor(struct sc_card *card, unsigned short fid, u8 factor,
sc_pkcs15_bignum_t data)
{
int r;
struct sc_apdu apdu;
u8 sbuff[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 };
LOG_FUNC_CALLED(card->ctx);
sbuff[0] = ((fid & 0xff00) >> 8);
sbuff[1] = (fid & 0x00ff);
memcpy(&sbuff[2], data.data, data.len);
// sc_mem_reverse(&sbuff[2], data.len);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3, 0xe7, factor, 0x00);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 2 + data.len;
apdu.data = sbuff;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "Write rsa key factor failed");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
internal_write_rsa_key(struct sc_card *card, unsigned short fid, struct sc_pkcs15_prkey_rsa *rsa)
{
int r;
LOG_FUNC_CALLED(card->ctx);
r = internal_write_rsa_key_factor(card, fid, 0x02, rsa->modulus);
LOG_TEST_RET(card->ctx, r, "write n failed");
r = internal_write_rsa_key_factor(card, fid, 0x03, rsa->d);
LOG_TEST_RET(card->ctx, r, "write d failed");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType)
{
if ((NULL == data) || (NULL == hash))
return SC_ERROR_INVALID_ARGUMENTS;
if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA1)
{
unsigned char data_hash[24] = { 0 };
size_t len = 0;
sha1_digest(data, datalen, data_hash);
len = REVERSE_ORDER4(datalen);
memcpy(&data_hash[20], &len, 4);
memcpy(hash, data_hash, 24);
}
else if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA256)
{
unsigned char data_hash[36] = { 0 };
size_t len = 0;
sha256_digest(data, datalen, data_hash);
len = REVERSE_ORDER4(datalen);
memcpy(&data_hash[32], &len, 4);
memcpy(hash, data_hash, 36);
}
else
{
return SC_ERROR_NOT_SUPPORTED;
}
return SC_SUCCESS;
}
static int
install_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid,
unsigned char useac, unsigned char modifyac, unsigned char EC,
unsigned char *data, unsigned long dataLen)
{
int r;
struct sc_apdu apdu;
unsigned char isapp = 0x00; /* appendable */
unsigned char tmp_data[256] = { 0 };
tmp_data[0] = ktype;
tmp_data[1] = kid;
tmp_data[2] = useac;
tmp_data[3] = modifyac;
tmp_data[8] = 0xFF;
if (0x04 == ktype || 0x06 == ktype) {
tmp_data[4] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO;
tmp_data[5] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO;
tmp_data[7] = (kid == PIN_ID[0] ? EPASS2003_AC_USER : EPASS2003_AC_SO);
tmp_data[9] = (EC << 4) | EC;
}
memcpy(&tmp_data[10], data, dataLen);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe3, isapp, 0x00);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 10 + dataLen;
apdu.data = tmp_data;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU install_secret_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "install_secret_key failed");
return r;
}
static int
internal_install_pre(struct sc_card *card)
{
int r;
/* init key for enc */
r = install_secret_key(card, 0x01, 0x00,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
0, g_init_key_enc, 16);
LOG_TEST_RET(card->ctx, r, "Install init key failed");
/* init key for mac */
r = install_secret_key(card, 0x02, 0x00,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
0, g_init_key_mac, 16);
LOG_TEST_RET(card->ctx, r, "Install init key failed");
return r;
}
/* use external auth secret as pin */
static int
internal_install_pin(struct sc_card *card, sc_epass2003_wkey_data * pin)
{
int r;
unsigned char hash[HASH_LEN] = { 0 };
r = hash_data(pin->key_data.es_secret.key_val, pin->key_data.es_secret.key_len, hash, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash data failed");
r = install_secret_key(card, 0x04, pin->key_data.es_secret.kid,
pin->key_data.es_secret.ac[0],
pin->key_data.es_secret.ac[1],
pin->key_data.es_secret.EC, hash, HASH_LEN);
LOG_TEST_RET(card->ctx, r, "Install failed");
return r;
}
static int
epass2003_write_key(struct sc_card *card, sc_epass2003_wkey_data * data)
{
LOG_FUNC_CALLED(card->ctx);
if (data->type & SC_EPASS2003_KEY) {
if (data->type == SC_EPASS2003_KEY_RSA)
return internal_write_rsa_key(card, data->key_data.es_key.fid,
data->key_data.es_key.rsa);
else
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
} else if (data->type & SC_EPASS2003_SECRET) {
if (data->type == SC_EPASS2003_SECRET_PRE)
return internal_install_pre(card);
else if (data->type == SC_EPASS2003_SECRET_PIN)
return internal_install_pin(card, data);
else
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
else {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_gen_key(struct sc_card *card, sc_epass2003_gen_key_data * data)
{
int r;
size_t len = data->key_length;
struct sc_apdu apdu;
u8 rbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 };
u8 sbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 };
LOG_FUNC_CALLED(card->ctx);
if(len == 256)
{
sbuf[0] = 0x02;
}
else
{
sbuf[0] = 0x01;
}
sbuf[1] = (u8) ((len >> 8) & 0xff);
sbuf[2] = (u8) (len & 0xff);
sbuf[3] = (u8) ((data->prkey_id >> 8) & 0xFF);
sbuf[4] = (u8) ((data->prkey_id) & 0xFF);
sbuf[5] = (u8) ((data->pukey_id >> 8) & 0xFF);
sbuf[6] = (u8) ((data->pukey_id) & 0xFF);
/* generate key */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00);
apdu.lc = apdu.datalen = 7;
apdu.data = sbuf;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "generate keypair failed");
/* read public key */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xb4, 0x02, 0x00);
if(len == 256)
{
apdu.p1 = 0x00;
}
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 2;
apdu.data = &sbuf[5];
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0x00;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "get pukey failed");
if (len < apdu.resplen)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
data->modulus = (u8 *) malloc(len);
if (!data->modulus)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(data->modulus, rbuf, len);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_erase_card(struct sc_card *card)
{
int r;
LOG_FUNC_CALLED(card->ctx);
sc_invalidate_cache(card);
r = sc_delete_file(card, sc_get_mf_path());
LOG_TEST_RET(card->ctx, r, "delete MF failed");
LOG_FUNC_RETURN(card->ctx, r);
}
static int
epass2003_get_serialnr(struct sc_card *card, sc_serial_number_t * serial)
{
u8 rbuf[8];
size_t rbuf_len = sizeof(rbuf);
LOG_FUNC_CALLED(card->ctx);
if (SC_SUCCESS != get_data(card, 0x80, rbuf, rbuf_len))
return SC_ERROR_CARD_CMD_FAILED;
card->serialnr.len = serial->len = 8;
memcpy(card->serialnr.value, rbuf, 8);
memcpy(serial->value, rbuf, 8);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr)
{
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx, "cmd is %0lx", cmd);
switch (cmd) {
case SC_CARDCTL_ENTERSAFE_WRITE_KEY:
return epass2003_write_key(card, (sc_epass2003_wkey_data *) ptr);
case SC_CARDCTL_ENTERSAFE_GENERATE_KEY:
return epass2003_gen_key(card, (sc_epass2003_gen_key_data *) ptr);
case SC_CARDCTL_ERASE_CARD:
return epass2003_erase_card(card);
case SC_CARDCTL_GET_SERIALNR:
return epass2003_get_serialnr(card, (sc_serial_number_t *) ptr);
default:
return SC_ERROR_NOT_SUPPORTED;
}
}
static void
internal_sanitize_pin_info(struct sc_pin_cmd_pin *pin, unsigned int num)
{
pin->encoding = SC_PIN_ENCODING_ASCII;
pin->min_length = 4;
pin->max_length = 16;
pin->pad_length = 16;
pin->offset = 5 + num * 16;
pin->pad_char = 0x00;
}
static int
get_external_key_maxtries(struct sc_card *card, unsigned char *maxtries)
{
unsigned char maxcounter[2] = { 0 };
static const sc_path_t file_path = {
{0x3f, 0x00, 0x50, 0x15, 0x9f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 6,
0,
0,
SC_PATH_TYPE_PATH,
{{0}, 0}
};
int ret;
ret = sc_select_file(card, &file_path, NULL);
LOG_TEST_RET(card->ctx, ret, "select max counter file failed");
ret = sc_read_binary(card, 0, maxcounter, 2, 0);
LOG_TEST_RET(card->ctx, ret, "read max counter file failed");
*maxtries = maxcounter[0];
return SC_SUCCESS;
}
static int
get_external_key_retries(struct sc_card *card, unsigned char kid, unsigned char *retries)
{
int r;
struct sc_apdu apdu;
unsigned char random[16] = { 0 };
r = sc_get_challenge(card, random, 8);
LOG_TEST_RET(card->ctx, r, "get challenge get_external_key_retries failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x82, 0x01, 0x80 | kid);
apdu.resp = NULL;
apdu.resplen = 0;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU get_external_key_retries failed");
if (retries && ((0x63 == (apdu.sw1 & 0xff)) && (0xC0 == (apdu.sw2 & 0xf0)))) {
*retries = (apdu.sw2 & 0x0f);
r = SC_SUCCESS;
}
else {
LOG_TEST_RET(card->ctx, r, "get_external_key_retries failed");
r = SC_ERROR_CARD_CMD_FAILED;
}
return r;
}
static int
epass2003_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
{
u8 rbuf[16];
size_t out_len;
int r;
LOG_FUNC_CALLED(card->ctx);
r = iso_ops->get_challenge(card, rbuf, sizeof rbuf);
LOG_TEST_RET(card->ctx, r, "GET CHALLENGE cmd failed");
if (len < (size_t) r) {
out_len = len;
} else {
out_len = (size_t) r;
}
memcpy(rnd, rbuf, out_len);
LOG_FUNC_RETURN(card->ctx, (int) out_len);
}
static int
external_key_auth(struct sc_card *card, unsigned char kid,
unsigned char *data, size_t datalen)
{
int r;
struct sc_apdu apdu;
unsigned char random[16] = { 0 };
unsigned char tmp_data[16] = { 0 };
unsigned char hash[HASH_LEN] = { 0 };
unsigned char iv[16] = { 0 };
r = sc_get_challenge(card, random, 8);
LOG_TEST_RET(card->ctx, r, "get challenge external_key_auth failed");
r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash data failed");
des3_encrypt_cbc(hash, HASH_LEN, iv, random, 8, tmp_data);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x01, 0x80 | kid);
apdu.lc = apdu.datalen = 8;
apdu.data = tmp_data;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU external_key_auth failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "external_key_auth failed");
return r;
}
static int
update_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid,
const unsigned char *data, unsigned long datalen)
{
int r;
struct sc_apdu apdu;
unsigned char hash[HASH_LEN] = { 0 };
unsigned char tmp_data[256] = { 0 };
unsigned char maxtries = 0;
r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash data failed");
r = get_external_key_maxtries(card, &maxtries);
LOG_TEST_RET(card->ctx, r, "get max counter failed");
tmp_data[0] = (maxtries << 4) | maxtries;
memcpy(&tmp_data[1], hash, HASH_LEN);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe5, ktype, kid);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 1 + HASH_LEN;
apdu.data = tmp_data;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU update_secret_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "update_secret_key failed");
return r;
}
/* use external auth secret as pin */
static int
epass2003_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)
{
int r;
u8 kid;
u8 retries = 0;
u8 pin_low = 3;
unsigned char maxtries = 0;
LOG_FUNC_CALLED(card->ctx);
internal_sanitize_pin_info(&data->pin1, 0);
internal_sanitize_pin_info(&data->pin2, 1);
data->flags |= SC_PIN_CMD_NEED_PADDING;
kid = data->pin_reference;
/* get pin retries */
if (data->cmd == SC_PIN_CMD_GET_INFO) {
r = get_external_key_retries(card, 0x80 | kid, &retries);
if (r == SC_SUCCESS) {
data->pin1.tries_left = retries;
if (tries_left)
*tries_left = retries;
r = get_external_key_maxtries(card, &maxtries);
LOG_TEST_RET(card->ctx, r, "get max counter failed");
data->pin1.max_tries = maxtries;
}
//remove below code, because the old implement only return PIN retries, now modify the code and return PIN status
// return r;
}
else if (data->cmd == SC_PIN_CMD_UNBLOCK) { /* verify */
r = external_key_auth(card, (kid + 1), (unsigned char *)data->pin1.data,
data->pin1.len);
LOG_TEST_RET(card->ctx, r, "verify pin failed");
}
else if (data->cmd == SC_PIN_CMD_CHANGE || data->cmd == SC_PIN_CMD_UNBLOCK) { /* change */
r = update_secret_key(card, 0x04, kid, data->pin2.data,
(unsigned long)data->pin2.len);
LOG_TEST_RET(card->ctx, r, "verify pin failed");
}
else {
r = external_key_auth(card, kid, (unsigned char *)data->pin1.data,
data->pin1.len);
get_external_key_retries(card, 0x80 | kid, &retries);
if (retries < pin_low)
sc_log(card->ctx, "Verification failed (remaining tries: %d)", retries);
}
LOG_TEST_RET(card->ctx, r, "verify pin failed");
if (r == SC_SUCCESS)
{
data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN;
}
return r;
}
static struct sc_card_driver *sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (iso_ops == NULL)
iso_ops = iso_drv->ops;
epass2003_ops = *iso_ops;
epass2003_ops.match_card = epass2003_match_card;
epass2003_ops.init = epass2003_init;
epass2003_ops.finish = epass2003_finish;
epass2003_ops.write_binary = NULL;
epass2003_ops.write_record = NULL;
epass2003_ops.select_file = epass2003_select_file;
epass2003_ops.get_response = NULL;
epass2003_ops.restore_security_env = epass2003_restore_security_env;
epass2003_ops.set_security_env = epass2003_set_security_env;
epass2003_ops.decipher = epass2003_decipher;
epass2003_ops.compute_signature = epass2003_decipher;
epass2003_ops.create_file = epass2003_create_file;
epass2003_ops.delete_file = epass2003_delete_file;
epass2003_ops.list_files = epass2003_list_files;
epass2003_ops.card_ctl = epass2003_card_ctl;
epass2003_ops.process_fci = epass2003_process_fci;
epass2003_ops.construct_fci = epass2003_construct_fci;
epass2003_ops.pin_cmd = epass2003_pin_cmd;
epass2003_ops.check_sw = epass2003_check_sw;
epass2003_ops.get_challenge = epass2003_get_challenge;
return &epass2003_drv;
}
struct sc_card_driver *sc_get_epass2003_driver(void)
{
return sc_get_driver();
}
#endif /* #ifdef ENABLE_OPENSSL */
#endif /* #ifdef ENABLE_SM */
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_343_1 |
crossvul-cpp_data_bad_346_3 | /*
* card-tcos.c: Support for TCOS cards
*
* Copyright (C) 2011 Peter Koch <pk@opensc-project.org>
* Copyright (C) 2002 g10 Code GmbH
* Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
static struct sc_atr_table tcos_atrs[] = {
/* Infineon SLE44 */
{ "3B:BA:13:00:81:31:86:5D:00:64:05:0A:02:01:31:80:90:00:8B", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66S */
{ "3B:BA:14:00:81:31:86:5D:00:64:05:14:02:02:31:80:90:00:91", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66CX320P */
{ "3B:BA:96:00:81:31:86:5D:00:64:05:60:02:03:31:80:90:00:66", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66CX322P */
{ "3B:BA:96:00:81:31:86:5D:00:64:05:7B:02:03:31:80:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Philips P5CT072 */
{ "3B:BF:96:00:81:31:FE:5D:00:64:04:11:03:01:31:C0:73:F7:01:D0:00:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
{ "3B:BF:96:00:81:31:FE:5D:00:64:04:11:04:0F:31:C0:73:F7:01:D0:00:90:00:74", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
/* Philips P5CT080 */
{ "3B:BF:B6:00:81:31:FE:5D:00:64:04:28:03:02:31:C0:73:F7:01:D0:00:90:00:67", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
static struct sc_card_operations tcos_ops;
static struct sc_card_driver tcos_drv = {
"TCOS 3.0",
"tcos",
&tcos_ops,
NULL, 0, NULL
};
static const struct sc_card_operations *iso_ops = NULL;
typedef struct tcos_data_st {
unsigned int pad_flags;
unsigned int next_sign;
} tcos_data;
static int tcos_finish(sc_card_t *card)
{
free(card->drv_data);
return 0;
}
static int tcos_match_card(sc_card_t *card)
{
int i;
i = _sc_match_atr(card, tcos_atrs, &card->type);
if (i < 0)
return 0;
return 1;
}
static int tcos_init(sc_card_t *card)
{
unsigned long flags;
tcos_data *data = malloc(sizeof(tcos_data));
if (!data) return SC_ERROR_OUT_OF_MEMORY;
card->name = "TCOS";
card->drv_data = (void *)data;
card->cla = 0x00;
flags = SC_ALGORITHM_RSA_RAW;
flags |= SC_ALGORITHM_RSA_PAD_PKCS1;
flags |= SC_ALGORITHM_RSA_HASH_NONE;
_sc_card_add_rsa_alg(card, 512, flags, 0);
_sc_card_add_rsa_alg(card, 768, flags, 0);
_sc_card_add_rsa_alg(card, 1024, flags, 0);
if (card->type == SC_CARD_TYPE_TCOS_V3) {
card->caps |= SC_CARD_CAP_APDU_EXT;
_sc_card_add_rsa_alg(card, 1280, flags, 0);
_sc_card_add_rsa_alg(card, 1536, flags, 0);
_sc_card_add_rsa_alg(card, 1792, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
}
return 0;
}
/* Hmmm, I don't know what to do. It seems that the ACL design of
OpenSC should be enhanced to allow for the command based security
attributes of TCOS. FIXME: This just allows to create a very basic
file. */
static int tcos_construct_fci(const sc_file_t *file,
u8 *out, size_t *outlen)
{
u8 *p = out;
u8 buf[64];
size_t n;
/* FIXME: possible buffer overflow */
*p++ = 0x6F; /* FCI */
p++;
/* File size */
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
sc_asn1_put_tag(0x81, buf, 2, p, 16, &p);
/* File descriptor */
n = 0;
buf[n] = file->shareable ? 0x40 : 0;
switch (file->type) {
case SC_FILE_TYPE_WORKING_EF:
break;
case SC_FILE_TYPE_DF:
buf[0] |= 0x38;
break;
default:
return SC_ERROR_NOT_SUPPORTED;
}
buf[n++] |= file->ef_structure & 7;
if ( (file->ef_structure & 7) > 1) {
/* record structured file */
buf[n++] = 0x41; /* indicate 3rd byte */
buf[n++] = file->record_length;
}
sc_asn1_put_tag(0x82, buf, n, p, 8, &p);
/* File identifier */
buf[0] = (file->id >> 8) & 0xFF;
buf[1] = file->id & 0xFF;
sc_asn1_put_tag(0x83, buf, 2, p, 16, &p);
/* Directory name */
if (file->type == SC_FILE_TYPE_DF) {
if (file->namelen) {
sc_asn1_put_tag(0x84, file->name, file->namelen,
p, 16, &p);
}
else {
/* TCOS needs one, so we use a faked one */
snprintf ((char *) buf, sizeof(buf)-1, "foo-%lu",
(unsigned long) time (NULL));
sc_asn1_put_tag(0x84, buf, strlen ((char *) buf), p, 16, &p);
}
}
/* File descriptor extension */
if (file->prop_attr_len && file->prop_attr) {
n = file->prop_attr_len;
memcpy(buf, file->prop_attr, n);
}
else {
n = 0;
buf[n++] = 0x01; /* not invalidated, permanent */
if (file->type == SC_FILE_TYPE_WORKING_EF)
buf[n++] = 0x00; /* generic data file */
}
sc_asn1_put_tag(0x85, buf, n, p, 16, &p);
/* Security attributes */
if (file->sec_attr_len && file->sec_attr) {
memcpy(buf, file->sec_attr, file->sec_attr_len);
n = file->sec_attr_len;
}
else {
/* no attributes given - fall back to default one */
memcpy (buf+ 0, "\xa4\x00\x00\x00\xff\xff", 6); /* select */
memcpy (buf+ 6, "\xb0\x00\x00\x00\xff\xff", 6); /* read bin */
memcpy (buf+12, "\xd6\x00\x00\x00\xff\xff", 6); /* upd bin */
memcpy (buf+18, "\x60\x00\x00\x00\xff\xff", 6); /* admin grp*/
n = 24;
}
sc_asn1_put_tag(0x86, buf, n, p, sizeof (buf), &p);
/* fixup length of FCI */
out[1] = p - out - 2;
*outlen = p - out;
return 0;
}
static int tcos_create_file(sc_card_t *card, sc_file_t *file)
{
int r;
size_t len;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_apdu_t apdu;
len = SC_MAX_APDU_BUFFER_SIZE;
r = tcos_construct_fci(file, sbuf, &len);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "tcos_construct_fci() failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00);
apdu.cla |= 0x80; /* this is an proprietary extension */
apdu.lc = len;
apdu.datalen = len;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static unsigned int map_operations (int commandbyte )
{
unsigned int op = (unsigned int)-1;
switch ( (commandbyte & 0xfe) ) {
case 0xe2: /* append record */ op = SC_AC_OP_UPDATE; break;
case 0x24: /* change password */ op = SC_AC_OP_UPDATE; break;
case 0xe0: /* create */ op = SC_AC_OP_CREATE; break;
case 0xe4: /* delete */ op = SC_AC_OP_DELETE; break;
case 0xe8: /* exclude sfi */ op = SC_AC_OP_WRITE; break;
case 0x82: /* external auth */ op = SC_AC_OP_READ; break;
case 0xe6: /* include sfi */ op = SC_AC_OP_WRITE; break;
case 0x88: /* internal auth */ op = SC_AC_OP_READ; break;
case 0x04: /* invalidate */ op = SC_AC_OP_INVALIDATE; break;
case 0x2a: /* perform sec. op */ op = SC_AC_OP_SELECT; break;
case 0xb0: /* read binary */ op = SC_AC_OP_READ; break;
case 0xb2: /* read record */ op = SC_AC_OP_READ; break;
case 0x44: /* rehabilitate */ op = SC_AC_OP_REHABILITATE; break;
case 0xa4: /* select */ op = SC_AC_OP_SELECT; break;
case 0xee: /* set permanent */ op = SC_AC_OP_CREATE; break;
case 0x2c: /* unblock password */op = SC_AC_OP_WRITE; break;
case 0xd6: /* update binary */ op = SC_AC_OP_WRITE; break;
case 0xdc: /* update record */ op = SC_AC_OP_WRITE; break;
case 0x20: /* verify password */ op = SC_AC_OP_SELECT; break;
case 0x60: /* admin group */ op = SC_AC_OP_CREATE; break;
}
return op;
}
/* Hmmm, I don't know what to do. It seems that the ACL design of
OpenSC should be enhanced to allow for the command based security
attributes of TCOS. FIXME: This just allows to create a very basic
file. */
static void parse_sec_attr(sc_card_t *card,
sc_file_t *file, const u8 *buf, size_t len)
{
unsigned int op;
/* list directory is not covered by ACLs - so always add an entry */
sc_file_add_acl_entry (file, SC_AC_OP_LIST_FILES,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
/* FIXME: check for what LOCK is used */
sc_file_add_acl_entry (file, SC_AC_OP_LOCK,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
for (; len >= 6; len -= 6, buf += 6) {
/* FIXME: temporary hacks */
if (!memcmp(buf, "\xa4\x00\x00\x00\xff\xff", 6)) /* select */
sc_file_add_acl_entry (file, SC_AC_OP_SELECT,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\xb0\x00\x00\x00\xff\xff", 6)) /*read*/
sc_file_add_acl_entry (file, SC_AC_OP_READ,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\xd6\x00\x00\x00\xff\xff", 6)) /*upd*/
sc_file_add_acl_entry (file, SC_AC_OP_UPDATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\x60\x00\x00\x00\xff\xff", 6)) {/*adm */
sc_file_add_acl_entry (file, SC_AC_OP_WRITE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_CREATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_INVALIDATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_REHABILITATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
}
else {
/* the first byte tells use the command or the
command group. We have to mask bit 0
because this one distinguish between AND/OR
combination of PINs*/
op = map_operations (buf[0]);
if (op == (unsigned int)-1)
{
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"Unknown security command byte %02x\n",
buf[0]);
continue;
}
if (!buf[1])
sc_file_add_acl_entry (file, op,
SC_AC_NONE,
SC_AC_KEY_REF_NONE);
else
sc_file_add_acl_entry (file, op,
SC_AC_CHV, buf[1]);
if (!buf[2] && !buf[3])
sc_file_add_acl_entry (file, op,
SC_AC_NONE,
SC_AC_KEY_REF_NONE);
else
sc_file_add_acl_entry (file, op,
SC_AC_TERM,
(buf[2]<<8)|buf[3]);
}
}
}
static int tcos_select_file(sc_card_t *card,
const sc_path_t *in_path,
sc_file_t **file_out)
{
sc_context_t *ctx;
sc_apdu_t apdu;
sc_file_t *file=NULL;
u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
unsigned int i;
int r, pathlen;
assert(card != NULL && in_path != NULL);
ctx=card->ctx;
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS;
/* fall through */
case SC_PATH_TYPE_FROM_CURRENT:
apdu.p1 = 9;
break;
case SC_PATH_TYPE_DF_NAME:
apdu.p1 = 4;
break;
case SC_PATH_TYPE_PATH:
apdu.p1 = 8;
if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2;
if (pathlen == 0) apdu.p1 = 0;
break;
case SC_PATH_TYPE_PARENT:
apdu.p1 = 3;
pathlen = 0;
break;
default:
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
if (file_out != NULL) {
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = 256;
} else {
apdu.resplen = 0;
apdu.le = 0;
apdu.p2 = 0x0C;
apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT;
}
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r);
if (apdu.resplen < 1 || apdu.resp[0] != 0x62){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
file = sc_file_new();
if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
*file_out = file;
file->path = *in_path;
for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){
int j, len=apdu.resp[i+1];
unsigned char type=apdu.resp[i], *d=apdu.resp+i+2;
switch (type) {
case 0x80:
case 0x81:
file->size=0;
for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j];
break;
case 0x82:
file->shareable = (d[0] & 0x40) ? 1 : 0;
file->ef_structure = d[0] & 7;
switch ((d[0]>>3) & 7) {
case 0: file->type = SC_FILE_TYPE_WORKING_EF; break;
case 7: file->type = SC_FILE_TYPE_DF; break;
default:
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
break;
case 0x83:
file->id = (d[0]<<8) | d[1];
break;
case 0x84:
memcpy(file->name, d, len);
file->namelen = len;
break;
case 0x86:
sc_file_set_sec_attr(file, d, len);
break;
default:
if (len>0) sc_file_set_prop_attr(file, d, len);
}
}
file->magic = SC_FILE_MAGIC;
parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len);
return 0;
}
static int tcos_list_files(sc_card_t *card, u8 *buf, size_t buflen)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE], p1;
int r, count = 0;
assert(card != NULL);
ctx = card->ctx;
for (p1=1; p1<=2; p1++) {
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xAA, p1, 0);
apdu.cla = 0x80;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1==0x6A && (apdu.sw2==0x82 || apdu.sw2==0x88)) continue;
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "List Dir failed");
if (apdu.resplen > buflen) return SC_ERROR_BUFFER_TOO_SMALL;
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"got %"SC_FORMAT_LEN_SIZE_T"u %s-FileIDs\n",
apdu.resplen / 2, p1 == 1 ? "DF" : "EF");
memcpy(buf, apdu.resp, apdu.resplen);
buf += apdu.resplen;
buflen -= apdu.resplen;
count += apdu.resplen;
}
return count;
}
static int tcos_delete_file(sc_card_t *card, const sc_path_t *path)
{
int r;
u8 sbuf[2];
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (path->type != SC_PATH_TYPE_FILE_ID && path->len != 2) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File type has to be SC_PATH_TYPE_FILE_ID\n");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
}
sbuf[0] = path->value[0];
sbuf[1] = path->value[1];
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.lc = 2;
apdu.datalen = 2;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static int tcos_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE], *p;
int r, default_key, tcos3;
tcos_data *data;
assert(card != NULL && env != NULL);
ctx = card->ctx;
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
data=(tcos_data *)card->drv_data;
if (se_num || (env->operation!=SC_SEC_OPERATION_DECIPHER && env->operation!=SC_SEC_OPERATION_SIGN)){
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
}
if(!(env->flags & SC_SEC_ENV_KEY_REF_PRESENT))
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"No Key-Reference in SecEnvironment\n");
else
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Key-Reference %02X (len=%"SC_FORMAT_LEN_SIZE_T"u)\n",
env->key_ref[0], env->key_ref_len);
/* Key-Reference 0x80 ?? */
default_key= !(env->flags & SC_SEC_ENV_KEY_REF_PRESENT) || (env->key_ref_len==1 && env->key_ref[0]==0x80);
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"TCOS3:%d PKCS1:%d\n", tcos3,
!!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1));
data->pad_flags = env->algorithm_flags;
data->next_sign = default_key;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, tcos3 ? 0x41 : 0xC1, 0xB8);
p = sbuf;
*p++=0x80; *p++=0x01; *p++=tcos3 ? 0x0A : 0x10;
if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) {
*p++ = (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) ? 0x83 : 0x84;
*p++ = env->key_ref_len;
memcpy(p, env->key_ref, env->key_ref_len);
p += env->key_ref_len;
}
apdu.data = sbuf;
apdu.lc = apdu.datalen = (p - sbuf);
r=sc_transmit_apdu(card, &apdu);
if (r) {
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"%s: APDU transmit failed", sc_strerror(r));
return r;
}
if (apdu.sw1==0x6A && (apdu.sw2==0x81 || apdu.sw2==0x88)) {
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Detected Signature-Only key\n");
if (env->operation==SC_SEC_OPERATION_SIGN && default_key) return SC_SUCCESS;
}
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int tcos_restore_security_env(sc_card_t *card, int se_num)
{
return 0;
}
static int tcos_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen)
{
size_t i, dlen=datalen;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
int tcos3, r;
assert(card != NULL && data != NULL && out != NULL);
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
if (datalen > 255) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
if(((tcos_data *)card->drv_data)->next_sign){
if(datalen>48){
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Data to be signed is too long (TCOS supports max. 48 bytes)\n");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x9E, 0x9A);
memcpy(sbuf, data, datalen);
dlen=datalen;
} else {
int keylen= tcos3 ? 256 : 128;
sc_format_apdu(card, &apdu, keylen>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86);
for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff;
sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00;
memcpy(sbuf+keylen-datalen+1, data, datalen);
dlen=keylen+1;
}
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = tcos3 ? 256 : 128;
apdu.data = sbuf;
apdu.lc = apdu.datalen = dlen;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (tcos3 && apdu.p1==0x80 && apdu.sw1==0x6A && apdu.sw2==0x87) {
int keylen=128;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86);
for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff;
sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00;
memcpy(sbuf+keylen-datalen+1, data, datalen);
dlen=keylen+1;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 128;
apdu.data = sbuf;
apdu.lc = apdu.datalen = dlen;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
}
if (apdu.sw1==0x90 && apdu.sw2==0x00) {
size_t len = apdu.resplen>outlen ? outlen : apdu.resplen;
memcpy(out, apdu.resp, len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
tcos_data *data;
int tcos3, r;
assert(card != NULL && crgram != NULL && out != NULL);
ctx = card->ctx;
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
data=(tcos_data *)card->drv_data;
SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_NORMAL);
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"TCOS3:%d PKCS1:%d\n",tcos3,
!!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1));
sc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = crgram_len;
apdu.data = sbuf;
apdu.lc = apdu.datalen = crgram_len+1;
sbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02);
memcpy(sbuf+1, crgram, crgram_len);
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1==0x90 && apdu.sw2==0x00) {
size_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen;
unsigned int offset=0;
if(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2){
offset=2; while(offset<len && apdu.resp[offset]!=0) ++offset;
offset=(offset<len-1) ? offset+1 : 0;
}
memcpy(out, apdu.resp+offset, len-offset);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len-offset);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
/* Issue the SET PERMANENT command. With ENABLE_NULLPIN set the
NullPIN method will be activated, otherwise the permanent operation
will be done on the active file. */
static int tcos_setperm(sc_card_t *card, int enable_nullpin)
{
int r;
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xEE, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.lc = 0;
apdu.datalen = 0;
apdu.data = NULL;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static int tcos_get_serialnr(sc_card_t *card, sc_serial_number_t *serial)
{
int r;
if (!serial)
return SC_ERROR_INVALID_ARGUMENTS;
/* see if we have cached serial number */
if (card->serialnr.len) {
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
card->serialnr.len = sizeof card->serialnr.value;
r = sc_parse_ef_gdo(card, card->serialnr.value, &card->serialnr.len, NULL, 0);
if (r < 0) {
card->serialnr.len = 0;
return r;
}
/* copy and return serial number */
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
static int tcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
switch (cmd) {
case SC_CARDCTL_TCOS_SETPERM:
return tcos_setperm(card, !!ptr);
case SC_CARDCTL_GET_SERIALNR:
return tcos_get_serialnr(card, (sc_serial_number_t *)ptr);
}
return SC_ERROR_NOT_SUPPORTED;
}
struct sc_card_driver * sc_get_tcos_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (iso_ops == NULL) iso_ops = iso_drv->ops;
tcos_ops = *iso_drv->ops;
tcos_ops.match_card = tcos_match_card;
tcos_ops.init = tcos_init;
tcos_ops.finish = tcos_finish;
tcos_ops.create_file = tcos_create_file;
tcos_ops.set_security_env = tcos_set_security_env;
tcos_ops.select_file = tcos_select_file;
tcos_ops.list_files = tcos_list_files;
tcos_ops.delete_file = tcos_delete_file;
tcos_ops.set_security_env = tcos_set_security_env;
tcos_ops.compute_signature = tcos_compute_signature;
tcos_ops.decipher = tcos_decipher;
tcos_ops.restore_security_env = tcos_restore_security_env;
tcos_ops.card_ctl = tcos_card_ctl;
return &tcos_drv;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_346_3 |
crossvul-cpp_data_good_1618_0 | /*******************************************************************************
* Vhost kernel TCM fabric driver for virtio SCSI initiators
*
* (C) Copyright 2010-2013 Datera, Inc.
* (C) Copyright 2010-2012 IBM Corp.
*
* Licensed to the Linux Foundation under the General Public License (GPL) version 2.
*
* Authors: Nicholas A. Bellinger <nab@daterainc.com>
* Stefan Hajnoczi <stefanha@linux.vnet.ibm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
****************************************************************************/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <generated/utsrelease.h>
#include <linux/utsname.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/kthread.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/configfs.h>
#include <linux/ctype.h>
#include <linux/compat.h>
#include <linux/eventfd.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <asm/unaligned.h>
#include <scsi/scsi.h>
#include <target/target_core_base.h>
#include <target/target_core_fabric.h>
#include <target/target_core_fabric_configfs.h>
#include <target/target_core_configfs.h>
#include <target/configfs_macros.h>
#include <linux/vhost.h>
#include <linux/virtio_scsi.h>
#include <linux/llist.h>
#include <linux/bitmap.h>
#include <linux/percpu_ida.h>
#include "vhost.h"
#define VHOST_SCSI_VERSION "v0.1"
#define VHOST_SCSI_NAMELEN 256
#define VHOST_SCSI_MAX_CDB_SIZE 32
#define VHOST_SCSI_DEFAULT_TAGS 256
#define VHOST_SCSI_PREALLOC_SGLS 2048
#define VHOST_SCSI_PREALLOC_UPAGES 2048
#define VHOST_SCSI_PREALLOC_PROT_SGLS 512
struct vhost_scsi_inflight {
/* Wait for the flush operation to finish */
struct completion comp;
/* Refcount for the inflight reqs */
struct kref kref;
};
struct vhost_scsi_cmd {
/* Descriptor from vhost_get_vq_desc() for virt_queue segment */
int tvc_vq_desc;
/* virtio-scsi initiator task attribute */
int tvc_task_attr;
/* virtio-scsi response incoming iovecs */
int tvc_in_iovs;
/* virtio-scsi initiator data direction */
enum dma_data_direction tvc_data_direction;
/* Expected data transfer length from virtio-scsi header */
u32 tvc_exp_data_len;
/* The Tag from include/linux/virtio_scsi.h:struct virtio_scsi_cmd_req */
u64 tvc_tag;
/* The number of scatterlists associated with this cmd */
u32 tvc_sgl_count;
u32 tvc_prot_sgl_count;
/* Saved unpacked SCSI LUN for vhost_scsi_submission_work() */
u32 tvc_lun;
/* Pointer to the SGL formatted memory from virtio-scsi */
struct scatterlist *tvc_sgl;
struct scatterlist *tvc_prot_sgl;
struct page **tvc_upages;
/* Pointer to response header iovec */
struct iovec *tvc_resp_iov;
/* Pointer to vhost_scsi for our device */
struct vhost_scsi *tvc_vhost;
/* Pointer to vhost_virtqueue for the cmd */
struct vhost_virtqueue *tvc_vq;
/* Pointer to vhost nexus memory */
struct vhost_scsi_nexus *tvc_nexus;
/* The TCM I/O descriptor that is accessed via container_of() */
struct se_cmd tvc_se_cmd;
/* work item used for cmwq dispatch to vhost_scsi_submission_work() */
struct work_struct work;
/* Copy of the incoming SCSI command descriptor block (CDB) */
unsigned char tvc_cdb[VHOST_SCSI_MAX_CDB_SIZE];
/* Sense buffer that will be mapped into outgoing status */
unsigned char tvc_sense_buf[TRANSPORT_SENSE_BUFFER];
/* Completed commands list, serviced from vhost worker thread */
struct llist_node tvc_completion_list;
/* Used to track inflight cmd */
struct vhost_scsi_inflight *inflight;
};
struct vhost_scsi_nexus {
/* Pointer to TCM session for I_T Nexus */
struct se_session *tvn_se_sess;
};
struct vhost_scsi_nacl {
/* Binary World Wide unique Port Name for Vhost Initiator port */
u64 iport_wwpn;
/* ASCII formatted WWPN for Sas Initiator port */
char iport_name[VHOST_SCSI_NAMELEN];
/* Returned by vhost_scsi_make_nodeacl() */
struct se_node_acl se_node_acl;
};
struct vhost_scsi_tpg {
/* Vhost port target portal group tag for TCM */
u16 tport_tpgt;
/* Used to track number of TPG Port/Lun Links wrt to explict I_T Nexus shutdown */
int tv_tpg_port_count;
/* Used for vhost_scsi device reference to tpg_nexus, protected by tv_tpg_mutex */
int tv_tpg_vhost_count;
/* list for vhost_scsi_list */
struct list_head tv_tpg_list;
/* Used to protect access for tpg_nexus */
struct mutex tv_tpg_mutex;
/* Pointer to the TCM VHost I_T Nexus for this TPG endpoint */
struct vhost_scsi_nexus *tpg_nexus;
/* Pointer back to vhost_scsi_tport */
struct vhost_scsi_tport *tport;
/* Returned by vhost_scsi_make_tpg() */
struct se_portal_group se_tpg;
/* Pointer back to vhost_scsi, protected by tv_tpg_mutex */
struct vhost_scsi *vhost_scsi;
};
struct vhost_scsi_tport {
/* SCSI protocol the tport is providing */
u8 tport_proto_id;
/* Binary World Wide unique Port Name for Vhost Target port */
u64 tport_wwpn;
/* ASCII formatted WWPN for Vhost Target port */
char tport_name[VHOST_SCSI_NAMELEN];
/* Returned by vhost_scsi_make_tport() */
struct se_wwn tport_wwn;
};
struct vhost_scsi_evt {
/* event to be sent to guest */
struct virtio_scsi_event event;
/* event list, serviced from vhost worker thread */
struct llist_node list;
};
enum {
VHOST_SCSI_VQ_CTL = 0,
VHOST_SCSI_VQ_EVT = 1,
VHOST_SCSI_VQ_IO = 2,
};
/* Note: can't set VIRTIO_F_VERSION_1 yet, since that implies ANY_LAYOUT. */
enum {
VHOST_SCSI_FEATURES = VHOST_FEATURES | (1ULL << VIRTIO_SCSI_F_HOTPLUG) |
(1ULL << VIRTIO_SCSI_F_T10_PI) |
(1ULL << VIRTIO_F_ANY_LAYOUT) |
(1ULL << VIRTIO_F_VERSION_1)
};
#define VHOST_SCSI_MAX_TARGET 256
#define VHOST_SCSI_MAX_VQ 128
#define VHOST_SCSI_MAX_EVENT 128
struct vhost_scsi_virtqueue {
struct vhost_virtqueue vq;
/*
* Reference counting for inflight reqs, used for flush operation. At
* each time, one reference tracks new commands submitted, while we
* wait for another one to reach 0.
*/
struct vhost_scsi_inflight inflights[2];
/*
* Indicate current inflight in use, protected by vq->mutex.
* Writers must also take dev mutex and flush under it.
*/
int inflight_idx;
};
struct vhost_scsi {
/* Protected by vhost_scsi->dev.mutex */
struct vhost_scsi_tpg **vs_tpg;
char vs_vhost_wwpn[TRANSPORT_IQN_LEN];
struct vhost_dev dev;
struct vhost_scsi_virtqueue vqs[VHOST_SCSI_MAX_VQ];
struct vhost_work vs_completion_work; /* cmd completion work item */
struct llist_head vs_completion_list; /* cmd completion queue */
struct vhost_work vs_event_work; /* evt injection work item */
struct llist_head vs_event_list; /* evt injection queue */
bool vs_events_missed; /* any missed events, protected by vq->mutex */
int vs_events_nr; /* num of pending events, protected by vq->mutex */
};
/* Local pointer to allocated TCM configfs fabric module */
static struct target_fabric_configfs *vhost_scsi_fabric_configfs;
static struct workqueue_struct *vhost_scsi_workqueue;
/* Global spinlock to protect vhost_scsi TPG list for vhost IOCTL access */
static DEFINE_MUTEX(vhost_scsi_mutex);
static LIST_HEAD(vhost_scsi_list);
static int iov_num_pages(void __user *iov_base, size_t iov_len)
{
return (PAGE_ALIGN((unsigned long)iov_base + iov_len) -
((unsigned long)iov_base & PAGE_MASK)) >> PAGE_SHIFT;
}
static void vhost_scsi_done_inflight(struct kref *kref)
{
struct vhost_scsi_inflight *inflight;
inflight = container_of(kref, struct vhost_scsi_inflight, kref);
complete(&inflight->comp);
}
static void vhost_scsi_init_inflight(struct vhost_scsi *vs,
struct vhost_scsi_inflight *old_inflight[])
{
struct vhost_scsi_inflight *new_inflight;
struct vhost_virtqueue *vq;
int idx, i;
for (i = 0; i < VHOST_SCSI_MAX_VQ; i++) {
vq = &vs->vqs[i].vq;
mutex_lock(&vq->mutex);
/* store old infight */
idx = vs->vqs[i].inflight_idx;
if (old_inflight)
old_inflight[i] = &vs->vqs[i].inflights[idx];
/* setup new infight */
vs->vqs[i].inflight_idx = idx ^ 1;
new_inflight = &vs->vqs[i].inflights[idx ^ 1];
kref_init(&new_inflight->kref);
init_completion(&new_inflight->comp);
mutex_unlock(&vq->mutex);
}
}
static struct vhost_scsi_inflight *
vhost_scsi_get_inflight(struct vhost_virtqueue *vq)
{
struct vhost_scsi_inflight *inflight;
struct vhost_scsi_virtqueue *svq;
svq = container_of(vq, struct vhost_scsi_virtqueue, vq);
inflight = &svq->inflights[svq->inflight_idx];
kref_get(&inflight->kref);
return inflight;
}
static void vhost_scsi_put_inflight(struct vhost_scsi_inflight *inflight)
{
kref_put(&inflight->kref, vhost_scsi_done_inflight);
}
static int vhost_scsi_check_true(struct se_portal_group *se_tpg)
{
return 1;
}
static int vhost_scsi_check_false(struct se_portal_group *se_tpg)
{
return 0;
}
static char *vhost_scsi_get_fabric_name(void)
{
return "vhost";
}
static u8 vhost_scsi_get_fabric_proto_ident(struct se_portal_group *se_tpg)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
struct vhost_scsi_tport *tport = tpg->tport;
switch (tport->tport_proto_id) {
case SCSI_PROTOCOL_SAS:
return sas_get_fabric_proto_ident(se_tpg);
case SCSI_PROTOCOL_FCP:
return fc_get_fabric_proto_ident(se_tpg);
case SCSI_PROTOCOL_ISCSI:
return iscsi_get_fabric_proto_ident(se_tpg);
default:
pr_err("Unknown tport_proto_id: 0x%02x, using"
" SAS emulation\n", tport->tport_proto_id);
break;
}
return sas_get_fabric_proto_ident(se_tpg);
}
static char *vhost_scsi_get_fabric_wwn(struct se_portal_group *se_tpg)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
struct vhost_scsi_tport *tport = tpg->tport;
return &tport->tport_name[0];
}
static u16 vhost_scsi_get_tpgt(struct se_portal_group *se_tpg)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
return tpg->tport_tpgt;
}
static u32 vhost_scsi_get_default_depth(struct se_portal_group *se_tpg)
{
return 1;
}
static u32
vhost_scsi_get_pr_transport_id(struct se_portal_group *se_tpg,
struct se_node_acl *se_nacl,
struct t10_pr_registration *pr_reg,
int *format_code,
unsigned char *buf)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
struct vhost_scsi_tport *tport = tpg->tport;
switch (tport->tport_proto_id) {
case SCSI_PROTOCOL_SAS:
return sas_get_pr_transport_id(se_tpg, se_nacl, pr_reg,
format_code, buf);
case SCSI_PROTOCOL_FCP:
return fc_get_pr_transport_id(se_tpg, se_nacl, pr_reg,
format_code, buf);
case SCSI_PROTOCOL_ISCSI:
return iscsi_get_pr_transport_id(se_tpg, se_nacl, pr_reg,
format_code, buf);
default:
pr_err("Unknown tport_proto_id: 0x%02x, using"
" SAS emulation\n", tport->tport_proto_id);
break;
}
return sas_get_pr_transport_id(se_tpg, se_nacl, pr_reg,
format_code, buf);
}
static u32
vhost_scsi_get_pr_transport_id_len(struct se_portal_group *se_tpg,
struct se_node_acl *se_nacl,
struct t10_pr_registration *pr_reg,
int *format_code)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
struct vhost_scsi_tport *tport = tpg->tport;
switch (tport->tport_proto_id) {
case SCSI_PROTOCOL_SAS:
return sas_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,
format_code);
case SCSI_PROTOCOL_FCP:
return fc_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,
format_code);
case SCSI_PROTOCOL_ISCSI:
return iscsi_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,
format_code);
default:
pr_err("Unknown tport_proto_id: 0x%02x, using"
" SAS emulation\n", tport->tport_proto_id);
break;
}
return sas_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,
format_code);
}
static char *
vhost_scsi_parse_pr_out_transport_id(struct se_portal_group *se_tpg,
const char *buf,
u32 *out_tid_len,
char **port_nexus_ptr)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
struct vhost_scsi_tport *tport = tpg->tport;
switch (tport->tport_proto_id) {
case SCSI_PROTOCOL_SAS:
return sas_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
port_nexus_ptr);
case SCSI_PROTOCOL_FCP:
return fc_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
port_nexus_ptr);
case SCSI_PROTOCOL_ISCSI:
return iscsi_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
port_nexus_ptr);
default:
pr_err("Unknown tport_proto_id: 0x%02x, using"
" SAS emulation\n", tport->tport_proto_id);
break;
}
return sas_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
port_nexus_ptr);
}
static struct se_node_acl *
vhost_scsi_alloc_fabric_acl(struct se_portal_group *se_tpg)
{
struct vhost_scsi_nacl *nacl;
nacl = kzalloc(sizeof(struct vhost_scsi_nacl), GFP_KERNEL);
if (!nacl) {
pr_err("Unable to allocate struct vhost_scsi_nacl\n");
return NULL;
}
return &nacl->se_node_acl;
}
static void
vhost_scsi_release_fabric_acl(struct se_portal_group *se_tpg,
struct se_node_acl *se_nacl)
{
struct vhost_scsi_nacl *nacl = container_of(se_nacl,
struct vhost_scsi_nacl, se_node_acl);
kfree(nacl);
}
static u32 vhost_scsi_tpg_get_inst_index(struct se_portal_group *se_tpg)
{
return 1;
}
static void vhost_scsi_release_cmd(struct se_cmd *se_cmd)
{
struct vhost_scsi_cmd *tv_cmd = container_of(se_cmd,
struct vhost_scsi_cmd, tvc_se_cmd);
struct se_session *se_sess = tv_cmd->tvc_nexus->tvn_se_sess;
int i;
if (tv_cmd->tvc_sgl_count) {
for (i = 0; i < tv_cmd->tvc_sgl_count; i++)
put_page(sg_page(&tv_cmd->tvc_sgl[i]));
}
if (tv_cmd->tvc_prot_sgl_count) {
for (i = 0; i < tv_cmd->tvc_prot_sgl_count; i++)
put_page(sg_page(&tv_cmd->tvc_prot_sgl[i]));
}
vhost_scsi_put_inflight(tv_cmd->inflight);
percpu_ida_free(&se_sess->sess_tag_pool, se_cmd->map_tag);
}
static int vhost_scsi_shutdown_session(struct se_session *se_sess)
{
return 0;
}
static void vhost_scsi_close_session(struct se_session *se_sess)
{
return;
}
static u32 vhost_scsi_sess_get_index(struct se_session *se_sess)
{
return 0;
}
static int vhost_scsi_write_pending(struct se_cmd *se_cmd)
{
/* Go ahead and process the write immediately */
target_execute_cmd(se_cmd);
return 0;
}
static int vhost_scsi_write_pending_status(struct se_cmd *se_cmd)
{
return 0;
}
static void vhost_scsi_set_default_node_attrs(struct se_node_acl *nacl)
{
return;
}
static u32 vhost_scsi_get_task_tag(struct se_cmd *se_cmd)
{
return 0;
}
static int vhost_scsi_get_cmd_state(struct se_cmd *se_cmd)
{
return 0;
}
static void vhost_scsi_complete_cmd(struct vhost_scsi_cmd *cmd)
{
struct vhost_scsi *vs = cmd->tvc_vhost;
llist_add(&cmd->tvc_completion_list, &vs->vs_completion_list);
vhost_work_queue(&vs->dev, &vs->vs_completion_work);
}
static int vhost_scsi_queue_data_in(struct se_cmd *se_cmd)
{
struct vhost_scsi_cmd *cmd = container_of(se_cmd,
struct vhost_scsi_cmd, tvc_se_cmd);
vhost_scsi_complete_cmd(cmd);
return 0;
}
static int vhost_scsi_queue_status(struct se_cmd *se_cmd)
{
struct vhost_scsi_cmd *cmd = container_of(se_cmd,
struct vhost_scsi_cmd, tvc_se_cmd);
vhost_scsi_complete_cmd(cmd);
return 0;
}
static void vhost_scsi_queue_tm_rsp(struct se_cmd *se_cmd)
{
return;
}
static void vhost_scsi_aborted_task(struct se_cmd *se_cmd)
{
return;
}
static void vhost_scsi_free_evt(struct vhost_scsi *vs, struct vhost_scsi_evt *evt)
{
vs->vs_events_nr--;
kfree(evt);
}
static struct vhost_scsi_evt *
vhost_scsi_allocate_evt(struct vhost_scsi *vs,
u32 event, u32 reason)
{
struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
struct vhost_scsi_evt *evt;
if (vs->vs_events_nr > VHOST_SCSI_MAX_EVENT) {
vs->vs_events_missed = true;
return NULL;
}
evt = kzalloc(sizeof(*evt), GFP_KERNEL);
if (!evt) {
vq_err(vq, "Failed to allocate vhost_scsi_evt\n");
vs->vs_events_missed = true;
return NULL;
}
evt->event.event = cpu_to_vhost32(vq, event);
evt->event.reason = cpu_to_vhost32(vq, reason);
vs->vs_events_nr++;
return evt;
}
static void vhost_scsi_free_cmd(struct vhost_scsi_cmd *cmd)
{
struct se_cmd *se_cmd = &cmd->tvc_se_cmd;
/* TODO locking against target/backend threads? */
transport_generic_free_cmd(se_cmd, 0);
}
static int vhost_scsi_check_stop_free(struct se_cmd *se_cmd)
{
return target_put_sess_cmd(se_cmd->se_sess, se_cmd);
}
static void
vhost_scsi_do_evt_work(struct vhost_scsi *vs, struct vhost_scsi_evt *evt)
{
struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
struct virtio_scsi_event *event = &evt->event;
struct virtio_scsi_event __user *eventp;
unsigned out, in;
int head, ret;
if (!vq->private_data) {
vs->vs_events_missed = true;
return;
}
again:
vhost_disable_notify(&vs->dev, vq);
head = vhost_get_vq_desc(vq, vq->iov,
ARRAY_SIZE(vq->iov), &out, &in,
NULL, NULL);
if (head < 0) {
vs->vs_events_missed = true;
return;
}
if (head == vq->num) {
if (vhost_enable_notify(&vs->dev, vq))
goto again;
vs->vs_events_missed = true;
return;
}
if ((vq->iov[out].iov_len != sizeof(struct virtio_scsi_event))) {
vq_err(vq, "Expecting virtio_scsi_event, got %zu bytes\n",
vq->iov[out].iov_len);
vs->vs_events_missed = true;
return;
}
if (vs->vs_events_missed) {
event->event |= cpu_to_vhost32(vq, VIRTIO_SCSI_T_EVENTS_MISSED);
vs->vs_events_missed = false;
}
eventp = vq->iov[out].iov_base;
ret = __copy_to_user(eventp, event, sizeof(*event));
if (!ret)
vhost_add_used_and_signal(&vs->dev, vq, head, 0);
else
vq_err(vq, "Faulted on vhost_scsi_send_event\n");
}
static void vhost_scsi_evt_work(struct vhost_work *work)
{
struct vhost_scsi *vs = container_of(work, struct vhost_scsi,
vs_event_work);
struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
struct vhost_scsi_evt *evt;
struct llist_node *llnode;
mutex_lock(&vq->mutex);
llnode = llist_del_all(&vs->vs_event_list);
while (llnode) {
evt = llist_entry(llnode, struct vhost_scsi_evt, list);
llnode = llist_next(llnode);
vhost_scsi_do_evt_work(vs, evt);
vhost_scsi_free_evt(vs, evt);
}
mutex_unlock(&vq->mutex);
}
/* Fill in status and signal that we are done processing this command
*
* This is scheduled in the vhost work queue so we are called with the owner
* process mm and can access the vring.
*/
static void vhost_scsi_complete_cmd_work(struct vhost_work *work)
{
struct vhost_scsi *vs = container_of(work, struct vhost_scsi,
vs_completion_work);
DECLARE_BITMAP(signal, VHOST_SCSI_MAX_VQ);
struct virtio_scsi_cmd_resp v_rsp;
struct vhost_scsi_cmd *cmd;
struct llist_node *llnode;
struct se_cmd *se_cmd;
struct iov_iter iov_iter;
int ret, vq;
bitmap_zero(signal, VHOST_SCSI_MAX_VQ);
llnode = llist_del_all(&vs->vs_completion_list);
while (llnode) {
cmd = llist_entry(llnode, struct vhost_scsi_cmd,
tvc_completion_list);
llnode = llist_next(llnode);
se_cmd = &cmd->tvc_se_cmd;
pr_debug("%s tv_cmd %p resid %u status %#02x\n", __func__,
cmd, se_cmd->residual_count, se_cmd->scsi_status);
memset(&v_rsp, 0, sizeof(v_rsp));
v_rsp.resid = cpu_to_vhost32(cmd->tvc_vq, se_cmd->residual_count);
/* TODO is status_qualifier field needed? */
v_rsp.status = se_cmd->scsi_status;
v_rsp.sense_len = cpu_to_vhost32(cmd->tvc_vq,
se_cmd->scsi_sense_length);
memcpy(v_rsp.sense, cmd->tvc_sense_buf,
se_cmd->scsi_sense_length);
iov_iter_init(&iov_iter, READ, cmd->tvc_resp_iov,
cmd->tvc_in_iovs, sizeof(v_rsp));
ret = copy_to_iter(&v_rsp, sizeof(v_rsp), &iov_iter);
if (likely(ret == sizeof(v_rsp))) {
struct vhost_scsi_virtqueue *q;
vhost_add_used(cmd->tvc_vq, cmd->tvc_vq_desc, 0);
q = container_of(cmd->tvc_vq, struct vhost_scsi_virtqueue, vq);
vq = q - vs->vqs;
__set_bit(vq, signal);
} else
pr_err("Faulted on virtio_scsi_cmd_resp\n");
vhost_scsi_free_cmd(cmd);
}
vq = -1;
while ((vq = find_next_bit(signal, VHOST_SCSI_MAX_VQ, vq + 1))
< VHOST_SCSI_MAX_VQ)
vhost_signal(&vs->dev, &vs->vqs[vq].vq);
}
static struct vhost_scsi_cmd *
vhost_scsi_get_tag(struct vhost_virtqueue *vq, struct vhost_scsi_tpg *tpg,
unsigned char *cdb, u64 scsi_tag, u16 lun, u8 task_attr,
u32 exp_data_len, int data_direction)
{
struct vhost_scsi_cmd *cmd;
struct vhost_scsi_nexus *tv_nexus;
struct se_session *se_sess;
struct scatterlist *sg, *prot_sg;
struct page **pages;
int tag;
tv_nexus = tpg->tpg_nexus;
if (!tv_nexus) {
pr_err("Unable to locate active struct vhost_scsi_nexus\n");
return ERR_PTR(-EIO);
}
se_sess = tv_nexus->tvn_se_sess;
tag = percpu_ida_alloc(&se_sess->sess_tag_pool, TASK_RUNNING);
if (tag < 0) {
pr_err("Unable to obtain tag for vhost_scsi_cmd\n");
return ERR_PTR(-ENOMEM);
}
cmd = &((struct vhost_scsi_cmd *)se_sess->sess_cmd_map)[tag];
sg = cmd->tvc_sgl;
prot_sg = cmd->tvc_prot_sgl;
pages = cmd->tvc_upages;
memset(cmd, 0, sizeof(struct vhost_scsi_cmd));
cmd->tvc_sgl = sg;
cmd->tvc_prot_sgl = prot_sg;
cmd->tvc_upages = pages;
cmd->tvc_se_cmd.map_tag = tag;
cmd->tvc_tag = scsi_tag;
cmd->tvc_lun = lun;
cmd->tvc_task_attr = task_attr;
cmd->tvc_exp_data_len = exp_data_len;
cmd->tvc_data_direction = data_direction;
cmd->tvc_nexus = tv_nexus;
cmd->inflight = vhost_scsi_get_inflight(vq);
memcpy(cmd->tvc_cdb, cdb, VHOST_SCSI_MAX_CDB_SIZE);
return cmd;
}
/*
* Map a user memory range into a scatterlist
*
* Returns the number of scatterlist entries used or -errno on error.
*/
static int
vhost_scsi_map_to_sgl(struct vhost_scsi_cmd *cmd,
void __user *ptr,
size_t len,
struct scatterlist *sgl,
bool write)
{
unsigned int npages = 0, offset, nbytes;
unsigned int pages_nr = iov_num_pages(ptr, len);
struct scatterlist *sg = sgl;
struct page **pages = cmd->tvc_upages;
int ret, i;
if (pages_nr > VHOST_SCSI_PREALLOC_UPAGES) {
pr_err("vhost_scsi_map_to_sgl() pages_nr: %u greater than"
" preallocated VHOST_SCSI_PREALLOC_UPAGES: %u\n",
pages_nr, VHOST_SCSI_PREALLOC_UPAGES);
return -ENOBUFS;
}
ret = get_user_pages_fast((unsigned long)ptr, pages_nr, write, pages);
/* No pages were pinned */
if (ret < 0)
goto out;
/* Less pages pinned than wanted */
if (ret != pages_nr) {
for (i = 0; i < ret; i++)
put_page(pages[i]);
ret = -EFAULT;
goto out;
}
while (len > 0) {
offset = (uintptr_t)ptr & ~PAGE_MASK;
nbytes = min_t(unsigned int, PAGE_SIZE - offset, len);
sg_set_page(sg, pages[npages], nbytes, offset);
ptr += nbytes;
len -= nbytes;
sg++;
npages++;
}
out:
return ret;
}
static int
vhost_scsi_calc_sgls(struct iov_iter *iter, size_t bytes, int max_sgls)
{
int sgl_count = 0;
if (!iter || !iter->iov) {
pr_err("%s: iter->iov is NULL, but expected bytes: %zu"
" present\n", __func__, bytes);
return -EINVAL;
}
sgl_count = iov_iter_npages(iter, 0xffff);
if (sgl_count > max_sgls) {
pr_err("%s: requested sgl_count: %d exceeds pre-allocated"
" max_sgls: %d\n", __func__, sgl_count, max_sgls);
return -EINVAL;
}
return sgl_count;
}
static int
vhost_scsi_iov_to_sgl(struct vhost_scsi_cmd *cmd, bool write,
struct iov_iter *iter,
struct scatterlist *sg, int sg_count)
{
size_t off = iter->iov_offset;
int i, ret;
for (i = 0; i < iter->nr_segs; i++) {
void __user *base = iter->iov[i].iov_base + off;
size_t len = iter->iov[i].iov_len - off;
ret = vhost_scsi_map_to_sgl(cmd, base, len, sg, write);
if (ret < 0) {
for (i = 0; i < sg_count; i++) {
struct page *page = sg_page(&sg[i]);
if (page)
put_page(page);
}
return ret;
}
sg += ret;
off = 0;
}
return 0;
}
static int
vhost_scsi_mapal(struct vhost_scsi_cmd *cmd,
size_t prot_bytes, struct iov_iter *prot_iter,
size_t data_bytes, struct iov_iter *data_iter)
{
int sgl_count, ret;
bool write = (cmd->tvc_data_direction == DMA_FROM_DEVICE);
if (prot_bytes) {
sgl_count = vhost_scsi_calc_sgls(prot_iter, prot_bytes,
VHOST_SCSI_PREALLOC_PROT_SGLS);
if (sgl_count < 0)
return sgl_count;
sg_init_table(cmd->tvc_prot_sgl, sgl_count);
cmd->tvc_prot_sgl_count = sgl_count;
pr_debug("%s prot_sg %p prot_sgl_count %u\n", __func__,
cmd->tvc_prot_sgl, cmd->tvc_prot_sgl_count);
ret = vhost_scsi_iov_to_sgl(cmd, write, prot_iter,
cmd->tvc_prot_sgl,
cmd->tvc_prot_sgl_count);
if (ret < 0) {
cmd->tvc_prot_sgl_count = 0;
return ret;
}
}
sgl_count = vhost_scsi_calc_sgls(data_iter, data_bytes,
VHOST_SCSI_PREALLOC_SGLS);
if (sgl_count < 0)
return sgl_count;
sg_init_table(cmd->tvc_sgl, sgl_count);
cmd->tvc_sgl_count = sgl_count;
pr_debug("%s data_sg %p data_sgl_count %u\n", __func__,
cmd->tvc_sgl, cmd->tvc_sgl_count);
ret = vhost_scsi_iov_to_sgl(cmd, write, data_iter,
cmd->tvc_sgl, cmd->tvc_sgl_count);
if (ret < 0) {
cmd->tvc_sgl_count = 0;
return ret;
}
return 0;
}
static void vhost_scsi_submission_work(struct work_struct *work)
{
struct vhost_scsi_cmd *cmd =
container_of(work, struct vhost_scsi_cmd, work);
struct vhost_scsi_nexus *tv_nexus;
struct se_cmd *se_cmd = &cmd->tvc_se_cmd;
struct scatterlist *sg_ptr, *sg_prot_ptr = NULL;
int rc;
/* FIXME: BIDI operation */
if (cmd->tvc_sgl_count) {
sg_ptr = cmd->tvc_sgl;
if (cmd->tvc_prot_sgl_count)
sg_prot_ptr = cmd->tvc_prot_sgl;
else
se_cmd->prot_pto = true;
} else {
sg_ptr = NULL;
}
tv_nexus = cmd->tvc_nexus;
rc = target_submit_cmd_map_sgls(se_cmd, tv_nexus->tvn_se_sess,
cmd->tvc_cdb, &cmd->tvc_sense_buf[0],
cmd->tvc_lun, cmd->tvc_exp_data_len,
cmd->tvc_task_attr, cmd->tvc_data_direction,
TARGET_SCF_ACK_KREF, sg_ptr, cmd->tvc_sgl_count,
NULL, 0, sg_prot_ptr, cmd->tvc_prot_sgl_count);
if (rc < 0) {
transport_send_check_condition_and_sense(se_cmd,
TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE, 0);
transport_generic_free_cmd(se_cmd, 0);
}
}
static void
vhost_scsi_send_bad_target(struct vhost_scsi *vs,
struct vhost_virtqueue *vq,
int head, unsigned out)
{
struct virtio_scsi_cmd_resp __user *resp;
struct virtio_scsi_cmd_resp rsp;
int ret;
memset(&rsp, 0, sizeof(rsp));
rsp.response = VIRTIO_SCSI_S_BAD_TARGET;
resp = vq->iov[out].iov_base;
ret = __copy_to_user(resp, &rsp, sizeof(rsp));
if (!ret)
vhost_add_used_and_signal(&vs->dev, vq, head, 0);
else
pr_err("Faulted on virtio_scsi_cmd_resp\n");
}
static void
vhost_scsi_handle_vq(struct vhost_scsi *vs, struct vhost_virtqueue *vq)
{
struct vhost_scsi_tpg **vs_tpg, *tpg;
struct virtio_scsi_cmd_req v_req;
struct virtio_scsi_cmd_req_pi v_req_pi;
struct vhost_scsi_cmd *cmd;
struct iov_iter out_iter, in_iter, prot_iter, data_iter;
u64 tag;
u32 exp_data_len, data_direction;
unsigned out, in;
int head, ret, prot_bytes;
size_t req_size, rsp_size = sizeof(struct virtio_scsi_cmd_resp);
size_t out_size, in_size;
u16 lun;
u8 *target, *lunp, task_attr;
bool t10_pi = vhost_has_feature(vq, VIRTIO_SCSI_F_T10_PI);
void *req, *cdb;
mutex_lock(&vq->mutex);
/*
* We can handle the vq only after the endpoint is setup by calling the
* VHOST_SCSI_SET_ENDPOINT ioctl.
*/
vs_tpg = vq->private_data;
if (!vs_tpg)
goto out;
vhost_disable_notify(&vs->dev, vq);
for (;;) {
head = vhost_get_vq_desc(vq, vq->iov,
ARRAY_SIZE(vq->iov), &out, &in,
NULL, NULL);
pr_debug("vhost_get_vq_desc: head: %d, out: %u in: %u\n",
head, out, in);
/* On error, stop handling until the next kick. */
if (unlikely(head < 0))
break;
/* Nothing new? Wait for eventfd to tell us they refilled. */
if (head == vq->num) {
if (unlikely(vhost_enable_notify(&vs->dev, vq))) {
vhost_disable_notify(&vs->dev, vq);
continue;
}
break;
}
/*
* Check for a sane response buffer so we can report early
* errors back to the guest.
*/
if (unlikely(vq->iov[out].iov_len < rsp_size)) {
vq_err(vq, "Expecting at least virtio_scsi_cmd_resp"
" size, got %zu bytes\n", vq->iov[out].iov_len);
break;
}
/*
* Setup pointers and values based upon different virtio-scsi
* request header if T10_PI is enabled in KVM guest.
*/
if (t10_pi) {
req = &v_req_pi;
req_size = sizeof(v_req_pi);
lunp = &v_req_pi.lun[0];
target = &v_req_pi.lun[1];
} else {
req = &v_req;
req_size = sizeof(v_req);
lunp = &v_req.lun[0];
target = &v_req.lun[1];
}
/*
* FIXME: Not correct for BIDI operation
*/
out_size = iov_length(vq->iov, out);
in_size = iov_length(&vq->iov[out], in);
/*
* Copy over the virtio-scsi request header, which for a
* ANY_LAYOUT enabled guest may span multiple iovecs, or a
* single iovec may contain both the header + outgoing
* WRITE payloads.
*
* copy_from_iter() will advance out_iter, so that it will
* point at the start of the outgoing WRITE payload, if
* DMA_TO_DEVICE is set.
*/
iov_iter_init(&out_iter, WRITE, vq->iov, out, out_size);
ret = copy_from_iter(req, req_size, &out_iter);
if (unlikely(ret != req_size)) {
vq_err(vq, "Faulted on copy_from_iter\n");
vhost_scsi_send_bad_target(vs, vq, head, out);
continue;
}
/* virtio-scsi spec requires byte 0 of the lun to be 1 */
if (unlikely(*lunp != 1)) {
vq_err(vq, "Illegal virtio-scsi lun: %u\n", *lunp);
vhost_scsi_send_bad_target(vs, vq, head, out);
continue;
}
tpg = ACCESS_ONCE(vs_tpg[*target]);
if (unlikely(!tpg)) {
/* Target does not exist, fail the request */
vhost_scsi_send_bad_target(vs, vq, head, out);
continue;
}
/*
* Determine data_direction by calculating the total outgoing
* iovec sizes + incoming iovec sizes vs. virtio-scsi request +
* response headers respectively.
*
* For DMA_TO_DEVICE this is out_iter, which is already pointing
* to the right place.
*
* For DMA_FROM_DEVICE, the iovec will be just past the end
* of the virtio-scsi response header in either the same
* or immediately following iovec.
*
* Any associated T10_PI bytes for the outgoing / incoming
* payloads are included in calculation of exp_data_len here.
*/
prot_bytes = 0;
if (out_size > req_size) {
data_direction = DMA_TO_DEVICE;
exp_data_len = out_size - req_size;
data_iter = out_iter;
} else if (in_size > rsp_size) {
data_direction = DMA_FROM_DEVICE;
exp_data_len = in_size - rsp_size;
iov_iter_init(&in_iter, READ, &vq->iov[out], in,
rsp_size + exp_data_len);
iov_iter_advance(&in_iter, rsp_size);
data_iter = in_iter;
} else {
data_direction = DMA_NONE;
exp_data_len = 0;
}
/*
* If T10_PI header + payload is present, setup prot_iter values
* and recalculate data_iter for vhost_scsi_mapal() mapping to
* host scatterlists via get_user_pages_fast().
*/
if (t10_pi) {
if (v_req_pi.pi_bytesout) {
if (data_direction != DMA_TO_DEVICE) {
vq_err(vq, "Received non zero pi_bytesout,"
" but wrong data_direction\n");
vhost_scsi_send_bad_target(vs, vq, head, out);
continue;
}
prot_bytes = vhost32_to_cpu(vq, v_req_pi.pi_bytesout);
} else if (v_req_pi.pi_bytesin) {
if (data_direction != DMA_FROM_DEVICE) {
vq_err(vq, "Received non zero pi_bytesin,"
" but wrong data_direction\n");
vhost_scsi_send_bad_target(vs, vq, head, out);
continue;
}
prot_bytes = vhost32_to_cpu(vq, v_req_pi.pi_bytesin);
}
/*
* Set prot_iter to data_iter, and advance past any
* preceeding prot_bytes that may be present.
*
* Also fix up the exp_data_len to reflect only the
* actual data payload length.
*/
if (prot_bytes) {
exp_data_len -= prot_bytes;
prot_iter = data_iter;
iov_iter_advance(&data_iter, prot_bytes);
}
tag = vhost64_to_cpu(vq, v_req_pi.tag);
task_attr = v_req_pi.task_attr;
cdb = &v_req_pi.cdb[0];
lun = ((v_req_pi.lun[2] << 8) | v_req_pi.lun[3]) & 0x3FFF;
} else {
tag = vhost64_to_cpu(vq, v_req.tag);
task_attr = v_req.task_attr;
cdb = &v_req.cdb[0];
lun = ((v_req.lun[2] << 8) | v_req.lun[3]) & 0x3FFF;
}
/*
* Check that the received CDB size does not exceeded our
* hardcoded max for vhost-scsi, then get a pre-allocated
* cmd descriptor for the new virtio-scsi tag.
*
* TODO what if cdb was too small for varlen cdb header?
*/
if (unlikely(scsi_command_size(cdb) > VHOST_SCSI_MAX_CDB_SIZE)) {
vq_err(vq, "Received SCSI CDB with command_size: %d that"
" exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n",
scsi_command_size(cdb), VHOST_SCSI_MAX_CDB_SIZE);
vhost_scsi_send_bad_target(vs, vq, head, out);
continue;
}
cmd = vhost_scsi_get_tag(vq, tpg, cdb, tag, lun, task_attr,
exp_data_len + prot_bytes,
data_direction);
if (IS_ERR(cmd)) {
vq_err(vq, "vhost_scsi_get_tag failed %ld\n",
PTR_ERR(cmd));
vhost_scsi_send_bad_target(vs, vq, head, out);
continue;
}
cmd->tvc_vhost = vs;
cmd->tvc_vq = vq;
cmd->tvc_resp_iov = &vq->iov[out];
cmd->tvc_in_iovs = in;
pr_debug("vhost_scsi got command opcode: %#02x, lun: %d\n",
cmd->tvc_cdb[0], cmd->tvc_lun);
pr_debug("cmd: %p exp_data_len: %d, prot_bytes: %d data_direction:"
" %d\n", cmd, exp_data_len, prot_bytes, data_direction);
if (data_direction != DMA_NONE) {
ret = vhost_scsi_mapal(cmd,
prot_bytes, &prot_iter,
exp_data_len, &data_iter);
if (unlikely(ret)) {
vq_err(vq, "Failed to map iov to sgl\n");
vhost_scsi_release_cmd(&cmd->tvc_se_cmd);
vhost_scsi_send_bad_target(vs, vq, head, out);
continue;
}
}
/*
* Save the descriptor from vhost_get_vq_desc() to be used to
* complete the virtio-scsi request in TCM callback context via
* vhost_scsi_queue_data_in() and vhost_scsi_queue_status()
*/
cmd->tvc_vq_desc = head;
/*
* Dispatch cmd descriptor for cmwq execution in process
* context provided by vhost_scsi_workqueue. This also ensures
* cmd is executed on the same kworker CPU as this vhost
* thread to gain positive L2 cache locality effects.
*/
INIT_WORK(&cmd->work, vhost_scsi_submission_work);
queue_work(vhost_scsi_workqueue, &cmd->work);
}
out:
mutex_unlock(&vq->mutex);
}
static void vhost_scsi_ctl_handle_kick(struct vhost_work *work)
{
pr_debug("%s: The handling func for control queue.\n", __func__);
}
static void
vhost_scsi_send_evt(struct vhost_scsi *vs,
struct vhost_scsi_tpg *tpg,
struct se_lun *lun,
u32 event,
u32 reason)
{
struct vhost_scsi_evt *evt;
evt = vhost_scsi_allocate_evt(vs, event, reason);
if (!evt)
return;
if (tpg && lun) {
/* TODO: share lun setup code with virtio-scsi.ko */
/*
* Note: evt->event is zeroed when we allocate it and
* lun[4-7] need to be zero according to virtio-scsi spec.
*/
evt->event.lun[0] = 0x01;
evt->event.lun[1] = tpg->tport_tpgt;
if (lun->unpacked_lun >= 256)
evt->event.lun[2] = lun->unpacked_lun >> 8 | 0x40 ;
evt->event.lun[3] = lun->unpacked_lun & 0xFF;
}
llist_add(&evt->list, &vs->vs_event_list);
vhost_work_queue(&vs->dev, &vs->vs_event_work);
}
static void vhost_scsi_evt_handle_kick(struct vhost_work *work)
{
struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
poll.work);
struct vhost_scsi *vs = container_of(vq->dev, struct vhost_scsi, dev);
mutex_lock(&vq->mutex);
if (!vq->private_data)
goto out;
if (vs->vs_events_missed)
vhost_scsi_send_evt(vs, NULL, NULL, VIRTIO_SCSI_T_NO_EVENT, 0);
out:
mutex_unlock(&vq->mutex);
}
static void vhost_scsi_handle_kick(struct vhost_work *work)
{
struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
poll.work);
struct vhost_scsi *vs = container_of(vq->dev, struct vhost_scsi, dev);
vhost_scsi_handle_vq(vs, vq);
}
static void vhost_scsi_flush_vq(struct vhost_scsi *vs, int index)
{
vhost_poll_flush(&vs->vqs[index].vq.poll);
}
/* Callers must hold dev mutex */
static void vhost_scsi_flush(struct vhost_scsi *vs)
{
struct vhost_scsi_inflight *old_inflight[VHOST_SCSI_MAX_VQ];
int i;
/* Init new inflight and remember the old inflight */
vhost_scsi_init_inflight(vs, old_inflight);
/*
* The inflight->kref was initialized to 1. We decrement it here to
* indicate the start of the flush operation so that it will reach 0
* when all the reqs are finished.
*/
for (i = 0; i < VHOST_SCSI_MAX_VQ; i++)
kref_put(&old_inflight[i]->kref, vhost_scsi_done_inflight);
/* Flush both the vhost poll and vhost work */
for (i = 0; i < VHOST_SCSI_MAX_VQ; i++)
vhost_scsi_flush_vq(vs, i);
vhost_work_flush(&vs->dev, &vs->vs_completion_work);
vhost_work_flush(&vs->dev, &vs->vs_event_work);
/* Wait for all reqs issued before the flush to be finished */
for (i = 0; i < VHOST_SCSI_MAX_VQ; i++)
wait_for_completion(&old_inflight[i]->comp);
}
/*
* Called from vhost_scsi_ioctl() context to walk the list of available
* vhost_scsi_tpg with an active struct vhost_scsi_nexus
*
* The lock nesting rule is:
* vhost_scsi_mutex -> vs->dev.mutex -> tpg->tv_tpg_mutex -> vq->mutex
*/
static int
vhost_scsi_set_endpoint(struct vhost_scsi *vs,
struct vhost_scsi_target *t)
{
struct se_portal_group *se_tpg;
struct vhost_scsi_tport *tv_tport;
struct vhost_scsi_tpg *tpg;
struct vhost_scsi_tpg **vs_tpg;
struct vhost_virtqueue *vq;
int index, ret, i, len;
bool match = false;
mutex_lock(&vhost_scsi_mutex);
mutex_lock(&vs->dev.mutex);
/* Verify that ring has been setup correctly. */
for (index = 0; index < vs->dev.nvqs; ++index) {
/* Verify that ring has been setup correctly. */
if (!vhost_vq_access_ok(&vs->vqs[index].vq)) {
ret = -EFAULT;
goto out;
}
}
len = sizeof(vs_tpg[0]) * VHOST_SCSI_MAX_TARGET;
vs_tpg = kzalloc(len, GFP_KERNEL);
if (!vs_tpg) {
ret = -ENOMEM;
goto out;
}
if (vs->vs_tpg)
memcpy(vs_tpg, vs->vs_tpg, len);
list_for_each_entry(tpg, &vhost_scsi_list, tv_tpg_list) {
mutex_lock(&tpg->tv_tpg_mutex);
if (!tpg->tpg_nexus) {
mutex_unlock(&tpg->tv_tpg_mutex);
continue;
}
if (tpg->tv_tpg_vhost_count != 0) {
mutex_unlock(&tpg->tv_tpg_mutex);
continue;
}
tv_tport = tpg->tport;
if (!strcmp(tv_tport->tport_name, t->vhost_wwpn)) {
if (vs->vs_tpg && vs->vs_tpg[tpg->tport_tpgt]) {
kfree(vs_tpg);
mutex_unlock(&tpg->tv_tpg_mutex);
ret = -EEXIST;
goto out;
}
/*
* In order to ensure individual vhost-scsi configfs
* groups cannot be removed while in use by vhost ioctl,
* go ahead and take an explicit se_tpg->tpg_group.cg_item
* dependency now.
*/
se_tpg = &tpg->se_tpg;
ret = configfs_depend_item(se_tpg->se_tpg_tfo->tf_subsys,
&se_tpg->tpg_group.cg_item);
if (ret) {
pr_warn("configfs_depend_item() failed: %d\n", ret);
kfree(vs_tpg);
mutex_unlock(&tpg->tv_tpg_mutex);
goto out;
}
tpg->tv_tpg_vhost_count++;
tpg->vhost_scsi = vs;
vs_tpg[tpg->tport_tpgt] = tpg;
smp_mb__after_atomic();
match = true;
}
mutex_unlock(&tpg->tv_tpg_mutex);
}
if (match) {
memcpy(vs->vs_vhost_wwpn, t->vhost_wwpn,
sizeof(vs->vs_vhost_wwpn));
for (i = 0; i < VHOST_SCSI_MAX_VQ; i++) {
vq = &vs->vqs[i].vq;
mutex_lock(&vq->mutex);
vq->private_data = vs_tpg;
vhost_init_used(vq);
mutex_unlock(&vq->mutex);
}
ret = 0;
} else {
ret = -EEXIST;
}
/*
* Act as synchronize_rcu to make sure access to
* old vs->vs_tpg is finished.
*/
vhost_scsi_flush(vs);
kfree(vs->vs_tpg);
vs->vs_tpg = vs_tpg;
out:
mutex_unlock(&vs->dev.mutex);
mutex_unlock(&vhost_scsi_mutex);
return ret;
}
static int
vhost_scsi_clear_endpoint(struct vhost_scsi *vs,
struct vhost_scsi_target *t)
{
struct se_portal_group *se_tpg;
struct vhost_scsi_tport *tv_tport;
struct vhost_scsi_tpg *tpg;
struct vhost_virtqueue *vq;
bool match = false;
int index, ret, i;
u8 target;
mutex_lock(&vhost_scsi_mutex);
mutex_lock(&vs->dev.mutex);
/* Verify that ring has been setup correctly. */
for (index = 0; index < vs->dev.nvqs; ++index) {
if (!vhost_vq_access_ok(&vs->vqs[index].vq)) {
ret = -EFAULT;
goto err_dev;
}
}
if (!vs->vs_tpg) {
ret = 0;
goto err_dev;
}
for (i = 0; i < VHOST_SCSI_MAX_TARGET; i++) {
target = i;
tpg = vs->vs_tpg[target];
if (!tpg)
continue;
mutex_lock(&tpg->tv_tpg_mutex);
tv_tport = tpg->tport;
if (!tv_tport) {
ret = -ENODEV;
goto err_tpg;
}
if (strcmp(tv_tport->tport_name, t->vhost_wwpn)) {
pr_warn("tv_tport->tport_name: %s, tpg->tport_tpgt: %hu"
" does not match t->vhost_wwpn: %s, t->vhost_tpgt: %hu\n",
tv_tport->tport_name, tpg->tport_tpgt,
t->vhost_wwpn, t->vhost_tpgt);
ret = -EINVAL;
goto err_tpg;
}
tpg->tv_tpg_vhost_count--;
tpg->vhost_scsi = NULL;
vs->vs_tpg[target] = NULL;
match = true;
mutex_unlock(&tpg->tv_tpg_mutex);
/*
* Release se_tpg->tpg_group.cg_item configfs dependency now
* to allow vhost-scsi WWPN se_tpg->tpg_group shutdown to occur.
*/
se_tpg = &tpg->se_tpg;
configfs_undepend_item(se_tpg->se_tpg_tfo->tf_subsys,
&se_tpg->tpg_group.cg_item);
}
if (match) {
for (i = 0; i < VHOST_SCSI_MAX_VQ; i++) {
vq = &vs->vqs[i].vq;
mutex_lock(&vq->mutex);
vq->private_data = NULL;
mutex_unlock(&vq->mutex);
}
}
/*
* Act as synchronize_rcu to make sure access to
* old vs->vs_tpg is finished.
*/
vhost_scsi_flush(vs);
kfree(vs->vs_tpg);
vs->vs_tpg = NULL;
WARN_ON(vs->vs_events_nr);
mutex_unlock(&vs->dev.mutex);
mutex_unlock(&vhost_scsi_mutex);
return 0;
err_tpg:
mutex_unlock(&tpg->tv_tpg_mutex);
err_dev:
mutex_unlock(&vs->dev.mutex);
mutex_unlock(&vhost_scsi_mutex);
return ret;
}
static int vhost_scsi_set_features(struct vhost_scsi *vs, u64 features)
{
struct vhost_virtqueue *vq;
int i;
if (features & ~VHOST_SCSI_FEATURES)
return -EOPNOTSUPP;
mutex_lock(&vs->dev.mutex);
if ((features & (1 << VHOST_F_LOG_ALL)) &&
!vhost_log_access_ok(&vs->dev)) {
mutex_unlock(&vs->dev.mutex);
return -EFAULT;
}
for (i = 0; i < VHOST_SCSI_MAX_VQ; i++) {
vq = &vs->vqs[i].vq;
mutex_lock(&vq->mutex);
vq->acked_features = features;
mutex_unlock(&vq->mutex);
}
mutex_unlock(&vs->dev.mutex);
return 0;
}
static int vhost_scsi_open(struct inode *inode, struct file *f)
{
struct vhost_scsi *vs;
struct vhost_virtqueue **vqs;
int r = -ENOMEM, i;
vs = kzalloc(sizeof(*vs), GFP_KERNEL | __GFP_NOWARN | __GFP_REPEAT);
if (!vs) {
vs = vzalloc(sizeof(*vs));
if (!vs)
goto err_vs;
}
vqs = kmalloc(VHOST_SCSI_MAX_VQ * sizeof(*vqs), GFP_KERNEL);
if (!vqs)
goto err_vqs;
vhost_work_init(&vs->vs_completion_work, vhost_scsi_complete_cmd_work);
vhost_work_init(&vs->vs_event_work, vhost_scsi_evt_work);
vs->vs_events_nr = 0;
vs->vs_events_missed = false;
vqs[VHOST_SCSI_VQ_CTL] = &vs->vqs[VHOST_SCSI_VQ_CTL].vq;
vqs[VHOST_SCSI_VQ_EVT] = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
vs->vqs[VHOST_SCSI_VQ_CTL].vq.handle_kick = vhost_scsi_ctl_handle_kick;
vs->vqs[VHOST_SCSI_VQ_EVT].vq.handle_kick = vhost_scsi_evt_handle_kick;
for (i = VHOST_SCSI_VQ_IO; i < VHOST_SCSI_MAX_VQ; i++) {
vqs[i] = &vs->vqs[i].vq;
vs->vqs[i].vq.handle_kick = vhost_scsi_handle_kick;
}
vhost_dev_init(&vs->dev, vqs, VHOST_SCSI_MAX_VQ);
vhost_scsi_init_inflight(vs, NULL);
f->private_data = vs;
return 0;
err_vqs:
kvfree(vs);
err_vs:
return r;
}
static int vhost_scsi_release(struct inode *inode, struct file *f)
{
struct vhost_scsi *vs = f->private_data;
struct vhost_scsi_target t;
mutex_lock(&vs->dev.mutex);
memcpy(t.vhost_wwpn, vs->vs_vhost_wwpn, sizeof(t.vhost_wwpn));
mutex_unlock(&vs->dev.mutex);
vhost_scsi_clear_endpoint(vs, &t);
vhost_dev_stop(&vs->dev);
vhost_dev_cleanup(&vs->dev, false);
/* Jobs can re-queue themselves in evt kick handler. Do extra flush. */
vhost_scsi_flush(vs);
kfree(vs->dev.vqs);
kvfree(vs);
return 0;
}
static long
vhost_scsi_ioctl(struct file *f,
unsigned int ioctl,
unsigned long arg)
{
struct vhost_scsi *vs = f->private_data;
struct vhost_scsi_target backend;
void __user *argp = (void __user *)arg;
u64 __user *featurep = argp;
u32 __user *eventsp = argp;
u32 events_missed;
u64 features;
int r, abi_version = VHOST_SCSI_ABI_VERSION;
struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
switch (ioctl) {
case VHOST_SCSI_SET_ENDPOINT:
if (copy_from_user(&backend, argp, sizeof backend))
return -EFAULT;
if (backend.reserved != 0)
return -EOPNOTSUPP;
return vhost_scsi_set_endpoint(vs, &backend);
case VHOST_SCSI_CLEAR_ENDPOINT:
if (copy_from_user(&backend, argp, sizeof backend))
return -EFAULT;
if (backend.reserved != 0)
return -EOPNOTSUPP;
return vhost_scsi_clear_endpoint(vs, &backend);
case VHOST_SCSI_GET_ABI_VERSION:
if (copy_to_user(argp, &abi_version, sizeof abi_version))
return -EFAULT;
return 0;
case VHOST_SCSI_SET_EVENTS_MISSED:
if (get_user(events_missed, eventsp))
return -EFAULT;
mutex_lock(&vq->mutex);
vs->vs_events_missed = events_missed;
mutex_unlock(&vq->mutex);
return 0;
case VHOST_SCSI_GET_EVENTS_MISSED:
mutex_lock(&vq->mutex);
events_missed = vs->vs_events_missed;
mutex_unlock(&vq->mutex);
if (put_user(events_missed, eventsp))
return -EFAULT;
return 0;
case VHOST_GET_FEATURES:
features = VHOST_SCSI_FEATURES;
if (copy_to_user(featurep, &features, sizeof features))
return -EFAULT;
return 0;
case VHOST_SET_FEATURES:
if (copy_from_user(&features, featurep, sizeof features))
return -EFAULT;
return vhost_scsi_set_features(vs, features);
default:
mutex_lock(&vs->dev.mutex);
r = vhost_dev_ioctl(&vs->dev, ioctl, argp);
/* TODO: flush backend after dev ioctl. */
if (r == -ENOIOCTLCMD)
r = vhost_vring_ioctl(&vs->dev, ioctl, argp);
mutex_unlock(&vs->dev.mutex);
return r;
}
}
#ifdef CONFIG_COMPAT
static long vhost_scsi_compat_ioctl(struct file *f, unsigned int ioctl,
unsigned long arg)
{
return vhost_scsi_ioctl(f, ioctl, (unsigned long)compat_ptr(arg));
}
#endif
static const struct file_operations vhost_scsi_fops = {
.owner = THIS_MODULE,
.release = vhost_scsi_release,
.unlocked_ioctl = vhost_scsi_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = vhost_scsi_compat_ioctl,
#endif
.open = vhost_scsi_open,
.llseek = noop_llseek,
};
static struct miscdevice vhost_scsi_misc = {
MISC_DYNAMIC_MINOR,
"vhost-scsi",
&vhost_scsi_fops,
};
static int __init vhost_scsi_register(void)
{
return misc_register(&vhost_scsi_misc);
}
static int vhost_scsi_deregister(void)
{
return misc_deregister(&vhost_scsi_misc);
}
static char *vhost_scsi_dump_proto_id(struct vhost_scsi_tport *tport)
{
switch (tport->tport_proto_id) {
case SCSI_PROTOCOL_SAS:
return "SAS";
case SCSI_PROTOCOL_FCP:
return "FCP";
case SCSI_PROTOCOL_ISCSI:
return "iSCSI";
default:
break;
}
return "Unknown";
}
static void
vhost_scsi_do_plug(struct vhost_scsi_tpg *tpg,
struct se_lun *lun, bool plug)
{
struct vhost_scsi *vs = tpg->vhost_scsi;
struct vhost_virtqueue *vq;
u32 reason;
if (!vs)
return;
mutex_lock(&vs->dev.mutex);
if (plug)
reason = VIRTIO_SCSI_EVT_RESET_RESCAN;
else
reason = VIRTIO_SCSI_EVT_RESET_REMOVED;
vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
mutex_lock(&vq->mutex);
if (vhost_has_feature(vq, VIRTIO_SCSI_F_HOTPLUG))
vhost_scsi_send_evt(vs, tpg, lun,
VIRTIO_SCSI_T_TRANSPORT_RESET, reason);
mutex_unlock(&vq->mutex);
mutex_unlock(&vs->dev.mutex);
}
static void vhost_scsi_hotplug(struct vhost_scsi_tpg *tpg, struct se_lun *lun)
{
vhost_scsi_do_plug(tpg, lun, true);
}
static void vhost_scsi_hotunplug(struct vhost_scsi_tpg *tpg, struct se_lun *lun)
{
vhost_scsi_do_plug(tpg, lun, false);
}
static int vhost_scsi_port_link(struct se_portal_group *se_tpg,
struct se_lun *lun)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
mutex_lock(&vhost_scsi_mutex);
mutex_lock(&tpg->tv_tpg_mutex);
tpg->tv_tpg_port_count++;
mutex_unlock(&tpg->tv_tpg_mutex);
vhost_scsi_hotplug(tpg, lun);
mutex_unlock(&vhost_scsi_mutex);
return 0;
}
static void vhost_scsi_port_unlink(struct se_portal_group *se_tpg,
struct se_lun *lun)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
mutex_lock(&vhost_scsi_mutex);
mutex_lock(&tpg->tv_tpg_mutex);
tpg->tv_tpg_port_count--;
mutex_unlock(&tpg->tv_tpg_mutex);
vhost_scsi_hotunplug(tpg, lun);
mutex_unlock(&vhost_scsi_mutex);
}
static struct se_node_acl *
vhost_scsi_make_nodeacl(struct se_portal_group *se_tpg,
struct config_group *group,
const char *name)
{
struct se_node_acl *se_nacl, *se_nacl_new;
struct vhost_scsi_nacl *nacl;
u64 wwpn = 0;
u32 nexus_depth;
/* vhost_scsi_parse_wwn(name, &wwpn, 1) < 0)
return ERR_PTR(-EINVAL); */
se_nacl_new = vhost_scsi_alloc_fabric_acl(se_tpg);
if (!se_nacl_new)
return ERR_PTR(-ENOMEM);
nexus_depth = 1;
/*
* se_nacl_new may be released by core_tpg_add_initiator_node_acl()
* when converting a NodeACL from demo mode -> explict
*/
se_nacl = core_tpg_add_initiator_node_acl(se_tpg, se_nacl_new,
name, nexus_depth);
if (IS_ERR(se_nacl)) {
vhost_scsi_release_fabric_acl(se_tpg, se_nacl_new);
return se_nacl;
}
/*
* Locate our struct vhost_scsi_nacl and set the FC Nport WWPN
*/
nacl = container_of(se_nacl, struct vhost_scsi_nacl, se_node_acl);
nacl->iport_wwpn = wwpn;
return se_nacl;
}
static void vhost_scsi_drop_nodeacl(struct se_node_acl *se_acl)
{
struct vhost_scsi_nacl *nacl = container_of(se_acl,
struct vhost_scsi_nacl, se_node_acl);
core_tpg_del_initiator_node_acl(se_acl->se_tpg, se_acl, 1);
kfree(nacl);
}
static void vhost_scsi_free_cmd_map_res(struct vhost_scsi_nexus *nexus,
struct se_session *se_sess)
{
struct vhost_scsi_cmd *tv_cmd;
unsigned int i;
if (!se_sess->sess_cmd_map)
return;
for (i = 0; i < VHOST_SCSI_DEFAULT_TAGS; i++) {
tv_cmd = &((struct vhost_scsi_cmd *)se_sess->sess_cmd_map)[i];
kfree(tv_cmd->tvc_sgl);
kfree(tv_cmd->tvc_prot_sgl);
kfree(tv_cmd->tvc_upages);
}
}
static int vhost_scsi_make_nexus(struct vhost_scsi_tpg *tpg,
const char *name)
{
struct se_portal_group *se_tpg;
struct se_session *se_sess;
struct vhost_scsi_nexus *tv_nexus;
struct vhost_scsi_cmd *tv_cmd;
unsigned int i;
mutex_lock(&tpg->tv_tpg_mutex);
if (tpg->tpg_nexus) {
mutex_unlock(&tpg->tv_tpg_mutex);
pr_debug("tpg->tpg_nexus already exists\n");
return -EEXIST;
}
se_tpg = &tpg->se_tpg;
tv_nexus = kzalloc(sizeof(struct vhost_scsi_nexus), GFP_KERNEL);
if (!tv_nexus) {
mutex_unlock(&tpg->tv_tpg_mutex);
pr_err("Unable to allocate struct vhost_scsi_nexus\n");
return -ENOMEM;
}
/*
* Initialize the struct se_session pointer and setup tagpool
* for struct vhost_scsi_cmd descriptors
*/
tv_nexus->tvn_se_sess = transport_init_session_tags(
VHOST_SCSI_DEFAULT_TAGS,
sizeof(struct vhost_scsi_cmd),
TARGET_PROT_DIN_PASS | TARGET_PROT_DOUT_PASS);
if (IS_ERR(tv_nexus->tvn_se_sess)) {
mutex_unlock(&tpg->tv_tpg_mutex);
kfree(tv_nexus);
return -ENOMEM;
}
se_sess = tv_nexus->tvn_se_sess;
for (i = 0; i < VHOST_SCSI_DEFAULT_TAGS; i++) {
tv_cmd = &((struct vhost_scsi_cmd *)se_sess->sess_cmd_map)[i];
tv_cmd->tvc_sgl = kzalloc(sizeof(struct scatterlist) *
VHOST_SCSI_PREALLOC_SGLS, GFP_KERNEL);
if (!tv_cmd->tvc_sgl) {
mutex_unlock(&tpg->tv_tpg_mutex);
pr_err("Unable to allocate tv_cmd->tvc_sgl\n");
goto out;
}
tv_cmd->tvc_upages = kzalloc(sizeof(struct page *) *
VHOST_SCSI_PREALLOC_UPAGES, GFP_KERNEL);
if (!tv_cmd->tvc_upages) {
mutex_unlock(&tpg->tv_tpg_mutex);
pr_err("Unable to allocate tv_cmd->tvc_upages\n");
goto out;
}
tv_cmd->tvc_prot_sgl = kzalloc(sizeof(struct scatterlist) *
VHOST_SCSI_PREALLOC_PROT_SGLS, GFP_KERNEL);
if (!tv_cmd->tvc_prot_sgl) {
mutex_unlock(&tpg->tv_tpg_mutex);
pr_err("Unable to allocate tv_cmd->tvc_prot_sgl\n");
goto out;
}
}
/*
* Since we are running in 'demo mode' this call with generate a
* struct se_node_acl for the vhost_scsi struct se_portal_group with
* the SCSI Initiator port name of the passed configfs group 'name'.
*/
tv_nexus->tvn_se_sess->se_node_acl = core_tpg_check_initiator_node_acl(
se_tpg, (unsigned char *)name);
if (!tv_nexus->tvn_se_sess->se_node_acl) {
mutex_unlock(&tpg->tv_tpg_mutex);
pr_debug("core_tpg_check_initiator_node_acl() failed"
" for %s\n", name);
goto out;
}
/*
* Now register the TCM vhost virtual I_T Nexus as active with the
* call to __transport_register_session()
*/
__transport_register_session(se_tpg, tv_nexus->tvn_se_sess->se_node_acl,
tv_nexus->tvn_se_sess, tv_nexus);
tpg->tpg_nexus = tv_nexus;
mutex_unlock(&tpg->tv_tpg_mutex);
return 0;
out:
vhost_scsi_free_cmd_map_res(tv_nexus, se_sess);
transport_free_session(se_sess);
kfree(tv_nexus);
return -ENOMEM;
}
static int vhost_scsi_drop_nexus(struct vhost_scsi_tpg *tpg)
{
struct se_session *se_sess;
struct vhost_scsi_nexus *tv_nexus;
mutex_lock(&tpg->tv_tpg_mutex);
tv_nexus = tpg->tpg_nexus;
if (!tv_nexus) {
mutex_unlock(&tpg->tv_tpg_mutex);
return -ENODEV;
}
se_sess = tv_nexus->tvn_se_sess;
if (!se_sess) {
mutex_unlock(&tpg->tv_tpg_mutex);
return -ENODEV;
}
if (tpg->tv_tpg_port_count != 0) {
mutex_unlock(&tpg->tv_tpg_mutex);
pr_err("Unable to remove TCM_vhost I_T Nexus with"
" active TPG port count: %d\n",
tpg->tv_tpg_port_count);
return -EBUSY;
}
if (tpg->tv_tpg_vhost_count != 0) {
mutex_unlock(&tpg->tv_tpg_mutex);
pr_err("Unable to remove TCM_vhost I_T Nexus with"
" active TPG vhost count: %d\n",
tpg->tv_tpg_vhost_count);
return -EBUSY;
}
pr_debug("TCM_vhost_ConfigFS: Removing I_T Nexus to emulated"
" %s Initiator Port: %s\n", vhost_scsi_dump_proto_id(tpg->tport),
tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
vhost_scsi_free_cmd_map_res(tv_nexus, se_sess);
/*
* Release the SCSI I_T Nexus to the emulated vhost Target Port
*/
transport_deregister_session(tv_nexus->tvn_se_sess);
tpg->tpg_nexus = NULL;
mutex_unlock(&tpg->tv_tpg_mutex);
kfree(tv_nexus);
return 0;
}
static ssize_t vhost_scsi_tpg_show_nexus(struct se_portal_group *se_tpg,
char *page)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
struct vhost_scsi_nexus *tv_nexus;
ssize_t ret;
mutex_lock(&tpg->tv_tpg_mutex);
tv_nexus = tpg->tpg_nexus;
if (!tv_nexus) {
mutex_unlock(&tpg->tv_tpg_mutex);
return -ENODEV;
}
ret = snprintf(page, PAGE_SIZE, "%s\n",
tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
mutex_unlock(&tpg->tv_tpg_mutex);
return ret;
}
static ssize_t vhost_scsi_tpg_store_nexus(struct se_portal_group *se_tpg,
const char *page,
size_t count)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
struct vhost_scsi_tport *tport_wwn = tpg->tport;
unsigned char i_port[VHOST_SCSI_NAMELEN], *ptr, *port_ptr;
int ret;
/*
* Shutdown the active I_T nexus if 'NULL' is passed..
*/
if (!strncmp(page, "NULL", 4)) {
ret = vhost_scsi_drop_nexus(tpg);
return (!ret) ? count : ret;
}
/*
* Otherwise make sure the passed virtual Initiator port WWN matches
* the fabric protocol_id set in vhost_scsi_make_tport(), and call
* vhost_scsi_make_nexus().
*/
if (strlen(page) >= VHOST_SCSI_NAMELEN) {
pr_err("Emulated NAA Sas Address: %s, exceeds"
" max: %d\n", page, VHOST_SCSI_NAMELEN);
return -EINVAL;
}
snprintf(&i_port[0], VHOST_SCSI_NAMELEN, "%s", page);
ptr = strstr(i_port, "naa.");
if (ptr) {
if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_SAS) {
pr_err("Passed SAS Initiator Port %s does not"
" match target port protoid: %s\n", i_port,
vhost_scsi_dump_proto_id(tport_wwn));
return -EINVAL;
}
port_ptr = &i_port[0];
goto check_newline;
}
ptr = strstr(i_port, "fc.");
if (ptr) {
if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_FCP) {
pr_err("Passed FCP Initiator Port %s does not"
" match target port protoid: %s\n", i_port,
vhost_scsi_dump_proto_id(tport_wwn));
return -EINVAL;
}
port_ptr = &i_port[3]; /* Skip over "fc." */
goto check_newline;
}
ptr = strstr(i_port, "iqn.");
if (ptr) {
if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_ISCSI) {
pr_err("Passed iSCSI Initiator Port %s does not"
" match target port protoid: %s\n", i_port,
vhost_scsi_dump_proto_id(tport_wwn));
return -EINVAL;
}
port_ptr = &i_port[0];
goto check_newline;
}
pr_err("Unable to locate prefix for emulated Initiator Port:"
" %s\n", i_port);
return -EINVAL;
/*
* Clear any trailing newline for the NAA WWN
*/
check_newline:
if (i_port[strlen(i_port)-1] == '\n')
i_port[strlen(i_port)-1] = '\0';
ret = vhost_scsi_make_nexus(tpg, port_ptr);
if (ret < 0)
return ret;
return count;
}
TF_TPG_BASE_ATTR(vhost_scsi, nexus, S_IRUGO | S_IWUSR);
static struct configfs_attribute *vhost_scsi_tpg_attrs[] = {
&vhost_scsi_tpg_nexus.attr,
NULL,
};
static struct se_portal_group *
vhost_scsi_make_tpg(struct se_wwn *wwn,
struct config_group *group,
const char *name)
{
struct vhost_scsi_tport *tport = container_of(wwn,
struct vhost_scsi_tport, tport_wwn);
struct vhost_scsi_tpg *tpg;
u16 tpgt;
int ret;
if (strstr(name, "tpgt_") != name)
return ERR_PTR(-EINVAL);
if (kstrtou16(name + 5, 10, &tpgt) || tpgt >= VHOST_SCSI_MAX_TARGET)
return ERR_PTR(-EINVAL);
tpg = kzalloc(sizeof(struct vhost_scsi_tpg), GFP_KERNEL);
if (!tpg) {
pr_err("Unable to allocate struct vhost_scsi_tpg");
return ERR_PTR(-ENOMEM);
}
mutex_init(&tpg->tv_tpg_mutex);
INIT_LIST_HEAD(&tpg->tv_tpg_list);
tpg->tport = tport;
tpg->tport_tpgt = tpgt;
ret = core_tpg_register(&vhost_scsi_fabric_configfs->tf_ops, wwn,
&tpg->se_tpg, tpg, TRANSPORT_TPG_TYPE_NORMAL);
if (ret < 0) {
kfree(tpg);
return NULL;
}
mutex_lock(&vhost_scsi_mutex);
list_add_tail(&tpg->tv_tpg_list, &vhost_scsi_list);
mutex_unlock(&vhost_scsi_mutex);
return &tpg->se_tpg;
}
static void vhost_scsi_drop_tpg(struct se_portal_group *se_tpg)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
mutex_lock(&vhost_scsi_mutex);
list_del(&tpg->tv_tpg_list);
mutex_unlock(&vhost_scsi_mutex);
/*
* Release the virtual I_T Nexus for this vhost TPG
*/
vhost_scsi_drop_nexus(tpg);
/*
* Deregister the se_tpg from TCM..
*/
core_tpg_deregister(se_tpg);
kfree(tpg);
}
static struct se_wwn *
vhost_scsi_make_tport(struct target_fabric_configfs *tf,
struct config_group *group,
const char *name)
{
struct vhost_scsi_tport *tport;
char *ptr;
u64 wwpn = 0;
int off = 0;
/* if (vhost_scsi_parse_wwn(name, &wwpn, 1) < 0)
return ERR_PTR(-EINVAL); */
tport = kzalloc(sizeof(struct vhost_scsi_tport), GFP_KERNEL);
if (!tport) {
pr_err("Unable to allocate struct vhost_scsi_tport");
return ERR_PTR(-ENOMEM);
}
tport->tport_wwpn = wwpn;
/*
* Determine the emulated Protocol Identifier and Target Port Name
* based on the incoming configfs directory name.
*/
ptr = strstr(name, "naa.");
if (ptr) {
tport->tport_proto_id = SCSI_PROTOCOL_SAS;
goto check_len;
}
ptr = strstr(name, "fc.");
if (ptr) {
tport->tport_proto_id = SCSI_PROTOCOL_FCP;
off = 3; /* Skip over "fc." */
goto check_len;
}
ptr = strstr(name, "iqn.");
if (ptr) {
tport->tport_proto_id = SCSI_PROTOCOL_ISCSI;
goto check_len;
}
pr_err("Unable to locate prefix for emulated Target Port:"
" %s\n", name);
kfree(tport);
return ERR_PTR(-EINVAL);
check_len:
if (strlen(name) >= VHOST_SCSI_NAMELEN) {
pr_err("Emulated %s Address: %s, exceeds"
" max: %d\n", name, vhost_scsi_dump_proto_id(tport),
VHOST_SCSI_NAMELEN);
kfree(tport);
return ERR_PTR(-EINVAL);
}
snprintf(&tport->tport_name[0], VHOST_SCSI_NAMELEN, "%s", &name[off]);
pr_debug("TCM_VHost_ConfigFS: Allocated emulated Target"
" %s Address: %s\n", vhost_scsi_dump_proto_id(tport), name);
return &tport->tport_wwn;
}
static void vhost_scsi_drop_tport(struct se_wwn *wwn)
{
struct vhost_scsi_tport *tport = container_of(wwn,
struct vhost_scsi_tport, tport_wwn);
pr_debug("TCM_VHost_ConfigFS: Deallocating emulated Target"
" %s Address: %s\n", vhost_scsi_dump_proto_id(tport),
tport->tport_name);
kfree(tport);
}
static ssize_t
vhost_scsi_wwn_show_attr_version(struct target_fabric_configfs *tf,
char *page)
{
return sprintf(page, "TCM_VHOST fabric module %s on %s/%s"
"on "UTS_RELEASE"\n", VHOST_SCSI_VERSION, utsname()->sysname,
utsname()->machine);
}
TF_WWN_ATTR_RO(vhost_scsi, version);
static struct configfs_attribute *vhost_scsi_wwn_attrs[] = {
&vhost_scsi_wwn_version.attr,
NULL,
};
static struct target_core_fabric_ops vhost_scsi_ops = {
.get_fabric_name = vhost_scsi_get_fabric_name,
.get_fabric_proto_ident = vhost_scsi_get_fabric_proto_ident,
.tpg_get_wwn = vhost_scsi_get_fabric_wwn,
.tpg_get_tag = vhost_scsi_get_tpgt,
.tpg_get_default_depth = vhost_scsi_get_default_depth,
.tpg_get_pr_transport_id = vhost_scsi_get_pr_transport_id,
.tpg_get_pr_transport_id_len = vhost_scsi_get_pr_transport_id_len,
.tpg_parse_pr_out_transport_id = vhost_scsi_parse_pr_out_transport_id,
.tpg_check_demo_mode = vhost_scsi_check_true,
.tpg_check_demo_mode_cache = vhost_scsi_check_true,
.tpg_check_demo_mode_write_protect = vhost_scsi_check_false,
.tpg_check_prod_mode_write_protect = vhost_scsi_check_false,
.tpg_alloc_fabric_acl = vhost_scsi_alloc_fabric_acl,
.tpg_release_fabric_acl = vhost_scsi_release_fabric_acl,
.tpg_get_inst_index = vhost_scsi_tpg_get_inst_index,
.release_cmd = vhost_scsi_release_cmd,
.check_stop_free = vhost_scsi_check_stop_free,
.shutdown_session = vhost_scsi_shutdown_session,
.close_session = vhost_scsi_close_session,
.sess_get_index = vhost_scsi_sess_get_index,
.sess_get_initiator_sid = NULL,
.write_pending = vhost_scsi_write_pending,
.write_pending_status = vhost_scsi_write_pending_status,
.set_default_node_attributes = vhost_scsi_set_default_node_attrs,
.get_task_tag = vhost_scsi_get_task_tag,
.get_cmd_state = vhost_scsi_get_cmd_state,
.queue_data_in = vhost_scsi_queue_data_in,
.queue_status = vhost_scsi_queue_status,
.queue_tm_rsp = vhost_scsi_queue_tm_rsp,
.aborted_task = vhost_scsi_aborted_task,
/*
* Setup callers for generic logic in target_core_fabric_configfs.c
*/
.fabric_make_wwn = vhost_scsi_make_tport,
.fabric_drop_wwn = vhost_scsi_drop_tport,
.fabric_make_tpg = vhost_scsi_make_tpg,
.fabric_drop_tpg = vhost_scsi_drop_tpg,
.fabric_post_link = vhost_scsi_port_link,
.fabric_pre_unlink = vhost_scsi_port_unlink,
.fabric_make_np = NULL,
.fabric_drop_np = NULL,
.fabric_make_nodeacl = vhost_scsi_make_nodeacl,
.fabric_drop_nodeacl = vhost_scsi_drop_nodeacl,
};
static int vhost_scsi_register_configfs(void)
{
struct target_fabric_configfs *fabric;
int ret;
pr_debug("vhost-scsi fabric module %s on %s/%s"
" on "UTS_RELEASE"\n", VHOST_SCSI_VERSION, utsname()->sysname,
utsname()->machine);
/*
* Register the top level struct config_item_type with TCM core
*/
fabric = target_fabric_configfs_init(THIS_MODULE, "vhost");
if (IS_ERR(fabric)) {
pr_err("target_fabric_configfs_init() failed\n");
return PTR_ERR(fabric);
}
/*
* Setup fabric->tf_ops from our local vhost_scsi_ops
*/
fabric->tf_ops = vhost_scsi_ops;
/*
* Setup default attribute lists for various fabric->tf_cit_tmpl
*/
fabric->tf_cit_tmpl.tfc_wwn_cit.ct_attrs = vhost_scsi_wwn_attrs;
fabric->tf_cit_tmpl.tfc_tpg_base_cit.ct_attrs = vhost_scsi_tpg_attrs;
fabric->tf_cit_tmpl.tfc_tpg_attrib_cit.ct_attrs = NULL;
fabric->tf_cit_tmpl.tfc_tpg_param_cit.ct_attrs = NULL;
fabric->tf_cit_tmpl.tfc_tpg_np_base_cit.ct_attrs = NULL;
fabric->tf_cit_tmpl.tfc_tpg_nacl_base_cit.ct_attrs = NULL;
fabric->tf_cit_tmpl.tfc_tpg_nacl_attrib_cit.ct_attrs = NULL;
fabric->tf_cit_tmpl.tfc_tpg_nacl_auth_cit.ct_attrs = NULL;
fabric->tf_cit_tmpl.tfc_tpg_nacl_param_cit.ct_attrs = NULL;
/*
* Register the fabric for use within TCM
*/
ret = target_fabric_configfs_register(fabric);
if (ret < 0) {
pr_err("target_fabric_configfs_register() failed"
" for TCM_VHOST\n");
return ret;
}
/*
* Setup our local pointer to *fabric
*/
vhost_scsi_fabric_configfs = fabric;
pr_debug("TCM_VHOST[0] - Set fabric -> vhost_scsi_fabric_configfs\n");
return 0;
};
static void vhost_scsi_deregister_configfs(void)
{
if (!vhost_scsi_fabric_configfs)
return;
target_fabric_configfs_deregister(vhost_scsi_fabric_configfs);
vhost_scsi_fabric_configfs = NULL;
pr_debug("TCM_VHOST[0] - Cleared vhost_scsi_fabric_configfs\n");
};
static int __init vhost_scsi_init(void)
{
int ret = -ENOMEM;
/*
* Use our own dedicated workqueue for submitting I/O into
* target core to avoid contention within system_wq.
*/
vhost_scsi_workqueue = alloc_workqueue("vhost_scsi", 0, 0);
if (!vhost_scsi_workqueue)
goto out;
ret = vhost_scsi_register();
if (ret < 0)
goto out_destroy_workqueue;
ret = vhost_scsi_register_configfs();
if (ret < 0)
goto out_vhost_scsi_deregister;
return 0;
out_vhost_scsi_deregister:
vhost_scsi_deregister();
out_destroy_workqueue:
destroy_workqueue(vhost_scsi_workqueue);
out:
return ret;
};
static void vhost_scsi_exit(void)
{
vhost_scsi_deregister_configfs();
vhost_scsi_deregister();
destroy_workqueue(vhost_scsi_workqueue);
};
MODULE_DESCRIPTION("VHOST_SCSI series fabric driver");
MODULE_ALIAS("tcm_vhost");
MODULE_LICENSE("GPL");
module_init(vhost_scsi_init);
module_exit(vhost_scsi_exit);
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_1618_0 |
crossvul-cpp_data_bad_1618_0 | /*******************************************************************************
* Vhost kernel TCM fabric driver for virtio SCSI initiators
*
* (C) Copyright 2010-2013 Datera, Inc.
* (C) Copyright 2010-2012 IBM Corp.
*
* Licensed to the Linux Foundation under the General Public License (GPL) version 2.
*
* Authors: Nicholas A. Bellinger <nab@daterainc.com>
* Stefan Hajnoczi <stefanha@linux.vnet.ibm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
****************************************************************************/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <generated/utsrelease.h>
#include <linux/utsname.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/kthread.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/configfs.h>
#include <linux/ctype.h>
#include <linux/compat.h>
#include <linux/eventfd.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <asm/unaligned.h>
#include <scsi/scsi.h>
#include <target/target_core_base.h>
#include <target/target_core_fabric.h>
#include <target/target_core_fabric_configfs.h>
#include <target/target_core_configfs.h>
#include <target/configfs_macros.h>
#include <linux/vhost.h>
#include <linux/virtio_scsi.h>
#include <linux/llist.h>
#include <linux/bitmap.h>
#include <linux/percpu_ida.h>
#include "vhost.h"
#define VHOST_SCSI_VERSION "v0.1"
#define VHOST_SCSI_NAMELEN 256
#define VHOST_SCSI_MAX_CDB_SIZE 32
#define VHOST_SCSI_DEFAULT_TAGS 256
#define VHOST_SCSI_PREALLOC_SGLS 2048
#define VHOST_SCSI_PREALLOC_UPAGES 2048
#define VHOST_SCSI_PREALLOC_PROT_SGLS 512
struct vhost_scsi_inflight {
/* Wait for the flush operation to finish */
struct completion comp;
/* Refcount for the inflight reqs */
struct kref kref;
};
struct vhost_scsi_cmd {
/* Descriptor from vhost_get_vq_desc() for virt_queue segment */
int tvc_vq_desc;
/* virtio-scsi initiator task attribute */
int tvc_task_attr;
/* virtio-scsi response incoming iovecs */
int tvc_in_iovs;
/* virtio-scsi initiator data direction */
enum dma_data_direction tvc_data_direction;
/* Expected data transfer length from virtio-scsi header */
u32 tvc_exp_data_len;
/* The Tag from include/linux/virtio_scsi.h:struct virtio_scsi_cmd_req */
u64 tvc_tag;
/* The number of scatterlists associated with this cmd */
u32 tvc_sgl_count;
u32 tvc_prot_sgl_count;
/* Saved unpacked SCSI LUN for vhost_scsi_submission_work() */
u32 tvc_lun;
/* Pointer to the SGL formatted memory from virtio-scsi */
struct scatterlist *tvc_sgl;
struct scatterlist *tvc_prot_sgl;
struct page **tvc_upages;
/* Pointer to response header iovec */
struct iovec *tvc_resp_iov;
/* Pointer to vhost_scsi for our device */
struct vhost_scsi *tvc_vhost;
/* Pointer to vhost_virtqueue for the cmd */
struct vhost_virtqueue *tvc_vq;
/* Pointer to vhost nexus memory */
struct vhost_scsi_nexus *tvc_nexus;
/* The TCM I/O descriptor that is accessed via container_of() */
struct se_cmd tvc_se_cmd;
/* work item used for cmwq dispatch to vhost_scsi_submission_work() */
struct work_struct work;
/* Copy of the incoming SCSI command descriptor block (CDB) */
unsigned char tvc_cdb[VHOST_SCSI_MAX_CDB_SIZE];
/* Sense buffer that will be mapped into outgoing status */
unsigned char tvc_sense_buf[TRANSPORT_SENSE_BUFFER];
/* Completed commands list, serviced from vhost worker thread */
struct llist_node tvc_completion_list;
/* Used to track inflight cmd */
struct vhost_scsi_inflight *inflight;
};
struct vhost_scsi_nexus {
/* Pointer to TCM session for I_T Nexus */
struct se_session *tvn_se_sess;
};
struct vhost_scsi_nacl {
/* Binary World Wide unique Port Name for Vhost Initiator port */
u64 iport_wwpn;
/* ASCII formatted WWPN for Sas Initiator port */
char iport_name[VHOST_SCSI_NAMELEN];
/* Returned by vhost_scsi_make_nodeacl() */
struct se_node_acl se_node_acl;
};
struct vhost_scsi_tpg {
/* Vhost port target portal group tag for TCM */
u16 tport_tpgt;
/* Used to track number of TPG Port/Lun Links wrt to explict I_T Nexus shutdown */
int tv_tpg_port_count;
/* Used for vhost_scsi device reference to tpg_nexus, protected by tv_tpg_mutex */
int tv_tpg_vhost_count;
/* list for vhost_scsi_list */
struct list_head tv_tpg_list;
/* Used to protect access for tpg_nexus */
struct mutex tv_tpg_mutex;
/* Pointer to the TCM VHost I_T Nexus for this TPG endpoint */
struct vhost_scsi_nexus *tpg_nexus;
/* Pointer back to vhost_scsi_tport */
struct vhost_scsi_tport *tport;
/* Returned by vhost_scsi_make_tpg() */
struct se_portal_group se_tpg;
/* Pointer back to vhost_scsi, protected by tv_tpg_mutex */
struct vhost_scsi *vhost_scsi;
};
struct vhost_scsi_tport {
/* SCSI protocol the tport is providing */
u8 tport_proto_id;
/* Binary World Wide unique Port Name for Vhost Target port */
u64 tport_wwpn;
/* ASCII formatted WWPN for Vhost Target port */
char tport_name[VHOST_SCSI_NAMELEN];
/* Returned by vhost_scsi_make_tport() */
struct se_wwn tport_wwn;
};
struct vhost_scsi_evt {
/* event to be sent to guest */
struct virtio_scsi_event event;
/* event list, serviced from vhost worker thread */
struct llist_node list;
};
enum {
VHOST_SCSI_VQ_CTL = 0,
VHOST_SCSI_VQ_EVT = 1,
VHOST_SCSI_VQ_IO = 2,
};
/* Note: can't set VIRTIO_F_VERSION_1 yet, since that implies ANY_LAYOUT. */
enum {
VHOST_SCSI_FEATURES = VHOST_FEATURES | (1ULL << VIRTIO_SCSI_F_HOTPLUG) |
(1ULL << VIRTIO_SCSI_F_T10_PI) |
(1ULL << VIRTIO_F_ANY_LAYOUT) |
(1ULL << VIRTIO_F_VERSION_1)
};
#define VHOST_SCSI_MAX_TARGET 256
#define VHOST_SCSI_MAX_VQ 128
#define VHOST_SCSI_MAX_EVENT 128
struct vhost_scsi_virtqueue {
struct vhost_virtqueue vq;
/*
* Reference counting for inflight reqs, used for flush operation. At
* each time, one reference tracks new commands submitted, while we
* wait for another one to reach 0.
*/
struct vhost_scsi_inflight inflights[2];
/*
* Indicate current inflight in use, protected by vq->mutex.
* Writers must also take dev mutex and flush under it.
*/
int inflight_idx;
};
struct vhost_scsi {
/* Protected by vhost_scsi->dev.mutex */
struct vhost_scsi_tpg **vs_tpg;
char vs_vhost_wwpn[TRANSPORT_IQN_LEN];
struct vhost_dev dev;
struct vhost_scsi_virtqueue vqs[VHOST_SCSI_MAX_VQ];
struct vhost_work vs_completion_work; /* cmd completion work item */
struct llist_head vs_completion_list; /* cmd completion queue */
struct vhost_work vs_event_work; /* evt injection work item */
struct llist_head vs_event_list; /* evt injection queue */
bool vs_events_missed; /* any missed events, protected by vq->mutex */
int vs_events_nr; /* num of pending events, protected by vq->mutex */
};
/* Local pointer to allocated TCM configfs fabric module */
static struct target_fabric_configfs *vhost_scsi_fabric_configfs;
static struct workqueue_struct *vhost_scsi_workqueue;
/* Global spinlock to protect vhost_scsi TPG list for vhost IOCTL access */
static DEFINE_MUTEX(vhost_scsi_mutex);
static LIST_HEAD(vhost_scsi_list);
static int iov_num_pages(void __user *iov_base, size_t iov_len)
{
return (PAGE_ALIGN((unsigned long)iov_base + iov_len) -
((unsigned long)iov_base & PAGE_MASK)) >> PAGE_SHIFT;
}
static void vhost_scsi_done_inflight(struct kref *kref)
{
struct vhost_scsi_inflight *inflight;
inflight = container_of(kref, struct vhost_scsi_inflight, kref);
complete(&inflight->comp);
}
static void vhost_scsi_init_inflight(struct vhost_scsi *vs,
struct vhost_scsi_inflight *old_inflight[])
{
struct vhost_scsi_inflight *new_inflight;
struct vhost_virtqueue *vq;
int idx, i;
for (i = 0; i < VHOST_SCSI_MAX_VQ; i++) {
vq = &vs->vqs[i].vq;
mutex_lock(&vq->mutex);
/* store old infight */
idx = vs->vqs[i].inflight_idx;
if (old_inflight)
old_inflight[i] = &vs->vqs[i].inflights[idx];
/* setup new infight */
vs->vqs[i].inflight_idx = idx ^ 1;
new_inflight = &vs->vqs[i].inflights[idx ^ 1];
kref_init(&new_inflight->kref);
init_completion(&new_inflight->comp);
mutex_unlock(&vq->mutex);
}
}
static struct vhost_scsi_inflight *
vhost_scsi_get_inflight(struct vhost_virtqueue *vq)
{
struct vhost_scsi_inflight *inflight;
struct vhost_scsi_virtqueue *svq;
svq = container_of(vq, struct vhost_scsi_virtqueue, vq);
inflight = &svq->inflights[svq->inflight_idx];
kref_get(&inflight->kref);
return inflight;
}
static void vhost_scsi_put_inflight(struct vhost_scsi_inflight *inflight)
{
kref_put(&inflight->kref, vhost_scsi_done_inflight);
}
static int vhost_scsi_check_true(struct se_portal_group *se_tpg)
{
return 1;
}
static int vhost_scsi_check_false(struct se_portal_group *se_tpg)
{
return 0;
}
static char *vhost_scsi_get_fabric_name(void)
{
return "vhost";
}
static u8 vhost_scsi_get_fabric_proto_ident(struct se_portal_group *se_tpg)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
struct vhost_scsi_tport *tport = tpg->tport;
switch (tport->tport_proto_id) {
case SCSI_PROTOCOL_SAS:
return sas_get_fabric_proto_ident(se_tpg);
case SCSI_PROTOCOL_FCP:
return fc_get_fabric_proto_ident(se_tpg);
case SCSI_PROTOCOL_ISCSI:
return iscsi_get_fabric_proto_ident(se_tpg);
default:
pr_err("Unknown tport_proto_id: 0x%02x, using"
" SAS emulation\n", tport->tport_proto_id);
break;
}
return sas_get_fabric_proto_ident(se_tpg);
}
static char *vhost_scsi_get_fabric_wwn(struct se_portal_group *se_tpg)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
struct vhost_scsi_tport *tport = tpg->tport;
return &tport->tport_name[0];
}
static u16 vhost_scsi_get_tpgt(struct se_portal_group *se_tpg)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
return tpg->tport_tpgt;
}
static u32 vhost_scsi_get_default_depth(struct se_portal_group *se_tpg)
{
return 1;
}
static u32
vhost_scsi_get_pr_transport_id(struct se_portal_group *se_tpg,
struct se_node_acl *se_nacl,
struct t10_pr_registration *pr_reg,
int *format_code,
unsigned char *buf)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
struct vhost_scsi_tport *tport = tpg->tport;
switch (tport->tport_proto_id) {
case SCSI_PROTOCOL_SAS:
return sas_get_pr_transport_id(se_tpg, se_nacl, pr_reg,
format_code, buf);
case SCSI_PROTOCOL_FCP:
return fc_get_pr_transport_id(se_tpg, se_nacl, pr_reg,
format_code, buf);
case SCSI_PROTOCOL_ISCSI:
return iscsi_get_pr_transport_id(se_tpg, se_nacl, pr_reg,
format_code, buf);
default:
pr_err("Unknown tport_proto_id: 0x%02x, using"
" SAS emulation\n", tport->tport_proto_id);
break;
}
return sas_get_pr_transport_id(se_tpg, se_nacl, pr_reg,
format_code, buf);
}
static u32
vhost_scsi_get_pr_transport_id_len(struct se_portal_group *se_tpg,
struct se_node_acl *se_nacl,
struct t10_pr_registration *pr_reg,
int *format_code)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
struct vhost_scsi_tport *tport = tpg->tport;
switch (tport->tport_proto_id) {
case SCSI_PROTOCOL_SAS:
return sas_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,
format_code);
case SCSI_PROTOCOL_FCP:
return fc_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,
format_code);
case SCSI_PROTOCOL_ISCSI:
return iscsi_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,
format_code);
default:
pr_err("Unknown tport_proto_id: 0x%02x, using"
" SAS emulation\n", tport->tport_proto_id);
break;
}
return sas_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,
format_code);
}
static char *
vhost_scsi_parse_pr_out_transport_id(struct se_portal_group *se_tpg,
const char *buf,
u32 *out_tid_len,
char **port_nexus_ptr)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
struct vhost_scsi_tport *tport = tpg->tport;
switch (tport->tport_proto_id) {
case SCSI_PROTOCOL_SAS:
return sas_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
port_nexus_ptr);
case SCSI_PROTOCOL_FCP:
return fc_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
port_nexus_ptr);
case SCSI_PROTOCOL_ISCSI:
return iscsi_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
port_nexus_ptr);
default:
pr_err("Unknown tport_proto_id: 0x%02x, using"
" SAS emulation\n", tport->tport_proto_id);
break;
}
return sas_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
port_nexus_ptr);
}
static struct se_node_acl *
vhost_scsi_alloc_fabric_acl(struct se_portal_group *se_tpg)
{
struct vhost_scsi_nacl *nacl;
nacl = kzalloc(sizeof(struct vhost_scsi_nacl), GFP_KERNEL);
if (!nacl) {
pr_err("Unable to allocate struct vhost_scsi_nacl\n");
return NULL;
}
return &nacl->se_node_acl;
}
static void
vhost_scsi_release_fabric_acl(struct se_portal_group *se_tpg,
struct se_node_acl *se_nacl)
{
struct vhost_scsi_nacl *nacl = container_of(se_nacl,
struct vhost_scsi_nacl, se_node_acl);
kfree(nacl);
}
static u32 vhost_scsi_tpg_get_inst_index(struct se_portal_group *se_tpg)
{
return 1;
}
static void vhost_scsi_release_cmd(struct se_cmd *se_cmd)
{
struct vhost_scsi_cmd *tv_cmd = container_of(se_cmd,
struct vhost_scsi_cmd, tvc_se_cmd);
struct se_session *se_sess = tv_cmd->tvc_nexus->tvn_se_sess;
int i;
if (tv_cmd->tvc_sgl_count) {
for (i = 0; i < tv_cmd->tvc_sgl_count; i++)
put_page(sg_page(&tv_cmd->tvc_sgl[i]));
}
if (tv_cmd->tvc_prot_sgl_count) {
for (i = 0; i < tv_cmd->tvc_prot_sgl_count; i++)
put_page(sg_page(&tv_cmd->tvc_prot_sgl[i]));
}
vhost_scsi_put_inflight(tv_cmd->inflight);
percpu_ida_free(&se_sess->sess_tag_pool, se_cmd->map_tag);
}
static int vhost_scsi_shutdown_session(struct se_session *se_sess)
{
return 0;
}
static void vhost_scsi_close_session(struct se_session *se_sess)
{
return;
}
static u32 vhost_scsi_sess_get_index(struct se_session *se_sess)
{
return 0;
}
static int vhost_scsi_write_pending(struct se_cmd *se_cmd)
{
/* Go ahead and process the write immediately */
target_execute_cmd(se_cmd);
return 0;
}
static int vhost_scsi_write_pending_status(struct se_cmd *se_cmd)
{
return 0;
}
static void vhost_scsi_set_default_node_attrs(struct se_node_acl *nacl)
{
return;
}
static u32 vhost_scsi_get_task_tag(struct se_cmd *se_cmd)
{
return 0;
}
static int vhost_scsi_get_cmd_state(struct se_cmd *se_cmd)
{
return 0;
}
static void vhost_scsi_complete_cmd(struct vhost_scsi_cmd *cmd)
{
struct vhost_scsi *vs = cmd->tvc_vhost;
llist_add(&cmd->tvc_completion_list, &vs->vs_completion_list);
vhost_work_queue(&vs->dev, &vs->vs_completion_work);
}
static int vhost_scsi_queue_data_in(struct se_cmd *se_cmd)
{
struct vhost_scsi_cmd *cmd = container_of(se_cmd,
struct vhost_scsi_cmd, tvc_se_cmd);
vhost_scsi_complete_cmd(cmd);
return 0;
}
static int vhost_scsi_queue_status(struct se_cmd *se_cmd)
{
struct vhost_scsi_cmd *cmd = container_of(se_cmd,
struct vhost_scsi_cmd, tvc_se_cmd);
vhost_scsi_complete_cmd(cmd);
return 0;
}
static void vhost_scsi_queue_tm_rsp(struct se_cmd *se_cmd)
{
return;
}
static void vhost_scsi_aborted_task(struct se_cmd *se_cmd)
{
return;
}
static void vhost_scsi_free_evt(struct vhost_scsi *vs, struct vhost_scsi_evt *evt)
{
vs->vs_events_nr--;
kfree(evt);
}
static struct vhost_scsi_evt *
vhost_scsi_allocate_evt(struct vhost_scsi *vs,
u32 event, u32 reason)
{
struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
struct vhost_scsi_evt *evt;
if (vs->vs_events_nr > VHOST_SCSI_MAX_EVENT) {
vs->vs_events_missed = true;
return NULL;
}
evt = kzalloc(sizeof(*evt), GFP_KERNEL);
if (!evt) {
vq_err(vq, "Failed to allocate vhost_scsi_evt\n");
vs->vs_events_missed = true;
return NULL;
}
evt->event.event = cpu_to_vhost32(vq, event);
evt->event.reason = cpu_to_vhost32(vq, reason);
vs->vs_events_nr++;
return evt;
}
static void vhost_scsi_free_cmd(struct vhost_scsi_cmd *cmd)
{
struct se_cmd *se_cmd = &cmd->tvc_se_cmd;
/* TODO locking against target/backend threads? */
transport_generic_free_cmd(se_cmd, 0);
}
static int vhost_scsi_check_stop_free(struct se_cmd *se_cmd)
{
return target_put_sess_cmd(se_cmd->se_sess, se_cmd);
}
static void
vhost_scsi_do_evt_work(struct vhost_scsi *vs, struct vhost_scsi_evt *evt)
{
struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
struct virtio_scsi_event *event = &evt->event;
struct virtio_scsi_event __user *eventp;
unsigned out, in;
int head, ret;
if (!vq->private_data) {
vs->vs_events_missed = true;
return;
}
again:
vhost_disable_notify(&vs->dev, vq);
head = vhost_get_vq_desc(vq, vq->iov,
ARRAY_SIZE(vq->iov), &out, &in,
NULL, NULL);
if (head < 0) {
vs->vs_events_missed = true;
return;
}
if (head == vq->num) {
if (vhost_enable_notify(&vs->dev, vq))
goto again;
vs->vs_events_missed = true;
return;
}
if ((vq->iov[out].iov_len != sizeof(struct virtio_scsi_event))) {
vq_err(vq, "Expecting virtio_scsi_event, got %zu bytes\n",
vq->iov[out].iov_len);
vs->vs_events_missed = true;
return;
}
if (vs->vs_events_missed) {
event->event |= cpu_to_vhost32(vq, VIRTIO_SCSI_T_EVENTS_MISSED);
vs->vs_events_missed = false;
}
eventp = vq->iov[out].iov_base;
ret = __copy_to_user(eventp, event, sizeof(*event));
if (!ret)
vhost_add_used_and_signal(&vs->dev, vq, head, 0);
else
vq_err(vq, "Faulted on vhost_scsi_send_event\n");
}
static void vhost_scsi_evt_work(struct vhost_work *work)
{
struct vhost_scsi *vs = container_of(work, struct vhost_scsi,
vs_event_work);
struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
struct vhost_scsi_evt *evt;
struct llist_node *llnode;
mutex_lock(&vq->mutex);
llnode = llist_del_all(&vs->vs_event_list);
while (llnode) {
evt = llist_entry(llnode, struct vhost_scsi_evt, list);
llnode = llist_next(llnode);
vhost_scsi_do_evt_work(vs, evt);
vhost_scsi_free_evt(vs, evt);
}
mutex_unlock(&vq->mutex);
}
/* Fill in status and signal that we are done processing this command
*
* This is scheduled in the vhost work queue so we are called with the owner
* process mm and can access the vring.
*/
static void vhost_scsi_complete_cmd_work(struct vhost_work *work)
{
struct vhost_scsi *vs = container_of(work, struct vhost_scsi,
vs_completion_work);
DECLARE_BITMAP(signal, VHOST_SCSI_MAX_VQ);
struct virtio_scsi_cmd_resp v_rsp;
struct vhost_scsi_cmd *cmd;
struct llist_node *llnode;
struct se_cmd *se_cmd;
struct iov_iter iov_iter;
int ret, vq;
bitmap_zero(signal, VHOST_SCSI_MAX_VQ);
llnode = llist_del_all(&vs->vs_completion_list);
while (llnode) {
cmd = llist_entry(llnode, struct vhost_scsi_cmd,
tvc_completion_list);
llnode = llist_next(llnode);
se_cmd = &cmd->tvc_se_cmd;
pr_debug("%s tv_cmd %p resid %u status %#02x\n", __func__,
cmd, se_cmd->residual_count, se_cmd->scsi_status);
memset(&v_rsp, 0, sizeof(v_rsp));
v_rsp.resid = cpu_to_vhost32(cmd->tvc_vq, se_cmd->residual_count);
/* TODO is status_qualifier field needed? */
v_rsp.status = se_cmd->scsi_status;
v_rsp.sense_len = cpu_to_vhost32(cmd->tvc_vq,
se_cmd->scsi_sense_length);
memcpy(v_rsp.sense, cmd->tvc_sense_buf,
se_cmd->scsi_sense_length);
iov_iter_init(&iov_iter, READ, cmd->tvc_resp_iov,
cmd->tvc_in_iovs, sizeof(v_rsp));
ret = copy_to_iter(&v_rsp, sizeof(v_rsp), &iov_iter);
if (likely(ret == sizeof(v_rsp))) {
struct vhost_scsi_virtqueue *q;
vhost_add_used(cmd->tvc_vq, cmd->tvc_vq_desc, 0);
q = container_of(cmd->tvc_vq, struct vhost_scsi_virtqueue, vq);
vq = q - vs->vqs;
__set_bit(vq, signal);
} else
pr_err("Faulted on virtio_scsi_cmd_resp\n");
vhost_scsi_free_cmd(cmd);
}
vq = -1;
while ((vq = find_next_bit(signal, VHOST_SCSI_MAX_VQ, vq + 1))
< VHOST_SCSI_MAX_VQ)
vhost_signal(&vs->dev, &vs->vqs[vq].vq);
}
static struct vhost_scsi_cmd *
vhost_scsi_get_tag(struct vhost_virtqueue *vq, struct vhost_scsi_tpg *tpg,
unsigned char *cdb, u64 scsi_tag, u16 lun, u8 task_attr,
u32 exp_data_len, int data_direction)
{
struct vhost_scsi_cmd *cmd;
struct vhost_scsi_nexus *tv_nexus;
struct se_session *se_sess;
struct scatterlist *sg, *prot_sg;
struct page **pages;
int tag;
tv_nexus = tpg->tpg_nexus;
if (!tv_nexus) {
pr_err("Unable to locate active struct vhost_scsi_nexus\n");
return ERR_PTR(-EIO);
}
se_sess = tv_nexus->tvn_se_sess;
tag = percpu_ida_alloc(&se_sess->sess_tag_pool, TASK_RUNNING);
if (tag < 0) {
pr_err("Unable to obtain tag for vhost_scsi_cmd\n");
return ERR_PTR(-ENOMEM);
}
cmd = &((struct vhost_scsi_cmd *)se_sess->sess_cmd_map)[tag];
sg = cmd->tvc_sgl;
prot_sg = cmd->tvc_prot_sgl;
pages = cmd->tvc_upages;
memset(cmd, 0, sizeof(struct vhost_scsi_cmd));
cmd->tvc_sgl = sg;
cmd->tvc_prot_sgl = prot_sg;
cmd->tvc_upages = pages;
cmd->tvc_se_cmd.map_tag = tag;
cmd->tvc_tag = scsi_tag;
cmd->tvc_lun = lun;
cmd->tvc_task_attr = task_attr;
cmd->tvc_exp_data_len = exp_data_len;
cmd->tvc_data_direction = data_direction;
cmd->tvc_nexus = tv_nexus;
cmd->inflight = vhost_scsi_get_inflight(vq);
memcpy(cmd->tvc_cdb, cdb, VHOST_SCSI_MAX_CDB_SIZE);
return cmd;
}
/*
* Map a user memory range into a scatterlist
*
* Returns the number of scatterlist entries used or -errno on error.
*/
static int
vhost_scsi_map_to_sgl(struct vhost_scsi_cmd *cmd,
void __user *ptr,
size_t len,
struct scatterlist *sgl,
bool write)
{
unsigned int npages = 0, offset, nbytes;
unsigned int pages_nr = iov_num_pages(ptr, len);
struct scatterlist *sg = sgl;
struct page **pages = cmd->tvc_upages;
int ret, i;
if (pages_nr > VHOST_SCSI_PREALLOC_UPAGES) {
pr_err("vhost_scsi_map_to_sgl() pages_nr: %u greater than"
" preallocated VHOST_SCSI_PREALLOC_UPAGES: %u\n",
pages_nr, VHOST_SCSI_PREALLOC_UPAGES);
return -ENOBUFS;
}
ret = get_user_pages_fast((unsigned long)ptr, pages_nr, write, pages);
/* No pages were pinned */
if (ret < 0)
goto out;
/* Less pages pinned than wanted */
if (ret != pages_nr) {
for (i = 0; i < ret; i++)
put_page(pages[i]);
ret = -EFAULT;
goto out;
}
while (len > 0) {
offset = (uintptr_t)ptr & ~PAGE_MASK;
nbytes = min_t(unsigned int, PAGE_SIZE - offset, len);
sg_set_page(sg, pages[npages], nbytes, offset);
ptr += nbytes;
len -= nbytes;
sg++;
npages++;
}
out:
return ret;
}
static int
vhost_scsi_calc_sgls(struct iov_iter *iter, size_t bytes, int max_sgls)
{
int sgl_count = 0;
if (!iter || !iter->iov) {
pr_err("%s: iter->iov is NULL, but expected bytes: %zu"
" present\n", __func__, bytes);
return -EINVAL;
}
sgl_count = iov_iter_npages(iter, 0xffff);
if (sgl_count > max_sgls) {
pr_err("%s: requested sgl_count: %d exceeds pre-allocated"
" max_sgls: %d\n", __func__, sgl_count, max_sgls);
return -EINVAL;
}
return sgl_count;
}
static int
vhost_scsi_iov_to_sgl(struct vhost_scsi_cmd *cmd, bool write,
struct iov_iter *iter,
struct scatterlist *sg, int sg_count)
{
size_t off = iter->iov_offset;
int i, ret;
for (i = 0; i < iter->nr_segs; i++) {
void __user *base = iter->iov[i].iov_base + off;
size_t len = iter->iov[i].iov_len - off;
ret = vhost_scsi_map_to_sgl(cmd, base, len, sg, write);
if (ret < 0) {
for (i = 0; i < sg_count; i++) {
struct page *page = sg_page(&sg[i]);
if (page)
put_page(page);
}
return ret;
}
sg += ret;
off = 0;
}
return 0;
}
static int
vhost_scsi_mapal(struct vhost_scsi_cmd *cmd,
size_t prot_bytes, struct iov_iter *prot_iter,
size_t data_bytes, struct iov_iter *data_iter)
{
int sgl_count, ret;
bool write = (cmd->tvc_data_direction == DMA_FROM_DEVICE);
if (prot_bytes) {
sgl_count = vhost_scsi_calc_sgls(prot_iter, prot_bytes,
VHOST_SCSI_PREALLOC_PROT_SGLS);
if (sgl_count < 0)
return sgl_count;
sg_init_table(cmd->tvc_prot_sgl, sgl_count);
cmd->tvc_prot_sgl_count = sgl_count;
pr_debug("%s prot_sg %p prot_sgl_count %u\n", __func__,
cmd->tvc_prot_sgl, cmd->tvc_prot_sgl_count);
ret = vhost_scsi_iov_to_sgl(cmd, write, prot_iter,
cmd->tvc_prot_sgl,
cmd->tvc_prot_sgl_count);
if (ret < 0) {
cmd->tvc_prot_sgl_count = 0;
return ret;
}
}
sgl_count = vhost_scsi_calc_sgls(data_iter, data_bytes,
VHOST_SCSI_PREALLOC_SGLS);
if (sgl_count < 0)
return sgl_count;
sg_init_table(cmd->tvc_sgl, sgl_count);
cmd->tvc_sgl_count = sgl_count;
pr_debug("%s data_sg %p data_sgl_count %u\n", __func__,
cmd->tvc_sgl, cmd->tvc_sgl_count);
ret = vhost_scsi_iov_to_sgl(cmd, write, data_iter,
cmd->tvc_sgl, cmd->tvc_sgl_count);
if (ret < 0) {
cmd->tvc_sgl_count = 0;
return ret;
}
return 0;
}
static void vhost_scsi_submission_work(struct work_struct *work)
{
struct vhost_scsi_cmd *cmd =
container_of(work, struct vhost_scsi_cmd, work);
struct vhost_scsi_nexus *tv_nexus;
struct se_cmd *se_cmd = &cmd->tvc_se_cmd;
struct scatterlist *sg_ptr, *sg_prot_ptr = NULL;
int rc;
/* FIXME: BIDI operation */
if (cmd->tvc_sgl_count) {
sg_ptr = cmd->tvc_sgl;
if (cmd->tvc_prot_sgl_count)
sg_prot_ptr = cmd->tvc_prot_sgl;
else
se_cmd->prot_pto = true;
} else {
sg_ptr = NULL;
}
tv_nexus = cmd->tvc_nexus;
rc = target_submit_cmd_map_sgls(se_cmd, tv_nexus->tvn_se_sess,
cmd->tvc_cdb, &cmd->tvc_sense_buf[0],
cmd->tvc_lun, cmd->tvc_exp_data_len,
cmd->tvc_task_attr, cmd->tvc_data_direction,
TARGET_SCF_ACK_KREF, sg_ptr, cmd->tvc_sgl_count,
NULL, 0, sg_prot_ptr, cmd->tvc_prot_sgl_count);
if (rc < 0) {
transport_send_check_condition_and_sense(se_cmd,
TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE, 0);
transport_generic_free_cmd(se_cmd, 0);
}
}
static void
vhost_scsi_send_bad_target(struct vhost_scsi *vs,
struct vhost_virtqueue *vq,
int head, unsigned out)
{
struct virtio_scsi_cmd_resp __user *resp;
struct virtio_scsi_cmd_resp rsp;
int ret;
memset(&rsp, 0, sizeof(rsp));
rsp.response = VIRTIO_SCSI_S_BAD_TARGET;
resp = vq->iov[out].iov_base;
ret = __copy_to_user(resp, &rsp, sizeof(rsp));
if (!ret)
vhost_add_used_and_signal(&vs->dev, vq, head, 0);
else
pr_err("Faulted on virtio_scsi_cmd_resp\n");
}
static void
vhost_scsi_handle_vq(struct vhost_scsi *vs, struct vhost_virtqueue *vq)
{
struct vhost_scsi_tpg **vs_tpg, *tpg;
struct virtio_scsi_cmd_req v_req;
struct virtio_scsi_cmd_req_pi v_req_pi;
struct vhost_scsi_cmd *cmd;
struct iov_iter out_iter, in_iter, prot_iter, data_iter;
u64 tag;
u32 exp_data_len, data_direction;
unsigned out, in;
int head, ret, prot_bytes;
size_t req_size, rsp_size = sizeof(struct virtio_scsi_cmd_resp);
size_t out_size, in_size;
u16 lun;
u8 *target, *lunp, task_attr;
bool t10_pi = vhost_has_feature(vq, VIRTIO_SCSI_F_T10_PI);
void *req, *cdb;
mutex_lock(&vq->mutex);
/*
* We can handle the vq only after the endpoint is setup by calling the
* VHOST_SCSI_SET_ENDPOINT ioctl.
*/
vs_tpg = vq->private_data;
if (!vs_tpg)
goto out;
vhost_disable_notify(&vs->dev, vq);
for (;;) {
head = vhost_get_vq_desc(vq, vq->iov,
ARRAY_SIZE(vq->iov), &out, &in,
NULL, NULL);
pr_debug("vhost_get_vq_desc: head: %d, out: %u in: %u\n",
head, out, in);
/* On error, stop handling until the next kick. */
if (unlikely(head < 0))
break;
/* Nothing new? Wait for eventfd to tell us they refilled. */
if (head == vq->num) {
if (unlikely(vhost_enable_notify(&vs->dev, vq))) {
vhost_disable_notify(&vs->dev, vq);
continue;
}
break;
}
/*
* Check for a sane response buffer so we can report early
* errors back to the guest.
*/
if (unlikely(vq->iov[out].iov_len < rsp_size)) {
vq_err(vq, "Expecting at least virtio_scsi_cmd_resp"
" size, got %zu bytes\n", vq->iov[out].iov_len);
break;
}
/*
* Setup pointers and values based upon different virtio-scsi
* request header if T10_PI is enabled in KVM guest.
*/
if (t10_pi) {
req = &v_req_pi;
req_size = sizeof(v_req_pi);
lunp = &v_req_pi.lun[0];
target = &v_req_pi.lun[1];
} else {
req = &v_req;
req_size = sizeof(v_req);
lunp = &v_req.lun[0];
target = &v_req.lun[1];
}
/*
* FIXME: Not correct for BIDI operation
*/
out_size = iov_length(vq->iov, out);
in_size = iov_length(&vq->iov[out], in);
/*
* Copy over the virtio-scsi request header, which for a
* ANY_LAYOUT enabled guest may span multiple iovecs, or a
* single iovec may contain both the header + outgoing
* WRITE payloads.
*
* copy_from_iter() will advance out_iter, so that it will
* point at the start of the outgoing WRITE payload, if
* DMA_TO_DEVICE is set.
*/
iov_iter_init(&out_iter, WRITE, vq->iov, out, out_size);
ret = copy_from_iter(req, req_size, &out_iter);
if (unlikely(ret != req_size)) {
vq_err(vq, "Faulted on copy_from_iter\n");
vhost_scsi_send_bad_target(vs, vq, head, out);
continue;
}
/* virtio-scsi spec requires byte 0 of the lun to be 1 */
if (unlikely(*lunp != 1)) {
vq_err(vq, "Illegal virtio-scsi lun: %u\n", *lunp);
vhost_scsi_send_bad_target(vs, vq, head, out);
continue;
}
tpg = ACCESS_ONCE(vs_tpg[*target]);
if (unlikely(!tpg)) {
/* Target does not exist, fail the request */
vhost_scsi_send_bad_target(vs, vq, head, out);
continue;
}
/*
* Determine data_direction by calculating the total outgoing
* iovec sizes + incoming iovec sizes vs. virtio-scsi request +
* response headers respectively.
*
* For DMA_TO_DEVICE this is out_iter, which is already pointing
* to the right place.
*
* For DMA_FROM_DEVICE, the iovec will be just past the end
* of the virtio-scsi response header in either the same
* or immediately following iovec.
*
* Any associated T10_PI bytes for the outgoing / incoming
* payloads are included in calculation of exp_data_len here.
*/
prot_bytes = 0;
if (out_size > req_size) {
data_direction = DMA_TO_DEVICE;
exp_data_len = out_size - req_size;
data_iter = out_iter;
} else if (in_size > rsp_size) {
data_direction = DMA_FROM_DEVICE;
exp_data_len = in_size - rsp_size;
iov_iter_init(&in_iter, READ, &vq->iov[out], in,
rsp_size + exp_data_len);
iov_iter_advance(&in_iter, rsp_size);
data_iter = in_iter;
} else {
data_direction = DMA_NONE;
exp_data_len = 0;
}
/*
* If T10_PI header + payload is present, setup prot_iter values
* and recalculate data_iter for vhost_scsi_mapal() mapping to
* host scatterlists via get_user_pages_fast().
*/
if (t10_pi) {
if (v_req_pi.pi_bytesout) {
if (data_direction != DMA_TO_DEVICE) {
vq_err(vq, "Received non zero pi_bytesout,"
" but wrong data_direction\n");
vhost_scsi_send_bad_target(vs, vq, head, out);
continue;
}
prot_bytes = vhost32_to_cpu(vq, v_req_pi.pi_bytesout);
} else if (v_req_pi.pi_bytesin) {
if (data_direction != DMA_FROM_DEVICE) {
vq_err(vq, "Received non zero pi_bytesin,"
" but wrong data_direction\n");
vhost_scsi_send_bad_target(vs, vq, head, out);
continue;
}
prot_bytes = vhost32_to_cpu(vq, v_req_pi.pi_bytesin);
}
/*
* Set prot_iter to data_iter, and advance past any
* preceeding prot_bytes that may be present.
*
* Also fix up the exp_data_len to reflect only the
* actual data payload length.
*/
if (prot_bytes) {
exp_data_len -= prot_bytes;
prot_iter = data_iter;
iov_iter_advance(&data_iter, prot_bytes);
}
tag = vhost64_to_cpu(vq, v_req_pi.tag);
task_attr = v_req_pi.task_attr;
cdb = &v_req_pi.cdb[0];
lun = ((v_req_pi.lun[2] << 8) | v_req_pi.lun[3]) & 0x3FFF;
} else {
tag = vhost64_to_cpu(vq, v_req.tag);
task_attr = v_req.task_attr;
cdb = &v_req.cdb[0];
lun = ((v_req.lun[2] << 8) | v_req.lun[3]) & 0x3FFF;
}
/*
* Check that the received CDB size does not exceeded our
* hardcoded max for vhost-scsi, then get a pre-allocated
* cmd descriptor for the new virtio-scsi tag.
*
* TODO what if cdb was too small for varlen cdb header?
*/
if (unlikely(scsi_command_size(cdb) > VHOST_SCSI_MAX_CDB_SIZE)) {
vq_err(vq, "Received SCSI CDB with command_size: %d that"
" exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n",
scsi_command_size(cdb), VHOST_SCSI_MAX_CDB_SIZE);
vhost_scsi_send_bad_target(vs, vq, head, out);
continue;
}
cmd = vhost_scsi_get_tag(vq, tpg, cdb, tag, lun, task_attr,
exp_data_len + prot_bytes,
data_direction);
if (IS_ERR(cmd)) {
vq_err(vq, "vhost_scsi_get_tag failed %ld\n",
PTR_ERR(cmd));
vhost_scsi_send_bad_target(vs, vq, head, out);
continue;
}
cmd->tvc_vhost = vs;
cmd->tvc_vq = vq;
cmd->tvc_resp_iov = &vq->iov[out];
cmd->tvc_in_iovs = in;
pr_debug("vhost_scsi got command opcode: %#02x, lun: %d\n",
cmd->tvc_cdb[0], cmd->tvc_lun);
pr_debug("cmd: %p exp_data_len: %d, prot_bytes: %d data_direction:"
" %d\n", cmd, exp_data_len, prot_bytes, data_direction);
if (data_direction != DMA_NONE) {
ret = vhost_scsi_mapal(cmd,
prot_bytes, &prot_iter,
exp_data_len, &data_iter);
if (unlikely(ret)) {
vq_err(vq, "Failed to map iov to sgl\n");
vhost_scsi_release_cmd(&cmd->tvc_se_cmd);
vhost_scsi_send_bad_target(vs, vq, head, out);
continue;
}
}
/*
* Save the descriptor from vhost_get_vq_desc() to be used to
* complete the virtio-scsi request in TCM callback context via
* vhost_scsi_queue_data_in() and vhost_scsi_queue_status()
*/
cmd->tvc_vq_desc = head;
/*
* Dispatch cmd descriptor for cmwq execution in process
* context provided by vhost_scsi_workqueue. This also ensures
* cmd is executed on the same kworker CPU as this vhost
* thread to gain positive L2 cache locality effects.
*/
INIT_WORK(&cmd->work, vhost_scsi_submission_work);
queue_work(vhost_scsi_workqueue, &cmd->work);
}
out:
mutex_unlock(&vq->mutex);
}
static void vhost_scsi_ctl_handle_kick(struct vhost_work *work)
{
pr_debug("%s: The handling func for control queue.\n", __func__);
}
static void
vhost_scsi_send_evt(struct vhost_scsi *vs,
struct vhost_scsi_tpg *tpg,
struct se_lun *lun,
u32 event,
u32 reason)
{
struct vhost_scsi_evt *evt;
evt = vhost_scsi_allocate_evt(vs, event, reason);
if (!evt)
return;
if (tpg && lun) {
/* TODO: share lun setup code with virtio-scsi.ko */
/*
* Note: evt->event is zeroed when we allocate it and
* lun[4-7] need to be zero according to virtio-scsi spec.
*/
evt->event.lun[0] = 0x01;
evt->event.lun[1] = tpg->tport_tpgt & 0xFF;
if (lun->unpacked_lun >= 256)
evt->event.lun[2] = lun->unpacked_lun >> 8 | 0x40 ;
evt->event.lun[3] = lun->unpacked_lun & 0xFF;
}
llist_add(&evt->list, &vs->vs_event_list);
vhost_work_queue(&vs->dev, &vs->vs_event_work);
}
static void vhost_scsi_evt_handle_kick(struct vhost_work *work)
{
struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
poll.work);
struct vhost_scsi *vs = container_of(vq->dev, struct vhost_scsi, dev);
mutex_lock(&vq->mutex);
if (!vq->private_data)
goto out;
if (vs->vs_events_missed)
vhost_scsi_send_evt(vs, NULL, NULL, VIRTIO_SCSI_T_NO_EVENT, 0);
out:
mutex_unlock(&vq->mutex);
}
static void vhost_scsi_handle_kick(struct vhost_work *work)
{
struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
poll.work);
struct vhost_scsi *vs = container_of(vq->dev, struct vhost_scsi, dev);
vhost_scsi_handle_vq(vs, vq);
}
static void vhost_scsi_flush_vq(struct vhost_scsi *vs, int index)
{
vhost_poll_flush(&vs->vqs[index].vq.poll);
}
/* Callers must hold dev mutex */
static void vhost_scsi_flush(struct vhost_scsi *vs)
{
struct vhost_scsi_inflight *old_inflight[VHOST_SCSI_MAX_VQ];
int i;
/* Init new inflight and remember the old inflight */
vhost_scsi_init_inflight(vs, old_inflight);
/*
* The inflight->kref was initialized to 1. We decrement it here to
* indicate the start of the flush operation so that it will reach 0
* when all the reqs are finished.
*/
for (i = 0; i < VHOST_SCSI_MAX_VQ; i++)
kref_put(&old_inflight[i]->kref, vhost_scsi_done_inflight);
/* Flush both the vhost poll and vhost work */
for (i = 0; i < VHOST_SCSI_MAX_VQ; i++)
vhost_scsi_flush_vq(vs, i);
vhost_work_flush(&vs->dev, &vs->vs_completion_work);
vhost_work_flush(&vs->dev, &vs->vs_event_work);
/* Wait for all reqs issued before the flush to be finished */
for (i = 0; i < VHOST_SCSI_MAX_VQ; i++)
wait_for_completion(&old_inflight[i]->comp);
}
/*
* Called from vhost_scsi_ioctl() context to walk the list of available
* vhost_scsi_tpg with an active struct vhost_scsi_nexus
*
* The lock nesting rule is:
* vhost_scsi_mutex -> vs->dev.mutex -> tpg->tv_tpg_mutex -> vq->mutex
*/
static int
vhost_scsi_set_endpoint(struct vhost_scsi *vs,
struct vhost_scsi_target *t)
{
struct se_portal_group *se_tpg;
struct vhost_scsi_tport *tv_tport;
struct vhost_scsi_tpg *tpg;
struct vhost_scsi_tpg **vs_tpg;
struct vhost_virtqueue *vq;
int index, ret, i, len;
bool match = false;
mutex_lock(&vhost_scsi_mutex);
mutex_lock(&vs->dev.mutex);
/* Verify that ring has been setup correctly. */
for (index = 0; index < vs->dev.nvqs; ++index) {
/* Verify that ring has been setup correctly. */
if (!vhost_vq_access_ok(&vs->vqs[index].vq)) {
ret = -EFAULT;
goto out;
}
}
len = sizeof(vs_tpg[0]) * VHOST_SCSI_MAX_TARGET;
vs_tpg = kzalloc(len, GFP_KERNEL);
if (!vs_tpg) {
ret = -ENOMEM;
goto out;
}
if (vs->vs_tpg)
memcpy(vs_tpg, vs->vs_tpg, len);
list_for_each_entry(tpg, &vhost_scsi_list, tv_tpg_list) {
mutex_lock(&tpg->tv_tpg_mutex);
if (!tpg->tpg_nexus) {
mutex_unlock(&tpg->tv_tpg_mutex);
continue;
}
if (tpg->tv_tpg_vhost_count != 0) {
mutex_unlock(&tpg->tv_tpg_mutex);
continue;
}
tv_tport = tpg->tport;
if (!strcmp(tv_tport->tport_name, t->vhost_wwpn)) {
if (vs->vs_tpg && vs->vs_tpg[tpg->tport_tpgt]) {
kfree(vs_tpg);
mutex_unlock(&tpg->tv_tpg_mutex);
ret = -EEXIST;
goto out;
}
/*
* In order to ensure individual vhost-scsi configfs
* groups cannot be removed while in use by vhost ioctl,
* go ahead and take an explicit se_tpg->tpg_group.cg_item
* dependency now.
*/
se_tpg = &tpg->se_tpg;
ret = configfs_depend_item(se_tpg->se_tpg_tfo->tf_subsys,
&se_tpg->tpg_group.cg_item);
if (ret) {
pr_warn("configfs_depend_item() failed: %d\n", ret);
kfree(vs_tpg);
mutex_unlock(&tpg->tv_tpg_mutex);
goto out;
}
tpg->tv_tpg_vhost_count++;
tpg->vhost_scsi = vs;
vs_tpg[tpg->tport_tpgt] = tpg;
smp_mb__after_atomic();
match = true;
}
mutex_unlock(&tpg->tv_tpg_mutex);
}
if (match) {
memcpy(vs->vs_vhost_wwpn, t->vhost_wwpn,
sizeof(vs->vs_vhost_wwpn));
for (i = 0; i < VHOST_SCSI_MAX_VQ; i++) {
vq = &vs->vqs[i].vq;
mutex_lock(&vq->mutex);
vq->private_data = vs_tpg;
vhost_init_used(vq);
mutex_unlock(&vq->mutex);
}
ret = 0;
} else {
ret = -EEXIST;
}
/*
* Act as synchronize_rcu to make sure access to
* old vs->vs_tpg is finished.
*/
vhost_scsi_flush(vs);
kfree(vs->vs_tpg);
vs->vs_tpg = vs_tpg;
out:
mutex_unlock(&vs->dev.mutex);
mutex_unlock(&vhost_scsi_mutex);
return ret;
}
static int
vhost_scsi_clear_endpoint(struct vhost_scsi *vs,
struct vhost_scsi_target *t)
{
struct se_portal_group *se_tpg;
struct vhost_scsi_tport *tv_tport;
struct vhost_scsi_tpg *tpg;
struct vhost_virtqueue *vq;
bool match = false;
int index, ret, i;
u8 target;
mutex_lock(&vhost_scsi_mutex);
mutex_lock(&vs->dev.mutex);
/* Verify that ring has been setup correctly. */
for (index = 0; index < vs->dev.nvqs; ++index) {
if (!vhost_vq_access_ok(&vs->vqs[index].vq)) {
ret = -EFAULT;
goto err_dev;
}
}
if (!vs->vs_tpg) {
ret = 0;
goto err_dev;
}
for (i = 0; i < VHOST_SCSI_MAX_TARGET; i++) {
target = i;
tpg = vs->vs_tpg[target];
if (!tpg)
continue;
mutex_lock(&tpg->tv_tpg_mutex);
tv_tport = tpg->tport;
if (!tv_tport) {
ret = -ENODEV;
goto err_tpg;
}
if (strcmp(tv_tport->tport_name, t->vhost_wwpn)) {
pr_warn("tv_tport->tport_name: %s, tpg->tport_tpgt: %hu"
" does not match t->vhost_wwpn: %s, t->vhost_tpgt: %hu\n",
tv_tport->tport_name, tpg->tport_tpgt,
t->vhost_wwpn, t->vhost_tpgt);
ret = -EINVAL;
goto err_tpg;
}
tpg->tv_tpg_vhost_count--;
tpg->vhost_scsi = NULL;
vs->vs_tpg[target] = NULL;
match = true;
mutex_unlock(&tpg->tv_tpg_mutex);
/*
* Release se_tpg->tpg_group.cg_item configfs dependency now
* to allow vhost-scsi WWPN se_tpg->tpg_group shutdown to occur.
*/
se_tpg = &tpg->se_tpg;
configfs_undepend_item(se_tpg->se_tpg_tfo->tf_subsys,
&se_tpg->tpg_group.cg_item);
}
if (match) {
for (i = 0; i < VHOST_SCSI_MAX_VQ; i++) {
vq = &vs->vqs[i].vq;
mutex_lock(&vq->mutex);
vq->private_data = NULL;
mutex_unlock(&vq->mutex);
}
}
/*
* Act as synchronize_rcu to make sure access to
* old vs->vs_tpg is finished.
*/
vhost_scsi_flush(vs);
kfree(vs->vs_tpg);
vs->vs_tpg = NULL;
WARN_ON(vs->vs_events_nr);
mutex_unlock(&vs->dev.mutex);
mutex_unlock(&vhost_scsi_mutex);
return 0;
err_tpg:
mutex_unlock(&tpg->tv_tpg_mutex);
err_dev:
mutex_unlock(&vs->dev.mutex);
mutex_unlock(&vhost_scsi_mutex);
return ret;
}
static int vhost_scsi_set_features(struct vhost_scsi *vs, u64 features)
{
struct vhost_virtqueue *vq;
int i;
if (features & ~VHOST_SCSI_FEATURES)
return -EOPNOTSUPP;
mutex_lock(&vs->dev.mutex);
if ((features & (1 << VHOST_F_LOG_ALL)) &&
!vhost_log_access_ok(&vs->dev)) {
mutex_unlock(&vs->dev.mutex);
return -EFAULT;
}
for (i = 0; i < VHOST_SCSI_MAX_VQ; i++) {
vq = &vs->vqs[i].vq;
mutex_lock(&vq->mutex);
vq->acked_features = features;
mutex_unlock(&vq->mutex);
}
mutex_unlock(&vs->dev.mutex);
return 0;
}
static int vhost_scsi_open(struct inode *inode, struct file *f)
{
struct vhost_scsi *vs;
struct vhost_virtqueue **vqs;
int r = -ENOMEM, i;
vs = kzalloc(sizeof(*vs), GFP_KERNEL | __GFP_NOWARN | __GFP_REPEAT);
if (!vs) {
vs = vzalloc(sizeof(*vs));
if (!vs)
goto err_vs;
}
vqs = kmalloc(VHOST_SCSI_MAX_VQ * sizeof(*vqs), GFP_KERNEL);
if (!vqs)
goto err_vqs;
vhost_work_init(&vs->vs_completion_work, vhost_scsi_complete_cmd_work);
vhost_work_init(&vs->vs_event_work, vhost_scsi_evt_work);
vs->vs_events_nr = 0;
vs->vs_events_missed = false;
vqs[VHOST_SCSI_VQ_CTL] = &vs->vqs[VHOST_SCSI_VQ_CTL].vq;
vqs[VHOST_SCSI_VQ_EVT] = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
vs->vqs[VHOST_SCSI_VQ_CTL].vq.handle_kick = vhost_scsi_ctl_handle_kick;
vs->vqs[VHOST_SCSI_VQ_EVT].vq.handle_kick = vhost_scsi_evt_handle_kick;
for (i = VHOST_SCSI_VQ_IO; i < VHOST_SCSI_MAX_VQ; i++) {
vqs[i] = &vs->vqs[i].vq;
vs->vqs[i].vq.handle_kick = vhost_scsi_handle_kick;
}
vhost_dev_init(&vs->dev, vqs, VHOST_SCSI_MAX_VQ);
vhost_scsi_init_inflight(vs, NULL);
f->private_data = vs;
return 0;
err_vqs:
kvfree(vs);
err_vs:
return r;
}
static int vhost_scsi_release(struct inode *inode, struct file *f)
{
struct vhost_scsi *vs = f->private_data;
struct vhost_scsi_target t;
mutex_lock(&vs->dev.mutex);
memcpy(t.vhost_wwpn, vs->vs_vhost_wwpn, sizeof(t.vhost_wwpn));
mutex_unlock(&vs->dev.mutex);
vhost_scsi_clear_endpoint(vs, &t);
vhost_dev_stop(&vs->dev);
vhost_dev_cleanup(&vs->dev, false);
/* Jobs can re-queue themselves in evt kick handler. Do extra flush. */
vhost_scsi_flush(vs);
kfree(vs->dev.vqs);
kvfree(vs);
return 0;
}
static long
vhost_scsi_ioctl(struct file *f,
unsigned int ioctl,
unsigned long arg)
{
struct vhost_scsi *vs = f->private_data;
struct vhost_scsi_target backend;
void __user *argp = (void __user *)arg;
u64 __user *featurep = argp;
u32 __user *eventsp = argp;
u32 events_missed;
u64 features;
int r, abi_version = VHOST_SCSI_ABI_VERSION;
struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
switch (ioctl) {
case VHOST_SCSI_SET_ENDPOINT:
if (copy_from_user(&backend, argp, sizeof backend))
return -EFAULT;
if (backend.reserved != 0)
return -EOPNOTSUPP;
return vhost_scsi_set_endpoint(vs, &backend);
case VHOST_SCSI_CLEAR_ENDPOINT:
if (copy_from_user(&backend, argp, sizeof backend))
return -EFAULT;
if (backend.reserved != 0)
return -EOPNOTSUPP;
return vhost_scsi_clear_endpoint(vs, &backend);
case VHOST_SCSI_GET_ABI_VERSION:
if (copy_to_user(argp, &abi_version, sizeof abi_version))
return -EFAULT;
return 0;
case VHOST_SCSI_SET_EVENTS_MISSED:
if (get_user(events_missed, eventsp))
return -EFAULT;
mutex_lock(&vq->mutex);
vs->vs_events_missed = events_missed;
mutex_unlock(&vq->mutex);
return 0;
case VHOST_SCSI_GET_EVENTS_MISSED:
mutex_lock(&vq->mutex);
events_missed = vs->vs_events_missed;
mutex_unlock(&vq->mutex);
if (put_user(events_missed, eventsp))
return -EFAULT;
return 0;
case VHOST_GET_FEATURES:
features = VHOST_SCSI_FEATURES;
if (copy_to_user(featurep, &features, sizeof features))
return -EFAULT;
return 0;
case VHOST_SET_FEATURES:
if (copy_from_user(&features, featurep, sizeof features))
return -EFAULT;
return vhost_scsi_set_features(vs, features);
default:
mutex_lock(&vs->dev.mutex);
r = vhost_dev_ioctl(&vs->dev, ioctl, argp);
/* TODO: flush backend after dev ioctl. */
if (r == -ENOIOCTLCMD)
r = vhost_vring_ioctl(&vs->dev, ioctl, argp);
mutex_unlock(&vs->dev.mutex);
return r;
}
}
#ifdef CONFIG_COMPAT
static long vhost_scsi_compat_ioctl(struct file *f, unsigned int ioctl,
unsigned long arg)
{
return vhost_scsi_ioctl(f, ioctl, (unsigned long)compat_ptr(arg));
}
#endif
static const struct file_operations vhost_scsi_fops = {
.owner = THIS_MODULE,
.release = vhost_scsi_release,
.unlocked_ioctl = vhost_scsi_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = vhost_scsi_compat_ioctl,
#endif
.open = vhost_scsi_open,
.llseek = noop_llseek,
};
static struct miscdevice vhost_scsi_misc = {
MISC_DYNAMIC_MINOR,
"vhost-scsi",
&vhost_scsi_fops,
};
static int __init vhost_scsi_register(void)
{
return misc_register(&vhost_scsi_misc);
}
static int vhost_scsi_deregister(void)
{
return misc_deregister(&vhost_scsi_misc);
}
static char *vhost_scsi_dump_proto_id(struct vhost_scsi_tport *tport)
{
switch (tport->tport_proto_id) {
case SCSI_PROTOCOL_SAS:
return "SAS";
case SCSI_PROTOCOL_FCP:
return "FCP";
case SCSI_PROTOCOL_ISCSI:
return "iSCSI";
default:
break;
}
return "Unknown";
}
static void
vhost_scsi_do_plug(struct vhost_scsi_tpg *tpg,
struct se_lun *lun, bool plug)
{
struct vhost_scsi *vs = tpg->vhost_scsi;
struct vhost_virtqueue *vq;
u32 reason;
if (!vs)
return;
mutex_lock(&vs->dev.mutex);
if (plug)
reason = VIRTIO_SCSI_EVT_RESET_RESCAN;
else
reason = VIRTIO_SCSI_EVT_RESET_REMOVED;
vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
mutex_lock(&vq->mutex);
if (vhost_has_feature(vq, VIRTIO_SCSI_F_HOTPLUG))
vhost_scsi_send_evt(vs, tpg, lun,
VIRTIO_SCSI_T_TRANSPORT_RESET, reason);
mutex_unlock(&vq->mutex);
mutex_unlock(&vs->dev.mutex);
}
static void vhost_scsi_hotplug(struct vhost_scsi_tpg *tpg, struct se_lun *lun)
{
vhost_scsi_do_plug(tpg, lun, true);
}
static void vhost_scsi_hotunplug(struct vhost_scsi_tpg *tpg, struct se_lun *lun)
{
vhost_scsi_do_plug(tpg, lun, false);
}
static int vhost_scsi_port_link(struct se_portal_group *se_tpg,
struct se_lun *lun)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
mutex_lock(&vhost_scsi_mutex);
mutex_lock(&tpg->tv_tpg_mutex);
tpg->tv_tpg_port_count++;
mutex_unlock(&tpg->tv_tpg_mutex);
vhost_scsi_hotplug(tpg, lun);
mutex_unlock(&vhost_scsi_mutex);
return 0;
}
static void vhost_scsi_port_unlink(struct se_portal_group *se_tpg,
struct se_lun *lun)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
mutex_lock(&vhost_scsi_mutex);
mutex_lock(&tpg->tv_tpg_mutex);
tpg->tv_tpg_port_count--;
mutex_unlock(&tpg->tv_tpg_mutex);
vhost_scsi_hotunplug(tpg, lun);
mutex_unlock(&vhost_scsi_mutex);
}
static struct se_node_acl *
vhost_scsi_make_nodeacl(struct se_portal_group *se_tpg,
struct config_group *group,
const char *name)
{
struct se_node_acl *se_nacl, *se_nacl_new;
struct vhost_scsi_nacl *nacl;
u64 wwpn = 0;
u32 nexus_depth;
/* vhost_scsi_parse_wwn(name, &wwpn, 1) < 0)
return ERR_PTR(-EINVAL); */
se_nacl_new = vhost_scsi_alloc_fabric_acl(se_tpg);
if (!se_nacl_new)
return ERR_PTR(-ENOMEM);
nexus_depth = 1;
/*
* se_nacl_new may be released by core_tpg_add_initiator_node_acl()
* when converting a NodeACL from demo mode -> explict
*/
se_nacl = core_tpg_add_initiator_node_acl(se_tpg, se_nacl_new,
name, nexus_depth);
if (IS_ERR(se_nacl)) {
vhost_scsi_release_fabric_acl(se_tpg, se_nacl_new);
return se_nacl;
}
/*
* Locate our struct vhost_scsi_nacl and set the FC Nport WWPN
*/
nacl = container_of(se_nacl, struct vhost_scsi_nacl, se_node_acl);
nacl->iport_wwpn = wwpn;
return se_nacl;
}
static void vhost_scsi_drop_nodeacl(struct se_node_acl *se_acl)
{
struct vhost_scsi_nacl *nacl = container_of(se_acl,
struct vhost_scsi_nacl, se_node_acl);
core_tpg_del_initiator_node_acl(se_acl->se_tpg, se_acl, 1);
kfree(nacl);
}
static void vhost_scsi_free_cmd_map_res(struct vhost_scsi_nexus *nexus,
struct se_session *se_sess)
{
struct vhost_scsi_cmd *tv_cmd;
unsigned int i;
if (!se_sess->sess_cmd_map)
return;
for (i = 0; i < VHOST_SCSI_DEFAULT_TAGS; i++) {
tv_cmd = &((struct vhost_scsi_cmd *)se_sess->sess_cmd_map)[i];
kfree(tv_cmd->tvc_sgl);
kfree(tv_cmd->tvc_prot_sgl);
kfree(tv_cmd->tvc_upages);
}
}
static int vhost_scsi_make_nexus(struct vhost_scsi_tpg *tpg,
const char *name)
{
struct se_portal_group *se_tpg;
struct se_session *se_sess;
struct vhost_scsi_nexus *tv_nexus;
struct vhost_scsi_cmd *tv_cmd;
unsigned int i;
mutex_lock(&tpg->tv_tpg_mutex);
if (tpg->tpg_nexus) {
mutex_unlock(&tpg->tv_tpg_mutex);
pr_debug("tpg->tpg_nexus already exists\n");
return -EEXIST;
}
se_tpg = &tpg->se_tpg;
tv_nexus = kzalloc(sizeof(struct vhost_scsi_nexus), GFP_KERNEL);
if (!tv_nexus) {
mutex_unlock(&tpg->tv_tpg_mutex);
pr_err("Unable to allocate struct vhost_scsi_nexus\n");
return -ENOMEM;
}
/*
* Initialize the struct se_session pointer and setup tagpool
* for struct vhost_scsi_cmd descriptors
*/
tv_nexus->tvn_se_sess = transport_init_session_tags(
VHOST_SCSI_DEFAULT_TAGS,
sizeof(struct vhost_scsi_cmd),
TARGET_PROT_DIN_PASS | TARGET_PROT_DOUT_PASS);
if (IS_ERR(tv_nexus->tvn_se_sess)) {
mutex_unlock(&tpg->tv_tpg_mutex);
kfree(tv_nexus);
return -ENOMEM;
}
se_sess = tv_nexus->tvn_se_sess;
for (i = 0; i < VHOST_SCSI_DEFAULT_TAGS; i++) {
tv_cmd = &((struct vhost_scsi_cmd *)se_sess->sess_cmd_map)[i];
tv_cmd->tvc_sgl = kzalloc(sizeof(struct scatterlist) *
VHOST_SCSI_PREALLOC_SGLS, GFP_KERNEL);
if (!tv_cmd->tvc_sgl) {
mutex_unlock(&tpg->tv_tpg_mutex);
pr_err("Unable to allocate tv_cmd->tvc_sgl\n");
goto out;
}
tv_cmd->tvc_upages = kzalloc(sizeof(struct page *) *
VHOST_SCSI_PREALLOC_UPAGES, GFP_KERNEL);
if (!tv_cmd->tvc_upages) {
mutex_unlock(&tpg->tv_tpg_mutex);
pr_err("Unable to allocate tv_cmd->tvc_upages\n");
goto out;
}
tv_cmd->tvc_prot_sgl = kzalloc(sizeof(struct scatterlist) *
VHOST_SCSI_PREALLOC_PROT_SGLS, GFP_KERNEL);
if (!tv_cmd->tvc_prot_sgl) {
mutex_unlock(&tpg->tv_tpg_mutex);
pr_err("Unable to allocate tv_cmd->tvc_prot_sgl\n");
goto out;
}
}
/*
* Since we are running in 'demo mode' this call with generate a
* struct se_node_acl for the vhost_scsi struct se_portal_group with
* the SCSI Initiator port name of the passed configfs group 'name'.
*/
tv_nexus->tvn_se_sess->se_node_acl = core_tpg_check_initiator_node_acl(
se_tpg, (unsigned char *)name);
if (!tv_nexus->tvn_se_sess->se_node_acl) {
mutex_unlock(&tpg->tv_tpg_mutex);
pr_debug("core_tpg_check_initiator_node_acl() failed"
" for %s\n", name);
goto out;
}
/*
* Now register the TCM vhost virtual I_T Nexus as active with the
* call to __transport_register_session()
*/
__transport_register_session(se_tpg, tv_nexus->tvn_se_sess->se_node_acl,
tv_nexus->tvn_se_sess, tv_nexus);
tpg->tpg_nexus = tv_nexus;
mutex_unlock(&tpg->tv_tpg_mutex);
return 0;
out:
vhost_scsi_free_cmd_map_res(tv_nexus, se_sess);
transport_free_session(se_sess);
kfree(tv_nexus);
return -ENOMEM;
}
static int vhost_scsi_drop_nexus(struct vhost_scsi_tpg *tpg)
{
struct se_session *se_sess;
struct vhost_scsi_nexus *tv_nexus;
mutex_lock(&tpg->tv_tpg_mutex);
tv_nexus = tpg->tpg_nexus;
if (!tv_nexus) {
mutex_unlock(&tpg->tv_tpg_mutex);
return -ENODEV;
}
se_sess = tv_nexus->tvn_se_sess;
if (!se_sess) {
mutex_unlock(&tpg->tv_tpg_mutex);
return -ENODEV;
}
if (tpg->tv_tpg_port_count != 0) {
mutex_unlock(&tpg->tv_tpg_mutex);
pr_err("Unable to remove TCM_vhost I_T Nexus with"
" active TPG port count: %d\n",
tpg->tv_tpg_port_count);
return -EBUSY;
}
if (tpg->tv_tpg_vhost_count != 0) {
mutex_unlock(&tpg->tv_tpg_mutex);
pr_err("Unable to remove TCM_vhost I_T Nexus with"
" active TPG vhost count: %d\n",
tpg->tv_tpg_vhost_count);
return -EBUSY;
}
pr_debug("TCM_vhost_ConfigFS: Removing I_T Nexus to emulated"
" %s Initiator Port: %s\n", vhost_scsi_dump_proto_id(tpg->tport),
tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
vhost_scsi_free_cmd_map_res(tv_nexus, se_sess);
/*
* Release the SCSI I_T Nexus to the emulated vhost Target Port
*/
transport_deregister_session(tv_nexus->tvn_se_sess);
tpg->tpg_nexus = NULL;
mutex_unlock(&tpg->tv_tpg_mutex);
kfree(tv_nexus);
return 0;
}
static ssize_t vhost_scsi_tpg_show_nexus(struct se_portal_group *se_tpg,
char *page)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
struct vhost_scsi_nexus *tv_nexus;
ssize_t ret;
mutex_lock(&tpg->tv_tpg_mutex);
tv_nexus = tpg->tpg_nexus;
if (!tv_nexus) {
mutex_unlock(&tpg->tv_tpg_mutex);
return -ENODEV;
}
ret = snprintf(page, PAGE_SIZE, "%s\n",
tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
mutex_unlock(&tpg->tv_tpg_mutex);
return ret;
}
static ssize_t vhost_scsi_tpg_store_nexus(struct se_portal_group *se_tpg,
const char *page,
size_t count)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
struct vhost_scsi_tport *tport_wwn = tpg->tport;
unsigned char i_port[VHOST_SCSI_NAMELEN], *ptr, *port_ptr;
int ret;
/*
* Shutdown the active I_T nexus if 'NULL' is passed..
*/
if (!strncmp(page, "NULL", 4)) {
ret = vhost_scsi_drop_nexus(tpg);
return (!ret) ? count : ret;
}
/*
* Otherwise make sure the passed virtual Initiator port WWN matches
* the fabric protocol_id set in vhost_scsi_make_tport(), and call
* vhost_scsi_make_nexus().
*/
if (strlen(page) >= VHOST_SCSI_NAMELEN) {
pr_err("Emulated NAA Sas Address: %s, exceeds"
" max: %d\n", page, VHOST_SCSI_NAMELEN);
return -EINVAL;
}
snprintf(&i_port[0], VHOST_SCSI_NAMELEN, "%s", page);
ptr = strstr(i_port, "naa.");
if (ptr) {
if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_SAS) {
pr_err("Passed SAS Initiator Port %s does not"
" match target port protoid: %s\n", i_port,
vhost_scsi_dump_proto_id(tport_wwn));
return -EINVAL;
}
port_ptr = &i_port[0];
goto check_newline;
}
ptr = strstr(i_port, "fc.");
if (ptr) {
if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_FCP) {
pr_err("Passed FCP Initiator Port %s does not"
" match target port protoid: %s\n", i_port,
vhost_scsi_dump_proto_id(tport_wwn));
return -EINVAL;
}
port_ptr = &i_port[3]; /* Skip over "fc." */
goto check_newline;
}
ptr = strstr(i_port, "iqn.");
if (ptr) {
if (tport_wwn->tport_proto_id != SCSI_PROTOCOL_ISCSI) {
pr_err("Passed iSCSI Initiator Port %s does not"
" match target port protoid: %s\n", i_port,
vhost_scsi_dump_proto_id(tport_wwn));
return -EINVAL;
}
port_ptr = &i_port[0];
goto check_newline;
}
pr_err("Unable to locate prefix for emulated Initiator Port:"
" %s\n", i_port);
return -EINVAL;
/*
* Clear any trailing newline for the NAA WWN
*/
check_newline:
if (i_port[strlen(i_port)-1] == '\n')
i_port[strlen(i_port)-1] = '\0';
ret = vhost_scsi_make_nexus(tpg, port_ptr);
if (ret < 0)
return ret;
return count;
}
TF_TPG_BASE_ATTR(vhost_scsi, nexus, S_IRUGO | S_IWUSR);
static struct configfs_attribute *vhost_scsi_tpg_attrs[] = {
&vhost_scsi_tpg_nexus.attr,
NULL,
};
static struct se_portal_group *
vhost_scsi_make_tpg(struct se_wwn *wwn,
struct config_group *group,
const char *name)
{
struct vhost_scsi_tport *tport = container_of(wwn,
struct vhost_scsi_tport, tport_wwn);
struct vhost_scsi_tpg *tpg;
unsigned long tpgt;
int ret;
if (strstr(name, "tpgt_") != name)
return ERR_PTR(-EINVAL);
if (kstrtoul(name + 5, 10, &tpgt) || tpgt > UINT_MAX)
return ERR_PTR(-EINVAL);
tpg = kzalloc(sizeof(struct vhost_scsi_tpg), GFP_KERNEL);
if (!tpg) {
pr_err("Unable to allocate struct vhost_scsi_tpg");
return ERR_PTR(-ENOMEM);
}
mutex_init(&tpg->tv_tpg_mutex);
INIT_LIST_HEAD(&tpg->tv_tpg_list);
tpg->tport = tport;
tpg->tport_tpgt = tpgt;
ret = core_tpg_register(&vhost_scsi_fabric_configfs->tf_ops, wwn,
&tpg->se_tpg, tpg, TRANSPORT_TPG_TYPE_NORMAL);
if (ret < 0) {
kfree(tpg);
return NULL;
}
mutex_lock(&vhost_scsi_mutex);
list_add_tail(&tpg->tv_tpg_list, &vhost_scsi_list);
mutex_unlock(&vhost_scsi_mutex);
return &tpg->se_tpg;
}
static void vhost_scsi_drop_tpg(struct se_portal_group *se_tpg)
{
struct vhost_scsi_tpg *tpg = container_of(se_tpg,
struct vhost_scsi_tpg, se_tpg);
mutex_lock(&vhost_scsi_mutex);
list_del(&tpg->tv_tpg_list);
mutex_unlock(&vhost_scsi_mutex);
/*
* Release the virtual I_T Nexus for this vhost TPG
*/
vhost_scsi_drop_nexus(tpg);
/*
* Deregister the se_tpg from TCM..
*/
core_tpg_deregister(se_tpg);
kfree(tpg);
}
static struct se_wwn *
vhost_scsi_make_tport(struct target_fabric_configfs *tf,
struct config_group *group,
const char *name)
{
struct vhost_scsi_tport *tport;
char *ptr;
u64 wwpn = 0;
int off = 0;
/* if (vhost_scsi_parse_wwn(name, &wwpn, 1) < 0)
return ERR_PTR(-EINVAL); */
tport = kzalloc(sizeof(struct vhost_scsi_tport), GFP_KERNEL);
if (!tport) {
pr_err("Unable to allocate struct vhost_scsi_tport");
return ERR_PTR(-ENOMEM);
}
tport->tport_wwpn = wwpn;
/*
* Determine the emulated Protocol Identifier and Target Port Name
* based on the incoming configfs directory name.
*/
ptr = strstr(name, "naa.");
if (ptr) {
tport->tport_proto_id = SCSI_PROTOCOL_SAS;
goto check_len;
}
ptr = strstr(name, "fc.");
if (ptr) {
tport->tport_proto_id = SCSI_PROTOCOL_FCP;
off = 3; /* Skip over "fc." */
goto check_len;
}
ptr = strstr(name, "iqn.");
if (ptr) {
tport->tport_proto_id = SCSI_PROTOCOL_ISCSI;
goto check_len;
}
pr_err("Unable to locate prefix for emulated Target Port:"
" %s\n", name);
kfree(tport);
return ERR_PTR(-EINVAL);
check_len:
if (strlen(name) >= VHOST_SCSI_NAMELEN) {
pr_err("Emulated %s Address: %s, exceeds"
" max: %d\n", name, vhost_scsi_dump_proto_id(tport),
VHOST_SCSI_NAMELEN);
kfree(tport);
return ERR_PTR(-EINVAL);
}
snprintf(&tport->tport_name[0], VHOST_SCSI_NAMELEN, "%s", &name[off]);
pr_debug("TCM_VHost_ConfigFS: Allocated emulated Target"
" %s Address: %s\n", vhost_scsi_dump_proto_id(tport), name);
return &tport->tport_wwn;
}
static void vhost_scsi_drop_tport(struct se_wwn *wwn)
{
struct vhost_scsi_tport *tport = container_of(wwn,
struct vhost_scsi_tport, tport_wwn);
pr_debug("TCM_VHost_ConfigFS: Deallocating emulated Target"
" %s Address: %s\n", vhost_scsi_dump_proto_id(tport),
tport->tport_name);
kfree(tport);
}
static ssize_t
vhost_scsi_wwn_show_attr_version(struct target_fabric_configfs *tf,
char *page)
{
return sprintf(page, "TCM_VHOST fabric module %s on %s/%s"
"on "UTS_RELEASE"\n", VHOST_SCSI_VERSION, utsname()->sysname,
utsname()->machine);
}
TF_WWN_ATTR_RO(vhost_scsi, version);
static struct configfs_attribute *vhost_scsi_wwn_attrs[] = {
&vhost_scsi_wwn_version.attr,
NULL,
};
static struct target_core_fabric_ops vhost_scsi_ops = {
.get_fabric_name = vhost_scsi_get_fabric_name,
.get_fabric_proto_ident = vhost_scsi_get_fabric_proto_ident,
.tpg_get_wwn = vhost_scsi_get_fabric_wwn,
.tpg_get_tag = vhost_scsi_get_tpgt,
.tpg_get_default_depth = vhost_scsi_get_default_depth,
.tpg_get_pr_transport_id = vhost_scsi_get_pr_transport_id,
.tpg_get_pr_transport_id_len = vhost_scsi_get_pr_transport_id_len,
.tpg_parse_pr_out_transport_id = vhost_scsi_parse_pr_out_transport_id,
.tpg_check_demo_mode = vhost_scsi_check_true,
.tpg_check_demo_mode_cache = vhost_scsi_check_true,
.tpg_check_demo_mode_write_protect = vhost_scsi_check_false,
.tpg_check_prod_mode_write_protect = vhost_scsi_check_false,
.tpg_alloc_fabric_acl = vhost_scsi_alloc_fabric_acl,
.tpg_release_fabric_acl = vhost_scsi_release_fabric_acl,
.tpg_get_inst_index = vhost_scsi_tpg_get_inst_index,
.release_cmd = vhost_scsi_release_cmd,
.check_stop_free = vhost_scsi_check_stop_free,
.shutdown_session = vhost_scsi_shutdown_session,
.close_session = vhost_scsi_close_session,
.sess_get_index = vhost_scsi_sess_get_index,
.sess_get_initiator_sid = NULL,
.write_pending = vhost_scsi_write_pending,
.write_pending_status = vhost_scsi_write_pending_status,
.set_default_node_attributes = vhost_scsi_set_default_node_attrs,
.get_task_tag = vhost_scsi_get_task_tag,
.get_cmd_state = vhost_scsi_get_cmd_state,
.queue_data_in = vhost_scsi_queue_data_in,
.queue_status = vhost_scsi_queue_status,
.queue_tm_rsp = vhost_scsi_queue_tm_rsp,
.aborted_task = vhost_scsi_aborted_task,
/*
* Setup callers for generic logic in target_core_fabric_configfs.c
*/
.fabric_make_wwn = vhost_scsi_make_tport,
.fabric_drop_wwn = vhost_scsi_drop_tport,
.fabric_make_tpg = vhost_scsi_make_tpg,
.fabric_drop_tpg = vhost_scsi_drop_tpg,
.fabric_post_link = vhost_scsi_port_link,
.fabric_pre_unlink = vhost_scsi_port_unlink,
.fabric_make_np = NULL,
.fabric_drop_np = NULL,
.fabric_make_nodeacl = vhost_scsi_make_nodeacl,
.fabric_drop_nodeacl = vhost_scsi_drop_nodeacl,
};
static int vhost_scsi_register_configfs(void)
{
struct target_fabric_configfs *fabric;
int ret;
pr_debug("vhost-scsi fabric module %s on %s/%s"
" on "UTS_RELEASE"\n", VHOST_SCSI_VERSION, utsname()->sysname,
utsname()->machine);
/*
* Register the top level struct config_item_type with TCM core
*/
fabric = target_fabric_configfs_init(THIS_MODULE, "vhost");
if (IS_ERR(fabric)) {
pr_err("target_fabric_configfs_init() failed\n");
return PTR_ERR(fabric);
}
/*
* Setup fabric->tf_ops from our local vhost_scsi_ops
*/
fabric->tf_ops = vhost_scsi_ops;
/*
* Setup default attribute lists for various fabric->tf_cit_tmpl
*/
fabric->tf_cit_tmpl.tfc_wwn_cit.ct_attrs = vhost_scsi_wwn_attrs;
fabric->tf_cit_tmpl.tfc_tpg_base_cit.ct_attrs = vhost_scsi_tpg_attrs;
fabric->tf_cit_tmpl.tfc_tpg_attrib_cit.ct_attrs = NULL;
fabric->tf_cit_tmpl.tfc_tpg_param_cit.ct_attrs = NULL;
fabric->tf_cit_tmpl.tfc_tpg_np_base_cit.ct_attrs = NULL;
fabric->tf_cit_tmpl.tfc_tpg_nacl_base_cit.ct_attrs = NULL;
fabric->tf_cit_tmpl.tfc_tpg_nacl_attrib_cit.ct_attrs = NULL;
fabric->tf_cit_tmpl.tfc_tpg_nacl_auth_cit.ct_attrs = NULL;
fabric->tf_cit_tmpl.tfc_tpg_nacl_param_cit.ct_attrs = NULL;
/*
* Register the fabric for use within TCM
*/
ret = target_fabric_configfs_register(fabric);
if (ret < 0) {
pr_err("target_fabric_configfs_register() failed"
" for TCM_VHOST\n");
return ret;
}
/*
* Setup our local pointer to *fabric
*/
vhost_scsi_fabric_configfs = fabric;
pr_debug("TCM_VHOST[0] - Set fabric -> vhost_scsi_fabric_configfs\n");
return 0;
};
static void vhost_scsi_deregister_configfs(void)
{
if (!vhost_scsi_fabric_configfs)
return;
target_fabric_configfs_deregister(vhost_scsi_fabric_configfs);
vhost_scsi_fabric_configfs = NULL;
pr_debug("TCM_VHOST[0] - Cleared vhost_scsi_fabric_configfs\n");
};
static int __init vhost_scsi_init(void)
{
int ret = -ENOMEM;
/*
* Use our own dedicated workqueue for submitting I/O into
* target core to avoid contention within system_wq.
*/
vhost_scsi_workqueue = alloc_workqueue("vhost_scsi", 0, 0);
if (!vhost_scsi_workqueue)
goto out;
ret = vhost_scsi_register();
if (ret < 0)
goto out_destroy_workqueue;
ret = vhost_scsi_register_configfs();
if (ret < 0)
goto out_vhost_scsi_deregister;
return 0;
out_vhost_scsi_deregister:
vhost_scsi_deregister();
out_destroy_workqueue:
destroy_workqueue(vhost_scsi_workqueue);
out:
return ret;
};
static void vhost_scsi_exit(void)
{
vhost_scsi_deregister_configfs();
vhost_scsi_deregister();
destroy_workqueue(vhost_scsi_workqueue);
};
MODULE_DESCRIPTION("VHOST_SCSI series fabric driver");
MODULE_ALIAS("tcm_vhost");
MODULE_LICENSE("GPL");
module_init(vhost_scsi_init);
module_exit(vhost_scsi_exit);
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1618_0 |
crossvul-cpp_data_good_5477_1 | /* $Id$ */
/*
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
/*
* TIFF Library.
*
* Predictor Tag Support (used by multiple codecs).
*/
#include "tiffiop.h"
#include "tif_predict.h"
#define PredictorState(tif) ((TIFFPredictorState*) (tif)->tif_data)
static int horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc);
static int horAcc16(TIFF* tif, uint8* cp0, tmsize_t cc);
static int horAcc32(TIFF* tif, uint8* cp0, tmsize_t cc);
static int swabHorAcc16(TIFF* tif, uint8* cp0, tmsize_t cc);
static int swabHorAcc32(TIFF* tif, uint8* cp0, tmsize_t cc);
static int horDiff8(TIFF* tif, uint8* cp0, tmsize_t cc);
static int horDiff16(TIFF* tif, uint8* cp0, tmsize_t cc);
static int horDiff32(TIFF* tif, uint8* cp0, tmsize_t cc);
static int swabHorDiff16(TIFF* tif, uint8* cp0, tmsize_t cc);
static int swabHorDiff32(TIFF* tif, uint8* cp0, tmsize_t cc);
static int fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc);
static int fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc);
static int PredictorDecodeRow(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s);
static int PredictorDecodeTile(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s);
static int PredictorEncodeRow(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s);
static int PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s);
static int
PredictorSetup(TIFF* tif)
{
static const char module[] = "PredictorSetup";
TIFFPredictorState* sp = PredictorState(tif);
TIFFDirectory* td = &tif->tif_dir;
switch (sp->predictor) /* no differencing */
{
case PREDICTOR_NONE:
return 1;
case PREDICTOR_HORIZONTAL:
if (td->td_bitspersample != 8
&& td->td_bitspersample != 16
&& td->td_bitspersample != 32) {
TIFFErrorExt(tif->tif_clientdata, module,
"Horizontal differencing \"Predictor\" not supported with %d-bit samples",
td->td_bitspersample);
return 0;
}
break;
case PREDICTOR_FLOATINGPOINT:
if (td->td_sampleformat != SAMPLEFORMAT_IEEEFP) {
TIFFErrorExt(tif->tif_clientdata, module,
"Floating point \"Predictor\" not supported with %d data format",
td->td_sampleformat);
return 0;
}
if (td->td_bitspersample != 16
&& td->td_bitspersample != 24
&& td->td_bitspersample != 32
&& td->td_bitspersample != 64) { /* Should 64 be allowed? */
TIFFErrorExt(tif->tif_clientdata, module,
"Floating point \"Predictor\" not supported with %d-bit samples",
td->td_bitspersample);
return 0;
}
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"\"Predictor\" value %d not supported",
sp->predictor);
return 0;
}
sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ?
td->td_samplesperpixel : 1);
/*
* Calculate the scanline/tile-width size in bytes.
*/
if (isTiled(tif))
sp->rowsize = TIFFTileRowSize(tif);
else
sp->rowsize = TIFFScanlineSize(tif);
if (sp->rowsize == 0)
return 0;
return 1;
}
static int
PredictorSetupDecode(TIFF* tif)
{
TIFFPredictorState* sp = PredictorState(tif);
TIFFDirectory* td = &tif->tif_dir;
if (!(*sp->setupdecode)(tif) || !PredictorSetup(tif))
return 0;
if (sp->predictor == 2) {
switch (td->td_bitspersample) {
case 8: sp->decodepfunc = horAcc8; break;
case 16: sp->decodepfunc = horAcc16; break;
case 32: sp->decodepfunc = horAcc32; break;
}
/*
* Override default decoding method with one that does the
* predictor stuff.
*/
if( tif->tif_decoderow != PredictorDecodeRow )
{
sp->decoderow = tif->tif_decoderow;
tif->tif_decoderow = PredictorDecodeRow;
sp->decodestrip = tif->tif_decodestrip;
tif->tif_decodestrip = PredictorDecodeTile;
sp->decodetile = tif->tif_decodetile;
tif->tif_decodetile = PredictorDecodeTile;
}
/*
* If the data is horizontally differenced 16-bit data that
* requires byte-swapping, then it must be byte swapped before
* the accumulation step. We do this with a special-purpose
* routine and override the normal post decoding logic that
* the library setup when the directory was read.
*/
if (tif->tif_flags & TIFF_SWAB) {
if (sp->decodepfunc == horAcc16) {
sp->decodepfunc = swabHorAcc16;
tif->tif_postdecode = _TIFFNoPostDecode;
} else if (sp->decodepfunc == horAcc32) {
sp->decodepfunc = swabHorAcc32;
tif->tif_postdecode = _TIFFNoPostDecode;
}
}
}
else if (sp->predictor == 3) {
sp->decodepfunc = fpAcc;
/*
* Override default decoding method with one that does the
* predictor stuff.
*/
if( tif->tif_decoderow != PredictorDecodeRow )
{
sp->decoderow = tif->tif_decoderow;
tif->tif_decoderow = PredictorDecodeRow;
sp->decodestrip = tif->tif_decodestrip;
tif->tif_decodestrip = PredictorDecodeTile;
sp->decodetile = tif->tif_decodetile;
tif->tif_decodetile = PredictorDecodeTile;
}
/*
* The data should not be swapped outside of the floating
* point predictor, the accumulation routine should return
* byres in the native order.
*/
if (tif->tif_flags & TIFF_SWAB) {
tif->tif_postdecode = _TIFFNoPostDecode;
}
/*
* Allocate buffer to keep the decoded bytes before
* rearranging in the right order
*/
}
return 1;
}
static int
PredictorSetupEncode(TIFF* tif)
{
TIFFPredictorState* sp = PredictorState(tif);
TIFFDirectory* td = &tif->tif_dir;
if (!(*sp->setupencode)(tif) || !PredictorSetup(tif))
return 0;
if (sp->predictor == 2) {
switch (td->td_bitspersample) {
case 8: sp->encodepfunc = horDiff8; break;
case 16: sp->encodepfunc = horDiff16; break;
case 32: sp->encodepfunc = horDiff32; break;
}
/*
* Override default encoding method with one that does the
* predictor stuff.
*/
if( tif->tif_encoderow != PredictorEncodeRow )
{
sp->encoderow = tif->tif_encoderow;
tif->tif_encoderow = PredictorEncodeRow;
sp->encodestrip = tif->tif_encodestrip;
tif->tif_encodestrip = PredictorEncodeTile;
sp->encodetile = tif->tif_encodetile;
tif->tif_encodetile = PredictorEncodeTile;
}
/*
* If the data is horizontally differenced 16-bit data that
* requires byte-swapping, then it must be byte swapped after
* the differentiation step. We do this with a special-purpose
* routine and override the normal post decoding logic that
* the library setup when the directory was read.
*/
if (tif->tif_flags & TIFF_SWAB) {
if (sp->encodepfunc == horDiff16) {
sp->encodepfunc = swabHorDiff16;
tif->tif_postdecode = _TIFFNoPostDecode;
} else if (sp->encodepfunc == horDiff32) {
sp->encodepfunc = swabHorDiff32;
tif->tif_postdecode = _TIFFNoPostDecode;
}
}
}
else if (sp->predictor == 3) {
sp->encodepfunc = fpDiff;
/*
* Override default encoding method with one that does the
* predictor stuff.
*/
if( tif->tif_encoderow != PredictorEncodeRow )
{
sp->encoderow = tif->tif_encoderow;
tif->tif_encoderow = PredictorEncodeRow;
sp->encodestrip = tif->tif_encodestrip;
tif->tif_encodestrip = PredictorEncodeTile;
sp->encodetile = tif->tif_encodetile;
tif->tif_encodetile = PredictorEncodeTile;
}
}
return 1;
}
#define REPEAT4(n, op) \
switch (n) { \
default: { tmsize_t i; for (i = n-4; i > 0; i--) { op; } } \
case 4: op; \
case 3: op; \
case 2: op; \
case 1: op; \
case 0: ; \
}
/* Remarks related to C standard compliance in all below functions : */
/* - to avoid any undefined behaviour, we only operate on unsigned types */
/* since the behaviour of "overflows" is defined (wrap over) */
/* - when storing into the byte stream, we explicitly mask with 0xff so */
/* as to make icc -check=conversions happy (not necessary by the standard) */
static int
horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
unsigned char* cp = (unsigned char*) cp0;
if((cc%stride)!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horAcc8",
"%s", "(cc%stride)!=0");
return 0;
}
if (cc > stride) {
/*
* Pipeline the most common cases.
*/
if (stride == 3) {
unsigned int cr = cp[0];
unsigned int cg = cp[1];
unsigned int cb = cp[2];
cc -= 3;
cp += 3;
while (cc>0) {
cp[0] = (unsigned char) ((cr += cp[0]) & 0xff);
cp[1] = (unsigned char) ((cg += cp[1]) & 0xff);
cp[2] = (unsigned char) ((cb += cp[2]) & 0xff);
cc -= 3;
cp += 3;
}
} else if (stride == 4) {
unsigned int cr = cp[0];
unsigned int cg = cp[1];
unsigned int cb = cp[2];
unsigned int ca = cp[3];
cc -= 4;
cp += 4;
while (cc>0) {
cp[0] = (unsigned char) ((cr += cp[0]) & 0xff);
cp[1] = (unsigned char) ((cg += cp[1]) & 0xff);
cp[2] = (unsigned char) ((cb += cp[2]) & 0xff);
cp[3] = (unsigned char) ((ca += cp[3]) & 0xff);
cc -= 4;
cp += 4;
}
} else {
cc -= stride;
do {
REPEAT4(stride, cp[stride] =
(unsigned char) ((cp[stride] + *cp) & 0xff); cp++)
cc -= stride;
} while (cc>0);
}
}
return 1;
}
static int
swabHorAcc16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint16* wp = (uint16*) cp0;
tmsize_t wc = cc / 2;
TIFFSwabArrayOfShort(wp, wc);
return horAcc16(tif, cp0, cc);
}
static int
horAcc16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint16* wp = (uint16*) cp0;
tmsize_t wc = cc / 2;
if((cc%(2*stride))!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horAcc16",
"%s", "cc%(2*stride))!=0");
return 0;
}
if (wc > stride) {
wc -= stride;
do {
REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] + (unsigned int)wp[0]) & 0xffff); wp++)
wc -= stride;
} while (wc > 0);
}
return 1;
}
static int
swabHorAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
TIFFSwabArrayOfLong(wp, wc);
return horAcc32(tif, cp0, cc);
}
static int
horAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
if((cc%(4*stride))!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horAcc32",
"%s", "cc%(4*stride))!=0");
return 0;
}
if (wc > stride) {
wc -= stride;
do {
REPEAT4(stride, wp[stride] += wp[0]; wp++)
wc -= stride;
} while (wc > 0);
}
return 1;
}
/*
* Floating point predictor accumulation routine.
*/
static int
fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32 bps = tif->tif_dir.td_bitspersample / 8;
tmsize_t wc = cc / bps;
tmsize_t count = cc;
uint8 *cp = (uint8 *) cp0;
uint8 *tmp;
if(cc%(bps*stride)!=0)
{
TIFFErrorExt(tif->tif_clientdata, "fpAcc",
"%s", "cc%(bps*stride))!=0");
return 0;
}
tmp = (uint8 *)_TIFFmalloc(cc);
if (!tmp)
return 0;
while (count > stride) {
REPEAT4(stride, cp[stride] =
(unsigned char) ((cp[stride] + cp[0]) & 0xff); cp++)
count -= stride;
}
_TIFFmemcpy(tmp, cp0, cc);
cp = (uint8 *) cp0;
for (count = 0; count < wc; count++) {
uint32 byte;
for (byte = 0; byte < bps; byte++) {
#if WORDS_BIGENDIAN
cp[bps * count + byte] = tmp[byte * wc + count];
#else
cp[bps * count + byte] =
tmp[(bps - byte - 1) * wc + count];
#endif
}
}
_TIFFfree(tmp);
return 1;
}
/*
* Decode a scanline and apply the predictor routine.
*/
static int
PredictorDecodeRow(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->decoderow != NULL);
assert(sp->decodepfunc != NULL);
if ((*sp->decoderow)(tif, op0, occ0, s)) {
return (*sp->decodepfunc)(tif, op0, occ0);
} else
return 0;
}
/*
* Decode a tile/strip and apply the predictor routine.
* Note that horizontal differencing must be done on a
* row-by-row basis. The width of a "row" has already
* been calculated at pre-decode time according to the
* strip/tile dimensions.
*/
static int
PredictorDecodeTile(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->decodetile != NULL);
if ((*sp->decodetile)(tif, op0, occ0, s)) {
tmsize_t rowsize = sp->rowsize;
assert(rowsize > 0);
if((occ0%rowsize) !=0)
{
TIFFErrorExt(tif->tif_clientdata, "PredictorDecodeTile",
"%s", "occ0%rowsize != 0");
return 0;
}
assert(sp->decodepfunc != NULL);
while (occ0 > 0) {
if( !(*sp->decodepfunc)(tif, op0, rowsize) )
return 0;
occ0 -= rowsize;
op0 += rowsize;
}
return 1;
} else
return 0;
}
static int
horDiff8(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
unsigned char* cp = (unsigned char*) cp0;
if((cc%stride)!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horDiff8",
"%s", "(cc%stride)!=0");
return 0;
}
if (cc > stride) {
cc -= stride;
/*
* Pipeline the most common cases.
*/
if (stride == 3) {
unsigned int r1, g1, b1;
unsigned int r2 = cp[0];
unsigned int g2 = cp[1];
unsigned int b2 = cp[2];
do {
r1 = cp[3]; cp[3] = (unsigned char)((r1-r2)&0xff); r2 = r1;
g1 = cp[4]; cp[4] = (unsigned char)((g1-g2)&0xff); g2 = g1;
b1 = cp[5]; cp[5] = (unsigned char)((b1-b2)&0xff); b2 = b1;
cp += 3;
} while ((cc -= 3) > 0);
} else if (stride == 4) {
unsigned int r1, g1, b1, a1;
unsigned int r2 = cp[0];
unsigned int g2 = cp[1];
unsigned int b2 = cp[2];
unsigned int a2 = cp[3];
do {
r1 = cp[4]; cp[4] = (unsigned char)((r1-r2)&0xff); r2 = r1;
g1 = cp[5]; cp[5] = (unsigned char)((g1-g2)&0xff); g2 = g1;
b1 = cp[6]; cp[6] = (unsigned char)((b1-b2)&0xff); b2 = b1;
a1 = cp[7]; cp[7] = (unsigned char)((a1-a2)&0xff); a2 = a1;
cp += 4;
} while ((cc -= 4) > 0);
} else {
cp += cc - 1;
do {
REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--)
} while ((cc -= stride) > 0);
}
}
return 1;
}
static int
horDiff16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
uint16 *wp = (uint16*) cp0;
tmsize_t wc = cc/2;
if((cc%(2*stride))!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horDiff8",
"%s", "(cc%(2*stride))!=0");
return 0;
}
if (wc > stride) {
wc -= stride;
wp += wc - 1;
do {
REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] - (unsigned int)wp[0]) & 0xffff); wp--)
wc -= stride;
} while (wc > 0);
}
return 1;
}
static int
swabHorDiff16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint16* wp = (uint16*) cp0;
tmsize_t wc = cc / 2;
if( !horDiff16(tif, cp0, cc) )
return 0;
TIFFSwabArrayOfShort(wp, wc);
return 1;
}
static int
horDiff32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
uint32 *wp = (uint32*) cp0;
tmsize_t wc = cc/4;
if((cc%(4*stride))!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horDiff32",
"%s", "(cc%(4*stride))!=0");
return 0;
}
if (wc > stride) {
wc -= stride;
wp += wc - 1;
do {
REPEAT4(stride, wp[stride] -= wp[0]; wp--)
wc -= stride;
} while (wc > 0);
}
return 1;
}
static int
swabHorDiff32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
if( !horDiff32(tif, cp0, cc) )
return 0;
TIFFSwabArrayOfLong(wp, wc);
return 1;
}
/*
* Floating point predictor differencing routine.
*/
static int
fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32 bps = tif->tif_dir.td_bitspersample / 8;
tmsize_t wc = cc / bps;
tmsize_t count;
uint8 *cp = (uint8 *) cp0;
uint8 *tmp;
if((cc%(bps*stride))!=0)
{
TIFFErrorExt(tif->tif_clientdata, "fpDiff",
"%s", "(cc%(bps*stride))!=0");
return 0;
}
tmp = (uint8 *)_TIFFmalloc(cc);
if (!tmp)
return 0;
_TIFFmemcpy(tmp, cp0, cc);
for (count = 0; count < wc; count++) {
uint32 byte;
for (byte = 0; byte < bps; byte++) {
#if WORDS_BIGENDIAN
cp[byte * wc + count] = tmp[bps * count + byte];
#else
cp[(bps - byte - 1) * wc + count] =
tmp[bps * count + byte];
#endif
}
}
_TIFFfree(tmp);
cp = (uint8 *) cp0;
cp += cc - stride - 1;
for (count = cc; count > stride; count -= stride)
REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--)
return 1;
}
static int
PredictorEncodeRow(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->encodepfunc != NULL);
assert(sp->encoderow != NULL);
/* XXX horizontal differencing alters user's data XXX */
if( !(*sp->encodepfunc)(tif, bp, cc) )
return 0;
return (*sp->encoderow)(tif, bp, cc, s);
}
static int
PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s)
{
static const char module[] = "PredictorEncodeTile";
TIFFPredictorState *sp = PredictorState(tif);
uint8 *working_copy;
tmsize_t cc = cc0, rowsize;
unsigned char* bp;
int result_code;
assert(sp != NULL);
assert(sp->encodepfunc != NULL);
assert(sp->encodetile != NULL);
/*
* Do predictor manipulation in a working buffer to avoid altering
* the callers buffer. http://trac.osgeo.org/gdal/ticket/1965
*/
working_copy = (uint8*) _TIFFmalloc(cc0);
if( working_copy == NULL )
{
TIFFErrorExt(tif->tif_clientdata, module,
"Out of memory allocating " TIFF_SSIZE_FORMAT " byte temp buffer.",
cc0 );
return 0;
}
memcpy( working_copy, bp0, cc0 );
bp = working_copy;
rowsize = sp->rowsize;
assert(rowsize > 0);
if((cc0%rowsize)!=0)
{
TIFFErrorExt(tif->tif_clientdata, "PredictorEncodeTile",
"%s", "(cc0%rowsize)!=0");
_TIFFfree( working_copy );
return 0;
}
while (cc > 0) {
(*sp->encodepfunc)(tif, bp, rowsize);
cc -= rowsize;
bp += rowsize;
}
result_code = (*sp->encodetile)(tif, working_copy, cc0, s);
_TIFFfree( working_copy );
return result_code;
}
#define FIELD_PREDICTOR (FIELD_CODEC+0) /* XXX */
static const TIFFField predictFields[] = {
{ TIFFTAG_PREDICTOR, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UINT16, FIELD_PREDICTOR, FALSE, FALSE, "Predictor", NULL },
};
static int
PredictorVSetField(TIFF* tif, uint32 tag, va_list ap)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->vsetparent != NULL);
switch (tag) {
case TIFFTAG_PREDICTOR:
sp->predictor = (uint16) va_arg(ap, uint16_vap);
TIFFSetFieldBit(tif, FIELD_PREDICTOR);
break;
default:
return (*sp->vsetparent)(tif, tag, ap);
}
tif->tif_flags |= TIFF_DIRTYDIRECT;
return 1;
}
static int
PredictorVGetField(TIFF* tif, uint32 tag, va_list ap)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->vgetparent != NULL);
switch (tag) {
case TIFFTAG_PREDICTOR:
*va_arg(ap, uint16*) = (uint16)sp->predictor;
break;
default:
return (*sp->vgetparent)(tif, tag, ap);
}
return 1;
}
static void
PredictorPrintDir(TIFF* tif, FILE* fd, long flags)
{
TIFFPredictorState* sp = PredictorState(tif);
(void) flags;
if (TIFFFieldSet(tif,FIELD_PREDICTOR)) {
fprintf(fd, " Predictor: ");
switch (sp->predictor) {
case 1: fprintf(fd, "none "); break;
case 2: fprintf(fd, "horizontal differencing "); break;
case 3: fprintf(fd, "floating point predictor "); break;
}
fprintf(fd, "%u (0x%x)\n", sp->predictor, sp->predictor);
}
if (sp->printdir)
(*sp->printdir)(tif, fd, flags);
}
int
TIFFPredictorInit(TIFF* tif)
{
TIFFPredictorState* sp = PredictorState(tif);
assert(sp != 0);
/*
* Merge codec-specific tag information.
*/
if (!_TIFFMergeFields(tif, predictFields,
TIFFArrayCount(predictFields))) {
TIFFErrorExt(tif->tif_clientdata, "TIFFPredictorInit",
"Merging Predictor codec-specific tags failed");
return 0;
}
/*
* Override parent get/set field methods.
*/
sp->vgetparent = tif->tif_tagmethods.vgetfield;
tif->tif_tagmethods.vgetfield =
PredictorVGetField;/* hook for predictor tag */
sp->vsetparent = tif->tif_tagmethods.vsetfield;
tif->tif_tagmethods.vsetfield =
PredictorVSetField;/* hook for predictor tag */
sp->printdir = tif->tif_tagmethods.printdir;
tif->tif_tagmethods.printdir =
PredictorPrintDir; /* hook for predictor tag */
sp->setupdecode = tif->tif_setupdecode;
tif->tif_setupdecode = PredictorSetupDecode;
sp->setupencode = tif->tif_setupencode;
tif->tif_setupencode = PredictorSetupEncode;
sp->predictor = 1; /* default value */
sp->encodepfunc = NULL; /* no predictor routine */
sp->decodepfunc = NULL; /* no predictor routine */
return 1;
}
int
TIFFPredictorCleanup(TIFF* tif)
{
TIFFPredictorState* sp = PredictorState(tif);
assert(sp != 0);
tif->tif_tagmethods.vgetfield = sp->vgetparent;
tif->tif_tagmethods.vsetfield = sp->vsetparent;
tif->tif_tagmethods.printdir = sp->printdir;
tif->tif_setupdecode = sp->setupdecode;
tif->tif_setupencode = sp->setupencode;
return 1;
}
/* vim: set ts=8 sts=8 sw=8 noet: */
/*
* Local Variables:
* mode: c
* c-basic-offset: 8
* fill-column: 78
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5477_1 |
crossvul-cpp_data_good_3420_0 | /*
* ScreenPressor decoder
*
* Copyright (c) 2017 Paul B Mahol
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "avcodec.h"
#include "bytestream.h"
#include "internal.h"
#define TOP 0x01000000
#define BOT 0x010000
typedef struct RangeCoder {
unsigned code;
unsigned range;
unsigned code1;
} RangeCoder;
typedef struct PixelModel {
unsigned freq[256];
unsigned lookup[16];
unsigned total_freq;
} PixelModel;
typedef struct SCPRContext {
AVFrame *last_frame;
AVFrame *current_frame;
GetByteContext gb;
RangeCoder rc;
PixelModel pixel_model[3][4096];
unsigned op_model[6][7];
unsigned run_model[6][257];
unsigned range_model[257];
unsigned count_model[257];
unsigned fill_model[6];
unsigned sxy_model[4][17];
unsigned mv_model[2][513];
unsigned nbx, nby;
unsigned nbcount;
unsigned *blocks;
unsigned cbits;
int cxshift;
int (*get_freq)(RangeCoder *rc, unsigned total_freq, unsigned *freq);
int (*decode)(GetByteContext *gb, RangeCoder *rc, unsigned cumFreq, unsigned freq, unsigned total_freq);
} SCPRContext;
static void init_rangecoder(RangeCoder *rc, GetByteContext *gb)
{
rc->code1 = 0;
rc->range = 0xFFFFFFFFU;
rc->code = bytestream2_get_be32(gb);
}
static void reinit_tables(SCPRContext *s)
{
int comp, i, j;
for (comp = 0; comp < 3; comp++) {
for (j = 0; j < 4096; j++) {
if (s->pixel_model[comp][j].total_freq != 256) {
for (i = 0; i < 256; i++)
s->pixel_model[comp][j].freq[i] = 1;
for (i = 0; i < 16; i++)
s->pixel_model[comp][j].lookup[i] = 16;
s->pixel_model[comp][j].total_freq = 256;
}
}
}
for (j = 0; j < 6; j++) {
unsigned *p = s->run_model[j];
for (i = 0; i < 256; i++)
p[i] = 1;
p[256] = 256;
}
for (j = 0; j < 6; j++) {
unsigned *op = s->op_model[j];
for (i = 0; i < 6; i++)
op[i] = 1;
op[6] = 6;
}
for (i = 0; i < 256; i++) {
s->range_model[i] = 1;
s->count_model[i] = 1;
}
s->range_model[256] = 256;
s->count_model[256] = 256;
for (i = 0; i < 5; i++) {
s->fill_model[i] = 1;
}
s->fill_model[5] = 5;
for (j = 0; j < 4; j++) {
for (i = 0; i < 16; i++) {
s->sxy_model[j][i] = 1;
}
s->sxy_model[j][16] = 16;
}
for (i = 0; i < 512; i++) {
s->mv_model[0][i] = 1;
s->mv_model[1][i] = 1;
}
s->mv_model[0][512] = 512;
s->mv_model[1][512] = 512;
}
static int decode(GetByteContext *gb, RangeCoder *rc, unsigned cumFreq, unsigned freq, unsigned total_freq)
{
rc->code -= cumFreq * rc->range;
rc->range *= freq;
while (rc->range < TOP && bytestream2_get_bytes_left(gb) > 0) {
unsigned byte = bytestream2_get_byte(gb);
rc->code = (rc->code << 8) | byte;
rc->range <<= 8;
}
return 0;
}
static int get_freq(RangeCoder *rc, unsigned total_freq, unsigned *freq)
{
if (total_freq == 0)
return AVERROR_INVALIDDATA;
rc->range = rc->range / total_freq;
if (rc->range == 0)
return AVERROR_INVALIDDATA;
*freq = rc->code / rc->range;
return 0;
}
static int decode0(GetByteContext *gb, RangeCoder *rc, unsigned cumFreq, unsigned freq, unsigned total_freq)
{
unsigned t;
if (total_freq == 0)
return AVERROR_INVALIDDATA;
t = rc->range * (uint64_t)cumFreq / total_freq;
rc->code1 += t + 1;
rc->range = rc->range * (uint64_t)(freq + cumFreq) / total_freq - (t + 1);
while (rc->range < TOP && bytestream2_get_bytes_left(gb) > 0) {
unsigned byte = bytestream2_get_byte(gb);
rc->code = (rc->code << 8) | byte;
rc->code1 <<= 8;
rc->range <<= 8;
}
return 0;
}
static int get_freq0(RangeCoder *rc, unsigned total_freq, unsigned *freq)
{
if (rc->range == 0)
return AVERROR_INVALIDDATA;
*freq = total_freq * (uint64_t)(rc->code - rc->code1) / rc->range;
return 0;
}
static int decode_value(SCPRContext *s, unsigned *cnt, unsigned maxc, unsigned step, unsigned *rval)
{
GetByteContext *gb = &s->gb;
RangeCoder *rc = &s->rc;
unsigned totfr = cnt[maxc];
unsigned value;
unsigned c = 0, cumfr = 0, cnt_c = 0;
int i, ret;
if ((ret = s->get_freq(rc, totfr, &value)) < 0)
return ret;
while (c < maxc) {
cnt_c = cnt[c];
if (value >= cumfr + cnt_c)
cumfr += cnt_c;
else
break;
c++;
}
if ((ret = s->decode(gb, rc, cumfr, cnt_c, totfr)) < 0)
return ret;
cnt[c] = cnt_c + step;
totfr += step;
if (totfr > BOT) {
totfr = 0;
for (i = 0; i < maxc; i++) {
unsigned nc = (cnt[i] >> 1) + 1;
cnt[i] = nc;
totfr += nc;
}
}
cnt[maxc] = totfr;
*rval = c;
return 0;
}
static int decode_unit(SCPRContext *s, PixelModel *pixel, unsigned step, unsigned *rval)
{
GetByteContext *gb = &s->gb;
RangeCoder *rc = &s->rc;
unsigned totfr = pixel->total_freq;
unsigned value, x = 0, cumfr = 0, cnt_x = 0;
int i, j, ret, c, cnt_c;
if ((ret = s->get_freq(rc, totfr, &value)) < 0)
return ret;
while (x < 16) {
cnt_x = pixel->lookup[x];
if (value >= cumfr + cnt_x)
cumfr += cnt_x;
else
break;
x++;
}
c = x * 16;
cnt_c = 0;
while (c < 256) {
cnt_c = pixel->freq[c];
if (value >= cumfr + cnt_c)
cumfr += cnt_c;
else
break;
c++;
}
if ((ret = s->decode(gb, rc, cumfr, cnt_c, totfr)) < 0)
return ret;
pixel->freq[c] = cnt_c + step;
pixel->lookup[x] = cnt_x + step;
totfr += step;
if (totfr > BOT) {
totfr = 0;
for (i = 0; i < 256; i++) {
unsigned nc = (pixel->freq[i] >> 1) + 1;
pixel->freq[i] = nc;
totfr += nc;
}
for (i = 0; i < 16; i++) {
unsigned sum = 0;
unsigned i16_17 = i << 4;
for (j = 0; j < 16; j++)
sum += pixel->freq[i16_17 + j];
pixel->lookup[i] = sum;
}
}
pixel->total_freq = totfr;
*rval = c & s->cbits;
return 0;
}
static int decompress_i(AVCodecContext *avctx, uint32_t *dst, int linesize)
{
SCPRContext *s = avctx->priv_data;
GetByteContext *gb = &s->gb;
int cx = 0, cx1 = 0, k = 0, clr = 0;
int run, r, g, b, off, y = 0, x = 0, z, ret;
unsigned backstep = linesize - avctx->width;
const int cxshift = s->cxshift;
unsigned lx, ly, ptype;
reinit_tables(s);
bytestream2_skip(gb, 2);
init_rangecoder(&s->rc, gb);
while (k < avctx->width + 1) {
ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r);
if (ret < 0)
return ret;
cx1 = (cx << 6) & 0xFC0;
cx = r >> cxshift;
ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g);
if (ret < 0)
return ret;
cx1 = (cx << 6) & 0xFC0;
cx = g >> cxshift;
ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b);
if (ret < 0)
return ret;
cx1 = (cx << 6) & 0xFC0;
cx = b >> cxshift;
ret = decode_value(s, s->run_model[0], 256, 400, &run);
if (ret < 0)
return ret;
clr = (b << 16) + (g << 8) + r;
k += run;
while (run-- > 0) {
if (y >= avctx->height)
return AVERROR_INVALIDDATA;
dst[y * linesize + x] = clr;
lx = x;
ly = y;
x++;
if (x >= avctx->width) {
x = 0;
y++;
}
}
}
off = -linesize - 1;
ptype = 0;
while (x < avctx->width && y < avctx->height) {
ret = decode_value(s, s->op_model[ptype], 6, 1000, &ptype);
if (ret < 0)
return ret;
if (ptype == 0) {
ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r);
if (ret < 0)
return ret;
cx1 = (cx << 6) & 0xFC0;
cx = r >> cxshift;
ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g);
if (ret < 0)
return ret;
cx1 = (cx << 6) & 0xFC0;
cx = g >> cxshift;
ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b);
if (ret < 0)
return ret;
clr = (b << 16) + (g << 8) + r;
}
if (ptype > 5)
return AVERROR_INVALIDDATA;
ret = decode_value(s, s->run_model[ptype], 256, 400, &run);
if (ret < 0)
return ret;
switch (ptype) {
case 0:
while (run-- > 0) {
if (y >= avctx->height)
return AVERROR_INVALIDDATA;
dst[y * linesize + x] = clr;
lx = x;
ly = y;
x++;
if (x >= avctx->width) {
x = 0;
y++;
}
}
break;
case 1:
while (run-- > 0) {
if (y >= avctx->height)
return AVERROR_INVALIDDATA;
dst[y * linesize + x] = dst[ly * linesize + lx];
lx = x;
ly = y;
x++;
if (x >= avctx->width) {
x = 0;
y++;
}
}
clr = dst[ly * linesize + lx];
break;
case 2:
while (run-- > 0) {
if (y < 1 || y >= avctx->height)
return AVERROR_INVALIDDATA;
clr = dst[y * linesize + x + off + 1];
dst[y * linesize + x] = clr;
lx = x;
ly = y;
x++;
if (x >= avctx->width) {
x = 0;
y++;
}
}
break;
case 4:
while (run-- > 0) {
uint8_t *odst = (uint8_t *)dst;
if (y < 1 || y >= avctx->height ||
(y == 1 && x == 0))
return AVERROR_INVALIDDATA;
if (x == 0) {
z = backstep;
} else {
z = 0;
}
r = odst[(ly * linesize + lx) * 4] +
odst[((y * linesize + x) + off - z) * 4 + 4] -
odst[((y * linesize + x) + off - z) * 4];
g = odst[(ly * linesize + lx) * 4 + 1] +
odst[((y * linesize + x) + off - z) * 4 + 5] -
odst[((y * linesize + x) + off - z) * 4 + 1];
b = odst[(ly * linesize + lx) * 4 + 2] +
odst[((y * linesize + x) + off - z) * 4 + 6] -
odst[((y * linesize + x) + off - z) * 4 + 2];
clr = ((b & 0xFF) << 16) + ((g & 0xFF) << 8) + (r & 0xFF);
dst[y * linesize + x] = clr;
lx = x;
ly = y;
x++;
if (x >= avctx->width) {
x = 0;
y++;
}
}
break;
case 5:
while (run-- > 0) {
if (y < 1 || y >= avctx->height ||
(y == 1 && x == 0))
return AVERROR_INVALIDDATA;
if (x == 0) {
z = backstep;
} else {
z = 0;
}
clr = dst[y * linesize + x + off - z];
dst[y * linesize + x] = clr;
lx = x;
ly = y;
x++;
if (x >= avctx->width) {
x = 0;
y++;
}
}
break;
}
if (avctx->bits_per_coded_sample == 16) {
cx1 = (clr & 0x3F00) >> 2;
cx = (clr & 0xFFFFFF) >> 16;
} else {
cx1 = (clr & 0xFC00) >> 4;
cx = (clr & 0xFFFFFF) >> 18;
}
}
return 0;
}
static int decompress_p(AVCodecContext *avctx,
uint32_t *dst, int linesize,
uint32_t *prev, int plinesize)
{
SCPRContext *s = avctx->priv_data;
GetByteContext *gb = &s->gb;
int ret, temp, min, max, x, y, cx = 0, cx1 = 0;
int backstep = linesize - avctx->width;
const int cxshift = s->cxshift;
if (bytestream2_get_byte(gb) == 0)
return 0;
bytestream2_skip(gb, 1);
init_rangecoder(&s->rc, gb);
ret = decode_value(s, s->range_model, 256, 1, &min);
ret |= decode_value(s, s->range_model, 256, 1, &temp);
min += temp << 8;
ret |= decode_value(s, s->range_model, 256, 1, &max);
ret |= decode_value(s, s->range_model, 256, 1, &temp);
if (ret < 0)
return ret;
max += temp << 8;
memset(s->blocks, 0, sizeof(*s->blocks) * s->nbcount);
while (min <= max) {
int fill, count;
ret = decode_value(s, s->fill_model, 5, 10, &fill);
ret |= decode_value(s, s->count_model, 256, 20, &count);
if (ret < 0)
return ret;
while (min < s->nbcount && count-- > 0) {
s->blocks[min++] = fill;
}
}
for (y = 0; y < s->nby; y++) {
for (x = 0; x < s->nbx; x++) {
int sy1 = 0, sy2 = 16, sx1 = 0, sx2 = 16;
if (s->blocks[y * s->nbx + x] == 0)
continue;
if (((s->blocks[y * s->nbx + x] - 1) & 1) > 0) {
ret = decode_value(s, s->sxy_model[0], 16, 100, &sx1);
ret |= decode_value(s, s->sxy_model[1], 16, 100, &sy1);
ret |= decode_value(s, s->sxy_model[2], 16, 100, &sx2);
ret |= decode_value(s, s->sxy_model[3], 16, 100, &sy2);
if (ret < 0)
return ret;
sx2++;
sy2++;
}
if (((s->blocks[y * s->nbx + x] - 1) & 2) > 0) {
int i, j, by = y * 16, bx = x * 16;
int mvx, mvy;
ret = decode_value(s, s->mv_model[0], 512, 100, &mvx);
ret |= decode_value(s, s->mv_model[1], 512, 100, &mvy);
if (ret < 0)
return ret;
mvx -= 256;
mvy -= 256;
if (by + mvy + sy1 < 0 || bx + mvx + sx1 < 0 ||
by + mvy + sy1 >= avctx->height || bx + mvx + sx1 >= avctx->width)
return AVERROR_INVALIDDATA;
for (i = 0; i < sy2 - sy1 && (by + sy1 + i) < avctx->height && (by + mvy + sy1 + i) < avctx->height; i++) {
for (j = 0; j < sx2 - sx1 && (bx + sx1 + j) < avctx->width && (bx + mvx + sx1 + j) < avctx->width; j++) {
dst[(by + i + sy1) * linesize + bx + sx1 + j] = prev[(by + mvy + sy1 + i) * plinesize + bx + sx1 + mvx + j];
}
}
} else {
int run, r, g, b, z, bx = x * 16 + sx1, by = y * 16 + sy1;
unsigned clr, ptype = 0;
for (; by < y * 16 + sy2 && by < avctx->height;) {
ret = decode_value(s, s->op_model[ptype], 6, 1000, &ptype);
if (ptype == 0) {
ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r);
if (ret < 0)
return ret;
cx1 = (cx << 6) & 0xFC0;
cx = r >> cxshift;
ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g);
if (ret < 0)
return ret;
cx1 = (cx << 6) & 0xFC0;
cx = g >> cxshift;
ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b);
if (ret < 0)
return ret;
clr = (b << 16) + (g << 8) + r;
}
if (ptype > 5)
return AVERROR_INVALIDDATA;
ret = decode_value(s, s->run_model[ptype], 256, 400, &run);
if (ret < 0)
return ret;
switch (ptype) {
case 0:
while (run-- > 0) {
if (by >= avctx->height)
return AVERROR_INVALIDDATA;
dst[by * linesize + bx] = clr;
bx++;
if (bx >= x * 16 + sx2 || bx >= avctx->width) {
bx = x * 16 + sx1;
by++;
}
}
break;
case 1:
while (run-- > 0) {
if (bx == 0) {
if (by < 1)
return AVERROR_INVALIDDATA;
z = backstep;
} else {
z = 0;
}
if (by >= avctx->height)
return AVERROR_INVALIDDATA;
clr = dst[by * linesize + bx - 1 - z];
dst[by * linesize + bx] = clr;
bx++;
if (bx >= x * 16 + sx2 || bx >= avctx->width) {
bx = x * 16 + sx1;
by++;
}
}
break;
case 2:
while (run-- > 0) {
if (by < 1 || by >= avctx->height)
return AVERROR_INVALIDDATA;
clr = dst[(by - 1) * linesize + bx];
dst[by * linesize + bx] = clr;
bx++;
if (bx >= x * 16 + sx2 || bx >= avctx->width) {
bx = x * 16 + sx1;
by++;
}
}
break;
case 3:
while (run-- > 0) {
if (by >= avctx->height)
return AVERROR_INVALIDDATA;
clr = prev[by * plinesize + bx];
dst[by * linesize + bx] = clr;
bx++;
if (bx >= x * 16 + sx2 || bx >= avctx->width) {
bx = x * 16 + sx1;
by++;
}
}
break;
case 4:
while (run-- > 0) {
uint8_t *odst = (uint8_t *)dst;
if (by < 1 || by >= avctx->height)
return AVERROR_INVALIDDATA;
if (bx == 0) {
z = backstep;
} else {
z = 0;
}
r = odst[((by - 1) * linesize + bx) * 4] +
odst[(by * linesize + bx - 1 - z) * 4] -
odst[((by - 1) * linesize + bx - 1 - z) * 4];
g = odst[((by - 1) * linesize + bx) * 4 + 1] +
odst[(by * linesize + bx - 1 - z) * 4 + 1] -
odst[((by - 1) * linesize + bx - 1 - z) * 4 + 1];
b = odst[((by - 1) * linesize + bx) * 4 + 2] +
odst[(by * linesize + bx - 1 - z) * 4 + 2] -
odst[((by - 1) * linesize + bx - 1 - z) * 4 + 2];
clr = ((b & 0xFF) << 16) + ((g & 0xFF) << 8) + (r & 0xFF);
dst[by * linesize + bx] = clr;
bx++;
if (bx >= x * 16 + sx2 || bx >= avctx->width) {
bx = x * 16 + sx1;
by++;
}
}
break;
case 5:
while (run-- > 0) {
if (by < 1 || by >= avctx->height)
return AVERROR_INVALIDDATA;
if (bx == 0) {
z = backstep;
} else {
z = 0;
}
clr = dst[(by - 1) * linesize + bx - 1 - z];
dst[by * linesize + bx] = clr;
bx++;
if (bx >= x * 16 + sx2 || bx >= avctx->width) {
bx = x * 16 + sx1;
by++;
}
}
break;
}
if (avctx->bits_per_coded_sample == 16) {
cx1 = (clr & 0x3F00) >> 2;
cx = (clr & 0xFFFFFF) >> 16;
} else {
cx1 = (clr & 0xFC00) >> 4;
cx = (clr & 0xFFFFFF) >> 18;
}
}
}
}
}
return 0;
}
static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
AVPacket *avpkt)
{
SCPRContext *s = avctx->priv_data;
GetByteContext *gb = &s->gb;
AVFrame *frame = data;
int ret, type;
if (avctx->bits_per_coded_sample == 16) {
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
return ret;
}
if ((ret = ff_reget_buffer(avctx, s->current_frame)) < 0)
return ret;
bytestream2_init(gb, avpkt->data, avpkt->size);
type = bytestream2_peek_byte(gb);
if (type == 2) {
s->get_freq = get_freq0;
s->decode = decode0;
frame->key_frame = 1;
ret = decompress_i(avctx, (uint32_t *)s->current_frame->data[0],
s->current_frame->linesize[0] / 4);
} else if (type == 18) {
s->get_freq = get_freq;
s->decode = decode;
frame->key_frame = 1;
ret = decompress_i(avctx, (uint32_t *)s->current_frame->data[0],
s->current_frame->linesize[0] / 4);
} else if (type == 17) {
uint32_t clr, *dst = (uint32_t *)s->current_frame->data[0];
int x, y;
frame->key_frame = 1;
bytestream2_skip(gb, 1);
if (avctx->bits_per_coded_sample == 16) {
uint16_t value = bytestream2_get_le16(gb);
int r, g, b;
r = (value ) & 31;
g = (value >> 5) & 31;
b = (value >> 10) & 31;
clr = (r << 16) + (g << 8) + b;
} else {
clr = bytestream2_get_le24(gb);
}
for (y = 0; y < avctx->height; y++) {
for (x = 0; x < avctx->width; x++) {
dst[x] = clr;
}
dst += s->current_frame->linesize[0] / 4;
}
} else if (type == 0 || type == 1) {
frame->key_frame = 0;
ret = av_frame_copy(s->current_frame, s->last_frame);
if (ret < 0)
return ret;
ret = decompress_p(avctx, (uint32_t *)s->current_frame->data[0],
s->current_frame->linesize[0] / 4,
(uint32_t *)s->last_frame->data[0],
s->last_frame->linesize[0] / 4);
} else {
return AVERROR_PATCHWELCOME;
}
if (ret < 0)
return ret;
if (avctx->bits_per_coded_sample != 16) {
ret = av_frame_ref(data, s->current_frame);
if (ret < 0)
return ret;
} else {
uint8_t *dst = frame->data[0];
int x, y;
ret = av_frame_copy(frame, s->current_frame);
if (ret < 0)
return ret;
for (y = 0; y < avctx->height; y++) {
for (x = 0; x < avctx->width * 4; x++) {
dst[x] = dst[x] << 3;
}
dst += frame->linesize[0];
}
}
frame->pict_type = frame->key_frame ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
FFSWAP(AVFrame *, s->current_frame, s->last_frame);
frame->data[0] += frame->linesize[0] * (avctx->height - 1);
frame->linesize[0] *= -1;
*got_frame = 1;
return avpkt->size;
}
static av_cold int decode_init(AVCodecContext *avctx)
{
SCPRContext *s = avctx->priv_data;
switch (avctx->bits_per_coded_sample) {
case 16: avctx->pix_fmt = AV_PIX_FMT_RGB0; break;
case 24:
case 32: avctx->pix_fmt = AV_PIX_FMT_BGR0; break;
default:
av_log(avctx, AV_LOG_ERROR, "Unsupported bitdepth %i\n", avctx->bits_per_coded_sample);
return AVERROR_INVALIDDATA;
}
s->get_freq = get_freq0;
s->decode = decode0;
s->cxshift = avctx->bits_per_coded_sample == 16 ? 0 : 2;
s->cbits = avctx->bits_per_coded_sample == 16 ? 0x1F : 0xFF;
s->nbx = (avctx->width + 15) / 16;
s->nby = (avctx->height + 15) / 16;
s->nbcount = s->nbx * s->nby;
s->blocks = av_malloc_array(s->nbcount, sizeof(*s->blocks));
if (!s->blocks)
return AVERROR(ENOMEM);
s->last_frame = av_frame_alloc();
s->current_frame = av_frame_alloc();
if (!s->last_frame || !s->current_frame)
return AVERROR(ENOMEM);
return 0;
}
static av_cold int decode_close(AVCodecContext *avctx)
{
SCPRContext *s = avctx->priv_data;
av_freep(&s->blocks);
av_frame_free(&s->last_frame);
av_frame_free(&s->current_frame);
return 0;
}
AVCodec ff_scpr_decoder = {
.name = "scpr",
.long_name = NULL_IF_CONFIG_SMALL("ScreenPressor"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_SCPR,
.priv_data_size = sizeof(SCPRContext),
.init = decode_init,
.close = decode_close,
.decode = decode_frame,
.capabilities = AV_CODEC_CAP_DR1,
.caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
FF_CODEC_CAP_INIT_CLEANUP,
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3420_0 |
crossvul-cpp_data_bad_2308_0 | /* ssl/d1_lib.c */
/*
* DTLS implementation written by Nagendra Modadugu
* (nagendra@cs.stanford.edu) for the OpenSSL project 2005.
*/
/* ====================================================================
* Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#define USE_SOCKETS
#include <openssl/objects.h>
#include "ssl_locl.h"
#if defined(OPENSSL_SYS_VMS)
#include <sys/timeb.h>
#endif
static void get_current_time(struct timeval *t);
static void dtls1_set_handshake_header(SSL *s, int type, unsigned long len);
static int dtls1_handshake_write(SSL *s);
const char dtls1_version_str[]="DTLSv1" OPENSSL_VERSION_PTEXT;
int dtls1_listen(SSL *s, struct sockaddr *client);
SSL3_ENC_METHOD DTLSv1_enc_data={
tls1_enc,
tls1_mac,
tls1_setup_key_block,
tls1_generate_master_secret,
tls1_change_cipher_state,
tls1_final_finish_mac,
TLS1_FINISH_MAC_LENGTH,
tls1_cert_verify_mac,
TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
tls1_alert_code,
tls1_export_keying_material,
SSL_ENC_FLAG_DTLS|SSL_ENC_FLAG_EXPLICIT_IV,
DTLS1_HM_HEADER_LENGTH,
dtls1_set_handshake_header,
dtls1_handshake_write
};
SSL3_ENC_METHOD DTLSv1_2_enc_data={
tls1_enc,
tls1_mac,
tls1_setup_key_block,
tls1_generate_master_secret,
tls1_change_cipher_state,
tls1_final_finish_mac,
TLS1_FINISH_MAC_LENGTH,
tls1_cert_verify_mac,
TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
tls1_alert_code,
tls1_export_keying_material,
SSL_ENC_FLAG_DTLS|SSL_ENC_FLAG_EXPLICIT_IV|SSL_ENC_FLAG_SIGALGS
|SSL_ENC_FLAG_SHA256_PRF|SSL_ENC_FLAG_TLS1_2_CIPHERS,
DTLS1_HM_HEADER_LENGTH,
dtls1_set_handshake_header,
dtls1_handshake_write
};
long dtls1_default_timeout(void)
{
/* 2 hours, the 24 hours mentioned in the DTLSv1 spec
* is way too long for http, the cache would over fill */
return(60*60*2);
}
int dtls1_new(SSL *s)
{
DTLS1_STATE *d1;
if (!ssl3_new(s)) return(0);
if ((d1=OPENSSL_malloc(sizeof *d1)) == NULL) return (0);
memset(d1,0, sizeof *d1);
/* d1->handshake_epoch=0; */
d1->unprocessed_rcds.q=pqueue_new();
d1->processed_rcds.q=pqueue_new();
d1->buffered_messages = pqueue_new();
d1->sent_messages=pqueue_new();
d1->buffered_app_data.q=pqueue_new();
if ( s->server)
{
d1->cookie_len = sizeof(s->d1->cookie);
}
if( ! d1->unprocessed_rcds.q || ! d1->processed_rcds.q
|| ! d1->buffered_messages || ! d1->sent_messages || ! d1->buffered_app_data.q)
{
if ( d1->unprocessed_rcds.q) pqueue_free(d1->unprocessed_rcds.q);
if ( d1->processed_rcds.q) pqueue_free(d1->processed_rcds.q);
if ( d1->buffered_messages) pqueue_free(d1->buffered_messages);
if ( d1->sent_messages) pqueue_free(d1->sent_messages);
if ( d1->buffered_app_data.q) pqueue_free(d1->buffered_app_data.q);
OPENSSL_free(d1);
return (0);
}
s->d1=d1;
s->method->ssl_clear(s);
return(1);
}
static void dtls1_clear_queues(SSL *s)
{
pitem *item = NULL;
hm_fragment *frag = NULL;
DTLS1_RECORD_DATA *rdata;
while( (item = pqueue_pop(s->d1->unprocessed_rcds.q)) != NULL)
{
rdata = (DTLS1_RECORD_DATA *) item->data;
if (rdata->rbuf.buf)
{
OPENSSL_free(rdata->rbuf.buf);
}
OPENSSL_free(item->data);
pitem_free(item);
}
while( (item = pqueue_pop(s->d1->processed_rcds.q)) != NULL)
{
rdata = (DTLS1_RECORD_DATA *) item->data;
if (rdata->rbuf.buf)
{
OPENSSL_free(rdata->rbuf.buf);
}
OPENSSL_free(item->data);
pitem_free(item);
}
while( (item = pqueue_pop(s->d1->buffered_messages)) != NULL)
{
frag = (hm_fragment *)item->data;
OPENSSL_free(frag->fragment);
OPENSSL_free(frag);
pitem_free(item);
}
while ( (item = pqueue_pop(s->d1->sent_messages)) != NULL)
{
frag = (hm_fragment *)item->data;
OPENSSL_free(frag->fragment);
OPENSSL_free(frag);
pitem_free(item);
}
while ( (item = pqueue_pop(s->d1->buffered_app_data.q)) != NULL)
{
frag = (hm_fragment *)item->data;
OPENSSL_free(frag->fragment);
OPENSSL_free(frag);
pitem_free(item);
}
}
void dtls1_free(SSL *s)
{
ssl3_free(s);
dtls1_clear_queues(s);
pqueue_free(s->d1->unprocessed_rcds.q);
pqueue_free(s->d1->processed_rcds.q);
pqueue_free(s->d1->buffered_messages);
pqueue_free(s->d1->sent_messages);
pqueue_free(s->d1->buffered_app_data.q);
OPENSSL_free(s->d1);
s->d1 = NULL;
}
void dtls1_clear(SSL *s)
{
pqueue unprocessed_rcds;
pqueue processed_rcds;
pqueue buffered_messages;
pqueue sent_messages;
pqueue buffered_app_data;
unsigned int mtu;
if (s->d1)
{
unprocessed_rcds = s->d1->unprocessed_rcds.q;
processed_rcds = s->d1->processed_rcds.q;
buffered_messages = s->d1->buffered_messages;
sent_messages = s->d1->sent_messages;
buffered_app_data = s->d1->buffered_app_data.q;
mtu = s->d1->mtu;
dtls1_clear_queues(s);
memset(s->d1, 0, sizeof(*(s->d1)));
if (s->server)
{
s->d1->cookie_len = sizeof(s->d1->cookie);
}
if (SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)
{
s->d1->mtu = mtu;
}
s->d1->unprocessed_rcds.q = unprocessed_rcds;
s->d1->processed_rcds.q = processed_rcds;
s->d1->buffered_messages = buffered_messages;
s->d1->sent_messages = sent_messages;
s->d1->buffered_app_data.q = buffered_app_data;
}
ssl3_clear(s);
if (s->options & SSL_OP_CISCO_ANYCONNECT)
s->version=DTLS1_BAD_VER;
else if (s->method->version == DTLS_ANY_VERSION)
s->version=DTLS1_2_VERSION;
else
s->version=s->method->version;
}
long dtls1_ctrl(SSL *s, int cmd, long larg, void *parg)
{
int ret=0;
switch (cmd)
{
case DTLS_CTRL_GET_TIMEOUT:
if (dtls1_get_timeout(s, (struct timeval*) parg) != NULL)
{
ret = 1;
}
break;
case DTLS_CTRL_HANDLE_TIMEOUT:
ret = dtls1_handle_timeout(s);
break;
case DTLS_CTRL_LISTEN:
ret = dtls1_listen(s, parg);
break;
default:
ret = ssl3_ctrl(s, cmd, larg, parg);
break;
}
return(ret);
}
/*
* As it's impossible to use stream ciphers in "datagram" mode, this
* simple filter is designed to disengage them in DTLS. Unfortunately
* there is no universal way to identify stream SSL_CIPHER, so we have
* to explicitly list their SSL_* codes. Currently RC4 is the only one
* available, but if new ones emerge, they will have to be added...
*/
const SSL_CIPHER *dtls1_get_cipher(unsigned int u)
{
const SSL_CIPHER *ciph = ssl3_get_cipher(u);
if (ciph != NULL)
{
if (ciph->algorithm_enc == SSL_RC4)
return NULL;
}
return ciph;
}
void dtls1_start_timer(SSL *s)
{
#ifndef OPENSSL_NO_SCTP
/* Disable timer for SCTP */
if (BIO_dgram_is_sctp(SSL_get_wbio(s)))
{
memset(&(s->d1->next_timeout), 0, sizeof(struct timeval));
return;
}
#endif
/* If timer is not set, initialize duration with 1 second */
if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0)
{
s->d1->timeout_duration = 1;
}
/* Set timeout to current time */
get_current_time(&(s->d1->next_timeout));
/* Add duration to current time */
s->d1->next_timeout.tv_sec += s->d1->timeout_duration;
BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0, &(s->d1->next_timeout));
}
struct timeval* dtls1_get_timeout(SSL *s, struct timeval* timeleft)
{
struct timeval timenow;
/* If no timeout is set, just return NULL */
if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0)
{
return NULL;
}
/* Get current time */
get_current_time(&timenow);
/* If timer already expired, set remaining time to 0 */
if (s->d1->next_timeout.tv_sec < timenow.tv_sec ||
(s->d1->next_timeout.tv_sec == timenow.tv_sec &&
s->d1->next_timeout.tv_usec <= timenow.tv_usec))
{
memset(timeleft, 0, sizeof(struct timeval));
return timeleft;
}
/* Calculate time left until timer expires */
memcpy(timeleft, &(s->d1->next_timeout), sizeof(struct timeval));
timeleft->tv_sec -= timenow.tv_sec;
timeleft->tv_usec -= timenow.tv_usec;
if (timeleft->tv_usec < 0)
{
timeleft->tv_sec--;
timeleft->tv_usec += 1000000;
}
/* If remaining time is less than 15 ms, set it to 0
* to prevent issues because of small devergences with
* socket timeouts.
*/
if (timeleft->tv_sec == 0 && timeleft->tv_usec < 15000)
{
memset(timeleft, 0, sizeof(struct timeval));
}
return timeleft;
}
int dtls1_is_timer_expired(SSL *s)
{
struct timeval timeleft;
/* Get time left until timeout, return false if no timer running */
if (dtls1_get_timeout(s, &timeleft) == NULL)
{
return 0;
}
/* Return false if timer is not expired yet */
if (timeleft.tv_sec > 0 || timeleft.tv_usec > 0)
{
return 0;
}
/* Timer expired, so return true */
return 1;
}
void dtls1_double_timeout(SSL *s)
{
s->d1->timeout_duration *= 2;
if (s->d1->timeout_duration > 60)
s->d1->timeout_duration = 60;
dtls1_start_timer(s);
}
void dtls1_stop_timer(SSL *s)
{
/* Reset everything */
memset(&(s->d1->timeout), 0, sizeof(struct dtls1_timeout_st));
memset(&(s->d1->next_timeout), 0, sizeof(struct timeval));
s->d1->timeout_duration = 1;
BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0, &(s->d1->next_timeout));
/* Clear retransmission buffer */
dtls1_clear_record_buffer(s);
}
int dtls1_check_timeout_num(SSL *s)
{
s->d1->timeout.num_alerts++;
/* Reduce MTU after 2 unsuccessful retransmissions */
if (s->d1->timeout.num_alerts > 2)
{
s->d1->mtu = BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_GET_FALLBACK_MTU, 0, NULL);
}
if (s->d1->timeout.num_alerts > DTLS1_TMO_ALERT_COUNT)
{
/* fail the connection, enough alerts have been sent */
SSLerr(SSL_F_DTLS1_CHECK_TIMEOUT_NUM,SSL_R_READ_TIMEOUT_EXPIRED);
return -1;
}
return 0;
}
int dtls1_handle_timeout(SSL *s)
{
/* if no timer is expired, don't do anything */
if (!dtls1_is_timer_expired(s))
{
return 0;
}
dtls1_double_timeout(s);
if (dtls1_check_timeout_num(s) < 0)
return -1;
s->d1->timeout.read_timeouts++;
if (s->d1->timeout.read_timeouts > DTLS1_TMO_READ_COUNT)
{
s->d1->timeout.read_timeouts = 1;
}
#ifndef OPENSSL_NO_HEARTBEATS
if (s->tlsext_hb_pending)
{
s->tlsext_hb_pending = 0;
return dtls1_heartbeat(s);
}
#endif
dtls1_start_timer(s);
return dtls1_retransmit_buffered_messages(s);
}
static void get_current_time(struct timeval *t)
{
#if defined(_WIN32)
SYSTEMTIME st;
union { unsigned __int64 ul; FILETIME ft; } now;
GetSystemTime(&st);
SystemTimeToFileTime(&st,&now.ft);
#ifdef __MINGW32__
now.ul -= 116444736000000000ULL;
#else
now.ul -= 116444736000000000UI64; /* re-bias to 1/1/1970 */
#endif
t->tv_sec = (long)(now.ul/10000000);
t->tv_usec = ((int)(now.ul%10000000))/10;
#elif defined(OPENSSL_SYS_VMS)
struct timeb tb;
ftime(&tb);
t->tv_sec = (long)tb.time;
t->tv_usec = (long)tb.millitm * 1000;
#else
gettimeofday(t, NULL);
#endif
}
int dtls1_listen(SSL *s, struct sockaddr *client)
{
int ret;
SSL_set_options(s, SSL_OP_COOKIE_EXCHANGE);
s->d1->listen = 1;
ret = SSL_accept(s);
if (ret <= 0) return ret;
(void) BIO_dgram_get_peer(SSL_get_rbio(s), client);
return 1;
}
static void dtls1_set_handshake_header(SSL *s, int htype, unsigned long len)
{
unsigned char *p = (unsigned char *)s->init_buf->data;
dtls1_set_message_header(s, p, htype, len, 0, len);
s->init_num = (int)len + DTLS1_HM_HEADER_LENGTH;
s->init_off = 0;
/* Buffer the message to handle re-xmits */
dtls1_buffer_message(s, 0);
}
static int dtls1_handshake_write(SSL *s)
{
return dtls1_do_write(s, SSL3_RT_HANDSHAKE);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2308_0 |
crossvul-cpp_data_bad_345_3 | /*
* card-tcos.c: Support for TCOS cards
*
* Copyright (C) 2011 Peter Koch <pk@opensc-project.org>
* Copyright (C) 2002 g10 Code GmbH
* Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
static struct sc_atr_table tcos_atrs[] = {
/* Infineon SLE44 */
{ "3B:BA:13:00:81:31:86:5D:00:64:05:0A:02:01:31:80:90:00:8B", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66S */
{ "3B:BA:14:00:81:31:86:5D:00:64:05:14:02:02:31:80:90:00:91", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66CX320P */
{ "3B:BA:96:00:81:31:86:5D:00:64:05:60:02:03:31:80:90:00:66", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66CX322P */
{ "3B:BA:96:00:81:31:86:5D:00:64:05:7B:02:03:31:80:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Philips P5CT072 */
{ "3B:BF:96:00:81:31:FE:5D:00:64:04:11:03:01:31:C0:73:F7:01:D0:00:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
{ "3B:BF:96:00:81:31:FE:5D:00:64:04:11:04:0F:31:C0:73:F7:01:D0:00:90:00:74", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
/* Philips P5CT080 */
{ "3B:BF:B6:00:81:31:FE:5D:00:64:04:28:03:02:31:C0:73:F7:01:D0:00:90:00:67", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
static struct sc_card_operations tcos_ops;
static struct sc_card_driver tcos_drv = {
"TCOS 3.0",
"tcos",
&tcos_ops,
NULL, 0, NULL
};
static const struct sc_card_operations *iso_ops = NULL;
typedef struct tcos_data_st {
unsigned int pad_flags;
unsigned int next_sign;
} tcos_data;
static int tcos_finish(sc_card_t *card)
{
free(card->drv_data);
return 0;
}
static int tcos_match_card(sc_card_t *card)
{
int i;
i = _sc_match_atr(card, tcos_atrs, &card->type);
if (i < 0)
return 0;
return 1;
}
static int tcos_init(sc_card_t *card)
{
unsigned long flags;
tcos_data *data = malloc(sizeof(tcos_data));
if (!data) return SC_ERROR_OUT_OF_MEMORY;
card->name = "TCOS";
card->drv_data = (void *)data;
card->cla = 0x00;
flags = SC_ALGORITHM_RSA_RAW;
flags |= SC_ALGORITHM_RSA_PAD_PKCS1;
flags |= SC_ALGORITHM_RSA_HASH_NONE;
_sc_card_add_rsa_alg(card, 512, flags, 0);
_sc_card_add_rsa_alg(card, 768, flags, 0);
_sc_card_add_rsa_alg(card, 1024, flags, 0);
if (card->type == SC_CARD_TYPE_TCOS_V3) {
card->caps |= SC_CARD_CAP_APDU_EXT;
_sc_card_add_rsa_alg(card, 1280, flags, 0);
_sc_card_add_rsa_alg(card, 1536, flags, 0);
_sc_card_add_rsa_alg(card, 1792, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
}
return 0;
}
/* Hmmm, I don't know what to do. It seems that the ACL design of
OpenSC should be enhanced to allow for the command based security
attributes of TCOS. FIXME: This just allows to create a very basic
file. */
static int tcos_construct_fci(const sc_file_t *file,
u8 *out, size_t *outlen)
{
u8 *p = out;
u8 buf[64];
size_t n;
/* FIXME: possible buffer overflow */
*p++ = 0x6F; /* FCI */
p++;
/* File size */
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
sc_asn1_put_tag(0x81, buf, 2, p, 16, &p);
/* File descriptor */
n = 0;
buf[n] = file->shareable ? 0x40 : 0;
switch (file->type) {
case SC_FILE_TYPE_WORKING_EF:
break;
case SC_FILE_TYPE_DF:
buf[0] |= 0x38;
break;
default:
return SC_ERROR_NOT_SUPPORTED;
}
buf[n++] |= file->ef_structure & 7;
if ( (file->ef_structure & 7) > 1) {
/* record structured file */
buf[n++] = 0x41; /* indicate 3rd byte */
buf[n++] = file->record_length;
}
sc_asn1_put_tag(0x82, buf, n, p, 8, &p);
/* File identifier */
buf[0] = (file->id >> 8) & 0xFF;
buf[1] = file->id & 0xFF;
sc_asn1_put_tag(0x83, buf, 2, p, 16, &p);
/* Directory name */
if (file->type == SC_FILE_TYPE_DF) {
if (file->namelen) {
sc_asn1_put_tag(0x84, file->name, file->namelen,
p, 16, &p);
}
else {
/* TCOS needs one, so we use a faked one */
snprintf ((char *) buf, sizeof(buf)-1, "foo-%lu",
(unsigned long) time (NULL));
sc_asn1_put_tag(0x84, buf, strlen ((char *) buf), p, 16, &p);
}
}
/* File descriptor extension */
if (file->prop_attr_len && file->prop_attr) {
n = file->prop_attr_len;
memcpy(buf, file->prop_attr, n);
}
else {
n = 0;
buf[n++] = 0x01; /* not invalidated, permanent */
if (file->type == SC_FILE_TYPE_WORKING_EF)
buf[n++] = 0x00; /* generic data file */
}
sc_asn1_put_tag(0x85, buf, n, p, 16, &p);
/* Security attributes */
if (file->sec_attr_len && file->sec_attr) {
memcpy(buf, file->sec_attr, file->sec_attr_len);
n = file->sec_attr_len;
}
else {
/* no attributes given - fall back to default one */
memcpy (buf+ 0, "\xa4\x00\x00\x00\xff\xff", 6); /* select */
memcpy (buf+ 6, "\xb0\x00\x00\x00\xff\xff", 6); /* read bin */
memcpy (buf+12, "\xd6\x00\x00\x00\xff\xff", 6); /* upd bin */
memcpy (buf+18, "\x60\x00\x00\x00\xff\xff", 6); /* admin grp*/
n = 24;
}
sc_asn1_put_tag(0x86, buf, n, p, sizeof (buf), &p);
/* fixup length of FCI */
out[1] = p - out - 2;
*outlen = p - out;
return 0;
}
static int tcos_create_file(sc_card_t *card, sc_file_t *file)
{
int r;
size_t len;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_apdu_t apdu;
len = SC_MAX_APDU_BUFFER_SIZE;
r = tcos_construct_fci(file, sbuf, &len);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "tcos_construct_fci() failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00);
apdu.cla |= 0x80; /* this is an proprietary extension */
apdu.lc = len;
apdu.datalen = len;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static unsigned int map_operations (int commandbyte )
{
unsigned int op = (unsigned int)-1;
switch ( (commandbyte & 0xfe) ) {
case 0xe2: /* append record */ op = SC_AC_OP_UPDATE; break;
case 0x24: /* change password */ op = SC_AC_OP_UPDATE; break;
case 0xe0: /* create */ op = SC_AC_OP_CREATE; break;
case 0xe4: /* delete */ op = SC_AC_OP_DELETE; break;
case 0xe8: /* exclude sfi */ op = SC_AC_OP_WRITE; break;
case 0x82: /* external auth */ op = SC_AC_OP_READ; break;
case 0xe6: /* include sfi */ op = SC_AC_OP_WRITE; break;
case 0x88: /* internal auth */ op = SC_AC_OP_READ; break;
case 0x04: /* invalidate */ op = SC_AC_OP_INVALIDATE; break;
case 0x2a: /* perform sec. op */ op = SC_AC_OP_SELECT; break;
case 0xb0: /* read binary */ op = SC_AC_OP_READ; break;
case 0xb2: /* read record */ op = SC_AC_OP_READ; break;
case 0x44: /* rehabilitate */ op = SC_AC_OP_REHABILITATE; break;
case 0xa4: /* select */ op = SC_AC_OP_SELECT; break;
case 0xee: /* set permanent */ op = SC_AC_OP_CREATE; break;
case 0x2c: /* unblock password */op = SC_AC_OP_WRITE; break;
case 0xd6: /* update binary */ op = SC_AC_OP_WRITE; break;
case 0xdc: /* update record */ op = SC_AC_OP_WRITE; break;
case 0x20: /* verify password */ op = SC_AC_OP_SELECT; break;
case 0x60: /* admin group */ op = SC_AC_OP_CREATE; break;
}
return op;
}
/* Hmmm, I don't know what to do. It seems that the ACL design of
OpenSC should be enhanced to allow for the command based security
attributes of TCOS. FIXME: This just allows to create a very basic
file. */
static void parse_sec_attr(sc_card_t *card,
sc_file_t *file, const u8 *buf, size_t len)
{
unsigned int op;
/* list directory is not covered by ACLs - so always add an entry */
sc_file_add_acl_entry (file, SC_AC_OP_LIST_FILES,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
/* FIXME: check for what LOCK is used */
sc_file_add_acl_entry (file, SC_AC_OP_LOCK,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
for (; len >= 6; len -= 6, buf += 6) {
/* FIXME: temporary hacks */
if (!memcmp(buf, "\xa4\x00\x00\x00\xff\xff", 6)) /* select */
sc_file_add_acl_entry (file, SC_AC_OP_SELECT,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\xb0\x00\x00\x00\xff\xff", 6)) /*read*/
sc_file_add_acl_entry (file, SC_AC_OP_READ,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\xd6\x00\x00\x00\xff\xff", 6)) /*upd*/
sc_file_add_acl_entry (file, SC_AC_OP_UPDATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\x60\x00\x00\x00\xff\xff", 6)) {/*adm */
sc_file_add_acl_entry (file, SC_AC_OP_WRITE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_CREATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_INVALIDATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_REHABILITATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
}
else {
/* the first byte tells use the command or the
command group. We have to mask bit 0
because this one distinguish between AND/OR
combination of PINs*/
op = map_operations (buf[0]);
if (op == (unsigned int)-1)
{
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"Unknown security command byte %02x\n",
buf[0]);
continue;
}
if (!buf[1])
sc_file_add_acl_entry (file, op,
SC_AC_NONE,
SC_AC_KEY_REF_NONE);
else
sc_file_add_acl_entry (file, op,
SC_AC_CHV, buf[1]);
if (!buf[2] && !buf[3])
sc_file_add_acl_entry (file, op,
SC_AC_NONE,
SC_AC_KEY_REF_NONE);
else
sc_file_add_acl_entry (file, op,
SC_AC_TERM,
(buf[2]<<8)|buf[3]);
}
}
}
static int tcos_select_file(sc_card_t *card,
const sc_path_t *in_path,
sc_file_t **file_out)
{
sc_context_t *ctx;
sc_apdu_t apdu;
sc_file_t *file=NULL;
u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
unsigned int i;
int r, pathlen;
assert(card != NULL && in_path != NULL);
ctx=card->ctx;
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS;
/* fall through */
case SC_PATH_TYPE_FROM_CURRENT:
apdu.p1 = 9;
break;
case SC_PATH_TYPE_DF_NAME:
apdu.p1 = 4;
break;
case SC_PATH_TYPE_PATH:
apdu.p1 = 8;
if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2;
if (pathlen == 0) apdu.p1 = 0;
break;
case SC_PATH_TYPE_PARENT:
apdu.p1 = 3;
pathlen = 0;
break;
default:
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
if (file_out != NULL) {
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = 256;
} else {
apdu.resplen = 0;
apdu.le = 0;
apdu.p2 = 0x0C;
apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT;
}
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r);
if (apdu.resplen < 1 || apdu.resp[0] != 0x62){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
file = sc_file_new();
if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
*file_out = file;
file->path = *in_path;
for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){
int j, len=apdu.resp[i+1];
unsigned char type=apdu.resp[i], *d=apdu.resp+i+2;
switch (type) {
case 0x80:
case 0x81:
file->size=0;
for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j];
break;
case 0x82:
file->shareable = (d[0] & 0x40) ? 1 : 0;
file->ef_structure = d[0] & 7;
switch ((d[0]>>3) & 7) {
case 0: file->type = SC_FILE_TYPE_WORKING_EF; break;
case 7: file->type = SC_FILE_TYPE_DF; break;
default:
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
break;
case 0x83:
file->id = (d[0]<<8) | d[1];
break;
case 0x84:
memcpy(file->name, d, len);
file->namelen = len;
break;
case 0x86:
sc_file_set_sec_attr(file, d, len);
break;
default:
if (len>0) sc_file_set_prop_attr(file, d, len);
}
}
file->magic = SC_FILE_MAGIC;
parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len);
return 0;
}
static int tcos_list_files(sc_card_t *card, u8 *buf, size_t buflen)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE], p1;
int r, count = 0;
assert(card != NULL);
ctx = card->ctx;
for (p1=1; p1<=2; p1++) {
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xAA, p1, 0);
apdu.cla = 0x80;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1==0x6A && (apdu.sw2==0x82 || apdu.sw2==0x88)) continue;
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "List Dir failed");
if (apdu.resplen > buflen) return SC_ERROR_BUFFER_TOO_SMALL;
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"got %"SC_FORMAT_LEN_SIZE_T"u %s-FileIDs\n",
apdu.resplen / 2, p1 == 1 ? "DF" : "EF");
memcpy(buf, apdu.resp, apdu.resplen);
buf += apdu.resplen;
buflen -= apdu.resplen;
count += apdu.resplen;
}
return count;
}
static int tcos_delete_file(sc_card_t *card, const sc_path_t *path)
{
int r;
u8 sbuf[2];
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (path->type != SC_PATH_TYPE_FILE_ID && path->len != 2) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File type has to be SC_PATH_TYPE_FILE_ID\n");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
}
sbuf[0] = path->value[0];
sbuf[1] = path->value[1];
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.lc = 2;
apdu.datalen = 2;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static int tcos_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE], *p;
int r, default_key, tcos3;
tcos_data *data;
assert(card != NULL && env != NULL);
ctx = card->ctx;
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
data=(tcos_data *)card->drv_data;
if (se_num || (env->operation!=SC_SEC_OPERATION_DECIPHER && env->operation!=SC_SEC_OPERATION_SIGN)){
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
}
if(!(env->flags & SC_SEC_ENV_KEY_REF_PRESENT))
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"No Key-Reference in SecEnvironment\n");
else
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Key-Reference %02X (len=%"SC_FORMAT_LEN_SIZE_T"u)\n",
env->key_ref[0], env->key_ref_len);
/* Key-Reference 0x80 ?? */
default_key= !(env->flags & SC_SEC_ENV_KEY_REF_PRESENT) || (env->key_ref_len==1 && env->key_ref[0]==0x80);
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"TCOS3:%d PKCS1:%d\n", tcos3,
!!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1));
data->pad_flags = env->algorithm_flags;
data->next_sign = default_key;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, tcos3 ? 0x41 : 0xC1, 0xB8);
p = sbuf;
*p++=0x80; *p++=0x01; *p++=tcos3 ? 0x0A : 0x10;
if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) {
*p++ = (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) ? 0x83 : 0x84;
*p++ = env->key_ref_len;
memcpy(p, env->key_ref, env->key_ref_len);
p += env->key_ref_len;
}
apdu.data = sbuf;
apdu.lc = apdu.datalen = (p - sbuf);
r=sc_transmit_apdu(card, &apdu);
if (r) {
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"%s: APDU transmit failed", sc_strerror(r));
return r;
}
if (apdu.sw1==0x6A && (apdu.sw2==0x81 || apdu.sw2==0x88)) {
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Detected Signature-Only key\n");
if (env->operation==SC_SEC_OPERATION_SIGN && default_key) return SC_SUCCESS;
}
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int tcos_restore_security_env(sc_card_t *card, int se_num)
{
return 0;
}
static int tcos_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen)
{
size_t i, dlen=datalen;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
int tcos3, r;
assert(card != NULL && data != NULL && out != NULL);
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
if (datalen > 255) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
if(((tcos_data *)card->drv_data)->next_sign){
if(datalen>48){
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Data to be signed is too long (TCOS supports max. 48 bytes)\n");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x9E, 0x9A);
memcpy(sbuf, data, datalen);
dlen=datalen;
} else {
int keylen= tcos3 ? 256 : 128;
sc_format_apdu(card, &apdu, keylen>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86);
for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff;
sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00;
memcpy(sbuf+keylen-datalen+1, data, datalen);
dlen=keylen+1;
}
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = tcos3 ? 256 : 128;
apdu.data = sbuf;
apdu.lc = apdu.datalen = dlen;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (tcos3 && apdu.p1==0x80 && apdu.sw1==0x6A && apdu.sw2==0x87) {
int keylen=128;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86);
for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff;
sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00;
memcpy(sbuf+keylen-datalen+1, data, datalen);
dlen=keylen+1;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 128;
apdu.data = sbuf;
apdu.lc = apdu.datalen = dlen;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
}
if (apdu.sw1==0x90 && apdu.sw2==0x00) {
size_t len = apdu.resplen>outlen ? outlen : apdu.resplen;
memcpy(out, apdu.resp, len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
tcos_data *data;
int tcos3, r;
assert(card != NULL && crgram != NULL && out != NULL);
ctx = card->ctx;
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
data=(tcos_data *)card->drv_data;
SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_NORMAL);
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"TCOS3:%d PKCS1:%d\n",tcos3,
!!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1));
sc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = crgram_len;
apdu.data = sbuf;
apdu.lc = apdu.datalen = crgram_len+1;
sbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02);
memcpy(sbuf+1, crgram, crgram_len);
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1==0x90 && apdu.sw2==0x00) {
size_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen;
unsigned int offset=0;
if(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2){
offset=2; while(offset<len && apdu.resp[offset]!=0) ++offset;
offset=(offset<len-1) ? offset+1 : 0;
}
memcpy(out, apdu.resp+offset, len-offset);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len-offset);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
/* Issue the SET PERMANENT command. With ENABLE_NULLPIN set the
NullPIN method will be activated, otherwise the permanent operation
will be done on the active file. */
static int tcos_setperm(sc_card_t *card, int enable_nullpin)
{
int r;
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xEE, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.lc = 0;
apdu.datalen = 0;
apdu.data = NULL;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static int tcos_get_serialnr(sc_card_t *card, sc_serial_number_t *serial)
{
int r;
if (!serial)
return SC_ERROR_INVALID_ARGUMENTS;
/* see if we have cached serial number */
if (card->serialnr.len) {
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
card->serialnr.len = sizeof card->serialnr.value;
r = sc_parse_ef_gdo(card, card->serialnr.value, &card->serialnr.len, NULL, 0);
if (r < 0) {
card->serialnr.len = 0;
return r;
}
/* copy and return serial number */
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
static int tcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
switch (cmd) {
case SC_CARDCTL_TCOS_SETPERM:
return tcos_setperm(card, !!ptr);
case SC_CARDCTL_GET_SERIALNR:
return tcos_get_serialnr(card, (sc_serial_number_t *)ptr);
}
return SC_ERROR_NOT_SUPPORTED;
}
struct sc_card_driver * sc_get_tcos_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (iso_ops == NULL) iso_ops = iso_drv->ops;
tcos_ops = *iso_drv->ops;
tcos_ops.match_card = tcos_match_card;
tcos_ops.init = tcos_init;
tcos_ops.finish = tcos_finish;
tcos_ops.create_file = tcos_create_file;
tcos_ops.set_security_env = tcos_set_security_env;
tcos_ops.select_file = tcos_select_file;
tcos_ops.list_files = tcos_list_files;
tcos_ops.delete_file = tcos_delete_file;
tcos_ops.set_security_env = tcos_set_security_env;
tcos_ops.compute_signature = tcos_compute_signature;
tcos_ops.decipher = tcos_decipher;
tcos_ops.restore_security_env = tcos_restore_security_env;
tcos_ops.card_ctl = tcos_card_ctl;
return &tcos_drv;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_345_3 |
crossvul-cpp_data_good_346_6 | /*
* pkcs15-sc-hsm.c : Initialize PKCS#15 emulation
*
* Copyright (C) 2012 Andreas Schwier, CardContact, Minden, Germany
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "internal.h"
#include "pkcs15.h"
#include "asn1.h"
#include "common/compat_strlcpy.h"
#include "common/compat_strnlen.h"
#include "card-sc-hsm.h"
extern struct sc_aid sc_hsm_aid;
void sc_hsm_set_serialnr(sc_card_t *card, char *serial);
static struct ec_curve curves[] = {
{
{ (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x01", 8}, // secp192r1 aka prime192r1
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 24},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 24},
{ (unsigned char *) "\x64\x21\x05\x19\xE5\x9C\x80\xE7\x0F\xA7\xE9\xAB\x72\x24\x30\x49\xFE\xB8\xDE\xEC\xC1\x46\xB9\xB1", 24},
{ (unsigned char *) "\x04\x18\x8D\xA8\x0E\xB0\x30\x90\xF6\x7C\xBF\x20\xEB\x43\xA1\x88\x00\xF4\xFF\x0A\xFD\x82\xFF\x10\x12\x07\x19\x2B\x95\xFF\xC8\xDA\x78\x63\x10\x11\xED\x6B\x24\xCD\xD5\x73\xF9\x77\xA1\x1E\x79\x48\x11", 49},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x99\xDE\xF8\x36\x14\x6B\xC9\xB1\xB4\xD2\x28\x31", 24},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x07", 8}, // secp256r1 aka prime256r1
{ (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 32},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 32},
{ (unsigned char *) "\x5A\xC6\x35\xD8\xAA\x3A\x93\xE7\xB3\xEB\xBD\x55\x76\x98\x86\xBC\x65\x1D\x06\xB0\xCC\x53\xB0\xF6\x3B\xCE\x3C\x3E\x27\xD2\x60\x4B", 32},
{ (unsigned char *) "\x04\x6B\x17\xD1\xF2\xE1\x2C\x42\x47\xF8\xBC\xE6\xE5\x63\xA4\x40\xF2\x77\x03\x7D\x81\x2D\xEB\x33\xA0\xF4\xA1\x39\x45\xD8\x98\xC2\x96\x4F\xE3\x42\xE2\xFE\x1A\x7F\x9B\x8E\xE7\xEB\x4A\x7C\x0F\x9E\x16\x2B\xCE\x33\x57\x6B\x31\x5E\xCE\xCB\xB6\x40\x68\x37\xBF\x51\xF5", 65},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xBC\xE6\xFA\xAD\xA7\x17\x9E\x84\xF3\xB9\xCA\xC2\xFC\x63\x25\x51", 32},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x03", 9}, // brainpoolP192r1
{ (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x30\x93\xD1\x8D\xB7\x8F\xCE\x47\x6D\xE1\xA8\x62\x97", 24},
{ (unsigned char *) "\x6A\x91\x17\x40\x76\xB1\xE0\xE1\x9C\x39\xC0\x31\xFE\x86\x85\xC1\xCA\xE0\x40\xE5\xC6\x9A\x28\xEF", 24},
{ (unsigned char *) "\x46\x9A\x28\xEF\x7C\x28\xCC\xA3\xDC\x72\x1D\x04\x4F\x44\x96\xBC\xCA\x7E\xF4\x14\x6F\xBF\x25\xC9", 24},
{ (unsigned char *) "\x04\xC0\xA0\x64\x7E\xAA\xB6\xA4\x87\x53\xB0\x33\xC5\x6C\xB0\xF0\x90\x0A\x2F\x5C\x48\x53\x37\x5F\xD6\x14\xB6\x90\x86\x6A\xBD\x5B\xB8\x8B\x5F\x48\x28\xC1\x49\x00\x02\xE6\x77\x3F\xA2\xFA\x29\x9B\x8F", 49},
{ (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x2F\x9E\x9E\x91\x6B\x5B\xE8\xF1\x02\x9A\xC4\xAC\xC1", 24},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x05", 9}, // brainpoolP224r1
{ (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD1\xD7\x87\xB0\x9F\x07\x57\x97\xDA\x89\xF5\x7E\xC8\xC0\xFF", 28},
{ (unsigned char *) "\x68\xA5\xE6\x2C\xA9\xCE\x6C\x1C\x29\x98\x03\xA6\xC1\x53\x0B\x51\x4E\x18\x2A\xD8\xB0\x04\x2A\x59\xCA\xD2\x9F\x43", 28},
{ (unsigned char *) "\x25\x80\xF6\x3C\xCF\xE4\x41\x38\x87\x07\x13\xB1\xA9\x23\x69\xE3\x3E\x21\x35\xD2\x66\xDB\xB3\x72\x38\x6C\x40\x0B", 28},
{ (unsigned char *) "\x04\x0D\x90\x29\xAD\x2C\x7E\x5C\xF4\x34\x08\x23\xB2\xA8\x7D\xC6\x8C\x9E\x4C\xE3\x17\x4C\x1E\x6E\xFD\xEE\x12\xC0\x7D\x58\xAA\x56\xF7\x72\xC0\x72\x6F\x24\xC6\xB8\x9E\x4E\xCD\xAC\x24\x35\x4B\x9E\x99\xCA\xA3\xF6\xD3\x76\x14\x02\xCD", 57},
{ (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD0\xFB\x98\xD1\x16\xBC\x4B\x6D\xDE\xBC\xA3\xA5\xA7\x93\x9F", 28},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x07", 9}, // brainpoolP256r1
{ (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x72\x6E\x3B\xF6\x23\xD5\x26\x20\x28\x20\x13\x48\x1D\x1F\x6E\x53\x77", 32},
{ (unsigned char *) "\x7D\x5A\x09\x75\xFC\x2C\x30\x57\xEE\xF6\x75\x30\x41\x7A\xFF\xE7\xFB\x80\x55\xC1\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9", 32},
{ (unsigned char *) "\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9\xBB\xD7\x7C\xBF\x95\x84\x16\x29\x5C\xF7\xE1\xCE\x6B\xCC\xDC\x18\xFF\x8C\x07\xB6", 32},
{ (unsigned char *) "\x04\x8B\xD2\xAE\xB9\xCB\x7E\x57\xCB\x2C\x4B\x48\x2F\xFC\x81\xB7\xAF\xB9\xDE\x27\xE1\xE3\xBD\x23\xC2\x3A\x44\x53\xBD\x9A\xCE\x32\x62\x54\x7E\xF8\x35\xC3\xDA\xC4\xFD\x97\xF8\x46\x1A\x14\x61\x1D\xC9\xC2\x77\x45\x13\x2D\xED\x8E\x54\x5C\x1D\x54\xC7\x2F\x04\x69\x97", 65},
{ (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x71\x8C\x39\x7A\xA3\xB5\x61\xA6\xF7\x90\x1E\x0E\x82\x97\x48\x56\xA7", 32},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x09", 9}, // brainpoolP320r1
{ (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA6\xF6\xF4\x0D\xEF\x4F\x92\xB9\xEC\x78\x93\xEC\x28\xFC\xD4\x12\xB1\xF1\xB3\x2E\x27", 40},
{ (unsigned char *) "\x3E\xE3\x0B\x56\x8F\xBA\xB0\xF8\x83\xCC\xEB\xD4\x6D\x3F\x3B\xB8\xA2\xA7\x35\x13\xF5\xEB\x79\xDA\x66\x19\x0E\xB0\x85\xFF\xA9\xF4\x92\xF3\x75\xA9\x7D\x86\x0E\xB4", 40},
{ (unsigned char *) "\x52\x08\x83\x94\x9D\xFD\xBC\x42\xD3\xAD\x19\x86\x40\x68\x8A\x6F\xE1\x3F\x41\x34\x95\x54\xB4\x9A\xCC\x31\xDC\xCD\x88\x45\x39\x81\x6F\x5E\xB4\xAC\x8F\xB1\xF1\xA6", 40},
{ (unsigned char *) "\x04\x43\xBD\x7E\x9A\xFB\x53\xD8\xB8\x52\x89\xBC\xC4\x8E\xE5\xBF\xE6\xF2\x01\x37\xD1\x0A\x08\x7E\xB6\xE7\x87\x1E\x2A\x10\xA5\x99\xC7\x10\xAF\x8D\x0D\x39\xE2\x06\x11\x14\xFD\xD0\x55\x45\xEC\x1C\xC8\xAB\x40\x93\x24\x7F\x77\x27\x5E\x07\x43\xFF\xED\x11\x71\x82\xEA\xA9\xC7\x78\x77\xAA\xAC\x6A\xC7\xD3\x52\x45\xD1\x69\x2E\x8E\xE1", 81},
{ (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA5\xB6\x8F\x12\xA3\x2D\x48\x2E\xC7\xEE\x86\x58\xE9\x86\x91\x55\x5B\x44\xC5\x93\x11", 40},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x81\x04\x00\x1F", 5}, // secp192k1
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xEE\x37", 24},
{ (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 24},
{ (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03", 24},
{ (unsigned char *) "\x04\xDB\x4F\xF1\x0E\xC0\x57\xE9\xAE\x26\xB0\x7D\x02\x80\xB7\xF4\x34\x1D\xA5\xD1\xB1\xEA\xE0\x6C\x7D\x9B\x2F\x2F\x6D\x9C\x56\x28\xA7\x84\x41\x63\xD0\x15\xBE\x86\x34\x40\x82\xAA\x88\xD9\x5E\x2F\x9D", 49},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\x26\xF2\xFC\x17\x0F\x69\x46\x6A\x74\xDE\xFD\x8D", 24},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x81\x04\x00\x0A", 5}, // secp256k1
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFC\x2F", 32},
{ (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 32},
{ (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x07", 32},
{ (unsigned char *) "\x04\x79\xBE\x66\x7E\xF9\xDC\xBB\xAC\x55\xA0\x62\x95\xCE\x87\x0B\x07\x02\x9B\xFC\xDB\x2D\xCE\x28\xD9\x59\xF2\x81\x5B\x16\xF8\x17\x98\x48\x3A\xDA\x77\x26\xA3\xC4\x65\x5D\xA4\xFB\xFC\x0E\x11\x08\xA8\xFD\x17\xB4\x48\xA6\x85\x54\x19\x9C\x47\xD0\x8F\xFB\x10\xD4\xB8", 65},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xBA\xAE\xDC\xE6\xAF\x48\xA0\x3B\xBF\xD2\x5E\x8C\xD0\x36\x41\x41", 32},
{ (unsigned char *) "\x01", 1}
},
{
{ NULL, 0},
{ NULL, 0},
{ NULL, 0},
{ NULL, 0},
{ NULL, 0},
{ NULL, 0},
{ NULL, 0}
}
};
#define C_ASN1_CVC_PUBKEY_SIZE 10
static const struct sc_asn1_entry c_asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE] = {
{ "publicKeyOID", SC_ASN1_OBJECT, SC_ASN1_UNI | SC_ASN1_OBJECT, 0, NULL, NULL },
{ "primeOrModulus", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 1, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "coefficientAorExponent", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 2, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "coefficientB", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 3, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "basePointG", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 4, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "order", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 5, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "publicPoint", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 6, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "cofactor", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 7, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "modulusSize", SC_ASN1_INTEGER, SC_ASN1_UNI | SC_ASN1_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_CVC_BODY_SIZE 5
static const struct sc_asn1_entry c_asn1_cvc_body[C_ASN1_CVC_BODY_SIZE] = {
{ "certificateProfileIdentifier", SC_ASN1_INTEGER, SC_ASN1_APP | 0x1F29, 0, NULL, NULL },
{ "certificationAuthorityReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL },
{ "publicKey", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F49, 0, NULL, NULL },
{ "certificateHolderReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 0x1F20, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_CVCERT_SIZE 3
static const struct sc_asn1_entry c_asn1_cvcert[C_ASN1_CVCERT_SIZE] = {
{ "certificateBody", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F4E, 0, NULL, NULL },
{ "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_CVC_SIZE 2
static const struct sc_asn1_entry c_asn1_cvc[C_ASN1_CVC_SIZE] = {
{ "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_AUTHREQ_SIZE 4
static const struct sc_asn1_entry c_asn1_authreq[C_ASN1_AUTHREQ_SIZE] = {
{ "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL },
{ "outerCAR", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL },
{ "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_REQ_SIZE 2
static const struct sc_asn1_entry c_asn1_req[C_ASN1_REQ_SIZE] = {
{ "authenticatedrequest", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 7, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static int read_file(sc_pkcs15_card_t * p15card, u8 fid[2],
u8 *efbin, size_t *len, int optional)
{
sc_path_t path;
int r;
sc_path_set(&path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0);
/* look this up with our AID */
path.aid = sc_hsm_aid;
/* we don't have a pre-known size of the file */
path.count = -1;
if (!p15card->opts.use_file_cache || !efbin
|| SC_SUCCESS != sc_pkcs15_read_cached_file(p15card, &path, &efbin, len)) {
/* avoid re-selection of SC-HSM */
path.aid.len = 0;
r = sc_select_file(p15card->card, &path, NULL);
if (r < 0) {
sc_log(p15card->card->ctx, "Could not select EF");
} else {
r = sc_read_binary(p15card->card, 0, efbin, *len, 0);
}
if (r < 0) {
sc_log(p15card->card->ctx, "Could not read EF");
if (!optional) {
return r;
}
/* optional files are saved as empty files to avoid card
* transactions. Parsing the file's data will reveal that they were
* missing. */
*len = 0;
} else {
*len = r;
}
if (p15card->opts.use_file_cache) {
/* save this with our AID */
path.aid = sc_hsm_aid;
sc_pkcs15_cache_file(p15card, &path, efbin, *len);
}
}
return SC_SUCCESS;
}
/*
* Decode a card verifiable certificate as defined in TR-03110.
*/
int sc_pkcs15emu_sc_hsm_decode_cvc(sc_pkcs15_card_t * p15card,
const u8 ** buf, size_t *buflen,
sc_cvc_t *cvc)
{
sc_card_t *card = p15card->card;
struct sc_asn1_entry asn1_req[C_ASN1_REQ_SIZE];
struct sc_asn1_entry asn1_authreq[C_ASN1_AUTHREQ_SIZE];
struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE];
struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE];
struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE];
struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE];
unsigned int cla,tag;
size_t taglen;
size_t lenchr = sizeof(cvc->chr);
size_t lencar = sizeof(cvc->car);
size_t lenoutercar = sizeof(cvc->outer_car);
const u8 *tbuf;
int r;
memset(cvc, 0, sizeof(*cvc));
sc_copy_asn1_entry(c_asn1_req, asn1_req);
sc_copy_asn1_entry(c_asn1_authreq, asn1_authreq);
sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc);
sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert);
sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body);
sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey);
sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 1, &cvc->primeOrModulus, &cvc->primeOrModuluslen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 2, &cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 3, &cvc->coefficientB, &cvc->coefficientBlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 4, &cvc->basePointG, &cvc->basePointGlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 5, &cvc->order, &cvc->orderlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 6, &cvc->publicPoint, &cvc->publicPointlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 7, &cvc->cofactor, &cvc->cofactorlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 0);
sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 0);
sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 0);
sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 0);
sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 0);
sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 0);
sc_format_asn1_entry(asn1_cvcert + 1, &cvc->signature, &cvc->signatureLen, 0);
sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 0);
sc_format_asn1_entry(asn1_authreq , &asn1_cvcert, NULL, 0);
sc_format_asn1_entry(asn1_authreq + 1, &cvc->outer_car, &lenoutercar, 0);
sc_format_asn1_entry(asn1_authreq + 2, &cvc->outerSignature, &cvc->outerSignatureLen, 0);
sc_format_asn1_entry(asn1_req , &asn1_authreq, NULL, 0);
/* sc_asn1_print_tags(*buf, *buflen); */
tbuf = *buf;
r = sc_asn1_read_tag(&tbuf, *buflen, &cla, &tag, &taglen);
LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate");
/* Determine if we deal with an authenticated request, plain request or certificate */
if ((cla == (SC_ASN1_TAG_APPLICATION|SC_ASN1_TAG_CONSTRUCTED)) && (tag == 7)) {
r = sc_asn1_decode(card->ctx, asn1_req, *buf, *buflen, buf, buflen);
} else {
r = sc_asn1_decode(card->ctx, asn1_cvc, *buf, *buflen, buf, buflen);
}
LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
/*
* Encode a card verifiable certificate as defined in TR-03110.
*/
int sc_pkcs15emu_sc_hsm_encode_cvc(sc_pkcs15_card_t * p15card,
sc_cvc_t *cvc,
u8 ** buf, size_t *buflen)
{
sc_card_t *card = p15card->card;
struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE];
struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE];
struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE];
struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE];
size_t lenchr;
size_t lencar;
int r;
sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc);
sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert);
sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body);
sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey);
asn1_cvc_pubkey[1].flags = SC_ASN1_OPTIONAL;
asn1_cvcert[1].flags = SC_ASN1_OPTIONAL;
sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 1);
if (cvc->primeOrModulus && (cvc->primeOrModuluslen > 0)) {
sc_format_asn1_entry(asn1_cvc_pubkey + 1, cvc->primeOrModulus, &cvc->primeOrModuluslen, 1);
}
sc_format_asn1_entry(asn1_cvc_pubkey + 2, cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 1);
if (cvc->coefficientB && (cvc->coefficientBlen > 0)) {
sc_format_asn1_entry(asn1_cvc_pubkey + 3, cvc->coefficientB, &cvc->coefficientBlen, 1);
sc_format_asn1_entry(asn1_cvc_pubkey + 4, cvc->basePointG, &cvc->basePointGlen, 1);
sc_format_asn1_entry(asn1_cvc_pubkey + 5, cvc->order, &cvc->orderlen, 1);
if (cvc->publicPoint && (cvc->publicPointlen > 0)) {
sc_format_asn1_entry(asn1_cvc_pubkey + 6, cvc->publicPoint, &cvc->publicPointlen, 1);
}
sc_format_asn1_entry(asn1_cvc_pubkey + 7, cvc->cofactor, &cvc->cofactorlen, 1);
}
if (cvc->modulusSize > 0) {
sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 1);
}
sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 1);
lencar = strnlen(cvc->car, sizeof cvc->car);
sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 1);
sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 1);
lenchr = strnlen(cvc->chr, sizeof cvc->chr);
sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 1);
sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 1);
if (cvc->signature && (cvc->signatureLen > 0)) {
sc_format_asn1_entry(asn1_cvcert + 1, cvc->signature, &cvc->signatureLen, 1);
}
sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 1);
r = sc_asn1_encode(card->ctx, asn1_cvc, buf, buflen);
LOG_TEST_RET(card->ctx, r, "Could not encode card verifiable certificate");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
int sc_pkcs15emu_sc_hsm_get_curve(struct ec_curve **curve, u8 *oid, size_t oidlen)
{
int i;
for (i = 0; curves[i].oid.value; i++) {
if ((curves[i].oid.len == oidlen) && !memcmp(curves[i].oid.value, oid, oidlen)) {
*curve = &curves[i];
return SC_SUCCESS;
}
}
return SC_ERROR_INVALID_DATA;
}
int sc_pkcs15emu_sc_hsm_get_curve_oid(sc_cvc_t *cvc, const struct sc_lv_data **oid)
{
int i;
for (i = 0; curves[i].oid.value; i++) {
if ((curves[i].prime.len == cvc->primeOrModuluslen) && !memcmp(curves[i].prime.value, cvc->primeOrModulus, cvc->primeOrModuluslen)) {
*oid = &curves[i].oid;
return SC_SUCCESS;
}
}
return SC_ERROR_INVALID_DATA;
}
static int sc_pkcs15emu_sc_hsm_get_rsa_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey)
{
pubkey->algorithm = SC_ALGORITHM_RSA;
pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id));
if (!pubkey->alg_id)
return SC_ERROR_OUT_OF_MEMORY;
pubkey->alg_id->algorithm = SC_ALGORITHM_RSA;
pubkey->u.rsa.modulus.len = cvc->primeOrModuluslen;
pubkey->u.rsa.modulus.data = malloc(pubkey->u.rsa.modulus.len);
pubkey->u.rsa.exponent.len = cvc->coefficientAorExponentlen;
pubkey->u.rsa.exponent.data = malloc(pubkey->u.rsa.exponent.len);
if (!pubkey->u.rsa.modulus.data || !pubkey->u.rsa.exponent.data)
return SC_ERROR_OUT_OF_MEMORY;
memcpy(pubkey->u.rsa.exponent.data, cvc->coefficientAorExponent, pubkey->u.rsa.exponent.len);
memcpy(pubkey->u.rsa.modulus.data, cvc->primeOrModulus, pubkey->u.rsa.modulus.len);
return SC_SUCCESS;
}
static int sc_pkcs15emu_sc_hsm_get_ec_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey)
{
struct sc_ec_parameters *ecp;
const struct sc_lv_data *oid;
int r;
pubkey->algorithm = SC_ALGORITHM_EC;
r = sc_pkcs15emu_sc_hsm_get_curve_oid(cvc, &oid);
if (r != SC_SUCCESS)
return r;
ecp = calloc(1, sizeof(struct sc_ec_parameters));
if (!ecp)
return SC_ERROR_OUT_OF_MEMORY;
ecp->der.len = oid->len + 2;
ecp->der.value = calloc(ecp->der.len, 1);
if (!ecp->der.value) {
free(ecp);
return SC_ERROR_OUT_OF_MEMORY;
}
*(ecp->der.value + 0) = 0x06;
*(ecp->der.value + 1) = (u8)oid->len;
memcpy(ecp->der.value + 2, oid->value, oid->len);
ecp->type = 1; // Named curve
pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id));
if (!pubkey->alg_id) {
free(ecp->der.value);
free(ecp);
return SC_ERROR_OUT_OF_MEMORY;
}
pubkey->alg_id->algorithm = SC_ALGORITHM_EC;
pubkey->alg_id->params = ecp;
pubkey->u.ec.ecpointQ.value = malloc(cvc->publicPointlen);
if (!pubkey->u.ec.ecpointQ.value)
return SC_ERROR_OUT_OF_MEMORY;
memcpy(pubkey->u.ec.ecpointQ.value, cvc->publicPoint, cvc->publicPointlen);
pubkey->u.ec.ecpointQ.len = cvc->publicPointlen;
pubkey->u.ec.params.der.value = malloc(ecp->der.len);
if (!pubkey->u.ec.params.der.value)
return SC_ERROR_OUT_OF_MEMORY;
memcpy(pubkey->u.ec.params.der.value, ecp->der.value, ecp->der.len);
pubkey->u.ec.params.der.len = ecp->der.len;
/* FIXME: check return value? */
sc_pkcs15_fix_ec_parameters(ctx, &pubkey->u.ec.params);
return SC_SUCCESS;
}
int sc_pkcs15emu_sc_hsm_get_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey)
{
if (cvc->publicPoint && cvc->publicPointlen) {
return sc_pkcs15emu_sc_hsm_get_ec_public_key(ctx, cvc, pubkey);
} else {
return sc_pkcs15emu_sc_hsm_get_rsa_public_key(ctx, cvc, pubkey);
}
}
void sc_pkcs15emu_sc_hsm_free_cvc(sc_cvc_t *cvc)
{
if (cvc->signature) {
free(cvc->signature);
cvc->signature = NULL;
}
if (cvc->primeOrModulus) {
free(cvc->primeOrModulus);
cvc->primeOrModulus = NULL;
}
if (cvc->coefficientAorExponent) {
free(cvc->coefficientAorExponent);
cvc->coefficientAorExponent = NULL;
}
if (cvc->coefficientB) {
free(cvc->coefficientB);
cvc->coefficientB = NULL;
}
if (cvc->basePointG) {
free(cvc->basePointG);
cvc->basePointG = NULL;
}
if (cvc->order) {
free(cvc->order);
cvc->order = NULL;
}
if (cvc->publicPoint) {
free(cvc->publicPoint);
cvc->publicPoint = NULL;
}
if (cvc->cofactor) {
free(cvc->cofactor);
cvc->cofactor = NULL;
}
}
static int sc_pkcs15emu_sc_hsm_add_pubkey(sc_pkcs15_card_t *p15card, u8 *efbin, size_t len, sc_pkcs15_prkey_info_t *key_info, char *label)
{
struct sc_context *ctx = p15card->card->ctx;
sc_card_t *card = p15card->card;
sc_pkcs15_pubkey_info_t pubkey_info;
sc_pkcs15_object_t pubkey_obj;
struct sc_pkcs15_pubkey pubkey;
sc_cvc_t cvc;
u8 *cvcpo;
int r;
cvcpo = efbin;
memset(&cvc, 0, sizeof(cvc));
r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&cvcpo, &len, &cvc);
LOG_TEST_RET(ctx, r, "Could decode certificate signing request");
memset(&pubkey, 0, sizeof(pubkey));
r = sc_pkcs15emu_sc_hsm_get_public_key(ctx, &cvc, &pubkey);
LOG_TEST_RET(card->ctx, r, "Could not extract public key");
memset(&pubkey_info, 0, sizeof(pubkey_info));
memset(&pubkey_obj, 0, sizeof(pubkey_obj));
r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_obj.content.value, &pubkey_obj.content.len);
LOG_TEST_RET(ctx, r, "Could not encode public key");
r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_info.direct.raw.value, &pubkey_info.direct.raw.len);
LOG_TEST_RET(ctx, r, "Could not encode public key");
r = sc_pkcs15_encode_pubkey_as_spki(ctx, &pubkey, &pubkey_info.direct.spki.value, &pubkey_info.direct.spki.len);
LOG_TEST_RET(ctx, r, "Could not encode public key");
pubkey_info.id = key_info->id;
strlcpy(pubkey_obj.label, label, sizeof(pubkey_obj.label));
if (pubkey.algorithm == SC_ALGORITHM_RSA) {
pubkey_info.modulus_length = pubkey.u.rsa.modulus.len << 3;
pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_ENCRYPT|SC_PKCS15_PRKEY_USAGE_VERIFY|SC_PKCS15_PRKEY_USAGE_WRAP;
r = sc_pkcs15emu_add_rsa_pubkey(p15card, &pubkey_obj, &pubkey_info);
} else {
/* TODO fix if support of non multiple of 8 curves are added */
pubkey_info.field_length = cvc.primeOrModuluslen << 3;
pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_VERIFY;
r = sc_pkcs15emu_add_ec_pubkey(p15card, &pubkey_obj, &pubkey_info);
}
LOG_TEST_RET(ctx, r, "Could not add public key");
sc_pkcs15emu_sc_hsm_free_cvc(&cvc);
sc_pkcs15_erase_pubkey(&pubkey);
return SC_SUCCESS;
}
/*
* Add a key and the key description in PKCS#15 format to the framework
*/
static int sc_pkcs15emu_sc_hsm_add_prkd(sc_pkcs15_card_t * p15card, u8 keyid) {
sc_card_t *card = p15card->card;
sc_pkcs15_cert_info_t cert_info;
sc_pkcs15_object_t cert_obj;
struct sc_pkcs15_object prkd;
sc_pkcs15_prkey_info_t *key_info;
u8 fid[2];
/* enough to hold a complete certificate */
u8 efbin[4096];
u8 *ptr;
size_t len;
int r;
fid[0] = PRKD_PREFIX;
fid[1] = keyid;
/* Try to select a related EF containing the PKCS#15 description of the key */
len = sizeof efbin;
r = read_file(p15card, fid, efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD");
ptr = efbin;
memset(&prkd, 0, sizeof(prkd));
r = sc_pkcs15_decode_prkdf_entry(p15card, &prkd, (const u8 **)&ptr, &len);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD");
/* All keys require user PIN authentication */
prkd.auth_id.len = 1;
prkd.auth_id.value[0] = 1;
/*
* Set private key flag as all keys are private anyway
*/
prkd.flags |= SC_PKCS15_CO_FLAG_PRIVATE;
key_info = (sc_pkcs15_prkey_info_t *)prkd.data;
key_info->key_reference = keyid;
key_info->path.aid.len = 0;
if (prkd.type == SC_PKCS15_TYPE_PRKEY_RSA) {
r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkd, key_info);
} else {
r = sc_pkcs15emu_add_ec_prkey(p15card, &prkd, key_info);
}
LOG_TEST_RET(card->ctx, r, "Could not add private key to framework");
/* Check if we also have a certificate for the private key */
fid[0] = EE_CERTIFICATE_PREFIX;
len = sizeof efbin;
r = read_file(p15card, fid, efbin, &len, 0);
LOG_TEST_RET(card->ctx, r, "Could not read EF");
if (efbin[0] == 0x67) { /* Decode CSR and create public key object */
sc_pkcs15emu_sc_hsm_add_pubkey(p15card, efbin, len, key_info, prkd.label);
free(key_info);
return SC_SUCCESS; /* Ignore any errors */
}
if (efbin[0] != 0x30) {
free(key_info);
return SC_SUCCESS;
}
memset(&cert_info, 0, sizeof(cert_info));
memset(&cert_obj, 0, sizeof(cert_obj));
cert_info.id = key_info->id;
sc_path_set(&cert_info.path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0);
cert_info.path.count = -1;
if (p15card->opts.use_file_cache) {
/* look this up with our AID, which should already be cached from the
* call to `read_file`. This may have the side effect that OpenSC's
* caching layer re-selects our applet *if the cached file cannot be
* found/used* and we may loose the authentication status. We assume
* that caching works perfectly without this side effect. */
cert_info.path.aid = sc_hsm_aid;
}
strlcpy(cert_obj.label, prkd.label, sizeof(cert_obj.label));
r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info);
free(key_info);
LOG_TEST_RET(card->ctx, r, "Could not add certificate");
return SC_SUCCESS;
}
/*
* Add a data object and description in PKCS#15 format to the framework
*/
static int sc_pkcs15emu_sc_hsm_add_dcod(sc_pkcs15_card_t * p15card, u8 id) {
sc_card_t *card = p15card->card;
sc_pkcs15_data_info_t *data_info;
sc_pkcs15_object_t data_obj;
u8 fid[2];
u8 efbin[512];
const u8 *ptr;
size_t len;
int r;
fid[0] = DCOD_PREFIX;
fid[1] = id;
/* Try to select a related EF containing the PKCS#15 description of the data */
len = sizeof efbin;
r = read_file(p15card, fid, efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD");
ptr = efbin;
memset(&data_obj, 0, sizeof(data_obj));
r = sc_pkcs15_decode_dodf_entry(p15card, &data_obj, &ptr, &len);
LOG_TEST_RET(card->ctx, r, "Could not decode optional EF.DCOD");
data_info = (sc_pkcs15_data_info_t *)data_obj.data;
r = sc_pkcs15emu_add_data_object(p15card, &data_obj, data_info);
LOG_TEST_RET(card->ctx, r, "Could not add data object to framework");
return SC_SUCCESS;
}
/*
* Add a unrelated certificate object and description in PKCS#15 format to the framework
*/
static int sc_pkcs15emu_sc_hsm_add_cd(sc_pkcs15_card_t * p15card, u8 id) {
sc_card_t *card = p15card->card;
sc_pkcs15_cert_info_t *cert_info;
sc_pkcs15_object_t obj;
u8 fid[2];
u8 efbin[512];
const u8 *ptr;
size_t len;
int r;
fid[0] = CD_PREFIX;
fid[1] = id;
/* Try to select a related EF containing the PKCS#15 description of the data */
len = sizeof efbin;
r = read_file(p15card, fid, efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD");
ptr = efbin;
memset(&obj, 0, sizeof(obj));
r = sc_pkcs15_decode_cdf_entry(p15card, &obj, &ptr, &len);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.CDOD");
cert_info = (sc_pkcs15_cert_info_t *)obj.data;
r = sc_pkcs15emu_add_x509_cert(p15card, &obj, cert_info);
LOG_TEST_RET(card->ctx, r, "Could not add data object to framework");
return SC_SUCCESS;
}
static int sc_pkcs15emu_sc_hsm_read_tokeninfo (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
int r;
u8 efbin[512];
size_t len;
LOG_FUNC_CALLED(card->ctx);
/* Read token info */
len = sizeof efbin;
r = read_file(p15card, (u8 *) "\x2F\x03", efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo");
r = sc_pkcs15_parse_tokeninfo(card->ctx, p15card->tokeninfo, efbin, len);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
/*
* Initialize PKCS#15 emulation with user PIN, private keys, certificate and data objects
*
*/
static int sc_pkcs15emu_sc_hsm_init (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
sc_hsm_private_data_t *priv = (sc_hsm_private_data_t *) card->drv_data;
sc_file_t *file = NULL;
sc_path_t path;
u8 filelist[MAX_EXT_APDU_LENGTH];
int filelistlength;
int r, i;
sc_cvc_t devcert;
struct sc_app_info *appinfo;
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
struct sc_pin_cmd_data pindata;
u8 efbin[1024];
u8 *ptr;
size_t len;
LOG_FUNC_CALLED(card->ctx);
appinfo = calloc(1, sizeof(struct sc_app_info));
if (appinfo == NULL) {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
appinfo->aid = sc_hsm_aid;
appinfo->ddo.aid = sc_hsm_aid;
p15card->app = appinfo;
sc_path_set(&path, SC_PATH_TYPE_DF_NAME, sc_hsm_aid.value, sc_hsm_aid.len, 0, 0);
r = sc_select_file(card, &path, &file);
LOG_TEST_RET(card->ctx, r, "Could not select SmartCard-HSM application");
p15card->card->version.hw_major = 24; /* JCOP 2.4.1r3 */
p15card->card->version.hw_minor = 13;
if (file && file->prop_attr && file->prop_attr_len >= 2) {
p15card->card->version.fw_major = file->prop_attr[file->prop_attr_len - 2];
p15card->card->version.fw_minor = file->prop_attr[file->prop_attr_len - 1];
}
sc_file_free(file);
/* Read device certificate to determine serial number */
if (priv->EF_C_DevAut && priv->EF_C_DevAut_len) {
ptr = priv->EF_C_DevAut;
len = priv->EF_C_DevAut_len;
} else {
len = sizeof efbin;
r = read_file(p15card, (u8 *) "\x2F\x02", efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.C_DevAut");
if (len > 0) {
/* save EF_C_DevAut for further use */
ptr = realloc(priv->EF_C_DevAut, len);
if (ptr) {
memcpy(ptr, efbin, len);
priv->EF_C_DevAut = ptr;
priv->EF_C_DevAut_len = len;
}
}
ptr = efbin;
}
memset(&devcert, 0 ,sizeof(devcert));
r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&ptr, &len, &devcert);
LOG_TEST_RET(card->ctx, r, "Could not decode EF.C_DevAut");
sc_pkcs15emu_sc_hsm_read_tokeninfo(p15card);
if (p15card->tokeninfo->label == NULL) {
if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID
|| p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) {
p15card->tokeninfo->label = strdup("GoID");
} else {
p15card->tokeninfo->label = strdup("SmartCard-HSM");
}
if (p15card->tokeninfo->label == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
if ((p15card->tokeninfo->manufacturer_id != NULL) && !strcmp("(unknown)", p15card->tokeninfo->manufacturer_id)) {
free(p15card->tokeninfo->manufacturer_id);
p15card->tokeninfo->manufacturer_id = NULL;
}
if (p15card->tokeninfo->manufacturer_id == NULL) {
if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID
|| p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) {
p15card->tokeninfo->manufacturer_id = strdup("Bundesdruckerei GmbH");
} else {
p15card->tokeninfo->manufacturer_id = strdup("www.CardContact.de");
}
if (p15card->tokeninfo->manufacturer_id == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
appinfo->label = strdup(p15card->tokeninfo->label);
if (appinfo->label == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
len = strnlen(devcert.chr, sizeof devcert.chr); /* Strip last 5 digit sequence number from CHR */
assert(len >= 8);
len -= 5;
p15card->tokeninfo->serial_number = calloc(len + 1, 1);
if (p15card->tokeninfo->serial_number == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(p15card->tokeninfo->serial_number, devcert.chr, len);
*(p15card->tokeninfo->serial_number + len) = 0;
sc_hsm_set_serialnr(card, p15card->tokeninfo->serial_number);
sc_pkcs15emu_sc_hsm_free_cvc(&devcert);
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = 1;
pin_info.path.aid = sc_hsm_aid;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = 0x81;
pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_EXCHANGE_REF_DATA;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = 6;
pin_info.attrs.pin.stored_length = 0;
pin_info.attrs.pin.max_length = 15;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = 3;
pin_info.max_tries = 3;
pin_obj.auth_id.len = 1;
pin_obj.auth_id.value[0] = 2;
strlcpy(pin_obj.label, "UserPIN", sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE;
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
LOG_FUNC_RETURN(card->ctx, r);
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = 2;
pin_info.path.aid = sc_hsm_aid;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = 0x88;
pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED|SC_PKCS15_PIN_FLAG_SO_PIN;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_BCD;
pin_info.attrs.pin.min_length = 16;
pin_info.attrs.pin.stored_length = 0;
pin_info.attrs.pin.max_length = 16;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = 15;
pin_info.max_tries = 15;
strlcpy(pin_obj.label, "SOPIN", sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
LOG_FUNC_RETURN(card->ctx, r);
if (card->type == SC_CARD_TYPE_SC_HSM_SOC
|| card->type == SC_CARD_TYPE_SC_HSM_GOID) {
/* SC-HSM of this type always has a PIN-Pad */
r = SC_SUCCESS;
} else {
memset(&pindata, 0, sizeof(pindata));
pindata.cmd = SC_PIN_CMD_GET_INFO;
pindata.pin_type = SC_AC_CHV;
pindata.pin_reference = 0x85;
r = sc_pin_cmd(card, &pindata, NULL);
}
if (r == SC_ERROR_DATA_OBJECT_NOT_FOUND) {
memset(&pindata, 0, sizeof(pindata));
pindata.cmd = SC_PIN_CMD_GET_INFO;
pindata.pin_type = SC_AC_CHV;
pindata.pin_reference = 0x86;
r = sc_pin_cmd(card, &pindata, NULL);
}
if ((r != SC_ERROR_DATA_OBJECT_NOT_FOUND) && (r != SC_ERROR_INCORRECT_PARAMETERS))
card->caps |= SC_CARD_CAP_PROTECTED_AUTHENTICATION_PATH;
filelistlength = sc_list_files(card, filelist, sizeof(filelist));
LOG_TEST_RET(card->ctx, filelistlength, "Could not enumerate file and key identifier");
for (i = 0; i < filelistlength; i += 2) {
switch(filelist[i]) {
case KEY_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_prkd(p15card, filelist[i + 1]);
break;
case DCOD_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_dcod(p15card, filelist[i + 1]);
break;
case CD_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_cd(p15card, filelist[i + 1]);
break;
}
if (r != SC_SUCCESS) {
sc_log(card->ctx, "Error %d adding elements to framework", r);
}
}
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
int sc_pkcs15emu_sc_hsm_init_ex(sc_pkcs15_card_t *p15card,
struct sc_aid *aid,
sc_pkcs15emu_opt_t *opts)
{
if (opts && (opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)) {
return sc_pkcs15emu_sc_hsm_init(p15card);
} else {
if (p15card->card->type != SC_CARD_TYPE_SC_HSM
&& p15card->card->type != SC_CARD_TYPE_SC_HSM_SOC
&& p15card->card->type != SC_CARD_TYPE_SC_HSM_GOID) {
return SC_ERROR_WRONG_CARD;
}
return sc_pkcs15emu_sc_hsm_init(p15card);
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_346_6 |
crossvul-cpp_data_bad_1064_0 | /*
* asn1.c: ASN.1 decoding functions (DER)
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <assert.h>
#include <ctype.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "internal.h"
#include "asn1.h"
static int asn1_decode(sc_context_t *ctx, struct sc_asn1_entry *asn1,
const u8 *in, size_t len, const u8 **newp, size_t *len_left,
int choice, int depth);
static int asn1_encode(sc_context_t *ctx, const struct sc_asn1_entry *asn1,
u8 **ptr, size_t *size, int depth);
static int asn1_write_element(sc_context_t *ctx, unsigned int tag,
const u8 * data, size_t datalen, u8 ** out, size_t * outlen);
static const char *tag2str(unsigned int tag)
{
static const char *tags[] = {
"EOC", "BOOLEAN", "INTEGER", "BIT STRING", "OCTET STRING", /* 0-4 */
"NULL", "OBJECT IDENTIFIER", "OBJECT DESCRIPTOR", "EXTERNAL", "REAL", /* 5-9 */
"ENUMERATED", "Universal 11", "UTF8String", "Universal 13", /* 10-13 */
"Universal 14", "Universal 15", "SEQUENCE", "SET", /* 15-17 */
"NumericString", "PrintableString", "T61String", /* 18-20 */
"VideotexString", "IA5String", "UTCTIME", "GENERALIZEDTIME", /* 21-24 */
"GraphicString", "VisibleString", "GeneralString", /* 25-27 */
"UniversalString", "Universal 29", "BMPString" /* 28-30 */
};
if (tag > 30)
return "(unknown)";
return tags[tag];
}
int sc_asn1_read_tag(const u8 ** buf, size_t buflen, unsigned int *cla_out,
unsigned int *tag_out, size_t *taglen)
{
const u8 *p = *buf;
size_t left = buflen, len;
unsigned int cla, tag, i;
*buf = NULL;
if (left == 0)
return SC_ERROR_INVALID_ASN1_OBJECT;
if (*p == 0xff || *p == 0) {
/* end of data reached */
*taglen = 0;
*tag_out = SC_ASN1_TAG_EOC;
return SC_SUCCESS;
}
/* parse tag byte(s)
* Resulted tag is presented by integer that has not to be
* confused with the 'tag number' part of ASN.1 tag.
*/
cla = (*p & SC_ASN1_TAG_CLASS) | (*p & SC_ASN1_TAG_CONSTRUCTED);
tag = *p & SC_ASN1_TAG_PRIMITIVE;
p++;
left--;
if (tag == SC_ASN1_TAG_PRIMITIVE) {
/* high tag number */
size_t n = SC_ASN1_TAGNUM_SIZE - 1;
/* search the last tag octet */
do {
if (left == 0 || n == 0)
/* either an invalid tag or it doesn't fit in
* unsigned int */
return SC_ERROR_INVALID_ASN1_OBJECT;
tag <<= 8;
tag |= *p;
p++;
left--;
n--;
} while (tag & 0x80);
}
/* parse length byte(s) */
if (left == 0)
return SC_ERROR_INVALID_ASN1_OBJECT;
len = *p;
p++;
left--;
if (len & 0x80) {
len &= 0x7f;
unsigned int a = 0;
if (len > sizeof a || len > left)
return SC_ERROR_INVALID_ASN1_OBJECT;
for (i = 0; i < len; i++) {
a <<= 8;
a |= *p;
p++;
left--;
}
len = a;
}
*cla_out = cla;
*tag_out = tag;
*taglen = len;
*buf = p;
if (len > left)
return SC_ERROR_ASN1_END_OF_CONTENTS;
return SC_SUCCESS;
}
void sc_format_asn1_entry(struct sc_asn1_entry *entry, void *parm, void *arg,
int set_present)
{
entry->parm = parm;
entry->arg = arg;
if (set_present)
entry->flags |= SC_ASN1_PRESENT;
}
void sc_copy_asn1_entry(const struct sc_asn1_entry *src,
struct sc_asn1_entry *dest)
{
while (src->name != NULL) {
*dest = *src;
dest++;
src++;
}
dest->name = NULL;
}
static void print_indent(size_t depth)
{
for (; depth > 0; depth--) {
putchar(' ');
}
}
static void print_hex(const u8 * buf, size_t buflen, size_t depth)
{
size_t lines_len = buflen * 5 + 128;
char *lines = malloc(lines_len);
char *line = lines;
if (buf == NULL || buflen == 0 || lines == NULL) {
free(lines);
return;
}
sc_hex_dump(buf, buflen, lines, lines_len);
while (*line != '\0') {
char *line_end = strchr(line, '\n');
ptrdiff_t width = line_end - line;
if (!line_end || width <= 1) {
/* don't print empty lines */
break;
}
if (buflen > 8) {
putchar('\n');
print_indent(depth);
} else {
printf(": ");
}
printf("%.*s", (int) width, line);
line = line_end + 1;
}
free(lines);
}
static void print_ascii(const u8 * buf, size_t buflen)
{
for (; 0 < buflen; buflen--, buf++) {
if (isprint(*buf))
printf("%c", *buf);
else
putchar('.');
}
}
static void sc_asn1_print_octet_string(const u8 * buf, size_t buflen, size_t depth)
{
print_hex(buf, buflen, depth);
}
static void sc_asn1_print_utf8string(const u8 * buf, size_t buflen)
{
/* FIXME UTF-8 is not ASCII */
print_ascii(buf, buflen);
}
static void sc_asn1_print_integer(const u8 * buf, size_t buflen)
{
size_t a = 0;
if (buflen > sizeof(a)) {
printf("0x%s", sc_dump_hex(buf, buflen));
} else {
size_t i;
for (i = 0; i < buflen; i++) {
a <<= 8;
a |= buf[i];
}
printf("%"SC_FORMAT_LEN_SIZE_T"u", a);
}
}
static void sc_asn1_print_boolean(const u8 * buf, size_t buflen)
{
if (!buflen)
return;
if (buf[0])
printf("true");
else
printf("false");
}
static void sc_asn1_print_bit_string(const u8 * buf, size_t buflen, size_t depth)
{
#ifndef _WIN32
long long a = 0;
#else
__int64 a = 0;
#endif
int r, i;
if (buflen > sizeof(a) + 1) {
print_hex(buf, buflen, depth);
} else {
r = sc_asn1_decode_bit_string(buf, buflen, &a, sizeof(a));
if (r < 0) {
printf("decode error");
return;
}
for (i = r - 1; i >= 0; i--) {
printf("%c", ((a >> i) & 1) ? '1' : '0');
}
}
}
#ifdef ENABLE_OPENSSL
#include <openssl/objects.h>
static void openssl_print_object_sn(const char *s)
{
ASN1_OBJECT *obj = OBJ_txt2obj(s, 0);
if (obj) {
int nid = OBJ_obj2nid(obj);
if (nid != NID_undef) {
printf(", %s", OBJ_nid2sn(nid));
}
ASN1_OBJECT_free(obj);
}
}
#else
static void openssl_print_object_sn(const char *s)
{
}
#endif
static void sc_asn1_print_object_id(const u8 * buf, size_t buflen)
{
struct sc_object_id oid;
const char *sbuf;
if (sc_asn1_decode_object_id(buf, buflen, &oid)) {
printf("decode error");
return;
}
sbuf = sc_dump_oid(&oid);
printf(" %s", sbuf);
openssl_print_object_sn(sbuf);
}
static void sc_asn1_print_utctime(const u8 * buf, size_t buflen)
{
if (buflen < 8) {
printf("Error in decoding.\n");
return;
}
print_ascii(buf, 2); /* YY */
putchar('-');
print_ascii(buf+2, 2); /* MM */
putchar('-');
print_ascii(buf+4, 2); /* DD */
putchar(' ');
print_ascii(buf+6, 2); /* hh */
buf += 8;
buflen -= 8;
if (buflen >= 2 && isdigit(buf[0]) && isdigit(buf[1])) {
putchar(':');
print_ascii(buf, 2); /* mm */
buf += 2;
buflen -= 2;
}
if (buflen >= 2 && isdigit(buf[0]) && isdigit(buf[1])) {
putchar(':');
print_ascii(buf, 2); /* ss */
buf += 2;
buflen -= 2;
}
if (buflen >= 4 && '.' == buf[0]) {
print_ascii(buf, 4); /* fff */
buf += 4;
buflen -= 4;
}
if (buflen >= 1 && 'Z' == buf[0]) {
printf(" UTC");
} else if (buflen >= 5 && ('-' == buf[0] || '+' == buf[0])) {
putchar(' ');
print_ascii(buf, 3); /* +/-hh */
putchar(':');
print_ascii(buf+3, 2); /* mm */
}
}
static void sc_asn1_print_generalizedtime(const u8 * buf, size_t buflen)
{
if (buflen < 8) {
printf("Error in decoding.\n");
return;
}
print_ascii(buf, 2);
sc_asn1_print_utctime(buf + 2, buflen - 2);
}
static void print_tags_recursive(const u8 * buf0, const u8 * buf,
size_t buflen, size_t depth)
{
int r;
size_t i;
size_t bytesleft = buflen;
const char *classes[4] = {
"Universal",
"Application",
"Context",
"Private"
};
const u8 *p = buf;
while (bytesleft >= 2) {
unsigned int cla = 0, tag = 0, hlen;
const u8 *tagp = p;
size_t len;
r = sc_asn1_read_tag(&tagp, bytesleft, &cla, &tag, &len);
if (r != SC_SUCCESS || tagp == NULL) {
printf("Error in decoding.\n");
return;
}
hlen = tagp - p;
if (cla == 0 && tag == 0) {
printf("Zero tag, finishing\n");
break;
}
print_indent(depth);
/* let i be the length of the tag in bytes */
for (i = 1; i < sizeof tag - 1; i++) {
if (!(tag >> 8*i))
break;
}
printf("%02X", cla<<(i-1)*8 | tag);
if ((cla & SC_ASN1_TAG_CLASS) == SC_ASN1_TAG_UNIVERSAL) {
printf(" %s", tag2str(tag));
} else {
printf(" %s %-2u",
classes[cla >> 6],
i == 1 ? tag & SC_ASN1_TAG_PRIMITIVE : tag & (((unsigned int) ~0) >> (i-1)*8));
}
if (!((cla & SC_ASN1_TAG_CLASS) == SC_ASN1_TAG_UNIVERSAL
&& tag == SC_ASN1_TAG_NULL && len == 0)) {
printf(" (%"SC_FORMAT_LEN_SIZE_T"u byte%s)",
len,
len != 1 ? "s" : "");
}
if (len + hlen > bytesleft) {
printf(" Illegal length!\n");
return;
}
p += hlen + len;
bytesleft -= hlen + len;
if (cla & SC_ASN1_TAG_CONSTRUCTED) {
putchar('\n');
print_tags_recursive(buf0, tagp, len, depth + 2*i + 1);
continue;
}
switch (tag) {
case SC_ASN1_TAG_BIT_STRING:
printf(": ");
sc_asn1_print_bit_string(tagp, len, depth + 2*i + 1);
break;
case SC_ASN1_TAG_OCTET_STRING:
sc_asn1_print_octet_string(tagp, len, depth + 2*i + 1);
break;
case SC_ASN1_TAG_OBJECT:
printf(": ");
sc_asn1_print_object_id(tagp, len);
break;
case SC_ASN1_TAG_INTEGER:
case SC_ASN1_TAG_ENUMERATED:
printf(": ");
sc_asn1_print_integer(tagp, len);
break;
case SC_ASN1_TAG_IA5STRING:
case SC_ASN1_TAG_PRINTABLESTRING:
case SC_ASN1_TAG_T61STRING:
case SC_ASN1_TAG_UTF8STRING:
printf(": ");
sc_asn1_print_utf8string(tagp, len);
break;
case SC_ASN1_TAG_BOOLEAN:
printf(": ");
sc_asn1_print_boolean(tagp, len);
break;
case SC_ASN1_GENERALIZEDTIME:
printf(": ");
sc_asn1_print_generalizedtime(tagp, len);
break;
case SC_ASN1_UTCTIME:
printf(": ");
sc_asn1_print_utctime(tagp, len);
break;
}
if ((cla & SC_ASN1_TAG_CLASS) == SC_ASN1_TAG_APPLICATION) {
print_hex(tagp, len, depth + 2*i + 1);
}
if ((cla & SC_ASN1_TAG_CLASS) == SC_ASN1_TAG_CONTEXT) {
print_hex(tagp, len, depth + 2*i + 1);
}
putchar('\n');
}
}
void sc_asn1_print_tags(const u8 * buf, size_t buflen)
{
print_tags_recursive(buf, buf, buflen, 0);
}
const u8 *sc_asn1_find_tag(sc_context_t *ctx, const u8 * buf,
size_t buflen, unsigned int tag_in, size_t *taglen_in)
{
size_t left = buflen, taglen;
const u8 *p = buf;
*taglen_in = 0;
while (left >= 2) {
unsigned int cla = 0, tag, mask = 0xff00;
buf = p;
/* read a tag */
if (sc_asn1_read_tag(&p, left, &cla, &tag, &taglen) != SC_SUCCESS
|| p == NULL)
return NULL;
left -= (p - buf);
/* we need to shift the class byte to the leftmost
* byte of the tag */
while ((tag & mask) != 0) {
cla <<= 8;
mask <<= 8;
}
/* compare the read tag with the given tag */
if ((tag | cla) == tag_in) {
/* we have a match => return length and value part */
if (taglen > left)
return NULL;
*taglen_in = taglen;
return p;
}
/* otherwise continue reading tags */
left -= taglen;
p += taglen;
}
return NULL;
}
const u8 *sc_asn1_skip_tag(sc_context_t *ctx, const u8 ** buf, size_t *buflen,
unsigned int tag_in, size_t *taglen_out)
{
const u8 *p = *buf;
size_t len = *buflen, taglen;
unsigned int cla = 0, tag;
if (sc_asn1_read_tag((const u8 **) &p, len, &cla, &tag, &taglen) != SC_SUCCESS
|| p == NULL)
return NULL;
switch (cla & 0xC0) {
case SC_ASN1_TAG_UNIVERSAL:
if ((tag_in & SC_ASN1_CLASS_MASK) != SC_ASN1_UNI)
return NULL;
break;
case SC_ASN1_TAG_APPLICATION:
if ((tag_in & SC_ASN1_CLASS_MASK) != SC_ASN1_APP)
return NULL;
break;
case SC_ASN1_TAG_CONTEXT:
if ((tag_in & SC_ASN1_CLASS_MASK) != SC_ASN1_CTX)
return NULL;
break;
case SC_ASN1_TAG_PRIVATE:
if ((tag_in & SC_ASN1_CLASS_MASK) != SC_ASN1_PRV)
return NULL;
break;
}
if (cla & SC_ASN1_TAG_CONSTRUCTED) {
if ((tag_in & SC_ASN1_CONS) == 0)
return NULL;
} else
if (tag_in & SC_ASN1_CONS)
return NULL;
if ((tag_in & SC_ASN1_TAG_MASK) != tag)
return NULL;
len -= (p - *buf); /* header size */
if (taglen > len) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"too long ASN.1 object (size %"SC_FORMAT_LEN_SIZE_T"u while only %"SC_FORMAT_LEN_SIZE_T"u available)\n",
taglen, len);
return NULL;
}
*buflen -= (p - *buf) + taglen;
*buf = p + taglen; /* point to next tag */
*taglen_out = taglen;
return p;
}
const u8 *sc_asn1_verify_tag(sc_context_t *ctx, const u8 * buf, size_t buflen,
unsigned int tag_in, size_t *taglen_out)
{
return sc_asn1_skip_tag(ctx, &buf, &buflen, tag_in, taglen_out);
}
static int decode_bit_string(const u8 * inbuf, size_t inlen, void *outbuf,
size_t outlen, int invert)
{
const u8 *in = inbuf;
u8 *out = (u8 *) outbuf;
int i, count = 0;
int zero_bits;
size_t octets_left;
if (outlen < octets_left)
return SC_ERROR_BUFFER_TOO_SMALL;
if (inlen < 1)
return SC_ERROR_INVALID_ASN1_OBJECT;
zero_bits = *in & 0x07;
octets_left = inlen - 1;
in++;
memset(outbuf, 0, outlen);
while (octets_left) {
/* 1st octet of input: ABCDEFGH, where A is the MSB */
/* 1st octet of output: HGFEDCBA, where A is the LSB */
/* first bit in bit string is the LSB in first resulting octet */
int bits_to_go;
*out = 0;
if (octets_left == 1)
bits_to_go = 8 - zero_bits;
else
bits_to_go = 8;
if (invert)
for (i = 0; i < bits_to_go; i++) {
*out |= ((*in >> (7 - i)) & 1) << i;
}
else {
*out = *in;
}
out++;
in++;
octets_left--;
count++;
}
return (count * 8) - zero_bits;
}
int sc_asn1_decode_bit_string(const u8 * inbuf, size_t inlen,
void *outbuf, size_t outlen)
{
return decode_bit_string(inbuf, inlen, outbuf, outlen, 1);
}
int sc_asn1_decode_bit_string_ni(const u8 * inbuf, size_t inlen,
void *outbuf, size_t outlen)
{
return decode_bit_string(inbuf, inlen, outbuf, outlen, 0);
}
static int encode_bit_string(const u8 * inbuf, size_t bits_left, u8 **outbuf,
size_t *outlen, int invert)
{
const u8 *in = inbuf;
u8 *out;
size_t bytes;
int skipped = 0;
bytes = (bits_left + 7)/8 + 1;
*outbuf = out = malloc(bytes);
if (out == NULL)
return SC_ERROR_OUT_OF_MEMORY;
*outlen = bytes;
out += 1;
while (bits_left) {
int i, bits_to_go = 8;
*out = 0;
if (bits_left < 8) {
bits_to_go = bits_left;
skipped = 8 - bits_left;
}
if (invert) {
for (i = 0; i < bits_to_go; i++)
*out |= ((*in >> i) & 1) << (7 - i);
} else {
*out = *in;
if (bits_left < 8)
return SC_ERROR_NOT_SUPPORTED; /* FIXME */
}
bits_left -= bits_to_go;
out++, in++;
}
out = *outbuf;
out[0] = skipped;
return 0;
}
/*
* Bitfields are just bit strings, stored in an unsigned int
* (taking endianness into account)
*/
static int decode_bit_field(const u8 * inbuf, size_t inlen, void *outbuf, size_t outlen)
{
u8 data[sizeof(unsigned int)];
unsigned int field = 0;
int i, n;
if (outlen != sizeof(data))
return SC_ERROR_BUFFER_TOO_SMALL;
n = decode_bit_string(inbuf, inlen, data, sizeof(data), 1);
if (n < 0)
return n;
for (i = 0; i < n; i += 8) {
field |= (data[i/8] << i);
}
memcpy(outbuf, &field, outlen);
return 0;
}
static int encode_bit_field(const u8 *inbuf, size_t inlen,
u8 **outbuf, size_t *outlen)
{
u8 data[sizeof(unsigned int)];
unsigned int field = 0;
size_t i, bits;
if (inlen != sizeof(data))
return SC_ERROR_BUFFER_TOO_SMALL;
/* count the bits */
memcpy(&field, inbuf, inlen);
for (bits = 0; field; bits++)
field >>= 1;
memcpy(&field, inbuf, inlen);
for (i = 0; i < bits; i += 8)
data[i/8] = field >> i;
return encode_bit_string(data, bits, outbuf, outlen, 1);
}
int sc_asn1_decode_integer(const u8 * inbuf, size_t inlen, int *out)
{
int a = 0;
size_t i;
if (inlen > sizeof(int) || inlen == 0)
return SC_ERROR_INVALID_ASN1_OBJECT;
if (inbuf[0] & 0x80)
a = -1;
for (i = 0; i < inlen; i++) {
a <<= 8;
a |= *inbuf++;
}
*out = a;
return 0;
}
static int asn1_encode_integer(int in, u8 ** obj, size_t * objsize)
{
int i = sizeof(in) * 8, skip_zero, skip_sign;
u8 *p, b;
if (in < 0)
{
skip_sign = 1;
skip_zero= 0;
}
else
{
skip_sign = 0;
skip_zero= 1;
}
*obj = p = malloc(sizeof(in)+1);
if (*obj == NULL)
return SC_ERROR_OUT_OF_MEMORY;
do {
i -= 8;
b = in >> i;
if (skip_sign)
{
if (b != 0xff)
skip_sign = 0;
if (b & 0x80)
{
*p = b;
if (0xff == b)
continue;
}
else
{
p++;
skip_sign = 0;
}
}
if (b == 0 && skip_zero)
continue;
if (skip_zero) {
skip_zero = 0;
/* prepend 0x00 if MSb is 1 and integer positive */
if ((b & 0x80) != 0 && in > 0)
*p++ = 0;
}
*p++ = b;
} while (i > 0);
if (skip_sign)
p++;
*objsize = p - *obj;
if (*objsize == 0) {
*objsize = 1;
(*obj)[0] = 0;
}
return 0;
}
int
sc_asn1_decode_object_id(const u8 *inbuf, size_t inlen, struct sc_object_id *id)
{
int a;
const u8 *p = inbuf;
int *octet;
if (inlen == 0 || inbuf == NULL || id == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
sc_init_oid(id);
octet = id->value;
a = *p;
*octet++ = a / 40;
*octet++ = a % 40;
inlen--;
while (inlen) {
p++;
a = *p & 0x7F;
inlen--;
while (inlen && *p & 0x80) {
p++;
a <<= 7;
a |= *p & 0x7F;
inlen--;
}
*octet++ = a;
if (octet - id->value >= SC_MAX_OBJECT_ID_OCTETS) {
sc_init_oid(id);
return SC_ERROR_INVALID_ASN1_OBJECT;
}
};
return 0;
}
int
sc_asn1_encode_object_id(u8 **buf, size_t *buflen, const struct sc_object_id *id)
{
u8 temp[SC_MAX_OBJECT_ID_OCTETS*5], *p = temp;
int i;
if (!buflen || !id)
return SC_ERROR_INVALID_ARGUMENTS;
/* an OID must have at least two components */
if (id->value[0] == -1 || id->value[1] == -1)
return SC_ERROR_INVALID_ARGUMENTS;
for (i = 0; i < SC_MAX_OBJECT_ID_OCTETS; i++) {
unsigned int k, shift;
if (id->value[i] == -1)
break;
k = id->value[i];
switch (i) {
case 0:
if (k > 2)
return SC_ERROR_INVALID_ARGUMENTS;
*p = k * 40;
break;
case 1:
if (k > 39)
return SC_ERROR_INVALID_ARGUMENTS;
*p++ += k;
break;
default:
shift = 28;
while (shift && (k >> shift) == 0)
shift -= 7;
while (shift) {
*p++ = 0x80 | ((k >> shift) & 0x7f);
shift -= 7;
}
*p++ = k & 0x7F;
break;
}
}
*buflen = p - temp;
if (buf) {
*buf = malloc(*buflen);
if (!*buf)
return SC_ERROR_OUT_OF_MEMORY;
memcpy(*buf, temp, *buflen);
}
return 0;
}
static int sc_asn1_decode_utf8string(const u8 *inbuf, size_t inlen,
u8 *out, size_t *outlen)
{
if (inlen+1 > *outlen)
return SC_ERROR_BUFFER_TOO_SMALL;
*outlen = inlen+1;
memcpy(out, inbuf, inlen);
out[inlen] = 0;
return 0;
}
int sc_asn1_put_tag(unsigned int tag, const u8 * data, size_t datalen, u8 * out, size_t outlen, u8 **ptr)
{
size_t c = 0;
size_t tag_len;
size_t ii;
u8 *p = out;
u8 tag_char[4] = {0, 0, 0, 0};
/* Check tag */
if (tag == 0 || tag > 0xFFFFFFFF) {
/* A tag of 0x00 is not valid and at most 4-byte tag names are supported. */
return SC_ERROR_INVALID_DATA;
}
for (tag_len = 0; tag; tag >>= 8) {
/* Note: tag char will be reversed order. */
tag_char[tag_len++] = tag & 0xFF;
}
if (tag_len > 1) {
if ((tag_char[tag_len - 1] & SC_ASN1_TAG_PRIMITIVE) != SC_ASN1_TAG_ESCAPE_MARKER) {
/* First byte is not escape marker. */
return SC_ERROR_INVALID_DATA;
}
for (ii = 1; ii < tag_len - 1; ii++) {
if ((tag_char[ii] & 0x80) != 0x80) {
/* MS bit is not 'one'. */
return SC_ERROR_INVALID_DATA;
}
}
if ((tag_char[0] & 0x80) != 0x00) {
/* MS bit of the last byte is not 'zero'. */
return SC_ERROR_INVALID_DATA;
}
}
/* Calculate the number of additional bytes necessary to encode the length. */
/* c+1 is the size of the length field. */
if (datalen > 127) {
c = 1;
while (datalen >> (c << 3))
c++;
}
if (outlen == 0 || out == NULL) {
/* Caller only asks for the length that would be written. */
return tag_len + (c+1) + datalen;
}
/* We will write the tag, so check the length. */
if (outlen < tag_len + (c+1) + datalen)
return SC_ERROR_BUFFER_TOO_SMALL;
for (ii=0;ii<tag_len;ii++)
*p++ = tag_char[tag_len - ii - 1];
if (c > 0) {
*p++ = 0x80 | c;
while (c--)
*p++ = (datalen >> (c << 3)) & 0xFF;
}
else {
*p++ = datalen & 0x7F;
}
if(data && datalen > 0) {
memcpy(p, data, datalen);
p += datalen;
}
if (ptr != NULL)
*ptr = p;
return 0;
}
int sc_asn1_write_element(sc_context_t *ctx, unsigned int tag,
const u8 * data, size_t datalen, u8 ** out, size_t * outlen)
{
return asn1_write_element(ctx, tag, data, datalen, out, outlen);
}
static int asn1_write_element(sc_context_t *ctx, unsigned int tag,
const u8 * data, size_t datalen, u8 ** out, size_t * outlen)
{
unsigned char t;
unsigned char *buf, *p;
int c = 0;
unsigned short_tag;
unsigned char tag_char[3] = {0, 0, 0};
size_t tag_len, ii;
short_tag = tag & SC_ASN1_TAG_MASK;
for (tag_len = 0; short_tag >> (8 * tag_len); tag_len++)
tag_char[tag_len] = (short_tag >> (8 * tag_len)) & 0xFF;
if (!tag_len)
tag_len = 1;
if (tag_len > 1) {
if ((tag_char[tag_len - 1] & SC_ASN1_TAG_PRIMITIVE) != SC_ASN1_TAG_ESCAPE_MARKER)
SC_TEST_RET(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_INVALID_DATA, "First byte of the long tag is not 'escape marker'");
for (ii = 1; ii < tag_len - 1; ii++)
if (!(tag_char[ii] & 0x80))
SC_TEST_RET(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_INVALID_DATA, "MS bit expected to be 'one'");
if (tag_char[0] & 0x80)
SC_TEST_RET(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_INVALID_DATA, "MS bit of the last byte expected to be 'zero'");
}
t = tag_char[tag_len - 1] & 0x1F;
switch (tag & SC_ASN1_CLASS_MASK) {
case SC_ASN1_UNI:
break;
case SC_ASN1_APP:
t |= SC_ASN1_TAG_APPLICATION;
break;
case SC_ASN1_CTX:
t |= SC_ASN1_TAG_CONTEXT;
break;
case SC_ASN1_PRV:
t |= SC_ASN1_TAG_PRIVATE;
break;
}
if (tag & SC_ASN1_CONS)
t |= SC_ASN1_TAG_CONSTRUCTED;
if (datalen > 127) {
c = 1;
while (datalen >> (c << 3))
c++;
}
*outlen = tag_len + 1 + c + datalen;
buf = malloc(*outlen);
if (buf == NULL)
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_OUT_OF_MEMORY);
*out = p = buf;
*p++ = t;
for (ii=1;ii<tag_len;ii++)
*p++ = tag_char[tag_len - ii - 1];
if (c) {
*p++ = 0x80 | c;
while (c--)
*p++ = (datalen >> (c << 3)) & 0xFF;
}
else {
*p++ = datalen & 0x7F;
}
memcpy(p, data, datalen);
return SC_SUCCESS;
}
static const struct sc_asn1_entry c_asn1_path_ext[3] = {
{ "aid", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x0F, 0, NULL, NULL },
{ "path", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_OCTET_STRING, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static const struct sc_asn1_entry c_asn1_path[5] = {
{ "path", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_OCTET_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ "index", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "length", SC_ASN1_INTEGER, SC_ASN1_CTX | 0, SC_ASN1_OPTIONAL, NULL, NULL },
/* For some multi-applications PKCS#15 card the ODF records can hold the references to
* the xDF files and objects placed elsewhere then under the application DF of the ODF itself.
* In such a case the 'path' ASN1 data includes also the ID of the target application (AID).
* This path extension do not make a part of PKCS#15 standard.
*/
{ "pathExtended", SC_ASN1_STRUCT, SC_ASN1_CTX | 1 | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static int asn1_decode_path(sc_context_t *ctx, const u8 *in, size_t len,
sc_path_t *path, int depth)
{
int idx, count, r;
struct sc_asn1_entry asn1_path_ext[3], asn1_path[5];
unsigned char path_value[SC_MAX_PATH_SIZE], aid_value[SC_MAX_AID_SIZE];
size_t path_len = sizeof(path_value), aid_len = sizeof(aid_value);
memset(path, 0, sizeof(struct sc_path));
sc_copy_asn1_entry(c_asn1_path_ext, asn1_path_ext);
sc_copy_asn1_entry(c_asn1_path, asn1_path);
sc_format_asn1_entry(asn1_path_ext + 0, aid_value, &aid_len, 0);
sc_format_asn1_entry(asn1_path_ext + 1, path_value, &path_len, 0);
sc_format_asn1_entry(asn1_path + 0, path_value, &path_len, 0);
sc_format_asn1_entry(asn1_path + 1, &idx, NULL, 0);
sc_format_asn1_entry(asn1_path + 2, &count, NULL, 0);
sc_format_asn1_entry(asn1_path + 3, asn1_path_ext, NULL, 0);
r = asn1_decode(ctx, asn1_path, in, len, NULL, NULL, 0, depth + 1);
if (r)
return r;
if (asn1_path[3].flags & SC_ASN1_PRESENT) {
/* extended path present: set 'path' and 'aid' */
memcpy(path->aid.value, aid_value, aid_len);
path->aid.len = aid_len;
memcpy(path->value, path_value, path_len);
path->len = path_len;
}
else if (asn1_path[0].flags & SC_ASN1_PRESENT) {
/* path present: set 'path' */
memcpy(path->value, path_value, path_len);
path->len = path_len;
}
else {
/* failed if both 'path' and 'pathExtended' are absent */
return SC_ERROR_ASN1_OBJECT_NOT_FOUND;
}
if (path->len == 2)
path->type = SC_PATH_TYPE_FILE_ID;
else if (path->aid.len && path->len > 2)
path->type = SC_PATH_TYPE_FROM_CURRENT;
else
path->type = SC_PATH_TYPE_PATH;
if ((asn1_path[1].flags & SC_ASN1_PRESENT) && (asn1_path[2].flags & SC_ASN1_PRESENT)) {
path->index = idx;
path->count = count;
}
else {
path->index = 0;
path->count = -1;
}
return SC_SUCCESS;
}
static int asn1_encode_path(sc_context_t *ctx, const sc_path_t *path,
u8 **buf, size_t *bufsize, int depth, unsigned int parent_flags)
{
int r;
struct sc_asn1_entry asn1_path[5];
sc_path_t tpath = *path;
sc_copy_asn1_entry(c_asn1_path, asn1_path);
sc_format_asn1_entry(asn1_path + 0, (void *) &tpath.value, (void *) &tpath.len, 1);
asn1_path[0].flags |= parent_flags;
if (path->count > 0) {
sc_format_asn1_entry(asn1_path + 1, (void *) &tpath.index, NULL, 1);
sc_format_asn1_entry(asn1_path + 2, (void *) &tpath.count, NULL, 1);
}
r = asn1_encode(ctx, asn1_path, buf, bufsize, depth + 1);
return r;
}
static const struct sc_asn1_entry c_asn1_se[2] = {
{ "seInfo", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static const struct sc_asn1_entry c_asn1_se_info[4] = {
{ "se", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, 0, NULL, NULL },
{ "owner",SC_ASN1_OBJECT, SC_ASN1_TAG_OBJECT, SC_ASN1_OPTIONAL, NULL, NULL },
{ "aid", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_OCTET_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static int asn1_decode_se_info(sc_context_t *ctx, const u8 *obj, size_t objlen,
sc_pkcs15_sec_env_info_t ***se, size_t *num, int depth)
{
struct sc_pkcs15_sec_env_info **ses;
const unsigned char *ptr = obj;
size_t idx, ptrlen = objlen;
int ret;
ses = calloc(SC_MAX_SE_NUM, sizeof(sc_pkcs15_sec_env_info_t *));
if (ses == NULL)
return SC_ERROR_OUT_OF_MEMORY;
for (idx=0; idx < SC_MAX_SE_NUM && ptrlen; ) {
struct sc_asn1_entry asn1_se[2];
struct sc_asn1_entry asn1_se_info[4];
struct sc_pkcs15_sec_env_info si;
sc_copy_asn1_entry(c_asn1_se, asn1_se);
sc_copy_asn1_entry(c_asn1_se_info, asn1_se_info);
si.aid.len = sizeof(si.aid.value);
sc_format_asn1_entry(asn1_se_info + 0, &si.se, NULL, 0);
sc_format_asn1_entry(asn1_se_info + 1, &si.owner, NULL, 0);
sc_format_asn1_entry(asn1_se_info + 2, &si.aid.value, &si.aid.len, 0);
sc_format_asn1_entry(asn1_se + 0, asn1_se_info, NULL, 0);
ret = asn1_decode(ctx, asn1_se, ptr, ptrlen, &ptr, &ptrlen, 0, depth+1);
if (ret != SC_SUCCESS)
goto err;
if (!(asn1_se_info[1].flags & SC_ASN1_PRESENT))
sc_init_oid(&si.owner);
ses[idx] = calloc(1, sizeof(sc_pkcs15_sec_env_info_t));
if (ses[idx] == NULL) {
ret = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
memcpy(ses[idx], &si, sizeof(struct sc_pkcs15_sec_env_info));
idx++;
}
*se = ses;
*num = idx;
ret = SC_SUCCESS;
err:
if (ret != SC_SUCCESS) {
size_t i;
for (i = 0; i < idx; i++)
if (ses[i])
free(ses[i]);
free(ses);
}
return ret;
}
static int asn1_encode_se_info(sc_context_t *ctx,
struct sc_pkcs15_sec_env_info **se, size_t se_num,
unsigned char **buf, size_t *bufsize, int depth)
{
unsigned char *ptr = NULL, *out = NULL, *p;
size_t ptrlen = 0, outlen = 0, idx;
int ret;
for (idx=0; idx < se_num; idx++) {
struct sc_asn1_entry asn1_se[2];
struct sc_asn1_entry asn1_se_info[4];
sc_copy_asn1_entry(c_asn1_se, asn1_se);
sc_copy_asn1_entry(c_asn1_se_info, asn1_se_info);
sc_format_asn1_entry(asn1_se_info + 0, &se[idx]->se, NULL, 1);
if (sc_valid_oid(&se[idx]->owner))
sc_format_asn1_entry(asn1_se_info + 1, &se[idx]->owner, NULL, 1);
if (se[idx]->aid.len)
sc_format_asn1_entry(asn1_se_info + 2, &se[idx]->aid.value, &se[idx]->aid.len, 1);
sc_format_asn1_entry(asn1_se + 0, asn1_se_info, NULL, 1);
ret = sc_asn1_encode(ctx, asn1_se, &ptr, &ptrlen);
if (ret != SC_SUCCESS)
goto err;
if (!ptrlen)
continue;
p = (unsigned char *) realloc(out, outlen + ptrlen);
if (!p) {
ret = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
out = p;
memcpy(out + outlen, ptr, ptrlen);
outlen += ptrlen;
free(ptr);
ptr = NULL;
ptrlen = 0;
}
*buf = out;
*bufsize = outlen;
ret = SC_SUCCESS;
err:
if (ret != SC_SUCCESS && out != NULL)
free(out);
return ret;
}
/* TODO: According to specification type of 'SecurityCondition' is 'CHOICE'.
* Do it at least for SC_ASN1_PKCS15_ID(authId), SC_ASN1_STRUCT(authReference) and NULL(always). */
static const struct sc_asn1_entry c_asn1_access_control_rule[3] = {
{ "accessMode", SC_ASN1_BIT_FIELD, SC_ASN1_TAG_BIT_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ "securityCondition", SC_ASN1_PKCS15_ID, SC_ASN1_TAG_OCTET_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
/*
* in src/libopensc/pkcs15.h SC_PKCS15_MAX_ACCESS_RULES defined as 8
*/
static const struct sc_asn1_entry c_asn1_access_control_rules[SC_PKCS15_MAX_ACCESS_RULES + 1] = {
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static const struct sc_asn1_entry c_asn1_com_obj_attr[6] = {
{ "label", SC_ASN1_UTF8STRING, SC_ASN1_TAG_UTF8STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ "flags", SC_ASN1_BIT_FIELD, SC_ASN1_TAG_BIT_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ "authId", SC_ASN1_PKCS15_ID, SC_ASN1_TAG_OCTET_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ "userConsent", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRules", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static const struct sc_asn1_entry c_asn1_p15_obj[5] = {
{ "commonObjectAttributes", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ "classAttributes", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ "subClassAttributes", SC_ASN1_STRUCT, SC_ASN1_CTX | 0 | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "typeAttributes", SC_ASN1_STRUCT, SC_ASN1_CTX | 1 | SC_ASN1_CONS, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static int asn1_decode_p15_object(sc_context_t *ctx, const u8 *in,
size_t len, struct sc_asn1_pkcs15_object *obj,
int depth)
{
struct sc_pkcs15_object *p15_obj = obj->p15_obj;
struct sc_asn1_entry asn1_c_attr[6], asn1_p15_obj[5];
struct sc_asn1_entry asn1_ac_rules[SC_PKCS15_MAX_ACCESS_RULES + 1], asn1_ac_rule[SC_PKCS15_MAX_ACCESS_RULES][3];
size_t flags_len = sizeof(p15_obj->flags);
size_t label_len = sizeof(p15_obj->label);
size_t access_mode_len = sizeof(p15_obj->access_rules[0].access_mode);
int r, ii;
for (ii=0; ii<SC_PKCS15_MAX_ACCESS_RULES; ii++)
sc_copy_asn1_entry(c_asn1_access_control_rule, asn1_ac_rule[ii]);
sc_copy_asn1_entry(c_asn1_access_control_rules, asn1_ac_rules);
sc_copy_asn1_entry(c_asn1_com_obj_attr, asn1_c_attr);
sc_copy_asn1_entry(c_asn1_p15_obj, asn1_p15_obj);
sc_format_asn1_entry(asn1_c_attr + 0, p15_obj->label, &label_len, 0);
sc_format_asn1_entry(asn1_c_attr + 1, &p15_obj->flags, &flags_len, 0);
sc_format_asn1_entry(asn1_c_attr + 2, &p15_obj->auth_id, NULL, 0);
sc_format_asn1_entry(asn1_c_attr + 3, &p15_obj->user_consent, NULL, 0);
for (ii=0; ii<SC_PKCS15_MAX_ACCESS_RULES; ii++) {
sc_format_asn1_entry(asn1_ac_rule[ii] + 0, &p15_obj->access_rules[ii].access_mode, &access_mode_len, 0);
sc_format_asn1_entry(asn1_ac_rule[ii] + 1, &p15_obj->access_rules[ii].auth_id, NULL, 0);
sc_format_asn1_entry(asn1_ac_rules + ii, asn1_ac_rule[ii], NULL, 0);
}
sc_format_asn1_entry(asn1_c_attr + 4, asn1_ac_rules, NULL, 0);
sc_format_asn1_entry(asn1_p15_obj + 0, asn1_c_attr, NULL, 0);
sc_format_asn1_entry(asn1_p15_obj + 1, obj->asn1_class_attr, NULL, 0);
sc_format_asn1_entry(asn1_p15_obj + 2, obj->asn1_subclass_attr, NULL, 0);
sc_format_asn1_entry(asn1_p15_obj + 3, obj->asn1_type_attr, NULL, 0);
r = asn1_decode(ctx, asn1_p15_obj, in, len, NULL, NULL, 0, depth + 1);
return r;
}
static int asn1_encode_p15_object(sc_context_t *ctx, const struct sc_asn1_pkcs15_object *obj,
u8 **buf, size_t *bufsize, int depth)
{
struct sc_pkcs15_object p15_obj = *obj->p15_obj;
struct sc_asn1_entry asn1_c_attr[6], asn1_p15_obj[5];
struct sc_asn1_entry asn1_ac_rules[SC_PKCS15_MAX_ACCESS_RULES + 1], asn1_ac_rule[SC_PKCS15_MAX_ACCESS_RULES][3];
size_t label_len = strlen(p15_obj.label);
size_t flags_len;
size_t access_mode_len;
int r, ii;
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "encode p15 obj(type:0x%X,access_mode:0x%X)", p15_obj.type, p15_obj.access_rules[0].access_mode);
if (p15_obj.access_rules[0].access_mode) {
for (ii=0; ii<SC_PKCS15_MAX_ACCESS_RULES; ii++) {
sc_copy_asn1_entry(c_asn1_access_control_rule, asn1_ac_rule[ii]);
if (p15_obj.access_rules[ii].auth_id.len == 0) {
asn1_ac_rule[ii][1].type = SC_ASN1_NULL;
asn1_ac_rule[ii][1].tag = SC_ASN1_TAG_NULL;
}
}
sc_copy_asn1_entry(c_asn1_access_control_rules, asn1_ac_rules);
}
sc_copy_asn1_entry(c_asn1_com_obj_attr, asn1_c_attr);
sc_copy_asn1_entry(c_asn1_p15_obj, asn1_p15_obj);
if (label_len != 0)
sc_format_asn1_entry(asn1_c_attr + 0, (void *) p15_obj.label, &label_len, 1);
if (p15_obj.flags) {
flags_len = sizeof(p15_obj.flags);
sc_format_asn1_entry(asn1_c_attr + 1, (void *) &p15_obj.flags, &flags_len, 1);
}
if (p15_obj.auth_id.len)
sc_format_asn1_entry(asn1_c_attr + 2, (void *) &p15_obj.auth_id, NULL, 1);
if (p15_obj.user_consent)
sc_format_asn1_entry(asn1_c_attr + 3, (void *) &p15_obj.user_consent, NULL, 1);
if (p15_obj.access_rules[0].access_mode) {
for (ii=0; p15_obj.access_rules[ii].access_mode; ii++) {
access_mode_len = sizeof(p15_obj.access_rules[ii].access_mode);
sc_format_asn1_entry(asn1_ac_rule[ii] + 0, (void *) &p15_obj.access_rules[ii].access_mode, &access_mode_len, 1);
sc_format_asn1_entry(asn1_ac_rule[ii] + 1, (void *) &p15_obj.access_rules[ii].auth_id, NULL, 1);
sc_format_asn1_entry(asn1_ac_rules + ii, asn1_ac_rule[ii], NULL, 1);
}
sc_format_asn1_entry(asn1_c_attr + 4, asn1_ac_rules, NULL, 1);
}
sc_format_asn1_entry(asn1_p15_obj + 0, asn1_c_attr, NULL, 1);
sc_format_asn1_entry(asn1_p15_obj + 1, obj->asn1_class_attr, NULL, 1);
if (obj->asn1_subclass_attr != NULL && obj->asn1_subclass_attr->name)
sc_format_asn1_entry(asn1_p15_obj + 2, obj->asn1_subclass_attr, NULL, 1);
sc_format_asn1_entry(asn1_p15_obj + 3, obj->asn1_type_attr, NULL, 1);
r = asn1_encode(ctx, asn1_p15_obj, buf, bufsize, depth + 1);
return r;
}
static int asn1_decode_entry(sc_context_t *ctx,struct sc_asn1_entry *entry,
const u8 *obj, size_t objlen, int depth)
{
void *parm = entry->parm;
int (*callback_func)(sc_context_t *nctx, void *arg, const u8 *nobj,
size_t nobjlen, int ndepth);
size_t *len = (size_t *) entry->arg;
int r = 0;
callback_func = parm;
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sdecoding '%s', raw data:%s%s\n",
depth, depth, "", entry->name,
sc_dump_hex(obj, objlen > 16 ? 16 : objlen),
objlen > 16 ? "..." : "");
switch (entry->type) {
case SC_ASN1_STRUCT:
if (parm != NULL)
r = asn1_decode(ctx, (struct sc_asn1_entry *) parm, obj,
objlen, NULL, NULL, 0, depth + 1);
break;
case SC_ASN1_NULL:
break;
case SC_ASN1_BOOLEAN:
if (parm != NULL) {
if (objlen != 1) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"invalid ASN.1 object length: %"SC_FORMAT_LEN_SIZE_T"u\n",
objlen);
r = SC_ERROR_INVALID_ASN1_OBJECT;
} else
*((int *) parm) = obj[0] ? 1 : 0;
}
break;
case SC_ASN1_INTEGER:
case SC_ASN1_ENUMERATED:
if (parm != NULL) {
r = sc_asn1_decode_integer(obj, objlen, (int *) entry->parm);
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sdecoding '%s' returned %d\n", depth, depth, "",
entry->name, *((int *) entry->parm));
}
break;
case SC_ASN1_BIT_STRING_NI:
case SC_ASN1_BIT_STRING:
if (parm != NULL) {
int invert = entry->type == SC_ASN1_BIT_STRING ? 1 : 0;
assert(len != NULL);
if (objlen < 1) {
r = SC_ERROR_INVALID_ASN1_OBJECT;
break;
}
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen-1);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
*len = objlen-1;
parm = *buf;
}
r = decode_bit_string(obj, objlen, (u8 *) parm, *len, invert);
if (r >= 0) {
*len = r;
r = 0;
}
}
break;
case SC_ASN1_BIT_FIELD:
if (parm != NULL)
r = decode_bit_field(obj, objlen, (u8 *) parm, *len);
break;
case SC_ASN1_OCTET_STRING:
if (parm != NULL) {
size_t c;
assert(len != NULL);
/* Strip off padding zero */
if ((entry->flags & SC_ASN1_UNSIGNED)
&& obj[0] == 0x00 && objlen > 1) {
objlen--;
obj++;
}
/* Allocate buffer if needed */
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
c = *len = objlen;
parm = *buf;
} else
c = objlen > *len ? *len : objlen;
memcpy(parm, obj, c);
*len = c;
}
break;
case SC_ASN1_GENERALIZEDTIME:
if (parm != NULL) {
size_t c;
assert(len != NULL);
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
c = *len = objlen;
parm = *buf;
} else
c = objlen > *len ? *len : objlen;
memcpy(parm, obj, c);
*len = c;
}
break;
case SC_ASN1_OBJECT:
if (parm != NULL)
r = sc_asn1_decode_object_id(obj, objlen, (struct sc_object_id *) parm);
break;
case SC_ASN1_PRINTABLESTRING:
case SC_ASN1_UTF8STRING:
if (parm != NULL) {
assert(len != NULL);
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen+1);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
*len = objlen+1;
parm = *buf;
}
r = sc_asn1_decode_utf8string(obj, objlen, (u8 *) parm, len);
if (entry->flags & SC_ASN1_ALLOC) {
*len -= 1;
}
}
break;
case SC_ASN1_PATH:
if (entry->parm != NULL)
r = asn1_decode_path(ctx, obj, objlen, (sc_path_t *) parm, depth);
break;
case SC_ASN1_PKCS15_ID:
if (entry->parm != NULL) {
struct sc_pkcs15_id *id = (struct sc_pkcs15_id *) parm;
size_t c = objlen > sizeof(id->value) ? sizeof(id->value) : objlen;
memcpy(id->value, obj, c);
id->len = c;
}
break;
case SC_ASN1_PKCS15_OBJECT:
if (entry->parm != NULL)
r = asn1_decode_p15_object(ctx, obj, objlen, (struct sc_asn1_pkcs15_object *) parm, depth);
break;
case SC_ASN1_ALGORITHM_ID:
if (entry->parm != NULL)
r = sc_asn1_decode_algorithm_id(ctx, obj, objlen, (struct sc_algorithm_id *) parm, depth);
break;
case SC_ASN1_SE_INFO:
if (entry->parm != NULL)
r = asn1_decode_se_info(ctx, obj, objlen, (sc_pkcs15_sec_env_info_t ***)entry->parm, len, depth);
break;
case SC_ASN1_CALLBACK:
if (entry->parm != NULL)
r = callback_func(ctx, entry->arg, obj, objlen, depth);
break;
default:
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "invalid ASN.1 type: %d\n", entry->type);
return SC_ERROR_INVALID_ASN1_OBJECT;
}
if (r) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "decoding of ASN.1 object '%s' failed: %s\n", entry->name,
sc_strerror(r));
return r;
}
entry->flags |= SC_ASN1_PRESENT;
return 0;
}
static int asn1_decode(sc_context_t *ctx, struct sc_asn1_entry *asn1,
const u8 *in, size_t len, const u8 **newp, size_t *len_left,
int choice, int depth)
{
int r, idx = 0;
const u8 *p = in, *obj;
struct sc_asn1_entry *entry = asn1;
size_t left = len, objlen;
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"%*.*scalled, left=%"SC_FORMAT_LEN_SIZE_T"u, depth %d%s\n",
depth, depth, "", left, depth, choice ? ", choice" : "");
if (!p)
return SC_ERROR_ASN1_OBJECT_NOT_FOUND;
if (left < 2) {
while (asn1->name && (asn1->flags & SC_ASN1_OPTIONAL))
asn1++;
/* If all elements were optional, there's nothing
* to complain about */
if (asn1->name == NULL)
return 0;
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "End of ASN.1 stream, "
"non-optional field \"%s\" not found\n",
asn1->name);
return SC_ERROR_ASN1_OBJECT_NOT_FOUND;
}
if (p[0] == 0 || p[0] == 0xFF || len == 0)
return SC_ERROR_ASN1_END_OF_CONTENTS;
for (idx = 0; asn1[idx].name != NULL; idx++) {
entry = &asn1[idx];
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "Looking for '%s', tag 0x%x%s%s\n",
entry->name, entry->tag, choice? ", CHOICE" : "",
(entry->flags & SC_ASN1_OPTIONAL)? ", OPTIONAL": "");
/* Special case CHOICE has no tag */
if (entry->type == SC_ASN1_CHOICE) {
r = asn1_decode(ctx,
(struct sc_asn1_entry *) entry->parm,
p, left, &p, &left, 1, depth + 1);
if (r >= 0)
r = 0;
goto decode_ok;
}
obj = sc_asn1_skip_tag(ctx, &p, &left, entry->tag, &objlen);
if (obj == NULL) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "'%s' not present\n", entry->name);
if (choice)
continue;
if (entry->flags & SC_ASN1_OPTIONAL)
continue;
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "mandatory ASN.1 object '%s' not found\n", entry->name);
if (left) {
u8 line[128], *linep = line;
size_t i;
line[0] = 0;
for (i = 0; i < 10 && i < left; i++) {
sprintf((char *) linep, "%02X ", p[i]);
linep += 3;
}
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "next tag: %s\n", line);
}
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_ASN1_OBJECT_NOT_FOUND);
}
r = asn1_decode_entry(ctx, entry, obj, objlen, depth);
decode_ok:
if (r)
return r;
if (choice)
break;
}
if (choice && asn1[idx].name == NULL) /* No match */
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_ASN1_OBJECT_NOT_FOUND);
if (newp != NULL)
*newp = p;
if (len_left != NULL)
*len_left = left;
if (choice)
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, idx);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, 0);
}
int sc_asn1_decode(sc_context_t *ctx, struct sc_asn1_entry *asn1,
const u8 *in, size_t len, const u8 **newp, size_t *len_left)
{
return asn1_decode(ctx, asn1, in, len, newp, len_left, 0, 0);
}
int sc_asn1_decode_choice(sc_context_t *ctx, struct sc_asn1_entry *asn1,
const u8 *in, size_t len, const u8 **newp, size_t *len_left)
{
return asn1_decode(ctx, asn1, in, len, newp, len_left, 1, 0);
}
static int asn1_encode_entry(sc_context_t *ctx, const struct sc_asn1_entry *entry,
u8 **obj, size_t *objlen, int depth)
{
void *parm = entry->parm;
int (*callback_func)(sc_context_t *nctx, void *arg, u8 **nobj,
size_t *nobjlen, int ndepth);
const size_t *len = (const size_t *) entry->arg;
int r = 0;
u8 * buf = NULL;
size_t buflen = 0;
callback_func = parm;
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sencoding '%s'%s\n",
depth, depth, "", entry->name,
(entry->flags & SC_ASN1_PRESENT)? "" : " (not present)");
if (!(entry->flags & SC_ASN1_PRESENT))
goto no_object;
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"%*.*stype=%d, tag=0x%02x, parm=%p, len=%"SC_FORMAT_LEN_SIZE_T"u\n",
depth, depth, "", entry->type, entry->tag, parm,
len ? *len : 0);
if (entry->type == SC_ASN1_CHOICE) {
const struct sc_asn1_entry *list, *choice = NULL;
list = (const struct sc_asn1_entry *) parm;
while (list->name != NULL) {
if (list->flags & SC_ASN1_PRESENT) {
if (choice) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"ASN.1 problem: more than "
"one CHOICE when encoding %s: "
"%s and %s both present\n",
entry->name,
choice->name,
list->name);
return SC_ERROR_INVALID_ASN1_OBJECT;
}
choice = list;
}
list++;
}
if (choice == NULL)
goto no_object;
return asn1_encode_entry(ctx, choice, obj, objlen, depth + 1);
}
if (entry->type != SC_ASN1_NULL && parm == NULL) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "unexpected parm == NULL\n");
return SC_ERROR_INVALID_ASN1_OBJECT;
}
switch (entry->type) {
case SC_ASN1_STRUCT:
r = asn1_encode(ctx, (const struct sc_asn1_entry *) parm, &buf,
&buflen, depth + 1);
break;
case SC_ASN1_NULL:
buf = NULL;
buflen = 0;
break;
case SC_ASN1_BOOLEAN:
buf = malloc(1);
if (buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
buf[0] = *((int *) parm) ? 0xFF : 0;
buflen = 1;
break;
case SC_ASN1_INTEGER:
case SC_ASN1_ENUMERATED:
r = asn1_encode_integer(*((int *) entry->parm), &buf, &buflen);
break;
case SC_ASN1_BIT_STRING_NI:
case SC_ASN1_BIT_STRING:
if (len != NULL) {
if (entry->type == SC_ASN1_BIT_STRING)
r = encode_bit_string((const u8 *) parm, *len, &buf, &buflen, 1);
else
r = encode_bit_string((const u8 *) parm, *len, &buf, &buflen, 0);
} else {
r = SC_ERROR_INVALID_ARGUMENTS;
}
break;
case SC_ASN1_BIT_FIELD:
if (len != NULL) {
r = encode_bit_field((const u8 *) parm, *len, &buf, &buflen);
} else {
r = SC_ERROR_INVALID_ARGUMENTS;
}
break;
case SC_ASN1_PRINTABLESTRING:
case SC_ASN1_OCTET_STRING:
case SC_ASN1_UTF8STRING:
if (len != NULL) {
buf = malloc(*len + 1);
if (buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
buflen = 0;
/* If the integer is supposed to be unsigned, insert
* a padding byte if the MSB is one */
if ((entry->flags & SC_ASN1_UNSIGNED)
&& (((u8 *) parm)[0] & 0x80)) {
buf[buflen++] = 0x00;
}
memcpy(buf + buflen, parm, *len);
buflen += *len;
} else {
r = SC_ERROR_INVALID_ARGUMENTS;
}
break;
case SC_ASN1_GENERALIZEDTIME:
if (len != NULL) {
buf = malloc(*len);
if (buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
memcpy(buf, parm, *len);
buflen = *len;
} else {
r = SC_ERROR_INVALID_ARGUMENTS;
}
break;
case SC_ASN1_OBJECT:
r = sc_asn1_encode_object_id(&buf, &buflen, (struct sc_object_id *) parm);
break;
case SC_ASN1_PATH:
r = asn1_encode_path(ctx, (const sc_path_t *) parm, &buf, &buflen, depth, entry->flags);
break;
case SC_ASN1_PKCS15_ID:
{
const struct sc_pkcs15_id *id = (const struct sc_pkcs15_id *) parm;
buf = malloc(id->len);
if (buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
memcpy(buf, id->value, id->len);
buflen = id->len;
}
break;
case SC_ASN1_PKCS15_OBJECT:
r = asn1_encode_p15_object(ctx, (const struct sc_asn1_pkcs15_object *) parm, &buf, &buflen, depth);
break;
case SC_ASN1_ALGORITHM_ID:
r = sc_asn1_encode_algorithm_id(ctx, &buf, &buflen, (const struct sc_algorithm_id *) parm, depth);
break;
case SC_ASN1_SE_INFO:
if (!len)
return SC_ERROR_INVALID_ASN1_OBJECT;
r = asn1_encode_se_info(ctx, (struct sc_pkcs15_sec_env_info **)parm, *len, &buf, &buflen, depth);
break;
case SC_ASN1_CALLBACK:
r = callback_func(ctx, entry->arg, &buf, &buflen, depth);
break;
default:
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "invalid ASN.1 type: %d\n", entry->type);
return SC_ERROR_INVALID_ASN1_OBJECT;
}
if (r) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "encoding of ASN.1 object '%s' failed: %s\n", entry->name,
sc_strerror(r));
if (buf)
free(buf);
return r;
}
/* Treatment of OPTIONAL elements:
* - if the encoding has 0 length, and the element is OPTIONAL,
* we don't write anything (unless it's an ASN1 NULL and the
* SC_ASN1_PRESENT flag is set).
* - if the encoding has 0 length, but the element is non-OPTIONAL,
* constructed, we write a empty element (e.g. a SEQUENCE of
* length 0). In case of an ASN1 NULL just write the tag and
* length (i.e. 0x05,0x00).
* - any other empty objects are considered bogus
*/
no_object:
if (!buflen && entry->flags & SC_ASN1_OPTIONAL && !(entry->flags & SC_ASN1_PRESENT)) {
/* This happens when we try to encode e.g. the
* subClassAttributes, which may be empty */
*obj = NULL;
*objlen = 0;
r = 0;
} else if (!buflen && (entry->flags & SC_ASN1_EMPTY_ALLOWED)) {
*obj = NULL;
*objlen = 0;
r = asn1_write_element(ctx, entry->tag, buf, buflen, obj, objlen);
if (r)
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "error writing ASN.1 tag and length: %s\n", sc_strerror(r));
} else if (buflen || entry->type == SC_ASN1_NULL || entry->tag & SC_ASN1_CONS) {
r = asn1_write_element(ctx, entry->tag, buf, buflen, obj, objlen);
if (r)
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "error writing ASN.1 tag and length: %s\n",
sc_strerror(r));
} else if (!(entry->flags & SC_ASN1_PRESENT)) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "cannot encode non-optional ASN.1 object: not given by caller\n");
r = SC_ERROR_INVALID_ASN1_OBJECT;
} else {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "cannot encode empty non-optional ASN.1 object\n");
r = SC_ERROR_INVALID_ASN1_OBJECT;
}
if (buf)
free(buf);
if (r >= 0)
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"%*.*slength of encoded item=%"SC_FORMAT_LEN_SIZE_T"u\n",
depth, depth, "", *objlen);
return r;
}
static int asn1_encode(sc_context_t *ctx, const struct sc_asn1_entry *asn1,
u8 **ptr, size_t *size, int depth)
{
int r, idx = 0;
u8 *obj = NULL, *buf = NULL, *tmp;
size_t total = 0, objsize;
for (idx = 0; asn1[idx].name != NULL; idx++) {
r = asn1_encode_entry(ctx, &asn1[idx], &obj, &objsize, depth);
if (r) {
if (obj)
free(obj);
if (buf)
free(buf);
return r;
}
/* in case of an empty (optional) element continue with
* the next asn1 element */
if (!objsize)
continue;
tmp = (u8 *) realloc(buf, total + objsize);
if (!tmp) {
if (obj)
free(obj);
if (buf)
free(buf);
return SC_ERROR_OUT_OF_MEMORY;
}
buf = tmp;
memcpy(buf + total, obj, objsize);
free(obj);
obj = NULL;
total += objsize;
}
*ptr = buf;
*size = total;
return 0;
}
int sc_asn1_encode(sc_context_t *ctx, const struct sc_asn1_entry *asn1,
u8 **ptr, size_t *size)
{
return asn1_encode(ctx, asn1, ptr, size, 0);
}
int _sc_asn1_encode(sc_context_t *ctx, const struct sc_asn1_entry *asn1,
u8 **ptr, size_t *size, int depth)
{
return asn1_encode(ctx, asn1, ptr, size, depth);
}
int
_sc_asn1_decode(sc_context_t *ctx, struct sc_asn1_entry *asn1,
const u8 *in, size_t len, const u8 **newp, size_t *left,
int choice, int depth)
{
return asn1_decode(ctx, asn1, in, len, newp, left, choice, depth);
}
int
sc_der_copy(sc_pkcs15_der_t *dst, const sc_pkcs15_der_t *src)
{
if (!dst)
return SC_ERROR_INVALID_ARGUMENTS;
memset(dst, 0, sizeof(*dst));
if (src->len) {
dst->value = malloc(src->len);
if (!dst->value)
return SC_ERROR_OUT_OF_MEMORY;
dst->len = src->len;
memcpy(dst->value, src->value, src->len);
}
return SC_SUCCESS;
}
int
sc_encode_oid (struct sc_context *ctx, struct sc_object_id *id,
unsigned char **out, size_t *size)
{
static const struct sc_asn1_entry c_asn1_object_id[2] = {
{ "oid", SC_ASN1_OBJECT, SC_ASN1_TAG_OBJECT, SC_ASN1_ALLOC, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
struct sc_asn1_entry asn1_object_id[2];
int rv;
sc_copy_asn1_entry(c_asn1_object_id, asn1_object_id);
sc_format_asn1_entry(asn1_object_id + 0, id, NULL, 1);
rv = _sc_asn1_encode(ctx, asn1_object_id, out, size, 1);
LOG_TEST_RET(ctx, rv, "Cannot encode object ID");
return SC_SUCCESS;
}
#define C_ASN1_SIG_VALUE_SIZE 2
static struct sc_asn1_entry c_asn1_sig_value[C_ASN1_SIG_VALUE_SIZE] = {
{ "ECDSA-Sig-Value", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_SIG_VALUE_COEFFICIENTS_SIZE 3
static struct sc_asn1_entry c_asn1_sig_value_coefficients[C_ASN1_SIG_VALUE_COEFFICIENTS_SIZE] = {
{ "r", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_INTEGER, SC_ASN1_ALLOC|SC_ASN1_UNSIGNED, NULL, NULL },
{ "s", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_INTEGER, SC_ASN1_ALLOC|SC_ASN1_UNSIGNED, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
int
sc_asn1_sig_value_rs_to_sequence(struct sc_context *ctx, unsigned char *in, size_t inlen,
unsigned char **buf, size_t *buflen)
{
struct sc_asn1_entry asn1_sig_value[C_ASN1_SIG_VALUE_SIZE];
struct sc_asn1_entry asn1_sig_value_coefficients[C_ASN1_SIG_VALUE_COEFFICIENTS_SIZE];
unsigned char *r = in, *s = in + inlen/2;
size_t r_len = inlen/2, s_len = inlen/2;
int rv;
LOG_FUNC_CALLED(ctx);
/* R/S are filled up with zeroes, we do not want that in sequence format */
while(r_len > 1 && *r == 0x00) {
r++;
r_len--;
}
while(s_len > 1 && *s == 0x00) {
s++;
s_len--;
}
sc_copy_asn1_entry(c_asn1_sig_value, asn1_sig_value);
sc_format_asn1_entry(asn1_sig_value + 0, asn1_sig_value_coefficients, NULL, 1);
sc_copy_asn1_entry(c_asn1_sig_value_coefficients, asn1_sig_value_coefficients);
sc_format_asn1_entry(asn1_sig_value_coefficients + 0, r, &r_len, 1);
sc_format_asn1_entry(asn1_sig_value_coefficients + 1, s, &s_len, 1);
rv = sc_asn1_encode(ctx, asn1_sig_value, buf, buflen);
LOG_TEST_RET(ctx, rv, "ASN.1 encoding ECDSA-SIg-Value failed");
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
int
sc_asn1_sig_value_sequence_to_rs(struct sc_context *ctx, const unsigned char *in, size_t inlen,
unsigned char *buf, size_t buflen)
{
struct sc_asn1_entry asn1_sig_value[C_ASN1_SIG_VALUE_SIZE];
struct sc_asn1_entry asn1_sig_value_coefficients[C_ASN1_SIG_VALUE_COEFFICIENTS_SIZE];
unsigned char *r = NULL, *s = NULL;
size_t r_len, s_len, halflen = buflen/2;
int rv;
LOG_FUNC_CALLED(ctx);
if (!buf || !buflen)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
sc_copy_asn1_entry(c_asn1_sig_value, asn1_sig_value);
sc_format_asn1_entry(asn1_sig_value + 0, asn1_sig_value_coefficients, NULL, 0);
sc_copy_asn1_entry(c_asn1_sig_value_coefficients, asn1_sig_value_coefficients);
sc_format_asn1_entry(asn1_sig_value_coefficients + 0, &r, &r_len, 0);
sc_format_asn1_entry(asn1_sig_value_coefficients + 1, &s, &s_len, 0);
rv = sc_asn1_decode(ctx, asn1_sig_value, in, inlen, NULL, NULL);
LOG_TEST_GOTO_ERR(ctx, rv, "ASN.1 decoding ECDSA-Sig-Value failed");
if (halflen < r_len || halflen < s_len) {
rv = SC_ERROR_BUFFER_TOO_SMALL;
goto err;
}
memset(buf, 0, buflen);
memcpy(buf + (halflen - r_len), r, r_len);
memcpy(buf + (buflen - s_len), s, s_len);
sc_log(ctx, "r(%"SC_FORMAT_LEN_SIZE_T"u): %s", halflen,
sc_dump_hex(buf, halflen));
sc_log(ctx, "s(%"SC_FORMAT_LEN_SIZE_T"u): %s", halflen,
sc_dump_hex(buf + halflen, halflen));
rv = SC_SUCCESS;
err:
free(r);
free(s);
LOG_FUNC_RETURN(ctx, rv);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1064_0 |
crossvul-cpp_data_bad_2933_0 | /*
* Smacker decoder
* Copyright (c) 2006 Konstantin Shishkov
*
* This file is part of Libav.
*
* Libav is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Libav is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Libav; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* Smacker decoder
*/
/*
* Based on http://wiki.multimedia.cx/index.php?title=Smacker
*/
#include <stdio.h>
#include <stdlib.h>
#include "libavutil/channel_layout.h"
#define BITSTREAM_READER_LE
#include "avcodec.h"
#include "bitstream.h"
#include "bytestream.h"
#include "internal.h"
#include "mathops.h"
#include "vlc.h"
#define SMKTREE_BITS 9
#define SMK_NODE 0x80000000
typedef struct SmackVContext {
AVCodecContext *avctx;
AVFrame *pic;
int *mmap_tbl, *mclr_tbl, *full_tbl, *type_tbl;
int mmap_last[3], mclr_last[3], full_last[3], type_last[3];
} SmackVContext;
/**
* Context used for code reconstructing
*/
typedef struct HuffContext {
int length;
int maxlength;
int current;
uint32_t *bits;
int *lengths;
int *values;
} HuffContext;
/* common parameters used for decode_bigtree */
typedef struct DBCtx {
VLC *v1, *v2;
int *recode1, *recode2;
int escapes[3];
int *last;
int lcur;
} DBCtx;
/* possible runs of blocks */
static const int block_runs[64] = {
1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32,
33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, 52, 53, 54, 55, 56,
57, 58, 59, 128, 256, 512, 1024, 2048 };
enum SmkBlockTypes {
SMK_BLK_MONO = 0,
SMK_BLK_FULL = 1,
SMK_BLK_SKIP = 2,
SMK_BLK_FILL = 3 };
/**
* Decode local frame tree
*/
static int smacker_decode_tree(BitstreamContext *bc, HuffContext *hc,
uint32_t prefix, int length)
{
if (!bitstream_read_bit(bc)) { // Leaf
if(hc->current >= 256){
av_log(NULL, AV_LOG_ERROR, "Tree size exceeded!\n");
return AVERROR_INVALIDDATA;
}
if(length){
hc->bits[hc->current] = prefix;
hc->lengths[hc->current] = length;
} else {
hc->bits[hc->current] = 0;
hc->lengths[hc->current] = 0;
}
hc->values[hc->current] = bitstream_read(bc, 8);
hc->current++;
if(hc->maxlength < length)
hc->maxlength = length;
return 0;
} else { //Node
int r;
length++;
r = smacker_decode_tree(bc, hc, prefix, length);
if(r)
return r;
return smacker_decode_tree(bc, hc, prefix | (1 << (length - 1)), length);
}
}
/**
* Decode header tree
*/
static int smacker_decode_bigtree(BitstreamContext *bc, HuffContext *hc,
DBCtx *ctx)
{
if (hc->current + 1 >= hc->length) {
av_log(NULL, AV_LOG_ERROR, "Tree size exceeded!\n");
return AVERROR_INVALIDDATA;
}
if (!bitstream_read_bit(bc)) { // Leaf
int val, i1, i2;
i1 = ctx->v1->table ? bitstream_read_vlc(bc, ctx->v1->table, SMKTREE_BITS, 3) : 0;
i2 = ctx->v2->table ? bitstream_read_vlc(bc, ctx->v2->table, SMKTREE_BITS, 3) : 0;
if (i1 < 0 || i2 < 0)
return AVERROR_INVALIDDATA;
val = ctx->recode1[i1] | (ctx->recode2[i2] << 8);
if(val == ctx->escapes[0]) {
ctx->last[0] = hc->current;
val = 0;
} else if(val == ctx->escapes[1]) {
ctx->last[1] = hc->current;
val = 0;
} else if(val == ctx->escapes[2]) {
ctx->last[2] = hc->current;
val = 0;
}
hc->values[hc->current++] = val;
return 1;
} else { //Node
int r = 0, r_new, t;
t = hc->current++;
r = smacker_decode_bigtree(bc, hc, ctx);
if(r < 0)
return r;
hc->values[t] = SMK_NODE | r;
r++;
r_new = smacker_decode_bigtree(bc, hc, ctx);
if (r_new < 0)
return r_new;
return r + r_new;
}
}
/**
* Store large tree as Libav's vlc codes
*/
static int smacker_decode_header_tree(SmackVContext *smk, BitstreamContext *bc,
int **recodes, int *last, int size)
{
int res;
HuffContext huff;
HuffContext tmp1, tmp2;
VLC vlc[2] = { { 0 } };
int escapes[3];
DBCtx ctx;
int err = 0;
if(size >= UINT_MAX>>4){ // (((size + 3) >> 2) + 3) << 2 must not overflow
av_log(smk->avctx, AV_LOG_ERROR, "size too large\n");
return AVERROR_INVALIDDATA;
}
tmp1.length = 256;
tmp1.maxlength = 0;
tmp1.current = 0;
tmp1.bits = av_mallocz(256 * 4);
tmp1.lengths = av_mallocz(256 * sizeof(int));
tmp1.values = av_mallocz(256 * sizeof(int));
tmp2.length = 256;
tmp2.maxlength = 0;
tmp2.current = 0;
tmp2.bits = av_mallocz(256 * 4);
tmp2.lengths = av_mallocz(256 * sizeof(int));
tmp2.values = av_mallocz(256 * sizeof(int));
if (!tmp1.bits || !tmp1.lengths || !tmp1.values ||
!tmp2.bits || !tmp2.lengths || !tmp2.values) {
err = AVERROR(ENOMEM);
goto error;
}
if (bitstream_read_bit(bc)) {
smacker_decode_tree(bc, &tmp1, 0, 0);
bitstream_skip(bc, 1);
res = init_vlc(&vlc[0], SMKTREE_BITS, tmp1.length,
tmp1.lengths, sizeof(int), sizeof(int),
tmp1.bits, sizeof(uint32_t), sizeof(uint32_t), INIT_VLC_LE);
if(res < 0) {
av_log(smk->avctx, AV_LOG_ERROR, "Cannot build VLC table\n");
err = res;
goto error;
}
} else {
av_log(smk->avctx, AV_LOG_ERROR, "Skipping low bytes tree\n");
}
if (bitstream_read_bit(bc)) {
smacker_decode_tree(bc, &tmp2, 0, 0);
bitstream_skip(bc, 1);
res = init_vlc(&vlc[1], SMKTREE_BITS, tmp2.length,
tmp2.lengths, sizeof(int), sizeof(int),
tmp2.bits, sizeof(uint32_t), sizeof(uint32_t), INIT_VLC_LE);
if(res < 0) {
av_log(smk->avctx, AV_LOG_ERROR, "Cannot build VLC table\n");
err = res;
goto error;
}
} else {
av_log(smk->avctx, AV_LOG_ERROR, "Skipping high bytes tree\n");
}
escapes[0] = bitstream_read(bc, 8);
escapes[0] |= bitstream_read(bc, 8) << 8;
escapes[1] = bitstream_read(bc, 8);
escapes[1] |= bitstream_read(bc, 8) << 8;
escapes[2] = bitstream_read(bc, 8);
escapes[2] |= bitstream_read(bc, 8) << 8;
last[0] = last[1] = last[2] = -1;
ctx.escapes[0] = escapes[0];
ctx.escapes[1] = escapes[1];
ctx.escapes[2] = escapes[2];
ctx.v1 = &vlc[0];
ctx.v2 = &vlc[1];
ctx.recode1 = tmp1.values;
ctx.recode2 = tmp2.values;
ctx.last = last;
huff.length = ((size + 3) >> 2) + 4;
huff.maxlength = 0;
huff.current = 0;
huff.values = av_mallocz(huff.length * sizeof(int));
if (!huff.values) {
err = AVERROR(ENOMEM);
goto error;
}
if ((res = smacker_decode_bigtree(bc, &huff, &ctx)) < 0)
err = res;
bitstream_skip(bc, 1);
if(ctx.last[0] == -1) ctx.last[0] = huff.current++;
if(ctx.last[1] == -1) ctx.last[1] = huff.current++;
if(ctx.last[2] == -1) ctx.last[2] = huff.current++;
if (ctx.last[0] >= huff.length ||
ctx.last[1] >= huff.length ||
ctx.last[2] >= huff.length) {
av_log(smk->avctx, AV_LOG_ERROR, "Huffman codes out of range\n");
err = AVERROR_INVALIDDATA;
}
*recodes = huff.values;
error:
if(vlc[0].table)
ff_free_vlc(&vlc[0]);
if(vlc[1].table)
ff_free_vlc(&vlc[1]);
av_free(tmp1.bits);
av_free(tmp1.lengths);
av_free(tmp1.values);
av_free(tmp2.bits);
av_free(tmp2.lengths);
av_free(tmp2.values);
return err;
}
static int decode_header_trees(SmackVContext *smk) {
BitstreamContext bc;
int mmap_size, mclr_size, full_size, type_size, ret;
mmap_size = AV_RL32(smk->avctx->extradata);
mclr_size = AV_RL32(smk->avctx->extradata + 4);
full_size = AV_RL32(smk->avctx->extradata + 8);
type_size = AV_RL32(smk->avctx->extradata + 12);
bitstream_init8(&bc, smk->avctx->extradata + 16, smk->avctx->extradata_size - 16);
if (!bitstream_read_bit(&bc)) {
av_log(smk->avctx, AV_LOG_INFO, "Skipping MMAP tree\n");
smk->mmap_tbl = av_malloc(sizeof(int) * 2);
if (!smk->mmap_tbl)
return AVERROR(ENOMEM);
smk->mmap_tbl[0] = 0;
smk->mmap_last[0] = smk->mmap_last[1] = smk->mmap_last[2] = 1;
} else {
if ((ret = smacker_decode_header_tree(smk, &bc, &smk->mmap_tbl, smk->mmap_last, mmap_size)) < 0)
return ret;
}
if (!bitstream_read_bit(&bc)) {
av_log(smk->avctx, AV_LOG_INFO, "Skipping MCLR tree\n");
smk->mclr_tbl = av_malloc(sizeof(int) * 2);
if (!smk->mclr_tbl)
return AVERROR(ENOMEM);
smk->mclr_tbl[0] = 0;
smk->mclr_last[0] = smk->mclr_last[1] = smk->mclr_last[2] = 1;
} else {
if ((ret = smacker_decode_header_tree(smk, &bc, &smk->mclr_tbl, smk->mclr_last, mclr_size)) < 0)
return ret;
}
if (!bitstream_read_bit(&bc)) {
av_log(smk->avctx, AV_LOG_INFO, "Skipping FULL tree\n");
smk->full_tbl = av_malloc(sizeof(int) * 2);
if (!smk->full_tbl)
return AVERROR(ENOMEM);
smk->full_tbl[0] = 0;
smk->full_last[0] = smk->full_last[1] = smk->full_last[2] = 1;
} else {
if ((ret = smacker_decode_header_tree(smk, &bc, &smk->full_tbl, smk->full_last, full_size)) < 0)
return ret;
}
if (!bitstream_read_bit(&bc)) {
av_log(smk->avctx, AV_LOG_INFO, "Skipping TYPE tree\n");
smk->type_tbl = av_malloc(sizeof(int) * 2);
if (!smk->type_tbl)
return AVERROR(ENOMEM);
smk->type_tbl[0] = 0;
smk->type_last[0] = smk->type_last[1] = smk->type_last[2] = 1;
} else {
if ((ret = smacker_decode_header_tree(smk, &bc, &smk->type_tbl, smk->type_last, type_size)) < 0)
return ret;
}
return 0;
}
static av_always_inline void last_reset(int *recode, int *last) {
recode[last[0]] = recode[last[1]] = recode[last[2]] = 0;
}
/* get code and update history */
static av_always_inline int smk_get_code(BitstreamContext *bc, int *recode,
int *last)
{
register int *table = recode;
int v;
while(*table & SMK_NODE) {
if (bitstream_read_bit(bc))
table += (*table) & (~SMK_NODE);
table++;
}
v = *table;
if(v != recode[last[0]]) {
recode[last[2]] = recode[last[1]];
recode[last[1]] = recode[last[0]];
recode[last[0]] = v;
}
return v;
}
static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
AVPacket *avpkt)
{
SmackVContext * const smk = avctx->priv_data;
uint8_t *out;
uint32_t *pal;
GetByteContext gb2;
BitstreamContext bc;
int blocks, blk, bw, bh;
int i, ret;
int stride;
int flags;
if (avpkt->size <= 769)
return 0;
if ((ret = ff_reget_buffer(avctx, smk->pic)) < 0) {
av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
return ret;
}
/* make the palette available on the way out */
pal = (uint32_t*)smk->pic->data[1];
bytestream2_init(&gb2, avpkt->data, avpkt->size);
flags = bytestream2_get_byteu(&gb2);
smk->pic->palette_has_changed = flags & 1;
smk->pic->key_frame = !!(flags & 2);
if(smk->pic->key_frame)
smk->pic->pict_type = AV_PICTURE_TYPE_I;
else
smk->pic->pict_type = AV_PICTURE_TYPE_P;
for(i = 0; i < 256; i++)
*pal++ = bytestream2_get_be24u(&gb2);
last_reset(smk->mmap_tbl, smk->mmap_last);
last_reset(smk->mclr_tbl, smk->mclr_last);
last_reset(smk->full_tbl, smk->full_last);
last_reset(smk->type_tbl, smk->type_last);
bitstream_init8(&bc, avpkt->data + 769, avpkt->size - 769);
blk = 0;
bw = avctx->width >> 2;
bh = avctx->height >> 2;
blocks = bw * bh;
out = smk->pic->data[0];
stride = smk->pic->linesize[0];
while(blk < blocks) {
int type, run, mode;
uint16_t pix;
type = smk_get_code(&bc, smk->type_tbl, smk->type_last);
run = block_runs[(type >> 2) & 0x3F];
switch(type & 3){
case SMK_BLK_MONO:
while(run-- && blk < blocks){
int clr, map;
int hi, lo;
clr = smk_get_code(&bc, smk->mclr_tbl, smk->mclr_last);
map = smk_get_code(&bc, smk->mmap_tbl, smk->mmap_last);
out = smk->pic->data[0] + (blk / bw) * (stride * 4) + (blk % bw) * 4;
hi = clr >> 8;
lo = clr & 0xFF;
for(i = 0; i < 4; i++) {
if(map & 1) out[0] = hi; else out[0] = lo;
if(map & 2) out[1] = hi; else out[1] = lo;
if(map & 4) out[2] = hi; else out[2] = lo;
if(map & 8) out[3] = hi; else out[3] = lo;
map >>= 4;
out += stride;
}
blk++;
}
break;
case SMK_BLK_FULL:
mode = 0;
if(avctx->codec_tag == MKTAG('S', 'M', 'K', '4')) { // In case of Smacker v4 we have three modes
if (bitstream_read_bit(&bc))
mode = 1;
else if (bitstream_read_bit(&bc))
mode = 2;
}
while(run-- && blk < blocks){
out = smk->pic->data[0] + (blk / bw) * (stride * 4) + (blk % bw) * 4;
switch(mode){
case 0:
for(i = 0; i < 4; i++) {
pix = smk_get_code(&bc, smk->full_tbl, smk->full_last);
AV_WL16(out+2,pix);
pix = smk_get_code(&bc, smk->full_tbl, smk->full_last);
AV_WL16(out,pix);
out += stride;
}
break;
case 1:
pix = smk_get_code(&bc, smk->full_tbl, smk->full_last);
out[0] = out[1] = pix & 0xFF;
out[2] = out[3] = pix >> 8;
out += stride;
out[0] = out[1] = pix & 0xFF;
out[2] = out[3] = pix >> 8;
out += stride;
pix = smk_get_code(&bc, smk->full_tbl, smk->full_last);
out[0] = out[1] = pix & 0xFF;
out[2] = out[3] = pix >> 8;
out += stride;
out[0] = out[1] = pix & 0xFF;
out[2] = out[3] = pix >> 8;
out += stride;
break;
case 2:
for(i = 0; i < 2; i++) {
uint16_t pix1, pix2;
pix2 = smk_get_code(&bc, smk->full_tbl, smk->full_last);
pix1 = smk_get_code(&bc, smk->full_tbl, smk->full_last);
AV_WL16(out,pix1);
AV_WL16(out+2,pix2);
out += stride;
AV_WL16(out,pix1);
AV_WL16(out+2,pix2);
out += stride;
}
break;
}
blk++;
}
break;
case SMK_BLK_SKIP:
while(run-- && blk < blocks)
blk++;
break;
case SMK_BLK_FILL:
mode = type >> 8;
while(run-- && blk < blocks){
uint32_t col;
out = smk->pic->data[0] + (blk / bw) * (stride * 4) + (blk % bw) * 4;
col = mode * 0x01010101;
for(i = 0; i < 4; i++) {
*((uint32_t*)out) = col;
out += stride;
}
blk++;
}
break;
}
}
if ((ret = av_frame_ref(data, smk->pic)) < 0)
return ret;
*got_frame = 1;
/* always report that the buffer was completely consumed */
return avpkt->size;
}
static av_cold int decode_end(AVCodecContext *avctx)
{
SmackVContext * const smk = avctx->priv_data;
av_freep(&smk->mmap_tbl);
av_freep(&smk->mclr_tbl);
av_freep(&smk->full_tbl);
av_freep(&smk->type_tbl);
av_frame_free(&smk->pic);
return 0;
}
static av_cold int decode_init(AVCodecContext *avctx)
{
SmackVContext * const c = avctx->priv_data;
int ret;
c->avctx = avctx;
avctx->pix_fmt = AV_PIX_FMT_PAL8;
c->pic = av_frame_alloc();
if (!c->pic)
return AVERROR(ENOMEM);
/* decode huffman trees from extradata */
if(avctx->extradata_size < 16){
av_log(avctx, AV_LOG_ERROR, "Extradata missing!\n");
return AVERROR_INVALIDDATA;
}
if ((ret = decode_header_trees(c))) {
decode_end(avctx);
return ret;
}
return 0;
}
static av_cold int smka_decode_init(AVCodecContext *avctx)
{
if (avctx->channels < 1 || avctx->channels > 2) {
av_log(avctx, AV_LOG_ERROR, "invalid number of channels\n");
return AVERROR_INVALIDDATA;
}
avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
avctx->sample_fmt = avctx->bits_per_coded_sample == 8 ? AV_SAMPLE_FMT_U8 : AV_SAMPLE_FMT_S16;
return 0;
}
/**
* Decode Smacker audio data
*/
static int smka_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame_ptr, AVPacket *avpkt)
{
AVFrame *frame = data;
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
BitstreamContext bc;
HuffContext h[4] = { { 0 } };
VLC vlc[4] = { { 0 } };
int16_t *samples;
uint8_t *samples8;
int val;
int i, res, ret;
int unp_size;
int bits, stereo;
int pred[2] = {0, 0};
if (buf_size <= 4) {
av_log(avctx, AV_LOG_ERROR, "packet is too small\n");
return AVERROR_INVALIDDATA;
}
unp_size = AV_RL32(buf);
bitstream_init8(&bc, buf + 4, buf_size - 4);
if (!bitstream_read_bit(&bc)) {
av_log(avctx, AV_LOG_INFO, "Sound: no data\n");
*got_frame_ptr = 0;
return 1;
}
stereo = bitstream_read_bit(&bc);
bits = bitstream_read_bit(&bc);
if (stereo ^ (avctx->channels != 1)) {
av_log(avctx, AV_LOG_ERROR, "channels mismatch\n");
return AVERROR_INVALIDDATA;
}
if (bits && avctx->sample_fmt == AV_SAMPLE_FMT_U8) {
av_log(avctx, AV_LOG_ERROR, "sample format mismatch\n");
return AVERROR_INVALIDDATA;
}
if (unp_size % (avctx->channels * (bits + 1))) {
av_log(avctx, AV_LOG_ERROR,
"The buffer does not contain an integer number of samples\n");
return AVERROR_INVALIDDATA;
}
/* get output buffer */
frame->nb_samples = unp_size / (avctx->channels * (bits + 1));
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
return ret;
}
samples = (int16_t *)frame->data[0];
samples8 = frame->data[0];
// Initialize
for(i = 0; i < (1 << (bits + stereo)); i++) {
h[i].length = 256;
h[i].maxlength = 0;
h[i].current = 0;
h[i].bits = av_mallocz(256 * 4);
h[i].lengths = av_mallocz(256 * sizeof(int));
h[i].values = av_mallocz(256 * sizeof(int));
if (!h[i].bits || !h[i].lengths || !h[i].values) {
ret = AVERROR(ENOMEM);
goto error;
}
bitstream_skip(&bc, 1);
if (smacker_decode_tree(&bc, &h[i], 0, 0) < 0) {
ret = AVERROR_INVALIDDATA;
goto error;
}
bitstream_skip(&bc, 1);
if(h[i].current > 1) {
res = init_vlc(&vlc[i], SMKTREE_BITS, h[i].length,
h[i].lengths, sizeof(int), sizeof(int),
h[i].bits, sizeof(uint32_t), sizeof(uint32_t), INIT_VLC_LE);
if(res < 0) {
av_log(avctx, AV_LOG_ERROR, "Cannot build VLC table\n");
ret = AVERROR_INVALIDDATA;
goto error;
}
}
}
/* this codec relies on wraparound instead of clipping audio */
if(bits) { //decode 16-bit data
for(i = stereo; i >= 0; i--)
pred[i] = sign_extend(av_bswap16(bitstream_read(&bc, 16)), 16);
for(i = 0; i <= stereo; i++)
*samples++ = pred[i];
for(; i < unp_size / 2; i++) {
if(i & stereo) {
if(vlc[2].table)
res = bitstream_read_vlc(&bc, vlc[2].table, SMKTREE_BITS, 3);
else
res = 0;
val = h[2].values[res];
if(vlc[3].table)
res = bitstream_read_vlc(&bc, vlc[3].table, SMKTREE_BITS, 3);
else
res = 0;
val |= h[3].values[res] << 8;
pred[1] += sign_extend(val, 16);
*samples++ = pred[1];
} else {
if(vlc[0].table)
res = bitstream_read_vlc(&bc, vlc[0].table, SMKTREE_BITS, 3);
else
res = 0;
val = h[0].values[res];
if(vlc[1].table)
res = bitstream_read_vlc(&bc, vlc[1].table, SMKTREE_BITS, 3);
else
res = 0;
val |= h[1].values[res] << 8;
pred[0] += sign_extend(val, 16);
*samples++ = pred[0];
}
}
} else { //8-bit data
for(i = stereo; i >= 0; i--)
pred[i] = bitstream_read(&bc, 8);
for(i = 0; i <= stereo; i++)
*samples8++ = pred[i];
for(; i < unp_size; i++) {
if(i & stereo){
if(vlc[1].table)
res = bitstream_read_vlc(&bc, vlc[1].table, SMKTREE_BITS, 3);
else
res = 0;
pred[1] += sign_extend(h[1].values[res], 8);
*samples8++ = pred[1];
} else {
if(vlc[0].table)
res = bitstream_read_vlc(&bc, vlc[0].table, SMKTREE_BITS, 3);
else
res = 0;
pred[0] += sign_extend(h[0].values[res], 8);
*samples8++ = pred[0];
}
}
}
*got_frame_ptr = 1;
ret = buf_size;
error:
for(i = 0; i < 4; i++) {
if(vlc[i].table)
ff_free_vlc(&vlc[i]);
av_free(h[i].bits);
av_free(h[i].lengths);
av_free(h[i].values);
}
return ret;
}
AVCodec ff_smacker_decoder = {
.name = "smackvid",
.long_name = NULL_IF_CONFIG_SMALL("Smacker video"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_SMACKVIDEO,
.priv_data_size = sizeof(SmackVContext),
.init = decode_init,
.close = decode_end,
.decode = decode_frame,
.capabilities = AV_CODEC_CAP_DR1,
};
AVCodec ff_smackaud_decoder = {
.name = "smackaud",
.long_name = NULL_IF_CONFIG_SMALL("Smacker audio"),
.type = AVMEDIA_TYPE_AUDIO,
.id = AV_CODEC_ID_SMACKAUDIO,
.init = smka_decode_init,
.decode = smka_decode_frame,
.capabilities = AV_CODEC_CAP_DR1,
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2933_0 |
crossvul-cpp_data_bad_346_9 | /*
* Copyright (C) 2017 Frank Morgner <frankmorgner@gmail.com>
*
* This file is part of OpenSC.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "egk-tool-cmdline.h"
#include "libopensc/log.h"
#include "libopensc/opensc.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#endif
#ifdef ENABLE_ZLIB
#include <zlib.h>
int uncompress_gzip(void* uncompressed, size_t *uncompressed_len,
const void* compressed, size_t compressed_len)
{
z_stream stream;
memset(&stream, 0, sizeof stream);
stream.total_in = compressed_len;
stream.avail_in = compressed_len;
stream.total_out = *uncompressed_len;
stream.avail_out = *uncompressed_len;
stream.next_in = (Bytef *) compressed;
stream.next_out = (Bytef *) uncompressed;
/* 15 window bits, and the +32 tells zlib to to detect if using gzip or zlib */
if (Z_OK == inflateInit2(&stream, (15 + 32))
&& Z_STREAM_END == inflate(&stream, Z_FINISH)) {
*uncompressed_len = stream.total_out;
} else {
return SC_ERROR_INVALID_DATA;
}
inflateEnd(&stream);
return SC_SUCCESS;
}
#else
int uncompress_gzip(void* uncompressed, size_t *uncompressed_len,
const void* compressed, size_t compressed_len)
{
return SC_ERROR_NOT_SUPPORTED;
}
#endif
#define PRINT(c) (isprint(c) ? c : '?')
void dump_binary(void *buf, size_t buf_len)
{
#ifdef _WIN32
_setmode(fileno(stdout), _O_BINARY);
#endif
fwrite(buf, 1, buf_len, stdout);
#ifdef _WIN32
_setmode(fileno(stdout), _O_TEXT);
#endif
}
const unsigned char aid_hca[] = {0xD2, 0x76, 0x00, 0x00, 0x01, 0x02};
static int initialize(int reader_id, int verbose,
sc_context_t **ctx, sc_reader_t **reader)
{
unsigned int i, reader_count;
int r;
if (!ctx || !reader)
return SC_ERROR_INVALID_ARGUMENTS;
r = sc_establish_context(ctx, "");
if (r < 0 || !*ctx) {
fprintf(stderr, "Failed to create initial context: %s", sc_strerror(r));
return r;
}
(*ctx)->debug = verbose;
(*ctx)->flags |= SC_CTX_FLAG_ENABLE_DEFAULT_DRIVER;
reader_count = sc_ctx_get_reader_count(*ctx);
if (reader_count == 0) {
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "No reader not found.\n");
return SC_ERROR_NO_READERS_FOUND;
}
if (reader_id < 0) {
/* Automatically try to skip to a reader with a card if reader not specified */
for (i = 0; i < reader_count; i++) {
*reader = sc_ctx_get_reader(*ctx, i);
if (sc_detect_card_presence(*reader) & SC_READER_CARD_PRESENT) {
reader_id = i;
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "Using the first reader"
" with a card: %s", (*reader)->name);
break;
}
}
if ((unsigned int) reader_id >= reader_count) {
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "No card found, using the first reader.");
reader_id = 0;
}
}
if ((unsigned int) reader_id >= reader_count) {
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "Invalid reader number "
"(%d), only %d available.\n", reader_id, reader_count);
return SC_ERROR_NO_READERS_FOUND;
}
*reader = sc_ctx_get_reader(*ctx, reader_id);
return SC_SUCCESS;
}
int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len)
{
struct sc_path path;
struct sc_file *file;
unsigned char *p;
int ok = 0;
int r;
size_t len;
sc_format_path(str_path, &path);
if (SC_SUCCESS != sc_select_file(card, &path, &file)) {
goto err;
}
len = file ? file->size : 4096;
p = realloc(*data, len);
if (!p) {
goto err;
}
*data = p;
*data_len = len;
r = sc_read_binary(card, 0, p, len, 0);
if (r < 0)
goto err;
*data_len = r;
ok = 1;
err:
sc_file_free(file);
return ok;
}
void decode_version(unsigned char *bcd, unsigned int *major, unsigned int *minor, unsigned int *fix)
{
*major = 0;
*minor = 0;
*fix = 0;
/* decode BCD to decimal */
if ((bcd[0]>>4) < 10 && ((bcd[0]&0xF) < 10) && ((bcd[1]>>4) < 10)) {
*major = (bcd[0]>>4)*100 + (bcd[0]&0xF)*10 + (bcd[1]>>4);
}
if (((bcd[1]&0xF) < 10) && ((bcd[2]>>4) < 10) && ((bcd[2]&0xF) < 10)) {
*minor = (bcd[1]&0xF)*100 + (bcd[2]>>4)*10 + (bcd[2]&0xF);
}
if ((bcd[3]>>4) < 10 && ((bcd[3]&0xF) < 10)
&& (bcd[4]>>4) < 10 && ((bcd[4]&0xF) < 10)) {
*fix = (bcd[3]>>4)*1000 + (bcd[3]&0xF)*100
+ (bcd[4]>>4)*10 + (bcd[4]&0xF);
}
}
int
main (int argc, char **argv)
{
struct gengetopt_args_info cmdline;
struct sc_path path;
struct sc_context *ctx;
struct sc_reader *reader = NULL;
struct sc_card *card;
unsigned char *data = NULL;
size_t data_len = 0;
int r;
if (cmdline_parser(argc, argv, &cmdline) != 0)
exit(1);
r = initialize(cmdline.reader_arg, cmdline.verbose_given, &ctx, &reader);
if (r < 0) {
fprintf(stderr, "Can't initialize reader\n");
exit(1);
}
if (sc_connect_card(reader, &card) < 0) {
fprintf(stderr, "Could not connect to card\n");
sc_release_context(ctx);
exit(1);
}
sc_path_set(&path, SC_PATH_TYPE_DF_NAME, aid_hca, sizeof aid_hca, 0, 0);
if (SC_SUCCESS != sc_select_file(card, &path, NULL))
goto err;
if (cmdline.pd_flag
&& read_file(card, "D001", &data, &data_len)
&& data_len >= 2) {
size_t len_pd = (data[0] << 8) | data[1];
if (len_pd + 2 <= data_len) {
unsigned char uncompressed[1024];
size_t uncompressed_len = sizeof uncompressed;
if (uncompress_gzip(uncompressed, &uncompressed_len,
data + 2, len_pd) == SC_SUCCESS) {
dump_binary(uncompressed, uncompressed_len);
} else {
dump_binary(data + 2, len_pd);
}
}
}
if ((cmdline.vd_flag || cmdline.gvd_flag)
&& read_file(card, "D001", &data, &data_len)
&& data_len >= 8) {
size_t off_vd = (data[0] << 8) | data[1];
size_t end_vd = (data[2] << 8) | data[3];
size_t off_gvd = (data[4] << 8) | data[5];
size_t end_gvd = (data[6] << 8) | data[7];
size_t len_vd = end_vd - off_vd + 1;
size_t len_gvd = end_gvd - off_gvd + 1;
if (off_vd <= end_vd && end_vd < data_len
&& off_gvd <= end_gvd && end_gvd < data_len) {
unsigned char uncompressed[1024];
size_t uncompressed_len = sizeof uncompressed;
if (cmdline.vd_flag) {
if (uncompress_gzip(uncompressed, &uncompressed_len,
data + off_vd, len_vd) == SC_SUCCESS) {
dump_binary(uncompressed, uncompressed_len);
} else {
dump_binary(data + off_vd, len_vd);
}
}
if (cmdline.gvd_flag) {
if (uncompress_gzip(uncompressed, &uncompressed_len,
data + off_gvd, len_gvd) == SC_SUCCESS) {
dump_binary(uncompressed, uncompressed_len);
} else {
dump_binary(data + off_gvd, len_gvd);
}
}
}
}
if (cmdline.vsd_status_flag
&& read_file(card, "D00C", &data, &data_len)
&& data_len >= 25) {
char *status;
unsigned int major, minor, fix;
switch (data[0]) {
case '0':
status = "Transactions pending";
break;
case '1':
status = "No transactions pending";
break;
default:
status = "Unknown";
break;
}
decode_version(data+15, &major, &minor, &fix);
printf(
"Status %s\n"
"Timestamp %c%c.%c%c.%c%c%c%c at %c%c:%c%c:%c%c\n"
"Version %u.%u.%u\n",
status,
PRINT(data[7]), PRINT(data[8]),
PRINT(data[5]), PRINT(data[6]),
PRINT(data[1]), PRINT(data[2]), PRINT(data[3]), PRINT(data[4]),
PRINT(data[9]), PRINT(data[10]),
PRINT(data[11]), PRINT(data[12]),
PRINT(data[13]), PRINT(data[14]),
major, minor, fix);
}
err:
sc_disconnect_card(card);
sc_release_context(ctx);
cmdline_parser_free (&cmdline);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_346_9 |
crossvul-cpp_data_good_2_0 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* RFC1870 SMTP Service Extension for Message Size
* RFC2195 CRAM-MD5 authentication
* RFC2831 DIGEST-MD5 authentication
* RFC3207 SMTP over TLS
* RFC4422 Simple Authentication and Security Layer (SASL)
* RFC4616 PLAIN authentication
* RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism
* RFC4954 SMTP Authentication
* RFC5321 SMTP protocol
* RFC6749 OAuth 2.0 Authorization Framework
* Draft SMTP URL Interface <draft-earhart-url-smtp-00.txt>
* Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt>
*
***************************************************************************/
#include "curl_setup.h"
#ifndef CURL_DISABLE_SMTP
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_UTSNAME_H
#include <sys/utsname.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef __VMS
#include <in.h>
#include <inet.h>
#endif
#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
#undef in_addr_t
#define in_addr_t unsigned long
#endif
#include <curl/curl.h>
#include "urldata.h"
#include "sendf.h"
#include "hostip.h"
#include "progress.h"
#include "transfer.h"
#include "escape.h"
#include "http.h" /* for HTTP proxy tunnel stuff */
#include "mime.h"
#include "socks.h"
#include "smtp.h"
#include "strtoofft.h"
#include "strcase.h"
#include "vtls/vtls.h"
#include "connect.h"
#include "strerror.h"
#include "select.h"
#include "multiif.h"
#include "url.h"
#include "curl_gethostname.h"
#include "curl_sasl.h"
#include "warnless.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
/* Local API functions */
static CURLcode smtp_regular_transfer(struct connectdata *conn, bool *done);
static CURLcode smtp_do(struct connectdata *conn, bool *done);
static CURLcode smtp_done(struct connectdata *conn, CURLcode status,
bool premature);
static CURLcode smtp_connect(struct connectdata *conn, bool *done);
static CURLcode smtp_disconnect(struct connectdata *conn, bool dead);
static CURLcode smtp_multi_statemach(struct connectdata *conn, bool *done);
static int smtp_getsock(struct connectdata *conn, curl_socket_t *socks,
int numsocks);
static CURLcode smtp_doing(struct connectdata *conn, bool *dophase_done);
static CURLcode smtp_setup_connection(struct connectdata *conn);
static CURLcode smtp_parse_url_options(struct connectdata *conn);
static CURLcode smtp_parse_url_path(struct connectdata *conn);
static CURLcode smtp_parse_custom_request(struct connectdata *conn);
static CURLcode smtp_perform_auth(struct connectdata *conn, const char *mech,
const char *initresp);
static CURLcode smtp_continue_auth(struct connectdata *conn, const char *resp);
static void smtp_get_message(char *buffer, char **outptr);
/*
* SMTP protocol handler.
*/
const struct Curl_handler Curl_handler_smtp = {
"SMTP", /* scheme */
smtp_setup_connection, /* setup_connection */
smtp_do, /* do_it */
smtp_done, /* done */
ZERO_NULL, /* do_more */
smtp_connect, /* connect_it */
smtp_multi_statemach, /* connecting */
smtp_doing, /* doing */
smtp_getsock, /* proto_getsock */
smtp_getsock, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
smtp_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
PORT_SMTP, /* defport */
CURLPROTO_SMTP, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY | /* flags */
PROTOPT_URLOPTIONS
};
#ifdef USE_SSL
/*
* SMTPS protocol handler.
*/
const struct Curl_handler Curl_handler_smtps = {
"SMTPS", /* scheme */
smtp_setup_connection, /* setup_connection */
smtp_do, /* do_it */
smtp_done, /* done */
ZERO_NULL, /* do_more */
smtp_connect, /* connect_it */
smtp_multi_statemach, /* connecting */
smtp_doing, /* doing */
smtp_getsock, /* proto_getsock */
smtp_getsock, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
smtp_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
PORT_SMTPS, /* defport */
CURLPROTO_SMTPS, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_SSL
| PROTOPT_NOURLQUERY | PROTOPT_URLOPTIONS /* flags */
};
#endif
/* SASL parameters for the smtp protocol */
static const struct SASLproto saslsmtp = {
"smtp", /* The service name */
334, /* Code received when continuation is expected */
235, /* Code to receive upon authentication success */
512 - 8, /* Maximum initial response length (no max) */
smtp_perform_auth, /* Send authentication command */
smtp_continue_auth, /* Send authentication continuation */
smtp_get_message /* Get SASL response message */
};
#ifdef USE_SSL
static void smtp_to_smtps(struct connectdata *conn)
{
/* Change the connection handler */
conn->handler = &Curl_handler_smtps;
/* Set the connection's upgraded to TLS flag */
conn->tls_upgraded = TRUE;
}
#else
#define smtp_to_smtps(x) Curl_nop_stmt
#endif
/***********************************************************************
*
* smtp_endofresp()
*
* Checks for an ending SMTP status code at the start of the given string, but
* also detects various capabilities from the EHLO response including the
* supported authentication mechanisms.
*/
static bool smtp_endofresp(struct connectdata *conn, char *line, size_t len,
int *resp)
{
struct smtp_conn *smtpc = &conn->proto.smtpc;
bool result = FALSE;
/* Nothing for us */
if(len < 4 || !ISDIGIT(line[0]) || !ISDIGIT(line[1]) || !ISDIGIT(line[2]))
return FALSE;
/* Do we have a command response? This should be the response code followed
by a space and optionally some text as per RFC-5321 and as outlined in
Section 4. Examples of RFC-4954 but some e-mail servers ignore this and
only send the response code instead as per Section 4.2. */
if(line[3] == ' ' || len == 5) {
result = TRUE;
*resp = curlx_sltosi(strtol(line, NULL, 10));
/* Make sure real server never sends internal value */
if(*resp == 1)
*resp = 0;
}
/* Do we have a multiline (continuation) response? */
else if(line[3] == '-' &&
(smtpc->state == SMTP_EHLO || smtpc->state == SMTP_COMMAND)) {
result = TRUE;
*resp = 1; /* Internal response code */
}
return result;
}
/***********************************************************************
*
* smtp_get_message()
*
* Gets the authentication message from the response buffer.
*/
static void smtp_get_message(char *buffer, char **outptr)
{
size_t len = strlen(buffer);
char *message = NULL;
if(len > 4) {
/* Find the start of the message */
len -= 4;
for(message = buffer + 4; *message == ' ' || *message == '\t';
message++, len--)
;
/* Find the end of the message */
for(; len--;)
if(message[len] != '\r' && message[len] != '\n' && message[len] != ' ' &&
message[len] != '\t')
break;
/* Terminate the message */
if(++len) {
message[len] = '\0';
}
}
else
/* junk input => zero length output */
message = &buffer[len];
*outptr = message;
}
/***********************************************************************
*
* state()
*
* This is the ONLY way to change SMTP state!
*/
static void state(struct connectdata *conn, smtpstate newstate)
{
struct smtp_conn *smtpc = &conn->proto.smtpc;
#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
/* for debug purposes */
static const char * const names[] = {
"STOP",
"SERVERGREET",
"EHLO",
"HELO",
"STARTTLS",
"UPGRADETLS",
"AUTH",
"COMMAND",
"MAIL",
"RCPT",
"DATA",
"POSTDATA",
"QUIT",
/* LAST */
};
if(smtpc->state != newstate)
infof(conn->data, "SMTP %p state change from %s to %s\n",
(void *)smtpc, names[smtpc->state], names[newstate]);
#endif
smtpc->state = newstate;
}
/***********************************************************************
*
* smtp_perform_ehlo()
*
* Sends the EHLO command to not only initialise communication with the ESMTP
* server but to also obtain a list of server side supported capabilities.
*/
static CURLcode smtp_perform_ehlo(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct smtp_conn *smtpc = &conn->proto.smtpc;
smtpc->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanism yet */
smtpc->sasl.authused = SASL_AUTH_NONE; /* Clear the authentication mechanism
used for esmtp connections */
smtpc->tls_supported = FALSE; /* Clear the TLS capability */
smtpc->auth_supported = FALSE; /* Clear the AUTH capability */
/* Send the EHLO command */
result = Curl_pp_sendf(&smtpc->pp, "EHLO %s", smtpc->domain);
if(!result)
state(conn, SMTP_EHLO);
return result;
}
/***********************************************************************
*
* smtp_perform_helo()
*
* Sends the HELO command to initialise communication with the SMTP server.
*/
static CURLcode smtp_perform_helo(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct smtp_conn *smtpc = &conn->proto.smtpc;
smtpc->sasl.authused = SASL_AUTH_NONE; /* No authentication mechanism used
in smtp connections */
/* Send the HELO command */
result = Curl_pp_sendf(&smtpc->pp, "HELO %s", smtpc->domain);
if(!result)
state(conn, SMTP_HELO);
return result;
}
/***********************************************************************
*
* smtp_perform_starttls()
*
* Sends the STLS command to start the upgrade to TLS.
*/
static CURLcode smtp_perform_starttls(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
/* Send the STARTTLS command */
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", "STARTTLS");
if(!result)
state(conn, SMTP_STARTTLS);
return result;
}
/***********************************************************************
*
* smtp_perform_upgrade_tls()
*
* Performs the upgrade to TLS.
*/
static CURLcode smtp_perform_upgrade_tls(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct smtp_conn *smtpc = &conn->proto.smtpc;
/* Start the SSL connection */
result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &smtpc->ssldone);
if(!result) {
if(smtpc->state != SMTP_UPGRADETLS)
state(conn, SMTP_UPGRADETLS);
if(smtpc->ssldone) {
smtp_to_smtps(conn);
result = smtp_perform_ehlo(conn);
}
}
return result;
}
/***********************************************************************
*
* smtp_perform_auth()
*
* Sends an AUTH command allowing the client to login with the given SASL
* authentication mechanism.
*/
static CURLcode smtp_perform_auth(struct connectdata *conn,
const char *mech,
const char *initresp)
{
CURLcode result = CURLE_OK;
struct smtp_conn *smtpc = &conn->proto.smtpc;
if(initresp) { /* AUTH <mech> ...<crlf> */
/* Send the AUTH command with the initial response */
result = Curl_pp_sendf(&smtpc->pp, "AUTH %s %s", mech, initresp);
}
else {
/* Send the AUTH command */
result = Curl_pp_sendf(&smtpc->pp, "AUTH %s", mech);
}
return result;
}
/***********************************************************************
*
* smtp_continue_auth()
*
* Sends SASL continuation data or cancellation.
*/
static CURLcode smtp_continue_auth(struct connectdata *conn, const char *resp)
{
struct smtp_conn *smtpc = &conn->proto.smtpc;
return Curl_pp_sendf(&smtpc->pp, "%s", resp);
}
/***********************************************************************
*
* smtp_perform_authentication()
*
* Initiates the authentication sequence, with the appropriate SASL
* authentication mechanism.
*/
static CURLcode smtp_perform_authentication(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct smtp_conn *smtpc = &conn->proto.smtpc;
saslprogress progress;
/* Check we have enough data to authenticate with, and the
server supports authentiation, and end the connect phase if not */
if(!smtpc->auth_supported ||
!Curl_sasl_can_authenticate(&smtpc->sasl, conn)) {
state(conn, SMTP_STOP);
return result;
}
/* Calculate the SASL login details */
result = Curl_sasl_start(&smtpc->sasl, conn, FALSE, &progress);
if(!result) {
if(progress == SASL_INPROGRESS)
state(conn, SMTP_AUTH);
else {
/* Other mechanisms not supported */
infof(conn->data, "No known authentication mechanisms supported!\n");
result = CURLE_LOGIN_DENIED;
}
}
return result;
}
/***********************************************************************
*
* smtp_perform_command()
*
* Sends a SMTP based command.
*/
static CURLcode smtp_perform_command(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct SMTP *smtp = data->req.protop;
/* Send the command */
if(smtp->rcpt)
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s %s",
smtp->custom && smtp->custom[0] != '\0' ?
smtp->custom : "VRFY",
smtp->rcpt->data);
else
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s",
smtp->custom && smtp->custom[0] != '\0' ?
smtp->custom : "HELP");
if(!result)
state(conn, SMTP_COMMAND);
return result;
}
/***********************************************************************
*
* smtp_perform_mail()
*
* Sends an MAIL command to initiate the upload of a message.
*/
static CURLcode smtp_perform_mail(struct connectdata *conn)
{
char *from = NULL;
char *auth = NULL;
char *size = NULL;
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
/* Calculate the FROM parameter */
if(!data->set.str[STRING_MAIL_FROM])
/* Null reverse-path, RFC-5321, sect. 3.6.3 */
from = strdup("<>");
else if(data->set.str[STRING_MAIL_FROM][0] == '<')
from = aprintf("%s", data->set.str[STRING_MAIL_FROM]);
else
from = aprintf("<%s>", data->set.str[STRING_MAIL_FROM]);
if(!from)
return CURLE_OUT_OF_MEMORY;
/* Calculate the optional AUTH parameter */
if(data->set.str[STRING_MAIL_AUTH] && conn->proto.smtpc.sasl.authused) {
if(data->set.str[STRING_MAIL_AUTH][0] != '\0')
auth = aprintf("%s", data->set.str[STRING_MAIL_AUTH]);
else
/* Empty AUTH, RFC-2554, sect. 5 */
auth = strdup("<>");
if(!auth) {
free(from);
return CURLE_OUT_OF_MEMORY;
}
}
/* Prepare the mime data if some. */
if(data->set.mimepost.kind != MIMEKIND_NONE) {
/* Use the whole structure as data. */
data->set.mimepost.flags &= ~MIME_BODY_ONLY;
/* Add external headers and mime version. */
curl_mime_headers(&data->set.mimepost, data->set.headers, 0);
result = Curl_mime_prepare_headers(&data->set.mimepost, NULL,
NULL, MIMESTRATEGY_MAIL);
if(!result)
if(!Curl_checkheaders(conn, "Mime-Version"))
result = Curl_mime_add_header(&data->set.mimepost.curlheaders,
"Mime-Version: 1.0");
/* Make sure we will read the entire mime structure. */
if(!result)
result = Curl_mime_rewind(&data->set.mimepost);
if(result) {
free(from);
free(auth);
return result;
}
data->state.infilesize = Curl_mime_size(&data->set.mimepost);
/* Read from mime structure. */
data->state.fread_func = (curl_read_callback) Curl_mime_read;
data->state.in = (void *) &data->set.mimepost;
}
/* Calculate the optional SIZE parameter */
if(conn->proto.smtpc.size_supported && data->state.infilesize > 0) {
size = aprintf("%" CURL_FORMAT_CURL_OFF_T, data->state.infilesize);
if(!size) {
free(from);
free(auth);
return CURLE_OUT_OF_MEMORY;
}
}
/* Send the MAIL command */
if(!auth && !size)
result = Curl_pp_sendf(&conn->proto.smtpc.pp,
"MAIL FROM:%s", from);
else if(auth && !size)
result = Curl_pp_sendf(&conn->proto.smtpc.pp,
"MAIL FROM:%s AUTH=%s", from, auth);
else if(auth && size)
result = Curl_pp_sendf(&conn->proto.smtpc.pp,
"MAIL FROM:%s AUTH=%s SIZE=%s", from, auth, size);
else
result = Curl_pp_sendf(&conn->proto.smtpc.pp,
"MAIL FROM:%s SIZE=%s", from, size);
free(from);
free(auth);
free(size);
if(!result)
state(conn, SMTP_MAIL);
return result;
}
/***********************************************************************
*
* smtp_perform_rcpt_to()
*
* Sends a RCPT TO command for a given recipient as part of the message upload
* process.
*/
static CURLcode smtp_perform_rcpt_to(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct SMTP *smtp = data->req.protop;
/* Send the RCPT TO command */
if(smtp->rcpt->data[0] == '<')
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "RCPT TO:%s",
smtp->rcpt->data);
else
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "RCPT TO:<%s>",
smtp->rcpt->data);
if(!result)
state(conn, SMTP_RCPT);
return result;
}
/***********************************************************************
*
* smtp_perform_quit()
*
* Performs the quit action prior to sclose() being called.
*/
static CURLcode smtp_perform_quit(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
/* Send the QUIT command */
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", "QUIT");
if(!result)
state(conn, SMTP_QUIT);
return result;
}
/* For the initial server greeting */
static CURLcode smtp_state_servergreet_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
(void)instate; /* no use for this yet */
if(smtpcode/100 != 2) {
failf(data, "Got unexpected smtp-server response: %d", smtpcode);
result = CURLE_WEIRD_SERVER_REPLY;
}
else
result = smtp_perform_ehlo(conn);
return result;
}
/* For STARTTLS responses */
static CURLcode smtp_state_starttls_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
(void)instate; /* no use for this yet */
if(smtpcode != 220) {
if(data->set.use_ssl != CURLUSESSL_TRY) {
failf(data, "STARTTLS denied, code %d", smtpcode);
result = CURLE_USE_SSL_FAILED;
}
else
result = smtp_perform_authentication(conn);
}
else
result = smtp_perform_upgrade_tls(conn);
return result;
}
/* For EHLO responses */
static CURLcode smtp_state_ehlo_resp(struct connectdata *conn, int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct smtp_conn *smtpc = &conn->proto.smtpc;
const char *line = data->state.buffer;
size_t len = strlen(line);
(void)instate; /* no use for this yet */
if(smtpcode/100 != 2 && smtpcode != 1) {
if(data->set.use_ssl <= CURLUSESSL_TRY || conn->ssl[FIRSTSOCKET].use)
result = smtp_perform_helo(conn);
else {
failf(data, "Remote access denied: %d", smtpcode);
result = CURLE_REMOTE_ACCESS_DENIED;
}
}
else {
line += 4;
len -= 4;
/* Does the server support the STARTTLS capability? */
if(len >= 8 && !memcmp(line, "STARTTLS", 8))
smtpc->tls_supported = TRUE;
/* Does the server support the SIZE capability? */
else if(len >= 4 && !memcmp(line, "SIZE", 4))
smtpc->size_supported = TRUE;
/* Does the server support authentication? */
else if(len >= 5 && !memcmp(line, "AUTH ", 5)) {
smtpc->auth_supported = TRUE;
/* Advance past the AUTH keyword */
line += 5;
len -= 5;
/* Loop through the data line */
for(;;) {
size_t llen;
size_t wordlen;
unsigned int mechbit;
while(len &&
(*line == ' ' || *line == '\t' ||
*line == '\r' || *line == '\n')) {
line++;
len--;
}
if(!len)
break;
/* Extract the word */
for(wordlen = 0; wordlen < len && line[wordlen] != ' ' &&
line[wordlen] != '\t' && line[wordlen] != '\r' &&
line[wordlen] != '\n';)
wordlen++;
/* Test the word for a matching authentication mechanism */
mechbit = Curl_sasl_decode_mech(line, wordlen, &llen);
if(mechbit && llen == wordlen)
smtpc->sasl.authmechs |= mechbit;
line += wordlen;
len -= wordlen;
}
}
if(smtpcode != 1) {
if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) {
/* We don't have a SSL/TLS connection yet, but SSL is requested */
if(smtpc->tls_supported)
/* Switch to TLS connection now */
result = smtp_perform_starttls(conn);
else if(data->set.use_ssl == CURLUSESSL_TRY)
/* Fallback and carry on with authentication */
result = smtp_perform_authentication(conn);
else {
failf(data, "STARTTLS not supported.");
result = CURLE_USE_SSL_FAILED;
}
}
else
result = smtp_perform_authentication(conn);
}
}
return result;
}
/* For HELO responses */
static CURLcode smtp_state_helo_resp(struct connectdata *conn, int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
(void)instate; /* no use for this yet */
if(smtpcode/100 != 2) {
failf(data, "Remote access denied: %d", smtpcode);
result = CURLE_REMOTE_ACCESS_DENIED;
}
else
/* End of connect phase */
state(conn, SMTP_STOP);
return result;
}
/* For SASL authentication responses */
static CURLcode smtp_state_auth_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct smtp_conn *smtpc = &conn->proto.smtpc;
saslprogress progress;
(void)instate; /* no use for this yet */
result = Curl_sasl_continue(&smtpc->sasl, conn, smtpcode, &progress);
if(!result)
switch(progress) {
case SASL_DONE:
state(conn, SMTP_STOP); /* Authenticated */
break;
case SASL_IDLE: /* No mechanism left after cancellation */
failf(data, "Authentication cancelled");
result = CURLE_LOGIN_DENIED;
break;
default:
break;
}
return result;
}
/* For command responses */
static CURLcode smtp_state_command_resp(struct connectdata *conn, int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct SMTP *smtp = data->req.protop;
char *line = data->state.buffer;
size_t len = strlen(line);
(void)instate; /* no use for this yet */
if((smtp->rcpt && smtpcode/100 != 2 && smtpcode != 553 && smtpcode != 1) ||
(!smtp->rcpt && smtpcode/100 != 2 && smtpcode != 1)) {
failf(data, "Command failed: %d", smtpcode);
result = CURLE_RECV_ERROR;
}
else {
/* Temporarily add the LF character back and send as body to the client */
if(!data->set.opt_no_body) {
line[len] = '\n';
result = Curl_client_write(conn, CLIENTWRITE_BODY, line, len + 1);
line[len] = '\0';
}
if(smtpcode != 1) {
if(smtp->rcpt) {
smtp->rcpt = smtp->rcpt->next;
if(smtp->rcpt) {
/* Send the next command */
result = smtp_perform_command(conn);
}
else
/* End of DO phase */
state(conn, SMTP_STOP);
}
else
/* End of DO phase */
state(conn, SMTP_STOP);
}
}
return result;
}
/* For MAIL responses */
static CURLcode smtp_state_mail_resp(struct connectdata *conn, int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
(void)instate; /* no use for this yet */
if(smtpcode/100 != 2) {
failf(data, "MAIL failed: %d", smtpcode);
result = CURLE_SEND_ERROR;
}
else
/* Start the RCPT TO command */
result = smtp_perform_rcpt_to(conn);
return result;
}
/* For RCPT responses */
static CURLcode smtp_state_rcpt_resp(struct connectdata *conn, int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct SMTP *smtp = data->req.protop;
(void)instate; /* no use for this yet */
if(smtpcode/100 != 2) {
failf(data, "RCPT failed: %d", smtpcode);
result = CURLE_SEND_ERROR;
}
else {
smtp->rcpt = smtp->rcpt->next;
if(smtp->rcpt)
/* Send the next RCPT TO command */
result = smtp_perform_rcpt_to(conn);
else {
/* Send the DATA command */
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", "DATA");
if(!result)
state(conn, SMTP_DATA);
}
}
return result;
}
/* For DATA response */
static CURLcode smtp_state_data_resp(struct connectdata *conn, int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
(void)instate; /* no use for this yet */
if(smtpcode != 354) {
failf(data, "DATA failed: %d", smtpcode);
result = CURLE_SEND_ERROR;
}
else {
/* Set the progress upload size */
Curl_pgrsSetUploadSize(data, data->state.infilesize);
/* SMTP upload */
Curl_setup_transfer(conn, -1, -1, FALSE, NULL, FIRSTSOCKET, NULL);
/* End of DO phase */
state(conn, SMTP_STOP);
}
return result;
}
/* For POSTDATA responses, which are received after the entire DATA
part has been sent to the server */
static CURLcode smtp_state_postdata_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
(void)instate; /* no use for this yet */
if(smtpcode != 250)
result = CURLE_RECV_ERROR;
/* End of DONE phase */
state(conn, SMTP_STOP);
return result;
}
static CURLcode smtp_statemach_act(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
curl_socket_t sock = conn->sock[FIRSTSOCKET];
struct Curl_easy *data = conn->data;
int smtpcode;
struct smtp_conn *smtpc = &conn->proto.smtpc;
struct pingpong *pp = &smtpc->pp;
size_t nread = 0;
/* Busy upgrading the connection; right now all I/O is SSL/TLS, not SMTP */
if(smtpc->state == SMTP_UPGRADETLS)
return smtp_perform_upgrade_tls(conn);
/* Flush any data that needs to be sent */
if(pp->sendleft)
return Curl_pp_flushsend(pp);
do {
/* Read the response from the server */
result = Curl_pp_readresp(sock, pp, &smtpcode, &nread);
if(result)
return result;
/* Store the latest response for later retrieval if necessary */
if(smtpc->state != SMTP_QUIT && smtpcode != 1)
data->info.httpcode = smtpcode;
if(!smtpcode)
break;
/* We have now received a full SMTP server response */
switch(smtpc->state) {
case SMTP_SERVERGREET:
result = smtp_state_servergreet_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_EHLO:
result = smtp_state_ehlo_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_HELO:
result = smtp_state_helo_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_STARTTLS:
result = smtp_state_starttls_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_AUTH:
result = smtp_state_auth_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_COMMAND:
result = smtp_state_command_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_MAIL:
result = smtp_state_mail_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_RCPT:
result = smtp_state_rcpt_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_DATA:
result = smtp_state_data_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_POSTDATA:
result = smtp_state_postdata_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_QUIT:
/* fallthrough, just stop! */
default:
/* internal error */
state(conn, SMTP_STOP);
break;
}
} while(!result && smtpc->state != SMTP_STOP && Curl_pp_moredata(pp));
return result;
}
/* Called repeatedly until done from multi.c */
static CURLcode smtp_multi_statemach(struct connectdata *conn, bool *done)
{
CURLcode result = CURLE_OK;
struct smtp_conn *smtpc = &conn->proto.smtpc;
if((conn->handler->flags & PROTOPT_SSL) && !smtpc->ssldone) {
result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &smtpc->ssldone);
if(result || !smtpc->ssldone)
return result;
}
result = Curl_pp_statemach(&smtpc->pp, FALSE);
*done = (smtpc->state == SMTP_STOP) ? TRUE : FALSE;
return result;
}
static CURLcode smtp_block_statemach(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct smtp_conn *smtpc = &conn->proto.smtpc;
while(smtpc->state != SMTP_STOP && !result)
result = Curl_pp_statemach(&smtpc->pp, TRUE);
return result;
}
/* Allocate and initialize the SMTP struct for the current Curl_easy if
required */
static CURLcode smtp_init(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct SMTP *smtp;
smtp = data->req.protop = calloc(sizeof(struct SMTP), 1);
if(!smtp)
result = CURLE_OUT_OF_MEMORY;
return result;
}
/* For the SMTP "protocol connect" and "doing" phases only */
static int smtp_getsock(struct connectdata *conn, curl_socket_t *socks,
int numsocks)
{
return Curl_pp_getsock(&conn->proto.smtpc.pp, socks, numsocks);
}
/***********************************************************************
*
* smtp_connect()
*
* This function should do everything that is to be considered a part of
* the connection phase.
*
* The variable pointed to by 'done' will be TRUE if the protocol-layer
* connect phase is done when this function returns, or FALSE if not.
*/
static CURLcode smtp_connect(struct connectdata *conn, bool *done)
{
CURLcode result = CURLE_OK;
struct smtp_conn *smtpc = &conn->proto.smtpc;
struct pingpong *pp = &smtpc->pp;
*done = FALSE; /* default to not done yet */
/* We always support persistent connections in SMTP */
connkeep(conn, "SMTP default");
/* Set the default response time-out */
pp->response_time = RESP_TIMEOUT;
pp->statemach_act = smtp_statemach_act;
pp->endofresp = smtp_endofresp;
pp->conn = conn;
/* Initialize the SASL storage */
Curl_sasl_init(&smtpc->sasl, &saslsmtp);
/* Initialise the pingpong layer */
Curl_pp_init(pp);
/* Parse the URL options */
result = smtp_parse_url_options(conn);
if(result)
return result;
/* Parse the URL path */
result = smtp_parse_url_path(conn);
if(result)
return result;
/* Start off waiting for the server greeting response */
state(conn, SMTP_SERVERGREET);
result = smtp_multi_statemach(conn, done);
return result;
}
/***********************************************************************
*
* smtp_done()
*
* The DONE function. This does what needs to be done after a single DO has
* performed.
*
* Input argument is already checked for validity.
*/
static CURLcode smtp_done(struct connectdata *conn, CURLcode status,
bool premature)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct SMTP *smtp = data->req.protop;
struct pingpong *pp = &conn->proto.smtpc.pp;
char *eob;
ssize_t len;
ssize_t bytes_written;
(void)premature;
if(!smtp || !pp->conn)
return CURLE_OK;
/* Cleanup our per-request based variables */
Curl_safefree(smtp->custom);
if(status) {
connclose(conn, "SMTP done with bad status"); /* marked for closure */
result = status; /* use the already set error code */
}
else if(!data->set.connect_only && data->set.mail_rcpt &&
(data->set.upload || data->set.mimepost.kind)) {
/* Calculate the EOB taking into account any terminating CRLF from the
previous line of the email or the CRLF of the DATA command when there
is "no mail data". RFC-5321, sect. 4.1.1.4.
Note: As some SSL backends, such as OpenSSL, will cause Curl_write() to
fail when using a different pointer following a previous write, that
returned CURLE_AGAIN, we duplicate the EOB now rather than when the
bytes written doesn't equal len. */
if(smtp->trailing_crlf || !conn->data->state.infilesize) {
eob = strdup(SMTP_EOB + 2);
len = SMTP_EOB_LEN - 2;
}
else {
eob = strdup(SMTP_EOB);
len = SMTP_EOB_LEN;
}
if(!eob)
return CURLE_OUT_OF_MEMORY;
/* Send the end of block data */
result = Curl_write(conn, conn->writesockfd, eob, len, &bytes_written);
if(result) {
free(eob);
return result;
}
if(bytes_written != len) {
/* The whole chunk was not sent so keep it around and adjust the
pingpong structure accordingly */
pp->sendthis = eob;
pp->sendsize = len;
pp->sendleft = len - bytes_written;
}
else {
/* Successfully sent so adjust the response timeout relative to now */
pp->response = Curl_now();
free(eob);
}
state(conn, SMTP_POSTDATA);
/* Run the state-machine
TODO: when the multi interface is used, this _really_ should be using
the smtp_multi_statemach function but we have no general support for
non-blocking DONE operations!
*/
result = smtp_block_statemach(conn);
}
/* Clear the transfer mode for the next request */
smtp->transfer = FTPTRANSFER_BODY;
return result;
}
/***********************************************************************
*
* smtp_perform()
*
* This is the actual DO function for SMTP. Transfer a mail, send a command
* or get some data according to the options previously setup.
*/
static CURLcode smtp_perform(struct connectdata *conn, bool *connected,
bool *dophase_done)
{
/* This is SMTP and no proxy */
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct SMTP *smtp = data->req.protop;
DEBUGF(infof(conn->data, "DO phase starts\n"));
if(data->set.opt_no_body) {
/* Requested no body means no transfer */
smtp->transfer = FTPTRANSFER_INFO;
}
*dophase_done = FALSE; /* not done yet */
/* Store the first recipient (or NULL if not specified) */
smtp->rcpt = data->set.mail_rcpt;
/* Initial data character is the first character in line: it is implicitly
preceded by a virtual CRLF. */
smtp->trailing_crlf = TRUE;
smtp->eob = 2;
/* Start the first command in the DO phase */
if((data->set.upload || data->set.mimepost.kind) && data->set.mail_rcpt)
/* MAIL transfer */
result = smtp_perform_mail(conn);
else
/* SMTP based command (VRFY, EXPN, NOOP, RSET or HELP) */
result = smtp_perform_command(conn);
if(result)
return result;
/* Run the state-machine */
result = smtp_multi_statemach(conn, dophase_done);
*connected = conn->bits.tcpconnect[FIRSTSOCKET];
if(*dophase_done)
DEBUGF(infof(conn->data, "DO phase is complete\n"));
return result;
}
/***********************************************************************
*
* smtp_do()
*
* This function is registered as 'curl_do' function. It decodes the path
* parts etc as a wrapper to the actual DO function (smtp_perform).
*
* The input argument is already checked for validity.
*/
static CURLcode smtp_do(struct connectdata *conn, bool *done)
{
CURLcode result = CURLE_OK;
*done = FALSE; /* default to false */
/* Parse the custom request */
result = smtp_parse_custom_request(conn);
if(result)
return result;
result = smtp_regular_transfer(conn, done);
return result;
}
/***********************************************************************
*
* smtp_disconnect()
*
* Disconnect from an SMTP server. Cleanup protocol-specific per-connection
* resources. BLOCKING.
*/
static CURLcode smtp_disconnect(struct connectdata *conn, bool dead_connection)
{
struct smtp_conn *smtpc = &conn->proto.smtpc;
/* We cannot send quit unconditionally. If this connection is stale or
bad in any way, sending quit and waiting around here will make the
disconnect wait in vain and cause more problems than we need to. */
/* The SMTP session may or may not have been allocated/setup at this
point! */
if(!dead_connection && smtpc->pp.conn && smtpc->pp.conn->bits.protoconnstart)
if(!smtp_perform_quit(conn))
(void)smtp_block_statemach(conn); /* ignore errors on QUIT */
/* Disconnect from the server */
Curl_pp_disconnect(&smtpc->pp);
/* Cleanup the SASL module */
Curl_sasl_cleanup(conn, smtpc->sasl.authused);
/* Cleanup our connection based variables */
Curl_safefree(smtpc->domain);
return CURLE_OK;
}
/* Call this when the DO phase has completed */
static CURLcode smtp_dophase_done(struct connectdata *conn, bool connected)
{
struct SMTP *smtp = conn->data->req.protop;
(void)connected;
if(smtp->transfer != FTPTRANSFER_BODY)
/* no data to transfer */
Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
return CURLE_OK;
}
/* Called from multi.c while DOing */
static CURLcode smtp_doing(struct connectdata *conn, bool *dophase_done)
{
CURLcode result = smtp_multi_statemach(conn, dophase_done);
if(result)
DEBUGF(infof(conn->data, "DO phase failed\n"));
else if(*dophase_done) {
result = smtp_dophase_done(conn, FALSE /* not connected */);
DEBUGF(infof(conn->data, "DO phase is complete\n"));
}
return result;
}
/***********************************************************************
*
* smtp_regular_transfer()
*
* The input argument is already checked for validity.
*
* Performs all commands done before a regular transfer between a local and a
* remote host.
*/
static CURLcode smtp_regular_transfer(struct connectdata *conn,
bool *dophase_done)
{
CURLcode result = CURLE_OK;
bool connected = FALSE;
struct Curl_easy *data = conn->data;
/* Make sure size is unknown at this point */
data->req.size = -1;
/* Set the progress data */
Curl_pgrsSetUploadCounter(data, 0);
Curl_pgrsSetDownloadCounter(data, 0);
Curl_pgrsSetUploadSize(data, -1);
Curl_pgrsSetDownloadSize(data, -1);
/* Carry out the perform */
result = smtp_perform(conn, &connected, dophase_done);
/* Perform post DO phase operations if necessary */
if(!result && *dophase_done)
result = smtp_dophase_done(conn, connected);
return result;
}
static CURLcode smtp_setup_connection(struct connectdata *conn)
{
struct Curl_easy *data = conn->data;
CURLcode result;
/* Clear the TLS upgraded flag */
conn->tls_upgraded = FALSE;
/* Initialise the SMTP layer */
result = smtp_init(conn);
if(result)
return result;
data->state.path++; /* don't include the initial slash */
return CURLE_OK;
}
/***********************************************************************
*
* smtp_parse_url_options()
*
* Parse the URL login options.
*/
static CURLcode smtp_parse_url_options(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct smtp_conn *smtpc = &conn->proto.smtpc;
const char *ptr = conn->options;
smtpc->sasl.resetprefs = TRUE;
while(!result && ptr && *ptr) {
const char *key = ptr;
const char *value;
while(*ptr && *ptr != '=')
ptr++;
value = ptr + 1;
while(*ptr && *ptr != ';')
ptr++;
if(strncasecompare(key, "AUTH=", 5))
result = Curl_sasl_parse_url_auth_option(&smtpc->sasl,
value, ptr - value);
else
result = CURLE_URL_MALFORMAT;
if(*ptr == ';')
ptr++;
}
return result;
}
/***********************************************************************
*
* smtp_parse_url_path()
*
* Parse the URL path into separate path components.
*/
static CURLcode smtp_parse_url_path(struct connectdata *conn)
{
/* The SMTP struct is already initialised in smtp_connect() */
struct Curl_easy *data = conn->data;
struct smtp_conn *smtpc = &conn->proto.smtpc;
const char *path = data->state.path;
char localhost[HOSTNAME_MAX + 1];
/* Calculate the path if necessary */
if(!*path) {
if(!Curl_gethostname(localhost, sizeof(localhost)))
path = localhost;
else
path = "localhost";
}
/* URL decode the path and use it as the domain in our EHLO */
return Curl_urldecode(conn->data, path, 0, &smtpc->domain, NULL, TRUE);
}
/***********************************************************************
*
* smtp_parse_custom_request()
*
* Parse the custom request.
*/
static CURLcode smtp_parse_custom_request(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct SMTP *smtp = data->req.protop;
const char *custom = data->set.str[STRING_CUSTOMREQUEST];
/* URL decode the custom request */
if(custom)
result = Curl_urldecode(data, custom, 0, &smtp->custom, NULL, TRUE);
return result;
}
CURLcode Curl_smtp_escape_eob(struct connectdata *conn, const ssize_t nread)
{
/* When sending a SMTP payload we must detect CRLF. sequences making sure
they are sent as CRLF.. instead, as a . on the beginning of a line will
be deleted by the server when not part of an EOB terminator and a
genuine CRLF.CRLF which isn't escaped will wrongly be detected as end of
data by the server
*/
ssize_t i;
ssize_t si;
struct Curl_easy *data = conn->data;
struct SMTP *smtp = data->req.protop;
char *scratch = data->state.scratch;
char *newscratch = NULL;
char *oldscratch = NULL;
size_t eob_sent;
/* Do we need to allocate a scratch buffer? */
if(!scratch || data->set.crlf) {
oldscratch = scratch;
scratch = newscratch = malloc(2 * UPLOAD_BUFSIZE);
if(!newscratch) {
failf(data, "Failed to alloc scratch buffer!");
return CURLE_OUT_OF_MEMORY;
}
}
DEBUGASSERT(UPLOAD_BUFSIZE >= nread);
/* Have we already sent part of the EOB? */
eob_sent = smtp->eob;
/* This loop can be improved by some kind of Boyer-Moore style of
approach but that is saved for later... */
for(i = 0, si = 0; i < nread; i++) {
if(SMTP_EOB[smtp->eob] == data->req.upload_fromhere[i]) {
smtp->eob++;
/* Is the EOB potentially the terminating CRLF? */
if(2 == smtp->eob || SMTP_EOB_LEN == smtp->eob)
smtp->trailing_crlf = TRUE;
else
smtp->trailing_crlf = FALSE;
}
else if(smtp->eob) {
/* A previous substring matched so output that first */
memcpy(&scratch[si], &SMTP_EOB[eob_sent], smtp->eob - eob_sent);
si += smtp->eob - eob_sent;
/* Then compare the first byte */
if(SMTP_EOB[0] == data->req.upload_fromhere[i])
smtp->eob = 1;
else
smtp->eob = 0;
eob_sent = 0;
/* Reset the trailing CRLF flag as there was more data */
smtp->trailing_crlf = FALSE;
}
/* Do we have a match for CRLF. as per RFC-5321, sect. 4.5.2 */
if(SMTP_EOB_FIND_LEN == smtp->eob) {
/* Copy the replacement data to the target buffer */
memcpy(&scratch[si], &SMTP_EOB_REPL[eob_sent],
SMTP_EOB_REPL_LEN - eob_sent);
si += SMTP_EOB_REPL_LEN - eob_sent;
smtp->eob = 0;
eob_sent = 0;
}
else if(!smtp->eob)
scratch[si++] = data->req.upload_fromhere[i];
}
if(smtp->eob - eob_sent) {
/* A substring matched before processing ended so output that now */
memcpy(&scratch[si], &SMTP_EOB[eob_sent], smtp->eob - eob_sent);
si += smtp->eob - eob_sent;
}
/* Only use the new buffer if we replaced something */
if(si != nread) {
/* Upload from the new (replaced) buffer instead */
data->req.upload_fromhere = scratch;
/* Save the buffer so it can be freed later */
data->state.scratch = scratch;
/* Free the old scratch buffer */
free(oldscratch);
/* Set the new amount too */
data->req.upload_present = si;
}
else
free(newscratch);
return CURLE_OK;
}
#endif /* CURL_DISABLE_SMTP */
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2_0 |
crossvul-cpp_data_bad_4767_0 | /* $OpenBSD: monitor.c,v 1.165 2016/09/05 13:57:31 djm Exp $ */
/*
* Copyright 2002 Niels Provos <provos@citi.umich.edu>
* Copyright 2002 Markus Friedl <markus@openbsd.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/tree.h>
#include <sys/queue.h>
#ifdef WITH_OPENSSL
#include <openssl/dh.h>
#endif
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <paths.h>
#include <poll.h>
#include <pwd.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "atomicio.h"
#include "xmalloc.h"
#include "ssh.h"
#include "key.h"
#include "buffer.h"
#include "hostfile.h"
#include "auth.h"
#include "cipher.h"
#include "kex.h"
#include "dh.h"
#include <zlib.h>
#include "packet.h"
#include "auth-options.h"
#include "sshpty.h"
#include "channels.h"
#include "session.h"
#include "sshlogin.h"
#include "canohost.h"
#include "log.h"
#include "misc.h"
#include "servconf.h"
#include "monitor.h"
#include "monitor_mm.h"
#ifdef GSSAPI
#include "ssh-gss.h"
#endif
#include "monitor_wrap.h"
#include "monitor_fdpass.h"
#include "compat.h"
#include "ssh2.h"
#include "authfd.h"
#include "match.h"
#include "ssherr.h"
#ifdef GSSAPI
static Gssctxt *gsscontext = NULL;
#endif
/* Imports */
extern ServerOptions options;
extern u_int utmp_len;
extern u_char session_id[];
extern Buffer auth_debug;
extern int auth_debug_init;
extern Buffer loginmsg;
/* State exported from the child */
static struct sshbuf *child_state;
/* Functions on the monitor that answer unprivileged requests */
int mm_answer_moduli(int, Buffer *);
int mm_answer_sign(int, Buffer *);
int mm_answer_pwnamallow(int, Buffer *);
int mm_answer_auth2_read_banner(int, Buffer *);
int mm_answer_authserv(int, Buffer *);
int mm_answer_authpassword(int, Buffer *);
int mm_answer_bsdauthquery(int, Buffer *);
int mm_answer_bsdauthrespond(int, Buffer *);
int mm_answer_skeyquery(int, Buffer *);
int mm_answer_skeyrespond(int, Buffer *);
int mm_answer_keyallowed(int, Buffer *);
int mm_answer_keyverify(int, Buffer *);
int mm_answer_pty(int, Buffer *);
int mm_answer_pty_cleanup(int, Buffer *);
int mm_answer_term(int, Buffer *);
int mm_answer_rsa_keyallowed(int, Buffer *);
int mm_answer_rsa_challenge(int, Buffer *);
int mm_answer_rsa_response(int, Buffer *);
int mm_answer_sesskey(int, Buffer *);
int mm_answer_sessid(int, Buffer *);
#ifdef GSSAPI
int mm_answer_gss_setup_ctx(int, Buffer *);
int mm_answer_gss_accept_ctx(int, Buffer *);
int mm_answer_gss_userok(int, Buffer *);
int mm_answer_gss_checkmic(int, Buffer *);
#endif
static int monitor_read_log(struct monitor *);
static Authctxt *authctxt;
/* local state for key verify */
static u_char *key_blob = NULL;
static u_int key_bloblen = 0;
static int key_blobtype = MM_NOKEY;
static char *hostbased_cuser = NULL;
static char *hostbased_chost = NULL;
static char *auth_method = "unknown";
static char *auth_submethod = NULL;
static u_int session_id2_len = 0;
static u_char *session_id2 = NULL;
static pid_t monitor_child_pid;
struct mon_table {
enum monitor_reqtype type;
int flags;
int (*f)(int, Buffer *);
};
#define MON_ISAUTH 0x0004 /* Required for Authentication */
#define MON_AUTHDECIDE 0x0008 /* Decides Authentication */
#define MON_ONCE 0x0010 /* Disable after calling */
#define MON_ALOG 0x0020 /* Log auth attempt without authenticating */
#define MON_AUTH (MON_ISAUTH|MON_AUTHDECIDE)
#define MON_PERMIT 0x1000 /* Request is permitted */
struct mon_table mon_dispatch_proto20[] = {
#ifdef WITH_OPENSSL
{MONITOR_REQ_MODULI, MON_ONCE, mm_answer_moduli},
#endif
{MONITOR_REQ_SIGN, MON_ONCE, mm_answer_sign},
{MONITOR_REQ_PWNAM, MON_ONCE, mm_answer_pwnamallow},
{MONITOR_REQ_AUTHSERV, MON_ONCE, mm_answer_authserv},
{MONITOR_REQ_AUTH2_READ_BANNER, MON_ONCE, mm_answer_auth2_read_banner},
{MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword},
{MONITOR_REQ_BSDAUTHQUERY, MON_ISAUTH, mm_answer_bsdauthquery},
{MONITOR_REQ_BSDAUTHRESPOND, MON_AUTH, mm_answer_bsdauthrespond},
{MONITOR_REQ_KEYALLOWED, MON_ISAUTH, mm_answer_keyallowed},
{MONITOR_REQ_KEYVERIFY, MON_AUTH, mm_answer_keyverify},
#ifdef GSSAPI
{MONITOR_REQ_GSSSETUP, MON_ISAUTH, mm_answer_gss_setup_ctx},
{MONITOR_REQ_GSSSTEP, 0, mm_answer_gss_accept_ctx},
{MONITOR_REQ_GSSUSEROK, MON_ONCE|MON_AUTHDECIDE, mm_answer_gss_userok},
{MONITOR_REQ_GSSCHECKMIC, MON_ONCE, mm_answer_gss_checkmic},
#endif
{0, 0, NULL}
};
struct mon_table mon_dispatch_postauth20[] = {
#ifdef WITH_OPENSSL
{MONITOR_REQ_MODULI, 0, mm_answer_moduli},
#endif
{MONITOR_REQ_SIGN, 0, mm_answer_sign},
{MONITOR_REQ_PTY, 0, mm_answer_pty},
{MONITOR_REQ_PTYCLEANUP, 0, mm_answer_pty_cleanup},
{MONITOR_REQ_TERM, 0, mm_answer_term},
{0, 0, NULL}
};
struct mon_table *mon_dispatch;
/* Specifies if a certain message is allowed at the moment */
static void
monitor_permit(struct mon_table *ent, enum monitor_reqtype type, int permit)
{
while (ent->f != NULL) {
if (ent->type == type) {
ent->flags &= ~MON_PERMIT;
ent->flags |= permit ? MON_PERMIT : 0;
return;
}
ent++;
}
}
static void
monitor_permit_authentications(int permit)
{
struct mon_table *ent = mon_dispatch;
while (ent->f != NULL) {
if (ent->flags & MON_AUTH) {
ent->flags &= ~MON_PERMIT;
ent->flags |= permit ? MON_PERMIT : 0;
}
ent++;
}
}
void
monitor_child_preauth(Authctxt *_authctxt, struct monitor *pmonitor)
{
struct mon_table *ent;
int authenticated = 0, partial = 0;
debug3("preauth child monitor started");
close(pmonitor->m_recvfd);
close(pmonitor->m_log_sendfd);
pmonitor->m_log_sendfd = pmonitor->m_recvfd = -1;
authctxt = _authctxt;
memset(authctxt, 0, sizeof(*authctxt));
mon_dispatch = mon_dispatch_proto20;
/* Permit requests for moduli and signatures */
monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
/* The first few requests do not require asynchronous access */
while (!authenticated) {
partial = 0;
auth_method = "unknown";
auth_submethod = NULL;
authenticated = (monitor_read(pmonitor, mon_dispatch, &ent) == 1);
/* Special handling for multiple required authentications */
if (options.num_auth_methods != 0) {
if (authenticated &&
!auth2_update_methods_lists(authctxt,
auth_method, auth_submethod)) {
debug3("%s: method %s: partial", __func__,
auth_method);
authenticated = 0;
partial = 1;
}
}
if (authenticated) {
if (!(ent->flags & MON_AUTHDECIDE))
fatal("%s: unexpected authentication from %d",
__func__, ent->type);
if (authctxt->pw->pw_uid == 0 &&
!auth_root_allowed(auth_method))
authenticated = 0;
}
if (ent->flags & (MON_AUTHDECIDE|MON_ALOG)) {
auth_log(authctxt, authenticated, partial,
auth_method, auth_submethod);
if (!partial && !authenticated)
authctxt->failures++;
}
}
if (!authctxt->valid)
fatal("%s: authenticated invalid user", __func__);
if (strcmp(auth_method, "unknown") == 0)
fatal("%s: authentication method name unknown", __func__);
debug("%s: %s has been authenticated by privileged process",
__func__, authctxt->user);
mm_get_keystate(pmonitor);
/* Drain any buffered messages from the child */
while (pmonitor->m_log_recvfd != -1 && monitor_read_log(pmonitor) == 0)
;
close(pmonitor->m_sendfd);
close(pmonitor->m_log_recvfd);
pmonitor->m_sendfd = pmonitor->m_log_recvfd = -1;
}
static void
monitor_set_child_handler(pid_t pid)
{
monitor_child_pid = pid;
}
static void
monitor_child_handler(int sig)
{
kill(monitor_child_pid, sig);
}
void
monitor_child_postauth(struct monitor *pmonitor)
{
close(pmonitor->m_recvfd);
pmonitor->m_recvfd = -1;
monitor_set_child_handler(pmonitor->m_pid);
signal(SIGHUP, &monitor_child_handler);
signal(SIGTERM, &monitor_child_handler);
signal(SIGINT, &monitor_child_handler);
mon_dispatch = mon_dispatch_postauth20;
/* Permit requests for moduli and signatures */
monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
if (!no_pty_flag) {
monitor_permit(mon_dispatch, MONITOR_REQ_PTY, 1);
monitor_permit(mon_dispatch, MONITOR_REQ_PTYCLEANUP, 1);
}
for (;;)
monitor_read(pmonitor, mon_dispatch, NULL);
}
void
monitor_sync(struct monitor *pmonitor)
{
if (options.compression) {
/* The member allocation is not visible, so sync it */
mm_share_sync(&pmonitor->m_zlib, &pmonitor->m_zback);
}
}
/* Allocation functions for zlib */
static void *
mm_zalloc(struct mm_master *mm, u_int ncount, u_int size)
{
if (size == 0 || ncount == 0 || ncount > SIZE_MAX / size)
fatal("%s: mm_zalloc(%u, %u)", __func__, ncount, size);
return mm_malloc(mm, size * ncount);
}
static void
mm_zfree(struct mm_master *mm, void *address)
{
mm_free(mm, address);
}
static int
monitor_read_log(struct monitor *pmonitor)
{
Buffer logmsg;
u_int len, level;
char *msg;
buffer_init(&logmsg);
/* Read length */
buffer_append_space(&logmsg, 4);
if (atomicio(read, pmonitor->m_log_recvfd,
buffer_ptr(&logmsg), buffer_len(&logmsg)) != buffer_len(&logmsg)) {
if (errno == EPIPE) {
buffer_free(&logmsg);
debug("%s: child log fd closed", __func__);
close(pmonitor->m_log_recvfd);
pmonitor->m_log_recvfd = -1;
return -1;
}
fatal("%s: log fd read: %s", __func__, strerror(errno));
}
len = buffer_get_int(&logmsg);
if (len <= 4 || len > 8192)
fatal("%s: invalid log message length %u", __func__, len);
/* Read severity, message */
buffer_clear(&logmsg);
buffer_append_space(&logmsg, len);
if (atomicio(read, pmonitor->m_log_recvfd,
buffer_ptr(&logmsg), buffer_len(&logmsg)) != buffer_len(&logmsg))
fatal("%s: log fd read: %s", __func__, strerror(errno));
/* Log it */
level = buffer_get_int(&logmsg);
msg = buffer_get_string(&logmsg, NULL);
if (log_level_name(level) == NULL)
fatal("%s: invalid log level %u (corrupted message?)",
__func__, level);
do_log2(level, "%s [preauth]", msg);
buffer_free(&logmsg);
free(msg);
return 0;
}
int
monitor_read(struct monitor *pmonitor, struct mon_table *ent,
struct mon_table **pent)
{
Buffer m;
int ret;
u_char type;
struct pollfd pfd[2];
for (;;) {
memset(&pfd, 0, sizeof(pfd));
pfd[0].fd = pmonitor->m_sendfd;
pfd[0].events = POLLIN;
pfd[1].fd = pmonitor->m_log_recvfd;
pfd[1].events = pfd[1].fd == -1 ? 0 : POLLIN;
if (poll(pfd, pfd[1].fd == -1 ? 1 : 2, -1) == -1) {
if (errno == EINTR || errno == EAGAIN)
continue;
fatal("%s: poll: %s", __func__, strerror(errno));
}
if (pfd[1].revents) {
/*
* Drain all log messages before processing next
* monitor request.
*/
monitor_read_log(pmonitor);
continue;
}
if (pfd[0].revents)
break; /* Continues below */
}
buffer_init(&m);
mm_request_receive(pmonitor->m_sendfd, &m);
type = buffer_get_char(&m);
debug3("%s: checking request %d", __func__, type);
while (ent->f != NULL) {
if (ent->type == type)
break;
ent++;
}
if (ent->f != NULL) {
if (!(ent->flags & MON_PERMIT))
fatal("%s: unpermitted request %d", __func__,
type);
ret = (*ent->f)(pmonitor->m_sendfd, &m);
buffer_free(&m);
/* The child may use this request only once, disable it */
if (ent->flags & MON_ONCE) {
debug2("%s: %d used once, disabling now", __func__,
type);
ent->flags &= ~MON_PERMIT;
}
if (pent != NULL)
*pent = ent;
return ret;
}
fatal("%s: unsupported request: %d", __func__, type);
/* NOTREACHED */
return (-1);
}
/* allowed key state */
static int
monitor_allowed_key(u_char *blob, u_int bloblen)
{
/* make sure key is allowed */
if (key_blob == NULL || key_bloblen != bloblen ||
timingsafe_bcmp(key_blob, blob, key_bloblen))
return (0);
return (1);
}
static void
monitor_reset_key_state(void)
{
/* reset state */
free(key_blob);
free(hostbased_cuser);
free(hostbased_chost);
key_blob = NULL;
key_bloblen = 0;
key_blobtype = MM_NOKEY;
hostbased_cuser = NULL;
hostbased_chost = NULL;
}
#ifdef WITH_OPENSSL
int
mm_answer_moduli(int sock, Buffer *m)
{
DH *dh;
int min, want, max;
min = buffer_get_int(m);
want = buffer_get_int(m);
max = buffer_get_int(m);
debug3("%s: got parameters: %d %d %d",
__func__, min, want, max);
/* We need to check here, too, in case the child got corrupted */
if (max < min || want < min || max < want)
fatal("%s: bad parameters: %d %d %d",
__func__, min, want, max);
buffer_clear(m);
dh = choose_dh(min, want, max);
if (dh == NULL) {
buffer_put_char(m, 0);
return (0);
} else {
/* Send first bignum */
buffer_put_char(m, 1);
buffer_put_bignum2(m, dh->p);
buffer_put_bignum2(m, dh->g);
DH_free(dh);
}
mm_request_send(sock, MONITOR_ANS_MODULI, m);
return (0);
}
#endif
int
mm_answer_sign(int sock, Buffer *m)
{
struct ssh *ssh = active_state; /* XXX */
extern int auth_sock; /* XXX move to state struct? */
struct sshkey *key;
struct sshbuf *sigbuf = NULL;
u_char *p = NULL, *signature = NULL;
char *alg = NULL;
size_t datlen, siglen, alglen;
int r, is_proof = 0;
u_int keyid;
const char proof_req[] = "hostkeys-prove-00@openssh.com";
debug3("%s", __func__);
if ((r = sshbuf_get_u32(m, &keyid)) != 0 ||
(r = sshbuf_get_string(m, &p, &datlen)) != 0 ||
(r = sshbuf_get_cstring(m, &alg, &alglen)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
if (keyid > INT_MAX)
fatal("%s: invalid key ID", __func__);
/*
* Supported KEX types use SHA1 (20 bytes), SHA256 (32 bytes),
* SHA384 (48 bytes) and SHA512 (64 bytes).
*
* Otherwise, verify the signature request is for a hostkey
* proof.
*
* XXX perform similar check for KEX signature requests too?
* it's not trivial, since what is signed is the hash, rather
* than the full kex structure...
*/
if (datlen != 20 && datlen != 32 && datlen != 48 && datlen != 64) {
/*
* Construct expected hostkey proof and compare it to what
* the client sent us.
*/
if (session_id2_len == 0) /* hostkeys is never first */
fatal("%s: bad data length: %zu", __func__, datlen);
if ((key = get_hostkey_public_by_index(keyid, ssh)) == NULL)
fatal("%s: no hostkey for index %d", __func__, keyid);
if ((sigbuf = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new", __func__);
if ((r = sshbuf_put_cstring(sigbuf, proof_req)) != 0 ||
(r = sshbuf_put_string(sigbuf, session_id2,
session_id2_len)) != 0 ||
(r = sshkey_puts(key, sigbuf)) != 0)
fatal("%s: couldn't prepare private key "
"proof buffer: %s", __func__, ssh_err(r));
if (datlen != sshbuf_len(sigbuf) ||
memcmp(p, sshbuf_ptr(sigbuf), sshbuf_len(sigbuf)) != 0)
fatal("%s: bad data length: %zu, hostkey proof len %zu",
__func__, datlen, sshbuf_len(sigbuf));
sshbuf_free(sigbuf);
is_proof = 1;
}
/* save session id, it will be passed on the first call */
if (session_id2_len == 0) {
session_id2_len = datlen;
session_id2 = xmalloc(session_id2_len);
memcpy(session_id2, p, session_id2_len);
}
if ((key = get_hostkey_by_index(keyid)) != NULL) {
if ((r = sshkey_sign(key, &signature, &siglen, p, datlen, alg,
datafellows)) != 0)
fatal("%s: sshkey_sign failed: %s",
__func__, ssh_err(r));
} else if ((key = get_hostkey_public_by_index(keyid, ssh)) != NULL &&
auth_sock > 0) {
if ((r = ssh_agent_sign(auth_sock, key, &signature, &siglen,
p, datlen, alg, datafellows)) != 0) {
fatal("%s: ssh_agent_sign failed: %s",
__func__, ssh_err(r));
}
} else
fatal("%s: no hostkey from index %d", __func__, keyid);
debug3("%s: %s signature %p(%zu)", __func__,
is_proof ? "KEX" : "hostkey proof", signature, siglen);
sshbuf_reset(m);
if ((r = sshbuf_put_string(m, signature, siglen)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
free(alg);
free(p);
free(signature);
mm_request_send(sock, MONITOR_ANS_SIGN, m);
/* Turn on permissions for getpwnam */
monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
return (0);
}
/* Retrieves the password entry and also checks if the user is permitted */
int
mm_answer_pwnamallow(int sock, Buffer *m)
{
char *username;
struct passwd *pwent;
int allowed = 0;
u_int i;
debug3("%s", __func__);
if (authctxt->attempt++ != 0)
fatal("%s: multiple attempts for getpwnam", __func__);
username = buffer_get_string(m, NULL);
pwent = getpwnamallow(username);
authctxt->user = xstrdup(username);
setproctitle("%s [priv]", pwent ? username : "unknown");
free(username);
buffer_clear(m);
if (pwent == NULL) {
buffer_put_char(m, 0);
authctxt->pw = fakepw();
goto out;
}
allowed = 1;
authctxt->pw = pwent;
authctxt->valid = 1;
buffer_put_char(m, 1);
buffer_put_string(m, pwent, sizeof(struct passwd));
buffer_put_cstring(m, pwent->pw_name);
buffer_put_cstring(m, "*");
buffer_put_cstring(m, pwent->pw_gecos);
buffer_put_cstring(m, pwent->pw_class);
buffer_put_cstring(m, pwent->pw_dir);
buffer_put_cstring(m, pwent->pw_shell);
out:
buffer_put_string(m, &options, sizeof(options));
#define M_CP_STROPT(x) do { \
if (options.x != NULL) \
buffer_put_cstring(m, options.x); \
} while (0)
#define M_CP_STRARRAYOPT(x, nx) do { \
for (i = 0; i < options.nx; i++) \
buffer_put_cstring(m, options.x[i]); \
} while (0)
/* See comment in servconf.h */
COPY_MATCH_STRING_OPTS();
#undef M_CP_STROPT
#undef M_CP_STRARRAYOPT
/* Create valid auth method lists */
if (auth2_setup_methods_lists(authctxt) != 0) {
/*
* The monitor will continue long enough to let the child
* run to it's packet_disconnect(), but it must not allow any
* authentication to succeed.
*/
debug("%s: no valid authentication method lists", __func__);
}
debug3("%s: sending MONITOR_ANS_PWNAM: %d", __func__, allowed);
mm_request_send(sock, MONITOR_ANS_PWNAM, m);
/* Allow service/style information on the auth context */
monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1);
monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1);
return (0);
}
int mm_answer_auth2_read_banner(int sock, Buffer *m)
{
char *banner;
buffer_clear(m);
banner = auth2_read_banner();
buffer_put_cstring(m, banner != NULL ? banner : "");
mm_request_send(sock, MONITOR_ANS_AUTH2_READ_BANNER, m);
free(banner);
return (0);
}
int
mm_answer_authserv(int sock, Buffer *m)
{
monitor_permit_authentications(1);
authctxt->service = buffer_get_string(m, NULL);
authctxt->style = buffer_get_string(m, NULL);
debug3("%s: service=%s, style=%s",
__func__, authctxt->service, authctxt->style);
if (strlen(authctxt->style) == 0) {
free(authctxt->style);
authctxt->style = NULL;
}
return (0);
}
int
mm_answer_authpassword(int sock, Buffer *m)
{
static int call_count;
char *passwd;
int authenticated;
u_int plen;
if (!options.password_authentication)
fatal("%s: password authentication not enabled", __func__);
passwd = buffer_get_string(m, &plen);
/* Only authenticate if the context is valid */
authenticated = options.password_authentication &&
auth_password(authctxt, passwd);
explicit_bzero(passwd, strlen(passwd));
free(passwd);
buffer_clear(m);
buffer_put_int(m, authenticated);
debug3("%s: sending result %d", __func__, authenticated);
mm_request_send(sock, MONITOR_ANS_AUTHPASSWORD, m);
call_count++;
if (plen == 0 && call_count == 1)
auth_method = "none";
else
auth_method = "password";
/* Causes monitor loop to terminate if authenticated */
return (authenticated);
}
int
mm_answer_bsdauthquery(int sock, Buffer *m)
{
char *name, *infotxt;
u_int numprompts;
u_int *echo_on;
char **prompts;
u_int success;
if (!options.kbd_interactive_authentication)
fatal("%s: kbd-int authentication not enabled", __func__);
success = bsdauth_query(authctxt, &name, &infotxt, &numprompts,
&prompts, &echo_on) < 0 ? 0 : 1;
buffer_clear(m);
buffer_put_int(m, success);
if (success)
buffer_put_cstring(m, prompts[0]);
debug3("%s: sending challenge success: %u", __func__, success);
mm_request_send(sock, MONITOR_ANS_BSDAUTHQUERY, m);
if (success) {
free(name);
free(infotxt);
free(prompts);
free(echo_on);
}
return (0);
}
int
mm_answer_bsdauthrespond(int sock, Buffer *m)
{
char *response;
int authok;
if (!options.kbd_interactive_authentication)
fatal("%s: kbd-int authentication not enabled", __func__);
if (authctxt->as == NULL)
fatal("%s: no bsd auth session", __func__);
response = buffer_get_string(m, NULL);
authok = options.challenge_response_authentication &&
auth_userresponse(authctxt->as, response, 0);
authctxt->as = NULL;
debug3("%s: <%s> = <%d>", __func__, response, authok);
free(response);
buffer_clear(m);
buffer_put_int(m, authok);
debug3("%s: sending authenticated: %d", __func__, authok);
mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m);
auth_method = "keyboard-interactive";
auth_submethod = "bsdauth";
return (authok != 0);
}
int
mm_answer_keyallowed(int sock, Buffer *m)
{
Key *key;
char *cuser, *chost;
u_char *blob;
u_int bloblen, pubkey_auth_attempt;
enum mm_keytype type = 0;
int allowed = 0;
debug3("%s entering", __func__);
type = buffer_get_int(m);
cuser = buffer_get_string(m, NULL);
chost = buffer_get_string(m, NULL);
blob = buffer_get_string(m, &bloblen);
pubkey_auth_attempt = buffer_get_int(m);
key = key_from_blob(blob, bloblen);
debug3("%s: key_from_blob: %p", __func__, key);
if (key != NULL && authctxt->valid) {
/* These should not make it past the privsep child */
if (key_type_plain(key->type) == KEY_RSA &&
(datafellows & SSH_BUG_RSASIGMD5) != 0)
fatal("%s: passed a SSH_BUG_RSASIGMD5 key", __func__);
switch (type) {
case MM_USERKEY:
allowed = options.pubkey_authentication &&
!auth2_userkey_already_used(authctxt, key) &&
match_pattern_list(sshkey_ssh_name(key),
options.pubkey_key_types, 0) == 1 &&
user_key_allowed(authctxt->pw, key,
pubkey_auth_attempt);
pubkey_auth_info(authctxt, key, NULL);
auth_method = "publickey";
if (options.pubkey_authentication &&
(!pubkey_auth_attempt || allowed != 1))
auth_clear_options();
break;
case MM_HOSTKEY:
allowed = options.hostbased_authentication &&
match_pattern_list(sshkey_ssh_name(key),
options.hostbased_key_types, 0) == 1 &&
hostbased_key_allowed(authctxt->pw,
cuser, chost, key);
pubkey_auth_info(authctxt, key,
"client user \"%.100s\", client host \"%.100s\"",
cuser, chost);
auth_method = "hostbased";
break;
default:
fatal("%s: unknown key type %d", __func__, type);
break;
}
}
debug3("%s: key %p is %s",
__func__, key, allowed ? "allowed" : "not allowed");
if (key != NULL)
key_free(key);
/* clear temporarily storage (used by verify) */
monitor_reset_key_state();
if (allowed) {
/* Save temporarily for comparison in verify */
key_blob = blob;
key_bloblen = bloblen;
key_blobtype = type;
hostbased_cuser = cuser;
hostbased_chost = chost;
} else {
/* Log failed attempt */
auth_log(authctxt, 0, 0, auth_method, NULL);
free(blob);
free(cuser);
free(chost);
}
buffer_clear(m);
buffer_put_int(m, allowed);
buffer_put_int(m, forced_command != NULL);
mm_request_send(sock, MONITOR_ANS_KEYALLOWED, m);
return (0);
}
static int
monitor_valid_userblob(u_char *data, u_int datalen)
{
Buffer b;
u_char *p;
char *userstyle, *cp;
u_int len;
int fail = 0;
buffer_init(&b);
buffer_append(&b, data, datalen);
if (datafellows & SSH_OLD_SESSIONID) {
p = buffer_ptr(&b);
len = buffer_len(&b);
if ((session_id2 == NULL) ||
(len < session_id2_len) ||
(timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
fail++;
buffer_consume(&b, session_id2_len);
} else {
p = buffer_get_string(&b, &len);
if ((session_id2 == NULL) ||
(len != session_id2_len) ||
(timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
fail++;
free(p);
}
if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
fail++;
cp = buffer_get_cstring(&b, NULL);
xasprintf(&userstyle, "%s%s%s", authctxt->user,
authctxt->style ? ":" : "",
authctxt->style ? authctxt->style : "");
if (strcmp(userstyle, cp) != 0) {
logit("wrong user name passed to monitor: "
"expected %s != %.100s", userstyle, cp);
fail++;
}
free(userstyle);
free(cp);
buffer_skip_string(&b);
if (datafellows & SSH_BUG_PKAUTH) {
if (!buffer_get_char(&b))
fail++;
} else {
cp = buffer_get_cstring(&b, NULL);
if (strcmp("publickey", cp) != 0)
fail++;
free(cp);
if (!buffer_get_char(&b))
fail++;
buffer_skip_string(&b);
}
buffer_skip_string(&b);
if (buffer_len(&b) != 0)
fail++;
buffer_free(&b);
return (fail == 0);
}
static int
monitor_valid_hostbasedblob(u_char *data, u_int datalen, char *cuser,
char *chost)
{
Buffer b;
char *p, *userstyle;
u_int len;
int fail = 0;
buffer_init(&b);
buffer_append(&b, data, datalen);
p = buffer_get_string(&b, &len);
if ((session_id2 == NULL) ||
(len != session_id2_len) ||
(timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
fail++;
free(p);
if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
fail++;
p = buffer_get_cstring(&b, NULL);
xasprintf(&userstyle, "%s%s%s", authctxt->user,
authctxt->style ? ":" : "",
authctxt->style ? authctxt->style : "");
if (strcmp(userstyle, p) != 0) {
logit("wrong user name passed to monitor: expected %s != %.100s",
userstyle, p);
fail++;
}
free(userstyle);
free(p);
buffer_skip_string(&b); /* service */
p = buffer_get_cstring(&b, NULL);
if (strcmp(p, "hostbased") != 0)
fail++;
free(p);
buffer_skip_string(&b); /* pkalg */
buffer_skip_string(&b); /* pkblob */
/* verify client host, strip trailing dot if necessary */
p = buffer_get_string(&b, NULL);
if (((len = strlen(p)) > 0) && p[len - 1] == '.')
p[len - 1] = '\0';
if (strcmp(p, chost) != 0)
fail++;
free(p);
/* verify client user */
p = buffer_get_string(&b, NULL);
if (strcmp(p, cuser) != 0)
fail++;
free(p);
if (buffer_len(&b) != 0)
fail++;
buffer_free(&b);
return (fail == 0);
}
int
mm_answer_keyverify(int sock, Buffer *m)
{
Key *key;
u_char *signature, *data, *blob;
u_int signaturelen, datalen, bloblen;
int verified = 0;
int valid_data = 0;
blob = buffer_get_string(m, &bloblen);
signature = buffer_get_string(m, &signaturelen);
data = buffer_get_string(m, &datalen);
if (hostbased_cuser == NULL || hostbased_chost == NULL ||
!monitor_allowed_key(blob, bloblen))
fatal("%s: bad key, not previously allowed", __func__);
key = key_from_blob(blob, bloblen);
if (key == NULL)
fatal("%s: bad public key blob", __func__);
switch (key_blobtype) {
case MM_USERKEY:
valid_data = monitor_valid_userblob(data, datalen);
break;
case MM_HOSTKEY:
valid_data = monitor_valid_hostbasedblob(data, datalen,
hostbased_cuser, hostbased_chost);
break;
default:
valid_data = 0;
break;
}
if (!valid_data)
fatal("%s: bad signature data blob", __func__);
verified = key_verify(key, signature, signaturelen, data, datalen);
debug3("%s: key %p signature %s",
__func__, key, (verified == 1) ? "verified" : "unverified");
/* If auth was successful then record key to ensure it isn't reused */
if (verified == 1 && key_blobtype == MM_USERKEY)
auth2_record_userkey(authctxt, key);
else
key_free(key);
free(blob);
free(signature);
free(data);
auth_method = key_blobtype == MM_USERKEY ? "publickey" : "hostbased";
monitor_reset_key_state();
buffer_clear(m);
buffer_put_int(m, verified);
mm_request_send(sock, MONITOR_ANS_KEYVERIFY, m);
return (verified == 1);
}
static void
mm_record_login(Session *s, struct passwd *pw)
{
struct ssh *ssh = active_state; /* XXX */
socklen_t fromlen;
struct sockaddr_storage from;
/*
* Get IP address of client. If the connection is not a socket, let
* the address be 0.0.0.0.
*/
memset(&from, 0, sizeof(from));
fromlen = sizeof(from);
if (packet_connection_is_on_socket()) {
if (getpeername(packet_get_connection_in(),
(struct sockaddr *)&from, &fromlen) < 0) {
debug("getpeername: %.100s", strerror(errno));
cleanup_exit(255);
}
}
/* Record that there was a login on that tty from the remote host. */
record_login(s->pid, s->tty, pw->pw_name, pw->pw_uid,
session_get_remote_name_or_ip(ssh, utmp_len, options.use_dns),
(struct sockaddr *)&from, fromlen);
}
static void
mm_session_close(Session *s)
{
debug3("%s: session %d pid %ld", __func__, s->self, (long)s->pid);
if (s->ttyfd != -1) {
debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ptyfd);
session_pty_cleanup2(s);
}
session_unused(s->self);
}
int
mm_answer_pty(int sock, Buffer *m)
{
extern struct monitor *pmonitor;
Session *s;
int res, fd0;
debug3("%s entering", __func__);
buffer_clear(m);
s = session_new();
if (s == NULL)
goto error;
s->authctxt = authctxt;
s->pw = authctxt->pw;
s->pid = pmonitor->m_pid;
res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty));
if (res == 0)
goto error;
pty_setowner(authctxt->pw, s->tty);
buffer_put_int(m, 1);
buffer_put_cstring(m, s->tty);
/* We need to trick ttyslot */
if (dup2(s->ttyfd, 0) == -1)
fatal("%s: dup2", __func__);
mm_record_login(s, authctxt->pw);
/* Now we can close the file descriptor again */
close(0);
/* send messages generated by record_login */
buffer_put_string(m, buffer_ptr(&loginmsg), buffer_len(&loginmsg));
buffer_clear(&loginmsg);
mm_request_send(sock, MONITOR_ANS_PTY, m);
if (mm_send_fd(sock, s->ptyfd) == -1 ||
mm_send_fd(sock, s->ttyfd) == -1)
fatal("%s: send fds failed", __func__);
/* make sure nothing uses fd 0 */
if ((fd0 = open(_PATH_DEVNULL, O_RDONLY)) < 0)
fatal("%s: open(/dev/null): %s", __func__, strerror(errno));
if (fd0 != 0)
error("%s: fd0 %d != 0", __func__, fd0);
/* slave is not needed */
close(s->ttyfd);
s->ttyfd = s->ptyfd;
/* no need to dup() because nobody closes ptyfd */
s->ptymaster = s->ptyfd;
debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ttyfd);
return (0);
error:
if (s != NULL)
mm_session_close(s);
buffer_put_int(m, 0);
mm_request_send(sock, MONITOR_ANS_PTY, m);
return (0);
}
int
mm_answer_pty_cleanup(int sock, Buffer *m)
{
Session *s;
char *tty;
debug3("%s entering", __func__);
tty = buffer_get_string(m, NULL);
if ((s = session_by_tty(tty)) != NULL)
mm_session_close(s);
buffer_clear(m);
free(tty);
return (0);
}
int
mm_answer_term(int sock, Buffer *req)
{
extern struct monitor *pmonitor;
int res, status;
debug3("%s: tearing down sessions", __func__);
/* The child is terminating */
session_destroy_all(&mm_session_close);
while (waitpid(pmonitor->m_pid, &status, 0) == -1)
if (errno != EINTR)
exit(1);
res = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
/* Terminate process */
exit(res);
}
void
monitor_apply_keystate(struct monitor *pmonitor)
{
struct ssh *ssh = active_state; /* XXX */
struct kex *kex;
int r;
debug3("%s: packet_set_state", __func__);
if ((r = ssh_packet_set_state(ssh, child_state)) != 0)
fatal("%s: packet_set_state: %s", __func__, ssh_err(r));
sshbuf_free(child_state);
child_state = NULL;
if ((kex = ssh->kex) != NULL) {
/* XXX set callbacks */
#ifdef WITH_OPENSSL
kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
#endif
kex->kex[KEX_C25519_SHA256] = kexc25519_server;
kex->load_host_public_key=&get_hostkey_public_by_type;
kex->load_host_private_key=&get_hostkey_private_by_type;
kex->host_key_index=&get_hostkey_index;
kex->sign = sshd_hostkey_sign;
}
/* Update with new address */
if (options.compression) {
ssh_packet_set_compress_hooks(ssh, pmonitor->m_zlib,
(ssh_packet_comp_alloc_func *)mm_zalloc,
(ssh_packet_comp_free_func *)mm_zfree);
}
}
/* This function requries careful sanity checking */
void
mm_get_keystate(struct monitor *pmonitor)
{
debug3("%s: Waiting for new keys", __func__);
if ((child_state = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
mm_request_receive_expect(pmonitor->m_sendfd, MONITOR_REQ_KEYEXPORT,
child_state);
debug3("%s: GOT new keys", __func__);
}
/* XXX */
#define FD_CLOSEONEXEC(x) do { \
if (fcntl(x, F_SETFD, FD_CLOEXEC) == -1) \
fatal("fcntl(%d, F_SETFD)", x); \
} while (0)
static void
monitor_openfds(struct monitor *mon, int do_logfds)
{
int pair[2];
if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
fatal("%s: socketpair: %s", __func__, strerror(errno));
FD_CLOSEONEXEC(pair[0]);
FD_CLOSEONEXEC(pair[1]);
mon->m_recvfd = pair[0];
mon->m_sendfd = pair[1];
if (do_logfds) {
if (pipe(pair) == -1)
fatal("%s: pipe: %s", __func__, strerror(errno));
FD_CLOSEONEXEC(pair[0]);
FD_CLOSEONEXEC(pair[1]);
mon->m_log_recvfd = pair[0];
mon->m_log_sendfd = pair[1];
} else
mon->m_log_recvfd = mon->m_log_sendfd = -1;
}
#define MM_MEMSIZE 65536
struct monitor *
monitor_init(void)
{
struct ssh *ssh = active_state; /* XXX */
struct monitor *mon;
mon = xcalloc(1, sizeof(*mon));
monitor_openfds(mon, 1);
/* Used to share zlib space across processes */
if (options.compression) {
mon->m_zback = mm_create(NULL, MM_MEMSIZE);
mon->m_zlib = mm_create(mon->m_zback, 20 * MM_MEMSIZE);
/* Compression needs to share state across borders */
ssh_packet_set_compress_hooks(ssh, mon->m_zlib,
(ssh_packet_comp_alloc_func *)mm_zalloc,
(ssh_packet_comp_free_func *)mm_zfree);
}
return mon;
}
void
monitor_reinit(struct monitor *mon)
{
monitor_openfds(mon, 0);
}
#ifdef GSSAPI
int
mm_answer_gss_setup_ctx(int sock, Buffer *m)
{
gss_OID_desc goid;
OM_uint32 major;
u_int len;
if (!options.gss_authentication)
fatal("%s: GSSAPI authentication not enabled", __func__);
goid.elements = buffer_get_string(m, &len);
goid.length = len;
major = ssh_gssapi_server_ctx(&gsscontext, &goid);
free(goid.elements);
buffer_clear(m);
buffer_put_int(m, major);
mm_request_send(sock, MONITOR_ANS_GSSSETUP, m);
/* Now we have a context, enable the step */
monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 1);
return (0);
}
int
mm_answer_gss_accept_ctx(int sock, Buffer *m)
{
gss_buffer_desc in;
gss_buffer_desc out = GSS_C_EMPTY_BUFFER;
OM_uint32 major, minor;
OM_uint32 flags = 0; /* GSI needs this */
u_int len;
if (!options.gss_authentication)
fatal("%s: GSSAPI authentication not enabled", __func__);
in.value = buffer_get_string(m, &len);
in.length = len;
major = ssh_gssapi_accept_ctx(gsscontext, &in, &out, &flags);
free(in.value);
buffer_clear(m);
buffer_put_int(m, major);
buffer_put_string(m, out.value, out.length);
buffer_put_int(m, flags);
mm_request_send(sock, MONITOR_ANS_GSSSTEP, m);
gss_release_buffer(&minor, &out);
if (major == GSS_S_COMPLETE) {
monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0);
monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1);
}
return (0);
}
int
mm_answer_gss_checkmic(int sock, Buffer *m)
{
gss_buffer_desc gssbuf, mic;
OM_uint32 ret;
u_int len;
if (!options.gss_authentication)
fatal("%s: GSSAPI authentication not enabled", __func__);
gssbuf.value = buffer_get_string(m, &len);
gssbuf.length = len;
mic.value = buffer_get_string(m, &len);
mic.length = len;
ret = ssh_gssapi_checkmic(gsscontext, &gssbuf, &mic);
free(gssbuf.value);
free(mic.value);
buffer_clear(m);
buffer_put_int(m, ret);
mm_request_send(sock, MONITOR_ANS_GSSCHECKMIC, m);
if (!GSS_ERROR(ret))
monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
return (0);
}
int
mm_answer_gss_userok(int sock, Buffer *m)
{
int authenticated;
if (!options.gss_authentication)
fatal("%s: GSSAPI authentication not enabled", __func__);
authenticated = authctxt->valid && ssh_gssapi_userok(authctxt->user);
buffer_clear(m);
buffer_put_int(m, authenticated);
debug3("%s: sending result %d", __func__, authenticated);
mm_request_send(sock, MONITOR_ANS_GSSUSEROK, m);
auth_method = "gssapi-with-mic";
/* Monitor loop will terminate if authenticated */
return (authenticated);
}
#endif /* GSSAPI */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4767_0 |
crossvul-cpp_data_good_2018_0 | /*
* Kernel-based Virtual Machine driver for Linux
*
* derived from drivers/kvm/kvm_main.c
*
* Copyright (C) 2006 Qumranet, Inc.
* Copyright (C) 2008 Qumranet, Inc.
* Copyright IBM Corporation, 2008
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Authors:
* Avi Kivity <avi@qumranet.com>
* Yaniv Kamay <yaniv@qumranet.com>
* Amit Shah <amit.shah@qumranet.com>
* Ben-Ami Yassour <benami@il.ibm.com>
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
*/
#include <linux/kvm_host.h>
#include "irq.h"
#include "mmu.h"
#include "i8254.h"
#include "tss.h"
#include "kvm_cache_regs.h"
#include "x86.h"
#include "cpuid.h"
#include <linux/clocksource.h>
#include <linux/interrupt.h>
#include <linux/kvm.h>
#include <linux/fs.h>
#include <linux/vmalloc.h>
#include <linux/module.h>
#include <linux/mman.h>
#include <linux/highmem.h>
#include <linux/iommu.h>
#include <linux/intel-iommu.h>
#include <linux/cpufreq.h>
#include <linux/user-return-notifier.h>
#include <linux/srcu.h>
#include <linux/slab.h>
#include <linux/perf_event.h>
#include <linux/uaccess.h>
#include <linux/hash.h>
#include <linux/pci.h>
#include <linux/timekeeper_internal.h>
#include <linux/pvclock_gtod.h>
#include <trace/events/kvm.h>
#define CREATE_TRACE_POINTS
#include "trace.h"
#include <asm/debugreg.h>
#include <asm/msr.h>
#include <asm/desc.h>
#include <asm/mtrr.h>
#include <asm/mce.h>
#include <asm/i387.h>
#include <asm/fpu-internal.h> /* Ugh! */
#include <asm/xcr.h>
#include <asm/pvclock.h>
#include <asm/div64.h>
#define MAX_IO_MSRS 256
#define KVM_MAX_MCE_BANKS 32
#define KVM_MCE_CAP_SUPPORTED (MCG_CTL_P | MCG_SER_P)
#define emul_to_vcpu(ctxt) \
container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
/* EFER defaults:
* - enable syscall per default because its emulated by KVM
* - enable LME and LMA per default on 64 bit KVM
*/
#ifdef CONFIG_X86_64
static
u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
#else
static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
#endif
#define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
#define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
static void update_cr8_intercept(struct kvm_vcpu *vcpu);
static void process_nmi(struct kvm_vcpu *vcpu);
struct kvm_x86_ops *kvm_x86_ops;
EXPORT_SYMBOL_GPL(kvm_x86_ops);
static bool ignore_msrs = 0;
module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
unsigned int min_timer_period_us = 500;
module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
bool kvm_has_tsc_control;
EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
u32 kvm_max_guest_tsc_khz;
EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
/* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
static u32 tsc_tolerance_ppm = 250;
module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
#define KVM_NR_SHARED_MSRS 16
struct kvm_shared_msrs_global {
int nr;
u32 msrs[KVM_NR_SHARED_MSRS];
};
struct kvm_shared_msrs {
struct user_return_notifier urn;
bool registered;
struct kvm_shared_msr_values {
u64 host;
u64 curr;
} values[KVM_NR_SHARED_MSRS];
};
static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
static struct kvm_shared_msrs __percpu *shared_msrs;
struct kvm_stats_debugfs_item debugfs_entries[] = {
{ "pf_fixed", VCPU_STAT(pf_fixed) },
{ "pf_guest", VCPU_STAT(pf_guest) },
{ "tlb_flush", VCPU_STAT(tlb_flush) },
{ "invlpg", VCPU_STAT(invlpg) },
{ "exits", VCPU_STAT(exits) },
{ "io_exits", VCPU_STAT(io_exits) },
{ "mmio_exits", VCPU_STAT(mmio_exits) },
{ "signal_exits", VCPU_STAT(signal_exits) },
{ "irq_window", VCPU_STAT(irq_window_exits) },
{ "nmi_window", VCPU_STAT(nmi_window_exits) },
{ "halt_exits", VCPU_STAT(halt_exits) },
{ "halt_wakeup", VCPU_STAT(halt_wakeup) },
{ "hypercalls", VCPU_STAT(hypercalls) },
{ "request_irq", VCPU_STAT(request_irq_exits) },
{ "irq_exits", VCPU_STAT(irq_exits) },
{ "host_state_reload", VCPU_STAT(host_state_reload) },
{ "efer_reload", VCPU_STAT(efer_reload) },
{ "fpu_reload", VCPU_STAT(fpu_reload) },
{ "insn_emulation", VCPU_STAT(insn_emulation) },
{ "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
{ "irq_injections", VCPU_STAT(irq_injections) },
{ "nmi_injections", VCPU_STAT(nmi_injections) },
{ "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
{ "mmu_pte_write", VM_STAT(mmu_pte_write) },
{ "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
{ "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
{ "mmu_flooded", VM_STAT(mmu_flooded) },
{ "mmu_recycled", VM_STAT(mmu_recycled) },
{ "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
{ "mmu_unsync", VM_STAT(mmu_unsync) },
{ "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
{ "largepages", VM_STAT(lpages) },
{ NULL }
};
u64 __read_mostly host_xcr0;
static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
{
int i;
for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
vcpu->arch.apf.gfns[i] = ~0;
}
static void kvm_on_user_return(struct user_return_notifier *urn)
{
unsigned slot;
struct kvm_shared_msrs *locals
= container_of(urn, struct kvm_shared_msrs, urn);
struct kvm_shared_msr_values *values;
for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
values = &locals->values[slot];
if (values->host != values->curr) {
wrmsrl(shared_msrs_global.msrs[slot], values->host);
values->curr = values->host;
}
}
locals->registered = false;
user_return_notifier_unregister(urn);
}
static void shared_msr_update(unsigned slot, u32 msr)
{
u64 value;
unsigned int cpu = smp_processor_id();
struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
/* only read, and nobody should modify it at this time,
* so don't need lock */
if (slot >= shared_msrs_global.nr) {
printk(KERN_ERR "kvm: invalid MSR slot!");
return;
}
rdmsrl_safe(msr, &value);
smsr->values[slot].host = value;
smsr->values[slot].curr = value;
}
void kvm_define_shared_msr(unsigned slot, u32 msr)
{
if (slot >= shared_msrs_global.nr)
shared_msrs_global.nr = slot + 1;
shared_msrs_global.msrs[slot] = msr;
/* we need ensured the shared_msr_global have been updated */
smp_wmb();
}
EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
static void kvm_shared_msr_cpu_online(void)
{
unsigned i;
for (i = 0; i < shared_msrs_global.nr; ++i)
shared_msr_update(i, shared_msrs_global.msrs[i]);
}
void kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
{
unsigned int cpu = smp_processor_id();
struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
if (((value ^ smsr->values[slot].curr) & mask) == 0)
return;
smsr->values[slot].curr = value;
wrmsrl(shared_msrs_global.msrs[slot], value);
if (!smsr->registered) {
smsr->urn.on_user_return = kvm_on_user_return;
user_return_notifier_register(&smsr->urn);
smsr->registered = true;
}
}
EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
static void drop_user_return_notifiers(void *ignore)
{
unsigned int cpu = smp_processor_id();
struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
if (smsr->registered)
kvm_on_user_return(&smsr->urn);
}
u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
{
return vcpu->arch.apic_base;
}
EXPORT_SYMBOL_GPL(kvm_get_apic_base);
int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
{
u64 old_state = vcpu->arch.apic_base &
(MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
u64 new_state = msr_info->data &
(MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) |
0x2ff | (guest_cpuid_has_x2apic(vcpu) ? 0 : X2APIC_ENABLE);
if (!msr_info->host_initiated &&
((msr_info->data & reserved_bits) != 0 ||
new_state == X2APIC_ENABLE ||
(new_state == MSR_IA32_APICBASE_ENABLE &&
old_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) ||
(new_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE) &&
old_state == 0)))
return 1;
kvm_lapic_set_base(vcpu, msr_info->data);
return 0;
}
EXPORT_SYMBOL_GPL(kvm_set_apic_base);
asmlinkage void kvm_spurious_fault(void)
{
/* Fault while not rebooting. We want the trace. */
BUG();
}
EXPORT_SYMBOL_GPL(kvm_spurious_fault);
#define EXCPT_BENIGN 0
#define EXCPT_CONTRIBUTORY 1
#define EXCPT_PF 2
static int exception_class(int vector)
{
switch (vector) {
case PF_VECTOR:
return EXCPT_PF;
case DE_VECTOR:
case TS_VECTOR:
case NP_VECTOR:
case SS_VECTOR:
case GP_VECTOR:
return EXCPT_CONTRIBUTORY;
default:
break;
}
return EXCPT_BENIGN;
}
static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
unsigned nr, bool has_error, u32 error_code,
bool reinject)
{
u32 prev_nr;
int class1, class2;
kvm_make_request(KVM_REQ_EVENT, vcpu);
if (!vcpu->arch.exception.pending) {
queue:
vcpu->arch.exception.pending = true;
vcpu->arch.exception.has_error_code = has_error;
vcpu->arch.exception.nr = nr;
vcpu->arch.exception.error_code = error_code;
vcpu->arch.exception.reinject = reinject;
return;
}
/* to check exception */
prev_nr = vcpu->arch.exception.nr;
if (prev_nr == DF_VECTOR) {
/* triple fault -> shutdown */
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
return;
}
class1 = exception_class(prev_nr);
class2 = exception_class(nr);
if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
|| (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
/* generate double fault per SDM Table 5-5 */
vcpu->arch.exception.pending = true;
vcpu->arch.exception.has_error_code = true;
vcpu->arch.exception.nr = DF_VECTOR;
vcpu->arch.exception.error_code = 0;
} else
/* replace previous exception with a new one in a hope
that instruction re-execution will regenerate lost
exception */
goto queue;
}
void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
{
kvm_multiple_exception(vcpu, nr, false, 0, false);
}
EXPORT_SYMBOL_GPL(kvm_queue_exception);
void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
{
kvm_multiple_exception(vcpu, nr, false, 0, true);
}
EXPORT_SYMBOL_GPL(kvm_requeue_exception);
void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
{
if (err)
kvm_inject_gp(vcpu, 0);
else
kvm_x86_ops->skip_emulated_instruction(vcpu);
}
EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
{
++vcpu->stat.pf_guest;
vcpu->arch.cr2 = fault->address;
kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
}
EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
void kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
{
if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
else
vcpu->arch.mmu.inject_page_fault(vcpu, fault);
}
void kvm_inject_nmi(struct kvm_vcpu *vcpu)
{
atomic_inc(&vcpu->arch.nmi_queued);
kvm_make_request(KVM_REQ_NMI, vcpu);
}
EXPORT_SYMBOL_GPL(kvm_inject_nmi);
void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
{
kvm_multiple_exception(vcpu, nr, true, error_code, false);
}
EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
{
kvm_multiple_exception(vcpu, nr, true, error_code, true);
}
EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
/*
* Checks if cpl <= required_cpl; if true, return true. Otherwise queue
* a #GP and return false.
*/
bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
{
if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
return true;
kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
return false;
}
EXPORT_SYMBOL_GPL(kvm_require_cpl);
/*
* This function will be used to read from the physical memory of the currently
* running guest. The difference to kvm_read_guest_page is that this function
* can read from guest physical or from the guest's guest physical memory.
*/
int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
gfn_t ngfn, void *data, int offset, int len,
u32 access)
{
gfn_t real_gfn;
gpa_t ngpa;
ngpa = gfn_to_gpa(ngfn);
real_gfn = mmu->translate_gpa(vcpu, ngpa, access);
if (real_gfn == UNMAPPED_GVA)
return -EFAULT;
real_gfn = gpa_to_gfn(real_gfn);
return kvm_read_guest_page(vcpu->kvm, real_gfn, data, offset, len);
}
EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
void *data, int offset, int len, u32 access)
{
return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
data, offset, len, access);
}
/*
* Load the pae pdptrs. Return true is they are all valid.
*/
int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
{
gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
int i;
int ret;
u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
offset * sizeof(u64), sizeof(pdpte),
PFERR_USER_MASK|PFERR_WRITE_MASK);
if (ret < 0) {
ret = 0;
goto out;
}
for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
if (is_present_gpte(pdpte[i]) &&
(pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
ret = 0;
goto out;
}
}
ret = 1;
memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
__set_bit(VCPU_EXREG_PDPTR,
(unsigned long *)&vcpu->arch.regs_avail);
__set_bit(VCPU_EXREG_PDPTR,
(unsigned long *)&vcpu->arch.regs_dirty);
out:
return ret;
}
EXPORT_SYMBOL_GPL(load_pdptrs);
static bool pdptrs_changed(struct kvm_vcpu *vcpu)
{
u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
bool changed = true;
int offset;
gfn_t gfn;
int r;
if (is_long_mode(vcpu) || !is_pae(vcpu))
return false;
if (!test_bit(VCPU_EXREG_PDPTR,
(unsigned long *)&vcpu->arch.regs_avail))
return true;
gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
PFERR_USER_MASK | PFERR_WRITE_MASK);
if (r < 0)
goto out;
changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
out:
return changed;
}
int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
{
unsigned long old_cr0 = kvm_read_cr0(vcpu);
unsigned long update_bits = X86_CR0_PG | X86_CR0_WP |
X86_CR0_CD | X86_CR0_NW;
cr0 |= X86_CR0_ET;
#ifdef CONFIG_X86_64
if (cr0 & 0xffffffff00000000UL)
return 1;
#endif
cr0 &= ~CR0_RESERVED_BITS;
if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
return 1;
if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
return 1;
if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
#ifdef CONFIG_X86_64
if ((vcpu->arch.efer & EFER_LME)) {
int cs_db, cs_l;
if (!is_pae(vcpu))
return 1;
kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
if (cs_l)
return 1;
} else
#endif
if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
kvm_read_cr3(vcpu)))
return 1;
}
if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
return 1;
kvm_x86_ops->set_cr0(vcpu, cr0);
if ((cr0 ^ old_cr0) & X86_CR0_PG) {
kvm_clear_async_pf_completion_queue(vcpu);
kvm_async_pf_hash_reset(vcpu);
}
if ((cr0 ^ old_cr0) & update_bits)
kvm_mmu_reset_context(vcpu);
return 0;
}
EXPORT_SYMBOL_GPL(kvm_set_cr0);
void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
{
(void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
}
EXPORT_SYMBOL_GPL(kvm_lmsw);
static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
{
if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
!vcpu->guest_xcr0_loaded) {
/* kvm_set_xcr() also depends on this */
xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
vcpu->guest_xcr0_loaded = 1;
}
}
static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
{
if (vcpu->guest_xcr0_loaded) {
if (vcpu->arch.xcr0 != host_xcr0)
xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
vcpu->guest_xcr0_loaded = 0;
}
}
int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
{
u64 xcr0;
u64 valid_bits;
/* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
if (index != XCR_XFEATURE_ENABLED_MASK)
return 1;
xcr0 = xcr;
if (!(xcr0 & XSTATE_FP))
return 1;
if ((xcr0 & XSTATE_YMM) && !(xcr0 & XSTATE_SSE))
return 1;
/*
* Do not allow the guest to set bits that we do not support
* saving. However, xcr0 bit 0 is always set, even if the
* emulated CPU does not support XSAVE (see fx_init).
*/
valid_bits = vcpu->arch.guest_supported_xcr0 | XSTATE_FP;
if (xcr0 & ~valid_bits)
return 1;
kvm_put_guest_xcr0(vcpu);
vcpu->arch.xcr0 = xcr0;
return 0;
}
int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
{
if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
__kvm_set_xcr(vcpu, index, xcr)) {
kvm_inject_gp(vcpu, 0);
return 1;
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_set_xcr);
int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
{
unsigned long old_cr4 = kvm_read_cr4(vcpu);
unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE |
X86_CR4_PAE | X86_CR4_SMEP;
if (cr4 & CR4_RESERVED_BITS)
return 1;
if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
return 1;
if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
return 1;
if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_FSGSBASE))
return 1;
if (is_long_mode(vcpu)) {
if (!(cr4 & X86_CR4_PAE))
return 1;
} else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
&& ((cr4 ^ old_cr4) & pdptr_bits)
&& !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
kvm_read_cr3(vcpu)))
return 1;
if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
if (!guest_cpuid_has_pcid(vcpu))
return 1;
/* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
return 1;
}
if (kvm_x86_ops->set_cr4(vcpu, cr4))
return 1;
if (((cr4 ^ old_cr4) & pdptr_bits) ||
(!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
kvm_mmu_reset_context(vcpu);
if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
kvm_update_cpuid(vcpu);
return 0;
}
EXPORT_SYMBOL_GPL(kvm_set_cr4);
int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
{
if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
kvm_mmu_sync_roots(vcpu);
kvm_mmu_flush_tlb(vcpu);
return 0;
}
if (is_long_mode(vcpu)) {
if (kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE)) {
if (cr3 & CR3_PCID_ENABLED_RESERVED_BITS)
return 1;
} else
if (cr3 & CR3_L_MODE_RESERVED_BITS)
return 1;
} else {
if (is_pae(vcpu)) {
if (cr3 & CR3_PAE_RESERVED_BITS)
return 1;
if (is_paging(vcpu) &&
!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
return 1;
}
/*
* We don't check reserved bits in nonpae mode, because
* this isn't enforced, and VMware depends on this.
*/
}
vcpu->arch.cr3 = cr3;
__set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
kvm_mmu_new_cr3(vcpu);
return 0;
}
EXPORT_SYMBOL_GPL(kvm_set_cr3);
int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
{
if (cr8 & CR8_RESERVED_BITS)
return 1;
if (irqchip_in_kernel(vcpu->kvm))
kvm_lapic_set_tpr(vcpu, cr8);
else
vcpu->arch.cr8 = cr8;
return 0;
}
EXPORT_SYMBOL_GPL(kvm_set_cr8);
unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
{
if (irqchip_in_kernel(vcpu->kvm))
return kvm_lapic_get_cr8(vcpu);
else
return vcpu->arch.cr8;
}
EXPORT_SYMBOL_GPL(kvm_get_cr8);
static void kvm_update_dr6(struct kvm_vcpu *vcpu)
{
if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
}
static void kvm_update_dr7(struct kvm_vcpu *vcpu)
{
unsigned long dr7;
if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
dr7 = vcpu->arch.guest_debug_dr7;
else
dr7 = vcpu->arch.dr7;
kvm_x86_ops->set_dr7(vcpu, dr7);
vcpu->arch.switch_db_regs = (dr7 & DR7_BP_EN_MASK);
}
static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
{
switch (dr) {
case 0 ... 3:
vcpu->arch.db[dr] = val;
if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
vcpu->arch.eff_db[dr] = val;
break;
case 4:
if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
return 1; /* #UD */
/* fall through */
case 6:
if (val & 0xffffffff00000000ULL)
return -1; /* #GP */
vcpu->arch.dr6 = (val & DR6_VOLATILE) | DR6_FIXED_1;
kvm_update_dr6(vcpu);
break;
case 5:
if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
return 1; /* #UD */
/* fall through */
default: /* 7 */
if (val & 0xffffffff00000000ULL)
return -1; /* #GP */
vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
kvm_update_dr7(vcpu);
break;
}
return 0;
}
int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
{
int res;
res = __kvm_set_dr(vcpu, dr, val);
if (res > 0)
kvm_queue_exception(vcpu, UD_VECTOR);
else if (res < 0)
kvm_inject_gp(vcpu, 0);
return res;
}
EXPORT_SYMBOL_GPL(kvm_set_dr);
static int _kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
{
switch (dr) {
case 0 ... 3:
*val = vcpu->arch.db[dr];
break;
case 4:
if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
return 1;
/* fall through */
case 6:
if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
*val = vcpu->arch.dr6;
else
*val = kvm_x86_ops->get_dr6(vcpu);
break;
case 5:
if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
return 1;
/* fall through */
default: /* 7 */
*val = vcpu->arch.dr7;
break;
}
return 0;
}
int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
{
if (_kvm_get_dr(vcpu, dr, val)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_get_dr);
bool kvm_rdpmc(struct kvm_vcpu *vcpu)
{
u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
u64 data;
int err;
err = kvm_pmu_read_pmc(vcpu, ecx, &data);
if (err)
return err;
kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
return err;
}
EXPORT_SYMBOL_GPL(kvm_rdpmc);
/*
* List of msr numbers which we expose to userspace through KVM_GET_MSRS
* and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
*
* This list is modified at module load time to reflect the
* capabilities of the host cpu. This capabilities test skips MSRs that are
* kvm-specific. Those are put in the beginning of the list.
*/
#define KVM_SAVE_MSRS_BEGIN 12
static u32 msrs_to_save[] = {
MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
MSR_KVM_PV_EOI_EN,
MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
MSR_STAR,
#ifdef CONFIG_X86_64
MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
#endif
MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
MSR_IA32_FEATURE_CONTROL
};
static unsigned num_msrs_to_save;
static const u32 emulated_msrs[] = {
MSR_IA32_TSC_ADJUST,
MSR_IA32_TSCDEADLINE,
MSR_IA32_MISC_ENABLE,
MSR_IA32_MCG_STATUS,
MSR_IA32_MCG_CTL,
};
bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
{
if (efer & efer_reserved_bits)
return false;
if (efer & EFER_FFXSR) {
struct kvm_cpuid_entry2 *feat;
feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
return false;
}
if (efer & EFER_SVME) {
struct kvm_cpuid_entry2 *feat;
feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
return false;
}
return true;
}
EXPORT_SYMBOL_GPL(kvm_valid_efer);
static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
{
u64 old_efer = vcpu->arch.efer;
if (!kvm_valid_efer(vcpu, efer))
return 1;
if (is_paging(vcpu)
&& (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
return 1;
efer &= ~EFER_LMA;
efer |= vcpu->arch.efer & EFER_LMA;
kvm_x86_ops->set_efer(vcpu, efer);
/* Update reserved bits */
if ((efer ^ old_efer) & EFER_NX)
kvm_mmu_reset_context(vcpu);
return 0;
}
void kvm_enable_efer_bits(u64 mask)
{
efer_reserved_bits &= ~mask;
}
EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
/*
* Writes msr value into into the appropriate "register".
* Returns 0 on success, non-0 otherwise.
* Assumes vcpu_load() was already called.
*/
int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
{
return kvm_x86_ops->set_msr(vcpu, msr);
}
/*
* Adapt set_msr() to msr_io()'s calling convention
*/
static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
{
struct msr_data msr;
msr.data = *data;
msr.index = index;
msr.host_initiated = true;
return kvm_set_msr(vcpu, &msr);
}
#ifdef CONFIG_X86_64
struct pvclock_gtod_data {
seqcount_t seq;
struct { /* extract of a clocksource struct */
int vclock_mode;
cycle_t cycle_last;
cycle_t mask;
u32 mult;
u32 shift;
} clock;
/* open coded 'struct timespec' */
u64 monotonic_time_snsec;
time_t monotonic_time_sec;
};
static struct pvclock_gtod_data pvclock_gtod_data;
static void update_pvclock_gtod(struct timekeeper *tk)
{
struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
write_seqcount_begin(&vdata->seq);
/* copy pvclock gtod data */
vdata->clock.vclock_mode = tk->clock->archdata.vclock_mode;
vdata->clock.cycle_last = tk->clock->cycle_last;
vdata->clock.mask = tk->clock->mask;
vdata->clock.mult = tk->mult;
vdata->clock.shift = tk->shift;
vdata->monotonic_time_sec = tk->xtime_sec
+ tk->wall_to_monotonic.tv_sec;
vdata->monotonic_time_snsec = tk->xtime_nsec
+ (tk->wall_to_monotonic.tv_nsec
<< tk->shift);
while (vdata->monotonic_time_snsec >=
(((u64)NSEC_PER_SEC) << tk->shift)) {
vdata->monotonic_time_snsec -=
((u64)NSEC_PER_SEC) << tk->shift;
vdata->monotonic_time_sec++;
}
write_seqcount_end(&vdata->seq);
}
#endif
static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
{
int version;
int r;
struct pvclock_wall_clock wc;
struct timespec boot;
if (!wall_clock)
return;
r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
if (r)
return;
if (version & 1)
++version; /* first time write, random junk */
++version;
kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
/*
* The guest calculates current wall clock time by adding
* system time (updated by kvm_guest_time_update below) to the
* wall clock specified here. guest system time equals host
* system time for us, thus we must fill in host boot time here.
*/
getboottime(&boot);
if (kvm->arch.kvmclock_offset) {
struct timespec ts = ns_to_timespec(kvm->arch.kvmclock_offset);
boot = timespec_sub(boot, ts);
}
wc.sec = boot.tv_sec;
wc.nsec = boot.tv_nsec;
wc.version = version;
kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
version++;
kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
}
static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
{
uint32_t quotient, remainder;
/* Don't try to replace with do_div(), this one calculates
* "(dividend << 32) / divisor" */
__asm__ ( "divl %4"
: "=a" (quotient), "=d" (remainder)
: "0" (0), "1" (dividend), "r" (divisor) );
return quotient;
}
static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
s8 *pshift, u32 *pmultiplier)
{
uint64_t scaled64;
int32_t shift = 0;
uint64_t tps64;
uint32_t tps32;
tps64 = base_khz * 1000LL;
scaled64 = scaled_khz * 1000LL;
while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
tps64 >>= 1;
shift--;
}
tps32 = (uint32_t)tps64;
while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
scaled64 >>= 1;
else
tps32 <<= 1;
shift++;
}
*pshift = shift;
*pmultiplier = div_frac(scaled64, tps32);
pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
__func__, base_khz, scaled_khz, shift, *pmultiplier);
}
static inline u64 get_kernel_ns(void)
{
struct timespec ts;
WARN_ON(preemptible());
ktime_get_ts(&ts);
monotonic_to_bootbased(&ts);
return timespec_to_ns(&ts);
}
#ifdef CONFIG_X86_64
static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
#endif
static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
unsigned long max_tsc_khz;
static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
{
return pvclock_scale_delta(nsec, vcpu->arch.virtual_tsc_mult,
vcpu->arch.virtual_tsc_shift);
}
static u32 adjust_tsc_khz(u32 khz, s32 ppm)
{
u64 v = (u64)khz * (1000000 + ppm);
do_div(v, 1000000);
return v;
}
static void kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
{
u32 thresh_lo, thresh_hi;
int use_scaling = 0;
/* tsc_khz can be zero if TSC calibration fails */
if (this_tsc_khz == 0)
return;
/* Compute a scale to convert nanoseconds in TSC cycles */
kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
&vcpu->arch.virtual_tsc_shift,
&vcpu->arch.virtual_tsc_mult);
vcpu->arch.virtual_tsc_khz = this_tsc_khz;
/*
* Compute the variation in TSC rate which is acceptable
* within the range of tolerance and decide if the
* rate being applied is within that bounds of the hardware
* rate. If so, no scaling or compensation need be done.
*/
thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
if (this_tsc_khz < thresh_lo || this_tsc_khz > thresh_hi) {
pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", this_tsc_khz, thresh_lo, thresh_hi);
use_scaling = 1;
}
kvm_x86_ops->set_tsc_khz(vcpu, this_tsc_khz, use_scaling);
}
static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
{
u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
vcpu->arch.virtual_tsc_mult,
vcpu->arch.virtual_tsc_shift);
tsc += vcpu->arch.this_tsc_write;
return tsc;
}
void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
{
#ifdef CONFIG_X86_64
bool vcpus_matched;
bool do_request = false;
struct kvm_arch *ka = &vcpu->kvm->arch;
struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
atomic_read(&vcpu->kvm->online_vcpus));
if (vcpus_matched && gtod->clock.vclock_mode == VCLOCK_TSC)
if (!ka->use_master_clock)
do_request = 1;
if (!vcpus_matched && ka->use_master_clock)
do_request = 1;
if (do_request)
kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
atomic_read(&vcpu->kvm->online_vcpus),
ka->use_master_clock, gtod->clock.vclock_mode);
#endif
}
static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
{
u64 curr_offset = kvm_x86_ops->read_tsc_offset(vcpu);
vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
}
void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
{
struct kvm *kvm = vcpu->kvm;
u64 offset, ns, elapsed;
unsigned long flags;
s64 usdiff;
bool matched;
u64 data = msr->data;
raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
ns = get_kernel_ns();
elapsed = ns - kvm->arch.last_tsc_nsec;
if (vcpu->arch.virtual_tsc_khz) {
int faulted = 0;
/* n.b - signed multiplication and division required */
usdiff = data - kvm->arch.last_tsc_write;
#ifdef CONFIG_X86_64
usdiff = (usdiff * 1000) / vcpu->arch.virtual_tsc_khz;
#else
/* do_div() only does unsigned */
asm("1: idivl %[divisor]\n"
"2: xor %%edx, %%edx\n"
" movl $0, %[faulted]\n"
"3:\n"
".section .fixup,\"ax\"\n"
"4: movl $1, %[faulted]\n"
" jmp 3b\n"
".previous\n"
_ASM_EXTABLE(1b, 4b)
: "=A"(usdiff), [faulted] "=r" (faulted)
: "A"(usdiff * 1000), [divisor] "rm"(vcpu->arch.virtual_tsc_khz));
#endif
do_div(elapsed, 1000);
usdiff -= elapsed;
if (usdiff < 0)
usdiff = -usdiff;
/* idivl overflow => difference is larger than USEC_PER_SEC */
if (faulted)
usdiff = USEC_PER_SEC;
} else
usdiff = USEC_PER_SEC; /* disable TSC match window below */
/*
* Special case: TSC write with a small delta (1 second) of virtual
* cycle time against real time is interpreted as an attempt to
* synchronize the CPU.
*
* For a reliable TSC, we can match TSC offsets, and for an unstable
* TSC, we add elapsed time in this computation. We could let the
* compensation code attempt to catch up if we fall behind, but
* it's better to try to match offsets from the beginning.
*/
if (usdiff < USEC_PER_SEC &&
vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
if (!check_tsc_unstable()) {
offset = kvm->arch.cur_tsc_offset;
pr_debug("kvm: matched tsc offset for %llu\n", data);
} else {
u64 delta = nsec_to_cycles(vcpu, elapsed);
data += delta;
offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
}
matched = true;
} else {
/*
* We split periods of matched TSC writes into generations.
* For each generation, we track the original measured
* nanosecond time, offset, and write, so if TSCs are in
* sync, we can match exact offset, and if not, we can match
* exact software computation in compute_guest_tsc()
*
* These values are tracked in kvm->arch.cur_xxx variables.
*/
kvm->arch.cur_tsc_generation++;
kvm->arch.cur_tsc_nsec = ns;
kvm->arch.cur_tsc_write = data;
kvm->arch.cur_tsc_offset = offset;
matched = false;
pr_debug("kvm: new tsc generation %u, clock %llu\n",
kvm->arch.cur_tsc_generation, data);
}
/*
* We also track th most recent recorded KHZ, write and time to
* allow the matching interval to be extended at each write.
*/
kvm->arch.last_tsc_nsec = ns;
kvm->arch.last_tsc_write = data;
kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
vcpu->arch.last_guest_tsc = data;
/* Keep track of which generation this VCPU has synchronized to */
vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
if (guest_cpuid_has_tsc_adjust(vcpu) && !msr->host_initiated)
update_ia32_tsc_adjust_msr(vcpu, offset);
kvm_x86_ops->write_tsc_offset(vcpu, offset);
raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
if (matched)
kvm->arch.nr_vcpus_matched_tsc++;
else
kvm->arch.nr_vcpus_matched_tsc = 0;
kvm_track_tsc_matching(vcpu);
spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
}
EXPORT_SYMBOL_GPL(kvm_write_tsc);
#ifdef CONFIG_X86_64
static cycle_t read_tsc(void)
{
cycle_t ret;
u64 last;
/*
* Empirically, a fence (of type that depends on the CPU)
* before rdtsc is enough to ensure that rdtsc is ordered
* with respect to loads. The various CPU manuals are unclear
* as to whether rdtsc can be reordered with later loads,
* but no one has ever seen it happen.
*/
rdtsc_barrier();
ret = (cycle_t)vget_cycles();
last = pvclock_gtod_data.clock.cycle_last;
if (likely(ret >= last))
return ret;
/*
* GCC likes to generate cmov here, but this branch is extremely
* predictable (it's just a funciton of time and the likely is
* very likely) and there's a data dependence, so force GCC
* to generate a branch instead. I don't barrier() because
* we don't actually need a barrier, and if this function
* ever gets inlined it will generate worse code.
*/
asm volatile ("");
return last;
}
static inline u64 vgettsc(cycle_t *cycle_now)
{
long v;
struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
*cycle_now = read_tsc();
v = (*cycle_now - gtod->clock.cycle_last) & gtod->clock.mask;
return v * gtod->clock.mult;
}
static int do_monotonic(struct timespec *ts, cycle_t *cycle_now)
{
unsigned long seq;
u64 ns;
int mode;
struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
ts->tv_nsec = 0;
do {
seq = read_seqcount_begin(>od->seq);
mode = gtod->clock.vclock_mode;
ts->tv_sec = gtod->monotonic_time_sec;
ns = gtod->monotonic_time_snsec;
ns += vgettsc(cycle_now);
ns >>= gtod->clock.shift;
} while (unlikely(read_seqcount_retry(>od->seq, seq)));
timespec_add_ns(ts, ns);
return mode;
}
/* returns true if host is using tsc clocksource */
static bool kvm_get_time_and_clockread(s64 *kernel_ns, cycle_t *cycle_now)
{
struct timespec ts;
/* checked again under seqlock below */
if (pvclock_gtod_data.clock.vclock_mode != VCLOCK_TSC)
return false;
if (do_monotonic(&ts, cycle_now) != VCLOCK_TSC)
return false;
monotonic_to_bootbased(&ts);
*kernel_ns = timespec_to_ns(&ts);
return true;
}
#endif
/*
*
* Assuming a stable TSC across physical CPUS, and a stable TSC
* across virtual CPUs, the following condition is possible.
* Each numbered line represents an event visible to both
* CPUs at the next numbered event.
*
* "timespecX" represents host monotonic time. "tscX" represents
* RDTSC value.
*
* VCPU0 on CPU0 | VCPU1 on CPU1
*
* 1. read timespec0,tsc0
* 2. | timespec1 = timespec0 + N
* | tsc1 = tsc0 + M
* 3. transition to guest | transition to guest
* 4. ret0 = timespec0 + (rdtsc - tsc0) |
* 5. | ret1 = timespec1 + (rdtsc - tsc1)
* | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
*
* Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
*
* - ret0 < ret1
* - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
* ...
* - 0 < N - M => M < N
*
* That is, when timespec0 != timespec1, M < N. Unfortunately that is not
* always the case (the difference between two distinct xtime instances
* might be smaller then the difference between corresponding TSC reads,
* when updating guest vcpus pvclock areas).
*
* To avoid that problem, do not allow visibility of distinct
* system_timestamp/tsc_timestamp values simultaneously: use a master
* copy of host monotonic time values. Update that master copy
* in lockstep.
*
* Rely on synchronization of host TSCs and guest TSCs for monotonicity.
*
*/
static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
{
#ifdef CONFIG_X86_64
struct kvm_arch *ka = &kvm->arch;
int vclock_mode;
bool host_tsc_clocksource, vcpus_matched;
vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
atomic_read(&kvm->online_vcpus));
/*
* If the host uses TSC clock, then passthrough TSC as stable
* to the guest.
*/
host_tsc_clocksource = kvm_get_time_and_clockread(
&ka->master_kernel_ns,
&ka->master_cycle_now);
ka->use_master_clock = host_tsc_clocksource & vcpus_matched;
if (ka->use_master_clock)
atomic_set(&kvm_guest_has_master_clock, 1);
vclock_mode = pvclock_gtod_data.clock.vclock_mode;
trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
vcpus_matched);
#endif
}
static void kvm_gen_update_masterclock(struct kvm *kvm)
{
#ifdef CONFIG_X86_64
int i;
struct kvm_vcpu *vcpu;
struct kvm_arch *ka = &kvm->arch;
spin_lock(&ka->pvclock_gtod_sync_lock);
kvm_make_mclock_inprogress_request(kvm);
/* no guest entries from this point */
pvclock_update_vm_gtod_copy(kvm);
kvm_for_each_vcpu(i, vcpu, kvm)
set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
/* guest entries allowed */
kvm_for_each_vcpu(i, vcpu, kvm)
clear_bit(KVM_REQ_MCLOCK_INPROGRESS, &vcpu->requests);
spin_unlock(&ka->pvclock_gtod_sync_lock);
#endif
}
static int kvm_guest_time_update(struct kvm_vcpu *v)
{
unsigned long flags, this_tsc_khz;
struct kvm_vcpu_arch *vcpu = &v->arch;
struct kvm_arch *ka = &v->kvm->arch;
s64 kernel_ns;
u64 tsc_timestamp, host_tsc;
struct pvclock_vcpu_time_info guest_hv_clock;
u8 pvclock_flags;
bool use_master_clock;
kernel_ns = 0;
host_tsc = 0;
/*
* If the host uses TSC clock, then passthrough TSC as stable
* to the guest.
*/
spin_lock(&ka->pvclock_gtod_sync_lock);
use_master_clock = ka->use_master_clock;
if (use_master_clock) {
host_tsc = ka->master_cycle_now;
kernel_ns = ka->master_kernel_ns;
}
spin_unlock(&ka->pvclock_gtod_sync_lock);
/* Keep irq disabled to prevent changes to the clock */
local_irq_save(flags);
this_tsc_khz = __get_cpu_var(cpu_tsc_khz);
if (unlikely(this_tsc_khz == 0)) {
local_irq_restore(flags);
kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
return 1;
}
if (!use_master_clock) {
host_tsc = native_read_tsc();
kernel_ns = get_kernel_ns();
}
tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, host_tsc);
/*
* We may have to catch up the TSC to match elapsed wall clock
* time for two reasons, even if kvmclock is used.
* 1) CPU could have been running below the maximum TSC rate
* 2) Broken TSC compensation resets the base at each VCPU
* entry to avoid unknown leaps of TSC even when running
* again on the same CPU. This may cause apparent elapsed
* time to disappear, and the guest to stand still or run
* very slowly.
*/
if (vcpu->tsc_catchup) {
u64 tsc = compute_guest_tsc(v, kernel_ns);
if (tsc > tsc_timestamp) {
adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
tsc_timestamp = tsc;
}
}
local_irq_restore(flags);
if (!vcpu->pv_time_enabled)
return 0;
if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz,
&vcpu->hv_clock.tsc_shift,
&vcpu->hv_clock.tsc_to_system_mul);
vcpu->hw_tsc_khz = this_tsc_khz;
}
/* With all the info we got, fill in the values */
vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
vcpu->last_kernel_ns = kernel_ns;
vcpu->last_guest_tsc = tsc_timestamp;
/*
* The interface expects us to write an even number signaling that the
* update is finished. Since the guest won't see the intermediate
* state, we just increase by 2 at the end.
*/
vcpu->hv_clock.version += 2;
if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
&guest_hv_clock, sizeof(guest_hv_clock))))
return 0;
/* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
pvclock_flags = (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
if (vcpu->pvclock_set_guest_stopped_request) {
pvclock_flags |= PVCLOCK_GUEST_STOPPED;
vcpu->pvclock_set_guest_stopped_request = false;
}
/* If the host uses TSC clocksource, then it is stable */
if (use_master_clock)
pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
vcpu->hv_clock.flags = pvclock_flags;
kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
&vcpu->hv_clock,
sizeof(vcpu->hv_clock));
return 0;
}
/*
* kvmclock updates which are isolated to a given vcpu, such as
* vcpu->cpu migration, should not allow system_timestamp from
* the rest of the vcpus to remain static. Otherwise ntp frequency
* correction applies to one vcpu's system_timestamp but not
* the others.
*
* So in those cases, request a kvmclock update for all vcpus.
* The worst case for a remote vcpu to update its kvmclock
* is then bounded by maximum nohz sleep latency.
*/
static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
{
int i;
struct kvm *kvm = v->kvm;
struct kvm_vcpu *vcpu;
kvm_for_each_vcpu(i, vcpu, kvm) {
set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
kvm_vcpu_kick(vcpu);
}
}
static bool msr_mtrr_valid(unsigned msr)
{
switch (msr) {
case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
case MSR_MTRRfix64K_00000:
case MSR_MTRRfix16K_80000:
case MSR_MTRRfix16K_A0000:
case MSR_MTRRfix4K_C0000:
case MSR_MTRRfix4K_C8000:
case MSR_MTRRfix4K_D0000:
case MSR_MTRRfix4K_D8000:
case MSR_MTRRfix4K_E0000:
case MSR_MTRRfix4K_E8000:
case MSR_MTRRfix4K_F0000:
case MSR_MTRRfix4K_F8000:
case MSR_MTRRdefType:
case MSR_IA32_CR_PAT:
return true;
case 0x2f8:
return true;
}
return false;
}
static bool valid_pat_type(unsigned t)
{
return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
}
static bool valid_mtrr_type(unsigned t)
{
return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
}
static bool mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
{
int i;
if (!msr_mtrr_valid(msr))
return false;
if (msr == MSR_IA32_CR_PAT) {
for (i = 0; i < 8; i++)
if (!valid_pat_type((data >> (i * 8)) & 0xff))
return false;
return true;
} else if (msr == MSR_MTRRdefType) {
if (data & ~0xcff)
return false;
return valid_mtrr_type(data & 0xff);
} else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
for (i = 0; i < 8 ; i++)
if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
return false;
return true;
}
/* variable MTRRs */
return valid_mtrr_type(data & 0xff);
}
static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
{
u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
if (!mtrr_valid(vcpu, msr, data))
return 1;
if (msr == MSR_MTRRdefType) {
vcpu->arch.mtrr_state.def_type = data;
vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
} else if (msr == MSR_MTRRfix64K_00000)
p[0] = data;
else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
p[1 + msr - MSR_MTRRfix16K_80000] = data;
else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
p[3 + msr - MSR_MTRRfix4K_C0000] = data;
else if (msr == MSR_IA32_CR_PAT)
vcpu->arch.pat = data;
else { /* Variable MTRRs */
int idx, is_mtrr_mask;
u64 *pt;
idx = (msr - 0x200) / 2;
is_mtrr_mask = msr - 0x200 - 2 * idx;
if (!is_mtrr_mask)
pt =
(u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
else
pt =
(u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
*pt = data;
}
kvm_mmu_reset_context(vcpu);
return 0;
}
static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
{
u64 mcg_cap = vcpu->arch.mcg_cap;
unsigned bank_num = mcg_cap & 0xff;
switch (msr) {
case MSR_IA32_MCG_STATUS:
vcpu->arch.mcg_status = data;
break;
case MSR_IA32_MCG_CTL:
if (!(mcg_cap & MCG_CTL_P))
return 1;
if (data != 0 && data != ~(u64)0)
return -1;
vcpu->arch.mcg_ctl = data;
break;
default:
if (msr >= MSR_IA32_MC0_CTL &&
msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
u32 offset = msr - MSR_IA32_MC0_CTL;
/* only 0 or all 1s can be written to IA32_MCi_CTL
* some Linux kernels though clear bit 10 in bank 4 to
* workaround a BIOS/GART TBL issue on AMD K8s, ignore
* this to avoid an uncatched #GP in the guest
*/
if ((offset & 0x3) == 0 &&
data != 0 && (data | (1 << 10)) != ~(u64)0)
return -1;
vcpu->arch.mce_banks[offset] = data;
break;
}
return 1;
}
return 0;
}
static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
{
struct kvm *kvm = vcpu->kvm;
int lm = is_long_mode(vcpu);
u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
: (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
: kvm->arch.xen_hvm_config.blob_size_32;
u32 page_num = data & ~PAGE_MASK;
u64 page_addr = data & PAGE_MASK;
u8 *page;
int r;
r = -E2BIG;
if (page_num >= blob_size)
goto out;
r = -ENOMEM;
page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
if (IS_ERR(page)) {
r = PTR_ERR(page);
goto out;
}
if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
goto out_free;
r = 0;
out_free:
kfree(page);
out:
return r;
}
static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
{
return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
}
static bool kvm_hv_msr_partition_wide(u32 msr)
{
bool r = false;
switch (msr) {
case HV_X64_MSR_GUEST_OS_ID:
case HV_X64_MSR_HYPERCALL:
case HV_X64_MSR_REFERENCE_TSC:
case HV_X64_MSR_TIME_REF_COUNT:
r = true;
break;
}
return r;
}
static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
{
struct kvm *kvm = vcpu->kvm;
switch (msr) {
case HV_X64_MSR_GUEST_OS_ID:
kvm->arch.hv_guest_os_id = data;
/* setting guest os id to zero disables hypercall page */
if (!kvm->arch.hv_guest_os_id)
kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
break;
case HV_X64_MSR_HYPERCALL: {
u64 gfn;
unsigned long addr;
u8 instructions[4];
/* if guest os id is not set hypercall should remain disabled */
if (!kvm->arch.hv_guest_os_id)
break;
if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
kvm->arch.hv_hypercall = data;
break;
}
gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return 1;
kvm_x86_ops->patch_hypercall(vcpu, instructions);
((unsigned char *)instructions)[3] = 0xc3; /* ret */
if (__copy_to_user((void __user *)addr, instructions, 4))
return 1;
kvm->arch.hv_hypercall = data;
mark_page_dirty(kvm, gfn);
break;
}
case HV_X64_MSR_REFERENCE_TSC: {
u64 gfn;
HV_REFERENCE_TSC_PAGE tsc_ref;
memset(&tsc_ref, 0, sizeof(tsc_ref));
kvm->arch.hv_tsc_page = data;
if (!(data & HV_X64_MSR_TSC_REFERENCE_ENABLE))
break;
gfn = data >> HV_X64_MSR_TSC_REFERENCE_ADDRESS_SHIFT;
if (kvm_write_guest(kvm, data,
&tsc_ref, sizeof(tsc_ref)))
return 1;
mark_page_dirty(kvm, gfn);
break;
}
default:
vcpu_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
"data 0x%llx\n", msr, data);
return 1;
}
return 0;
}
static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
{
switch (msr) {
case HV_X64_MSR_APIC_ASSIST_PAGE: {
u64 gfn;
unsigned long addr;
if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
vcpu->arch.hv_vapic = data;
break;
}
gfn = data >> HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT;
addr = gfn_to_hva(vcpu->kvm, gfn);
if (kvm_is_error_hva(addr))
return 1;
if (__clear_user((void __user *)addr, PAGE_SIZE))
return 1;
vcpu->arch.hv_vapic = data;
mark_page_dirty(vcpu->kvm, gfn);
break;
}
case HV_X64_MSR_EOI:
return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
case HV_X64_MSR_ICR:
return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
case HV_X64_MSR_TPR:
return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
default:
vcpu_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
"data 0x%llx\n", msr, data);
return 1;
}
return 0;
}
static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
{
gpa_t gpa = data & ~0x3f;
/* Bits 2:5 are reserved, Should be zero */
if (data & 0x3c)
return 1;
vcpu->arch.apf.msr_val = data;
if (!(data & KVM_ASYNC_PF_ENABLED)) {
kvm_clear_async_pf_completion_queue(vcpu);
kvm_async_pf_hash_reset(vcpu);
return 0;
}
if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
sizeof(u32)))
return 1;
vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
kvm_async_pf_wakeup_all(vcpu);
return 0;
}
static void kvmclock_reset(struct kvm_vcpu *vcpu)
{
vcpu->arch.pv_time_enabled = false;
}
static void accumulate_steal_time(struct kvm_vcpu *vcpu)
{
u64 delta;
if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
return;
delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
vcpu->arch.st.last_steal = current->sched_info.run_delay;
vcpu->arch.st.accum_steal = delta;
}
static void record_steal_time(struct kvm_vcpu *vcpu)
{
if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
return;
if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
&vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
return;
vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
vcpu->arch.st.steal.version += 2;
vcpu->arch.st.accum_steal = 0;
kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
&vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
}
int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
{
bool pr = false;
u32 msr = msr_info->index;
u64 data = msr_info->data;
switch (msr) {
case MSR_AMD64_NB_CFG:
case MSR_IA32_UCODE_REV:
case MSR_IA32_UCODE_WRITE:
case MSR_VM_HSAVE_PA:
case MSR_AMD64_PATCH_LOADER:
case MSR_AMD64_BU_CFG2:
break;
case MSR_EFER:
return set_efer(vcpu, data);
case MSR_K7_HWCR:
data &= ~(u64)0x40; /* ignore flush filter disable */
data &= ~(u64)0x100; /* ignore ignne emulation enable */
data &= ~(u64)0x8; /* ignore TLB cache disable */
if (data != 0) {
vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
data);
return 1;
}
break;
case MSR_FAM10H_MMIO_CONF_BASE:
if (data != 0) {
vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
"0x%llx\n", data);
return 1;
}
break;
case MSR_IA32_DEBUGCTLMSR:
if (!data) {
/* We support the non-activated case already */
break;
} else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
/* Values other than LBR and BTF are vendor-specific,
thus reserved and should throw a #GP */
return 1;
}
vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
__func__, data);
break;
case 0x200 ... 0x2ff:
return set_msr_mtrr(vcpu, msr, data);
case MSR_IA32_APICBASE:
return kvm_set_apic_base(vcpu, msr_info);
case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
return kvm_x2apic_msr_write(vcpu, msr, data);
case MSR_IA32_TSCDEADLINE:
kvm_set_lapic_tscdeadline_msr(vcpu, data);
break;
case MSR_IA32_TSC_ADJUST:
if (guest_cpuid_has_tsc_adjust(vcpu)) {
if (!msr_info->host_initiated) {
u64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
kvm_x86_ops->adjust_tsc_offset(vcpu, adj, true);
}
vcpu->arch.ia32_tsc_adjust_msr = data;
}
break;
case MSR_IA32_MISC_ENABLE:
vcpu->arch.ia32_misc_enable_msr = data;
break;
case MSR_KVM_WALL_CLOCK_NEW:
case MSR_KVM_WALL_CLOCK:
vcpu->kvm->arch.wall_clock = data;
kvm_write_wall_clock(vcpu->kvm, data);
break;
case MSR_KVM_SYSTEM_TIME_NEW:
case MSR_KVM_SYSTEM_TIME: {
u64 gpa_offset;
kvmclock_reset(vcpu);
vcpu->arch.time = data;
kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
/* we verify if the enable bit is set... */
if (!(data & 1))
break;
gpa_offset = data & ~(PAGE_MASK | 1);
if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
&vcpu->arch.pv_time, data & ~1ULL,
sizeof(struct pvclock_vcpu_time_info)))
vcpu->arch.pv_time_enabled = false;
else
vcpu->arch.pv_time_enabled = true;
break;
}
case MSR_KVM_ASYNC_PF_EN:
if (kvm_pv_enable_async_pf(vcpu, data))
return 1;
break;
case MSR_KVM_STEAL_TIME:
if (unlikely(!sched_info_on()))
return 1;
if (data & KVM_STEAL_RESERVED_MASK)
return 1;
if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
data & KVM_STEAL_VALID_BITS,
sizeof(struct kvm_steal_time)))
return 1;
vcpu->arch.st.msr_val = data;
if (!(data & KVM_MSR_ENABLED))
break;
vcpu->arch.st.last_steal = current->sched_info.run_delay;
preempt_disable();
accumulate_steal_time(vcpu);
preempt_enable();
kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
break;
case MSR_KVM_PV_EOI_EN:
if (kvm_lapic_enable_pv_eoi(vcpu, data))
return 1;
break;
case MSR_IA32_MCG_CTL:
case MSR_IA32_MCG_STATUS:
case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
return set_msr_mce(vcpu, msr, data);
/* Performance counters are not protected by a CPUID bit,
* so we should check all of them in the generic path for the sake of
* cross vendor migration.
* Writing a zero into the event select MSRs disables them,
* which we perfectly emulate ;-). Any other value should be at least
* reported, some guests depend on them.
*/
case MSR_K7_EVNTSEL0:
case MSR_K7_EVNTSEL1:
case MSR_K7_EVNTSEL2:
case MSR_K7_EVNTSEL3:
if (data != 0)
vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
/* at least RHEL 4 unconditionally writes to the perfctr registers,
* so we ignore writes to make it happy.
*/
case MSR_K7_PERFCTR0:
case MSR_K7_PERFCTR1:
case MSR_K7_PERFCTR2:
case MSR_K7_PERFCTR3:
vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
case MSR_P6_PERFCTR0:
case MSR_P6_PERFCTR1:
pr = true;
case MSR_P6_EVNTSEL0:
case MSR_P6_EVNTSEL1:
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_set_msr(vcpu, msr_info);
if (pr || data != 0)
vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
case MSR_K7_CLK_CTL:
/*
* Ignore all writes to this no longer documented MSR.
* Writes are only relevant for old K7 processors,
* all pre-dating SVM, but a recommended workaround from
* AMD for these chips. It is possible to specify the
* affected processor models on the command line, hence
* the need to ignore the workaround.
*/
break;
case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
if (kvm_hv_msr_partition_wide(msr)) {
int r;
mutex_lock(&vcpu->kvm->lock);
r = set_msr_hyperv_pw(vcpu, msr, data);
mutex_unlock(&vcpu->kvm->lock);
return r;
} else
return set_msr_hyperv(vcpu, msr, data);
break;
case MSR_IA32_BBL_CR_CTL3:
/* Drop writes to this legacy MSR -- see rdmsr
* counterpart for further detail.
*/
vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
break;
case MSR_AMD64_OSVW_ID_LENGTH:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
vcpu->arch.osvw.length = data;
break;
case MSR_AMD64_OSVW_STATUS:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
vcpu->arch.osvw.status = data;
break;
default:
if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
return xen_hvm_config(vcpu, data);
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_set_msr(vcpu, msr_info);
if (!ignore_msrs) {
vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
msr, data);
return 1;
} else {
vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
msr, data);
break;
}
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_set_msr_common);
/*
* Reads an msr value (of 'msr_index') into 'pdata'.
* Returns 0 on success, non-0 otherwise.
* Assumes vcpu_load() was already called.
*/
int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
{
return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
}
static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
{
u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
if (!msr_mtrr_valid(msr))
return 1;
if (msr == MSR_MTRRdefType)
*pdata = vcpu->arch.mtrr_state.def_type +
(vcpu->arch.mtrr_state.enabled << 10);
else if (msr == MSR_MTRRfix64K_00000)
*pdata = p[0];
else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
*pdata = p[1 + msr - MSR_MTRRfix16K_80000];
else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
*pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
else if (msr == MSR_IA32_CR_PAT)
*pdata = vcpu->arch.pat;
else { /* Variable MTRRs */
int idx, is_mtrr_mask;
u64 *pt;
idx = (msr - 0x200) / 2;
is_mtrr_mask = msr - 0x200 - 2 * idx;
if (!is_mtrr_mask)
pt =
(u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
else
pt =
(u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
*pdata = *pt;
}
return 0;
}
static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
{
u64 data;
u64 mcg_cap = vcpu->arch.mcg_cap;
unsigned bank_num = mcg_cap & 0xff;
switch (msr) {
case MSR_IA32_P5_MC_ADDR:
case MSR_IA32_P5_MC_TYPE:
data = 0;
break;
case MSR_IA32_MCG_CAP:
data = vcpu->arch.mcg_cap;
break;
case MSR_IA32_MCG_CTL:
if (!(mcg_cap & MCG_CTL_P))
return 1;
data = vcpu->arch.mcg_ctl;
break;
case MSR_IA32_MCG_STATUS:
data = vcpu->arch.mcg_status;
break;
default:
if (msr >= MSR_IA32_MC0_CTL &&
msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
u32 offset = msr - MSR_IA32_MC0_CTL;
data = vcpu->arch.mce_banks[offset];
break;
}
return 1;
}
*pdata = data;
return 0;
}
static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
{
u64 data = 0;
struct kvm *kvm = vcpu->kvm;
switch (msr) {
case HV_X64_MSR_GUEST_OS_ID:
data = kvm->arch.hv_guest_os_id;
break;
case HV_X64_MSR_HYPERCALL:
data = kvm->arch.hv_hypercall;
break;
case HV_X64_MSR_TIME_REF_COUNT: {
data =
div_u64(get_kernel_ns() + kvm->arch.kvmclock_offset, 100);
break;
}
case HV_X64_MSR_REFERENCE_TSC:
data = kvm->arch.hv_tsc_page;
break;
default:
vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
return 1;
}
*pdata = data;
return 0;
}
static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
{
u64 data = 0;
switch (msr) {
case HV_X64_MSR_VP_INDEX: {
int r;
struct kvm_vcpu *v;
kvm_for_each_vcpu(r, v, vcpu->kvm)
if (v == vcpu)
data = r;
break;
}
case HV_X64_MSR_EOI:
return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
case HV_X64_MSR_ICR:
return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
case HV_X64_MSR_TPR:
return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
case HV_X64_MSR_APIC_ASSIST_PAGE:
data = vcpu->arch.hv_vapic;
break;
default:
vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
return 1;
}
*pdata = data;
return 0;
}
int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
{
u64 data;
switch (msr) {
case MSR_IA32_PLATFORM_ID:
case MSR_IA32_EBL_CR_POWERON:
case MSR_IA32_DEBUGCTLMSR:
case MSR_IA32_LASTBRANCHFROMIP:
case MSR_IA32_LASTBRANCHTOIP:
case MSR_IA32_LASTINTFROMIP:
case MSR_IA32_LASTINTTOIP:
case MSR_K8_SYSCFG:
case MSR_K7_HWCR:
case MSR_VM_HSAVE_PA:
case MSR_K7_EVNTSEL0:
case MSR_K7_PERFCTR0:
case MSR_K8_INT_PENDING_MSG:
case MSR_AMD64_NB_CFG:
case MSR_FAM10H_MMIO_CONF_BASE:
case MSR_AMD64_BU_CFG2:
data = 0;
break;
case MSR_P6_PERFCTR0:
case MSR_P6_PERFCTR1:
case MSR_P6_EVNTSEL0:
case MSR_P6_EVNTSEL1:
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_get_msr(vcpu, msr, pdata);
data = 0;
break;
case MSR_IA32_UCODE_REV:
data = 0x100000000ULL;
break;
case MSR_MTRRcap:
data = 0x500 | KVM_NR_VAR_MTRR;
break;
case 0x200 ... 0x2ff:
return get_msr_mtrr(vcpu, msr, pdata);
case 0xcd: /* fsb frequency */
data = 3;
break;
/*
* MSR_EBC_FREQUENCY_ID
* Conservative value valid for even the basic CPU models.
* Models 0,1: 000 in bits 23:21 indicating a bus speed of
* 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
* and 266MHz for model 3, or 4. Set Core Clock
* Frequency to System Bus Frequency Ratio to 1 (bits
* 31:24) even though these are only valid for CPU
* models > 2, however guests may end up dividing or
* multiplying by zero otherwise.
*/
case MSR_EBC_FREQUENCY_ID:
data = 1 << 24;
break;
case MSR_IA32_APICBASE:
data = kvm_get_apic_base(vcpu);
break;
case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
return kvm_x2apic_msr_read(vcpu, msr, pdata);
break;
case MSR_IA32_TSCDEADLINE:
data = kvm_get_lapic_tscdeadline_msr(vcpu);
break;
case MSR_IA32_TSC_ADJUST:
data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
break;
case MSR_IA32_MISC_ENABLE:
data = vcpu->arch.ia32_misc_enable_msr;
break;
case MSR_IA32_PERF_STATUS:
/* TSC increment by tick */
data = 1000ULL;
/* CPU multiplier */
data |= (((uint64_t)4ULL) << 40);
break;
case MSR_EFER:
data = vcpu->arch.efer;
break;
case MSR_KVM_WALL_CLOCK:
case MSR_KVM_WALL_CLOCK_NEW:
data = vcpu->kvm->arch.wall_clock;
break;
case MSR_KVM_SYSTEM_TIME:
case MSR_KVM_SYSTEM_TIME_NEW:
data = vcpu->arch.time;
break;
case MSR_KVM_ASYNC_PF_EN:
data = vcpu->arch.apf.msr_val;
break;
case MSR_KVM_STEAL_TIME:
data = vcpu->arch.st.msr_val;
break;
case MSR_KVM_PV_EOI_EN:
data = vcpu->arch.pv_eoi.msr_val;
break;
case MSR_IA32_P5_MC_ADDR:
case MSR_IA32_P5_MC_TYPE:
case MSR_IA32_MCG_CAP:
case MSR_IA32_MCG_CTL:
case MSR_IA32_MCG_STATUS:
case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
return get_msr_mce(vcpu, msr, pdata);
case MSR_K7_CLK_CTL:
/*
* Provide expected ramp-up count for K7. All other
* are set to zero, indicating minimum divisors for
* every field.
*
* This prevents guest kernels on AMD host with CPU
* type 6, model 8 and higher from exploding due to
* the rdmsr failing.
*/
data = 0x20000000;
break;
case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
if (kvm_hv_msr_partition_wide(msr)) {
int r;
mutex_lock(&vcpu->kvm->lock);
r = get_msr_hyperv_pw(vcpu, msr, pdata);
mutex_unlock(&vcpu->kvm->lock);
return r;
} else
return get_msr_hyperv(vcpu, msr, pdata);
break;
case MSR_IA32_BBL_CR_CTL3:
/* This legacy MSR exists but isn't fully documented in current
* silicon. It is however accessed by winxp in very narrow
* scenarios where it sets bit #19, itself documented as
* a "reserved" bit. Best effort attempt to source coherent
* read data here should the balance of the register be
* interpreted by the guest:
*
* L2 cache control register 3: 64GB range, 256KB size,
* enabled, latency 0x1, configured
*/
data = 0xbe702111;
break;
case MSR_AMD64_OSVW_ID_LENGTH:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
data = vcpu->arch.osvw.length;
break;
case MSR_AMD64_OSVW_STATUS:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
data = vcpu->arch.osvw.status;
break;
default:
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_get_msr(vcpu, msr, pdata);
if (!ignore_msrs) {
vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
return 1;
} else {
vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
data = 0;
}
break;
}
*pdata = data;
return 0;
}
EXPORT_SYMBOL_GPL(kvm_get_msr_common);
/*
* Read or write a bunch of msrs. All parameters are kernel addresses.
*
* @return number of msrs set successfully.
*/
static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
struct kvm_msr_entry *entries,
int (*do_msr)(struct kvm_vcpu *vcpu,
unsigned index, u64 *data))
{
int i, idx;
idx = srcu_read_lock(&vcpu->kvm->srcu);
for (i = 0; i < msrs->nmsrs; ++i)
if (do_msr(vcpu, entries[i].index, &entries[i].data))
break;
srcu_read_unlock(&vcpu->kvm->srcu, idx);
return i;
}
/*
* Read or write a bunch of msrs. Parameters are user addresses.
*
* @return number of msrs set successfully.
*/
static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
int (*do_msr)(struct kvm_vcpu *vcpu,
unsigned index, u64 *data),
int writeback)
{
struct kvm_msrs msrs;
struct kvm_msr_entry *entries;
int r, n;
unsigned size;
r = -EFAULT;
if (copy_from_user(&msrs, user_msrs, sizeof msrs))
goto out;
r = -E2BIG;
if (msrs.nmsrs >= MAX_IO_MSRS)
goto out;
size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
entries = memdup_user(user_msrs->entries, size);
if (IS_ERR(entries)) {
r = PTR_ERR(entries);
goto out;
}
r = n = __msr_io(vcpu, &msrs, entries, do_msr);
if (r < 0)
goto out_free;
r = -EFAULT;
if (writeback && copy_to_user(user_msrs->entries, entries, size))
goto out_free;
r = n;
out_free:
kfree(entries);
out:
return r;
}
int kvm_dev_ioctl_check_extension(long ext)
{
int r;
switch (ext) {
case KVM_CAP_IRQCHIP:
case KVM_CAP_HLT:
case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
case KVM_CAP_SET_TSS_ADDR:
case KVM_CAP_EXT_CPUID:
case KVM_CAP_EXT_EMUL_CPUID:
case KVM_CAP_CLOCKSOURCE:
case KVM_CAP_PIT:
case KVM_CAP_NOP_IO_DELAY:
case KVM_CAP_MP_STATE:
case KVM_CAP_SYNC_MMU:
case KVM_CAP_USER_NMI:
case KVM_CAP_REINJECT_CONTROL:
case KVM_CAP_IRQ_INJECT_STATUS:
case KVM_CAP_IRQFD:
case KVM_CAP_IOEVENTFD:
case KVM_CAP_PIT2:
case KVM_CAP_PIT_STATE2:
case KVM_CAP_SET_IDENTITY_MAP_ADDR:
case KVM_CAP_XEN_HVM:
case KVM_CAP_ADJUST_CLOCK:
case KVM_CAP_VCPU_EVENTS:
case KVM_CAP_HYPERV:
case KVM_CAP_HYPERV_VAPIC:
case KVM_CAP_HYPERV_SPIN:
case KVM_CAP_PCI_SEGMENT:
case KVM_CAP_DEBUGREGS:
case KVM_CAP_X86_ROBUST_SINGLESTEP:
case KVM_CAP_XSAVE:
case KVM_CAP_ASYNC_PF:
case KVM_CAP_GET_TSC_KHZ:
case KVM_CAP_KVMCLOCK_CTRL:
case KVM_CAP_READONLY_MEM:
case KVM_CAP_HYPERV_TIME:
#ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
case KVM_CAP_ASSIGN_DEV_IRQ:
case KVM_CAP_PCI_2_3:
#endif
r = 1;
break;
case KVM_CAP_COALESCED_MMIO:
r = KVM_COALESCED_MMIO_PAGE_OFFSET;
break;
case KVM_CAP_VAPIC:
r = !kvm_x86_ops->cpu_has_accelerated_tpr();
break;
case KVM_CAP_NR_VCPUS:
r = KVM_SOFT_MAX_VCPUS;
break;
case KVM_CAP_MAX_VCPUS:
r = KVM_MAX_VCPUS;
break;
case KVM_CAP_NR_MEMSLOTS:
r = KVM_USER_MEM_SLOTS;
break;
case KVM_CAP_PV_MMU: /* obsolete */
r = 0;
break;
#ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
case KVM_CAP_IOMMU:
r = iommu_present(&pci_bus_type);
break;
#endif
case KVM_CAP_MCE:
r = KVM_MAX_MCE_BANKS;
break;
case KVM_CAP_XCRS:
r = cpu_has_xsave;
break;
case KVM_CAP_TSC_CONTROL:
r = kvm_has_tsc_control;
break;
case KVM_CAP_TSC_DEADLINE_TIMER:
r = boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER);
break;
default:
r = 0;
break;
}
return r;
}
long kvm_arch_dev_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
void __user *argp = (void __user *)arg;
long r;
switch (ioctl) {
case KVM_GET_MSR_INDEX_LIST: {
struct kvm_msr_list __user *user_msr_list = argp;
struct kvm_msr_list msr_list;
unsigned n;
r = -EFAULT;
if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
goto out;
n = msr_list.nmsrs;
msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
goto out;
r = -E2BIG;
if (n < msr_list.nmsrs)
goto out;
r = -EFAULT;
if (copy_to_user(user_msr_list->indices, &msrs_to_save,
num_msrs_to_save * sizeof(u32)))
goto out;
if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
&emulated_msrs,
ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
goto out;
r = 0;
break;
}
case KVM_GET_SUPPORTED_CPUID:
case KVM_GET_EMULATED_CPUID: {
struct kvm_cpuid2 __user *cpuid_arg = argp;
struct kvm_cpuid2 cpuid;
r = -EFAULT;
if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
goto out;
r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
ioctl);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
goto out;
r = 0;
break;
}
case KVM_X86_GET_MCE_CAP_SUPPORTED: {
u64 mce_cap;
mce_cap = KVM_MCE_CAP_SUPPORTED;
r = -EFAULT;
if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
goto out;
r = 0;
break;
}
default:
r = -EINVAL;
}
out:
return r;
}
static void wbinvd_ipi(void *garbage)
{
wbinvd();
}
static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
{
return kvm_arch_has_noncoherent_dma(vcpu->kvm);
}
void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
{
/* Address WBINVD may be executed by guest */
if (need_emulate_wbinvd(vcpu)) {
if (kvm_x86_ops->has_wbinvd_exit())
cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
smp_call_function_single(vcpu->cpu,
wbinvd_ipi, NULL, 1);
}
kvm_x86_ops->vcpu_load(vcpu, cpu);
/* Apply any externally detected TSC adjustments (due to suspend) */
if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
vcpu->arch.tsc_offset_adjustment = 0;
set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
}
if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
native_read_tsc() - vcpu->arch.last_host_tsc;
if (tsc_delta < 0)
mark_tsc_unstable("KVM discovered backwards TSC");
if (check_tsc_unstable()) {
u64 offset = kvm_x86_ops->compute_tsc_offset(vcpu,
vcpu->arch.last_guest_tsc);
kvm_x86_ops->write_tsc_offset(vcpu, offset);
vcpu->arch.tsc_catchup = 1;
}
/*
* On a host with synchronized TSC, there is no need to update
* kvmclock on vcpu->cpu migration
*/
if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
if (vcpu->cpu != cpu)
kvm_migrate_timers(vcpu);
vcpu->cpu = cpu;
}
accumulate_steal_time(vcpu);
kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
}
void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
{
kvm_x86_ops->vcpu_put(vcpu);
kvm_put_guest_fpu(vcpu);
vcpu->arch.last_host_tsc = native_read_tsc();
}
static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
struct kvm_lapic_state *s)
{
kvm_x86_ops->sync_pir_to_irr(vcpu);
memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
return 0;
}
static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
struct kvm_lapic_state *s)
{
kvm_apic_post_state_restore(vcpu, s);
update_cr8_intercept(vcpu);
return 0;
}
static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
struct kvm_interrupt *irq)
{
if (irq->irq >= KVM_NR_INTERRUPTS)
return -EINVAL;
if (irqchip_in_kernel(vcpu->kvm))
return -ENXIO;
kvm_queue_interrupt(vcpu, irq->irq, false);
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 0;
}
static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
{
kvm_inject_nmi(vcpu);
return 0;
}
static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
struct kvm_tpr_access_ctl *tac)
{
if (tac->flags)
return -EINVAL;
vcpu->arch.tpr_access_reporting = !!tac->enabled;
return 0;
}
static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
u64 mcg_cap)
{
int r;
unsigned bank_num = mcg_cap & 0xff, bank;
r = -EINVAL;
if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
goto out;
if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
goto out;
r = 0;
vcpu->arch.mcg_cap = mcg_cap;
/* Init IA32_MCG_CTL to all 1s */
if (mcg_cap & MCG_CTL_P)
vcpu->arch.mcg_ctl = ~(u64)0;
/* Init IA32_MCi_CTL to all 1s */
for (bank = 0; bank < bank_num; bank++)
vcpu->arch.mce_banks[bank*4] = ~(u64)0;
out:
return r;
}
static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
struct kvm_x86_mce *mce)
{
u64 mcg_cap = vcpu->arch.mcg_cap;
unsigned bank_num = mcg_cap & 0xff;
u64 *banks = vcpu->arch.mce_banks;
if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
return -EINVAL;
/*
* if IA32_MCG_CTL is not all 1s, the uncorrected error
* reporting is disabled
*/
if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
vcpu->arch.mcg_ctl != ~(u64)0)
return 0;
banks += 4 * mce->bank;
/*
* if IA32_MCi_CTL is not all 1s, the uncorrected error
* reporting is disabled for the bank
*/
if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
return 0;
if (mce->status & MCI_STATUS_UC) {
if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
!kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
return 0;
}
if (banks[1] & MCI_STATUS_VAL)
mce->status |= MCI_STATUS_OVER;
banks[2] = mce->addr;
banks[3] = mce->misc;
vcpu->arch.mcg_status = mce->mcg_status;
banks[1] = mce->status;
kvm_queue_exception(vcpu, MC_VECTOR);
} else if (!(banks[1] & MCI_STATUS_VAL)
|| !(banks[1] & MCI_STATUS_UC)) {
if (banks[1] & MCI_STATUS_VAL)
mce->status |= MCI_STATUS_OVER;
banks[2] = mce->addr;
banks[3] = mce->misc;
banks[1] = mce->status;
} else
banks[1] |= MCI_STATUS_OVER;
return 0;
}
static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
struct kvm_vcpu_events *events)
{
process_nmi(vcpu);
events->exception.injected =
vcpu->arch.exception.pending &&
!kvm_exception_is_soft(vcpu->arch.exception.nr);
events->exception.nr = vcpu->arch.exception.nr;
events->exception.has_error_code = vcpu->arch.exception.has_error_code;
events->exception.pad = 0;
events->exception.error_code = vcpu->arch.exception.error_code;
events->interrupt.injected =
vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
events->interrupt.nr = vcpu->arch.interrupt.nr;
events->interrupt.soft = 0;
events->interrupt.shadow =
kvm_x86_ops->get_interrupt_shadow(vcpu,
KVM_X86_SHADOW_INT_MOV_SS | KVM_X86_SHADOW_INT_STI);
events->nmi.injected = vcpu->arch.nmi_injected;
events->nmi.pending = vcpu->arch.nmi_pending != 0;
events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
events->nmi.pad = 0;
events->sipi_vector = 0; /* never valid when reporting to user space */
events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
| KVM_VCPUEVENT_VALID_SHADOW);
memset(&events->reserved, 0, sizeof(events->reserved));
}
static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
struct kvm_vcpu_events *events)
{
if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
| KVM_VCPUEVENT_VALID_SIPI_VECTOR
| KVM_VCPUEVENT_VALID_SHADOW))
return -EINVAL;
process_nmi(vcpu);
vcpu->arch.exception.pending = events->exception.injected;
vcpu->arch.exception.nr = events->exception.nr;
vcpu->arch.exception.has_error_code = events->exception.has_error_code;
vcpu->arch.exception.error_code = events->exception.error_code;
vcpu->arch.interrupt.pending = events->interrupt.injected;
vcpu->arch.interrupt.nr = events->interrupt.nr;
vcpu->arch.interrupt.soft = events->interrupt.soft;
if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
kvm_x86_ops->set_interrupt_shadow(vcpu,
events->interrupt.shadow);
vcpu->arch.nmi_injected = events->nmi.injected;
if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
vcpu->arch.nmi_pending = events->nmi.pending;
kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
kvm_vcpu_has_lapic(vcpu))
vcpu->arch.apic->sipi_vector = events->sipi_vector;
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 0;
}
static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
struct kvm_debugregs *dbgregs)
{
unsigned long val;
memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
_kvm_get_dr(vcpu, 6, &val);
dbgregs->dr6 = val;
dbgregs->dr7 = vcpu->arch.dr7;
dbgregs->flags = 0;
memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
}
static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
struct kvm_debugregs *dbgregs)
{
if (dbgregs->flags)
return -EINVAL;
memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
vcpu->arch.dr6 = dbgregs->dr6;
kvm_update_dr6(vcpu);
vcpu->arch.dr7 = dbgregs->dr7;
kvm_update_dr7(vcpu);
return 0;
}
static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
struct kvm_xsave *guest_xsave)
{
if (cpu_has_xsave) {
memcpy(guest_xsave->region,
&vcpu->arch.guest_fpu.state->xsave,
vcpu->arch.guest_xstate_size);
*(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] &=
vcpu->arch.guest_supported_xcr0 | XSTATE_FPSSE;
} else {
memcpy(guest_xsave->region,
&vcpu->arch.guest_fpu.state->fxsave,
sizeof(struct i387_fxsave_struct));
*(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
XSTATE_FPSSE;
}
}
static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
struct kvm_xsave *guest_xsave)
{
u64 xstate_bv =
*(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
if (cpu_has_xsave) {
/*
* Here we allow setting states that are not present in
* CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
* with old userspace.
*/
if (xstate_bv & ~KVM_SUPPORTED_XCR0)
return -EINVAL;
if (xstate_bv & ~host_xcr0)
return -EINVAL;
memcpy(&vcpu->arch.guest_fpu.state->xsave,
guest_xsave->region, vcpu->arch.guest_xstate_size);
} else {
if (xstate_bv & ~XSTATE_FPSSE)
return -EINVAL;
memcpy(&vcpu->arch.guest_fpu.state->fxsave,
guest_xsave->region, sizeof(struct i387_fxsave_struct));
}
return 0;
}
static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
struct kvm_xcrs *guest_xcrs)
{
if (!cpu_has_xsave) {
guest_xcrs->nr_xcrs = 0;
return;
}
guest_xcrs->nr_xcrs = 1;
guest_xcrs->flags = 0;
guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
}
static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
struct kvm_xcrs *guest_xcrs)
{
int i, r = 0;
if (!cpu_has_xsave)
return -EINVAL;
if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
return -EINVAL;
for (i = 0; i < guest_xcrs->nr_xcrs; i++)
/* Only support XCR0 currently */
if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
guest_xcrs->xcrs[i].value);
break;
}
if (r)
r = -EINVAL;
return r;
}
/*
* kvm_set_guest_paused() indicates to the guest kernel that it has been
* stopped by the hypervisor. This function will be called from the host only.
* EINVAL is returned when the host attempts to set the flag for a guest that
* does not support pv clocks.
*/
static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
{
if (!vcpu->arch.pv_time_enabled)
return -EINVAL;
vcpu->arch.pvclock_set_guest_stopped_request = true;
kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
return 0;
}
long kvm_arch_vcpu_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm_vcpu *vcpu = filp->private_data;
void __user *argp = (void __user *)arg;
int r;
union {
struct kvm_lapic_state *lapic;
struct kvm_xsave *xsave;
struct kvm_xcrs *xcrs;
void *buffer;
} u;
u.buffer = NULL;
switch (ioctl) {
case KVM_GET_LAPIC: {
r = -EINVAL;
if (!vcpu->arch.apic)
goto out;
u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
r = -ENOMEM;
if (!u.lapic)
goto out;
r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
goto out;
r = 0;
break;
}
case KVM_SET_LAPIC: {
r = -EINVAL;
if (!vcpu->arch.apic)
goto out;
u.lapic = memdup_user(argp, sizeof(*u.lapic));
if (IS_ERR(u.lapic))
return PTR_ERR(u.lapic);
r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
break;
}
case KVM_INTERRUPT: {
struct kvm_interrupt irq;
r = -EFAULT;
if (copy_from_user(&irq, argp, sizeof irq))
goto out;
r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
break;
}
case KVM_NMI: {
r = kvm_vcpu_ioctl_nmi(vcpu);
break;
}
case KVM_SET_CPUID: {
struct kvm_cpuid __user *cpuid_arg = argp;
struct kvm_cpuid cpuid;
r = -EFAULT;
if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
goto out;
r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
break;
}
case KVM_SET_CPUID2: {
struct kvm_cpuid2 __user *cpuid_arg = argp;
struct kvm_cpuid2 cpuid;
r = -EFAULT;
if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
goto out;
r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
cpuid_arg->entries);
break;
}
case KVM_GET_CPUID2: {
struct kvm_cpuid2 __user *cpuid_arg = argp;
struct kvm_cpuid2 cpuid;
r = -EFAULT;
if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
goto out;
r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
cpuid_arg->entries);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
goto out;
r = 0;
break;
}
case KVM_GET_MSRS:
r = msr_io(vcpu, argp, kvm_get_msr, 1);
break;
case KVM_SET_MSRS:
r = msr_io(vcpu, argp, do_set_msr, 0);
break;
case KVM_TPR_ACCESS_REPORTING: {
struct kvm_tpr_access_ctl tac;
r = -EFAULT;
if (copy_from_user(&tac, argp, sizeof tac))
goto out;
r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &tac, sizeof tac))
goto out;
r = 0;
break;
};
case KVM_SET_VAPIC_ADDR: {
struct kvm_vapic_addr va;
r = -EINVAL;
if (!irqchip_in_kernel(vcpu->kvm))
goto out;
r = -EFAULT;
if (copy_from_user(&va, argp, sizeof va))
goto out;
r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
break;
}
case KVM_X86_SETUP_MCE: {
u64 mcg_cap;
r = -EFAULT;
if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
goto out;
r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
break;
}
case KVM_X86_SET_MCE: {
struct kvm_x86_mce mce;
r = -EFAULT;
if (copy_from_user(&mce, argp, sizeof mce))
goto out;
r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
break;
}
case KVM_GET_VCPU_EVENTS: {
struct kvm_vcpu_events events;
kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
r = -EFAULT;
if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
break;
r = 0;
break;
}
case KVM_SET_VCPU_EVENTS: {
struct kvm_vcpu_events events;
r = -EFAULT;
if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
break;
r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
break;
}
case KVM_GET_DEBUGREGS: {
struct kvm_debugregs dbgregs;
kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
r = -EFAULT;
if (copy_to_user(argp, &dbgregs,
sizeof(struct kvm_debugregs)))
break;
r = 0;
break;
}
case KVM_SET_DEBUGREGS: {
struct kvm_debugregs dbgregs;
r = -EFAULT;
if (copy_from_user(&dbgregs, argp,
sizeof(struct kvm_debugregs)))
break;
r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
break;
}
case KVM_GET_XSAVE: {
u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
r = -ENOMEM;
if (!u.xsave)
break;
kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
r = -EFAULT;
if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
break;
r = 0;
break;
}
case KVM_SET_XSAVE: {
u.xsave = memdup_user(argp, sizeof(*u.xsave));
if (IS_ERR(u.xsave))
return PTR_ERR(u.xsave);
r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
break;
}
case KVM_GET_XCRS: {
u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
r = -ENOMEM;
if (!u.xcrs)
break;
kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
r = -EFAULT;
if (copy_to_user(argp, u.xcrs,
sizeof(struct kvm_xcrs)))
break;
r = 0;
break;
}
case KVM_SET_XCRS: {
u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
if (IS_ERR(u.xcrs))
return PTR_ERR(u.xcrs);
r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
break;
}
case KVM_SET_TSC_KHZ: {
u32 user_tsc_khz;
r = -EINVAL;
user_tsc_khz = (u32)arg;
if (user_tsc_khz >= kvm_max_guest_tsc_khz)
goto out;
if (user_tsc_khz == 0)
user_tsc_khz = tsc_khz;
kvm_set_tsc_khz(vcpu, user_tsc_khz);
r = 0;
goto out;
}
case KVM_GET_TSC_KHZ: {
r = vcpu->arch.virtual_tsc_khz;
goto out;
}
case KVM_KVMCLOCK_CTRL: {
r = kvm_set_guest_paused(vcpu);
goto out;
}
default:
r = -EINVAL;
}
out:
kfree(u.buffer);
return r;
}
int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
{
return VM_FAULT_SIGBUS;
}
static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
{
int ret;
if (addr > (unsigned int)(-3 * PAGE_SIZE))
return -EINVAL;
ret = kvm_x86_ops->set_tss_addr(kvm, addr);
return ret;
}
static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
u64 ident_addr)
{
kvm->arch.ept_identity_map_addr = ident_addr;
return 0;
}
static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
u32 kvm_nr_mmu_pages)
{
if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
return -EINVAL;
mutex_lock(&kvm->slots_lock);
kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
mutex_unlock(&kvm->slots_lock);
return 0;
}
static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
{
return kvm->arch.n_max_mmu_pages;
}
static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
{
int r;
r = 0;
switch (chip->chip_id) {
case KVM_IRQCHIP_PIC_MASTER:
memcpy(&chip->chip.pic,
&pic_irqchip(kvm)->pics[0],
sizeof(struct kvm_pic_state));
break;
case KVM_IRQCHIP_PIC_SLAVE:
memcpy(&chip->chip.pic,
&pic_irqchip(kvm)->pics[1],
sizeof(struct kvm_pic_state));
break;
case KVM_IRQCHIP_IOAPIC:
r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
break;
default:
r = -EINVAL;
break;
}
return r;
}
static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
{
int r;
r = 0;
switch (chip->chip_id) {
case KVM_IRQCHIP_PIC_MASTER:
spin_lock(&pic_irqchip(kvm)->lock);
memcpy(&pic_irqchip(kvm)->pics[0],
&chip->chip.pic,
sizeof(struct kvm_pic_state));
spin_unlock(&pic_irqchip(kvm)->lock);
break;
case KVM_IRQCHIP_PIC_SLAVE:
spin_lock(&pic_irqchip(kvm)->lock);
memcpy(&pic_irqchip(kvm)->pics[1],
&chip->chip.pic,
sizeof(struct kvm_pic_state));
spin_unlock(&pic_irqchip(kvm)->lock);
break;
case KVM_IRQCHIP_IOAPIC:
r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
break;
default:
r = -EINVAL;
break;
}
kvm_pic_update_irq(pic_irqchip(kvm));
return r;
}
static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
{
int r = 0;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
return r;
}
static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
{
int r = 0;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
return r;
}
static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
{
int r = 0;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
sizeof(ps->channels));
ps->flags = kvm->arch.vpit->pit_state.flags;
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
memset(&ps->reserved, 0, sizeof(ps->reserved));
return r;
}
static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
{
int r = 0, start = 0;
u32 prev_legacy, cur_legacy;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
if (!prev_legacy && cur_legacy)
start = 1;
memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
sizeof(kvm->arch.vpit->pit_state.channels));
kvm->arch.vpit->pit_state.flags = ps->flags;
kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
return r;
}
static int kvm_vm_ioctl_reinject(struct kvm *kvm,
struct kvm_reinject_control *control)
{
if (!kvm->arch.vpit)
return -ENXIO;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
kvm->arch.vpit->pit_state.reinject = control->pit_reinject;
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
return 0;
}
/**
* kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
* @kvm: kvm instance
* @log: slot id and address to which we copy the log
*
* We need to keep it in mind that VCPU threads can write to the bitmap
* concurrently. So, to avoid losing data, we keep the following order for
* each bit:
*
* 1. Take a snapshot of the bit and clear it if needed.
* 2. Write protect the corresponding page.
* 3. Flush TLB's if needed.
* 4. Copy the snapshot to the userspace.
*
* Between 2 and 3, the guest may write to the page using the remaining TLB
* entry. This is not a problem because the page will be reported dirty at
* step 4 using the snapshot taken before and step 3 ensures that successive
* writes will be logged for the next call.
*/
int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
{
int r;
struct kvm_memory_slot *memslot;
unsigned long n, i;
unsigned long *dirty_bitmap;
unsigned long *dirty_bitmap_buffer;
bool is_dirty = false;
mutex_lock(&kvm->slots_lock);
r = -EINVAL;
if (log->slot >= KVM_USER_MEM_SLOTS)
goto out;
memslot = id_to_memslot(kvm->memslots, log->slot);
dirty_bitmap = memslot->dirty_bitmap;
r = -ENOENT;
if (!dirty_bitmap)
goto out;
n = kvm_dirty_bitmap_bytes(memslot);
dirty_bitmap_buffer = dirty_bitmap + n / sizeof(long);
memset(dirty_bitmap_buffer, 0, n);
spin_lock(&kvm->mmu_lock);
for (i = 0; i < n / sizeof(long); i++) {
unsigned long mask;
gfn_t offset;
if (!dirty_bitmap[i])
continue;
is_dirty = true;
mask = xchg(&dirty_bitmap[i], 0);
dirty_bitmap_buffer[i] = mask;
offset = i * BITS_PER_LONG;
kvm_mmu_write_protect_pt_masked(kvm, memslot, offset, mask);
}
if (is_dirty)
kvm_flush_remote_tlbs(kvm);
spin_unlock(&kvm->mmu_lock);
r = -EFAULT;
if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
goto out;
r = 0;
out:
mutex_unlock(&kvm->slots_lock);
return r;
}
int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
bool line_status)
{
if (!irqchip_in_kernel(kvm))
return -ENXIO;
irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
irq_event->irq, irq_event->level,
line_status);
return 0;
}
long kvm_arch_vm_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm *kvm = filp->private_data;
void __user *argp = (void __user *)arg;
int r = -ENOTTY;
/*
* This union makes it completely explicit to gcc-3.x
* that these two variables' stack usage should be
* combined, not added together.
*/
union {
struct kvm_pit_state ps;
struct kvm_pit_state2 ps2;
struct kvm_pit_config pit_config;
} u;
switch (ioctl) {
case KVM_SET_TSS_ADDR:
r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
break;
case KVM_SET_IDENTITY_MAP_ADDR: {
u64 ident_addr;
r = -EFAULT;
if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
goto out;
r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
break;
}
case KVM_SET_NR_MMU_PAGES:
r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
break;
case KVM_GET_NR_MMU_PAGES:
r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
break;
case KVM_CREATE_IRQCHIP: {
struct kvm_pic *vpic;
mutex_lock(&kvm->lock);
r = -EEXIST;
if (kvm->arch.vpic)
goto create_irqchip_unlock;
r = -EINVAL;
if (atomic_read(&kvm->online_vcpus))
goto create_irqchip_unlock;
r = -ENOMEM;
vpic = kvm_create_pic(kvm);
if (vpic) {
r = kvm_ioapic_init(kvm);
if (r) {
mutex_lock(&kvm->slots_lock);
kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
&vpic->dev_master);
kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
&vpic->dev_slave);
kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
&vpic->dev_eclr);
mutex_unlock(&kvm->slots_lock);
kfree(vpic);
goto create_irqchip_unlock;
}
} else
goto create_irqchip_unlock;
smp_wmb();
kvm->arch.vpic = vpic;
smp_wmb();
r = kvm_setup_default_irq_routing(kvm);
if (r) {
mutex_lock(&kvm->slots_lock);
mutex_lock(&kvm->irq_lock);
kvm_ioapic_destroy(kvm);
kvm_destroy_pic(kvm);
mutex_unlock(&kvm->irq_lock);
mutex_unlock(&kvm->slots_lock);
}
create_irqchip_unlock:
mutex_unlock(&kvm->lock);
break;
}
case KVM_CREATE_PIT:
u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
goto create_pit;
case KVM_CREATE_PIT2:
r = -EFAULT;
if (copy_from_user(&u.pit_config, argp,
sizeof(struct kvm_pit_config)))
goto out;
create_pit:
mutex_lock(&kvm->slots_lock);
r = -EEXIST;
if (kvm->arch.vpit)
goto create_pit_unlock;
r = -ENOMEM;
kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
if (kvm->arch.vpit)
r = 0;
create_pit_unlock:
mutex_unlock(&kvm->slots_lock);
break;
case KVM_GET_IRQCHIP: {
/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
struct kvm_irqchip *chip;
chip = memdup_user(argp, sizeof(*chip));
if (IS_ERR(chip)) {
r = PTR_ERR(chip);
goto out;
}
r = -ENXIO;
if (!irqchip_in_kernel(kvm))
goto get_irqchip_out;
r = kvm_vm_ioctl_get_irqchip(kvm, chip);
if (r)
goto get_irqchip_out;
r = -EFAULT;
if (copy_to_user(argp, chip, sizeof *chip))
goto get_irqchip_out;
r = 0;
get_irqchip_out:
kfree(chip);
break;
}
case KVM_SET_IRQCHIP: {
/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
struct kvm_irqchip *chip;
chip = memdup_user(argp, sizeof(*chip));
if (IS_ERR(chip)) {
r = PTR_ERR(chip);
goto out;
}
r = -ENXIO;
if (!irqchip_in_kernel(kvm))
goto set_irqchip_out;
r = kvm_vm_ioctl_set_irqchip(kvm, chip);
if (r)
goto set_irqchip_out;
r = 0;
set_irqchip_out:
kfree(chip);
break;
}
case KVM_GET_PIT: {
r = -EFAULT;
if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
goto out;
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
goto out;
r = 0;
break;
}
case KVM_SET_PIT: {
r = -EFAULT;
if (copy_from_user(&u.ps, argp, sizeof u.ps))
goto out;
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
break;
}
case KVM_GET_PIT2: {
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
goto out;
r = 0;
break;
}
case KVM_SET_PIT2: {
r = -EFAULT;
if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
goto out;
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
break;
}
case KVM_REINJECT_CONTROL: {
struct kvm_reinject_control control;
r = -EFAULT;
if (copy_from_user(&control, argp, sizeof(control)))
goto out;
r = kvm_vm_ioctl_reinject(kvm, &control);
break;
}
case KVM_XEN_HVM_CONFIG: {
r = -EFAULT;
if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
sizeof(struct kvm_xen_hvm_config)))
goto out;
r = -EINVAL;
if (kvm->arch.xen_hvm_config.flags)
goto out;
r = 0;
break;
}
case KVM_SET_CLOCK: {
struct kvm_clock_data user_ns;
u64 now_ns;
s64 delta;
r = -EFAULT;
if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
goto out;
r = -EINVAL;
if (user_ns.flags)
goto out;
r = 0;
local_irq_disable();
now_ns = get_kernel_ns();
delta = user_ns.clock - now_ns;
local_irq_enable();
kvm->arch.kvmclock_offset = delta;
kvm_gen_update_masterclock(kvm);
break;
}
case KVM_GET_CLOCK: {
struct kvm_clock_data user_ns;
u64 now_ns;
local_irq_disable();
now_ns = get_kernel_ns();
user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
local_irq_enable();
user_ns.flags = 0;
memset(&user_ns.pad, 0, sizeof(user_ns.pad));
r = -EFAULT;
if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
goto out;
r = 0;
break;
}
default:
;
}
out:
return r;
}
static void kvm_init_msr_list(void)
{
u32 dummy[2];
unsigned i, j;
/* skip the first msrs in the list. KVM-specific */
for (i = j = KVM_SAVE_MSRS_BEGIN; i < ARRAY_SIZE(msrs_to_save); i++) {
if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
continue;
if (j < i)
msrs_to_save[j] = msrs_to_save[i];
j++;
}
num_msrs_to_save = j;
}
static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
const void *v)
{
int handled = 0;
int n;
do {
n = min(len, 8);
if (!(vcpu->arch.apic &&
!kvm_iodevice_write(&vcpu->arch.apic->dev, addr, n, v))
&& kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
break;
handled += n;
addr += n;
len -= n;
v += n;
} while (len);
return handled;
}
static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
{
int handled = 0;
int n;
do {
n = min(len, 8);
if (!(vcpu->arch.apic &&
!kvm_iodevice_read(&vcpu->arch.apic->dev, addr, n, v))
&& kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
break;
trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
handled += n;
addr += n;
len -= n;
v += n;
} while (len);
return handled;
}
static void kvm_set_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg)
{
kvm_x86_ops->set_segment(vcpu, var, seg);
}
void kvm_get_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg)
{
kvm_x86_ops->get_segment(vcpu, var, seg);
}
gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access)
{
gpa_t t_gpa;
struct x86_exception exception;
BUG_ON(!mmu_is_nested(vcpu));
/* NPT walks are always user-walks */
access |= PFERR_USER_MASK;
t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, &exception);
return t_gpa;
}
gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
struct x86_exception *exception)
{
u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
}
gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
struct x86_exception *exception)
{
u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
access |= PFERR_FETCH_MASK;
return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
}
gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
struct x86_exception *exception)
{
u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
access |= PFERR_WRITE_MASK;
return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
}
/* uses this to access any guest's mapped memory without checking CPL */
gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
struct x86_exception *exception)
{
return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
}
static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
struct kvm_vcpu *vcpu, u32 access,
struct x86_exception *exception)
{
void *data = val;
int r = X86EMUL_CONTINUE;
while (bytes) {
gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
exception);
unsigned offset = addr & (PAGE_SIZE-1);
unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
int ret;
if (gpa == UNMAPPED_GVA)
return X86EMUL_PROPAGATE_FAULT;
ret = kvm_read_guest(vcpu->kvm, gpa, data, toread);
if (ret < 0) {
r = X86EMUL_IO_NEEDED;
goto out;
}
bytes -= toread;
data += toread;
addr += toread;
}
out:
return r;
}
/* used for instruction fetching */
static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
gva_t addr, void *val, unsigned int bytes,
struct x86_exception *exception)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
return kvm_read_guest_virt_helper(addr, val, bytes, vcpu,
access | PFERR_FETCH_MASK,
exception);
}
int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
gva_t addr, void *val, unsigned int bytes,
struct x86_exception *exception)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
exception);
}
EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
gva_t addr, void *val, unsigned int bytes,
struct x86_exception *exception)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
}
int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
gva_t addr, void *val,
unsigned int bytes,
struct x86_exception *exception)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
void *data = val;
int r = X86EMUL_CONTINUE;
while (bytes) {
gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
PFERR_WRITE_MASK,
exception);
unsigned offset = addr & (PAGE_SIZE-1);
unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
int ret;
if (gpa == UNMAPPED_GVA)
return X86EMUL_PROPAGATE_FAULT;
ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
if (ret < 0) {
r = X86EMUL_IO_NEEDED;
goto out;
}
bytes -= towrite;
data += towrite;
addr += towrite;
}
out:
return r;
}
EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
gpa_t *gpa, struct x86_exception *exception,
bool write)
{
u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
| (write ? PFERR_WRITE_MASK : 0);
if (vcpu_match_mmio_gva(vcpu, gva)
&& !permission_fault(vcpu->arch.walk_mmu, vcpu->arch.access, access)) {
*gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
(gva & (PAGE_SIZE - 1));
trace_vcpu_match_mmio(gva, *gpa, write, false);
return 1;
}
*gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
if (*gpa == UNMAPPED_GVA)
return -1;
/* For APIC access vmexit */
if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
return 1;
if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
trace_vcpu_match_mmio(gva, *gpa, write, true);
return 1;
}
return 0;
}
int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
const void *val, int bytes)
{
int ret;
ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
if (ret < 0)
return 0;
kvm_mmu_pte_write(vcpu, gpa, val, bytes);
return 1;
}
struct read_write_emulator_ops {
int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
int bytes);
int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
void *val, int bytes);
int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
int bytes, void *val);
int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
void *val, int bytes);
bool write;
};
static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
{
if (vcpu->mmio_read_completed) {
trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
vcpu->mmio_fragments[0].gpa, *(u64 *)val);
vcpu->mmio_read_completed = 0;
return 1;
}
return 0;
}
static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
void *val, int bytes)
{
return !kvm_read_guest(vcpu->kvm, gpa, val, bytes);
}
static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
void *val, int bytes)
{
return emulator_write_phys(vcpu, gpa, val, bytes);
}
static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
{
trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
return vcpu_mmio_write(vcpu, gpa, bytes, val);
}
static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
void *val, int bytes)
{
trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
return X86EMUL_IO_NEEDED;
}
static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
void *val, int bytes)
{
struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
return X86EMUL_CONTINUE;
}
static const struct read_write_emulator_ops read_emultor = {
.read_write_prepare = read_prepare,
.read_write_emulate = read_emulate,
.read_write_mmio = vcpu_mmio_read,
.read_write_exit_mmio = read_exit_mmio,
};
static const struct read_write_emulator_ops write_emultor = {
.read_write_emulate = write_emulate,
.read_write_mmio = write_mmio,
.read_write_exit_mmio = write_exit_mmio,
.write = true,
};
static int emulator_read_write_onepage(unsigned long addr, void *val,
unsigned int bytes,
struct x86_exception *exception,
struct kvm_vcpu *vcpu,
const struct read_write_emulator_ops *ops)
{
gpa_t gpa;
int handled, ret;
bool write = ops->write;
struct kvm_mmio_fragment *frag;
ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
if (ret < 0)
return X86EMUL_PROPAGATE_FAULT;
/* For APIC access vmexit */
if (ret)
goto mmio;
if (ops->read_write_emulate(vcpu, gpa, val, bytes))
return X86EMUL_CONTINUE;
mmio:
/*
* Is this MMIO handled locally?
*/
handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
if (handled == bytes)
return X86EMUL_CONTINUE;
gpa += handled;
bytes -= handled;
val += handled;
WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
frag->gpa = gpa;
frag->data = val;
frag->len = bytes;
return X86EMUL_CONTINUE;
}
int emulator_read_write(struct x86_emulate_ctxt *ctxt, unsigned long addr,
void *val, unsigned int bytes,
struct x86_exception *exception,
const struct read_write_emulator_ops *ops)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
gpa_t gpa;
int rc;
if (ops->read_write_prepare &&
ops->read_write_prepare(vcpu, val, bytes))
return X86EMUL_CONTINUE;
vcpu->mmio_nr_fragments = 0;
/* Crossing a page boundary? */
if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
int now;
now = -addr & ~PAGE_MASK;
rc = emulator_read_write_onepage(addr, val, now, exception,
vcpu, ops);
if (rc != X86EMUL_CONTINUE)
return rc;
addr += now;
val += now;
bytes -= now;
}
rc = emulator_read_write_onepage(addr, val, bytes, exception,
vcpu, ops);
if (rc != X86EMUL_CONTINUE)
return rc;
if (!vcpu->mmio_nr_fragments)
return rc;
gpa = vcpu->mmio_fragments[0].gpa;
vcpu->mmio_needed = 1;
vcpu->mmio_cur_fragment = 0;
vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
vcpu->run->exit_reason = KVM_EXIT_MMIO;
vcpu->run->mmio.phys_addr = gpa;
return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
}
static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
unsigned long addr,
void *val,
unsigned int bytes,
struct x86_exception *exception)
{
return emulator_read_write(ctxt, addr, val, bytes,
exception, &read_emultor);
}
int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
unsigned long addr,
const void *val,
unsigned int bytes,
struct x86_exception *exception)
{
return emulator_read_write(ctxt, addr, (void *)val, bytes,
exception, &write_emultor);
}
#define CMPXCHG_TYPE(t, ptr, old, new) \
(cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
#ifdef CONFIG_X86_64
# define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
#else
# define CMPXCHG64(ptr, old, new) \
(cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
#endif
static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
unsigned long addr,
const void *old,
const void *new,
unsigned int bytes,
struct x86_exception *exception)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
gpa_t gpa;
struct page *page;
char *kaddr;
bool exchanged;
/* guests cmpxchg8b have to be emulated atomically */
if (bytes > 8 || (bytes & (bytes - 1)))
goto emul_write;
gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
if (gpa == UNMAPPED_GVA ||
(gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
goto emul_write;
if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
goto emul_write;
page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
if (is_error_page(page))
goto emul_write;
kaddr = kmap_atomic(page);
kaddr += offset_in_page(gpa);
switch (bytes) {
case 1:
exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
break;
case 2:
exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
break;
case 4:
exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
break;
case 8:
exchanged = CMPXCHG64(kaddr, old, new);
break;
default:
BUG();
}
kunmap_atomic(kaddr);
kvm_release_page_dirty(page);
if (!exchanged)
return X86EMUL_CMPXCHG_FAILED;
kvm_mmu_pte_write(vcpu, gpa, new, bytes);
return X86EMUL_CONTINUE;
emul_write:
printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
return emulator_write_emulated(ctxt, addr, new, bytes, exception);
}
static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
{
/* TODO: String I/O for in kernel device */
int r;
if (vcpu->arch.pio.in)
r = kvm_io_bus_read(vcpu->kvm, KVM_PIO_BUS, vcpu->arch.pio.port,
vcpu->arch.pio.size, pd);
else
r = kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
vcpu->arch.pio.port, vcpu->arch.pio.size,
pd);
return r;
}
static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
unsigned short port, void *val,
unsigned int count, bool in)
{
trace_kvm_pio(!in, port, size, count);
vcpu->arch.pio.port = port;
vcpu->arch.pio.in = in;
vcpu->arch.pio.count = count;
vcpu->arch.pio.size = size;
if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
vcpu->arch.pio.count = 0;
return 1;
}
vcpu->run->exit_reason = KVM_EXIT_IO;
vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
vcpu->run->io.size = size;
vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
vcpu->run->io.count = count;
vcpu->run->io.port = port;
return 0;
}
static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
int size, unsigned short port, void *val,
unsigned int count)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
int ret;
if (vcpu->arch.pio.count)
goto data_avail;
ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
if (ret) {
data_avail:
memcpy(val, vcpu->arch.pio_data, size * count);
vcpu->arch.pio.count = 0;
return 1;
}
return 0;
}
static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
int size, unsigned short port,
const void *val, unsigned int count)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
memcpy(vcpu->arch.pio_data, val, size * count);
return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
}
static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
{
return kvm_x86_ops->get_segment_base(vcpu, seg);
}
static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
{
kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
}
int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
{
if (!need_emulate_wbinvd(vcpu))
return X86EMUL_CONTINUE;
if (kvm_x86_ops->has_wbinvd_exit()) {
int cpu = get_cpu();
cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
wbinvd_ipi, NULL, 1);
put_cpu();
cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
} else
wbinvd();
return X86EMUL_CONTINUE;
}
EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
{
kvm_emulate_wbinvd(emul_to_vcpu(ctxt));
}
int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
{
return _kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
}
int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
{
return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
}
static u64 mk_cr_64(u64 curr_cr, u32 new_val)
{
return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
}
static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
unsigned long value;
switch (cr) {
case 0:
value = kvm_read_cr0(vcpu);
break;
case 2:
value = vcpu->arch.cr2;
break;
case 3:
value = kvm_read_cr3(vcpu);
break;
case 4:
value = kvm_read_cr4(vcpu);
break;
case 8:
value = kvm_get_cr8(vcpu);
break;
default:
kvm_err("%s: unexpected cr %u\n", __func__, cr);
return 0;
}
return value;
}
static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
int res = 0;
switch (cr) {
case 0:
res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
break;
case 2:
vcpu->arch.cr2 = val;
break;
case 3:
res = kvm_set_cr3(vcpu, val);
break;
case 4:
res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
break;
case 8:
res = kvm_set_cr8(vcpu, val);
break;
default:
kvm_err("%s: unexpected cr %u\n", __func__, cr);
res = -1;
}
return res;
}
static void emulator_set_rflags(struct x86_emulate_ctxt *ctxt, ulong val)
{
kvm_set_rflags(emul_to_vcpu(ctxt), val);
}
static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
{
return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
}
static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
{
kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
}
static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
{
kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
}
static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
{
kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
}
static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
{
kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
}
static unsigned long emulator_get_cached_segment_base(
struct x86_emulate_ctxt *ctxt, int seg)
{
return get_segment_base(emul_to_vcpu(ctxt), seg);
}
static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
struct desc_struct *desc, u32 *base3,
int seg)
{
struct kvm_segment var;
kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
*selector = var.selector;
if (var.unusable) {
memset(desc, 0, sizeof(*desc));
return false;
}
if (var.g)
var.limit >>= 12;
set_desc_limit(desc, var.limit);
set_desc_base(desc, (unsigned long)var.base);
#ifdef CONFIG_X86_64
if (base3)
*base3 = var.base >> 32;
#endif
desc->type = var.type;
desc->s = var.s;
desc->dpl = var.dpl;
desc->p = var.present;
desc->avl = var.avl;
desc->l = var.l;
desc->d = var.db;
desc->g = var.g;
return true;
}
static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
struct desc_struct *desc, u32 base3,
int seg)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
struct kvm_segment var;
var.selector = selector;
var.base = get_desc_base(desc);
#ifdef CONFIG_X86_64
var.base |= ((u64)base3) << 32;
#endif
var.limit = get_desc_limit(desc);
if (desc->g)
var.limit = (var.limit << 12) | 0xfff;
var.type = desc->type;
var.present = desc->p;
var.dpl = desc->dpl;
var.db = desc->d;
var.s = desc->s;
var.l = desc->l;
var.g = desc->g;
var.avl = desc->avl;
var.present = desc->p;
var.unusable = !var.present;
var.padding = 0;
kvm_set_segment(vcpu, &var, seg);
return;
}
static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
u32 msr_index, u64 *pdata)
{
return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
}
static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
u32 msr_index, u64 data)
{
struct msr_data msr;
msr.data = data;
msr.index = msr_index;
msr.host_initiated = false;
return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
}
static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
u32 pmc, u64 *pdata)
{
return kvm_pmu_read_pmc(emul_to_vcpu(ctxt), pmc, pdata);
}
static void emulator_halt(struct x86_emulate_ctxt *ctxt)
{
emul_to_vcpu(ctxt)->arch.halt_request = 1;
}
static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
{
preempt_disable();
kvm_load_guest_fpu(emul_to_vcpu(ctxt));
/*
* CR0.TS may reference the host fpu state, not the guest fpu state,
* so it may be clear at this point.
*/
clts();
}
static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
{
preempt_enable();
}
static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
struct x86_instruction_info *info,
enum x86_intercept_stage stage)
{
return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
}
static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
{
kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
}
static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
{
return kvm_register_read(emul_to_vcpu(ctxt), reg);
}
static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
{
kvm_register_write(emul_to_vcpu(ctxt), reg, val);
}
static const struct x86_emulate_ops emulate_ops = {
.read_gpr = emulator_read_gpr,
.write_gpr = emulator_write_gpr,
.read_std = kvm_read_guest_virt_system,
.write_std = kvm_write_guest_virt_system,
.fetch = kvm_fetch_guest_virt,
.read_emulated = emulator_read_emulated,
.write_emulated = emulator_write_emulated,
.cmpxchg_emulated = emulator_cmpxchg_emulated,
.invlpg = emulator_invlpg,
.pio_in_emulated = emulator_pio_in_emulated,
.pio_out_emulated = emulator_pio_out_emulated,
.get_segment = emulator_get_segment,
.set_segment = emulator_set_segment,
.get_cached_segment_base = emulator_get_cached_segment_base,
.get_gdt = emulator_get_gdt,
.get_idt = emulator_get_idt,
.set_gdt = emulator_set_gdt,
.set_idt = emulator_set_idt,
.get_cr = emulator_get_cr,
.set_cr = emulator_set_cr,
.set_rflags = emulator_set_rflags,
.cpl = emulator_get_cpl,
.get_dr = emulator_get_dr,
.set_dr = emulator_set_dr,
.set_msr = emulator_set_msr,
.get_msr = emulator_get_msr,
.read_pmc = emulator_read_pmc,
.halt = emulator_halt,
.wbinvd = emulator_wbinvd,
.fix_hypercall = emulator_fix_hypercall,
.get_fpu = emulator_get_fpu,
.put_fpu = emulator_put_fpu,
.intercept = emulator_intercept,
.get_cpuid = emulator_get_cpuid,
};
static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
{
u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu, mask);
/*
* an sti; sti; sequence only disable interrupts for the first
* instruction. So, if the last instruction, be it emulated or
* not, left the system with the INT_STI flag enabled, it
* means that the last instruction is an sti. We should not
* leave the flag on in this case. The same goes for mov ss
*/
if (!(int_shadow & mask))
kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
}
static void inject_emulated_exception(struct kvm_vcpu *vcpu)
{
struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
if (ctxt->exception.vector == PF_VECTOR)
kvm_propagate_fault(vcpu, &ctxt->exception);
else if (ctxt->exception.error_code_valid)
kvm_queue_exception_e(vcpu, ctxt->exception.vector,
ctxt->exception.error_code);
else
kvm_queue_exception(vcpu, ctxt->exception.vector);
}
static void init_decode_cache(struct x86_emulate_ctxt *ctxt)
{
memset(&ctxt->opcode_len, 0,
(void *)&ctxt->_regs - (void *)&ctxt->opcode_len);
ctxt->fetch.start = 0;
ctxt->fetch.end = 0;
ctxt->io_read.pos = 0;
ctxt->io_read.end = 0;
ctxt->mem_read.pos = 0;
ctxt->mem_read.end = 0;
}
static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
{
struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
int cs_db, cs_l;
kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
ctxt->eflags = kvm_get_rflags(vcpu);
ctxt->eip = kvm_rip_read(vcpu);
ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
(ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
cs_l ? X86EMUL_MODE_PROT64 :
cs_db ? X86EMUL_MODE_PROT32 :
X86EMUL_MODE_PROT16;
ctxt->guest_mode = is_guest_mode(vcpu);
init_decode_cache(ctxt);
vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
}
int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
{
struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
int ret;
init_emulate_ctxt(vcpu);
ctxt->op_bytes = 2;
ctxt->ad_bytes = 2;
ctxt->_eip = ctxt->eip + inc_eip;
ret = emulate_int_real(ctxt, irq);
if (ret != X86EMUL_CONTINUE)
return EMULATE_FAIL;
ctxt->eip = ctxt->_eip;
kvm_rip_write(vcpu, ctxt->eip);
kvm_set_rflags(vcpu, ctxt->eflags);
if (irq == NMI_VECTOR)
vcpu->arch.nmi_pending = 0;
else
vcpu->arch.interrupt.pending = false;
return EMULATE_DONE;
}
EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
static int handle_emulation_failure(struct kvm_vcpu *vcpu)
{
int r = EMULATE_DONE;
++vcpu->stat.insn_emulation_fail;
trace_kvm_emulate_insn_failed(vcpu);
if (!is_guest_mode(vcpu)) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
vcpu->run->internal.ndata = 0;
r = EMULATE_FAIL;
}
kvm_queue_exception(vcpu, UD_VECTOR);
return r;
}
static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
bool write_fault_to_shadow_pgtable,
int emulation_type)
{
gpa_t gpa = cr2;
pfn_t pfn;
if (emulation_type & EMULTYPE_NO_REEXECUTE)
return false;
if (!vcpu->arch.mmu.direct_map) {
/*
* Write permission should be allowed since only
* write access need to be emulated.
*/
gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
/*
* If the mapping is invalid in guest, let cpu retry
* it to generate fault.
*/
if (gpa == UNMAPPED_GVA)
return true;
}
/*
* Do not retry the unhandleable instruction if it faults on the
* readonly host memory, otherwise it will goto a infinite loop:
* retry instruction -> write #PF -> emulation fail -> retry
* instruction -> ...
*/
pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
/*
* If the instruction failed on the error pfn, it can not be fixed,
* report the error to userspace.
*/
if (is_error_noslot_pfn(pfn))
return false;
kvm_release_pfn_clean(pfn);
/* The instructions are well-emulated on direct mmu. */
if (vcpu->arch.mmu.direct_map) {
unsigned int indirect_shadow_pages;
spin_lock(&vcpu->kvm->mmu_lock);
indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
spin_unlock(&vcpu->kvm->mmu_lock);
if (indirect_shadow_pages)
kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
return true;
}
/*
* if emulation was due to access to shadowed page table
* and it failed try to unshadow page and re-enter the
* guest to let CPU execute the instruction.
*/
kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
/*
* If the access faults on its page table, it can not
* be fixed by unprotecting shadow page and it should
* be reported to userspace.
*/
return !write_fault_to_shadow_pgtable;
}
static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
unsigned long cr2, int emulation_type)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
last_retry_eip = vcpu->arch.last_retry_eip;
last_retry_addr = vcpu->arch.last_retry_addr;
/*
* If the emulation is caused by #PF and it is non-page_table
* writing instruction, it means the VM-EXIT is caused by shadow
* page protected, we can zap the shadow page and retry this
* instruction directly.
*
* Note: if the guest uses a non-page-table modifying instruction
* on the PDE that points to the instruction, then we will unmap
* the instruction and go to an infinite loop. So, we cache the
* last retried eip and the last fault address, if we meet the eip
* and the address again, we can break out of the potential infinite
* loop.
*/
vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
if (!(emulation_type & EMULTYPE_RETRY))
return false;
if (x86_page_table_writing_insn(ctxt))
return false;
if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
return false;
vcpu->arch.last_retry_eip = ctxt->eip;
vcpu->arch.last_retry_addr = cr2;
if (!vcpu->arch.mmu.direct_map)
gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
return true;
}
static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
static int complete_emulated_pio(struct kvm_vcpu *vcpu);
static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
unsigned long *db)
{
u32 dr6 = 0;
int i;
u32 enable, rwlen;
enable = dr7;
rwlen = dr7 >> 16;
for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
dr6 |= (1 << i);
return dr6;
}
static void kvm_vcpu_check_singlestep(struct kvm_vcpu *vcpu, int *r)
{
struct kvm_run *kvm_run = vcpu->run;
/*
* Use the "raw" value to see if TF was passed to the processor.
* Note that the new value of the flags has not been saved yet.
*
* This is correct even for TF set by the guest, because "the
* processor will not generate this exception after the instruction
* that sets the TF flag".
*/
unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
if (unlikely(rflags & X86_EFLAGS_TF)) {
if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1;
kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
kvm_run->debug.arch.exception = DB_VECTOR;
kvm_run->exit_reason = KVM_EXIT_DEBUG;
*r = EMULATE_USER_EXIT;
} else {
vcpu->arch.emulate_ctxt.eflags &= ~X86_EFLAGS_TF;
/*
* "Certain debug exceptions may clear bit 0-3. The
* remaining contents of the DR6 register are never
* cleared by the processor".
*/
vcpu->arch.dr6 &= ~15;
vcpu->arch.dr6 |= DR6_BS;
kvm_queue_exception(vcpu, DB_VECTOR);
}
}
}
static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
{
struct kvm_run *kvm_run = vcpu->run;
unsigned long eip = vcpu->arch.emulate_ctxt.eip;
u32 dr6 = 0;
if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
(vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
dr6 = kvm_vcpu_check_hw_bp(eip, 0,
vcpu->arch.guest_debug_dr7,
vcpu->arch.eff_db);
if (dr6 != 0) {
kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
kvm_run->debug.arch.pc = kvm_rip_read(vcpu) +
get_segment_base(vcpu, VCPU_SREG_CS);
kvm_run->debug.arch.exception = DB_VECTOR;
kvm_run->exit_reason = KVM_EXIT_DEBUG;
*r = EMULATE_USER_EXIT;
return true;
}
}
if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK)) {
dr6 = kvm_vcpu_check_hw_bp(eip, 0,
vcpu->arch.dr7,
vcpu->arch.db);
if (dr6 != 0) {
vcpu->arch.dr6 &= ~15;
vcpu->arch.dr6 |= dr6;
kvm_queue_exception(vcpu, DB_VECTOR);
*r = EMULATE_DONE;
return true;
}
}
return false;
}
int x86_emulate_instruction(struct kvm_vcpu *vcpu,
unsigned long cr2,
int emulation_type,
void *insn,
int insn_len)
{
int r;
struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
bool writeback = true;
bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
/*
* Clear write_fault_to_shadow_pgtable here to ensure it is
* never reused.
*/
vcpu->arch.write_fault_to_shadow_pgtable = false;
kvm_clear_exception_queue(vcpu);
if (!(emulation_type & EMULTYPE_NO_DECODE)) {
init_emulate_ctxt(vcpu);
/*
* We will reenter on the same instruction since
* we do not set complete_userspace_io. This does not
* handle watchpoints yet, those would be handled in
* the emulate_ops.
*/
if (kvm_vcpu_check_breakpoint(vcpu, &r))
return r;
ctxt->interruptibility = 0;
ctxt->have_exception = false;
ctxt->perm_ok = false;
ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
r = x86_decode_insn(ctxt, insn, insn_len);
trace_kvm_emulate_insn_start(vcpu);
++vcpu->stat.insn_emulation;
if (r != EMULATION_OK) {
if (emulation_type & EMULTYPE_TRAP_UD)
return EMULATE_FAIL;
if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
emulation_type))
return EMULATE_DONE;
if (emulation_type & EMULTYPE_SKIP)
return EMULATE_FAIL;
return handle_emulation_failure(vcpu);
}
}
if (emulation_type & EMULTYPE_SKIP) {
kvm_rip_write(vcpu, ctxt->_eip);
return EMULATE_DONE;
}
if (retry_instruction(ctxt, cr2, emulation_type))
return EMULATE_DONE;
/* this is needed for vmware backdoor interface to work since it
changes registers values during IO operation */
if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
emulator_invalidate_register_cache(ctxt);
}
restart:
r = x86_emulate_insn(ctxt);
if (r == EMULATION_INTERCEPTED)
return EMULATE_DONE;
if (r == EMULATION_FAILED) {
if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
emulation_type))
return EMULATE_DONE;
return handle_emulation_failure(vcpu);
}
if (ctxt->have_exception) {
inject_emulated_exception(vcpu);
r = EMULATE_DONE;
} else if (vcpu->arch.pio.count) {
if (!vcpu->arch.pio.in) {
/* FIXME: return into emulator if single-stepping. */
vcpu->arch.pio.count = 0;
} else {
writeback = false;
vcpu->arch.complete_userspace_io = complete_emulated_pio;
}
r = EMULATE_USER_EXIT;
} else if (vcpu->mmio_needed) {
if (!vcpu->mmio_is_write)
writeback = false;
r = EMULATE_USER_EXIT;
vcpu->arch.complete_userspace_io = complete_emulated_mmio;
} else if (r == EMULATION_RESTART)
goto restart;
else
r = EMULATE_DONE;
if (writeback) {
toggle_interruptibility(vcpu, ctxt->interruptibility);
kvm_make_request(KVM_REQ_EVENT, vcpu);
vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
kvm_rip_write(vcpu, ctxt->eip);
if (r == EMULATE_DONE)
kvm_vcpu_check_singlestep(vcpu, &r);
kvm_set_rflags(vcpu, ctxt->eflags);
} else
vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
return r;
}
EXPORT_SYMBOL_GPL(x86_emulate_instruction);
int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
{
unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
size, port, &val, 1);
/* do not return to emulator after return from userspace */
vcpu->arch.pio.count = 0;
return ret;
}
EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
static void tsc_bad(void *info)
{
__this_cpu_write(cpu_tsc_khz, 0);
}
static void tsc_khz_changed(void *data)
{
struct cpufreq_freqs *freq = data;
unsigned long khz = 0;
if (data)
khz = freq->new;
else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
khz = cpufreq_quick_get(raw_smp_processor_id());
if (!khz)
khz = tsc_khz;
__this_cpu_write(cpu_tsc_khz, khz);
}
static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
void *data)
{
struct cpufreq_freqs *freq = data;
struct kvm *kvm;
struct kvm_vcpu *vcpu;
int i, send_ipi = 0;
/*
* We allow guests to temporarily run on slowing clocks,
* provided we notify them after, or to run on accelerating
* clocks, provided we notify them before. Thus time never
* goes backwards.
*
* However, we have a problem. We can't atomically update
* the frequency of a given CPU from this function; it is
* merely a notifier, which can be called from any CPU.
* Changing the TSC frequency at arbitrary points in time
* requires a recomputation of local variables related to
* the TSC for each VCPU. We must flag these local variables
* to be updated and be sure the update takes place with the
* new frequency before any guests proceed.
*
* Unfortunately, the combination of hotplug CPU and frequency
* change creates an intractable locking scenario; the order
* of when these callouts happen is undefined with respect to
* CPU hotplug, and they can race with each other. As such,
* merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
* undefined; you can actually have a CPU frequency change take
* place in between the computation of X and the setting of the
* variable. To protect against this problem, all updates of
* the per_cpu tsc_khz variable are done in an interrupt
* protected IPI, and all callers wishing to update the value
* must wait for a synchronous IPI to complete (which is trivial
* if the caller is on the CPU already). This establishes the
* necessary total order on variable updates.
*
* Note that because a guest time update may take place
* anytime after the setting of the VCPU's request bit, the
* correct TSC value must be set before the request. However,
* to ensure the update actually makes it to any guest which
* starts running in hardware virtualization between the set
* and the acquisition of the spinlock, we must also ping the
* CPU after setting the request bit.
*
*/
if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
return 0;
if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
return 0;
smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
spin_lock(&kvm_lock);
list_for_each_entry(kvm, &vm_list, vm_list) {
kvm_for_each_vcpu(i, vcpu, kvm) {
if (vcpu->cpu != freq->cpu)
continue;
kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
if (vcpu->cpu != smp_processor_id())
send_ipi = 1;
}
}
spin_unlock(&kvm_lock);
if (freq->old < freq->new && send_ipi) {
/*
* We upscale the frequency. Must make the guest
* doesn't see old kvmclock values while running with
* the new frequency, otherwise we risk the guest sees
* time go backwards.
*
* In case we update the frequency for another cpu
* (which might be in guest context) send an interrupt
* to kick the cpu out of guest context. Next time
* guest context is entered kvmclock will be updated,
* so the guest will not see stale values.
*/
smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
}
return 0;
}
static struct notifier_block kvmclock_cpufreq_notifier_block = {
.notifier_call = kvmclock_cpufreq_notifier
};
static int kvmclock_cpu_notifier(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
unsigned int cpu = (unsigned long)hcpu;
switch (action) {
case CPU_ONLINE:
case CPU_DOWN_FAILED:
smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
break;
case CPU_DOWN_PREPARE:
smp_call_function_single(cpu, tsc_bad, NULL, 1);
break;
}
return NOTIFY_OK;
}
static struct notifier_block kvmclock_cpu_notifier_block = {
.notifier_call = kvmclock_cpu_notifier,
.priority = -INT_MAX
};
static void kvm_timer_init(void)
{
int cpu;
max_tsc_khz = tsc_khz;
register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
#ifdef CONFIG_CPU_FREQ
struct cpufreq_policy policy;
memset(&policy, 0, sizeof(policy));
cpu = get_cpu();
cpufreq_get_policy(&policy, cpu);
if (policy.cpuinfo.max_freq)
max_tsc_khz = policy.cpuinfo.max_freq;
put_cpu();
#endif
cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
CPUFREQ_TRANSITION_NOTIFIER);
}
pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
for_each_online_cpu(cpu)
smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
}
static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
int kvm_is_in_guest(void)
{
return __this_cpu_read(current_vcpu) != NULL;
}
static int kvm_is_user_mode(void)
{
int user_mode = 3;
if (__this_cpu_read(current_vcpu))
user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
return user_mode != 0;
}
static unsigned long kvm_get_guest_ip(void)
{
unsigned long ip = 0;
if (__this_cpu_read(current_vcpu))
ip = kvm_rip_read(__this_cpu_read(current_vcpu));
return ip;
}
static struct perf_guest_info_callbacks kvm_guest_cbs = {
.is_in_guest = kvm_is_in_guest,
.is_user_mode = kvm_is_user_mode,
.get_guest_ip = kvm_get_guest_ip,
};
void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
{
__this_cpu_write(current_vcpu, vcpu);
}
EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
{
__this_cpu_write(current_vcpu, NULL);
}
EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
static void kvm_set_mmio_spte_mask(void)
{
u64 mask;
int maxphyaddr = boot_cpu_data.x86_phys_bits;
/*
* Set the reserved bits and the present bit of an paging-structure
* entry to generate page fault with PFER.RSV = 1.
*/
/* Mask the reserved physical address bits. */
mask = ((1ull << (51 - maxphyaddr + 1)) - 1) << maxphyaddr;
/* Bit 62 is always reserved for 32bit host. */
mask |= 0x3ull << 62;
/* Set the present bit. */
mask |= 1ull;
#ifdef CONFIG_X86_64
/*
* If reserved bit is not supported, clear the present bit to disable
* mmio page fault.
*/
if (maxphyaddr == 52)
mask &= ~1ull;
#endif
kvm_mmu_set_mmio_spte_mask(mask);
}
#ifdef CONFIG_X86_64
static void pvclock_gtod_update_fn(struct work_struct *work)
{
struct kvm *kvm;
struct kvm_vcpu *vcpu;
int i;
spin_lock(&kvm_lock);
list_for_each_entry(kvm, &vm_list, vm_list)
kvm_for_each_vcpu(i, vcpu, kvm)
set_bit(KVM_REQ_MASTERCLOCK_UPDATE, &vcpu->requests);
atomic_set(&kvm_guest_has_master_clock, 0);
spin_unlock(&kvm_lock);
}
static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
/*
* Notification about pvclock gtod data update.
*/
static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
void *priv)
{
struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
struct timekeeper *tk = priv;
update_pvclock_gtod(tk);
/* disable master clock if host does not trust, or does not
* use, TSC clocksource
*/
if (gtod->clock.vclock_mode != VCLOCK_TSC &&
atomic_read(&kvm_guest_has_master_clock) != 0)
queue_work(system_long_wq, &pvclock_gtod_work);
return 0;
}
static struct notifier_block pvclock_gtod_notifier = {
.notifier_call = pvclock_gtod_notify,
};
#endif
int kvm_arch_init(void *opaque)
{
int r;
struct kvm_x86_ops *ops = opaque;
if (kvm_x86_ops) {
printk(KERN_ERR "kvm: already loaded the other module\n");
r = -EEXIST;
goto out;
}
if (!ops->cpu_has_kvm_support()) {
printk(KERN_ERR "kvm: no hardware support\n");
r = -EOPNOTSUPP;
goto out;
}
if (ops->disabled_by_bios()) {
printk(KERN_ERR "kvm: disabled by bios\n");
r = -EOPNOTSUPP;
goto out;
}
r = -ENOMEM;
shared_msrs = alloc_percpu(struct kvm_shared_msrs);
if (!shared_msrs) {
printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
goto out;
}
r = kvm_mmu_module_init();
if (r)
goto out_free_percpu;
kvm_set_mmio_spte_mask();
kvm_init_msr_list();
kvm_x86_ops = ops;
kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
PT_DIRTY_MASK, PT64_NX_MASK, 0);
kvm_timer_init();
perf_register_guest_info_callbacks(&kvm_guest_cbs);
if (cpu_has_xsave)
host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
kvm_lapic_init();
#ifdef CONFIG_X86_64
pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
#endif
return 0;
out_free_percpu:
free_percpu(shared_msrs);
out:
return r;
}
void kvm_arch_exit(void)
{
perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
CPUFREQ_TRANSITION_NOTIFIER);
unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
#ifdef CONFIG_X86_64
pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
#endif
kvm_x86_ops = NULL;
kvm_mmu_module_exit();
free_percpu(shared_msrs);
}
int kvm_emulate_halt(struct kvm_vcpu *vcpu)
{
++vcpu->stat.halt_exits;
if (irqchip_in_kernel(vcpu->kvm)) {
vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
return 1;
} else {
vcpu->run->exit_reason = KVM_EXIT_HLT;
return 0;
}
}
EXPORT_SYMBOL_GPL(kvm_emulate_halt);
int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
{
u64 param, ingpa, outgpa, ret;
uint16_t code, rep_idx, rep_cnt, res = HV_STATUS_SUCCESS, rep_done = 0;
bool fast, longmode;
int cs_db, cs_l;
/*
* hypercall generates UD from non zero cpl and real mode
* per HYPER-V spec
*/
if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 0;
}
kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
longmode = is_long_mode(vcpu) && cs_l == 1;
if (!longmode) {
param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
(kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
(kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
(kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
}
#ifdef CONFIG_X86_64
else {
param = kvm_register_read(vcpu, VCPU_REGS_RCX);
ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
}
#endif
code = param & 0xffff;
fast = (param >> 16) & 0x1;
rep_cnt = (param >> 32) & 0xfff;
rep_idx = (param >> 48) & 0xfff;
trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
switch (code) {
case HV_X64_HV_NOTIFY_LONG_SPIN_WAIT:
kvm_vcpu_on_spin(vcpu);
break;
default:
res = HV_STATUS_INVALID_HYPERCALL_CODE;
break;
}
ret = res | (((u64)rep_done & 0xfff) << 32);
if (longmode) {
kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
} else {
kvm_register_write(vcpu, VCPU_REGS_RDX, ret >> 32);
kvm_register_write(vcpu, VCPU_REGS_RAX, ret & 0xffffffff);
}
return 1;
}
/*
* kvm_pv_kick_cpu_op: Kick a vcpu.
*
* @apicid - apicid of vcpu to be kicked.
*/
static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
{
struct kvm_lapic_irq lapic_irq;
lapic_irq.shorthand = 0;
lapic_irq.dest_mode = 0;
lapic_irq.dest_id = apicid;
lapic_irq.delivery_mode = APIC_DM_REMRD;
kvm_irq_delivery_to_apic(kvm, 0, &lapic_irq, NULL);
}
int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
{
unsigned long nr, a0, a1, a2, a3, ret;
int r = 1;
if (kvm_hv_hypercall_enabled(vcpu->kvm))
return kvm_hv_hypercall(vcpu);
nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
trace_kvm_hypercall(nr, a0, a1, a2, a3);
if (!is_long_mode(vcpu)) {
nr &= 0xFFFFFFFF;
a0 &= 0xFFFFFFFF;
a1 &= 0xFFFFFFFF;
a2 &= 0xFFFFFFFF;
a3 &= 0xFFFFFFFF;
}
if (kvm_x86_ops->get_cpl(vcpu) != 0) {
ret = -KVM_EPERM;
goto out;
}
switch (nr) {
case KVM_HC_VAPIC_POLL_IRQ:
ret = 0;
break;
case KVM_HC_KICK_CPU:
kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
ret = 0;
break;
default:
ret = -KVM_ENOSYS;
break;
}
out:
kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
++vcpu->stat.hypercalls;
return r;
}
EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
char instruction[3];
unsigned long rip = kvm_rip_read(vcpu);
kvm_x86_ops->patch_hypercall(vcpu, instruction);
return emulator_write_emulated(ctxt, rip, instruction, 3, NULL);
}
/*
* Check if userspace requested an interrupt window, and that the
* interrupt window is open.
*
* No need to exit to userspace if we already have an interrupt queued.
*/
static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
{
return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
vcpu->run->request_interrupt_window &&
kvm_arch_interrupt_allowed(vcpu));
}
static void post_kvm_run_save(struct kvm_vcpu *vcpu)
{
struct kvm_run *kvm_run = vcpu->run;
kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
kvm_run->cr8 = kvm_get_cr8(vcpu);
kvm_run->apic_base = kvm_get_apic_base(vcpu);
if (irqchip_in_kernel(vcpu->kvm))
kvm_run->ready_for_interrupt_injection = 1;
else
kvm_run->ready_for_interrupt_injection =
kvm_arch_interrupt_allowed(vcpu) &&
!kvm_cpu_has_interrupt(vcpu) &&
!kvm_event_needs_reinjection(vcpu);
}
static void update_cr8_intercept(struct kvm_vcpu *vcpu)
{
int max_irr, tpr;
if (!kvm_x86_ops->update_cr8_intercept)
return;
if (!vcpu->arch.apic)
return;
if (!vcpu->arch.apic->vapic_addr)
max_irr = kvm_lapic_find_highest_irr(vcpu);
else
max_irr = -1;
if (max_irr != -1)
max_irr >>= 4;
tpr = kvm_lapic_get_cr8(vcpu);
kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
}
static void inject_pending_event(struct kvm_vcpu *vcpu)
{
/* try to reinject previous events if any */
if (vcpu->arch.exception.pending) {
trace_kvm_inj_exception(vcpu->arch.exception.nr,
vcpu->arch.exception.has_error_code,
vcpu->arch.exception.error_code);
kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
vcpu->arch.exception.has_error_code,
vcpu->arch.exception.error_code,
vcpu->arch.exception.reinject);
return;
}
if (vcpu->arch.nmi_injected) {
kvm_x86_ops->set_nmi(vcpu);
return;
}
if (vcpu->arch.interrupt.pending) {
kvm_x86_ops->set_irq(vcpu);
return;
}
/* try to inject new event if pending */
if (vcpu->arch.nmi_pending) {
if (kvm_x86_ops->nmi_allowed(vcpu)) {
--vcpu->arch.nmi_pending;
vcpu->arch.nmi_injected = true;
kvm_x86_ops->set_nmi(vcpu);
}
} else if (kvm_cpu_has_injectable_intr(vcpu)) {
if (kvm_x86_ops->interrupt_allowed(vcpu)) {
kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
false);
kvm_x86_ops->set_irq(vcpu);
}
}
}
static void process_nmi(struct kvm_vcpu *vcpu)
{
unsigned limit = 2;
/*
* x86 is limited to one NMI running, and one NMI pending after it.
* If an NMI is already in progress, limit further NMIs to just one.
* Otherwise, allow two (and we'll inject the first one immediately).
*/
if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
limit = 1;
vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
kvm_make_request(KVM_REQ_EVENT, vcpu);
}
static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
{
u64 eoi_exit_bitmap[4];
u32 tmr[8];
if (!kvm_apic_hw_enabled(vcpu->arch.apic))
return;
memset(eoi_exit_bitmap, 0, 32);
memset(tmr, 0, 32);
kvm_ioapic_scan_entry(vcpu, eoi_exit_bitmap, tmr);
kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
kvm_apic_update_tmr(vcpu, tmr);
}
/*
* Returns 1 to let __vcpu_run() continue the guest execution loop without
* exiting to the userspace. Otherwise, the value will be returned to the
* userspace.
*/
static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
{
int r;
bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
vcpu->run->request_interrupt_window;
bool req_immediate_exit = false;
if (vcpu->requests) {
if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
kvm_mmu_unload(vcpu);
if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
__kvm_migrate_timers(vcpu);
if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
kvm_gen_update_masterclock(vcpu->kvm);
if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
kvm_gen_kvmclock_update(vcpu);
if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
r = kvm_guest_time_update(vcpu);
if (unlikely(r))
goto out;
}
if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
kvm_mmu_sync_roots(vcpu);
if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
kvm_x86_ops->tlb_flush(vcpu);
if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
r = 0;
goto out;
}
if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
r = 0;
goto out;
}
if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
vcpu->fpu_active = 0;
kvm_x86_ops->fpu_deactivate(vcpu);
}
if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
/* Page is swapped out. Do synthetic halt */
vcpu->arch.apf.halted = true;
r = 1;
goto out;
}
if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
record_steal_time(vcpu);
if (kvm_check_request(KVM_REQ_NMI, vcpu))
process_nmi(vcpu);
if (kvm_check_request(KVM_REQ_PMU, vcpu))
kvm_handle_pmu_event(vcpu);
if (kvm_check_request(KVM_REQ_PMI, vcpu))
kvm_deliver_pmi(vcpu);
if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
vcpu_scan_ioapic(vcpu);
}
if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
kvm_apic_accept_events(vcpu);
if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
r = 1;
goto out;
}
inject_pending_event(vcpu);
/* enable NMI/IRQ window open exits if needed */
if (vcpu->arch.nmi_pending)
req_immediate_exit =
kvm_x86_ops->enable_nmi_window(vcpu) != 0;
else if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
req_immediate_exit =
kvm_x86_ops->enable_irq_window(vcpu) != 0;
if (kvm_lapic_enabled(vcpu)) {
/*
* Update architecture specific hints for APIC
* virtual interrupt delivery.
*/
if (kvm_x86_ops->hwapic_irr_update)
kvm_x86_ops->hwapic_irr_update(vcpu,
kvm_lapic_find_highest_irr(vcpu));
update_cr8_intercept(vcpu);
kvm_lapic_sync_to_vapic(vcpu);
}
}
r = kvm_mmu_reload(vcpu);
if (unlikely(r)) {
goto cancel_injection;
}
preempt_disable();
kvm_x86_ops->prepare_guest_switch(vcpu);
if (vcpu->fpu_active)
kvm_load_guest_fpu(vcpu);
kvm_load_guest_xcr0(vcpu);
vcpu->mode = IN_GUEST_MODE;
srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
/* We should set ->mode before check ->requests,
* see the comment in make_all_cpus_request.
*/
smp_mb__after_srcu_read_unlock();
local_irq_disable();
if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
|| need_resched() || signal_pending(current)) {
vcpu->mode = OUTSIDE_GUEST_MODE;
smp_wmb();
local_irq_enable();
preempt_enable();
vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
r = 1;
goto cancel_injection;
}
if (req_immediate_exit)
smp_send_reschedule(vcpu->cpu);
kvm_guest_enter();
if (unlikely(vcpu->arch.switch_db_regs)) {
set_debugreg(0, 7);
set_debugreg(vcpu->arch.eff_db[0], 0);
set_debugreg(vcpu->arch.eff_db[1], 1);
set_debugreg(vcpu->arch.eff_db[2], 2);
set_debugreg(vcpu->arch.eff_db[3], 3);
}
trace_kvm_entry(vcpu->vcpu_id);
kvm_x86_ops->run(vcpu);
/*
* If the guest has used debug registers, at least dr7
* will be disabled while returning to the host.
* If we don't have active breakpoints in the host, we don't
* care about the messed up debug address registers. But if
* we have some of them active, restore the old state.
*/
if (hw_breakpoint_active())
hw_breakpoint_restore();
vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu,
native_read_tsc());
vcpu->mode = OUTSIDE_GUEST_MODE;
smp_wmb();
/* Interrupt is enabled by handle_external_intr() */
kvm_x86_ops->handle_external_intr(vcpu);
++vcpu->stat.exits;
/*
* We must have an instruction between local_irq_enable() and
* kvm_guest_exit(), so the timer interrupt isn't delayed by
* the interrupt shadow. The stat.exits increment will do nicely.
* But we need to prevent reordering, hence this barrier():
*/
barrier();
kvm_guest_exit();
preempt_enable();
vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
/*
* Profile KVM exit RIPs:
*/
if (unlikely(prof_on == KVM_PROFILING)) {
unsigned long rip = kvm_rip_read(vcpu);
profile_hit(KVM_PROFILING, (void *)rip);
}
if (unlikely(vcpu->arch.tsc_always_catchup))
kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
if (vcpu->arch.apic_attention)
kvm_lapic_sync_from_vapic(vcpu);
r = kvm_x86_ops->handle_exit(vcpu);
return r;
cancel_injection:
kvm_x86_ops->cancel_injection(vcpu);
if (unlikely(vcpu->arch.apic_attention))
kvm_lapic_sync_from_vapic(vcpu);
out:
return r;
}
static int __vcpu_run(struct kvm_vcpu *vcpu)
{
int r;
struct kvm *kvm = vcpu->kvm;
vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
r = 1;
while (r > 0) {
if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
!vcpu->arch.apf.halted)
r = vcpu_enter_guest(vcpu);
else {
srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
kvm_vcpu_block(vcpu);
vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
if (kvm_check_request(KVM_REQ_UNHALT, vcpu)) {
kvm_apic_accept_events(vcpu);
switch(vcpu->arch.mp_state) {
case KVM_MP_STATE_HALTED:
vcpu->arch.pv.pv_unhalted = false;
vcpu->arch.mp_state =
KVM_MP_STATE_RUNNABLE;
case KVM_MP_STATE_RUNNABLE:
vcpu->arch.apf.halted = false;
break;
case KVM_MP_STATE_INIT_RECEIVED:
break;
default:
r = -EINTR;
break;
}
}
}
if (r <= 0)
break;
clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
if (kvm_cpu_has_pending_timer(vcpu))
kvm_inject_pending_timer_irqs(vcpu);
if (dm_request_for_irq_injection(vcpu)) {
r = -EINTR;
vcpu->run->exit_reason = KVM_EXIT_INTR;
++vcpu->stat.request_irq_exits;
}
kvm_check_async_pf_completion(vcpu);
if (signal_pending(current)) {
r = -EINTR;
vcpu->run->exit_reason = KVM_EXIT_INTR;
++vcpu->stat.signal_exits;
}
if (need_resched()) {
srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
cond_resched();
vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
}
}
srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
return r;
}
static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
{
int r;
vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
if (r != EMULATE_DONE)
return 0;
return 1;
}
static int complete_emulated_pio(struct kvm_vcpu *vcpu)
{
BUG_ON(!vcpu->arch.pio.count);
return complete_emulated_io(vcpu);
}
/*
* Implements the following, as a state machine:
*
* read:
* for each fragment
* for each mmio piece in the fragment
* write gpa, len
* exit
* copy data
* execute insn
*
* write:
* for each fragment
* for each mmio piece in the fragment
* write gpa, len
* copy data
* exit
*/
static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
{
struct kvm_run *run = vcpu->run;
struct kvm_mmio_fragment *frag;
unsigned len;
BUG_ON(!vcpu->mmio_needed);
/* Complete previous fragment */
frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
len = min(8u, frag->len);
if (!vcpu->mmio_is_write)
memcpy(frag->data, run->mmio.data, len);
if (frag->len <= 8) {
/* Switch to the next fragment. */
frag++;
vcpu->mmio_cur_fragment++;
} else {
/* Go forward to the next mmio piece. */
frag->data += len;
frag->gpa += len;
frag->len -= len;
}
if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
vcpu->mmio_needed = 0;
/* FIXME: return into emulator if single-stepping. */
if (vcpu->mmio_is_write)
return 1;
vcpu->mmio_read_completed = 1;
return complete_emulated_io(vcpu);
}
run->exit_reason = KVM_EXIT_MMIO;
run->mmio.phys_addr = frag->gpa;
if (vcpu->mmio_is_write)
memcpy(run->mmio.data, frag->data, min(8u, frag->len));
run->mmio.len = min(8u, frag->len);
run->mmio.is_write = vcpu->mmio_is_write;
vcpu->arch.complete_userspace_io = complete_emulated_mmio;
return 0;
}
int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
{
int r;
sigset_t sigsaved;
if (!tsk_used_math(current) && init_fpu(current))
return -ENOMEM;
if (vcpu->sigset_active)
sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
kvm_vcpu_block(vcpu);
kvm_apic_accept_events(vcpu);
clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
r = -EAGAIN;
goto out;
}
/* re-sync apic's tpr */
if (!irqchip_in_kernel(vcpu->kvm)) {
if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
r = -EINVAL;
goto out;
}
}
if (unlikely(vcpu->arch.complete_userspace_io)) {
int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
vcpu->arch.complete_userspace_io = NULL;
r = cui(vcpu);
if (r <= 0)
goto out;
} else
WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
r = __vcpu_run(vcpu);
out:
post_kvm_run_save(vcpu);
if (vcpu->sigset_active)
sigprocmask(SIG_SETMASK, &sigsaved, NULL);
return r;
}
int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
{
if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
/*
* We are here if userspace calls get_regs() in the middle of
* instruction emulation. Registers state needs to be copied
* back from emulation context to vcpu. Userspace shouldn't do
* that usually, but some bad designed PV devices (vmware
* backdoor interface) need this to work
*/
emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
}
regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
#ifdef CONFIG_X86_64
regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
#endif
regs->rip = kvm_rip_read(vcpu);
regs->rflags = kvm_get_rflags(vcpu);
return 0;
}
int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
{
vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
#ifdef CONFIG_X86_64
kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
#endif
kvm_rip_write(vcpu, regs->rip);
kvm_set_rflags(vcpu, regs->rflags);
vcpu->arch.exception.pending = false;
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 0;
}
void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
{
struct kvm_segment cs;
kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
*db = cs.db;
*l = cs.l;
}
EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
struct kvm_sregs *sregs)
{
struct desc_ptr dt;
kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
kvm_x86_ops->get_idt(vcpu, &dt);
sregs->idt.limit = dt.size;
sregs->idt.base = dt.address;
kvm_x86_ops->get_gdt(vcpu, &dt);
sregs->gdt.limit = dt.size;
sregs->gdt.base = dt.address;
sregs->cr0 = kvm_read_cr0(vcpu);
sregs->cr2 = vcpu->arch.cr2;
sregs->cr3 = kvm_read_cr3(vcpu);
sregs->cr4 = kvm_read_cr4(vcpu);
sregs->cr8 = kvm_get_cr8(vcpu);
sregs->efer = vcpu->arch.efer;
sregs->apic_base = kvm_get_apic_base(vcpu);
memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
set_bit(vcpu->arch.interrupt.nr,
(unsigned long *)sregs->interrupt_bitmap);
return 0;
}
int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
struct kvm_mp_state *mp_state)
{
kvm_apic_accept_events(vcpu);
if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
vcpu->arch.pv.pv_unhalted)
mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
else
mp_state->mp_state = vcpu->arch.mp_state;
return 0;
}
int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
struct kvm_mp_state *mp_state)
{
if (!kvm_vcpu_has_lapic(vcpu) &&
mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
return -EINVAL;
if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
} else
vcpu->arch.mp_state = mp_state->mp_state;
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 0;
}
int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
int reason, bool has_error_code, u32 error_code)
{
struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
int ret;
init_emulate_ctxt(vcpu);
ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
has_error_code, error_code);
if (ret)
return EMULATE_FAIL;
kvm_rip_write(vcpu, ctxt->eip);
kvm_set_rflags(vcpu, ctxt->eflags);
kvm_make_request(KVM_REQ_EVENT, vcpu);
return EMULATE_DONE;
}
EXPORT_SYMBOL_GPL(kvm_task_switch);
int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
struct kvm_sregs *sregs)
{
struct msr_data apic_base_msr;
int mmu_reset_needed = 0;
int pending_vec, max_bits, idx;
struct desc_ptr dt;
if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
return -EINVAL;
dt.size = sregs->idt.limit;
dt.address = sregs->idt.base;
kvm_x86_ops->set_idt(vcpu, &dt);
dt.size = sregs->gdt.limit;
dt.address = sregs->gdt.base;
kvm_x86_ops->set_gdt(vcpu, &dt);
vcpu->arch.cr2 = sregs->cr2;
mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
vcpu->arch.cr3 = sregs->cr3;
__set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
kvm_set_cr8(vcpu, sregs->cr8);
mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
kvm_x86_ops->set_efer(vcpu, sregs->efer);
apic_base_msr.data = sregs->apic_base;
apic_base_msr.host_initiated = true;
kvm_set_apic_base(vcpu, &apic_base_msr);
mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
vcpu->arch.cr0 = sregs->cr0;
mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
if (sregs->cr4 & X86_CR4_OSXSAVE)
kvm_update_cpuid(vcpu);
idx = srcu_read_lock(&vcpu->kvm->srcu);
if (!is_long_mode(vcpu) && is_pae(vcpu)) {
load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
mmu_reset_needed = 1;
}
srcu_read_unlock(&vcpu->kvm->srcu, idx);
if (mmu_reset_needed)
kvm_mmu_reset_context(vcpu);
max_bits = KVM_NR_INTERRUPTS;
pending_vec = find_first_bit(
(const unsigned long *)sregs->interrupt_bitmap, max_bits);
if (pending_vec < max_bits) {
kvm_queue_interrupt(vcpu, pending_vec, false);
pr_debug("Set back pending irq %d\n", pending_vec);
}
kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
update_cr8_intercept(vcpu);
/* Older userspace won't unhalt the vcpu on reset. */
if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
!is_protmode(vcpu))
vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 0;
}
int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
struct kvm_guest_debug *dbg)
{
unsigned long rflags;
int i, r;
if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
r = -EBUSY;
if (vcpu->arch.exception.pending)
goto out;
if (dbg->control & KVM_GUESTDBG_INJECT_DB)
kvm_queue_exception(vcpu, DB_VECTOR);
else
kvm_queue_exception(vcpu, BP_VECTOR);
}
/*
* Read rflags as long as potentially injected trace flags are still
* filtered out.
*/
rflags = kvm_get_rflags(vcpu);
vcpu->guest_debug = dbg->control;
if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
vcpu->guest_debug = 0;
if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
for (i = 0; i < KVM_NR_DB_REGS; ++i)
vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
} else {
for (i = 0; i < KVM_NR_DB_REGS; i++)
vcpu->arch.eff_db[i] = vcpu->arch.db[i];
}
kvm_update_dr7(vcpu);
if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
get_segment_base(vcpu, VCPU_SREG_CS);
/*
* Trigger an rflags update that will inject or remove the trace
* flags.
*/
kvm_set_rflags(vcpu, rflags);
kvm_x86_ops->update_db_bp_intercept(vcpu);
r = 0;
out:
return r;
}
/*
* Translate a guest virtual address to a guest physical address.
*/
int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
struct kvm_translation *tr)
{
unsigned long vaddr = tr->linear_address;
gpa_t gpa;
int idx;
idx = srcu_read_lock(&vcpu->kvm->srcu);
gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
srcu_read_unlock(&vcpu->kvm->srcu, idx);
tr->physical_address = gpa;
tr->valid = gpa != UNMAPPED_GVA;
tr->writeable = 1;
tr->usermode = 0;
return 0;
}
int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
{
struct i387_fxsave_struct *fxsave =
&vcpu->arch.guest_fpu.state->fxsave;
memcpy(fpu->fpr, fxsave->st_space, 128);
fpu->fcw = fxsave->cwd;
fpu->fsw = fxsave->swd;
fpu->ftwx = fxsave->twd;
fpu->last_opcode = fxsave->fop;
fpu->last_ip = fxsave->rip;
fpu->last_dp = fxsave->rdp;
memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
return 0;
}
int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
{
struct i387_fxsave_struct *fxsave =
&vcpu->arch.guest_fpu.state->fxsave;
memcpy(fxsave->st_space, fpu->fpr, 128);
fxsave->cwd = fpu->fcw;
fxsave->swd = fpu->fsw;
fxsave->twd = fpu->ftwx;
fxsave->fop = fpu->last_opcode;
fxsave->rip = fpu->last_ip;
fxsave->rdp = fpu->last_dp;
memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
return 0;
}
int fx_init(struct kvm_vcpu *vcpu)
{
int err;
err = fpu_alloc(&vcpu->arch.guest_fpu);
if (err)
return err;
fpu_finit(&vcpu->arch.guest_fpu);
/*
* Ensure guest xcr0 is valid for loading
*/
vcpu->arch.xcr0 = XSTATE_FP;
vcpu->arch.cr0 |= X86_CR0_ET;
return 0;
}
EXPORT_SYMBOL_GPL(fx_init);
static void fx_free(struct kvm_vcpu *vcpu)
{
fpu_free(&vcpu->arch.guest_fpu);
}
void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
{
if (vcpu->guest_fpu_loaded)
return;
/*
* Restore all possible states in the guest,
* and assume host would use all available bits.
* Guest xcr0 would be loaded later.
*/
kvm_put_guest_xcr0(vcpu);
vcpu->guest_fpu_loaded = 1;
__kernel_fpu_begin();
fpu_restore_checking(&vcpu->arch.guest_fpu);
trace_kvm_fpu(1);
}
void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
{
kvm_put_guest_xcr0(vcpu);
if (!vcpu->guest_fpu_loaded)
return;
vcpu->guest_fpu_loaded = 0;
fpu_save_init(&vcpu->arch.guest_fpu);
__kernel_fpu_end();
++vcpu->stat.fpu_reload;
kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
trace_kvm_fpu(0);
}
void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
{
kvmclock_reset(vcpu);
free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
fx_free(vcpu);
kvm_x86_ops->vcpu_free(vcpu);
}
struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
unsigned int id)
{
if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
printk_once(KERN_WARNING
"kvm: SMP vm created on host with unstable TSC; "
"guest TSC will not be reliable\n");
return kvm_x86_ops->vcpu_create(kvm, id);
}
int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
{
int r;
vcpu->arch.mtrr_state.have_fixed = 1;
r = vcpu_load(vcpu);
if (r)
return r;
kvm_vcpu_reset(vcpu);
kvm_mmu_setup(vcpu);
vcpu_put(vcpu);
return r;
}
int kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
{
int r;
struct msr_data msr;
r = vcpu_load(vcpu);
if (r)
return r;
msr.data = 0x0;
msr.index = MSR_IA32_TSC;
msr.host_initiated = true;
kvm_write_tsc(vcpu, &msr);
vcpu_put(vcpu);
return r;
}
void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
{
int r;
vcpu->arch.apf.msr_val = 0;
r = vcpu_load(vcpu);
BUG_ON(r);
kvm_mmu_unload(vcpu);
vcpu_put(vcpu);
fx_free(vcpu);
kvm_x86_ops->vcpu_free(vcpu);
}
void kvm_vcpu_reset(struct kvm_vcpu *vcpu)
{
atomic_set(&vcpu->arch.nmi_queued, 0);
vcpu->arch.nmi_pending = 0;
vcpu->arch.nmi_injected = false;
memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
vcpu->arch.dr6 = DR6_FIXED_1;
kvm_update_dr6(vcpu);
vcpu->arch.dr7 = DR7_FIXED_1;
kvm_update_dr7(vcpu);
kvm_make_request(KVM_REQ_EVENT, vcpu);
vcpu->arch.apf.msr_val = 0;
vcpu->arch.st.msr_val = 0;
kvmclock_reset(vcpu);
kvm_clear_async_pf_completion_queue(vcpu);
kvm_async_pf_hash_reset(vcpu);
vcpu->arch.apf.halted = false;
kvm_pmu_reset(vcpu);
memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
vcpu->arch.regs_avail = ~0;
vcpu->arch.regs_dirty = ~0;
kvm_x86_ops->vcpu_reset(vcpu);
}
void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, unsigned int vector)
{
struct kvm_segment cs;
kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
cs.selector = vector << 8;
cs.base = vector << 12;
kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
kvm_rip_write(vcpu, 0);
}
int kvm_arch_hardware_enable(void *garbage)
{
struct kvm *kvm;
struct kvm_vcpu *vcpu;
int i;
int ret;
u64 local_tsc;
u64 max_tsc = 0;
bool stable, backwards_tsc = false;
kvm_shared_msr_cpu_online();
ret = kvm_x86_ops->hardware_enable(garbage);
if (ret != 0)
return ret;
local_tsc = native_read_tsc();
stable = !check_tsc_unstable();
list_for_each_entry(kvm, &vm_list, vm_list) {
kvm_for_each_vcpu(i, vcpu, kvm) {
if (!stable && vcpu->cpu == smp_processor_id())
set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
if (stable && vcpu->arch.last_host_tsc > local_tsc) {
backwards_tsc = true;
if (vcpu->arch.last_host_tsc > max_tsc)
max_tsc = vcpu->arch.last_host_tsc;
}
}
}
/*
* Sometimes, even reliable TSCs go backwards. This happens on
* platforms that reset TSC during suspend or hibernate actions, but
* maintain synchronization. We must compensate. Fortunately, we can
* detect that condition here, which happens early in CPU bringup,
* before any KVM threads can be running. Unfortunately, we can't
* bring the TSCs fully up to date with real time, as we aren't yet far
* enough into CPU bringup that we know how much real time has actually
* elapsed; our helper function, get_kernel_ns() will be using boot
* variables that haven't been updated yet.
*
* So we simply find the maximum observed TSC above, then record the
* adjustment to TSC in each VCPU. When the VCPU later gets loaded,
* the adjustment will be applied. Note that we accumulate
* adjustments, in case multiple suspend cycles happen before some VCPU
* gets a chance to run again. In the event that no KVM threads get a
* chance to run, we will miss the entire elapsed period, as we'll have
* reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
* loose cycle time. This isn't too big a deal, since the loss will be
* uniform across all VCPUs (not to mention the scenario is extremely
* unlikely). It is possible that a second hibernate recovery happens
* much faster than a first, causing the observed TSC here to be
* smaller; this would require additional padding adjustment, which is
* why we set last_host_tsc to the local tsc observed here.
*
* N.B. - this code below runs only on platforms with reliable TSC,
* as that is the only way backwards_tsc is set above. Also note
* that this runs for ALL vcpus, which is not a bug; all VCPUs should
* have the same delta_cyc adjustment applied if backwards_tsc
* is detected. Note further, this adjustment is only done once,
* as we reset last_host_tsc on all VCPUs to stop this from being
* called multiple times (one for each physical CPU bringup).
*
* Platforms with unreliable TSCs don't have to deal with this, they
* will be compensated by the logic in vcpu_load, which sets the TSC to
* catchup mode. This will catchup all VCPUs to real time, but cannot
* guarantee that they stay in perfect synchronization.
*/
if (backwards_tsc) {
u64 delta_cyc = max_tsc - local_tsc;
list_for_each_entry(kvm, &vm_list, vm_list) {
kvm_for_each_vcpu(i, vcpu, kvm) {
vcpu->arch.tsc_offset_adjustment += delta_cyc;
vcpu->arch.last_host_tsc = local_tsc;
set_bit(KVM_REQ_MASTERCLOCK_UPDATE,
&vcpu->requests);
}
/*
* We have to disable TSC offset matching.. if you were
* booting a VM while issuing an S4 host suspend....
* you may have some problem. Solving this issue is
* left as an exercise to the reader.
*/
kvm->arch.last_tsc_nsec = 0;
kvm->arch.last_tsc_write = 0;
}
}
return 0;
}
void kvm_arch_hardware_disable(void *garbage)
{
kvm_x86_ops->hardware_disable(garbage);
drop_user_return_notifiers(garbage);
}
int kvm_arch_hardware_setup(void)
{
return kvm_x86_ops->hardware_setup();
}
void kvm_arch_hardware_unsetup(void)
{
kvm_x86_ops->hardware_unsetup();
}
void kvm_arch_check_processor_compat(void *rtn)
{
kvm_x86_ops->check_processor_compatibility(rtn);
}
bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu)
{
return irqchip_in_kernel(vcpu->kvm) == (vcpu->arch.apic != NULL);
}
struct static_key kvm_no_apic_vcpu __read_mostly;
int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
{
struct page *page;
struct kvm *kvm;
int r;
BUG_ON(vcpu->kvm == NULL);
kvm = vcpu->kvm;
vcpu->arch.pv.pv_unhalted = false;
vcpu->arch.emulate_ctxt.ops = &emulate_ops;
if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
else
vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
page = alloc_page(GFP_KERNEL | __GFP_ZERO);
if (!page) {
r = -ENOMEM;
goto fail;
}
vcpu->arch.pio_data = page_address(page);
kvm_set_tsc_khz(vcpu, max_tsc_khz);
r = kvm_mmu_create(vcpu);
if (r < 0)
goto fail_free_pio_data;
if (irqchip_in_kernel(kvm)) {
r = kvm_create_lapic(vcpu);
if (r < 0)
goto fail_mmu_destroy;
} else
static_key_slow_inc(&kvm_no_apic_vcpu);
vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
GFP_KERNEL);
if (!vcpu->arch.mce_banks) {
r = -ENOMEM;
goto fail_free_lapic;
}
vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
r = -ENOMEM;
goto fail_free_mce_banks;
}
r = fx_init(vcpu);
if (r)
goto fail_free_wbinvd_dirty_mask;
vcpu->arch.ia32_tsc_adjust_msr = 0x0;
vcpu->arch.pv_time_enabled = false;
vcpu->arch.guest_supported_xcr0 = 0;
vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
kvm_async_pf_hash_reset(vcpu);
kvm_pmu_init(vcpu);
return 0;
fail_free_wbinvd_dirty_mask:
free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
fail_free_mce_banks:
kfree(vcpu->arch.mce_banks);
fail_free_lapic:
kvm_free_lapic(vcpu);
fail_mmu_destroy:
kvm_mmu_destroy(vcpu);
fail_free_pio_data:
free_page((unsigned long)vcpu->arch.pio_data);
fail:
return r;
}
void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
{
int idx;
kvm_pmu_destroy(vcpu);
kfree(vcpu->arch.mce_banks);
kvm_free_lapic(vcpu);
idx = srcu_read_lock(&vcpu->kvm->srcu);
kvm_mmu_destroy(vcpu);
srcu_read_unlock(&vcpu->kvm->srcu, idx);
free_page((unsigned long)vcpu->arch.pio_data);
if (!irqchip_in_kernel(vcpu->kvm))
static_key_slow_dec(&kvm_no_apic_vcpu);
}
int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
{
if (type)
return -EINVAL;
INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
atomic_set(&kvm->arch.noncoherent_dma_count, 0);
/* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
/* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
&kvm->arch.irq_sources_bitmap);
raw_spin_lock_init(&kvm->arch.tsc_write_lock);
mutex_init(&kvm->arch.apic_map_lock);
spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
pvclock_update_vm_gtod_copy(kvm);
return 0;
}
static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
{
int r;
r = vcpu_load(vcpu);
BUG_ON(r);
kvm_mmu_unload(vcpu);
vcpu_put(vcpu);
}
static void kvm_free_vcpus(struct kvm *kvm)
{
unsigned int i;
struct kvm_vcpu *vcpu;
/*
* Unpin any mmu pages first.
*/
kvm_for_each_vcpu(i, vcpu, kvm) {
kvm_clear_async_pf_completion_queue(vcpu);
kvm_unload_vcpu_mmu(vcpu);
}
kvm_for_each_vcpu(i, vcpu, kvm)
kvm_arch_vcpu_free(vcpu);
mutex_lock(&kvm->lock);
for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
kvm->vcpus[i] = NULL;
atomic_set(&kvm->online_vcpus, 0);
mutex_unlock(&kvm->lock);
}
void kvm_arch_sync_events(struct kvm *kvm)
{
kvm_free_all_assigned_devices(kvm);
kvm_free_pit(kvm);
}
void kvm_arch_destroy_vm(struct kvm *kvm)
{
if (current->mm == kvm->mm) {
/*
* Free memory regions allocated on behalf of userspace,
* unless the the memory map has changed due to process exit
* or fd copying.
*/
struct kvm_userspace_memory_region mem;
memset(&mem, 0, sizeof(mem));
mem.slot = APIC_ACCESS_PAGE_PRIVATE_MEMSLOT;
kvm_set_memory_region(kvm, &mem);
mem.slot = IDENTITY_PAGETABLE_PRIVATE_MEMSLOT;
kvm_set_memory_region(kvm, &mem);
mem.slot = TSS_PRIVATE_MEMSLOT;
kvm_set_memory_region(kvm, &mem);
}
kvm_iommu_unmap_guest(kvm);
kfree(kvm->arch.vpic);
kfree(kvm->arch.vioapic);
kvm_free_vcpus(kvm);
if (kvm->arch.apic_access_page)
put_page(kvm->arch.apic_access_page);
if (kvm->arch.ept_identity_pagetable)
put_page(kvm->arch.ept_identity_pagetable);
kfree(rcu_dereference_check(kvm->arch.apic_map, 1));
}
void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
struct kvm_memory_slot *dont)
{
int i;
for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
kvm_kvfree(free->arch.rmap[i]);
free->arch.rmap[i] = NULL;
}
if (i == 0)
continue;
if (!dont || free->arch.lpage_info[i - 1] !=
dont->arch.lpage_info[i - 1]) {
kvm_kvfree(free->arch.lpage_info[i - 1]);
free->arch.lpage_info[i - 1] = NULL;
}
}
}
int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
unsigned long npages)
{
int i;
for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
unsigned long ugfn;
int lpages;
int level = i + 1;
lpages = gfn_to_index(slot->base_gfn + npages - 1,
slot->base_gfn, level) + 1;
slot->arch.rmap[i] =
kvm_kvzalloc(lpages * sizeof(*slot->arch.rmap[i]));
if (!slot->arch.rmap[i])
goto out_free;
if (i == 0)
continue;
slot->arch.lpage_info[i - 1] = kvm_kvzalloc(lpages *
sizeof(*slot->arch.lpage_info[i - 1]));
if (!slot->arch.lpage_info[i - 1])
goto out_free;
if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
slot->arch.lpage_info[i - 1][0].write_count = 1;
if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
slot->arch.lpage_info[i - 1][lpages - 1].write_count = 1;
ugfn = slot->userspace_addr >> PAGE_SHIFT;
/*
* If the gfn and userspace address are not aligned wrt each
* other, or if explicitly asked to, disable large page
* support for this slot
*/
if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
!kvm_largepages_enabled()) {
unsigned long j;
for (j = 0; j < lpages; ++j)
slot->arch.lpage_info[i - 1][j].write_count = 1;
}
}
return 0;
out_free:
for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
kvm_kvfree(slot->arch.rmap[i]);
slot->arch.rmap[i] = NULL;
if (i == 0)
continue;
kvm_kvfree(slot->arch.lpage_info[i - 1]);
slot->arch.lpage_info[i - 1] = NULL;
}
return -ENOMEM;
}
void kvm_arch_memslots_updated(struct kvm *kvm)
{
/*
* memslots->generation has been incremented.
* mmio generation may have reached its maximum value.
*/
kvm_mmu_invalidate_mmio_sptes(kvm);
}
int kvm_arch_prepare_memory_region(struct kvm *kvm,
struct kvm_memory_slot *memslot,
struct kvm_userspace_memory_region *mem,
enum kvm_mr_change change)
{
/*
* Only private memory slots need to be mapped here since
* KVM_SET_MEMORY_REGION ioctl is no longer supported.
*/
if ((memslot->id >= KVM_USER_MEM_SLOTS) && (change == KVM_MR_CREATE)) {
unsigned long userspace_addr;
/*
* MAP_SHARED to prevent internal slot pages from being moved
* by fork()/COW.
*/
userspace_addr = vm_mmap(NULL, 0, memslot->npages * PAGE_SIZE,
PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, 0);
if (IS_ERR((void *)userspace_addr))
return PTR_ERR((void *)userspace_addr);
memslot->userspace_addr = userspace_addr;
}
return 0;
}
void kvm_arch_commit_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem,
const struct kvm_memory_slot *old,
enum kvm_mr_change change)
{
int nr_mmu_pages = 0;
if ((mem->slot >= KVM_USER_MEM_SLOTS) && (change == KVM_MR_DELETE)) {
int ret;
ret = vm_munmap(old->userspace_addr,
old->npages * PAGE_SIZE);
if (ret < 0)
printk(KERN_WARNING
"kvm_vm_ioctl_set_memory_region: "
"failed to munmap memory\n");
}
if (!kvm->arch.n_requested_mmu_pages)
nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
if (nr_mmu_pages)
kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
/*
* Write protect all pages for dirty logging.
* Existing largepage mappings are destroyed here and new ones will
* not be created until the end of the logging.
*/
if ((change != KVM_MR_DELETE) && (mem->flags & KVM_MEM_LOG_DIRTY_PAGES))
kvm_mmu_slot_remove_write_access(kvm, mem->slot);
}
void kvm_arch_flush_shadow_all(struct kvm *kvm)
{
kvm_mmu_invalidate_zap_all_pages(kvm);
}
void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
struct kvm_memory_slot *slot)
{
kvm_mmu_invalidate_zap_all_pages(kvm);
}
int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
{
return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
!vcpu->arch.apf.halted)
|| !list_empty_careful(&vcpu->async_pf.done)
|| kvm_apic_has_events(vcpu)
|| vcpu->arch.pv.pv_unhalted
|| atomic_read(&vcpu->arch.nmi_queued) ||
(kvm_arch_interrupt_allowed(vcpu) &&
kvm_cpu_has_interrupt(vcpu));
}
int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
{
return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
}
int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
{
return kvm_x86_ops->interrupt_allowed(vcpu);
}
bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
{
unsigned long current_rip = kvm_rip_read(vcpu) +
get_segment_base(vcpu, VCPU_SREG_CS);
return current_rip == linear_rip;
}
EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
{
unsigned long rflags;
rflags = kvm_x86_ops->get_rflags(vcpu);
if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
rflags &= ~X86_EFLAGS_TF;
return rflags;
}
EXPORT_SYMBOL_GPL(kvm_get_rflags);
void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
{
if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
rflags |= X86_EFLAGS_TF;
kvm_x86_ops->set_rflags(vcpu, rflags);
kvm_make_request(KVM_REQ_EVENT, vcpu);
}
EXPORT_SYMBOL_GPL(kvm_set_rflags);
void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
{
int r;
if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
work->wakeup_all)
return;
r = kvm_mmu_reload(vcpu);
if (unlikely(r))
return;
if (!vcpu->arch.mmu.direct_map &&
work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
return;
vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
}
static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
{
return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
}
static inline u32 kvm_async_pf_next_probe(u32 key)
{
return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
}
static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
{
u32 key = kvm_async_pf_hash_fn(gfn);
while (vcpu->arch.apf.gfns[key] != ~0)
key = kvm_async_pf_next_probe(key);
vcpu->arch.apf.gfns[key] = gfn;
}
static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
{
int i;
u32 key = kvm_async_pf_hash_fn(gfn);
for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
(vcpu->arch.apf.gfns[key] != gfn &&
vcpu->arch.apf.gfns[key] != ~0); i++)
key = kvm_async_pf_next_probe(key);
return key;
}
bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
{
return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
}
static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
{
u32 i, j, k;
i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
while (true) {
vcpu->arch.apf.gfns[i] = ~0;
do {
j = kvm_async_pf_next_probe(j);
if (vcpu->arch.apf.gfns[j] == ~0)
return;
k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
/*
* k lies cyclically in ]i,j]
* | i.k.j |
* |....j i.k.| or |.k..j i...|
*/
} while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
i = j;
}
}
static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
{
return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
sizeof(val));
}
void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
struct kvm_async_pf *work)
{
struct x86_exception fault;
trace_kvm_async_pf_not_present(work->arch.token, work->gva);
kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
(vcpu->arch.apf.send_user_only &&
kvm_x86_ops->get_cpl(vcpu) == 0))
kvm_make_request(KVM_REQ_APF_HALT, vcpu);
else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
fault.vector = PF_VECTOR;
fault.error_code_valid = true;
fault.error_code = 0;
fault.nested_page_fault = false;
fault.address = work->arch.token;
kvm_inject_page_fault(vcpu, &fault);
}
}
void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
struct kvm_async_pf *work)
{
struct x86_exception fault;
trace_kvm_async_pf_ready(work->arch.token, work->gva);
if (work->wakeup_all)
work->arch.token = ~0; /* broadcast wakeup */
else
kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
fault.vector = PF_VECTOR;
fault.error_code_valid = true;
fault.error_code = 0;
fault.nested_page_fault = false;
fault.address = work->arch.token;
kvm_inject_page_fault(vcpu, &fault);
}
vcpu->arch.apf.halted = false;
vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
}
bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
{
if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
return true;
else
return !kvm_event_needs_reinjection(vcpu) &&
kvm_x86_ops->interrupt_allowed(vcpu);
}
void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
{
atomic_inc(&kvm->arch.noncoherent_dma_count);
}
EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
{
atomic_dec(&kvm->arch.noncoherent_dma_count);
}
EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
{
return atomic_read(&kvm->arch.noncoherent_dma_count);
}
EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2018_0 |
crossvul-cpp_data_good_2933_0 | /*
* Smacker decoder
* Copyright (c) 2006 Konstantin Shishkov
*
* This file is part of Libav.
*
* Libav is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Libav is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Libav; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* Smacker decoder
*/
/*
* Based on http://wiki.multimedia.cx/index.php?title=Smacker
*/
#include <stdio.h>
#include <stdlib.h>
#include "libavutil/channel_layout.h"
#define BITSTREAM_READER_LE
#include "avcodec.h"
#include "bitstream.h"
#include "bytestream.h"
#include "internal.h"
#include "mathops.h"
#include "vlc.h"
#define SMKTREE_BITS 9
#define SMK_NODE 0x80000000
#define SMKTREE_DECODE_MAX_RECURSION 32
typedef struct SmackVContext {
AVCodecContext *avctx;
AVFrame *pic;
int *mmap_tbl, *mclr_tbl, *full_tbl, *type_tbl;
int mmap_last[3], mclr_last[3], full_last[3], type_last[3];
} SmackVContext;
/**
* Context used for code reconstructing
*/
typedef struct HuffContext {
int length;
int maxlength;
int current;
uint32_t *bits;
int *lengths;
int *values;
} HuffContext;
/* common parameters used for decode_bigtree */
typedef struct DBCtx {
VLC *v1, *v2;
int *recode1, *recode2;
int escapes[3];
int *last;
int lcur;
} DBCtx;
/* possible runs of blocks */
static const int block_runs[64] = {
1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32,
33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, 52, 53, 54, 55, 56,
57, 58, 59, 128, 256, 512, 1024, 2048 };
enum SmkBlockTypes {
SMK_BLK_MONO = 0,
SMK_BLK_FULL = 1,
SMK_BLK_SKIP = 2,
SMK_BLK_FILL = 3 };
/**
* Decode local frame tree
*/
static int smacker_decode_tree(BitstreamContext *bc, HuffContext *hc,
uint32_t prefix, int length)
{
if (length > SMKTREE_DECODE_MAX_RECURSION) {
av_log(NULL, AV_LOG_ERROR, "Maximum tree recursion level exceeded.\n");
return AVERROR_INVALIDDATA;
}
if (!bitstream_read_bit(bc)) { // Leaf
if(hc->current >= 256){
av_log(NULL, AV_LOG_ERROR, "Tree size exceeded!\n");
return AVERROR_INVALIDDATA;
}
if(length){
hc->bits[hc->current] = prefix;
hc->lengths[hc->current] = length;
} else {
hc->bits[hc->current] = 0;
hc->lengths[hc->current] = 0;
}
hc->values[hc->current] = bitstream_read(bc, 8);
hc->current++;
if(hc->maxlength < length)
hc->maxlength = length;
return 0;
} else { //Node
int r;
length++;
r = smacker_decode_tree(bc, hc, prefix, length);
if(r)
return r;
return smacker_decode_tree(bc, hc, prefix | (1 << (length - 1)), length);
}
}
/**
* Decode header tree
*/
static int smacker_decode_bigtree(BitstreamContext *bc, HuffContext *hc,
DBCtx *ctx)
{
if (hc->current + 1 >= hc->length) {
av_log(NULL, AV_LOG_ERROR, "Tree size exceeded!\n");
return AVERROR_INVALIDDATA;
}
if (!bitstream_read_bit(bc)) { // Leaf
int val, i1, i2;
i1 = ctx->v1->table ? bitstream_read_vlc(bc, ctx->v1->table, SMKTREE_BITS, 3) : 0;
i2 = ctx->v2->table ? bitstream_read_vlc(bc, ctx->v2->table, SMKTREE_BITS, 3) : 0;
if (i1 < 0 || i2 < 0)
return AVERROR_INVALIDDATA;
val = ctx->recode1[i1] | (ctx->recode2[i2] << 8);
if(val == ctx->escapes[0]) {
ctx->last[0] = hc->current;
val = 0;
} else if(val == ctx->escapes[1]) {
ctx->last[1] = hc->current;
val = 0;
} else if(val == ctx->escapes[2]) {
ctx->last[2] = hc->current;
val = 0;
}
hc->values[hc->current++] = val;
return 1;
} else { //Node
int r = 0, r_new, t;
t = hc->current++;
r = smacker_decode_bigtree(bc, hc, ctx);
if(r < 0)
return r;
hc->values[t] = SMK_NODE | r;
r++;
r_new = smacker_decode_bigtree(bc, hc, ctx);
if (r_new < 0)
return r_new;
return r + r_new;
}
}
/**
* Store large tree as Libav's vlc codes
*/
static int smacker_decode_header_tree(SmackVContext *smk, BitstreamContext *bc,
int **recodes, int *last, int size)
{
int res;
HuffContext huff;
HuffContext tmp1, tmp2;
VLC vlc[2] = { { 0 } };
int escapes[3];
DBCtx ctx;
int err = 0;
if(size >= UINT_MAX>>4){ // (((size + 3) >> 2) + 3) << 2 must not overflow
av_log(smk->avctx, AV_LOG_ERROR, "size too large\n");
return AVERROR_INVALIDDATA;
}
tmp1.length = 256;
tmp1.maxlength = 0;
tmp1.current = 0;
tmp1.bits = av_mallocz(256 * 4);
tmp1.lengths = av_mallocz(256 * sizeof(int));
tmp1.values = av_mallocz(256 * sizeof(int));
tmp2.length = 256;
tmp2.maxlength = 0;
tmp2.current = 0;
tmp2.bits = av_mallocz(256 * 4);
tmp2.lengths = av_mallocz(256 * sizeof(int));
tmp2.values = av_mallocz(256 * sizeof(int));
if (!tmp1.bits || !tmp1.lengths || !tmp1.values ||
!tmp2.bits || !tmp2.lengths || !tmp2.values) {
err = AVERROR(ENOMEM);
goto error;
}
if (bitstream_read_bit(bc)) {
smacker_decode_tree(bc, &tmp1, 0, 0);
bitstream_skip(bc, 1);
res = init_vlc(&vlc[0], SMKTREE_BITS, tmp1.length,
tmp1.lengths, sizeof(int), sizeof(int),
tmp1.bits, sizeof(uint32_t), sizeof(uint32_t), INIT_VLC_LE);
if(res < 0) {
av_log(smk->avctx, AV_LOG_ERROR, "Cannot build VLC table\n");
err = res;
goto error;
}
} else {
av_log(smk->avctx, AV_LOG_ERROR, "Skipping low bytes tree\n");
}
if (bitstream_read_bit(bc)) {
smacker_decode_tree(bc, &tmp2, 0, 0);
bitstream_skip(bc, 1);
res = init_vlc(&vlc[1], SMKTREE_BITS, tmp2.length,
tmp2.lengths, sizeof(int), sizeof(int),
tmp2.bits, sizeof(uint32_t), sizeof(uint32_t), INIT_VLC_LE);
if(res < 0) {
av_log(smk->avctx, AV_LOG_ERROR, "Cannot build VLC table\n");
err = res;
goto error;
}
} else {
av_log(smk->avctx, AV_LOG_ERROR, "Skipping high bytes tree\n");
}
escapes[0] = bitstream_read(bc, 8);
escapes[0] |= bitstream_read(bc, 8) << 8;
escapes[1] = bitstream_read(bc, 8);
escapes[1] |= bitstream_read(bc, 8) << 8;
escapes[2] = bitstream_read(bc, 8);
escapes[2] |= bitstream_read(bc, 8) << 8;
last[0] = last[1] = last[2] = -1;
ctx.escapes[0] = escapes[0];
ctx.escapes[1] = escapes[1];
ctx.escapes[2] = escapes[2];
ctx.v1 = &vlc[0];
ctx.v2 = &vlc[1];
ctx.recode1 = tmp1.values;
ctx.recode2 = tmp2.values;
ctx.last = last;
huff.length = ((size + 3) >> 2) + 4;
huff.maxlength = 0;
huff.current = 0;
huff.values = av_mallocz(huff.length * sizeof(int));
if (!huff.values) {
err = AVERROR(ENOMEM);
goto error;
}
if ((res = smacker_decode_bigtree(bc, &huff, &ctx)) < 0)
err = res;
bitstream_skip(bc, 1);
if(ctx.last[0] == -1) ctx.last[0] = huff.current++;
if(ctx.last[1] == -1) ctx.last[1] = huff.current++;
if(ctx.last[2] == -1) ctx.last[2] = huff.current++;
if (ctx.last[0] >= huff.length ||
ctx.last[1] >= huff.length ||
ctx.last[2] >= huff.length) {
av_log(smk->avctx, AV_LOG_ERROR, "Huffman codes out of range\n");
err = AVERROR_INVALIDDATA;
}
*recodes = huff.values;
error:
if(vlc[0].table)
ff_free_vlc(&vlc[0]);
if(vlc[1].table)
ff_free_vlc(&vlc[1]);
av_free(tmp1.bits);
av_free(tmp1.lengths);
av_free(tmp1.values);
av_free(tmp2.bits);
av_free(tmp2.lengths);
av_free(tmp2.values);
return err;
}
static int decode_header_trees(SmackVContext *smk) {
BitstreamContext bc;
int mmap_size, mclr_size, full_size, type_size, ret;
mmap_size = AV_RL32(smk->avctx->extradata);
mclr_size = AV_RL32(smk->avctx->extradata + 4);
full_size = AV_RL32(smk->avctx->extradata + 8);
type_size = AV_RL32(smk->avctx->extradata + 12);
bitstream_init8(&bc, smk->avctx->extradata + 16, smk->avctx->extradata_size - 16);
if (!bitstream_read_bit(&bc)) {
av_log(smk->avctx, AV_LOG_INFO, "Skipping MMAP tree\n");
smk->mmap_tbl = av_malloc(sizeof(int) * 2);
if (!smk->mmap_tbl)
return AVERROR(ENOMEM);
smk->mmap_tbl[0] = 0;
smk->mmap_last[0] = smk->mmap_last[1] = smk->mmap_last[2] = 1;
} else {
if ((ret = smacker_decode_header_tree(smk, &bc, &smk->mmap_tbl, smk->mmap_last, mmap_size)) < 0)
return ret;
}
if (!bitstream_read_bit(&bc)) {
av_log(smk->avctx, AV_LOG_INFO, "Skipping MCLR tree\n");
smk->mclr_tbl = av_malloc(sizeof(int) * 2);
if (!smk->mclr_tbl)
return AVERROR(ENOMEM);
smk->mclr_tbl[0] = 0;
smk->mclr_last[0] = smk->mclr_last[1] = smk->mclr_last[2] = 1;
} else {
if ((ret = smacker_decode_header_tree(smk, &bc, &smk->mclr_tbl, smk->mclr_last, mclr_size)) < 0)
return ret;
}
if (!bitstream_read_bit(&bc)) {
av_log(smk->avctx, AV_LOG_INFO, "Skipping FULL tree\n");
smk->full_tbl = av_malloc(sizeof(int) * 2);
if (!smk->full_tbl)
return AVERROR(ENOMEM);
smk->full_tbl[0] = 0;
smk->full_last[0] = smk->full_last[1] = smk->full_last[2] = 1;
} else {
if ((ret = smacker_decode_header_tree(smk, &bc, &smk->full_tbl, smk->full_last, full_size)) < 0)
return ret;
}
if (!bitstream_read_bit(&bc)) {
av_log(smk->avctx, AV_LOG_INFO, "Skipping TYPE tree\n");
smk->type_tbl = av_malloc(sizeof(int) * 2);
if (!smk->type_tbl)
return AVERROR(ENOMEM);
smk->type_tbl[0] = 0;
smk->type_last[0] = smk->type_last[1] = smk->type_last[2] = 1;
} else {
if ((ret = smacker_decode_header_tree(smk, &bc, &smk->type_tbl, smk->type_last, type_size)) < 0)
return ret;
}
return 0;
}
static av_always_inline void last_reset(int *recode, int *last) {
recode[last[0]] = recode[last[1]] = recode[last[2]] = 0;
}
/* get code and update history */
static av_always_inline int smk_get_code(BitstreamContext *bc, int *recode,
int *last)
{
register int *table = recode;
int v;
while(*table & SMK_NODE) {
if (bitstream_read_bit(bc))
table += (*table) & (~SMK_NODE);
table++;
}
v = *table;
if(v != recode[last[0]]) {
recode[last[2]] = recode[last[1]];
recode[last[1]] = recode[last[0]];
recode[last[0]] = v;
}
return v;
}
static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
AVPacket *avpkt)
{
SmackVContext * const smk = avctx->priv_data;
uint8_t *out;
uint32_t *pal;
GetByteContext gb2;
BitstreamContext bc;
int blocks, blk, bw, bh;
int i, ret;
int stride;
int flags;
if (avpkt->size <= 769)
return 0;
if ((ret = ff_reget_buffer(avctx, smk->pic)) < 0) {
av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
return ret;
}
/* make the palette available on the way out */
pal = (uint32_t*)smk->pic->data[1];
bytestream2_init(&gb2, avpkt->data, avpkt->size);
flags = bytestream2_get_byteu(&gb2);
smk->pic->palette_has_changed = flags & 1;
smk->pic->key_frame = !!(flags & 2);
if(smk->pic->key_frame)
smk->pic->pict_type = AV_PICTURE_TYPE_I;
else
smk->pic->pict_type = AV_PICTURE_TYPE_P;
for(i = 0; i < 256; i++)
*pal++ = bytestream2_get_be24u(&gb2);
last_reset(smk->mmap_tbl, smk->mmap_last);
last_reset(smk->mclr_tbl, smk->mclr_last);
last_reset(smk->full_tbl, smk->full_last);
last_reset(smk->type_tbl, smk->type_last);
bitstream_init8(&bc, avpkt->data + 769, avpkt->size - 769);
blk = 0;
bw = avctx->width >> 2;
bh = avctx->height >> 2;
blocks = bw * bh;
out = smk->pic->data[0];
stride = smk->pic->linesize[0];
while(blk < blocks) {
int type, run, mode;
uint16_t pix;
type = smk_get_code(&bc, smk->type_tbl, smk->type_last);
run = block_runs[(type >> 2) & 0x3F];
switch(type & 3){
case SMK_BLK_MONO:
while(run-- && blk < blocks){
int clr, map;
int hi, lo;
clr = smk_get_code(&bc, smk->mclr_tbl, smk->mclr_last);
map = smk_get_code(&bc, smk->mmap_tbl, smk->mmap_last);
out = smk->pic->data[0] + (blk / bw) * (stride * 4) + (blk % bw) * 4;
hi = clr >> 8;
lo = clr & 0xFF;
for(i = 0; i < 4; i++) {
if(map & 1) out[0] = hi; else out[0] = lo;
if(map & 2) out[1] = hi; else out[1] = lo;
if(map & 4) out[2] = hi; else out[2] = lo;
if(map & 8) out[3] = hi; else out[3] = lo;
map >>= 4;
out += stride;
}
blk++;
}
break;
case SMK_BLK_FULL:
mode = 0;
if(avctx->codec_tag == MKTAG('S', 'M', 'K', '4')) { // In case of Smacker v4 we have three modes
if (bitstream_read_bit(&bc))
mode = 1;
else if (bitstream_read_bit(&bc))
mode = 2;
}
while(run-- && blk < blocks){
out = smk->pic->data[0] + (blk / bw) * (stride * 4) + (blk % bw) * 4;
switch(mode){
case 0:
for(i = 0; i < 4; i++) {
pix = smk_get_code(&bc, smk->full_tbl, smk->full_last);
AV_WL16(out+2,pix);
pix = smk_get_code(&bc, smk->full_tbl, smk->full_last);
AV_WL16(out,pix);
out += stride;
}
break;
case 1:
pix = smk_get_code(&bc, smk->full_tbl, smk->full_last);
out[0] = out[1] = pix & 0xFF;
out[2] = out[3] = pix >> 8;
out += stride;
out[0] = out[1] = pix & 0xFF;
out[2] = out[3] = pix >> 8;
out += stride;
pix = smk_get_code(&bc, smk->full_tbl, smk->full_last);
out[0] = out[1] = pix & 0xFF;
out[2] = out[3] = pix >> 8;
out += stride;
out[0] = out[1] = pix & 0xFF;
out[2] = out[3] = pix >> 8;
out += stride;
break;
case 2:
for(i = 0; i < 2; i++) {
uint16_t pix1, pix2;
pix2 = smk_get_code(&bc, smk->full_tbl, smk->full_last);
pix1 = smk_get_code(&bc, smk->full_tbl, smk->full_last);
AV_WL16(out,pix1);
AV_WL16(out+2,pix2);
out += stride;
AV_WL16(out,pix1);
AV_WL16(out+2,pix2);
out += stride;
}
break;
}
blk++;
}
break;
case SMK_BLK_SKIP:
while(run-- && blk < blocks)
blk++;
break;
case SMK_BLK_FILL:
mode = type >> 8;
while(run-- && blk < blocks){
uint32_t col;
out = smk->pic->data[0] + (blk / bw) * (stride * 4) + (blk % bw) * 4;
col = mode * 0x01010101;
for(i = 0; i < 4; i++) {
*((uint32_t*)out) = col;
out += stride;
}
blk++;
}
break;
}
}
if ((ret = av_frame_ref(data, smk->pic)) < 0)
return ret;
*got_frame = 1;
/* always report that the buffer was completely consumed */
return avpkt->size;
}
static av_cold int decode_end(AVCodecContext *avctx)
{
SmackVContext * const smk = avctx->priv_data;
av_freep(&smk->mmap_tbl);
av_freep(&smk->mclr_tbl);
av_freep(&smk->full_tbl);
av_freep(&smk->type_tbl);
av_frame_free(&smk->pic);
return 0;
}
static av_cold int decode_init(AVCodecContext *avctx)
{
SmackVContext * const c = avctx->priv_data;
int ret;
c->avctx = avctx;
avctx->pix_fmt = AV_PIX_FMT_PAL8;
c->pic = av_frame_alloc();
if (!c->pic)
return AVERROR(ENOMEM);
/* decode huffman trees from extradata */
if(avctx->extradata_size < 16){
av_log(avctx, AV_LOG_ERROR, "Extradata missing!\n");
return AVERROR_INVALIDDATA;
}
if ((ret = decode_header_trees(c))) {
decode_end(avctx);
return ret;
}
return 0;
}
static av_cold int smka_decode_init(AVCodecContext *avctx)
{
if (avctx->channels < 1 || avctx->channels > 2) {
av_log(avctx, AV_LOG_ERROR, "invalid number of channels\n");
return AVERROR_INVALIDDATA;
}
avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
avctx->sample_fmt = avctx->bits_per_coded_sample == 8 ? AV_SAMPLE_FMT_U8 : AV_SAMPLE_FMT_S16;
return 0;
}
/**
* Decode Smacker audio data
*/
static int smka_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame_ptr, AVPacket *avpkt)
{
AVFrame *frame = data;
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
BitstreamContext bc;
HuffContext h[4] = { { 0 } };
VLC vlc[4] = { { 0 } };
int16_t *samples;
uint8_t *samples8;
int val;
int i, res, ret;
int unp_size;
int bits, stereo;
int pred[2] = {0, 0};
if (buf_size <= 4) {
av_log(avctx, AV_LOG_ERROR, "packet is too small\n");
return AVERROR_INVALIDDATA;
}
unp_size = AV_RL32(buf);
bitstream_init8(&bc, buf + 4, buf_size - 4);
if (!bitstream_read_bit(&bc)) {
av_log(avctx, AV_LOG_INFO, "Sound: no data\n");
*got_frame_ptr = 0;
return 1;
}
stereo = bitstream_read_bit(&bc);
bits = bitstream_read_bit(&bc);
if (stereo ^ (avctx->channels != 1)) {
av_log(avctx, AV_LOG_ERROR, "channels mismatch\n");
return AVERROR_INVALIDDATA;
}
if (bits && avctx->sample_fmt == AV_SAMPLE_FMT_U8) {
av_log(avctx, AV_LOG_ERROR, "sample format mismatch\n");
return AVERROR_INVALIDDATA;
}
if (unp_size % (avctx->channels * (bits + 1))) {
av_log(avctx, AV_LOG_ERROR,
"The buffer does not contain an integer number of samples\n");
return AVERROR_INVALIDDATA;
}
/* get output buffer */
frame->nb_samples = unp_size / (avctx->channels * (bits + 1));
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
return ret;
}
samples = (int16_t *)frame->data[0];
samples8 = frame->data[0];
// Initialize
for(i = 0; i < (1 << (bits + stereo)); i++) {
h[i].length = 256;
h[i].maxlength = 0;
h[i].current = 0;
h[i].bits = av_mallocz(256 * 4);
h[i].lengths = av_mallocz(256 * sizeof(int));
h[i].values = av_mallocz(256 * sizeof(int));
if (!h[i].bits || !h[i].lengths || !h[i].values) {
ret = AVERROR(ENOMEM);
goto error;
}
bitstream_skip(&bc, 1);
if (smacker_decode_tree(&bc, &h[i], 0, 0) < 0) {
ret = AVERROR_INVALIDDATA;
goto error;
}
bitstream_skip(&bc, 1);
if(h[i].current > 1) {
res = init_vlc(&vlc[i], SMKTREE_BITS, h[i].length,
h[i].lengths, sizeof(int), sizeof(int),
h[i].bits, sizeof(uint32_t), sizeof(uint32_t), INIT_VLC_LE);
if(res < 0) {
av_log(avctx, AV_LOG_ERROR, "Cannot build VLC table\n");
ret = AVERROR_INVALIDDATA;
goto error;
}
}
}
/* this codec relies on wraparound instead of clipping audio */
if(bits) { //decode 16-bit data
for(i = stereo; i >= 0; i--)
pred[i] = sign_extend(av_bswap16(bitstream_read(&bc, 16)), 16);
for(i = 0; i <= stereo; i++)
*samples++ = pred[i];
for(; i < unp_size / 2; i++) {
if(i & stereo) {
if(vlc[2].table)
res = bitstream_read_vlc(&bc, vlc[2].table, SMKTREE_BITS, 3);
else
res = 0;
val = h[2].values[res];
if(vlc[3].table)
res = bitstream_read_vlc(&bc, vlc[3].table, SMKTREE_BITS, 3);
else
res = 0;
val |= h[3].values[res] << 8;
pred[1] += sign_extend(val, 16);
*samples++ = pred[1];
} else {
if(vlc[0].table)
res = bitstream_read_vlc(&bc, vlc[0].table, SMKTREE_BITS, 3);
else
res = 0;
val = h[0].values[res];
if(vlc[1].table)
res = bitstream_read_vlc(&bc, vlc[1].table, SMKTREE_BITS, 3);
else
res = 0;
val |= h[1].values[res] << 8;
pred[0] += sign_extend(val, 16);
*samples++ = pred[0];
}
}
} else { //8-bit data
for(i = stereo; i >= 0; i--)
pred[i] = bitstream_read(&bc, 8);
for(i = 0; i <= stereo; i++)
*samples8++ = pred[i];
for(; i < unp_size; i++) {
if(i & stereo){
if(vlc[1].table)
res = bitstream_read_vlc(&bc, vlc[1].table, SMKTREE_BITS, 3);
else
res = 0;
pred[1] += sign_extend(h[1].values[res], 8);
*samples8++ = pred[1];
} else {
if(vlc[0].table)
res = bitstream_read_vlc(&bc, vlc[0].table, SMKTREE_BITS, 3);
else
res = 0;
pred[0] += sign_extend(h[0].values[res], 8);
*samples8++ = pred[0];
}
}
}
*got_frame_ptr = 1;
ret = buf_size;
error:
for(i = 0; i < 4; i++) {
if(vlc[i].table)
ff_free_vlc(&vlc[i]);
av_free(h[i].bits);
av_free(h[i].lengths);
av_free(h[i].values);
}
return ret;
}
AVCodec ff_smacker_decoder = {
.name = "smackvid",
.long_name = NULL_IF_CONFIG_SMALL("Smacker video"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_SMACKVIDEO,
.priv_data_size = sizeof(SmackVContext),
.init = decode_init,
.close = decode_end,
.decode = decode_frame,
.capabilities = AV_CODEC_CAP_DR1,
};
AVCodec ff_smackaud_decoder = {
.name = "smackaud",
.long_name = NULL_IF_CONFIG_SMALL("Smacker audio"),
.type = AVMEDIA_TYPE_AUDIO,
.id = AV_CODEC_ID_SMACKAUDIO,
.init = smka_decode_init,
.decode = smka_decode_frame,
.capabilities = AV_CODEC_CAP_DR1,
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2933_0 |
crossvul-cpp_data_good_507_3 | /******************************************************************************
** Copyright (c) 2015-2018, Intel Corporation **
** All rights reserved. **
** **
** Redistribution and use in source and binary forms, with or without **
** modification, are permitted provided that the following conditions **
** are met: **
** 1. Redistributions of source code must retain the above copyright **
** notice, this list of conditions and the following disclaimer. **
** 2. Redistributions in binary form must reproduce the above copyright **
** notice, this list of conditions and the following disclaimer in the **
** documentation and/or other materials provided with the distribution. **
** 3. Neither the name of the copyright holder nor the names of its **
** contributors may be used to endorse or promote products derived **
** from this software without specific prior written permission. **
** **
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS **
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT **
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR **
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT **
** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, **
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED **
** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR **
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF **
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING **
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS **
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **
******************************************************************************/
/* Alexander Heinecke (Intel Corp.)
******************************************************************************/
/**
* @file
* This file is part of GemmCodeGenerator.
*
* @author Alexander Heinecke (alexander.heinecke AT mytum.de, http://www5.in.tum.de/wiki/index.php/Alexander_Heinecke,_M.Sc.,_M.Sc._with_honors)
*
* @section LICENSE
* Copyright (c) 2012-2014, Technische Universitaet Muenchen
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @section DESCRIPTION
* <DESCRIPTION>
*/
#include "generator_common.h"
#include "generator_spgemm_csc_reader.h"
#if defined(LIBXSMM_OFFLOAD_TARGET)
# pragma offload_attribute(push,target(LIBXSMM_OFFLOAD_TARGET))
#endif
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdio.h>
#if defined(LIBXSMM_OFFLOAD_TARGET)
# pragma offload_attribute(pop)
#endif
LIBXSMM_API_INTERN
void libxsmm_sparse_csc_reader( libxsmm_generated_code* io_generated_code,
const char* i_csc_file_in,
unsigned int** o_row_idx,
unsigned int** o_column_idx,
double** o_values,
unsigned int* o_row_count,
unsigned int* o_column_count,
unsigned int* o_element_count ) {
FILE *l_csc_file_handle;
const unsigned int l_line_length = 512;
char l_line[512/*l_line_length*/+1];
unsigned int l_header_read = 0;
unsigned int* l_column_idx_id = NULL;
unsigned int l_i = 0;
l_csc_file_handle = fopen( i_csc_file_in, "r" );
if ( l_csc_file_handle == NULL ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_INPUT );
return;
}
while (fgets(l_line, l_line_length, l_csc_file_handle) != NULL) {
if ( strlen(l_line) == l_line_length ) {
free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id);
*o_row_idx = 0; *o_column_idx = 0; *o_values = 0;
fclose( l_csc_file_handle ); /* close mtx file */
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_LEN );
return;
}
/* check if we are still reading comments header */
if ( l_line[0] == '%' ) {
continue;
} else {
/* if we are the first line after comment header, we allocate our data structures */
if ( l_header_read == 0 ) {
if (3 == sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) &&
0 != *o_row_count && 0 != *o_column_count && 0 != *o_element_count)
{
/* allocate CSC data structure matching mtx file */
*o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count));
*o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * ((size_t)(*o_column_count) + 1));
*o_values = (double*) malloc(sizeof(double) * (*o_element_count));
l_column_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_column_count));
/* check if mallocs were successful */
if ( ( *o_row_idx == NULL ) ||
( *o_column_idx == NULL ) ||
( *o_values == NULL ) ||
( l_column_idx_id == NULL ) ) {
free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id);
*o_row_idx = 0; *o_column_idx = 0; *o_values = 0;
fclose(l_csc_file_handle); /* close mtx file */
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_ALLOC_DATA );
return;
}
/* set everything to zero for init */
memset(*o_row_idx, 0, sizeof(unsigned int) * (*o_element_count));
memset(*o_column_idx, 0, sizeof(unsigned int) * ((size_t)(*o_column_count) + 1));
memset(*o_values, 0, sizeof(double) * (*o_element_count));
memset(l_column_idx_id, 0, sizeof(unsigned int) * (*o_column_count));
/* init column idx */
for (l_i = 0; l_i <= *o_column_count; ++l_i) {
(*o_column_idx)[l_i] = *o_element_count;
}
/* init */
(*o_column_idx)[0] = 0;
l_i = 0;
l_header_read = 1;
} else {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_DESC );
fclose( l_csc_file_handle ); /* close mtx file */
return;
}
/* now we read the actual content */
} else {
unsigned int l_row = 0, l_column = 0;
double l_value = 0;
/* read a line of content */
if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) {
free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id);
*o_row_idx = 0; *o_column_idx = 0; *o_values = 0;
fclose(l_csc_file_handle); /* close mtx file */
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_ELEMS );
return;
}
/* adjust numbers to zero termination */
LIBXSMM_ASSERT(0 != l_row && 0 != l_column);
l_row--; l_column--;
/* add these values to row and value structure */
(*o_row_idx)[l_i] = l_row;
(*o_values)[l_i] = l_value;
l_i++;
/* handle columns, set id to own for this column, yeah we need to handle empty columns */
l_column_idx_id[l_column] = 1;
(*o_column_idx)[l_column+1] = l_i;
}
}
}
/* close mtx file */
fclose( l_csc_file_handle );
/* check if we read a file which was consistent */
if ( l_i != (*o_element_count) ) {
free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id);
*o_row_idx = 0; *o_column_idx = 0; *o_values = 0;
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_LEN );
return;
}
if ( l_column_idx_id != NULL ) {
/* let's handle empty columns */
for ( l_i = 0; l_i < (*o_column_count); l_i++) {
if ( l_column_idx_id[l_i] == 0 ) {
(*o_column_idx)[l_i+1] = (*o_column_idx)[l_i];
}
}
/* free helper data structure */
free( l_column_idx_id );
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_507_3 |
crossvul-cpp_data_bad_341_7 | /*
* sc.c: General functions
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
#ifdef ENABLE_OPENSSL
#include <openssl/crypto.h> /* for OPENSSL_cleanse */
#endif
#include "internal.h"
#ifdef PACKAGE_VERSION
static const char *sc_version = PACKAGE_VERSION;
#else
static const char *sc_version = "(undef)";
#endif
const char *sc_get_version(void)
{
return sc_version;
}
int sc_hex_to_bin(const char *in, u8 *out, size_t *outlen)
{
int err = SC_SUCCESS;
size_t left, count = 0, in_len;
if (in == NULL || out == NULL || outlen == NULL) {
return SC_ERROR_INVALID_ARGUMENTS;
}
left = *outlen;
in_len = strlen(in);
while (*in != '\0') {
int byte = 0, nybbles = 2;
while (nybbles-- && *in && *in != ':' && *in != ' ') {
char c;
byte <<= 4;
c = *in++;
if ('0' <= c && c <= '9')
c -= '0';
else
if ('a' <= c && c <= 'f')
c = c - 'a' + 10;
else
if ('A' <= c && c <= 'F')
c = c - 'A' + 10;
else {
err = SC_ERROR_INVALID_ARGUMENTS;
goto out;
}
byte |= c;
}
/* Detect premature end of string before byte is complete */
if (in_len > 1 && *in == '\0' && nybbles >= 0) {
err = SC_ERROR_INVALID_ARGUMENTS;
break;
}
if (*in == ':' || *in == ' ')
in++;
if (left <= 0) {
err = SC_ERROR_BUFFER_TOO_SMALL;
break;
}
out[count++] = (u8) byte;
left--;
}
out:
*outlen = count;
return err;
}
int sc_bin_to_hex(const u8 *in, size_t in_len, char *out, size_t out_len,
int in_sep)
{
unsigned int n, sep_len;
char *pos, *end, sep;
sep = (char)in_sep;
sep_len = sep > 0 ? 1 : 0;
pos = out;
end = out + out_len;
for (n = 0; n < in_len; n++) {
if (pos + 3 + sep_len >= end)
return SC_ERROR_BUFFER_TOO_SMALL;
if (n && sep_len)
*pos++ = sep;
sprintf(pos, "%02x", in[n]);
pos += 2;
}
*pos = '\0';
return SC_SUCCESS;
}
/*
* Right trim all non-printable characters
*/
size_t sc_right_trim(u8 *buf, size_t len) {
size_t i;
if (!buf)
return 0;
if (len > 0) {
for(i = len-1; i > 0; i--) {
if(!isprint(buf[i])) {
buf[i] = '\0';
len--;
continue;
}
break;
}
}
return len;
}
u8 *ulong2bebytes(u8 *buf, unsigned long x)
{
if (buf != NULL) {
buf[3] = (u8) (x & 0xff);
buf[2] = (u8) ((x >> 8) & 0xff);
buf[1] = (u8) ((x >> 16) & 0xff);
buf[0] = (u8) ((x >> 24) & 0xff);
}
return buf;
}
u8 *ushort2bebytes(u8 *buf, unsigned short x)
{
if (buf != NULL) {
buf[1] = (u8) (x & 0xff);
buf[0] = (u8) ((x >> 8) & 0xff);
}
return buf;
}
unsigned long bebytes2ulong(const u8 *buf)
{
if (buf == NULL)
return 0UL;
return (unsigned long) (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]);
}
unsigned short bebytes2ushort(const u8 *buf)
{
if (buf == NULL)
return 0U;
return (unsigned short) (buf[0] << 8 | buf[1]);
}
unsigned short lebytes2ushort(const u8 *buf)
{
if (buf == NULL)
return 0U;
return (unsigned short)buf[1] << 8 | (unsigned short)buf[0];
}
void sc_init_oid(struct sc_object_id *oid)
{
int ii;
if (!oid)
return;
for (ii=0; ii<SC_MAX_OBJECT_ID_OCTETS; ii++)
oid->value[ii] = -1;
}
int sc_format_oid(struct sc_object_id *oid, const char *in)
{
int ii, ret = SC_ERROR_INVALID_ARGUMENTS;
const char *p;
char *q;
if (oid == NULL || in == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
sc_init_oid(oid);
p = in;
for (ii=0; ii < SC_MAX_OBJECT_ID_OCTETS; ii++) {
oid->value[ii] = strtol(p, &q, 10);
if (!*q)
break;
if (!(q[0] == '.' && isdigit(q[1])))
goto out;
p = q + 1;
}
if (!sc_valid_oid(oid))
goto out;
ret = SC_SUCCESS;
out:
if (ret)
sc_init_oid(oid);
return ret;
}
int sc_compare_oid(const struct sc_object_id *oid1, const struct sc_object_id *oid2)
{
int i;
if (oid1 == NULL || oid2 == NULL) {
return SC_ERROR_INVALID_ARGUMENTS;
}
for (i = 0; i < SC_MAX_OBJECT_ID_OCTETS; i++) {
if (oid1->value[i] != oid2->value[i])
return 0;
if (oid1->value[i] == -1)
break;
}
return 1;
}
int sc_valid_oid(const struct sc_object_id *oid)
{
int ii;
if (!oid)
return 0;
if (oid->value[0] == -1 || oid->value[1] == -1)
return 0;
if (oid->value[0] > 2 || oid->value[1] > 39)
return 0;
for (ii=0;ii<SC_MAX_OBJECT_ID_OCTETS;ii++)
if (oid->value[ii])
break;
if (ii==SC_MAX_OBJECT_ID_OCTETS)
return 0;
return 1;
}
int sc_detect_card_presence(sc_reader_t *reader)
{
int r;
LOG_FUNC_CALLED(reader->ctx);
if (reader->ops->detect_card_presence == NULL)
LOG_FUNC_RETURN(reader->ctx, SC_ERROR_NOT_SUPPORTED);
r = reader->ops->detect_card_presence(reader);
LOG_FUNC_RETURN(reader->ctx, r);
}
int sc_path_set(sc_path_t *path, int type, const u8 *id, size_t id_len,
int idx, int count)
{
if (path == NULL || id == NULL || id_len == 0 || id_len > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memset(path, 0, sizeof(*path));
memcpy(path->value, id, id_len);
path->len = id_len;
path->type = type;
path->index = idx;
path->count = count;
return SC_SUCCESS;
}
void sc_format_path(const char *str, sc_path_t *path)
{
int type = SC_PATH_TYPE_PATH;
if (path) {
memset(path, 0, sizeof(*path));
if (*str == 'i' || *str == 'I') {
type = SC_PATH_TYPE_FILE_ID;
str++;
}
path->len = sizeof(path->value);
if (sc_hex_to_bin(str, path->value, &path->len) >= 0) {
path->type = type;
}
path->count = -1;
}
}
int sc_append_path(sc_path_t *dest, const sc_path_t *src)
{
return sc_concatenate_path(dest, dest, src);
}
int sc_append_path_id(sc_path_t *dest, const u8 *id, size_t idlen)
{
if (dest->len + idlen > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memcpy(dest->value + dest->len, id, idlen);
dest->len += idlen;
return SC_SUCCESS;
}
int sc_append_file_id(sc_path_t *dest, unsigned int fid)
{
u8 id[2] = { fid >> 8, fid & 0xff };
return sc_append_path_id(dest, id, 2);
}
int sc_concatenate_path(sc_path_t *d, const sc_path_t *p1, const sc_path_t *p2)
{
sc_path_t tpath;
if (d == NULL || p1 == NULL || p2 == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (p1->type == SC_PATH_TYPE_DF_NAME || p2->type == SC_PATH_TYPE_DF_NAME)
/* we do not support concatenation of AIDs at the moment */
return SC_ERROR_NOT_SUPPORTED;
if (p1->len + p2->len > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memset(&tpath, 0, sizeof(sc_path_t));
memcpy(tpath.value, p1->value, p1->len);
memcpy(tpath.value + p1->len, p2->value, p2->len);
tpath.len = p1->len + p2->len;
tpath.type = SC_PATH_TYPE_PATH;
/* use 'index' and 'count' entry of the second path object */
tpath.index = p2->index;
tpath.count = p2->count;
/* the result is currently always as path */
tpath.type = SC_PATH_TYPE_PATH;
*d = tpath;
return SC_SUCCESS;
}
const char *sc_print_path(const sc_path_t *path)
{
static char buffer[SC_MAX_PATH_STRING_SIZE + SC_MAX_AID_STRING_SIZE];
if (sc_path_print(buffer, sizeof(buffer), path) != SC_SUCCESS)
buffer[0] = '\0';
return buffer;
}
int sc_path_print(char *buf, size_t buflen, const sc_path_t *path)
{
size_t i;
if (buf == NULL || path == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (buflen < path->len * 2 + path->aid.len * 2 + 1)
return SC_ERROR_BUFFER_TOO_SMALL;
buf[0] = '\0';
if (path->aid.len) {
for (i = 0; i < path->aid.len; i++)
snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->aid.value[i]);
snprintf(buf + strlen(buf), buflen - strlen(buf), "::");
}
for (i = 0; i < path->len; i++)
snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->value[i]);
if (!path->aid.len && path->type == SC_PATH_TYPE_DF_NAME)
snprintf(buf + strlen(buf), buflen - strlen(buf), "::");
return SC_SUCCESS;
}
int sc_compare_path(const sc_path_t *path1, const sc_path_t *path2)
{
return path1->len == path2->len
&& !memcmp(path1->value, path2->value, path1->len);
}
int sc_compare_path_prefix(const sc_path_t *prefix, const sc_path_t *path)
{
sc_path_t tpath;
if (prefix->len > path->len)
return 0;
tpath = *path;
tpath.len = prefix->len;
return sc_compare_path(&tpath, prefix);
}
const sc_path_t *sc_get_mf_path(void)
{
static const sc_path_t mf_path = {
{0x3f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 2,
0,
0,
SC_PATH_TYPE_PATH,
{{0},0}
};
return &mf_path;
}
int sc_file_add_acl_entry(sc_file_t *file, unsigned int operation,
unsigned int method, unsigned long key_ref)
{
sc_acl_entry_t *p, *_new;
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return SC_ERROR_INVALID_ARGUMENTS;
}
switch (method) {
case SC_AC_NEVER:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 1;
return SC_SUCCESS;
case SC_AC_NONE:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 2;
return SC_SUCCESS;
case SC_AC_UNKNOWN:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 3;
return SC_SUCCESS;
default:
/* NONE and UNKNOWN get zapped when a new AC is added.
* If the ACL is NEVER, additional entries will be
* dropped silently. */
if (file->acl[operation] == (sc_acl_entry_t *) 1)
return SC_SUCCESS;
if (file->acl[operation] == (sc_acl_entry_t *) 2
|| file->acl[operation] == (sc_acl_entry_t *) 3)
file->acl[operation] = NULL;
}
/* If the entry is already present (e.g. due to the mapping)
* of the card's AC with OpenSC's), don't add it again. */
for (p = file->acl[operation]; p != NULL; p = p->next) {
if ((p->method == method) && (p->key_ref == key_ref))
return SC_SUCCESS;
}
_new = malloc(sizeof(sc_acl_entry_t));
if (_new == NULL)
return SC_ERROR_OUT_OF_MEMORY;
_new->method = method;
_new->key_ref = key_ref;
_new->next = NULL;
p = file->acl[operation];
if (p == NULL) {
file->acl[operation] = _new;
return SC_SUCCESS;
}
while (p->next != NULL)
p = p->next;
p->next = _new;
return SC_SUCCESS;
}
const sc_acl_entry_t * sc_file_get_acl_entry(const sc_file_t *file,
unsigned int operation)
{
sc_acl_entry_t *p;
static const sc_acl_entry_t e_never = {
SC_AC_NEVER, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
static const sc_acl_entry_t e_none = {
SC_AC_NONE, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
static const sc_acl_entry_t e_unknown = {
SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return NULL;
}
p = file->acl[operation];
if (p == (sc_acl_entry_t *) 1)
return &e_never;
if (p == (sc_acl_entry_t *) 2)
return &e_none;
if (p == (sc_acl_entry_t *) 3)
return &e_unknown;
return file->acl[operation];
}
void sc_file_clear_acl_entries(sc_file_t *file, unsigned int operation)
{
sc_acl_entry_t *e;
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return;
}
e = file->acl[operation];
if (e == (sc_acl_entry_t *) 1 ||
e == (sc_acl_entry_t *) 2 ||
e == (sc_acl_entry_t *) 3) {
file->acl[operation] = NULL;
return;
}
while (e != NULL) {
sc_acl_entry_t *tmp = e->next;
free(e);
e = tmp;
}
file->acl[operation] = NULL;
}
sc_file_t * sc_file_new(void)
{
sc_file_t *file = (sc_file_t *)calloc(1, sizeof(sc_file_t));
if (file == NULL)
return NULL;
file->magic = SC_FILE_MAGIC;
return file;
}
void sc_file_free(sc_file_t *file)
{
unsigned int i;
if (file == NULL || !sc_file_valid(file))
return;
file->magic = 0;
for (i = 0; i < SC_MAX_AC_OPS; i++)
sc_file_clear_acl_entries(file, i);
if (file->sec_attr)
free(file->sec_attr);
if (file->prop_attr)
free(file->prop_attr);
if (file->type_attr)
free(file->type_attr);
if (file->encoded_content)
free(file->encoded_content);
free(file);
}
void sc_file_dup(sc_file_t **dest, const sc_file_t *src)
{
sc_file_t *newf;
const sc_acl_entry_t *e;
unsigned int op;
*dest = NULL;
if (!sc_file_valid(src))
return;
newf = sc_file_new();
if (newf == NULL)
return;
*dest = newf;
memcpy(&newf->path, &src->path, sizeof(struct sc_path));
memcpy(&newf->name, &src->name, sizeof(src->name));
newf->namelen = src->namelen;
newf->type = src->type;
newf->shareable = src->shareable;
newf->ef_structure = src->ef_structure;
newf->size = src->size;
newf->id = src->id;
newf->status = src->status;
for (op = 0; op < SC_MAX_AC_OPS; op++) {
newf->acl[op] = NULL;
e = sc_file_get_acl_entry(src, op);
if (e != NULL) {
if (sc_file_add_acl_entry(newf, op, e->method, e->key_ref) < 0)
goto err;
}
}
newf->record_length = src->record_length;
newf->record_count = src->record_count;
if (sc_file_set_sec_attr(newf, src->sec_attr, src->sec_attr_len) < 0)
goto err;
if (sc_file_set_prop_attr(newf, src->prop_attr, src->prop_attr_len) < 0)
goto err;
if (sc_file_set_type_attr(newf, src->type_attr, src->type_attr_len) < 0)
goto err;
if (sc_file_set_content(newf, src->encoded_content, src->encoded_content_len) < 0)
goto err;
return;
err:
sc_file_free(newf);
*dest = NULL;
}
int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,
size_t sec_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (sec_attr == NULL) {
if (file->sec_attr != NULL)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return 0;
}
tmp = (u8 *) realloc(file->sec_attr, sec_attr_len);
if (!tmp) {
if (file->sec_attr)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->sec_attr = tmp;
memcpy(file->sec_attr, sec_attr, sec_attr_len);
file->sec_attr_len = sec_attr_len;
return 0;
}
int sc_file_set_prop_attr(sc_file_t *file, const u8 *prop_attr,
size_t prop_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (prop_attr == NULL) {
if (file->prop_attr != NULL)
free(file->prop_attr);
file->prop_attr = NULL;
file->prop_attr_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->prop_attr, prop_attr_len);
if (!tmp) {
if (file->prop_attr)
free(file->prop_attr);
file->prop_attr = NULL;
file->prop_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->prop_attr = tmp;
memcpy(file->prop_attr, prop_attr, prop_attr_len);
file->prop_attr_len = prop_attr_len;
return SC_SUCCESS;
}
int sc_file_set_type_attr(sc_file_t *file, const u8 *type_attr,
size_t type_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (type_attr == NULL) {
if (file->type_attr != NULL)
free(file->type_attr);
file->type_attr = NULL;
file->type_attr_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->type_attr, type_attr_len);
if (!tmp) {
if (file->type_attr)
free(file->type_attr);
file->type_attr = NULL;
file->type_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->type_attr = tmp;
memcpy(file->type_attr, type_attr, type_attr_len);
file->type_attr_len = type_attr_len;
return SC_SUCCESS;
}
int sc_file_set_content(sc_file_t *file, const u8 *content,
size_t content_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (content == NULL) {
if (file->encoded_content != NULL)
free(file->encoded_content);
file->encoded_content = NULL;
file->encoded_content_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->encoded_content, content_len);
if (!tmp) {
if (file->encoded_content)
free(file->encoded_content);
file->encoded_content = NULL;
file->encoded_content_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->encoded_content = tmp;
memcpy(file->encoded_content, content, content_len);
file->encoded_content_len = content_len;
return SC_SUCCESS;
}
int sc_file_valid(const sc_file_t *file) {
if (file == NULL)
return 0;
return file->magic == SC_FILE_MAGIC;
}
int _sc_parse_atr(sc_reader_t *reader)
{
u8 *p = reader->atr.value;
int atr_len = (int) reader->atr.len;
int n_hist, x;
int tx[4] = {-1, -1, -1, -1};
int i, FI, DI;
const int Fi_table[] = {
372, 372, 558, 744, 1116, 1488, 1860, -1,
-1, 512, 768, 1024, 1536, 2048, -1, -1 };
const int f_table[] = {
40, 50, 60, 80, 120, 160, 200, -1,
-1, 50, 75, 100, 150, 200, -1, -1 };
const int Di_table[] = {
-1, 1, 2, 4, 8, 16, 32, -1,
12, 20, -1, -1, -1, -1, -1, -1 };
reader->atr_info.hist_bytes_len = 0;
reader->atr_info.hist_bytes = NULL;
if (atr_len == 0) {
sc_log(reader->ctx, "empty ATR - card not present?\n");
return SC_ERROR_INTERNAL;
}
if (p[0] != 0x3B && p[0] != 0x3F) {
sc_log(reader->ctx, "invalid sync byte in ATR: 0x%02X\n", p[0]);
return SC_ERROR_INTERNAL;
}
n_hist = p[1] & 0x0F;
x = p[1] >> 4;
p += 2;
atr_len -= 2;
for (i = 0; i < 4 && atr_len > 0; i++) {
if (x & (1 << i)) {
tx[i] = *p;
p++;
atr_len--;
} else
tx[i] = -1;
}
if (tx[0] >= 0) {
reader->atr_info.FI = FI = tx[0] >> 4;
reader->atr_info.DI = DI = tx[0] & 0x0F;
reader->atr_info.Fi = Fi_table[FI];
reader->atr_info.f = f_table[FI];
reader->atr_info.Di = Di_table[DI];
} else {
reader->atr_info.Fi = -1;
reader->atr_info.f = -1;
reader->atr_info.Di = -1;
}
if (tx[2] >= 0)
reader->atr_info.N = tx[3];
else
reader->atr_info.N = -1;
while (tx[3] > 0 && tx[3] & 0xF0 && atr_len > 0) {
x = tx[3] >> 4;
for (i = 0; i < 4 && atr_len > 0; i++) {
if (x & (1 << i)) {
tx[i] = *p;
p++;
atr_len--;
} else
tx[i] = -1;
}
}
if (atr_len <= 0)
return SC_SUCCESS;
if (n_hist > atr_len)
n_hist = atr_len;
reader->atr_info.hist_bytes_len = n_hist;
reader->atr_info.hist_bytes = p;
return SC_SUCCESS;
}
void sc_mem_clear(void *ptr, size_t len)
{
if (len > 0) {
#ifdef ENABLE_OPENSSL
OPENSSL_cleanse(ptr, len);
#else
memset(ptr, 0, len);
#endif
}
}
int sc_mem_reverse(unsigned char *buf, size_t len)
{
unsigned char ch;
size_t ii;
if (!buf || !len)
return SC_ERROR_INVALID_ARGUMENTS;
for (ii = 0; ii < len / 2; ii++) {
ch = *(buf + ii);
*(buf + ii) = *(buf + len - 1 - ii);
*(buf + len - 1 - ii) = ch;
}
return SC_SUCCESS;
}
static int
sc_remote_apdu_allocate(struct sc_remote_data *rdata,
struct sc_remote_apdu **new_rapdu)
{
struct sc_remote_apdu *rapdu = NULL, *rr;
if (!rdata)
return SC_ERROR_INVALID_ARGUMENTS;
rapdu = calloc(1, sizeof(struct sc_remote_apdu));
if (rapdu == NULL)
return SC_ERROR_OUT_OF_MEMORY;
rapdu->apdu.data = &rapdu->sbuf[0];
rapdu->apdu.resp = &rapdu->rbuf[0];
rapdu->apdu.resplen = sizeof(rapdu->rbuf);
if (new_rapdu)
*new_rapdu = rapdu;
if (rdata->data == NULL) {
rdata->data = rapdu;
rdata->length = 1;
return SC_SUCCESS;
}
for (rr = rdata->data; rr->next; rr = rr->next)
;
rr->next = rapdu;
rdata->length++;
return SC_SUCCESS;
}
static void
sc_remote_apdu_free (struct sc_remote_data *rdata)
{
struct sc_remote_apdu *rapdu = NULL;
if (!rdata)
return;
rapdu = rdata->data;
while(rapdu) {
struct sc_remote_apdu *rr = rapdu->next;
free(rapdu);
rapdu = rr;
}
}
void sc_remote_data_init(struct sc_remote_data *rdata)
{
if (!rdata)
return;
memset(rdata, 0, sizeof(struct sc_remote_data));
rdata->alloc = sc_remote_apdu_allocate;
rdata->free = sc_remote_apdu_free;
}
static unsigned long sc_CRC_tab32[256];
static int sc_CRC_tab32_initialized = 0;
unsigned sc_crc32(const unsigned char *value, size_t len)
{
size_t ii, jj;
unsigned long crc;
unsigned long index, long_c;
if (!sc_CRC_tab32_initialized) {
for (ii=0; ii<256; ii++) {
crc = (unsigned long) ii;
for (jj=0; jj<8; jj++) {
if ( crc & 0x00000001L )
crc = ( crc >> 1 ) ^ 0xEDB88320l;
else
crc = crc >> 1;
}
sc_CRC_tab32[ii] = crc;
}
sc_CRC_tab32_initialized = 1;
}
crc = 0xffffffffL;
for (ii=0; ii<len; ii++) {
long_c = 0x000000ffL & (unsigned long) (*(value + ii));
index = crc ^ long_c;
crc = (crc >> 8) ^ sc_CRC_tab32[ index & 0xff ];
}
crc ^= 0xffffffff;
return crc%0xffff;
}
const u8 *sc_compacttlv_find_tag(const u8 *buf, size_t len, u8 tag, size_t *outlen)
{
if (buf != NULL) {
size_t idx;
u8 plain_tag = tag & 0xF0;
size_t expected_len = tag & 0x0F;
for (idx = 0; idx < len; idx++) {
if ((buf[idx] & 0xF0) == plain_tag && idx + expected_len < len &&
(expected_len == 0 || expected_len == (buf[idx] & 0x0F))) {
if (outlen != NULL)
*outlen = buf[idx] & 0x0F;
return buf + (idx + 1);
}
idx += (buf[idx] & 0x0F);
}
}
return NULL;
}
/**************************** mutex functions ************************/
int sc_mutex_create(const sc_context_t *ctx, void **mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->create_mutex != NULL)
return ctx->thread_ctx->create_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_lock(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->lock_mutex != NULL)
return ctx->thread_ctx->lock_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_unlock(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->unlock_mutex != NULL)
return ctx->thread_ctx->unlock_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_destroy(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->destroy_mutex != NULL)
return ctx->thread_ctx->destroy_mutex(mutex);
else
return SC_SUCCESS;
}
unsigned long sc_thread_id(const sc_context_t *ctx)
{
if (ctx == NULL || ctx->thread_ctx == NULL ||
ctx->thread_ctx->thread_id == NULL)
return 0UL;
else
return ctx->thread_ctx->thread_id();
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_341_7 |
crossvul-cpp_data_bad_2131_4 | /*
* HID driver for some petalynx "special" devices
*
* Copyright (c) 1999 Andreas Gal
* Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz>
* Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc
* Copyright (c) 2006-2007 Jiri Kosina
* Copyright (c) 2008 Jiri Slaby
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*/
#include <linux/device.h>
#include <linux/hid.h>
#include <linux/module.h>
#include "hid-ids.h"
/* Petalynx Maxter Remote has maximum for consumer page set too low */
static __u8 *pl_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
if (*rsize >= 60 && rdesc[39] == 0x2a && rdesc[40] == 0xf5 &&
rdesc[41] == 0x00 && rdesc[59] == 0x26 &&
rdesc[60] == 0xf9 && rdesc[61] == 0x00) {
hid_info(hdev, "fixing up Petalynx Maxter Remote report descriptor\n");
rdesc[60] = 0xfa;
rdesc[40] = 0xfa;
}
return rdesc;
}
#define pl_map_key_clear(c) hid_map_usage_clear(hi, usage, bit, max, \
EV_KEY, (c))
static int pl_input_mapping(struct hid_device *hdev, struct hid_input *hi,
struct hid_field *field, struct hid_usage *usage,
unsigned long **bit, int *max)
{
if ((usage->hid & HID_USAGE_PAGE) == HID_UP_LOGIVENDOR) {
switch (usage->hid & HID_USAGE) {
case 0x05a: pl_map_key_clear(KEY_TEXT); break;
case 0x05b: pl_map_key_clear(KEY_RED); break;
case 0x05c: pl_map_key_clear(KEY_GREEN); break;
case 0x05d: pl_map_key_clear(KEY_YELLOW); break;
case 0x05e: pl_map_key_clear(KEY_BLUE); break;
default:
return 0;
}
return 1;
}
if ((usage->hid & HID_USAGE_PAGE) == HID_UP_CONSUMER) {
switch (usage->hid & HID_USAGE) {
case 0x0f6: pl_map_key_clear(KEY_NEXT); break;
case 0x0fa: pl_map_key_clear(KEY_BACK); break;
default:
return 0;
}
return 1;
}
return 0;
}
static int pl_probe(struct hid_device *hdev, const struct hid_device_id *id)
{
int ret;
hdev->quirks |= HID_QUIRK_NOGET;
ret = hid_parse(hdev);
if (ret) {
hid_err(hdev, "parse failed\n");
goto err_free;
}
ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT);
if (ret) {
hid_err(hdev, "hw start failed\n");
goto err_free;
}
return 0;
err_free:
return ret;
}
static const struct hid_device_id pl_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_PETALYNX, USB_DEVICE_ID_PETALYNX_MAXTER_REMOTE) },
{ }
};
MODULE_DEVICE_TABLE(hid, pl_devices);
static struct hid_driver pl_driver = {
.name = "petalynx",
.id_table = pl_devices,
.report_fixup = pl_report_fixup,
.input_mapping = pl_input_mapping,
.probe = pl_probe,
};
module_hid_driver(pl_driver);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2131_4 |
crossvul-cpp_data_good_503_0 | /* radare - LGPL - Copyright 2015-2018 - pancake */
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <r_util.h>
typedef enum optype_t {
ARM_NOTYPE = -1,
ARM_GPR = 1,
ARM_CONSTANT = 2,
ARM_FP = 4,
ARM_MEM_OPT = 8
} OpType;
typedef enum regtype_t {
ARM_UNDEFINED = -1,
ARM_REG64 = 1,
ARM_REG32 = 2,
ARM_SP = 4,
ARM_PC = 8,
ARM_SIMD = 16
} RegType;
typedef enum shifttype_t {
ARM_NO_SHIFT = -1,
ARM_LSL = 0,
ARM_LSR = 1,
ARM_ASR = 2
} ShiftType;
typedef struct operand_t {
OpType type;
union {
struct {
int reg;
RegType reg_type;
ut16 sp_val;
};
struct {
ut64 immediate;
int sign;
};
struct {
ut64 shift_amount;
ShiftType shift;
};
struct {
ut32 mem_option;
};
};
} Operand;
#define MAX_OPERANDS 7
typedef struct Opcode_t {
char *mnemonic;
ut32 op[3];
size_t op_len;
ut8 opcode[3];
int operands_count;
Operand operands[MAX_OPERANDS];
} ArmOp;
static int get_mem_option(char *token) {
// values 4, 8, 12, are unused. XXX to adjust
const char *options[] = {"sy", "st", "ld", "xxx", "ish", "ishst",
"ishld", "xxx", "nsh", "nshst", "nshld",
"xxx", "osh", "oshst", "oshld", NULL};
int i = 0;
while (options[i]) {
if (!r_str_casecmp (token, options[i])) {
return 15 - i;
}
i++;
}
return -1;
}
static int countLeadingZeros(ut32 x) {
int count = 0;
while (x) {
x >>= 1;
--count;
}
return count;
}
static int countTrailingZeros(ut32 x) {
int count = 0;
while (x > 0) {
if ((x & 1) == 1) {
break;
} else {
count ++;
x = x >> 1;
}
}
return count;
}
static int calcNegOffset(int n, int shift) {
int a = n >> shift;
if (a == 0) {
return 0xff;
}
// find first set bit then invert it and all
// bits below it
int t = 0x400;
while (!(t & a) && a != 0 && t != 0) {
t = t >> 1;
}
t = t & (t - 1);
a = a ^ t;
// If bits below 32 are set
if (countTrailingZeros(n) > shift) {
a--;
}
return 0xff & (0xff - a);
}
static int countLeadingOnes(ut32 x) {
return countLeadingZeros (~x);
}
static int countTrailingOnes(ut32 x) {
return countTrailingZeros (~x);
}
static bool isMask(ut32 value) {
return value && ((value + 1) & value) == 0;
}
static bool isShiftedMask (ut32 value) {
return value && isMask ((value - 1) | value);
}
static ut32 decodeBitMasks(ut32 imm) {
// get element size
int size = 32;
// determine rot to make element be 0^m 1^n
ut32 cto, i;
ut32 mask = ((ut64) - 1LL) >> (64 - size);
if (isShiftedMask (imm)) {
i = countTrailingZeros (imm);
cto = countTrailingOnes (imm >> i);
} else {
imm |= ~mask;
if (!isShiftedMask (imm)) {
return UT32_MAX;
}
ut32 clo = countLeadingOnes (imm);
i = 64 - clo;
cto = clo + countTrailingOnes (imm) - (64 - size);
}
// Encode in Immr the number of RORs it would take to get *from* 0^m 1^n
// to our target value, where I is the number of RORs to go the opposite
// direction
ut32 immr = (size - i) & (size - 1);
// If size has a 1 in the n'th bit, create a value that has zeroes in
// bits [0, n] and ones above that.
ut64 nimms = ~(size - 1) << 1;
// Or the cto value into the low bits, which must be below the Nth bit
// bit mentioned above.
nimms |= (cto - 1);
// Extract and toggle seventh bit to make N field.
ut32 n = ((nimms >> 6) & 1) ^ 1;
ut64 encoding = (n << 12) | (immr << 6) | (nimms & 0x3f);
return encoding;
}
static ut32 mov(ArmOp *op) {
int k = 0;
ut32 data = UT32_MAX;
if (!strncmp (op->mnemonic, "movz", 4)) {
if (op->operands[0].reg_type & ARM_REG64) {
k = 0x80d2;
} else if (op->operands[0].reg_type & ARM_REG32) {
k = 0x8052;
}
} else if (!strncmp (op->mnemonic, "movk", 4)) {
if (op->operands[0].reg_type & ARM_REG32) {
k = 0x8072;
} else if (op->operands[0].reg_type & ARM_REG64) {
k = 0x80f2;
}
} else if (!strncmp (op->mnemonic, "movn", 4)) {
if (op->operands[0].reg_type & ARM_REG32) {
k = 0x8012;
} else if (op->operands[0].reg_type & ARM_REG64) {
k = 0x8092;
}
} else if (!strncmp (op->mnemonic, "mov", 3)) {
//printf ("%d - %d [%d]\n", op->operands[0].type, op->operands[1].type, ARM_GPR);
if (op->operands[0].type & ARM_GPR) {
if (op->operands[1].type & ARM_GPR) {
if (op->operands[1].reg_type & ARM_REG64) {
k = 0xe00300aa;
} else {
k = 0xe003002a;
}
data = k | op->operands[1].reg << 8;
} else if (op->operands[1].type & ARM_CONSTANT) {
k = 0x80d2;
data = k | op->operands[1].immediate << 29;
}
data |= op->operands[0].reg << 24;
}
return data;
}
data = k;
data |= (op->operands[0].reg << 24); // arg(0)
data |= ((op->operands[1].immediate & 7) << 29); // arg(1)
data |= (((op->operands[1].immediate >> 3) & 0xff) << 16); // arg(1)
data |= ((op->operands[1].immediate >> 10) << 7); // arg(1)
return data;
}
static ut32 cmp(ArmOp *op) {
ut32 data = UT32_MAX;
int k = 0;
if (op->operands[0].reg_type & ARM_REG64 && op->operands[1].reg_type & ARM_REG64) {
k = 0x1f0000eb;
} else if (op->operands[0].reg_type & ARM_REG32 && op->operands[1].reg_type & ARM_REG32) {
if (op->operands[2].shift_amount > 31) {
return UT32_MAX;
}
k = 0x1f00006b;
} else {
return UT32_MAX;
}
data = k | (op->operands[0].reg & 0x18) << 13 | op->operands[0].reg << 29 | op->operands[1].reg << 8;
if (op->operands[2].shift != ARM_NO_SHIFT) {
data |= op->operands[2].shift_amount << 18 | op->operands[2].shift << 14;
}
return data;
}
static ut32 regsluop(ArmOp *op, int k) {
ut32 data = UT32_MAX;
if (op->operands[1].reg_type & ARM_REG32) {
return data;
}
if (op->operands[0].reg_type & ARM_REG32) {
k -= 0x40;
}
if (op->operands[2].type & ARM_GPR) {
return data;
}
int n = op->operands[2].immediate;
if (n > 0xff || n < -0x100) {
return data;
}
data = k | op->operands[0].reg << 24 | op->operands[1].reg << 29 | (op->operands[1].reg & 56) << 13;
if (n < 0) {
n *= -1;
data |= ( 0xf & (0xf - (n - 1)) ) << 20;
if (countTrailingZeros(n) > 3) {
data |= (0x1f - ((n >> 4) - 1)) << 8;
} else {
data |= (0x1f - (n >> 4)) << 8;
}
} else {
data |= (0xf & (n & 63)) << 20;
if (countTrailingZeros(n) < 4) {
data |= (n >> 4) << 8;
} else {
data |= (0xff & n) << 4;
}
data |= (n >> 8) << 8;
}
return data;
}
// Register Load/store ops
static ut32 reglsop(ArmOp *op, int k) {
ut32 data = UT32_MAX;
if (op->operands[1].reg_type & ARM_REG32) {
return data;
}
if (op->operands[0].reg_type & ARM_REG32) {
k -= 0x40;
}
if (op->operands[2].type & ARM_GPR) {
k += 0x00682000;
data = k | op->operands[0].reg << 24 | op->operands[1].reg << 29 | (op->operands[1].reg & 56) << 13;
data |= op->operands[2].reg << 8;
} else {
int n = op->operands[2].immediate;
if (n > 0x100 || n < -0x100) {
return UT32_MAX;
}
if (n == 0 || (n > 0 && countTrailingZeros(n) >= 4)) {
k ++;
}
data = k | op->operands[0].reg << 24 | op->operands[1].reg << 29 | (op->operands[1].reg & 56) << 13;
if (n < 0) {
n *= -1;
data |= ( 0xf & (0xf - (n - 1)) ) << 20;
if (countTrailingZeros(n) > 3) {
data |= (0x1f - ((n >> 4) - 1)) << 8;
} else {
data |= (0x1f - (n >> 4)) << 8;
}
} else {
if (op->operands[0].reg_type & ARM_REG32) {
if (countTrailingZeros(n) < 2) {
data |= (0xf & (n & 63)) << 20;
data |= (n >> 4) << 8;
} else {
data++;
data |= (0xff & n) << 16;
}
data |= (n >> 8) << 8;
} else {
data |= (0xf & (n & 63)) << 20;
if (countTrailingZeros(n) < 4) {
data |= (n >> 4) << 8;
} else {
data |= (0xff & n) << 15;
}
data |= (n >> 8) << 23;
}
}
}
return data;
}
// Byte load/store ops
static ut32 bytelsop(ArmOp *op, int k) {
ut32 data = UT32_MAX;
if (op->operands[0].reg_type & ARM_REG64) {
return data;
}
if (op->operands[1].reg_type & ARM_REG32) {
return data;
}
if (op->operands[2].type & ARM_GPR) {
if ((k & 0xf) != 8) {
k--;
}
k += 0x00682000;
data = k | op->operands[0].reg << 24 | op->operands[1].reg << 29 | (op->operands[1].reg & 56) << 13;
data |= op->operands[2].reg << 8;
return data;
}
int n = op->operands[2].immediate;
if (n > 0xfff || n < -0x100) {
return UT32_MAX;
}
// Half ops
int halfop = false;
if ((k & 0xf) == 8) {
halfop = true;
if (n == 0 || (countTrailingZeros(n) && n > 0)) {
k++;
}
} else {
if (n < 0) {
k--;
}
}
data = k | op->operands[0].reg << 24 | op->operands[1].reg << 29 | (op->operands[1].reg & 56) << 13;
int imm = n;
int low_shift = 20;
int high_shift = 8;
int top_shift = 10;
if (n < 0) {
imm = 0xfff + (n + 1);
}
if (halfop) {
if (imm & 0x1 || n < 0) {
data |= (0xf & imm) << low_shift ;
data |= (0x7 & (imm >> 4)) << high_shift;
data |= (0x7 & (imm >> 6)) << top_shift;
} else {
data |= (0xf & imm) << (low_shift - 3);
data |= (0x7 & (imm >> 4)) << (high_shift + 13);
data |= (0x7 & (imm >> 7)) << (top_shift - 2);
}
} else {
if (n < 0) {
data |= (0xf & imm) << 20;
data |= (0x1f & (imm >> 4)) << 8;
} else {
data |= (0xf & imm) << 18;
data |= (0x3 & (imm >> 4)) << 22;
data |= (0x7 & (imm >> 6)) << 8;
}
}
return data;
}
static ut32 branch(ArmOp *op, ut64 addr, int k) {
ut32 data = UT32_MAX;
int n = 0;
if (op->operands[0].type & ARM_CONSTANT) {
n = op->operands[0].immediate;
if (!(n & 0x3 || n > 0x7ffffff)) {
n -= addr;
n = n >> 2;
int t = n >> 24;
int h = n >> 16;
int m = (n & 0xff00) >> 8;
n &= 0xff;
data = k;
data |= n << 24;
data |= m << 16;
data |= h << 8;
data |= t;
}
} else {
n = op->operands[0].reg;
if (n < 0 || n > 31) {
return -1;
}
n = n << 5;
int h = n >> 8;
n &= 0xff;
data = k;
data |= n << 24;
data |= h << 16;
}
return data;
}
static ut32 bdot(ArmOp *op, ut64 addr, int k) {
ut32 data = UT32_MAX;
int n = 0;
int a = 0;
n = op->operands[0].immediate;
// I am sure there's a logical way to do negative offsets,
// but I was unable to find any sensible docs so I did my best
if (!(n & 0x3 || n > 0x7ffffff)) {
n -= addr;
data = k;
if (n < 0) {
n *= -1;
a = (n << 3) - 1;
data |= (0xff - a) << 24;
a = calcNegOffset(n, 5);
data |= a << 16;
a = calcNegOffset(n, 13);
data |= a << 8;
} else {
data |= (n & 31) << 27;
data |= (0xff & (n >> 5)) << 16;
data |= (0xff & (n >> 13)) << 8;
}
}
return data;
}
static ut32 mem_barrier (ArmOp *op, ut64 addr, int k) {
ut32 data = UT32_MAX;
data = k;
if (!strncmp (op->mnemonic, "isb", 3)) {
if (op->operands[0].mem_option == 15 || op->operands[0].type == ARM_NOTYPE) {
return data;
} else {
return UT32_MAX;
}
}
if (op->operands[0].type == ARM_MEM_OPT) {
data |= op->operands[0].mem_option << 16;
} else if (op->operands_count == 1 && op->operands[0].type == ARM_CONSTANT) {
data |= (op->operands[0].immediate << 16);
}
return data;
}
#include "armass64_const.h"
static ut32 msrk(ut16 v) {
ut32 r = 0;
ut32 a = ((v >> 12) & 0xf) << 1;
ut32 b = ((v & 0xfff) >> 3) & 0xff;
r |= a << 8;
r |= b << 16;
return r;
}
static ut32 msr(ArmOp *op, int w) {
ut32 data = UT32_MAX;
int i;
ut32 r, b;
/* handle swapped args */
if (w) {
if (op->operands[1].reg_type != (ARM_REG64 | ARM_SP)) {
if (op->operands[1].type == ARM_CONSTANT) {
for (i = 0; msr_const[i].name; i++) {
if (op->operands[1].immediate == msr_const[i].val) {
op->operands[1].sp_val = msr_const[i].val;
op->operands[1].reg = op->operands[1].immediate;
break;
}
}
} else {
return data;
}
}
r = op->operands[0].reg;
b = msrk (op->operands[0].sp_val);
} else {
if (op->operands[0].reg_type != (ARM_REG64 | ARM_SP)) {
if (op->operands[0].type == ARM_CONSTANT) {
for (i = 0; msr_const[i].name; i++) {
if (op->operands[0].immediate == msr_const[i].val) {
op->operands[0].sp_val = msr_const[i].val;
op->operands[0].reg = op->operands[0].immediate;
break;
}
}
} else {
return data;
}
}
r = op->operands[0].reg;
b = msrk (op->operands[0].sp_val);
}
data = (r << 24) | b | 0xd5;
if (w) {
/* mrs */
data |= 0x413000;
}
if (op->operands[1].reg_type == ARM_REG64) {
data |= op->operands[1].reg << 24;
}
return data;
}
static ut32 orr(ArmOp *op, int addr) {
ut32 data = UT32_MAX;
if (op->operands[2].type & ARM_GPR) {
// All operands need to be the same
if (!(op->operands[0].reg_type == op->operands[1].reg_type &&
op->operands[1].reg_type == op->operands[2].reg_type)) {
return data;
}
if (op->operands[0].reg_type & ARM_REG64) {
data = 0x000000aa;
} else {
data = 0x0000002a;
}
data += op->operands[0].reg << 24;
data += op->operands[1].reg << 29;
data += (op->operands[1].reg >> 3) << 16;
data += op->operands[2].reg << 8;
} else if (op->operands[2].type & ARM_CONSTANT) {
// Reg types need to match
if (!(op->operands[0].reg_type == op->operands[1].reg_type)) {
return data;
}
if (op->operands[0].reg_type & ARM_REG64) {
data = 0x000040b2;
} else {
data = 0x00000032;
}
data += op->operands[0].reg << 24;
data += op->operands[1].reg << 29;
data += (op->operands[1].reg >> 3) << 16;
ut32 imm = decodeBitMasks (op->operands[2].immediate);
if (imm == -1) {
return imm;
}
int low = imm & 0xF;
if (op->operands[0].reg_type & ARM_REG64) {
imm = ((imm >> 6) | 0x78);
if (imm > 120) {
data |= imm << 8;
}
} else {
imm = ((imm >> 2));
if (imm > 120) {
data |= imm << 4;
}
}
data |= (4 * low) << 16;
}
return data;
}
static ut32 adrp(ArmOp *op, ut64 addr, ut32 k) { //, int reg, ut64 dst) {
ut64 at = 0LL;
ut32 data = k;
if (op->operands[0].type == ARM_GPR) {
data += ((op->operands[0].reg & 0xff) << 24);
} else {
eprintf ("Usage: adrp x0, addr\n");
return UT32_MAX;
}
if (op->operands[1].type == ARM_CONSTANT) {
// XXX what about negative values?
at = op->operands[1].immediate - addr;
at /= 4;
} else {
eprintf ("Usage: adrp, x0, addr\n");
return UT32_MAX;
}
ut8 b0 = at;
ut8 b1 = (at >> 3) & 0xff;
#if 0
ut8 b2 = (at >> (8 + 7)) & 0xff;
data += b0 << 29;
data += b1 << 16;
data += b2 << 24;
#endif
data += b0 << 16;
data += b1 << 8;
return data;
}
static ut32 adr(ArmOp *op, int addr) {
ut32 data = UT32_MAX;
ut64 at = 0LL;
if (op->operands[1].type & ARM_CONSTANT) {
// XXX what about negative values?
at = op->operands[1].immediate - addr;
at /= 4;
}
data = 0x00000030;
data += 0x01000000 * op->operands[0].reg;
ut8 b0 = at;
ut8 b1 = (at >> 3) & 0xff;
ut8 b2 = (at >> (8 + 7)) & 0xff;
data += b0 << 29;
data += b1 << 16;
data += b2 << 24;
return data;
}
static ut32 stp(ArmOp *op, int k) {
ut32 data = UT32_MAX;
if (op->operands[3].immediate & 0x7) {
return data;
}
if (k == 0x000040a9 && (op->operands[0].reg == op->operands[1].reg)) {
return data;
}
data = k;
data += op->operands[0].reg << 24;
data += op->operands[1].reg << 18;
data += (op->operands[2].reg & 0x7) << 29;
data += (op->operands[2].reg >> 3) << 16;
data += (op->operands[3].immediate & 0x8) << 20;
data += (op->operands[3].immediate >> 4) << 8;
return data;
}
static ut32 exception(ArmOp *op, ut32 k) {
ut32 data = UT32_MAX;
if (op->operands[0].type == ARM_CONSTANT) {
int n = op->operands[0].immediate;
data = k;
data += (((n / 8) & 0xff) << 16);
data += n << 29;//((n >> 8) << 8);
}
return data;
}
static ut32 arithmetic (ArmOp *op, int k) {
ut32 data = UT32_MAX;
if (op->operands_count < 3) {
return data;
}
if (!(op->operands[0].type & ARM_GPR &&
op->operands[1].type & ARM_GPR)) {
return data;
}
if (op->operands[2].type & ARM_GPR) {
k -= 6;
}
data = k;
data += op->operands[0].reg << 24;
data += (op->operands[1].reg & 7) << (24 + 5);
data += (op->operands[1].reg >> 3) << 16;
if (op->operands[2].reg_type & ARM_REG64) {
data += op->operands[2].reg << 8;
} else {
data += (op->operands[2].reg & 0x3f) << 18;
data += (op->operands[2].reg >> 6) << 8;
}
return data;
}
static bool parseOperands(char* str, ArmOp *op) {
char *t = strdup (str);
int operand = 0;
char *token = t;
char *x;
int imm_count = 0;
int mem_opt = 0;
if (!token) {
return false;
}
while (token) {
char *next = strchr (token, ',');
if (next) {
*next++ = 0;
}
while (token[0] == ' ') {
token++;
}
if (operand >= MAX_OPERANDS) {
eprintf ("Too many operands\n");
return false;
}
op->operands[operand].type = ARM_NOTYPE;
op->operands[operand].reg_type = ARM_UNDEFINED;
op->operands[operand].shift = ARM_NO_SHIFT;
while (token[0] == ' ' || token[0] == '[' || token[0] == ']') {
token ++;
}
if (!strncmp (token, "lsl", 3)) {
op->operands[operand].shift = ARM_LSL;
} else if (!strncmp (token, "lsr", 3)) {
op->operands[operand].shift = ARM_LSR;
} else if (!strncmp (token, "asr", 3)) {
op->operands[operand].shift = ARM_ASR;
}
if (op->operands[operand].shift != ARM_NO_SHIFT) {
op->operands_count ++;
op->operands[operand].shift_amount = r_num_math (NULL, token + 4);
if (op->operands[operand].shift_amount > 63) {
return false;
}
operand ++;
token = next;
continue;
}
switch (token[0]) {
case 'x':
x = strchr (token, ',');
if (x) {
x[0] = '\0';
}
op->operands_count ++;
op->operands[operand].type = ARM_GPR;
op->operands[operand].reg_type = ARM_REG64;
op->operands[operand].reg = r_num_math (NULL, token + 1);
if (op->operands[operand].reg > 31) {
return false;
}
break;
case 'w':
op->operands_count ++;
op->operands[operand].type = ARM_GPR;
op->operands[operand].reg_type = ARM_REG32;
op->operands[operand].reg = r_num_math (NULL, token + 1);
if (op->operands[operand].reg > 31) {
return false;
}
break;
case 'v':
op->operands_count ++;
op->operands[operand].type = ARM_FP;
op->operands[operand].reg = r_num_math (NULL, token + 1);
break;
case 's':
case 'S':
if (token[1] == 'P' || token [1] == 'p') {
int i;
for (i = 0; msr_const[i].name; i++) {
if (!r_str_ncasecmp (token, msr_const[i].name, strlen (msr_const[i].name))) {
op->operands[operand].sp_val = msr_const[i].val;
break;
}
}
op->operands_count ++;
op->operands[operand].type = ARM_GPR;
op->operands[operand].reg_type = ARM_SP | ARM_REG64;
op->operands[operand].reg = 31;
break;
}
mem_opt = get_mem_option (token);
if (mem_opt != -1) {
op->operands_count ++;
op->operands[operand].type = ARM_MEM_OPT;
op->operands[operand].mem_option = mem_opt;
}
break;
case 'L':
case 'l':
case 'I':
case 'i':
case 'N':
case 'n':
case 'O':
case 'o':
case 'p':
case 'P':
mem_opt = get_mem_option (token);
if (mem_opt != -1) {
op->operands_count ++;
op->operands[operand].type = ARM_MEM_OPT;
op->operands[operand].mem_option = mem_opt;
}
break;
case '-':
op->operands[operand].sign = -1;
// falthru
default:
op->operands_count ++;
op->operands[operand].type = ARM_CONSTANT;
op->operands[operand].immediate = r_num_math (NULL, token);
imm_count++;
break;
}
token = next;
operand ++;
if (operand > MAX_OPERANDS) {
free (t);
return false;
}
}
free (t);
return true;
}
static bool parseOpcode(const char *str, ArmOp *op) {
char *in = strdup (str);
char *space = strchr (in, ' ');
if (!space) {
op->operands[0].type = ARM_NOTYPE;
op->mnemonic = in;
return true;
}
space[0] = '\0';
op->mnemonic = in;
space ++;
return parseOperands (space, op);
}
bool arm64ass(const char *str, ut64 addr, ut32 *op) {
ArmOp ops = {0};
if (!parseOpcode (str, &ops)) {
return false;
}
/* TODO: write tests for this and move out the regsize logic into the mov */
if (!strncmp (str, "mov", 3)) {
*op = mov (&ops);
return *op != -1;
}
if (!strncmp (str, "cmp", 3)) {
*op = cmp (&ops);
return *op != -1;
}
if (!strncmp (str, "ldrb", 4)) {
*op = bytelsop (&ops, 0x00004039);
return *op != -1;
}
if (!strncmp (str, "ldrh", 4)) {
*op = bytelsop (&ops, 0x00004078);
return *op != -1;
}
if (!strncmp (str, "ldrsh", 5)) {
*op = bytelsop (&ops, 0x0000c078);
return *op != -1;
}
if (!strncmp (str, "ldrsw", 5)) {
*op = bytelsop (&ops, 0x000080b8);
return *op != -1;
}
if (!strncmp (str, "ldrsb", 5)) {
*op = bytelsop (&ops, 0x0000c039);
return *op != -1;
}
if (!strncmp (str, "strb", 4)) {
*op = bytelsop (&ops, 0x00000039);
return *op != -1;
}
if (!strncmp (str, "strh", 4)) {
*op = bytelsop (&ops, 0x00000078);
return *op != -1;
}
if (!strncmp (str, "ldr", 3)) {
*op = reglsop (&ops, 0x000040f8);
return *op != -1;
}
if (!strncmp (str, "stur", 4)) {
*op = regsluop (&ops, 0x000000f8);
return *op != -1;
}
if (!strncmp (str, "ldur", 4)) {
*op = regsluop (&ops, 0x000040f8);
return *op != -1;
}
if (!strncmp (str, "str", 3)) {
*op = reglsop (&ops, 0x000000f8);
return *op != -1;
}
if (!strncmp (str, "stp", 3)) {
*op = stp (&ops, 0x000000a9);
return *op != -1;
}
if (!strncmp (str, "ldp", 3)) {
*op = stp (&ops, 0x000040a9);
return *op != -1;
}
if (!strncmp (str, "sub", 3)) { // w
*op = arithmetic (&ops, 0xd1);
return *op != -1;
}
if (!strncmp (str, "add", 3)) { // w
*op = arithmetic (&ops, 0x91);
return *op != -1;
}
if (!strncmp (str, "adr x", 5)) { // w
*op = adr (&ops, addr);
return *op != -1;
}
if (!strncmp (str, "adrp x", 6)) {
*op = adrp (&ops, addr, 0x00000090);
return *op != -1;
}
if (!strcmp (str, "isb")) {
*op = 0xdf3f03d5;
return *op != -1;
}
if (!strcmp (str, "nop")) {
*op = 0x1f2003d5;
return *op != -1;
}
if (!strcmp (str, "ret")) {
*op = 0xc0035fd6;
return true;
}
if (!strncmp (str, "msr ", 4)) {
*op = msr (&ops, 0);
if (*op != UT32_MAX) {
return true;
}
}
if (!strncmp (str, "mrs ", 4)) {
*op = msr (&ops, 1);
if (*op != UT32_MAX) {
return true;
}
}
if (!strncmp (str, "orr ", 4)) {
*op = orr (&ops, addr);
return *op != UT32_MAX;
}
if (!strncmp (str, "svc ", 4)) { // system level exception
*op = exception (&ops, 0x010000d4);
return *op != -1;
}
if (!strncmp (str, "hvc ", 4)) { // hypervisor level exception
*op = exception (&ops, 0x020000d4);
return *op != -1;
}
if (!strncmp (str, "smc ", 4)) { // secure monitor exception
*op = exception (&ops, 0x030000d4);
return *op != -1;
}
if (!strncmp (str, "brk ", 4)) { // breakpoint
*op = exception (&ops, 0x000020d4);
return *op != -1;
}
if (!strncmp (str, "hlt ", 4)) { // halt
*op = exception (&ops, 0x000040d4);
return *op != -1;
}
if (!strncmp (str, "b ", 2)) {
*op = branch (&ops, addr, 0x14);
return *op != -1;
}
if (!strncmp (str, "b.eq ", 5)) {
*op = bdot (&ops, addr, 0x00000054);
return *op != -1;
}
if (!strncmp (str, "b.hs ", 5)) {
*op = bdot (&ops, addr, 0x02000054);
return *op != -1;
}
if (!strncmp (str, "bl ", 3)) {
*op = branch (&ops, addr, 0x94);
return *op != -1;
}
if (!strncmp (str, "br x", 4)) {
*op = branch (&ops, addr, 0x1fd6);
return *op != -1;
}
if (!strncmp (str, "blr x", 5)) {
*op = branch (&ops, addr, 0x3fd6);
return *op != -1;
}
if (!strncmp (str, "dmb ", 4)) {
*op = mem_barrier (&ops, addr, 0xbf3003d5);
return *op != -1;
}
if (!strncmp (str, "dsb ", 4)) {
*op = mem_barrier (&ops, addr, 0x9f3003d5);
return *op != -1;
}
if (!strncmp (str, "isb", 3)) {
*op = mem_barrier (&ops, addr, 0xdf3f03d5);
return *op != -1;
}
return false;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_503_0 |
crossvul-cpp_data_good_5740_1 | /*
* NET4: Implementation of BSD Unix domain sockets.
*
* Authors: Alan Cox, <alan@lxorguk.ukuu.org.uk>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Fixes:
* Linus Torvalds : Assorted bug cures.
* Niibe Yutaka : async I/O support.
* Carsten Paeth : PF_UNIX check, address fixes.
* Alan Cox : Limit size of allocated blocks.
* Alan Cox : Fixed the stupid socketpair bug.
* Alan Cox : BSD compatibility fine tuning.
* Alan Cox : Fixed a bug in connect when interrupted.
* Alan Cox : Sorted out a proper draft version of
* file descriptor passing hacked up from
* Mike Shaver's work.
* Marty Leisner : Fixes to fd passing
* Nick Nevin : recvmsg bugfix.
* Alan Cox : Started proper garbage collector
* Heiko EiBfeldt : Missing verify_area check
* Alan Cox : Started POSIXisms
* Andreas Schwab : Replace inode by dentry for proper
* reference counting
* Kirk Petersen : Made this a module
* Christoph Rohland : Elegant non-blocking accept/connect algorithm.
* Lots of bug fixes.
* Alexey Kuznetosv : Repaired (I hope) bugs introduces
* by above two patches.
* Andrea Arcangeli : If possible we block in connect(2)
* if the max backlog of the listen socket
* is been reached. This won't break
* old apps and it will avoid huge amount
* of socks hashed (this for unix_gc()
* performances reasons).
* Security fix that limits the max
* number of socks to 2*max_files and
* the number of skb queueable in the
* dgram receiver.
* Artur Skawina : Hash function optimizations
* Alexey Kuznetsov : Full scale SMP. Lot of bugs are introduced 8)
* Malcolm Beattie : Set peercred for socketpair
* Michal Ostrowski : Module initialization cleanup.
* Arnaldo C. Melo : Remove MOD_{INC,DEC}_USE_COUNT,
* the core infrastructure is doing that
* for all net proto families now (2.5.69+)
*
*
* Known differences from reference BSD that was tested:
*
* [TO FIX]
* ECONNREFUSED is not returned from one end of a connected() socket to the
* other the moment one end closes.
* fstat() doesn't return st_dev=0, and give the blksize as high water mark
* and a fake inode identifier (nor the BSD first socket fstat twice bug).
* [NOT TO FIX]
* accept() returns a path name even if the connecting socket has closed
* in the meantime (BSD loses the path and gives up).
* accept() returns 0 length path for an unbound connector. BSD returns 16
* and a null first byte in the path (but not for gethost/peername - BSD bug ??)
* socketpair(...SOCK_RAW..) doesn't panic the kernel.
* BSD af_unix apparently has connect forgetting to block properly.
* (need to check this with the POSIX spec in detail)
*
* Differences from 2.0.0-11-... (ANK)
* Bug fixes and improvements.
* - client shutdown killed server socket.
* - removed all useless cli/sti pairs.
*
* Semantic changes/extensions.
* - generic control message passing.
* - SCM_CREDENTIALS control message.
* - "Abstract" (not FS based) socket bindings.
* Abstract names are sequences of bytes (not zero terminated)
* started by 0, so that this name space does not intersect
* with BSD names.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/stat.h>
#include <linux/dcache.h>
#include <linux/namei.h>
#include <linux/socket.h>
#include <linux/un.h>
#include <linux/fcntl.h>
#include <linux/termios.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/in.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <net/af_unix.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <net/scm.h>
#include <linux/init.h>
#include <linux/poll.h>
#include <linux/rtnetlink.h>
#include <linux/mount.h>
#include <net/checksum.h>
#include <linux/security.h>
#include <linux/freezer.h>
struct hlist_head unix_socket_table[2 * UNIX_HASH_SIZE];
EXPORT_SYMBOL_GPL(unix_socket_table);
DEFINE_SPINLOCK(unix_table_lock);
EXPORT_SYMBOL_GPL(unix_table_lock);
static atomic_long_t unix_nr_socks;
static struct hlist_head *unix_sockets_unbound(void *addr)
{
unsigned long hash = (unsigned long)addr;
hash ^= hash >> 16;
hash ^= hash >> 8;
hash %= UNIX_HASH_SIZE;
return &unix_socket_table[UNIX_HASH_SIZE + hash];
}
#define UNIX_ABSTRACT(sk) (unix_sk(sk)->addr->hash < UNIX_HASH_SIZE)
#ifdef CONFIG_SECURITY_NETWORK
static void unix_get_secdata(struct scm_cookie *scm, struct sk_buff *skb)
{
UNIXCB(skb).secid = scm->secid;
}
static inline void unix_set_secdata(struct scm_cookie *scm, struct sk_buff *skb)
{
scm->secid = UNIXCB(skb).secid;
}
static inline bool unix_secdata_eq(struct scm_cookie *scm, struct sk_buff *skb)
{
return (scm->secid == UNIXCB(skb).secid);
}
#else
static inline void unix_get_secdata(struct scm_cookie *scm, struct sk_buff *skb)
{ }
static inline void unix_set_secdata(struct scm_cookie *scm, struct sk_buff *skb)
{ }
static inline bool unix_secdata_eq(struct scm_cookie *scm, struct sk_buff *skb)
{
return true;
}
#endif /* CONFIG_SECURITY_NETWORK */
/*
* SMP locking strategy:
* hash table is protected with spinlock unix_table_lock
* each socket state is protected by separate spin lock.
*/
static inline unsigned int unix_hash_fold(__wsum n)
{
unsigned int hash = (__force unsigned int)csum_fold(n);
hash ^= hash>>8;
return hash&(UNIX_HASH_SIZE-1);
}
#define unix_peer(sk) (unix_sk(sk)->peer)
static inline int unix_our_peer(struct sock *sk, struct sock *osk)
{
return unix_peer(osk) == sk;
}
static inline int unix_may_send(struct sock *sk, struct sock *osk)
{
return unix_peer(osk) == NULL || unix_our_peer(sk, osk);
}
static inline int unix_recvq_full(struct sock const *sk)
{
return skb_queue_len(&sk->sk_receive_queue) > sk->sk_max_ack_backlog;
}
struct sock *unix_peer_get(struct sock *s)
{
struct sock *peer;
unix_state_lock(s);
peer = unix_peer(s);
if (peer)
sock_hold(peer);
unix_state_unlock(s);
return peer;
}
EXPORT_SYMBOL_GPL(unix_peer_get);
static inline void unix_release_addr(struct unix_address *addr)
{
if (atomic_dec_and_test(&addr->refcnt))
kfree(addr);
}
/*
* Check unix socket name:
* - should be not zero length.
* - if started by not zero, should be NULL terminated (FS object)
* - if started by zero, it is abstract name.
*/
static int unix_mkname(struct sockaddr_un *sunaddr, int len, unsigned int *hashp)
{
if (len <= sizeof(short) || len > sizeof(*sunaddr))
return -EINVAL;
if (!sunaddr || sunaddr->sun_family != AF_UNIX)
return -EINVAL;
if (sunaddr->sun_path[0]) {
/*
* This may look like an off by one error but it is a bit more
* subtle. 108 is the longest valid AF_UNIX path for a binding.
* sun_path[108] doesn't as such exist. However in kernel space
* we are guaranteed that it is a valid memory location in our
* kernel address buffer.
*/
((char *)sunaddr)[len] = 0;
len = strlen(sunaddr->sun_path)+1+sizeof(short);
return len;
}
*hashp = unix_hash_fold(csum_partial(sunaddr, len, 0));
return len;
}
static void __unix_remove_socket(struct sock *sk)
{
sk_del_node_init(sk);
}
static void __unix_insert_socket(struct hlist_head *list, struct sock *sk)
{
WARN_ON(!sk_unhashed(sk));
sk_add_node(sk, list);
}
static inline void unix_remove_socket(struct sock *sk)
{
spin_lock(&unix_table_lock);
__unix_remove_socket(sk);
spin_unlock(&unix_table_lock);
}
static inline void unix_insert_socket(struct hlist_head *list, struct sock *sk)
{
spin_lock(&unix_table_lock);
__unix_insert_socket(list, sk);
spin_unlock(&unix_table_lock);
}
static struct sock *__unix_find_socket_byname(struct net *net,
struct sockaddr_un *sunname,
int len, int type, unsigned int hash)
{
struct sock *s;
sk_for_each(s, &unix_socket_table[hash ^ type]) {
struct unix_sock *u = unix_sk(s);
if (!net_eq(sock_net(s), net))
continue;
if (u->addr->len == len &&
!memcmp(u->addr->name, sunname, len))
goto found;
}
s = NULL;
found:
return s;
}
static inline struct sock *unix_find_socket_byname(struct net *net,
struct sockaddr_un *sunname,
int len, int type,
unsigned int hash)
{
struct sock *s;
spin_lock(&unix_table_lock);
s = __unix_find_socket_byname(net, sunname, len, type, hash);
if (s)
sock_hold(s);
spin_unlock(&unix_table_lock);
return s;
}
static struct sock *unix_find_socket_byinode(struct inode *i)
{
struct sock *s;
spin_lock(&unix_table_lock);
sk_for_each(s,
&unix_socket_table[i->i_ino & (UNIX_HASH_SIZE - 1)]) {
struct dentry *dentry = unix_sk(s)->path.dentry;
if (dentry && d_backing_inode(dentry) == i) {
sock_hold(s);
goto found;
}
}
s = NULL;
found:
spin_unlock(&unix_table_lock);
return s;
}
/* Support code for asymmetrically connected dgram sockets
*
* If a datagram socket is connected to a socket not itself connected
* to the first socket (eg, /dev/log), clients may only enqueue more
* messages if the present receive queue of the server socket is not
* "too large". This means there's a second writeability condition
* poll and sendmsg need to test. The dgram recv code will do a wake
* up on the peer_wait wait queue of a socket upon reception of a
* datagram which needs to be propagated to sleeping would-be writers
* since these might not have sent anything so far. This can't be
* accomplished via poll_wait because the lifetime of the server
* socket might be less than that of its clients if these break their
* association with it or if the server socket is closed while clients
* are still connected to it and there's no way to inform "a polling
* implementation" that it should let go of a certain wait queue
*
* In order to propagate a wake up, a wait_queue_t of the client
* socket is enqueued on the peer_wait queue of the server socket
* whose wake function does a wake_up on the ordinary client socket
* wait queue. This connection is established whenever a write (or
* poll for write) hit the flow control condition and broken when the
* association to the server socket is dissolved or after a wake up
* was relayed.
*/
static int unix_dgram_peer_wake_relay(wait_queue_t *q, unsigned mode, int flags,
void *key)
{
struct unix_sock *u;
wait_queue_head_t *u_sleep;
u = container_of(q, struct unix_sock, peer_wake);
__remove_wait_queue(&unix_sk(u->peer_wake.private)->peer_wait,
q);
u->peer_wake.private = NULL;
/* relaying can only happen while the wq still exists */
u_sleep = sk_sleep(&u->sk);
if (u_sleep)
wake_up_interruptible_poll(u_sleep, key);
return 0;
}
static int unix_dgram_peer_wake_connect(struct sock *sk, struct sock *other)
{
struct unix_sock *u, *u_other;
int rc;
u = unix_sk(sk);
u_other = unix_sk(other);
rc = 0;
spin_lock(&u_other->peer_wait.lock);
if (!u->peer_wake.private) {
u->peer_wake.private = other;
__add_wait_queue(&u_other->peer_wait, &u->peer_wake);
rc = 1;
}
spin_unlock(&u_other->peer_wait.lock);
return rc;
}
static void unix_dgram_peer_wake_disconnect(struct sock *sk,
struct sock *other)
{
struct unix_sock *u, *u_other;
u = unix_sk(sk);
u_other = unix_sk(other);
spin_lock(&u_other->peer_wait.lock);
if (u->peer_wake.private == other) {
__remove_wait_queue(&u_other->peer_wait, &u->peer_wake);
u->peer_wake.private = NULL;
}
spin_unlock(&u_other->peer_wait.lock);
}
static void unix_dgram_peer_wake_disconnect_wakeup(struct sock *sk,
struct sock *other)
{
unix_dgram_peer_wake_disconnect(sk, other);
wake_up_interruptible_poll(sk_sleep(sk),
POLLOUT |
POLLWRNORM |
POLLWRBAND);
}
/* preconditions:
* - unix_peer(sk) == other
* - association is stable
*/
static int unix_dgram_peer_wake_me(struct sock *sk, struct sock *other)
{
int connected;
connected = unix_dgram_peer_wake_connect(sk, other);
if (unix_recvq_full(other))
return 1;
if (connected)
unix_dgram_peer_wake_disconnect(sk, other);
return 0;
}
static int unix_writable(const struct sock *sk)
{
return sk->sk_state != TCP_LISTEN &&
(atomic_read(&sk->sk_wmem_alloc) << 2) <= sk->sk_sndbuf;
}
static void unix_write_space(struct sock *sk)
{
struct socket_wq *wq;
rcu_read_lock();
if (unix_writable(sk)) {
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait,
POLLOUT | POLLWRNORM | POLLWRBAND);
sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
}
rcu_read_unlock();
}
/* When dgram socket disconnects (or changes its peer), we clear its receive
* queue of packets arrived from previous peer. First, it allows to do
* flow control based only on wmem_alloc; second, sk connected to peer
* may receive messages only from that peer. */
static void unix_dgram_disconnected(struct sock *sk, struct sock *other)
{
if (!skb_queue_empty(&sk->sk_receive_queue)) {
skb_queue_purge(&sk->sk_receive_queue);
wake_up_interruptible_all(&unix_sk(sk)->peer_wait);
/* If one link of bidirectional dgram pipe is disconnected,
* we signal error. Messages are lost. Do not make this,
* when peer was not connected to us.
*/
if (!sock_flag(other, SOCK_DEAD) && unix_peer(other) == sk) {
other->sk_err = ECONNRESET;
other->sk_error_report(other);
}
}
}
static void unix_sock_destructor(struct sock *sk)
{
struct unix_sock *u = unix_sk(sk);
skb_queue_purge(&sk->sk_receive_queue);
WARN_ON(atomic_read(&sk->sk_wmem_alloc));
WARN_ON(!sk_unhashed(sk));
WARN_ON(sk->sk_socket);
if (!sock_flag(sk, SOCK_DEAD)) {
pr_info("Attempt to release alive unix socket: %p\n", sk);
return;
}
if (u->addr)
unix_release_addr(u->addr);
atomic_long_dec(&unix_nr_socks);
local_bh_disable();
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
local_bh_enable();
#ifdef UNIX_REFCNT_DEBUG
pr_debug("UNIX %p is destroyed, %ld are still alive.\n", sk,
atomic_long_read(&unix_nr_socks));
#endif
}
static void unix_release_sock(struct sock *sk, int embrion)
{
struct unix_sock *u = unix_sk(sk);
struct path path;
struct sock *skpair;
struct sk_buff *skb;
int state;
unix_remove_socket(sk);
/* Clear state */
unix_state_lock(sk);
sock_orphan(sk);
sk->sk_shutdown = SHUTDOWN_MASK;
path = u->path;
u->path.dentry = NULL;
u->path.mnt = NULL;
state = sk->sk_state;
sk->sk_state = TCP_CLOSE;
unix_state_unlock(sk);
wake_up_interruptible_all(&u->peer_wait);
skpair = unix_peer(sk);
if (skpair != NULL) {
if (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET) {
unix_state_lock(skpair);
/* No more writes */
skpair->sk_shutdown = SHUTDOWN_MASK;
if (!skb_queue_empty(&sk->sk_receive_queue) || embrion)
skpair->sk_err = ECONNRESET;
unix_state_unlock(skpair);
skpair->sk_state_change(skpair);
sk_wake_async(skpair, SOCK_WAKE_WAITD, POLL_HUP);
}
unix_dgram_peer_wake_disconnect(sk, skpair);
sock_put(skpair); /* It may now die */
unix_peer(sk) = NULL;
}
/* Try to flush out this socket. Throw out buffers at least */
while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) {
if (state == TCP_LISTEN)
unix_release_sock(skb->sk, 1);
/* passed fds are erased in the kfree_skb hook */
UNIXCB(skb).consumed = skb->len;
kfree_skb(skb);
}
if (path.dentry)
path_put(&path);
sock_put(sk);
/* ---- Socket is dead now and most probably destroyed ---- */
/*
* Fixme: BSD difference: In BSD all sockets connected to us get
* ECONNRESET and we die on the spot. In Linux we behave
* like files and pipes do and wait for the last
* dereference.
*
* Can't we simply set sock->err?
*
* What the above comment does talk about? --ANK(980817)
*/
if (unix_tot_inflight)
unix_gc(); /* Garbage collect fds */
}
static void init_peercred(struct sock *sk)
{
put_pid(sk->sk_peer_pid);
if (sk->sk_peer_cred)
put_cred(sk->sk_peer_cred);
sk->sk_peer_pid = get_pid(task_tgid(current));
sk->sk_peer_cred = get_current_cred();
}
static void copy_peercred(struct sock *sk, struct sock *peersk)
{
put_pid(sk->sk_peer_pid);
if (sk->sk_peer_cred)
put_cred(sk->sk_peer_cred);
sk->sk_peer_pid = get_pid(peersk->sk_peer_pid);
sk->sk_peer_cred = get_cred(peersk->sk_peer_cred);
}
static int unix_listen(struct socket *sock, int backlog)
{
int err;
struct sock *sk = sock->sk;
struct unix_sock *u = unix_sk(sk);
struct pid *old_pid = NULL;
err = -EOPNOTSUPP;
if (sock->type != SOCK_STREAM && sock->type != SOCK_SEQPACKET)
goto out; /* Only stream/seqpacket sockets accept */
err = -EINVAL;
if (!u->addr)
goto out; /* No listens on an unbound socket */
unix_state_lock(sk);
if (sk->sk_state != TCP_CLOSE && sk->sk_state != TCP_LISTEN)
goto out_unlock;
if (backlog > sk->sk_max_ack_backlog)
wake_up_interruptible_all(&u->peer_wait);
sk->sk_max_ack_backlog = backlog;
sk->sk_state = TCP_LISTEN;
/* set credentials so connect can copy them */
init_peercred(sk);
err = 0;
out_unlock:
unix_state_unlock(sk);
put_pid(old_pid);
out:
return err;
}
static int unix_release(struct socket *);
static int unix_bind(struct socket *, struct sockaddr *, int);
static int unix_stream_connect(struct socket *, struct sockaddr *,
int addr_len, int flags);
static int unix_socketpair(struct socket *, struct socket *);
static int unix_accept(struct socket *, struct socket *, int);
static int unix_getname(struct socket *, struct sockaddr *, int *, int);
static unsigned int unix_poll(struct file *, struct socket *, poll_table *);
static unsigned int unix_dgram_poll(struct file *, struct socket *,
poll_table *);
static int unix_ioctl(struct socket *, unsigned int, unsigned long);
static int unix_shutdown(struct socket *, int);
static int unix_stream_sendmsg(struct socket *, struct msghdr *, size_t);
static int unix_stream_recvmsg(struct socket *, struct msghdr *, size_t, int);
static ssize_t unix_stream_sendpage(struct socket *, struct page *, int offset,
size_t size, int flags);
static ssize_t unix_stream_splice_read(struct socket *, loff_t *ppos,
struct pipe_inode_info *, size_t size,
unsigned int flags);
static int unix_dgram_sendmsg(struct socket *, struct msghdr *, size_t);
static int unix_dgram_recvmsg(struct socket *, struct msghdr *, size_t, int);
static int unix_dgram_connect(struct socket *, struct sockaddr *,
int, int);
static int unix_seqpacket_sendmsg(struct socket *, struct msghdr *, size_t);
static int unix_seqpacket_recvmsg(struct socket *, struct msghdr *, size_t,
int);
static int unix_set_peek_off(struct sock *sk, int val)
{
struct unix_sock *u = unix_sk(sk);
if (mutex_lock_interruptible(&u->readlock))
return -EINTR;
sk->sk_peek_off = val;
mutex_unlock(&u->readlock);
return 0;
}
static const struct proto_ops unix_stream_ops = {
.family = PF_UNIX,
.owner = THIS_MODULE,
.release = unix_release,
.bind = unix_bind,
.connect = unix_stream_connect,
.socketpair = unix_socketpair,
.accept = unix_accept,
.getname = unix_getname,
.poll = unix_poll,
.ioctl = unix_ioctl,
.listen = unix_listen,
.shutdown = unix_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = unix_stream_sendmsg,
.recvmsg = unix_stream_recvmsg,
.mmap = sock_no_mmap,
.sendpage = unix_stream_sendpage,
.splice_read = unix_stream_splice_read,
.set_peek_off = unix_set_peek_off,
};
static const struct proto_ops unix_dgram_ops = {
.family = PF_UNIX,
.owner = THIS_MODULE,
.release = unix_release,
.bind = unix_bind,
.connect = unix_dgram_connect,
.socketpair = unix_socketpair,
.accept = sock_no_accept,
.getname = unix_getname,
.poll = unix_dgram_poll,
.ioctl = unix_ioctl,
.listen = sock_no_listen,
.shutdown = unix_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = unix_dgram_sendmsg,
.recvmsg = unix_dgram_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
.set_peek_off = unix_set_peek_off,
};
static const struct proto_ops unix_seqpacket_ops = {
.family = PF_UNIX,
.owner = THIS_MODULE,
.release = unix_release,
.bind = unix_bind,
.connect = unix_stream_connect,
.socketpair = unix_socketpair,
.accept = unix_accept,
.getname = unix_getname,
.poll = unix_dgram_poll,
.ioctl = unix_ioctl,
.listen = unix_listen,
.shutdown = unix_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = unix_seqpacket_sendmsg,
.recvmsg = unix_seqpacket_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
.set_peek_off = unix_set_peek_off,
};
static struct proto unix_proto = {
.name = "UNIX",
.owner = THIS_MODULE,
.obj_size = sizeof(struct unix_sock),
};
/*
* AF_UNIX sockets do not interact with hardware, hence they
* dont trigger interrupts - so it's safe for them to have
* bh-unsafe locking for their sk_receive_queue.lock. Split off
* this special lock-class by reinitializing the spinlock key:
*/
static struct lock_class_key af_unix_sk_receive_queue_lock_key;
static struct sock *unix_create1(struct net *net, struct socket *sock, int kern)
{
struct sock *sk = NULL;
struct unix_sock *u;
atomic_long_inc(&unix_nr_socks);
if (atomic_long_read(&unix_nr_socks) > 2 * get_max_files())
goto out;
sk = sk_alloc(net, PF_UNIX, GFP_KERNEL, &unix_proto, kern);
if (!sk)
goto out;
sock_init_data(sock, sk);
lockdep_set_class(&sk->sk_receive_queue.lock,
&af_unix_sk_receive_queue_lock_key);
sk->sk_write_space = unix_write_space;
sk->sk_max_ack_backlog = net->unx.sysctl_max_dgram_qlen;
sk->sk_destruct = unix_sock_destructor;
u = unix_sk(sk);
u->path.dentry = NULL;
u->path.mnt = NULL;
spin_lock_init(&u->lock);
atomic_long_set(&u->inflight, 0);
INIT_LIST_HEAD(&u->link);
mutex_init(&u->readlock); /* single task reading lock */
init_waitqueue_head(&u->peer_wait);
init_waitqueue_func_entry(&u->peer_wake, unix_dgram_peer_wake_relay);
unix_insert_socket(unix_sockets_unbound(sk), sk);
out:
if (sk == NULL)
atomic_long_dec(&unix_nr_socks);
else {
local_bh_disable();
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
local_bh_enable();
}
return sk;
}
static int unix_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
if (protocol && protocol != PF_UNIX)
return -EPROTONOSUPPORT;
sock->state = SS_UNCONNECTED;
switch (sock->type) {
case SOCK_STREAM:
sock->ops = &unix_stream_ops;
break;
/*
* Believe it or not BSD has AF_UNIX, SOCK_RAW though
* nothing uses it.
*/
case SOCK_RAW:
sock->type = SOCK_DGRAM;
case SOCK_DGRAM:
sock->ops = &unix_dgram_ops;
break;
case SOCK_SEQPACKET:
sock->ops = &unix_seqpacket_ops;
break;
default:
return -ESOCKTNOSUPPORT;
}
return unix_create1(net, sock, kern) ? 0 : -ENOMEM;
}
static int unix_release(struct socket *sock)
{
struct sock *sk = sock->sk;
if (!sk)
return 0;
unix_release_sock(sk, 0);
sock->sk = NULL;
return 0;
}
static int unix_autobind(struct socket *sock)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct unix_sock *u = unix_sk(sk);
static u32 ordernum = 1;
struct unix_address *addr;
int err;
unsigned int retries = 0;
err = mutex_lock_interruptible(&u->readlock);
if (err)
return err;
err = 0;
if (u->addr)
goto out;
err = -ENOMEM;
addr = kzalloc(sizeof(*addr) + sizeof(short) + 16, GFP_KERNEL);
if (!addr)
goto out;
addr->name->sun_family = AF_UNIX;
atomic_set(&addr->refcnt, 1);
retry:
addr->len = sprintf(addr->name->sun_path+1, "%05x", ordernum) + 1 + sizeof(short);
addr->hash = unix_hash_fold(csum_partial(addr->name, addr->len, 0));
spin_lock(&unix_table_lock);
ordernum = (ordernum+1)&0xFFFFF;
if (__unix_find_socket_byname(net, addr->name, addr->len, sock->type,
addr->hash)) {
spin_unlock(&unix_table_lock);
/*
* __unix_find_socket_byname() may take long time if many names
* are already in use.
*/
cond_resched();
/* Give up if all names seems to be in use. */
if (retries++ == 0xFFFFF) {
err = -ENOSPC;
kfree(addr);
goto out;
}
goto retry;
}
addr->hash ^= sk->sk_type;
__unix_remove_socket(sk);
u->addr = addr;
__unix_insert_socket(&unix_socket_table[addr->hash], sk);
spin_unlock(&unix_table_lock);
err = 0;
out: mutex_unlock(&u->readlock);
return err;
}
static struct sock *unix_find_other(struct net *net,
struct sockaddr_un *sunname, int len,
int type, unsigned int hash, int *error)
{
struct sock *u;
struct path path;
int err = 0;
if (sunname->sun_path[0]) {
struct inode *inode;
err = kern_path(sunname->sun_path, LOOKUP_FOLLOW, &path);
if (err)
goto fail;
inode = d_backing_inode(path.dentry);
err = inode_permission(inode, MAY_WRITE);
if (err)
goto put_fail;
err = -ECONNREFUSED;
if (!S_ISSOCK(inode->i_mode))
goto put_fail;
u = unix_find_socket_byinode(inode);
if (!u)
goto put_fail;
if (u->sk_type == type)
touch_atime(&path);
path_put(&path);
err = -EPROTOTYPE;
if (u->sk_type != type) {
sock_put(u);
goto fail;
}
} else {
err = -ECONNREFUSED;
u = unix_find_socket_byname(net, sunname, len, type, hash);
if (u) {
struct dentry *dentry;
dentry = unix_sk(u)->path.dentry;
if (dentry)
touch_atime(&unix_sk(u)->path);
} else
goto fail;
}
return u;
put_fail:
path_put(&path);
fail:
*error = err;
return NULL;
}
static int unix_mknod(struct dentry *dentry, struct path *path, umode_t mode,
struct path *res)
{
int err;
err = security_path_mknod(path, dentry, mode, 0);
if (!err) {
err = vfs_mknod(d_inode(path->dentry), dentry, mode, 0);
if (!err) {
res->mnt = mntget(path->mnt);
res->dentry = dget(dentry);
}
}
return err;
}
static int unix_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct unix_sock *u = unix_sk(sk);
struct sockaddr_un *sunaddr = (struct sockaddr_un *)uaddr;
char *sun_path = sunaddr->sun_path;
int err, name_err;
unsigned int hash;
struct unix_address *addr;
struct hlist_head *list;
struct path path;
struct dentry *dentry;
err = -EINVAL;
if (sunaddr->sun_family != AF_UNIX)
goto out;
if (addr_len == sizeof(short)) {
err = unix_autobind(sock);
goto out;
}
err = unix_mkname(sunaddr, addr_len, &hash);
if (err < 0)
goto out;
addr_len = err;
name_err = 0;
dentry = NULL;
if (sun_path[0]) {
/* Get the parent directory, calculate the hash for last
* component.
*/
dentry = kern_path_create(AT_FDCWD, sun_path, &path, 0);
if (IS_ERR(dentry)) {
/* delay report until after 'already bound' check */
name_err = PTR_ERR(dentry);
dentry = NULL;
}
}
err = mutex_lock_interruptible(&u->readlock);
if (err)
goto out_path;
err = -EINVAL;
if (u->addr)
goto out_up;
if (name_err) {
err = name_err == -EEXIST ? -EADDRINUSE : name_err;
goto out_up;
}
err = -ENOMEM;
addr = kmalloc(sizeof(*addr)+addr_len, GFP_KERNEL);
if (!addr)
goto out_up;
memcpy(addr->name, sunaddr, addr_len);
addr->len = addr_len;
addr->hash = hash ^ sk->sk_type;
atomic_set(&addr->refcnt, 1);
if (dentry) {
struct path u_path;
umode_t mode = S_IFSOCK |
(SOCK_INODE(sock)->i_mode & ~current_umask());
err = unix_mknod(dentry, &path, mode, &u_path);
if (err) {
if (err == -EEXIST)
err = -EADDRINUSE;
unix_release_addr(addr);
goto out_up;
}
addr->hash = UNIX_HASH_SIZE;
hash = d_backing_inode(dentry)->i_ino & (UNIX_HASH_SIZE - 1);
spin_lock(&unix_table_lock);
u->path = u_path;
list = &unix_socket_table[hash];
} else {
spin_lock(&unix_table_lock);
err = -EADDRINUSE;
if (__unix_find_socket_byname(net, sunaddr, addr_len,
sk->sk_type, hash)) {
unix_release_addr(addr);
goto out_unlock;
}
list = &unix_socket_table[addr->hash];
}
err = 0;
__unix_remove_socket(sk);
u->addr = addr;
__unix_insert_socket(list, sk);
out_unlock:
spin_unlock(&unix_table_lock);
out_up:
mutex_unlock(&u->readlock);
out_path:
if (dentry)
done_path_create(&path, dentry);
out:
return err;
}
static void unix_state_double_lock(struct sock *sk1, struct sock *sk2)
{
if (unlikely(sk1 == sk2) || !sk2) {
unix_state_lock(sk1);
return;
}
if (sk1 < sk2) {
unix_state_lock(sk1);
unix_state_lock_nested(sk2);
} else {
unix_state_lock(sk2);
unix_state_lock_nested(sk1);
}
}
static void unix_state_double_unlock(struct sock *sk1, struct sock *sk2)
{
if (unlikely(sk1 == sk2) || !sk2) {
unix_state_unlock(sk1);
return;
}
unix_state_unlock(sk1);
unix_state_unlock(sk2);
}
static int unix_dgram_connect(struct socket *sock, struct sockaddr *addr,
int alen, int flags)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct sockaddr_un *sunaddr = (struct sockaddr_un *)addr;
struct sock *other;
unsigned int hash;
int err;
if (addr->sa_family != AF_UNSPEC) {
err = unix_mkname(sunaddr, alen, &hash);
if (err < 0)
goto out;
alen = err;
if (test_bit(SOCK_PASSCRED, &sock->flags) &&
!unix_sk(sk)->addr && (err = unix_autobind(sock)) != 0)
goto out;
restart:
other = unix_find_other(net, sunaddr, alen, sock->type, hash, &err);
if (!other)
goto out;
unix_state_double_lock(sk, other);
/* Apparently VFS overslept socket death. Retry. */
if (sock_flag(other, SOCK_DEAD)) {
unix_state_double_unlock(sk, other);
sock_put(other);
goto restart;
}
err = -EPERM;
if (!unix_may_send(sk, other))
goto out_unlock;
err = security_unix_may_send(sk->sk_socket, other->sk_socket);
if (err)
goto out_unlock;
} else {
/*
* 1003.1g breaking connected state with AF_UNSPEC
*/
other = NULL;
unix_state_double_lock(sk, other);
}
/*
* If it was connected, reconnect.
*/
if (unix_peer(sk)) {
struct sock *old_peer = unix_peer(sk);
unix_peer(sk) = other;
unix_dgram_peer_wake_disconnect_wakeup(sk, old_peer);
unix_state_double_unlock(sk, other);
if (other != old_peer)
unix_dgram_disconnected(sk, old_peer);
sock_put(old_peer);
} else {
unix_peer(sk) = other;
unix_state_double_unlock(sk, other);
}
return 0;
out_unlock:
unix_state_double_unlock(sk, other);
sock_put(other);
out:
return err;
}
static long unix_wait_for_peer(struct sock *other, long timeo)
{
struct unix_sock *u = unix_sk(other);
int sched;
DEFINE_WAIT(wait);
prepare_to_wait_exclusive(&u->peer_wait, &wait, TASK_INTERRUPTIBLE);
sched = !sock_flag(other, SOCK_DEAD) &&
!(other->sk_shutdown & RCV_SHUTDOWN) &&
unix_recvq_full(other);
unix_state_unlock(other);
if (sched)
timeo = schedule_timeout(timeo);
finish_wait(&u->peer_wait, &wait);
return timeo;
}
static int unix_stream_connect(struct socket *sock, struct sockaddr *uaddr,
int addr_len, int flags)
{
struct sockaddr_un *sunaddr = (struct sockaddr_un *)uaddr;
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct unix_sock *u = unix_sk(sk), *newu, *otheru;
struct sock *newsk = NULL;
struct sock *other = NULL;
struct sk_buff *skb = NULL;
unsigned int hash;
int st;
int err;
long timeo;
err = unix_mkname(sunaddr, addr_len, &hash);
if (err < 0)
goto out;
addr_len = err;
if (test_bit(SOCK_PASSCRED, &sock->flags) && !u->addr &&
(err = unix_autobind(sock)) != 0)
goto out;
timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
/* First of all allocate resources.
If we will make it after state is locked,
we will have to recheck all again in any case.
*/
err = -ENOMEM;
/* create new sock for complete connection */
newsk = unix_create1(sock_net(sk), NULL, 0);
if (newsk == NULL)
goto out;
/* Allocate skb for sending to listening sock */
skb = sock_wmalloc(newsk, 1, 0, GFP_KERNEL);
if (skb == NULL)
goto out;
restart:
/* Find listening sock. */
other = unix_find_other(net, sunaddr, addr_len, sk->sk_type, hash, &err);
if (!other)
goto out;
/* Latch state of peer */
unix_state_lock(other);
/* Apparently VFS overslept socket death. Retry. */
if (sock_flag(other, SOCK_DEAD)) {
unix_state_unlock(other);
sock_put(other);
goto restart;
}
err = -ECONNREFUSED;
if (other->sk_state != TCP_LISTEN)
goto out_unlock;
if (other->sk_shutdown & RCV_SHUTDOWN)
goto out_unlock;
if (unix_recvq_full(other)) {
err = -EAGAIN;
if (!timeo)
goto out_unlock;
timeo = unix_wait_for_peer(other, timeo);
err = sock_intr_errno(timeo);
if (signal_pending(current))
goto out;
sock_put(other);
goto restart;
}
/* Latch our state.
It is tricky place. We need to grab our state lock and cannot
drop lock on peer. It is dangerous because deadlock is
possible. Connect to self case and simultaneous
attempt to connect are eliminated by checking socket
state. other is TCP_LISTEN, if sk is TCP_LISTEN we
check this before attempt to grab lock.
Well, and we have to recheck the state after socket locked.
*/
st = sk->sk_state;
switch (st) {
case TCP_CLOSE:
/* This is ok... continue with connect */
break;
case TCP_ESTABLISHED:
/* Socket is already connected */
err = -EISCONN;
goto out_unlock;
default:
err = -EINVAL;
goto out_unlock;
}
unix_state_lock_nested(sk);
if (sk->sk_state != st) {
unix_state_unlock(sk);
unix_state_unlock(other);
sock_put(other);
goto restart;
}
err = security_unix_stream_connect(sk, other, newsk);
if (err) {
unix_state_unlock(sk);
goto out_unlock;
}
/* The way is open! Fastly set all the necessary fields... */
sock_hold(sk);
unix_peer(newsk) = sk;
newsk->sk_state = TCP_ESTABLISHED;
newsk->sk_type = sk->sk_type;
init_peercred(newsk);
newu = unix_sk(newsk);
RCU_INIT_POINTER(newsk->sk_wq, &newu->peer_wq);
otheru = unix_sk(other);
/* copy address information from listening to new sock*/
if (otheru->addr) {
atomic_inc(&otheru->addr->refcnt);
newu->addr = otheru->addr;
}
if (otheru->path.dentry) {
path_get(&otheru->path);
newu->path = otheru->path;
}
/* Set credentials */
copy_peercred(sk, other);
sock->state = SS_CONNECTED;
sk->sk_state = TCP_ESTABLISHED;
sock_hold(newsk);
smp_mb__after_atomic(); /* sock_hold() does an atomic_inc() */
unix_peer(sk) = newsk;
unix_state_unlock(sk);
/* take ten and and send info to listening sock */
spin_lock(&other->sk_receive_queue.lock);
__skb_queue_tail(&other->sk_receive_queue, skb);
spin_unlock(&other->sk_receive_queue.lock);
unix_state_unlock(other);
other->sk_data_ready(other);
sock_put(other);
return 0;
out_unlock:
if (other)
unix_state_unlock(other);
out:
kfree_skb(skb);
if (newsk)
unix_release_sock(newsk, 0);
if (other)
sock_put(other);
return err;
}
static int unix_socketpair(struct socket *socka, struct socket *sockb)
{
struct sock *ska = socka->sk, *skb = sockb->sk;
/* Join our sockets back to back */
sock_hold(ska);
sock_hold(skb);
unix_peer(ska) = skb;
unix_peer(skb) = ska;
init_peercred(ska);
init_peercred(skb);
if (ska->sk_type != SOCK_DGRAM) {
ska->sk_state = TCP_ESTABLISHED;
skb->sk_state = TCP_ESTABLISHED;
socka->state = SS_CONNECTED;
sockb->state = SS_CONNECTED;
}
return 0;
}
static void unix_sock_inherit_flags(const struct socket *old,
struct socket *new)
{
if (test_bit(SOCK_PASSCRED, &old->flags))
set_bit(SOCK_PASSCRED, &new->flags);
if (test_bit(SOCK_PASSSEC, &old->flags))
set_bit(SOCK_PASSSEC, &new->flags);
}
static int unix_accept(struct socket *sock, struct socket *newsock, int flags)
{
struct sock *sk = sock->sk;
struct sock *tsk;
struct sk_buff *skb;
int err;
err = -EOPNOTSUPP;
if (sock->type != SOCK_STREAM && sock->type != SOCK_SEQPACKET)
goto out;
err = -EINVAL;
if (sk->sk_state != TCP_LISTEN)
goto out;
/* If socket state is TCP_LISTEN it cannot change (for now...),
* so that no locks are necessary.
*/
skb = skb_recv_datagram(sk, 0, flags&O_NONBLOCK, &err);
if (!skb) {
/* This means receive shutdown. */
if (err == 0)
err = -EINVAL;
goto out;
}
tsk = skb->sk;
skb_free_datagram(sk, skb);
wake_up_interruptible(&unix_sk(sk)->peer_wait);
/* attach accepted sock to socket */
unix_state_lock(tsk);
newsock->state = SS_CONNECTED;
unix_sock_inherit_flags(sock, newsock);
sock_graft(tsk, newsock);
unix_state_unlock(tsk);
return 0;
out:
return err;
}
static int unix_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer)
{
struct sock *sk = sock->sk;
struct unix_sock *u;
DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr, uaddr);
int err = 0;
if (peer) {
sk = unix_peer_get(sk);
err = -ENOTCONN;
if (!sk)
goto out;
err = 0;
} else {
sock_hold(sk);
}
u = unix_sk(sk);
unix_state_lock(sk);
if (!u->addr) {
sunaddr->sun_family = AF_UNIX;
sunaddr->sun_path[0] = 0;
*uaddr_len = sizeof(short);
} else {
struct unix_address *addr = u->addr;
*uaddr_len = addr->len;
memcpy(sunaddr, addr->name, *uaddr_len);
}
unix_state_unlock(sk);
sock_put(sk);
out:
return err;
}
static void unix_detach_fds(struct scm_cookie *scm, struct sk_buff *skb)
{
int i;
scm->fp = UNIXCB(skb).fp;
UNIXCB(skb).fp = NULL;
for (i = scm->fp->count-1; i >= 0; i--)
unix_notinflight(scm->fp->fp[i]);
}
static void unix_destruct_scm(struct sk_buff *skb)
{
struct scm_cookie scm;
memset(&scm, 0, sizeof(scm));
scm.pid = UNIXCB(skb).pid;
if (UNIXCB(skb).fp)
unix_detach_fds(&scm, skb);
/* Alas, it calls VFS */
/* So fscking what? fput() had been SMP-safe since the last Summer */
scm_destroy(&scm);
sock_wfree(skb);
}
/*
* The "user->unix_inflight" variable is protected by the garbage
* collection lock, and we just read it locklessly here. If you go
* over the limit, there might be a tiny race in actually noticing
* it across threads. Tough.
*/
static inline bool too_many_unix_fds(struct task_struct *p)
{
struct user_struct *user = current_user();
if (unlikely(user->unix_inflight > task_rlimit(p, RLIMIT_NOFILE)))
return !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN);
return false;
}
#define MAX_RECURSION_LEVEL 4
static int unix_attach_fds(struct scm_cookie *scm, struct sk_buff *skb)
{
int i;
unsigned char max_level = 0;
int unix_sock_count = 0;
if (too_many_unix_fds(current))
return -ETOOMANYREFS;
for (i = scm->fp->count - 1; i >= 0; i--) {
struct sock *sk = unix_get_socket(scm->fp->fp[i]);
if (sk) {
unix_sock_count++;
max_level = max(max_level,
unix_sk(sk)->recursion_level);
}
}
if (unlikely(max_level > MAX_RECURSION_LEVEL))
return -ETOOMANYREFS;
/*
* Need to duplicate file references for the sake of garbage
* collection. Otherwise a socket in the fps might become a
* candidate for GC while the skb is not yet queued.
*/
UNIXCB(skb).fp = scm_fp_dup(scm->fp);
if (!UNIXCB(skb).fp)
return -ENOMEM;
for (i = scm->fp->count - 1; i >= 0; i--)
unix_inflight(scm->fp->fp[i]);
return max_level;
}
static int unix_scm_to_skb(struct scm_cookie *scm, struct sk_buff *skb, bool send_fds)
{
int err = 0;
UNIXCB(skb).pid = get_pid(scm->pid);
UNIXCB(skb).uid = scm->creds.uid;
UNIXCB(skb).gid = scm->creds.gid;
UNIXCB(skb).fp = NULL;
unix_get_secdata(scm, skb);
if (scm->fp && send_fds)
err = unix_attach_fds(scm, skb);
skb->destructor = unix_destruct_scm;
return err;
}
static bool unix_passcred_enabled(const struct socket *sock,
const struct sock *other)
{
return test_bit(SOCK_PASSCRED, &sock->flags) ||
!other->sk_socket ||
test_bit(SOCK_PASSCRED, &other->sk_socket->flags);
}
/*
* Some apps rely on write() giving SCM_CREDENTIALS
* We include credentials if source or destination socket
* asserted SOCK_PASSCRED.
*/
static void maybe_add_creds(struct sk_buff *skb, const struct socket *sock,
const struct sock *other)
{
if (UNIXCB(skb).pid)
return;
if (unix_passcred_enabled(sock, other)) {
UNIXCB(skb).pid = get_pid(task_tgid(current));
current_uid_gid(&UNIXCB(skb).uid, &UNIXCB(skb).gid);
}
}
static int maybe_init_creds(struct scm_cookie *scm,
struct socket *socket,
const struct sock *other)
{
int err;
struct msghdr msg = { .msg_controllen = 0 };
err = scm_send(socket, &msg, scm, false);
if (err)
return err;
if (unix_passcred_enabled(socket, other)) {
scm->pid = get_pid(task_tgid(current));
current_uid_gid(&scm->creds.uid, &scm->creds.gid);
}
return err;
}
static bool unix_skb_scm_eq(struct sk_buff *skb,
struct scm_cookie *scm)
{
const struct unix_skb_parms *u = &UNIXCB(skb);
return u->pid == scm->pid &&
uid_eq(u->uid, scm->creds.uid) &&
gid_eq(u->gid, scm->creds.gid) &&
unix_secdata_eq(scm, skb);
}
/*
* Send AF_UNIX data.
*/
static int unix_dgram_sendmsg(struct socket *sock, struct msghdr *msg,
size_t len)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct unix_sock *u = unix_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr, msg->msg_name);
struct sock *other = NULL;
int namelen = 0; /* fake GCC */
int err;
unsigned int hash;
struct sk_buff *skb;
long timeo;
struct scm_cookie scm;
int max_level;
int data_len = 0;
int sk_locked;
wait_for_unix_gc();
err = scm_send(sock, msg, &scm, false);
if (err < 0)
return err;
err = -EOPNOTSUPP;
if (msg->msg_flags&MSG_OOB)
goto out;
if (msg->msg_namelen) {
err = unix_mkname(sunaddr, msg->msg_namelen, &hash);
if (err < 0)
goto out;
namelen = err;
} else {
sunaddr = NULL;
err = -ENOTCONN;
other = unix_peer_get(sk);
if (!other)
goto out;
}
if (test_bit(SOCK_PASSCRED, &sock->flags) && !u->addr
&& (err = unix_autobind(sock)) != 0)
goto out;
err = -EMSGSIZE;
if (len > sk->sk_sndbuf - 32)
goto out;
if (len > SKB_MAX_ALLOC) {
data_len = min_t(size_t,
len - SKB_MAX_ALLOC,
MAX_SKB_FRAGS * PAGE_SIZE);
data_len = PAGE_ALIGN(data_len);
BUILD_BUG_ON(SKB_MAX_ALLOC < PAGE_SIZE);
}
skb = sock_alloc_send_pskb(sk, len - data_len, data_len,
msg->msg_flags & MSG_DONTWAIT, &err,
PAGE_ALLOC_COSTLY_ORDER);
if (skb == NULL)
goto out;
err = unix_scm_to_skb(&scm, skb, true);
if (err < 0)
goto out_free;
max_level = err + 1;
skb_put(skb, len - data_len);
skb->data_len = data_len;
skb->len = len;
err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, len);
if (err)
goto out_free;
timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
restart:
if (!other) {
err = -ECONNRESET;
if (sunaddr == NULL)
goto out_free;
other = unix_find_other(net, sunaddr, namelen, sk->sk_type,
hash, &err);
if (other == NULL)
goto out_free;
}
if (sk_filter(other, skb) < 0) {
/* Toss the packet but do not return any error to the sender */
err = len;
goto out_free;
}
sk_locked = 0;
unix_state_lock(other);
restart_locked:
err = -EPERM;
if (!unix_may_send(sk, other))
goto out_unlock;
if (unlikely(sock_flag(other, SOCK_DEAD))) {
/*
* Check with 1003.1g - what should
* datagram error
*/
unix_state_unlock(other);
sock_put(other);
if (!sk_locked)
unix_state_lock(sk);
err = 0;
if (unix_peer(sk) == other) {
unix_peer(sk) = NULL;
unix_dgram_peer_wake_disconnect_wakeup(sk, other);
unix_state_unlock(sk);
unix_dgram_disconnected(sk, other);
sock_put(other);
err = -ECONNREFUSED;
} else {
unix_state_unlock(sk);
}
other = NULL;
if (err)
goto out_free;
goto restart;
}
err = -EPIPE;
if (other->sk_shutdown & RCV_SHUTDOWN)
goto out_unlock;
if (sk->sk_type != SOCK_SEQPACKET) {
err = security_unix_may_send(sk->sk_socket, other->sk_socket);
if (err)
goto out_unlock;
}
if (unlikely(unix_peer(other) != sk && unix_recvq_full(other))) {
if (timeo) {
timeo = unix_wait_for_peer(other, timeo);
err = sock_intr_errno(timeo);
if (signal_pending(current))
goto out_free;
goto restart;
}
if (!sk_locked) {
unix_state_unlock(other);
unix_state_double_lock(sk, other);
}
if (unix_peer(sk) != other ||
unix_dgram_peer_wake_me(sk, other)) {
err = -EAGAIN;
sk_locked = 1;
goto out_unlock;
}
if (!sk_locked) {
sk_locked = 1;
goto restart_locked;
}
}
if (unlikely(sk_locked))
unix_state_unlock(sk);
if (sock_flag(other, SOCK_RCVTSTAMP))
__net_timestamp(skb);
maybe_add_creds(skb, sock, other);
skb_queue_tail(&other->sk_receive_queue, skb);
if (max_level > unix_sk(other)->recursion_level)
unix_sk(other)->recursion_level = max_level;
unix_state_unlock(other);
other->sk_data_ready(other);
sock_put(other);
scm_destroy(&scm);
return len;
out_unlock:
if (sk_locked)
unix_state_unlock(sk);
unix_state_unlock(other);
out_free:
kfree_skb(skb);
out:
if (other)
sock_put(other);
scm_destroy(&scm);
return err;
}
/* We use paged skbs for stream sockets, and limit occupancy to 32768
* bytes, and a minimun of a full page.
*/
#define UNIX_SKB_FRAGS_SZ (PAGE_SIZE << get_order(32768))
static int unix_stream_sendmsg(struct socket *sock, struct msghdr *msg,
size_t len)
{
struct sock *sk = sock->sk;
struct sock *other = NULL;
int err, size;
struct sk_buff *skb;
int sent = 0;
struct scm_cookie scm;
bool fds_sent = false;
int max_level;
int data_len;
wait_for_unix_gc();
err = scm_send(sock, msg, &scm, false);
if (err < 0)
return err;
err = -EOPNOTSUPP;
if (msg->msg_flags&MSG_OOB)
goto out_err;
if (msg->msg_namelen) {
err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
goto out_err;
} else {
err = -ENOTCONN;
other = unix_peer(sk);
if (!other)
goto out_err;
}
if (sk->sk_shutdown & SEND_SHUTDOWN)
goto pipe_err;
while (sent < len) {
size = len - sent;
/* Keep two messages in the pipe so it schedules better */
size = min_t(int, size, (sk->sk_sndbuf >> 1) - 64);
/* allow fallback to order-0 allocations */
size = min_t(int, size, SKB_MAX_HEAD(0) + UNIX_SKB_FRAGS_SZ);
data_len = max_t(int, 0, size - SKB_MAX_HEAD(0));
data_len = min_t(size_t, size, PAGE_ALIGN(data_len));
skb = sock_alloc_send_pskb(sk, size - data_len, data_len,
msg->msg_flags & MSG_DONTWAIT, &err,
get_order(UNIX_SKB_FRAGS_SZ));
if (!skb)
goto out_err;
/* Only send the fds in the first buffer */
err = unix_scm_to_skb(&scm, skb, !fds_sent);
if (err < 0) {
kfree_skb(skb);
goto out_err;
}
max_level = err + 1;
fds_sent = true;
skb_put(skb, size - data_len);
skb->data_len = data_len;
skb->len = size;
err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, size);
if (err) {
kfree_skb(skb);
goto out_err;
}
unix_state_lock(other);
if (sock_flag(other, SOCK_DEAD) ||
(other->sk_shutdown & RCV_SHUTDOWN))
goto pipe_err_free;
maybe_add_creds(skb, sock, other);
skb_queue_tail(&other->sk_receive_queue, skb);
if (max_level > unix_sk(other)->recursion_level)
unix_sk(other)->recursion_level = max_level;
unix_state_unlock(other);
other->sk_data_ready(other);
sent += size;
}
scm_destroy(&scm);
return sent;
pipe_err_free:
unix_state_unlock(other);
kfree_skb(skb);
pipe_err:
if (sent == 0 && !(msg->msg_flags&MSG_NOSIGNAL))
send_sig(SIGPIPE, current, 0);
err = -EPIPE;
out_err:
scm_destroy(&scm);
return sent ? : err;
}
static ssize_t unix_stream_sendpage(struct socket *socket, struct page *page,
int offset, size_t size, int flags)
{
int err;
bool send_sigpipe = false;
bool init_scm = true;
struct scm_cookie scm;
struct sock *other, *sk = socket->sk;
struct sk_buff *skb, *newskb = NULL, *tail = NULL;
if (flags & MSG_OOB)
return -EOPNOTSUPP;
other = unix_peer(sk);
if (!other || sk->sk_state != TCP_ESTABLISHED)
return -ENOTCONN;
if (false) {
alloc_skb:
unix_state_unlock(other);
mutex_unlock(&unix_sk(other)->readlock);
newskb = sock_alloc_send_pskb(sk, 0, 0, flags & MSG_DONTWAIT,
&err, 0);
if (!newskb)
goto err;
}
/* we must acquire readlock as we modify already present
* skbs in the sk_receive_queue and mess with skb->len
*/
err = mutex_lock_interruptible(&unix_sk(other)->readlock);
if (err) {
err = flags & MSG_DONTWAIT ? -EAGAIN : -ERESTARTSYS;
goto err;
}
if (sk->sk_shutdown & SEND_SHUTDOWN) {
err = -EPIPE;
send_sigpipe = true;
goto err_unlock;
}
unix_state_lock(other);
if (sock_flag(other, SOCK_DEAD) ||
other->sk_shutdown & RCV_SHUTDOWN) {
err = -EPIPE;
send_sigpipe = true;
goto err_state_unlock;
}
if (init_scm) {
err = maybe_init_creds(&scm, socket, other);
if (err)
goto err_state_unlock;
init_scm = false;
}
skb = skb_peek_tail(&other->sk_receive_queue);
if (tail && tail == skb) {
skb = newskb;
} else if (!skb || !unix_skb_scm_eq(skb, &scm)) {
if (newskb) {
skb = newskb;
} else {
tail = skb;
goto alloc_skb;
}
} else if (newskb) {
/* this is fast path, we don't necessarily need to
* call to kfree_skb even though with newskb == NULL
* this - does no harm
*/
consume_skb(newskb);
newskb = NULL;
}
if (skb_append_pagefrags(skb, page, offset, size)) {
tail = skb;
goto alloc_skb;
}
skb->len += size;
skb->data_len += size;
skb->truesize += size;
atomic_add(size, &sk->sk_wmem_alloc);
if (newskb) {
err = unix_scm_to_skb(&scm, skb, false);
if (err)
goto err_state_unlock;
spin_lock(&other->sk_receive_queue.lock);
__skb_queue_tail(&other->sk_receive_queue, newskb);
spin_unlock(&other->sk_receive_queue.lock);
}
unix_state_unlock(other);
mutex_unlock(&unix_sk(other)->readlock);
other->sk_data_ready(other);
scm_destroy(&scm);
return size;
err_state_unlock:
unix_state_unlock(other);
err_unlock:
mutex_unlock(&unix_sk(other)->readlock);
err:
kfree_skb(newskb);
if (send_sigpipe && !(flags & MSG_NOSIGNAL))
send_sig(SIGPIPE, current, 0);
if (!init_scm)
scm_destroy(&scm);
return err;
}
static int unix_seqpacket_sendmsg(struct socket *sock, struct msghdr *msg,
size_t len)
{
int err;
struct sock *sk = sock->sk;
err = sock_error(sk);
if (err)
return err;
if (sk->sk_state != TCP_ESTABLISHED)
return -ENOTCONN;
if (msg->msg_namelen)
msg->msg_namelen = 0;
return unix_dgram_sendmsg(sock, msg, len);
}
static int unix_seqpacket_recvmsg(struct socket *sock, struct msghdr *msg,
size_t size, int flags)
{
struct sock *sk = sock->sk;
if (sk->sk_state != TCP_ESTABLISHED)
return -ENOTCONN;
return unix_dgram_recvmsg(sock, msg, size, flags);
}
static void unix_copy_addr(struct msghdr *msg, struct sock *sk)
{
struct unix_sock *u = unix_sk(sk);
if (u->addr) {
msg->msg_namelen = u->addr->len;
memcpy(msg->msg_name, u->addr->name, u->addr->len);
}
}
static int unix_dgram_recvmsg(struct socket *sock, struct msghdr *msg,
size_t size, int flags)
{
struct scm_cookie scm;
struct sock *sk = sock->sk;
struct unix_sock *u = unix_sk(sk);
int noblock = flags & MSG_DONTWAIT;
struct sk_buff *skb;
int err;
int peeked, skip;
err = -EOPNOTSUPP;
if (flags&MSG_OOB)
goto out;
err = mutex_lock_interruptible(&u->readlock);
if (unlikely(err)) {
/* recvmsg() in non blocking mode is supposed to return -EAGAIN
* sk_rcvtimeo is not honored by mutex_lock_interruptible()
*/
err = noblock ? -EAGAIN : -ERESTARTSYS;
goto out;
}
skip = sk_peek_offset(sk, flags);
skb = __skb_recv_datagram(sk, flags, &peeked, &skip, &err);
if (!skb) {
unix_state_lock(sk);
/* Signal EOF on disconnected non-blocking SEQPACKET socket. */
if (sk->sk_type == SOCK_SEQPACKET && err == -EAGAIN &&
(sk->sk_shutdown & RCV_SHUTDOWN))
err = 0;
unix_state_unlock(sk);
goto out_unlock;
}
wake_up_interruptible_sync_poll(&u->peer_wait,
POLLOUT | POLLWRNORM | POLLWRBAND);
if (msg->msg_name)
unix_copy_addr(msg, skb->sk);
if (size > skb->len - skip)
size = skb->len - skip;
else if (size < skb->len - skip)
msg->msg_flags |= MSG_TRUNC;
err = skb_copy_datagram_msg(skb, skip, msg, size);
if (err)
goto out_free;
if (sock_flag(sk, SOCK_RCVTSTAMP))
__sock_recv_timestamp(msg, sk, skb);
memset(&scm, 0, sizeof(scm));
scm_set_cred(&scm, UNIXCB(skb).pid, UNIXCB(skb).uid, UNIXCB(skb).gid);
unix_set_secdata(&scm, skb);
if (!(flags & MSG_PEEK)) {
if (UNIXCB(skb).fp)
unix_detach_fds(&scm, skb);
sk_peek_offset_bwd(sk, skb->len);
} else {
/* It is questionable: on PEEK we could:
- do not return fds - good, but too simple 8)
- return fds, and do not return them on read (old strategy,
apparently wrong)
- clone fds (I chose it for now, it is the most universal
solution)
POSIX 1003.1g does not actually define this clearly
at all. POSIX 1003.1g doesn't define a lot of things
clearly however!
*/
sk_peek_offset_fwd(sk, size);
if (UNIXCB(skb).fp)
scm.fp = scm_fp_dup(UNIXCB(skb).fp);
}
err = (flags & MSG_TRUNC) ? skb->len - skip : size;
scm_recv(sock, msg, &scm, flags);
out_free:
skb_free_datagram(sk, skb);
out_unlock:
mutex_unlock(&u->readlock);
out:
return err;
}
/*
* Sleep until more data has arrived. But check for races..
*/
static long unix_stream_data_wait(struct sock *sk, long timeo,
struct sk_buff *last, unsigned int last_len)
{
struct sk_buff *tail;
DEFINE_WAIT(wait);
unix_state_lock(sk);
for (;;) {
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
tail = skb_peek_tail(&sk->sk_receive_queue);
if (tail != last ||
(tail && tail->len != last_len) ||
sk->sk_err ||
(sk->sk_shutdown & RCV_SHUTDOWN) ||
signal_pending(current) ||
!timeo)
break;
sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
unix_state_unlock(sk);
timeo = freezable_schedule_timeout(timeo);
unix_state_lock(sk);
if (sock_flag(sk, SOCK_DEAD))
break;
sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
}
finish_wait(sk_sleep(sk), &wait);
unix_state_unlock(sk);
return timeo;
}
static unsigned int unix_skb_len(const struct sk_buff *skb)
{
return skb->len - UNIXCB(skb).consumed;
}
struct unix_stream_read_state {
int (*recv_actor)(struct sk_buff *, int, int,
struct unix_stream_read_state *);
struct socket *socket;
struct msghdr *msg;
struct pipe_inode_info *pipe;
size_t size;
int flags;
unsigned int splice_flags;
};
static int unix_stream_read_generic(struct unix_stream_read_state *state)
{
struct scm_cookie scm;
struct socket *sock = state->socket;
struct sock *sk = sock->sk;
struct unix_sock *u = unix_sk(sk);
int copied = 0;
int flags = state->flags;
int noblock = flags & MSG_DONTWAIT;
bool check_creds = false;
int target;
int err = 0;
long timeo;
int skip;
size_t size = state->size;
unsigned int last_len;
err = -EINVAL;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
err = -EOPNOTSUPP;
if (flags & MSG_OOB)
goto out;
target = sock_rcvlowat(sk, flags & MSG_WAITALL, size);
timeo = sock_rcvtimeo(sk, noblock);
memset(&scm, 0, sizeof(scm));
/* Lock the socket to prevent queue disordering
* while sleeps in memcpy_tomsg
*/
mutex_lock(&u->readlock);
if (flags & MSG_PEEK)
skip = sk_peek_offset(sk, flags);
else
skip = 0;
do {
int chunk;
bool drop_skb;
struct sk_buff *skb, *last;
unix_state_lock(sk);
if (sock_flag(sk, SOCK_DEAD)) {
err = -ECONNRESET;
goto unlock;
}
last = skb = skb_peek(&sk->sk_receive_queue);
last_len = last ? last->len : 0;
again:
if (skb == NULL) {
unix_sk(sk)->recursion_level = 0;
if (copied >= target)
goto unlock;
/*
* POSIX 1003.1g mandates this order.
*/
err = sock_error(sk);
if (err)
goto unlock;
if (sk->sk_shutdown & RCV_SHUTDOWN)
goto unlock;
unix_state_unlock(sk);
err = -EAGAIN;
if (!timeo)
break;
mutex_unlock(&u->readlock);
timeo = unix_stream_data_wait(sk, timeo, last,
last_len);
if (signal_pending(current)) {
err = sock_intr_errno(timeo);
goto out;
}
mutex_lock(&u->readlock);
continue;
unlock:
unix_state_unlock(sk);
break;
}
while (skip >= unix_skb_len(skb)) {
skip -= unix_skb_len(skb);
last = skb;
last_len = skb->len;
skb = skb_peek_next(skb, &sk->sk_receive_queue);
if (!skb)
goto again;
}
unix_state_unlock(sk);
if (check_creds) {
/* Never glue messages from different writers */
if (!unix_skb_scm_eq(skb, &scm))
break;
} else if (test_bit(SOCK_PASSCRED, &sock->flags)) {
/* Copy credentials */
scm_set_cred(&scm, UNIXCB(skb).pid, UNIXCB(skb).uid, UNIXCB(skb).gid);
unix_set_secdata(&scm, skb);
check_creds = true;
}
/* Copy address just once */
if (state->msg && state->msg->msg_name) {
DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr,
state->msg->msg_name);
unix_copy_addr(state->msg, skb->sk);
sunaddr = NULL;
}
chunk = min_t(unsigned int, unix_skb_len(skb) - skip, size);
skb_get(skb);
chunk = state->recv_actor(skb, skip, chunk, state);
drop_skb = !unix_skb_len(skb);
/* skb is only safe to use if !drop_skb */
consume_skb(skb);
if (chunk < 0) {
if (copied == 0)
copied = -EFAULT;
break;
}
copied += chunk;
size -= chunk;
if (drop_skb) {
/* the skb was touched by a concurrent reader;
* we should not expect anything from this skb
* anymore and assume it invalid - we can be
* sure it was dropped from the socket queue
*
* let's report a short read
*/
err = 0;
break;
}
/* Mark read part of skb as used */
if (!(flags & MSG_PEEK)) {
UNIXCB(skb).consumed += chunk;
sk_peek_offset_bwd(sk, chunk);
if (UNIXCB(skb).fp)
unix_detach_fds(&scm, skb);
if (unix_skb_len(skb))
break;
skb_unlink(skb, &sk->sk_receive_queue);
consume_skb(skb);
if (scm.fp)
break;
} else {
/* It is questionable, see note in unix_dgram_recvmsg.
*/
if (UNIXCB(skb).fp)
scm.fp = scm_fp_dup(UNIXCB(skb).fp);
sk_peek_offset_fwd(sk, chunk);
if (UNIXCB(skb).fp)
break;
skip = 0;
last = skb;
last_len = skb->len;
unix_state_lock(sk);
skb = skb_peek_next(skb, &sk->sk_receive_queue);
if (skb)
goto again;
unix_state_unlock(sk);
break;
}
} while (size);
mutex_unlock(&u->readlock);
if (state->msg)
scm_recv(sock, state->msg, &scm, flags);
else
scm_destroy(&scm);
out:
return copied ? : err;
}
static int unix_stream_read_actor(struct sk_buff *skb,
int skip, int chunk,
struct unix_stream_read_state *state)
{
int ret;
ret = skb_copy_datagram_msg(skb, UNIXCB(skb).consumed + skip,
state->msg, chunk);
return ret ?: chunk;
}
static int unix_stream_recvmsg(struct socket *sock, struct msghdr *msg,
size_t size, int flags)
{
struct unix_stream_read_state state = {
.recv_actor = unix_stream_read_actor,
.socket = sock,
.msg = msg,
.size = size,
.flags = flags
};
return unix_stream_read_generic(&state);
}
static ssize_t skb_unix_socket_splice(struct sock *sk,
struct pipe_inode_info *pipe,
struct splice_pipe_desc *spd)
{
int ret;
struct unix_sock *u = unix_sk(sk);
mutex_unlock(&u->readlock);
ret = splice_to_pipe(pipe, spd);
mutex_lock(&u->readlock);
return ret;
}
static int unix_stream_splice_actor(struct sk_buff *skb,
int skip, int chunk,
struct unix_stream_read_state *state)
{
return skb_splice_bits(skb, state->socket->sk,
UNIXCB(skb).consumed + skip,
state->pipe, chunk, state->splice_flags,
skb_unix_socket_splice);
}
static ssize_t unix_stream_splice_read(struct socket *sock, loff_t *ppos,
struct pipe_inode_info *pipe,
size_t size, unsigned int flags)
{
struct unix_stream_read_state state = {
.recv_actor = unix_stream_splice_actor,
.socket = sock,
.pipe = pipe,
.size = size,
.splice_flags = flags,
};
if (unlikely(*ppos))
return -ESPIPE;
if (sock->file->f_flags & O_NONBLOCK ||
flags & SPLICE_F_NONBLOCK)
state.flags = MSG_DONTWAIT;
return unix_stream_read_generic(&state);
}
static int unix_shutdown(struct socket *sock, int mode)
{
struct sock *sk = sock->sk;
struct sock *other;
if (mode < SHUT_RD || mode > SHUT_RDWR)
return -EINVAL;
/* This maps:
* SHUT_RD (0) -> RCV_SHUTDOWN (1)
* SHUT_WR (1) -> SEND_SHUTDOWN (2)
* SHUT_RDWR (2) -> SHUTDOWN_MASK (3)
*/
++mode;
unix_state_lock(sk);
sk->sk_shutdown |= mode;
other = unix_peer(sk);
if (other)
sock_hold(other);
unix_state_unlock(sk);
sk->sk_state_change(sk);
if (other &&
(sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET)) {
int peer_mode = 0;
if (mode&RCV_SHUTDOWN)
peer_mode |= SEND_SHUTDOWN;
if (mode&SEND_SHUTDOWN)
peer_mode |= RCV_SHUTDOWN;
unix_state_lock(other);
other->sk_shutdown |= peer_mode;
unix_state_unlock(other);
other->sk_state_change(other);
if (peer_mode == SHUTDOWN_MASK)
sk_wake_async(other, SOCK_WAKE_WAITD, POLL_HUP);
else if (peer_mode & RCV_SHUTDOWN)
sk_wake_async(other, SOCK_WAKE_WAITD, POLL_IN);
}
if (other)
sock_put(other);
return 0;
}
long unix_inq_len(struct sock *sk)
{
struct sk_buff *skb;
long amount = 0;
if (sk->sk_state == TCP_LISTEN)
return -EINVAL;
spin_lock(&sk->sk_receive_queue.lock);
if (sk->sk_type == SOCK_STREAM ||
sk->sk_type == SOCK_SEQPACKET) {
skb_queue_walk(&sk->sk_receive_queue, skb)
amount += unix_skb_len(skb);
} else {
skb = skb_peek(&sk->sk_receive_queue);
if (skb)
amount = skb->len;
}
spin_unlock(&sk->sk_receive_queue.lock);
return amount;
}
EXPORT_SYMBOL_GPL(unix_inq_len);
long unix_outq_len(struct sock *sk)
{
return sk_wmem_alloc_get(sk);
}
EXPORT_SYMBOL_GPL(unix_outq_len);
static int unix_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct sock *sk = sock->sk;
long amount = 0;
int err;
switch (cmd) {
case SIOCOUTQ:
amount = unix_outq_len(sk);
err = put_user(amount, (int __user *)arg);
break;
case SIOCINQ:
amount = unix_inq_len(sk);
if (amount < 0)
err = amount;
else
err = put_user(amount, (int __user *)arg);
break;
default:
err = -ENOIOCTLCMD;
break;
}
return err;
}
static unsigned int unix_poll(struct file *file, struct socket *sock, poll_table *wait)
{
struct sock *sk = sock->sk;
unsigned int mask;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
/* exceptional events? */
if (sk->sk_err)
mask |= POLLERR;
if (sk->sk_shutdown == SHUTDOWN_MASK)
mask |= POLLHUP;
if (sk->sk_shutdown & RCV_SHUTDOWN)
mask |= POLLRDHUP | POLLIN | POLLRDNORM;
/* readable? */
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
/* Connection-based need to check for termination and startup */
if ((sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET) &&
sk->sk_state == TCP_CLOSE)
mask |= POLLHUP;
/*
* we set writable also when the other side has shut down the
* connection. This prevents stuck sockets.
*/
if (unix_writable(sk))
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
return mask;
}
static unsigned int unix_dgram_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk, *other;
unsigned int mask, writable;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
/* exceptional events? */
if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
mask |= POLLERR |
(sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? POLLPRI : 0);
if (sk->sk_shutdown & RCV_SHUTDOWN)
mask |= POLLRDHUP | POLLIN | POLLRDNORM;
if (sk->sk_shutdown == SHUTDOWN_MASK)
mask |= POLLHUP;
/* readable? */
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
/* Connection-based need to check for termination and startup */
if (sk->sk_type == SOCK_SEQPACKET) {
if (sk->sk_state == TCP_CLOSE)
mask |= POLLHUP;
/* connection hasn't started yet? */
if (sk->sk_state == TCP_SYN_SENT)
return mask;
}
/* No write status requested, avoid expensive OUT tests. */
if (!(poll_requested_events(wait) & (POLLWRBAND|POLLWRNORM|POLLOUT)))
return mask;
writable = unix_writable(sk);
if (writable) {
unix_state_lock(sk);
other = unix_peer(sk);
if (other && unix_peer(other) != sk &&
unix_recvq_full(other) &&
unix_dgram_peer_wake_me(sk, other))
writable = 0;
unix_state_unlock(sk);
}
if (writable)
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
else
sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
return mask;
}
#ifdef CONFIG_PROC_FS
#define BUCKET_SPACE (BITS_PER_LONG - (UNIX_HASH_BITS + 1) - 1)
#define get_bucket(x) ((x) >> BUCKET_SPACE)
#define get_offset(x) ((x) & ((1L << BUCKET_SPACE) - 1))
#define set_bucket_offset(b, o) ((b) << BUCKET_SPACE | (o))
static struct sock *unix_from_bucket(struct seq_file *seq, loff_t *pos)
{
unsigned long offset = get_offset(*pos);
unsigned long bucket = get_bucket(*pos);
struct sock *sk;
unsigned long count = 0;
for (sk = sk_head(&unix_socket_table[bucket]); sk; sk = sk_next(sk)) {
if (sock_net(sk) != seq_file_net(seq))
continue;
if (++count == offset)
break;
}
return sk;
}
static struct sock *unix_next_socket(struct seq_file *seq,
struct sock *sk,
loff_t *pos)
{
unsigned long bucket;
while (sk > (struct sock *)SEQ_START_TOKEN) {
sk = sk_next(sk);
if (!sk)
goto next_bucket;
if (sock_net(sk) == seq_file_net(seq))
return sk;
}
do {
sk = unix_from_bucket(seq, pos);
if (sk)
return sk;
next_bucket:
bucket = get_bucket(*pos) + 1;
*pos = set_bucket_offset(bucket, 1);
} while (bucket < ARRAY_SIZE(unix_socket_table));
return NULL;
}
static void *unix_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(unix_table_lock)
{
spin_lock(&unix_table_lock);
if (!*pos)
return SEQ_START_TOKEN;
if (get_bucket(*pos) >= ARRAY_SIZE(unix_socket_table))
return NULL;
return unix_next_socket(seq, NULL, pos);
}
static void *unix_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
++*pos;
return unix_next_socket(seq, v, pos);
}
static void unix_seq_stop(struct seq_file *seq, void *v)
__releases(unix_table_lock)
{
spin_unlock(&unix_table_lock);
}
static int unix_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_puts(seq, "Num RefCount Protocol Flags Type St "
"Inode Path\n");
else {
struct sock *s = v;
struct unix_sock *u = unix_sk(s);
unix_state_lock(s);
seq_printf(seq, "%pK: %08X %08X %08X %04X %02X %5lu",
s,
atomic_read(&s->sk_refcnt),
0,
s->sk_state == TCP_LISTEN ? __SO_ACCEPTCON : 0,
s->sk_type,
s->sk_socket ?
(s->sk_state == TCP_ESTABLISHED ? SS_CONNECTED : SS_UNCONNECTED) :
(s->sk_state == TCP_ESTABLISHED ? SS_CONNECTING : SS_DISCONNECTING),
sock_i_ino(s));
if (u->addr) {
int i, len;
seq_putc(seq, ' ');
i = 0;
len = u->addr->len - sizeof(short);
if (!UNIX_ABSTRACT(s))
len--;
else {
seq_putc(seq, '@');
i++;
}
for ( ; i < len; i++)
seq_putc(seq, u->addr->name->sun_path[i]);
}
unix_state_unlock(s);
seq_putc(seq, '\n');
}
return 0;
}
static const struct seq_operations unix_seq_ops = {
.start = unix_seq_start,
.next = unix_seq_next,
.stop = unix_seq_stop,
.show = unix_seq_show,
};
static int unix_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &unix_seq_ops,
sizeof(struct seq_net_private));
}
static const struct file_operations unix_seq_fops = {
.owner = THIS_MODULE,
.open = unix_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif
static const struct net_proto_family unix_family_ops = {
.family = PF_UNIX,
.create = unix_create,
.owner = THIS_MODULE,
};
static int __net_init unix_net_init(struct net *net)
{
int error = -ENOMEM;
net->unx.sysctl_max_dgram_qlen = 10;
if (unix_sysctl_register(net))
goto out;
#ifdef CONFIG_PROC_FS
if (!proc_create("unix", 0, net->proc_net, &unix_seq_fops)) {
unix_sysctl_unregister(net);
goto out;
}
#endif
error = 0;
out:
return error;
}
static void __net_exit unix_net_exit(struct net *net)
{
unix_sysctl_unregister(net);
remove_proc_entry("unix", net->proc_net);
}
static struct pernet_operations unix_net_ops = {
.init = unix_net_init,
.exit = unix_net_exit,
};
static int __init af_unix_init(void)
{
int rc = -1;
BUILD_BUG_ON(sizeof(struct unix_skb_parms) > FIELD_SIZEOF(struct sk_buff, cb));
rc = proto_register(&unix_proto, 1);
if (rc != 0) {
pr_crit("%s: Cannot create unix_sock SLAB cache!\n", __func__);
goto out;
}
sock_register(&unix_family_ops);
register_pernet_subsys(&unix_net_ops);
out:
return rc;
}
static void __exit af_unix_exit(void)
{
sock_unregister(PF_UNIX);
proto_unregister(&unix_proto);
unregister_pernet_subsys(&unix_net_ops);
}
/* Earlier than device_initcall() so that other drivers invoking
request_module() don't end up in a loop when modprobe tries
to use a UNIX socket. But later than subsys_initcall() because
we depend on stuff initialised there */
fs_initcall(af_unix_init);
module_exit(af_unix_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_UNIX);
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5740_1 |
crossvul-cpp_data_good_3635_0 | #include <linux/etherdevice.h>
#include <linux/if_macvlan.h>
#include <linux/interrupt.h>
#include <linux/nsproxy.h>
#include <linux/compat.h>
#include <linux/if_tun.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/cache.h>
#include <linux/sched.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/wait.h>
#include <linux/cdev.h>
#include <linux/idr.h>
#include <linux/fs.h>
#include <net/net_namespace.h>
#include <net/rtnetlink.h>
#include <net/sock.h>
#include <linux/virtio_net.h>
/*
* A macvtap queue is the central object of this driver, it connects
* an open character device to a macvlan interface. There can be
* multiple queues on one interface, which map back to queues
* implemented in hardware on the underlying device.
*
* macvtap_proto is used to allocate queues through the sock allocation
* mechanism.
*
* TODO: multiqueue support is currently not implemented, even though
* macvtap is basically prepared for that. We will need to add this
* here as well as in virtio-net and qemu to get line rate on 10gbit
* adapters from a guest.
*/
struct macvtap_queue {
struct sock sk;
struct socket sock;
struct socket_wq wq;
int vnet_hdr_sz;
struct macvlan_dev __rcu *vlan;
struct file *file;
unsigned int flags;
};
static struct proto macvtap_proto = {
.name = "macvtap",
.owner = THIS_MODULE,
.obj_size = sizeof (struct macvtap_queue),
};
/*
* Variables for dealing with macvtaps device numbers.
*/
static dev_t macvtap_major;
#define MACVTAP_NUM_DEVS (1U << MINORBITS)
static DEFINE_MUTEX(minor_lock);
static DEFINE_IDR(minor_idr);
#define GOODCOPY_LEN 128
static struct class *macvtap_class;
static struct cdev macvtap_cdev;
static const struct proto_ops macvtap_socket_ops;
/*
* RCU usage:
* The macvtap_queue and the macvlan_dev are loosely coupled, the
* pointers from one to the other can only be read while rcu_read_lock
* or macvtap_lock is held.
*
* Both the file and the macvlan_dev hold a reference on the macvtap_queue
* through sock_hold(&q->sk). When the macvlan_dev goes away first,
* q->vlan becomes inaccessible. When the files gets closed,
* macvtap_get_queue() fails.
*
* There may still be references to the struct sock inside of the
* queue from outbound SKBs, but these never reference back to the
* file or the dev. The data structure is freed through __sk_free
* when both our references and any pending SKBs are gone.
*/
static DEFINE_SPINLOCK(macvtap_lock);
/*
* get_slot: return a [unused/occupied] slot in vlan->taps[]:
* - if 'q' is NULL, return the first empty slot;
* - otherwise, return the slot this pointer occupies.
*/
static int get_slot(struct macvlan_dev *vlan, struct macvtap_queue *q)
{
int i;
for (i = 0; i < MAX_MACVTAP_QUEUES; i++) {
if (rcu_dereference(vlan->taps[i]) == q)
return i;
}
/* Should never happen */
BUG_ON(1);
}
static int macvtap_set_queue(struct net_device *dev, struct file *file,
struct macvtap_queue *q)
{
struct macvlan_dev *vlan = netdev_priv(dev);
int index;
int err = -EBUSY;
spin_lock(&macvtap_lock);
if (vlan->numvtaps == MAX_MACVTAP_QUEUES)
goto out;
err = 0;
index = get_slot(vlan, NULL);
rcu_assign_pointer(q->vlan, vlan);
rcu_assign_pointer(vlan->taps[index], q);
sock_hold(&q->sk);
q->file = file;
file->private_data = q;
vlan->numvtaps++;
out:
spin_unlock(&macvtap_lock);
return err;
}
/*
* The file owning the queue got closed, give up both
* the reference that the files holds as well as the
* one from the macvlan_dev if that still exists.
*
* Using the spinlock makes sure that we don't get
* to the queue again after destroying it.
*/
static void macvtap_put_queue(struct macvtap_queue *q)
{
struct macvlan_dev *vlan;
spin_lock(&macvtap_lock);
vlan = rcu_dereference_protected(q->vlan,
lockdep_is_held(&macvtap_lock));
if (vlan) {
int index = get_slot(vlan, q);
RCU_INIT_POINTER(vlan->taps[index], NULL);
RCU_INIT_POINTER(q->vlan, NULL);
sock_put(&q->sk);
--vlan->numvtaps;
}
spin_unlock(&macvtap_lock);
synchronize_rcu();
sock_put(&q->sk);
}
/*
* Select a queue based on the rxq of the device on which this packet
* arrived. If the incoming device is not mq, calculate a flow hash
* to select a queue. If all fails, find the first available queue.
* Cache vlan->numvtaps since it can become zero during the execution
* of this function.
*/
static struct macvtap_queue *macvtap_get_queue(struct net_device *dev,
struct sk_buff *skb)
{
struct macvlan_dev *vlan = netdev_priv(dev);
struct macvtap_queue *tap = NULL;
int numvtaps = vlan->numvtaps;
__u32 rxq;
if (!numvtaps)
goto out;
/* Check if we can use flow to select a queue */
rxq = skb_get_rxhash(skb);
if (rxq) {
tap = rcu_dereference(vlan->taps[rxq % numvtaps]);
if (tap)
goto out;
}
if (likely(skb_rx_queue_recorded(skb))) {
rxq = skb_get_rx_queue(skb);
while (unlikely(rxq >= numvtaps))
rxq -= numvtaps;
tap = rcu_dereference(vlan->taps[rxq]);
if (tap)
goto out;
}
/* Everything failed - find first available queue */
for (rxq = 0; rxq < MAX_MACVTAP_QUEUES; rxq++) {
tap = rcu_dereference(vlan->taps[rxq]);
if (tap)
break;
}
out:
return tap;
}
/*
* The net_device is going away, give up the reference
* that it holds on all queues and safely set the pointer
* from the queues to NULL.
*/
static void macvtap_del_queues(struct net_device *dev)
{
struct macvlan_dev *vlan = netdev_priv(dev);
struct macvtap_queue *q, *qlist[MAX_MACVTAP_QUEUES];
int i, j = 0;
/* macvtap_put_queue can free some slots, so go through all slots */
spin_lock(&macvtap_lock);
for (i = 0; i < MAX_MACVTAP_QUEUES && vlan->numvtaps; i++) {
q = rcu_dereference_protected(vlan->taps[i],
lockdep_is_held(&macvtap_lock));
if (q) {
qlist[j++] = q;
RCU_INIT_POINTER(vlan->taps[i], NULL);
RCU_INIT_POINTER(q->vlan, NULL);
vlan->numvtaps--;
}
}
BUG_ON(vlan->numvtaps != 0);
/* guarantee that any future macvtap_set_queue will fail */
vlan->numvtaps = MAX_MACVTAP_QUEUES;
spin_unlock(&macvtap_lock);
synchronize_rcu();
for (--j; j >= 0; j--)
sock_put(&qlist[j]->sk);
}
/*
* Forward happens for data that gets sent from one macvlan
* endpoint to another one in bridge mode. We just take
* the skb and put it into the receive queue.
*/
static int macvtap_forward(struct net_device *dev, struct sk_buff *skb)
{
struct macvtap_queue *q = macvtap_get_queue(dev, skb);
if (!q)
goto drop;
if (skb_queue_len(&q->sk.sk_receive_queue) >= dev->tx_queue_len)
goto drop;
skb_queue_tail(&q->sk.sk_receive_queue, skb);
wake_up_interruptible_poll(sk_sleep(&q->sk), POLLIN | POLLRDNORM | POLLRDBAND);
return NET_RX_SUCCESS;
drop:
kfree_skb(skb);
return NET_RX_DROP;
}
/*
* Receive is for data from the external interface (lowerdev),
* in case of macvtap, we can treat that the same way as
* forward, which macvlan cannot.
*/
static int macvtap_receive(struct sk_buff *skb)
{
skb_push(skb, ETH_HLEN);
return macvtap_forward(skb->dev, skb);
}
static int macvtap_get_minor(struct macvlan_dev *vlan)
{
int retval = -ENOMEM;
int id;
mutex_lock(&minor_lock);
if (idr_pre_get(&minor_idr, GFP_KERNEL) == 0)
goto exit;
retval = idr_get_new_above(&minor_idr, vlan, 1, &id);
if (retval < 0) {
if (retval == -EAGAIN)
retval = -ENOMEM;
goto exit;
}
if (id < MACVTAP_NUM_DEVS) {
vlan->minor = id;
} else {
printk(KERN_ERR "too many macvtap devices\n");
retval = -EINVAL;
idr_remove(&minor_idr, id);
}
exit:
mutex_unlock(&minor_lock);
return retval;
}
static void macvtap_free_minor(struct macvlan_dev *vlan)
{
mutex_lock(&minor_lock);
if (vlan->minor) {
idr_remove(&minor_idr, vlan->minor);
vlan->minor = 0;
}
mutex_unlock(&minor_lock);
}
static struct net_device *dev_get_by_macvtap_minor(int minor)
{
struct net_device *dev = NULL;
struct macvlan_dev *vlan;
mutex_lock(&minor_lock);
vlan = idr_find(&minor_idr, minor);
if (vlan) {
dev = vlan->dev;
dev_hold(dev);
}
mutex_unlock(&minor_lock);
return dev;
}
static int macvtap_newlink(struct net *src_net,
struct net_device *dev,
struct nlattr *tb[],
struct nlattr *data[])
{
/* Don't put anything that may fail after macvlan_common_newlink
* because we can't undo what it does.
*/
return macvlan_common_newlink(src_net, dev, tb, data,
macvtap_receive, macvtap_forward);
}
static void macvtap_dellink(struct net_device *dev,
struct list_head *head)
{
macvtap_del_queues(dev);
macvlan_dellink(dev, head);
}
static void macvtap_setup(struct net_device *dev)
{
macvlan_common_setup(dev);
dev->tx_queue_len = TUN_READQ_SIZE;
}
static struct rtnl_link_ops macvtap_link_ops __read_mostly = {
.kind = "macvtap",
.setup = macvtap_setup,
.newlink = macvtap_newlink,
.dellink = macvtap_dellink,
};
static void macvtap_sock_write_space(struct sock *sk)
{
wait_queue_head_t *wqueue;
if (!sock_writeable(sk) ||
!test_and_clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags))
return;
wqueue = sk_sleep(sk);
if (wqueue && waitqueue_active(wqueue))
wake_up_interruptible_poll(wqueue, POLLOUT | POLLWRNORM | POLLWRBAND);
}
static void macvtap_sock_destruct(struct sock *sk)
{
skb_queue_purge(&sk->sk_receive_queue);
}
static int macvtap_open(struct inode *inode, struct file *file)
{
struct net *net = current->nsproxy->net_ns;
struct net_device *dev = dev_get_by_macvtap_minor(iminor(inode));
struct macvtap_queue *q;
int err;
err = -ENODEV;
if (!dev)
goto out;
err = -ENOMEM;
q = (struct macvtap_queue *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
&macvtap_proto);
if (!q)
goto out;
q->sock.wq = &q->wq;
init_waitqueue_head(&q->wq.wait);
q->sock.type = SOCK_RAW;
q->sock.state = SS_CONNECTED;
q->sock.file = file;
q->sock.ops = &macvtap_socket_ops;
sock_init_data(&q->sock, &q->sk);
q->sk.sk_write_space = macvtap_sock_write_space;
q->sk.sk_destruct = macvtap_sock_destruct;
q->flags = IFF_VNET_HDR | IFF_NO_PI | IFF_TAP;
q->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
/*
* so far only KVM virtio_net uses macvtap, enable zero copy between
* guest kernel and host kernel when lower device supports zerocopy
*
* The macvlan supports zerocopy iff the lower device supports zero
* copy so we don't have to look at the lower device directly.
*/
if ((dev->features & NETIF_F_HIGHDMA) && (dev->features & NETIF_F_SG))
sock_set_flag(&q->sk, SOCK_ZEROCOPY);
err = macvtap_set_queue(dev, file, q);
if (err)
sock_put(&q->sk);
out:
if (dev)
dev_put(dev);
return err;
}
static int macvtap_release(struct inode *inode, struct file *file)
{
struct macvtap_queue *q = file->private_data;
macvtap_put_queue(q);
return 0;
}
static unsigned int macvtap_poll(struct file *file, poll_table * wait)
{
struct macvtap_queue *q = file->private_data;
unsigned int mask = POLLERR;
if (!q)
goto out;
mask = 0;
poll_wait(file, &q->wq.wait, wait);
if (!skb_queue_empty(&q->sk.sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
if (sock_writeable(&q->sk) ||
(!test_and_set_bit(SOCK_ASYNC_NOSPACE, &q->sock.flags) &&
sock_writeable(&q->sk)))
mask |= POLLOUT | POLLWRNORM;
out:
return mask;
}
static inline struct sk_buff *macvtap_alloc_skb(struct sock *sk, size_t prepad,
size_t len, size_t linear,
int noblock, int *err)
{
struct sk_buff *skb;
/* Under a page? Don't bother with paged skb. */
if (prepad + len < PAGE_SIZE || !linear)
linear = len;
skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
err);
if (!skb)
return NULL;
skb_reserve(skb, prepad);
skb_put(skb, linear);
skb->data_len = len - linear;
skb->len += len - linear;
return skb;
}
/* set skb frags from iovec, this can move to core network code for reuse */
static int zerocopy_sg_from_iovec(struct sk_buff *skb, const struct iovec *from,
int offset, size_t count)
{
int len = iov_length(from, count) - offset;
int copy = skb_headlen(skb);
int size, offset1 = 0;
int i = 0;
/* Skip over from offset */
while (count && (offset >= from->iov_len)) {
offset -= from->iov_len;
++from;
--count;
}
/* copy up to skb headlen */
while (count && (copy > 0)) {
size = min_t(unsigned int, copy, from->iov_len - offset);
if (copy_from_user(skb->data + offset1, from->iov_base + offset,
size))
return -EFAULT;
if (copy > size) {
++from;
--count;
offset = 0;
} else
offset += size;
copy -= size;
offset1 += size;
}
if (len == offset1)
return 0;
while (count--) {
struct page *page[MAX_SKB_FRAGS];
int num_pages;
unsigned long base;
unsigned long truesize;
len = from->iov_len - offset;
if (!len) {
offset = 0;
++from;
continue;
}
base = (unsigned long)from->iov_base + offset;
size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT;
if (i + size > MAX_SKB_FRAGS)
return -EMSGSIZE;
num_pages = get_user_pages_fast(base, size, 0, &page[i]);
if (num_pages != size) {
for (i = 0; i < num_pages; i++)
put_page(page[i]);
return -EFAULT;
}
truesize = size * PAGE_SIZE;
skb->data_len += len;
skb->len += len;
skb->truesize += truesize;
atomic_add(truesize, &skb->sk->sk_wmem_alloc);
while (len) {
int off = base & ~PAGE_MASK;
int size = min_t(int, len, PAGE_SIZE - off);
__skb_fill_page_desc(skb, i, page[i], off, size);
skb_shinfo(skb)->nr_frags++;
/* increase sk_wmem_alloc */
base += size;
len -= size;
i++;
}
offset = 0;
++from;
}
return 0;
}
/*
* macvtap_skb_from_vnet_hdr and macvtap_skb_to_vnet_hdr should
* be shared with the tun/tap driver.
*/
static int macvtap_skb_from_vnet_hdr(struct sk_buff *skb,
struct virtio_net_hdr *vnet_hdr)
{
unsigned short gso_type = 0;
if (vnet_hdr->gso_type != VIRTIO_NET_HDR_GSO_NONE) {
switch (vnet_hdr->gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
case VIRTIO_NET_HDR_GSO_TCPV4:
gso_type = SKB_GSO_TCPV4;
break;
case VIRTIO_NET_HDR_GSO_TCPV6:
gso_type = SKB_GSO_TCPV6;
break;
case VIRTIO_NET_HDR_GSO_UDP:
gso_type = SKB_GSO_UDP;
break;
default:
return -EINVAL;
}
if (vnet_hdr->gso_type & VIRTIO_NET_HDR_GSO_ECN)
gso_type |= SKB_GSO_TCP_ECN;
if (vnet_hdr->gso_size == 0)
return -EINVAL;
}
if (vnet_hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
if (!skb_partial_csum_set(skb, vnet_hdr->csum_start,
vnet_hdr->csum_offset))
return -EINVAL;
}
if (vnet_hdr->gso_type != VIRTIO_NET_HDR_GSO_NONE) {
skb_shinfo(skb)->gso_size = vnet_hdr->gso_size;
skb_shinfo(skb)->gso_type = gso_type;
/* Header must be checked, and gso_segs computed. */
skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
skb_shinfo(skb)->gso_segs = 0;
}
return 0;
}
static int macvtap_skb_to_vnet_hdr(const struct sk_buff *skb,
struct virtio_net_hdr *vnet_hdr)
{
memset(vnet_hdr, 0, sizeof(*vnet_hdr));
if (skb_is_gso(skb)) {
struct skb_shared_info *sinfo = skb_shinfo(skb);
/* This is a hint as to how much should be linear. */
vnet_hdr->hdr_len = skb_headlen(skb);
vnet_hdr->gso_size = sinfo->gso_size;
if (sinfo->gso_type & SKB_GSO_TCPV4)
vnet_hdr->gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
else if (sinfo->gso_type & SKB_GSO_TCPV6)
vnet_hdr->gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
else if (sinfo->gso_type & SKB_GSO_UDP)
vnet_hdr->gso_type = VIRTIO_NET_HDR_GSO_UDP;
else
BUG();
if (sinfo->gso_type & SKB_GSO_TCP_ECN)
vnet_hdr->gso_type |= VIRTIO_NET_HDR_GSO_ECN;
} else
vnet_hdr->gso_type = VIRTIO_NET_HDR_GSO_NONE;
if (skb->ip_summed == CHECKSUM_PARTIAL) {
vnet_hdr->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
vnet_hdr->csum_start = skb_checksum_start_offset(skb);
vnet_hdr->csum_offset = skb->csum_offset;
} else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
vnet_hdr->flags = VIRTIO_NET_HDR_F_DATA_VALID;
} /* else everything is zero */
return 0;
}
/* Get packet from user space buffer */
static ssize_t macvtap_get_user(struct macvtap_queue *q, struct msghdr *m,
const struct iovec *iv, unsigned long total_len,
size_t count, int noblock)
{
struct sk_buff *skb;
struct macvlan_dev *vlan;
unsigned long len = total_len;
int err;
struct virtio_net_hdr vnet_hdr = { 0 };
int vnet_hdr_len = 0;
int copylen = 0;
bool zerocopy = false;
if (q->flags & IFF_VNET_HDR) {
vnet_hdr_len = q->vnet_hdr_sz;
err = -EINVAL;
if (len < vnet_hdr_len)
goto err;
len -= vnet_hdr_len;
err = memcpy_fromiovecend((void *)&vnet_hdr, iv, 0,
sizeof(vnet_hdr));
if (err < 0)
goto err;
if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 >
vnet_hdr.hdr_len)
vnet_hdr.hdr_len = vnet_hdr.csum_start +
vnet_hdr.csum_offset + 2;
err = -EINVAL;
if (vnet_hdr.hdr_len > len)
goto err;
}
err = -EINVAL;
if (unlikely(len < ETH_HLEN))
goto err;
err = -EMSGSIZE;
if (unlikely(count > UIO_MAXIOV))
goto err;
if (m && m->msg_control && sock_flag(&q->sk, SOCK_ZEROCOPY))
zerocopy = true;
if (zerocopy) {
/* Userspace may produce vectors with count greater than
* MAX_SKB_FRAGS, so we need to linearize parts of the skb
* to let the rest of data to be fit in the frags.
*/
if (count > MAX_SKB_FRAGS) {
copylen = iov_length(iv, count - MAX_SKB_FRAGS);
if (copylen < vnet_hdr_len)
copylen = 0;
else
copylen -= vnet_hdr_len;
}
/* There are 256 bytes to be copied in skb, so there is enough
* room for skb expand head in case it is used.
* The rest buffer is mapped from userspace.
*/
if (copylen < vnet_hdr.hdr_len)
copylen = vnet_hdr.hdr_len;
if (!copylen)
copylen = GOODCOPY_LEN;
} else
copylen = len;
skb = macvtap_alloc_skb(&q->sk, NET_IP_ALIGN, copylen,
vnet_hdr.hdr_len, noblock, &err);
if (!skb)
goto err;
if (zerocopy)
err = zerocopy_sg_from_iovec(skb, iv, vnet_hdr_len, count);
else
err = skb_copy_datagram_from_iovec(skb, 0, iv, vnet_hdr_len,
len);
if (err)
goto err_kfree;
skb_set_network_header(skb, ETH_HLEN);
skb_reset_mac_header(skb);
skb->protocol = eth_hdr(skb)->h_proto;
if (vnet_hdr_len) {
err = macvtap_skb_from_vnet_hdr(skb, &vnet_hdr);
if (err)
goto err_kfree;
}
rcu_read_lock_bh();
vlan = rcu_dereference_bh(q->vlan);
/* copy skb_ubuf_info for callback when skb has no error */
if (zerocopy) {
skb_shinfo(skb)->destructor_arg = m->msg_control;
skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
}
if (vlan)
macvlan_start_xmit(skb, vlan->dev);
else
kfree_skb(skb);
rcu_read_unlock_bh();
return total_len;
err_kfree:
kfree_skb(skb);
err:
rcu_read_lock_bh();
vlan = rcu_dereference_bh(q->vlan);
if (vlan)
vlan->dev->stats.tx_dropped++;
rcu_read_unlock_bh();
return err;
}
static ssize_t macvtap_aio_write(struct kiocb *iocb, const struct iovec *iv,
unsigned long count, loff_t pos)
{
struct file *file = iocb->ki_filp;
ssize_t result = -ENOLINK;
struct macvtap_queue *q = file->private_data;
result = macvtap_get_user(q, NULL, iv, iov_length(iv, count), count,
file->f_flags & O_NONBLOCK);
return result;
}
/* Put packet to the user space buffer */
static ssize_t macvtap_put_user(struct macvtap_queue *q,
const struct sk_buff *skb,
const struct iovec *iv, int len)
{
struct macvlan_dev *vlan;
int ret;
int vnet_hdr_len = 0;
if (q->flags & IFF_VNET_HDR) {
struct virtio_net_hdr vnet_hdr;
vnet_hdr_len = q->vnet_hdr_sz;
if ((len -= vnet_hdr_len) < 0)
return -EINVAL;
ret = macvtap_skb_to_vnet_hdr(skb, &vnet_hdr);
if (ret)
return ret;
if (memcpy_toiovecend(iv, (void *)&vnet_hdr, 0, sizeof(vnet_hdr)))
return -EFAULT;
}
len = min_t(int, skb->len, len);
ret = skb_copy_datagram_const_iovec(skb, 0, iv, vnet_hdr_len, len);
rcu_read_lock_bh();
vlan = rcu_dereference_bh(q->vlan);
if (vlan)
macvlan_count_rx(vlan, len, ret == 0, 0);
rcu_read_unlock_bh();
return ret ? ret : (len + vnet_hdr_len);
}
static ssize_t macvtap_do_read(struct macvtap_queue *q, struct kiocb *iocb,
const struct iovec *iv, unsigned long len,
int noblock)
{
DECLARE_WAITQUEUE(wait, current);
struct sk_buff *skb;
ssize_t ret = 0;
add_wait_queue(sk_sleep(&q->sk), &wait);
while (len) {
current->state = TASK_INTERRUPTIBLE;
/* Read frames from the queue */
skb = skb_dequeue(&q->sk.sk_receive_queue);
if (!skb) {
if (noblock) {
ret = -EAGAIN;
break;
}
if (signal_pending(current)) {
ret = -ERESTARTSYS;
break;
}
/* Nothing to read, let's sleep */
schedule();
continue;
}
ret = macvtap_put_user(q, skb, iv, len);
kfree_skb(skb);
break;
}
current->state = TASK_RUNNING;
remove_wait_queue(sk_sleep(&q->sk), &wait);
return ret;
}
static ssize_t macvtap_aio_read(struct kiocb *iocb, const struct iovec *iv,
unsigned long count, loff_t pos)
{
struct file *file = iocb->ki_filp;
struct macvtap_queue *q = file->private_data;
ssize_t len, ret = 0;
len = iov_length(iv, count);
if (len < 0) {
ret = -EINVAL;
goto out;
}
ret = macvtap_do_read(q, iocb, iv, len, file->f_flags & O_NONBLOCK);
ret = min_t(ssize_t, ret, len); /* XXX copied from tun.c. Why? */
out:
return ret;
}
/*
* provide compatibility with generic tun/tap interface
*/
static long macvtap_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct macvtap_queue *q = file->private_data;
struct macvlan_dev *vlan;
void __user *argp = (void __user *)arg;
struct ifreq __user *ifr = argp;
unsigned int __user *up = argp;
unsigned int u;
int __user *sp = argp;
int s;
int ret;
switch (cmd) {
case TUNSETIFF:
/* ignore the name, just look at flags */
if (get_user(u, &ifr->ifr_flags))
return -EFAULT;
ret = 0;
if ((u & ~IFF_VNET_HDR) != (IFF_NO_PI | IFF_TAP))
ret = -EINVAL;
else
q->flags = u;
return ret;
case TUNGETIFF:
rcu_read_lock_bh();
vlan = rcu_dereference_bh(q->vlan);
if (vlan)
dev_hold(vlan->dev);
rcu_read_unlock_bh();
if (!vlan)
return -ENOLINK;
ret = 0;
if (copy_to_user(&ifr->ifr_name, vlan->dev->name, IFNAMSIZ) ||
put_user(q->flags, &ifr->ifr_flags))
ret = -EFAULT;
dev_put(vlan->dev);
return ret;
case TUNGETFEATURES:
if (put_user(IFF_TAP | IFF_NO_PI | IFF_VNET_HDR, up))
return -EFAULT;
return 0;
case TUNSETSNDBUF:
if (get_user(u, up))
return -EFAULT;
q->sk.sk_sndbuf = u;
return 0;
case TUNGETVNETHDRSZ:
s = q->vnet_hdr_sz;
if (put_user(s, sp))
return -EFAULT;
return 0;
case TUNSETVNETHDRSZ:
if (get_user(s, sp))
return -EFAULT;
if (s < (int)sizeof(struct virtio_net_hdr))
return -EINVAL;
q->vnet_hdr_sz = s;
return 0;
case TUNSETOFFLOAD:
/* let the user check for future flags */
if (arg & ~(TUN_F_CSUM | TUN_F_TSO4 | TUN_F_TSO6 |
TUN_F_TSO_ECN | TUN_F_UFO))
return -EINVAL;
/* TODO: only accept frames with the features that
got enabled for forwarded frames */
if (!(q->flags & IFF_VNET_HDR))
return -EINVAL;
return 0;
default:
return -EINVAL;
}
}
#ifdef CONFIG_COMPAT
static long macvtap_compat_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
return macvtap_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
}
#endif
static const struct file_operations macvtap_fops = {
.owner = THIS_MODULE,
.open = macvtap_open,
.release = macvtap_release,
.aio_read = macvtap_aio_read,
.aio_write = macvtap_aio_write,
.poll = macvtap_poll,
.llseek = no_llseek,
.unlocked_ioctl = macvtap_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = macvtap_compat_ioctl,
#endif
};
static int macvtap_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t total_len)
{
struct macvtap_queue *q = container_of(sock, struct macvtap_queue, sock);
return macvtap_get_user(q, m, m->msg_iov, total_len, m->msg_iovlen,
m->msg_flags & MSG_DONTWAIT);
}
static int macvtap_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t total_len,
int flags)
{
struct macvtap_queue *q = container_of(sock, struct macvtap_queue, sock);
int ret;
if (flags & ~(MSG_DONTWAIT|MSG_TRUNC))
return -EINVAL;
ret = macvtap_do_read(q, iocb, m->msg_iov, total_len,
flags & MSG_DONTWAIT);
if (ret > total_len) {
m->msg_flags |= MSG_TRUNC;
ret = flags & MSG_TRUNC ? ret : total_len;
}
return ret;
}
/* Ops structure to mimic raw sockets with tun */
static const struct proto_ops macvtap_socket_ops = {
.sendmsg = macvtap_sendmsg,
.recvmsg = macvtap_recvmsg,
};
/* Get an underlying socket object from tun file. Returns error unless file is
* attached to a device. The returned object works like a packet socket, it
* can be used for sock_sendmsg/sock_recvmsg. The caller is responsible for
* holding a reference to the file for as long as the socket is in use. */
struct socket *macvtap_get_socket(struct file *file)
{
struct macvtap_queue *q;
if (file->f_op != &macvtap_fops)
return ERR_PTR(-EINVAL);
q = file->private_data;
if (!q)
return ERR_PTR(-EBADFD);
return &q->sock;
}
EXPORT_SYMBOL_GPL(macvtap_get_socket);
static int macvtap_device_event(struct notifier_block *unused,
unsigned long event, void *ptr)
{
struct net_device *dev = ptr;
struct macvlan_dev *vlan;
struct device *classdev;
dev_t devt;
int err;
if (dev->rtnl_link_ops != &macvtap_link_ops)
return NOTIFY_DONE;
vlan = netdev_priv(dev);
switch (event) {
case NETDEV_REGISTER:
/* Create the device node here after the network device has
* been registered but before register_netdevice has
* finished running.
*/
err = macvtap_get_minor(vlan);
if (err)
return notifier_from_errno(err);
devt = MKDEV(MAJOR(macvtap_major), vlan->minor);
classdev = device_create(macvtap_class, &dev->dev, devt,
dev, "tap%d", dev->ifindex);
if (IS_ERR(classdev)) {
macvtap_free_minor(vlan);
return notifier_from_errno(PTR_ERR(classdev));
}
break;
case NETDEV_UNREGISTER:
devt = MKDEV(MAJOR(macvtap_major), vlan->minor);
device_destroy(macvtap_class, devt);
macvtap_free_minor(vlan);
break;
}
return NOTIFY_DONE;
}
static struct notifier_block macvtap_notifier_block __read_mostly = {
.notifier_call = macvtap_device_event,
};
static int macvtap_init(void)
{
int err;
err = alloc_chrdev_region(&macvtap_major, 0,
MACVTAP_NUM_DEVS, "macvtap");
if (err)
goto out1;
cdev_init(&macvtap_cdev, &macvtap_fops);
err = cdev_add(&macvtap_cdev, macvtap_major, MACVTAP_NUM_DEVS);
if (err)
goto out2;
macvtap_class = class_create(THIS_MODULE, "macvtap");
if (IS_ERR(macvtap_class)) {
err = PTR_ERR(macvtap_class);
goto out3;
}
err = register_netdevice_notifier(&macvtap_notifier_block);
if (err)
goto out4;
err = macvlan_link_register(&macvtap_link_ops);
if (err)
goto out5;
return 0;
out5:
unregister_netdevice_notifier(&macvtap_notifier_block);
out4:
class_unregister(macvtap_class);
out3:
cdev_del(&macvtap_cdev);
out2:
unregister_chrdev_region(macvtap_major, MACVTAP_NUM_DEVS);
out1:
return err;
}
module_init(macvtap_init);
static void macvtap_exit(void)
{
rtnl_link_unregister(&macvtap_link_ops);
unregister_netdevice_notifier(&macvtap_notifier_block);
class_unregister(macvtap_class);
cdev_del(&macvtap_cdev);
unregister_chrdev_region(macvtap_major, MACVTAP_NUM_DEVS);
}
module_exit(macvtap_exit);
MODULE_ALIAS_RTNL_LINK("macvtap");
MODULE_AUTHOR("Arnd Bergmann <arnd@arndb.de>");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3635_0 |
crossvul-cpp_data_bad_160_4 | /*
* This file is part of Espruino, a JavaScript interpreter for Microcontrollers
*
* Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ----------------------------------------------------------------------------
* Variables
* ----------------------------------------------------------------------------
*/
#include "jsvar.h"
#include "jslex.h"
#include "jsparse.h"
#include "jswrap_json.h"
#include "jsinteractive.h"
#include "jswrapper.h"
#include "jswrap_math.h" // for jswrap_math_mod
#include "jswrap_object.h" // for jswrap_object_toString
#include "jswrap_arraybuffer.h" // for jsvNewTypedArray
#include "jswrap_dataview.h" // for jsvNewDataViewWithData
#ifdef DEBUG
/** When freeing, clear the references (nextChild/etc) in the JsVar.
* This means we can assert at the end of jsvFreePtr to make sure
* everything really is free. */
#define CLEAR_MEMORY_ON_FREE
#endif
/** Basically, JsVars are stored in one big array, so save the need for
* lots of memory allocation. On Linux, the arrays are in blocks, so that
* more blocks can be allocated. We can't use realloc on one big block as
* this may change the address of vars that are already locked!
*
*/
#ifdef RESIZABLE_JSVARS
JsVar **jsVarBlocks = 0;
unsigned int jsVarsSize = 0;
#define JSVAR_BLOCK_SIZE 4096
#define JSVAR_BLOCK_SHIFT 12
#else
JsVar jsVars[JSVAR_CACHE_SIZE];
unsigned int jsVarsSize = JSVAR_CACHE_SIZE;
#endif
typedef enum {
MEM_NOT_BUSY,
MEMBUSY_SYSTEM,
MEMBUSY_GC
} MemBusyType;
volatile bool touchedFreeList = false;
volatile JsVarRef jsVarFirstEmpty; ///< reference of first unused variable (variables are in a linked list)
volatile MemBusyType isMemoryBusy; ///< Are we doing garbage collection or similar, so can't access memory?
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
bool jsvIsRoot(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_ROOT; }
bool jsvIsPin(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_PIN; }
bool jsvIsSimpleInt(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_INTEGER; } // is just a very basic integer value
bool jsvIsInt(const JsVar *v) { return v && ((v->flags&JSV_VARTYPEMASK)==JSV_INTEGER || (v->flags&JSV_VARTYPEMASK)==JSV_PIN || (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT || (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_INT || (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_BOOL); }
bool jsvIsFloat(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_FLOAT; }
bool jsvIsBoolean(const JsVar *v) { return v && ((v->flags&JSV_VARTYPEMASK)==JSV_BOOLEAN || (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_BOOL); }
bool jsvIsString(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)>=_JSV_STRING_START && (v->flags&JSV_VARTYPEMASK)<=_JSV_STRING_END; } ///< String, or a NAME too
bool jsvIsBasicString(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)>=JSV_STRING_0 && (v->flags&JSV_VARTYPEMASK)<=JSV_STRING_MAX; } ///< Just a string (NOT a name)
bool jsvIsStringExt(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)>=JSV_STRING_EXT_0 && (v->flags&JSV_VARTYPEMASK)<=JSV_STRING_EXT_MAX; } ///< The extra bits dumped onto the end of a string to store more data
bool jsvIsFlatString(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_FLAT_STRING; }
bool jsvIsNativeString(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_NATIVE_STRING; }
bool jsvIsNumeric(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)>=_JSV_NUMERIC_START && (v->flags&JSV_VARTYPEMASK)<=_JSV_NUMERIC_END; }
bool jsvIsFunction(const JsVar *v) { return v && ((v->flags&JSV_VARTYPEMASK)==JSV_FUNCTION || (v->flags&JSV_VARTYPEMASK)==JSV_FUNCTION_RETURN); }
bool jsvIsFunctionReturn(const JsVar *v) { return v && ((v->flags&JSV_VARTYPEMASK)==JSV_FUNCTION_RETURN); } ///< Is this a function with an implicit 'return' at the start?
bool jsvIsFunctionParameter(const JsVar *v) { return v && (v->flags&JSV_NATIVE) && jsvIsString(v); }
bool jsvIsObject(const JsVar *v) { return v && (((v->flags&JSV_VARTYPEMASK)==JSV_OBJECT) || ((v->flags&JSV_VARTYPEMASK)==JSV_ROOT)); }
bool jsvIsArray(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_ARRAY; }
bool jsvIsArrayBuffer(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_ARRAYBUFFER; }
bool jsvIsArrayBufferName(const JsVar *v) { return v && (v->flags&(JSV_VARTYPEMASK))==JSV_ARRAYBUFFERNAME; }
bool jsvIsNative(const JsVar *v) { return v && (v->flags&JSV_NATIVE)!=0; }
bool jsvIsNativeFunction(const JsVar *v) { return v && (v->flags&(JSV_NATIVE|JSV_VARTYPEMASK))==(JSV_NATIVE|JSV_FUNCTION); }
bool jsvIsUndefined(const JsVar *v) { return v==0; }
bool jsvIsNull(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_NULL; }
bool jsvIsBasic(const JsVar *v) { return jsvIsNumeric(v) || jsvIsString(v);} ///< Is this *not* an array/object/etc
bool jsvIsName(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)>=_JSV_NAME_START && (v->flags&JSV_VARTYPEMASK)<=_JSV_NAME_END; } ///< NAMEs are what's used to name a variable (it is not the data itself)
/// Names with values have firstChild set to a value - AND NOT A REFERENCE
bool jsvIsNameWithValue(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)>=_JSV_NAME_WITH_VALUE_START && (v->flags&JSV_VARTYPEMASK)<=_JSV_NAME_WITH_VALUE_END; }
bool jsvIsNameInt(const JsVar *v) { return v && ((v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_INT || ((v->flags&JSV_VARTYPEMASK)>=JSV_NAME_STRING_INT_0 && (v->flags&JSV_VARTYPEMASK)<=JSV_NAME_STRING_INT_MAX)); }
bool jsvIsNameIntInt(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_INT; }
bool jsvIsNameIntBool(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_BOOL; }
/// What happens when we access a variable that doesn't exist. We get a NAME where the next + previous siblings point to the object that may one day contain them
bool jsvIsNewChild(const JsVar *v) { return jsvIsName(v) && jsvGetNextSibling(v) && jsvGetNextSibling(v)==jsvGetPrevSibling(v); }
/// Are var.varData.ref.* (excl pad) used for data (so we expect them not to be empty)
bool jsvIsRefUsedForData(const JsVar *v) { return jsvIsStringExt(v) || (jsvIsString(v)&&!jsvIsName(v)) || jsvIsFloat(v) || jsvIsNativeFunction(v) || jsvIsArrayBuffer(v) || jsvIsArrayBufferName(v); }
/// Can the given variable be converted into an integer without loss of precision
bool jsvIsIntegerish(const JsVar *v) { return jsvIsInt(v) || jsvIsPin(v) || jsvIsBoolean(v) || jsvIsNull(v); }
bool jsvIsIterable(const JsVar *v) {
return jsvIsArray(v) || jsvIsObject(v) || jsvIsFunction(v) ||
jsvIsString(v) || jsvIsArrayBuffer(v);
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
/** Return a pointer - UNSAFE for null refs.
* This is effectively a Lock without locking! */
static ALWAYS_INLINE JsVar *jsvGetAddressOf(JsVarRef ref) {
assert(ref);
#ifdef RESIZABLE_JSVARS
JsVarRef t = ref-1;
return &jsVarBlocks[t>>JSVAR_BLOCK_SHIFT][t&(JSVAR_BLOCK_SIZE-1)];
#else
return &jsVars[ref-1];
#endif
}
JsVar *_jsvGetAddressOf(JsVarRef ref) {
return jsvGetAddressOf(ref);
}
#ifdef JSVARREF_PACKED_BITS
#define JSVARREF_PACKED_BIT_MASK ((1U<<JSVARREF_PACKED_BITS)-1)
JsVarRef jsvGetFirstChild(const JsVar *v) { return (JsVarRef)(v->varData.ref.firstChild | (((v->varData.ref.pack)&JSVARREF_PACKED_BIT_MASK))<<8); }
JsVarRefSigned jsvGetFirstChildSigned(const JsVar *v) {
JsVarRefSigned r = (JsVarRefSigned)jsvGetFirstChild(v);
if (r & (1<<(JSVARREF_PACKED_BITS+7)))
r -= 1<<(JSVARREF_PACKED_BITS+8);
return r;
}
JsVarRef jsvGetNextSibling(const JsVar *v) { return (JsVarRef)(v->varData.ref.nextSibling | (((v->varData.ref.pack >> (JSVARREF_PACKED_BITS*2))&JSVARREF_PACKED_BIT_MASK))<<8); }
JsVarRef jsvGetPrevSibling(const JsVar *v) { return (JsVarRef)(v->varData.ref.prevSibling | (((v->varData.ref.pack >> (JSVARREF_PACKED_BITS*3))&JSVARREF_PACKED_BIT_MASK))<<8); }
void jsvSetFirstChild(JsVar *v, JsVarRef r) {
v->varData.ref.firstChild = (unsigned char)(r & 0xFF);
v->varData.ref.pack = (unsigned char)((v->varData.ref.pack & ~JSVARREF_PACKED_BIT_MASK) | ((r >> 8) & JSVARREF_PACKED_BIT_MASK));
}
void jsvSetNextSibling(JsVar *v, JsVarRef r) {
v->varData.ref.nextSibling = (unsigned char)(r & 0xFF);
v->varData.ref.pack = (unsigned char)((v->varData.ref.pack & ~(JSVARREF_PACKED_BIT_MASK<<(JSVARREF_PACKED_BITS*2))) | (((r >> 8) & JSVARREF_PACKED_BIT_MASK) << (JSVARREF_PACKED_BITS*2)));
}
void jsvSetPrevSibling(JsVar *v, JsVarRef r) {
v->varData.ref.prevSibling = (unsigned char)(r & 0xFF);
v->varData.ref.pack = (unsigned char)((v->varData.ref.pack & ~(JSVARREF_PACKED_BIT_MASK<<(JSVARREF_PACKED_BITS*3))) | (((r >> 8) & JSVARREF_PACKED_BIT_MASK) << (JSVARREF_PACKED_BITS*3)));
}
/* lastchild stores the upper 2 bits in JsVarFlags because then STRING_EXT can use one more character! */
JsVarRef jsvGetLastChild(const JsVar *v) {
return (JsVarRef)(v->varData.ref.lastChild | (((v->flags >> JSV_LASTCHILD_BIT_SHIFT)&JSVARREF_PACKED_BIT_MASK))<<8);
}
void jsvSetLastChild(JsVar *v, JsVarRef r) {
v->varData.ref.lastChild = (unsigned char)(r & 0xFF);
v->flags = (v->flags & ~JSV_LASTCHILD_BIT_MASK) | ((r >> 8) << JSV_LASTCHILD_BIT_SHIFT);
}
#endif
// For debugging/testing ONLY - maximum # of vars we are allowed to use
void jsvSetMaxVarsUsed(unsigned int size) {
#ifdef RESIZABLE_JSVARS
assert(size < JSVAR_BLOCK_SIZE); // remember - this is only for DEBUGGING - as such it doesn't use multiple blocks
#else
assert(size < JSVAR_CACHE_SIZE);
#endif
jsVarsSize = size;
}
// maps the empty variables in...
void jsvCreateEmptyVarList() {
assert(!isMemoryBusy);
isMemoryBusy = MEMBUSY_SYSTEM;
jsVarFirstEmpty = 0;
JsVar firstVar; // temporary var to simplify code in the loop below
jsvSetNextSibling(&firstVar, 0);
JsVar *lastEmpty = &firstVar;
JsVarRef i;
for (i=1;i<=jsVarsSize;i++) {
JsVar *var = jsvGetAddressOf(i);
if ((var->flags&JSV_VARTYPEMASK) == JSV_UNUSED) {
jsvSetNextSibling(lastEmpty, i);
lastEmpty = var;
} else if (jsvIsFlatString(var)) {
// skip over used blocks for flat strings
i = (JsVarRef)(i+jsvGetFlatStringBlocks(var));
}
}
jsvSetNextSibling(lastEmpty, 0);
jsVarFirstEmpty = jsvGetNextSibling(&firstVar);
isMemoryBusy = MEM_NOT_BUSY;
}
/* Removes the empty variable counter, cleaving clear runs of 0s
where no data resides. This helps if compressing the variables
for storage. */
void jsvClearEmptyVarList() {
assert(!isMemoryBusy);
isMemoryBusy = MEMBUSY_SYSTEM;
jsVarFirstEmpty = 0;
JsVarRef i;
for (i=1;i<=jsVarsSize;i++) {
JsVar *var = jsvGetAddressOf(i);
if ((var->flags&JSV_VARTYPEMASK) == JSV_UNUSED) {
// completely zero it (JSV_UNUSED==0, so it still stays the same)
memset((void*)var,0,sizeof(JsVar));
} else if (jsvIsFlatString(var)) {
// skip over used blocks for flat strings
i = (JsVarRef)(i+jsvGetFlatStringBlocks(var));
}
}
isMemoryBusy = MEM_NOT_BUSY;
}
void jsvSoftInit() {
jsvCreateEmptyVarList();
}
void jsvSoftKill() {
jsvClearEmptyVarList();
}
/** This links all JsVars together, so we can have our nice
* linked list of free JsVars. It returns the ref of the first
* item - that we should set jsVarFirstEmpty to (if it is 0) */
static JsVarRef jsvInitJsVars(JsVarRef start, unsigned int count) {
JsVarRef i;
for (i=start;i<start+count;i++) {
JsVar *v = jsvGetAddressOf(i);
v->flags = JSV_UNUSED;
// v->locks = 0; // locks is 0 anyway because it is stored in flags
jsvSetNextSibling(v, (JsVarRef)(i+1)); // link to next
}
jsvSetNextSibling(jsvGetAddressOf((JsVarRef)(start+count-1)), (JsVarRef)0); // set the final one to 0
return start;
}
void jsvInit() {
#ifdef RESIZABLE_JSVARS
jsVarsSize = JSVAR_BLOCK_SIZE;
jsVarBlocks = malloc(sizeof(JsVar*)); // just 1
jsVarBlocks[0] = malloc(sizeof(JsVar) * JSVAR_BLOCK_SIZE);
#endif
jsVarFirstEmpty = jsvInitJsVars(1/*first*/, jsVarsSize);
jsvSoftInit();
}
void jsvKill() {
#ifdef RESIZABLE_JSVARS
unsigned int i;
for (i=0;i<jsVarsSize>>JSVAR_BLOCK_SHIFT;i++)
free(jsVarBlocks[i]);
free(jsVarBlocks);
jsVarBlocks = 0;
jsVarsSize = 0;
#endif
}
/** Find or create the ROOT variable item - used mainly
* if recovering from a saved state. */
JsVar *jsvFindOrCreateRoot() {
JsVarRef i;
for (i=1;i<=jsVarsSize;i++)
if (jsvIsRoot(jsvGetAddressOf(i)))
return jsvLock(i);
return jsvRef(jsvNewWithFlags(JSV_ROOT));
}
/// Get number of memory records (JsVars) used
unsigned int jsvGetMemoryUsage() {
unsigned int usage = 0;
unsigned int i;
for (i=1;i<=jsVarsSize;i++) {
JsVar *v = jsvGetAddressOf((JsVarRef)i);
if ((v->flags&JSV_VARTYPEMASK) != JSV_UNUSED) {
usage++;
if (jsvIsFlatString(v)) {
unsigned int b = (unsigned int)jsvGetFlatStringBlocks(v);
i+=b;
usage+=b;
}
}
}
return usage;
}
/// Get total amount of memory records
unsigned int jsvGetMemoryTotal() {
return jsVarsSize;
}
/// Try and allocate more memory - only works if RESIZABLE_JSVARS is defined
void jsvSetMemoryTotal(unsigned int jsNewVarCount) {
#ifdef RESIZABLE_JSVARS
assert(!isMemoryBusy);
if (jsNewVarCount <= jsVarsSize) return; // never allow us to have less!
isMemoryBusy = MEMBUSY_SYSTEM;
// When resizing, we just allocate a bunch more
unsigned int oldSize = jsVarsSize;
unsigned int oldBlockCount = jsVarsSize >> JSVAR_BLOCK_SHIFT;
unsigned int newBlockCount = (jsNewVarCount+JSVAR_BLOCK_SIZE-1) >> JSVAR_BLOCK_SHIFT;
jsVarsSize = newBlockCount << JSVAR_BLOCK_SHIFT;
// resize block table
jsVarBlocks = realloc(jsVarBlocks, sizeof(JsVar*)*newBlockCount);
// allocate more blocks
unsigned int i;
for (i=oldBlockCount;i<newBlockCount;i++)
jsVarBlocks[i] = malloc(sizeof(JsVar) * JSVAR_BLOCK_SIZE);
/** and now reset all the newly allocated vars. We know jsVarFirstEmpty
* is 0 (because jsiFreeMoreMemory returned 0) so we can just assign it. */
assert(!jsVarFirstEmpty);
jsVarFirstEmpty = jsvInitJsVars(oldSize+1, jsVarsSize-oldSize);
// jsiConsolePrintf("Resized memory from %d blocks to %d\n", oldBlockCount, newBlockCount);
touchedFreeList = true;
isMemoryBusy = MEM_NOT_BUSY;
#else
NOT_USED(jsNewVarCount);
assert(0);
#endif
}
bool jsvMoreFreeVariablesThan(unsigned int vars) {
if (!vars) return false;
JsVarRef r = jsVarFirstEmpty;
while (r) {
if (!vars--) return true;
r = jsvGetNextSibling(jsvGetAddressOf(r));
}
return false;
}
/// Get whether memory is full or not
bool jsvIsMemoryFull() {
return !jsVarFirstEmpty;
}
// Show what is still allocated, for debugging memory problems
void jsvShowAllocated() {
JsVarRef i;
for (i=1;i<=jsVarsSize;i++) {
if ((jsvGetAddressOf(i)->flags&JSV_VARTYPEMASK) != JSV_UNUSED) {
jsiConsolePrintf("USED VAR #%d:",i);
jsvTrace(jsvGetAddressOf(i), 2);
}
}
}
bool jsvHasCharacterData(const JsVar *v) {
return jsvIsString(v) || jsvIsStringExt(v);
}
bool jsvHasStringExt(const JsVar *v) {
return jsvIsString(v) || jsvIsStringExt(v);
}
bool jsvHasChildren(const JsVar *v) {
return jsvIsFunction(v) || jsvIsObject(v) || jsvIsArray(v) || jsvIsRoot(v);
}
/// Is this variable a type that uses firstChild to point to a single Variable (ie. it doesn't have multiple children)
bool jsvHasSingleChild(const JsVar *v) {
return jsvIsArrayBuffer(v) ||
(jsvIsName(v) && !jsvIsNameWithValue(v));
}
/** Return the is the number of characters this one JsVar can contain, NOT string length (eg, a chain of JsVars)
* This will return an invalid length when applied to Flat Strings */
size_t jsvGetMaxCharactersInVar(const JsVar *v) {
// see jsvCopy - we need to know about this in there too
if (jsvIsStringExt(v)) return JSVAR_DATA_STRING_MAX_LEN;
assert(jsvHasCharacterData(v));
if (jsvIsName(v)) return JSVAR_DATA_STRING_NAME_LEN;
return JSVAR_DATA_STRING_LEN;
}
/// This is the number of characters a JsVar can contain, NOT string length
size_t jsvGetCharactersInVar(const JsVar *v) {
unsigned int f = v->flags&JSV_VARTYPEMASK;
if (f == JSV_FLAT_STRING)
return (size_t)v->varData.integer;
if (f == JSV_NATIVE_STRING)
return (size_t)v->varData.nativeStr.len;
assert(f >= JSV_NAME_STRING_INT_0);
assert((JSV_NAME_STRING_INT_0 < JSV_NAME_STRING_0) &&
(JSV_NAME_STRING_0 < JSV_STRING_0) &&
(JSV_STRING_0 < JSV_STRING_EXT_0)); // this relies on ordering
if (f<=JSV_NAME_STRING_MAX) {
if (f<=JSV_NAME_STRING_INT_MAX)
return f-JSV_NAME_STRING_INT_0;
else
return f-JSV_NAME_STRING_0;
} else {
if (f<=JSV_STRING_MAX) return f-JSV_STRING_0;
assert(f <= JSV_STRING_EXT_MAX);
return f - JSV_STRING_EXT_0;
}
}
/// This is the number of characters a JsVar can contain, NOT string length
void jsvSetCharactersInVar(JsVar *v, size_t chars) {
unsigned int f = v->flags&JSV_VARTYPEMASK;
assert(!(jsvIsFlatString(v) || jsvIsNativeString(v)));
JsVarFlags m = (JsVarFlags)(v->flags&~JSV_VARTYPEMASK);
assert(f >= JSV_NAME_STRING_INT_0);
assert((JSV_NAME_STRING_INT_0 < JSV_NAME_STRING_0) &&
(JSV_NAME_STRING_0 < JSV_STRING_0) &&
(JSV_STRING_0 < JSV_STRING_EXT_0)); // this relies on ordering
if (f<=JSV_NAME_STRING_MAX) {
assert(chars <= JSVAR_DATA_STRING_NAME_LEN);
if (f<=JSV_NAME_STRING_INT_MAX)
v->flags = (JsVarFlags)(m | (JSV_NAME_STRING_INT_0+chars));
else
v->flags = (JsVarFlags)(m | (JSV_NAME_STRING_0+chars));
} else {
if (f<=JSV_STRING_MAX) {
assert(chars <= JSVAR_DATA_STRING_LEN);
v->flags = (JsVarFlags)(m | (JSV_STRING_0+chars));
} else {
assert(chars <= JSVAR_DATA_STRING_MAX_LEN);
assert(f <= JSV_STRING_EXT_MAX);
v->flags = (JsVarFlags)(m | (JSV_STRING_EXT_0+chars));
}
}
}
void jsvResetVariable(JsVar *v, JsVarFlags flags) {
assert((v->flags&JSV_VARTYPEMASK) == JSV_UNUSED);
// make sure we clear all data...
/* Force a proper zeroing of all data. We don't use
* memset because that'd create a function call. This
* should just generate a bunch of STR instructions */
unsigned int i;
assert((sizeof(JsVar)&3) == 0); // must be a multiple of 4 in size
for (i=0;i<sizeof(JsVar)/sizeof(uint32_t);i++)
((uint32_t*)v)[i] = 0;
// set flags
assert(!(flags & JSV_LOCK_MASK));
v->flags = flags | JSV_LOCK_ONE;
}
JsVar *jsvNewWithFlags(JsVarFlags flags) {
if (isMemoryBusy) {
jsErrorFlags |= JSERR_MEMORY_BUSY;
return 0;
}
JsVar *v = 0;
jshInterruptOff(); // to allow this to be used from an IRQ
if (jsVarFirstEmpty!=0) {
v = jsvGetAddressOf(jsVarFirstEmpty); // jsvResetVariable will lock
jsVarFirstEmpty = jsvGetNextSibling(v); // move our reference to the next in the fr
touchedFreeList = true;
}
jshInterruptOn();
if (v) {
assert(v->flags == JSV_UNUSED);
// Cope with IRQs/multi-threading when getting a new free variable
/* JsVarRef empty;
JsVarRef next;
JsVar *v;
do {
empty = jsVarFirstEmpty;
v = jsvGetAddressOf(empty); // jsvResetVariable will lock
next = jsvGetNextSibling(v); // move our reference to the next in the free list
touchedFreeList = true;
} while (!__sync_bool_compare_and_swap(&jsVarFirstEmpty, empty, next));
assert(v->flags == JSV_UNUSED);*/
jsvResetVariable(v, flags); // setup variable, and add one lock
// return pointer
return v;
}
jsErrorFlags |= JSERR_LOW_MEMORY;
/* If we're calling from an IRQ, do NOT try and do fancy
* stuff to free memory */
if (jshIsInInterrupt()) {
return 0;
}
/* we don't have memory - second last hope - run garbage collector */
if (jsvGarbageCollect()) {
return jsvNewWithFlags(flags); // if it freed something, continue
}
/* we don't have memory - last hope - ask jsInteractive to try and free some it
may have kicking around */
if (jsiFreeMoreMemory()) {
return jsvNewWithFlags(flags);
}
/* We couldn't claim any more memory by Garbage collecting... */
#ifdef RESIZABLE_JSVARS
jsvSetMemoryTotal(jsVarsSize*2);
return jsvNewWithFlags(flags);
#else
// On a micro, we're screwed.
jsErrorFlags |= JSERR_MEMORY;
jspSetInterrupted(true);
return 0;
#endif
}
static NO_INLINE void jsvFreePtrInternal(JsVar *var) {
assert(jsvGetLocks(var)==0);
var->flags = JSV_UNUSED;
// add this to our free list
jshInterruptOff(); // to allow this to be used from an IRQ
jsvSetNextSibling(var, jsVarFirstEmpty);
jsVarFirstEmpty = jsvGetRef(var);
touchedFreeList = true;
jshInterruptOn();
}
ALWAYS_INLINE void jsvFreePtr(JsVar *var) {
/* To be here, we're not supposed to be part of anything else. If
* we were, we'd have been freed by jsvGarbageCollect */
assert((!jsvGetNextSibling(var) && !jsvGetPrevSibling(var)) || // check that next/prevSibling are not set
jsvIsRefUsedForData(var) || // UNLESS we're part of a string and nextSibling/prevSibling are used for string data
(jsvIsName(var) && (jsvGetNextSibling(var)==jsvGetPrevSibling(var)))); // UNLESS we're signalling that we're jsvIsNewChild
// Names that Link to other things
if (jsvIsNameWithValue(var)) {
#ifdef CLEAR_MEMORY_ON_FREE
jsvSetFirstChild(var, 0); // it just contained random data - zero it
#endif // CLEAR_MEMORY_ON_FREE
} else if (jsvHasSingleChild(var)) {
if (jsvGetFirstChild(var)) {
JsVar *child = jsvLock(jsvGetFirstChild(var));
jsvUnRef(child);
#ifdef CLEAR_MEMORY_ON_FREE
jsvSetFirstChild(var, 0); // unlink the child
#endif // CLEAR_MEMORY_ON_FREE
jsvUnLock(child); // unlock should trigger a free
}
}
/* No else, because a String Name may have a single child, but
* also StringExts */
/* Now, free children - see jsvar.h comments for how! */
if (jsvHasStringExt(var)) {
// Free the string without recursing
JsVarRef stringDataRef = jsvGetLastChild(var);
#ifdef CLEAR_MEMORY_ON_FREE
jsvSetLastChild(var, 0);
#endif // CLEAR_MEMORY_ON_FREE
while (stringDataRef) {
JsVar *child = jsvGetAddressOf(stringDataRef);
assert(jsvIsStringExt(child));
stringDataRef = jsvGetLastChild(child);
jsvFreePtrInternal(child);
}
// We might be a flat string
if (jsvIsFlatString(var)) {
// in which case we need to free all the blocks.
size_t count = jsvGetFlatStringBlocks(var);
JsVarRef i = (JsVarRef)(jsvGetRef(var)+count);
// do it in reverse, so the free list ends up in kind of the right order
while (count--) {
JsVar *p = jsvGetAddressOf(i--);
p->flags = JSV_UNUSED; // set locks to 0 so the assert in jsvFreePtrInternal doesn't get fed up
jsvFreePtrInternal(p);
}
} else if (jsvIsBasicString(var)) {
#ifdef CLEAR_MEMORY_ON_FREE
jsvSetFirstChild(var, 0); // firstchild could have had string data in
#endif // CLEAR_MEMORY_ON_FREE
}
}
/* NO ELSE HERE - because jsvIsNewChild stuff can be for Names, which
can be ints or strings */
if (jsvHasChildren(var)) {
JsVarRef childref = jsvGetFirstChild(var);
#ifdef CLEAR_MEMORY_ON_FREE
jsvSetFirstChild(var, 0);
jsvSetLastChild(var, 0);
#endif // CLEAR_MEMORY_ON_FREE
while (childref) {
JsVar *child = jsvLock(childref);
assert(jsvIsName(child));
childref = jsvGetNextSibling(child);
jsvSetPrevSibling(child, 0);
jsvSetNextSibling(child, 0);
jsvUnRef(child);
jsvUnLock(child);
}
} else {
#ifdef CLEAR_MEMORY_ON_FREE
#if JSVARREF_SIZE==1
assert(jsvIsFloat(var) || !jsvGetFirstChild(var));
assert(jsvIsFloat(var) || !jsvGetLastChild(var));
#else
assert(!jsvGetFirstChild(var)); // strings use firstchild now as well
assert(!jsvGetLastChild(var));
#endif
#endif // CLEAR_MEMORY_ON_FREE
if (jsvIsName(var)) {
assert(jsvGetNextSibling(var)==jsvGetPrevSibling(var)); // the case for jsvIsNewChild
if (jsvGetNextSibling(var)) {
jsvUnRefRef(jsvGetNextSibling(var));
jsvUnRefRef(jsvGetPrevSibling(var));
}
}
}
// free!
jsvFreePtrInternal(var);
}
/// Get a reference from a var - SAFE for null vars
ALWAYS_INLINE JsVarRef jsvGetRef(JsVar *var) {
if (!var) return 0;
#ifdef RESIZABLE_JSVARS
unsigned int i, c = jsVarsSize>>JSVAR_BLOCK_SHIFT;
for (i=0;i<c;i++) {
if (var>=jsVarBlocks[i] && var<&jsVarBlocks[i][JSVAR_BLOCK_SIZE]) {
JsVarRef r = (JsVarRef)(1 + (i<<JSVAR_BLOCK_SHIFT) + (var - jsVarBlocks[i]));
return r;
}
}
return 0;
#else
return (JsVarRef)(1 + (var - jsVars));
#endif
}
/// Lock this reference and return a pointer - UNSAFE for null refs
ALWAYS_INLINE JsVar *jsvLock(JsVarRef ref) {
JsVar *var = jsvGetAddressOf(ref);
//var->locks++;
assert(jsvGetLocks(var) < JSV_LOCK_MAX);
var->flags += JSV_LOCK_ONE;
#ifdef DEBUG
if (jsvGetLocks(var)==0) {
jsError("Too many locks to Variable!");
//jsPrint("Var #");jsPrintInt(ref);jsPrint("\n");
}
#endif
return var;
}
/// Lock this pointer and return a pointer - UNSAFE for null pointer
ALWAYS_INLINE JsVar *jsvLockAgain(JsVar *var) {
assert(var);
assert(jsvGetLocks(var) < JSV_LOCK_MAX);
var->flags += JSV_LOCK_ONE;
return var;
}
/// Lock this pointer and return a pointer - UNSAFE for null pointer
ALWAYS_INLINE JsVar *jsvLockAgainSafe(JsVar *var) {
return var ? jsvLockAgain(var) : 0;
}
// CALL ONLY FROM jsvUnlock
// jsvGetLocks(var) must == 0
static NO_INLINE void jsvUnLockFreeIfNeeded(JsVar *var) {
assert(jsvGetLocks(var) == 0);
/* if we know we're free, then we can just free this variable right now.
* Loops of variables are handled by the Garbage Collector.
* Note: we checked locks already in jsvUnLock as it is fastest to check */
if (jsvGetRefs(var) == 0 &&
jsvHasRef(var) &&
(var->flags&JSV_VARTYPEMASK)!=JSV_UNUSED) { // we might be in an IRQ now, with GC in the main thread. If so, don't free!
jsvFreePtr(var);
}
}
/// Unlock this variable - this is SAFE for null variables
ALWAYS_INLINE void jsvUnLock(JsVar *var) {
if (!var) return;
assert(jsvGetLocks(var)>0);
var->flags -= JSV_LOCK_ONE;
// Now see if we can properly free the data
// Note: we check locks first as they are already in a register
if ((var->flags & JSV_LOCK_MASK) == 0) jsvUnLockFreeIfNeeded(var);
}
/// Unlock 2 variables in one go
void jsvUnLock2(JsVar *var1, JsVar *var2) {
jsvUnLock(var1);
jsvUnLock(var2);
}
/// Unlock 3 variables in one go
void jsvUnLock3(JsVar *var1, JsVar *var2, JsVar *var3) {
jsvUnLock(var1);
jsvUnLock(var2);
jsvUnLock(var3);
}
/// Unlock 4 variables in one go
void jsvUnLock4(JsVar *var1, JsVar *var2, JsVar *var3, JsVar *var4) {
jsvUnLock(var1);
jsvUnLock(var2);
jsvUnLock(var3);
jsvUnLock(var4);
}
/// Unlock an array of variables
NO_INLINE void jsvUnLockMany(unsigned int count, JsVar **vars) {
while (count) jsvUnLock(vars[--count]);
}
/// Reference - set this variable as used by something
JsVar *jsvRef(JsVar *var) {
assert(var && jsvHasRef(var));
jsvSetRefs(var, (JsVarRefCounter)(jsvGetRefs(var)+1));
assert(jsvGetRefs(var));
return var;
}
/// Unreference - set this variable as not used by anything
void jsvUnRef(JsVar *var) {
assert(var && jsvGetRefs(var)>0 && jsvHasRef(var));
jsvSetRefs(var, (JsVarRefCounter)(jsvGetRefs(var)-1));
}
/// Helper fn, Reference - set this variable as used by something
JsVarRef jsvRefRef(JsVarRef ref) {
JsVar *v;
assert(ref);
v = jsvLock(ref);
assert(!jsvIsStringExt(v));
jsvRef(v);
jsvUnLock(v);
return ref;
}
/// Helper fn, Unreference - set this variable as not used by anything
JsVarRef jsvUnRefRef(JsVarRef ref) {
JsVar *v;
assert(ref);
v = jsvLock(ref);
assert(!jsvIsStringExt(v));
jsvUnRef(v);
jsvUnLock(v);
return 0;
}
JsVar *jsvNewFlatStringOfLength(unsigned int byteLength) {
if (isMemoryBusy) {
jsErrorFlags |= JSERR_MEMORY_BUSY;
return 0;
}
// Work out how many blocks we need. One for the header, plus some for the characters
size_t requiredBlocks = 1 + ((byteLength+sizeof(JsVar)-1) / sizeof(JsVar));
JsVar *flatString = 0;
/* Now try and find a contiguous set of 'requiredBlocks' blocks by
searching the free list. This can be done as long as nobody's
messed with the free list in the mean time (which we check for with
touchedFreeList). If someone has messed with it, we restart.*/
bool memoryTouched = true;
while (memoryTouched) {
memoryTouched = false;
touchedFreeList = false;
JsVarRef beforeStartBlock = 0;
JsVarRef curr = jsVarFirstEmpty;
JsVarRef startBlock = curr;
unsigned int blockCount = 1;
while (curr && !touchedFreeList) {
JsVar *currVar = jsvGetAddressOf(curr);
JsVarRef next = jsvGetNextSibling(currVar);
#ifdef RESIZABLE_JSVARS
if (next && jsvGetAddressOf(next)==currVar+1) {
#else
if (next == curr+1) {
#endif
blockCount++;
if (blockCount>=requiredBlocks) {
JsVar *nextVar = jsvGetAddressOf(next);
JsVarRef nextFree = jsvGetNextSibling(nextVar);
jshInterruptOff();
if (!touchedFreeList) {
// we're there! Quickly re-link free list
if (beforeStartBlock) {
jsvSetNextSibling(jsvGetAddressOf(beforeStartBlock),nextFree);
} else {
jsVarFirstEmpty = nextFree;
}
flatString = jsvGetAddressOf(startBlock);
// Set up the header block (including one lock)
jsvResetVariable(flatString, JSV_FLAT_STRING);
flatString->varData.integer = (JsVarInt)byteLength;
}
jshInterruptOn();
// if success, break out!
if (flatString) break;
}
} else {
// this block is not immediately after the last - restart run
blockCount = 1;
beforeStartBlock = curr;
startBlock = next;
}
// move to next!
curr = next;
}
// memory list has been touched - restart!
if (touchedFreeList) {
memoryTouched = true;
}
}
/* Nope... we couldn't find a free string. It could be because
* the free list is fragmented, so GCing might well fix it - which
* we'll try. */
if (!flatString) {
if (jsvGarbageCollect())
return jsvNewFlatStringOfLength(byteLength);
return 0;
}
/* We now have the string! All that's left is to clear it,
* which we can do outside of an IRQ */
// clear data
memset((char*)&flatString[1], 0, sizeof(JsVar)*(requiredBlocks-1));
/* We did mess with the free list - set it here in case we
are trying to create a flat string in an IRQ while trying to
make one outside the IRQ too */
touchedFreeList = true;
// and we're done
return flatString;
}
JsVar *jsvNewFromString(const char *str) {
// Create a var
JsVar *first = jsvNewWithFlags(JSV_STRING_0);
if (!first) return 0; // out of memory
// Now we copy the string, but keep creating new jsVars if we go
// over the end
JsVar *var = jsvLockAgain(first);
while (*str) {
// copy data in
size_t i, l = jsvGetMaxCharactersInVar(var);
for (i=0;i<l && *str;i++)
var->varData.str[i] = *(str++);
// we already set the variable data to 0, so no need for adding one
// we've stopped if the string was empty
jsvSetCharactersInVar(var, i);
// if there is still some left, it's because we filled up our var...
// make a new one, link it in, and unlock the old one.
if (*str) {
JsVar *next = jsvNewWithFlags(JSV_STRING_EXT_0);
if (!next) {
// Truncating string as not enough memory
jsvUnLock(var);
return first;
}
// we don't ref, because StringExts are never reffed as they only have one owner (and ALWAYS have an owner)
jsvSetLastChild(var, jsvGetRef(next));
jsvUnLock(var);
var = next;
}
}
jsvUnLock(var);
// return
return first;
}
JsVar *jsvNewStringOfLength(unsigned int byteLength, const char *initialData) {
// if string large enough, try and make a flat string instead
if (byteLength > JSV_FLAT_STRING_BREAK_EVEN) {
JsVar *v = jsvNewFlatStringOfLength(byteLength);
if (v) {
if (initialData) jsvSetString(v, initialData, byteLength);
return v;
}
}
// Create a var
JsVar *first = jsvNewWithFlags(JSV_STRING_0);
if (!first) return 0; // out of memory, will have already set flag
// Now keep creating enough new jsVars
JsVar *var = jsvLockAgain(first);
while (true) {
// copy data in
unsigned int l = (unsigned int)jsvGetMaxCharactersInVar(var);
if (l>=byteLength) {
if (initialData)
memcpy(var->varData.str, initialData, byteLength);
// we've got enough
jsvSetCharactersInVar(var, byteLength);
break;
} else {
if (initialData) {
memcpy(var->varData.str, initialData, l);
initialData+=l;
}
// We need more
jsvSetCharactersInVar(var, l);
byteLength -= l;
// Make a new one, link it in, and unlock the old one.
JsVar *next = jsvNewWithFlags(JSV_STRING_EXT_0);
if (!next) break; // out of memory, will have already set flag
// we don't ref, because StringExts are never reffed as they only have one owner (and ALWAYS have an owner)
jsvSetLastChild(var, jsvGetRef(next));
jsvUnLock(var);
var = next;
}
}
jsvUnLock(var);
// return
return first;
}
JsVar *jsvNewFromInteger(JsVarInt value) {
JsVar *var = jsvNewWithFlags(JSV_INTEGER);
if (!var) return 0; // no memory
var->varData.integer = value;
return var;
}
JsVar *jsvNewFromBool(bool value) {
JsVar *var = jsvNewWithFlags(JSV_BOOLEAN);
if (!var) return 0; // no memory
var->varData.integer = value ? 1 : 0;
return var;
}
JsVar *jsvNewFromFloat(JsVarFloat value) {
JsVar *var = jsvNewWithFlags(JSV_FLOAT);
if (!var) return 0; // no memory
var->varData.floating = value;
return var;
}
JsVar *jsvNewFromLongInteger(long long value) {
if (value>=-2147483648LL && value<=2147483647LL)
return jsvNewFromInteger((JsVarInt)value);
else
return jsvNewFromFloat((JsVarFloat)value);
}
JsVar *jsvMakeIntoVariableName(JsVar *var, JsVar *valueOrZero) {
if (!var) return 0;
assert(jsvGetRefs(var)==0); // make sure it's unused
assert(jsvIsSimpleInt(var) || jsvIsString(var));
JsVarFlags varType = (var->flags & JSV_VARTYPEMASK);
if (varType==JSV_INTEGER) {
int t = JSV_NAME_INT;
if ((jsvIsInt(valueOrZero) || jsvIsBoolean(valueOrZero)) && !jsvIsPin(valueOrZero)) {
JsVarInt v = valueOrZero->varData.integer;
if (v>=JSVARREF_MIN && v<=JSVARREF_MAX) {
t = jsvIsInt(valueOrZero) ? JSV_NAME_INT_INT : JSV_NAME_INT_BOOL;
jsvSetFirstChild(var, (JsVarRef)v);
valueOrZero = 0;
}
}
var->flags = (JsVarFlags)(var->flags & ~JSV_VARTYPEMASK) | t;
} else if (varType>=_JSV_STRING_START && varType<=_JSV_STRING_END) {
if (jsvGetCharactersInVar(var) > JSVAR_DATA_STRING_NAME_LEN) {
/* Argh. String is too large to fit in a JSV_NAME! We must chomp make
* new STRINGEXTs to put the data in
*/
JsvStringIterator it;
jsvStringIteratorNew(&it, var, JSVAR_DATA_STRING_NAME_LEN);
JsVar *startExt = jsvNewWithFlags(JSV_STRING_EXT_0);
JsVar *ext = jsvLockAgainSafe(startExt);
size_t nChars = 0;
while (ext && jsvStringIteratorHasChar(&it)) {
if (nChars >= JSVAR_DATA_STRING_MAX_LEN) {
jsvSetCharactersInVar(ext, nChars);
JsVar *ext2 = jsvNewWithFlags(JSV_STRING_EXT_0);
if (ext2) {
jsvSetLastChild(ext, jsvGetRef(ext2));
}
jsvUnLock(ext);
ext = ext2;
nChars = 0;
}
ext->varData.str[nChars++] = jsvStringIteratorGetChar(&it);
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
if (ext) {
jsvSetCharactersInVar(ext, nChars);
jsvUnLock(ext);
}
jsvSetCharactersInVar(var, JSVAR_DATA_STRING_NAME_LEN);
// Free any old stringexts
JsVarRef oldRef = jsvGetLastChild(var);
while (oldRef) {
JsVar *v = jsvGetAddressOf(oldRef);
oldRef = jsvGetLastChild(v);
jsvFreePtrInternal(v);
}
// set up new stringexts
jsvSetLastChild(var, jsvGetRef(startExt));
jsvSetNextSibling(var, 0);
jsvSetPrevSibling(var, 0);
jsvSetFirstChild(var, 0);
jsvUnLock(startExt);
}
size_t t = JSV_NAME_STRING_0;
if (jsvIsInt(valueOrZero) && !jsvIsPin(valueOrZero)) {
JsVarInt v = valueOrZero->varData.integer;
if (v>=JSVARREF_MIN && v<=JSVARREF_MAX) {
t = JSV_NAME_STRING_INT_0;
jsvSetFirstChild(var, (JsVarRef)v);
valueOrZero = 0;
}
} else
jsvSetFirstChild(var, 0);
var->flags = (var->flags & (JsVarFlags)~JSV_VARTYPEMASK) | (t+jsvGetCharactersInVar(var));
} else assert(0);
if (valueOrZero)
jsvSetFirstChild(var, jsvGetRef(jsvRef(valueOrZero)));
return var;
}
void jsvMakeFunctionParameter(JsVar *v) {
assert(jsvIsString(v));
if (!jsvIsName(v)) jsvMakeIntoVariableName(v,0);
v->flags = (JsVarFlags)(v->flags | JSV_NATIVE);
}
JsVar *jsvNewFromPin(int pin) {
JsVar *v = jsvNewFromInteger((JsVarInt)pin);
if (v) {
v->flags = (JsVarFlags)((v->flags & ~JSV_VARTYPEMASK) | JSV_PIN);
}
return v;
}
JsVar *jsvNewObject() {
return jsvNewWithFlags(JSV_OBJECT);
}
JsVar *jsvNewEmptyArray() {
return jsvNewWithFlags(JSV_ARRAY);
}
/// Create an array containing the given elements
JsVar *jsvNewArray(JsVar **elements, int elementCount) {
JsVar *arr = jsvNewEmptyArray();
if (!arr) return 0;
int i;
for (i=0;i<elementCount;i++)
jsvArrayPush(arr, elements[i]);
return arr;
}
JsVar *jsvNewNativeFunction(void (*ptr)(void), unsigned short argTypes) {
JsVar *func = jsvNewWithFlags(JSV_FUNCTION | JSV_NATIVE);
if (!func) return 0;
func->varData.native.ptr = ptr;
func->varData.native.argTypes = argTypes;
return func;
}
JsVar *jsvNewNativeString(char *ptr, size_t len) {
if (len>JSV_NATIVE_STR_MAX_LENGTH) len=JSV_NATIVE_STR_MAX_LENGTH; // crop string to what we can store in nativeStr.len
JsVar *str = jsvNewWithFlags(JSV_NATIVE_STRING);
if (!str) return 0;
str->varData.nativeStr.ptr = ptr;
str->varData.nativeStr.len = (uint16_t)len;
return str;
}
void *jsvGetNativeFunctionPtr(const JsVar *function) {
/* see descriptions in jsvar.h. If we have a child called JSPARSE_FUNCTION_CODE_NAME
* then we execute code straight from that */
JsVar *flatString = jsvFindChildFromString((JsVar*)function, JSPARSE_FUNCTION_CODE_NAME, 0);
if (flatString) {
flatString = jsvSkipNameAndUnLock(flatString);
void *v = (void*)((size_t)function->varData.native.ptr + (char*)jsvGetFlatStringPointer(flatString));
jsvUnLock(flatString);
return v;
} else
return (void *)function->varData.native.ptr;
}
/// Create a new ArrayBuffer backed by the given string. If length is not specified, it will be worked out
JsVar *jsvNewArrayBufferFromString(JsVar *str, unsigned int lengthOrZero) {
JsVar *arr = jsvNewWithFlags(JSV_ARRAYBUFFER);
if (!arr) return 0;
jsvSetFirstChild(arr, jsvGetRef(jsvRef(str)));
arr->varData.arraybuffer.type = ARRAYBUFFERVIEW_ARRAYBUFFER;
assert(arr->varData.arraybuffer.byteOffset == 0);
if (lengthOrZero==0) lengthOrZero = (unsigned int)jsvGetStringLength(str);
arr->varData.arraybuffer.length = (unsigned short)lengthOrZero;
return arr;
}
bool jsvIsBasicVarEqual(JsVar *a, JsVar *b) {
// quick checks
if (a==b) return true;
if (!a || !b) return false; // one of them is undefined
// OPT: would this be useful as compare instead?
assert(jsvIsBasic(a) && jsvIsBasic(b));
if (jsvIsNumeric(a) && jsvIsNumeric(b)) {
if (jsvIsIntegerish(a)) {
if (jsvIsIntegerish(b)) {
return a->varData.integer == b->varData.integer;
} else {
assert(jsvIsFloat(b));
return a->varData.integer == b->varData.floating;
}
} else {
assert(jsvIsFloat(a));
if (jsvIsIntegerish(b)) {
return a->varData.floating == b->varData.integer;
} else {
assert(jsvIsFloat(b));
return a->varData.floating == b->varData.floating;
}
}
} else if (jsvIsString(a) && jsvIsString(b)) {
JsvStringIterator ita, itb;
jsvStringIteratorNew(&ita, a, 0);
jsvStringIteratorNew(&itb, b, 0);
while (true) {
char a = jsvStringIteratorGetChar(&ita);
char b = jsvStringIteratorGetChar(&itb);
if (a != b) {
jsvStringIteratorFree(&ita);
jsvStringIteratorFree(&itb);
return false;
}
if (!a) { // equal, but end of string
jsvStringIteratorFree(&ita);
jsvStringIteratorFree(&itb);
return true;
}
jsvStringIteratorNext(&ita);
jsvStringIteratorNext(&itb);
}
// we never get here
return false; // make compiler happy
} else {
//TODO: are there any other combinations we should check here?? String v int?
return false;
}
}
bool jsvIsEqual(JsVar *a, JsVar *b) {
if (jsvIsBasic(a) && jsvIsBasic(b))
return jsvIsBasicVarEqual(a,b);
return jsvGetRef(a)==jsvGetRef(b);
}
/// Get a const string representing this variable - if we can. Otherwise return 0
const char *jsvGetConstString(const JsVar *v) {
if (jsvIsUndefined(v)) {
return "undefined";
} else if (jsvIsNull(v)) {
return "null";
} else if (jsvIsBoolean(v)) {
return jsvGetBool(v) ? "true" : "false";
}
return 0;
}
/// Return the 'type' of the JS variable (eg. JS's typeof operator)
const char *jsvGetTypeOf(const JsVar *v) {
if (jsvIsUndefined(v)) return "undefined";
if (jsvIsNull(v) || jsvIsObject(v) ||
jsvIsArray(v) || jsvIsArrayBuffer(v)) return "object";
if (jsvIsFunction(v)) return "function";
if (jsvIsString(v)) return "string";
if (jsvIsBoolean(v)) return "boolean";
if (jsvIsNumeric(v)) return "number";
return "?";
}
/// Return the JsVar, or if it's an object and has a valueOf function, call that
JsVar *jsvGetValueOf(JsVar *v) {
if (!jsvIsObject(v)) return jsvLockAgainSafe(v);
JsVar *valueOf = jspGetNamedField(v, "valueOf", false);
if (!jsvIsFunction(valueOf)) {
jsvUnLock(valueOf);
return jsvLockAgain(v);
}
v = jspeFunctionCall(valueOf, 0, v, false, 0, 0);
jsvUnLock(valueOf);
return v;
}
/** Save this var as a string to the given buffer, and return how long it was (return val doesn't include terminating 0)
If the buffer length is exceeded, the returned value will == len */
size_t jsvGetString(const JsVar *v, char *str, size_t len) {
const char *s = jsvGetConstString(v);
if (s) {
strncpy(str, s, len);
return strlen(s);
} else if (jsvIsInt(v)) {
itostr(v->varData.integer, str, 10);
return strlen(str);
} else if (jsvIsFloat(v)) {
ftoa_bounded(v->varData.floating, str, len);
return strlen(str);
} else if (jsvHasCharacterData(v)) {
assert(!jsvIsStringExt(v));
size_t l = len;
JsvStringIterator it;
jsvStringIteratorNewConst(&it, v, 0);
while (jsvStringIteratorHasChar(&it)) {
if (l--<=1) {
*str = 0;
jsvStringIteratorFree(&it);
return len;
}
*(str++) = jsvStringIteratorGetChar(&it);
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
*str = 0;
return len-l;
} else {
// Try and get as a JsVar string, and try again
JsVar *stringVar = jsvAsString((JsVar*)v, false); // we know we're casting to non-const here
if (stringVar) {
size_t l = jsvGetString(stringVar, str, len); // call again - but this time with converted var
jsvUnLock(stringVar);
return l;
} else {
strncpy(str, "", len);
jsExceptionHere(JSET_INTERNALERROR, "Variable type cannot be converted to string");
return 0;
}
}
}
/// Get len bytes of string data from this string. Does not error if string len is not equal to len
size_t jsvGetStringChars(const JsVar *v, size_t startChar, char *str, size_t len) {
assert(jsvHasCharacterData(v));
size_t l = len;
JsvStringIterator it;
jsvStringIteratorNewConst(&it, v, startChar);
while (jsvStringIteratorHasChar(&it)) {
if (l--<=0) {
jsvStringIteratorFree(&it);
return len;
}
*(str++) = jsvStringIteratorGetChar(&it);
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
*str = 0;
return len-l;
}
/// Set the Data in this string. This must JUST overwrite - not extend or shrink
void jsvSetString(JsVar *v, const char *str, size_t len) {
assert(jsvHasCharacterData(v));
// the iterator checks, so it is safe not to assert if the length is different
//assert(len == jsvGetStringLength(v));
JsvStringIterator it;
jsvStringIteratorNew(&it, v, 0);
size_t i;
for (i=0;i<len;i++) {
jsvStringIteratorSetChar(&it, str[i]);
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
}
/** If var is a string, lock and return it, else
* create a new string. unlockVar means this will auto-unlock 'var' */
JsVar *jsvAsString(JsVar *v, bool unlockVar) {
JsVar *str = 0;
// If it is string-ish, but not quite a string, copy it
if (jsvHasCharacterData(v) && jsvIsName(v)) {
str = jsvNewFromStringVar(v,0,JSVAPPENDSTRINGVAR_MAXLENGTH);
} else if (jsvIsString(v)) { // If it is a string - just return a reference
str = jsvLockAgain(v);
} else if (jsvIsObject(v)) { // If it is an object and we can call toString on it
JsVar *toStringFn = jspGetNamedField(v, "toString", false);
if (toStringFn && toStringFn->varData.native.ptr != (void (*)(void))jswrap_object_toString) {
// Function found and it's not the default one - execute it
JsVar *result = jspExecuteFunction(toStringFn,v,0,0);
jsvUnLock(toStringFn);
str = jsvAsString(result, true);
} else {
jsvUnLock(toStringFn);
str = jsvNewFromString("[object Object]");
}
} else {
const char *constChar = jsvGetConstString(v);
assert(JS_NUMBER_BUFFER_SIZE>=10);
char buf[JS_NUMBER_BUFFER_SIZE];
if (constChar) {
// if we could get this as a simple const char, do that..
str = jsvNewFromString(constChar);
} else if (jsvIsPin(v)) {
jshGetPinString(buf, (Pin)v->varData.integer);
str = jsvNewFromString(buf);
} else if (jsvIsInt(v)) {
itostr(v->varData.integer, buf, 10);
str = jsvNewFromString(buf);
} else if (jsvIsFloat(v)) {
ftoa_bounded(v->varData.floating, buf, sizeof(buf));
str = jsvNewFromString(buf);
} else if (jsvIsArray(v) || jsvIsArrayBuffer(v)) {
JsVar *filler = jsvNewFromString(",");
str = jsvArrayJoin(v, filler);
jsvUnLock(filler);
} else if (jsvIsFunction(v)) {
str = jsvNewFromEmptyString();
if (str) jsfGetJSON(v, str, JSON_NONE);
} else {
jsExceptionHere(JSET_INTERNALERROR, "Variable type cannot be converted to string");
str = 0;
}
}
if (unlockVar) jsvUnLock(v);
return str;
}
JsVar *jsvAsFlatString(JsVar *var) {
if (jsvIsFlatString(var)) return jsvLockAgain(var);
JsVar *str = jsvAsString(var, false);
size_t len = jsvGetStringLength(str);
JsVar *flat = jsvNewFlatStringOfLength((unsigned int)len);
if (flat) {
JsvStringIterator src;
JsvStringIterator dst;
jsvStringIteratorNew(&src, str, 0);
jsvStringIteratorNew(&dst, flat, 0);
while (len--) {
jsvStringIteratorSetChar(&dst, jsvStringIteratorGetChar(&src));
if (len>0) {
jsvStringIteratorNext(&src);
jsvStringIteratorNext(&dst);
}
}
jsvStringIteratorFree(&src);
jsvStringIteratorFree(&dst);
}
jsvUnLock(str);
return flat;
}
/** Given a JsVar meant to be an index to an array, convert it to
* the actual variable type we'll use to access the array. For example
* a["0"] is actually translated to a[0]
*/
JsVar *jsvAsArrayIndex(JsVar *index) {
if (jsvIsSimpleInt(index)) {
return jsvLockAgain(index); // we're ok!
} else if (jsvIsString(index)) {
/* Index filtering (bug #19) - if we have an array index A that is:
is_string(A) && int_to_string(string_to_int(A)) == A
then convert it to an integer. Shouldn't be too nasty for performance
as we only do this when accessing an array with a string */
if (jsvIsStringNumericStrict(index)) {
JsVar *i = jsvNewFromInteger(jsvGetInteger(index));
JsVar *is = jsvAsString(i, false);
if (jsvCompareString(index,is,0,0,false)==0) {
// two items are identical - use the integer
jsvUnLock(is);
return i;
} else {
// not identical, use as a string
jsvUnLock2(i,is);
}
}
} else if (jsvIsFloat(index)) {
// if it's a float that is actually integral, return an integer...
JsVarFloat v = jsvGetFloat(index);
JsVarInt vi = jsvGetInteger(index);
if (v == vi) return jsvNewFromInteger(vi);
}
// else if it's not a simple numeric type, convert it to a string
return jsvAsString(index, false);
}
/** Same as jsvAsArrayIndex, but ensures that 'index' is unlocked */
JsVar *jsvAsArrayIndexAndUnLock(JsVar *a) {
JsVar *b = jsvAsArrayIndex(a);
jsvUnLock(a);
return b;
}
/// Returns true if the string is empty - faster than jsvGetStringLength(v)==0
bool jsvIsEmptyString(JsVar *v) {
if (!jsvHasCharacterData(v)) return true;
return jsvGetCharactersInVar(v)==0;
}
size_t jsvGetStringLength(const JsVar *v) {
size_t strLength = 0;
const JsVar *var = v;
JsVar *newVar = 0;
if (!jsvHasCharacterData(v)) return 0;
while (var) {
JsVarRef ref = jsvGetLastChild(var);
strLength += jsvGetCharactersInVar(var);
// Go to next
jsvUnLock(newVar); // note use of if (ref), not var
var = newVar = ref ? jsvLock(ref) : 0;
}
jsvUnLock(newVar); // note use of if (ref), not var
return strLength;
}
size_t jsvGetFlatStringBlocks(const JsVar *v) {
assert(jsvIsFlatString(v));
return ((size_t)v->varData.integer+sizeof(JsVar)-1) / sizeof(JsVar);
}
char *jsvGetFlatStringPointer(JsVar *v) {
assert(jsvIsFlatString(v));
if (!jsvIsFlatString(v)) return 0;
return (char*)(v+1); // pointer to the next JsVar
}
JsVar *jsvGetFlatStringFromPointer(char *v) {
JsVar *secondVar = (JsVar*)v;
JsVar *flatStr = secondVar-1;
assert(jsvIsFlatString(flatStr));
return flatStr;
}
/// If the variable points to a *flat* area of memory, return a pointer (and set length). Otherwise return 0.
char *jsvGetDataPointer(JsVar *v, size_t *len) {
assert(len);
if (jsvIsArrayBuffer(v)) {
/* Arraybuffers generally use some kind of string to store their data.
* Find it, then call ourselves again to figure out if we can get a
* raw pointer to it. */
JsVar *d = jsvGetArrayBufferBackingString(v);
char *r = jsvGetDataPointer(d, len);
jsvUnLock(d);
if (r) {
r += v->varData.arraybuffer.byteOffset;
*len = v->varData.arraybuffer.length;
}
return r;
}
if (jsvIsNativeString(v)) {
*len = v->varData.nativeStr.len;
return (char*)v->varData.nativeStr.ptr;
}
if (jsvIsFlatString(v)) {
*len = jsvGetStringLength(v);
return jsvGetFlatStringPointer(v);
}
return 0;
}
// IN A STRING get the number of lines in the string (min=1)
size_t jsvGetLinesInString(JsVar *v) {
size_t lines = 1;
JsvStringIterator it;
jsvStringIteratorNew(&it, v, 0);
while (jsvStringIteratorHasChar(&it)) {
if (jsvStringIteratorGetChar(&it)=='\n') lines++;
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
return lines;
}
// IN A STRING Get the number of characters on a line - lines start at 1
size_t jsvGetCharsOnLine(JsVar *v, size_t line) {
size_t currentLine = 1;
size_t chars = 0;
JsvStringIterator it;
jsvStringIteratorNew(&it, v, 0);
while (jsvStringIteratorHasChar(&it)) {
if (jsvStringIteratorGetChar(&it)=='\n') {
currentLine++;
if (currentLine > line) break;
} else if (currentLine==line) chars++;
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
return chars;
}
// IN A STRING, get the 1-based line and column of the given character. Both values must be non-null
void jsvGetLineAndCol(JsVar *v, size_t charIdx, size_t *line, size_t *col) {
size_t x = 1;
size_t y = 1;
size_t n = 0;
assert(line && col);
JsvStringIterator it;
jsvStringIteratorNew(&it, v, 0);
while (jsvStringIteratorHasChar(&it)) {
char ch = jsvStringIteratorGetChar(&it);
if (n==charIdx) {
jsvStringIteratorFree(&it);
*line = y;
*col = x;
return;
}
x++;
if (ch=='\n') {
x=1; y++;
}
n++;
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
// uh-oh - not found
*line = y;
*col = x;
}
// IN A STRING, get a character index from a line and column
size_t jsvGetIndexFromLineAndCol(JsVar *v, size_t line, size_t col) {
size_t x = 1;
size_t y = 1;
size_t n = 0;
JsvStringIterator it;
jsvStringIteratorNew(&it, v, 0);
while (jsvStringIteratorHasChar(&it)) {
char ch = jsvStringIteratorGetChar(&it);
if ((y==line && x>=col) || y>line) {
jsvStringIteratorFree(&it);
return (y>line) ? (n-1) : n;
}
x++;
if (ch=='\n') {
x=1; y++;
}
n++;
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
return n;
}
void jsvAppendString(JsVar *var, const char *str) {
assert(jsvIsString(var));
JsvStringIterator dst;
jsvStringIteratorNew(&dst, var, 0);
jsvStringIteratorGotoEnd(&dst);
// now start appending
/* This isn't as fast as something single-purpose, but it's not that bad,
* and is less likely to break :) */
while (*str)
jsvStringIteratorAppend(&dst, *(str++));
jsvStringIteratorFree(&dst);
}
// Append the given string to this one - but does not use null-terminated strings
void jsvAppendStringBuf(JsVar *var, const char *str, size_t length) {
assert(jsvIsString(var));
JsvStringIterator dst;
jsvStringIteratorNew(&dst, var, 0);
jsvStringIteratorGotoEnd(&dst);
// now start appending
/* This isn't as fast as something single-purpose, but it's not that bad,
* and is less likely to break :) */
while (length) {
jsvStringIteratorAppend(&dst, *(str++));
length--;
}
jsvStringIteratorFree(&dst);
}
/// Special version of append designed for use with vcbprintf_callback (See jsvAppendPrintf)
void jsvStringIteratorPrintfCallback(const char *str, void *user_data) {
while (*str)
jsvStringIteratorAppend((JsvStringIterator *)user_data, *(str++));
}
void jsvAppendPrintf(JsVar *var, const char *fmt, ...) {
JsvStringIterator it;
jsvStringIteratorNew(&it, var, 0);
jsvStringIteratorGotoEnd(&it);
va_list argp;
va_start(argp, fmt);
vcbprintf((vcbprintf_callback)jsvStringIteratorPrintfCallback,&it, fmt, argp);
va_end(argp);
jsvStringIteratorFree(&it);
}
JsVar *jsvVarPrintf( const char *fmt, ...) {
JsVar *str = jsvNewFromEmptyString();
if (!str) return 0;
JsvStringIterator it;
jsvStringIteratorNew(&it, str, 0);
jsvStringIteratorGotoEnd(&it);
va_list argp;
va_start(argp, fmt);
vcbprintf((vcbprintf_callback)jsvStringIteratorPrintfCallback,&it, fmt, argp);
va_end(argp);
jsvStringIteratorFree(&it);
return str;
}
/** Append str to var. Both must be strings. stridx = start char or str, maxLength = max number of characters (can be JSVAPPENDSTRINGVAR_MAXLENGTH) */
void jsvAppendStringVar(JsVar *var, const JsVar *str, size_t stridx, size_t maxLength) {
assert(jsvIsString(var));
JsvStringIterator dst;
jsvStringIteratorNew(&dst, var, 0);
jsvStringIteratorGotoEnd(&dst);
// now start appending
/* This isn't as fast as something single-purpose, but it's not that bad,
* and is less likely to break :) */
JsvStringIterator it;
jsvStringIteratorNewConst(&it, str, stridx);
while (jsvStringIteratorHasChar(&it) && (maxLength-->0)) {
char ch = jsvStringIteratorGetChar(&it);
jsvStringIteratorAppend(&dst, ch);
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
jsvStringIteratorFree(&dst);
}
/** Create a new variable from a substring. argument must be a string. stridx = start char or str, maxLength = max number of characters (can be JSVAPPENDSTRINGVAR_MAXLENGTH) */
JsVar *jsvNewFromStringVar(const JsVar *str, size_t stridx, size_t maxLength) {
JsVar *var = jsvNewFromEmptyString();
if (var) jsvAppendStringVar(var, str, stridx, maxLength);
return var;
}
/** Append all of str to var. Both must be strings. */
void jsvAppendStringVarComplete(JsVar *var, const JsVar *str) {
jsvAppendStringVar(var, str, 0, JSVAPPENDSTRINGVAR_MAXLENGTH);
}
char jsvGetCharInString(JsVar *v, size_t idx) {
if (!jsvIsString(v)) return 0;
JsvStringIterator it;
jsvStringIteratorNew(&it, v, idx);
char ch = jsvStringIteratorGetChar(&it);
jsvStringIteratorFree(&it);
return ch;
}
/// Get the index of a character in a string, or -1
int jsvGetStringIndexOf(JsVar *str, char ch) {
JsvStringIterator it;
jsvStringIteratorNew(&it, str, 0);
while (jsvStringIteratorHasChar(&it)) {
if (jsvStringIteratorGetChar(&it) == ch) {
int idx = (int)jsvStringIteratorGetIndex(&it);
jsvStringIteratorFree(&it);
return idx;
};
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
return -1;
}
/** Does this string contain only Numeric characters (with optional '-'/'+' at the front)? NOT '.'/'e' and similar (allowDecimalPoint is for '.' only) */
bool jsvIsStringNumericInt(const JsVar *var, bool allowDecimalPoint) {
assert(jsvIsString(var));
JsvStringIterator it;
jsvStringIteratorNewConst(&it, var, 0); // we know it's non const
// skip whitespace
while (jsvStringIteratorHasChar(&it) && isWhitespace(jsvStringIteratorGetChar(&it)))
jsvStringIteratorNext(&it);
// skip a minus. if there was one
if (jsvStringIteratorGetChar(&it)=='-' || jsvStringIteratorGetChar(&it)=='+')
jsvStringIteratorNext(&it);
int radix = 0;
if (jsvStringIteratorGetChar(&it)=='0') {
jsvStringIteratorNext(&it);
char buf[3];
buf[0] = '0';
buf[1] = jsvStringIteratorGetChar(&it);
buf[2] = 0;
const char *p = buf;
radix = getRadix(&p,0,0);
if (p>&buf[1]) jsvStringIteratorNext(&it);
}
if (radix==0) radix=10;
// now check...
int chars=0;
while (jsvStringIteratorHasChar(&it)) {
chars++;
char ch = jsvStringIteratorGetChar(&it);
if (ch=='.' && allowDecimalPoint) {
allowDecimalPoint = false; // there can be only one
} else {
int n = chtod(ch);
if (n<0 || n>=radix) {
jsvStringIteratorFree(&it);
return false;
}
}
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
return chars>0;
}
/** Does this string contain only Numeric characters? This is for arrays
* and makes the assertion that int_to_string(string_to_int(var))==var */
bool jsvIsStringNumericStrict(const JsVar *var) {
assert(jsvIsString(var));
JsvStringIterator it;
jsvStringIteratorNewConst(&it, var, 0); // we know it's non const
bool hadNonZero = false;
bool hasLeadingZero = false;
int chars = 0;
while (jsvStringIteratorHasChar(&it)) {
chars++;
char ch = jsvStringIteratorGetChar(&it);
if (!isNumeric(ch)) {
// test for leading zero ensures int_to_string(string_to_int(var))==var
jsvStringIteratorFree(&it);
return false;
}
if (!hadNonZero && ch=='0') hasLeadingZero=true;
if (ch!='0') hadNonZero=true;
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
return chars>0 && (!hasLeadingZero || chars==1);
}
JsVarInt jsvGetInteger(const JsVar *v) {
if (!v) return 0; // undefined
/* strtol understands about hex and octal */
if (jsvIsNull(v)) return 0;
if (jsvIsUndefined(v)) return 0;
if (jsvIsIntegerish(v) || jsvIsArrayBufferName(v)) return v->varData.integer;
if (jsvIsArray(v) || jsvIsArrayBuffer(v)) {
JsVarInt l = jsvGetLength((JsVar *)v);
if (l==0) return 0; // 0 length, return 0
if (l==1) {
if (jsvIsArrayBuffer(v))
return jsvGetIntegerAndUnLock(jsvArrayBufferGet((JsVar*)v,0));
return jsvGetIntegerAndUnLock(jsvSkipNameAndUnLock(jsvGetArrayItem(v,0)));
}
}
if (jsvIsFloat(v)) {
if (isfinite(v->varData.floating))
return (JsVarInt)(long long)v->varData.floating;
return 0;
}
if (jsvIsString(v) && jsvIsStringNumericInt(v, true/* allow decimal point*/)) {
char buf[32];
if (jsvGetString(v, buf, sizeof(buf))==sizeof(buf))
jsExceptionHere(JSET_ERROR, "String too big to convert to integer\n");
else
return (JsVarInt)stringToInt(buf);
}
return 0;
}
long long jsvGetLongInteger(const JsVar *v) {
if (jsvIsInt(v)) return jsvGetInteger(v);
return (long long)jsvGetFloat(v);
}
long long jsvGetLongIntegerAndUnLock(JsVar *v) {
long long i = jsvGetLongInteger(v);
jsvUnLock(v);
return i;
}
void jsvSetInteger(JsVar *v, JsVarInt value) {
assert(jsvIsInt(v));
v->varData.integer = value;
}
/**
* Get the boolean value of a variable.
* From a JavaScript variable, we determine its boolean value. The rules
* are:
*
* * If integer, true if value is not 0.
* * If float, true if value is not 0.0.
* * If function, array or object, always true.
* * If string, true if length of string is greater than 0.
*/
bool jsvGetBool(const JsVar *v) {
if (jsvIsString(v))
return jsvGetStringLength((JsVar*)v)!=0;
if (jsvIsFunction(v) || jsvIsArray(v) || jsvIsObject(v) || jsvIsArrayBuffer(v))
return true;
if (jsvIsFloat(v)) {
JsVarFloat f = jsvGetFloat(v);
return !isnan(f) && f!=0.0;
}
return jsvGetInteger(v)!=0;
}
JsVarFloat jsvGetFloat(const JsVar *v) {
if (!v) return NAN; // undefined
if (jsvIsFloat(v)) return v->varData.floating;
if (jsvIsIntegerish(v)) return (JsVarFloat)v->varData.integer;
if (jsvIsArray(v) || jsvIsArrayBuffer(v)) {
JsVarInt l = jsvGetLength(v);
if (l==0) return 0; // zero element array==0 (not undefined)
if (l==1) {
if (jsvIsArrayBuffer(v))
return jsvGetFloatAndUnLock(jsvArrayBufferGet((JsVar*)v,0));
return jsvGetFloatAndUnLock(jsvSkipNameAndUnLock(jsvGetArrayItem(v,0)));
}
}
if (jsvIsString(v)) {
char buf[64];
if (jsvGetString(v, buf, sizeof(buf))==sizeof(buf)) {
jsExceptionHere(JSET_ERROR, "String too big to convert to float\n");
} else {
if (buf[0]==0) return 0; // empty string -> 0
if (!strcmp(buf,"Infinity")) return INFINITY;
if (!strcmp(buf,"-Infinity")) return -INFINITY;
return stringToFloat(buf);
}
}
return NAN;
}
/// Convert the given variable to a number
JsVar *jsvAsNumber(JsVar *var) {
// stuff that we can just keep
if (jsvIsInt(var) || jsvIsFloat(var)) return jsvLockAgain(var);
// stuff that can be converted to an int
if (jsvIsBoolean(var) ||
jsvIsPin(var) ||
jsvIsNull(var) ||
jsvIsBoolean(var) ||
jsvIsArrayBufferName(var))
return jsvNewFromInteger(jsvGetInteger(var));
if (jsvIsString(var) && (jsvIsEmptyString(var) || jsvIsStringNumericInt(var, false/* no decimal pt - handle that with GetFloat */))) {
// handle strings like this, in case they're too big for an int
char buf[64];
if (jsvGetString(var, buf, sizeof(buf))==sizeof(buf)) {
jsExceptionHere(JSET_ERROR, "String too big to convert to integer\n");
return jsvNewFromFloat(NAN);
} else
return jsvNewFromLongInteger(stringToInt(buf));
}
// Else just try and get a float
return jsvNewFromFloat(jsvGetFloat(var));
}
JsVarInt jsvGetIntegerAndUnLock(JsVar *v) { return _jsvGetIntegerAndUnLock(v); }
JsVarFloat jsvGetFloatAndUnLock(JsVar *v) { return _jsvGetFloatAndUnLock(v); }
bool jsvGetBoolAndUnLock(JsVar *v) { return _jsvGetBoolAndUnLock(v); }
/** Get the item at the given location in the array buffer and return the result */
size_t jsvGetArrayBufferLength(const JsVar *arrayBuffer) {
assert(jsvIsArrayBuffer(arrayBuffer));
return arrayBuffer->varData.arraybuffer.length;
}
/** Get the String the contains the data for this arrayBuffer */
JsVar *jsvGetArrayBufferBackingString(JsVar *arrayBuffer) {
jsvLockAgain(arrayBuffer);
while (jsvIsArrayBuffer(arrayBuffer)) {
JsVar *s = jsvLock(jsvGetFirstChild(arrayBuffer));
jsvUnLock(arrayBuffer);
arrayBuffer = s;
}
assert(jsvIsString(arrayBuffer));
return arrayBuffer;
}
/** Get the item at the given location in the array buffer and return the result */
JsVar *jsvArrayBufferGet(JsVar *arrayBuffer, size_t idx) {
JsvArrayBufferIterator it;
jsvArrayBufferIteratorNew(&it, arrayBuffer, idx);
JsVar *v = jsvArrayBufferIteratorGetValue(&it);
jsvArrayBufferIteratorFree(&it);
return v;
}
/** Set the item at the given location in the array buffer */
void jsvArrayBufferSet(JsVar *arrayBuffer, size_t idx, JsVar *value) {
JsvArrayBufferIterator it;
jsvArrayBufferIteratorNew(&it, arrayBuffer, idx);
jsvArrayBufferIteratorSetValue(&it, value);
jsvArrayBufferIteratorFree(&it);
}
/** Given an integer name that points to an arraybuffer or an arraybufferview, evaluate it and return the result */
JsVar *jsvArrayBufferGetFromName(JsVar *name) {
assert(jsvIsArrayBufferName(name));
size_t idx = (size_t)jsvGetInteger(name);
JsVar *arrayBuffer = jsvLock(jsvGetFirstChild(name));
JsVar *value = jsvArrayBufferGet(arrayBuffer, idx);
jsvUnLock(arrayBuffer);
return value;
}
JsVar *jsvGetFunctionArgumentLength(JsVar *functionScope) {
JsVar *args = jsvNewEmptyArray();
if (!args) return 0; // out of memory
JsvObjectIterator it;
jsvObjectIteratorNew(&it, functionScope);
while (jsvObjectIteratorHasValue(&it)) {
JsVar *idx = jsvObjectIteratorGetKey(&it);
if (jsvIsFunctionParameter(idx)) {
JsVar *val = jsvSkipOneName(idx);
jsvArrayPushAndUnLock(args, val);
}
jsvUnLock(idx);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
return args;
}
/** Is this variable actually defined? eg, can we pass it into `jsvSkipName`
* without getting a ReferenceError? This also returns false if the variable
* if ok, but has the value `undefined`. */
bool jsvIsVariableDefined(JsVar *a) {
return !jsvIsName(a) ||
jsvIsNameWithValue(a) ||
(jsvGetFirstChild(a)!=0);
}
/** If a is a name skip it and go to what it points to - and so on.
* ALWAYS locks - so must unlock what it returns. It MAY
* return 0. Throws a ReferenceError if variable is not defined,
* but you can check if it will with jsvIsReferenceError */
JsVar *jsvSkipName(JsVar *a) {
if (!a) return 0;
if (jsvIsArrayBufferName(a)) return jsvArrayBufferGetFromName(a);
if (jsvIsNameInt(a)) return jsvNewFromInteger((JsVarInt)jsvGetFirstChildSigned(a));
if (jsvIsNameIntBool(a)) return jsvNewFromBool(jsvGetFirstChild(a)!=0);
JsVar *pa = jsvLockAgain(a);
while (jsvIsName(pa)) {
JsVarRef n = jsvGetFirstChild(pa);
jsvUnLock(pa);
if (!n) {
if (pa==a && jsvGetRefs(a)==0 && !jsvIsNewChild(a)) {
jsExceptionHere(JSET_REFERENCEERROR, "%q is not defined", a);
}
return 0;
}
pa = jsvLock(n);
assert(pa!=a);
}
return pa;
}
/** If a is a name skip it and go to what it points to.
* ALWAYS locks - so must unlock what it returns. It MAY
* return 0. Throws a ReferenceError if variable is not defined,
* but you can check if it will with jsvIsReferenceError */
JsVar *jsvSkipOneName(JsVar *a) {
if (!a) return 0;
if (jsvIsArrayBufferName(a)) return jsvArrayBufferGetFromName(a);
if (jsvIsNameInt(a)) return jsvNewFromInteger((JsVarInt)jsvGetFirstChildSigned(a));
if (jsvIsNameIntBool(a)) return jsvNewFromBool(jsvGetFirstChild(a)!=0);
JsVar *pa = jsvLockAgain(a);
if (jsvIsName(pa)) {
JsVarRef n = jsvGetFirstChild(pa);
jsvUnLock(pa);
if (!n) {
if (pa==a && jsvGetRefs(a)==0 && !jsvIsNewChild(a)) {
jsExceptionHere(JSET_REFERENCEERROR, "%q is not defined", a);
}
return 0;
}
pa = jsvLock(n);
assert(pa!=a);
}
return pa;
}
/** If a is a's child is a name skip it and go to what it points to.
* ALWAYS locks - so must unlock what it returns. */
JsVar *jsvSkipToLastName(JsVar *a) {
assert(jsvIsName(a));
a = jsvLockAgain(a);
while (true) {
if (!jsvGetFirstChild(a)) return a;
JsVar *child = jsvLock(jsvGetFirstChild(a));
if (jsvIsName(child)) {
jsvUnLock(a);
a = child;
} else {
jsvUnLock(child);
return a;
}
}
return 0; // not called
}
/** Same as jsvSkipName, but ensures that 'a' is unlocked */
JsVar *jsvSkipNameAndUnLock(JsVar *a) {
JsVar *b = jsvSkipName(a);
jsvUnLock(a);
return b;
}
/** Same as jsvSkipOneName, but ensures that 'a' is unlocked */
JsVar *jsvSkipOneNameAndUnLock(JsVar *a) {
JsVar *b = jsvSkipOneName(a);
jsvUnLock(a);
return b;
}
bool jsvIsStringEqualOrStartsWithOffset(JsVar *var, const char *str, bool isStartsWith, size_t startIdx, bool ignoreCase) {
if (!jsvHasCharacterData(var)) {
return 0; // not a string so not equal!
}
JsvStringIterator it;
jsvStringIteratorNew(&it, var, startIdx);
if (ignoreCase) {
while (jsvStringIteratorHasChar(&it) && *str &&
jsvStringCharToLower(jsvStringIteratorGetChar(&it)) == jsvStringCharToLower(*str)) {
str++;
jsvStringIteratorNext(&it);
}
} else {
while (jsvStringIteratorHasChar(&it) && *str &&
jsvStringIteratorGetChar(&it) == *str) {
str++;
jsvStringIteratorNext(&it);
}
}
bool eq = (isStartsWith && !*str) ||
jsvStringIteratorGetChar(&it)==*str; // should both be 0 if equal
jsvStringIteratorFree(&it);
return eq;
}
/*
jsvIsStringEqualOrStartsWith(A, B, false) is a proper A==B
jsvIsStringEqualOrStartsWith(A, B, true) is A.startsWith(B)
*/
bool jsvIsStringEqualOrStartsWith(JsVar *var, const char *str, bool isStartsWith) {
return jsvIsStringEqualOrStartsWithOffset(var, str, isStartsWith, 0, false);
}
// Also see jsvIsBasicVarEqual
bool jsvIsStringEqual(JsVar *var, const char *str) {
return jsvIsStringEqualOrStartsWith(var, str, false);
}
// Also see jsvIsBasicVarEqual
bool jsvIsStringIEqualAndUnLock(JsVar *var, const char *str) {
bool b = jsvIsStringEqualOrStartsWithOffset(var, str, false, 0, true);
jsvUnLock(var);
return b;
}
/** Compare 2 strings, starting from the given character positions. equalAtEndOfString means that
* if one of the strings ends (even if the other hasn't), we treat them as equal.
* For a basic strcmp, do: jsvCompareString(a,b,0,0,false)
* */
int jsvCompareString(JsVar *va, JsVar *vb, size_t starta, size_t startb, bool equalAtEndOfString) {
JsvStringIterator ita, itb;
jsvStringIteratorNew(&ita, va, starta);
jsvStringIteratorNew(&itb, vb, startb);
// step to first positions
while (true) {
int ca = jsvStringIteratorGetCharOrMinusOne(&ita);
int cb = jsvStringIteratorGetCharOrMinusOne(&itb);
if (ca != cb) {
jsvStringIteratorFree(&ita);
jsvStringIteratorFree(&itb);
if ((ca<0 || cb<0) && equalAtEndOfString) return 0;
return ca - cb;
}
if (ca < 0) { // both equal, but end of string
jsvStringIteratorFree(&ita);
jsvStringIteratorFree(&itb);
return 0;
}
jsvStringIteratorNext(&ita);
jsvStringIteratorNext(&itb);
}
// never get here, but the compiler warns...
return true;
}
/** Return a new string containing just the characters that are
* shared between two strings. */
JsVar *jsvGetCommonCharacters(JsVar *va, JsVar *vb) {
JsVar *v = jsvNewFromEmptyString();
if (!v) return 0;
JsvStringIterator ita, itb;
jsvStringIteratorNew(&ita, va, 0);
jsvStringIteratorNew(&itb, vb, 0);
int ca = jsvStringIteratorGetCharOrMinusOne(&ita);
int cb = jsvStringIteratorGetCharOrMinusOne(&itb);
while (ca>0 && cb>0 && ca == cb) {
jsvAppendCharacter(v, (char)ca);
jsvStringIteratorNext(&ita);
jsvStringIteratorNext(&itb);
ca = jsvStringIteratorGetCharOrMinusOne(&ita);
cb = jsvStringIteratorGetCharOrMinusOne(&itb);
}
jsvStringIteratorFree(&ita);
jsvStringIteratorFree(&itb);
return v;
}
/** Compare 2 integers, >0 if va>vb, <0 if va<vb. If compared with a non-integer, that gets put later */
int jsvCompareInteger(JsVar *va, JsVar *vb) {
if (jsvIsInt(va) && jsvIsInt(vb))
return (int)(jsvGetInteger(va) - jsvGetInteger(vb));
else if (jsvIsInt(va))
return -1;
else if (jsvIsInt(vb))
return 1;
else
return 0;
}
/** Copy only a name, not what it points to. ALTHOUGH the link to what it points to is maintained unless linkChildren=false
If keepAsName==false, this will be converted into a normal variable */
JsVar *jsvCopyNameOnly(JsVar *src, bool linkChildren, bool keepAsName) {
assert(jsvIsName(src));
JsVarFlags flags = src->flags;
JsVar *dst = 0;
if (!keepAsName) {
JsVarFlags t = src->flags & JSV_VARTYPEMASK;
if (t>=_JSV_NAME_INT_START && t<=_JSV_NAME_INT_END) {
flags = (flags & ~JSV_VARTYPEMASK) | JSV_INTEGER;
} else {
assert((JSV_NAME_STRING_INT_0 < JSV_NAME_STRING_0) &&
(JSV_NAME_STRING_0 < JSV_STRING_0) &&
(JSV_STRING_0 < JSV_STRING_EXT_0)); // this relies on ordering
assert(t>=JSV_NAME_STRING_INT_0 && t<=JSV_NAME_STRING_MAX);
if (jsvGetLastChild(src)) {
/* it's not a simple name string - it has STRING_EXT bits on the end.
* Because the max length of NAME and STRING is different we must just
* copy */
dst = jsvNewFromStringVar(src, 0, JSVAPPENDSTRINGVAR_MAXLENGTH);
if (!dst) return 0;
} else {
flags = (flags & (JsVarFlags)~JSV_VARTYPEMASK) | (JSV_STRING_0 + jsvGetCharactersInVar(src));
}
}
}
if (!dst) {
dst = jsvNewWithFlags(flags & JSV_VARIABLEINFOMASK);
if (!dst) return 0; // out of memory
memcpy(&dst->varData, &src->varData, JSVAR_DATA_STRING_NAME_LEN);
assert(jsvGetLastChild(dst) == 0);
assert(jsvGetFirstChild(dst) == 0);
assert(jsvGetPrevSibling(dst) == 0);
assert(jsvGetNextSibling(dst) == 0);
// Copy extra string data if there was any
if (jsvHasStringExt(src)) {
// If it had extra string data it should have been handled above
assert(keepAsName || !jsvGetLastChild(src));
// copy extra bits of string if there were any
if (jsvGetLastChild(src)) {
JsVar *child = jsvLock(jsvGetLastChild(src));
JsVar *childCopy = jsvCopy(child, true);
if (childCopy) { // could be out of memory
jsvSetLastChild(dst, jsvGetRef(childCopy)); // no ref for stringext
jsvUnLock(childCopy);
}
jsvUnLock(child);
}
} else {
assert(jsvIsBasic(src)); // in case we missed something!
}
}
// Copy LINK of what it points to
if (linkChildren && jsvGetFirstChild(src)) {
if (jsvIsNameWithValue(src))
jsvSetFirstChild(dst, jsvGetFirstChild(src));
else
jsvSetFirstChild(dst, jsvRefRef(jsvGetFirstChild(src)));
}
return dst;
}
JsVar *jsvCopy(JsVar *src, bool copyChildren) {
if (jsvIsFlatString(src)) {
// Copy a Flat String into a non-flat string - it's just safer
return jsvNewFromStringVar(src, 0, JSVAPPENDSTRINGVAR_MAXLENGTH);
}
JsVar *dst = jsvNewWithFlags(src->flags & JSV_VARIABLEINFOMASK);
if (!dst) return 0; // out of memory
if (!jsvIsStringExt(src)) {
memcpy(&dst->varData, &src->varData, (jsvIsBasicString(src)||jsvIsNativeString(src)) ? JSVAR_DATA_STRING_LEN : JSVAR_DATA_STRING_NAME_LEN);
if (!(jsvIsBasicString(src)||jsvIsNativeString(src))) {
assert(jsvGetPrevSibling(dst) == 0);
assert(jsvGetNextSibling(dst) == 0);
assert(jsvGetFirstChild(dst) == 0);
}
assert(jsvGetLastChild(dst) == 0);
} else {
// stringexts use the extra pointers after varData to store characters
// see jsvGetMaxCharactersInVar
memcpy(&dst->varData, &src->varData, JSVAR_DATA_STRING_MAX_LEN);
assert(jsvGetLastChild(dst) == 0);
}
// Copy what names point to
if (copyChildren && jsvIsName(src)) {
if (jsvGetFirstChild(src)) {
if (jsvIsNameWithValue(src)) {
// name_int/etc don't need references
jsvSetFirstChild(dst, jsvGetFirstChild(src));
} else {
JsVar *child = jsvLock(jsvGetFirstChild(src));
JsVar *childCopy = jsvRef(jsvCopy(child, true));
jsvUnLock(child);
if (childCopy) { // could have been out of memory
jsvSetFirstChild(dst, jsvGetRef(childCopy));
jsvUnLock(childCopy);
}
}
}
}
if (jsvHasStringExt(src)) {
// copy extra bits of string if there were any
if (jsvGetLastChild(src)) {
JsVar *child = jsvLock(jsvGetLastChild(src));
JsVar *childCopy = jsvCopy(child, true);
if (childCopy) {// could be out of memory
jsvSetLastChild(dst, jsvGetRef(childCopy)); // no ref for stringext
jsvUnLock(childCopy);
}
jsvUnLock(child);
}
} else if (jsvHasChildren(src)) {
if (copyChildren) {
// Copy children..
JsVarRef vr;
vr = jsvGetFirstChild(src);
while (vr) {
JsVar *name = jsvLock(vr);
JsVar *child = jsvCopyNameOnly(name, true/*link children*/, true/*keep as name*/); // NO DEEP COPY!
if (child) { // could have been out of memory
jsvAddName(dst, child);
jsvUnLock(child);
}
vr = jsvGetNextSibling(name);
jsvUnLock(name);
}
}
} else {
assert(jsvIsBasic(src)); // in case we missed something!
}
return dst;
}
void jsvAddName(JsVar *parent, JsVar *namedChild) {
namedChild = jsvRef(namedChild); // ref here VERY important as adding to structure!
assert(jsvIsName(namedChild));
// update array length
if (jsvIsArray(parent) && jsvIsInt(namedChild)) {
JsVarInt index = namedChild->varData.integer;
if (index >= jsvGetArrayLength(parent)) {
jsvSetArrayLength(parent, index + 1, false);
}
}
if (jsvGetLastChild(parent)) { // we have children already
JsVar *insertAfter = jsvLock(jsvGetLastChild(parent));
if (jsvIsArray(parent)) {
// we must insert in order - so step back until we get the right place
while (insertAfter && jsvCompareInteger(namedChild, insertAfter)<0) {
JsVarRef prev = jsvGetPrevSibling(insertAfter);
jsvUnLock(insertAfter);
insertAfter = prev ? jsvLock(prev) : 0;
}
}
if (insertAfter) {
if (jsvGetNextSibling(insertAfter)) {
// great, we're in the middle...
JsVar *insertBefore = jsvLock(jsvGetNextSibling(insertAfter));
jsvSetPrevSibling(insertBefore, jsvGetRef(namedChild));
jsvSetNextSibling(namedChild, jsvGetRef(insertBefore));
jsvUnLock(insertBefore);
} else {
// We're at the end - just set up the parent
jsvSetLastChild(parent, jsvGetRef(namedChild));
}
jsvSetNextSibling(insertAfter, jsvGetRef(namedChild));
jsvSetPrevSibling(namedChild, jsvGetRef(insertAfter));
jsvUnLock(insertAfter);
} else { // Insert right at the beginning of the array
// Link 2 children together
JsVar *firstChild = jsvLock(jsvGetFirstChild(parent));
jsvSetPrevSibling(firstChild, jsvGetRef(namedChild));
jsvUnLock(firstChild);
jsvSetNextSibling(namedChild, jsvGetFirstChild(parent));
// finally set the new child as the first one
jsvSetFirstChild(parent, jsvGetRef(namedChild));
}
} else { // we have no children - just add it
JsVarRef r = jsvGetRef(namedChild);
jsvSetFirstChild(parent, r);
jsvSetLastChild(parent, r);
}
}
JsVar *jsvAddNamedChild(JsVar *parent, JsVar *child, const char *name) {
JsVar *namedChild = jsvMakeIntoVariableName(jsvNewFromString(name), child);
if (!namedChild) return 0; // Out of memory
jsvAddName(parent, namedChild);
return namedChild;
}
JsVar *jsvSetNamedChild(JsVar *parent, JsVar *child, const char *name) {
JsVar *namedChild = jsvFindChildFromString(parent, name, true);
if (namedChild) // could be out of memory
return jsvSetValueOfName(namedChild, child);
return 0;
}
JsVar *jsvSetValueOfName(JsVar *name, JsVar *src) {
assert(name && jsvIsName(name));
assert(name!=src); // no infinite loops!
// all is fine, so replace the existing child...
/* Existing child may be null in the case of Z = 0 where
* we create 'Z' and pass it down to '=' to have the value
* filled in (or it may be undefined). */
if (jsvIsNameWithValue(name)) {
if (jsvIsString(name))
name->flags = (name->flags & (JsVarFlags)~JSV_VARTYPEMASK) | (JSV_NAME_STRING_0 + jsvGetCharactersInVar(name));
else
name->flags = (name->flags & (JsVarFlags)~JSV_VARTYPEMASK) | JSV_NAME_INT;
jsvSetFirstChild(name, 0);
} else if (jsvGetFirstChild(name))
jsvUnRefRef(jsvGetFirstChild(name)); // free existing
if (src) {
if (jsvIsInt(name)) {
if ((jsvIsInt(src) || jsvIsBoolean(src)) && !jsvIsPin(src)) {
JsVarInt v = src->varData.integer;
if (v>=JSVARREF_MIN && v<=JSVARREF_MAX) {
name->flags = (name->flags & (JsVarFlags)~JSV_VARTYPEMASK) | (jsvIsInt(src) ? JSV_NAME_INT_INT : JSV_NAME_INT_BOOL);
jsvSetFirstChild(name, (JsVarRef)v);
return name;
}
}
} else if (jsvIsString(name)) {
if (jsvIsInt(src) && !jsvIsPin(src)) {
JsVarInt v = src->varData.integer;
if (v>=JSVARREF_MIN && v<=JSVARREF_MAX) {
name->flags = (name->flags & (JsVarFlags)~JSV_VARTYPEMASK) | (JSV_NAME_STRING_INT_0 + jsvGetCharactersInVar(name));
jsvSetFirstChild(name, (JsVarRef)v);
return name;
}
}
}
// we can link to a name if we want (so can remove the assert!)
jsvSetFirstChild(name, jsvGetRef(jsvRef(src)));
} else
jsvSetFirstChild(name, 0);
return name;
}
JsVar *jsvFindChildFromString(JsVar *parent, const char *name, bool addIfNotFound) {
/* Pull out first 4 bytes, and ensure that everything
* is 0 padded so that we can do a nice speedy check. */
char fastCheck[4];
fastCheck[0] = name[0];
if (name[0]) {
fastCheck[1] = name[1];
if (name[1]) {
fastCheck[2] = name[2];
if (name[2]) {
fastCheck[3] = name[3];
} else {
fastCheck[3] = 0;
}
} else {
fastCheck[2] = 0;
fastCheck[3] = 0;
}
} else {
fastCheck[1] = 0;
fastCheck[2] = 0;
fastCheck[3] = 0;
}
assert(jsvHasChildren(parent));
JsVarRef childref = jsvGetFirstChild(parent);
while (childref) {
// Don't Lock here, just use GetAddressOf - to try and speed up the finding
// TODO: We can do this now, but when/if we move to cacheing vars, it'll break
JsVar *child = jsvGetAddressOf(childref);
if (*(int*)fastCheck==*(int*)child->varData.str && // speedy check of first 4 bytes
jsvIsStringEqual(child, name)) {
// found it! unlock parent but leave child locked
return jsvLockAgain(child);
}
childref = jsvGetNextSibling(child);
}
JsVar *child = 0;
if (addIfNotFound) {
child = jsvMakeIntoVariableName(jsvNewFromString(name), 0);
if (child) // could be out of memory
jsvAddName(parent, child);
}
return child;
}
/// See jsvIsNewChild - for fields that don't exist yet
JsVar *jsvCreateNewChild(JsVar *parent, JsVar *index, JsVar *child) {
JsVar *newChild = jsvAsName(index);
if (!newChild) return 0;
assert(!jsvGetFirstChild(newChild));
if (child) jsvSetValueOfName(newChild, child);
assert(!jsvGetNextSibling(newChild) && !jsvGetPrevSibling(newChild));
// by setting the siblings as the same, we signal that if set,
// we should be made a member of the given object
JsVarRef r = jsvGetRef(jsvRef(jsvRef(parent)));
jsvSetNextSibling(newChild, r);
jsvSetPrevSibling(newChild, r);
return newChild;
}
/** Try and turn the supplied variable into a name. If not, make a new one. This locks again. */
JsVar *jsvAsName(JsVar *var) {
if (!var) return 0;
if (jsvGetRefs(var) == 0) {
// Not reffed - great! let's just use it
if (!jsvIsName(var))
var = jsvMakeIntoVariableName(var, 0);
return jsvLockAgain(var);
} else { // it was reffed, we must add a new one
return jsvMakeIntoVariableName(jsvCopy(var, false), 0);
}
}
/** Non-recursive finding */
JsVar *jsvFindChildFromVar(JsVar *parent, JsVar *childName, bool addIfNotFound) {
JsVar *child;
JsVarRef childref = jsvGetFirstChild(parent);
while (childref) {
child = jsvLock(childref);
if (jsvIsBasicVarEqual(child, childName)) {
// found it! unlock parent but leave child locked
return child;
}
childref = jsvGetNextSibling(child);
jsvUnLock(child);
}
child = 0;
if (addIfNotFound && childName) {
child = jsvAsName(childName);
jsvAddName(parent, child);
}
return child;
}
void jsvRemoveChild(JsVar *parent, JsVar *child) {
assert(jsvHasChildren(parent));
assert(jsvIsName(child));
JsVarRef childref = jsvGetRef(child);
bool wasChild = false;
// unlink from parent
if (jsvGetFirstChild(parent) == childref) {
jsvSetFirstChild(parent, jsvGetNextSibling(child));
wasChild = true;
}
if (jsvGetLastChild(parent) == childref) {
jsvSetLastChild(parent, jsvGetPrevSibling(child));
wasChild = true;
// If this was an array and we were the last
// element, update the length
if (jsvIsArray(parent)) {
JsVarInt l = 0;
// get index of last child
if (jsvGetLastChild(parent))
l = jsvGetIntegerAndUnLock(jsvLock(jsvGetLastChild(parent)))+1;
// set it
jsvSetArrayLength(parent, l, false);
}
}
// unlink from child list
if (jsvGetPrevSibling(child)) {
JsVar *v = jsvLock(jsvGetPrevSibling(child));
assert(jsvGetNextSibling(v) == jsvGetRef(child));
jsvSetNextSibling(v, jsvGetNextSibling(child));
jsvUnLock(v);
wasChild = true;
}
if (jsvGetNextSibling(child)) {
JsVar *v = jsvLock(jsvGetNextSibling(child));
assert(jsvGetPrevSibling(v) == jsvGetRef(child));
jsvSetPrevSibling(v, jsvGetPrevSibling(child));
jsvUnLock(v);
wasChild = true;
}
jsvSetPrevSibling(child, 0);
jsvSetNextSibling(child, 0);
if (wasChild)
jsvUnRef(child);
}
void jsvRemoveAllChildren(JsVar *parent) {
assert(jsvHasChildren(parent));
while (jsvGetFirstChild(parent)) {
JsVar *v = jsvLock(jsvGetFirstChild(parent));
jsvRemoveChild(parent, v);
jsvUnLock(v);
}
}
/// Check if the given name is a child of the parent
bool jsvIsChild(JsVar *parent, JsVar *child) {
assert(jsvIsArray(parent) || jsvIsObject(parent));
assert(jsvIsName(child));
JsVarRef childref = jsvGetRef(child);
JsVarRef indexref;
indexref = jsvGetFirstChild(parent);
while (indexref) {
if (indexref == childref) return true;
// get next
JsVar *indexVar = jsvLock(indexref);
indexref = jsvGetNextSibling(indexVar);
jsvUnLock(indexVar);
}
return false; // not found undefined
}
/// Get the named child of an object. If createChild!=0 then create the child
JsVar *jsvObjectGetChild(JsVar *obj, const char *name, JsVarFlags createChild) {
if (!obj) return 0;
assert(jsvHasChildren(obj));
JsVar *childName = jsvFindChildFromString(obj, name, createChild!=0);
JsVar *child = jsvSkipName(childName);
if (!child && createChild && childName!=0/*out of memory?*/) {
child = jsvNewWithFlags(createChild);
jsvSetValueOfName(childName, child);
jsvUnLock(childName);
return child;
}
jsvUnLock(childName);
return child;
}
/// Set the named child of an object, and return the child (so you can choose to unlock it if you want)
JsVar *jsvObjectSetChild(JsVar *obj, const char *name, JsVar *child) {
assert(jsvHasChildren(obj));
if (!jsvHasChildren(obj)) return 0;
// child can actually be a name (for instance if it is a named function)
JsVar *childName = jsvFindChildFromString(obj, name, true);
if (!childName) return 0; // out of memory
jsvSetValueOfName(childName, child);
jsvUnLock(childName);
return child;
}
/// Set the named child of an object, and return the child (so you can choose to unlock it if you want)
JsVar *jsvObjectSetChildVar(JsVar *obj, JsVar *name, JsVar *child) {
assert(jsvHasChildren(obj));
if (!jsvHasChildren(obj)) return 0;
// child can actually be a name (for instance if it is a named function)
JsVar *childName = jsvFindChildFromVar(obj, name, true);
if (!childName) return 0; // out of memory
jsvSetValueOfName(childName, child);
jsvUnLock(childName);
return child;
}
void jsvObjectSetChildAndUnLock(JsVar *obj, const char *name, JsVar *child) {
jsvUnLock(jsvObjectSetChild(obj, name, child));
}
void jsvObjectRemoveChild(JsVar *obj, const char *name) {
JsVar *child = jsvFindChildFromString(obj, name, false);
if (child) {
jsvRemoveChild(obj, child);
jsvUnLock(child);
}
}
/** Set the named child of an object, and return the child (so you can choose to unlock it if you want).
* If the child is 0, the 'name' is also removed from the object */
JsVar *jsvObjectSetOrRemoveChild(JsVar *obj, const char *name, JsVar *child) {
if (child)
jsvObjectSetChild(obj, name, child);
else
jsvObjectRemoveChild(obj, name);
return child;
}
/** Append all keys from the source object to the target object. Will ignore hidden/internal fields */
void jsvObjectAppendAll(JsVar *target, JsVar *source) {
assert(jsvIsObject(target));
assert(jsvIsObject(source));
JsvObjectIterator it;
jsvObjectIteratorNew(&it, source);
while (jsvObjectIteratorHasValue(&it)) {
JsVar *k = jsvObjectIteratorGetKey(&it);
JsVar *v = jsvSkipName(k);
if (!jsvIsInternalObjectKey(k))
jsvObjectSetChildVar(target, k, v);
jsvUnLock2(k,v);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
}
int jsvGetChildren(const JsVar *v) {
//OPT: could length be stored as the value of the array?
int children = 0;
JsVarRef childref = jsvGetFirstChild(v);
while (childref) {
JsVar *child = jsvLock(childref);
children++;
childref = jsvGetNextSibling(child);
jsvUnLock(child);
}
return children;
}
/// Get the first child's name from an object,array or function
JsVar *jsvGetFirstName(JsVar *v) {
assert(jsvHasChildren(v));
if (!jsvGetFirstChild(v)) return 0;
return jsvLock(jsvGetFirstChild(v));
}
JsVarInt jsvGetArrayLength(const JsVar *arr) {
if (!arr) return 0;
assert(jsvIsArray(arr));
return arr->varData.integer;
}
JsVarInt jsvSetArrayLength(JsVar *arr, JsVarInt length, bool truncate) {
assert(jsvIsArray(arr));
if (truncate && length < arr->varData.integer) {
// @TODO implement truncation here
}
arr->varData.integer = length;
return length;
}
JsVarInt jsvGetLength(const JsVar *src) {
if (jsvIsArray(src)) {
return jsvGetArrayLength(src);
} else if (jsvIsArrayBuffer(src)) {
return (JsVarInt)jsvGetArrayBufferLength(src);
} else if (jsvIsString(src)) {
return (JsVarInt)jsvGetStringLength(src);
} else if (jsvIsObject(src) || jsvIsFunction(src)) {
return jsvGetChildren(src);
} else {
return 1;
}
}
/** Count the amount of JsVars used. Mostly useful for debugging */
static size_t _jsvCountJsVarsUsedRecursive(JsVar *v, bool resetRecursionFlag) {
if (!v) return 0;
// Use IS_RECURSING flag to stop recursion
if (resetRecursionFlag) {
if (!(v->flags & JSV_IS_RECURSING))
return 0;
v->flags &= ~JSV_IS_RECURSING;
} else {
if (v->flags & JSV_IS_RECURSING)
return 0;
v->flags |= JSV_IS_RECURSING;
}
size_t count = 1;
if (jsvHasSingleChild(v) || jsvHasChildren(v)) {
JsVarRef childref = jsvGetFirstChild(v);
while (childref) {
JsVar *child = jsvLock(childref);
count += _jsvCountJsVarsUsedRecursive(child, resetRecursionFlag);
if (jsvHasChildren(v)) childref = jsvGetNextSibling(child);
else childref = 0;
jsvUnLock(child);
}
} else if (jsvIsFlatString(v))
count += jsvGetFlatStringBlocks(v);
if (jsvHasCharacterData(v)) {
JsVarRef childref = jsvGetLastChild(v);
while (childref) {
JsVar *child = jsvLock(childref);
count++;
childref = jsvGetLastChild(child);
jsvUnLock(child);
}
}
if (jsvIsName(v) && !jsvIsNameWithValue(v) && jsvGetFirstChild(v)) {
JsVar *child = jsvLock(jsvGetFirstChild(v));
count += _jsvCountJsVarsUsedRecursive(child, resetRecursionFlag);
jsvUnLock(child);
}
return count;
}
/** Count the amount of JsVars used. Mostly useful for debugging */
size_t jsvCountJsVarsUsed(JsVar *v) {
// we do this so we don't count the same item twice, but don't use too much memory
size_t c = _jsvCountJsVarsUsedRecursive(v, false);
_jsvCountJsVarsUsedRecursive(v, true);
return c;
}
JsVar *jsvGetArrayIndex(const JsVar *arr, JsVarInt index) {
JsVarRef childref = jsvGetLastChild(arr);
JsVarInt lastArrayIndex = 0;
// Look at last non-string element!
while (childref) {
JsVar *child = jsvLock(childref);
if (jsvIsInt(child)) {
lastArrayIndex = child->varData.integer;
// it was the last element... sorted!
if (lastArrayIndex == index) {
return child;
}
jsvUnLock(child);
break;
}
// if not an int, keep going
childref = jsvGetPrevSibling(child);
jsvUnLock(child);
}
// it's not in this array - don't search the whole lot...
if (index > lastArrayIndex)
return 0;
// otherwise is it more than halfway through?
if (index > lastArrayIndex/2) {
// it's in the final half of the array (probably) - search backwards
while (childref) {
JsVar *child = jsvLock(childref);
assert(jsvIsInt(child));
if (child->varData.integer == index) {
return child;
}
childref = jsvGetPrevSibling(child);
jsvUnLock(child);
}
} else {
// it's in the first half of the array (probably) - search forwards
childref = jsvGetFirstChild(arr);
while (childref) {
JsVar *child = jsvLock(childref);
assert(jsvIsInt(child));
if (child->varData.integer == index) {
return child;
}
childref = jsvGetNextSibling(child);
jsvUnLock(child);
}
}
return 0; // undefined
}
JsVar *jsvGetArrayItem(const JsVar *arr, JsVarInt index) {
return jsvSkipNameAndUnLock(jsvGetArrayIndex(arr,index));
}
void jsvSetArrayItem(JsVar *arr, JsVarInt index, JsVar *item) {
JsVar *indexVar = jsvGetArrayIndex(arr, index);
if (indexVar) {
jsvSetValueOfName(indexVar, item);
} else {
indexVar = jsvMakeIntoVariableName(jsvNewFromInteger(index), item);
jsvAddName(arr, indexVar);
}
jsvUnLock(indexVar);
}
// Get all elements from arr and put them in itemPtr (unless it'd overflow).
// Makes sure all of itemPtr either contains a JsVar or 0
void jsvGetArrayItems(JsVar *arr, unsigned int itemCount, JsVar **itemPtr) {
JsvObjectIterator it;
jsvObjectIteratorNew(&it, arr);
unsigned int i = 0;
while (jsvObjectIteratorHasValue(&it)) {
if (i<itemCount)
itemPtr[i++] = jsvObjectIteratorGetValue(&it);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
while (i<itemCount)
itemPtr[i++] = 0; // just ensure we don't end up with bad data
}
/// Get the index of the value in the array (matchExact==use pointer not equality check, matchIntegerIndices = don't check non-integers)
JsVar *jsvGetIndexOfFull(JsVar *arr, JsVar *value, bool matchExact, bool matchIntegerIndices, int startIdx) {
JsVarRef indexref;
assert(jsvIsArray(arr) || jsvIsObject(arr));
indexref = jsvGetFirstChild(arr);
while (indexref) {
JsVar *childIndex = jsvLock(indexref);
if (!matchIntegerIndices ||
(jsvIsInt(childIndex) && jsvGetInteger(childIndex)>=startIdx)) {
assert(jsvIsName(childIndex));
JsVar *childValue = jsvSkipName(childIndex);
if (childValue==value ||
(!matchExact && jsvMathsOpTypeEqual(childValue, value))) {
jsvUnLock(childValue);
return childIndex;
}
jsvUnLock(childValue);
}
indexref = jsvGetNextSibling(childIndex);
jsvUnLock(childIndex);
}
return 0; // undefined
}
/// Get the index of the value in the array or object (matchExact==use pointer, not equality check)
JsVar *jsvGetIndexOf(JsVar *arr, JsVar *value, bool matchExact) {
return jsvGetIndexOfFull(arr, value, matchExact, false, 0);
}
/// Adds new elements to the end of an array, and returns the new length. initialValue is the item index when no items are currently in the array.
JsVarInt jsvArrayAddToEnd(JsVar *arr, JsVar *value, JsVarInt initialValue) {
assert(jsvIsArray(arr));
JsVarInt index = initialValue;
if (jsvGetLastChild(arr)) {
JsVar *last = jsvLock(jsvGetLastChild(arr));
index = jsvGetInteger(last)+1;
jsvUnLock(last);
}
JsVar *idx = jsvMakeIntoVariableName(jsvNewFromInteger(index), value);
if (!idx) return 0; // out of memory - error flag will have been set already
jsvAddName(arr, idx);
jsvUnLock(idx);
return index+1;
}
/// Adds new elements to the end of an array, and returns the new length
JsVarInt jsvArrayPush(JsVar *arr, JsVar *value) {
assert(jsvIsArray(arr));
JsVarInt index = jsvGetArrayLength(arr);
JsVar *idx = jsvMakeIntoVariableName(jsvNewFromInteger(index), value);
if (!idx) return 0; // out of memory - error flag will have been set already
jsvAddName(arr, idx);
jsvUnLock(idx);
return jsvGetArrayLength(arr);
}
/// Adds a new element to the end of an array, unlocks it, and returns the new length
JsVarInt jsvArrayPushAndUnLock(JsVar *arr, JsVar *value) {
JsVarInt l = jsvArrayPush(arr, value);
jsvUnLock(value);
return l;
}
/// Append all values from the source array to the target array
void jsvArrayPushAll(JsVar *target, JsVar *source, bool checkDuplicates) {
assert(jsvIsArray(target));
assert(jsvIsArray(source));
JsvObjectIterator it;
jsvObjectIteratorNew(&it, source);
while (jsvObjectIteratorHasValue(&it)) {
JsVar *v = jsvObjectIteratorGetValue(&it);
bool add = true;
if (checkDuplicates) {
JsVar *idx = jsvGetIndexOf(target, v, false);
if (idx) {
add = false;
jsvUnLock(idx);
}
}
if (add) jsvArrayPush(target, v);
jsvUnLock(v);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
}
/// Removes the last element of an array, and returns that element (or 0 if empty). includes the NAME
JsVar *jsvArrayPop(JsVar *arr) {
assert(jsvIsArray(arr));
JsVar *child = 0;
JsVarInt length = jsvGetArrayLength(arr);
if (length > 0) {
length--;
if (jsvGetLastChild(arr)) {
// find last child with an integer key
JsVarRef ref = jsvGetLastChild(arr);
child = jsvLock(ref);
while (child && !jsvIsInt(child)) {
ref = jsvGetPrevSibling(child);
jsvUnLock(child);
if (ref) {
child = jsvLock(ref);
} else {
child = 0;
}
}
// check if the last integer key really is the last element
if (child) {
if (jsvGetInteger(child) == length) {
// child is the last element - remove it
jsvRemoveChild(arr, child);
} else {
// child is not the last element
jsvUnLock(child);
child = 0;
}
}
}
// and finally shrink the array
jsvSetArrayLength(arr, length, false);
}
return child;
}
/// Removes the first element of an array, and returns that element (or 0 if empty). DOES NOT RENUMBER.
JsVar *jsvArrayPopFirst(JsVar *arr) {
assert(jsvIsArray(arr));
if (jsvGetFirstChild(arr)) {
JsVar *child = jsvLock(jsvGetFirstChild(arr));
if (jsvGetFirstChild(arr) == jsvGetLastChild(arr))
jsvSetLastChild(arr, 0); // if 1 item in array
jsvSetFirstChild(arr, jsvGetNextSibling(child)); // unlink from end of array
jsvUnRef(child); // as no longer in array
if (jsvGetNextSibling(child)) {
JsVar *v = jsvLock(jsvGetNextSibling(child));
jsvSetPrevSibling(v, 0);
jsvUnLock(v);
}
jsvSetNextSibling(child, 0);
return child; // and return it
} else {
// no children!
return 0;
}
}
/// Adds a new variable element to the end of an array (IF it was not already there). Return true if successful
void jsvArrayAddUnique(JsVar *arr, JsVar *v) {
JsVar *idx = jsvGetIndexOf(arr, v, false); // did it already exist?
if (!idx) {
jsvArrayPush(arr, v); // if 0, it failed
} else {
jsvUnLock(idx);
}
}
/// Join all elements of an array together into a string
JsVar *jsvArrayJoin(JsVar *arr, JsVar *filler) {
JsVar *str = jsvNewFromEmptyString();
if (!str) return 0; // out of memory
JsvIterator it;
jsvIteratorNew(&it, arr, JSIF_EVERY_ARRAY_ELEMENT);
bool first = true;
while (!jspIsInterrupted() && jsvIteratorHasElement(&it)) {
JsVar *key = jsvIteratorGetKey(&it);
if (jsvIsInt(key)) {
// add the filler
if (filler && !first)
jsvAppendStringVarComplete(str, filler);
first = false;
// add the value
JsVar *value = jsvIteratorGetValue(&it);
if (value && !jsvIsNull(value)) {
JsVar *valueStr = jsvAsString(value, false);
if (valueStr) { // could be out of memory
jsvAppendStringVarComplete(str, valueStr);
jsvUnLock(valueStr);
}
}
jsvUnLock(value);
}
jsvUnLock(key);
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
return str;
}
/// Insert a new element before beforeIndex, DOES NOT UPDATE INDICES
void jsvArrayInsertBefore(JsVar *arr, JsVar *beforeIndex, JsVar *element) {
if (beforeIndex) {
JsVar *idxVar = jsvMakeIntoVariableName(jsvNewFromInteger(0), element);
if (!idxVar) return; // out of memory
JsVarRef idxRef = jsvGetRef(jsvRef(idxVar));
JsVarRef prev = jsvGetPrevSibling(beforeIndex);
if (prev) {
JsVar *prevVar = jsvRef(jsvLock(prev));
jsvSetInteger(idxVar, jsvGetInteger(prevVar)+1); // update index number
jsvSetNextSibling(prevVar, idxRef);
jsvUnLock(prevVar);
jsvSetPrevSibling(idxVar, prev);
} else {
jsvSetPrevSibling(idxVar, 0);
jsvSetFirstChild(arr, idxRef);
}
jsvSetPrevSibling(beforeIndex, idxRef);
jsvSetNextSibling(idxVar, jsvGetRef(jsvRef(beforeIndex)));
jsvUnLock(idxVar);
} else
jsvArrayPush(arr, element);
}
/** Same as jsvMathsOpPtr, but if a or b are a name, skip them
* and go to what they point to. Also handle the case where
* they may be objects with valueOf functions. */
JsVar *jsvMathsOpSkipNames(JsVar *a, JsVar *b, int op) {
JsVar *pa = jsvSkipName(a);
JsVar *pb = jsvSkipName(b);
JsVar *oa = jsvGetValueOf(pa);
JsVar *ob = jsvGetValueOf(pb);
jsvUnLock2(pa, pb);
JsVar *res = jsvMathsOp(oa,ob,op);
jsvUnLock2(oa, ob);
return res;
}
JsVar *jsvMathsOpError(int op, const char *datatype) {
char opName[32];
jslTokenAsString(op, opName, sizeof(opName));
jsError("Operation %s not supported on the %s datatype", opName, datatype);
return 0;
}
bool jsvMathsOpTypeEqual(JsVar *a, JsVar *b) {
// check type first, then call again to check data
bool eql = (a==0) == (b==0);
if (a && b) {
// Check whether both are numbers, otherwise check the variable
// type flags themselves
eql = ((jsvIsInt(a)||jsvIsFloat(a)) && (jsvIsInt(b)||jsvIsFloat(b))) ||
((a->flags & JSV_VARTYPEMASK) == (b->flags & JSV_VARTYPEMASK));
}
if (eql) {
JsVar *contents = jsvMathsOp(a,b, LEX_EQUAL);
if (!jsvGetBool(contents)) eql = false;
jsvUnLock(contents);
} else {
/* Make sure we don't get in the situation where we have two equal
* strings with a check that fails because they were stored differently */
assert(!(jsvIsString(a) && jsvIsString(b) && jsvIsBasicVarEqual(a,b)));
}
return eql;
}
JsVar *jsvMathsOp(JsVar *a, JsVar *b, int op) {
// Type equality check
if (op == LEX_TYPEEQUAL || op == LEX_NTYPEEQUAL) {
bool eql = jsvMathsOpTypeEqual(a,b);
if (op == LEX_TYPEEQUAL)
return jsvNewFromBool(eql);
else
return jsvNewFromBool(!eql);
}
bool needsInt = op=='&' || op=='|' || op=='^' || op==LEX_LSHIFT || op==LEX_RSHIFT || op==LEX_RSHIFTUNSIGNED;
bool needsNumeric = needsInt || op=='*' || op=='/' || op=='%' || op=='-';
bool isCompare = op==LEX_EQUAL || op==LEX_NEQUAL || op=='<' || op==LEX_LEQUAL || op=='>'|| op==LEX_GEQUAL;
if (isCompare) {
if (jsvIsNumeric(a) && jsvIsString(b)) {
needsNumeric = true;
needsInt = jsvIsIntegerish(a) && jsvIsStringNumericInt(b, false);
} else if (jsvIsNumeric(b) && jsvIsString(a)) {
needsNumeric = true;
needsInt = jsvIsIntegerish(b) && jsvIsStringNumericInt(a, false);
}
}
// do maths...
if (jsvIsUndefined(a) && jsvIsUndefined(b)) {
if (op == LEX_EQUAL)
return jsvNewFromBool(true);
else if (op == LEX_NEQUAL)
return jsvNewFromBool(false);
else
return 0; // undefined
} else if (needsNumeric ||
((jsvIsNumeric(a) || jsvIsUndefined(a) || jsvIsNull(a)) &&
(jsvIsNumeric(b) || jsvIsUndefined(b) || jsvIsNull(b)))) {
if (needsInt || (jsvIsIntegerish(a) && jsvIsIntegerish(b))) {
// note that int+undefined should be handled as a double
// use ints
JsVarInt da = jsvGetInteger(a);
JsVarInt db = jsvGetInteger(b);
switch (op) {
case '+': return jsvNewFromLongInteger((long long)da + (long long)db);
case '-': return jsvNewFromLongInteger((long long)da - (long long)db);
case '*': return jsvNewFromLongInteger((long long)da * (long long)db);
case '/': return jsvNewFromFloat((JsVarFloat)da/(JsVarFloat)db);
case '&': return jsvNewFromInteger(da&db);
case '|': return jsvNewFromInteger(da|db);
case '^': return jsvNewFromInteger(da^db);
case '%': return db ? jsvNewFromInteger(da%db) : jsvNewFromFloat(NAN);
case LEX_LSHIFT: return jsvNewFromInteger(da << db);
case LEX_RSHIFT: return jsvNewFromInteger(da >> db);
case LEX_RSHIFTUNSIGNED: return jsvNewFromInteger((JsVarInt)(((JsVarIntUnsigned)da) >> db));
case LEX_EQUAL: return jsvNewFromBool(da==db && jsvIsNull(a)==jsvIsNull(b));
case LEX_NEQUAL: return jsvNewFromBool(da!=db || jsvIsNull(a)!=jsvIsNull(b));
case '<': return jsvNewFromBool(da<db);
case LEX_LEQUAL: return jsvNewFromBool(da<=db);
case '>': return jsvNewFromBool(da>db);
case LEX_GEQUAL: return jsvNewFromBool(da>=db);
default: return jsvMathsOpError(op, "Integer");
}
} else {
// use doubles
JsVarFloat da = jsvGetFloat(a);
JsVarFloat db = jsvGetFloat(b);
switch (op) {
case '+': return jsvNewFromFloat(da+db);
case '-': return jsvNewFromFloat(da-db);
case '*': return jsvNewFromFloat(da*db);
case '/': return jsvNewFromFloat(da/db);
case '%': return jsvNewFromFloat(jswrap_math_mod(da, db));
case LEX_EQUAL:
case LEX_NEQUAL: { bool equal = da==db;
if ((jsvIsNull(a) && jsvIsUndefined(b)) ||
(jsvIsNull(b) && jsvIsUndefined(a))) equal = true; // JS quirk :)
return jsvNewFromBool((op==LEX_EQUAL) ? equal : ((bool)!equal));
}
case '<': return jsvNewFromBool(da<db);
case LEX_LEQUAL: return jsvNewFromBool(da<=db);
case '>': return jsvNewFromBool(da>db);
case LEX_GEQUAL: return jsvNewFromBool(da>=db);
default: return jsvMathsOpError(op, "Double");
}
}
} else if ((jsvIsArray(a) || jsvIsObject(a) || jsvIsFunction(a) ||
jsvIsArray(b) || jsvIsObject(b) || jsvIsFunction(b)) &&
jsvIsArray(a)==jsvIsArray(b) && // Fix #283 - convert to string and test if only one is an array
(op == LEX_EQUAL || op==LEX_NEQUAL)) {
bool equal = a==b;
if (jsvIsNativeFunction(a) || jsvIsNativeFunction(b)) {
// even if one is not native, the contents will be different
equal = a && b &&
a->varData.native.ptr == b->varData.native.ptr &&
a->varData.native.argTypes == b->varData.native.argTypes &&
jsvGetFirstChild(a) == jsvGetFirstChild(b);
}
/* Just check pointers */
switch (op) {
case LEX_EQUAL: return jsvNewFromBool(equal);
case LEX_NEQUAL: return jsvNewFromBool(!equal);
default: return jsvMathsOpError(op, jsvIsArray(a)?"Array":"Object");
}
} else {
JsVar *da = jsvAsString(a, false);
JsVar *db = jsvAsString(b, false);
if (!da || !db) { // out of memory
jsvUnLock2(da, db);
return 0;
}
if (op=='+') {
JsVar *v = jsvCopy(da, false);
// TODO: can we be fancy and not copy da if we know it isn't reffed? what about locks?
if (v) // could be out of memory
jsvAppendStringVarComplete(v, db);
jsvUnLock2(da, db);
return v;
}
int cmp = jsvCompareString(da,db,0,0,false);
jsvUnLock2(da, db);
// use strings
switch (op) {
case LEX_EQUAL: return jsvNewFromBool(cmp==0);
case LEX_NEQUAL: return jsvNewFromBool(cmp!=0);
case '<': return jsvNewFromBool(cmp<0);
case LEX_LEQUAL: return jsvNewFromBool(cmp<=0);
case '>': return jsvNewFromBool(cmp>0);
case LEX_GEQUAL: return jsvNewFromBool(cmp>=0);
default: return jsvMathsOpError(op, "String");
}
}
}
JsVar *jsvNegateAndUnLock(JsVar *v) {
JsVar *zero = jsvNewFromInteger(0);
JsVar *res = jsvMathsOpSkipNames(zero, v, '-');
jsvUnLock2(zero, v);
return res;
}
/** If the given element is found, return the path to it as a string of
* the form 'foo.bar', else return 0. If we would have returned a.b and
* ignoreParent is a, don't! */
JsVar *jsvGetPathTo(JsVar *root, JsVar *element, int maxDepth, JsVar *ignoreParent) {
if (maxDepth<=0) return 0;
JsvIterator it;
jsvIteratorNew(&it, root, JSIF_DEFINED_ARRAY_ElEMENTS);
while (jsvIteratorHasElement(&it)) {
JsVar *el = jsvIteratorGetValue(&it);
if (el == element && root != ignoreParent) {
// if we found it - send the key name back!
JsVar *name = jsvAsString(jsvIteratorGetKey(&it), true);
jsvIteratorFree(&it);
return name;
} else if (jsvIsObject(el) || jsvIsArray(el) || jsvIsFunction(el)) {
// recursively search
JsVar *n = jsvGetPathTo(el, element, maxDepth-1, ignoreParent);
if (n) {
// we found it! Append our name onto it as well
JsVar *keyName = jsvIteratorGetKey(&it);
JsVar *name = jsvVarPrintf(jsvIsObject(el) ? "%v.%v" : "%v[%q]",keyName,n);
jsvUnLock2(keyName, n);
jsvIteratorFree(&it);
return name;
}
}
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
return 0;
}
void jsvTraceLockInfo(JsVar *v) {
jsiConsolePrintf("#%d[r%d,l%d] ",jsvGetRef(v),jsvGetRefs(v),jsvGetLocks(v));
}
/** Get the lowest level at which searchRef appears */
int _jsvTraceGetLowestLevel(JsVar *var, JsVar *searchVar) {
if (var == searchVar) return 0;
int found = -1;
// Use IS_RECURSING flag to stop recursion
if (var->flags & JSV_IS_RECURSING)
return -1;
var->flags |= JSV_IS_RECURSING;
if (jsvHasSingleChild(var) && jsvGetFirstChild(var)) {
JsVar *child = jsvLock(jsvGetFirstChild(var));
int f = _jsvTraceGetLowestLevel(child, searchVar);
jsvUnLock(child);
if (f>=0 && (found<0 || f<found)) found=f+1;
}
if (jsvHasChildren(var)) {
JsVarRef childRef = jsvGetFirstChild(var);
while (childRef) {
JsVar *child = jsvLock(childRef);
int f = _jsvTraceGetLowestLevel(child, searchVar);
if (f>=0 && (found<0 || f<found)) found=f+1;
childRef = jsvGetNextSibling(child);
jsvUnLock(child);
}
}
var->flags &= ~JSV_IS_RECURSING;
return found; // searchRef not found
}
void _jsvTrace(JsVar *var, int indent, JsVar *baseVar, int level) {
#ifdef SAVE_ON_FLASH
jsiConsolePrint("Trace unimplemented in this version.\n");
#else
int i;
for (i=0;i<indent;i++) jsiConsolePrint(" ");
if (!var) {
jsiConsolePrint("undefined");
return;
}
jsvTraceLockInfo(var);
int lowestLevel = _jsvTraceGetLowestLevel(baseVar, var);
if (lowestLevel < level) {
// If this data is available elsewhere in the tree (but nearer the root)
// then don't print it. This makes the dump significantly more readable!
// It also stops us getting in recursive loops ...
jsiConsolePrint("...\n");
return;
}
if (jsvIsName(var)) jsiConsolePrint("Name ");
char endBracket = ' ';
if (jsvIsObject(var)) { jsiConsolePrint("Object { "); endBracket = '}'; }
else if (jsvIsArray(var)) { jsiConsolePrintf("Array(%d) [ ", var->varData.integer); endBracket = ']'; }
else if (jsvIsNativeFunction(var)) { jsiConsolePrintf("NativeFunction 0x%x (%d) { ", var->varData.native.ptr, var->varData.native.argTypes); endBracket = '}'; }
else if (jsvIsFunction(var)) {
jsiConsolePrint("Function { ");
if (jsvIsFunctionReturn(var)) jsiConsolePrint("return ");
endBracket = '}';
} else if (jsvIsPin(var)) jsiConsolePrintf("Pin %d", jsvGetInteger(var));
else if (jsvIsInt(var)) jsiConsolePrintf("Integer %d", jsvGetInteger(var));
else if (jsvIsBoolean(var)) jsiConsolePrintf("Bool %s", jsvGetBool(var)?"true":"false");
else if (jsvIsFloat(var)) jsiConsolePrintf("Double %f", jsvGetFloat(var));
else if (jsvIsFunctionParameter(var)) jsiConsolePrintf("Param %q ", var);
else if (jsvIsArrayBufferName(var)) jsiConsolePrintf("ArrayBufferName[%d] ", jsvGetInteger(var));
else if (jsvIsArrayBuffer(var)) jsiConsolePrintf("%s ", jswGetBasicObjectName(var)?jswGetBasicObjectName(var):"unknown ArrayBuffer"); // way to get nice name
else if (jsvIsString(var)) {
size_t blocks = 1;
if (jsvGetLastChild(var)) {
JsVar *v = jsvLock(jsvGetLastChild(var));
blocks += jsvCountJsVarsUsed(v);
jsvUnLock(v);
}
if (jsvIsFlatString(var)) {
blocks += jsvGetFlatStringBlocks(var);
}
jsiConsolePrintf("%sString [%d blocks] %q", jsvIsFlatString(var)?"Flat":(jsvIsNativeString(var)?"Native":""), blocks, var);
} else {
jsiConsolePrintf("Unknown %d", var->flags & (JsVarFlags)~(JSV_LOCK_MASK));
}
// print a value if it was stored in here as well...
if (jsvIsNameInt(var)) {
jsiConsolePrintf("= int %d\n", (int)jsvGetFirstChildSigned(var));
return;
} else if (jsvIsNameIntBool(var)) {
jsiConsolePrintf("= bool %s\n", jsvGetFirstChild(var)?"true":"false");
return;
}
if (jsvHasSingleChild(var)) {
JsVar *child = jsvGetFirstChild(var) ? jsvLock(jsvGetFirstChild(var)) : 0;
_jsvTrace(child, indent+2, baseVar, level+1);
jsvUnLock(child);
} else if (jsvHasChildren(var)) {
JsvIterator it;
jsvIteratorNew(&it, var, JSIF_DEFINED_ARRAY_ElEMENTS);
bool first = true;
while (jsvIteratorHasElement(&it) && !jspIsInterrupted()) {
if (first) jsiConsolePrintf("\n");
first = false;
JsVar *child = jsvIteratorGetKey(&it);
_jsvTrace(child, indent+2, baseVar, level+1);
jsvUnLock(child);
jsiConsolePrintf("\n");
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
if (!first)
for (i=0;i<indent;i++) jsiConsolePrint(" ");
}
jsiConsolePrintf("%c", endBracket);
#endif
}
/** Write debug info for this Var out to the console */
void jsvTrace(JsVar *var, int indent) {
_jsvTrace(var,indent,var,0);
jsiConsolePrintf("\n");
}
/** Recursively mark the variable */
static void jsvGarbageCollectMarkUsed(JsVar *var) {
var->flags &= (JsVarFlags)~JSV_GARBAGE_COLLECT;
if (jsvHasCharacterData(var)) {
// non-recursively scan strings
JsVarRef child = jsvGetLastChild(var);
while (child) {
JsVar *childVar;
childVar = jsvGetAddressOf(child);
childVar->flags &= (JsVarFlags)~JSV_GARBAGE_COLLECT;
child = jsvGetLastChild(childVar);
}
}
// intentionally no else
if (jsvHasSingleChild(var)) {
if (jsvGetFirstChild(var)) {
JsVar *childVar = jsvGetAddressOf(jsvGetFirstChild(var));
if (childVar->flags & JSV_GARBAGE_COLLECT)
jsvGarbageCollectMarkUsed(childVar);
}
} else if (jsvHasChildren(var)) {
JsVarRef child = jsvGetFirstChild(var);
while (child) {
JsVar *childVar;
childVar = jsvGetAddressOf(child);
if (childVar->flags & JSV_GARBAGE_COLLECT)
jsvGarbageCollectMarkUsed(childVar);
child = jsvGetNextSibling(childVar);
}
}
}
/** Run a garbage collection sweep - return nonzero if things have been freed */
int jsvGarbageCollect() {
if (isMemoryBusy) return false;
isMemoryBusy = MEMBUSY_GC;
JsVarRef i;
// Add GC flags to anything that is currently used
for (i=1;i<=jsVarsSize;i++) {
JsVar *var = jsvGetAddressOf(i);
if ((var->flags&JSV_VARTYPEMASK) != JSV_UNUSED) { // if it is not unused
var->flags |= (JsVarFlags)JSV_GARBAGE_COLLECT;
// if we have a flat string, skip that many blocks
if (jsvIsFlatString(var))
i = (JsVarRef)(i+jsvGetFlatStringBlocks(var));
}
}
/* recursively remove anything that is referenced from a var that is locked. */
for (i=1;i<=jsVarsSize;i++) {
JsVar *var = jsvGetAddressOf(i);
if ((var->flags & JSV_GARBAGE_COLLECT) && // not already GC'd
jsvGetLocks(var)>0) // or it is locked
jsvGarbageCollectMarkUsed(var);
// if we have a flat string, skip that many blocks
if (jsvIsFlatString(var))
i = (JsVarRef)(i+jsvGetFlatStringBlocks(var));
}
/* now sweep for things that we can GC!
* Also update the free list - this means that every new variable that
* gets allocated gets allocated towards the start of memory, which
* hopefully helps compact everything towards the start. */
unsigned int freedCount = 0;
jsVarFirstEmpty = 0;
JsVar *lastEmpty = 0;
for (i=1;i<=jsVarsSize;i++) {
JsVar *var = jsvGetAddressOf(i);
if (var->flags & JSV_GARBAGE_COLLECT) {
if (jsvIsFlatString(var)) {
// If we're a flat string, there are more blocks to free.
unsigned int count = (unsigned int)jsvGetFlatStringBlocks(var);
freedCount+=count;
// Free the first block
var->flags = JSV_UNUSED;
// add this to our free list
if (lastEmpty) jsvSetNextSibling(lastEmpty, i);
else jsVarFirstEmpty = i;
lastEmpty = var;
// free subsequent blocks
while (count-- > 0) {
i++;
var = jsvGetAddressOf((JsVarRef)(i));
var->flags = JSV_UNUSED;
// add this to our free list
if (lastEmpty) jsvSetNextSibling(lastEmpty, i);
else jsVarFirstEmpty = i;
lastEmpty = var;
}
} else {
// otherwise just free 1 block
if (jsvHasSingleChild(var)) {
/* If this had a child that wasn't listed for GC then we need to
* unref it. Everything else is fine because it'll disappear anyway.
* We don't have to check if we should free this other variable
* here because we know the GC picked up it was referenced from
* somewhere else. */
JsVarRef ch = jsvGetFirstChild(var);
if (ch) {
JsVar *child = jsvGetAddressOf(ch); // not locked
if (child->flags!=JSV_UNUSED && // not already GC'd!
!(child->flags&JSV_GARBAGE_COLLECT)) // not marked for GC
jsvUnRef(child);
}
}
/* Sanity checks here. We're making sure that any variables that are
* linked from this one have either already been garbage collected or
* are marked for GC */
assert(!jsvHasChildren(var) || !jsvGetFirstChild(var) ||
jsvGetAddressOf(jsvGetFirstChild(var))->flags==JSV_UNUSED ||
(jsvGetAddressOf(jsvGetFirstChild(var))->flags&JSV_GARBAGE_COLLECT));
assert(!jsvHasChildren(var) || !jsvGetLastChild(var) ||
jsvGetAddressOf(jsvGetLastChild(var))->flags==JSV_UNUSED ||
(jsvGetAddressOf(jsvGetLastChild(var))->flags&JSV_GARBAGE_COLLECT));
assert(!jsvIsName(var) || !jsvGetPrevSibling(var) ||
jsvGetAddressOf(jsvGetPrevSibling(var))->flags==JSV_UNUSED ||
(jsvGetAddressOf(jsvGetPrevSibling(var))->flags&JSV_GARBAGE_COLLECT));
assert(!jsvIsName(var) || !jsvGetNextSibling(var) ||
jsvGetAddressOf(jsvGetNextSibling(var))->flags==JSV_UNUSED ||
(jsvGetAddressOf(jsvGetNextSibling(var))->flags&JSV_GARBAGE_COLLECT));
// free!
var->flags = JSV_UNUSED;
// add this to our free list
if (lastEmpty) jsvSetNextSibling(lastEmpty, i);
else jsVarFirstEmpty = i;
lastEmpty = var;
freedCount++;
}
} else if (jsvIsFlatString(var)) {
// if we have a flat string, skip forward that many blocks
i = (JsVarRef)(i+jsvGetFlatStringBlocks(var));
} else if (var->flags == JSV_UNUSED) {
// this is already free - add it to the free list
if (lastEmpty) jsvSetNextSibling(lastEmpty, i);
else jsVarFirstEmpty = i;
lastEmpty = var;
}
}
if (lastEmpty) jsvSetNextSibling(lastEmpty, 0);
isMemoryBusy = MEM_NOT_BUSY;
return (int)freedCount;
}
#ifndef RELEASE
// Dump any locked variables that aren't referenced from `global` - for debugging memory leaks
void jsvDumpLockedVars() {
jsvGarbageCollect();
if (isMemoryBusy) return;
isMemoryBusy = MEMBUSY_SYSTEM;
JsVarRef i;
// clear garbage collect flags
for (i=1;i<=jsVarsSize;i++) {
JsVar *var = jsvGetAddressOf(i);
if ((var->flags&JSV_VARTYPEMASK) != JSV_UNUSED) { // if it is not unused
var->flags |= (JsVarFlags)JSV_GARBAGE_COLLECT;
// if we have a flat string, skip that many blocks
if (jsvIsFlatString(var))
i = (JsVarRef)(i+jsvGetFlatStringBlocks(var));
}
}
// Add global
jsvGarbageCollectMarkUsed(execInfo.root);
// Now dump any that aren't used!
for (i=1;i<=jsVarsSize;i++) {
JsVar *var = jsvGetAddressOf(i);
if ((var->flags&JSV_VARTYPEMASK) != JSV_UNUSED) {
if (var->flags & JSV_GARBAGE_COLLECT) {
jsvGarbageCollectMarkUsed(var);
jsvTrace(var, 0);
}
}
}
isMemoryBusy = MEM_NOT_BUSY;
}
// Dump the free list - in order
void jsvDumpFreeList() {
JsVarRef ref = jsVarFirstEmpty;
int n = 0;
while (ref) {
jsiConsolePrintf("%5d ", (int)ref);
if (++n >= 16) {
n = 0;
jsiConsolePrintf("\n");
}
JsVar *v = jsvGetAddressOf(ref);
ref = jsvGetNextSibling(v);
}
jsiConsolePrintf("\n");
}
#endif
/** Remove whitespace to the right of a string - on MULTIPLE LINES */
JsVar *jsvStringTrimRight(JsVar *srcString) {
JsvStringIterator src, dst;
JsVar *dstString = jsvNewFromEmptyString();
jsvStringIteratorNew(&src, srcString, 0);
jsvStringIteratorNew(&dst, dstString, 0);
int spaces = 0;
while (jsvStringIteratorHasChar(&src)) {
char ch = jsvStringIteratorGetChar(&src);
jsvStringIteratorNext(&src);
if (ch==' ') spaces++;
else if (ch=='\n') {
spaces = 0;
jsvStringIteratorAppend(&dst, ch);
} else {
for (;spaces>0;spaces--)
jsvStringIteratorAppend(&dst, ' ');
jsvStringIteratorAppend(&dst, ch);
}
}
jsvStringIteratorFree(&src);
jsvStringIteratorFree(&dst);
return dstString;
}
/// If v is the key of a function, return true if it is internal and shouldn't be visible to the user
bool jsvIsInternalFunctionKey(JsVar *v) {
return (jsvIsString(v) && (
v->varData.str[0]==JS_HIDDEN_CHAR)
) ||
jsvIsFunctionParameter(v);
}
/// If v is the key of an object, return true if it is internal and shouldn't be visible to the user
bool jsvIsInternalObjectKey(JsVar *v) {
return (jsvIsString(v) && (
v->varData.str[0]==JS_HIDDEN_CHAR ||
jsvIsStringEqual(v, JSPARSE_INHERITS_VAR) ||
jsvIsStringEqual(v, JSPARSE_CONSTRUCTOR_VAR)
));
}
/// Get the correct checker function for the given variable. see jsvIsInternalFunctionKey/jsvIsInternalObjectKey
JsvIsInternalChecker jsvGetInternalFunctionCheckerFor(JsVar *v) {
if (jsvIsFunction(v)) return jsvIsInternalFunctionKey;
if (jsvIsObject(v)) return jsvIsInternalObjectKey;
return 0;
}
/** Using 'configs', this reads 'object' into the given pointers, returns true on success.
* If object is not undefined and not an object, an error is raised.
* If there are fields that are not in the list of configs, an error is raised
*/
bool jsvReadConfigObject(JsVar *object, jsvConfigObject *configs, int nConfigs) {
if (jsvIsUndefined(object)) return true;
if (!jsvIsObject(object)) {
jsExceptionHere(JSET_ERROR, "Expecting an Object, or undefined");
return false;
}
// Ok, it's an object
JsvObjectIterator it;
jsvObjectIteratorNew(&it, object);
bool ok = true;
while (ok && jsvObjectIteratorHasValue(&it)) {
JsVar *key = jsvObjectIteratorGetKey(&it);
bool found = false;
int i;
for (i=0;i<nConfigs;i++) {
if (jsvIsStringEqual(key, configs[i].name)) {
found = true;
if (configs[i].ptr) {
JsVar *val = jsvObjectIteratorGetValue(&it);
switch (configs[i].type) {
case 0: break;
case JSV_OBJECT:
case JSV_STRING_0:
case JSV_ARRAY:
case JSV_FUNCTION:
*((JsVar**)configs[i].ptr) = jsvLockAgain(val); break;
case JSV_PIN: *((Pin*)configs[i].ptr) = jshGetPinFromVar(val); break;
case JSV_BOOLEAN: *((bool*)configs[i].ptr) = jsvGetBool(val); break;
case JSV_INTEGER: *((JsVarInt*)configs[i].ptr) = jsvGetInteger(val); break;
case JSV_FLOAT: *((JsVarFloat*)configs[i].ptr) = jsvGetFloat(val); break;
default: assert(0); break;
}
jsvUnLock(val);
}
}
}
if (!found) {
jsExceptionHere(JSET_ERROR, "Unknown option %q", key);
ok = false;
}
jsvUnLock(key);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
return ok;
}
/// Is the variable an instance of the given class. Eg. `jsvIsInstanceOf(e, "Error")` - does a simple, non-recursive check that doesn't take account of builtins like String
bool jsvIsInstanceOf(JsVar *var, const char *constructorName) {
bool isInst = false;
if (!jsvHasChildren(var)) return false;
JsVar *proto = jsvObjectGetChild(var, JSPARSE_INHERITS_VAR, 0);
if (jsvIsObject(proto)) {
JsVar *constr = jsvObjectGetChild(proto, JSPARSE_CONSTRUCTOR_VAR, 0);
if (constr)
isInst = jspIsConstructor(constr, constructorName);
jsvUnLock(constr);
}
jsvUnLock(proto);
return isInst;
}
JsVar *jsvNewTypedArray(JsVarDataArrayBufferViewType type, JsVarInt length) {
JsVar *lenVar = jsvNewFromInteger(length);
if (!lenVar) return 0;
JsVar *array = jswrap_typedarray_constructor(type, lenVar,0,0);
jsvUnLock(lenVar);
return array;
}
#ifndef SAVE_ON_FLASH
JsVar *jsvNewDataViewWithData(JsVarInt length, unsigned char *data) {
JsVar *buf = jswrap_arraybuffer_constructor(length);
if (!buf) return 0;
JsVar *view = jswrap_dataview_constructor(buf, 0, 0);
if (!view) {
jsvUnLock(buf);
return 0;
}
if (data) {
JsVar *arrayBufferData = jsvGetArrayBufferBackingString(buf);
if (arrayBufferData)
jsvSetString(arrayBufferData, (char *)data, (size_t)length);
jsvUnLock(arrayBufferData);
}
jsvUnLock(buf);
return view;
}
#endif
JsVar *jsvNewArrayBufferWithPtr(unsigned int length, char **ptr) {
assert(ptr);
*ptr=0;
JsVar *backingString = jsvNewFlatStringOfLength(length);
if (!backingString) return 0;
JsVar *arr = jsvNewArrayBufferFromString(backingString, length);
if (!arr) {
jsvUnLock(backingString);
return 0;
}
*ptr = jsvGetFlatStringPointer(backingString);
jsvUnLock(backingString);
return arr;
}
JsVar *jsvNewArrayBufferWithData(JsVarInt length, unsigned char *data) {
assert(data);
JsVar *dst = 0;
JsVar *arr = jsvNewArrayBufferWithPtr((unsigned int)length, (char**)&dst);
if (!dst) {
jsvUnLock(arr);
return 0;
}
memcpy(dst, data, (size_t)length);
return arr;
}
void *jsvMalloc(size_t size) {
/** Allocate flat string, return pointer to its first element.
* As we drop the pointer here, it's left locked. jsvGetFlatStringPointer
* is also safe if 0 is passed in. */
JsVar *flatStr = jsvNewFlatStringOfLength((unsigned int)size);
if (!flatStr) {
jsErrorFlags |= JSERR_LOW_MEMORY;
// Not allocated - try and free any command history/etc
while (jsiFreeMoreMemory());
// Garbage collect
jsvGarbageCollect();
// Try again
flatStr = jsvNewFlatStringOfLength((unsigned int)size);
}
// intentionally no jsvUnLock - see above
void *p = (void*)jsvGetFlatStringPointer(flatStr);
if (p) {
//jsiConsolePrintf("jsvMalloc var %d-%d at %d (%d bytes)\n", jsvGetRef(flatStr), jsvGetRef(flatStr)+jsvGetFlatStringBlocks(flatStr), p, size);
memset(p,0,size);
}
return p;
}
void jsvFree(void *ptr) {
JsVar *flatStr = jsvGetFlatStringFromPointer((char *)ptr);
//jsiConsolePrintf("jsvFree var %d at %d (%d bytes)\n", jsvGetRef(flatStr), ptr, jsvGetLength(flatStr));
jsvUnLock(flatStr);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_160_4 |
crossvul-cpp_data_good_5203_0 | /**
* collectd - src/network.c
* Copyright (C) 2005-2013 Florian octo Forster
* Copyright (C) 2009 Aman Gupta
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; only version 2.1 of the License is
* applicable.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Authors:
* Florian octo Forster <octo at collectd.org>
* Aman Gupta <aman at tmm1.net>
**/
#define _DEFAULT_SOURCE
#define _BSD_SOURCE /* For struct ip_mreq */
#include "collectd.h"
#include "plugin.h"
#include "common.h"
#include "configfile.h"
#include "utils_fbhash.h"
#include "utils_avltree.h"
#include "utils_cache.h"
#include "utils_complain.h"
#include "network.h"
#if HAVE_PTHREAD_H
# include <pthread.h>
#endif
#if HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
#if HAVE_NETDB_H
# include <netdb.h>
#endif
#if HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif
#if HAVE_ARPA_INET_H
# include <arpa/inet.h>
#endif
#if HAVE_POLL_H
# include <poll.h>
#endif
#if HAVE_NET_IF_H
# include <net/if.h>
#endif
#if HAVE_LIBGCRYPT
# include <pthread.h>
# if defined __APPLE__
/* default xcode compiler throws warnings even when deprecated functionality
* is not used. -Werror breaks the build because of erroneous warnings.
* http://stackoverflow.com/questions/10556299/compiler-warnings-with-libgcrypt-v1-5-0/12830209#12830209
*/
# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
# endif
/* FreeBSD's copy of libgcrypt extends the existing GCRYPT_NO_DEPRECATED
* to properly hide all deprecated functionality.
* http://svnweb.freebsd.org/ports/head/security/libgcrypt/files/patch-src__gcrypt.h.in
*/
# define GCRYPT_NO_DEPRECATED
# include <gcrypt.h>
# if defined __APPLE__
/* Re enable deprecation warnings */
# pragma GCC diagnostic warning "-Wdeprecated-declarations"
# endif
# if GCRYPT_VERSION_NUMBER < 0x010600
GCRY_THREAD_OPTION_PTHREAD_IMPL;
# endif
#endif
#ifndef IPV6_ADD_MEMBERSHIP
# ifdef IPV6_JOIN_GROUP
# define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
# else
# error "Neither IP_ADD_MEMBERSHIP nor IPV6_JOIN_GROUP is defined"
# endif
#endif /* !IP_ADD_MEMBERSHIP */
/*
* Maximum size required for encryption / signing:
*
* 42 bytes for the encryption header
* + 64 bytes for the username
* -----------
* = 106 bytes
*/
#define BUFF_SIG_SIZE 106
/*
* Private data types
*/
#define SECURITY_LEVEL_NONE 0
#if HAVE_LIBGCRYPT
# define SECURITY_LEVEL_SIGN 1
# define SECURITY_LEVEL_ENCRYPT 2
#endif
struct sockent_client
{
int fd;
struct sockaddr_storage *addr;
socklen_t addrlen;
#if HAVE_LIBGCRYPT
int security_level;
char *username;
char *password;
gcry_cipher_hd_t cypher;
unsigned char password_hash[32];
#endif
};
struct sockent_server
{
int *fd;
size_t fd_num;
#if HAVE_LIBGCRYPT
int security_level;
char *auth_file;
fbhash_t *userdb;
gcry_cipher_hd_t cypher;
#endif
};
typedef struct sockent
{
#define SOCKENT_TYPE_CLIENT 1
#define SOCKENT_TYPE_SERVER 2
int type;
char *node;
char *service;
int interface;
union
{
struct sockent_client client;
struct sockent_server server;
} data;
struct sockent *next;
} sockent_t;
/* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-------+-----------------------+-------------------------------+
* ! Ver. ! ! Length !
* +-------+-----------------------+-------------------------------+
*/
struct part_header_s
{
uint16_t type;
uint16_t length;
};
typedef struct part_header_s part_header_t;
/* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-------------------------------+-------------------------------+
* ! Type ! Length !
* +-------------------------------+-------------------------------+
* : (Length - 4) Bytes :
* +---------------------------------------------------------------+
*/
struct part_string_s
{
part_header_t *head;
char *value;
};
typedef struct part_string_s part_string_t;
/* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-------------------------------+-------------------------------+
* ! Type ! Length !
* +-------------------------------+-------------------------------+
* : (Length - 4 == 2 || 4 || 8) Bytes :
* +---------------------------------------------------------------+
*/
struct part_number_s
{
part_header_t *head;
uint64_t *value;
};
typedef struct part_number_s part_number_t;
/* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-------------------------------+-------------------------------+
* ! Type ! Length !
* +-------------------------------+---------------+---------------+
* ! Num of values ! Type0 ! Type1 !
* +-------------------------------+---------------+---------------+
* ! Value0 !
* ! !
* +---------------------------------------------------------------+
* ! Value1 !
* ! !
* +---------------------------------------------------------------+
*/
struct part_values_s
{
part_header_t *head;
uint16_t *num_values;
uint8_t *values_types;
value_t *values;
};
typedef struct part_values_s part_values_t;
/* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-------------------------------+-------------------------------+
* ! Type ! Length !
* +-------------------------------+-------------------------------+
* ! Hash (Bits 0 - 31) !
* : : :
* ! Hash (Bits 224 - 255) !
* +---------------------------------------------------------------+
*/
/* Minimum size */
#define PART_SIGNATURE_SHA256_SIZE 36
struct part_signature_sha256_s
{
part_header_t head;
unsigned char hash[32];
char *username;
};
typedef struct part_signature_sha256_s part_signature_sha256_t;
/* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-------------------------------+-------------------------------+
* ! Type ! Length !
* +-------------------------------+-------------------------------+
* ! Original length ! Padding (0 - 15 bytes) !
* +-------------------------------+-------------------------------+
* ! Hash (Bits 0 - 31) !
* : : :
* ! Hash (Bits 128 - 159) !
* +---------------------------------------------------------------+
*/
/* Minimum size */
#define PART_ENCRYPTION_AES256_SIZE 42
struct part_encryption_aes256_s
{
part_header_t head;
uint16_t username_length;
char *username;
unsigned char iv[16];
/* <encrypted> */
unsigned char hash[20];
/* <payload /> */
/* </encrypted> */
};
typedef struct part_encryption_aes256_s part_encryption_aes256_t;
struct receive_list_entry_s
{
char *data;
int data_len;
int fd;
struct receive_list_entry_s *next;
};
typedef struct receive_list_entry_s receive_list_entry_t;
/*
* Private variables
*/
static int network_config_ttl = 0;
/* Ethernet - (IPv6 + UDP) = 1500 - (40 + 8) = 1452 */
static size_t network_config_packet_size = 1452;
static int network_config_forward = 0;
static int network_config_stats = 0;
static sockent_t *sending_sockets = NULL;
static receive_list_entry_t *receive_list_head = NULL;
static receive_list_entry_t *receive_list_tail = NULL;
static pthread_mutex_t receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t receive_list_cond = PTHREAD_COND_INITIALIZER;
static uint64_t receive_list_length = 0;
static sockent_t *listen_sockets = NULL;
static struct pollfd *listen_sockets_pollfd = NULL;
static size_t listen_sockets_num = 0;
/* The receive and dispatch threads will run as long as `listen_loop' is set to
* zero. */
static int listen_loop = 0;
static int receive_thread_running = 0;
static pthread_t receive_thread_id;
static int dispatch_thread_running = 0;
static pthread_t dispatch_thread_id;
/* Buffer in which to-be-sent network packets are constructed. */
static char *send_buffer;
static char *send_buffer_ptr;
static int send_buffer_fill;
static value_list_t send_buffer_vl = VALUE_LIST_STATIC;
static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
/* XXX: These counters are incremented from one place only. The spot in which
* the values are incremented is either only reachable by one thread (the
* dispatch thread, for example) or locked by some lock (send_buffer_lock for
* example). Only if neither is true, the stats_lock is acquired. The counters
* are always read without holding a lock in the hope that writing 8 bytes to
* memory is an atomic operation. */
static derive_t stats_octets_rx = 0;
static derive_t stats_octets_tx = 0;
static derive_t stats_packets_rx = 0;
static derive_t stats_packets_tx = 0;
static derive_t stats_values_dispatched = 0;
static derive_t stats_values_not_dispatched = 0;
static derive_t stats_values_sent = 0;
static derive_t stats_values_not_sent = 0;
static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
/*
* Private functions
*/
static _Bool check_receive_okay (const value_list_t *vl) /* {{{ */
{
uint64_t time_sent = 0;
int status;
status = uc_meta_data_get_unsigned_int (vl,
"network:time_sent", &time_sent);
/* This is a value we already sent. Don't allow it to be received again in
* order to avoid looping. */
if ((status == 0) && (time_sent >= ((uint64_t) vl->time)))
return (0);
return (1);
} /* }}} _Bool check_receive_okay */
static _Bool check_send_okay (const value_list_t *vl) /* {{{ */
{
_Bool received = 0;
int status;
if (network_config_forward != 0)
return (1);
if (vl->meta == NULL)
return (1);
status = meta_data_get_boolean (vl->meta, "network:received", &received);
if (status == -ENOENT)
return (1);
else if (status != 0)
{
ERROR ("network plugin: check_send_okay: meta_data_get_boolean failed "
"with status %i.", status);
return (1);
}
/* By default, only *send* value lists that were not *received* by the
* network plugin. */
return (!received);
} /* }}} _Bool check_send_okay */
static _Bool check_notify_received (const notification_t *n) /* {{{ */
{
notification_meta_t *ptr;
for (ptr = n->meta; ptr != NULL; ptr = ptr->next)
if ((strcmp ("network:received", ptr->name) == 0)
&& (ptr->type == NM_TYPE_BOOLEAN))
return ((_Bool) ptr->nm_value.nm_boolean);
return (0);
} /* }}} _Bool check_notify_received */
static _Bool check_send_notify_okay (const notification_t *n) /* {{{ */
{
static c_complain_t complain_forwarding = C_COMPLAIN_INIT_STATIC;
_Bool received = 0;
if (n->meta == NULL)
return (1);
received = check_notify_received (n);
if (network_config_forward && received)
{
c_complain_once (LOG_ERR, &complain_forwarding,
"network plugin: A notification has been received via the network "
"and forwarding is enabled. Forwarding of notifications is currently "
"not supported, because there is not loop-deteciton available. "
"Please contact the collectd mailing list if you need this "
"feature.");
}
/* By default, only *send* value lists that were not *received* by the
* network plugin. */
return (!received);
} /* }}} _Bool check_send_notify_okay */
static int network_dispatch_values (value_list_t *vl, /* {{{ */
const char *username)
{
int status;
if ((vl->time <= 0)
|| (strlen (vl->host) <= 0)
|| (strlen (vl->plugin) <= 0)
|| (strlen (vl->type) <= 0))
return (-EINVAL);
if (!check_receive_okay (vl))
{
#if COLLECT_DEBUG
char name[6*DATA_MAX_NAME_LEN];
FORMAT_VL (name, sizeof (name), vl);
name[sizeof (name) - 1] = 0;
DEBUG ("network plugin: network_dispatch_values: "
"NOT dispatching %s.", name);
#endif
stats_values_not_dispatched++;
return (0);
}
assert (vl->meta == NULL);
vl->meta = meta_data_create ();
if (vl->meta == NULL)
{
ERROR ("network plugin: meta_data_create failed.");
return (-ENOMEM);
}
status = meta_data_add_boolean (vl->meta, "network:received", 1);
if (status != 0)
{
ERROR ("network plugin: meta_data_add_boolean failed.");
meta_data_destroy (vl->meta);
vl->meta = NULL;
return (status);
}
if (username != NULL)
{
status = meta_data_add_string (vl->meta, "network:username", username);
if (status != 0)
{
ERROR ("network plugin: meta_data_add_string failed.");
meta_data_destroy (vl->meta);
vl->meta = NULL;
return (status);
}
}
plugin_dispatch_values (vl);
stats_values_dispatched++;
meta_data_destroy (vl->meta);
vl->meta = NULL;
return (0);
} /* }}} int network_dispatch_values */
static int network_dispatch_notification (notification_t *n) /* {{{ */
{
int status;
assert (n->meta == NULL);
status = plugin_notification_meta_add_boolean (n, "network:received", 1);
if (status != 0)
{
ERROR ("network plugin: plugin_notification_meta_add_boolean failed.");
plugin_notification_meta_free (n->meta);
n->meta = NULL;
return (status);
}
status = plugin_dispatch_notification (n);
plugin_notification_meta_free (n->meta);
n->meta = NULL;
return (status);
} /* }}} int network_dispatch_notification */
#if HAVE_LIBGCRYPT
static void network_init_gcrypt (void) /* {{{ */
{
/* http://lists.gnupg.org/pipermail/gcrypt-devel/2003-August/000458.html
* Because you can't know in a library whether another library has
* already initialized the library */
if (gcry_control (GCRYCTL_ANY_INITIALIZATION_P))
return;
/* http://www.gnupg.org/documentation/manuals/gcrypt/Multi_002dThreading.html
* To ensure thread-safety, it's important to set GCRYCTL_SET_THREAD_CBS
* *before* initalizing Libgcrypt with gcry_check_version(), which itself must
* be called before any other gcry_* function. GCRYCTL_ANY_INITIALIZATION_P
* above doesn't count, as it doesn't implicitly initalize Libgcrypt.
*
* tl;dr: keep all these gry_* statements in this exact order please. */
# if GCRYPT_VERSION_NUMBER < 0x010600
gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
# endif
gcry_check_version (NULL);
gcry_control (GCRYCTL_INIT_SECMEM, 32768);
gcry_control (GCRYCTL_INITIALIZATION_FINISHED);
} /* }}} void network_init_gcrypt */
static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
const void *iv, size_t iv_size, const char *username)
{
gcry_error_t err;
gcry_cipher_hd_t *cyper_ptr;
unsigned char password_hash[32];
if (se->type == SOCKENT_TYPE_CLIENT)
{
cyper_ptr = &se->data.client.cypher;
memcpy (password_hash, se->data.client.password_hash,
sizeof (password_hash));
}
else
{
char *secret;
cyper_ptr = &se->data.server.cypher;
if (username == NULL)
return (NULL);
secret = fbh_get (se->data.server.userdb, username);
if (secret == NULL)
return (NULL);
gcry_md_hash_buffer (GCRY_MD_SHA256,
password_hash,
secret, strlen (secret));
sfree (secret);
}
if (*cyper_ptr == NULL)
{
err = gcry_cipher_open (cyper_ptr,
GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, /* flags = */ 0);
if (err != 0)
{
ERROR ("network plugin: gcry_cipher_open returned: %s",
gcry_strerror (err));
*cyper_ptr = NULL;
return (NULL);
}
}
else
{
gcry_cipher_reset (*cyper_ptr);
}
assert (*cyper_ptr != NULL);
err = gcry_cipher_setkey (*cyper_ptr,
password_hash, sizeof (password_hash));
if (err != 0)
{
ERROR ("network plugin: gcry_cipher_setkey returned: %s",
gcry_strerror (err));
gcry_cipher_close (*cyper_ptr);
*cyper_ptr = NULL;
return (NULL);
}
err = gcry_cipher_setiv (*cyper_ptr, iv, iv_size);
if (err != 0)
{
ERROR ("network plugin: gcry_cipher_setkey returned: %s",
gcry_strerror (err));
gcry_cipher_close (*cyper_ptr);
*cyper_ptr = NULL;
return (NULL);
}
return (*cyper_ptr);
} /* }}} int network_get_aes256_cypher */
#endif /* HAVE_LIBGCRYPT */
static int write_part_values (char **ret_buffer, int *ret_buffer_len,
const data_set_t *ds, const value_list_t *vl)
{
char *packet_ptr;
int packet_len;
int num_values;
part_header_t pkg_ph;
uint16_t pkg_num_values;
uint8_t *pkg_values_types;
value_t *pkg_values;
int offset;
int i;
num_values = vl->values_len;
packet_len = sizeof (part_header_t) + sizeof (uint16_t)
+ (num_values * sizeof (uint8_t))
+ (num_values * sizeof (value_t));
if (*ret_buffer_len < packet_len)
return (-1);
pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
if (pkg_values_types == NULL)
{
ERROR ("network plugin: write_part_values: malloc failed.");
return (-1);
}
pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
if (pkg_values == NULL)
{
free (pkg_values_types);
ERROR ("network plugin: write_part_values: malloc failed.");
return (-1);
}
pkg_ph.type = htons (TYPE_VALUES);
pkg_ph.length = htons (packet_len);
pkg_num_values = htons ((uint16_t) vl->values_len);
for (i = 0; i < num_values; i++)
{
pkg_values_types[i] = (uint8_t) ds->ds[i].type;
switch (ds->ds[i].type)
{
case DS_TYPE_COUNTER:
pkg_values[i].counter = htonll (vl->values[i].counter);
break;
case DS_TYPE_GAUGE:
pkg_values[i].gauge = htond (vl->values[i].gauge);
break;
case DS_TYPE_DERIVE:
pkg_values[i].derive = htonll (vl->values[i].derive);
break;
case DS_TYPE_ABSOLUTE:
pkg_values[i].absolute = htonll (vl->values[i].absolute);
break;
default:
free (pkg_values_types);
free (pkg_values);
ERROR ("network plugin: write_part_values: "
"Unknown data source type: %i",
ds->ds[i].type);
return (-1);
} /* switch (ds->ds[i].type) */
} /* for (num_values) */
/*
* Use `memcpy' to write everything to the buffer, because the pointer
* may be unaligned and some architectures, such as SPARC, can't handle
* that.
*/
packet_ptr = *ret_buffer;
offset = 0;
memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
offset += sizeof (pkg_ph);
memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
offset += sizeof (pkg_num_values);
memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
offset += num_values * sizeof (uint8_t);
memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
offset += num_values * sizeof (value_t);
assert (offset == packet_len);
*ret_buffer = packet_ptr + packet_len;
*ret_buffer_len -= packet_len;
free (pkg_values_types);
free (pkg_values);
return (0);
} /* int write_part_values */
static int write_part_number (char **ret_buffer, int *ret_buffer_len,
int type, uint64_t value)
{
char *packet_ptr;
int packet_len;
part_header_t pkg_head;
uint64_t pkg_value;
int offset;
packet_len = sizeof (pkg_head) + sizeof (pkg_value);
if (*ret_buffer_len < packet_len)
return (-1);
pkg_head.type = htons (type);
pkg_head.length = htons (packet_len);
pkg_value = htonll (value);
packet_ptr = *ret_buffer;
offset = 0;
memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
offset += sizeof (pkg_head);
memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
offset += sizeof (pkg_value);
assert (offset == packet_len);
*ret_buffer = packet_ptr + packet_len;
*ret_buffer_len -= packet_len;
return (0);
} /* int write_part_number */
static int write_part_string (char **ret_buffer, int *ret_buffer_len,
int type, const char *str, int str_len)
{
char *buffer;
int buffer_len;
uint16_t pkg_type;
uint16_t pkg_length;
int offset;
buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
if (*ret_buffer_len < buffer_len)
return (-1);
pkg_type = htons (type);
pkg_length = htons (buffer_len);
buffer = *ret_buffer;
offset = 0;
memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
offset += sizeof (pkg_type);
memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
offset += sizeof (pkg_length);
memcpy (buffer + offset, str, str_len);
offset += str_len;
memset (buffer + offset, '\0', 1);
offset += 1;
assert (offset == buffer_len);
*ret_buffer = buffer + buffer_len;
*ret_buffer_len -= buffer_len;
return (0);
} /* int write_part_string */
static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
value_t **ret_values, int *ret_num_values)
{
char *buffer = *ret_buffer;
size_t buffer_len = *ret_buffer_len;
uint16_t tmp16;
size_t exp_size;
int i;
uint16_t pkg_length;
uint16_t pkg_type;
uint16_t pkg_numval;
uint8_t *pkg_types;
value_t *pkg_values;
if (buffer_len < 15)
{
NOTICE ("network plugin: packet is too short: "
"buffer_len = %zu", buffer_len);
return (-1);
}
memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
buffer += sizeof (tmp16);
pkg_type = ntohs (tmp16);
memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
buffer += sizeof (tmp16);
pkg_length = ntohs (tmp16);
memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
buffer += sizeof (tmp16);
pkg_numval = ntohs (tmp16);
assert (pkg_type == TYPE_VALUES);
exp_size = 3 * sizeof (uint16_t)
+ pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
if (buffer_len < exp_size)
{
WARNING ("network plugin: parse_part_values: "
"Packet too short: "
"Chunk of size %zu expected, "
"but buffer has only %zu bytes left.",
exp_size, buffer_len);
return (-1);
}
if (pkg_length != exp_size)
{
WARNING ("network plugin: parse_part_values: "
"Length and number of values "
"in the packet don't match.");
return (-1);
}
pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
if ((pkg_types == NULL) || (pkg_values == NULL))
{
sfree (pkg_types);
sfree (pkg_values);
ERROR ("network plugin: parse_part_values: malloc failed.");
return (-1);
}
memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
buffer += pkg_numval * sizeof (uint8_t);
memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
buffer += pkg_numval * sizeof (value_t);
for (i = 0; i < pkg_numval; i++)
{
switch (pkg_types[i])
{
case DS_TYPE_COUNTER:
pkg_values[i].counter = (counter_t) ntohll (pkg_values[i].counter);
break;
case DS_TYPE_GAUGE:
pkg_values[i].gauge = (gauge_t) ntohd (pkg_values[i].gauge);
break;
case DS_TYPE_DERIVE:
pkg_values[i].derive = (derive_t) ntohll (pkg_values[i].derive);
break;
case DS_TYPE_ABSOLUTE:
pkg_values[i].absolute = (absolute_t) ntohll (pkg_values[i].absolute);
break;
default:
NOTICE ("network plugin: parse_part_values: "
"Don't know how to handle data source type %"PRIu8,
pkg_types[i]);
sfree (pkg_types);
sfree (pkg_values);
return (-1);
} /* switch (pkg_types[i]) */
}
*ret_buffer = buffer;
*ret_buffer_len = buffer_len - pkg_length;
*ret_num_values = pkg_numval;
*ret_values = pkg_values;
sfree (pkg_types);
return (0);
} /* int parse_part_values */
static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
uint64_t *value)
{
char *buffer = *ret_buffer;
size_t buffer_len = *ret_buffer_len;
uint16_t tmp16;
uint64_t tmp64;
size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
uint16_t pkg_length;
if (buffer_len < exp_size)
{
WARNING ("network plugin: parse_part_number: "
"Packet too short: "
"Chunk of size %zu expected, "
"but buffer has only %zu bytes left.",
exp_size, buffer_len);
return (-1);
}
memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
buffer += sizeof (tmp16);
/* pkg_type = ntohs (tmp16); */
memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
buffer += sizeof (tmp16);
pkg_length = ntohs (tmp16);
memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
buffer += sizeof (tmp64);
*value = ntohll (tmp64);
*ret_buffer = buffer;
*ret_buffer_len = buffer_len - pkg_length;
return (0);
} /* int parse_part_number */
static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
char *output, int output_len)
{
char *buffer = *ret_buffer;
size_t buffer_len = *ret_buffer_len;
uint16_t tmp16;
size_t header_size = 2 * sizeof (uint16_t);
uint16_t pkg_length;
if (buffer_len < header_size)
{
WARNING ("network plugin: parse_part_string: "
"Packet too short: "
"Chunk of at least size %zu expected, "
"but buffer has only %zu bytes left.",
header_size, buffer_len);
return (-1);
}
memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
buffer += sizeof (tmp16);
/* pkg_type = ntohs (tmp16); */
memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
buffer += sizeof (tmp16);
pkg_length = ntohs (tmp16);
/* Check that packet fits in the input buffer */
if (pkg_length > buffer_len)
{
WARNING ("network plugin: parse_part_string: "
"Packet too big: "
"Chunk of size %"PRIu16" received, "
"but buffer has only %zu bytes left.",
pkg_length, buffer_len);
return (-1);
}
/* Check that pkg_length is in the valid range */
if (pkg_length <= header_size)
{
WARNING ("network plugin: parse_part_string: "
"Packet too short: "
"Header claims this packet is only %hu "
"bytes long.", pkg_length);
return (-1);
}
/* Check that the package data fits into the output buffer.
* The previous if-statement ensures that:
* `pkg_length > header_size' */
if ((output_len < 0)
|| ((size_t) output_len < ((size_t) pkg_length - header_size)))
{
WARNING ("network plugin: parse_part_string: "
"Output buffer too small.");
return (-1);
}
/* All sanity checks successfull, let's copy the data over */
output_len = pkg_length - header_size;
memcpy ((void *) output, (void *) buffer, output_len);
buffer += output_len;
/* For some very weird reason '\0' doesn't do the trick on SPARC in
* this statement. */
if (output[output_len - 1] != 0)
{
WARNING ("network plugin: parse_part_string: "
"Received string does not end "
"with a NULL-byte.");
return (-1);
}
*ret_buffer = buffer;
*ret_buffer_len = buffer_len - pkg_length;
return (0);
} /* int parse_part_string */
/* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
* parse_packet and vice versa. */
#define PP_SIGNED 0x01
#define PP_ENCRYPTED 0x02
static int parse_packet (sockent_t *se,
void *buffer, size_t buffer_size, int flags,
const char *username);
#define BUFFER_READ(p,s) do { \
memcpy ((p), buffer + buffer_offset, (s)); \
buffer_offset += (s); \
} while (0)
#if HAVE_LIBGCRYPT
static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
void **ret_buffer, size_t *ret_buffer_len, int flags)
{
static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC;
char *buffer;
size_t buffer_len;
size_t buffer_offset;
size_t username_len;
char *secret;
part_signature_sha256_t pss;
uint16_t pss_head_length;
char hash[sizeof (pss.hash)];
gcry_md_hd_t hd;
gcry_error_t err;
unsigned char *hash_ptr;
buffer = *ret_buffer;
buffer_len = *ret_buffer_len;
buffer_offset = 0;
if (se->data.server.userdb == NULL)
{
c_complain (LOG_NOTICE, &complain_no_users,
"network plugin: Received signed network packet but can't verify it "
"because no user DB has been configured. Will accept it.");
return (0);
}
/* Check if the buffer has enough data for this structure. */
if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
return (-ENOMEM);
/* Read type and length header */
BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
pss_head_length = ntohs (pss.head.length);
/* Check if the `pss_head_length' is within bounds. */
if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
|| (pss_head_length > buffer_len))
{
ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
return (-1);
}
/* Copy the hash. */
BUFFER_READ (pss.hash, sizeof (pss.hash));
/* Calculate username length (without null byte) and allocate memory */
username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
pss.username = malloc (username_len + 1);
if (pss.username == NULL)
return (-ENOMEM);
/* Read the username */
BUFFER_READ (pss.username, username_len);
pss.username[username_len] = 0;
assert (buffer_offset == pss_head_length);
/* Query the password */
secret = fbh_get (se->data.server.userdb, pss.username);
if (secret == NULL)
{
ERROR ("network plugin: Unknown user: %s", pss.username);
sfree (pss.username);
return (-ENOENT);
}
/* Create a hash device and check the HMAC */
hd = NULL;
err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
if (err != 0)
{
ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
gcry_strerror (err));
sfree (secret);
sfree (pss.username);
return (-1);
}
err = gcry_md_setkey (hd, secret, strlen (secret));
if (err != 0)
{
ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
gcry_md_close (hd);
sfree (secret);
sfree (pss.username);
return (-1);
}
gcry_md_write (hd,
buffer + PART_SIGNATURE_SHA256_SIZE,
buffer_len - PART_SIGNATURE_SHA256_SIZE);
hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
if (hash_ptr == NULL)
{
ERROR ("network plugin: gcry_md_read failed.");
gcry_md_close (hd);
sfree (secret);
sfree (pss.username);
return (-1);
}
memcpy (hash, hash_ptr, sizeof (hash));
/* Clean up */
gcry_md_close (hd);
hd = NULL;
if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
{
WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
"Hash mismatch.");
}
else
{
parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
flags | PP_SIGNED, pss.username);
}
sfree (secret);
sfree (pss.username);
*ret_buffer = buffer + buffer_len;
*ret_buffer_len = 0;
return (0);
} /* }}} int parse_part_sign_sha256 */
/* #endif HAVE_LIBGCRYPT */
#else /* if !HAVE_LIBGCRYPT */
static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
void **ret_buffer, size_t *ret_buffer_size, int flags)
{
static int warning_has_been_printed = 0;
char *buffer;
size_t buffer_size;
size_t buffer_offset;
uint16_t part_len;
part_signature_sha256_t pss;
buffer = *ret_buffer;
buffer_size = *ret_buffer_size;
buffer_offset = 0;
if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
return (-ENOMEM);
BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
part_len = ntohs (pss.head.length);
if ((part_len <= PART_SIGNATURE_SHA256_SIZE)
|| (part_len > buffer_size))
return (-EINVAL);
if (warning_has_been_printed == 0)
{
WARNING ("network plugin: Received signed packet, but the network "
"plugin was not linked with libgcrypt, so I cannot "
"verify the signature. The packet will be accepted.");
warning_has_been_printed = 1;
}
parse_packet (se, buffer + part_len, buffer_size - part_len, flags,
/* username = */ NULL);
*ret_buffer = buffer + buffer_size;
*ret_buffer_size = 0;
return (0);
} /* }}} int parse_part_sign_sha256 */
#endif /* !HAVE_LIBGCRYPT */
#if HAVE_LIBGCRYPT
static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
void **ret_buffer, size_t *ret_buffer_len,
int flags)
{
char *buffer = *ret_buffer;
size_t buffer_len = *ret_buffer_len;
size_t payload_len;
size_t part_size;
size_t buffer_offset;
uint16_t username_len;
part_encryption_aes256_t pea;
unsigned char hash[sizeof (pea.hash)];
gcry_cipher_hd_t cypher;
gcry_error_t err;
/* Make sure at least the header if available. */
if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
{
NOTICE ("network plugin: parse_part_encr_aes256: "
"Discarding short packet.");
return (-1);
}
buffer_offset = 0;
/* Copy the unencrypted information into `pea'. */
BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
/* Check the `part size'. */
part_size = ntohs (pea.head.length);
if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
|| (part_size > buffer_len))
{
NOTICE ("network plugin: parse_part_encr_aes256: "
"Discarding part with invalid size.");
return (-1);
}
/* Read the username */
BUFFER_READ (&username_len, sizeof (username_len));
username_len = ntohs (username_len);
if ((username_len <= 0)
|| (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
{
NOTICE ("network plugin: parse_part_encr_aes256: "
"Discarding part with invalid username length.");
return (-1);
}
assert (username_len > 0);
pea.username = malloc (username_len + 1);
if (pea.username == NULL)
return (-ENOMEM);
BUFFER_READ (pea.username, username_len);
pea.username[username_len] = 0;
/* Last but not least, the initialization vector */
BUFFER_READ (pea.iv, sizeof (pea.iv));
/* Make sure we are at the right position */
assert (buffer_offset == (username_len +
PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
pea.username);
if (cypher == NULL)
{
sfree (pea.username);
return (-1);
}
payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
assert (payload_len > 0);
/* Decrypt the packet in-place */
err = gcry_cipher_decrypt (cypher,
buffer + buffer_offset,
part_size - buffer_offset,
/* in = */ NULL, /* in len = */ 0);
if (err != 0)
{
sfree (pea.username);
ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
gcry_strerror (err));
return (-1);
}
/* Read the hash */
BUFFER_READ (pea.hash, sizeof (pea.hash));
/* Make sure we're at the right position - again */
assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
assert (buffer_offset == (part_size - payload_len));
/* Check hash sum */
memset (hash, 0, sizeof (hash));
gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
buffer + buffer_offset, payload_len);
if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
{
sfree (pea.username);
ERROR ("network plugin: Decryption failed: Checksum mismatch.");
return (-1);
}
parse_packet (se, buffer + buffer_offset, payload_len,
flags | PP_ENCRYPTED, pea.username);
/* XXX: Free pea.username?!? */
/* Update return values */
*ret_buffer = buffer + part_size;
*ret_buffer_len = buffer_len - part_size;
sfree (pea.username);
return (0);
} /* }}} int parse_part_encr_aes256 */
/* #endif HAVE_LIBGCRYPT */
#else /* if !HAVE_LIBGCRYPT */
static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
void **ret_buffer, size_t *ret_buffer_size, int flags)
{
static int warning_has_been_printed = 0;
char *buffer;
size_t buffer_size;
size_t buffer_offset;
part_header_t ph;
size_t ph_length;
buffer = *ret_buffer;
buffer_size = *ret_buffer_size;
buffer_offset = 0;
/* parse_packet assures this minimum size. */
assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
BUFFER_READ (&ph.type, sizeof (ph.type));
BUFFER_READ (&ph.length, sizeof (ph.length));
ph_length = ntohs (ph.length);
if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
|| (ph_length > buffer_size))
{
ERROR ("network plugin: AES-256 encrypted part "
"with invalid length received.");
return (-1);
}
if (warning_has_been_printed == 0)
{
WARNING ("network plugin: Received encrypted packet, but the network "
"plugin was not linked with libgcrypt, so I cannot "
"decrypt it. The part will be discarded.");
warning_has_been_printed = 1;
}
*ret_buffer += ph_length;
*ret_buffer_size -= ph_length;
return (0);
} /* }}} int parse_part_encr_aes256 */
#endif /* !HAVE_LIBGCRYPT */
#undef BUFFER_READ
static int parse_packet (sockent_t *se, /* {{{ */
void *buffer, size_t buffer_size, int flags,
const char *username)
{
int status;
value_list_t vl = VALUE_LIST_INIT;
notification_t n;
#if HAVE_LIBGCRYPT
int packet_was_signed = (flags & PP_SIGNED);
int packet_was_encrypted = (flags & PP_ENCRYPTED);
int printed_ignore_warning = 0;
#endif /* HAVE_LIBGCRYPT */
memset (&vl, '\0', sizeof (vl));
memset (&n, '\0', sizeof (n));
status = 0;
while ((status == 0) && (0 < buffer_size)
&& ((unsigned int) buffer_size > sizeof (part_header_t)))
{
uint16_t pkg_length;
uint16_t pkg_type;
memcpy ((void *) &pkg_type,
(void *) buffer,
sizeof (pkg_type));
memcpy ((void *) &pkg_length,
(void *) (buffer + sizeof (pkg_type)),
sizeof (pkg_length));
pkg_length = ntohs (pkg_length);
pkg_type = ntohs (pkg_type);
if (pkg_length > buffer_size)
break;
/* Ensure that this loop terminates eventually */
if (pkg_length < (2 * sizeof (uint16_t)))
break;
if (pkg_type == TYPE_ENCR_AES256)
{
status = parse_part_encr_aes256 (se,
&buffer, &buffer_size, flags);
if (status != 0)
{
ERROR ("network plugin: Decrypting AES256 "
"part failed "
"with status %i.", status);
break;
}
}
#if HAVE_LIBGCRYPT
else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
&& (packet_was_encrypted == 0))
{
if (printed_ignore_warning == 0)
{
INFO ("network plugin: Unencrypted packet or "
"part has been ignored.");
printed_ignore_warning = 1;
}
buffer = ((char *) buffer) + pkg_length;
buffer_size -= (size_t) pkg_length;
continue;
}
#endif /* HAVE_LIBGCRYPT */
else if (pkg_type == TYPE_SIGN_SHA256)
{
status = parse_part_sign_sha256 (se,
&buffer, &buffer_size, flags);
if (status != 0)
{
ERROR ("network plugin: Verifying HMAC-SHA-256 "
"signature failed "
"with status %i.", status);
break;
}
}
#if HAVE_LIBGCRYPT
else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
&& (packet_was_encrypted == 0)
&& (packet_was_signed == 0))
{
if (printed_ignore_warning == 0)
{
INFO ("network plugin: Unsigned packet or "
"part has been ignored.");
printed_ignore_warning = 1;
}
buffer = ((char *) buffer) + pkg_length;
buffer_size -= (size_t) pkg_length;
continue;
}
#endif /* HAVE_LIBGCRYPT */
else if (pkg_type == TYPE_VALUES)
{
status = parse_part_values (&buffer, &buffer_size,
&vl.values, &vl.values_len);
if (status != 0)
break;
network_dispatch_values (&vl, username);
sfree (vl.values);
}
else if (pkg_type == TYPE_TIME)
{
uint64_t tmp = 0;
status = parse_part_number (&buffer, &buffer_size,
&tmp);
if (status == 0)
{
vl.time = TIME_T_TO_CDTIME_T (tmp);
n.time = TIME_T_TO_CDTIME_T (tmp);
}
}
else if (pkg_type == TYPE_TIME_HR)
{
uint64_t tmp = 0;
status = parse_part_number (&buffer, &buffer_size,
&tmp);
if (status == 0)
{
vl.time = (cdtime_t) tmp;
n.time = (cdtime_t) tmp;
}
}
else if (pkg_type == TYPE_INTERVAL)
{
uint64_t tmp = 0;
status = parse_part_number (&buffer, &buffer_size,
&tmp);
if (status == 0)
vl.interval = TIME_T_TO_CDTIME_T (tmp);
}
else if (pkg_type == TYPE_INTERVAL_HR)
{
uint64_t tmp = 0;
status = parse_part_number (&buffer, &buffer_size,
&tmp);
if (status == 0)
vl.interval = (cdtime_t) tmp;
}
else if (pkg_type == TYPE_HOST)
{
status = parse_part_string (&buffer, &buffer_size,
vl.host, sizeof (vl.host));
if (status == 0)
sstrncpy (n.host, vl.host, sizeof (n.host));
}
else if (pkg_type == TYPE_PLUGIN)
{
status = parse_part_string (&buffer, &buffer_size,
vl.plugin, sizeof (vl.plugin));
if (status == 0)
sstrncpy (n.plugin, vl.plugin,
sizeof (n.plugin));
}
else if (pkg_type == TYPE_PLUGIN_INSTANCE)
{
status = parse_part_string (&buffer, &buffer_size,
vl.plugin_instance,
sizeof (vl.plugin_instance));
if (status == 0)
sstrncpy (n.plugin_instance,
vl.plugin_instance,
sizeof (n.plugin_instance));
}
else if (pkg_type == TYPE_TYPE)
{
status = parse_part_string (&buffer, &buffer_size,
vl.type, sizeof (vl.type));
if (status == 0)
sstrncpy (n.type, vl.type, sizeof (n.type));
}
else if (pkg_type == TYPE_TYPE_INSTANCE)
{
status = parse_part_string (&buffer, &buffer_size,
vl.type_instance,
sizeof (vl.type_instance));
if (status == 0)
sstrncpy (n.type_instance, vl.type_instance,
sizeof (n.type_instance));
}
else if (pkg_type == TYPE_MESSAGE)
{
status = parse_part_string (&buffer, &buffer_size,
n.message, sizeof (n.message));
if (status != 0)
{
/* do nothing */
}
else if ((n.severity != NOTIF_FAILURE)
&& (n.severity != NOTIF_WARNING)
&& (n.severity != NOTIF_OKAY))
{
INFO ("network plugin: "
"Ignoring notification with "
"unknown severity %i.",
n.severity);
}
else if (n.time <= 0)
{
INFO ("network plugin: "
"Ignoring notification with "
"time == 0.");
}
else if (strlen (n.message) <= 0)
{
INFO ("network plugin: "
"Ignoring notification with "
"an empty message.");
}
else
{
network_dispatch_notification (&n);
}
}
else if (pkg_type == TYPE_SEVERITY)
{
uint64_t tmp = 0;
status = parse_part_number (&buffer, &buffer_size,
&tmp);
if (status == 0)
n.severity = (int) tmp;
}
else
{
DEBUG ("network plugin: parse_packet: Unknown part"
" type: 0x%04hx", pkg_type);
buffer = ((char *) buffer) + pkg_length;
buffer_size -= (size_t) pkg_length;
}
} /* while (buffer_size > sizeof (part_header_t)) */
if (status == 0 && buffer_size > 0)
WARNING ("network plugin: parse_packet: Received truncated "
"packet, try increasing `MaxPacketSize'");
return (status);
} /* }}} int parse_packet */
static void free_sockent_client (struct sockent_client *sec) /* {{{ */
{
if (sec->fd >= 0)
{
close (sec->fd);
sec->fd = -1;
}
sfree (sec->addr);
#if HAVE_LIBGCRYPT
sfree (sec->username);
sfree (sec->password);
if (sec->cypher != NULL)
gcry_cipher_close (sec->cypher);
#endif
} /* }}} void free_sockent_client */
static void free_sockent_server (struct sockent_server *ses) /* {{{ */
{
size_t i;
for (i = 0; i < ses->fd_num; i++)
{
if (ses->fd[i] >= 0)
{
close (ses->fd[i]);
ses->fd[i] = -1;
}
}
sfree (ses->fd);
#if HAVE_LIBGCRYPT
sfree (ses->auth_file);
fbh_destroy (ses->userdb);
if (ses->cypher != NULL)
gcry_cipher_close (ses->cypher);
#endif
} /* }}} void free_sockent_server */
static void sockent_destroy (sockent_t *se) /* {{{ */
{
sockent_t *next;
DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
while (se != NULL)
{
next = se->next;
sfree (se->node);
sfree (se->service);
if (se->type == SOCKENT_TYPE_CLIENT)
free_sockent_client (&se->data.client);
else
free_sockent_server (&se->data.server);
sfree (se);
se = next;
}
} /* }}} void sockent_destroy */
/*
* int network_set_ttl
*
* Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
* `IPV6_UNICAST_HOPS', depending on which option is applicable.
*
* The `struct addrinfo' is used to destinguish between unicast and multicast
* sockets.
*/
static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
{
DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
network_config_ttl);
assert (se->type == SOCKENT_TYPE_CLIENT);
if ((network_config_ttl < 1) || (network_config_ttl > 255))
return (-1);
if (ai->ai_family == AF_INET)
{
struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
int optname;
if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
optname = IP_MULTICAST_TTL;
else
optname = IP_TTL;
if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
&network_config_ttl,
sizeof (network_config_ttl)) != 0)
{
char errbuf[1024];
ERROR ("network plugin: setsockopt (ipv4-ttl): %s",
sstrerror (errno, errbuf, sizeof (errbuf)));
return (-1);
}
}
else if (ai->ai_family == AF_INET6)
{
/* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
int optname;
if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
optname = IPV6_MULTICAST_HOPS;
else
optname = IPV6_UNICAST_HOPS;
if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
&network_config_ttl,
sizeof (network_config_ttl)) != 0)
{
char errbuf[1024];
ERROR ("network plugin: setsockopt(ipv6-ttl): %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
return (-1);
}
}
return (0);
} /* int network_set_ttl */
static int network_set_interface (const sockent_t *se, const struct addrinfo *ai) /* {{{ */
{
DEBUG ("network plugin: network_set_interface: interface index = %i;",
se->interface);
assert (se->type == SOCKENT_TYPE_CLIENT);
if (ai->ai_family == AF_INET)
{
struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
{
#if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
/* If possible, use the "ip_mreqn" structure which has
* an "interface index" member. Using the interface
* index is preferred here, because of its similarity
* to the way IPv6 handles this. Unfortunately, it
* appears not to be portable. */
struct ip_mreqn mreq;
memset (&mreq, 0, sizeof (mreq));
mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
mreq.imr_address.s_addr = ntohl (INADDR_ANY);
mreq.imr_ifindex = se->interface;
#else
struct ip_mreq mreq;
memset (&mreq, 0, sizeof (mreq));
mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
#endif
if (setsockopt (se->data.client.fd, IPPROTO_IP, IP_MULTICAST_IF,
&mreq, sizeof (mreq)) != 0)
{
char errbuf[1024];
ERROR ("network plugin: setsockopt (ipv4-multicast-if): %s",
sstrerror (errno, errbuf, sizeof (errbuf)));
return (-1);
}
return (0);
}
}
else if (ai->ai_family == AF_INET6)
{
struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
{
if (setsockopt (se->data.client.fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
&se->interface,
sizeof (se->interface)) != 0)
{
char errbuf[1024];
ERROR ("network plugin: setsockopt (ipv6-multicast-if): %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
return (-1);
}
return (0);
}
}
/* else: Not a multicast interface. */
if (se->interface != 0)
{
#if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
char interface_name[IFNAMSIZ];
if (if_indextoname (se->interface, interface_name) == NULL)
return (-1);
DEBUG ("network plugin: Binding socket to interface %s", interface_name);
if (setsockopt (se->data.client.fd, SOL_SOCKET, SO_BINDTODEVICE,
interface_name,
sizeof(interface_name)) == -1 )
{
char errbuf[1024];
ERROR ("network plugin: setsockopt (bind-if): %s",
sstrerror (errno, errbuf, sizeof (errbuf)));
return (-1);
}
/* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
#else
WARNING ("network plugin: Cannot set the interface on a unicast "
"socket because "
# if !defined(SO_BINDTODEVICE)
"the \"SO_BINDTODEVICE\" socket option "
# else
"the \"if_indextoname\" function "
# endif
"is not available on your system.");
#endif
}
return (0);
} /* }}} network_set_interface */
static int network_bind_socket (int fd, const struct addrinfo *ai, const int interface_idx)
{
#if KERNEL_SOLARIS
char loop = 0;
#else
int loop = 0;
#endif
int yes = 1;
/* allow multiple sockets to use the same PORT number */
if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
&yes, sizeof(yes)) == -1) {
char errbuf[1024];
ERROR ("network plugin: setsockopt (reuseaddr): %s",
sstrerror (errno, errbuf, sizeof (errbuf)));
return (-1);
}
DEBUG ("fd = %i; calling `bind'", fd);
if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
{
char errbuf[1024];
ERROR ("bind: %s",
sstrerror (errno, errbuf, sizeof (errbuf)));
return (-1);
}
if (ai->ai_family == AF_INET)
{
struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
{
#if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
struct ip_mreqn mreq;
#else
struct ip_mreq mreq;
#endif
DEBUG ("fd = %i; IPv4 multicast address found", fd);
mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
#if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
/* Set the interface using the interface index if
* possible (available). Unfortunately, the struct
* ip_mreqn is not portable. */
mreq.imr_address.s_addr = ntohl (INADDR_ANY);
mreq.imr_ifindex = interface_idx;
#else
mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
#endif
if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
&loop, sizeof (loop)) == -1)
{
char errbuf[1024];
ERROR ("network plugin: setsockopt (multicast-loop): %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
return (-1);
}
if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
&mreq, sizeof (mreq)) == -1)
{
char errbuf[1024];
ERROR ("network plugin: setsockopt (add-membership): %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
return (-1);
}
return (0);
}
}
else if (ai->ai_family == AF_INET6)
{
/* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
{
struct ipv6_mreq mreq;
DEBUG ("fd = %i; IPv6 multicast address found", fd);
memcpy (&mreq.ipv6mr_multiaddr,
&addr->sin6_addr,
sizeof (addr->sin6_addr));
/* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
* ipv6mr_interface may be set to zeroes to
* choose the default multicast interface or to
* the index of a particular multicast-capable
* interface if the host is multihomed.
* Membership is associ-associated with a
* single interface; programs running on
* multihomed hosts may need to join the same
* group on more than one interface.*/
mreq.ipv6mr_interface = interface_idx;
if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
&loop, sizeof (loop)) == -1)
{
char errbuf[1024];
ERROR ("network plugin: setsockopt (ipv6-multicast-loop): %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
return (-1);
}
if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
&mreq, sizeof (mreq)) == -1)
{
char errbuf[1024];
ERROR ("network plugin: setsockopt (ipv6-add-membership): %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
return (-1);
}
return (0);
}
}
#if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
/* if a specific interface was set, bind the socket to it. But to avoid
* possible problems with multicast routing, only do that for non-multicast
* addresses */
if (interface_idx != 0)
{
char interface_name[IFNAMSIZ];
if (if_indextoname (interface_idx, interface_name) == NULL)
return (-1);
DEBUG ("fd = %i; Binding socket to interface %s", fd, interface_name);
if (setsockopt (fd, SOL_SOCKET, SO_BINDTODEVICE,
interface_name,
sizeof(interface_name)) == -1 )
{
char errbuf[1024];
ERROR ("network plugin: setsockopt (bind-if): %s",
sstrerror (errno, errbuf, sizeof (errbuf)));
return (-1);
}
}
#endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
return (0);
} /* int network_bind_socket */
/* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
* or `SOCKENT_TYPE_SERVER' */
static sockent_t *sockent_create (int type) /* {{{ */
{
sockent_t *se;
if ((type != SOCKENT_TYPE_CLIENT) && (type != SOCKENT_TYPE_SERVER))
return (NULL);
se = malloc (sizeof (*se));
if (se == NULL)
return (NULL);
memset (se, 0, sizeof (*se));
se->type = type;
se->node = NULL;
se->service = NULL;
se->interface = 0;
se->next = NULL;
if (type == SOCKENT_TYPE_SERVER)
{
se->data.server.fd = NULL;
se->data.server.fd_num = 0;
#if HAVE_LIBGCRYPT
se->data.server.security_level = SECURITY_LEVEL_NONE;
se->data.server.auth_file = NULL;
se->data.server.userdb = NULL;
se->data.server.cypher = NULL;
#endif
}
else
{
se->data.client.fd = -1;
se->data.client.addr = NULL;
#if HAVE_LIBGCRYPT
se->data.client.security_level = SECURITY_LEVEL_NONE;
se->data.client.username = NULL;
se->data.client.password = NULL;
se->data.client.cypher = NULL;
#endif
}
return (se);
} /* }}} sockent_t *sockent_create */
static int sockent_init_crypto (sockent_t *se) /* {{{ */
{
#if HAVE_LIBGCRYPT /* {{{ */
if (se->type == SOCKENT_TYPE_CLIENT)
{
if (se->data.client.security_level > SECURITY_LEVEL_NONE)
{
network_init_gcrypt ();
if ((se->data.client.username == NULL)
|| (se->data.client.password == NULL))
{
ERROR ("network plugin: Client socket with "
"security requested, but no "
"credentials are configured.");
return (-1);
}
gcry_md_hash_buffer (GCRY_MD_SHA256,
se->data.client.password_hash,
se->data.client.password,
strlen (se->data.client.password));
}
}
else /* (se->type == SOCKENT_TYPE_SERVER) */
{
if (se->data.server.security_level > SECURITY_LEVEL_NONE)
{
network_init_gcrypt ();
if (se->data.server.auth_file == NULL)
{
ERROR ("network plugin: Server socket with "
"security requested, but no "
"password file is configured.");
return (-1);
}
}
if (se->data.server.auth_file != NULL)
{
se->data.server.userdb = fbh_create (se->data.server.auth_file);
if (se->data.server.userdb == NULL)
{
ERROR ("network plugin: Reading password file "
"`%s' failed.",
se->data.server.auth_file);
if (se->data.server.security_level > SECURITY_LEVEL_NONE)
return (-1);
}
}
}
#endif /* }}} HAVE_LIBGCRYPT */
return (0);
} /* }}} int sockent_init_crypto */
static int sockent_client_connect (sockent_t *se) /* {{{ */
{
static c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
struct sockent_client *client;
struct addrinfo ai_hints;
struct addrinfo *ai_list = NULL, *ai_ptr;
int status;
if ((se == NULL) || (se->type != SOCKENT_TYPE_CLIENT))
return (EINVAL);
client = &se->data.client;
if (client->fd >= 0) /* already connected */
return (0);
memset (&ai_hints, 0, sizeof (ai_hints));
#ifdef AI_ADDRCONFIG
ai_hints.ai_flags |= AI_ADDRCONFIG;
#endif
ai_hints.ai_family = AF_UNSPEC;
ai_hints.ai_socktype = SOCK_DGRAM;
ai_hints.ai_protocol = IPPROTO_UDP;
status = getaddrinfo (se->node,
(se->service != NULL) ? se->service : NET_DEFAULT_PORT,
&ai_hints, &ai_list);
if (status != 0)
{
c_complain (LOG_ERR, &complaint,
"network plugin: getaddrinfo (%s, %s) failed: %s",
(se->node == NULL) ? "(null)" : se->node,
(se->service == NULL) ? "(null)" : se->service,
gai_strerror (status));
return (-1);
}
else
{
c_release (LOG_NOTICE, &complaint,
"network plugin: Successfully resolved \"%s\".",
se->node);
}
for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
{
client->fd = socket (ai_ptr->ai_family,
ai_ptr->ai_socktype,
ai_ptr->ai_protocol);
if (client->fd < 0)
{
char errbuf[1024];
ERROR ("network plugin: socket(2) failed: %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
continue;
}
client->addr = malloc (sizeof (*client->addr));
if (client->addr == NULL)
{
ERROR ("network plugin: malloc failed.");
close (client->fd);
client->fd = -1;
continue;
}
memset (client->addr, 0, sizeof (*client->addr));
assert (sizeof (*client->addr) >= ai_ptr->ai_addrlen);
memcpy (client->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
client->addrlen = ai_ptr->ai_addrlen;
network_set_ttl (se, ai_ptr);
network_set_interface (se, ai_ptr);
/* We don't open more than one write-socket per
* node/service pair.. */
break;
}
freeaddrinfo (ai_list);
if (client->fd < 0)
return (-1);
return (0);
} /* }}} int sockent_client_connect */
static int sockent_client_disconnect (sockent_t *se) /* {{{ */
{
struct sockent_client *client;
if ((se == NULL) || (se->type != SOCKENT_TYPE_CLIENT))
return (EINVAL);
client = &se->data.client;
if (client->fd >= 0) /* connected */
{
close (client->fd);
client->fd = -1;
}
sfree (client->addr);
client->addrlen = 0;
return (0);
} /* }}} int sockent_client_disconnect */
/* Open the file descriptors for a initialized sockent structure. */
static int sockent_server_listen (sockent_t *se) /* {{{ */
{
struct addrinfo ai_hints;
struct addrinfo *ai_list, *ai_ptr;
int status;
const char *node;
const char *service;
if (se == NULL)
return (-1);
assert (se->data.server.fd == NULL);
assert (se->data.server.fd_num == 0);
node = se->node;
service = se->service;
if (service == NULL)
service = NET_DEFAULT_PORT;
DEBUG ("network plugin: sockent_server_listen: node = %s; service = %s;",
node, service);
memset (&ai_hints, 0, sizeof (ai_hints));
ai_hints.ai_flags = 0;
#ifdef AI_PASSIVE
ai_hints.ai_flags |= AI_PASSIVE;
#endif
#ifdef AI_ADDRCONFIG
ai_hints.ai_flags |= AI_ADDRCONFIG;
#endif
ai_hints.ai_family = AF_UNSPEC;
ai_hints.ai_socktype = SOCK_DGRAM;
ai_hints.ai_protocol = IPPROTO_UDP;
status = getaddrinfo (node, service, &ai_hints, &ai_list);
if (status != 0)
{
ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
(se->node == NULL) ? "(null)" : se->node,
(se->service == NULL) ? "(null)" : se->service,
gai_strerror (status));
return (-1);
}
for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
{
int *tmp;
tmp = realloc (se->data.server.fd,
sizeof (*tmp) * (se->data.server.fd_num + 1));
if (tmp == NULL)
{
ERROR ("network plugin: realloc failed.");
continue;
}
se->data.server.fd = tmp;
tmp = se->data.server.fd + se->data.server.fd_num;
*tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
ai_ptr->ai_protocol);
if (*tmp < 0)
{
char errbuf[1024];
ERROR ("network plugin: socket(2) failed: %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
continue;
}
status = network_bind_socket (*tmp, ai_ptr, se->interface);
if (status != 0)
{
close (*tmp);
*tmp = -1;
continue;
}
se->data.server.fd_num++;
continue;
} /* for (ai_list) */
freeaddrinfo (ai_list);
if (se->data.server.fd_num <= 0)
return (-1);
return (0);
} /* }}} int sockent_server_listen */
/* Add a sockent to the global list of sockets */
static int sockent_add (sockent_t *se) /* {{{ */
{
sockent_t *last_ptr;
if (se == NULL)
return (-1);
if (se->type == SOCKENT_TYPE_SERVER)
{
struct pollfd *tmp;
size_t i;
tmp = realloc (listen_sockets_pollfd,
sizeof (*tmp) * (listen_sockets_num
+ se->data.server.fd_num));
if (tmp == NULL)
{
ERROR ("network plugin: realloc failed.");
return (-1);
}
listen_sockets_pollfd = tmp;
tmp = listen_sockets_pollfd + listen_sockets_num;
for (i = 0; i < se->data.server.fd_num; i++)
{
memset (tmp + i, 0, sizeof (*tmp));
tmp[i].fd = se->data.server.fd[i];
tmp[i].events = POLLIN | POLLPRI;
tmp[i].revents = 0;
}
listen_sockets_num += se->data.server.fd_num;
if (listen_sockets == NULL)
{
listen_sockets = se;
return (0);
}
last_ptr = listen_sockets;
}
else /* if (se->type == SOCKENT_TYPE_CLIENT) */
{
if (sending_sockets == NULL)
{
sending_sockets = se;
return (0);
}
last_ptr = sending_sockets;
}
while (last_ptr->next != NULL)
last_ptr = last_ptr->next;
last_ptr->next = se;
return (0);
} /* }}} int sockent_add */
static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
{
while (42)
{
receive_list_entry_t *ent;
sockent_t *se;
/* Lock and wait for more data to come in */
pthread_mutex_lock (&receive_list_lock);
while ((listen_loop == 0)
&& (receive_list_head == NULL))
pthread_cond_wait (&receive_list_cond, &receive_list_lock);
/* Remove the head entry and unlock */
ent = receive_list_head;
if (ent != NULL)
receive_list_head = ent->next;
receive_list_length--;
pthread_mutex_unlock (&receive_list_lock);
/* Check whether we are supposed to exit. We do NOT check `listen_loop'
* because we dispatch all missing packets before shutting down. */
if (ent == NULL)
break;
/* Look for the correct `sockent_t' */
se = listen_sockets;
while (se != NULL)
{
size_t i;
for (i = 0; i < se->data.server.fd_num; i++)
if (se->data.server.fd[i] == ent->fd)
break;
if (i < se->data.server.fd_num)
break;
se = se->next;
}
if (se == NULL)
{
ERROR ("network plugin: Got packet from FD %i, but can't "
"find an appropriate socket entry.",
ent->fd);
sfree (ent->data);
sfree (ent);
continue;
}
parse_packet (se, ent->data, ent->data_len, /* flags = */ 0,
/* username = */ NULL);
sfree (ent->data);
sfree (ent);
} /* while (42) */
return (NULL);
} /* }}} void *dispatch_thread */
static int network_receive (void) /* {{{ */
{
char buffer[network_config_packet_size];
int buffer_len;
int i;
int status = 0;
receive_list_entry_t *private_list_head;
receive_list_entry_t *private_list_tail;
uint64_t private_list_length;
assert (listen_sockets_num > 0);
private_list_head = NULL;
private_list_tail = NULL;
private_list_length = 0;
while (listen_loop == 0)
{
status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
if (status <= 0)
{
char errbuf[1024];
if (errno == EINTR)
continue;
ERROR ("network plugin: poll(2) failed: %s",
sstrerror (errno, errbuf, sizeof (errbuf)));
break;
}
for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
{
receive_list_entry_t *ent;
if ((listen_sockets_pollfd[i].revents
& (POLLIN | POLLPRI)) == 0)
continue;
status--;
buffer_len = recv (listen_sockets_pollfd[i].fd,
buffer, sizeof (buffer),
0 /* no flags */);
if (buffer_len < 0)
{
char errbuf[1024];
status = (errno != 0) ? errno : -1;
ERROR ("network plugin: recv(2) failed: %s",
sstrerror (errno, errbuf, sizeof (errbuf)));
break;
}
stats_octets_rx += ((uint64_t) buffer_len);
stats_packets_rx++;
/* TODO: Possible performance enhancement: Do not free
* these entries in the dispatch thread but put them in
* another list, so we don't have to allocate more and
* more of these structures. */
ent = malloc (sizeof (receive_list_entry_t));
if (ent == NULL)
{
ERROR ("network plugin: malloc failed.");
status = ENOMEM;
break;
}
memset (ent, 0, sizeof (receive_list_entry_t));
ent->data = malloc (network_config_packet_size);
if (ent->data == NULL)
{
sfree (ent);
ERROR ("network plugin: malloc failed.");
status = ENOMEM;
break;
}
ent->fd = listen_sockets_pollfd[i].fd;
ent->next = NULL;
memcpy (ent->data, buffer, buffer_len);
ent->data_len = buffer_len;
if (private_list_head == NULL)
private_list_head = ent;
else
private_list_tail->next = ent;
private_list_tail = ent;
private_list_length++;
/* Do not block here. Blocking here has led to
* insufficient performance in the past. */
if (pthread_mutex_trylock (&receive_list_lock) == 0)
{
assert (((receive_list_head == NULL) && (receive_list_length == 0))
|| ((receive_list_head != NULL) && (receive_list_length != 0)));
if (receive_list_head == NULL)
receive_list_head = private_list_head;
else
receive_list_tail->next = private_list_head;
receive_list_tail = private_list_tail;
receive_list_length += private_list_length;
pthread_cond_signal (&receive_list_cond);
pthread_mutex_unlock (&receive_list_lock);
private_list_head = NULL;
private_list_tail = NULL;
private_list_length = 0;
}
status = 0;
} /* for (listen_sockets_pollfd) */
if (status != 0)
break;
} /* while (listen_loop == 0) */
/* Make sure everything is dispatched before exiting. */
if (private_list_head != NULL)
{
pthread_mutex_lock (&receive_list_lock);
if (receive_list_head == NULL)
receive_list_head = private_list_head;
else
receive_list_tail->next = private_list_head;
receive_list_tail = private_list_tail;
receive_list_length += private_list_length;
pthread_cond_signal (&receive_list_cond);
pthread_mutex_unlock (&receive_list_lock);
}
return (status);
} /* }}} int network_receive */
static void *receive_thread (void __attribute__((unused)) *arg)
{
return (network_receive () ? (void *) 1 : (void *) 0);
} /* void *receive_thread */
static void network_init_buffer (void)
{
memset (send_buffer, 0, network_config_packet_size);
send_buffer_ptr = send_buffer;
send_buffer_fill = 0;
memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
} /* int network_init_buffer */
static void networt_send_buffer_plain (sockent_t *se, /* {{{ */
const char *buffer, size_t buffer_size)
{
int status;
while (42)
{
status = sockent_client_connect (se);
if (status != 0)
return;
status = sendto (se->data.client.fd, buffer, buffer_size,
/* flags = */ 0,
(struct sockaddr *) se->data.client.addr,
se->data.client.addrlen);
if (status < 0)
{
char errbuf[1024];
if ((errno == EINTR) || (errno == EAGAIN))
continue;
ERROR ("network plugin: sendto failed: %s. Closing sending socket.",
sstrerror (errno, errbuf, sizeof (errbuf)));
sockent_client_disconnect (se);
return;
}
break;
} /* while (42) */
} /* }}} void networt_send_buffer_plain */
#if HAVE_LIBGCRYPT
#define BUFFER_ADD(p,s) do { \
memcpy (buffer + buffer_offset, (p), (s)); \
buffer_offset += (s); \
} while (0)
static void networt_send_buffer_signed (sockent_t *se, /* {{{ */
const char *in_buffer, size_t in_buffer_size)
{
part_signature_sha256_t ps;
char buffer[BUFF_SIG_SIZE + in_buffer_size];
size_t buffer_offset;
size_t username_len;
gcry_md_hd_t hd;
gcry_error_t err;
unsigned char *hash;
hd = NULL;
err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
if (err != 0)
{
ERROR ("network plugin: Creating HMAC object failed: %s",
gcry_strerror (err));
return;
}
err = gcry_md_setkey (hd, se->data.client.password,
strlen (se->data.client.password));
if (err != 0)
{
ERROR ("network plugin: gcry_md_setkey failed: %s",
gcry_strerror (err));
gcry_md_close (hd);
return;
}
username_len = strlen (se->data.client.username);
if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
{
ERROR ("network plugin: Username too long: %s",
se->data.client.username);
return;
}
memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
se->data.client.username, username_len);
memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
in_buffer, in_buffer_size);
/* Initialize the `ps' structure. */
memset (&ps, 0, sizeof (ps));
ps.head.type = htons (TYPE_SIGN_SHA256);
ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
/* Calculate the hash value. */
gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
username_len + in_buffer_size);
hash = gcry_md_read (hd, GCRY_MD_SHA256);
if (hash == NULL)
{
ERROR ("network plugin: gcry_md_read failed.");
gcry_md_close (hd);
return;
}
memcpy (ps.hash, hash, sizeof (ps.hash));
/* Add the header */
buffer_offset = 0;
BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
BUFFER_ADD (ps.hash, sizeof (ps.hash));
assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
gcry_md_close (hd);
hd = NULL;
buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
networt_send_buffer_plain (se, buffer, buffer_offset);
} /* }}} void networt_send_buffer_signed */
static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
const char *in_buffer, size_t in_buffer_size)
{
part_encryption_aes256_t pea;
char buffer[BUFF_SIG_SIZE + in_buffer_size];
size_t buffer_size;
size_t buffer_offset;
size_t header_size;
size_t username_len;
gcry_error_t err;
gcry_cipher_hd_t cypher;
/* Initialize the header fields */
memset (&pea, 0, sizeof (pea));
pea.head.type = htons (TYPE_ENCR_AES256);
pea.username = se->data.client.username;
username_len = strlen (pea.username);
if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
{
ERROR ("network plugin: Username too long: %s", pea.username);
return;
}
buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
header_size = PART_ENCRYPTION_AES256_SIZE + username_len
- sizeof (pea.hash);
assert (buffer_size <= sizeof (buffer));
DEBUG ("network plugin: networt_send_buffer_encrypted: "
"buffer_size = %zu;", buffer_size);
pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
+ username_len + in_buffer_size));
pea.username_length = htons ((uint16_t) username_len);
/* Chose a random initialization vector. */
gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
/* Create hash of the payload */
gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
/* Initialize the buffer */
buffer_offset = 0;
memset (buffer, 0, sizeof (buffer));
BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
BUFFER_ADD (pea.username, username_len);
BUFFER_ADD (pea.iv, sizeof (pea.iv));
assert (buffer_offset == header_size);
BUFFER_ADD (pea.hash, sizeof (pea.hash));
BUFFER_ADD (in_buffer, in_buffer_size);
assert (buffer_offset == buffer_size);
cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
se->data.client.password);
if (cypher == NULL)
return;
/* Encrypt the buffer in-place */
err = gcry_cipher_encrypt (cypher,
buffer + header_size,
buffer_size - header_size,
/* in = */ NULL, /* in len = */ 0);
if (err != 0)
{
ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
gcry_strerror (err));
return;
}
/* Send it out without further modifications */
networt_send_buffer_plain (se, buffer, buffer_size);
} /* }}} void networt_send_buffer_encrypted */
#undef BUFFER_ADD
#endif /* HAVE_LIBGCRYPT */
static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
{
sockent_t *se;
DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
for (se = sending_sockets; se != NULL; se = se->next)
{
#if HAVE_LIBGCRYPT
if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
networt_send_buffer_encrypted (se, buffer, buffer_len);
else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
networt_send_buffer_signed (se, buffer, buffer_len);
else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
#endif /* HAVE_LIBGCRYPT */
networt_send_buffer_plain (se, buffer, buffer_len);
} /* for (sending_sockets) */
} /* }}} void network_send_buffer */
static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
value_list_t *vl_def,
const data_set_t *ds, const value_list_t *vl)
{
char *buffer_orig = buffer;
if (strcmp (vl_def->host, vl->host) != 0)
{
if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
vl->host, strlen (vl->host)) != 0)
return (-1);
sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
}
if (vl_def->time != vl->time)
{
if (write_part_number (&buffer, &buffer_size, TYPE_TIME_HR,
(uint64_t) vl->time))
return (-1);
vl_def->time = vl->time;
}
if (vl_def->interval != vl->interval)
{
if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL_HR,
(uint64_t) vl->interval))
return (-1);
vl_def->interval = vl->interval;
}
if (strcmp (vl_def->plugin, vl->plugin) != 0)
{
if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
vl->plugin, strlen (vl->plugin)) != 0)
return (-1);
sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
}
if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
{
if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
vl->plugin_instance,
strlen (vl->plugin_instance)) != 0)
return (-1);
sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
}
if (strcmp (vl_def->type, vl->type) != 0)
{
if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
vl->type, strlen (vl->type)) != 0)
return (-1);
sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
}
if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
{
if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
vl->type_instance,
strlen (vl->type_instance)) != 0)
return (-1);
sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
}
if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
return (-1);
return (buffer - buffer_orig);
} /* }}} int add_to_buffer */
static void flush_buffer (void)
{
DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
send_buffer_fill);
network_send_buffer (send_buffer, (size_t) send_buffer_fill);
stats_octets_tx += ((uint64_t) send_buffer_fill);
stats_packets_tx++;
network_init_buffer ();
}
static int network_write (const data_set_t *ds, const value_list_t *vl,
user_data_t __attribute__((unused)) *user_data)
{
int status;
if (!check_send_okay (vl))
{
#if COLLECT_DEBUG
char name[6*DATA_MAX_NAME_LEN];
FORMAT_VL (name, sizeof (name), vl);
name[sizeof (name) - 1] = 0;
DEBUG ("network plugin: network_write: "
"NOT sending %s.", name);
#endif
/* Counter is not protected by another lock and may be reached by
* multiple threads */
pthread_mutex_lock (&stats_lock);
stats_values_not_sent++;
pthread_mutex_unlock (&stats_lock);
return (0);
}
uc_meta_data_add_unsigned_int (vl,
"network:time_sent", (uint64_t) vl->time);
pthread_mutex_lock (&send_buffer_lock);
status = add_to_buffer (send_buffer_ptr,
network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
&send_buffer_vl,
ds, vl);
if (status >= 0)
{
/* status == bytes added to the buffer */
send_buffer_fill += status;
send_buffer_ptr += status;
stats_values_sent++;
}
else
{
flush_buffer ();
status = add_to_buffer (send_buffer_ptr,
network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
&send_buffer_vl,
ds, vl);
if (status >= 0)
{
send_buffer_fill += status;
send_buffer_ptr += status;
stats_values_sent++;
}
}
if (status < 0)
{
ERROR ("network plugin: Unable to append to the "
"buffer for some weird reason");
}
else if ((network_config_packet_size - send_buffer_fill) < 15)
{
flush_buffer ();
}
pthread_mutex_unlock (&send_buffer_lock);
return ((status < 0) ? -1 : 0);
} /* int network_write */
static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
int *retval)
{
if ((ci->values_num != 1)
|| ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
&& (ci->values[0].type != OCONFIG_TYPE_STRING)))
{
ERROR ("network plugin: The `%s' config option needs "
"exactly one boolean argument.", ci->key);
return (-1);
}
if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
{
if (ci->values[0].value.boolean)
*retval = 1;
else
*retval = 0;
}
else
{
char *str = ci->values[0].value.string;
if (IS_TRUE (str))
*retval = 1;
else if (IS_FALSE (str))
*retval = 0;
else
{
ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
"option as boolean value.",
str, ci->key);
return (-1);
}
}
return (0);
} /* }}} int network_config_set_boolean */
static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
{
int tmp;
if ((ci->values_num != 1)
|| (ci->values[0].type != OCONFIG_TYPE_NUMBER))
{
WARNING ("network plugin: The `TimeToLive' config option needs exactly "
"one numeric argument.");
return (-1);
}
tmp = (int) ci->values[0].value.number;
if ((tmp > 0) && (tmp <= 255))
network_config_ttl = tmp;
else {
WARNING ("network plugin: The `TimeToLive' must be between 1 and 255.");
return (-1);
}
return (0);
} /* }}} int network_config_set_ttl */
static int network_config_set_interface (const oconfig_item_t *ci, /* {{{ */
int *interface)
{
if ((ci->values_num != 1)
|| (ci->values[0].type != OCONFIG_TYPE_STRING))
{
WARNING ("network plugin: The `Interface' config option needs exactly "
"one string argument.");
return (-1);
}
if (interface == NULL)
return (-1);
*interface = if_nametoindex (ci->values[0].value.string);
return (0);
} /* }}} int network_config_set_interface */
static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
{
int tmp;
if ((ci->values_num != 1)
|| (ci->values[0].type != OCONFIG_TYPE_NUMBER))
{
WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
"one numeric argument.");
return (-1);
}
tmp = (int) ci->values[0].value.number;
if ((tmp >= 1024) && (tmp <= 65535))
network_config_packet_size = tmp;
return (0);
} /* }}} int network_config_set_buffer_size */
#if HAVE_LIBGCRYPT
static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
char **ret_string)
{
char *tmp;
if ((ci->values_num != 1)
|| (ci->values[0].type != OCONFIG_TYPE_STRING))
{
WARNING ("network plugin: The `%s' config option needs exactly "
"one string argument.", ci->key);
return (-1);
}
tmp = strdup (ci->values[0].value.string);
if (tmp == NULL)
return (-1);
sfree (*ret_string);
*ret_string = tmp;
return (0);
} /* }}} int network_config_set_string */
#endif /* HAVE_LIBGCRYPT */
#if HAVE_LIBGCRYPT
static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
int *retval)
{
char *str;
if ((ci->values_num != 1)
|| (ci->values[0].type != OCONFIG_TYPE_STRING))
{
WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
"one string argument.");
return (-1);
}
str = ci->values[0].value.string;
if (strcasecmp ("Encrypt", str) == 0)
*retval = SECURITY_LEVEL_ENCRYPT;
else if (strcasecmp ("Sign", str) == 0)
*retval = SECURITY_LEVEL_SIGN;
else if (strcasecmp ("None", str) == 0)
*retval = SECURITY_LEVEL_NONE;
else
{
WARNING ("network plugin: Unknown security level: %s.", str);
return (-1);
}
return (0);
} /* }}} int network_config_set_security_level */
#endif /* HAVE_LIBGCRYPT */
static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
{
sockent_t *se;
int status;
int i;
if ((ci->values_num < 1) || (ci->values_num > 2)
|| (ci->values[0].type != OCONFIG_TYPE_STRING)
|| ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
{
ERROR ("network plugin: The `%s' config option needs "
"one or two string arguments.", ci->key);
return (-1);
}
se = sockent_create (SOCKENT_TYPE_SERVER);
if (se == NULL)
{
ERROR ("network plugin: sockent_create failed.");
return (-1);
}
se->node = strdup (ci->values[0].value.string);
if (ci->values_num >= 2)
se->service = strdup (ci->values[1].value.string);
for (i = 0; i < ci->children_num; i++)
{
oconfig_item_t *child = ci->children + i;
#if HAVE_LIBGCRYPT
if (strcasecmp ("AuthFile", child->key) == 0)
network_config_set_string (child, &se->data.server.auth_file);
else if (strcasecmp ("SecurityLevel", child->key) == 0)
network_config_set_security_level (child,
&se->data.server.security_level);
else
#endif /* HAVE_LIBGCRYPT */
if (strcasecmp ("Interface", child->key) == 0)
network_config_set_interface (child,
&se->interface);
else
{
WARNING ("network plugin: Option `%s' is not allowed here.",
child->key);
}
}
#if HAVE_LIBGCRYPT
if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
&& (se->data.server.auth_file == NULL))
{
ERROR ("network plugin: A security level higher than `none' was "
"requested, but no AuthFile option was given. Cowardly refusing to "
"open this socket!");
sockent_destroy (se);
return (-1);
}
#endif /* HAVE_LIBGCRYPT */
status = sockent_init_crypto (se);
if (status != 0)
{
ERROR ("network plugin: network_config_add_listen: sockent_init_crypto() failed.");
sockent_destroy (se);
return (-1);
}
status = sockent_server_listen (se);
if (status != 0)
{
ERROR ("network plugin: network_config_add_server: sockent_server_listen failed.");
sockent_destroy (se);
return (-1);
}
status = sockent_add (se);
if (status != 0)
{
ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
sockent_destroy (se);
return (-1);
}
return (0);
} /* }}} int network_config_add_listen */
static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
{
sockent_t *se;
int status;
int i;
if ((ci->values_num < 1) || (ci->values_num > 2)
|| (ci->values[0].type != OCONFIG_TYPE_STRING)
|| ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
{
ERROR ("network plugin: The `%s' config option needs "
"one or two string arguments.", ci->key);
return (-1);
}
se = sockent_create (SOCKENT_TYPE_CLIENT);
if (se == NULL)
{
ERROR ("network plugin: sockent_create failed.");
return (-1);
}
se->node = strdup (ci->values[0].value.string);
if (ci->values_num >= 2)
se->service = strdup (ci->values[1].value.string);
for (i = 0; i < ci->children_num; i++)
{
oconfig_item_t *child = ci->children + i;
#if HAVE_LIBGCRYPT
if (strcasecmp ("Username", child->key) == 0)
network_config_set_string (child, &se->data.client.username);
else if (strcasecmp ("Password", child->key) == 0)
network_config_set_string (child, &se->data.client.password);
else if (strcasecmp ("SecurityLevel", child->key) == 0)
network_config_set_security_level (child,
&se->data.client.security_level);
else
#endif /* HAVE_LIBGCRYPT */
if (strcasecmp ("Interface", child->key) == 0)
network_config_set_interface (child,
&se->interface);
else
{
WARNING ("network plugin: Option `%s' is not allowed here.",
child->key);
}
}
#if HAVE_LIBGCRYPT
if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
&& ((se->data.client.username == NULL)
|| (se->data.client.password == NULL)))
{
ERROR ("network plugin: A security level higher than `none' was "
"requested, but no Username or Password option was given. "
"Cowardly refusing to open this socket!");
sockent_destroy (se);
return (-1);
}
#endif /* HAVE_LIBGCRYPT */
status = sockent_init_crypto (se);
if (status != 0)
{
ERROR ("network plugin: network_config_add_server: sockent_init_crypto() failed.");
sockent_destroy (se);
return (-1);
}
/* No call to sockent_client_connect() here -- it is called from
* networt_send_buffer_plain(). */
status = sockent_add (se);
if (status != 0)
{
ERROR ("network plugin: network_config_add_server: sockent_add failed.");
sockent_destroy (se);
return (-1);
}
return (0);
} /* }}} int network_config_add_server */
static int network_config (oconfig_item_t *ci) /* {{{ */
{
int i;
/* The options need to be applied first */
for (i = 0; i < ci->children_num; i++)
{
oconfig_item_t *child = ci->children + i;
if (strcasecmp ("TimeToLive", child->key) == 0)
network_config_set_ttl (child);
}
for (i = 0; i < ci->children_num; i++)
{
oconfig_item_t *child = ci->children + i;
if (strcasecmp ("Listen", child->key) == 0)
network_config_add_listen (child);
else if (strcasecmp ("Server", child->key) == 0)
network_config_add_server (child);
else if (strcasecmp ("TimeToLive", child->key) == 0) {
/* Handled earlier */
}
else if (strcasecmp ("MaxPacketSize", child->key) == 0)
network_config_set_buffer_size (child);
else if (strcasecmp ("Forward", child->key) == 0)
network_config_set_boolean (child, &network_config_forward);
else if (strcasecmp ("ReportStats", child->key) == 0)
network_config_set_boolean (child, &network_config_stats);
else
{
WARNING ("network plugin: Option `%s' is not allowed here.",
child->key);
}
}
return (0);
} /* }}} int network_config */
static int network_notification (const notification_t *n,
user_data_t __attribute__((unused)) *user_data)
{
char buffer[network_config_packet_size];
char *buffer_ptr = buffer;
int buffer_free = sizeof (buffer);
int status;
if (!check_send_notify_okay (n))
return (0);
memset (buffer, 0, sizeof (buffer));
status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME_HR,
(uint64_t) n->time);
if (status != 0)
return (-1);
status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
(uint64_t) n->severity);
if (status != 0)
return (-1);
if (strlen (n->host) > 0)
{
status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
n->host, strlen (n->host));
if (status != 0)
return (-1);
}
if (strlen (n->plugin) > 0)
{
status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
n->plugin, strlen (n->plugin));
if (status != 0)
return (-1);
}
if (strlen (n->plugin_instance) > 0)
{
status = write_part_string (&buffer_ptr, &buffer_free,
TYPE_PLUGIN_INSTANCE,
n->plugin_instance, strlen (n->plugin_instance));
if (status != 0)
return (-1);
}
if (strlen (n->type) > 0)
{
status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
n->type, strlen (n->type));
if (status != 0)
return (-1);
}
if (strlen (n->type_instance) > 0)
{
status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
n->type_instance, strlen (n->type_instance));
if (status != 0)
return (-1);
}
status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
n->message, strlen (n->message));
if (status != 0)
return (-1);
network_send_buffer (buffer, sizeof (buffer) - buffer_free);
return (0);
} /* int network_notification */
static int network_shutdown (void)
{
sockent_t *se;
listen_loop++;
/* Kill the listening thread */
if (receive_thread_running != 0)
{
INFO ("network plugin: Stopping receive thread.");
pthread_kill (receive_thread_id, SIGTERM);
pthread_join (receive_thread_id, NULL /* no return value */);
memset (&receive_thread_id, 0, sizeof (receive_thread_id));
receive_thread_running = 0;
}
/* Shutdown the dispatching thread */
if (dispatch_thread_running != 0)
{
INFO ("network plugin: Stopping dispatch thread.");
pthread_mutex_lock (&receive_list_lock);
pthread_cond_broadcast (&receive_list_cond);
pthread_mutex_unlock (&receive_list_lock);
pthread_join (dispatch_thread_id, /* ret = */ NULL);
dispatch_thread_running = 0;
}
sockent_destroy (listen_sockets);
if (send_buffer_fill > 0)
flush_buffer ();
sfree (send_buffer);
for (se = sending_sockets; se != NULL; se = se->next)
sockent_client_disconnect (se);
sockent_destroy (sending_sockets);
plugin_unregister_config ("network");
plugin_unregister_init ("network");
plugin_unregister_write ("network");
plugin_unregister_shutdown ("network");
return (0);
} /* int network_shutdown */
static int network_stats_read (void) /* {{{ */
{
derive_t copy_octets_rx;
derive_t copy_octets_tx;
derive_t copy_packets_rx;
derive_t copy_packets_tx;
derive_t copy_values_dispatched;
derive_t copy_values_not_dispatched;
derive_t copy_values_sent;
derive_t copy_values_not_sent;
derive_t copy_receive_list_length;
value_list_t vl = VALUE_LIST_INIT;
value_t values[2];
copy_octets_rx = stats_octets_rx;
copy_octets_tx = stats_octets_tx;
copy_packets_rx = stats_packets_rx;
copy_packets_tx = stats_packets_tx;
copy_values_dispatched = stats_values_dispatched;
copy_values_not_dispatched = stats_values_not_dispatched;
copy_values_sent = stats_values_sent;
copy_values_not_sent = stats_values_not_sent;
copy_receive_list_length = receive_list_length;
/* Initialize `vl' */
vl.values = values;
vl.values_len = 2;
vl.time = 0;
sstrncpy (vl.host, hostname_g, sizeof (vl.host));
sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
/* Octets received / sent */
vl.values[0].derive = (derive_t) copy_octets_rx;
vl.values[1].derive = (derive_t) copy_octets_tx;
sstrncpy (vl.type, "if_octets", sizeof (vl.type));
plugin_dispatch_values (&vl);
/* Packets received / send */
vl.values[0].derive = (derive_t) copy_packets_rx;
vl.values[1].derive = (derive_t) copy_packets_tx;
sstrncpy (vl.type, "if_packets", sizeof (vl.type));
plugin_dispatch_values (&vl);
/* Values (not) dispatched and (not) send */
sstrncpy (vl.type, "total_values", sizeof (vl.type));
vl.values_len = 1;
vl.values[0].derive = (derive_t) copy_values_dispatched;
sstrncpy (vl.type_instance, "dispatch-accepted",
sizeof (vl.type_instance));
plugin_dispatch_values (&vl);
vl.values[0].derive = (derive_t) copy_values_not_dispatched;
sstrncpy (vl.type_instance, "dispatch-rejected",
sizeof (vl.type_instance));
plugin_dispatch_values (&vl);
vl.values[0].derive = (derive_t) copy_values_sent;
sstrncpy (vl.type_instance, "send-accepted",
sizeof (vl.type_instance));
plugin_dispatch_values (&vl);
vl.values[0].derive = (derive_t) copy_values_not_sent;
sstrncpy (vl.type_instance, "send-rejected",
sizeof (vl.type_instance));
plugin_dispatch_values (&vl);
/* Receive queue length */
vl.values[0].gauge = (gauge_t) copy_receive_list_length;
sstrncpy (vl.type, "queue_length", sizeof (vl.type));
vl.type_instance[0] = 0;
plugin_dispatch_values (&vl);
return (0);
} /* }}} int network_stats_read */
static int network_init (void)
{
static _Bool have_init = 0;
/* Check if we were already initialized. If so, just return - there's
* nothing more to do (for now, that is). */
if (have_init)
return (0);
have_init = 1;
#if HAVE_LIBGCRYPT
network_init_gcrypt ();
#endif
if (network_config_stats != 0)
plugin_register_read ("network", network_stats_read);
plugin_register_shutdown ("network", network_shutdown);
send_buffer = malloc (network_config_packet_size);
if (send_buffer == NULL)
{
ERROR ("network plugin: malloc failed.");
return (-1);
}
network_init_buffer ();
/* setup socket(s) and so on */
if (sending_sockets != NULL)
{
plugin_register_write ("network", network_write,
/* user_data = */ NULL);
plugin_register_notification ("network", network_notification,
/* user_data = */ NULL);
}
/* If no threads need to be started, return here. */
if ((listen_sockets_num == 0)
|| ((dispatch_thread_running != 0)
&& (receive_thread_running != 0)))
return (0);
if (dispatch_thread_running == 0)
{
int status;
status = plugin_thread_create (&dispatch_thread_id,
NULL /* no attributes */,
dispatch_thread,
NULL /* no argument */);
if (status != 0)
{
char errbuf[1024];
ERROR ("network: pthread_create failed: %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
}
else
{
dispatch_thread_running = 1;
}
}
if (receive_thread_running == 0)
{
int status;
status = plugin_thread_create (&receive_thread_id,
NULL /* no attributes */,
receive_thread,
NULL /* no argument */);
if (status != 0)
{
char errbuf[1024];
ERROR ("network: pthread_create failed: %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
}
else
{
receive_thread_running = 1;
}
}
return (0);
} /* int network_init */
/*
* The flush option of the network plugin cannot flush individual identifiers.
* All the values are added to a buffer and sent when the buffer is full, the
* requested value may or may not be in there, it's not worth finding out. We
* just send the buffer if `flush' is called - if the requested value was in
* there, good. If not, well, then there is nothing to flush.. -octo
*/
static int network_flush (__attribute__((unused)) cdtime_t timeout,
__attribute__((unused)) const char *identifier,
__attribute__((unused)) user_data_t *user_data)
{
pthread_mutex_lock (&send_buffer_lock);
if (send_buffer_fill > 0)
flush_buffer ();
pthread_mutex_unlock (&send_buffer_lock);
return (0);
} /* int network_flush */
void module_register (void)
{
plugin_register_complex_config ("network", network_config);
plugin_register_init ("network", network_init);
plugin_register_flush ("network", network_flush,
/* user_data = */ NULL);
} /* void module_register */
/* vim: set fdm=marker : */
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5203_0 |
crossvul-cpp_data_good_2769_0 | /*
zip_open.c -- open zip archive by name
Copyright (C) 1999-2016 Dieter Baron and Thomas Klausner
This file is part of libzip, a library to manipulate ZIP archives.
The authors can be contacted at <libzip@nih.at>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. The names of the authors may not be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/stat.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "zipint.h"
typedef enum {
EXISTS_ERROR = -1,
EXISTS_NOT = 0,
EXISTS_EMPTY,
EXISTS_NONEMPTY,
} exists_t;
static zip_t *_zip_allocate_new(zip_source_t *src, unsigned int flags, zip_error_t *error);
static zip_int64_t _zip_checkcons(zip_t *za, zip_cdir_t *cdir, zip_error_t *error);
static zip_cdir_t *_zip_find_central_dir(zip_t *za, zip_uint64_t len);
static exists_t _zip_file_exists(zip_source_t *src, zip_error_t *error);
static int _zip_headercomp(const zip_dirent_t *, const zip_dirent_t *);
static unsigned char *_zip_memmem(const unsigned char *, size_t, const unsigned char *, size_t);
static zip_cdir_t *_zip_read_cdir(zip_t *za, zip_buffer_t *buffer, zip_uint64_t buf_offset, zip_error_t *error);
static zip_cdir_t *_zip_read_eocd(zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error);
static zip_cdir_t *_zip_read_eocd64(zip_source_t *src, zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error);
ZIP_EXTERN zip_t *
zip_open(const char *fn, int _flags, int *zep)
{
zip_t *za;
zip_source_t *src;
struct zip_error error;
zip_error_init(&error);
if ((src = zip_source_file_create(fn, 0, -1, &error)) == NULL) {
_zip_set_open_error(zep, &error, 0);
zip_error_fini(&error);
return NULL;
}
if ((za = zip_open_from_source(src, _flags, &error)) == NULL) {
zip_source_free(src);
_zip_set_open_error(zep, &error, 0);
zip_error_fini(&error);
return NULL;
}
zip_error_fini(&error);
return za;
}
ZIP_EXTERN zip_t *
zip_open_from_source(zip_source_t *src, int _flags, zip_error_t *error)
{
static zip_int64_t needed_support_read = -1;
static zip_int64_t needed_support_write = -1;
unsigned int flags;
zip_int64_t supported;
exists_t exists;
if (_flags < 0 || src == NULL) {
zip_error_set(error, ZIP_ER_INVAL, 0);
return NULL;
}
flags = (unsigned int)_flags;
supported = zip_source_supports(src);
if (needed_support_read == -1) {
needed_support_read = zip_source_make_command_bitmap(ZIP_SOURCE_OPEN, ZIP_SOURCE_READ, ZIP_SOURCE_CLOSE, ZIP_SOURCE_SEEK, ZIP_SOURCE_TELL, ZIP_SOURCE_STAT, -1);
needed_support_write = zip_source_make_command_bitmap(ZIP_SOURCE_BEGIN_WRITE, ZIP_SOURCE_COMMIT_WRITE, ZIP_SOURCE_ROLLBACK_WRITE, ZIP_SOURCE_SEEK_WRITE, ZIP_SOURCE_TELL_WRITE, ZIP_SOURCE_REMOVE, -1);
}
if ((supported & needed_support_read) != needed_support_read) {
zip_error_set(error, ZIP_ER_OPNOTSUPP, 0);
return NULL;
}
if ((supported & needed_support_write) != needed_support_write) {
flags |= ZIP_RDONLY;
}
if ((flags & (ZIP_RDONLY|ZIP_TRUNCATE)) == (ZIP_RDONLY|ZIP_TRUNCATE)) {
zip_error_set(error, ZIP_ER_RDONLY, 0);
return NULL;
}
exists = _zip_file_exists(src, error);
switch (exists) {
case EXISTS_ERROR:
return NULL;
case EXISTS_NOT:
if ((flags & ZIP_CREATE) == 0) {
zip_error_set(error, ZIP_ER_NOENT, 0);
return NULL;
}
return _zip_allocate_new(src, flags, error);
default: {
zip_t *za;
if (flags & ZIP_EXCL) {
zip_error_set(error, ZIP_ER_EXISTS, 0);
return NULL;
}
if (zip_source_open(src) < 0) {
_zip_error_set_from_source(error, src);
return NULL;
}
if (flags & ZIP_TRUNCATE) {
za = _zip_allocate_new(src, flags, error);
}
else {
/* ZIP_CREATE gets ignored if file exists and not ZIP_EXCL, just like open() */
za = _zip_open(src, flags, error);
}
if (za == NULL) {
zip_source_close(src);
return NULL;
}
return za;
}
}
}
zip_t *
_zip_open(zip_source_t *src, unsigned int flags, zip_error_t *error)
{
zip_t *za;
zip_cdir_t *cdir;
struct zip_stat st;
zip_uint64_t len, idx;
zip_stat_init(&st);
if (zip_source_stat(src, &st) < 0) {
_zip_error_set_from_source(error, src);
return NULL;
}
if ((st.valid & ZIP_STAT_SIZE) == 0) {
zip_error_set(error, ZIP_ER_SEEK, EOPNOTSUPP);
return NULL;
}
len = st.size;
/* treat empty files as empty archives */
if (len == 0) {
if ((za=_zip_allocate_new(src, flags, error)) == NULL) {
zip_source_free(src);
return NULL;
}
return za;
}
if ((za=_zip_allocate_new(src, flags, error)) == NULL) {
return NULL;
}
if ((cdir = _zip_find_central_dir(za, len)) == NULL) {
_zip_error_copy(error, &za->error);
/* keep src so discard does not get rid of it */
zip_source_keep(src);
zip_discard(za);
return NULL;
}
za->entry = cdir->entry;
za->nentry = cdir->nentry;
za->nentry_alloc = cdir->nentry_alloc;
za->comment_orig = cdir->comment;
free(cdir);
_zip_hash_reserve_capacity(za->names, za->nentry, &za->error);
for (idx = 0; idx < za->nentry; idx++) {
const zip_uint8_t *name = _zip_string_get(za->entry[idx].orig->filename, NULL, 0, error);
if (name == NULL) {
/* keep src so discard does not get rid of it */
zip_source_keep(src);
zip_discard(za);
return NULL;
}
if (_zip_hash_add(za->names, name, idx, ZIP_FL_UNCHANGED, &za->error) == false) {
if (za->error.zip_err != ZIP_ER_EXISTS || (flags & ZIP_CHECKCONS)) {
_zip_error_copy(error, &za->error);
/* keep src so discard does not get rid of it */
zip_source_keep(src);
zip_discard(za);
return NULL;
}
}
}
za->ch_flags = za->flags;
return za;
}
void
_zip_set_open_error(int *zep, const zip_error_t *err, int ze)
{
if (err) {
ze = zip_error_code_zip(err);
if (zip_error_system_type(err) == ZIP_ET_SYS) {
errno = zip_error_code_system(err);
}
}
if (zep)
*zep = ze;
}
/* _zip_readcdir:
tries to find a valid end-of-central-directory at the beginning of
buf, and then the corresponding central directory entries.
Returns a struct zip_cdir which contains the central directory
entries, or NULL if unsuccessful. */
static zip_cdir_t *
_zip_read_cdir(zip_t *za, zip_buffer_t *buffer, zip_uint64_t buf_offset, zip_error_t *error)
{
zip_cdir_t *cd;
zip_uint16_t comment_len;
zip_uint64_t i, left;
zip_uint64_t eocd_offset = _zip_buffer_offset(buffer);
zip_buffer_t *cd_buffer;
if (_zip_buffer_left(buffer) < EOCDLEN) {
/* not enough bytes left for comment */
zip_error_set(error, ZIP_ER_NOZIP, 0);
return NULL;
}
/* check for end-of-central-dir magic */
if (memcmp(_zip_buffer_get(buffer, 4), EOCD_MAGIC, 4) != 0) {
zip_error_set(error, ZIP_ER_NOZIP, 0);
return NULL;
}
if (eocd_offset >= EOCD64LOCLEN && memcmp(_zip_buffer_data(buffer) + eocd_offset - EOCD64LOCLEN, EOCD64LOC_MAGIC, 4) == 0) {
_zip_buffer_set_offset(buffer, eocd_offset - EOCD64LOCLEN);
cd = _zip_read_eocd64(za->src, buffer, buf_offset, za->flags, error);
}
else {
_zip_buffer_set_offset(buffer, eocd_offset);
cd = _zip_read_eocd(buffer, buf_offset, za->flags, error);
}
if (cd == NULL)
return NULL;
_zip_buffer_set_offset(buffer, eocd_offset + 20);
comment_len = _zip_buffer_get_16(buffer);
if (cd->offset + cd->size > buf_offset + eocd_offset) {
/* cdir spans past EOCD record */
zip_error_set(error, ZIP_ER_INCONS, 0);
_zip_cdir_free(cd);
return NULL;
}
if (comment_len || (za->open_flags & ZIP_CHECKCONS)) {
zip_uint64_t tail_len;
_zip_buffer_set_offset(buffer, eocd_offset + EOCDLEN);
tail_len = _zip_buffer_left(buffer);
if (tail_len < comment_len || ((za->open_flags & ZIP_CHECKCONS) && tail_len != comment_len)) {
zip_error_set(error, ZIP_ER_INCONS, 0);
_zip_cdir_free(cd);
return NULL;
}
if (comment_len) {
if ((cd->comment=_zip_string_new(_zip_buffer_get(buffer, comment_len), comment_len, ZIP_FL_ENC_GUESS, error)) == NULL) {
_zip_cdir_free(cd);
return NULL;
}
}
}
if (cd->offset >= buf_offset) {
zip_uint8_t *data;
/* if buffer already read in, use it */
_zip_buffer_set_offset(buffer, cd->offset - buf_offset);
if ((data = _zip_buffer_get(buffer, cd->size)) == NULL) {
zip_error_set(error, ZIP_ER_INCONS, 0);
_zip_cdir_free(cd);
return NULL;
}
if ((cd_buffer = _zip_buffer_new(data, cd->size)) == NULL) {
zip_error_set(error, ZIP_ER_MEMORY, 0);
_zip_cdir_free(cd);
return NULL;
}
}
else {
cd_buffer = NULL;
if (zip_source_seek(za->src, (zip_int64_t)cd->offset, SEEK_SET) < 0) {
_zip_error_set_from_source(error, za->src);
_zip_cdir_free(cd);
return NULL;
}
/* possible consistency check: cd->offset = len-(cd->size+cd->comment_len+EOCDLEN) ? */
if (zip_source_tell(za->src) != (zip_int64_t)cd->offset) {
zip_error_set(error, ZIP_ER_NOZIP, 0);
_zip_cdir_free(cd);
return NULL;
}
}
left = (zip_uint64_t)cd->size;
i=0;
while (left > 0) {
bool grown = false;
zip_int64_t entry_size;
if (i == cd->nentry) {
/* InfoZIP has a hack to avoid using Zip64: it stores nentries % 0x10000 */
/* This hack isn't applicable if we're using Zip64, or if there is no central directory entry following. */
if (cd->is_zip64 || left < CDENTRYSIZE) {
break;
}
if (!_zip_cdir_grow(cd, 0x10000, error)) {
_zip_cdir_free(cd);
_zip_buffer_free(cd_buffer);
return NULL;
}
grown = true;
}
if ((cd->entry[i].orig=_zip_dirent_new()) == NULL || (entry_size = _zip_dirent_read(cd->entry[i].orig, za->src, cd_buffer, false, error)) < 0) {
if (grown && zip_error_code_zip(error) == ZIP_ER_NOZIP) {
zip_error_set(error, ZIP_ER_INCONS, 0);
}
_zip_cdir_free(cd);
_zip_buffer_free(cd_buffer);
return NULL;
}
i++;
left -= (zip_uint64_t)entry_size;
}
if (i != cd->nentry || left > 0) {
zip_error_set(error, ZIP_ER_INCONS, 0);
_zip_buffer_free(cd_buffer);
_zip_cdir_free(cd);
return NULL;
}
if (za->open_flags & ZIP_CHECKCONS) {
bool ok;
if (cd_buffer) {
ok = _zip_buffer_eof(cd_buffer);
}
else {
zip_int64_t offset = zip_source_tell(za->src);
if (offset < 0) {
_zip_error_set_from_source(error, za->src);
_zip_cdir_free(cd);
return NULL;
}
ok = ((zip_uint64_t)offset == cd->offset + cd->size);
}
if (!ok) {
zip_error_set(error, ZIP_ER_INCONS, 0);
_zip_buffer_free(cd_buffer);
_zip_cdir_free(cd);
return NULL;
}
}
_zip_buffer_free(cd_buffer);
return cd;
}
/* _zip_checkcons:
Checks the consistency of the central directory by comparing central
directory entries with local headers and checking for plausible
file and header offsets. Returns -1 if not plausible, else the
difference between the lowest and the highest fileposition reached */
static zip_int64_t
_zip_checkcons(zip_t *za, zip_cdir_t *cd, zip_error_t *error)
{
zip_uint64_t i;
zip_uint64_t min, max, j;
struct zip_dirent temp;
_zip_dirent_init(&temp);
if (cd->nentry) {
max = cd->entry[0].orig->offset;
min = cd->entry[0].orig->offset;
}
else
min = max = 0;
for (i=0; i<cd->nentry; i++) {
if (cd->entry[i].orig->offset < min)
min = cd->entry[i].orig->offset;
if (min > (zip_uint64_t)cd->offset) {
zip_error_set(error, ZIP_ER_NOZIP, 0);
return -1;
}
j = cd->entry[i].orig->offset + cd->entry[i].orig->comp_size
+ _zip_string_length(cd->entry[i].orig->filename) + LENTRYSIZE;
if (j > max)
max = j;
if (max > (zip_uint64_t)cd->offset) {
zip_error_set(error, ZIP_ER_NOZIP, 0);
return -1;
}
if (zip_source_seek(za->src, (zip_int64_t)cd->entry[i].orig->offset, SEEK_SET) < 0) {
_zip_error_set_from_source(error, za->src);
return -1;
}
if (_zip_dirent_read(&temp, za->src, NULL, true, error) == -1) {
_zip_dirent_finalize(&temp);
return -1;
}
if (_zip_headercomp(cd->entry[i].orig, &temp) != 0) {
zip_error_set(error, ZIP_ER_INCONS, 0);
_zip_dirent_finalize(&temp);
return -1;
}
cd->entry[i].orig->extra_fields = _zip_ef_merge(cd->entry[i].orig->extra_fields, temp.extra_fields);
cd->entry[i].orig->local_extra_fields_read = 1;
temp.extra_fields = NULL;
_zip_dirent_finalize(&temp);
}
return (max-min) < ZIP_INT64_MAX ? (zip_int64_t)(max-min) : ZIP_INT64_MAX;
}
/* _zip_headercomp:
compares a central directory entry and a local file header
Return 0 if they are consistent, -1 if not. */
static int
_zip_headercomp(const zip_dirent_t *central, const zip_dirent_t *local)
{
if ((central->version_needed < local->version_needed)
#if 0
/* some zip-files have different values in local
and global headers for the bitflags */
|| (central->bitflags != local->bitflags)
#endif
|| (central->comp_method != local->comp_method)
|| (central->last_mod != local->last_mod)
|| !_zip_string_equal(central->filename, local->filename))
return -1;
if ((central->crc != local->crc) || (central->comp_size != local->comp_size)
|| (central->uncomp_size != local->uncomp_size)) {
/* InfoZip stores valid values in local header even when data descriptor is used.
This is in violation of the appnote. */
if (((local->bitflags & ZIP_GPBF_DATA_DESCRIPTOR) == 0
|| local->crc != 0 || local->comp_size != 0 || local->uncomp_size != 0))
return -1;
}
return 0;
}
static zip_t *
_zip_allocate_new(zip_source_t *src, unsigned int flags, zip_error_t *error)
{
zip_t *za;
if ((za = _zip_new(error)) == NULL) {
return NULL;
}
za->src = src;
za->open_flags = flags;
if (flags & ZIP_RDONLY) {
za->flags |= ZIP_AFL_RDONLY;
za->ch_flags |= ZIP_AFL_RDONLY;
}
return za;
}
/*
* tests for file existence
*/
static exists_t
_zip_file_exists(zip_source_t *src, zip_error_t *error)
{
struct zip_stat st;
zip_stat_init(&st);
if (zip_source_stat(src, &st) != 0) {
zip_error_t *src_error = zip_source_error(src);
if (zip_error_code_zip(src_error) == ZIP_ER_READ && zip_error_code_system(src_error) == ENOENT) {
return EXISTS_NOT;
}
_zip_error_copy(error, src_error);
return EXISTS_ERROR;
}
return (st.valid & ZIP_STAT_SIZE) && st.size == 0 ? EXISTS_EMPTY : EXISTS_NONEMPTY;
}
static zip_cdir_t *
_zip_find_central_dir(zip_t *za, zip_uint64_t len)
{
zip_cdir_t *cdir, *cdirnew;
zip_uint8_t *match;
zip_int64_t buf_offset;
zip_uint64_t buflen;
zip_int64_t a;
zip_int64_t best;
zip_error_t error;
zip_buffer_t *buffer;
if (len < EOCDLEN) {
zip_error_set(&za->error, ZIP_ER_NOZIP, 0);
return NULL;
}
buflen = (len < CDBUFSIZE ? len : CDBUFSIZE);
if (zip_source_seek(za->src, -(zip_int64_t)buflen, SEEK_END) < 0) {
zip_error_t *src_error = zip_source_error(za->src);
if (zip_error_code_zip(src_error) != ZIP_ER_SEEK || zip_error_code_system(src_error) != EFBIG) {
/* seek before start of file on my machine */
_zip_error_copy(&za->error, src_error);
return NULL;
}
}
if ((buf_offset = zip_source_tell(za->src)) < 0) {
_zip_error_set_from_source(&za->error, za->src);
return NULL;
}
if ((buffer = _zip_buffer_new_from_source(za->src, buflen, NULL, &za->error)) == NULL) {
return NULL;
}
best = -1;
cdir = NULL;
if (buflen >= CDBUFSIZE) {
/* EOCD64 locator is before EOCD, so leave place for it */
_zip_buffer_set_offset(buffer, EOCD64LOCLEN);
}
zip_error_set(&error, ZIP_ER_NOZIP, 0);
match = _zip_buffer_get(buffer, 0);
while ((match=_zip_memmem(match, _zip_buffer_left(buffer)-(EOCDLEN-4), (const unsigned char *)EOCD_MAGIC, 4)) != NULL) {
_zip_buffer_set_offset(buffer, (zip_uint64_t)(match - _zip_buffer_data(buffer)));
if ((cdirnew = _zip_read_cdir(za, buffer, (zip_uint64_t)buf_offset, &error)) != NULL) {
if (cdir) {
if (best <= 0) {
best = _zip_checkcons(za, cdir, &error);
}
a = _zip_checkcons(za, cdirnew, &error);
if (best < a) {
_zip_cdir_free(cdir);
cdir = cdirnew;
best = a;
}
else {
_zip_cdir_free(cdirnew);
}
}
else {
cdir = cdirnew;
if (za->open_flags & ZIP_CHECKCONS)
best = _zip_checkcons(za, cdir, &error);
else {
best = 0;
}
}
cdirnew = NULL;
}
match++;
_zip_buffer_set_offset(buffer, (zip_uint64_t)(match - _zip_buffer_data(buffer)));
}
_zip_buffer_free(buffer);
if (best < 0) {
_zip_error_copy(&za->error, &error);
_zip_cdir_free(cdir);
return NULL;
}
return cdir;
}
static unsigned char *
_zip_memmem(const unsigned char *big, size_t biglen, const unsigned char *little, size_t littlelen)
{
const unsigned char *p;
if ((biglen < littlelen) || (littlelen == 0))
return NULL;
p = big-1;
while ((p=(const unsigned char *)
memchr(p+1, little[0], (size_t)(big-(p+1))+(size_t)(biglen-littlelen)+1)) != NULL) {
if (memcmp(p+1, little+1, littlelen-1)==0)
return (unsigned char *)p;
}
return NULL;
}
static zip_cdir_t *
_zip_read_eocd(zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error)
{
zip_cdir_t *cd;
zip_uint64_t i, nentry, size, offset, eocd_offset;
if (_zip_buffer_left(buffer) < EOCDLEN) {
zip_error_set(error, ZIP_ER_INCONS, 0);
return NULL;
}
eocd_offset = _zip_buffer_offset(buffer);
_zip_buffer_get(buffer, 4); /* magic already verified */
if (_zip_buffer_get_32(buffer) != 0) {
zip_error_set(error, ZIP_ER_MULTIDISK, 0);
return NULL;
}
/* number of cdir-entries on this disk */
i = _zip_buffer_get_16(buffer);
/* number of cdir-entries */
nentry = _zip_buffer_get_16(buffer);
if (nentry != i) {
zip_error_set(error, ZIP_ER_NOZIP, 0);
return NULL;
}
size = _zip_buffer_get_32(buffer);
offset = _zip_buffer_get_32(buffer);
if (offset+size < offset) {
zip_error_set(error, ZIP_ER_SEEK, EFBIG);
return NULL;
}
if (offset+size > buf_offset + eocd_offset) {
/* cdir spans past EOCD record */
zip_error_set(error, ZIP_ER_INCONS, 0);
return NULL;
}
if ((flags & ZIP_CHECKCONS) && offset+size != buf_offset + eocd_offset) {
zip_error_set(error, ZIP_ER_INCONS, 0);
return NULL;
}
if ((cd=_zip_cdir_new(nentry, error)) == NULL)
return NULL;
cd->is_zip64 = false;
cd->size = size;
cd->offset = offset;
return cd;
}
static zip_cdir_t *
_zip_read_eocd64(zip_source_t *src, zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error)
{
zip_cdir_t *cd;
zip_uint64_t offset;
zip_uint8_t eocd[EOCD64LEN];
zip_uint64_t eocd_offset;
zip_uint64_t size, nentry, i, eocdloc_offset;
bool free_buffer;
zip_uint32_t num_disks, num_disks64, eocd_disk, eocd_disk64;
eocdloc_offset = _zip_buffer_offset(buffer);
_zip_buffer_get(buffer, 4); /* magic already verified */
num_disks = _zip_buffer_get_16(buffer);
eocd_disk = _zip_buffer_get_16(buffer);
eocd_offset = _zip_buffer_get_64(buffer);
if (eocd_offset > ZIP_INT64_MAX || eocd_offset + EOCD64LEN < eocd_offset) {
zip_error_set(error, ZIP_ER_SEEK, EFBIG);
return NULL;
}
if (eocd_offset + EOCD64LEN > eocdloc_offset + buf_offset) {
zip_error_set(error, ZIP_ER_INCONS, 0);
return NULL;
}
if (eocd_offset >= buf_offset && eocd_offset + EOCD64LEN <= buf_offset + _zip_buffer_size(buffer)) {
_zip_buffer_set_offset(buffer, eocd_offset - buf_offset);
free_buffer = false;
}
else {
if (zip_source_seek(src, (zip_int64_t)eocd_offset, SEEK_SET) < 0) {
_zip_error_set_from_source(error, src);
return NULL;
}
if ((buffer = _zip_buffer_new_from_source(src, EOCD64LEN, eocd, error)) == NULL) {
return NULL;
}
free_buffer = true;
}
if (memcmp(_zip_buffer_get(buffer, 4), EOCD64_MAGIC, 4) != 0) {
zip_error_set(error, ZIP_ER_INCONS, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
size = _zip_buffer_get_64(buffer);
if ((flags & ZIP_CHECKCONS) && size + eocd_offset + 12 != buf_offset + eocdloc_offset) {
zip_error_set(error, ZIP_ER_INCONS, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
_zip_buffer_get(buffer, 4); /* skip version made by/needed */
num_disks64 = _zip_buffer_get_32(buffer);
eocd_disk64 = _zip_buffer_get_32(buffer);
/* if eocd values are 0xffff, we have to use eocd64 values.
otherwise, if the values are not the same, it's inconsistent;
in any case, if the value is not 0, we don't support it */
if (num_disks == 0xffff) {
num_disks = num_disks64;
}
if (eocd_disk == 0xffff) {
eocd_disk = eocd_disk64;
}
if ((flags & ZIP_CHECKCONS) && (eocd_disk != eocd_disk64 || num_disks != num_disks64)) {
zip_error_set(error, ZIP_ER_INCONS, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
if (num_disks != 0 || eocd_disk != 0) {
zip_error_set(error, ZIP_ER_MULTIDISK, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
nentry = _zip_buffer_get_64(buffer);
i = _zip_buffer_get_64(buffer);
if (nentry != i) {
zip_error_set(error, ZIP_ER_MULTIDISK, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
size = _zip_buffer_get_64(buffer);
offset = _zip_buffer_get_64(buffer);
if (!_zip_buffer_ok(buffer)) {
zip_error_set(error, ZIP_ER_INTERNAL, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
if (free_buffer) {
_zip_buffer_free(buffer);
}
if (offset > ZIP_INT64_MAX || offset+size < offset) {
zip_error_set(error, ZIP_ER_SEEK, EFBIG);
return NULL;
}
if (offset+size > buf_offset + eocd_offset) {
/* cdir spans past EOCD record */
zip_error_set(error, ZIP_ER_INCONS, 0);
return NULL;
}
if ((flags & ZIP_CHECKCONS) && offset+size != buf_offset + eocd_offset) {
zip_error_set(error, ZIP_ER_INCONS, 0);
return NULL;
}
if ((cd=_zip_cdir_new(nentry, error)) == NULL)
return NULL;
cd->is_zip64 = true;
cd->size = size;
cd->offset = offset;
return cd;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2769_0 |
crossvul-cpp_data_bad_340_10 | /*
* util.c: utility functions used by OpenSC command line tools.
*
* Copyright (C) 2011 OpenSC Project developers
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#ifndef _WIN32
#include <termios.h>
#else
#include <conio.h>
#endif
#include <ctype.h>
#include "util.h"
#include "ui/notify.h"
int
is_string_valid_atr(const char *atr_str)
{
unsigned char atr[SC_MAX_ATR_SIZE];
size_t atr_len = sizeof(atr);
if (sc_hex_to_bin(atr_str, atr, &atr_len))
return 0;
if (atr_len < 2)
return 0;
if (atr[0] != 0x3B && atr[0] != 0x3F)
return 0;
return 1;
}
int
util_connect_card_ex(sc_context_t *ctx, sc_card_t **cardp,
const char *reader_id, int do_wait, int do_lock, int verbose)
{
struct sc_reader *reader = NULL, *found = NULL;
struct sc_card *card = NULL;
int r;
sc_notify_init();
if (do_wait) {
unsigned int event;
if (sc_ctx_get_reader_count(ctx) == 0) {
fprintf(stderr, "Waiting for a reader to be attached...\n");
r = sc_wait_for_event(ctx, SC_EVENT_READER_ATTACHED, &found, &event, -1, NULL);
if (r < 0) {
fprintf(stderr, "Error while waiting for a reader: %s\n", sc_strerror(r));
return 3;
}
r = sc_ctx_detect_readers(ctx);
if (r < 0) {
fprintf(stderr, "Error while refreshing readers: %s\n", sc_strerror(r));
return 3;
}
}
fprintf(stderr, "Waiting for a card to be inserted...\n");
r = sc_wait_for_event(ctx, SC_EVENT_CARD_INSERTED, &found, &event, -1, NULL);
if (r < 0) {
fprintf(stderr, "Error while waiting for a card: %s\n", sc_strerror(r));
return 3;
}
reader = found;
}
else if (sc_ctx_get_reader_count(ctx) == 0) {
fprintf(stderr, "No smart card readers found.\n");
return 1;
}
else {
if (!reader_id) {
unsigned int i;
/* Automatically try to skip to a reader with a card if reader not specified */
for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) {
reader = sc_ctx_get_reader(ctx, i);
if (sc_detect_card_presence(reader) & SC_READER_CARD_PRESENT) {
fprintf(stderr, "Using reader with a card: %s\n", reader->name);
goto autofound;
}
}
/* If no reader had a card, default to the first reader */
reader = sc_ctx_get_reader(ctx, 0);
}
else {
/* If the reader identifier looks like an ATR, try to find the reader with that card */
if (is_string_valid_atr(reader_id)) {
unsigned char atr_buf[SC_MAX_ATR_SIZE];
size_t atr_buf_len = sizeof(atr_buf);
unsigned int i;
sc_hex_to_bin(reader_id, atr_buf, &atr_buf_len);
/* Loop readers, looking for a card with ATR */
for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) {
struct sc_reader *rdr = sc_ctx_get_reader(ctx, i);
if (!(sc_detect_card_presence(rdr) & SC_READER_CARD_PRESENT))
continue;
else if (rdr->atr.len != atr_buf_len)
continue;
else if (memcmp(rdr->atr.value, atr_buf, rdr->atr.len))
continue;
fprintf(stderr, "Matched ATR in reader: %s\n", rdr->name);
reader = rdr;
goto autofound;
}
}
else {
char *endptr = NULL;
unsigned int num;
errno = 0;
num = strtol(reader_id, &endptr, 0);
if (!errno && endptr && *endptr == '\0')
reader = sc_ctx_get_reader(ctx, num);
else
reader = sc_ctx_get_reader_by_name(ctx, reader_id);
}
}
autofound:
if (!reader) {
fprintf(stderr, "Reader \"%s\" not found (%d reader(s) detected)\n",
reader_id, sc_ctx_get_reader_count(ctx));
return 1;
}
if (sc_detect_card_presence(reader) <= 0) {
fprintf(stderr, "Card not present.\n");
return 3;
}
}
if (verbose)
printf("Connecting to card in reader %s...\n", reader->name);
r = sc_connect_card(reader, &card);
if (r < 0) {
fprintf(stderr, "Failed to connect to card: %s\n", sc_strerror(r));
return 1;
}
if (verbose)
printf("Using card driver %s.\n", card->driver->name);
if (do_lock) {
r = sc_lock(card);
if (r < 0) {
fprintf(stderr, "Failed to lock card: %s\n", sc_strerror(r));
sc_disconnect_card(card);
return 1;
}
}
*cardp = card;
return 0;
}
int
util_connect_card(sc_context_t *ctx, sc_card_t **cardp,
const char *reader_id, int do_wait, int verbose)
{
return util_connect_card_ex(ctx, cardp, reader_id, do_wait, 1, verbose);
}
void util_print_binary(FILE *f, const u8 *buf, int count)
{
int i;
for (i = 0; i < count; i++) {
unsigned char c = buf[i];
const char *format;
if (!isprint(c))
format = "\\x%02X";
else
format = "%c";
fprintf(f, format, c);
}
(void) fflush(f);
}
void util_hex_dump(FILE *f, const u8 *in, int len, const char *sep)
{
int i;
for (i = 0; i < len; i++) {
if (sep != NULL && i)
fprintf(f, "%s", sep);
fprintf(f, "%02X", in[i]);
}
}
void util_hex_dump_asc(FILE *f, const u8 *in, size_t count, int addr)
{
int lines = 0;
while (count) {
char ascbuf[17];
size_t i;
if (addr >= 0) {
fprintf(f, "%08X: ", addr);
addr += 16;
}
for (i = 0; i < count && i < 16; i++) {
fprintf(f, "%02X ", *in);
if (isprint(*in))
ascbuf[i] = *in;
else
ascbuf[i] = '.';
in++;
}
count -= i;
ascbuf[i] = 0;
for (; i < 16 && lines; i++)
fprintf(f, " ");
fprintf(f, "%s\n", ascbuf);
lines++;
}
}
NORETURN void
util_print_usage_and_die(const char *app_name, const struct option options[],
const char *option_help[], const char *args)
{
int i;
int header_shown = 0;
if (args)
printf("Usage: %s [OPTIONS] %s\n", app_name, args);
else
printf("Usage: %s [OPTIONS]\n", app_name);
for (i = 0; options[i].name; i++) {
char buf[40];
const char *arg_str;
/* Skip "hidden" options */
if (option_help[i] == NULL)
continue;
if (!header_shown++)
printf("Options:\n");
switch (options[i].has_arg) {
case 1:
arg_str = " <arg>";
break;
case 2:
arg_str = " [arg]";
break;
default:
arg_str = "";
break;
}
if (isascii(options[i].val) &&
isprint(options[i].val) && !isspace(options[i].val))
sprintf(buf, "-%c, --%s%s", options[i].val, options[i].name, arg_str);
else
sprintf(buf, " --%s%s", options[i].name, arg_str);
/* print the line - wrap if necessary */
if (strlen(buf) > 28) {
printf(" %s\n", buf);
buf[0] = '\0';
}
printf(" %-28s %s\n", buf, option_help[i]);
}
exit(2);
}
const char * util_acl_to_str(const sc_acl_entry_t *e)
{
static char line[80], buf[20];
unsigned int acl;
if (e == NULL)
return "N/A";
line[0] = 0;
while (e != NULL) {
acl = e->method;
switch (acl) {
case SC_AC_UNKNOWN:
return "N/A";
case SC_AC_NEVER:
return "NEVR";
case SC_AC_NONE:
return "NONE";
case SC_AC_CHV:
strcpy(buf, "CHV");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "%d", e->key_ref);
break;
case SC_AC_TERM:
strcpy(buf, "TERM");
break;
case SC_AC_PRO:
strcpy(buf, "PROT");
break;
case SC_AC_AUT:
strcpy(buf, "AUTH");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 4, "%d", e->key_ref);
break;
case SC_AC_SEN:
strcpy(buf, "Sec.Env. ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
case SC_AC_SCB:
strcpy(buf, "Sec.ControlByte ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "Ox%X", e->key_ref);
break;
case SC_AC_IDA:
strcpy(buf, "PKCS#15 AuthID ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
default:
strcpy(buf, "????");
break;
}
strcat(line, buf);
strcat(line, " ");
e = e->next;
}
line[strlen(line)-1] = 0; /* get rid of trailing space */
return line;
}
NORETURN void
util_fatal(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "error: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\nAborting.\n");
va_end(ap);
sc_notify_close();
exit(1);
}
void
util_error(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "error: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
}
void
util_warn(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "warning: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
}
int
util_getpass (char **lineptr, size_t *len, FILE *stream)
{
#define MAX_PASS_SIZE 128
char *buf;
size_t i;
int ch = 0;
#ifndef _WIN32
struct termios old, new;
fflush(stdout);
if (tcgetattr (fileno (stdout), &old) != 0)
return -1;
new = old;
new.c_lflag &= ~ECHO;
if (tcsetattr (fileno (stdout), TCSAFLUSH, &new) != 0)
return -1;
#endif
buf = calloc(1, MAX_PASS_SIZE);
if (!buf)
return -1;
for (i = 0; i < MAX_PASS_SIZE - 1; i++) {
#ifndef _WIN32
ch = getchar();
#else
ch = _getch();
#endif
if (ch == 0 || ch == 3)
break;
if (ch == '\n' || ch == '\r')
break;
buf[i] = (char) ch;
}
#ifndef _WIN32
tcsetattr (fileno (stdout), TCSAFLUSH, &old);
fputs("\n", stdout);
#endif
if (ch == 0 || ch == 3) {
free(buf);
return -1;
}
if (*lineptr && (!len || *len < i+1)) {
free(*lineptr);
*lineptr = NULL;
}
if (*lineptr) {
memcpy(*lineptr,buf,i+1);
memset(buf, 0, MAX_PASS_SIZE);
free(buf);
} else {
*lineptr = buf;
if (len)
*len = MAX_PASS_SIZE;
}
return i;
}
size_t
util_get_pin(const char *input, const char **pin)
{
size_t inputlen = strlen(input);
size_t pinlen = 0;
if(inputlen > 4 && strncasecmp(input, "env:", 4) == 0) {
// Get a PIN from a environment variable
*pin = getenv(input + 4);
pinlen = *pin ? strlen(*pin) : 0;
} else {
//Just use the input
*pin = input;
pinlen = inputlen;
}
return pinlen;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_340_10 |
crossvul-cpp_data_good_2414_0 | /*
* symlink.c
*
* PURPOSE
* Symlink handling routines for the OSTA-UDF(tm) filesystem.
*
* COPYRIGHT
* This file is distributed under the terms of the GNU General Public
* License (GPL). Copies of the GPL can be obtained from:
* ftp://prep.ai.mit.edu/pub/gnu/GPL
* Each contributing author retains all rights to their own work.
*
* (C) 1998-2001 Ben Fennema
* (C) 1999 Stelias Computing Inc
*
* HISTORY
*
* 04/16/99 blf Created.
*
*/
#include "udfdecl.h"
#include <linux/uaccess.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/time.h>
#include <linux/mm.h>
#include <linux/stat.h>
#include <linux/pagemap.h>
#include <linux/buffer_head.h>
#include "udf_i.h"
static int udf_pc_to_char(struct super_block *sb, unsigned char *from,
int fromlen, unsigned char *to, int tolen)
{
struct pathComponent *pc;
int elen = 0;
int comp_len;
unsigned char *p = to;
/* Reserve one byte for terminating \0 */
tolen--;
while (elen < fromlen) {
pc = (struct pathComponent *)(from + elen);
elen += sizeof(struct pathComponent);
switch (pc->componentType) {
case 1:
/*
* Symlink points to some place which should be agreed
* upon between originator and receiver of the media. Ignore.
*/
if (pc->lengthComponentIdent > 0) {
elen += pc->lengthComponentIdent;
break;
}
/* Fall through */
case 2:
if (tolen == 0)
return -ENAMETOOLONG;
p = to;
*p++ = '/';
tolen--;
break;
case 3:
if (tolen < 3)
return -ENAMETOOLONG;
memcpy(p, "../", 3);
p += 3;
tolen -= 3;
break;
case 4:
if (tolen < 2)
return -ENAMETOOLONG;
memcpy(p, "./", 2);
p += 2;
tolen -= 2;
/* that would be . - just ignore */
break;
case 5:
elen += pc->lengthComponentIdent;
if (elen > fromlen)
return -EIO;
comp_len = udf_get_filename(sb, pc->componentIdent,
pc->lengthComponentIdent,
p, tolen);
p += comp_len;
tolen -= comp_len;
if (tolen == 0)
return -ENAMETOOLONG;
*p++ = '/';
tolen--;
break;
}
}
if (p > to + 1)
p[-1] = '\0';
else
p[0] = '\0';
return 0;
}
static int udf_symlink_filler(struct file *file, struct page *page)
{
struct inode *inode = page->mapping->host;
struct buffer_head *bh = NULL;
unsigned char *symlink;
int err;
unsigned char *p = kmap(page);
struct udf_inode_info *iinfo;
uint32_t pos;
/* We don't support symlinks longer than one block */
if (inode->i_size > inode->i_sb->s_blocksize) {
err = -ENAMETOOLONG;
goto out_unmap;
}
iinfo = UDF_I(inode);
pos = udf_block_map(inode, 0);
down_read(&iinfo->i_data_sem);
if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) {
symlink = iinfo->i_ext.i_data + iinfo->i_lenEAttr;
} else {
bh = sb_bread(inode->i_sb, pos);
if (!bh) {
err = -EIO;
goto out_unlock_inode;
}
symlink = bh->b_data;
}
err = udf_pc_to_char(inode->i_sb, symlink, inode->i_size, p, PAGE_SIZE);
brelse(bh);
if (err)
goto out_unlock_inode;
up_read(&iinfo->i_data_sem);
SetPageUptodate(page);
kunmap(page);
unlock_page(page);
return 0;
out_unlock_inode:
up_read(&iinfo->i_data_sem);
SetPageError(page);
out_unmap:
kunmap(page);
unlock_page(page);
return err;
}
/*
* symlinks can't do much...
*/
const struct address_space_operations udf_symlink_aops = {
.readpage = udf_symlink_filler,
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2414_0 |
crossvul-cpp_data_good_339_0 | /*
* card-cac.c: Support for CAC from NIST SP800-73
* card-default.c: Support for cards with no driver
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
* Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov>
* Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com>
* Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com>
* Copyright (C) 2016 - 2018, Red Hat, Inc.
*
* CAC driver author: Robert Relyea <rrelyea@redhat.com>
* Further work: Jakub Jelen <jjelen@redhat.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <ctype.h>
#include <fcntl.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <io.h>
#else
#include <unistd.h>
#endif
#ifdef ENABLE_OPENSSL
/* openssl only needed for card administration */
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#endif /* ENABLE_OPENSSL */
#include "internal.h"
#include "simpletlv.h"
#include "cardctl.h"
#ifdef ENABLE_ZLIB
#include "compression.h"
#endif
#include "iso7816.h"
#define CAC_MAX_SIZE 4096 /* arbitrary, just needs to be 'large enough' */
/*
* CAC hardware and APDU constants
*/
#define CAC_MAX_CHUNK_SIZE 240
#define CAC_INS_SIGN_DECRYPT 0x42 /* A crypto operation */
#define CAC_INS_READ_FILE 0x52 /* read a TL or V file */
#define CAC_INS_GET_ACR 0x4c
#define CAC_INS_GET_PROPERTIES 0x56
#define CAC_P1_STEP 0x80
#define CAC_P1_FINAL 0x00
#define CAC_FILE_TAG 1
#define CAC_FILE_VALUE 2
/* TAGS in a TL file */
#define CAC_TAG_CERTIFICATE 0x70
#define CAC_TAG_CERTINFO 0x71
#define CAC_TAG_MSCUID 0x72
#define CAC_TAG_CUID 0xF0
#define CAC_TAG_CC_VERSION_NUMBER 0xF1
#define CAC_TAG_GRAMMAR_VERION_NUMBER 0xF2
#define CAC_TAG_CARDURL 0xF3
#define CAC_TAG_PKCS15 0xF4
#define CAC_TAG_ACCESS_CONTROL 0xF6
#define CAC_TAG_DATA_MODEL 0xF5
#define CAC_TAG_CARD_APDU 0xF7
#define CAC_TAG_REDIRECTION 0xFA
#define CAC_TAG_CAPABILITY_TUPLES 0xFB
#define CAC_TAG_STATUS_TUPLES 0xFC
#define CAC_TAG_NEXT_CCC 0xFD
#define CAC_TAG_ERROR_CODES 0xFE
#define CAC_TAG_APPLET_FAMILY 0x01
#define CAC_TAG_NUMBER_APPLETS 0x94
#define CAC_TAG_APPLET_ENTRY 0x93
#define CAC_TAG_APPLET_AID 0x92
#define CAC_TAG_APPLET_INFORMATION 0x01
#define CAC_TAG_NUMBER_OF_OBJECTS 0x40
#define CAC_TAG_TV_BUFFER 0x50
#define CAC_TAG_PKI_OBJECT 0x51
#define CAC_TAG_OBJECT_ID 0x41
#define CAC_TAG_BUFFER_PROPERTIES 0x42
#define CAC_TAG_PKI_PROPERTIES 0x43
#define CAC_APP_TYPE_GENERAL 0x01
#define CAC_APP_TYPE_SKI 0x02
#define CAC_APP_TYPE_PKI 0x04
#define CAC_ACR_ACR 0x00
#define CAC_ACR_APPLET_OBJECT 0x10
#define CAC_ACR_AMP 0x20
#define CAC_ACR_SERVICE 0x21
/* hardware data structures (returned in the CCC) */
/* part of the card_url */
typedef struct cac_access_profile {
u8 GCACR_listID;
u8 GCACR_readTagListACRID;
u8 GCACR_updatevalueACRID;
u8 GCACR_readvalueACRID;
u8 GCACR_createACRID;
u8 GCACR_deleteACRID;
u8 CryptoACR_listID;
u8 CryptoACR_getChallengeACRID;
u8 CryptoACR_internalAuthenicateACRID;
u8 CryptoACR_pkiComputeACRID;
u8 CryptoACR_readTagListACRID;
u8 CryptoACR_updatevalueACRID;
u8 CryptoACR_readvalueACRID;
u8 CryptoACR_createACRID;
u8 CryptoACR_deleteACRID;
} cac_access_profile_t;
/* part of the card url */
typedef struct cac_access_key_info {
u8 keyFileID[2];
u8 keynumber;
} cac_access_key_info_t;
typedef struct cac_card_url {
u8 rid[5];
u8 cardApplicationType;
u8 objectID[2];
u8 applicationID[2];
cac_access_profile_t accessProfile;
u8 pinID; /* not used for VM cards */
cac_access_key_info_t accessKeyInfo; /* not used for VM cards */
u8 keyCryptoAlgorithm; /* not used for VM cards */
} cac_card_url_t;
typedef struct cac_cuid {
u8 gsc_rid[5];
u8 manufacturer_id;
u8 card_type;
u8 card_id;
} cac_cuid_t;
/* data structures to store meta data about CAC objects */
typedef struct cac_object {
const char *name;
int fd;
sc_path_t path;
} cac_object_t;
#define CAC_MAX_OBJECTS 16
typedef struct {
/* OID has two bytes */
unsigned char oid[2];
/* Format is NOT SimpleTLV? */
unsigned char simpletlv;
/* Is certificate object and private key is initialized */
unsigned char privatekey;
} cac_properties_object_t;
typedef struct {
unsigned int num_objects;
cac_properties_object_t objects[CAC_MAX_OBJECTS];
} cac_properties_t;
/*
* Flags for Current Selected Object Type
* CAC files are TLV files, with TL and V separated. For generic
* containers we reintegrate the TL anv V portions into a single
* file to read. Certs are also TLV files, but pkcs15 wants the
* actual certificate. At select time we know the patch which tells
* us what time of files we want to read. We remember that type
* so that read_binary can do the appropriate processing.
*/
#define CAC_OBJECT_TYPE_CERT 1
#define CAC_OBJECT_TYPE_TLV_FILE 4
#define CAC_OBJECT_TYPE_GENERIC 5
/*
* CAC private data per card state
*/
typedef struct cac_private_data {
int object_type; /* select set this so we know how to read the file */
int cert_next; /* index number for the next certificate found in the list */
u8 *cache_buf; /* cached version of the currently selected file */
size_t cache_buf_len; /* length of the cached selected file */
int cached; /* is the cached selected file valid */
cac_cuid_t cuid; /* card unique ID from the CCC */
u8 *cac_id; /* card serial number */
size_t cac_id_len; /* card serial number len */
list_t pki_list; /* list of pki containers */
cac_object_t *pki_current; /* current pki object _ctl function */
list_t general_list; /* list of general containers */
cac_object_t *general_current; /* current object for _ctl function */
sc_path_t *aca_path; /* ACA path to be selected before pin verification */
} cac_private_data_t;
#define CAC_DATA(card) ((cac_private_data_t*)card->drv_data)
int cac_list_compare_path(const void *a, const void *b)
{
if (a == NULL || b == NULL)
return 1;
return memcmp( &((cac_object_t *) a)->path,
&((cac_object_t *) b)->path, sizeof(sc_path_t));
}
/* For SimCList autocopy, we need to know the size of the data elements */
size_t cac_list_meter(const void *el) {
return sizeof(cac_object_t);
}
static cac_private_data_t *cac_new_private_data(void)
{
cac_private_data_t *priv;
priv = calloc(1, sizeof(cac_private_data_t));
if (!priv)
return NULL;
list_init(&priv->pki_list);
list_attributes_comparator(&priv->pki_list, cac_list_compare_path);
list_attributes_copy(&priv->pki_list, cac_list_meter, 1);
list_init(&priv->general_list);
list_attributes_comparator(&priv->general_list, cac_list_compare_path);
list_attributes_copy(&priv->general_list, cac_list_meter, 1);
/* set other fields as appropriate */
return priv;
}
static void cac_free_private_data(cac_private_data_t *priv)
{
free(priv->cac_id);
free(priv->cache_buf);
free(priv->aca_path);
list_destroy(&priv->pki_list);
list_destroy(&priv->general_list);
free(priv);
return;
}
static int cac_add_object_to_list(list_t *list, const cac_object_t *object)
{
if (list_append(list, object) < 0)
return SC_ERROR_UNKNOWN;
return SC_SUCCESS;
}
/*
* Set up the normal CAC paths
*/
#define CAC_TO_AID(x) x, sizeof(x)-1
#define CAC_2_RID "\xA0\x00\x00\x01\x16"
#define CAC_1_RID "\xA0\x00\x00\x00\x79"
static const sc_path_t cac_ACA_Path = {
"", 0,
0,0,SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x10\x00") }
};
static const sc_path_t cac_CCC_Path = {
"", 0,
0,0,SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_2_RID "\xDB\x00") }
};
#define MAX_CAC_SLOTS 16 /* Maximum number of slots is 16 now */
/* default certificate labels for the CAC card */
static const char *cac_labels[MAX_CAC_SLOTS] = {
"CAC ID Certificate",
"CAC Email Signature Certificate",
"CAC Email Encryption Certificate",
"CAC Cert 4",
"CAC Cert 5",
"CAC Cert 6",
"CAC Cert 7",
"CAC Cert 8",
"CAC Cert 9",
"CAC Cert 10",
"CAC Cert 11",
"CAC Cert 12",
"CAC Cert 13",
"CAC Cert 14",
"CAC Cert 15",
"CAC Cert 16"
};
/* template for a CAC pki object */
static const cac_object_t cac_cac_pki_obj = {
"CAC Certificate", 0x0, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x01\x00") } }
};
/* template for emulated cuid */
static const cac_cuid_t cac_cac_cuid = {
{ 0xa0, 0x00, 0x00, 0x00, 0x79 },
2, 2, 0
};
/*
* CAC general objects defined in 4.3.1.2 of CAC Applet Developer Guide Version 1.0.
* doubles as a source for CAC-2 labels.
*/
static const cac_object_t cac_objects[] = {
{ "Person Instance", 0x200, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\x00") }}},
{ "Personnel", 0x201, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\x01") }}},
{ "Benefits", 0x202, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\x02") }}},
{ "Other Benefits", 0x203, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\x03") }}},
{ "PKI Credential", 0x2FD, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\xFD") }}},
{ "PKI Certificate", 0x2FE, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\xFE") }}},
};
static const int cac_object_count = sizeof(cac_objects)/sizeof(cac_objects[0]);
/*
* use the object id to find our object info on the object in our CAC-1 list
*/
static const cac_object_t *cac_find_obj_by_id(unsigned short object_id)
{
int i;
for (i = 0; i < cac_object_count; i++) {
if (cac_objects[i].fd == object_id) {
return &cac_objects[i];
}
}
return NULL;
}
/*
* Lookup the path in the pki list to see if it is a cert path
*/
static int cac_is_cert(cac_private_data_t * priv, const sc_path_t *in_path)
{
cac_object_t test_obj;
test_obj.path = *in_path;
test_obj.path.index = 0;
test_obj.path.count = 0;
return (list_contains(&priv->pki_list, &test_obj) != 0);
}
/*
* Send a command and receive data.
*
* A caller may provide a buffer, and length to read. If not provided,
* an internal 4096 byte buffer is used, and a copy is returned to the
* caller. that need to be freed by the caller.
*
* modelled after a similar function in card-piv.c
*/
static int cac_apdu_io(sc_card_t *card, int ins, int p1, int p2,
const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf,
size_t * recvbuflen)
{
int r;
sc_apdu_t apdu;
u8 rbufinitbuf[CAC_MAX_SIZE];
u8 *rbuf;
size_t rbuflen;
unsigned int apdu_case = SC_APDU_CASE_1;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u\n",
ins, p1, p2, sendbuflen, card->max_send_size,
card->max_recv_size);
rbuf = rbufinitbuf;
rbuflen = sizeof(rbufinitbuf);
/* if caller provided a buffer and length */
if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) {
rbuf = *recvbuf;
rbuflen = *recvbuflen;
}
if (recvbuf) {
if (sendbuf)
apdu_case = SC_APDU_CASE_4_SHORT;
else
apdu_case = SC_APDU_CASE_2_SHORT;
} else if (sendbuf)
apdu_case = SC_APDU_CASE_3_SHORT;
sc_format_apdu(card, &apdu, apdu_case, ins, p1, p2);
apdu.lc = sendbuflen;
apdu.datalen = sendbuflen;
apdu.data = sendbuf;
if (recvbuf) {
apdu.resp = rbuf;
apdu.le = (rbuflen > 255) ? 255 : rbuflen;
apdu.resplen = rbuflen;
} else {
apdu.resp = rbuf;
apdu.le = 0;
apdu.resplen = 0;
}
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p",
apdu.flags, apdu.le, apdu.resplen, apdu.resp);
/* with new adpu.c and chaining, this actually reads the whole object */
r = sc_transmit_apdu(card, &apdu);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"result r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x",
r, apdu.resplen, apdu.sw1, apdu.sw2);
if (r < 0) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,"Transmit failed");
goto err;
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r < 0) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card returned error ");
goto err;
}
if (recvbuflen) {
if (recvbuf && *recvbuf == NULL) {
*recvbuf = malloc(apdu.resplen);
if (*recvbuf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
memcpy(*recvbuf, rbuf, apdu.resplen);
}
*recvbuflen = apdu.resplen;
r = *recvbuflen;
}
err:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
/*
* Get ACR of currently ACA applet identified by the acr_type
* 5.3.3.5 Get ACR APDU
*/
static int
cac_get_acr(sc_card_t *card, int acr_type, u8 **out_buf, size_t *out_len)
{
u8 *out = NULL;
/* XXX assuming it will not be longer than 255 B */
size_t len = 256;
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* for simplicity we support only ACR without arguments now */
if (acr_type != 0x00 && acr_type != 0x10
&& acr_type != 0x20 && acr_type != 0x21) {
return SC_ERROR_INVALID_ARGUMENTS;
}
r = cac_apdu_io(card, CAC_INS_GET_ACR, acr_type, 0, NULL, 0, &out, &len);
if (len == 0) {
r = SC_ERROR_FILE_NOT_FOUND;
}
if (r < 0)
goto fail;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"got %"SC_FORMAT_LEN_SIZE_T"u bytes out=%p", len, out);
*out_len = len;
*out_buf = out;
return SC_SUCCESS;
fail:
if (out)
free(out);
*out_buf = NULL;
*out_len = 0;
return r;
}
/*
* Read a CAC TLV file. Parameters specify if the TLV file is TL (Tag/Length) file or a V (value) file
*/
#define HIGH_BYTE_OF_SHORT(x) (((x)>> 8) & 0xff)
#define LOW_BYTE_OF_SHORT(x) ((x) & 0xff)
static int cac_read_file(sc_card_t *card, int file_type, u8 **out_buf, size_t *out_len)
{
u8 params[2];
u8 count[2];
u8 *out = NULL;
u8 *out_ptr;
size_t offset = 0;
size_t size = 0;
size_t left = 0;
size_t len;
int r;
params[0] = file_type;
params[1] = 2;
/* get the size */
len = sizeof(count);
out_ptr = count;
r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, ¶ms[0], sizeof(params), &out_ptr, &len);
if (len == 0) {
r = SC_ERROR_FILE_NOT_FOUND;
}
if (r < 0)
goto fail;
left = size = lebytes2ushort(count);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"got %"SC_FORMAT_LEN_SIZE_T"u bytes out_ptr=%p count&=%p count[0]=0x%02x count[1]=0x%02x, len=0x%04"SC_FORMAT_LEN_SIZE_T"x (%"SC_FORMAT_LEN_SIZE_T"u)",
len, out_ptr, &count, count[0], count[1], size, size);
out = out_ptr = malloc(size);
if (out == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto fail;
}
for (offset += 2; left > 0; offset += len, left -= len, out_ptr += len) {
len = MIN(left, CAC_MAX_CHUNK_SIZE);
params[1] = len;
r = cac_apdu_io(card, CAC_INS_READ_FILE, HIGH_BYTE_OF_SHORT(offset), LOW_BYTE_OF_SHORT(offset),
¶ms[0], sizeof(params), &out_ptr, &len);
/* if there is no data, assume there is no file */
if (len == 0) {
r = SC_ERROR_FILE_NOT_FOUND;
}
if (r < 0) {
goto fail;
}
}
*out_len = size;
*out_buf = out;
return SC_SUCCESS;
fail:
if (out)
free(out);
*out_len = 0;
return r;
}
/*
* Callers of this may be expecting a certificate,
* select file will have saved the object type for us
* as well as set that we want the cert from the object.
*/
static int cac_read_binary(sc_card_t *card, unsigned int idx,
unsigned char *buf, size_t count, unsigned long flags)
{
cac_private_data_t * priv = CAC_DATA(card);
int r = 0;
u8 *tl = NULL, *val = NULL;
u8 *tl_ptr, *val_ptr, *tlv_ptr, *tl_start;
u8 *cert_ptr;
size_t tl_len, val_len, tlv_len;
size_t len, tl_head_len, cert_len;
u8 cert_type, tag;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* if we didn't return it all last time, return the remainder */
if (priv->cached) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u",
idx, count);
if (idx > priv->cache_buf_len) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_END_REACHED);
}
len = MIN(count, priv->cache_buf_len-idx);
memcpy(buf, &priv->cache_buf[idx], len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, len);
}
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u",
idx, count);
if (priv->cache_buf) {
free(priv->cache_buf);
priv->cache_buf = NULL;
priv->cache_buf_len = 0;
}
if (priv->object_type <= 0)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL);
r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len);
if (r < 0) {
goto done;
}
r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len);
if (r < 0)
goto done;
switch (priv->object_type) {
case CAC_OBJECT_TYPE_TLV_FILE:
tlv_len = tl_len + val_len;
priv->cache_buf = malloc(tlv_len);
if (priv->cache_buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto done;
}
priv->cache_buf_len = tlv_len;
for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf;
tl_len >= 2 && tlv_len > 0;
val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) {
/* get the tag and the length */
tl_start = tl_ptr;
if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS)
break;
tl_head_len = (tl_ptr - tl_start);
sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr);
tlv_len -= tl_head_len;
tl_len -= tl_head_len;
/* don't crash on bad data */
if (val_len < len) {
len = val_len;
}
/* if we run out of return space, truncate */
if (tlv_len < len) {
len = tlv_len;
}
memcpy(tlv_ptr, val_ptr, len);
}
break;
case CAC_OBJECT_TYPE_CERT:
/* read file */
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
" obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)",
val_len, val_len);
cert_len = 0;
cert_ptr = NULL;
cert_type = 0;
for (tl_ptr = tl, val_ptr = val; tl_len >= 2;
val_len -= len, val_ptr += len, tl_len -= tl_head_len) {
tl_start = tl_ptr;
if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS)
break;
tl_head_len = tl_ptr - tl_start;
/* incomplete value */
if (val_len < len)
break;
if (tag == CAC_TAG_CERTIFICATE) {
cert_len = len;
cert_ptr = val_ptr;
}
if (tag == CAC_TAG_CERTINFO) {
if ((len >= 1) && (val_len >=1)) {
cert_type = *val_ptr;
}
}
if (tag == CAC_TAG_MSCUID) {
sc_log_hex(card->ctx, "MSCUID", val_ptr, len);
}
if ((val_len < len) || (tl_len < tl_head_len)) {
break;
}
}
/* if the info byte is 1, then the cert is compressed, decompress it */
if ((cert_type & 0x3) == 1) {
#ifdef ENABLE_ZLIB
r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len,
cert_ptr, cert_len, COMPRESSION_AUTO);
#else
sc_log(card->ctx, "CAC compression not supported, no zlib");
r = SC_ERROR_NOT_SUPPORTED;
#endif
if (r)
goto done;
} else if (cert_len > 0) {
priv->cache_buf = malloc(cert_len);
if (priv->cache_buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto done;
}
priv->cache_buf_len = cert_len;
memcpy(priv->cache_buf, cert_ptr, cert_len);
} else {
sc_log(card->ctx, "Can't read zero-length certificate");
goto done;
}
break;
case CAC_OBJECT_TYPE_GENERIC:
/* TODO
* We have some two buffers in unknown encoding that we
* need to present in PKCS#15 layer.
*/
default:
/* Unknown object type */
sc_log(card->ctx, "Unknown object type: %x", priv->object_type);
r = SC_ERROR_INTERNAL;
goto done;
}
/* OK we've read the data, now copy the required portion out to the callers buffer */
priv->cached = 1;
len = MIN(count, priv->cache_buf_len-idx);
memcpy(buf, &priv->cache_buf[idx], len);
r = len;
done:
if (tl)
free(tl);
if (val)
free(val);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
/* CAC driver is read only */
static int cac_write_binary(sc_card_t *card, unsigned int idx,
const u8 *buf, size_t count, unsigned long flags)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED);
}
/* initialize getting a list and return the number of elements in the list */
static int cac_get_init_and_get_count(list_t *list, cac_object_t **entry, int *countp)
{
*countp = list_size(list);
list_iterator_start(list);
*entry = list_iterator_next(list);
return SC_SUCCESS;
}
/* finalize the list iterator */
static int cac_final_iterator(list_t *list)
{
list_iterator_stop(list);
return SC_SUCCESS;
}
/* fill in the obj_info for the current object on the list and advance to the next object */
static int cac_fill_object_info(list_t *list, cac_object_t **entry, sc_pkcs15_data_info_t *obj_info)
{
memset(obj_info, 0, sizeof(sc_pkcs15_data_info_t));
if (*entry == NULL) {
return SC_ERROR_FILE_END_REACHED;
}
obj_info->path = (*entry)->path;
obj_info->path.count = CAC_MAX_SIZE-1; /* read something from the object */
obj_info->id.value[0] = ((*entry)->fd >> 8) & 0xff;
obj_info->id.value[1] = (*entry)->fd & 0xff;
obj_info->id.len = 2;
strncpy(obj_info->app_label, (*entry)->name, SC_PKCS15_MAX_LABEL_SIZE-1);
*entry = list_iterator_next(list);
return SC_SUCCESS;
}
static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial)
{
cac_private_data_t * priv = CAC_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);
if (card->serialnr.len) {
*serial = card->serialnr;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
if (priv->cac_id_len) {
serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR);
memcpy(serial->value, priv->cac_id, serial->len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND);
}
static int cac_get_ACA_path(sc_card_t *card, sc_path_t *path)
{
cac_private_data_t * priv = CAC_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);
if (priv->aca_path) {
*path = *priv->aca_path;
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
static int cac_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
cac_private_data_t * priv = CAC_DATA(card);
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx, "cmd=%ld ptr=%p", cmd, ptr);
if (priv == NULL) {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
}
switch(cmd) {
case SC_CARDCTL_CAC_GET_ACA_PATH:
return cac_get_ACA_path(card, (sc_path_t *) ptr);
case SC_CARDCTL_GET_SERIALNR:
return cac_get_serial_nr_from_CUID(card, (sc_serial_number_t *) ptr);
case SC_CARDCTL_CAC_INIT_GET_GENERIC_OBJECTS:
return cac_get_init_and_get_count(&priv->general_list, &priv->general_current, (int *)ptr);
case SC_CARDCTL_CAC_INIT_GET_CERT_OBJECTS:
return cac_get_init_and_get_count(&priv->pki_list, &priv->pki_current, (int *)ptr);
case SC_CARDCTL_CAC_GET_NEXT_GENERIC_OBJECT:
return cac_fill_object_info(&priv->general_list, &priv->general_current, (sc_pkcs15_data_info_t *)ptr);
case SC_CARDCTL_CAC_GET_NEXT_CERT_OBJECT:
return cac_fill_object_info(&priv->pki_list, &priv->pki_current, (sc_pkcs15_data_info_t *)ptr);
case SC_CARDCTL_CAC_FINAL_GET_GENERIC_OBJECTS:
return cac_final_iterator(&priv->general_list);
case SC_CARDCTL_CAC_FINAL_GET_CERT_OBJECTS:
return cac_final_iterator(&priv->pki_list);
}
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
static int cac_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
{
/* CAC requires 8 byte response */
u8 rbuf[8];
u8 *rbufp = &rbuf[0];
size_t out_len = sizeof rbuf;
int r;
LOG_FUNC_CALLED(card->ctx);
r = cac_apdu_io(card, 0x84, 0x00, 0x00, NULL, 0, &rbufp, &out_len);
LOG_TEST_RET(card->ctx, r, "Could not get challenge");
if (len < out_len) {
out_len = len;
}
memcpy(rnd, rbuf, out_len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, (int) out_len);
}
static int cac_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num)
{
int r = SC_SUCCESS;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"flags=%08lx op=%d alg=%d algf=%08x algr=%08x kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u\n",
env->flags, env->operation, env->algorithm,
env->algorithm_flags, env->algorithm_ref, env->key_ref[0],
env->key_ref_len);
if (env->algorithm != SC_ALGORITHM_RSA) {
r = SC_ERROR_NO_CARD_SUPPORT;
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int cac_restore_security_env(sc_card_t *card, int se_num)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
static int cac_rsa_op(sc_card_t *card,
const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
int r;
u8 *outp, *rbuf;
size_t rbuflen, outplen;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"datalen=%"SC_FORMAT_LEN_SIZE_T"u outlen=%"SC_FORMAT_LEN_SIZE_T"u\n",
datalen, outlen);
outp = out;
outplen = outlen;
/* Not strictly necessary. This code requires the caller to have selected the correct PKI container
* and authenticated to that container with the verifyPin command... All of this under the reader lock.
* The PKCS #15 higher level driver code does all this correctly (it's the same for all cards, just
* different sets of APDU's that need to be called), so this call is really a little bit of paranoia */
r = sc_lock(card);
if (r != SC_SUCCESS)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
rbuf = NULL;
rbuflen = 0;
for (; datalen > CAC_MAX_CHUNK_SIZE; data += CAC_MAX_CHUNK_SIZE, datalen -= CAC_MAX_CHUNK_SIZE) {
r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_STEP, 0,
data, CAC_MAX_CHUNK_SIZE, &rbuf, &rbuflen);
if (r < 0) {
break;
}
if (rbuflen != 0) {
int n = MIN(rbuflen, outplen);
memcpy(outp,rbuf, n);
outp += n;
outplen -= n;
}
free(rbuf);
rbuf = NULL;
rbuflen = 0;
}
if (r < 0) {
goto err;
}
rbuf = NULL;
rbuflen = 0;
r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_FINAL, 0, data, datalen, &rbuf, &rbuflen);
if (r < 0) {
goto err;
}
if (rbuflen != 0) {
int n = MIN(rbuflen, outplen);
memcpy(outp,rbuf, n);
/*outp += n; unused */
outplen -= n;
}
free(rbuf);
rbuf = NULL;
r = outlen-outplen;
err:
sc_unlock(card);
if (r < 0) {
sc_mem_clear(out, outlen);
}
if (rbuf) {
free(rbuf);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
static int cac_compute_signature(sc_card_t *card,
const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen));
}
static int cac_decipher(sc_card_t *card,
const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen));
}
static int cac_parse_properties_object(sc_card_t *card, u8 type,
u8 *data, size_t data_len, cac_properties_object_t *object)
{
size_t len;
u8 *val, *val_end, tag;
int parsed = 0;
if (data_len < 11)
return -1;
/* Initilize: non-PKI applet */
object->privatekey = 0;
val = data;
val_end = data + data_len;
for (; val < val_end; val += len) {
/* get the tag and the length */
if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS)
break;
switch (tag) {
case CAC_TAG_OBJECT_ID:
if (len != 2) {
sc_log(card->ctx, "TAG: Object ID: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Object ID = 0x%02x 0x%02x", val[0], val[1]);
memcpy(&object->oid, val, 2);
parsed++;
break;
case CAC_TAG_BUFFER_PROPERTIES:
if (len != 5) {
sc_log(card->ctx, "TAG: Buffer Properties: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
/* First byte is "Type of Tag Supported" */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Buffer Properties: Type of Tag Supported = 0x%02x",
val[0]);
object->simpletlv = val[0];
parsed++;
break;
case CAC_TAG_PKI_PROPERTIES:
/* 4th byte is "Private Key Initialized" */
if (len != 4) {
sc_log(card->ctx, "TAG: PKI Properties: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
if (type != CAC_TAG_PKI_OBJECT) {
sc_log(card->ctx, "TAG: PKI Properties outside of PKI Object");
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: PKI Properties: Private Key Initialized = 0x%02x",
val[2]);
object->privatekey = val[2];
parsed++;
break;
default:
/* ignore tags we don't understand */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Unknown (0x%02x)",tag );
break;
}
}
if (parsed < 2)
return SC_ERROR_INVALID_DATA;
return SC_SUCCESS;
}
static int cac_get_properties(sc_card_t *card, cac_properties_t *prop)
{
u8 *rbuf = NULL;
size_t rbuflen = 0, len;
u8 *val, *val_end, tag;
size_t i = 0;
int r;
prop->num_objects = 0;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
r = cac_apdu_io(card, CAC_INS_GET_PROPERTIES, 0x01, 0x00, NULL, 0,
&rbuf, &rbuflen);
if (r < 0)
return r;
val = rbuf;
val_end = val + rbuflen;
for (; val < val_end; val += len) {
/* get the tag and the length */
if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS)
break;
switch (tag) {
case CAC_TAG_APPLET_INFORMATION:
if (len != 5) {
sc_log(card->ctx, "TAG: Applet Information: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Applet Information: Family: 0x%0x", val[0]);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
" Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x",
val[1], val[2], val[3], val[4]);
break;
case CAC_TAG_NUMBER_OF_OBJECTS:
if (len != 1) {
sc_log(card->ctx, "TAG: Num objects: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Num objects = %hhd", *val);
/* make sure we do not overrun buffer */
prop->num_objects = MIN(val[0], CAC_MAX_OBJECTS);
break;
case CAC_TAG_TV_BUFFER:
if (len != 17) {
sc_log(card->ctx, "TAG: TV Object: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: TV Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i);
if (i >= CAC_MAX_OBJECTS) {
free(rbuf);
return SC_SUCCESS;
}
if (cac_parse_properties_object(card, tag, val, len,
&prop->objects[i]) == SC_SUCCESS)
i++;
break;
case CAC_TAG_PKI_OBJECT:
if (len != 17) {
sc_log(card->ctx, "TAG: PKI Object: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: PKI Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i);
if (i >= CAC_MAX_OBJECTS) {
free(rbuf);
return SC_SUCCESS;
}
if (cac_parse_properties_object(card, tag, val, len,
&prop->objects[i]) == SC_SUCCESS)
i++;
break;
default:
/* ignore tags we don't understand */
sc_log(card->ctx, "TAG: Unknown (0x%02x), len=%"
SC_FORMAT_LEN_SIZE_T"u", tag, len);
break;
}
}
free(rbuf);
/* sanity */
if (i != prop->num_objects)
sc_log(card->ctx, "The announced number of objects (%u) "
"did not match reality (%"SC_FORMAT_LEN_SIZE_T"u)",
prop->num_objects, i);
prop->num_objects = i;
return SC_SUCCESS;
}
/*
* CAC cards use SC_PATH_SELECT_OBJECT_ID rather than SC_PATH_SELECT_FILE_ID. In order to use more
* of the PKCS #15 structure, we call the selection SC_PATH_SELECT_FILE_ID, but we set p1 to 2 instead
* of 0. Also cac1 does not do any FCI, but it doesn't understand not selecting it. It returns invalid INS
* if it doesn't like anything about the select, so we always 'request' FCI for CAC1
*
* The rest is just copied from iso7816_select_file
*/
static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out, int type)
{
struct sc_context *ctx;
struct sc_apdu apdu;
unsigned char buf[SC_MAX_APDU_BUFFER_SIZE];
unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
int r, pathlen, pathtype;
struct sc_file *file = NULL;
cac_private_data_t * priv = CAC_DATA(card);
assert(card != NULL && in_path != NULL);
ctx = card->ctx;
SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE);
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
pathtype = in_path->type;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)",
in_path->aid.value[0], in_path->aid.value[1],
in_path->aid.value[2], in_path->aid.value[3],
in_path->aid.value[4], in_path->aid.value[5],
in_path->aid.value[6], in_path->aid.len, in_path->value[0],
in_path->value[1], in_path->value[2], in_path->value[3],
in_path->len, in_path->type, in_path->type);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n",
file_out, in_path->index, in_path->count);
/* Sigh, sc_key_select expects paths to keys to have specific formats. There is no override.
* we have to add some bytes to the path to make it happy. A better fix would be to give sc_key_file
* a flag that says 'no, really this path is fine'. We only need to do this for private keys */
if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) {
if (pathlen > 2) {
path += 2;
pathlen -= 2;
}
}
/* CAC has multiple different type of objects that aren't PKCS #15. When we read
* them we need convert them to something PKCS #15 would understand. Find the object
* and object type here:
*/
if (priv) { /* don't record anything if we haven't been initialized yet */
priv->object_type = CAC_OBJECT_TYPE_GENERIC;
if (cac_is_cert(priv, in_path)) {
priv->object_type = CAC_OBJECT_TYPE_CERT;
}
/* forget any old cached values */
if (priv->cache_buf) {
free(priv->cache_buf);
priv->cache_buf = NULL;
}
priv->cache_buf_len = 0;
priv->cached = 0;
}
if (in_path->aid.len) {
if (!pathlen) {
memcpy(path, in_path->aid.value, in_path->aid.len);
pathlen = in_path->aid.len;
pathtype = SC_PATH_TYPE_DF_NAME;
} else {
/* First, select the application */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" );
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0);
apdu.data = in_path->aid.value;
apdu.datalen = in_path->aid.len;
apdu.lc = in_path->aid.len;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r)
LOG_FUNC_RETURN(ctx, r);
}
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0);
switch (pathtype) {
/* ideally we would had SC_PATH_TYPE_OBJECT_ID and add code to the iso7816 select.
* Unfortunately we'd also need to update the caching code as well. For now just
* use FILE_ID and change p1 here */
case SC_PATH_TYPE_FILE_ID:
apdu.p1 = 2;
if (pathlen != 2)
return SC_ERROR_INVALID_ARGUMENTS;
break;
case SC_PATH_TYPE_DF_NAME:
apdu.p1 = 4;
break;
default:
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
}
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256;
if (file_out != NULL) {
apdu.p2 = 0; /* first record, return FCI */
}
else {
apdu.p2 = 0x0C;
}
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, r, "APDU transmit failed");
if (file_out == NULL) {
/* For some cards 'SELECT' can be only with request to return FCI/FCP. */
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86) {
apdu.p2 = 0x00;
apdu.resplen = sizeof(buf);
if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS)
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
}
if (apdu.sw1 == 0x61)
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
LOG_FUNC_RETURN(ctx, r);
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r)
LOG_FUNC_RETURN(ctx, r);
/* This needs to come after the applet selection */
if (priv && in_path->len >= 2) {
/* get applet properties to know if we can treat the
* buffer as SimpleLTV and if we have PKI applet.
*
* Do this only if we select applets for reading
* (not during driver initialization)
*/
cac_properties_t prop;
size_t i = -1;
r = cac_get_properties(card, &prop);
if (r == SC_SUCCESS) {
for (i = 0; i < prop.num_objects; i++) {
sc_log(card->ctx, "Searching for our OID: 0x%02x 0x%02x = 0x%02x 0x%02x",
prop.objects[i].oid[0], prop.objects[i].oid[1],
in_path->value[0], in_path->value[1]);
if (memcmp(prop.objects[i].oid,
in_path->value, 2) == 0)
break;
}
}
if (i < prop.num_objects) {
if (prop.objects[i].privatekey)
priv->object_type = CAC_OBJECT_TYPE_CERT;
else if (prop.objects[i].simpletlv == 0)
priv->object_type = CAC_OBJECT_TYPE_TLV_FILE;
}
}
/* CAC cards never return FCI, fake one */
file = sc_file_new();
if (file == NULL)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
file->path = *in_path;
file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */
*file_out = file;
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out)
{
return cac_select_file_by_type(card, in_path, file_out, card->type);
}
static int cac_finish(sc_card_t *card)
{
cac_private_data_t * priv = CAC_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (priv) {
cac_free_private_data(priv);
}
return SC_SUCCESS;
}
/* select the Card Capabilities Container on CAC-2 */
static int cac_select_CCC(sc_card_t *card)
{
return cac_select_file_by_type(card, &cac_CCC_Path, NULL, SC_CARD_TYPE_CAC_II);
}
/* Select ACA in non-standard location */
static int cac_select_ACA(sc_card_t *card)
{
return cac_select_file_by_type(card, &cac_ACA_Path, NULL, SC_CARD_TYPE_CAC_II);
}
static int cac_path_from_cardurl(sc_card_t *card, sc_path_t *path, cac_card_url_t *val, int len)
{
if (len < 10) {
return SC_ERROR_INVALID_DATA;
}
sc_mem_clear(path, sizeof(sc_path_t));
memcpy(path->aid.value, &val->rid, sizeof(val->rid));
memcpy(&path->aid.value[5], &val->applicationID, sizeof(val->applicationID));
path->aid.len = sizeof(val->rid) + sizeof(val->applicationID);
memcpy(path->value, &val->objectID, sizeof(val->objectID));
path->len = sizeof(val->objectID);
path->type = SC_PATH_TYPE_FILE_ID;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)",
path->aid.value[0], path->aid.value[1], path->aid.value[2],
path->aid.value[3], path->aid.value[4], path->aid.value[5],
path->aid.value[6], path->aid.len, path->value[0],
path->value[1], path->len, path->type, path->type);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"rid=%x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u appid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u objid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u",
val->rid[0], val->rid[1], val->rid[2], val->rid[3],
val->rid[4], sizeof(val->rid), val->applicationID[0],
val->applicationID[1], sizeof(val->applicationID),
val->objectID[0], val->objectID[1], sizeof(val->objectID));
return SC_SUCCESS;
}
static int cac_parse_aid(sc_card_t *card, cac_private_data_t *priv, u8 *aid, int aid_len)
{
cac_object_t new_object;
cac_properties_t prop;
size_t i;
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* Search for PKI applets (7 B). Ignore generic objects for now */
if (aid_len != 7 || (memcmp(aid, CAC_1_RID "\x01", 6) != 0
&& memcmp(aid, CAC_1_RID "\x00", 6) != 0))
return SC_SUCCESS;
sc_mem_clear(&new_object.path, sizeof(sc_path_t));
memcpy(new_object.path.aid.value, aid, aid_len);
new_object.path.aid.len = aid_len;
/* Call without OID set will just select the AID without subseqent
* OID selection, which we need to figure out just now
*/
cac_select_file_by_type(card, &new_object.path, NULL, SC_CARD_TYPE_CAC_II);
r = cac_get_properties(card, &prop);
if (r < 0)
return SC_ERROR_INTERNAL;
for (i = 0; i < prop.num_objects; i++) {
/* don't fail just because we have more certs than we can support */
if (priv->cert_next >= MAX_CAC_SLOTS)
return SC_SUCCESS;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"ACA: pki_object found, cert_next=%d (%s), privkey=%d",
priv->cert_next, cac_labels[priv->cert_next],
prop.objects[i].privatekey);
/* If the private key is not initialized, we can safely
* ignore this object here, but increase the pointer to follow
* the certificate labels
*/
if (!prop.objects[i].privatekey) {
priv->cert_next++;
continue;
}
/* OID here has always 2B */
memcpy(new_object.path.value, &prop.objects[i].oid, 2);
new_object.path.len = 2;
new_object.path.type = SC_PATH_TYPE_FILE_ID;
new_object.name = cac_labels[priv->cert_next];
new_object.fd = priv->cert_next+1;
cac_add_object_to_list(&priv->pki_list, &new_object);
priv->cert_next++;
}
return SC_SUCCESS;
}
static int cac_parse_cardurl(sc_card_t *card, cac_private_data_t *priv, cac_card_url_t *val, int len)
{
cac_object_t new_object;
const cac_object_t *obj;
unsigned short object_id;
int r;
r = cac_path_from_cardurl(card, &new_object.path, val, len);
if (r != SC_SUCCESS) {
return r;
}
switch (val->cardApplicationType) {
case CAC_APP_TYPE_PKI:
/* we don't want to overflow the cac_label array. This test could
* go way if we create a label function that will create a unique label
* from a cert index.
*/
if (priv->cert_next >= MAX_CAC_SLOTS)
break; /* don't fail just because we have more certs than we can support */
new_object.name = cac_labels[priv->cert_next];
new_object.fd = priv->cert_next+1;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: pki_object found, cert_next=%d (%s),", priv->cert_next, new_object.name);
cac_add_object_to_list(&priv->pki_list, &new_object);
priv->cert_next++;
break;
case CAC_APP_TYPE_GENERAL:
object_id = bebytes2ushort(val->objectID);
obj = cac_find_obj_by_id(object_id);
if (obj == NULL)
break; /* don't fail just because we don't recognize the object */
new_object.name = obj->name;
new_object.fd = 0;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: gen_object found, objectID=%x (%s),", object_id, new_object.name);
cac_add_object_to_list(&priv->general_list, &new_object);
break;
case CAC_APP_TYPE_SKI:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: ski_object found");
break;
default:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: unknown object_object found (type=0x%02x)", val->cardApplicationType);
/* don't fail just because there is an unknown object in the CCC */
break;
}
return SC_SUCCESS;
}
static int cac_parse_cuid(sc_card_t *card, cac_private_data_t *priv, cac_cuid_t *val, size_t len)
{
size_t card_id_len;
if (len < sizeof(cac_cuid_t)) {
return SC_ERROR_INVALID_DATA;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "gsc_rid=%s", sc_dump_hex(val->gsc_rid, sizeof(val->gsc_rid)));
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "manufacture id=%x", val->manufacturer_id);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "cac_type=%d", val->card_type);
card_id_len = len - (&val->card_id - (u8 *)val);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"card_id=%s (%"SC_FORMAT_LEN_SIZE_T"u)",
sc_dump_hex(&val->card_id, card_id_len),
card_id_len);
priv->cuid = *val;
priv->cac_id = malloc(card_id_len);
if (priv->cac_id == NULL) {
return SC_ERROR_OUT_OF_MEMORY;
}
memcpy(priv->cac_id, &val->card_id, card_id_len);
priv->cac_id_len = card_id_len;
return SC_SUCCESS;
}
static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv);
static int cac_parse_CCC(sc_card_t *card, cac_private_data_t *priv, u8 *tl,
size_t tl_len, u8 *val, size_t val_len)
{
size_t len = 0;
u8 *tl_end = tl + tl_len;
u8 *val_end = val + val_len;
sc_path_t new_path;
int r;
for (; (tl < tl_end) && (val< val_end); val += len) {
/* get the tag and the length */
u8 tag;
if (sc_simpletlv_read_tag(&tl, tl_end - tl, &tag, &len) != SC_SUCCESS)
break;
switch (tag) {
case CAC_TAG_CUID:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CUID");
r = cac_parse_cuid(card, priv, (cac_cuid_t *)val, len);
if (r < 0)
return r;
break;
case CAC_TAG_CC_VERSION_NUMBER:
if (len != 1) {
sc_log(card->ctx, "TAG: CC Version: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
/* ignore the version numbers for now */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: CC Version = 0x%02x", *val);
break;
case CAC_TAG_GRAMMAR_VERION_NUMBER:
if (len != 1) {
sc_log(card->ctx, "TAG: Grammar Version: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
/* ignore the version numbers for now */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Grammar Version = 0x%02x", *val);
break;
case CAC_TAG_CARDURL:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CARDURL");
r = cac_parse_cardurl(card, priv, (cac_card_url_t *)val, len);
if (r < 0)
return r;
break;
/*
* The following are really for file systems cards. This code only cares about CAC VM cards
*/
case CAC_TAG_PKCS15:
if (len != 1) {
sc_log(card->ctx, "TAG: PKCS15: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
/* TODO should verify that this is '0'. If it's not
* zero, we should drop out of here and let the PKCS 15
* code handle this card */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG: PKCS15 = 0x%02x", *val);
break;
case CAC_TAG_DATA_MODEL:
case CAC_TAG_CARD_APDU:
case CAC_TAG_CAPABILITY_TUPLES:
case CAC_TAG_STATUS_TUPLES:
case CAC_TAG_REDIRECTION:
case CAC_TAG_ERROR_CODES:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:FSSpecific(0x%02x)", tag);
break;
case CAC_TAG_ACCESS_CONTROL:
/* TODO handle access control later */
sc_log_hex(card->ctx, "TAG:ACCESS Control", val, len);
break;
case CAC_TAG_NEXT_CCC:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:NEXT CCC");
r = cac_path_from_cardurl(card, &new_path, (cac_card_url_t *)val, len);
if (r < 0)
return r;
r = cac_select_file_by_type(card, &new_path, NULL, SC_CARD_TYPE_CAC_II);
if (r < 0)
return r;
r = cac_process_CCC(card, priv);
if (r < 0)
return r;
break;
default:
/* ignore tags we don't understand */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:Unknown (0x%02x)",tag );
break;
}
}
return SC_SUCCESS;
}
static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv)
{
u8 *tl = NULL, *val = NULL;
size_t tl_len, val_len;
int r;
r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len);
if (r < 0)
goto done;
r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len);
if (r < 0)
goto done;
r = cac_parse_CCC(card, priv, tl, tl_len, val, val_len);
done:
if (tl)
free(tl);
if (val)
free(val);
return r;
}
/* Service Applet Table (Table 5-21) should list all the applets on the
* card, which is a good start if we don't have CCC
*/
static int cac_parse_ACA_service(sc_card_t *card, cac_private_data_t *priv,
u8 *val, size_t val_len)
{
size_t len = 0;
u8 *val_end = val + val_len;
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
for (; val < val_end; val += len) {
/* get the tag and the length */
u8 tag;
if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS)
break;
switch (tag) {
case CAC_TAG_APPLET_FAMILY:
if (len != 5) {
sc_log(card->ctx, "TAG: Applet Information: "
"bad length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Applet Information: Family: 0x%02x", val[0]);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
" Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x",
val[1], val[2], val[3], val[4]);
break;
case CAC_TAG_NUMBER_APPLETS:
if (len != 1) {
sc_log(card->ctx, "TAG: Num applets: "
"bad length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Num applets = %hhd", *val);
break;
case CAC_TAG_APPLET_ENTRY:
/* Make sure we match the outer length */
if (len < 3 || val[2] != len - 3) {
sc_log(card->ctx, "TAG: Applet Entry: "
"bad length (%"SC_FORMAT_LEN_SIZE_T
"u) or length of internal buffer", len);
break;
}
sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Applet Entry: AID", &val[3], val[2]);
/* This is SimpleTLV prefixed with applet ID (1B) */
r = cac_parse_aid(card, priv, &val[3], val[2]);
if (r < 0)
return r;
break;
default:
/* ignore tags we don't understand */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Unknown (0x%02x)", tag);
break;
}
}
return SC_SUCCESS;
}
/* select a CAC pki applet by index */
static int cac_select_pki_applet(sc_card_t *card, int index)
{
sc_path_t applet_path = cac_cac_pki_obj.path;
applet_path.aid.value[applet_path.aid.len-1] = index;
return cac_select_file_by_type(card, &applet_path, NULL, SC_CARD_TYPE_CAC_II);
}
/*
* Find the first existing CAC applet. If none found, then this isn't a CAC
*/
static int cac_find_first_pki_applet(sc_card_t *card, int *index_out)
{
int r, i;
for (i = 0; i < MAX_CAC_SLOTS; i++) {
r = cac_select_pki_applet(card, i);
if (r == SC_SUCCESS) {
/* Try to read first two bytes of the buffer to
* make sure it is not just malfunctioning card
*/
u8 params[2] = {CAC_FILE_TAG, 2};
u8 data[2], *out_ptr = data;
size_t len = 2;
r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0,
¶ms[0], sizeof(params), &out_ptr, &len);
if (r != 2)
continue;
*index_out = i;
return SC_SUCCESS;
}
}
return SC_ERROR_OBJECT_NOT_FOUND;
}
/*
* This emulates CCC for Alt tokens, that do not come with CCC nor ACA applets
*/
static int cac_populate_cac_alt(sc_card_t *card, int index, cac_private_data_t *priv)
{
int r, i;
cac_object_t pki_obj = cac_cac_pki_obj;
u8 buf[100];
u8 *val;
size_t val_len;
/* populate PKI objects */
for (i = index; i < MAX_CAC_SLOTS; i++) {
r = cac_select_pki_applet(card, i);
if (r == SC_SUCCESS) {
pki_obj.name = cac_labels[i];
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"CAC: pki_object found, cert_next=%d (%s),", i, pki_obj.name);
pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i;
pki_obj.fd = i+1; /* don't use id of zero */
cac_add_object_to_list(&priv->pki_list, &pki_obj);
}
}
/* populate non-PKI objects */
for (i=0; i < cac_object_count; i++) {
r = cac_select_file_by_type(card, &cac_objects[i].path, NULL,
SC_CARD_TYPE_CAC_II);
if (r == SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"CAC: obj_object found, cert_next=%d (%s),",
i, cac_objects[i].name);
cac_add_object_to_list(&priv->general_list, &cac_objects[i]);
}
}
/*
* create a cuid to simulate the cac 2 cuid.
*/
priv->cuid = cac_cac_cuid;
/* create a serial number by hashing the first 100 bytes of the
* first certificate on the card */
r = cac_select_pki_applet(card, index);
if (r < 0) {
return r; /* shouldn't happen unless the card has been removed or is malfunctioning */
}
val = buf;
val_len = cac_read_binary(card, 0, val, sizeof(buf), 0);
if (val_len > 0) {
priv->cac_id = malloc(20);
if (priv->cac_id == NULL) {
return SC_ERROR_OUT_OF_MEMORY;
}
#ifdef ENABLE_OPENSSL
SHA1(val, val_len, priv->cac_id);
priv->cac_id_len = 20;
sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE,
"cuid", priv->cac_id, priv->cac_id_len);
#else
sc_log(card->ctx, "OpenSSL Required");
return SC_ERROR_NOT_SUPPORTED;
#endif /* ENABLE_OPENSSL */
}
return SC_SUCCESS;
}
static int cac_process_ACA(sc_card_t *card, cac_private_data_t *priv)
{
int r;
u8 *val = NULL;
size_t val_len;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* Assuming ACA is already selected */
r = cac_get_acr(card, CAC_ACR_SERVICE, &val, &val_len);
if (r < 0)
goto done;
r = cac_parse_ACA_service(card, priv, val, val_len);
if (r == SC_SUCCESS) {
priv->aca_path = malloc(sizeof(sc_path_t));
if (!priv->aca_path) {
r = SC_ERROR_OUT_OF_MEMORY;
goto done;
}
memcpy(priv->aca_path, &cac_ACA_Path, sizeof(sc_path_t));
}
done:
if (val)
free(val);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
/*
* Look for a CAC card. If it exists, initialize our data structures
*/
static int cac_find_and_initialize(sc_card_t *card, int initialize)
{
int r, index;
cac_private_data_t *priv = NULL;
/* already initialized? */
if (card->drv_data) {
return SC_SUCCESS;
}
/* is this a CAC-2 specified in NIST Interagency Report 6887 -
* "Government Smart Card Interoperability Specification v2.1 July 2003" */
r = cac_select_CCC(card);
if (r == SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CCC found, is CAC-2");
if (!initialize) /* match card only */
return r;
priv = cac_new_private_data();
if (!priv)
return SC_ERROR_OUT_OF_MEMORY;
r = cac_process_CCC(card, priv);
if (r == SC_SUCCESS) {
card->type = SC_CARD_TYPE_CAC_II;
card->drv_data = priv;
return r;
}
}
/* Even some ALT tokens can be missing CCC so we should try with ACA */
r = cac_select_ACA(card);
if (r == SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA found, is CAC-2 without CCC");
if (!initialize) /* match card only */
return r;
if (!priv) {
priv = cac_new_private_data();
if (!priv)
return SC_ERROR_OUT_OF_MEMORY;
}
r = cac_process_ACA(card, priv);
if (r == SC_SUCCESS) {
card->type = SC_CARD_TYPE_CAC_II;
card->drv_data = priv;
return r;
}
}
/* is this a CAC Alt token without any accompanying structures */
r = cac_find_first_pki_applet(card, &index);
if (r == SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC Alt");
if (!initialize) /* match card only */
return r;
if (!priv) {
priv = cac_new_private_data();
if (!priv)
return SC_ERROR_OUT_OF_MEMORY;
}
card->drv_data = priv; /* needed for the read_binary() */
r = cac_populate_cac_alt(card, index, priv);
if (r == SC_SUCCESS) {
card->type = SC_CARD_TYPE_CAC_II;
return r;
}
card->drv_data = NULL; /* reset on failure */
}
if (priv) {
cac_free_private_data(priv);
}
return r;
}
/* NOTE: returns a bool, 1 card matches, 0 it does not */
static int cac_match_card(sc_card_t *card)
{
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* Since we send an APDU, the card's logout function may be called...
* however it may be in dirty memory */
card->ops->logout = NULL;
r = cac_find_and_initialize(card, 0);
return (r == SC_SUCCESS); /* never match */
}
static int cac_init(sc_card_t *card)
{
int r;
unsigned long flags;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
r = cac_find_and_initialize(card, 1);
if (r < 0) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_CARD);
}
flags = SC_ALGORITHM_RSA_RAW;
_sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */
_sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */
_sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */
card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
static int cac_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left)
{
/* CAC, like PIV needs Extra validation of (new) PIN during
* a PIN change request, to ensure it's not outside the
* FIPS 201 4.1.6.1 (numeric only) and * FIPS 140-2
* (6 character minimum) requirements.
*/
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (data->cmd == SC_PIN_CMD_CHANGE) {
int i = 0;
if (data->pin2.len < 6) {
return SC_ERROR_INVALID_PIN_LENGTH;
}
for(i=0; i < data->pin2.len; ++i) {
if (!isdigit(data->pin2.data[i])) {
return SC_ERROR_INVALID_DATA;
}
}
}
return iso_drv->ops->pin_cmd(card, data, tries_left);
}
static struct sc_card_operations cac_ops;
static struct sc_card_driver cac_drv = {
"Common Access Card (CAC)",
"cac",
&cac_ops,
NULL, 0, NULL
};
static struct sc_card_driver * sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
cac_ops = *iso_drv->ops;
cac_ops.match_card = cac_match_card;
cac_ops.init = cac_init;
cac_ops.finish = cac_finish;
cac_ops.select_file = cac_select_file; /* need to record object type */
cac_ops.get_challenge = cac_get_challenge;
cac_ops.read_binary = cac_read_binary;
cac_ops.write_binary = cac_write_binary;
cac_ops.set_security_env = cac_set_security_env;
cac_ops.restore_security_env = cac_restore_security_env;
cac_ops.compute_signature = cac_compute_signature;
cac_ops.decipher = cac_decipher;
cac_ops.card_ctl = cac_card_ctl;
cac_ops.pin_cmd = cac_pin_cmd;
return &cac_drv;
}
struct sc_card_driver * sc_get_cac_driver(void)
{
return sc_get_driver();
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_339_0 |
crossvul-cpp_data_good_4824_0 | /*
+----------------------------------------------------------------------+
| phar php single-file executable PHP extension |
+----------------------------------------------------------------------+
| Copyright (c) 2005-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Gregory Beaver <cellog@php.net> |
| Marcus Boerger <helly@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#define PHAR_MAIN 1
#include "phar_internal.h"
#include "SAPI.h"
#include "func_interceptors.h"
static void destroy_phar_data(void *pDest);
ZEND_DECLARE_MODULE_GLOBALS(phar)
char *(*phar_save_resolve_path)(const char *filename, int filename_len TSRMLS_DC);
/**
* set's phar->is_writeable based on the current INI value
*/
static int phar_set_writeable_bit(void *pDest, void *argument TSRMLS_DC) /* {{{ */
{
zend_bool keep = *(zend_bool *)argument;
phar_archive_data *phar = *(phar_archive_data **)pDest;
if (!phar->is_data) {
phar->is_writeable = !keep;
}
return ZEND_HASH_APPLY_KEEP;
}
/* }}} */
/* if the original value is 0 (disabled), then allow setting/unsetting at will. Otherwise only allow 1 (enabled), and error on disabling */
ZEND_INI_MH(phar_ini_modify_handler) /* {{{ */
{
zend_bool old, ini;
if (entry->name_length == 14) {
old = PHAR_G(readonly_orig);
} else {
old = PHAR_G(require_hash_orig);
}
if (new_value_length == 2 && !strcasecmp("on", new_value)) {
ini = (zend_bool) 1;
}
else if (new_value_length == 3 && !strcasecmp("yes", new_value)) {
ini = (zend_bool) 1;
}
else if (new_value_length == 4 && !strcasecmp("true", new_value)) {
ini = (zend_bool) 1;
}
else {
ini = (zend_bool) atoi(new_value);
}
/* do not allow unsetting in runtime */
if (stage == ZEND_INI_STAGE_STARTUP) {
if (entry->name_length == 14) {
PHAR_G(readonly_orig) = ini;
} else {
PHAR_G(require_hash_orig) = ini;
}
} else if (old && !ini) {
return FAILURE;
}
if (entry->name_length == 14) {
PHAR_G(readonly) = ini;
if (PHAR_GLOBALS->request_init && PHAR_GLOBALS->phar_fname_map.arBuckets) {
zend_hash_apply_with_argument(&(PHAR_GLOBALS->phar_fname_map), phar_set_writeable_bit, (void *)&ini TSRMLS_CC);
}
} else {
PHAR_G(require_hash) = ini;
}
return SUCCESS;
}
/* }}}*/
/* this global stores the global cached pre-parsed manifests */
HashTable cached_phars;
HashTable cached_alias;
static void phar_split_cache_list(TSRMLS_D) /* {{{ */
{
char *tmp;
char *key, *lasts, *end;
char ds[2];
phar_archive_data *phar;
uint i = 0;
if (!PHAR_GLOBALS->cache_list || !(PHAR_GLOBALS->cache_list[0])) {
return;
}
ds[0] = DEFAULT_DIR_SEPARATOR;
ds[1] = '\0';
tmp = estrdup(PHAR_GLOBALS->cache_list);
/* fake request startup */
PHAR_GLOBALS->request_init = 1;
if (zend_hash_init(&EG(regular_list), 0, NULL, NULL, 0) == SUCCESS) {
EG(regular_list).nNextFreeElement=1; /* we don't want resource id 0 */
}
PHAR_G(has_bz2) = zend_hash_exists(&module_registry, "bz2", sizeof("bz2"));
PHAR_G(has_zlib) = zend_hash_exists(&module_registry, "zlib", sizeof("zlib"));
/* these two are dummies and will be destroyed later */
zend_hash_init(&cached_phars, sizeof(phar_archive_data*), zend_get_hash_value, destroy_phar_data, 1);
zend_hash_init(&cached_alias, sizeof(phar_archive_data*), zend_get_hash_value, NULL, 1);
/* these two are real and will be copied over cached_phars/cached_alias later */
zend_hash_init(&(PHAR_GLOBALS->phar_fname_map), sizeof(phar_archive_data*), zend_get_hash_value, destroy_phar_data, 1);
zend_hash_init(&(PHAR_GLOBALS->phar_alias_map), sizeof(phar_archive_data*), zend_get_hash_value, NULL, 1);
PHAR_GLOBALS->manifest_cached = 1;
PHAR_GLOBALS->persist = 1;
for (key = php_strtok_r(tmp, ds, &lasts);
key;
key = php_strtok_r(NULL, ds, &lasts)) {
end = strchr(key, DEFAULT_DIR_SEPARATOR);
if (end) {
if (SUCCESS == phar_open_from_filename(key, end - key, NULL, 0, 0, &phar, NULL TSRMLS_CC)) {
finish_up:
phar->phar_pos = i++;
php_stream_close(phar->fp);
phar->fp = NULL;
} else {
finish_error:
PHAR_GLOBALS->persist = 0;
PHAR_GLOBALS->manifest_cached = 0;
efree(tmp);
zend_hash_destroy(&(PHAR_G(phar_fname_map)));
PHAR_GLOBALS->phar_fname_map.arBuckets = 0;
zend_hash_destroy(&(PHAR_G(phar_alias_map)));
PHAR_GLOBALS->phar_alias_map.arBuckets = 0;
zend_hash_destroy(&cached_phars);
zend_hash_destroy(&cached_alias);
zend_hash_graceful_reverse_destroy(&EG(regular_list));
memset(&EG(regular_list), 0, sizeof(HashTable));
/* free cached manifests */
PHAR_GLOBALS->request_init = 0;
return;
}
} else {
if (SUCCESS == phar_open_from_filename(key, strlen(key), NULL, 0, 0, &phar, NULL TSRMLS_CC)) {
goto finish_up;
} else {
goto finish_error;
}
}
}
PHAR_GLOBALS->persist = 0;
PHAR_GLOBALS->request_init = 0;
/* destroy dummy values from before */
zend_hash_destroy(&cached_phars);
zend_hash_destroy(&cached_alias);
cached_phars = PHAR_GLOBALS->phar_fname_map;
cached_alias = PHAR_GLOBALS->phar_alias_map;
PHAR_GLOBALS->phar_fname_map.arBuckets = 0;
PHAR_GLOBALS->phar_alias_map.arBuckets = 0;
zend_hash_graceful_reverse_destroy(&EG(regular_list));
memset(&EG(regular_list), 0, sizeof(HashTable));
efree(tmp);
}
/* }}} */
ZEND_INI_MH(phar_ini_cache_list) /* {{{ */
{
PHAR_G(cache_list) = new_value;
if (stage == ZEND_INI_STAGE_STARTUP) {
phar_split_cache_list(TSRMLS_C);
}
return SUCCESS;
}
/* }}} */
PHP_INI_BEGIN()
STD_PHP_INI_BOOLEAN("phar.readonly", "1", PHP_INI_ALL, phar_ini_modify_handler, readonly, zend_phar_globals, phar_globals)
STD_PHP_INI_BOOLEAN("phar.require_hash", "1", PHP_INI_ALL, phar_ini_modify_handler, require_hash, zend_phar_globals, phar_globals)
STD_PHP_INI_ENTRY("phar.cache_list", "", PHP_INI_SYSTEM, phar_ini_cache_list, cache_list, zend_phar_globals, phar_globals)
PHP_INI_END()
/**
* When all uses of a phar have been concluded, this frees the manifest
* and the phar slot
*/
void phar_destroy_phar_data(phar_archive_data *phar TSRMLS_DC) /* {{{ */
{
if (phar->alias && phar->alias != phar->fname) {
pefree(phar->alias, phar->is_persistent);
phar->alias = NULL;
}
if (phar->fname) {
pefree(phar->fname, phar->is_persistent);
phar->fname = NULL;
}
if (phar->signature) {
pefree(phar->signature, phar->is_persistent);
phar->signature = NULL;
}
if (phar->manifest.arBuckets) {
zend_hash_destroy(&phar->manifest);
phar->manifest.arBuckets = NULL;
}
if (phar->mounted_dirs.arBuckets) {
zend_hash_destroy(&phar->mounted_dirs);
phar->mounted_dirs.arBuckets = NULL;
}
if (phar->virtual_dirs.arBuckets) {
zend_hash_destroy(&phar->virtual_dirs);
phar->virtual_dirs.arBuckets = NULL;
}
if (phar->metadata) {
if (phar->is_persistent) {
if (phar->metadata_len) {
/* for zip comments that are strings */
free(phar->metadata);
} else {
zval_internal_ptr_dtor(&phar->metadata);
}
} else {
zval_ptr_dtor(&phar->metadata);
}
phar->metadata_len = 0;
phar->metadata = 0;
}
if (phar->fp) {
php_stream_close(phar->fp);
phar->fp = 0;
}
if (phar->ufp) {
php_stream_close(phar->ufp);
phar->ufp = 0;
}
pefree(phar, phar->is_persistent);
}
/* }}}*/
/**
* Delete refcount and destruct if needed. On destruct return 1 else 0.
*/
int phar_archive_delref(phar_archive_data *phar TSRMLS_DC) /* {{{ */
{
if (phar->is_persistent) {
return 0;
}
if (--phar->refcount < 0) {
if (PHAR_GLOBALS->request_done
|| zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), phar->fname, phar->fname_len) != SUCCESS) {
phar_destroy_phar_data(phar TSRMLS_CC);
}
return 1;
} else if (!phar->refcount) {
/* invalidate phar cache */
PHAR_G(last_phar) = NULL;
PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
if (phar->fp && !(phar->flags & PHAR_FILE_COMPRESSION_MASK)) {
/* close open file handle - allows removal or rename of
the file on windows, which has greedy locking
only close if the archive was not already compressed. If it
was compressed, then the fp does not refer to the original file */
php_stream_close(phar->fp);
phar->fp = NULL;
}
if (!zend_hash_num_elements(&phar->manifest)) {
/* this is a new phar that has perhaps had an alias/metadata set, but has never
been flushed */
if (zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), phar->fname, phar->fname_len) != SUCCESS) {
phar_destroy_phar_data(phar TSRMLS_CC);
}
return 1;
}
}
return 0;
}
/* }}}*/
/**
* Destroy phar's in shutdown, here we don't care about aliases
*/
static void destroy_phar_data_only(void *pDest) /* {{{ */
{
phar_archive_data *phar_data = *(phar_archive_data **) pDest;
TSRMLS_FETCH();
if (EG(exception) || --phar_data->refcount < 0) {
phar_destroy_phar_data(phar_data TSRMLS_CC);
}
}
/* }}}*/
/**
* Delete aliases to phar's that got kicked out of the global table
*/
static int phar_unalias_apply(void *pDest, void *argument TSRMLS_DC) /* {{{ */
{
return *(void**)pDest == argument ? ZEND_HASH_APPLY_REMOVE : ZEND_HASH_APPLY_KEEP;
}
/* }}} */
/**
* Delete aliases to phar's that got kicked out of the global table
*/
static int phar_tmpclose_apply(void *pDest TSRMLS_DC) /* {{{ */
{
phar_entry_info *entry = (phar_entry_info *) pDest;
if (entry->fp_type != PHAR_TMP) {
return ZEND_HASH_APPLY_KEEP;
}
if (entry->fp && !entry->fp_refcount) {
php_stream_close(entry->fp);
entry->fp = NULL;
}
return ZEND_HASH_APPLY_KEEP;
}
/* }}} */
/**
* Filename map destructor
*/
static void destroy_phar_data(void *pDest) /* {{{ */
{
phar_archive_data *phar_data = *(phar_archive_data **) pDest;
TSRMLS_FETCH();
if (PHAR_GLOBALS->request_ends) {
/* first, iterate over the manifest and close all PHAR_TMP entry fp handles,
this prevents unnecessary unfreed stream resources */
zend_hash_apply(&(phar_data->manifest), phar_tmpclose_apply TSRMLS_CC);
destroy_phar_data_only(pDest);
return;
}
zend_hash_apply_with_argument(&(PHAR_GLOBALS->phar_alias_map), phar_unalias_apply, phar_data TSRMLS_CC);
if (--phar_data->refcount < 0) {
phar_destroy_phar_data(phar_data TSRMLS_CC);
}
}
/* }}}*/
/**
* destructor for the manifest hash, frees each file's entry
*/
void destroy_phar_manifest_entry(void *pDest) /* {{{ */
{
phar_entry_info *entry = (phar_entry_info *)pDest;
TSRMLS_FETCH();
if (entry->cfp) {
php_stream_close(entry->cfp);
entry->cfp = 0;
}
if (entry->fp) {
php_stream_close(entry->fp);
entry->fp = 0;
}
if (entry->metadata) {
if (entry->is_persistent) {
if (entry->metadata_len) {
/* for zip comments that are strings */
free(entry->metadata);
} else {
zval_internal_ptr_dtor(&entry->metadata);
}
} else {
zval_ptr_dtor(&entry->metadata);
}
entry->metadata_len = 0;
entry->metadata = 0;
}
if (entry->metadata_str.c) {
smart_str_free(&entry->metadata_str);
entry->metadata_str.c = 0;
}
pefree(entry->filename, entry->is_persistent);
if (entry->link) {
pefree(entry->link, entry->is_persistent);
entry->link = 0;
}
if (entry->tmp) {
pefree(entry->tmp, entry->is_persistent);
entry->tmp = 0;
}
}
/* }}} */
int phar_entry_delref(phar_entry_data *idata TSRMLS_DC) /* {{{ */
{
int ret = 0;
if (idata->internal_file && !idata->internal_file->is_persistent) {
if (--idata->internal_file->fp_refcount < 0) {
idata->internal_file->fp_refcount = 0;
}
if (idata->fp && idata->fp != idata->phar->fp && idata->fp != idata->phar->ufp && idata->fp != idata->internal_file->fp) {
php_stream_close(idata->fp);
}
/* if phar_get_or_create_entry_data returns a sub-directory, we have to free it */
if (idata->internal_file->is_temp_dir) {
destroy_phar_manifest_entry((void *)idata->internal_file);
efree(idata->internal_file);
}
}
phar_archive_delref(idata->phar TSRMLS_CC);
efree(idata);
return ret;
}
/* }}} */
/**
* Removes an entry, either by actually removing it or by marking it.
*/
void phar_entry_remove(phar_entry_data *idata, char **error TSRMLS_DC) /* {{{ */
{
phar_archive_data *phar;
phar = idata->phar;
if (idata->internal_file->fp_refcount < 2) {
if (idata->fp && idata->fp != idata->phar->fp && idata->fp != idata->phar->ufp && idata->fp != idata->internal_file->fp) {
php_stream_close(idata->fp);
}
zend_hash_del(&idata->phar->manifest, idata->internal_file->filename, idata->internal_file->filename_len);
idata->phar->refcount--;
efree(idata);
} else {
idata->internal_file->is_deleted = 1;
phar_entry_delref(idata TSRMLS_CC);
}
if (!phar->donotflush) {
phar_flush(phar, 0, 0, 0, error TSRMLS_CC);
}
}
/* }}} */
#define MAPPHAR_ALLOC_FAIL(msg) \
if (fp) {\
php_stream_close(fp);\
}\
if (error) {\
spprintf(error, 0, msg, fname);\
}\
return FAILURE;
#define MAPPHAR_FAIL(msg) \
efree(savebuf);\
if (mydata) {\
phar_destroy_phar_data(mydata TSRMLS_CC);\
}\
if (signature) {\
pefree(signature, PHAR_G(persist));\
}\
MAPPHAR_ALLOC_FAIL(msg)
#ifdef WORDS_BIGENDIAN
# define PHAR_GET_32(buffer, var) \
var = ((((unsigned char*)(buffer))[3]) << 24) \
| ((((unsigned char*)(buffer))[2]) << 16) \
| ((((unsigned char*)(buffer))[1]) << 8) \
| (((unsigned char*)(buffer))[0]); \
(buffer) += 4
# define PHAR_GET_16(buffer, var) \
var = ((((unsigned char*)(buffer))[1]) << 8) \
| (((unsigned char*)(buffer))[0]); \
(buffer) += 2
#else
# define PHAR_GET_32(buffer, var) \
memcpy(&var, buffer, sizeof(var)); \
buffer += 4
# define PHAR_GET_16(buffer, var) \
var = *(php_uint16*)(buffer); \
buffer += 2
#endif
#define PHAR_ZIP_16(var) ((php_uint16)((((php_uint16)var[0]) & 0xff) | \
(((php_uint16)var[1]) & 0xff) << 8))
#define PHAR_ZIP_32(var) ((php_uint32)((((php_uint32)var[0]) & 0xff) | \
(((php_uint32)var[1]) & 0xff) << 8 | \
(((php_uint32)var[2]) & 0xff) << 16 | \
(((php_uint32)var[3]) & 0xff) << 24))
/**
* Open an already loaded phar
*/
int phar_open_parsed_phar(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */
{
phar_archive_data *phar;
#ifdef PHP_WIN32
char *unixfname;
#endif
if (error) {
*error = NULL;
}
#ifdef PHP_WIN32
unixfname = estrndup(fname, fname_len);
phar_unixify_path_separators(unixfname, fname_len);
if (SUCCESS == phar_get_archive(&phar, unixfname, fname_len, alias, alias_len, error TSRMLS_CC)
&& ((alias && fname_len == phar->fname_len
&& !strncmp(unixfname, phar->fname, fname_len)) || !alias)
) {
phar_entry_info *stub;
efree(unixfname);
#else
if (SUCCESS == phar_get_archive(&phar, fname, fname_len, alias, alias_len, error TSRMLS_CC)
&& ((alias && fname_len == phar->fname_len
&& !strncmp(fname, phar->fname, fname_len)) || !alias)
) {
phar_entry_info *stub;
#endif
/* logic above is as follows:
If an explicit alias was requested, ensure the filename passed in
matches the phar's filename.
If no alias was passed in, then it can match either and be valid
*/
if (!is_data) {
/* prevent any ".phar" without a stub getting through */
if (!phar->halt_offset && !phar->is_brandnew && (phar->is_tar || phar->is_zip)) {
if (PHAR_G(readonly) && FAILURE == zend_hash_find(&(phar->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) {
if (error) {
spprintf(error, 0, "'%s' is not a phar archive. Use PharData::__construct() for a standard zip or tar archive", fname);
}
return FAILURE;
}
}
}
if (pphar) {
*pphar = phar;
}
return SUCCESS;
} else {
#ifdef PHP_WIN32
efree(unixfname);
#endif
if (pphar) {
*pphar = NULL;
}
if (phar && error && !(options & REPORT_ERRORS)) {
efree(error);
}
return FAILURE;
}
}
/* }}}*/
/**
* Parse out metadata from the manifest for a single file
*
* Meta-data is in this format:
* [len32][data...]
*
* data is the serialized zval
*/
int phar_parse_metadata(char **buffer, zval **metadata, php_uint32 zip_metadata_len TSRMLS_DC) /* {{{ */
{
php_unserialize_data_t var_hash;
if (zip_metadata_len) {
const unsigned char *p;
unsigned char *p_buff = (unsigned char *)estrndup(*buffer, zip_metadata_len);
p = p_buff;
ALLOC_ZVAL(*metadata);
INIT_ZVAL(**metadata);
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (!php_var_unserialize(metadata, &p, p + zip_metadata_len, &var_hash TSRMLS_CC)) {
efree(p_buff);
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
zval_ptr_dtor(metadata);
*metadata = NULL;
return FAILURE;
}
efree(p_buff);
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
if (PHAR_G(persist)) {
/* lazy init metadata */
zval_ptr_dtor(metadata);
*metadata = (zval *) pemalloc(zip_metadata_len, 1);
memcpy(*metadata, *buffer, zip_metadata_len);
return SUCCESS;
}
} else {
*metadata = NULL;
}
return SUCCESS;
}
/* }}}*/
/**
* Does not check for a previously opened phar in the cache.
*
* Parse a new one and add it to the cache, returning either SUCCESS or
* FAILURE, and setting pphar to the pointer to the manifest entry
*
* This is used by phar_open_from_filename to process the manifest, but can be called
* directly.
*/
static int phar_parse_pharfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, long halt_offset, phar_archive_data** pphar, php_uint32 compression, char **error TSRMLS_DC) /* {{{ */
{
char b32[4], *buffer, *endbuffer, *savebuf;
phar_archive_data *mydata = NULL;
phar_entry_info entry;
php_uint32 manifest_len, manifest_count, manifest_flags, manifest_index, tmp_len, sig_flags;
php_uint16 manifest_ver;
php_uint32 len;
long offset;
int sig_len, register_alias = 0, temp_alias = 0;
char *signature = NULL;
if (pphar) {
*pphar = NULL;
}
if (error) {
*error = NULL;
}
/* check for ?>\n and increment accordingly */
if (-1 == php_stream_seek(fp, halt_offset, SEEK_SET)) {
MAPPHAR_ALLOC_FAIL("cannot seek to __HALT_COMPILER(); location in phar \"%s\"")
}
buffer = b32;
if (3 != php_stream_read(fp, buffer, 3)) {
MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)")
}
if ((*buffer == ' ' || *buffer == '\n') && *(buffer + 1) == '?' && *(buffer + 2) == '>') {
int nextchar;
halt_offset += 3;
if (EOF == (nextchar = php_stream_getc(fp))) {
MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)")
}
if ((char) nextchar == '\r') {
/* if we have an \r we require an \n as well */
if (EOF == (nextchar = php_stream_getc(fp)) || (char)nextchar != '\n') {
MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)")
}
++halt_offset;
}
if ((char) nextchar == '\n') {
++halt_offset;
}
}
/* make sure we are at the right location to read the manifest */
if (-1 == php_stream_seek(fp, halt_offset, SEEK_SET)) {
MAPPHAR_ALLOC_FAIL("cannot seek to __HALT_COMPILER(); location in phar \"%s\"")
}
/* read in manifest */
buffer = b32;
if (4 != php_stream_read(fp, buffer, 4)) {
MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at manifest length)")
}
PHAR_GET_32(buffer, manifest_len);
if (manifest_len > 1048576 * 100) {
/* prevent serious memory issues by limiting manifest to at most 100 MB in length */
MAPPHAR_ALLOC_FAIL("manifest cannot be larger than 100 MB in phar \"%s\"")
}
buffer = (char *)emalloc(manifest_len);
savebuf = buffer;
endbuffer = buffer + manifest_len;
if (manifest_len < 10 || manifest_len != php_stream_read(fp, buffer, manifest_len)) {
MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest header)")
}
/* extract the number of entries */
PHAR_GET_32(buffer, manifest_count);
if (manifest_count == 0) {
MAPPHAR_FAIL("in phar \"%s\", manifest claims to have zero entries. Phars must have at least 1 entry");
}
/* extract API version, lowest nibble currently unused */
manifest_ver = (((unsigned char)buffer[0]) << 8)
+ ((unsigned char)buffer[1]);
buffer += 2;
if ((manifest_ver & PHAR_API_VER_MASK) < PHAR_API_MIN_READ) {
efree(savebuf);
php_stream_close(fp);
if (error) {
spprintf(error, 0, "phar \"%s\" is API version %1.u.%1.u.%1.u, and cannot be processed", fname, manifest_ver >> 12, (manifest_ver >> 8) & 0xF, (manifest_ver >> 4) & 0x0F);
}
return FAILURE;
}
PHAR_GET_32(buffer, manifest_flags);
manifest_flags &= ~PHAR_HDR_COMPRESSION_MASK;
manifest_flags &= ~PHAR_FILE_COMPRESSION_MASK;
/* remember whether this entire phar was compressed with gz/bzip2 */
manifest_flags |= compression;
/* The lowest nibble contains the phar wide flags. The compression flags can */
/* be ignored on reading because it is being generated anyways. */
if (manifest_flags & PHAR_HDR_SIGNATURE) {
char sig_buf[8], *sig_ptr = sig_buf;
off_t read_len;
size_t end_of_phar;
if (-1 == php_stream_seek(fp, -8, SEEK_END)
|| (read_len = php_stream_tell(fp)) < 20
|| 8 != php_stream_read(fp, sig_buf, 8)
|| memcmp(sig_buf+4, "GBMB", 4)) {
efree(savebuf);
php_stream_close(fp);
if (error) {
spprintf(error, 0, "phar \"%s\" has a broken signature", fname);
}
return FAILURE;
}
PHAR_GET_32(sig_ptr, sig_flags);
switch(sig_flags) {
case PHAR_SIG_OPENSSL: {
php_uint32 signature_len;
char *sig;
off_t whence;
/* we store the signature followed by the signature length */
if (-1 == php_stream_seek(fp, -12, SEEK_CUR)
|| 4 != php_stream_read(fp, sig_buf, 4)) {
efree(savebuf);
php_stream_close(fp);
if (error) {
spprintf(error, 0, "phar \"%s\" openssl signature length could not be read", fname);
}
return FAILURE;
}
sig_ptr = sig_buf;
PHAR_GET_32(sig_ptr, signature_len);
sig = (char *) emalloc(signature_len);
whence = signature_len + 4;
whence = -whence;
if (-1 == php_stream_seek(fp, whence, SEEK_CUR)
|| !(end_of_phar = php_stream_tell(fp))
|| signature_len != php_stream_read(fp, sig, signature_len)) {
efree(savebuf);
efree(sig);
php_stream_close(fp);
if (error) {
spprintf(error, 0, "phar \"%s\" openssl signature could not be read", fname);
}
return FAILURE;
}
if (FAILURE == phar_verify_signature(fp, end_of_phar, PHAR_SIG_OPENSSL, sig, signature_len, fname, &signature, &sig_len, error TSRMLS_CC)) {
efree(savebuf);
efree(sig);
php_stream_close(fp);
if (error) {
char *save = *error;
spprintf(error, 0, "phar \"%s\" openssl signature could not be verified: %s", fname, *error);
efree(save);
}
return FAILURE;
}
efree(sig);
}
break;
#if PHAR_HASH_OK
case PHAR_SIG_SHA512: {
unsigned char digest[64];
php_stream_seek(fp, -(8 + 64), SEEK_END);
read_len = php_stream_tell(fp);
if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) {
efree(savebuf);
php_stream_close(fp);
if (error) {
spprintf(error, 0, "phar \"%s\" has a broken signature", fname);
}
return FAILURE;
}
if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA512, (char *)digest, 64, fname, &signature, &sig_len, error TSRMLS_CC)) {
efree(savebuf);
php_stream_close(fp);
if (error) {
char *save = *error;
spprintf(error, 0, "phar \"%s\" SHA512 signature could not be verified: %s", fname, *error);
efree(save);
}
return FAILURE;
}
break;
}
case PHAR_SIG_SHA256: {
unsigned char digest[32];
php_stream_seek(fp, -(8 + 32), SEEK_END);
read_len = php_stream_tell(fp);
if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) {
efree(savebuf);
php_stream_close(fp);
if (error) {
spprintf(error, 0, "phar \"%s\" has a broken signature", fname);
}
return FAILURE;
}
if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA256, (char *)digest, 32, fname, &signature, &sig_len, error TSRMLS_CC)) {
efree(savebuf);
php_stream_close(fp);
if (error) {
char *save = *error;
spprintf(error, 0, "phar \"%s\" SHA256 signature could not be verified: %s", fname, *error);
efree(save);
}
return FAILURE;
}
break;
}
#else
case PHAR_SIG_SHA512:
case PHAR_SIG_SHA256:
efree(savebuf);
php_stream_close(fp);
if (error) {
spprintf(error, 0, "phar \"%s\" has a unsupported signature", fname);
}
return FAILURE;
#endif
case PHAR_SIG_SHA1: {
unsigned char digest[20];
php_stream_seek(fp, -(8 + 20), SEEK_END);
read_len = php_stream_tell(fp);
if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) {
efree(savebuf);
php_stream_close(fp);
if (error) {
spprintf(error, 0, "phar \"%s\" has a broken signature", fname);
}
return FAILURE;
}
if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA1, (char *)digest, 20, fname, &signature, &sig_len, error TSRMLS_CC)) {
efree(savebuf);
php_stream_close(fp);
if (error) {
char *save = *error;
spprintf(error, 0, "phar \"%s\" SHA1 signature could not be verified: %s", fname, *error);
efree(save);
}
return FAILURE;
}
break;
}
case PHAR_SIG_MD5: {
unsigned char digest[16];
php_stream_seek(fp, -(8 + 16), SEEK_END);
read_len = php_stream_tell(fp);
if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) {
efree(savebuf);
php_stream_close(fp);
if (error) {
spprintf(error, 0, "phar \"%s\" has a broken signature", fname);
}
return FAILURE;
}
if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_MD5, (char *)digest, 16, fname, &signature, &sig_len, error TSRMLS_CC)) {
efree(savebuf);
php_stream_close(fp);
if (error) {
char *save = *error;
spprintf(error, 0, "phar \"%s\" MD5 signature could not be verified: %s", fname, *error);
efree(save);
}
return FAILURE;
}
break;
}
default:
efree(savebuf);
php_stream_close(fp);
if (error) {
spprintf(error, 0, "phar \"%s\" has a broken or unsupported signature", fname);
}
return FAILURE;
}
} else if (PHAR_G(require_hash)) {
efree(savebuf);
php_stream_close(fp);
if (error) {
spprintf(error, 0, "phar \"%s\" does not have a signature", fname);
}
return FAILURE;
} else {
sig_flags = 0;
sig_len = 0;
}
/* extract alias */
PHAR_GET_32(buffer, tmp_len);
if (buffer + tmp_len > endbuffer) {
MAPPHAR_FAIL("internal corruption of phar \"%s\" (buffer overrun)");
}
if (manifest_len < 10 + tmp_len) {
MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest header)")
}
/* tmp_len = 0 says alias length is 0, which means the alias is not stored in the phar */
if (tmp_len) {
/* if the alias is stored we enforce it (implicit overrides explicit) */
if (alias && alias_len && (alias_len != (int)tmp_len || strncmp(alias, buffer, tmp_len)))
{
php_stream_close(fp);
if (signature) {
efree(signature);
}
if (error) {
spprintf(error, 0, "cannot load phar \"%s\" with implicit alias \"%.*s\" under different alias \"%s\"", fname, tmp_len, buffer, alias);
}
efree(savebuf);
return FAILURE;
}
alias_len = tmp_len;
alias = buffer;
buffer += tmp_len;
register_alias = 1;
} else if (!alias_len || !alias) {
/* if we neither have an explicit nor an implicit alias, we use the filename */
alias = NULL;
alias_len = 0;
register_alias = 0;
} else if (alias_len) {
register_alias = 1;
temp_alias = 1;
}
/* we have 5 32-bit items plus 1 byte at least */
if (manifest_count > ((manifest_len - 10 - tmp_len) / (5 * 4 + 1))) {
/* prevent serious memory issues */
MAPPHAR_FAIL("internal corruption of phar \"%s\" (too many manifest entries for size of manifest)")
}
mydata = pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist));
mydata->is_persistent = PHAR_G(persist);
/* check whether we have meta data, zero check works regardless of byte order */
PHAR_GET_32(buffer, len);
if (mydata->is_persistent) {
mydata->metadata_len = len;
if(!len) {
/* FIXME: not sure why this is needed but removing it breaks tests */
PHAR_GET_32(buffer, len);
}
}
if(len > endbuffer - buffer) {
MAPPHAR_FAIL("internal corruption of phar \"%s\" (trying to read past buffer end)");
}
if (phar_parse_metadata(&buffer, &mydata->metadata, len TSRMLS_CC) == FAILURE) {
MAPPHAR_FAIL("unable to read phar metadata in .phar file \"%s\"");
}
buffer += len;
/* set up our manifest */
zend_hash_init(&mydata->manifest, manifest_count,
zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)mydata->is_persistent);
zend_hash_init(&mydata->mounted_dirs, 5,
zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent);
zend_hash_init(&mydata->virtual_dirs, manifest_count * 2,
zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent);
mydata->fname = pestrndup(fname, fname_len, mydata->is_persistent);
#ifdef PHP_WIN32
phar_unixify_path_separators(mydata->fname, fname_len);
#endif
mydata->fname_len = fname_len;
offset = halt_offset + manifest_len + 4;
memset(&entry, 0, sizeof(phar_entry_info));
entry.phar = mydata;
entry.fp_type = PHAR_FP;
entry.is_persistent = mydata->is_persistent;
for (manifest_index = 0; manifest_index < manifest_count; ++manifest_index) {
if (buffer + 24 > endbuffer) {
MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest entry)")
}
PHAR_GET_32(buffer, entry.filename_len);
if (entry.filename_len == 0) {
MAPPHAR_FAIL("zero-length filename encountered in phar \"%s\"");
}
if (entry.is_persistent) {
entry.manifest_pos = manifest_index;
}
if (entry.filename_len > endbuffer - buffer - 20) {
MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest entry)");
}
if ((manifest_ver & PHAR_API_VER_MASK) >= PHAR_API_MIN_DIR && buffer[entry.filename_len - 1] == '/') {
entry.is_dir = 1;
} else {
entry.is_dir = 0;
}
phar_add_virtual_dirs(mydata, buffer, entry.filename_len TSRMLS_CC);
entry.filename = pestrndup(buffer, entry.filename_len, entry.is_persistent);
buffer += entry.filename_len;
PHAR_GET_32(buffer, entry.uncompressed_filesize);
PHAR_GET_32(buffer, entry.timestamp);
if (offset == halt_offset + (int)manifest_len + 4) {
mydata->min_timestamp = entry.timestamp;
mydata->max_timestamp = entry.timestamp;
} else {
if (mydata->min_timestamp > entry.timestamp) {
mydata->min_timestamp = entry.timestamp;
} else if (mydata->max_timestamp < entry.timestamp) {
mydata->max_timestamp = entry.timestamp;
}
}
PHAR_GET_32(buffer, entry.compressed_filesize);
PHAR_GET_32(buffer, entry.crc32);
PHAR_GET_32(buffer, entry.flags);
if (entry.is_dir) {
entry.filename_len--;
entry.flags |= PHAR_ENT_PERM_DEF_DIR;
}
PHAR_GET_32(buffer, len);
if (entry.is_persistent) {
entry.metadata_len = len;
} else {
entry.metadata_len = 0;
}
if (len > endbuffer - buffer) {
pefree(entry.filename, entry.is_persistent);
MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest entry)");
}
if (phar_parse_metadata(&buffer, &entry.metadata, len TSRMLS_CC) == FAILURE) {
pefree(entry.filename, entry.is_persistent);
MAPPHAR_FAIL("unable to read file metadata in .phar file \"%s\"");
}
buffer += len;
entry.offset = entry.offset_abs = offset;
offset += entry.compressed_filesize;
switch (entry.flags & PHAR_ENT_COMPRESSION_MASK) {
case PHAR_ENT_COMPRESSED_GZ:
if (!PHAR_G(has_zlib)) {
if (entry.metadata) {
if (entry.is_persistent) {
free(entry.metadata);
} else {
zval_ptr_dtor(&entry.metadata);
}
}
pefree(entry.filename, entry.is_persistent);
MAPPHAR_FAIL("zlib extension is required for gz compressed .phar file \"%s\"");
}
break;
case PHAR_ENT_COMPRESSED_BZ2:
if (!PHAR_G(has_bz2)) {
if (entry.metadata) {
if (entry.is_persistent) {
free(entry.metadata);
} else {
zval_ptr_dtor(&entry.metadata);
}
}
pefree(entry.filename, entry.is_persistent);
MAPPHAR_FAIL("bz2 extension is required for bzip2 compressed .phar file \"%s\"");
}
break;
default:
if (entry.uncompressed_filesize != entry.compressed_filesize) {
if (entry.metadata) {
if (entry.is_persistent) {
free(entry.metadata);
} else {
zval_ptr_dtor(&entry.metadata);
}
}
pefree(entry.filename, entry.is_persistent);
MAPPHAR_FAIL("internal corruption of phar \"%s\" (compressed and uncompressed size does not match for uncompressed entry)");
}
break;
}
manifest_flags |= (entry.flags & PHAR_ENT_COMPRESSION_MASK);
/* if signature matched, no need to check CRC32 for each file */
entry.is_crc_checked = (manifest_flags & PHAR_HDR_SIGNATURE ? 1 : 0);
phar_set_inode(&entry TSRMLS_CC);
zend_hash_add(&mydata->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), NULL);
}
snprintf(mydata->version, sizeof(mydata->version), "%u.%u.%u", manifest_ver >> 12, (manifest_ver >> 8) & 0xF, (manifest_ver >> 4) & 0xF);
mydata->internal_file_start = halt_offset + manifest_len + 4;
mydata->halt_offset = halt_offset;
mydata->flags = manifest_flags;
endbuffer = strrchr(mydata->fname, '/');
if (endbuffer) {
mydata->ext = memchr(endbuffer, '.', (mydata->fname + fname_len) - endbuffer);
if (mydata->ext == endbuffer) {
mydata->ext = memchr(endbuffer + 1, '.', (mydata->fname + fname_len) - endbuffer - 1);
}
if (mydata->ext) {
mydata->ext_len = (mydata->fname + mydata->fname_len) - mydata->ext;
}
}
mydata->alias = alias ?
pestrndup(alias, alias_len, mydata->is_persistent) :
pestrndup(mydata->fname, fname_len, mydata->is_persistent);
mydata->alias_len = alias ? alias_len : fname_len;
mydata->sig_flags = sig_flags;
mydata->fp = fp;
mydata->sig_len = sig_len;
mydata->signature = signature;
phar_request_initialize(TSRMLS_C);
if (register_alias) {
phar_archive_data **fd_ptr;
mydata->is_temporary_alias = temp_alias;
if (!phar_validate_alias(mydata->alias, mydata->alias_len)) {
signature = NULL;
fp = NULL;
MAPPHAR_FAIL("Cannot open archive \"%s\", invalid alias");
}
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) {
if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) {
signature = NULL;
fp = NULL;
MAPPHAR_FAIL("Cannot open archive \"%s\", alias is already in use by existing archive");
}
}
zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL);
} else {
mydata->is_temporary_alias = 1;
}
zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL);
efree(savebuf);
if (pphar) {
*pphar = mydata;
}
return SUCCESS;
}
/* }}} */
/**
* Create or open a phar for writing
*/
int phar_open_or_create_filename(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */
{
const char *ext_str, *z;
char *my_error;
int ext_len;
phar_archive_data **test, *unused = NULL;
test = &unused;
if (error) {
*error = NULL;
}
/* first try to open an existing file */
if (phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, !is_data, 0, 1 TSRMLS_CC) == SUCCESS) {
goto check_file;
}
/* next try to create a new file */
if (FAILURE == phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, !is_data, 1, 1 TSRMLS_CC)) {
if (error) {
if (ext_len == -2) {
spprintf(error, 0, "Cannot create a phar archive from a URL like \"%s\". Phar objects can only be created from local files", fname);
} else {
spprintf(error, 0, "Cannot create phar '%s', file extension (or combination) not recognised or the directory does not exist", fname);
}
}
return FAILURE;
}
check_file:
if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, is_data, options, test, &my_error TSRMLS_CC) == SUCCESS) {
if (pphar) {
*pphar = *test;
}
if ((*test)->is_data && !(*test)->is_tar && !(*test)->is_zip) {
if (error) {
spprintf(error, 0, "Cannot open '%s' as a PharData object. Use Phar::__construct() for executable archives", fname);
}
return FAILURE;
}
if (PHAR_G(readonly) && !(*test)->is_data && ((*test)->is_tar || (*test)->is_zip)) {
phar_entry_info *stub;
if (FAILURE == zend_hash_find(&((*test)->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) {
spprintf(error, 0, "'%s' is not a phar archive. Use PharData::__construct() for a standard zip or tar archive", fname);
return FAILURE;
}
}
if (!PHAR_G(readonly) || (*test)->is_data) {
(*test)->is_writeable = 1;
}
return SUCCESS;
} else if (my_error) {
if (error) {
*error = my_error;
} else {
efree(my_error);
}
return FAILURE;
}
if (ext_len > 3 && (z = memchr(ext_str, 'z', ext_len)) && ((ext_str + ext_len) - z >= 2) && !memcmp(z + 1, "ip", 2)) {
/* assume zip-based phar */
return phar_open_or_create_zip(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC);
}
if (ext_len > 3 && (z = memchr(ext_str, 't', ext_len)) && ((ext_str + ext_len) - z >= 2) && !memcmp(z + 1, "ar", 2)) {
/* assume tar-based phar */
return phar_open_or_create_tar(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC);
}
return phar_create_or_parse_filename(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC);
}
/* }}} */
int phar_create_or_parse_filename(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */
{
phar_archive_data *mydata;
php_stream *fp;
char *actual = NULL, *p;
if (!pphar) {
pphar = &mydata;
}
#if PHP_API_VERSION < 20100412
if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) {
return FAILURE;
}
#endif
if (php_check_open_basedir(fname TSRMLS_CC)) {
return FAILURE;
}
/* first open readonly so it won't be created if not present */
fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK|0, &actual);
if (actual) {
fname = actual;
fname_len = strlen(actual);
}
if (fp) {
if (phar_open_from_fp(fp, fname, fname_len, alias, alias_len, options, pphar, is_data, error TSRMLS_CC) == SUCCESS) {
if ((*pphar)->is_data || !PHAR_G(readonly)) {
(*pphar)->is_writeable = 1;
}
if (actual) {
efree(actual);
}
return SUCCESS;
} else {
/* file exists, but is either corrupt or not a phar archive */
if (actual) {
efree(actual);
}
return FAILURE;
}
}
if (actual) {
efree(actual);
}
if (PHAR_G(readonly) && !is_data) {
if (options & REPORT_ERRORS) {
if (error) {
spprintf(error, 0, "creating archive \"%s\" disabled by the php.ini setting phar.readonly", fname);
}
}
return FAILURE;
}
/* set up our manifest */
mydata = ecalloc(1, sizeof(phar_archive_data));
mydata->fname = expand_filepath(fname, NULL TSRMLS_CC);
fname_len = strlen(mydata->fname);
#ifdef PHP_WIN32
phar_unixify_path_separators(mydata->fname, fname_len);
#endif
p = strrchr(mydata->fname, '/');
if (p) {
mydata->ext = memchr(p, '.', (mydata->fname + fname_len) - p);
if (mydata->ext == p) {
mydata->ext = memchr(p + 1, '.', (mydata->fname + fname_len) - p - 1);
}
if (mydata->ext) {
mydata->ext_len = (mydata->fname + fname_len) - mydata->ext;
}
}
if (pphar) {
*pphar = mydata;
}
zend_hash_init(&mydata->manifest, sizeof(phar_entry_info),
zend_get_hash_value, destroy_phar_manifest_entry, 0);
zend_hash_init(&mydata->mounted_dirs, sizeof(char *),
zend_get_hash_value, NULL, 0);
zend_hash_init(&mydata->virtual_dirs, sizeof(char *),
zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent);
mydata->fname_len = fname_len;
snprintf(mydata->version, sizeof(mydata->version), "%s", PHP_PHAR_API_VERSION);
mydata->is_temporary_alias = alias ? 0 : 1;
mydata->internal_file_start = -1;
mydata->fp = NULL;
mydata->is_writeable = 1;
mydata->is_brandnew = 1;
phar_request_initialize(TSRMLS_C);
zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL);
if (is_data) {
alias = NULL;
alias_len = 0;
mydata->is_data = 1;
/* assume tar format, PharData can specify other */
mydata->is_tar = 1;
} else {
phar_archive_data **fd_ptr;
if (alias && SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) {
if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) {
if (error) {
spprintf(error, 4096, "phar error: phar \"%s\" cannot set alias \"%s\", already in use by another phar archive", mydata->fname, alias);
}
zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len);
if (pphar) {
*pphar = NULL;
}
return FAILURE;
}
}
mydata->alias = alias ? estrndup(alias, alias_len) : estrndup(mydata->fname, fname_len);
mydata->alias_len = alias ? alias_len : fname_len;
}
if (alias_len && alias) {
if (FAILURE == zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL)) {
if (options & REPORT_ERRORS) {
if (error) {
spprintf(error, 0, "archive \"%s\" cannot be associated with alias \"%s\", already in use", fname, alias);
}
}
zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len);
if (pphar) {
*pphar = NULL;
}
return FAILURE;
}
}
return SUCCESS;
}
/* }}}*/
/**
* Return an already opened filename.
*
* Or scan a phar file for the required __HALT_COMPILER(); ?> token and verify
* that the manifest is proper, then pass it to phar_parse_pharfile(). SUCCESS
* or FAILURE is returned and pphar is set to a pointer to the phar's manifest
*/
int phar_open_from_filename(char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */
{
php_stream *fp;
char *actual;
int ret, is_data = 0;
if (error) {
*error = NULL;
}
if (!strstr(fname, ".phar")) {
is_data = 1;
}
if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC) == SUCCESS) {
return SUCCESS;
} else if (error && *error) {
return FAILURE;
}
#if PHP_API_VERSION < 20100412
if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) {
return FAILURE;
}
#endif
if (php_check_open_basedir(fname TSRMLS_CC)) {
return FAILURE;
}
fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK, &actual);
if (!fp) {
if (options & REPORT_ERRORS) {
if (error) {
spprintf(error, 0, "unable to open phar for reading \"%s\"", fname);
}
}
if (actual) {
efree(actual);
}
return FAILURE;
}
if (actual) {
fname = actual;
fname_len = strlen(actual);
}
ret = phar_open_from_fp(fp, fname, fname_len, alias, alias_len, options, pphar, is_data, error TSRMLS_CC);
if (actual) {
efree(actual);
}
return ret;
}
/* }}}*/
static inline char *phar_strnstr(const char *buf, int buf_len, const char *search, int search_len) /* {{{ */
{
const char *c;
int so_far = 0;
if (buf_len < search_len) {
return NULL;
}
c = buf - 1;
do {
if (!(c = memchr(c + 1, search[0], buf_len - search_len - so_far))) {
return (char *) NULL;
}
so_far = c - buf;
if (so_far >= (buf_len - search_len)) {
return (char *) NULL;
}
if (!memcmp(c, search, search_len)) {
return (char *) c;
}
} while (1);
}
/* }}} */
/**
* Scan an open fp for the required __HALT_COMPILER(); ?> token and verify
* that the manifest is proper, then pass it to phar_parse_pharfile(). SUCCESS
* or FAILURE is returned and pphar is set to a pointer to the phar's manifest
*/
static int phar_open_from_fp(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, int is_data, char **error TSRMLS_DC) /* {{{ */
{
const char token[] = "__HALT_COMPILER();";
const char zip_magic[] = "PK\x03\x04";
const char gz_magic[] = "\x1f\x8b\x08";
const char bz_magic[] = "BZh";
char *pos, test = '\0';
const int window_size = 1024;
char buffer[1024 + sizeof(token)]; /* a 1024 byte window + the size of the halt_compiler token (moving window) */
const long readsize = sizeof(buffer) - sizeof(token);
const long tokenlen = sizeof(token) - 1;
long halt_offset;
size_t got;
php_uint32 compression = PHAR_FILE_COMPRESSED_NONE;
if (error) {
*error = NULL;
}
if (-1 == php_stream_rewind(fp)) {
MAPPHAR_ALLOC_FAIL("cannot rewind phar \"%s\"")
}
buffer[sizeof(buffer)-1] = '\0';
memset(buffer, 32, sizeof(token));
halt_offset = 0;
/* Maybe it's better to compile the file instead of just searching, */
/* but we only want the offset. So we want a .re scanner to find it. */
while(!php_stream_eof(fp)) {
if ((got = php_stream_read(fp, buffer+tokenlen, readsize)) < (size_t) tokenlen) {
MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated entry)")
}
if (!test) {
test = '\1';
pos = buffer+tokenlen;
if (!memcmp(pos, gz_magic, 3)) {
char err = 0;
php_stream_filter *filter;
php_stream *temp;
/* to properly decompress, we have to tell zlib to look for a zlib or gzip header */
zval filterparams;
if (!PHAR_G(has_zlib)) {
MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\" to temporary file, enable zlib extension in php.ini")
}
array_init(&filterparams);
/* this is defined in zlib's zconf.h */
#ifndef MAX_WBITS
#define MAX_WBITS 15
#endif
add_assoc_long(&filterparams, "window", MAX_WBITS + 32);
/* entire file is gzip-compressed, uncompress to temporary file */
if (!(temp = php_stream_fopen_tmpfile())) {
MAPPHAR_ALLOC_FAIL("unable to create temporary file for decompression of gzipped phar archive \"%s\"")
}
php_stream_rewind(fp);
filter = php_stream_filter_create("zlib.inflate", &filterparams, php_stream_is_persistent(fp) TSRMLS_CC);
if (!filter) {
err = 1;
add_assoc_long(&filterparams, "window", MAX_WBITS);
filter = php_stream_filter_create("zlib.inflate", &filterparams, php_stream_is_persistent(fp) TSRMLS_CC);
zval_dtor(&filterparams);
if (!filter) {
php_stream_close(temp);
MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\", ext/zlib is buggy in PHP versions older than 5.2.6")
}
} else {
zval_dtor(&filterparams);
}
php_stream_filter_append(&temp->writefilters, filter);
if (SUCCESS != php_stream_copy_to_stream_ex(fp, temp, PHP_STREAM_COPY_ALL, NULL)) {
if (err) {
php_stream_close(temp);
MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\", ext/zlib is buggy in PHP versions older than 5.2.6")
}
php_stream_close(temp);
MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\" to temporary file")
}
php_stream_filter_flush(filter, 1);
php_stream_filter_remove(filter, 1 TSRMLS_CC);
php_stream_close(fp);
fp = temp;
php_stream_rewind(fp);
compression = PHAR_FILE_COMPRESSED_GZ;
/* now, start over */
test = '\0';
continue;
} else if (!memcmp(pos, bz_magic, 3)) {
php_stream_filter *filter;
php_stream *temp;
if (!PHAR_G(has_bz2)) {
MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\" to temporary file, enable bz2 extension in php.ini")
}
/* entire file is bzip-compressed, uncompress to temporary file */
if (!(temp = php_stream_fopen_tmpfile())) {
MAPPHAR_ALLOC_FAIL("unable to create temporary file for decompression of bzipped phar archive \"%s\"")
}
php_stream_rewind(fp);
filter = php_stream_filter_create("bzip2.decompress", NULL, php_stream_is_persistent(fp) TSRMLS_CC);
if (!filter) {
php_stream_close(temp);
MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\", filter creation failed")
}
php_stream_filter_append(&temp->writefilters, filter);
if (SUCCESS != php_stream_copy_to_stream_ex(fp, temp, PHP_STREAM_COPY_ALL, NULL)) {
php_stream_close(temp);
MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\" to temporary file")
}
php_stream_filter_flush(filter, 1);
php_stream_filter_remove(filter, 1 TSRMLS_CC);
php_stream_close(fp);
fp = temp;
php_stream_rewind(fp);
compression = PHAR_FILE_COMPRESSED_BZ2;
/* now, start over */
test = '\0';
continue;
}
if (!memcmp(pos, zip_magic, 4)) {
php_stream_seek(fp, 0, SEEK_END);
return phar_parse_zipfile(fp, fname, fname_len, alias, alias_len, pphar, error TSRMLS_CC);
}
if (got > 512) {
if (phar_is_tar(pos, fname)) {
php_stream_rewind(fp);
return phar_parse_tarfile(fp, fname, fname_len, alias, alias_len, pphar, is_data, compression, error TSRMLS_CC);
}
}
}
if (got > 0 && (pos = phar_strnstr(buffer, got + sizeof(token), token, sizeof(token)-1)) != NULL) {
halt_offset += (pos - buffer); /* no -tokenlen+tokenlen here */
return phar_parse_pharfile(fp, fname, fname_len, alias, alias_len, halt_offset, pphar, compression, error TSRMLS_CC);
}
halt_offset += got;
memmove(buffer, buffer + window_size, tokenlen); /* move the memory buffer by the size of the window */
}
MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (__HALT_COMPILER(); not found)")
}
/* }}} */
/*
* given the location of the file extension and the start of the file path,
* determine the end of the portion of the path (i.e. /path/to/file.ext/blah
* grabs "/path/to/file.ext" as does the straight /path/to/file.ext),
* stat it to determine if it exists.
* if so, check to see if it is a directory and fail if so
* if not, check to see if its dirname() exists (i.e. "/path/to") and is a directory
* succeed if we are creating the file, otherwise fail.
*/
static int phar_analyze_path(const char *fname, const char *ext, int ext_len, int for_create TSRMLS_DC) /* {{{ */
{
php_stream_statbuf ssb;
char *realpath;
char *filename = estrndup(fname, (ext - fname) + ext_len);
if ((realpath = expand_filepath(filename, NULL TSRMLS_CC))) {
#ifdef PHP_WIN32
phar_unixify_path_separators(realpath, strlen(realpath));
#endif
if (zend_hash_exists(&(PHAR_GLOBALS->phar_fname_map), realpath, strlen(realpath))) {
efree(realpath);
efree(filename);
return SUCCESS;
}
if (PHAR_G(manifest_cached) && zend_hash_exists(&cached_phars, realpath, strlen(realpath))) {
efree(realpath);
efree(filename);
return SUCCESS;
}
efree(realpath);
}
if (SUCCESS == php_stream_stat_path((char *) filename, &ssb)) {
efree(filename);
if (ssb.sb.st_mode & S_IFDIR) {
return FAILURE;
}
if (for_create == 1) {
return FAILURE;
}
return SUCCESS;
} else {
char *slash;
if (!for_create) {
efree(filename);
return FAILURE;
}
slash = (char *) strrchr(filename, '/');
if (slash) {
*slash = '\0';
}
if (SUCCESS != php_stream_stat_path((char *) filename, &ssb)) {
if (!slash) {
if (!(realpath = expand_filepath(filename, NULL TSRMLS_CC))) {
efree(filename);
return FAILURE;
}
#ifdef PHP_WIN32
phar_unixify_path_separators(realpath, strlen(realpath));
#endif
slash = strstr(realpath, filename);
if (slash) {
slash += ((ext - fname) + ext_len);
*slash = '\0';
}
slash = strrchr(realpath, '/');
if (slash) {
*slash = '\0';
} else {
efree(realpath);
efree(filename);
return FAILURE;
}
if (SUCCESS != php_stream_stat_path(realpath, &ssb)) {
efree(realpath);
efree(filename);
return FAILURE;
}
efree(realpath);
if (ssb.sb.st_mode & S_IFDIR) {
efree(filename);
return SUCCESS;
}
}
efree(filename);
return FAILURE;
}
efree(filename);
if (ssb.sb.st_mode & S_IFDIR) {
return SUCCESS;
}
return FAILURE;
}
}
/* }}} */
/* check for ".phar" in extension */
static int phar_check_str(const char *fname, const char *ext_str, int ext_len, int executable, int for_create TSRMLS_DC) /* {{{ */
{
char test[51];
const char *pos;
if (ext_len >= 50) {
return FAILURE;
}
if (executable == 1) {
/* copy "." as well */
memcpy(test, ext_str - 1, ext_len + 1);
test[ext_len + 1] = '\0';
/* executable phars must contain ".phar" as a valid extension (phar://.pharmy/oops is invalid) */
/* (phar://hi/there/.phar/oops is also invalid) */
pos = strstr(test, ".phar");
if (pos && (*(pos - 1) != '/')
&& (pos += 5) && (*pos == '\0' || *pos == '/' || *pos == '.')) {
return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC);
} else {
return FAILURE;
}
}
/* data phars need only contain a single non-"." to be valid */
if (!executable) {
pos = strstr(ext_str, ".phar");
if (!(pos && (*(pos - 1) != '/')
&& (pos += 5) && (*pos == '\0' || *pos == '/' || *pos == '.')) && *(ext_str + 1) != '.' && *(ext_str + 1) != '/' && *(ext_str + 1) != '\0') {
return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC);
}
} else {
if (*(ext_str + 1) != '.' && *(ext_str + 1) != '/' && *(ext_str + 1) != '\0') {
return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC);
}
}
return FAILURE;
}
/* }}} */
/*
* if executable is 1, only returns SUCCESS if the extension is one of the tar/zip .phar extensions
* if executable is 0, it returns SUCCESS only if the filename does *not* contain ".phar" anywhere, and treats
* the first extension as the filename extension
*
* if an extension is found, it sets ext_str to the location of the file extension in filename,
* and ext_len to the length of the extension.
* for urls like "phar://alias/oops" it instead sets ext_len to -1 and returns FAILURE, which tells
* the calling function to use "alias" as the phar alias
*
* the last parameter should be set to tell the thing to assume that filename is the full path, and only to check the
* extension rules, not to iterate.
*/
int phar_detect_phar_fname_ext(const char *filename, int filename_len, const char **ext_str, int *ext_len, int executable, int for_create, int is_complete TSRMLS_DC) /* {{{ */
{
const char *pos, *slash;
*ext_str = NULL;
*ext_len = 0;
if (!filename_len || filename_len == 1) {
return FAILURE;
}
phar_request_initialize(TSRMLS_C);
/* first check for alias in first segment */
pos = memchr(filename, '/', filename_len);
if (pos && pos != filename) {
/* check for url like http:// or phar:// */
if (*(pos - 1) == ':' && (pos - filename) < filename_len - 1 && *(pos + 1) == '/') {
*ext_len = -2;
*ext_str = NULL;
return FAILURE;
}
if (zend_hash_exists(&(PHAR_GLOBALS->phar_alias_map), (char *) filename, pos - filename)) {
*ext_str = pos;
*ext_len = -1;
return FAILURE;
}
if (PHAR_G(manifest_cached) && zend_hash_exists(&cached_alias, (char *) filename, pos - filename)) {
*ext_str = pos;
*ext_len = -1;
return FAILURE;
}
}
if (zend_hash_num_elements(&(PHAR_GLOBALS->phar_fname_map)) || PHAR_G(manifest_cached)) {
phar_archive_data **pphar;
if (is_complete) {
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), (char *) filename, filename_len, (void **)&pphar)) {
*ext_str = filename + (filename_len - (*pphar)->ext_len);
woohoo:
*ext_len = (*pphar)->ext_len;
if (executable == 2) {
return SUCCESS;
}
if (executable == 1 && !(*pphar)->is_data) {
return SUCCESS;
}
if (!executable && (*pphar)->is_data) {
return SUCCESS;
}
return FAILURE;
}
if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, (char *) filename, filename_len, (void **)&pphar)) {
*ext_str = filename + (filename_len - (*pphar)->ext_len);
goto woohoo;
}
} else {
char *str_key;
uint keylen;
ulong unused;
for (zend_hash_internal_pointer_reset(&(PHAR_GLOBALS->phar_fname_map));
HASH_KEY_NON_EXISTENT != zend_hash_get_current_key_ex(&(PHAR_GLOBALS->phar_fname_map), &str_key, &keylen, &unused, 0, NULL);
zend_hash_move_forward(&(PHAR_GLOBALS->phar_fname_map))
) {
if (keylen > (uint) filename_len) {
continue;
}
if (!memcmp(filename, str_key, keylen) && ((uint)filename_len == keylen
|| filename[keylen] == '/' || filename[keylen] == '\0')) {
if (FAILURE == zend_hash_get_current_data(&(PHAR_GLOBALS->phar_fname_map), (void **) &pphar)) {
break;
}
*ext_str = filename + (keylen - (*pphar)->ext_len);
goto woohoo;
}
}
if (PHAR_G(manifest_cached)) {
for (zend_hash_internal_pointer_reset(&cached_phars);
HASH_KEY_NON_EXISTENT != zend_hash_get_current_key_ex(&cached_phars, &str_key, &keylen, &unused, 0, NULL);
zend_hash_move_forward(&cached_phars)
) {
if (keylen > (uint) filename_len) {
continue;
}
if (!memcmp(filename, str_key, keylen) && ((uint)filename_len == keylen
|| filename[keylen] == '/' || filename[keylen] == '\0')) {
if (FAILURE == zend_hash_get_current_data(&cached_phars, (void **) &pphar)) {
break;
}
*ext_str = filename + (keylen - (*pphar)->ext_len);
goto woohoo;
}
}
}
}
}
pos = memchr(filename + 1, '.', filename_len);
next_extension:
if (!pos) {
return FAILURE;
}
while (pos != filename && (*(pos - 1) == '/' || *(pos - 1) == '\0')) {
pos = memchr(pos + 1, '.', filename_len - (pos - filename) + 1);
if (!pos) {
return FAILURE;
}
}
slash = memchr(pos, '/', filename_len - (pos - filename));
if (!slash) {
/* this is a url like "phar://blah.phar" with no directory */
*ext_str = pos;
*ext_len = strlen(pos);
/* file extension must contain "phar" */
switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create TSRMLS_CC)) {
case SUCCESS:
return SUCCESS;
case FAILURE:
/* we are at the end of the string, so we fail */
return FAILURE;
}
}
/* we've found an extension that ends at a directory separator */
*ext_str = pos;
*ext_len = slash - pos;
switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create TSRMLS_CC)) {
case SUCCESS:
return SUCCESS;
case FAILURE:
/* look for more extensions */
pos = strchr(pos + 1, '.');
if (pos) {
*ext_str = NULL;
*ext_len = 0;
}
goto next_extension;
}
return FAILURE;
}
/* }}} */
static int php_check_dots(const char *element, int n) /* {{{ */
{
for(n--; n >= 0; --n) {
if (element[n] != '.') {
return 1;
}
}
return 0;
}
/* }}} */
#define IS_DIRECTORY_UP(element, len) \
(len >= 2 && !php_check_dots(element, len))
#define IS_DIRECTORY_CURRENT(element, len) \
(len == 1 && element[0] == '.')
#define IS_BACKSLASH(c) ((c) == '/')
#ifdef COMPILE_DL_PHAR
/* stupid-ass non-extern declaration in tsrm_strtok.h breaks dumbass MS compiler */
static inline int in_character_class(char ch, const char *delim) /* {{{ */
{
while (*delim) {
if (*delim == ch) {
return 1;
}
++delim;
}
return 0;
}
/* }}} */
char *tsrm_strtok_r(char *s, const char *delim, char **last) /* {{{ */
{
char *token;
if (s == NULL) {
s = *last;
}
while (*s && in_character_class(*s, delim)) {
++s;
}
if (!*s) {
return NULL;
}
token = s;
while (*s && !in_character_class(*s, delim)) {
++s;
}
if (!*s) {
*last = s;
} else {
*s = '\0';
*last = s + 1;
}
return token;
}
/* }}} */
#endif
/**
* Remove .. and . references within a phar filename
*/
char *phar_fix_filepath(char *path, int *new_len, int use_cwd TSRMLS_DC) /* {{{ */
{
char *newpath;
int newpath_len;
char *ptr;
char *tok;
int ptr_length, path_length = *new_len;
if (PHAR_G(cwd_len) && use_cwd && path_length > 2 && path[0] == '.' && path[1] == '/') {
newpath_len = PHAR_G(cwd_len);
newpath = emalloc(strlen(path) + newpath_len + 1);
memcpy(newpath, PHAR_G(cwd), newpath_len);
} else {
newpath = emalloc(strlen(path) + 2);
newpath[0] = '/';
newpath_len = 1;
}
ptr = path;
if (*ptr == '/') {
++ptr;
}
tok = ptr;
do {
ptr = memchr(ptr, '/', path_length - (ptr - path));
} while (ptr && ptr - tok == 0 && *ptr == '/' && ++ptr && ++tok);
if (!ptr && (path_length - (tok - path))) {
switch (path_length - (tok - path)) {
case 1:
if (*tok == '.') {
efree(path);
*new_len = 1;
efree(newpath);
return estrndup("/", 1);
}
break;
case 2:
if (tok[0] == '.' && tok[1] == '.') {
efree(path);
*new_len = 1;
efree(newpath);
return estrndup("/", 1);
}
}
efree(newpath);
return path;
}
while (ptr) {
ptr_length = ptr - tok;
last_time:
if (IS_DIRECTORY_UP(tok, ptr_length)) {
#define PREVIOUS newpath[newpath_len - 1]
while (newpath_len > 1 && !IS_BACKSLASH(PREVIOUS)) {
newpath_len--;
}
if (newpath[0] != '/') {
newpath[newpath_len] = '\0';
} else if (newpath_len > 1) {
--newpath_len;
}
} else if (!IS_DIRECTORY_CURRENT(tok, ptr_length)) {
if (newpath_len > 1) {
newpath[newpath_len++] = '/';
memcpy(newpath + newpath_len, tok, ptr_length+1);
} else {
memcpy(newpath + newpath_len, tok, ptr_length+1);
}
newpath_len += ptr_length;
}
if (ptr == path + path_length) {
break;
}
tok = ++ptr;
do {
ptr = memchr(ptr, '/', path_length - (ptr - path));
} while (ptr && ptr - tok == 0 && *ptr == '/' && ++ptr && ++tok);
if (!ptr && (path_length - (tok - path))) {
ptr_length = path_length - (tok - path);
ptr = path + path_length;
goto last_time;
}
}
efree(path);
*new_len = newpath_len;
newpath[newpath_len] = '\0';
return erealloc(newpath, newpath_len + 1);
}
/* }}} */
/**
* Process a phar stream name, ensuring we can handle any of:
*
* - whatever.phar
* - whatever.phar.gz
* - whatever.phar.bz2
* - whatever.phar.php
*
* Optionally the name might start with 'phar://'
*
* This is used by phar_parse_url()
*/
int phar_split_fname(const char *filename, int filename_len, char **arch, int *arch_len, char **entry, int *entry_len, int executable, int for_create TSRMLS_DC) /* {{{ */
{
const char *ext_str;
#ifdef PHP_WIN32
char *save;
#endif
int ext_len;
if (CHECK_NULL_PATH(filename, filename_len)) {
return FAILURE;
}
if (!strncasecmp(filename, "phar://", 7)) {
filename += 7;
filename_len -= 7;
}
ext_len = 0;
#ifdef PHP_WIN32
save = filename;
filename = estrndup(filename, filename_len);
phar_unixify_path_separators(filename, filename_len);
#endif
if (phar_detect_phar_fname_ext(filename, filename_len, &ext_str, &ext_len, executable, for_create, 0 TSRMLS_CC) == FAILURE) {
if (ext_len != -1) {
if (!ext_str) {
/* no / detected, restore arch for error message */
#ifdef PHP_WIN32
*arch = save;
#else
*arch = filename;
#endif
}
#ifdef PHP_WIN32
efree(filename);
#endif
return FAILURE;
}
ext_len = 0;
/* no extension detected - instead we are dealing with an alias */
}
*arch_len = ext_str - filename + ext_len;
*arch = estrndup(filename, *arch_len);
if (ext_str[ext_len]) {
*entry_len = filename_len - *arch_len;
*entry = estrndup(ext_str+ext_len, *entry_len);
#ifdef PHP_WIN32
phar_unixify_path_separators(*entry, *entry_len);
#endif
*entry = phar_fix_filepath(*entry, entry_len, 0 TSRMLS_CC);
} else {
*entry_len = 1;
*entry = estrndup("/", 1);
}
#ifdef PHP_WIN32
efree(filename);
#endif
return SUCCESS;
}
/* }}} */
/**
* Invoked when a user calls Phar::mapPhar() from within an executing .phar
* to set up its manifest directly
*/
int phar_open_executed_filename(char *alias, int alias_len, char **error TSRMLS_DC) /* {{{ */
{
char *fname;
zval *halt_constant;
php_stream *fp;
int fname_len;
char *actual = NULL;
int ret;
if (error) {
*error = NULL;
}
fname = (char*)zend_get_executed_filename(TSRMLS_C);
fname_len = strlen(fname);
if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, 0, REPORT_ERRORS, NULL, 0 TSRMLS_CC) == SUCCESS) {
return SUCCESS;
}
if (!strcmp(fname, "[no active file]")) {
if (error) {
spprintf(error, 0, "cannot initialize a phar outside of PHP execution");
}
return FAILURE;
}
MAKE_STD_ZVAL(halt_constant);
if (0 == zend_get_constant("__COMPILER_HALT_OFFSET__", 24, halt_constant TSRMLS_CC)) {
FREE_ZVAL(halt_constant);
if (error) {
spprintf(error, 0, "__HALT_COMPILER(); must be declared in a phar");
}
return FAILURE;
}
FREE_ZVAL(halt_constant);
#if PHP_API_VERSION < 20100412
if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) {
return FAILURE;
}
#endif
if (php_check_open_basedir(fname TSRMLS_CC)) {
return FAILURE;
}
fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, &actual);
if (!fp) {
if (error) {
spprintf(error, 0, "unable to open phar for reading \"%s\"", fname);
}
if (actual) {
efree(actual);
}
return FAILURE;
}
if (actual) {
fname = actual;
fname_len = strlen(actual);
}
ret = phar_open_from_fp(fp, fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, 0, error TSRMLS_CC);
if (actual) {
efree(actual);
}
return ret;
}
/* }}} */
/**
* Validate the CRC32 of a file opened from within the phar
*/
int phar_postprocess_file(phar_entry_data *idata, php_uint32 crc32, char **error, int process_zip TSRMLS_DC) /* {{{ */
{
php_uint32 crc = ~0;
int len = idata->internal_file->uncompressed_filesize;
php_stream *fp = idata->fp;
phar_entry_info *entry = idata->internal_file;
if (error) {
*error = NULL;
}
if (entry->is_zip && process_zip > 0) {
/* verify local file header */
phar_zip_file_header local;
phar_zip_data_desc desc;
if (SUCCESS != phar_open_archive_fp(idata->phar TSRMLS_CC)) {
spprintf(error, 0, "phar error: unable to open zip-based phar archive \"%s\" to verify local file header for file \"%s\"", idata->phar->fname, entry->filename);
return FAILURE;
}
php_stream_seek(phar_get_entrypfp(idata->internal_file TSRMLS_CC), entry->header_offset, SEEK_SET);
if (sizeof(local) != php_stream_read(phar_get_entrypfp(idata->internal_file TSRMLS_CC), (char *) &local, sizeof(local))) {
spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (cannot read local file header for file \"%s\")", idata->phar->fname, entry->filename);
return FAILURE;
}
/* check for data descriptor */
if (((PHAR_ZIP_16(local.flags)) & 0x8) == 0x8) {
php_stream_seek(phar_get_entrypfp(idata->internal_file TSRMLS_CC),
entry->header_offset + sizeof(local) +
PHAR_ZIP_16(local.filename_len) +
PHAR_ZIP_16(local.extra_len) +
entry->compressed_filesize, SEEK_SET);
if (sizeof(desc) != php_stream_read(phar_get_entrypfp(idata->internal_file TSRMLS_CC),
(char *) &desc, sizeof(desc))) {
spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (cannot read local data descriptor for file \"%s\")", idata->phar->fname, entry->filename);
return FAILURE;
}
if (desc.signature[0] == 'P' && desc.signature[1] == 'K') {
memcpy(&(local.crc32), &(desc.crc32), 12);
} else {
/* old data descriptors have no signature */
memcpy(&(local.crc32), &desc, 12);
}
}
/* verify local header */
if (entry->filename_len != PHAR_ZIP_16(local.filename_len) || entry->crc32 != PHAR_ZIP_32(local.crc32) || entry->uncompressed_filesize != PHAR_ZIP_32(local.uncompsize) || entry->compressed_filesize != PHAR_ZIP_32(local.compsize)) {
spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (local header of file \"%s\" does not match central directory)", idata->phar->fname, entry->filename);
return FAILURE;
}
/* construct actual offset to file start - local extra_len can be different from central extra_len */
entry->offset = entry->offset_abs =
sizeof(local) + entry->header_offset + PHAR_ZIP_16(local.filename_len) + PHAR_ZIP_16(local.extra_len);
if (idata->zero && idata->zero != entry->offset_abs) {
idata->zero = entry->offset_abs;
}
}
if (process_zip == 1) {
return SUCCESS;
}
php_stream_seek(fp, idata->zero, SEEK_SET);
while (len--) {
CRC32(crc, php_stream_getc(fp));
}
php_stream_seek(fp, idata->zero, SEEK_SET);
if (~crc == crc32) {
entry->is_crc_checked = 1;
return SUCCESS;
} else {
spprintf(error, 0, "phar error: internal corruption of phar \"%s\" (crc32 mismatch on file \"%s\")", idata->phar->fname, entry->filename);
return FAILURE;
}
}
/* }}} */
static inline void phar_set_32(char *buffer, int var) /* {{{ */
{
#ifdef WORDS_BIGENDIAN
*((buffer) + 3) = (unsigned char) (((var) >> 24) & 0xFF);
*((buffer) + 2) = (unsigned char) (((var) >> 16) & 0xFF);
*((buffer) + 1) = (unsigned char) (((var) >> 8) & 0xFF);
*((buffer) + 0) = (unsigned char) ((var) & 0xFF);
#else
memcpy(buffer, &var, sizeof(var));
#endif
} /* }}} */
static int phar_flush_clean_deleted_apply(void *data TSRMLS_DC) /* {{{ */
{
phar_entry_info *entry = (phar_entry_info *)data;
if (entry->fp_refcount <= 0 && entry->is_deleted) {
return ZEND_HASH_APPLY_REMOVE;
} else {
return ZEND_HASH_APPLY_KEEP;
}
}
/* }}} */
#include "stub.h"
char *phar_create_default_stub(const char *index_php, const char *web_index, size_t *len, char **error TSRMLS_DC) /* {{{ */
{
char *stub = NULL;
int index_len, web_len;
size_t dummy;
if (!len) {
len = &dummy;
}
if (error) {
*error = NULL;
}
if (!index_php) {
index_php = "index.php";
}
if (!web_index) {
web_index = "index.php";
}
index_len = strlen(index_php);
web_len = strlen(web_index);
if (index_len > 400) {
/* ridiculous size not allowed for index.php startup filename */
if (error) {
spprintf(error, 0, "Illegal filename passed in for stub creation, was %d characters long, and only 400 or less is allowed", index_len);
return NULL;
}
}
if (web_len > 400) {
/* ridiculous size not allowed for index.php startup filename */
if (error) {
spprintf(error, 0, "Illegal web filename passed in for stub creation, was %d characters long, and only 400 or less is allowed", web_len);
return NULL;
}
}
phar_get_stub(index_php, web_index, len, &stub, index_len+1, web_len+1 TSRMLS_CC);
return stub;
}
/* }}} */
/**
* Save phar contents to disk
*
* user_stub contains either a string, or a resource pointer, if len is a negative length.
* user_stub and len should be both 0 if the default or existing stub should be used
*/
int phar_flush(phar_archive_data *phar, char *user_stub, long len, int convert, char **error TSRMLS_DC) /* {{{ */
{
char halt_stub[] = "__HALT_COMPILER();";
char *newstub, *tmp;
phar_entry_info *entry, *newentry;
int halt_offset, restore_alias_len, global_flags = 0, closeoldfile;
char *pos, has_dirs = 0;
char manifest[18], entry_buffer[24];
off_t manifest_ftell;
long offset;
size_t wrote;
php_uint32 manifest_len, mytime, loc, new_manifest_count;
php_uint32 newcrc32;
php_stream *file, *oldfile, *newfile, *stubfile;
php_stream_filter *filter;
php_serialize_data_t metadata_hash;
smart_str main_metadata_str = {0};
int free_user_stub, free_fp = 1, free_ufp = 1;
int manifest_hack = 0;
if (phar->is_persistent) {
if (error) {
spprintf(error, 0, "internal error: attempt to flush cached zip-based phar \"%s\"", phar->fname);
}
return EOF;
}
if (error) {
*error = NULL;
}
if (!zend_hash_num_elements(&phar->manifest) && !user_stub) {
return EOF;
}
zend_hash_clean(&phar->virtual_dirs);
if (phar->is_zip) {
return phar_zip_flush(phar, user_stub, len, convert, error TSRMLS_CC);
}
if (phar->is_tar) {
return phar_tar_flush(phar, user_stub, len, convert, error TSRMLS_CC);
}
if (PHAR_G(readonly)) {
return EOF;
}
if (phar->fp && !phar->is_brandnew) {
oldfile = phar->fp;
closeoldfile = 0;
php_stream_rewind(oldfile);
} else {
oldfile = php_stream_open_wrapper(phar->fname, "rb", 0, NULL);
closeoldfile = oldfile != NULL;
}
newfile = php_stream_fopen_tmpfile();
if (!newfile) {
if (error) {
spprintf(error, 0, "unable to create temporary file");
}
if (closeoldfile) {
php_stream_close(oldfile);
}
return EOF;
}
if (user_stub) {
if (len < 0) {
/* resource passed in */
if (!(php_stream_from_zval_no_verify(stubfile, (zval **)user_stub))) {
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
if (error) {
spprintf(error, 0, "unable to access resource to copy stub to new phar \"%s\"", phar->fname);
}
return EOF;
}
if (len == -1) {
len = PHP_STREAM_COPY_ALL;
} else {
len = -len;
}
user_stub = 0;
if (!(len = php_stream_copy_to_mem(stubfile, &user_stub, len, 0)) || !user_stub) {
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
if (error) {
spprintf(error, 0, "unable to read resource to copy stub to new phar \"%s\"", phar->fname);
}
return EOF;
}
free_user_stub = 1;
} else {
free_user_stub = 0;
}
tmp = estrndup(user_stub, len);
if ((pos = php_stristr(tmp, halt_stub, len, sizeof(halt_stub) - 1)) == NULL) {
efree(tmp);
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
if (error) {
spprintf(error, 0, "illegal stub for phar \"%s\"", phar->fname);
}
if (free_user_stub) {
efree(user_stub);
}
return EOF;
}
pos = user_stub + (pos - tmp);
efree(tmp);
len = pos - user_stub + 18;
if ((size_t)len != php_stream_write(newfile, user_stub, len)
|| 5 != php_stream_write(newfile, " ?>\r\n", 5)) {
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
if (error) {
spprintf(error, 0, "unable to create stub from string in new phar \"%s\"", phar->fname);
}
if (free_user_stub) {
efree(user_stub);
}
return EOF;
}
phar->halt_offset = len + 5;
if (free_user_stub) {
efree(user_stub);
}
} else {
size_t written;
if (!user_stub && phar->halt_offset && oldfile && !phar->is_brandnew) {
php_stream_copy_to_stream_ex(oldfile, newfile, phar->halt_offset, &written);
newstub = NULL;
} else {
/* this is either a brand new phar or a default stub overwrite */
newstub = phar_create_default_stub(NULL, NULL, &(phar->halt_offset), NULL TSRMLS_CC);
written = php_stream_write(newfile, newstub, phar->halt_offset);
}
if (phar->halt_offset != written) {
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
if (error) {
if (newstub) {
spprintf(error, 0, "unable to create stub in new phar \"%s\"", phar->fname);
} else {
spprintf(error, 0, "unable to copy stub of old phar to new phar \"%s\"", phar->fname);
}
}
if (newstub) {
efree(newstub);
}
return EOF;
}
if (newstub) {
efree(newstub);
}
}
manifest_ftell = php_stream_tell(newfile);
halt_offset = manifest_ftell;
/* Check whether we can get rid of some of the deleted entries which are
* unused. However some might still be in use so even after this clean-up
* we need to skip entries marked is_deleted. */
zend_hash_apply(&phar->manifest, phar_flush_clean_deleted_apply TSRMLS_CC);
/* compress as necessary, calculate crcs, serialize meta-data, manifest size, and file sizes */
main_metadata_str.c = 0;
if (phar->metadata) {
PHP_VAR_SERIALIZE_INIT(metadata_hash);
php_var_serialize(&main_metadata_str, &phar->metadata, &metadata_hash TSRMLS_CC);
PHP_VAR_SERIALIZE_DESTROY(metadata_hash);
} else {
main_metadata_str.len = 0;
}
new_manifest_count = 0;
offset = 0;
for (zend_hash_internal_pointer_reset(&phar->manifest);
zend_hash_has_more_elements(&phar->manifest) == SUCCESS;
zend_hash_move_forward(&phar->manifest)) {
if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) {
continue;
}
if (entry->cfp) {
/* did we forget to get rid of cfp last time? */
php_stream_close(entry->cfp);
entry->cfp = 0;
}
if (entry->is_deleted || entry->is_mounted) {
/* remove this from the new phar */
continue;
}
if (!entry->is_modified && entry->fp_refcount) {
/* open file pointers refer to this fp, do not free the stream */
switch (entry->fp_type) {
case PHAR_FP:
free_fp = 0;
break;
case PHAR_UFP:
free_ufp = 0;
default:
break;
}
}
/* after excluding deleted files, calculate manifest size in bytes and number of entries */
++new_manifest_count;
phar_add_virtual_dirs(phar, entry->filename, entry->filename_len TSRMLS_CC);
if (entry->is_dir) {
/* we use this to calculate API version, 1.1.1 is used for phars with directories */
has_dirs = 1;
}
if (entry->metadata) {
if (entry->metadata_str.c) {
smart_str_free(&entry->metadata_str);
}
entry->metadata_str.c = 0;
entry->metadata_str.len = 0;
PHP_VAR_SERIALIZE_INIT(metadata_hash);
php_var_serialize(&entry->metadata_str, &entry->metadata, &metadata_hash TSRMLS_CC);
PHP_VAR_SERIALIZE_DESTROY(metadata_hash);
} else {
if (entry->metadata_str.c) {
smart_str_free(&entry->metadata_str);
}
entry->metadata_str.c = 0;
entry->metadata_str.len = 0;
}
/* 32 bits for filename length, length of filename, manifest + metadata, and add 1 for trailing / if a directory */
offset += 4 + entry->filename_len + sizeof(entry_buffer) + entry->metadata_str.len + (entry->is_dir ? 1 : 0);
/* compress and rehash as necessary */
if ((oldfile && !entry->is_modified) || entry->is_dir) {
if (entry->fp_type == PHAR_UFP) {
/* reset so we can copy the compressed data over */
entry->fp_type = PHAR_FP;
}
continue;
}
if (!phar_get_efp(entry, 0 TSRMLS_CC)) {
/* re-open internal file pointer just-in-time */
newentry = phar_open_jit(phar, entry, error TSRMLS_CC);
if (!newentry) {
/* major problem re-opening, so we ignore this file and the error */
efree(*error);
*error = NULL;
continue;
}
entry = newentry;
}
file = phar_get_efp(entry, 0 TSRMLS_CC);
if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC)) {
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
if (error) {
spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname);
}
return EOF;
}
newcrc32 = ~0;
mytime = entry->uncompressed_filesize;
for (loc = 0;loc < mytime; ++loc) {
CRC32(newcrc32, php_stream_getc(file));
}
entry->crc32 = ~newcrc32;
entry->is_crc_checked = 1;
if (!(entry->flags & PHAR_ENT_COMPRESSION_MASK)) {
/* not compressed */
entry->compressed_filesize = entry->uncompressed_filesize;
continue;
}
filter = php_stream_filter_create(phar_compress_filter(entry, 0), NULL, 0 TSRMLS_CC);
if (!filter) {
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
if (entry->flags & PHAR_ENT_COMPRESSED_GZ) {
if (error) {
spprintf(error, 0, "unable to gzip compress file \"%s\" to new phar \"%s\"", entry->filename, phar->fname);
}
} else {
if (error) {
spprintf(error, 0, "unable to bzip2 compress file \"%s\" to new phar \"%s\"", entry->filename, phar->fname);
}
}
return EOF;
}
/* create new file that holds the compressed version */
/* work around inability to specify freedom in write and strictness
in read count */
entry->cfp = php_stream_fopen_tmpfile();
if (!entry->cfp) {
if (error) {
spprintf(error, 0, "unable to create temporary file");
}
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
return EOF;
}
php_stream_flush(file);
if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) {
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
if (error) {
spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname);
}
return EOF;
}
php_stream_filter_append((&entry->cfp->writefilters), filter);
if (SUCCESS != php_stream_copy_to_stream_ex(file, entry->cfp, entry->uncompressed_filesize, NULL)) {
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
if (error) {
spprintf(error, 0, "unable to copy compressed file contents of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname);
}
return EOF;
}
php_stream_filter_flush(filter, 1);
php_stream_flush(entry->cfp);
php_stream_filter_remove(filter, 1 TSRMLS_CC);
php_stream_seek(entry->cfp, 0, SEEK_END);
entry->compressed_filesize = (php_uint32) php_stream_tell(entry->cfp);
/* generate crc on compressed file */
php_stream_rewind(entry->cfp);
entry->old_flags = entry->flags;
entry->is_modified = 1;
global_flags |= (entry->flags & PHAR_ENT_COMPRESSION_MASK);
}
global_flags |= PHAR_HDR_SIGNATURE;
/* write out manifest pre-header */
/* 4: manifest length
* 4: manifest entry count
* 2: phar version
* 4: phar global flags
* 4: alias length
* ?: the alias itself
* 4: phar metadata length
* ?: phar metadata
*/
restore_alias_len = phar->alias_len;
if (phar->is_temporary_alias) {
phar->alias_len = 0;
}
manifest_len = offset + phar->alias_len + sizeof(manifest) + main_metadata_str.len;
phar_set_32(manifest, manifest_len);
/* Hack - see bug #65028, add padding byte to the end of the manifest */
if(manifest[0] == '\r' || manifest[0] == '\n') {
manifest_len++;
phar_set_32(manifest, manifest_len);
manifest_hack = 1;
}
phar_set_32(manifest+4, new_manifest_count);
if (has_dirs) {
*(manifest + 8) = (unsigned char) (((PHAR_API_VERSION) >> 8) & 0xFF);
*(manifest + 9) = (unsigned char) (((PHAR_API_VERSION) & 0xF0));
} else {
*(manifest + 8) = (unsigned char) (((PHAR_API_VERSION_NODIR) >> 8) & 0xFF);
*(manifest + 9) = (unsigned char) (((PHAR_API_VERSION_NODIR) & 0xF0));
}
phar_set_32(manifest+10, global_flags);
phar_set_32(manifest+14, phar->alias_len);
/* write the manifest header */
if (sizeof(manifest) != php_stream_write(newfile, manifest, sizeof(manifest))
|| (size_t)phar->alias_len != php_stream_write(newfile, phar->alias, phar->alias_len)) {
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
phar->alias_len = restore_alias_len;
if (error) {
spprintf(error, 0, "unable to write manifest header of new phar \"%s\"", phar->fname);
}
return EOF;
}
phar->alias_len = restore_alias_len;
phar_set_32(manifest, main_metadata_str.len);
if (4 != php_stream_write(newfile, manifest, 4) || (main_metadata_str.len
&& main_metadata_str.len != php_stream_write(newfile, main_metadata_str.c, main_metadata_str.len))) {
smart_str_free(&main_metadata_str);
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
phar->alias_len = restore_alias_len;
if (error) {
spprintf(error, 0, "unable to write manifest meta-data of new phar \"%s\"", phar->fname);
}
return EOF;
}
smart_str_free(&main_metadata_str);
/* re-calculate the manifest location to simplify later code */
manifest_ftell = php_stream_tell(newfile);
/* now write the manifest */
for (zend_hash_internal_pointer_reset(&phar->manifest);
zend_hash_has_more_elements(&phar->manifest) == SUCCESS;
zend_hash_move_forward(&phar->manifest)) {
if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) {
continue;
}
if (entry->is_deleted || entry->is_mounted) {
/* remove this from the new phar if deleted, ignore if mounted */
continue;
}
if (entry->is_dir) {
/* add 1 for trailing slash */
phar_set_32(entry_buffer, entry->filename_len + 1);
} else {
phar_set_32(entry_buffer, entry->filename_len);
}
if (4 != php_stream_write(newfile, entry_buffer, 4)
|| entry->filename_len != php_stream_write(newfile, entry->filename, entry->filename_len)
|| (entry->is_dir && 1 != php_stream_write(newfile, "/", 1))) {
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
if (error) {
if (entry->is_dir) {
spprintf(error, 0, "unable to write filename of directory \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname);
} else {
spprintf(error, 0, "unable to write filename of file \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname);
}
}
return EOF;
}
/* set the manifest meta-data:
4: uncompressed filesize
4: creation timestamp
4: compressed filesize
4: crc32
4: flags
4: metadata-len
+: metadata
*/
mytime = time(NULL);
phar_set_32(entry_buffer, entry->uncompressed_filesize);
phar_set_32(entry_buffer+4, mytime);
phar_set_32(entry_buffer+8, entry->compressed_filesize);
phar_set_32(entry_buffer+12, entry->crc32);
phar_set_32(entry_buffer+16, entry->flags);
phar_set_32(entry_buffer+20, entry->metadata_str.len);
if (sizeof(entry_buffer) != php_stream_write(newfile, entry_buffer, sizeof(entry_buffer))
|| entry->metadata_str.len != php_stream_write(newfile, entry->metadata_str.c, entry->metadata_str.len)) {
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
if (error) {
spprintf(error, 0, "unable to write temporary manifest of file \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname);
}
return EOF;
}
}
/* Hack - see bug #65028, add padding byte to the end of the manifest */
if(manifest_hack) {
if(1 != php_stream_write(newfile, manifest, 1)) {
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
if (error) {
spprintf(error, 0, "unable to write manifest padding byte");
}
return EOF;
}
}
/* now copy the actual file data to the new phar */
offset = php_stream_tell(newfile);
for (zend_hash_internal_pointer_reset(&phar->manifest);
zend_hash_has_more_elements(&phar->manifest) == SUCCESS;
zend_hash_move_forward(&phar->manifest)) {
if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) {
continue;
}
if (entry->is_deleted || entry->is_dir || entry->is_mounted) {
continue;
}
if (entry->cfp) {
file = entry->cfp;
php_stream_rewind(file);
} else {
file = phar_get_efp(entry, 0 TSRMLS_CC);
if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) {
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
if (error) {
spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname);
}
return EOF;
}
}
if (!file) {
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
if (error) {
spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname);
}
return EOF;
}
/* this will have changed for all files that have either changed compression or been modified */
entry->offset = entry->offset_abs = offset;
offset += entry->compressed_filesize;
if (php_stream_copy_to_stream_ex(file, newfile, entry->compressed_filesize, &wrote) == FAILURE) {
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
if (error) {
spprintf(error, 0, "unable to write contents of file \"%s\" to new phar \"%s\"", entry->filename, phar->fname);
}
return EOF;
}
entry->is_modified = 0;
if (entry->cfp) {
php_stream_close(entry->cfp);
entry->cfp = NULL;
}
if (entry->fp_type == PHAR_MOD) {
/* this fp is in use by a phar_entry_data returned by phar_get_entry_data, it will be closed when the phar_entry_data is phar_entry_delref'ed */
if (entry->fp_refcount == 0 && entry->fp != phar->fp && entry->fp != phar->ufp) {
php_stream_close(entry->fp);
}
entry->fp = NULL;
entry->fp_type = PHAR_FP;
} else if (entry->fp_type == PHAR_UFP) {
entry->fp_type = PHAR_FP;
}
}
/* append signature */
if (global_flags & PHAR_HDR_SIGNATURE) {
char sig_buf[4];
php_stream_rewind(newfile);
if (phar->signature) {
efree(phar->signature);
phar->signature = NULL;
}
switch(phar->sig_flags) {
#ifndef PHAR_HASH_OK
case PHAR_SIG_SHA512:
case PHAR_SIG_SHA256:
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
if (error) {
spprintf(error, 0, "unable to write contents of file \"%s\" to new phar \"%s\" with requested hash type", entry->filename, phar->fname);
}
return EOF;
#endif
default: {
char *digest = NULL;
int digest_len;
if (FAILURE == phar_create_signature(phar, newfile, &digest, &digest_len, error TSRMLS_CC)) {
if (error) {
char *save = *error;
spprintf(error, 0, "phar error: unable to write signature: %s", save);
efree(save);
}
if (digest) {
efree(digest);
}
if (closeoldfile) {
php_stream_close(oldfile);
}
php_stream_close(newfile);
return EOF;
}
php_stream_write(newfile, digest, digest_len);
efree(digest);
if (phar->sig_flags == PHAR_SIG_OPENSSL) {
phar_set_32(sig_buf, digest_len);
php_stream_write(newfile, sig_buf, 4);
}
break;
}
}
phar_set_32(sig_buf, phar->sig_flags);
php_stream_write(newfile, sig_buf, 4);
php_stream_write(newfile, "GBMB", 4);
}
/* finally, close the temp file, rename the original phar,
move the temp to the old phar, unlink the old phar, and reload it into memory
*/
if (phar->fp && free_fp) {
php_stream_close(phar->fp);
}
if (phar->ufp) {
if (free_ufp) {
php_stream_close(phar->ufp);
}
phar->ufp = NULL;
}
if (closeoldfile) {
php_stream_close(oldfile);
}
phar->internal_file_start = halt_offset + manifest_len + 4;
phar->halt_offset = halt_offset;
phar->is_brandnew = 0;
php_stream_rewind(newfile);
if (phar->donotflush) {
/* deferred flush */
phar->fp = newfile;
} else {
phar->fp = php_stream_open_wrapper(phar->fname, "w+b", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, NULL);
if (!phar->fp) {
phar->fp = newfile;
if (error) {
spprintf(error, 4096, "unable to open new phar \"%s\" for writing", phar->fname);
}
return EOF;
}
if (phar->flags & PHAR_FILE_COMPRESSED_GZ) {
/* to properly compress, we have to tell zlib to add a zlib header */
zval filterparams;
array_init(&filterparams);
add_assoc_long(&filterparams, "window", MAX_WBITS+16);
filter = php_stream_filter_create("zlib.deflate", &filterparams, php_stream_is_persistent(phar->fp) TSRMLS_CC);
zval_dtor(&filterparams);
if (!filter) {
if (error) {
spprintf(error, 4096, "unable to compress all contents of phar \"%s\" using zlib, PHP versions older than 5.2.6 have a buggy zlib", phar->fname);
}
return EOF;
}
php_stream_filter_append(&phar->fp->writefilters, filter);
php_stream_copy_to_stream_ex(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL);
php_stream_filter_flush(filter, 1);
php_stream_filter_remove(filter, 1 TSRMLS_CC);
php_stream_close(phar->fp);
/* use the temp stream as our base */
phar->fp = newfile;
} else if (phar->flags & PHAR_FILE_COMPRESSED_BZ2) {
filter = php_stream_filter_create("bzip2.compress", NULL, php_stream_is_persistent(phar->fp) TSRMLS_CC);
php_stream_filter_append(&phar->fp->writefilters, filter);
php_stream_copy_to_stream_ex(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL);
php_stream_filter_flush(filter, 1);
php_stream_filter_remove(filter, 1 TSRMLS_CC);
php_stream_close(phar->fp);
/* use the temp stream as our base */
phar->fp = newfile;
} else {
php_stream_copy_to_stream_ex(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL);
/* we could also reopen the file in "rb" mode but there is no need for that */
php_stream_close(newfile);
}
}
if (-1 == php_stream_seek(phar->fp, phar->halt_offset, SEEK_SET)) {
if (error) {
spprintf(error, 0, "unable to seek to __HALT_COMPILER(); in new phar \"%s\"", phar->fname);
}
return EOF;
}
return EOF;
}
/* }}} */
#ifdef COMPILE_DL_PHAR
ZEND_GET_MODULE(phar)
#endif
/* {{{ phar_functions[]
*
* Every user visible function must have an entry in phar_functions[].
*/
zend_function_entry phar_functions[] = {
PHP_FE_END
};
/* }}}*/
static size_t phar_zend_stream_reader(void *handle, char *buf, size_t len TSRMLS_DC) /* {{{ */
{
return php_stream_read(phar_get_pharfp((phar_archive_data*)handle TSRMLS_CC), buf, len);
}
/* }}} */
static size_t phar_zend_stream_fsizer(void *handle TSRMLS_DC) /* {{{ */
{
return ((phar_archive_data*)handle)->halt_offset + 32;
} /* }}} */
zend_op_array *(*phar_orig_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC);
#define phar_orig_zend_open zend_stream_open_function
static char *phar_resolve_path(const char *filename, int filename_len TSRMLS_DC)
{
return phar_find_in_include_path((char *) filename, filename_len, NULL TSRMLS_CC);
}
static zend_op_array *phar_compile_file(zend_file_handle *file_handle, int type TSRMLS_DC) /* {{{ */
{
zend_op_array *res;
char *name = NULL;
int failed;
phar_archive_data *phar;
if (!file_handle || !file_handle->filename) {
return phar_orig_compile_file(file_handle, type TSRMLS_CC);
}
if (strstr(file_handle->filename, ".phar") && !strstr(file_handle->filename, "://")) {
if (SUCCESS == phar_open_from_filename((char*)file_handle->filename, strlen(file_handle->filename), NULL, 0, 0, &phar, NULL TSRMLS_CC)) {
if (phar->is_zip || phar->is_tar) {
zend_file_handle f = *file_handle;
/* zip or tar-based phar */
spprintf(&name, 4096, "phar://%s/%s", file_handle->filename, ".phar/stub.php");
if (SUCCESS == phar_orig_zend_open((const char *)name, file_handle TSRMLS_CC)) {
efree(name);
name = NULL;
file_handle->filename = f.filename;
if (file_handle->opened_path) {
efree(file_handle->opened_path);
}
file_handle->opened_path = f.opened_path;
file_handle->free_filename = f.free_filename;
} else {
*file_handle = f;
}
} else if (phar->flags & PHAR_FILE_COMPRESSION_MASK) {
/* compressed phar */
file_handle->type = ZEND_HANDLE_STREAM;
/* we do our own reading directly from the phar, don't change the next line */
file_handle->handle.stream.handle = phar;
file_handle->handle.stream.reader = phar_zend_stream_reader;
file_handle->handle.stream.closer = NULL;
file_handle->handle.stream.fsizer = phar_zend_stream_fsizer;
file_handle->handle.stream.isatty = 0;
phar->is_persistent ?
php_stream_rewind(PHAR_GLOBALS->cached_fp[phar->phar_pos].fp) :
php_stream_rewind(phar->fp);
memset(&file_handle->handle.stream.mmap, 0, sizeof(file_handle->handle.stream.mmap));
}
}
}
zend_try {
failed = 0;
CG(zend_lineno) = 0;
res = phar_orig_compile_file(file_handle, type TSRMLS_CC);
} zend_catch {
failed = 1;
res = NULL;
} zend_end_try();
if (name) {
efree(name);
}
if (failed) {
zend_bailout();
}
return res;
}
/* }}} */
typedef zend_op_array* (zend_compile_t)(zend_file_handle*, int TSRMLS_DC);
typedef zend_compile_t* (compile_hook)(zend_compile_t *ptr);
PHP_GINIT_FUNCTION(phar) /* {{{ */
{
phar_mime_type mime;
memset(phar_globals, 0, sizeof(zend_phar_globals));
phar_globals->readonly = 1;
zend_hash_init(&phar_globals->mime_types, 0, NULL, NULL, 1);
#define PHAR_SET_MIME(mimetype, ret, fileext) \
mime.mime = mimetype; \
mime.len = sizeof((mimetype))+1; \
mime.type = ret; \
zend_hash_add(&phar_globals->mime_types, fileext, sizeof(fileext)-1, (void *)&mime, sizeof(phar_mime_type), NULL); \
PHAR_SET_MIME("text/html", PHAR_MIME_PHPS, "phps")
PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "c")
PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "cc")
PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "cpp")
PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "c++")
PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "dtd")
PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "h")
PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "log")
PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "rng")
PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "txt")
PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "xsd")
PHAR_SET_MIME("", PHAR_MIME_PHP, "php")
PHAR_SET_MIME("", PHAR_MIME_PHP, "inc")
PHAR_SET_MIME("video/avi", PHAR_MIME_OTHER, "avi")
PHAR_SET_MIME("image/bmp", PHAR_MIME_OTHER, "bmp")
PHAR_SET_MIME("text/css", PHAR_MIME_OTHER, "css")
PHAR_SET_MIME("image/gif", PHAR_MIME_OTHER, "gif")
PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "htm")
PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "html")
PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "htmls")
PHAR_SET_MIME("image/x-ico", PHAR_MIME_OTHER, "ico")
PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpe")
PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpg")
PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpeg")
PHAR_SET_MIME("application/x-javascript", PHAR_MIME_OTHER, "js")
PHAR_SET_MIME("audio/midi", PHAR_MIME_OTHER, "midi")
PHAR_SET_MIME("audio/midi", PHAR_MIME_OTHER, "mid")
PHAR_SET_MIME("audio/mod", PHAR_MIME_OTHER, "mod")
PHAR_SET_MIME("movie/quicktime", PHAR_MIME_OTHER, "mov")
PHAR_SET_MIME("audio/mp3", PHAR_MIME_OTHER, "mp3")
PHAR_SET_MIME("video/mpeg", PHAR_MIME_OTHER, "mpg")
PHAR_SET_MIME("video/mpeg", PHAR_MIME_OTHER, "mpeg")
PHAR_SET_MIME("application/pdf", PHAR_MIME_OTHER, "pdf")
PHAR_SET_MIME("image/png", PHAR_MIME_OTHER, "png")
PHAR_SET_MIME("application/shockwave-flash", PHAR_MIME_OTHER, "swf")
PHAR_SET_MIME("image/tiff", PHAR_MIME_OTHER, "tif")
PHAR_SET_MIME("image/tiff", PHAR_MIME_OTHER, "tiff")
PHAR_SET_MIME("audio/wav", PHAR_MIME_OTHER, "wav")
PHAR_SET_MIME("image/xbm", PHAR_MIME_OTHER, "xbm")
PHAR_SET_MIME("text/xml", PHAR_MIME_OTHER, "xml")
phar_restore_orig_functions(TSRMLS_C);
}
/* }}} */
PHP_GSHUTDOWN_FUNCTION(phar) /* {{{ */
{
zend_hash_destroy(&phar_globals->mime_types);
}
/* }}} */
PHP_MINIT_FUNCTION(phar) /* {{{ */
{
REGISTER_INI_ENTRIES();
phar_orig_compile_file = zend_compile_file;
zend_compile_file = phar_compile_file;
phar_save_resolve_path = zend_resolve_path;
zend_resolve_path = phar_resolve_path;
phar_object_init(TSRMLS_C);
phar_intercept_functions_init(TSRMLS_C);
phar_save_orig_functions(TSRMLS_C);
return php_register_url_stream_wrapper("phar", &php_stream_phar_wrapper TSRMLS_CC);
}
/* }}} */
PHP_MSHUTDOWN_FUNCTION(phar) /* {{{ */
{
php_unregister_url_stream_wrapper("phar" TSRMLS_CC);
phar_intercept_functions_shutdown(TSRMLS_C);
if (zend_compile_file == phar_compile_file) {
zend_compile_file = phar_orig_compile_file;
}
if (PHAR_G(manifest_cached)) {
zend_hash_destroy(&(cached_phars));
zend_hash_destroy(&(cached_alias));
}
return SUCCESS;
}
/* }}} */
void phar_request_initialize(TSRMLS_D) /* {{{ */
{
if (!PHAR_GLOBALS->request_init)
{
PHAR_G(last_phar) = NULL;
PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
PHAR_G(has_bz2) = zend_hash_exists(&module_registry, "bz2", sizeof("bz2"));
PHAR_G(has_zlib) = zend_hash_exists(&module_registry, "zlib", sizeof("zlib"));
PHAR_GLOBALS->request_init = 1;
PHAR_GLOBALS->request_ends = 0;
PHAR_GLOBALS->request_done = 0;
zend_hash_init(&(PHAR_GLOBALS->phar_fname_map), 5, zend_get_hash_value, destroy_phar_data, 0);
zend_hash_init(&(PHAR_GLOBALS->phar_persist_map), 5, zend_get_hash_value, NULL, 0);
zend_hash_init(&(PHAR_GLOBALS->phar_alias_map), 5, zend_get_hash_value, NULL, 0);
if (PHAR_G(manifest_cached)) {
phar_archive_data **pphar;
phar_entry_fp *stuff = (phar_entry_fp *) ecalloc(zend_hash_num_elements(&cached_phars), sizeof(phar_entry_fp));
for (zend_hash_internal_pointer_reset(&cached_phars);
zend_hash_get_current_data(&cached_phars, (void **)&pphar) == SUCCESS;
zend_hash_move_forward(&cached_phars)) {
stuff[pphar[0]->phar_pos].manifest = (phar_entry_fp_info *) ecalloc( zend_hash_num_elements(&(pphar[0]->manifest)), sizeof(phar_entry_fp_info));
}
PHAR_GLOBALS->cached_fp = stuff;
}
PHAR_GLOBALS->phar_SERVER_mung_list = 0;
PHAR_G(cwd) = NULL;
PHAR_G(cwd_len) = 0;
PHAR_G(cwd_init) = 0;
}
}
/* }}} */
PHP_RSHUTDOWN_FUNCTION(phar) /* {{{ */
{
int i;
PHAR_GLOBALS->request_ends = 1;
if (PHAR_GLOBALS->request_init)
{
phar_release_functions(TSRMLS_C);
zend_hash_destroy(&(PHAR_GLOBALS->phar_alias_map));
PHAR_GLOBALS->phar_alias_map.arBuckets = NULL;
zend_hash_destroy(&(PHAR_GLOBALS->phar_fname_map));
PHAR_GLOBALS->phar_fname_map.arBuckets = NULL;
zend_hash_destroy(&(PHAR_GLOBALS->phar_persist_map));
PHAR_GLOBALS->phar_persist_map.arBuckets = NULL;
PHAR_GLOBALS->phar_SERVER_mung_list = 0;
if (PHAR_GLOBALS->cached_fp) {
for (i = 0; i < zend_hash_num_elements(&cached_phars); ++i) {
if (PHAR_GLOBALS->cached_fp[i].fp) {
php_stream_close(PHAR_GLOBALS->cached_fp[i].fp);
}
if (PHAR_GLOBALS->cached_fp[i].ufp) {
php_stream_close(PHAR_GLOBALS->cached_fp[i].ufp);
}
efree(PHAR_GLOBALS->cached_fp[i].manifest);
}
efree(PHAR_GLOBALS->cached_fp);
PHAR_GLOBALS->cached_fp = 0;
}
PHAR_GLOBALS->request_init = 0;
if (PHAR_G(cwd)) {
efree(PHAR_G(cwd));
}
PHAR_G(cwd) = NULL;
PHAR_G(cwd_len) = 0;
PHAR_G(cwd_init) = 0;
}
PHAR_GLOBALS->request_done = 1;
return SUCCESS;
}
/* }}} */
PHP_MINFO_FUNCTION(phar) /* {{{ */
{
phar_request_initialize(TSRMLS_C);
php_info_print_table_start();
php_info_print_table_header(2, "Phar: PHP Archive support", "enabled");
php_info_print_table_row(2, "Phar EXT version", PHP_PHAR_VERSION);
php_info_print_table_row(2, "Phar API version", PHP_PHAR_API_VERSION);
php_info_print_table_row(2, "SVN revision", "$Id$");
php_info_print_table_row(2, "Phar-based phar archives", "enabled");
php_info_print_table_row(2, "Tar-based phar archives", "enabled");
php_info_print_table_row(2, "ZIP-based phar archives", "enabled");
if (PHAR_G(has_zlib)) {
php_info_print_table_row(2, "gzip compression", "enabled");
} else {
php_info_print_table_row(2, "gzip compression", "disabled (install ext/zlib)");
}
if (PHAR_G(has_bz2)) {
php_info_print_table_row(2, "bzip2 compression", "enabled");
} else {
php_info_print_table_row(2, "bzip2 compression", "disabled (install pecl/bz2)");
}
#ifdef PHAR_HAVE_OPENSSL
php_info_print_table_row(2, "Native OpenSSL support", "enabled");
#else
if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) {
php_info_print_table_row(2, "OpenSSL support", "enabled");
} else {
php_info_print_table_row(2, "OpenSSL support", "disabled (install ext/openssl)");
}
#endif
php_info_print_table_end();
php_info_print_box_start(0);
PUTS("Phar based on pear/PHP_Archive, original concept by Davey Shafik.");
PUTS(!sapi_module.phpinfo_as_text?"<br />":"\n");
PUTS("Phar fully realized by Gregory Beaver and Marcus Boerger.");
PUTS(!sapi_module.phpinfo_as_text?"<br />":"\n");
PUTS("Portions of tar implementation Copyright (c) 2003-2009 Tim Kientzle.");
php_info_print_box_end();
DISPLAY_INI_ENTRIES();
}
/* }}} */
/* {{{ phar_module_entry
*/
static const zend_module_dep phar_deps[] = {
ZEND_MOD_OPTIONAL("apc")
ZEND_MOD_OPTIONAL("bz2")
ZEND_MOD_OPTIONAL("openssl")
ZEND_MOD_OPTIONAL("zlib")
ZEND_MOD_OPTIONAL("standard")
#if defined(HAVE_HASH) && !defined(COMPILE_DL_HASH)
ZEND_MOD_REQUIRED("hash")
#endif
#if HAVE_SPL
ZEND_MOD_REQUIRED("spl")
#endif
ZEND_MOD_END
};
zend_module_entry phar_module_entry = {
STANDARD_MODULE_HEADER_EX, NULL,
phar_deps,
"Phar",
phar_functions,
PHP_MINIT(phar),
PHP_MSHUTDOWN(phar),
NULL,
PHP_RSHUTDOWN(phar),
PHP_MINFO(phar),
PHP_PHAR_VERSION,
PHP_MODULE_GLOBALS(phar), /* globals descriptor */
PHP_GINIT(phar), /* globals ctor */
PHP_GSHUTDOWN(phar), /* globals dtor */
NULL, /* post deactivate */
STANDARD_MODULE_PROPERTIES_EX
};
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4824_0 |
crossvul-cpp_data_good_930_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% SSSSS TTTTT AAA TTTTT IIIII SSSSS TTTTT IIIII CCCC %
% SS T A A T I SS T I C %
% SSS T AAAAA T I SSS T I C %
% SS T A A T I SS T I C %
% SSSSS T A A T IIIII SSSSS T IIIII CCCC %
% %
% %
% MagickCore Image Statistical Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/accelerate-private.h"
#include "magick/animate.h"
#include "magick/animate.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/cache-private.h"
#include "magick/cache-view.h"
#include "magick/client.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/composite.h"
#include "magick/composite-private.h"
#include "magick/compress.h"
#include "magick/constitute.h"
#include "magick/deprecate.h"
#include "magick/display.h"
#include "magick/draw.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/gem.h"
#include "magick/geometry.h"
#include "magick/list.h"
#include "magick/image-private.h"
#include "magick/magic.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/paint.h"
#include "magick/pixel-private.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantize.h"
#include "magick/random_.h"
#include "magick/random-private.h"
#include "magick/resource_.h"
#include "magick/segment.h"
#include "magick/semaphore.h"
#include "magick/signature-private.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/thread-private.h"
#include "magick/timer.h"
#include "magick/utility.h"
#include "magick/version.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E v a l u a t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% EvaluateImage() applies a value to the image with an arithmetic, relational,
% or logical operator to an image. Use these operations to lighten or darken
% an image, to increase or decrease contrast in an image, or to produce the
% "negative" of an image.
%
% The format of the EvaluateImageChannel method is:
%
% MagickBooleanType EvaluateImage(Image *image,
% const MagickEvaluateOperator op,const double value,
% ExceptionInfo *exception)
% MagickBooleanType EvaluateImages(Image *images,
% const MagickEvaluateOperator op,const double value,
% ExceptionInfo *exception)
% MagickBooleanType EvaluateImageChannel(Image *image,
% const ChannelType channel,const MagickEvaluateOperator op,
% const double value,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o op: A channel op.
%
% o value: A value value.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickPixelPacket **DestroyPixelThreadSet(MagickPixelPacket **pixels)
{
register ssize_t
i;
assert(pixels != (MagickPixelPacket **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (pixels[i] != (MagickPixelPacket *) NULL)
pixels[i]=(MagickPixelPacket *) RelinquishMagickMemory(pixels[i]);
pixels=(MagickPixelPacket **) RelinquishMagickMemory(pixels);
return(pixels);
}
static MagickPixelPacket **AcquirePixelThreadSet(const Image *images)
{
const Image
*next;
MagickPixelPacket
**pixels;
register ssize_t
i,
j;
size_t
columns,
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixels=(MagickPixelPacket **) AcquireQuantumMemory(number_threads,
sizeof(*pixels));
if (pixels == (MagickPixelPacket **) NULL)
return((MagickPixelPacket **) NULL);
(void) memset(pixels,0,number_threads*sizeof(*pixels));
columns=images->columns;
for (next=images; next != (Image *) NULL; next=next->next)
columns=MagickMax(next->columns,columns);
for (i=0; i < (ssize_t) number_threads; i++)
{
pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(columns,
sizeof(**pixels));
if (pixels[i] == (MagickPixelPacket *) NULL)
return(DestroyPixelThreadSet(pixels));
for (j=0; j < (ssize_t) columns; j++)
GetMagickPixelPacket(images,&pixels[i][j]);
}
return(pixels);
}
static inline double EvaluateMax(const double x,const double y)
{
if (x > y)
return(x);
return(y);
}
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int IntensityCompare(const void *x,const void *y)
{
const MagickPixelPacket
*color_1,
*color_2;
int
intensity;
color_1=(const MagickPixelPacket *) x;
color_2=(const MagickPixelPacket *) y;
intensity=(int) MagickPixelIntensity(color_2)-(int)
MagickPixelIntensity(color_1);
return(intensity);
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info,
const Quantum pixel,const MagickEvaluateOperator op,
const MagickRealType value)
{
MagickRealType
result;
result=0.0;
switch (op)
{
case UndefinedEvaluateOperator:
break;
case AbsEvaluateOperator:
{
result=(MagickRealType) fabs((double) (pixel+value));
break;
}
case AddEvaluateOperator:
{
result=(MagickRealType) (pixel+value);
break;
}
case AddModulusEvaluateOperator:
{
/*
This returns a 'floored modulus' of the addition which is a
positive result. It differs from % or fmod() which returns a
'truncated modulus' result, where floor() is replaced by trunc()
and could return a negative result (which is clipped).
*/
result=pixel+value;
result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0));
break;
}
case AndEvaluateOperator:
{
result=(MagickRealType) ((size_t) pixel & (size_t) (value+0.5));
break;
}
case CosineEvaluateOperator:
{
result=(MagickRealType) (QuantumRange*(0.5*cos((double) (2.0*MagickPI*
QuantumScale*pixel*value))+0.5));
break;
}
case DivideEvaluateOperator:
{
result=pixel/(value == 0.0 ? 1.0 : value);
break;
}
case ExponentialEvaluateOperator:
{
result=(MagickRealType) (QuantumRange*exp((double) (value*QuantumScale*
pixel)));
break;
}
case GaussianNoiseEvaluateOperator:
{
result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
GaussianNoise,value);
break;
}
case ImpulseNoiseEvaluateOperator:
{
result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
ImpulseNoise,value);
break;
}
case LaplacianNoiseEvaluateOperator:
{
result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
LaplacianNoise,value);
break;
}
case LeftShiftEvaluateOperator:
{
result=(MagickRealType) ((size_t) pixel << (size_t) (value+0.5));
break;
}
case LogEvaluateOperator:
{
if ((QuantumScale*pixel) >= MagickEpsilon)
result=(MagickRealType) (QuantumRange*log((double) (QuantumScale*value*
pixel+1.0))/log((double) (value+1.0)));
break;
}
case MaxEvaluateOperator:
{
result=(MagickRealType) EvaluateMax((double) pixel,value);
break;
}
case MeanEvaluateOperator:
{
result=(MagickRealType) (pixel+value);
break;
}
case MedianEvaluateOperator:
{
result=(MagickRealType) (pixel+value);
break;
}
case MinEvaluateOperator:
{
result=(MagickRealType) MagickMin((double) pixel,value);
break;
}
case MultiplicativeNoiseEvaluateOperator:
{
result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
MultiplicativeGaussianNoise,value);
break;
}
case MultiplyEvaluateOperator:
{
result=(MagickRealType) (value*pixel);
break;
}
case OrEvaluateOperator:
{
result=(MagickRealType) ((size_t) pixel | (size_t) (value+0.5));
break;
}
case PoissonNoiseEvaluateOperator:
{
result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
PoissonNoise,value);
break;
}
case PowEvaluateOperator:
{
result=(MagickRealType) (QuantumRange*pow((double) (QuantumScale*pixel),
(double) value));
break;
}
case RightShiftEvaluateOperator:
{
result=(MagickRealType) ((size_t) pixel >> (size_t) (value+0.5));
break;
}
case RootMeanSquareEvaluateOperator:
{
result=(MagickRealType) (pixel*pixel+value);
break;
}
case SetEvaluateOperator:
{
result=value;
break;
}
case SineEvaluateOperator:
{
result=(MagickRealType) (QuantumRange*(0.5*sin((double) (2.0*MagickPI*
QuantumScale*pixel*value))+0.5));
break;
}
case SubtractEvaluateOperator:
{
result=(MagickRealType) (pixel-value);
break;
}
case SumEvaluateOperator:
{
result=(MagickRealType) (pixel+value);
break;
}
case ThresholdEvaluateOperator:
{
result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 :
QuantumRange);
break;
}
case ThresholdBlackEvaluateOperator:
{
result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : pixel);
break;
}
case ThresholdWhiteEvaluateOperator:
{
result=(MagickRealType) (((MagickRealType) pixel > value) ? QuantumRange :
pixel);
break;
}
case UniformNoiseEvaluateOperator:
{
result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
UniformNoise,value);
break;
}
case XorEvaluateOperator:
{
result=(MagickRealType) ((size_t) pixel ^ (size_t) (value+0.5));
break;
}
}
return(result);
}
static Image *AcquireImageCanvas(const Image *images,ExceptionInfo *exception)
{
const Image
*p,
*q;
size_t
columns,
number_channels,
rows;
q=images;
columns=images->columns;
rows=images->rows;
number_channels=0;
for (p=images; p != (Image *) NULL; p=p->next)
{
size_t
channels;
channels=3;
if (p->matte != MagickFalse)
channels+=1;
if (p->colorspace == CMYKColorspace)
channels+=1;
if (channels > number_channels)
{
number_channels=channels;
q=p;
}
if (p->columns > columns)
columns=p->columns;
if (p->rows > rows)
rows=p->rows;
}
return(CloneImage(q,columns,rows,MagickTrue,exception));
}
MagickExport MagickBooleanType EvaluateImage(Image *image,
const MagickEvaluateOperator op,const double value,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=EvaluateImageChannel(image,CompositeChannels,op,value,exception);
return(status);
}
MagickExport Image *EvaluateImages(const Image *images,
const MagickEvaluateOperator op,ExceptionInfo *exception)
{
#define EvaluateImageTag "Evaluate/Image"
CacheView
*evaluate_view;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
**magick_restrict evaluate_pixels,
zero;
RandomInfo
**magick_restrict random_info;
size_t
number_images;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
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);
image=AcquireImageCanvas(images,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
InheritException(exception,&image->exception);
image=DestroyImage(image);
return((Image *) NULL);
}
evaluate_pixels=AcquirePixelThreadSet(images);
if (evaluate_pixels == (MagickPixelPacket **) NULL)
{
image=DestroyImage(image);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
return((Image *) NULL);
}
/*
Evaluate image pixels.
*/
status=MagickTrue;
progress=0;
number_images=GetImageListLength(images);
GetMagickPixelPacket(images,&zero);
random_info=AcquireRandomInfoThreadSet();
evaluate_view=AcquireAuthenticCacheView(image,exception);
if (op == MedianEvaluateOperator)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,images,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
CacheView
*image_view;
const Image
*next;
const int
id = GetOpenMPThreadId();
register IndexPacket
*magick_restrict evaluate_indexes;
register MagickPixelPacket
*evaluate_pixel;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view);
evaluate_pixel=evaluate_pixels[id];
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) number_images; i++)
evaluate_pixel[i]=zero;
next=images;
for (i=0; i < (ssize_t) number_images; i++)
{
register const IndexPacket
*indexes;
register const PixelPacket
*p;
image_view=AcquireVirtualCacheView(next,exception);
p=GetCacheViewVirtualPixels(image_view,x,y,1,1,exception);
if (p == (const PixelPacket *) NULL)
{
image_view=DestroyCacheView(image_view);
break;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
evaluate_pixel[i].red=ApplyEvaluateOperator(random_info[id],
GetPixelRed(p),op,evaluate_pixel[i].red);
evaluate_pixel[i].green=ApplyEvaluateOperator(random_info[id],
GetPixelGreen(p),op,evaluate_pixel[i].green);
evaluate_pixel[i].blue=ApplyEvaluateOperator(random_info[id],
GetPixelBlue(p),op,evaluate_pixel[i].blue);
evaluate_pixel[i].opacity=ApplyEvaluateOperator(random_info[id],
GetPixelAlpha(p),op,evaluate_pixel[i].opacity);
if (image->colorspace == CMYKColorspace)
evaluate_pixel[i].index=ApplyEvaluateOperator(random_info[id],
*indexes,op,evaluate_pixel[i].index);
image_view=DestroyCacheView(image_view);
next=GetNextImageInList(next);
}
qsort((void *) evaluate_pixel,number_images,sizeof(*evaluate_pixel),
IntensityCompare);
SetPixelRed(q,ClampToQuantum(evaluate_pixel[i/2].red));
SetPixelGreen(q,ClampToQuantum(evaluate_pixel[i/2].green));
SetPixelBlue(q,ClampToQuantum(evaluate_pixel[i/2].blue));
SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[i/2].opacity));
if (image->colorspace == CMYKColorspace)
SetPixelIndex(evaluate_indexes+i,ClampToQuantum(
evaluate_pixel[i/2].index));
q++;
}
if (SyncCacheViewAuthenticPixels(evaluate_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,EvaluateImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
}
else
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,images,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
CacheView
*image_view;
const Image
*next;
const int
id = GetOpenMPThreadId();
register IndexPacket
*magick_restrict evaluate_indexes;
register ssize_t
i,
x;
register MagickPixelPacket
*evaluate_pixel;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view);
evaluate_pixel=evaluate_pixels[id];
for (x=0; x < (ssize_t) image->columns; x++)
evaluate_pixel[x]=zero;
next=images;
for (i=0; i < (ssize_t) number_images; i++)
{
register const IndexPacket
*indexes;
register const PixelPacket
*p;
image_view=AcquireVirtualCacheView(next,exception);
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,
exception);
if (p == (const PixelPacket *) NULL)
{
image_view=DestroyCacheView(image_view);
break;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
evaluate_pixel[x].red=ApplyEvaluateOperator(random_info[id],
GetPixelRed(p),i == 0 ? AddEvaluateOperator : op,
evaluate_pixel[x].red);
evaluate_pixel[x].green=ApplyEvaluateOperator(random_info[id],
GetPixelGreen(p),i == 0 ? AddEvaluateOperator : op,
evaluate_pixel[x].green);
evaluate_pixel[x].blue=ApplyEvaluateOperator(random_info[id],
GetPixelBlue(p),i == 0 ? AddEvaluateOperator : op,
evaluate_pixel[x].blue);
evaluate_pixel[x].opacity=ApplyEvaluateOperator(random_info[id],
GetPixelAlpha(p),i == 0 ? AddEvaluateOperator : op,
evaluate_pixel[x].opacity);
if (image->colorspace == CMYKColorspace)
evaluate_pixel[x].index=ApplyEvaluateOperator(random_info[id],
GetPixelIndex(indexes+x),i == 0 ? AddEvaluateOperator : op,
evaluate_pixel[x].index);
p++;
}
image_view=DestroyCacheView(image_view);
next=GetNextImageInList(next);
}
if (op == MeanEvaluateOperator)
for (x=0; x < (ssize_t) image->columns; x++)
{
evaluate_pixel[x].red/=number_images;
evaluate_pixel[x].green/=number_images;
evaluate_pixel[x].blue/=number_images;
evaluate_pixel[x].opacity/=number_images;
evaluate_pixel[x].index/=number_images;
}
if (op == RootMeanSquareEvaluateOperator)
for (x=0; x < (ssize_t) image->columns; x++)
{
evaluate_pixel[x].red=sqrt((double) evaluate_pixel[x].red/
number_images);
evaluate_pixel[x].green=sqrt((double) evaluate_pixel[x].green/
number_images);
evaluate_pixel[x].blue=sqrt((double) evaluate_pixel[x].blue/
number_images);
evaluate_pixel[x].opacity=sqrt((double) evaluate_pixel[x].opacity/
number_images);
evaluate_pixel[x].index=sqrt((double) evaluate_pixel[x].index/
number_images);
}
if (op == MultiplyEvaluateOperator)
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
for (j=0; j < (ssize_t) (number_images-1); j++)
{
evaluate_pixel[x].red*=(MagickRealType) QuantumScale;
evaluate_pixel[x].green*=(MagickRealType) QuantumScale;
evaluate_pixel[x].blue*=(MagickRealType) QuantumScale;
evaluate_pixel[x].opacity*=(MagickRealType) QuantumScale;
evaluate_pixel[x].index*=(MagickRealType) QuantumScale;
}
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ClampToQuantum(evaluate_pixel[x].red));
SetPixelGreen(q,ClampToQuantum(evaluate_pixel[x].green));
SetPixelBlue(q,ClampToQuantum(evaluate_pixel[x].blue));
SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[x].opacity));
if (image->colorspace == CMYKColorspace)
SetPixelIndex(evaluate_indexes+x,ClampToQuantum(
evaluate_pixel[x].index));
q++;
}
if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(images,EvaluateImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
}
evaluate_view=DestroyCacheView(evaluate_view);
evaluate_pixels=DestroyPixelThreadSet(evaluate_pixels);
random_info=DestroyRandomInfoThreadSet(random_info);
if (status == MagickFalse)
image=DestroyImage(image);
return(image);
}
MagickExport MagickBooleanType EvaluateImageChannel(Image *image,
const ChannelType channel,const MagickEvaluateOperator op,const double value,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
RandomInfo
**magick_restrict random_info;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
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);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
InheritException(exception,&image->exception);
return(MagickFalse);
}
status=MagickTrue;
progress=0;
random_info=AcquireRandomInfoThreadSet();
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register IndexPacket
*magick_restrict indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickRealType
result;
if ((channel & RedChannel) != 0)
{
result=ApplyEvaluateOperator(random_info[id],GetPixelRed(q),op,value);
if (op == MeanEvaluateOperator)
result/=2.0;
SetPixelRed(q,ClampToQuantum(result));
}
if ((channel & GreenChannel) != 0)
{
result=ApplyEvaluateOperator(random_info[id],GetPixelGreen(q),op,
value);
if (op == MeanEvaluateOperator)
result/=2.0;
SetPixelGreen(q,ClampToQuantum(result));
}
if ((channel & BlueChannel) != 0)
{
result=ApplyEvaluateOperator(random_info[id],GetPixelBlue(q),op,
value);
if (op == MeanEvaluateOperator)
result/=2.0;
SetPixelBlue(q,ClampToQuantum(result));
}
if ((channel & OpacityChannel) != 0)
{
if (image->matte == MagickFalse)
{
result=ApplyEvaluateOperator(random_info[id],GetPixelOpacity(q),
op,value);
if (op == MeanEvaluateOperator)
result/=2.0;
SetPixelOpacity(q,ClampToQuantum(result));
}
else
{
result=ApplyEvaluateOperator(random_info[id],GetPixelAlpha(q),
op,value);
if (op == MeanEvaluateOperator)
result/=2.0;
SetPixelAlpha(q,ClampToQuantum(result));
}
}
if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL))
{
result=ApplyEvaluateOperator(random_info[id],GetPixelIndex(indexes+x),
op,value);
if (op == MeanEvaluateOperator)
result/=2.0;
SetPixelIndex(indexes+x,ClampToQuantum(result));
}
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,EvaluateImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
random_info=DestroyRandomInfoThreadSet(random_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F u n c t i o n I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FunctionImage() applies a value to the image with an arithmetic, relational,
% or logical operator to an image. Use these operations to lighten or darken
% an image, to increase or decrease contrast in an image, or to produce the
% "negative" of an image.
%
% The format of the FunctionImageChannel method is:
%
% MagickBooleanType FunctionImage(Image *image,
% const MagickFunction function,const ssize_t number_parameters,
% const double *parameters,ExceptionInfo *exception)
% MagickBooleanType FunctionImageChannel(Image *image,
% const ChannelType channel,const MagickFunction function,
% const ssize_t number_parameters,const double *argument,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o function: A channel function.
%
% o parameters: one or more parameters.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Quantum ApplyFunction(Quantum pixel,const MagickFunction function,
const size_t number_parameters,const double *parameters,
ExceptionInfo *exception)
{
MagickRealType
result;
register ssize_t
i;
(void) exception;
result=0.0;
switch (function)
{
case PolynomialFunction:
{
/*
* Polynomial
* Parameters: polynomial constants, highest to lowest order
* For example: c0*x^3 + c1*x^2 + c2*x + c3
*/
result=0.0;
for (i=0; i < (ssize_t) number_parameters; i++)
result=result*QuantumScale*pixel + parameters[i];
result*=QuantumRange;
break;
}
case SinusoidFunction:
{
/* Sinusoid Function
* Parameters: Freq, Phase, Ampl, bias
*/
double freq,phase,ampl,bias;
freq = ( number_parameters >= 1 ) ? parameters[0] : 1.0;
phase = ( number_parameters >= 2 ) ? parameters[1] : 0.0;
ampl = ( number_parameters >= 3 ) ? parameters[2] : 0.5;
bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5;
result=(MagickRealType) (QuantumRange*(ampl*sin((double) (2.0*MagickPI*
(freq*QuantumScale*pixel + phase/360.0) )) + bias ) );
break;
}
case ArcsinFunction:
{
/* Arcsin Function (peged at range limits for invalid results)
* Parameters: Width, Center, Range, Bias
*/
double width,range,center,bias;
width = ( number_parameters >= 1 ) ? parameters[0] : 1.0;
center = ( number_parameters >= 2 ) ? parameters[1] : 0.5;
range = ( number_parameters >= 3 ) ? parameters[2] : 1.0;
bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5;
result = 2.0/width*(QuantumScale*pixel - center);
if ( result <= -1.0 )
result = bias - range/2.0;
else if ( result >= 1.0 )
result = bias + range/2.0;
else
result=(MagickRealType) (range/MagickPI*asin((double) result)+bias);
result *= QuantumRange;
break;
}
case ArctanFunction:
{
/* Arctan Function
* Parameters: Slope, Center, Range, Bias
*/
double slope,range,center,bias;
slope = ( number_parameters >= 1 ) ? parameters[0] : 1.0;
center = ( number_parameters >= 2 ) ? parameters[1] : 0.5;
range = ( number_parameters >= 3 ) ? parameters[2] : 1.0;
bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5;
result=(MagickRealType) (MagickPI*slope*(QuantumScale*pixel-center));
result=(MagickRealType) (QuantumRange*(range/MagickPI*atan((double)
result) + bias ) );
break;
}
case UndefinedFunction:
break;
}
return(ClampToQuantum(result));
}
MagickExport MagickBooleanType FunctionImage(Image *image,
const MagickFunction function,const size_t number_parameters,
const double *parameters,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=FunctionImageChannel(image,CompositeChannels,function,
number_parameters,parameters,exception);
return(status);
}
MagickExport MagickBooleanType FunctionImageChannel(Image *image,
const ChannelType channel,const MagickFunction function,
const size_t number_parameters,const double *parameters,
ExceptionInfo *exception)
{
#define FunctionImageTag "Function/Image "
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
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);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
InheritException(exception,&image->exception);
return(MagickFalse);
}
#if defined(MAGICKCORE_OPENCL_SUPPORT)
status=AccelerateFunctionImage(image,channel,function,number_parameters,
parameters,exception);
if (status != MagickFalse)
return(status);
#endif
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
SetPixelRed(q,ApplyFunction(GetPixelRed(q),function,
number_parameters,parameters,exception));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ApplyFunction(GetPixelGreen(q),function,
number_parameters,parameters,exception));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ApplyFunction(GetPixelBlue(q),function,
number_parameters,parameters,exception));
if ((channel & OpacityChannel) != 0)
{
if (image->matte == MagickFalse)
SetPixelOpacity(q,ApplyFunction(GetPixelOpacity(q),function,
number_parameters,parameters,exception));
else
SetPixelAlpha(q,ApplyFunction((Quantum) GetPixelAlpha(q),function,
number_parameters,parameters,exception));
}
if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL))
SetPixelIndex(indexes+x,ApplyFunction(GetPixelIndex(indexes+x),function,
number_parameters,parameters,exception));
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,FunctionImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l E n t r o p y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelEntropy() returns the entropy of one or more image channels.
%
% The format of the GetImageChannelEntropy method is:
%
% MagickBooleanType GetImageChannelEntropy(const Image *image,
% const ChannelType channel,double *entropy,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o entropy: the average entropy of the selected channels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageEntropy(const Image *image,
double *entropy,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=GetImageChannelEntropy(image,CompositeChannels,entropy,exception);
return(status);
}
MagickExport MagickBooleanType GetImageChannelEntropy(const Image *image,
const ChannelType channel,double *entropy,ExceptionInfo *exception)
{
ChannelStatistics
*channel_statistics;
size_t
channels;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
channel_statistics=GetImageChannelStatistics(image,exception);
if (channel_statistics == (ChannelStatistics *) NULL)
return(MagickFalse);
channels=0;
channel_statistics[CompositeChannels].entropy=0.0;
if ((channel & RedChannel) != 0)
{
channel_statistics[CompositeChannels].entropy+=
channel_statistics[RedChannel].entropy;
channels++;
}
if ((channel & GreenChannel) != 0)
{
channel_statistics[CompositeChannels].entropy+=
channel_statistics[GreenChannel].entropy;
channels++;
}
if ((channel & BlueChannel) != 0)
{
channel_statistics[CompositeChannels].entropy+=
channel_statistics[BlueChannel].entropy;
channels++;
}
if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse))
{
channel_statistics[CompositeChannels].entropy+=
channel_statistics[OpacityChannel].entropy;
channels++;
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
{
channel_statistics[CompositeChannels].entropy+=
channel_statistics[BlackChannel].entropy;
channels++;
}
channel_statistics[CompositeChannels].entropy/=channels;
*entropy=channel_statistics[CompositeChannels].entropy;
channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
channel_statistics);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t I m a g e C h a n n e l E x t r e m a %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelExtrema() returns the extrema of one or more image channels.
%
% The format of the GetImageChannelExtrema method is:
%
% MagickBooleanType GetImageChannelExtrema(const Image *image,
% const ChannelType channel,size_t *minima,size_t *maxima,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o minima: the minimum value in the channel.
%
% o maxima: the maximum value in the channel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageExtrema(const Image *image,
size_t *minima,size_t *maxima,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=GetImageChannelExtrema(image,CompositeChannels,minima,maxima,
exception);
return(status);
}
MagickExport MagickBooleanType GetImageChannelExtrema(const Image *image,
const ChannelType channel,size_t *minima,size_t *maxima,
ExceptionInfo *exception)
{
double
max,
min;
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=GetImageChannelRange(image,channel,&min,&max,exception);
*minima=(size_t) ceil(min-0.5);
*maxima=(size_t) floor(max+0.5);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l K u r t o s i s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelKurtosis() returns the kurtosis and skewness of one or more
% image channels.
%
% The format of the GetImageChannelKurtosis method is:
%
% MagickBooleanType GetImageChannelKurtosis(const Image *image,
% const ChannelType channel,double *kurtosis,double *skewness,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o kurtosis: the kurtosis of the channel.
%
% o skewness: the skewness of the channel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageKurtosis(const Image *image,
double *kurtosis,double *skewness,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=GetImageChannelKurtosis(image,CompositeChannels,kurtosis,skewness,
exception);
return(status);
}
MagickExport MagickBooleanType GetImageChannelKurtosis(const Image *image,
const ChannelType channel,double *kurtosis,double *skewness,
ExceptionInfo *exception)
{
double
area,
mean,
standard_deviation,
sum_squares,
sum_cubes,
sum_fourth_power;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
*kurtosis=0.0;
*skewness=0.0;
area=0.0;
mean=0.0;
standard_deviation=0.0;
sum_squares=0.0;
sum_cubes=0.0;
sum_fourth_power=0.0;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
{
mean+=GetPixelRed(p);
sum_squares+=(double) GetPixelRed(p)*GetPixelRed(p);
sum_cubes+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p);
sum_fourth_power+=(double) GetPixelRed(p)*GetPixelRed(p)*
GetPixelRed(p)*GetPixelRed(p);
area++;
}
if ((channel & GreenChannel) != 0)
{
mean+=GetPixelGreen(p);
sum_squares+=(double) GetPixelGreen(p)*GetPixelGreen(p);
sum_cubes+=(double) GetPixelGreen(p)*GetPixelGreen(p)*
GetPixelGreen(p);
sum_fourth_power+=(double) GetPixelGreen(p)*GetPixelGreen(p)*
GetPixelGreen(p)*GetPixelGreen(p);
area++;
}
if ((channel & BlueChannel) != 0)
{
mean+=GetPixelBlue(p);
sum_squares+=(double) GetPixelBlue(p)*GetPixelBlue(p);
sum_cubes+=(double) GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p);
sum_fourth_power+=(double) GetPixelBlue(p)*GetPixelBlue(p)*
GetPixelBlue(p)*GetPixelBlue(p);
area++;
}
if ((channel & OpacityChannel) != 0)
{
mean+=GetPixelAlpha(p);
sum_squares+=(double) GetPixelOpacity(p)*GetPixelAlpha(p);
sum_cubes+=(double) GetPixelOpacity(p)*GetPixelAlpha(p)*
GetPixelAlpha(p);
sum_fourth_power+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)*
GetPixelAlpha(p)*GetPixelAlpha(p);
area++;
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
{
double
index;
index=(double) GetPixelIndex(indexes+x);
mean+=index;
sum_squares+=index*index;
sum_cubes+=index*index*index;
sum_fourth_power+=index*index*index*index;
area++;
}
p++;
}
}
if (y < (ssize_t) image->rows)
return(MagickFalse);
if (area != 0.0)
{
mean/=area;
sum_squares/=area;
sum_cubes/=area;
sum_fourth_power/=area;
}
standard_deviation=sqrt(sum_squares-(mean*mean));
if (standard_deviation != 0.0)
{
*kurtosis=sum_fourth_power-4.0*mean*sum_cubes+6.0*mean*mean*sum_squares-
3.0*mean*mean*mean*mean;
*kurtosis/=standard_deviation*standard_deviation*standard_deviation*
standard_deviation;
*kurtosis-=3.0;
*skewness=sum_cubes-3.0*mean*sum_squares+2.0*mean*mean*mean;
*skewness/=standard_deviation*standard_deviation*standard_deviation;
}
return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l M e a n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelMean() returns the mean and standard deviation of one or more
% image channels.
%
% The format of the GetImageChannelMean method is:
%
% MagickBooleanType GetImageChannelMean(const Image *image,
% const ChannelType channel,double *mean,double *standard_deviation,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o mean: the average value in the channel.
%
% o standard_deviation: the standard deviation of the channel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean,
double *standard_deviation,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=GetImageChannelMean(image,CompositeChannels,mean,standard_deviation,
exception);
return(status);
}
MagickExport MagickBooleanType GetImageChannelMean(const Image *image,
const ChannelType channel,double *mean,double *standard_deviation,
ExceptionInfo *exception)
{
ChannelStatistics
*channel_statistics;
size_t
channels;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
channel_statistics=GetImageChannelStatistics(image,exception);
if (channel_statistics == (ChannelStatistics *) NULL)
return(MagickFalse);
channels=0;
channel_statistics[CompositeChannels].mean=0.0;
channel_statistics[CompositeChannels].standard_deviation=0.0;
if ((channel & RedChannel) != 0)
{
channel_statistics[CompositeChannels].mean+=
channel_statistics[RedChannel].mean;
channel_statistics[CompositeChannels].standard_deviation+=
channel_statistics[RedChannel].standard_deviation;
channels++;
}
if ((channel & GreenChannel) != 0)
{
channel_statistics[CompositeChannels].mean+=
channel_statistics[GreenChannel].mean;
channel_statistics[CompositeChannels].standard_deviation+=
channel_statistics[GreenChannel].standard_deviation;
channels++;
}
if ((channel & BlueChannel) != 0)
{
channel_statistics[CompositeChannels].mean+=
channel_statistics[BlueChannel].mean;
channel_statistics[CompositeChannels].standard_deviation+=
channel_statistics[BlueChannel].standard_deviation;
channels++;
}
if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse))
{
channel_statistics[CompositeChannels].mean+=
(QuantumRange-channel_statistics[OpacityChannel].mean);
channel_statistics[CompositeChannels].standard_deviation+=
channel_statistics[OpacityChannel].standard_deviation;
channels++;
}
if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace))
{
channel_statistics[CompositeChannels].mean+=
channel_statistics[BlackChannel].mean;
channel_statistics[CompositeChannels].standard_deviation+=
channel_statistics[CompositeChannels].standard_deviation;
channels++;
}
channel_statistics[CompositeChannels].mean/=channels;
channel_statistics[CompositeChannels].standard_deviation/=channels;
*mean=channel_statistics[CompositeChannels].mean;
*standard_deviation=channel_statistics[CompositeChannels].standard_deviation;
channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
channel_statistics);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l M o m e n t s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelMoments() returns the normalized moments of one or more image
% channels.
%
% The format of the GetImageChannelMoments method is:
%
% ChannelMoments *GetImageChannelMoments(const Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ChannelMoments *GetImageChannelMoments(const Image *image,
ExceptionInfo *exception)
{
#define MaxNumberImageMoments 8
ChannelMoments
*channel_moments;
double
M00[CompositeChannels+1],
M01[CompositeChannels+1],
M02[CompositeChannels+1],
M03[CompositeChannels+1],
M10[CompositeChannels+1],
M11[CompositeChannels+1],
M12[CompositeChannels+1],
M20[CompositeChannels+1],
M21[CompositeChannels+1],
M22[CompositeChannels+1],
M30[CompositeChannels+1];
MagickPixelPacket
pixel;
PointInfo
centroid[CompositeChannels+1];
ssize_t
channel,
channels,
y;
size_t
length;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
length=CompositeChannels+1UL;
channel_moments=(ChannelMoments *) AcquireQuantumMemory(length,
sizeof(*channel_moments));
if (channel_moments == (ChannelMoments *) NULL)
return(channel_moments);
(void) memset(channel_moments,0,length*sizeof(*channel_moments));
(void) memset(centroid,0,sizeof(centroid));
(void) memset(M00,0,sizeof(M00));
(void) memset(M01,0,sizeof(M01));
(void) memset(M02,0,sizeof(M02));
(void) memset(M03,0,sizeof(M03));
(void) memset(M10,0,sizeof(M10));
(void) memset(M11,0,sizeof(M11));
(void) memset(M12,0,sizeof(M12));
(void) memset(M20,0,sizeof(M20));
(void) memset(M21,0,sizeof(M21));
(void) memset(M22,0,sizeof(M22));
(void) memset(M30,0,sizeof(M30));
GetMagickPixelPacket(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
/*
Compute center of mass (centroid).
*/
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetMagickPixelPacket(image,p,indexes+x,&pixel);
M00[RedChannel]+=QuantumScale*pixel.red;
M10[RedChannel]+=x*QuantumScale*pixel.red;
M01[RedChannel]+=y*QuantumScale*pixel.red;
M00[GreenChannel]+=QuantumScale*pixel.green;
M10[GreenChannel]+=x*QuantumScale*pixel.green;
M01[GreenChannel]+=y*QuantumScale*pixel.green;
M00[BlueChannel]+=QuantumScale*pixel.blue;
M10[BlueChannel]+=x*QuantumScale*pixel.blue;
M01[BlueChannel]+=y*QuantumScale*pixel.blue;
if (image->matte != MagickFalse)
{
M00[OpacityChannel]+=QuantumScale*pixel.opacity;
M10[OpacityChannel]+=x*QuantumScale*pixel.opacity;
M01[OpacityChannel]+=y*QuantumScale*pixel.opacity;
}
if (image->colorspace == CMYKColorspace)
{
M00[IndexChannel]+=QuantumScale*pixel.index;
M10[IndexChannel]+=x*QuantumScale*pixel.index;
M01[IndexChannel]+=y*QuantumScale*pixel.index;
}
p++;
}
}
for (channel=0; channel <= CompositeChannels; channel++)
{
/*
Compute center of mass (centroid).
*/
if (M00[channel] < MagickEpsilon)
{
M00[channel]+=MagickEpsilon;
centroid[channel].x=(double) image->columns/2.0;
centroid[channel].y=(double) image->rows/2.0;
continue;
}
M00[channel]+=MagickEpsilon;
centroid[channel].x=M10[channel]/M00[channel];
centroid[channel].y=M01[channel]/M00[channel];
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
/*
Compute the image moments.
*/
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetMagickPixelPacket(image,p,indexes+x,&pixel);
M11[RedChannel]+=(x-centroid[RedChannel].x)*(y-
centroid[RedChannel].y)*QuantumScale*pixel.red;
M20[RedChannel]+=(x-centroid[RedChannel].x)*(x-
centroid[RedChannel].x)*QuantumScale*pixel.red;
M02[RedChannel]+=(y-centroid[RedChannel].y)*(y-
centroid[RedChannel].y)*QuantumScale*pixel.red;
M21[RedChannel]+=(x-centroid[RedChannel].x)*(x-
centroid[RedChannel].x)*(y-centroid[RedChannel].y)*QuantumScale*
pixel.red;
M12[RedChannel]+=(x-centroid[RedChannel].x)*(y-
centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale*
pixel.red;
M22[RedChannel]+=(x-centroid[RedChannel].x)*(x-
centroid[RedChannel].x)*(y-centroid[RedChannel].y)*(y-
centroid[RedChannel].y)*QuantumScale*pixel.red;
M30[RedChannel]+=(x-centroid[RedChannel].x)*(x-
centroid[RedChannel].x)*(x-centroid[RedChannel].x)*QuantumScale*
pixel.red;
M03[RedChannel]+=(y-centroid[RedChannel].y)*(y-
centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale*
pixel.red;
M11[GreenChannel]+=(x-centroid[GreenChannel].x)*(y-
centroid[GreenChannel].y)*QuantumScale*pixel.green;
M20[GreenChannel]+=(x-centroid[GreenChannel].x)*(x-
centroid[GreenChannel].x)*QuantumScale*pixel.green;
M02[GreenChannel]+=(y-centroid[GreenChannel].y)*(y-
centroid[GreenChannel].y)*QuantumScale*pixel.green;
M21[GreenChannel]+=(x-centroid[GreenChannel].x)*(x-
centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*QuantumScale*
pixel.green;
M12[GreenChannel]+=(x-centroid[GreenChannel].x)*(y-
centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale*
pixel.green;
M22[GreenChannel]+=(x-centroid[GreenChannel].x)*(x-
centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*(y-
centroid[GreenChannel].y)*QuantumScale*pixel.green;
M30[GreenChannel]+=(x-centroid[GreenChannel].x)*(x-
centroid[GreenChannel].x)*(x-centroid[GreenChannel].x)*QuantumScale*
pixel.green;
M03[GreenChannel]+=(y-centroid[GreenChannel].y)*(y-
centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale*
pixel.green;
M11[BlueChannel]+=(x-centroid[BlueChannel].x)*(y-
centroid[BlueChannel].y)*QuantumScale*pixel.blue;
M20[BlueChannel]+=(x-centroid[BlueChannel].x)*(x-
centroid[BlueChannel].x)*QuantumScale*pixel.blue;
M02[BlueChannel]+=(y-centroid[BlueChannel].y)*(y-
centroid[BlueChannel].y)*QuantumScale*pixel.blue;
M21[BlueChannel]+=(x-centroid[BlueChannel].x)*(x-
centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*QuantumScale*
pixel.blue;
M12[BlueChannel]+=(x-centroid[BlueChannel].x)*(y-
centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale*
pixel.blue;
M22[BlueChannel]+=(x-centroid[BlueChannel].x)*(x-
centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*(y-
centroid[BlueChannel].y)*QuantumScale*pixel.blue;
M30[BlueChannel]+=(x-centroid[BlueChannel].x)*(x-
centroid[BlueChannel].x)*(x-centroid[BlueChannel].x)*QuantumScale*
pixel.blue;
M03[BlueChannel]+=(y-centroid[BlueChannel].y)*(y-
centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale*
pixel.blue;
if (image->matte != MagickFalse)
{
M11[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y-
centroid[OpacityChannel].y)*QuantumScale*pixel.opacity;
M20[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x-
centroid[OpacityChannel].x)*QuantumScale*pixel.opacity;
M02[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y-
centroid[OpacityChannel].y)*QuantumScale*pixel.opacity;
M21[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x-
centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)*
QuantumScale*pixel.opacity;
M12[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y-
centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)*
QuantumScale*pixel.opacity;
M22[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x-
centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)*(y-
centroid[OpacityChannel].y)*QuantumScale*pixel.opacity;
M30[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x-
centroid[OpacityChannel].x)*(x-centroid[OpacityChannel].x)*
QuantumScale*pixel.opacity;
M03[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y-
centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)*
QuantumScale*pixel.opacity;
}
if (image->colorspace == CMYKColorspace)
{
M11[IndexChannel]+=(x-centroid[IndexChannel].x)*(y-
centroid[IndexChannel].y)*QuantumScale*pixel.index;
M20[IndexChannel]+=(x-centroid[IndexChannel].x)*(x-
centroid[IndexChannel].x)*QuantumScale*pixel.index;
M02[IndexChannel]+=(y-centroid[IndexChannel].y)*(y-
centroid[IndexChannel].y)*QuantumScale*pixel.index;
M21[IndexChannel]+=(x-centroid[IndexChannel].x)*(x-
centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)*
QuantumScale*pixel.index;
M12[IndexChannel]+=(x-centroid[IndexChannel].x)*(y-
centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)*
QuantumScale*pixel.index;
M22[IndexChannel]+=(x-centroid[IndexChannel].x)*(x-
centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)*(y-
centroid[IndexChannel].y)*QuantumScale*pixel.index;
M30[IndexChannel]+=(x-centroid[IndexChannel].x)*(x-
centroid[IndexChannel].x)*(x-centroid[IndexChannel].x)*
QuantumScale*pixel.index;
M03[IndexChannel]+=(y-centroid[IndexChannel].y)*(y-
centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)*
QuantumScale*pixel.index;
}
p++;
}
}
channels=3;
M00[CompositeChannels]+=(M00[RedChannel]+M00[GreenChannel]+M00[BlueChannel]);
M01[CompositeChannels]+=(M01[RedChannel]+M01[GreenChannel]+M01[BlueChannel]);
M02[CompositeChannels]+=(M02[RedChannel]+M02[GreenChannel]+M02[BlueChannel]);
M03[CompositeChannels]+=(M03[RedChannel]+M03[GreenChannel]+M03[BlueChannel]);
M10[CompositeChannels]+=(M10[RedChannel]+M10[GreenChannel]+M10[BlueChannel]);
M11[CompositeChannels]+=(M11[RedChannel]+M11[GreenChannel]+M11[BlueChannel]);
M12[CompositeChannels]+=(M12[RedChannel]+M12[GreenChannel]+M12[BlueChannel]);
M20[CompositeChannels]+=(M20[RedChannel]+M20[GreenChannel]+M20[BlueChannel]);
M21[CompositeChannels]+=(M21[RedChannel]+M21[GreenChannel]+M21[BlueChannel]);
M22[CompositeChannels]+=(M22[RedChannel]+M22[GreenChannel]+M22[BlueChannel]);
M30[CompositeChannels]+=(M30[RedChannel]+M30[GreenChannel]+M30[BlueChannel]);
if (image->matte != MagickFalse)
{
channels+=1;
M00[CompositeChannels]+=M00[OpacityChannel];
M01[CompositeChannels]+=M01[OpacityChannel];
M02[CompositeChannels]+=M02[OpacityChannel];
M03[CompositeChannels]+=M03[OpacityChannel];
M10[CompositeChannels]+=M10[OpacityChannel];
M11[CompositeChannels]+=M11[OpacityChannel];
M12[CompositeChannels]+=M12[OpacityChannel];
M20[CompositeChannels]+=M20[OpacityChannel];
M21[CompositeChannels]+=M21[OpacityChannel];
M22[CompositeChannels]+=M22[OpacityChannel];
M30[CompositeChannels]+=M30[OpacityChannel];
}
if (image->colorspace == CMYKColorspace)
{
channels+=1;
M00[CompositeChannels]+=M00[IndexChannel];
M01[CompositeChannels]+=M01[IndexChannel];
M02[CompositeChannels]+=M02[IndexChannel];
M03[CompositeChannels]+=M03[IndexChannel];
M10[CompositeChannels]+=M10[IndexChannel];
M11[CompositeChannels]+=M11[IndexChannel];
M12[CompositeChannels]+=M12[IndexChannel];
M20[CompositeChannels]+=M20[IndexChannel];
M21[CompositeChannels]+=M21[IndexChannel];
M22[CompositeChannels]+=M22[IndexChannel];
M30[CompositeChannels]+=M30[IndexChannel];
}
M00[CompositeChannels]/=(double) channels;
M01[CompositeChannels]/=(double) channels;
M02[CompositeChannels]/=(double) channels;
M03[CompositeChannels]/=(double) channels;
M10[CompositeChannels]/=(double) channels;
M11[CompositeChannels]/=(double) channels;
M12[CompositeChannels]/=(double) channels;
M20[CompositeChannels]/=(double) channels;
M21[CompositeChannels]/=(double) channels;
M22[CompositeChannels]/=(double) channels;
M30[CompositeChannels]/=(double) channels;
for (channel=0; channel <= CompositeChannels; channel++)
{
/*
Compute elliptical angle, major and minor axes, eccentricity, & intensity.
*/
channel_moments[channel].centroid=centroid[channel];
channel_moments[channel].ellipse_axis.x=sqrt((2.0/M00[channel])*
((M20[channel]+M02[channel])+sqrt(4.0*M11[channel]*M11[channel]+
(M20[channel]-M02[channel])*(M20[channel]-M02[channel]))));
channel_moments[channel].ellipse_axis.y=sqrt((2.0/M00[channel])*
((M20[channel]+M02[channel])-sqrt(4.0*M11[channel]*M11[channel]+
(M20[channel]-M02[channel])*(M20[channel]-M02[channel]))));
channel_moments[channel].ellipse_angle=RadiansToDegrees(0.5*atan(2.0*
M11[channel]/(M20[channel]-M02[channel]+MagickEpsilon)));
if (fabs(M11[channel]) < MagickEpsilon)
{
if (fabs(M20[channel]-M02[channel]) < MagickEpsilon)
channel_moments[channel].ellipse_angle+=0.0;
else
if ((M20[channel]-M02[channel]) < 0.0)
channel_moments[channel].ellipse_angle+=90.0;
else
channel_moments[channel].ellipse_angle+=0.0;
}
else
if (M11[channel] < 0.0)
{
if (fabs(M20[channel]-M02[channel]) < MagickEpsilon)
channel_moments[channel].ellipse_angle+=0.0;
else
if ((M20[channel]-M02[channel]) < 0.0)
channel_moments[channel].ellipse_angle+=90.0;
else
channel_moments[channel].ellipse_angle+=180.0;
}
else
{
if (fabs(M20[channel]-M02[channel]) < MagickEpsilon)
channel_moments[channel].ellipse_angle+=0.0;
else
if ((M20[channel]-M02[channel]) < 0.0)
channel_moments[channel].ellipse_angle+=90.0;
else
channel_moments[channel].ellipse_angle+=0.0;
}
channel_moments[channel].ellipse_eccentricity=sqrt(1.0-(
channel_moments[channel].ellipse_axis.y/
(channel_moments[channel].ellipse_axis.x+MagickEpsilon)));
channel_moments[channel].ellipse_intensity=M00[channel]/
(MagickPI*channel_moments[channel].ellipse_axis.x*
channel_moments[channel].ellipse_axis.y+MagickEpsilon);
}
for (channel=0; channel <= CompositeChannels; channel++)
{
/*
Normalize image moments.
*/
M10[channel]=0.0;
M01[channel]=0.0;
M11[channel]/=pow(M00[channel],1.0+(1.0+1.0)/2.0);
M20[channel]/=pow(M00[channel],1.0+(2.0+0.0)/2.0);
M02[channel]/=pow(M00[channel],1.0+(0.0+2.0)/2.0);
M21[channel]/=pow(M00[channel],1.0+(2.0+1.0)/2.0);
M12[channel]/=pow(M00[channel],1.0+(1.0+2.0)/2.0);
M22[channel]/=pow(M00[channel],1.0+(2.0+2.0)/2.0);
M30[channel]/=pow(M00[channel],1.0+(3.0+0.0)/2.0);
M03[channel]/=pow(M00[channel],1.0+(0.0+3.0)/2.0);
M00[channel]=1.0;
}
for (channel=0; channel <= CompositeChannels; channel++)
{
/*
Compute Hu invariant moments.
*/
channel_moments[channel].I[0]=M20[channel]+M02[channel];
channel_moments[channel].I[1]=(M20[channel]-M02[channel])*
(M20[channel]-M02[channel])+4.0*M11[channel]*M11[channel];
channel_moments[channel].I[2]=(M30[channel]-3.0*M12[channel])*
(M30[channel]-3.0*M12[channel])+(3.0*M21[channel]-M03[channel])*
(3.0*M21[channel]-M03[channel]);
channel_moments[channel].I[3]=(M30[channel]+M12[channel])*
(M30[channel]+M12[channel])+(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]);
channel_moments[channel].I[4]=(M30[channel]-3.0*M12[channel])*
(M30[channel]+M12[channel])*((M30[channel]+M12[channel])*
(M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]))+(3.0*M21[channel]-M03[channel])*
(M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])*
(M30[channel]+M12[channel])-(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]));
channel_moments[channel].I[5]=(M20[channel]-M02[channel])*
((M30[channel]+M12[channel])*(M30[channel]+M12[channel])-
(M21[channel]+M03[channel])*(M21[channel]+M03[channel]))+
4.0*M11[channel]*(M30[channel]+M12[channel])*(M21[channel]+M03[channel]);
channel_moments[channel].I[6]=(3.0*M21[channel]-M03[channel])*
(M30[channel]+M12[channel])*((M30[channel]+M12[channel])*
(M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]))-(M30[channel]-3*M12[channel])*
(M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])*
(M30[channel]+M12[channel])-(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]));
channel_moments[channel].I[7]=M11[channel]*((M30[channel]+M12[channel])*
(M30[channel]+M12[channel])-(M03[channel]+M21[channel])*
(M03[channel]+M21[channel]))-(M20[channel]-M02[channel])*
(M30[channel]+M12[channel])*(M03[channel]+M21[channel]);
}
if (y < (ssize_t) image->rows)
channel_moments=(ChannelMoments *) RelinquishMagickMemory(channel_moments);
return(channel_moments);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l P e r c e p t u a l H a s h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelPerceptualHash() returns the perceptual hash of one or more
% image channels.
%
% The format of the GetImageChannelPerceptualHash method is:
%
% ChannelPerceptualHash *GetImageChannelPerceptualHash(const Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double MagickLog10(const double x)
{
#define Log10Epsilon (1.0e-11)
if (fabs(x) < Log10Epsilon)
return(log10(Log10Epsilon));
return(log10(fabs(x)));
}
MagickExport ChannelPerceptualHash *GetImageChannelPerceptualHash(
const Image *image,ExceptionInfo *exception)
{
ChannelMoments
*moments;
ChannelPerceptualHash
*perceptual_hash;
Image
*hash_image;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
channel;
/*
Blur then transform to sRGB colorspace.
*/
hash_image=BlurImage(image,0.0,1.0,exception);
if (hash_image == (Image *) NULL)
return((ChannelPerceptualHash *) NULL);
hash_image->depth=8;
status=TransformImageColorspace(hash_image,sRGBColorspace);
if (status == MagickFalse)
return((ChannelPerceptualHash *) NULL);
moments=GetImageChannelMoments(hash_image,exception);
hash_image=DestroyImage(hash_image);
if (moments == (ChannelMoments *) NULL)
return((ChannelPerceptualHash *) NULL);
perceptual_hash=(ChannelPerceptualHash *) AcquireQuantumMemory(
CompositeChannels+1UL,sizeof(*perceptual_hash));
if (perceptual_hash == (ChannelPerceptualHash *) NULL)
return((ChannelPerceptualHash *) NULL);
for (channel=0; channel <= CompositeChannels; channel++)
for (i=0; i < MaximumNumberOfImageMoments; i++)
perceptual_hash[channel].P[i]=(-MagickLog10(moments[channel].I[i]));
moments=(ChannelMoments *) RelinquishMagickMemory(moments);
/*
Blur then transform to HCLp colorspace.
*/
hash_image=BlurImage(image,0.0,1.0,exception);
if (hash_image == (Image *) NULL)
{
perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory(
perceptual_hash);
return((ChannelPerceptualHash *) NULL);
}
hash_image->depth=8;
status=TransformImageColorspace(hash_image,HCLpColorspace);
if (status == MagickFalse)
{
perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory(
perceptual_hash);
return((ChannelPerceptualHash *) NULL);
}
moments=GetImageChannelMoments(hash_image,exception);
hash_image=DestroyImage(hash_image);
if (moments == (ChannelMoments *) NULL)
{
perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory(
perceptual_hash);
return((ChannelPerceptualHash *) NULL);
}
for (channel=0; channel <= CompositeChannels; channel++)
for (i=0; i < MaximumNumberOfImageMoments; i++)
perceptual_hash[channel].Q[i]=(-MagickLog10(moments[channel].I[i]));
moments=(ChannelMoments *) RelinquishMagickMemory(moments);
return(perceptual_hash);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l R a n g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelRange() returns the range of one or more image channels.
%
% The format of the GetImageChannelRange method is:
%
% MagickBooleanType GetImageChannelRange(const Image *image,
% const ChannelType channel,double *minima,double *maxima,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o minima: the minimum value in the channel.
%
% o maxima: the maximum value in the channel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageRange(const Image *image,
double *minima,double *maxima,ExceptionInfo *exception)
{
return(GetImageChannelRange(image,CompositeChannels,minima,maxima,exception));
}
MagickExport MagickBooleanType GetImageChannelRange(const Image *image,
const ChannelType channel,double *minima,double *maxima,
ExceptionInfo *exception)
{
MagickPixelPacket
pixel;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
*maxima=(-MagickMaximumValue);
*minima=MagickMaximumValue;
GetMagickPixelPacket(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetMagickPixelPacket(image,p,indexes+x,&pixel);
if ((channel & RedChannel) != 0)
{
if (pixel.red < *minima)
*minima=(double) pixel.red;
if (pixel.red > *maxima)
*maxima=(double) pixel.red;
}
if ((channel & GreenChannel) != 0)
{
if (pixel.green < *minima)
*minima=(double) pixel.green;
if (pixel.green > *maxima)
*maxima=(double) pixel.green;
}
if ((channel & BlueChannel) != 0)
{
if (pixel.blue < *minima)
*minima=(double) pixel.blue;
if (pixel.blue > *maxima)
*maxima=(double) pixel.blue;
}
if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse))
{
if ((QuantumRange-pixel.opacity) < *minima)
*minima=(double) (QuantumRange-pixel.opacity);
if ((QuantumRange-pixel.opacity) > *maxima)
*maxima=(double) (QuantumRange-pixel.opacity);
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
{
if ((double) pixel.index < *minima)
*minima=(double) pixel.index;
if ((double) pixel.index > *maxima)
*maxima=(double) pixel.index;
}
p++;
}
}
return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l S t a t i s t i c s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelStatistics() returns statistics for each channel in the
% image. The statistics include the channel depth, its minima, maxima, mean,
% standard deviation, kurtosis and skewness. You can access the red channel
% mean, for example, like this:
%
% channel_statistics=GetImageChannelStatistics(image,exception);
% red_mean=channel_statistics[RedChannel].mean;
%
% Use MagickRelinquishMemory() to free the statistics buffer.
%
% The format of the GetImageChannelStatistics method is:
%
% ChannelStatistics *GetImageChannelStatistics(const Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ChannelStatistics *GetImageChannelStatistics(const Image *image,
ExceptionInfo *exception)
{
ChannelStatistics
*channel_statistics;
double
area,
standard_deviation;
MagickPixelPacket
number_bins,
*histogram;
QuantumAny
range;
register ssize_t
i;
size_t
channels,
depth,
length;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
length=CompositeChannels+1UL;
channel_statistics=(ChannelStatistics *) AcquireQuantumMemory(length,
sizeof(*channel_statistics));
histogram=(MagickPixelPacket *) AcquireQuantumMemory(MaxMap+1U,
sizeof(*histogram));
if ((channel_statistics == (ChannelStatistics *) NULL) ||
(histogram == (MagickPixelPacket *) NULL))
{
if (histogram != (MagickPixelPacket *) NULL)
histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram);
if (channel_statistics != (ChannelStatistics *) NULL)
channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
channel_statistics);
return(channel_statistics);
}
(void) memset(channel_statistics,0,length*
sizeof(*channel_statistics));
for (i=0; i <= (ssize_t) CompositeChannels; i++)
{
channel_statistics[i].depth=1;
channel_statistics[i].maxima=(-MagickMaximumValue);
channel_statistics[i].minima=MagickMaximumValue;
}
(void) memset(histogram,0,(MaxMap+1U)*sizeof(*histogram));
(void) memset(&number_bins,0,sizeof(number_bins));
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
/*
Compute pixel statistics.
*/
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; )
{
if (channel_statistics[RedChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[RedChannel].depth;
range=GetQuantumRange(depth);
if (IsPixelAtDepth(GetPixelRed(p),range) == MagickFalse)
{
channel_statistics[RedChannel].depth++;
continue;
}
}
if (channel_statistics[GreenChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[GreenChannel].depth;
range=GetQuantumRange(depth);
if (IsPixelAtDepth(GetPixelGreen(p),range) == MagickFalse)
{
channel_statistics[GreenChannel].depth++;
continue;
}
}
if (channel_statistics[BlueChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[BlueChannel].depth;
range=GetQuantumRange(depth);
if (IsPixelAtDepth(GetPixelBlue(p),range) == MagickFalse)
{
channel_statistics[BlueChannel].depth++;
continue;
}
}
if (image->matte != MagickFalse)
{
if (channel_statistics[OpacityChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[OpacityChannel].depth;
range=GetQuantumRange(depth);
if (IsPixelAtDepth(GetPixelAlpha(p),range) == MagickFalse)
{
channel_statistics[OpacityChannel].depth++;
continue;
}
}
}
if (image->colorspace == CMYKColorspace)
{
if (channel_statistics[BlackChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[BlackChannel].depth;
range=GetQuantumRange(depth);
if (IsPixelAtDepth(GetPixelIndex(indexes+x),range) == MagickFalse)
{
channel_statistics[BlackChannel].depth++;
continue;
}
}
}
if ((double) GetPixelRed(p) < channel_statistics[RedChannel].minima)
channel_statistics[RedChannel].minima=(double) GetPixelRed(p);
if ((double) GetPixelRed(p) > channel_statistics[RedChannel].maxima)
channel_statistics[RedChannel].maxima=(double) GetPixelRed(p);
channel_statistics[RedChannel].sum+=GetPixelRed(p);
channel_statistics[RedChannel].sum_squared+=(double) GetPixelRed(p)*
GetPixelRed(p);
channel_statistics[RedChannel].sum_cubed+=(double)
GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p);
channel_statistics[RedChannel].sum_fourth_power+=(double)
GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p);
if ((double) GetPixelGreen(p) < channel_statistics[GreenChannel].minima)
channel_statistics[GreenChannel].minima=(double) GetPixelGreen(p);
if ((double) GetPixelGreen(p) > channel_statistics[GreenChannel].maxima)
channel_statistics[GreenChannel].maxima=(double) GetPixelGreen(p);
channel_statistics[GreenChannel].sum+=GetPixelGreen(p);
channel_statistics[GreenChannel].sum_squared+=(double) GetPixelGreen(p)*
GetPixelGreen(p);
channel_statistics[GreenChannel].sum_cubed+=(double) GetPixelGreen(p)*
GetPixelGreen(p)*GetPixelGreen(p);
channel_statistics[GreenChannel].sum_fourth_power+=(double)
GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p);
if ((double) GetPixelBlue(p) < channel_statistics[BlueChannel].minima)
channel_statistics[BlueChannel].minima=(double) GetPixelBlue(p);
if ((double) GetPixelBlue(p) > channel_statistics[BlueChannel].maxima)
channel_statistics[BlueChannel].maxima=(double) GetPixelBlue(p);
channel_statistics[BlueChannel].sum+=GetPixelBlue(p);
channel_statistics[BlueChannel].sum_squared+=(double) GetPixelBlue(p)*
GetPixelBlue(p);
channel_statistics[BlueChannel].sum_cubed+=(double) GetPixelBlue(p)*
GetPixelBlue(p)*GetPixelBlue(p);
channel_statistics[BlueChannel].sum_fourth_power+=(double)
GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p);
histogram[ScaleQuantumToMap(GetPixelRed(p))].red++;
histogram[ScaleQuantumToMap(GetPixelGreen(p))].green++;
histogram[ScaleQuantumToMap(GetPixelBlue(p))].blue++;
if (image->matte != MagickFalse)
{
if ((double) GetPixelAlpha(p) < channel_statistics[OpacityChannel].minima)
channel_statistics[OpacityChannel].minima=(double) GetPixelAlpha(p);
if ((double) GetPixelAlpha(p) > channel_statistics[OpacityChannel].maxima)
channel_statistics[OpacityChannel].maxima=(double) GetPixelAlpha(p);
channel_statistics[OpacityChannel].sum+=GetPixelAlpha(p);
channel_statistics[OpacityChannel].sum_squared+=(double)
GetPixelAlpha(p)*GetPixelAlpha(p);
channel_statistics[OpacityChannel].sum_cubed+=(double)
GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p);
channel_statistics[OpacityChannel].sum_fourth_power+=(double)
GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p);
histogram[ScaleQuantumToMap(GetPixelAlpha(p))].opacity++;
}
if (image->colorspace == CMYKColorspace)
{
if ((double) GetPixelIndex(indexes+x) < channel_statistics[BlackChannel].minima)
channel_statistics[BlackChannel].minima=(double)
GetPixelIndex(indexes+x);
if ((double) GetPixelIndex(indexes+x) > channel_statistics[BlackChannel].maxima)
channel_statistics[BlackChannel].maxima=(double)
GetPixelIndex(indexes+x);
channel_statistics[BlackChannel].sum+=GetPixelIndex(indexes+x);
channel_statistics[BlackChannel].sum_squared+=(double)
GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x);
channel_statistics[BlackChannel].sum_cubed+=(double)
GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)*
GetPixelIndex(indexes+x);
channel_statistics[BlackChannel].sum_fourth_power+=(double)
GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)*
GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x);
histogram[ScaleQuantumToMap(GetPixelIndex(indexes+x))].index++;
}
x++;
p++;
}
}
for (i=0; i < (ssize_t) CompositeChannels; i++)
{
double
area,
mean,
standard_deviation;
/*
Normalize pixel statistics.
*/
area=PerceptibleReciprocal((double) image->columns*image->rows);
mean=channel_statistics[i].sum*area;
channel_statistics[i].sum=mean;
channel_statistics[i].sum_squared*=area;
channel_statistics[i].sum_cubed*=area;
channel_statistics[i].sum_fourth_power*=area;
channel_statistics[i].mean=mean;
channel_statistics[i].variance=channel_statistics[i].sum_squared;
standard_deviation=sqrt(channel_statistics[i].variance-(mean*mean));
area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)*
((double) image->columns*image->rows);
standard_deviation=sqrt(area*standard_deviation*standard_deviation);
channel_statistics[i].standard_deviation=standard_deviation;
}
for (i=0; i < (ssize_t) (MaxMap+1U); i++)
{
if (histogram[i].red > 0.0)
number_bins.red++;
if (histogram[i].green > 0.0)
number_bins.green++;
if (histogram[i].blue > 0.0)
number_bins.blue++;
if ((image->matte != MagickFalse) && (histogram[i].opacity > 0.0))
number_bins.opacity++;
if ((image->colorspace == CMYKColorspace) && (histogram[i].index > 0.0))
number_bins.index++;
}
area=PerceptibleReciprocal((double) image->columns*image->rows);
for (i=0; i < (ssize_t) (MaxMap+1U); i++)
{
/*
Compute pixel entropy.
*/
histogram[i].red*=area;
channel_statistics[RedChannel].entropy+=-histogram[i].red*
MagickLog10(histogram[i].red)*
PerceptibleReciprocal(MagickLog10((double) number_bins.red));
histogram[i].green*=area;
channel_statistics[GreenChannel].entropy+=-histogram[i].green*
MagickLog10(histogram[i].green)*
PerceptibleReciprocal(MagickLog10((double) number_bins.green));
histogram[i].blue*=area;
channel_statistics[BlueChannel].entropy+=-histogram[i].blue*
MagickLog10(histogram[i].blue)*
PerceptibleReciprocal(MagickLog10((double) number_bins.blue));
if (image->matte != MagickFalse)
{
histogram[i].opacity*=area;
channel_statistics[OpacityChannel].entropy+=-histogram[i].opacity*
MagickLog10(histogram[i].opacity)*
PerceptibleReciprocal(MagickLog10((double) number_bins.opacity));
}
if (image->colorspace == CMYKColorspace)
{
histogram[i].index*=area;
channel_statistics[IndexChannel].entropy+=-histogram[i].index*
MagickLog10(histogram[i].index)*
PerceptibleReciprocal(MagickLog10((double) number_bins.index));
}
}
/*
Compute overall statistics.
*/
for (i=0; i < (ssize_t) CompositeChannels; i++)
{
channel_statistics[CompositeChannels].depth=(size_t) EvaluateMax((double)
channel_statistics[CompositeChannels].depth,(double)
channel_statistics[i].depth);
channel_statistics[CompositeChannels].minima=MagickMin(
channel_statistics[CompositeChannels].minima,
channel_statistics[i].minima);
channel_statistics[CompositeChannels].maxima=EvaluateMax(
channel_statistics[CompositeChannels].maxima,
channel_statistics[i].maxima);
channel_statistics[CompositeChannels].sum+=channel_statistics[i].sum;
channel_statistics[CompositeChannels].sum_squared+=
channel_statistics[i].sum_squared;
channel_statistics[CompositeChannels].sum_cubed+=
channel_statistics[i].sum_cubed;
channel_statistics[CompositeChannels].sum_fourth_power+=
channel_statistics[i].sum_fourth_power;
channel_statistics[CompositeChannels].mean+=channel_statistics[i].mean;
channel_statistics[CompositeChannels].variance+=
channel_statistics[i].variance-channel_statistics[i].mean*
channel_statistics[i].mean;
standard_deviation=sqrt(channel_statistics[i].variance-
(channel_statistics[i].mean*channel_statistics[i].mean));
area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)*
((double) image->columns*image->rows);
standard_deviation=sqrt(area*standard_deviation*standard_deviation);
channel_statistics[CompositeChannels].standard_deviation=standard_deviation;
channel_statistics[CompositeChannels].entropy+=
channel_statistics[i].entropy;
}
channels=3;
if (image->matte != MagickFalse)
channels++;
if (image->colorspace == CMYKColorspace)
channels++;
channel_statistics[CompositeChannels].sum/=channels;
channel_statistics[CompositeChannels].sum_squared/=channels;
channel_statistics[CompositeChannels].sum_cubed/=channels;
channel_statistics[CompositeChannels].sum_fourth_power/=channels;
channel_statistics[CompositeChannels].mean/=channels;
channel_statistics[CompositeChannels].kurtosis/=channels;
channel_statistics[CompositeChannels].skewness/=channels;
channel_statistics[CompositeChannels].entropy/=channels;
i=CompositeChannels;
area=PerceptibleReciprocal((double) channels*image->columns*image->rows);
channel_statistics[i].variance=channel_statistics[i].sum_squared;
channel_statistics[i].mean=channel_statistics[i].sum;
standard_deviation=sqrt(channel_statistics[i].variance-
(channel_statistics[i].mean*channel_statistics[i].mean));
standard_deviation=sqrt(PerceptibleReciprocal((double) channels*
image->columns*image->rows-1.0)*channels*image->columns*image->rows*
standard_deviation*standard_deviation);
channel_statistics[i].standard_deviation=standard_deviation;
for (i=0; i <= (ssize_t) CompositeChannels; i++)
{
/*
Compute kurtosis & skewness statistics.
*/
standard_deviation=PerceptibleReciprocal(
channel_statistics[i].standard_deviation);
channel_statistics[i].skewness=(channel_statistics[i].sum_cubed-3.0*
channel_statistics[i].mean*channel_statistics[i].sum_squared+2.0*
channel_statistics[i].mean*channel_statistics[i].mean*
channel_statistics[i].mean)*(standard_deviation*standard_deviation*
standard_deviation);
channel_statistics[i].kurtosis=(channel_statistics[i].sum_fourth_power-4.0*
channel_statistics[i].mean*channel_statistics[i].sum_cubed+6.0*
channel_statistics[i].mean*channel_statistics[i].mean*
channel_statistics[i].sum_squared-3.0*channel_statistics[i].mean*
channel_statistics[i].mean*1.0*channel_statistics[i].mean*
channel_statistics[i].mean)*(standard_deviation*standard_deviation*
standard_deviation*standard_deviation)-3.0;
}
channel_statistics[CompositeChannels].mean=0.0;
channel_statistics[CompositeChannels].standard_deviation=0.0;
for (i=0; i < (ssize_t) CompositeChannels; i++)
{
channel_statistics[CompositeChannels].mean+=
channel_statistics[i].mean;
channel_statistics[CompositeChannels].standard_deviation+=
channel_statistics[i].standard_deviation;
}
channel_statistics[CompositeChannels].mean/=(double) channels;
channel_statistics[CompositeChannels].standard_deviation/=(double) channels;
histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram);
if (y < (ssize_t) image->rows)
channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
channel_statistics);
return(channel_statistics);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P o l y n o m i a l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PolynomialImage() returns a new image where each pixel is the sum of the
% pixels in the image sequence after applying its corresponding terms
% (coefficient and degree pairs).
%
% The format of the PolynomialImage method is:
%
% Image *PolynomialImage(const Image *images,const size_t number_terms,
% const double *terms,ExceptionInfo *exception)
% Image *PolynomialImageChannel(const Image *images,
% const size_t number_terms,const ChannelType channel,
% const double *terms,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o images: the image sequence.
%
% o channel: the channel.
%
% o number_terms: the number of terms in the list. The actual list length
% is 2 x number_terms + 1 (the constant).
%
% o terms: the list of polynomial coefficients and degree pairs and a
% constant.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *PolynomialImage(const Image *images,
const size_t number_terms,const double *terms,ExceptionInfo *exception)
{
Image
*polynomial_image;
polynomial_image=PolynomialImageChannel(images,DefaultChannels,number_terms,
terms,exception);
return(polynomial_image);
}
MagickExport Image *PolynomialImageChannel(const Image *images,
const ChannelType channel,const size_t number_terms,const double *terms,
ExceptionInfo *exception)
{
#define PolynomialImageTag "Polynomial/Image"
CacheView
*polynomial_view;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
**magick_restrict polynomial_pixels,
zero;
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);
image=AcquireImageCanvas(images,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
InheritException(exception,&image->exception);
image=DestroyImage(image);
return((Image *) NULL);
}
polynomial_pixels=AcquirePixelThreadSet(images);
if (polynomial_pixels == (MagickPixelPacket **) NULL)
{
image=DestroyImage(image);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
return((Image *) NULL);
}
/*
Polynomial image pixels.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(images,&zero);
polynomial_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
CacheView
*image_view;
const Image
*next;
const int
id = GetOpenMPThreadId();
register IndexPacket
*magick_restrict polynomial_indexes;
register MagickPixelPacket
*polynomial_pixel;
register PixelPacket
*magick_restrict q;
register ssize_t
i,
x;
size_t
number_images;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(polynomial_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
polynomial_indexes=GetCacheViewAuthenticIndexQueue(polynomial_view);
polynomial_pixel=polynomial_pixels[id];
for (x=0; x < (ssize_t) image->columns; x++)
polynomial_pixel[x]=zero;
next=images;
number_images=GetImageListLength(images);
for (i=0; i < (ssize_t) number_images; i++)
{
register const IndexPacket
*indexes;
register const PixelPacket
*p;
if (i >= (ssize_t) number_terms)
break;
image_view=AcquireVirtualCacheView(next,exception);
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
{
image_view=DestroyCacheView(image_view);
break;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
double
coefficient,
degree;
coefficient=terms[i << 1];
degree=terms[(i << 1)+1];
if ((channel & RedChannel) != 0)
polynomial_pixel[x].red+=coefficient*pow(QuantumScale*p->red,degree);
if ((channel & GreenChannel) != 0)
polynomial_pixel[x].green+=coefficient*pow(QuantumScale*p->green,
degree);
if ((channel & BlueChannel) != 0)
polynomial_pixel[x].blue+=coefficient*pow(QuantumScale*p->blue,
degree);
if ((channel & OpacityChannel) != 0)
polynomial_pixel[x].opacity+=coefficient*pow(QuantumScale*
(QuantumRange-p->opacity),degree);
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
polynomial_pixel[x].index+=coefficient*pow(QuantumScale*indexes[x],
degree);
p++;
}
image_view=DestroyCacheView(image_view);
next=GetNextImageInList(next);
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].red));
SetPixelGreen(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].green));
SetPixelBlue(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].blue));
if (image->matte == MagickFalse)
SetPixelOpacity(q,ClampToQuantum(QuantumRange-QuantumRange*
polynomial_pixel[x].opacity));
else
SetPixelAlpha(q,ClampToQuantum(QuantumRange-QuantumRange*
polynomial_pixel[x].opacity));
if (image->colorspace == CMYKColorspace)
SetPixelIndex(polynomial_indexes+x,ClampToQuantum(QuantumRange*
polynomial_pixel[x].index));
q++;
}
if (SyncCacheViewAuthenticPixels(polynomial_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(images,PolynomialImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
polynomial_view=DestroyCacheView(polynomial_view);
polynomial_pixels=DestroyPixelThreadSet(polynomial_pixels);
if (status == MagickFalse)
image=DestroyImage(image);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S t a t i s t i c I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% StatisticImage() makes each pixel the min / max / median / mode / etc. of
% the neighborhood of the specified width and height.
%
% The format of the StatisticImage method is:
%
% Image *StatisticImage(const Image *image,const StatisticType type,
% const size_t width,const size_t height,ExceptionInfo *exception)
% Image *StatisticImageChannel(const Image *image,
% const ChannelType channel,const StatisticType type,
% const size_t width,const size_t height,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the image channel.
%
% o type: the statistic type (median, mode, etc.).
%
% o width: the width of the pixel neighborhood.
%
% o height: the height of the pixel neighborhood.
%
% o exception: return any errors or warnings in this structure.
%
*/
#define ListChannels 5
typedef struct _ListNode
{
size_t
next[9],
count,
signature;
} ListNode;
typedef struct _SkipList
{
ssize_t
level;
ListNode
*nodes;
} SkipList;
typedef struct _PixelList
{
size_t
length,
seed,
signature;
SkipList
lists[ListChannels];
} PixelList;
static PixelList *DestroyPixelList(PixelList *pixel_list)
{
register ssize_t
i;
if (pixel_list == (PixelList *) NULL)
return((PixelList *) NULL);
for (i=0; i < ListChannels; i++)
if (pixel_list->lists[i].nodes != (ListNode *) NULL)
pixel_list->lists[i].nodes=(ListNode *) RelinquishAlignedMemory(
pixel_list->lists[i].nodes);
pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list);
return(pixel_list);
}
static PixelList **DestroyPixelListThreadSet(PixelList **pixel_list)
{
register ssize_t
i;
assert(pixel_list != (PixelList **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (pixel_list[i] != (PixelList *) NULL)
pixel_list[i]=DestroyPixelList(pixel_list[i]);
pixel_list=(PixelList **) RelinquishMagickMemory(pixel_list);
return(pixel_list);
}
static PixelList *AcquirePixelList(const size_t width,const size_t height)
{
PixelList
*pixel_list;
register ssize_t
i;
pixel_list=(PixelList *) AcquireMagickMemory(sizeof(*pixel_list));
if (pixel_list == (PixelList *) NULL)
return(pixel_list);
(void) memset((void *) pixel_list,0,sizeof(*pixel_list));
pixel_list->length=width*height;
for (i=0; i < ListChannels; i++)
{
pixel_list->lists[i].nodes=(ListNode *) AcquireAlignedMemory(65537UL,
sizeof(*pixel_list->lists[i].nodes));
if (pixel_list->lists[i].nodes == (ListNode *) NULL)
return(DestroyPixelList(pixel_list));
(void) memset(pixel_list->lists[i].nodes,0,65537UL*
sizeof(*pixel_list->lists[i].nodes));
}
pixel_list->signature=MagickCoreSignature;
return(pixel_list);
}
static PixelList **AcquirePixelListThreadSet(const size_t width,
const size_t height)
{
PixelList
**pixel_list;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixel_list=(PixelList **) AcquireQuantumMemory(number_threads,
sizeof(*pixel_list));
if (pixel_list == (PixelList **) NULL)
return((PixelList **) NULL);
(void) memset(pixel_list,0,number_threads*sizeof(*pixel_list));
for (i=0; i < (ssize_t) number_threads; i++)
{
pixel_list[i]=AcquirePixelList(width,height);
if (pixel_list[i] == (PixelList *) NULL)
return(DestroyPixelListThreadSet(pixel_list));
}
return(pixel_list);
}
static void AddNodePixelList(PixelList *pixel_list,const ssize_t channel,
const size_t color)
{
register SkipList
*list;
register ssize_t
level;
size_t
search,
update[9];
/*
Initialize the node.
*/
list=pixel_list->lists+channel;
list->nodes[color].signature=pixel_list->signature;
list->nodes[color].count=1;
/*
Determine where it belongs in the list.
*/
search=65536UL;
for (level=list->level; level >= 0; level--)
{
while (list->nodes[search].next[level] < color)
search=list->nodes[search].next[level];
update[level]=search;
}
/*
Generate a pseudo-random level for this node.
*/
for (level=0; ; level++)
{
pixel_list->seed=(pixel_list->seed*42893621L)+1L;
if ((pixel_list->seed & 0x300) != 0x300)
break;
}
if (level > 8)
level=8;
if (level > (list->level+2))
level=list->level+2;
/*
If we're raising the list's level, link back to the root node.
*/
while (level > list->level)
{
list->level++;
update[list->level]=65536UL;
}
/*
Link the node into the skip-list.
*/
do
{
list->nodes[color].next[level]=list->nodes[update[level]].next[level];
list->nodes[update[level]].next[level]=color;
} while (level-- > 0);
}
static void GetMaximumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel)
{
register SkipList
*list;
register ssize_t
channel;
size_t
color,
maximum;
ssize_t
count;
unsigned short
channels[ListChannels];
/*
Find the maximum value for each of the color.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
count=0;
maximum=list->nodes[color].next[0];
do
{
color=list->nodes[color].next[0];
if (color > maximum)
maximum=color;
count+=list->nodes[color].count;
} while (count < (ssize_t) pixel_list->length);
channels[channel]=(unsigned short) maximum;
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetMeanPixelList(PixelList *pixel_list,MagickPixelPacket *pixel)
{
MagickRealType
sum;
register SkipList
*list;
register ssize_t
channel;
size_t
color;
ssize_t
count;
unsigned short
channels[ListChannels];
/*
Find the mean value for each of the color.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
count=0;
sum=0.0;
do
{
color=list->nodes[color].next[0];
sum+=(MagickRealType) list->nodes[color].count*color;
count+=list->nodes[color].count;
} while (count < (ssize_t) pixel_list->length);
sum/=pixel_list->length;
channels[channel]=(unsigned short) sum;
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetMedianPixelList(PixelList *pixel_list,MagickPixelPacket *pixel)
{
register SkipList
*list;
register ssize_t
channel;
size_t
color;
ssize_t
count;
unsigned short
channels[ListChannels];
/*
Find the median value for each of the color.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
count=0;
do
{
color=list->nodes[color].next[0];
count+=list->nodes[color].count;
} while (count <= (ssize_t) (pixel_list->length >> 1));
channels[channel]=(unsigned short) color;
}
GetMagickPixelPacket((const Image *) NULL,pixel);
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetMinimumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel)
{
register SkipList
*list;
register ssize_t
channel;
size_t
color,
minimum;
ssize_t
count;
unsigned short
channels[ListChannels];
/*
Find the minimum value for each of the color.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
count=0;
color=65536UL;
minimum=list->nodes[color].next[0];
do
{
color=list->nodes[color].next[0];
if (color < minimum)
minimum=color;
count+=list->nodes[color].count;
} while (count < (ssize_t) pixel_list->length);
channels[channel]=(unsigned short) minimum;
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetModePixelList(PixelList *pixel_list,MagickPixelPacket *pixel)
{
register SkipList
*list;
register ssize_t
channel;
size_t
color,
max_count,
mode;
ssize_t
count;
unsigned short
channels[5];
/*
Make each pixel the 'predominant color' of the specified neighborhood.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
mode=color;
max_count=list->nodes[mode].count;
count=0;
do
{
color=list->nodes[color].next[0];
if (list->nodes[color].count > max_count)
{
mode=color;
max_count=list->nodes[mode].count;
}
count+=list->nodes[color].count;
} while (count < (ssize_t) pixel_list->length);
channels[channel]=(unsigned short) mode;
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetNonpeakPixelList(PixelList *pixel_list,MagickPixelPacket *pixel)
{
register SkipList
*list;
register ssize_t
channel;
size_t
color,
next,
previous;
ssize_t
count;
unsigned short
channels[5];
/*
Finds the non peak value for each of the colors.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
next=list->nodes[color].next[0];
count=0;
do
{
previous=color;
color=next;
next=list->nodes[color].next[0];
count+=list->nodes[color].count;
} while (count <= (ssize_t) (pixel_list->length >> 1));
if ((previous == 65536UL) && (next != 65536UL))
color=next;
else
if ((previous != 65536UL) && (next == 65536UL))
color=previous;
channels[channel]=(unsigned short) color;
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetRootMeanSquarePixelList(PixelList *pixel_list,
MagickPixelPacket *pixel)
{
MagickRealType
sum;
register SkipList
*list;
register ssize_t
channel;
size_t
color;
ssize_t
count;
unsigned short
channels[ListChannels];
/*
Find the root mean square value for each of the color.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
count=0;
sum=0.0;
do
{
color=list->nodes[color].next[0];
sum+=(MagickRealType) (list->nodes[color].count*color*color);
count+=list->nodes[color].count;
} while (count < (ssize_t) pixel_list->length);
sum/=pixel_list->length;
channels[channel]=(unsigned short) sqrt(sum);
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetStandardDeviationPixelList(PixelList *pixel_list,
MagickPixelPacket *pixel)
{
MagickRealType
sum,
sum_squared;
register SkipList
*list;
register ssize_t
channel;
size_t
color;
ssize_t
count;
unsigned short
channels[ListChannels];
/*
Find the standard-deviation value for each of the color.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
count=0;
sum=0.0;
sum_squared=0.0;
do
{
register ssize_t
i;
color=list->nodes[color].next[0];
sum+=(MagickRealType) list->nodes[color].count*color;
for (i=0; i < (ssize_t) list->nodes[color].count; i++)
sum_squared+=((MagickRealType) color)*((MagickRealType) color);
count+=list->nodes[color].count;
} while (count < (ssize_t) pixel_list->length);
sum/=pixel_list->length;
sum_squared/=pixel_list->length;
channels[channel]=(unsigned short) sqrt(sum_squared-(sum*sum));
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static inline void InsertPixelList(const Image *image,const PixelPacket *pixel,
const IndexPacket *indexes,PixelList *pixel_list)
{
size_t
signature;
unsigned short
index;
index=ScaleQuantumToShort(GetPixelRed(pixel));
signature=pixel_list->lists[0].nodes[index].signature;
if (signature == pixel_list->signature)
pixel_list->lists[0].nodes[index].count++;
else
AddNodePixelList(pixel_list,0,index);
index=ScaleQuantumToShort(GetPixelGreen(pixel));
signature=pixel_list->lists[1].nodes[index].signature;
if (signature == pixel_list->signature)
pixel_list->lists[1].nodes[index].count++;
else
AddNodePixelList(pixel_list,1,index);
index=ScaleQuantumToShort(GetPixelBlue(pixel));
signature=pixel_list->lists[2].nodes[index].signature;
if (signature == pixel_list->signature)
pixel_list->lists[2].nodes[index].count++;
else
AddNodePixelList(pixel_list,2,index);
index=ScaleQuantumToShort(GetPixelOpacity(pixel));
signature=pixel_list->lists[3].nodes[index].signature;
if (signature == pixel_list->signature)
pixel_list->lists[3].nodes[index].count++;
else
AddNodePixelList(pixel_list,3,index);
if (image->colorspace == CMYKColorspace)
index=ScaleQuantumToShort(GetPixelIndex(indexes));
signature=pixel_list->lists[4].nodes[index].signature;
if (signature == pixel_list->signature)
pixel_list->lists[4].nodes[index].count++;
else
AddNodePixelList(pixel_list,4,index);
}
static void ResetPixelList(PixelList *pixel_list)
{
int
level;
register ListNode
*root;
register SkipList
*list;
register ssize_t
channel;
/*
Reset the skip-list.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
root=list->nodes+65536UL;
list->level=0;
for (level=0; level < 9; level++)
root->next[level]=65536UL;
}
pixel_list->seed=pixel_list->signature++;
}
MagickExport Image *StatisticImage(const Image *image,const StatisticType type,
const size_t width,const size_t height,ExceptionInfo *exception)
{
Image
*statistic_image;
statistic_image=StatisticImageChannel(image,DefaultChannels,type,width,
height,exception);
return(statistic_image);
}
MagickExport Image *StatisticImageChannel(const Image *image,
const ChannelType channel,const StatisticType type,const size_t width,
const size_t height,ExceptionInfo *exception)
{
#define StatisticImageTag "Statistic/Image"
CacheView
*image_view,
*statistic_view;
Image
*statistic_image;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelList
**magick_restrict pixel_list;
size_t
neighbor_height,
neighbor_width;
ssize_t
y;
/*
Initialize statistics image attributes.
*/
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);
statistic_image=CloneImage(image,0,0,MagickTrue,exception);
if (statistic_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(statistic_image,DirectClass) == MagickFalse)
{
InheritException(exception,&statistic_image->exception);
statistic_image=DestroyImage(statistic_image);
return((Image *) NULL);
}
neighbor_width=width == 0 ? GetOptimalKernelWidth2D((double) width,0.5) :
width;
neighbor_height=height == 0 ? GetOptimalKernelWidth2D((double) height,0.5) :
height;
pixel_list=AcquirePixelListThreadSet(neighbor_width,neighbor_height);
if (pixel_list == (PixelList **) NULL)
{
statistic_image=DestroyImage(statistic_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Make each pixel the min / max / median / mode / etc. of the neighborhood.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
statistic_view=AcquireAuthenticCacheView(statistic_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,statistic_image,statistic_image->rows,1)
#endif
for (y=0; y < (ssize_t) statistic_image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict statistic_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) neighbor_width/2L),y-
(ssize_t) (neighbor_height/2L),image->columns+neighbor_width,
neighbor_height,exception);
q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns, 1,exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
statistic_indexes=GetCacheViewAuthenticIndexQueue(statistic_view);
for (x=0; x < (ssize_t) statistic_image->columns; x++)
{
MagickPixelPacket
pixel;
register const IndexPacket
*magick_restrict s;
register const PixelPacket
*magick_restrict r;
register ssize_t
u,
v;
r=p;
s=indexes+x;
ResetPixelList(pixel_list[id]);
for (v=0; v < (ssize_t) neighbor_height; v++)
{
for (u=0; u < (ssize_t) neighbor_width; u++)
InsertPixelList(image,r+u,s+u,pixel_list[id]);
r+=image->columns+neighbor_width;
s+=image->columns+neighbor_width;
}
GetMagickPixelPacket(image,&pixel);
SetMagickPixelPacket(image,p+neighbor_width*neighbor_height/2,indexes+x+
neighbor_width*neighbor_height/2,&pixel);
switch (type)
{
case GradientStatistic:
{
MagickPixelPacket
maximum,
minimum;
GetMinimumPixelList(pixel_list[id],&pixel);
minimum=pixel;
GetMaximumPixelList(pixel_list[id],&pixel);
maximum=pixel;
pixel.red=MagickAbsoluteValue(maximum.red-minimum.red);
pixel.green=MagickAbsoluteValue(maximum.green-minimum.green);
pixel.blue=MagickAbsoluteValue(maximum.blue-minimum.blue);
pixel.opacity=MagickAbsoluteValue(maximum.opacity-minimum.opacity);
if (image->colorspace == CMYKColorspace)
pixel.index=MagickAbsoluteValue(maximum.index-minimum.index);
break;
}
case MaximumStatistic:
{
GetMaximumPixelList(pixel_list[id],&pixel);
break;
}
case MeanStatistic:
{
GetMeanPixelList(pixel_list[id],&pixel);
break;
}
case MedianStatistic:
default:
{
GetMedianPixelList(pixel_list[id],&pixel);
break;
}
case MinimumStatistic:
{
GetMinimumPixelList(pixel_list[id],&pixel);
break;
}
case ModeStatistic:
{
GetModePixelList(pixel_list[id],&pixel);
break;
}
case NonpeakStatistic:
{
GetNonpeakPixelList(pixel_list[id],&pixel);
break;
}
case RootMeanSquareStatistic:
{
GetRootMeanSquarePixelList(pixel_list[id],&pixel);
break;
}
case StandardDeviationStatistic:
{
GetStandardDeviationPixelList(pixel_list[id],&pixel);
break;
}
}
if ((channel & RedChannel) != 0)
SetPixelRed(q,ClampToQuantum(pixel.red));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ClampToQuantum(pixel.green));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ClampToQuantum(pixel.blue));
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,ClampToQuantum(pixel.opacity));
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(statistic_indexes+x,ClampToQuantum(pixel.index));
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(statistic_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,StatisticImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
statistic_view=DestroyCacheView(statistic_view);
image_view=DestroyCacheView(image_view);
pixel_list=DestroyPixelListThreadSet(pixel_list);
if (status == MagickFalse)
statistic_image=DestroyImage(statistic_image);
return(statistic_image);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_930_0 |
crossvul-cpp_data_good_3111_0 | /**********************************************************************
* $Id$
*
* Project: MapServer
* Purpose: OGC Filter Encoding implementation
* Author: Y. Assefa, DM Solutions Group (assefa@dmsolutions.ca)
*
**********************************************************************
* Copyright (c) 2003, Y. Assefa, DM Solutions Group Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies of this Software or works derived from this Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
****************************************************************************/
#define _GNU_SOURCE
#include "mapserver-config.h"
#ifdef USE_OGR
#include "cpl_minixml.h"
#include "cpl_string.h"
#endif
#include "mapogcfilter.h"
#include "mapserver.h"
#include "mapowscommon.h"
#include "maptime.h"
#include "mapows.h"
#include <ctype.h>
#if 0
static int FLTHasUniqueTopLevelDuringFilter(FilterEncodingNode *psFilterNode);
#endif
int FLTIsNumeric(const char *pszValue)
{
if (pszValue != NULL && *pszValue != '\0' && !isspace(*pszValue)) {
/*the regex seems to have a problem on windows when mapserver is built using
PHP regex*/
#if defined(_WIN32) && !defined(__CYGWIN__)
int i = 0, nLength=0, bString=0;
nLength = strlen(pszValue);
for (i=0; i<nLength; i++) {
if (i == 0) {
if (!isdigit(pszValue[i]) && pszValue[i] != '-') {
bString = 1;
break;
}
} else if (!isdigit(pszValue[i]) && pszValue[i] != '.') {
bString = 1;
break;
}
}
if (!bString)
return MS_TRUE;
#else
char * p;
strtod(pszValue, &p);
if ( p != pszValue && *p == '\0') return MS_TRUE;
#endif
}
return MS_FALSE;
}
/*
** Apply an expression to the layer's filter element.
**
*/
int FLTApplyExpressionToLayer(layerObj *lp, const char *pszExpression)
{
char *pszFinalExpression=NULL, *pszBuffer = NULL;
/*char *escapedTextString=NULL;*/
int bConcatWhere=0, bHasAWhere=0;
if (lp && pszExpression) {
if (lp->connectiontype == MS_POSTGIS || lp->connectiontype == MS_ORACLESPATIAL ||
lp->connectiontype == MS_PLUGIN) {
pszFinalExpression = msStrdup("(");
pszFinalExpression = msStringConcatenate(pszFinalExpression, pszExpression);
pszFinalExpression = msStringConcatenate(pszFinalExpression, ")");
} else if (lp->connectiontype == MS_OGR) {
pszFinalExpression = msStrdup(pszExpression);
if (lp->filter.type != MS_EXPRESSION) {
bConcatWhere = 1;
} else {
if (lp->filter.string && EQUALN(lp->filter.string,"WHERE ",6)) {
bHasAWhere = 1;
bConcatWhere =1;
}
}
} else
pszFinalExpression = msStrdup(pszExpression);
if (bConcatWhere)
pszBuffer = msStringConcatenate(pszBuffer, "WHERE ");
/* if the filter is set and it's an expression type, concatenate it with
this filter. If not just free it */
if (lp->filter.string && lp->filter.type == MS_EXPRESSION) {
pszBuffer = msStringConcatenate(pszBuffer, "((");
if (bHasAWhere)
pszBuffer = msStringConcatenate(pszBuffer, lp->filter.string+6);
else
pszBuffer = msStringConcatenate(pszBuffer, lp->filter.string);
pszBuffer = msStringConcatenate(pszBuffer, ") and ");
} else if (lp->filter.string)
msFreeExpression(&lp->filter);
pszBuffer = msStringConcatenate(pszBuffer, pszFinalExpression);
if(lp->filter.string && lp->filter.type == MS_EXPRESSION)
pszBuffer = msStringConcatenate(pszBuffer, ")");
/*assuming that expression was properly escaped
escapedTextString = msStringEscape(pszBuffer);
msLoadExpressionString(&lp->filter,
(char*)CPLSPrintf("%s", escapedTextString));
msFree(escapedTextString);
*/
msLoadExpressionString(&lp->filter, pszBuffer);
msFree(pszFinalExpression);
if (pszBuffer)
msFree(pszBuffer);
return MS_TRUE;
}
return MS_FALSE;
}
char *FLTGetExpressionForValuesRanges(layerObj *lp, const char *item, const char *value, int forcecharcter)
{
int bIscharacter, bSqlLayer=MS_FALSE;
char *pszExpression = NULL, *pszEscapedStr=NULL, *pszTmpExpression=NULL;
char **paszElements = NULL, **papszRangeElements=NULL;
int numelements,i,nrangeelements;
/* TODO: remove the bSqlLayer checks since we want to write MapServer expressions only. */
/* double minval, maxval; */
if (lp && item && value) {
if (strstr(value, "/") == NULL) {
/*value(s)*/
paszElements = msStringSplit (value, ',', &numelements);
if (paszElements && numelements > 0) {
if (forcecharcter)
bIscharacter = MS_TRUE;
bIscharacter= !FLTIsNumeric(paszElements[0]);
pszTmpExpression = msStringConcatenate(pszTmpExpression, "(");
for (i=0; i<numelements; i++) {
pszTmpExpression = msStringConcatenate(pszTmpExpression, "(");
if (bSqlLayer)
pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
else {
if (bIscharacter)
pszTmpExpression = msStringConcatenate(pszTmpExpression, "\"");
pszTmpExpression = msStringConcatenate(pszTmpExpression, "[");
pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
pszTmpExpression = msStringConcatenate(pszTmpExpression, "]");
if (bIscharacter)
pszTmpExpression = msStringConcatenate(pszTmpExpression, "\"");
}
if (bIscharacter) {
if (bSqlLayer)
pszTmpExpression = msStringConcatenate(pszTmpExpression, " = '");
else
pszTmpExpression = msStringConcatenate(pszTmpExpression, " = \"");
} else
pszTmpExpression = msStringConcatenate(pszTmpExpression, " = ");
pszEscapedStr = msLayerEscapeSQLParam(lp, paszElements[i]);
pszTmpExpression = msStringConcatenate(pszTmpExpression, pszEscapedStr);
if (bIscharacter) {
if (bSqlLayer)
pszTmpExpression = msStringConcatenate(pszTmpExpression, "'");
else
pszTmpExpression = msStringConcatenate(pszTmpExpression, "\"");
}
pszTmpExpression = msStringConcatenate(pszTmpExpression, ")");
msFree(pszEscapedStr);
pszEscapedStr=NULL;
if (pszExpression != NULL)
pszExpression = msStringConcatenate(pszExpression, " OR ");
pszExpression = msStringConcatenate(pszExpression, pszTmpExpression);
msFree(pszTmpExpression);
pszTmpExpression = NULL;
}
pszExpression = msStringConcatenate(pszExpression, ")");
}
msFreeCharArray(paszElements, numelements);
} else {
/*range(s)*/
paszElements = msStringSplit (value, ',', &numelements);
if (paszElements && numelements > 0) {
pszTmpExpression = msStringConcatenate(pszTmpExpression, "(");
for (i=0; i<numelements; i++) {
papszRangeElements = msStringSplit (paszElements[i], '/', &nrangeelements);
if (papszRangeElements && nrangeelements > 0) {
pszTmpExpression = msStringConcatenate(pszTmpExpression, "(");
if (nrangeelements == 2 || nrangeelements == 3) {
/*
minval = atof(papszRangeElements[0]);
maxval = atof(papszRangeElements[1]);
*/
if (bSqlLayer)
pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
else {
pszTmpExpression = msStringConcatenate(pszTmpExpression, "[");
pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
pszTmpExpression = msStringConcatenate(pszTmpExpression, "]");
}
pszTmpExpression = msStringConcatenate(pszTmpExpression, " >= ");
pszEscapedStr = msLayerEscapeSQLParam(lp, papszRangeElements[0]);
pszTmpExpression = msStringConcatenate(pszTmpExpression, pszEscapedStr);
msFree(pszEscapedStr);
pszEscapedStr=NULL;
pszTmpExpression = msStringConcatenate(pszTmpExpression, " AND ");
if (bSqlLayer)
pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
else {
pszTmpExpression = msStringConcatenate(pszTmpExpression, "[");
pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
pszTmpExpression = msStringConcatenate(pszTmpExpression, "]");
}
pszTmpExpression = msStringConcatenate(pszTmpExpression, " <= ");
pszEscapedStr = msLayerEscapeSQLParam(lp, papszRangeElements[1]);
pszTmpExpression = msStringConcatenate(pszTmpExpression, pszEscapedStr);
msFree(pszEscapedStr);
pszEscapedStr=NULL;
pszTmpExpression = msStringConcatenate(pszTmpExpression, ")");
} else if (nrangeelements == 1) {
pszTmpExpression = msStringConcatenate(pszTmpExpression, "(");
if (bSqlLayer)
pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
else {
pszTmpExpression = msStringConcatenate(pszTmpExpression, "[");
pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
pszTmpExpression = msStringConcatenate(pszTmpExpression, "]");
}
pszTmpExpression = msStringConcatenate(pszTmpExpression, " = ");
pszEscapedStr = msLayerEscapeSQLParam(lp, papszRangeElements[0]);
pszTmpExpression = msStringConcatenate(pszTmpExpression, pszEscapedStr);
msFree(pszEscapedStr);
pszEscapedStr=NULL;
pszTmpExpression = msStringConcatenate(pszTmpExpression, ")");
}
if (pszExpression != NULL)
pszExpression = msStringConcatenate(pszExpression, " OR ");
pszExpression = msStringConcatenate(pszExpression, pszTmpExpression);
msFree(pszTmpExpression);
pszTmpExpression = NULL;
}
msFreeCharArray(papszRangeElements, nrangeelements);
}
pszExpression = msStringConcatenate(pszExpression, ")");
}
msFreeCharArray(paszElements, numelements);
}
}
msFree(pszTmpExpression);
return pszExpression;
}
#ifdef USE_OGR
int FLTogrConvertGeometry(OGRGeometryH hGeometry, shapeObj *psShape,
OGRwkbGeometryType nType)
{
return msOGRGeometryToShape(hGeometry, psShape, nType);
}
static
int FLTShapeFromGMLTree(CPLXMLNode *psTree, shapeObj *psShape , char **ppszSRS)
{
const char *pszSRS = NULL;
if (psTree && psShape) {
CPLXMLNode *psNext = psTree->psNext;
OGRGeometryH hGeometry = NULL;
psTree->psNext = NULL;
hGeometry = OGR_G_CreateFromGMLTree(psTree );
psTree->psNext = psNext;
if (hGeometry) {
OGRwkbGeometryType nType;
nType = OGR_G_GetGeometryType(hGeometry);
if (nType == wkbPolygon25D || nType == wkbMultiPolygon25D)
nType = wkbPolygon;
else if (nType == wkbLineString25D || nType == wkbMultiLineString25D)
nType = wkbLineString;
else if (nType == wkbPoint25D || nType == wkbMultiPoint25D)
nType = wkbPoint;
FLTogrConvertGeometry(hGeometry, psShape, nType);
OGR_G_DestroyGeometry(hGeometry);
pszSRS = CPLGetXMLValue(psTree, "srsName", NULL);
if (ppszSRS && pszSRS)
*ppszSRS = msStrdup(pszSRS);
return MS_TRUE;
}
}
return MS_FALSE;
}
int FLTGetGeosOperator(char *pszValue)
{
if (!pszValue)
return -1;
if (strcasecmp(pszValue, "Equals") == 0)
return MS_GEOS_EQUALS;
else if (strcasecmp(pszValue, "Intersect") == 0 ||
strcasecmp(pszValue, "Intersects") == 0)
return MS_GEOS_INTERSECTS;
else if (strcasecmp(pszValue, "Disjoint") == 0)
return MS_GEOS_DISJOINT;
else if (strcasecmp(pszValue, "Touches") == 0)
return MS_GEOS_TOUCHES;
else if (strcasecmp(pszValue, "Crosses") == 0)
return MS_GEOS_CROSSES;
else if (strcasecmp(pszValue, "Within") == 0)
return MS_GEOS_WITHIN;
else if (strcasecmp(pszValue, "Contains") == 0)
return MS_GEOS_CONTAINS;
else if (strcasecmp(pszValue, "Overlaps") == 0)
return MS_GEOS_OVERLAPS;
else if (strcasecmp(pszValue, "Beyond") == 0)
return MS_GEOS_BEYOND;
else if (strcasecmp(pszValue, "DWithin") == 0)
return MS_GEOS_DWITHIN;
return -1;
}
int FLTIsGeosNode(char *pszValue)
{
if (FLTGetGeosOperator(pszValue) == -1)
return MS_FALSE;
return MS_TRUE;
}
/************************************************************************/
/* FLTIsSimpleFilterNoSpatial */
/* */
/* Filter encoding with only attribute queries */
/************************************************************************/
int FLTIsSimpleFilterNoSpatial(FilterEncodingNode *psNode)
{
if (FLTIsSimpleFilter(psNode) && FLTNumberOfFilterType(psNode, "BBOX") == 0)
return MS_TRUE;
return MS_FALSE;
}
/************************************************************************/
/* FLTApplySimpleSQLFilter() */
/************************************************************************/
int FLTApplySimpleSQLFilter(FilterEncodingNode *psNode, mapObj *map, int iLayerIndex)
{
layerObj *lp = NULL;
char *szExpression = NULL;
rectObj sQueryRect = map->extent;
const char *szEPSG = NULL;
projectionObj sProjTmp;
char *pszBuffer = NULL;
int bConcatWhere = 0;
int bHasAWhere =0;
char *pszTmp = NULL, *pszTmp2 = NULL;
char *tmpfilename = NULL;
const char* pszTimeField = NULL;
const char* pszTimeValue = NULL;
lp = (GET_LAYER(map, iLayerIndex));
/* if there is a bbox use it */
szEPSG = FLTGetBBOX(psNode, &sQueryRect);
if(szEPSG && map->projection.numargs > 0) {
msInitProjection(&sProjTmp);
/* Use the non EPSG variant since axis swapping is done in FLTDoAxisSwappingIfNecessary */
if (msLoadProjectionString(&sProjTmp, szEPSG) == 0) {
msProjectRect(&sProjTmp, &map->projection, &sQueryRect);
}
msFreeProjection(&sProjTmp);
}
if( lp->connectiontype == MS_OGR ) {
pszTimeValue = FLTGetDuring(psNode, &pszTimeField);
}
/* make sure that the layer can be queried*/
if (!lp->template) lp->template = msStrdup("ttt.html");
/* if there is no class, create at least one, so that query by rect would work */
if (lp->numclasses == 0) {
if (msGrowLayerClasses(lp) == NULL)
return MS_FAILURE;
initClass(lp->class[0]);
}
bConcatWhere = 0;
bHasAWhere = 0;
if (lp->connectiontype == MS_POSTGIS || lp->connectiontype == MS_ORACLESPATIAL ||
lp->connectiontype == MS_PLUGIN) {
szExpression = FLTGetSQLExpression(psNode, lp);
if (szExpression) {
pszTmp = msStrdup("(");
pszTmp = msStringConcatenate(pszTmp, szExpression);
pszTmp = msStringConcatenate(pszTmp, ")");
msFree(szExpression);
szExpression = pszTmp;
}
}
/* concatenates the WHERE clause for OGR layers. This only applies if
the expression was empty or not of an expression string. If there
is an sql type expression, it is assumed to have the WHERE clause.
If it is an expression and does not have a WHERE it is assumed to be a mapserver
type expression*/
else if (lp->connectiontype == MS_OGR) {
if (lp->filter.type != MS_EXPRESSION) {
szExpression = FLTGetSQLExpression(psNode, lp);
bConcatWhere = 1;
} else {
if (lp->filter.string && EQUALN(lp->filter.string,"WHERE ",6)) {
szExpression = FLTGetSQLExpression(psNode, lp);
bHasAWhere = 1;
bConcatWhere =1;
} else {
szExpression = FLTGetCommonExpression(psNode, lp);
}
}
} else {
szExpression = FLTGetCommonExpression(psNode, lp);
}
if (szExpression) {
if (bConcatWhere)
pszBuffer = msStringConcatenate(pszBuffer, "WHERE ");
/* if the filter is set and it's an expression type, concatenate it with
this filter. If not just free it */
if (lp->filter.string && lp->filter.type == MS_EXPRESSION) {
pszBuffer = msStringConcatenate(pszBuffer, "((");
if (bHasAWhere)
pszBuffer = msStringConcatenate(pszBuffer, lp->filter.string+6);
else
pszBuffer = msStringConcatenate(pszBuffer, lp->filter.string);
pszBuffer = msStringConcatenate(pszBuffer, ") and ");
} else if (lp->filter.string)
msFreeExpression(&lp->filter);
pszBuffer = msStringConcatenate(pszBuffer, szExpression);
if(lp->filter.string && lp->filter.type == MS_EXPRESSION)
pszBuffer = msStringConcatenate(pszBuffer, ")");
msLoadExpressionString(&lp->filter, pszBuffer);
free(szExpression);
}
if (pszTimeField && pszTimeValue)
msLayerSetTimeFilter(lp, pszTimeValue, pszTimeField);
if (pszBuffer)
free(pszBuffer);
map->query.type = MS_QUERY_BY_RECT;
map->query.mode = MS_QUERY_MULTIPLE;
map->query.layer = lp->index;
map->query.rect = sQueryRect;
if(map->debug == MS_DEBUGLEVEL_VVV) {
tmpfilename = msTmpFile(map, map->mappath, NULL, "_filter.map");
if (tmpfilename == NULL) {
tmpfilename = msTmpFile(map, NULL, NULL, "_filter.map" );
}
if (tmpfilename) {
msSaveMap(map,tmpfilename);
msDebug("FLTApplySimpleSQLFilter(): Map file after Filter was applied %s\n", tmpfilename);
msFree(tmpfilename);
}
}
/*for oracle connection, if we have a simple filter with no spatial constraints
we should set the connection function to NONE to have a better performance
(#2725)*/
if (lp->connectiontype == MS_ORACLESPATIAL && FLTIsSimpleFilterNoSpatial(psNode)) {
if (strcasestr(lp->data, "USING") == 0)
lp->data = msStringConcatenate(lp->data, " USING NONE");
else if (strcasestr(lp->data, "NONE") == 0) {
/*if one of the functions is used, just replace it with NONE*/
if (strcasestr(lp->data, "FILTER"))
lp->data = msCaseReplaceSubstring(lp->data, "FILTER", "NONE");
else if (strcasestr(lp->data, "GEOMRELATE"))
lp->data = msCaseReplaceSubstring(lp->data, "GEOMRELATE", "NONE");
else if (strcasestr(lp->data, "RELATE"))
lp->data = msCaseReplaceSubstring(lp->data, "RELATE", "NONE");
else if (strcasestr(lp->data, "VERSION")) {
/*should add NONE just before the VERSION. Cases are:
DATA "ORA_GEOMETRY FROM data USING VERSION 10g
DATA "ORA_GEOMETRY FROM data USING UNIQUE FID VERSION 10g"
*/
pszTmp = (char *)strcasestr(lp->data, "VERSION");
pszTmp2 = msStringConcatenate(pszTmp2, " NONE ");
pszTmp2 = msStringConcatenate(pszTmp2, pszTmp);
lp->data = msCaseReplaceSubstring(lp->data, pszTmp, pszTmp2);
msFree(pszTmp2);
} else if (strcasestr(lp->data, "SRID")) {
lp->data = msStringConcatenate(lp->data, " NONE");
}
}
}
return msQueryByRect(map);
/* return MS_SUCCESS; */
}
/************************************************************************/
/* FLTIsSimpleFilter */
/* */
/* Filter encoding with only attribute queries and only one bbox. */
/************************************************************************/
int FLTIsSimpleFilter(FilterEncodingNode *psNode)
{
if (FLTValidForBBoxFilter(psNode)) {
if (FLTNumberOfFilterType(psNode, "DWithin") == 0 &&
FLTNumberOfFilterType(psNode, "Intersect") == 0 &&
FLTNumberOfFilterType(psNode, "Intersects") == 0 &&
FLTNumberOfFilterType(psNode, "Equals") == 0 &&
FLTNumberOfFilterType(psNode, "Disjoint") == 0 &&
FLTNumberOfFilterType(psNode, "Touches") == 0 &&
FLTNumberOfFilterType(psNode, "Crosses") == 0 &&
FLTNumberOfFilterType(psNode, "Within") == 0 &&
FLTNumberOfFilterType(psNode, "Contains") == 0 &&
FLTNumberOfFilterType(psNode, "Overlaps") == 0 &&
FLTNumberOfFilterType(psNode, "Beyond") == 0)
return TRUE;
}
return FALSE;
}
/************************************************************************/
/* FLTApplyFilterToLayer */
/* */
/* Use the filter encoding node to create mapserver expressions */
/* and apply it to the layer. */
/************************************************************************/
int FLTApplyFilterToLayer(FilterEncodingNode *psNode, mapObj *map, int iLayerIndex)
{
layerObj *layer = GET_LAYER(map, iLayerIndex);
if ( ! layer->vtable) {
int rv = msInitializeVirtualTable(layer);
if (rv != MS_SUCCESS)
return rv;
}
return layer->vtable->LayerApplyFilterToLayer(psNode, map, iLayerIndex);
}
/************************************************************************/
/* FLTLayerApplyCondSQLFilterToLayer */
/* */
/* Helper function for layer virtual table architecture */
/************************************************************************/
int FLTLayerApplyCondSQLFilterToLayer(FilterEncodingNode *psNode, mapObj *map, int iLayerIndex)
{
return FLTLayerApplyPlainFilterToLayer(psNode, map, iLayerIndex);
}
/************************************************************************/
/* FLTGetTopBBOX */
/* */
/* Return the "top" BBOX if there's a unique one. */
/************************************************************************/
static int FLTGetTopBBOXInternal(FilterEncodingNode *psNode, FilterEncodingNode** ppsTopBBOX, int *pnCount)
{
if (psNode->pszValue && strcasecmp(psNode->pszValue, "BBOX") == 0) {
(*pnCount) ++;
if( *pnCount == 1 )
{
*ppsTopBBOX = psNode;
return TRUE;
}
*ppsTopBBOX = NULL;
return FALSE;
}
else if (psNode->pszValue && strcasecmp(psNode->pszValue, "AND") == 0) {
return FLTGetTopBBOXInternal(psNode->psLeftNode, ppsTopBBOX, pnCount) &&
FLTGetTopBBOXInternal(psNode->psRightNode, ppsTopBBOX, pnCount);
}
else
{
return TRUE;
}
}
static FilterEncodingNode* FLTGetTopBBOX(FilterEncodingNode *psNode)
{
int nCount = 0;
FilterEncodingNode* psTopBBOX = NULL;
FLTGetTopBBOXInternal(psNode, &psTopBBOX, &nCount);
return psTopBBOX;
}
/************************************************************************/
/* FLTLayerApplyPlainFilterToLayer */
/* */
/* Helper function for layer virtual table architecture */
/************************************************************************/
int FLTLayerApplyPlainFilterToLayer(FilterEncodingNode *psNode, mapObj *map,
int iLayerIndex)
{
char *pszExpression =NULL;
int status =MS_FALSE;
layerObj* lp = GET_LAYER(map, iLayerIndex);
pszExpression = FLTGetCommonExpression(psNode, lp);
if (pszExpression) {
const char* pszUseDefaultExtent;
FilterEncodingNode* psTopBBOX;
rectObj rect = map->extent;
pszUseDefaultExtent = msOWSLookupMetadata(&(lp->metadata), "F",
"use_default_extent_for_getfeature");
if( pszUseDefaultExtent && !CSLTestBoolean(pszUseDefaultExtent) &&
lp->connectiontype == MS_OGR )
{
const rectObj rectInvalid = MS_INIT_INVALID_RECT;
rect = rectInvalid;
}
psTopBBOX = FLTGetTopBBOX(psNode);
if( psTopBBOX )
{
int can_remove_expression = MS_TRUE;
const char* pszEPSG = FLTGetBBOX(psNode, &rect);
if(pszEPSG && map->projection.numargs > 0) {
projectionObj sProjTmp;
msInitProjection(&sProjTmp);
/* Use the non EPSG variant since axis swapping is done in FLTDoAxisSwappingIfNecessary */
if (msLoadProjectionString(&sProjTmp, pszEPSG) == 0) {
rectObj oldRect = rect;
msProjectRect(&sProjTmp, &map->projection, &rect);
/* If reprojection is involved, do not remove the expression */
if( rect.minx != oldRect.minx ||
rect.miny != oldRect.miny ||
rect.maxx != oldRect.maxx ||
rect.maxy != oldRect.maxy )
{
can_remove_expression = MS_FALSE;
}
}
msFreeProjection(&sProjTmp);
}
/* Small optimization: if the query is just a BBOX, then do a */
/* msQueryByRect() */
if( psTopBBOX == psNode && can_remove_expression )
{
msFree(pszExpression);
pszExpression = NULL;
}
}
if(map->debug == MS_DEBUGLEVEL_VVV)
{
if( pszExpression )
msDebug("FLTLayerApplyPlainFilterToLayer(): %s, rect=%.15g,%.15g,%.15g,%.15g\n", pszExpression, rect.minx, rect.miny, rect.maxx, rect.maxy);
else
msDebug("FLTLayerApplyPlainFilterToLayer(): rect=%.15g,%.15g,%.15g,%.15g\n", rect.minx, rect.miny, rect.maxx, rect.maxy);
}
status = FLTApplyFilterToLayerCommonExpressionWithRect(map, iLayerIndex,
pszExpression, rect);
msFree(pszExpression);
}
return status;
}
/************************************************************************/
/* FilterNode *FLTPaserFilterEncoding(char *szXMLString) */
/* */
/* Parses an Filter Encoding XML string and creates a */
/* FilterEncodingNodes corresponding to the string. */
/* Returns a pointer to the first node or NULL if */
/* unsuccessfull. */
/* Calling function should use FreeFilterEncodingNode function */
/* to free memeory. */
/************************************************************************/
FilterEncodingNode *FLTParseFilterEncoding(const char *szXMLString)
{
CPLXMLNode *psRoot = NULL, *psChild=NULL, *psFilter=NULL;
FilterEncodingNode *psFilterNode = NULL;
if (szXMLString == NULL || strlen(szXMLString) <= 0 ||
(strstr(szXMLString, "Filter") == NULL))
return NULL;
psRoot = CPLParseXMLString(szXMLString);
if( psRoot == NULL)
return NULL;
/* strip namespaces. We srtip all name spaces (#1350)*/
CPLStripXMLNamespace(psRoot, NULL, 1);
/* -------------------------------------------------------------------- */
/* get the root element (Filter). */
/* -------------------------------------------------------------------- */
psFilter = CPLGetXMLNode(psRoot, "=Filter");
if (!psFilter)
{
CPLDestroyXMLNode( psRoot );
return NULL;
}
psChild = psFilter->psChild;
while (psChild) {
if (FLTIsSupportedFilterType(psChild)) {
psFilterNode = FLTCreateFilterEncodingNode();
FLTInsertElementInNode(psFilterNode, psChild);
break;
} else
psChild = psChild->psNext;
}
CPLDestroyXMLNode( psRoot );
/* -------------------------------------------------------------------- */
/* validate the node tree to make sure that all the nodes are valid.*/
/* -------------------------------------------------------------------- */
if (!FLTValidFilterNode(psFilterNode)) {
FLTFreeFilterEncodingNode(psFilterNode);
return NULL;
}
return psFilterNode;
}
/************************************************************************/
/* int FLTValidFilterNode(FilterEncodingNode *psFilterNode) */
/* */
/* Validate that all the nodes are filled properly. We could */
/* have parts of the nodes that are correct and part which */
/* could be incorrect if the filter string sent is corrupted */
/* (eg missing a value :<PropertyName><PropertyName>) */
/************************************************************************/
int FLTValidFilterNode(FilterEncodingNode *psFilterNode)
{
int bReturn = 0;
if (!psFilterNode)
return 0;
if (psFilterNode->eType == FILTER_NODE_TYPE_UNDEFINED)
return 0;
if (psFilterNode->psLeftNode) {
bReturn = FLTValidFilterNode(psFilterNode->psLeftNode);
if (bReturn == 0)
return 0;
else if (psFilterNode->psRightNode)
return FLTValidFilterNode(psFilterNode->psRightNode);
}
return 1;
}
/************************************************************************/
/* FLTIsGeometryFilterNodeType */
/************************************************************************/
static int FLTIsGeometryFilterNodeType(int eType)
{
return (eType == FILTER_NODE_TYPE_GEOMETRY_POINT ||
eType == FILTER_NODE_TYPE_GEOMETRY_LINE ||
eType == FILTER_NODE_TYPE_GEOMETRY_POLYGON);
}
/************************************************************************/
/* FLTFreeFilterEncodingNode */
/* */
/* recursive freeing of Filer Encoding nodes. */
/************************************************************************/
void FLTFreeFilterEncodingNode(FilterEncodingNode *psFilterNode)
{
if (psFilterNode) {
if (psFilterNode->psLeftNode) {
FLTFreeFilterEncodingNode(psFilterNode->psLeftNode);
psFilterNode->psLeftNode = NULL;
}
if (psFilterNode->psRightNode) {
FLTFreeFilterEncodingNode(psFilterNode->psRightNode);
psFilterNode->psRightNode = NULL;
}
if (psFilterNode->pszSRS)
free( psFilterNode->pszSRS);
if( psFilterNode->pOther ) {
if (psFilterNode->pszValue != NULL &&
strcasecmp(psFilterNode->pszValue, "PropertyIsLike") == 0) {
FEPropertyIsLike* propIsLike = (FEPropertyIsLike *)psFilterNode->pOther;
if( propIsLike->pszWildCard )
free( propIsLike->pszWildCard );
if( propIsLike->pszSingleChar )
free( propIsLike->pszSingleChar );
if( propIsLike->pszEscapeChar )
free( propIsLike->pszEscapeChar );
} else if (FLTIsGeometryFilterNodeType(psFilterNode->eType)) {
msFreeShape((shapeObj *)(psFilterNode->pOther));
}
/* else */
/* TODO free pOther special fields */
free( psFilterNode->pOther );
}
/* Cannot free pszValue before, 'cause we are testing it above */
if( psFilterNode->pszValue )
free( psFilterNode->pszValue );
free(psFilterNode);
}
}
/************************************************************************/
/* FLTCreateFilterEncodingNode */
/* */
/* return a FilerEncoding node. */
/************************************************************************/
FilterEncodingNode *FLTCreateFilterEncodingNode(void)
{
FilterEncodingNode *psFilterNode = NULL;
psFilterNode =
(FilterEncodingNode *)malloc(sizeof (FilterEncodingNode));
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
psFilterNode->pszValue = NULL;
psFilterNode->pOther = NULL;
psFilterNode->pszSRS = NULL;
psFilterNode->psLeftNode = NULL;
psFilterNode->psRightNode = NULL;
return psFilterNode;
}
FilterEncodingNode *FLTCreateBinaryCompFilterEncodingNode(void)
{
FilterEncodingNode *psFilterNode = NULL;
psFilterNode = FLTCreateFilterEncodingNode();
/* used to store case sensitivity flag. Default is 0 meaning the
comparing is case sensititive */
psFilterNode->pOther = (int *)malloc(sizeof(int));
(*(int *)(psFilterNode->pOther)) = 0;
return psFilterNode;
}
/************************************************************************/
/* FLTFindGeometryNode */
/* */
/************************************************************************/
static CPLXMLNode* FLTFindGeometryNode(CPLXMLNode* psXMLNode,
int* pbPoint,
int* pbLine,
int* pbPolygon)
{
CPLXMLNode *psGMLElement = NULL;
psGMLElement = CPLGetXMLNode(psXMLNode, "Point");
if (!psGMLElement)
psGMLElement = CPLGetXMLNode(psXMLNode, "PointType");
if (psGMLElement)
*pbPoint =1;
else {
psGMLElement= CPLGetXMLNode(psXMLNode, "Polygon");
if (psGMLElement)
*pbPolygon = 1;
else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "MultiPolygon")))
*pbPolygon = 1;
else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "Surface")))
*pbPolygon = 1;
else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "MultiSurface")))
*pbPolygon = 1;
else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "Box")))
*pbPolygon = 1;
else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "LineString")))
*pbLine = 1;
else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "MultiLineString")))
*pbLine = 1;
else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "Curve")))
*pbLine = 1;
else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "MultiCurve")))
*pbLine = 1;
else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "MultiPoint")))
*pbPoint = 1;
}
return psGMLElement;
}
/************************************************************************/
/* FLTGetPropertyName */
/************************************************************************/
static const char* FLTGetPropertyName(CPLXMLNode* psXMLNode)
{
const char* pszPropertyName;
pszPropertyName = CPLGetXMLValue(psXMLNode, "PropertyName", NULL);
if( pszPropertyName == NULL ) /* FE 2.0 ? */
pszPropertyName = CPLGetXMLValue(psXMLNode, "ValueReference", NULL);
return pszPropertyName;
}
/************************************************************************/
/* FLTGetFirstChildNode */
/************************************************************************/
static CPLXMLNode* FLTGetFirstChildNode(CPLXMLNode* psXMLNode)
{
if( psXMLNode == NULL )
return NULL;
psXMLNode = psXMLNode->psChild;
while( psXMLNode != NULL )
{
if( psXMLNode->eType == CXT_Element )
return psXMLNode;
psXMLNode = psXMLNode->psNext;
}
return NULL;
}
/************************************************************************/
/* FLTGetNextSibblingNode */
/************************************************************************/
static CPLXMLNode* FLTGetNextSibblingNode(CPLXMLNode* psXMLNode)
{
if( psXMLNode == NULL )
return NULL;
psXMLNode = psXMLNode->psNext;
while( psXMLNode != NULL )
{
if( psXMLNode->eType == CXT_Element )
return psXMLNode;
psXMLNode = psXMLNode->psNext;
}
return NULL;
}
/************************************************************************/
/* FLTInsertElementInNode */
/* */
/* Utility function to parse an XML node and transfter the */
/* contennts into the Filer Encoding node structure. */
/************************************************************************/
void FLTInsertElementInNode(FilterEncodingNode *psFilterNode,
CPLXMLNode *psXMLNode)
{
int nStrLength = 0;
char *pszTmp = NULL;
FilterEncodingNode *psCurFilNode= NULL;
CPLXMLNode *psCurXMLNode = NULL;
CPLXMLNode *psTmpNode = NULL;
CPLXMLNode *psFeatureIdNode = NULL;
const char *pszFeatureId=NULL;
char *pszFeatureIdList=NULL;
if (psFilterNode && psXMLNode && psXMLNode->pszValue) {
psFilterNode->pszValue = msStrdup(psXMLNode->pszValue);
psFilterNode->psLeftNode = NULL;
psFilterNode->psRightNode = NULL;
/* -------------------------------------------------------------------- */
/* Logical filter. AND, OR and NOT are supported. Example of */
/* filer using logical filters : */
/* <Filter> */
/* <And> */
/* <PropertyIsGreaterThan> */
/* <PropertyName>Person/Age</PropertyName> */
/* <Literal>50</Literal> */
/* </PropertyIsGreaterThan> */
/* <PropertyIsEqualTo> */
/* <PropertyName>Person/Address/City</PropertyName> */
/* <Literal>Toronto</Literal> */
/* </PropertyIsEqualTo> */
/* </And> */
/* </Filter> */
/* -------------------------------------------------------------------- */
if (FLTIsLogicalFilterType(psXMLNode->pszValue)) {
psFilterNode->eType = FILTER_NODE_TYPE_LOGICAL;
if (strcasecmp(psFilterNode->pszValue, "AND") == 0 ||
strcasecmp(psFilterNode->pszValue, "OR") == 0) {
CPLXMLNode* psFirstNode = FLTGetFirstChildNode(psXMLNode);
CPLXMLNode* psSecondNode = FLTGetNextSibblingNode(psFirstNode);
if (psFirstNode && psSecondNode) {
/*2 operators */
CPLXMLNode* psNextNode = FLTGetNextSibblingNode(psSecondNode);
if (psNextNode == NULL) {
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
FLTInsertElementInNode(psFilterNode->psLeftNode, psFirstNode);
psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
FLTInsertElementInNode(psFilterNode->psRightNode, psSecondNode);
} else {
psCurXMLNode = psFirstNode;
psCurFilNode = psFilterNode;
while(psCurXMLNode) {
psNextNode = FLTGetNextSibblingNode(psCurXMLNode);
if (FLTGetNextSibblingNode(psNextNode)) {
psCurFilNode->psLeftNode = FLTCreateFilterEncodingNode();
FLTInsertElementInNode(psCurFilNode->psLeftNode, psCurXMLNode);
psCurFilNode->psRightNode = FLTCreateFilterEncodingNode();
psCurFilNode->psRightNode->eType = FILTER_NODE_TYPE_LOGICAL;
psCurFilNode->psRightNode->pszValue = msStrdup(psFilterNode->pszValue);
psCurFilNode = psCurFilNode->psRightNode;
psCurXMLNode = psNextNode;
} else { /*last 2 operators*/
psCurFilNode->psLeftNode = FLTCreateFilterEncodingNode();
FLTInsertElementInNode(psCurFilNode->psLeftNode, psCurXMLNode);
psCurFilNode->psRightNode = FLTCreateFilterEncodingNode();
FLTInsertElementInNode(psCurFilNode->psRightNode, psNextNode);
break;
}
}
}
}
else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
} else if (strcasecmp(psFilterNode->pszValue, "NOT") == 0) {
CPLXMLNode* psFirstNode = FLTGetFirstChildNode(psXMLNode);
if (psFirstNode) {
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
FLTInsertElementInNode(psFilterNode->psLeftNode,
psFirstNode);
}
else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
} else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}/* end if is logical */
/* -------------------------------------------------------------------- */
/* Spatial Filter. */
/* BBOX : */
/* <Filter> */
/* <BBOX> */
/* <PropertyName>Geometry</PropertyName> */
/* <gml:Box srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">*/
/* <gml:coordinates>13.0983,31.5899 35.5472,42.8143</gml:coordinates>*/
/* </gml:Box> */
/* </BBOX> */
/* </Filter> */
/* */
/* DWithin */
/* */
/* <xsd:element name="DWithin" */
/* type="ogc:DistanceBufferType" */
/* substitutionGroup="ogc:spatialOps"/> */
/* */
/* <xsd:complexType name="DistanceBufferType"> */
/* <xsd:complexContent> */
/* <xsd:extension base="ogc:SpatialOpsType"> */
/* <xsd:sequence> */
/* <xsd:element ref="ogc:PropertyName"/> */
/* <xsd:element ref="gml:_Geometry"/> */
/* <xsd:element name="Distance" type="ogc:DistanceType"/>*/
/* </xsd:sequence> */
/* </xsd:extension> */
/* </xsd:complexContent> */
/* </xsd:complexType> */
/* */
/* */
/* <Filter> */
/* <DWithin> */
/* <PropertyName>Geometry</PropertyName> */
/* <gml:Point> */
/* <gml:coordinates>13.0983,31.5899</gml:coordinates> */
/* </gml:Point> */
/* <Distance units="url#m">10</Distance> */
/* </DWithin> */
/* </Filter> */
/* */
/* Intersect */
/* */
/* type="ogc:BinarySpatialOpType" substitutionGroup="ogc:spatialOps"/>*/
/* <xsd:element name="Intersects" */
/* type="ogc:BinarySpatialOpType" */
/* substitutionGroup="ogc:spatialOps"/> */
/* */
/* <xsd:complexType name="BinarySpatialOpType"> */
/* <xsd:complexContent> */
/* <xsd:extension base="ogc:SpatialOpsType"> */
/* <xsd:sequence> */
/* <xsd:element ref="ogc:PropertyName"/> */
/* <xsd:choice> */
/* <xsd:element ref="gml:_Geometry"/> */
/* <xsd:element ref="gml:Box"/> */
/* </xsd:sequence> */
/* </xsd:extension> */
/* </xsd:complexContent> */
/* </xsd:complexType> */
/* -------------------------------------------------------------------- */
else if (FLTIsSpatialFilterType(psXMLNode->pszValue)) {
psFilterNode->eType = FILTER_NODE_TYPE_SPATIAL;
if (strcasecmp(psXMLNode->pszValue, "BBOX") == 0) {
char *pszSRS = NULL;
const char* pszPropertyName = NULL;
CPLXMLNode *psBox = NULL, *psEnvelope=NULL;
rectObj sBox;
int bCoordinatesValid = 0;
pszPropertyName = FLTGetPropertyName(psXMLNode);
psBox = CPLGetXMLNode(psXMLNode, "Box");
if (!psBox)
psBox = CPLGetXMLNode(psXMLNode, "BoxType");
/*FE 1.0 used box FE1.1 uses envelop*/
if (psBox)
bCoordinatesValid = FLTParseGMLBox(psBox, &sBox, &pszSRS);
else if ((psEnvelope = CPLGetXMLNode(psXMLNode, "Envelope")))
bCoordinatesValid = FLTParseGMLEnvelope(psEnvelope, &sBox, &pszSRS);
if (bCoordinatesValid) {
/*set the srs if available*/
if (pszSRS)
psFilterNode->pszSRS = pszSRS;
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
/* PropertyName is optional since FE 1.1.0, in which case */
/* the BBOX must apply to all geometry fields. As we support */
/* currently only one geometry field, this doesn't make much */
/* difference to further processing. */
if( pszPropertyName != NULL ) {
psFilterNode->psLeftNode->pszValue = msStrdup(pszPropertyName);
}
/* coordinates */
psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_BBOX;
psFilterNode->psRightNode->pOther =
(rectObj *)msSmallMalloc(sizeof(rectObj));
((rectObj *)psFilterNode->psRightNode->pOther)->minx = sBox.minx;
((rectObj *)psFilterNode->psRightNode->pOther)->miny = sBox.miny;
((rectObj *)psFilterNode->psRightNode->pOther)->maxx = sBox.maxx;
((rectObj *)psFilterNode->psRightNode->pOther)->maxy = sBox.maxy;
} else {
msFree(pszSRS);
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
} else if (strcasecmp(psXMLNode->pszValue, "DWithin") == 0 ||
strcasecmp(psXMLNode->pszValue, "Beyond") == 0)
{
shapeObj *psShape = NULL;
int bPoint = 0, bLine = 0, bPolygon = 0;
const char *pszUnits = NULL;
const char* pszDistance = NULL;
const char* pszPropertyName;
char *pszSRS = NULL;
CPLXMLNode *psGMLElement = NULL, *psDistance=NULL;
pszPropertyName = FLTGetPropertyName(psXMLNode);
psGMLElement = FLTFindGeometryNode(psXMLNode, &bPoint, &bLine, &bPolygon);
psDistance = CPLGetXMLNode(psXMLNode, "Distance");
if( psDistance != NULL )
pszDistance = CPLGetXMLValue(psDistance, NULL, NULL );
if (pszPropertyName != NULL && psGMLElement && psDistance != NULL ) {
pszUnits = CPLGetXMLValue(psDistance, "units", NULL);
if( pszUnits == NULL ) /* FE 2.0 */
pszUnits = CPLGetXMLValue(psDistance, "uom", NULL);
psShape = (shapeObj *)msSmallMalloc(sizeof(shapeObj));
msInitShape(psShape);
if (FLTShapeFromGMLTree(psGMLElement, psShape, &pszSRS))
{
/*set the srs if available*/
if (pszSRS)
psFilterNode->pszSRS = pszSRS;
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
psFilterNode->psLeftNode->pszValue = msStrdup(pszPropertyName);
psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
if (bPoint)
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_POINT;
else if (bLine)
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_LINE;
else if (bPolygon)
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_POLYGON;
psFilterNode->psRightNode->pOther = (shapeObj *)psShape;
/*the value will be distance;units*/
psFilterNode->psRightNode->pszValue = msStrdup(pszDistance);
if (pszUnits) {
psFilterNode->psRightNode->pszValue= msStringConcatenate(psFilterNode->psRightNode->pszValue, ";");
psFilterNode->psRightNode->pszValue= msStringConcatenate(psFilterNode->psRightNode->pszValue, pszUnits);
}
}
else
{
free(psShape);
msFree(pszSRS);
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
} else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
} else if (strcasecmp(psXMLNode->pszValue, "Intersect") == 0 ||
strcasecmp(psXMLNode->pszValue, "Intersects") == 0 ||
strcasecmp(psXMLNode->pszValue, "Equals") == 0 ||
strcasecmp(psXMLNode->pszValue, "Disjoint") == 0 ||
strcasecmp(psXMLNode->pszValue, "Touches") == 0 ||
strcasecmp(psXMLNode->pszValue, "Crosses") == 0 ||
strcasecmp(psXMLNode->pszValue, "Within") == 0 ||
strcasecmp(psXMLNode->pszValue, "Contains") == 0 ||
strcasecmp(psXMLNode->pszValue, "Overlaps") == 0) {
shapeObj *psShape = NULL;
int bLine = 0, bPolygon = 0, bPoint=0;
char *pszSRS = NULL;
const char* pszPropertyName;
CPLXMLNode *psGMLElement = NULL;
pszPropertyName = FLTGetPropertyName(psXMLNode);
psGMLElement = FLTFindGeometryNode(psXMLNode, &bPoint, &bLine, &bPolygon);
if (pszPropertyName != NULL && psGMLElement) {
psShape = (shapeObj *)msSmallMalloc(sizeof(shapeObj));
msInitShape(psShape);
if (FLTShapeFromGMLTree(psGMLElement, psShape, &pszSRS))
{
/*set the srs if available*/
if (pszSRS)
psFilterNode->pszSRS = pszSRS;
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
psFilterNode->psLeftNode->pszValue = msStrdup(pszPropertyName);
psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
if (bPoint)
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_POINT;
else if (bLine)
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_LINE;
else if (bPolygon)
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_POLYGON;
psFilterNode->psRightNode->pOther = (shapeObj *)psShape;
}
else
{
free(psShape);
msFree(pszSRS);
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
} else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
}/* end of is spatial */
/* -------------------------------------------------------------------- */
/* Comparison Filter */
/* -------------------------------------------------------------------- */
else if (FLTIsComparisonFilterType(psXMLNode->pszValue)) {
psFilterNode->eType = FILTER_NODE_TYPE_COMPARISON;
/* -------------------------------------------------------------------- */
/* binary comaparison types. Example : */
/* */
/* <Filter> */
/* <PropertyIsEqualTo> */
/* <PropertyName>SomeProperty</PropertyName> */
/* <Literal>100</Literal> */
/* </PropertyIsEqualTo> */
/* </Filter> */
/* -------------------------------------------------------------------- */
if (FLTIsBinaryComparisonFilterType(psXMLNode->pszValue)) {
const char* pszPropertyName = FLTGetPropertyName(psXMLNode);
if (pszPropertyName != NULL ) {
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
psFilterNode->psLeftNode->pszValue = msStrdup(pszPropertyName);
psTmpNode = CPLSearchXMLNode(psXMLNode, "Literal");
if (psTmpNode) {
const char* pszLiteral = CPLGetXMLValue(psTmpNode, NULL, NULL);
psFilterNode->psRightNode = FLTCreateBinaryCompFilterEncodingNode();
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_LITERAL;
if (pszLiteral != NULL) {
const char* pszMatchCase;
psFilterNode->psRightNode->pszValue = msStrdup(pszLiteral);
pszMatchCase = CPLGetXMLValue(psXMLNode, "matchCase", NULL);
/*check if the matchCase attribute is set*/
if( pszMatchCase != NULL && strcasecmp( pszMatchCase, "false") == 0) {
(*(int *)psFilterNode->psRightNode->pOther) = 1;
}
}
/* special case where the user puts an empty value */
/* for the Literal so it can end up as an empty */
/* string query in the expression */
else
psFilterNode->psRightNode->pszValue = NULL;
}
}
if (psFilterNode->psLeftNode == NULL || psFilterNode->psRightNode == NULL)
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
/* -------------------------------------------------------------------- */
/* PropertyIsBetween filter : extract property name and boudary */
/* values. The boundary values are stored in the right */
/* node. The values are separated by a semi-column (;) */
/* Eg of Filter : */
/* <PropertyIsBetween> */
/* <PropertyName>DEPTH</PropertyName> */
/* <LowerBoundary><Literal>400</Literal></LowerBoundary> */
/* <UpperBoundary><Literal>800</Literal></UpperBoundary> */
/* </PropertyIsBetween> */
/* */
/* Or */
/* <PropertyIsBetween> */
/* <PropertyName>DEPTH</PropertyName> */
/* <LowerBoundary>400</LowerBoundary> */
/* <UpperBoundary>800</UpperBoundary> */
/* </PropertyIsBetween> */
/* -------------------------------------------------------------------- */
else if (strcasecmp(psXMLNode->pszValue, "PropertyIsBetween") == 0) {
const char* pszPropertyName = FLTGetPropertyName(psXMLNode);
CPLXMLNode* psLowerBoundary = CPLGetXMLNode(psXMLNode, "LowerBoundary");
CPLXMLNode* psUpperBoundary = CPLGetXMLNode(psXMLNode, "UpperBoundary");
const char* pszLowerNode = NULL;
const char* pszUpperNode = NULL;
if( psLowerBoundary != NULL )
{
/* check if the <Literal> is there */
if (CPLGetXMLNode(psLowerBoundary, "Literal") != NULL)
pszLowerNode = CPLGetXMLValue(psLowerBoundary, "Literal", NULL);
else
pszLowerNode = CPLGetXMLValue(psLowerBoundary, NULL, NULL);
}
if( psUpperBoundary != NULL )
{
if (CPLGetXMLNode(psUpperBoundary, "Literal") != NULL)
pszUpperNode = CPLGetXMLValue(psUpperBoundary, "Literal", NULL);
else
pszUpperNode = CPLGetXMLValue(psUpperBoundary, NULL, NULL);
}
if (pszPropertyName != NULL && pszLowerNode != NULL && pszUpperNode != NULL) {
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
psFilterNode->psLeftNode->pszValue = msStrdup(pszPropertyName);
psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_BOUNDARY;
/* adding a ; between bounary values */
nStrLength = strlen(pszLowerNode) + strlen(pszUpperNode) + 2;
psFilterNode->psRightNode->pszValue =
(char *)malloc(sizeof(char)*(nStrLength));
strcpy( psFilterNode->psRightNode->pszValue, pszLowerNode);
strlcat(psFilterNode->psRightNode->pszValue, ";", nStrLength);
strlcat(psFilterNode->psRightNode->pszValue, pszUpperNode, nStrLength);
} else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}/* end of PropertyIsBetween */
/* -------------------------------------------------------------------- */
/* PropertyIsLike */
/* */
/* <Filter> */
/* <PropertyIsLike wildCard="*" singleChar="#" escape="!"> */
/* <PropertyName>LAST_NAME</PropertyName> */
/* <Literal>JOHN*</Literal> */
/* </PropertyIsLike> */
/* </Filter> */
/* -------------------------------------------------------------------- */
else if (strcasecmp(psXMLNode->pszValue, "PropertyIsLike") == 0) {
const char* pszPropertyName = FLTGetPropertyName(psXMLNode);
const char* pszLiteral = CPLGetXMLValue(psXMLNode, "Literal", NULL);
const char* pszWildCard = CPLGetXMLValue(psXMLNode, "wildCard", NULL);
const char* pszSingleChar = CPLGetXMLValue(psXMLNode, "singleChar", NULL);
const char* pszEscapeChar = CPLGetXMLValue(psXMLNode, "escape", NULL);
if( pszEscapeChar == NULL )
pszEscapeChar = CPLGetXMLValue(psXMLNode, "escapeChar", NULL);
if (pszPropertyName != NULL && pszLiteral != NULL &&
pszWildCard != NULL && pszSingleChar != NULL && pszEscapeChar != NULL)
{
FEPropertyIsLike* propIsLike;
propIsLike = (FEPropertyIsLike *)malloc(sizeof(FEPropertyIsLike));
psFilterNode->pOther = propIsLike;
propIsLike->bCaseInsensitive = 0;
propIsLike->pszWildCard = msStrdup(pszWildCard);
propIsLike->pszSingleChar = msStrdup(pszSingleChar);
propIsLike->pszEscapeChar = msStrdup(pszEscapeChar);
pszTmp = (char *)CPLGetXMLValue(psXMLNode, "matchCase", NULL);
if (pszTmp && strcasecmp(pszTmp, "false") == 0) {
propIsLike->bCaseInsensitive =1;
}
/* -------------------------------------------------------------------- */
/* Create left and right node for the attribute and the value. */
/* -------------------------------------------------------------------- */
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
psFilterNode->psLeftNode->pszValue = msStrdup(pszPropertyName);
psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
psFilterNode->psRightNode->pszValue = msStrdup(pszLiteral);
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_LITERAL;
} else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
else if (strcasecmp(psXMLNode->pszValue, "PropertyIsNull") == 0) {
const char* pszPropertyName = FLTGetPropertyName(psXMLNode);
if( pszPropertyName != NULL )
{
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
psFilterNode->psLeftNode->pszValue = msStrdup(pszPropertyName);
psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
} else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
else if (strcasecmp(psXMLNode->pszValue, "PropertyIsNil") == 0) {
const char* pszPropertyName = FLTGetPropertyName(psXMLNode);
if( pszPropertyName != NULL )
{
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
psFilterNode->psLeftNode->pszValue = msStrdup(pszPropertyName);
psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
} else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
}
/* -------------------------------------------------------------------- */
/* FeatureId Filter */
/* */
/* <ogc:Filter> */
/* <ogc:FeatureId fid="INWATERA_1M.1013"/> */
/* <ogc:FeatureId fid="INWATERA_1M.10"/> */
/* <ogc:FeatureId fid="INWATERA_1M.13"/> */
/* <ogc:FeatureId fid="INWATERA_1M.140"/> */
/* <ogc:FeatureId fid="INWATERA_1M.5001"/> */
/* <ogc:FeatureId fid="INWATERA_1M.2001"/> */
/* </ogc:Filter> */
/* */
/* */
/* Note that for FES1.1.0 the featureid has been depricated in */
/* favor of GmlObjectId */
/* <GmlObjectId gml:id="TREESA_1M.1234"/> */
/* */
/* And in FES 2.0, in favor of <fes:ResourceId rid="foo.1234"/> */
/* -------------------------------------------------------------------- */
else if (FLTIsFeatureIdFilterType(psXMLNode->pszValue)) {
psFilterNode->eType = FILTER_NODE_TYPE_FEATUREID;
pszFeatureId = CPLGetXMLValue(psXMLNode, "fid", NULL);
/*for FE 1.1.0 GmlObjectId */
if (pszFeatureId == NULL)
pszFeatureId = CPLGetXMLValue(psXMLNode, "id", NULL);
/*for FE 2.0 ResourceId */
if (pszFeatureId == NULL)
pszFeatureId = CPLGetXMLValue(psXMLNode, "rid", NULL);
pszFeatureIdList = NULL;
psFeatureIdNode = psXMLNode;
while (psFeatureIdNode) {
pszFeatureId = CPLGetXMLValue(psFeatureIdNode, "fid", NULL);
if (!pszFeatureId)
pszFeatureId = CPLGetXMLValue(psFeatureIdNode, "id", NULL);
if (!pszFeatureId)
pszFeatureId = CPLGetXMLValue(psFeatureIdNode, "rid", NULL);
if (pszFeatureId) {
if (pszFeatureIdList)
pszFeatureIdList = msStringConcatenate(pszFeatureIdList, ",");
pszFeatureIdList = msStringConcatenate(pszFeatureIdList, pszFeatureId);
}
psFeatureIdNode = psFeatureIdNode->psNext;
}
if (pszFeatureIdList) {
msFree(psFilterNode->pszValue);
psFilterNode->pszValue = msStrdup(pszFeatureIdList);
msFree(pszFeatureIdList);
} else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
/* -------------------------------------------------------------------- */
/* Temporal Filter. */
/*
<fes:During>
<fes:ValueReference>gml:TimeInstant</fes:ValueReference>
<gml:TimePeriod gml:id="TP1">
<gml:begin>
<gml:TimeInstant gml:id="TI1">
<gml:timePosition>2005-05-17T00:00:00Z</gml:timePosition>
</gml:TimeInstant>
</gml:begin>
<gml:end>
<gml:TimeInstant gml:id="TI2">
<gml:timePosition>2005-05-23T00:00:00Z</gml:timePosition>
</gml:TimeInstant>
</gml:end>
</gml:TimePeriod>
</fes:During>
*/
/* -------------------------------------------------------------------- */
else if (FLTIsTemporalFilterType(psXMLNode->pszValue)) {
psFilterNode->eType = FILTER_NODE_TYPE_TEMPORAL;
if (strcasecmp(psXMLNode->pszValue, "During") == 0) {
const char* pszPropertyName = NULL;
const char* pszBeginTime;
const char* pszEndTime;
pszPropertyName = FLTGetPropertyName(psXMLNode);
pszBeginTime = CPLGetXMLValue(psXMLNode, "TimePeriod.begin.TimeInstant.timePosition", NULL);
if( pszBeginTime == NULL )
pszBeginTime = CPLGetXMLValue(psXMLNode, "TimePeriod.beginPosition", NULL);
pszEndTime = CPLGetXMLValue(psXMLNode, "TimePeriod.end.TimeInstant.timePosition", NULL);
if( pszEndTime == NULL )
pszEndTime = CPLGetXMLValue(psXMLNode, "TimePeriod.endPosition", NULL);
if (pszPropertyName && pszBeginTime && pszEndTime &&
strchr(pszBeginTime, '\'') == NULL && strchr(pszBeginTime, '\\') == NULL &&
strchr(pszEndTime, '\'') == NULL && strchr(pszEndTime, '\\') == NULL &&
msTimeGetResolution(pszBeginTime) >= 0 &&
msTimeGetResolution(pszEndTime) >= 0) {
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
psFilterNode->psLeftNode->pszValue = msStrdup(pszPropertyName);
psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_TIME_PERIOD;
psFilterNode->psRightNode->pszValue = msSmallMalloc( strlen(pszBeginTime) + strlen(pszEndTime) + 2 );
sprintf(psFilterNode->psRightNode->pszValue, "%s/%s", pszBeginTime, pszEndTime);
}
else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
} else {
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
}/* end of is temporal */
}
}
/************************************************************************/
/* int FLTIsLogicalFilterType((char *pszValue) */
/* */
/* return TRUE if the value of the node is of logical filter */
/* encoding type. */
/************************************************************************/
int FLTIsLogicalFilterType(const char *pszValue)
{
if (pszValue) {
if (strcasecmp(pszValue, "AND") == 0 ||
strcasecmp(pszValue, "OR") == 0 ||
strcasecmp(pszValue, "NOT") == 0)
return MS_TRUE;
}
return MS_FALSE;
}
/************************************************************************/
/* int FLTIsBinaryComparisonFilterType(char *pszValue) */
/* */
/* Binary comparison filter type. */
/************************************************************************/
int FLTIsBinaryComparisonFilterType(const char *pszValue)
{
if (pszValue) {
if (strcasecmp(pszValue, "PropertyIsEqualTo") == 0 ||
strcasecmp(pszValue, "PropertyIsNotEqualTo") == 0 ||
strcasecmp(pszValue, "PropertyIsLessThan") == 0 ||
strcasecmp(pszValue, "PropertyIsGreaterThan") == 0 ||
strcasecmp(pszValue, "PropertyIsLessThanOrEqualTo") == 0 ||
strcasecmp(pszValue, "PropertyIsGreaterThanOrEqualTo") == 0)
return MS_TRUE;
}
return MS_FALSE;
}
/************************************************************************/
/* int FLTIsComparisonFilterType(char *pszValue) */
/* */
/* return TRUE if the value of the node is of comparison filter */
/* encoding type. */
/************************************************************************/
int FLTIsComparisonFilterType(const char *pszValue)
{
if (pszValue) {
if (FLTIsBinaryComparisonFilterType(pszValue) ||
strcasecmp(pszValue, "PropertyIsLike") == 0 ||
strcasecmp(pszValue, "PropertyIsBetween") == 0 ||
strcasecmp(pszValue, "PropertyIsNull") == 0 ||
strcasecmp(pszValue, "PropertyIsNil") == 0)
return MS_TRUE;
}
return MS_FALSE;
}
/************************************************************************/
/* int FLTIsFeatureIdFilterType(char *pszValue) */
/* */
/* return TRUE if the value of the node is of featureid filter */
/* encoding type. */
/************************************************************************/
int FLTIsFeatureIdFilterType(const char *pszValue)
{
if (pszValue && (strcasecmp(pszValue, "FeatureId") == 0 ||
strcasecmp(pszValue, "GmlObjectId") == 0 ||
strcasecmp(pszValue, "ResourceId") == 0))
return MS_TRUE;
return MS_FALSE;
}
/************************************************************************/
/* int FLTIsSpatialFilterType(char *pszValue) */
/* */
/* return TRUE if the value of the node is of spatial filter */
/* encoding type. */
/************************************************************************/
int FLTIsSpatialFilterType(const char *pszValue)
{
if (pszValue) {
if ( strcasecmp(pszValue, "BBOX") == 0 ||
strcasecmp(pszValue, "DWithin") == 0 ||
strcasecmp(pszValue, "Intersect") == 0 ||
strcasecmp(pszValue, "Intersects") == 0 ||
strcasecmp(pszValue, "Equals") == 0 ||
strcasecmp(pszValue, "Disjoint") == 0 ||
strcasecmp(pszValue, "Touches") == 0 ||
strcasecmp(pszValue, "Crosses") == 0 ||
strcasecmp(pszValue, "Within") == 0 ||
strcasecmp(pszValue, "Contains") == 0 ||
strcasecmp(pszValue, "Overlaps") == 0 ||
strcasecmp(pszValue, "Beyond") == 0)
return MS_TRUE;
}
return MS_FALSE;
}
/************************************************************************/
/* int FLTIsTemportalFilterType(char *pszValue) */
/* */
/* return TRUE if the value of the node is of temporal filter */
/* encoding type. */
/************************************************************************/
int FLTIsTemporalFilterType(const char *pszValue)
{
if (pszValue) {
if ( strcasecmp(pszValue, "During") == 0 )
return MS_TRUE;
}
return MS_FALSE;
}
/************************************************************************/
/* int FLTIsSupportedFilterType(CPLXMLNode *psXMLNode) */
/* */
/* Verfify if the value of the node is one of the supported */
/* filter type. */
/************************************************************************/
int FLTIsSupportedFilterType(CPLXMLNode *psXMLNode)
{
if (psXMLNode) {
if (FLTIsLogicalFilterType(psXMLNode->pszValue) ||
FLTIsSpatialFilterType(psXMLNode->pszValue) ||
FLTIsComparisonFilterType(psXMLNode->pszValue) ||
FLTIsFeatureIdFilterType(psXMLNode->pszValue) ||
FLTIsTemporalFilterType(psXMLNode->pszValue))
return MS_TRUE;
}
return MS_FALSE;
}
/************************************************************************/
/* FLTNumberOfFilterType */
/* */
/* Loop trhough the nodes and return the number of nodes of */
/* specified value. */
/************************************************************************/
int FLTNumberOfFilterType(FilterEncodingNode *psFilterNode, const char *szType)
{
int nCount = 0;
int nLeftNode=0 , nRightNode = 0;
if (!psFilterNode || !szType || !psFilterNode->pszValue)
return 0;
if (strcasecmp(psFilterNode->pszValue, (char*)szType) == 0)
nCount++;
if (psFilterNode->psLeftNode)
nLeftNode = FLTNumberOfFilterType(psFilterNode->psLeftNode, szType);
nCount += nLeftNode;
if (psFilterNode->psRightNode)
nRightNode = FLTNumberOfFilterType(psFilterNode->psRightNode, szType);
nCount += nRightNode;
return nCount;
}
/************************************************************************/
/* FLTValidForBBoxFilter */
/* */
/* Validate if there is only one BBOX filter node. Here is waht */
/* is supported (is valid) : */
/* - one node which is a BBOX */
/* - a logical AND with a valid BBOX */
/* */
/* eg 1: <Filter> */
/* <BBOX> */
/* <PropertyName>Geometry</PropertyName> */
/* <gml:Box srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">*/
/* <gml:coordinates>13.0983,31.5899 35.5472,42.8143</gml:coordinates>*/
/* </gml:Box> */
/* </BBOX> */
/* </Filter> */
/* */
/* eg 2 :<Filter> */
/* <AND> */
/* <BBOX> */
/* <PropertyName>Geometry</PropertyName> */
/* <gml:Box srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">*/
/* <gml:coordinates>13.0983,31.5899 35.5472,42.8143</gml:coordinates>*/
/* </gml:Box> */
/* </BBOX> */
/* <PropertyIsEqualTo> */
/* <PropertyName>SomeProperty</PropertyName> */
/* <Literal>100</Literal> */
/* </PropertyIsEqualTo> */
/* </AND> */
/* </Filter> */
/* */
/************************************************************************/
int FLTValidForBBoxFilter(FilterEncodingNode *psFilterNode)
{
int nCount = 0;
if (!psFilterNode || !psFilterNode->pszValue)
return 1;
nCount = FLTNumberOfFilterType(psFilterNode, "BBOX");
if (nCount > 1)
return 0;
else if (nCount == 0)
return 1;
/* nCount ==1 */
if (strcasecmp(psFilterNode->pszValue, "BBOX") == 0)
return 1;
if (strcasecmp(psFilterNode->pszValue, "AND") == 0) {
return FLTValidForBBoxFilter(psFilterNode->psLeftNode) &&
FLTValidForBBoxFilter(psFilterNode->psRightNode);
}
return 0;
}
#if 0
static int FLTHasUniqueTopLevelDuringFilter(FilterEncodingNode *psFilterNode)
{
int nCount = 0;
if (!psFilterNode || !psFilterNode->pszValue)
return 1;
nCount = FLTNumberOfFilterType(psFilterNode, "During");
if (nCount > 1)
return 0;
else if (nCount == 0)
return 1;
/* nCount ==1 */
if (strcasecmp(psFilterNode->pszValue, "During") == 0)
return 1;
if (strcasecmp(psFilterNode->pszValue, "AND") == 0) {
return FLTHasUniqueTopLevelDuringFilter(psFilterNode->psLeftNode) &&
FLTHasUniqueTopLevelDuringFilter(psFilterNode->psRightNode);
}
return 0;
}
#endif
int FLTIsLineFilter(FilterEncodingNode *psFilterNode)
{
if (!psFilterNode || !psFilterNode->pszValue)
return 0;
if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL &&
psFilterNode->psRightNode &&
psFilterNode->psRightNode->eType == FILTER_NODE_TYPE_GEOMETRY_LINE)
return 1;
return 0;
}
int FLTIsPolygonFilter(FilterEncodingNode *psFilterNode)
{
if (!psFilterNode || !psFilterNode->pszValue)
return 0;
if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL &&
psFilterNode->psRightNode &&
psFilterNode->psRightNode->eType == FILTER_NODE_TYPE_GEOMETRY_POLYGON)
return 1;
return 0;
}
int FLTIsPointFilter(FilterEncodingNode *psFilterNode)
{
if (!psFilterNode || !psFilterNode->pszValue)
return 0;
if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL &&
psFilterNode->psRightNode &&
psFilterNode->psRightNode->eType == FILTER_NODE_TYPE_GEOMETRY_POINT)
return 1;
return 0;
}
int FLTIsBBoxFilter(FilterEncodingNode *psFilterNode)
{
if (!psFilterNode || !psFilterNode->pszValue)
return 0;
if (strcasecmp(psFilterNode->pszValue, "BBOX") == 0)
return 1;
return 0;
}
shapeObj *FLTGetShape(FilterEncodingNode *psFilterNode, double *pdfDistance,
int *pnUnit)
{
char **tokens = NULL;
int nTokens = 0;
FilterEncodingNode *psNode = psFilterNode;
char *szUnitStr = NULL;
char *szUnit = NULL;
if (psNode) {
if (psNode->eType == FILTER_NODE_TYPE_SPATIAL && psNode->psRightNode)
psNode = psNode->psRightNode;
if (FLTIsGeometryFilterNodeType(psNode->eType)) {
if (psNode->pszValue && pdfDistance) {
/*
sytnax expected is "distance;unit" or just "distance"
if unit is there syntax is "URI#unit" (eg http://..../#m)
or just "unit"
*/
tokens = msStringSplit(psNode->pszValue,';', &nTokens);
if (tokens && nTokens >= 1) {
*pdfDistance = atof(tokens[0]);
if (nTokens == 2 && pnUnit) {
szUnitStr = msStrdup(tokens[1]);
msFreeCharArray(tokens, nTokens);
nTokens = 0;
tokens = msStringSplit(szUnitStr,'#', &nTokens);
msFree(szUnitStr);
if (tokens && nTokens >= 1) {
if (nTokens ==1)
szUnit = tokens[0];
else
szUnit = tokens[1];
if (strcasecmp(szUnit,"m") == 0 ||
strcasecmp(szUnit,"meters") == 0 )
*pnUnit = MS_METERS;
else if (strcasecmp(szUnit,"km") == 0 ||
strcasecmp(szUnit,"kilometers") == 0)
*pnUnit = MS_KILOMETERS;
else if (strcasecmp(szUnit,"NM") == 0 ||
strcasecmp(szUnit,"nauticalmiles") == 0)
*pnUnit = MS_NAUTICALMILES;
else if (strcasecmp(szUnit,"mi") == 0 ||
strcasecmp(szUnit,"miles") == 0)
*pnUnit = MS_MILES;
else if (strcasecmp(szUnit,"in") == 0 ||
strcasecmp(szUnit,"inches") == 0)
*pnUnit = MS_INCHES;
else if (strcasecmp(szUnit,"ft") == 0 ||
strcasecmp(szUnit,"feet") == 0)
*pnUnit = MS_FEET;
else if (strcasecmp(szUnit,"deg") == 0 ||
strcasecmp(szUnit,"dd") == 0)
*pnUnit = MS_DD;
else if (strcasecmp(szUnit,"px") == 0)
*pnUnit = MS_PIXELS;
}
}
}
msFreeCharArray(tokens, nTokens);
}
return (shapeObj *)psNode->pOther;
}
}
return NULL;
}
/************************************************************************/
/* FLTGetBBOX */
/* */
/* Loop through the nodes are return the coordinates of the */
/* first bbox node found. The retrun value is the epsg code of */
/* the bbox. */
/************************************************************************/
const char *FLTGetBBOX(FilterEncodingNode *psFilterNode, rectObj *psRect)
{
const char *pszReturn = NULL;
if (!psFilterNode || !psRect)
return NULL;
if (psFilterNode->pszValue && strcasecmp(psFilterNode->pszValue, "BBOX") == 0) {
if (psFilterNode->psRightNode && psFilterNode->psRightNode->pOther) {
rectObj* pRect= (rectObj *)psFilterNode->psRightNode->pOther;
psRect->minx = pRect->minx;
psRect->miny = pRect->miny;
psRect->maxx = pRect->maxx;
psRect->maxy = pRect->maxy;
return psFilterNode->pszSRS;
}
} else {
pszReturn = FLTGetBBOX(psFilterNode->psLeftNode, psRect);
if (pszReturn)
return pszReturn;
else
return FLTGetBBOX(psFilterNode->psRightNode, psRect);
}
return pszReturn;
}
const char* FLTGetDuring(FilterEncodingNode *psFilterNode, const char** ppszTimeField)
{
const char *pszReturn = NULL;
if (!psFilterNode || !ppszTimeField)
return NULL;
if (psFilterNode->pszValue && strcasecmp(psFilterNode->pszValue, "During") == 0) {
*ppszTimeField = psFilterNode->psLeftNode->pszValue;
return psFilterNode->psRightNode->pszValue;
} else {
pszReturn = FLTGetDuring(psFilterNode->psLeftNode, ppszTimeField);
if (pszReturn)
return pszReturn;
else
return FLTGetDuring(psFilterNode->psRightNode, ppszTimeField);
}
return pszReturn;
}
/************************************************************************/
/* GetMapserverExpression */
/* */
/* Return a mapserver expression base on the Filer encoding nodes. */
/************************************************************************/
char *FLTGetMapserverExpression(FilterEncodingNode *psFilterNode, layerObj *lp)
{
char *pszExpression = NULL;
const char *pszAttribute = NULL;
char szTmp[256];
char **tokens = NULL;
int nTokens = 0, i=0,bString=0;
if (!psFilterNode)
return NULL;
if (psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON) {
if ( psFilterNode->psLeftNode && psFilterNode->psRightNode) {
if (FLTIsBinaryComparisonFilterType(psFilterNode->pszValue)) {
pszExpression = FLTGetBinaryComparisonExpresssion(psFilterNode, lp);
} else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsBetween") == 0) {
pszExpression = FLTGetIsBetweenComparisonExpresssion(psFilterNode, lp);
} else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsLike") == 0) {
pszExpression = FLTGetIsLikeComparisonExpression(psFilterNode);
}
}
} else if (psFilterNode->eType == FILTER_NODE_TYPE_LOGICAL) {
if (strcasecmp(psFilterNode->pszValue, "AND") == 0 ||
strcasecmp(psFilterNode->pszValue, "OR") == 0) {
pszExpression = FLTGetLogicalComparisonExpresssion(psFilterNode, lp);
} else if (strcasecmp(psFilterNode->pszValue, "NOT") == 0) {
pszExpression = FLTGetLogicalComparisonExpresssion(psFilterNode, lp);
}
} else if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL) {
/* TODO */
} else if (psFilterNode->eType == FILTER_NODE_TYPE_FEATUREID) {
#if defined(USE_WMS_SVR) || defined (USE_WFS_SVR) || defined (USE_WCS_SVR) || defined(USE_SOS_SVR)
if (psFilterNode->pszValue) {
pszAttribute = msOWSLookupMetadata(&(lp->metadata), "OFG", "featureid");
if (pszAttribute) {
tokens = msStringSplit(psFilterNode->pszValue,',', &nTokens);
if (tokens && nTokens > 0) {
for (i=0; i<nTokens; i++) {
const char* pszId = tokens[i];
const char* pszDot = strchr(pszId, '.');
if( pszDot )
pszId = pszDot + 1;
if (i == 0) {
if(FLTIsNumeric(pszId) == MS_FALSE)
bString = 1;
}
if (bString)
snprintf(szTmp, sizeof(szTmp), "('[%s]' = '%s')" , pszAttribute, pszId);
else
snprintf(szTmp, sizeof(szTmp), "([%s] = %s)" , pszAttribute, pszId);
if (pszExpression != NULL)
pszExpression = msStringConcatenate(pszExpression, " OR ");
else
pszExpression = msStringConcatenate(pszExpression, "(");
pszExpression = msStringConcatenate(pszExpression, szTmp);
}
msFreeCharArray(tokens, nTokens);
}
}
/*opening and closing brackets are needed for mapserver expressions*/
if (pszExpression)
pszExpression = msStringConcatenate(pszExpression, ")");
}
#else
msSetError(MS_MISCERR, "OWS support is not available.",
"FLTGetMapserverExpression()");
return(MS_FAILURE);
#endif
}
return pszExpression;
}
/************************************************************************/
/* FLTGetSQLExpression */
/* */
/* Build SQL expressions from the mapserver nodes. */
/************************************************************************/
char *FLTGetSQLExpression(FilterEncodingNode *psFilterNode, layerObj *lp)
{
char *pszExpression = NULL;
const char *pszAttribute = NULL;
char szTmp[256];
char **tokens = NULL;
int nTokens = 0, i=0, bString=0;
if (psFilterNode == NULL || lp == NULL)
return NULL;
if (psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON) {
if ( psFilterNode->psLeftNode && psFilterNode->psRightNode) {
if (FLTIsBinaryComparisonFilterType(psFilterNode->pszValue)) {
pszExpression =
FLTGetBinaryComparisonSQLExpresssion(psFilterNode, lp);
} else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsBetween") == 0) {
pszExpression =
FLTGetIsBetweenComparisonSQLExpresssion(psFilterNode, lp);
} else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsLike") == 0) {
pszExpression =
FLTGetIsLikeComparisonSQLExpression(psFilterNode, lp);
}
}
} else if (psFilterNode->eType == FILTER_NODE_TYPE_LOGICAL) {
if (strcasecmp(psFilterNode->pszValue, "AND") == 0 ||
strcasecmp(psFilterNode->pszValue, "OR") == 0) {
pszExpression =
FLTGetLogicalComparisonSQLExpresssion(psFilterNode, lp);
} else if (strcasecmp(psFilterNode->pszValue, "NOT") == 0) {
pszExpression =
FLTGetLogicalComparisonSQLExpresssion(psFilterNode, lp);
}
}
else if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL) {
/* TODO */
} else if (psFilterNode->eType == FILTER_NODE_TYPE_FEATUREID) {
#if defined(USE_WMS_SVR) || defined (USE_WFS_SVR) || defined (USE_WCS_SVR) || defined(USE_SOS_SVR)
if (psFilterNode->pszValue) {
pszAttribute = msOWSLookupMetadata(&(lp->metadata), "OFG", "featureid");
if (pszAttribute) {
tokens = msStringSplit(psFilterNode->pszValue,',', &nTokens);
bString = 0;
if (tokens && nTokens > 0) {
for (i=0; i<nTokens; i++) {
char *pszEscapedStr = NULL;
const char* pszId = tokens[i];
const char* pszDot = strchr(pszId, '.');
if( pszDot )
pszId = pszDot + 1;
if (strlen(pszId) <= 0)
continue;
if (FLTIsNumeric(pszId) == MS_FALSE)
bString = 1;
pszEscapedStr = msLayerEscapeSQLParam(lp, pszId);
if (bString)
{
if( lp->connectiontype == MS_OGR || lp->connectiontype == MS_POSTGIS )
snprintf(szTmp, sizeof(szTmp), "(CAST(%s AS CHARACTER(255)) = '%s')" , pszAttribute, pszEscapedStr);
else
snprintf(szTmp, sizeof(szTmp), "(%s = '%s')" , pszAttribute, pszEscapedStr);
}
else
snprintf(szTmp, sizeof(szTmp), "(%s = %s)" , pszAttribute, pszEscapedStr);
msFree(pszEscapedStr);
pszEscapedStr=NULL;
if (pszExpression != NULL)
pszExpression = msStringConcatenate(pszExpression, " OR ");
else
/*opening and closing brackets*/
pszExpression = msStringConcatenate(pszExpression, "(");
pszExpression = msStringConcatenate(pszExpression, szTmp);
}
msFreeCharArray(tokens, nTokens);
}
}
/*opening and closing brackets*/
if (pszExpression)
pszExpression = msStringConcatenate(pszExpression, ")");
}
#else
msSetError(MS_MISCERR, "OWS support is not available.",
"FLTGetSQLExpression()");
return(MS_FAILURE);
#endif
}
else if ( lp->connectiontype != MS_OGR &&
psFilterNode->eType == FILTER_NODE_TYPE_TEMPORAL )
pszExpression = FLTGetTimeExpression(psFilterNode, lp);
return pszExpression;
}
/************************************************************************/
/* FLTGetNodeExpression */
/* */
/* Return the expresion for a specific node. */
/************************************************************************/
char *FLTGetNodeExpression(FilterEncodingNode *psFilterNode, layerObj *lp)
{
char *pszExpression = NULL;
if (!psFilterNode)
return NULL;
if (FLTIsLogicalFilterType(psFilterNode->pszValue))
pszExpression = FLTGetLogicalComparisonExpresssion(psFilterNode, lp);
else if (FLTIsComparisonFilterType(psFilterNode->pszValue)) {
if (FLTIsBinaryComparisonFilterType(psFilterNode->pszValue))
pszExpression = FLTGetBinaryComparisonExpresssion(psFilterNode, lp);
else if (strcasecmp(psFilterNode->pszValue, "PropertyIsBetween") == 0)
pszExpression = FLTGetIsBetweenComparisonExpresssion(psFilterNode, lp);
else if (strcasecmp(psFilterNode->pszValue, "PropertyIsLike") == 0)
pszExpression = FLTGetIsLikeComparisonExpression(psFilterNode);
}
return pszExpression;
}
/************************************************************************/
/* FLTGetLogicalComparisonSQLExpresssion */
/* */
/* Return the expression for logical comparison expression. */
/************************************************************************/
char *FLTGetLogicalComparisonSQLExpresssion(FilterEncodingNode *psFilterNode,
layerObj *lp)
{
char *pszBuffer = NULL;
char *pszTmp = NULL;
int nTmp = 0;
if (lp == NULL)
return NULL;
/* ==================================================================== */
/* special case for BBOX node. */
/* ==================================================================== */
if (psFilterNode->psLeftNode && psFilterNode->psRightNode &&
((strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") == 0) ||
(strcasecmp(psFilterNode->psRightNode->pszValue, "BBOX") == 0))) {
if (strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") != 0)
pszTmp = FLTGetSQLExpression(psFilterNode->psLeftNode, lp);
else
pszTmp = FLTGetSQLExpression(psFilterNode->psRightNode, lp);
if (!pszTmp)
return NULL;
pszBuffer = (char *)malloc(sizeof(char) * (strlen(pszTmp) + 1));
sprintf(pszBuffer, "%s", pszTmp);
}
/* ==================================================================== */
/* special case for temporal filter node (OGR layer only) */
/* ==================================================================== */
else if (lp->connectiontype == MS_OGR &&
psFilterNode->psLeftNode && psFilterNode->psRightNode &&
(psFilterNode->psLeftNode->eType == FILTER_NODE_TYPE_TEMPORAL ||
psFilterNode->psRightNode->eType == FILTER_NODE_TYPE_TEMPORAL) ) {
if (psFilterNode->psLeftNode->eType != FILTER_NODE_TYPE_TEMPORAL)
pszTmp = FLTGetSQLExpression(psFilterNode->psLeftNode, lp);
else
pszTmp = FLTGetSQLExpression(psFilterNode->psRightNode, lp);
if (!pszTmp)
return NULL;
pszBuffer = (char *)malloc(sizeof(char) * (strlen(pszTmp) + 1));
sprintf(pszBuffer, "%s", pszTmp);
}
/* -------------------------------------------------------------------- */
/* OR and AND */
/* -------------------------------------------------------------------- */
else if (psFilterNode->psLeftNode && psFilterNode->psRightNode) {
pszTmp = FLTGetSQLExpression(psFilterNode->psLeftNode, lp);
if (!pszTmp)
return NULL;
pszBuffer = (char *)malloc(sizeof(char) *
(strlen(pszTmp) +
strlen(psFilterNode->pszValue) + 5));
pszBuffer[0] = '\0';
strcat(pszBuffer, " (");
strcat(pszBuffer, pszTmp);
strcat(pszBuffer, " ");
strcat(pszBuffer, psFilterNode->pszValue);
strcat(pszBuffer, " ");
free( pszTmp );
nTmp = strlen(pszBuffer);
pszTmp = FLTGetSQLExpression(psFilterNode->psRightNode, lp);
if (!pszTmp) {
free(pszBuffer);
return NULL;
}
pszBuffer = (char *)realloc(pszBuffer,
sizeof(char) * (strlen(pszTmp) + nTmp +3));
strcat(pszBuffer, pszTmp);
strcat(pszBuffer, ") ");
}
/* -------------------------------------------------------------------- */
/* NOT */
/* -------------------------------------------------------------------- */
else if (psFilterNode->psLeftNode &&
strcasecmp(psFilterNode->pszValue, "NOT") == 0) {
pszTmp = FLTGetSQLExpression(psFilterNode->psLeftNode, lp);
if (!pszTmp)
return NULL;
pszBuffer = (char *)malloc(sizeof(char) * (strlen(pszTmp) + 9));
pszBuffer[0] = '\0';
strcat(pszBuffer, " (NOT ");
strcat(pszBuffer, pszTmp);
strcat(pszBuffer, ") ");
} else
return NULL;
/* -------------------------------------------------------------------- */
/* Cleanup. */
/* -------------------------------------------------------------------- */
if( pszTmp != NULL )
free( pszTmp );
return pszBuffer;
}
/************************************************************************/
/* FLTGetLogicalComparisonExpresssion */
/* */
/* Return the expression for logical comparison expression. */
/************************************************************************/
char *FLTGetLogicalComparisonExpresssion(FilterEncodingNode *psFilterNode, layerObj *lp)
{
char *pszTmp = NULL;
char *pszBuffer = NULL;
int nTmp = 0;
if (!psFilterNode || !FLTIsLogicalFilterType(psFilterNode->pszValue))
return NULL;
/* ==================================================================== */
/* special case for BBOX node. */
/* ==================================================================== */
if (psFilterNode->psLeftNode && psFilterNode->psRightNode &&
(strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") == 0 ||
strcasecmp(psFilterNode->psRightNode->pszValue, "BBOX") == 0 ||
FLTIsGeosNode(psFilterNode->psLeftNode->pszValue) ||
FLTIsGeosNode(psFilterNode->psRightNode->pszValue)))
{
/*strcat(szBuffer, " (");*/
if (strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") != 0 &&
strcasecmp(psFilterNode->psLeftNode->pszValue, "DWithin") != 0 &&
FLTIsGeosNode(psFilterNode->psLeftNode->pszValue) == MS_FALSE)
pszTmp = FLTGetNodeExpression(psFilterNode->psLeftNode, lp);
else
pszTmp = FLTGetNodeExpression(psFilterNode->psRightNode, lp);
if (!pszTmp)
return NULL;
pszBuffer = (char *)malloc(sizeof(char) * (strlen(pszTmp) + 3));
pszBuffer[0] = '\0';
/*
if (strcasecmp(psFilterNode->psLeftNode->pszValue, "PropertyIsLike") == 0 ||
strcasecmp(psFilterNode->psRightNode->pszValue, "PropertyIsLike") == 0)
sprintf(pszBuffer, "%s", pszTmp);
else
*/
sprintf(pszBuffer, "(%s)", pszTmp);
free(pszTmp);
return pszBuffer;
}
/* -------------------------------------------------------------------- */
/* OR and AND */
/* -------------------------------------------------------------------- */
if (psFilterNode->psLeftNode && psFilterNode->psRightNode) {
pszTmp = FLTGetNodeExpression(psFilterNode->psLeftNode, lp);
if (!pszTmp)
return NULL;
pszBuffer = (char *)malloc(sizeof(char) *
(strlen(pszTmp) + strlen(psFilterNode->pszValue) + 5));
pszBuffer[0] = '\0';
strcat(pszBuffer, " (");
strcat(pszBuffer, pszTmp);
strcat(pszBuffer, " ");
strcat(pszBuffer, psFilterNode->pszValue);
strcat(pszBuffer, " ");
free(pszTmp);
pszTmp = FLTGetNodeExpression(psFilterNode->psRightNode, lp);
if (!pszTmp) {
msFree(pszBuffer);
return NULL;
}
nTmp = strlen(pszBuffer);
pszBuffer = (char *)realloc(pszBuffer,
sizeof(char) * (strlen(pszTmp) + nTmp +3));
strcat(pszBuffer, pszTmp);
strcat(pszBuffer, ") ");
free(pszTmp);
}
/* -------------------------------------------------------------------- */
/* NOT */
/* -------------------------------------------------------------------- */
else if (psFilterNode->psLeftNode &&
strcasecmp(psFilterNode->pszValue, "NOT") == 0) {
pszTmp = FLTGetNodeExpression(psFilterNode->psLeftNode, lp);
if (!pszTmp)
return NULL;
pszBuffer = (char *)malloc(sizeof(char) *
(strlen(pszTmp) + 9));
pszBuffer[0] = '\0';
strcat(pszBuffer, " (NOT ");
strcat(pszBuffer, pszTmp);
strcat(pszBuffer, ") ");
free(pszTmp);
} else
return NULL;
return pszBuffer;
}
/************************************************************************/
/* FLTGetBinaryComparisonExpresssion */
/* */
/* Return the expression for a binary comparison filter node. */
/************************************************************************/
char *FLTGetBinaryComparisonExpresssion(FilterEncodingNode *psFilterNode, layerObj *lp)
{
const size_t bufferSize = 1024;
char szBuffer[1024];
int bString=0;
char szTmp[256];
szBuffer[0] = '\0';
if (!psFilterNode || !FLTIsBinaryComparisonFilterType(psFilterNode->pszValue))
return NULL;
/* -------------------------------------------------------------------- */
/* check if the value is a numeric value or alphanumeric. If it */
/* is alphanumeric, add quotes around attribute and values. */
/* -------------------------------------------------------------------- */
bString = 0;
if (psFilterNode->psRightNode->pszValue) {
const char* pszOFGType;
snprintf(szTmp, sizeof(szTmp), "%s_type", psFilterNode->psLeftNode->pszValue);
pszOFGType = msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp);
if (pszOFGType!= NULL && strcasecmp(pszOFGType, "Character") == 0)
bString = 1;
else if (FLTIsNumeric(psFilterNode->psRightNode->pszValue) == MS_FALSE)
bString = 1;
}
/* specical case to be able to have empty strings in the expression. */
if (psFilterNode->psRightNode->pszValue == NULL)
bString = 1;
if (bString)
strlcat(szBuffer, " (\"[", bufferSize);
else
strlcat(szBuffer, " ([", bufferSize);
/* attribute */
strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
if (bString)
strlcat(szBuffer, "]\" ", bufferSize);
else
strlcat(szBuffer, "] ", bufferSize);
/* logical operator */
if (strcasecmp(psFilterNode->pszValue,
"PropertyIsEqualTo") == 0) {
/*case insensitive set ? */
if (psFilterNode->psRightNode->pOther &&
(*(int *)psFilterNode->psRightNode->pOther) == 1) {
strlcat(szBuffer, "IEQ", bufferSize);
} else
strlcat(szBuffer, "=", bufferSize);
} else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsNotEqualTo") == 0)
strlcat(szBuffer, "!=", bufferSize);
else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsLessThan") == 0)
strlcat(szBuffer, "<", bufferSize);
else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsGreaterThan") == 0)
strlcat(szBuffer, ">", bufferSize);
else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsLessThanOrEqualTo") == 0)
strlcat(szBuffer, "<=", bufferSize);
else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsGreaterThanOrEqualTo") == 0)
strlcat(szBuffer, ">=", bufferSize);
strlcat(szBuffer, " ", bufferSize);
/* value */
if (bString)
strlcat(szBuffer, "\"", bufferSize);
if (psFilterNode->psRightNode->pszValue)
strlcat(szBuffer, psFilterNode->psRightNode->pszValue, bufferSize);
if (bString)
strlcat(szBuffer, "\"", bufferSize);
strlcat(szBuffer, ") ", bufferSize);
return msStrdup(szBuffer);
}
/************************************************************************/
/* FLTGetBinaryComparisonSQLExpresssion */
/* */
/* Return the expression for a binary comparison filter node. */
/************************************************************************/
char *FLTGetBinaryComparisonSQLExpresssion(FilterEncodingNode *psFilterNode,
layerObj *lp)
{
const size_t bufferSize = 1024;
char szBuffer[1024];
int bString=0;
char szTmp[256];
char* pszEscapedStr = NULL;
szBuffer[0] = '\0';
if (!psFilterNode || !
FLTIsBinaryComparisonFilterType(psFilterNode->pszValue))
return NULL;
/* -------------------------------------------------------------------- */
/* check if the value is a numeric value or alphanumeric. If it */
/* is alphanumeric, add quotes around attribute and values. */
/* -------------------------------------------------------------------- */
bString = 0;
if (psFilterNode->psRightNode->pszValue) {
const char* pszOFGType;
snprintf(szTmp, sizeof(szTmp), "%s_type", psFilterNode->psLeftNode->pszValue);
pszOFGType = msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp);
if (pszOFGType!= NULL && strcasecmp(pszOFGType, "Character") == 0)
bString = 1;
else if (FLTIsNumeric(psFilterNode->psRightNode->pszValue) == MS_FALSE)
bString = 1;
}
/* specical case to be able to have empty strings in the expression. */
if (psFilterNode->psRightNode->pszValue == NULL)
bString = 1;
/*opening bracket*/
strlcat(szBuffer, " (", bufferSize);
pszEscapedStr = msLayerEscapePropertyName(lp, psFilterNode->psLeftNode->pszValue);
/* attribute */
/*case insensitive set ? */
if (bString &&
strcasecmp(psFilterNode->pszValue,
"PropertyIsEqualTo") == 0 &&
psFilterNode->psRightNode->pOther &&
(*(int *)psFilterNode->psRightNode->pOther) == 1) {
snprintf(szTmp, sizeof(szTmp), "lower(%s) ", pszEscapedStr);
strlcat(szBuffer, szTmp, bufferSize);
} else
strlcat(szBuffer, pszEscapedStr, bufferSize);
msFree(pszEscapedStr);
pszEscapedStr = NULL;
/* logical operator */
if (strcasecmp(psFilterNode->pszValue,
"PropertyIsEqualTo") == 0)
strlcat(szBuffer, "=", bufferSize);
else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsNotEqualTo") == 0)
strlcat(szBuffer, "<>", bufferSize);
else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsLessThan") == 0)
strlcat(szBuffer, "<", bufferSize);
else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsGreaterThan") == 0)
strlcat(szBuffer, ">", bufferSize);
else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsLessThanOrEqualTo") == 0)
strlcat(szBuffer, "<=", bufferSize);
else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsGreaterThanOrEqualTo") == 0)
strlcat(szBuffer, ">=", bufferSize);
strlcat(szBuffer, " ", bufferSize);
/* value */
if (bString &&
psFilterNode->psRightNode->pszValue &&
strcasecmp(psFilterNode->pszValue,
"PropertyIsEqualTo") == 0 &&
psFilterNode->psRightNode->pOther &&
(*(int *)psFilterNode->psRightNode->pOther) == 1) {
char* pszEscapedStr;
pszEscapedStr = msLayerEscapeSQLParam(lp, psFilterNode->psRightNode->pszValue);
snprintf(szTmp, sizeof(szTmp), "lower('%s') ", pszEscapedStr);
msFree(pszEscapedStr);
strlcat(szBuffer, szTmp, bufferSize);
} else {
if (bString)
strlcat(szBuffer, "'", bufferSize);
if (psFilterNode->psRightNode->pszValue) {
if (bString) {
char* pszEscapedStr;
pszEscapedStr = msLayerEscapeSQLParam(lp, psFilterNode->psRightNode->pszValue);
strlcat(szBuffer, pszEscapedStr, bufferSize);
msFree(pszEscapedStr);
pszEscapedStr=NULL;
} else
strlcat(szBuffer, psFilterNode->psRightNode->pszValue, bufferSize);
}
if (bString)
strlcat(szBuffer, "'", bufferSize);
}
/*closing bracket*/
strlcat(szBuffer, ") ", bufferSize);
return msStrdup(szBuffer);
}
/************************************************************************/
/* FLTGetIsBetweenComparisonSQLExpresssion */
/* */
/* Build an SQL expresssion for IsBteween Filter. */
/************************************************************************/
char *FLTGetIsBetweenComparisonSQLExpresssion(FilterEncodingNode *psFilterNode,
layerObj *lp)
{
const size_t bufferSize = 1024;
char szBuffer[1024];
char **aszBounds = NULL;
int nBounds = 0;
int bString=0;
char szTmp[256];
char* pszEscapedStr;
szBuffer[0] = '\0';
if (!psFilterNode ||
!(strcasecmp(psFilterNode->pszValue, "PropertyIsBetween") == 0))
return NULL;
if (!psFilterNode->psLeftNode || !psFilterNode->psRightNode )
return NULL;
/* -------------------------------------------------------------------- */
/* Get the bounds value which are stored like boundmin;boundmax */
/* -------------------------------------------------------------------- */
aszBounds = msStringSplit(psFilterNode->psRightNode->pszValue, ';', &nBounds);
if (nBounds != 2) {
msFreeCharArray(aszBounds, nBounds);
return NULL;
}
/* -------------------------------------------------------------------- */
/* check if the value is a numeric value or alphanumeric. If it */
/* is alphanumeric, add quotes around attribute and values. */
/* -------------------------------------------------------------------- */
bString = 0;
if (aszBounds[0]) {
const char* pszOFGType;
snprintf(szTmp, sizeof(szTmp), "%s_type", psFilterNode->psLeftNode->pszValue);
pszOFGType = msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp);
if (pszOFGType!= NULL && strcasecmp(pszOFGType, "Character") == 0)
bString = 1;
else if (FLTIsNumeric(aszBounds[0]) == MS_FALSE)
bString = 1;
}
if (!bString) {
if (aszBounds[1]) {
if (FLTIsNumeric(aszBounds[1]) == MS_FALSE)
bString = 1;
}
}
/* -------------------------------------------------------------------- */
/* build expresssion. */
/* -------------------------------------------------------------------- */
/*opening paranthesis */
strlcat(szBuffer, " (", bufferSize);
/* attribute */
pszEscapedStr = msLayerEscapePropertyName(lp, psFilterNode->psLeftNode->pszValue);
strlcat(szBuffer, pszEscapedStr, bufferSize);
msFree(pszEscapedStr);
pszEscapedStr = NULL;
/*between*/
strlcat(szBuffer, " BETWEEN ", bufferSize);
/*bound 1*/
if (bString)
strlcat(szBuffer,"'", bufferSize);
pszEscapedStr = msLayerEscapeSQLParam( lp, aszBounds[0]);
strlcat(szBuffer, pszEscapedStr, bufferSize);
msFree(pszEscapedStr);
pszEscapedStr=NULL;
if (bString)
strlcat(szBuffer,"'", bufferSize);
strlcat(szBuffer, " AND ", bufferSize);
/*bound 2*/
if (bString)
strlcat(szBuffer, "'", bufferSize);
pszEscapedStr = msLayerEscapeSQLParam( lp, aszBounds[1]);
strlcat(szBuffer, pszEscapedStr, bufferSize);
msFree(pszEscapedStr);
pszEscapedStr=NULL;
if (bString)
strlcat(szBuffer,"'", bufferSize);
/*closing paranthesis*/
strlcat(szBuffer, ")", bufferSize);
msFreeCharArray(aszBounds, nBounds);
return msStrdup(szBuffer);
}
/************************************************************************/
/* FLTGetIsBetweenComparisonExpresssion */
/* */
/* Build expresssion for IsBteween Filter. */
/************************************************************************/
char *FLTGetIsBetweenComparisonExpresssion(FilterEncodingNode *psFilterNode,
layerObj *lp)
{
const size_t bufferSize = 1024;
char szBuffer[1024];
char **aszBounds = NULL;
int nBounds = 0;
int bString=0;
char szTmp[256];
szBuffer[0] = '\0';
if (!psFilterNode ||
!(strcasecmp(psFilterNode->pszValue, "PropertyIsBetween") == 0))
return NULL;
if (!psFilterNode->psLeftNode || !psFilterNode->psRightNode )
return NULL;
/* -------------------------------------------------------------------- */
/* Get the bounds value which are stored like boundmin;boundmax */
/* -------------------------------------------------------------------- */
aszBounds = msStringSplit(psFilterNode->psRightNode->pszValue, ';', &nBounds);
if (nBounds != 2) {
msFreeCharArray(aszBounds, nBounds);
return NULL;
}
/* -------------------------------------------------------------------- */
/* check if the value is a numeric value or alphanumeric. If it */
/* is alphanumeric, add quotes around attribute and values. */
/* -------------------------------------------------------------------- */
bString = 0;
if (aszBounds[0]) {
const char* pszOFGType;
snprintf(szTmp, sizeof(szTmp), "%s_type", psFilterNode->psLeftNode->pszValue);
pszOFGType = msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp);
if (pszOFGType!= NULL && strcasecmp(pszOFGType, "Character") == 0)
bString = 1;
else if (FLTIsNumeric(aszBounds[0]) == MS_FALSE)
bString = 1;
}
if (!bString) {
if (aszBounds[1]) {
if (FLTIsNumeric(aszBounds[1]) == MS_FALSE)
bString = 1;
}
}
/* -------------------------------------------------------------------- */
/* build expresssion. */
/* -------------------------------------------------------------------- */
if (bString)
strlcat(szBuffer, " (\"[", bufferSize);
else
strlcat(szBuffer, " ([", bufferSize);
/* attribute */
strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
if (bString)
strlcat(szBuffer, "]\" ", bufferSize);
else
strlcat(szBuffer, "] ", bufferSize);
strlcat(szBuffer, " >= ", bufferSize);
if (bString)
strlcat(szBuffer,"\"", bufferSize);
strlcat(szBuffer, aszBounds[0], bufferSize);
if (bString)
strlcat(szBuffer,"\"", bufferSize);
strlcat(szBuffer, " AND ", bufferSize);
if (bString)
strlcat(szBuffer, " \"[", bufferSize);
else
strlcat(szBuffer, " [", bufferSize);
/* attribute */
strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
if (bString)
strlcat(szBuffer, "]\" ", bufferSize);
else
strlcat(szBuffer, "] ", bufferSize);
strlcat(szBuffer, " <= ", bufferSize);
if (bString)
strlcat(szBuffer,"\"", bufferSize);
strlcat(szBuffer, aszBounds[1], bufferSize);
if (bString)
strlcat(szBuffer,"\"", bufferSize);
strlcat(szBuffer, ")", bufferSize);
msFreeCharArray(aszBounds, nBounds);
return msStrdup(szBuffer);
}
/************************************************************************/
/* FLTGetIsLikeComparisonExpression */
/* */
/* Build expression for IsLike filter. */
/************************************************************************/
char *FLTGetIsLikeComparisonExpression(FilterEncodingNode *psFilterNode)
{
const size_t bufferSize = 1024;
char szBuffer[1024];
char szTmp[256];
char *pszValue = NULL;
const char *pszWild = NULL;
const char *pszSingle = NULL;
const char *pszEscape = NULL;
int bCaseInsensitive = 0;
int nLength=0, i=0, iTmp=0;
FEPropertyIsLike* propIsLike;
if (!psFilterNode || !psFilterNode->pOther || !psFilterNode->psLeftNode ||
!psFilterNode->psRightNode || !psFilterNode->psRightNode->pszValue)
return NULL;
propIsLike = (FEPropertyIsLike *)psFilterNode->pOther;
pszWild = propIsLike->pszWildCard;
pszSingle = propIsLike->pszSingleChar;
pszEscape = propIsLike->pszEscapeChar;
bCaseInsensitive = propIsLike->bCaseInsensitive;
if (!pszWild || strlen(pszWild) == 0 ||
!pszSingle || strlen(pszSingle) == 0 ||
!pszEscape || strlen(pszEscape) == 0)
return NULL;
/* -------------------------------------------------------------------- */
/* Use operand with regular expressions. */
/* -------------------------------------------------------------------- */
szBuffer[0] = '\0';
sprintf(szTmp, "%s", " (\"[");
szTmp[4] = '\0';
strlcat(szBuffer, szTmp, bufferSize);
/* attribute */
strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
szBuffer[strlen(szBuffer)] = '\0';
/*#3521 */
if(bCaseInsensitive == 1)
sprintf(szTmp, "%s", "]\" ~* /");
else
sprintf(szTmp, "%s", "]\" =~ /");
szTmp[7] = '\0';
strlcat(szBuffer, szTmp, bufferSize);
szBuffer[strlen(szBuffer)] = '\0';
pszValue = psFilterNode->psRightNode->pszValue;
nLength = strlen(pszValue);
if( 1 + 2 * nLength + 1 + 1 >= sizeof(szTmp) )
return NULL;
iTmp =0;
if (nLength > 0 && pszValue[0] != pszWild[0] &&
pszValue[0] != pszSingle[0] &&
pszValue[0] != pszEscape[0]) {
szTmp[iTmp]= '^';
iTmp++;
}
for (i=0; i<nLength; i++) {
if (pszValue[i] != pszWild[0] &&
pszValue[i] != pszSingle[0] &&
pszValue[i] != pszEscape[0]) {
szTmp[iTmp] = pszValue[i];
iTmp++;
szTmp[iTmp] = '\0';
} else if (pszValue[i] == pszSingle[0]) {
szTmp[iTmp] = '.';
iTmp++;
szTmp[iTmp] = '\0';
} else if (pszValue[i] == pszEscape[0]) {
szTmp[iTmp] = '\\';
iTmp++;
szTmp[iTmp] = '\0';
} else if (pszValue[i] == pszWild[0]) {
/* strcat(szBuffer, "[0-9,a-z,A-Z,\\s]*"); */
/* iBuffer+=17; */
szTmp[iTmp++] = '.';
szTmp[iTmp++] = '*';
szTmp[iTmp] = '\0';
}
}
szTmp[iTmp] = '/';
szTmp[++iTmp] = '\0';
strlcat(szBuffer, szTmp, bufferSize);
strlcat(szBuffer, ")", bufferSize);
return msStrdup(szBuffer);
}
/************************************************************************/
/* FLTGetIsLikeComparisonSQLExpression */
/* */
/* Build an sql expression for IsLike filter. */
/************************************************************************/
char *FLTGetIsLikeComparisonSQLExpression(FilterEncodingNode *psFilterNode,
layerObj *lp)
{
const size_t bufferSize = 1024;
char szBuffer[1024];
char *pszValue = NULL;
const char *pszWild = NULL;
const char *pszSingle = NULL;
const char *pszEscape = NULL;
char szTmp[4];
int nLength=0, i=0, j=0;
int bCaseInsensitive = 0;
char *pszEscapedStr = NULL;
FEPropertyIsLike* propIsLike;
if (!psFilterNode || !psFilterNode->pOther || !psFilterNode->psLeftNode ||
!psFilterNode->psRightNode || !psFilterNode->psRightNode->pszValue)
return NULL;
propIsLike = (FEPropertyIsLike *)psFilterNode->pOther;
pszWild = propIsLike->pszWildCard;
pszSingle = propIsLike->pszSingleChar;
pszEscape = propIsLike->pszEscapeChar;
bCaseInsensitive = propIsLike->bCaseInsensitive;
if (!pszWild || strlen(pszWild) == 0 ||
!pszSingle || strlen(pszSingle) == 0 ||
!pszEscape || strlen(pszEscape) == 0)
return NULL;
if (pszEscape[0] == '\'') {
/* This might be valid, but the risk of SQL injection is too high */
/* and the below code is not ready for that */
/* Someone who does this has clearly suspect intentions ! */
msSetError(MS_MISCERR, "Single quote character is not allowed as an escaping character.",
"FLTGetIsLikeComparisonSQLExpression()");
return NULL;
}
szBuffer[0] = '\0';
/*opening bracket*/
strlcat(szBuffer, " (", bufferSize);
/* attribute name */
pszEscapedStr = msLayerEscapePropertyName(lp, psFilterNode->psLeftNode->pszValue);
strlcat(szBuffer, pszEscapedStr, bufferSize);
msFree(pszEscapedStr);
pszEscapedStr = NULL;
if (lp->connectiontype == MS_POSTGIS) {
if (bCaseInsensitive == 1)
strlcat(szBuffer, "::text ilike '", bufferSize);
else
strlcat(szBuffer, "::text like '", bufferSize);
} else
strlcat(szBuffer, " like '", bufferSize);
pszValue = psFilterNode->psRightNode->pszValue;
nLength = strlen(pszValue);
pszEscapedStr = (char*) msSmallMalloc( 3 * nLength + 1);
for (i=0, j=0; i<nLength; i++) {
char c = pszValue[i];
if (c != pszWild[0] &&
c != pszSingle[0] &&
c != pszEscape[0]) {
if (c == '\'') {
pszEscapedStr[j++] = '\'';
pszEscapedStr[j++] = '\'';
} else if (c == '\\') {
pszEscapedStr[j++] = '\\';
pszEscapedStr[j++] = '\\';
} else
pszEscapedStr[j++] = c;
} else if (c == pszSingle[0]) {
pszEscapedStr[j++] = '_';
} else if (c == pszEscape[0]) {
pszEscapedStr[j++] = pszEscape[0];
if (i+1<nLength) {
char nextC = pszValue[i+1];
i++;
if (nextC == '\'') {
pszEscapedStr[j++] = '\'';
pszEscapedStr[j++] = '\'';
} else
pszEscapedStr[j++] = nextC;
}
} else if (c == pszWild[0]) {
pszEscapedStr[j++] = '%';
}
}
pszEscapedStr[j++] = 0;
strlcat(szBuffer, pszEscapedStr, bufferSize);
msFree(pszEscapedStr);
strlcat(szBuffer, "'", bufferSize);
if (lp->connectiontype != MS_OGR) {
if (lp->connectiontype == MS_POSTGIS && pszEscape[0] == '\\')
strlcat(szBuffer, " escape E'", bufferSize);
else
strlcat(szBuffer, " escape '", bufferSize);
szTmp[0] = pszEscape[0];
if (pszEscape[0] == '\\') {
szTmp[1] = '\\';
szTmp[2] = '\'';
szTmp[3] = '\0';
} else {
szTmp[1] = '\'';
szTmp[2] = '\0';
}
strlcat(szBuffer, szTmp, bufferSize);
}
strlcat(szBuffer, ") ", bufferSize);
return msStrdup(szBuffer);
}
/************************************************************************/
/* FLTHasSpatialFilter */
/* */
/* Utility function to see if a spatial filter is included in */
/* the node. */
/************************************************************************/
int FLTHasSpatialFilter(FilterEncodingNode *psNode)
{
int bResult = MS_FALSE;
if (!psNode)
return MS_FALSE;
if (psNode->eType == FILTER_NODE_TYPE_LOGICAL) {
if (psNode->psLeftNode)
bResult = FLTHasSpatialFilter(psNode->psLeftNode);
if (bResult)
return MS_TRUE;
if (psNode->psRightNode)
bResult = FLTHasSpatialFilter(psNode->psRightNode);
if (bResult)
return MS_TRUE;
} else if (FLTIsBBoxFilter(psNode) || FLTIsPointFilter(psNode) ||
FLTIsLineFilter(psNode) || FLTIsPolygonFilter(psNode))
return MS_TRUE;
return MS_FALSE;
}
/************************************************************************/
/* FLTCreateFeatureIdFilterEncoding */
/* */
/* Utility function to create a filter node of FeatureId type. */
/************************************************************************/
FilterEncodingNode *FLTCreateFeatureIdFilterEncoding(const char *pszString)
{
FilterEncodingNode *psFilterNode = NULL;
if (pszString) {
psFilterNode = FLTCreateFilterEncodingNode();
psFilterNode->eType = FILTER_NODE_TYPE_FEATUREID;
psFilterNode->pszValue = msStrdup(pszString);
return psFilterNode;
}
return NULL;
}
/************************************************************************/
/* FLTParseGMLBox */
/* */
/* Parse gml box. Used for FE 1.0 */
/************************************************************************/
int FLTParseGMLBox(CPLXMLNode *psBox, rectObj *psBbox, char **ppszSRS)
{
int bCoordinatesValid = 0;
CPLXMLNode *psCoordinates = NULL;
CPLXMLNode *psCoord1 = NULL, *psCoord2 = NULL;
char **papszCoords=NULL, **papszMin=NULL, **papszMax = NULL;
int nCoords = 0, nCoordsMin = 0, nCoordsMax = 0;
const char *pszTmpCoord = NULL;
const char *pszSRS = NULL;
const char *pszTS = NULL;
const char *pszCS = NULL;
double minx = 0.0, miny = 0.0, maxx = 0.0, maxy = 0.0;
if (psBox) {
pszSRS = CPLGetXMLValue(psBox, "srsName", NULL);
if (ppszSRS && pszSRS)
*ppszSRS = msStrdup(pszSRS);
psCoordinates = CPLGetXMLNode(psBox, "coordinates");
pszTS = CPLGetXMLValue(psCoordinates, "ts", NULL);
if( pszTS == NULL )
pszTS = " ";
pszCS = CPLGetXMLValue(psCoordinates, "cs", NULL);
if( pszCS == NULL )
pszCS = ",";
pszTmpCoord = CPLGetXMLValue(psCoordinates, NULL, NULL);
if (pszTmpCoord) {
papszCoords = msStringSplit(pszTmpCoord, pszTS[0], &nCoords);
if (papszCoords && nCoords == 2) {
papszMin = msStringSplit(papszCoords[0], pszCS[0], &nCoordsMin);
if (papszMin && nCoordsMin == 2) {
papszMax = msStringSplit(papszCoords[1], pszCS[0], &nCoordsMax);
}
if (papszMax && nCoordsMax == 2) {
bCoordinatesValid =1;
minx = atof(papszMin[0]);
miny = atof(papszMin[1]);
maxx = atof(papszMax[0]);
maxy = atof(papszMax[1]);
}
msFreeCharArray(papszMin, nCoordsMin);
msFreeCharArray(papszMax, nCoordsMax);
}
msFreeCharArray(papszCoords, nCoords);
} else {
psCoord1 = CPLGetXMLNode(psBox, "coord");
psCoord2 = FLTGetNextSibblingNode(psCoord1);
if (psCoord1 && psCoord2 && strcmp(psCoord2->pszValue, "coord") == 0) {
const char* pszX = CPLGetXMLValue(psCoord1, "X", NULL);
const char* pszY = CPLGetXMLValue(psCoord1, "Y", NULL);
if (pszX && pszY) {
minx = atof(pszX);
miny = atof(pszY);
pszX = CPLGetXMLValue(psCoord2, "X", NULL);
pszY = CPLGetXMLValue(psCoord2, "Y", NULL);
if (pszX && pszY) {
maxx = atof(pszX);
maxy = atof(pszY);
bCoordinatesValid = 1;
}
}
}
}
}
if (bCoordinatesValid) {
psBbox->minx = minx;
psBbox->miny = miny;
psBbox->maxx = maxx;
psBbox->maxy = maxy;
}
return bCoordinatesValid;
}
/************************************************************************/
/* FLTParseGMLEnvelope */
/* */
/* Utility function to parse a gml:Envelope (used for SOS and FE1.1)*/
/************************************************************************/
int FLTParseGMLEnvelope(CPLXMLNode *psRoot, rectObj *psBbox, char **ppszSRS)
{
CPLXMLNode *psUpperCorner=NULL, *psLowerCorner=NULL;
const char *pszLowerCorner=NULL, *pszUpperCorner=NULL;
int bValid = 0;
char **tokens;
int n;
if (psRoot && psBbox && psRoot->eType == CXT_Element &&
EQUAL(psRoot->pszValue,"Envelope")) {
/*Get the srs if available*/
if (ppszSRS) {
const char* pszSRS = CPLGetXMLValue(psRoot, "srsName", NULL);
if( pszSRS != NULL )
*ppszSRS = msStrdup(pszSRS);
}
psLowerCorner = CPLSearchXMLNode(psRoot, "lowerCorner");
psUpperCorner = CPLSearchXMLNode(psRoot, "upperCorner");
if (psLowerCorner && psUpperCorner) {
pszLowerCorner = CPLGetXMLValue(psLowerCorner, NULL, NULL);
pszUpperCorner = CPLGetXMLValue(psUpperCorner, NULL, NULL);
if (pszLowerCorner && pszUpperCorner) {
tokens = msStringSplit(pszLowerCorner, ' ', &n);
if (tokens && n >= 2) {
psBbox->minx = atof(tokens[0]);
psBbox->miny = atof(tokens[1]);
msFreeCharArray(tokens, n);
tokens = msStringSplit(pszUpperCorner, ' ', &n);
if (tokens && n >= 2) {
psBbox->maxx = atof(tokens[0]);
psBbox->maxy = atof(tokens[1]);
bValid = 1;
}
}
msFreeCharArray(tokens, n);
}
}
}
return bValid;
}
/************************************************************************/
/* FLTNeedSRSSwapping */
/************************************************************************/
static int FLTNeedSRSSwapping( const char* pszSRS )
{
int bNeedSwapping = MS_FALSE;
projectionObj sProjTmp;
msInitProjection(&sProjTmp);
if (msLoadProjectionStringEPSG(&sProjTmp, pszSRS) == 0) {
bNeedSwapping = msIsAxisInvertedProj(&sProjTmp);
}
msFreeProjection(&sProjTmp);
return bNeedSwapping;
}
/************************************************************************/
/* FLTDoAxisSwappingIfNecessary */
/* */
/* Explore all geometries and BBOX to do axis swapping when the */
/* SRS requires it. If no explicit SRS is attached to the geometry */
/* the bDefaultSRSNeedsAxisSwapping is taken into account. The */
/* caller will have to determine its value from a more general */
/* context. */
/************************************************************************/
void FLTDoAxisSwappingIfNecessary(FilterEncodingNode *psFilterNode,
int bDefaultSRSNeedsAxisSwapping)
{
if( psFilterNode == NULL )
return;
if( psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL &&
psFilterNode->psRightNode->eType == FILTER_NODE_TYPE_BBOX )
{
rectObj* rect = (rectObj *)psFilterNode->psRightNode->pOther;
const char* pszSRS = psFilterNode->pszSRS;
if( (pszSRS != NULL && FLTNeedSRSSwapping(pszSRS)) ||
(pszSRS == NULL && bDefaultSRSNeedsAxisSwapping) )
{
double tmp;
tmp = rect->minx;
rect->minx = rect->miny;
rect->miny = tmp;
tmp = rect->maxx;
rect->maxx = rect->maxy;
rect->maxy = tmp;
}
}
else if( psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL &&
FLTIsGeometryFilterNodeType(psFilterNode->psRightNode->eType) )
{
shapeObj* shape = (shapeObj *)(psFilterNode->psRightNode->pOther);
const char* pszSRS = psFilterNode->pszSRS;
if( (pszSRS != NULL && FLTNeedSRSSwapping(pszSRS)) ||
(pszSRS == NULL && bDefaultSRSNeedsAxisSwapping) )
{
msAxisSwapShape(shape);
}
}
else
{
FLTDoAxisSwappingIfNecessary(psFilterNode->psLeftNode, bDefaultSRSNeedsAxisSwapping);
FLTDoAxisSwappingIfNecessary(psFilterNode->psRightNode, bDefaultSRSNeedsAxisSwapping);
}
}
static void FLTReplacePropertyName(FilterEncodingNode *psFilterNode,
const char *pszOldName,
const char *pszNewName)
{
if (psFilterNode && pszOldName && pszNewName) {
if (psFilterNode->eType == FILTER_NODE_TYPE_PROPERTYNAME) {
if (psFilterNode->pszValue &&
strcasecmp(psFilterNode->pszValue, pszOldName) == 0) {
msFree(psFilterNode->pszValue);
psFilterNode->pszValue = msStrdup(pszNewName);
}
}
if (psFilterNode->psLeftNode)
FLTReplacePropertyName(psFilterNode->psLeftNode, pszOldName,
pszNewName);
if (psFilterNode->psRightNode)
FLTReplacePropertyName(psFilterNode->psRightNode, pszOldName,
pszNewName);
}
}
static int FLTIsGMLDefaultProperty(const char* pszName)
{
return (strcmp(pszName, "gml:name") == 0 ||
strcmp(pszName, "gml:description") == 0 ||
strcmp(pszName, "gml:descriptionReference") == 0 ||
strcmp(pszName, "gml:identifier") == 0 ||
strcmp(pszName, "gml:boundedBy") == 0 ||
strcmp(pszName, "@gml:id") == 0);
}
static void FLTStripNameSpacesFromPropertyName(FilterEncodingNode *psFilterNode)
{
char **tokens=NULL;
int n=0;
if (psFilterNode) {
if (psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON &&
psFilterNode->psLeftNode != NULL &&
psFilterNode->psLeftNode->eType == FILTER_NODE_TYPE_PROPERTYNAME &&
FLTIsGMLDefaultProperty(psFilterNode->psLeftNode->pszValue) )
{
return;
}
if (psFilterNode->eType == FILTER_NODE_TYPE_PROPERTYNAME) {
if (psFilterNode->pszValue &&
strstr(psFilterNode->pszValue, ":")) {
tokens = msStringSplit(psFilterNode->pszValue, ':', &n);
if (tokens && n==2) {
msFree(psFilterNode->pszValue);
psFilterNode->pszValue = msStrdup(tokens[1]);
}
msFreeCharArray(tokens, n);
}
}
if (psFilterNode->psLeftNode)
FLTStripNameSpacesFromPropertyName(psFilterNode->psLeftNode);
if (psFilterNode->psRightNode)
FLTStripNameSpacesFromPropertyName(psFilterNode->psRightNode);
}
}
static void FLTRemoveGroupName(FilterEncodingNode *psFilterNode,
gmlGroupListObj* groupList)
{
int i;
if (psFilterNode) {
if (psFilterNode->eType == FILTER_NODE_TYPE_PROPERTYNAME) {
if( psFilterNode->pszValue != NULL )
{
const char* pszPropertyName = psFilterNode->pszValue;
const char* pszSlash = strchr(pszPropertyName, '/');
if( pszSlash != NULL ) {
const char* pszColon = strchr(pszPropertyName, ':');
if( pszColon != NULL && pszColon < pszSlash )
pszPropertyName = pszColon + 1;
for(i=0;i<groupList->numgroups;i++) {
const char* pszGroupName = groupList->groups[i].name;
size_t nGroupNameLen = strlen(pszGroupName);
if(strncasecmp(pszPropertyName, pszGroupName, nGroupNameLen) == 0 &&
pszPropertyName[nGroupNameLen] == '/') {
char* pszTmp;
pszPropertyName = pszPropertyName + nGroupNameLen + 1;
pszColon = strchr(pszPropertyName, ':');
if( pszColon != NULL )
pszPropertyName = pszColon + 1;
pszTmp = msStrdup(pszPropertyName);
msFree(psFilterNode->pszValue);
psFilterNode->pszValue = pszTmp;
break;
}
}
}
}
}
if (psFilterNode->psLeftNode)
FLTRemoveGroupName(psFilterNode->psLeftNode, groupList);
if (psFilterNode->psRightNode)
FLTRemoveGroupName(psFilterNode->psRightNode, groupList);
}
}
/************************************************************************/
/* FLTPreParseFilterForAliasAndGroup */
/* */
/* Utility function to replace aliased' and grouped attributes */
/* with their internal name. */
/************************************************************************/
void FLTPreParseFilterForAliasAndGroup(FilterEncodingNode *psFilterNode,
mapObj *map, int i, const char *namespaces)
{
layerObj *lp=NULL;
char szTmp[256];
const char *pszFullName = NULL;
int layerWasOpened = MS_FALSE;
#if defined(USE_WMS_SVR) || defined (USE_WFS_SVR) || defined (USE_WCS_SVR) || defined(USE_SOS_SVR)
if (psFilterNode && map && i>=0 && i<map->numlayers) {
/*strip name spaces before hand*/
FLTStripNameSpacesFromPropertyName(psFilterNode);
lp = GET_LAYER(map, i);
layerWasOpened = msLayerIsOpen(lp);
if (msLayerOpen(lp) == MS_SUCCESS && msLayerGetItems(lp) == MS_SUCCESS) {
/* Remove group names from property names if using groupname/itemname syntax */
gmlGroupListObj* groupList = msGMLGetGroups(lp, namespaces);
if( groupList && groupList->numgroups > 0 )
FLTRemoveGroupName(psFilterNode, groupList);
msGMLFreeGroups(groupList);
for(i=0; i<lp->numitems; i++) {
if (!lp->items[i] || strlen(lp->items[i]) <= 0)
continue;
snprintf(szTmp, sizeof(szTmp), "%s_alias", lp->items[i]);
pszFullName = msOWSLookupMetadata(&(lp->metadata), namespaces, szTmp);
if (pszFullName) {
FLTReplacePropertyName(psFilterNode, pszFullName,
lp->items[i]);
}
}
if (!layerWasOpened) /* do not close the layer if it has been opened somewhere else (paging?) */
msLayerClose(lp);
}
}
#else
msSetError(MS_MISCERR, "OWS support is not available.",
"FLTPreParseFilterForAlias()");
#endif
}
/************************************************************************/
/* FLTCheckFeatureIdFilters */
/* */
/* Check that FeatureId filters match features in the active */
/* layer. */
/************************************************************************/
int FLTCheckFeatureIdFilters(FilterEncodingNode *psFilterNode,
mapObj *map, int i)
{
int status = MS_SUCCESS;
if (psFilterNode->eType == FILTER_NODE_TYPE_FEATUREID)
{
char** tokens;
int nTokens = 0;
layerObj* lp;
int j;
lp = GET_LAYER(map, i);
tokens = msStringSplit(psFilterNode->pszValue,',', &nTokens);
for (j=0; j<nTokens; j++) {
const char* pszId = tokens[j];
const char* pszDot = strchr(pszId, '.');
if( pszDot )
{
if( pszDot - pszId != strlen(lp->name) ||
strncasecmp(pszId, lp->name, strlen(lp->name)) != 0 )
{
msSetError(MS_MISCERR, "Feature id %s not consistent with feature type name %s.",
"FLTPreParseFilterForAlias()", pszId, lp->name);
status = MS_FAILURE;
break;
}
}
}
msFreeCharArray(tokens, nTokens);
}
if (psFilterNode->psLeftNode)
{
status = FLTCheckFeatureIdFilters(psFilterNode->psLeftNode, map, i);
if( status == MS_SUCCESS )
{
if (psFilterNode->psRightNode)
status = FLTCheckFeatureIdFilters(psFilterNode->psRightNode, map, i);
}
}
return status;
}
/************************************************************************/
/* FLTCheckInvalidOperand */
/* */
/* Check that the operand of a comparison operator is valid */
/* Currently only detects use of boundedBy in a binary comparison */
/************************************************************************/
int FLTCheckInvalidOperand(FilterEncodingNode *psFilterNode)
{
int status = MS_SUCCESS;
if (psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON &&
psFilterNode->psLeftNode != NULL &&
psFilterNode->psLeftNode->eType == FILTER_NODE_TYPE_PROPERTYNAME)
{
if( strcmp(psFilterNode->psLeftNode->pszValue, "gml:boundedBy") == 0 &&
strcmp(psFilterNode->pszValue, "PropertyIsNull") != 0 &&
strcmp(psFilterNode->pszValue, "PropertyIsNil") != 0 )
{
msSetError(MS_MISCERR, "Operand '%s' is invalid in comparison.",
"FLTCheckInvalidOperand()", psFilterNode->psLeftNode->pszValue);
return MS_FAILURE;
}
}
if (psFilterNode->psLeftNode)
{
status = FLTCheckInvalidOperand(psFilterNode->psLeftNode);
if( status == MS_SUCCESS )
{
if (psFilterNode->psRightNode)
status = FLTCheckInvalidOperand(psFilterNode->psRightNode);
}
}
return status;
}
/************************************************************************/
/* FLTProcessPropertyIsNull */
/* */
/* HACK for PropertyIsNull processing. PostGIS & Spatialite only */
/* for now. */
/************************************************************************/
int FLTProcessPropertyIsNull(FilterEncodingNode *psFilterNode,
mapObj *map, int i)
{
int status = MS_SUCCESS;
if (psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON &&
psFilterNode->psLeftNode != NULL &&
psFilterNode->psLeftNode->eType == FILTER_NODE_TYPE_PROPERTYNAME &&
strcmp(psFilterNode->pszValue, "PropertyIsNull") == 0 &&
!FLTIsGMLDefaultProperty(psFilterNode->psLeftNode->pszValue) )
{
layerObj* lp;
int layerWasOpened;
lp = GET_LAYER(map, i);
layerWasOpened = msLayerIsOpen(lp);
/* Horrible HACK to compensate for the lack of null testing in MapServer */
if( (lp->connectiontype == MS_POSTGIS ||
(lp->connectiontype == MS_OGR && msOGRIsSpatialite(lp))) &&
strcmp(psFilterNode->pszValue, "PropertyIsNull") == 0 )
{
msFree(psFilterNode->pszValue);
psFilterNode->pszValue = msStrdup("PropertyIsEqualTo");
psFilterNode->psRightNode = FLTCreateBinaryCompFilterEncodingNode();
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_LITERAL;
psFilterNode->psRightNode->pszValue = msStrdup("_MAPSERVER_NULL_");
}
if (!layerWasOpened) /* do not close the layer if it has been opened somewhere else (paging?) */
msLayerClose(lp);
}
if (psFilterNode->psLeftNode)
{
status = FLTProcessPropertyIsNull(psFilterNode->psLeftNode, map, i);
if( status == MS_SUCCESS )
{
if (psFilterNode->psRightNode)
status = FLTProcessPropertyIsNull(psFilterNode->psRightNode, map, i);
}
}
return status;
}
/************************************************************************/
/* FLTCheckInvalidProperty */
/* */
/* Check that property names are known */
/************************************************************************/
int FLTCheckInvalidProperty(FilterEncodingNode *psFilterNode,
mapObj *map, int i)
{
int status = MS_SUCCESS;
if (psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON &&
psFilterNode->psLeftNode != NULL &&
psFilterNode->psLeftNode->eType == FILTER_NODE_TYPE_PROPERTYNAME)
{
layerObj* lp;
int layerWasOpened;
int bFound = MS_FALSE;
if ((strcmp(psFilterNode->pszValue, "PropertyIsNull") == 0 ||
strcmp(psFilterNode->pszValue, "PropertyIsNil") == 0) &&
FLTIsGMLDefaultProperty(psFilterNode->psLeftNode->pszValue) )
{
return MS_SUCCESS;
}
lp = GET_LAYER(map, i);
layerWasOpened = msLayerIsOpen(lp);
if ((layerWasOpened || msLayerOpen(lp) == MS_SUCCESS)
&& msLayerGetItems(lp) == MS_SUCCESS) {
int i;
gmlItemListObj* items = msGMLGetItems(lp, "G");
for(i=0; i<items->numitems; i++) {
if (!items->items[i].name || strlen(items->items[i].name) <= 0 ||
!items->items[i].visible)
continue;
if (strcasecmp(items->items[i].name, psFilterNode->psLeftNode->pszValue) == 0) {
bFound = MS_TRUE;
break;
}
}
msGMLFreeItems(items);
}
if (!layerWasOpened) /* do not close the layer if it has been opened somewhere else (paging?) */
msLayerClose(lp);
if( !bFound )
{
msSetError(MS_MISCERR, "Property '%s' is unknown.",
"FLTCheckInvalidProperty()", psFilterNode->psLeftNode->pszValue);
return MS_FAILURE;
}
}
if (psFilterNode->psLeftNode)
{
status = FLTCheckInvalidProperty(psFilterNode->psLeftNode, map, i);
if( status == MS_SUCCESS )
{
if (psFilterNode->psRightNode)
status = FLTCheckInvalidProperty(psFilterNode->psRightNode, map, i);
}
}
return status;
}
/************************************************************************/
/* FLTSimplify */
/* */
/* Simplify the expression by removing parts that evaluate to */
/* constants. */
/* The passed psFilterNode is potentially consumed by the function */
/* and replaced by the returned value. */
/* If the function returns NULL, *pnEvaluation = MS_FALSE means */
/* that the filter evaluates to FALSE, or MS_TRUE that it */
/* evaluates to TRUE */
/************************************************************************/
FilterEncodingNode* FLTSimplify(FilterEncodingNode *psFilterNode,
int* pnEvaluation)
{
*pnEvaluation = -1;
/* There are no nullable or nillable property in WFS currently */
/* except gml:name or gml:description that are null */
if( psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON &&
(strcmp(psFilterNode->pszValue, "PropertyIsNull") == 0 ||
strcmp(psFilterNode->pszValue, "PropertyIsNil") == 0 ) &&
psFilterNode->psLeftNode != NULL &&
psFilterNode->psLeftNode->eType == FILTER_NODE_TYPE_PROPERTYNAME )
{
if( strcmp(psFilterNode->pszValue, "PropertyIsNull") == 0 &&
FLTIsGMLDefaultProperty(psFilterNode->psLeftNode->pszValue) &&
strcmp(psFilterNode->psLeftNode->pszValue, "@gml:id") != 0 &&
strcmp(psFilterNode->psLeftNode->pszValue, "gml:boundedBy") != 0)
*pnEvaluation = MS_TRUE;
else
*pnEvaluation = MS_FALSE;
FLTFreeFilterEncodingNode(psFilterNode);
return NULL;
}
if( psFilterNode->eType == FILTER_NODE_TYPE_LOGICAL &&
strcasecmp(psFilterNode->pszValue, "NOT") == 0 &&
psFilterNode->psLeftNode != NULL )
{
int nEvaluation;
psFilterNode->psLeftNode = FLTSimplify(psFilterNode->psLeftNode,
&nEvaluation);
if( psFilterNode->psLeftNode == NULL )
{
*pnEvaluation = 1 - nEvaluation;
FLTFreeFilterEncodingNode(psFilterNode);
return NULL;
}
}
if( psFilterNode->eType == FILTER_NODE_TYPE_LOGICAL &&
(strcasecmp(psFilterNode->pszValue, "AND") == 0 ||
strcasecmp(psFilterNode->pszValue, "OR") == 0) &&
psFilterNode->psLeftNode != NULL &&
psFilterNode->psRightNode != NULL )
{
FilterEncodingNode* psOtherNode;
int nEvaluation;
int nExpectedValForFastExit;
psFilterNode->psLeftNode = FLTSimplify(psFilterNode->psLeftNode,
&nEvaluation);
if( strcasecmp(psFilterNode->pszValue, "AND") == 0 )
nExpectedValForFastExit = MS_FALSE;
else
nExpectedValForFastExit = MS_TRUE;
if( psFilterNode->psLeftNode == NULL )
{
if( nEvaluation == nExpectedValForFastExit )
{
*pnEvaluation = nEvaluation;
FLTFreeFilterEncodingNode(psFilterNode);
return NULL;
}
psOtherNode = psFilterNode->psRightNode;
psFilterNode->psRightNode = NULL;
FLTFreeFilterEncodingNode(psFilterNode);
return FLTSimplify(psOtherNode, pnEvaluation);
}
psFilterNode->psRightNode = FLTSimplify(psFilterNode->psRightNode,
&nEvaluation);
if( psFilterNode->psRightNode == NULL )
{
if( nEvaluation == nExpectedValForFastExit )
{
*pnEvaluation = nEvaluation;
FLTFreeFilterEncodingNode(psFilterNode);
return NULL;
}
psOtherNode = psFilterNode->psLeftNode;
psFilterNode->psLeftNode = NULL;
FLTFreeFilterEncodingNode(psFilterNode);
return FLTSimplify(psOtherNode, pnEvaluation);
}
}
return psFilterNode;
}
#ifdef USE_LIBXML2
xmlNodePtr FLTGetCapabilities(xmlNsPtr psNsParent, xmlNsPtr psNsOgc, int bTemporal)
{
xmlNodePtr psRootNode = NULL, psNode = NULL, psSubNode = NULL, psSubSubNode = NULL;
psRootNode = xmlNewNode(psNsParent, BAD_CAST "Filter_Capabilities");
psNode = xmlNewChild(psRootNode, psNsOgc, BAD_CAST "Spatial_Capabilities", NULL);
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "GeometryOperands", NULL);
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "GeometryOperand", BAD_CAST "gml:Point");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "GeometryOperand", BAD_CAST "gml:LineString");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "GeometryOperand", BAD_CAST "gml:Polygon");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "GeometryOperand", BAD_CAST "gml:Envelope");
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "SpatialOperators", NULL);
#ifdef USE_GEOS
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Equals");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Disjoint");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Touches");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Within");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Overlaps");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Crosses");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Intersects");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Contains");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "DWithin");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Beyond");
#endif
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "BBOX");
if (bTemporal) {
psNode = xmlNewChild(psRootNode, psNsOgc, BAD_CAST "Temporal_Capabilities", NULL);
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "TemporalOperands", NULL);
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "TemporalOperand", BAD_CAST "gml:TimePeriod");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "TemporalOperand", BAD_CAST "gml:TimeInstant");
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "TemporalOperators", NULL);
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "TemporalOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "TM_Equals");
}
psNode = xmlNewChild(psRootNode, psNsOgc, BAD_CAST "Scalar_Capabilities", NULL);
xmlNewChild(psNode, psNsOgc, BAD_CAST "LogicalOperators", NULL);
psNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperators", NULL);
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "LessThan");
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "GreaterThan");
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "LessThanEqualTo");
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "GreaterThanEqualTo");
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "EqualTo");
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "NotEqualTo");
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "Like");
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "Between");
psNode = xmlNewChild(psRootNode, psNsOgc, BAD_CAST "Id_Capabilities", NULL);
xmlNewChild(psNode, psNsOgc, BAD_CAST "EID", NULL);
xmlNewChild(psNode, psNsOgc, BAD_CAST "FID", NULL);
return psRootNode;
}
#endif
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3111_0 |
crossvul-cpp_data_good_5513_0 |
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "gd.h"
#include "gdhelpers.h"
#include "php.h"
#ifdef _MSC_VER
# if _MSC_VER >= 1300
/* in MSVC.NET these are available but only for __cplusplus and not _MSC_EXTENSIONS */
# if !defined(_MSC_EXTENSIONS) && defined(__cplusplus)
# define HAVE_FABSF 1
extern float fabsf(float x);
# define HAVE_FLOORF 1
extern float floorf(float x);
# endif /*MSVC.NET */
# endif /* MSC */
#endif
#ifndef HAVE_FABSF
# define HAVE_FABSF 0
#endif
#ifndef HAVE_FLOORF
# define HAVE_FLOORF 0
#endif
#if HAVE_FABSF == 0
/* float fabsf(float x); */
# ifndef fabsf
# define fabsf(x) ((float)(fabs(x)))
# endif
#endif
#if HAVE_FLOORF == 0
# ifndef floorf
/* float floorf(float x);*/
# define floorf(x) ((float)(floor(x)))
# endif
#endif
#ifdef _OSD_POSIX /* BS2000 uses the EBCDIC char set instead of ASCII */
#define CHARSET_EBCDIC
#define __attribute__(any) /*nothing */
#endif
/*_OSD_POSIX*/
#ifndef CHARSET_EBCDIC
#define ASC(ch) ch
#else /*CHARSET_EBCDIC */
#define ASC(ch) gd_toascii[(unsigned char)ch]
static const unsigned char gd_toascii[256] =
{
/*00 */ 0x00, 0x01, 0x02, 0x03, 0x85, 0x09, 0x86, 0x7f,
0x87, 0x8d, 0x8e, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /*................ */
/*10 */ 0x10, 0x11, 0x12, 0x13, 0x8f, 0x0a, 0x08, 0x97,
0x18, 0x19, 0x9c, 0x9d, 0x1c, 0x1d, 0x1e, 0x1f, /*................ */
/*20 */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x92, 0x17, 0x1b,
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x05, 0x06, 0x07, /*................ */
/*30 */ 0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04,
0x98, 0x99, 0x9a, 0x9b, 0x14, 0x15, 0x9e, 0x1a, /*................ */
/*40 */ 0x20, 0xa0, 0xe2, 0xe4, 0xe0, 0xe1, 0xe3, 0xe5,
0xe7, 0xf1, 0x60, 0x2e, 0x3c, 0x28, 0x2b, 0x7c, /* .........`.<(+| */
/*50 */ 0x26, 0xe9, 0xea, 0xeb, 0xe8, 0xed, 0xee, 0xef,
0xec, 0xdf, 0x21, 0x24, 0x2a, 0x29, 0x3b, 0x9f, /*&.........!$*);. */
/*60 */ 0x2d, 0x2f, 0xc2, 0xc4, 0xc0, 0xc1, 0xc3, 0xc5,
0xc7, 0xd1, 0x5e, 0x2c, 0x25, 0x5f, 0x3e, 0x3f,
/*-/........^,%_>?*/
/*70 */ 0xf8, 0xc9, 0xca, 0xcb, 0xc8, 0xcd, 0xce, 0xcf,
0xcc, 0xa8, 0x3a, 0x23, 0x40, 0x27, 0x3d, 0x22, /*..........:#@'=" */
/*80 */ 0xd8, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
0x68, 0x69, 0xab, 0xbb, 0xf0, 0xfd, 0xfe, 0xb1, /*.abcdefghi...... */
/*90 */ 0xb0, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,
0x71, 0x72, 0xaa, 0xba, 0xe6, 0xb8, 0xc6, 0xa4, /*.jklmnopqr...... */
/*a0 */ 0xb5, 0xaf, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
0x79, 0x7a, 0xa1, 0xbf, 0xd0, 0xdd, 0xde, 0xae, /*..stuvwxyz...... */
/*b0 */ 0xa2, 0xa3, 0xa5, 0xb7, 0xa9, 0xa7, 0xb6, 0xbc,
0xbd, 0xbe, 0xac, 0x5b, 0x5c, 0x5d, 0xb4, 0xd7, /*...........[\].. */
/*c0 */ 0xf9, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
0x48, 0x49, 0xad, 0xf4, 0xf6, 0xf2, 0xf3, 0xf5, /*.ABCDEFGHI...... */
/*d0 */ 0xa6, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50,
0x51, 0x52, 0xb9, 0xfb, 0xfc, 0xdb, 0xfa, 0xff, /*.JKLMNOPQR...... */
/*e0 */ 0xd9, 0xf7, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
0x59, 0x5a, 0xb2, 0xd4, 0xd6, 0xd2, 0xd3, 0xd5, /*..STUVWXYZ...... */
/*f0 */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0xb3, 0x7b, 0xdc, 0x7d, 0xda, 0x7e /*0123456789.{.}.~ */
};
#endif /*CHARSET_EBCDIC */
/* 2.0.10: cast instead of floor() yields 35% performance improvement. Thanks to John Buckman. */
#define floor_cast(exp) ((long) exp)
extern int gdCosT[];
extern int gdSinT[];
static void gdImageBrushApply(gdImagePtr im, int x, int y);
static void gdImageTileApply(gdImagePtr im, int x, int y);
static void gdImageAntiAliasedApply(gdImagePtr im, int x, int y);
static int gdLayerOverlay(int dst, int src);
static int gdAlphaOverlayColor(int src, int dst, int max);
int gdImageGetTrueColorPixel(gdImagePtr im, int x, int y);
void php_gd_error_ex(int type, const char *format, ...)
{
va_list args;
TSRMLS_FETCH();
va_start(args, format);
php_verror(NULL, "", type, format, args TSRMLS_CC);
va_end(args);
}
void php_gd_error(const char *format, ...)
{
va_list args;
TSRMLS_FETCH();
va_start(args, format);
php_verror(NULL, "", E_WARNING, format, args TSRMLS_CC);
va_end(args);
}
gdImagePtr gdImageCreate (int sx, int sy)
{
int i;
gdImagePtr im;
if (overflow2(sx, sy)) {
return NULL;
}
if (overflow2(sizeof(unsigned char *), sy)) {
return NULL;
}
if (overflow2(sizeof(unsigned char *), sx)) {
return NULL;
}
im = (gdImage *) gdCalloc(1, sizeof(gdImage));
/* Row-major ever since gd 1.3 */
im->pixels = (unsigned char **) gdMalloc(sizeof(unsigned char *) * sy);
im->AA_opacity = (unsigned char **) gdMalloc(sizeof(unsigned char *) * sy);
im->polyInts = 0;
im->polyAllocated = 0;
im->brush = 0;
im->tile = 0;
im->style = 0;
for (i = 0; i < sy; i++) {
/* Row-major ever since gd 1.3 */
im->pixels[i] = (unsigned char *) gdCalloc(sx, sizeof(unsigned char));
im->AA_opacity[i] = (unsigned char *) gdCalloc(sx, sizeof(unsigned char));
}
im->sx = sx;
im->sy = sy;
im->colorsTotal = 0;
im->transparent = (-1);
im->interlace = 0;
im->thick = 1;
im->AA = 0;
im->AA_polygon = 0;
for (i = 0; i < gdMaxColors; i++) {
im->open[i] = 1;
im->red[i] = 0;
im->green[i] = 0;
im->blue[i] = 0;
}
im->trueColor = 0;
im->tpixels = 0;
im->cx1 = 0;
im->cy1 = 0;
im->cx2 = im->sx - 1;
im->cy2 = im->sy - 1;
im->interpolation = NULL;
im->interpolation_id = GD_BILINEAR_FIXED;
return im;
}
gdImagePtr gdImageCreateTrueColor (int sx, int sy)
{
int i;
gdImagePtr im;
if (overflow2(sx, sy)) {
return NULL;
}
if (overflow2(sizeof(unsigned char *), sy)) {
return NULL;
}
if (overflow2(sizeof(int *), sx)) {
return NULL;
}
im = (gdImage *) gdMalloc(sizeof(gdImage));
memset(im, 0, sizeof(gdImage));
im->tpixels = (int **) gdMalloc(sizeof(int *) * sy);
im->AA_opacity = (unsigned char **) gdMalloc(sizeof(unsigned char *) * sy);
im->polyInts = 0;
im->polyAllocated = 0;
im->brush = 0;
im->tile = 0;
im->style = 0;
for (i = 0; i < sy; i++) {
im->tpixels[i] = (int *) gdCalloc(sx, sizeof(int));
im->AA_opacity[i] = (unsigned char *) gdCalloc(sx, sizeof(unsigned char));
}
im->sx = sx;
im->sy = sy;
im->transparent = (-1);
im->interlace = 0;
im->trueColor = 1;
/* 2.0.2: alpha blending is now on by default, and saving of alpha is
* off by default. This allows font antialiasing to work as expected
* on the first try in JPEGs -- quite important -- and also allows
* for smaller PNGs when saving of alpha channel is not really
* desired, which it usually isn't!
*/
im->saveAlphaFlag = 0;
im->alphaBlendingFlag = 1;
im->thick = 1;
im->AA = 0;
im->AA_polygon = 0;
im->cx1 = 0;
im->cy1 = 0;
im->cx2 = im->sx - 1;
im->cy2 = im->sy - 1;
im->interpolation = NULL;
im->interpolation_id = GD_BILINEAR_FIXED;
return im;
}
void gdImageDestroy (gdImagePtr im)
{
int i;
if (im->pixels) {
for (i = 0; i < im->sy; i++) {
gdFree(im->pixels[i]);
}
gdFree(im->pixels);
}
if (im->tpixels) {
for (i = 0; i < im->sy; i++) {
gdFree(im->tpixels[i]);
}
gdFree(im->tpixels);
}
if (im->AA_opacity) {
for (i = 0; i < im->sy; i++) {
gdFree(im->AA_opacity[i]);
}
gdFree(im->AA_opacity);
}
if (im->polyInts) {
gdFree(im->polyInts);
}
if (im->style) {
gdFree(im->style);
}
gdFree(im);
}
int gdImageColorClosest (gdImagePtr im, int r, int g, int b)
{
return gdImageColorClosestAlpha (im, r, g, b, gdAlphaOpaque);
}
int gdImageColorClosestAlpha (gdImagePtr im, int r, int g, int b, int a)
{
int i;
long rd, gd, bd, ad;
int ct = (-1);
int first = 1;
long mindist = 0;
if (im->trueColor) {
return gdTrueColorAlpha(r, g, b, a);
}
for (i = 0; i < im->colorsTotal; i++) {
long dist;
if (im->open[i]) {
continue;
}
rd = im->red[i] - r;
gd = im->green[i] - g;
bd = im->blue[i] - b;
/* gd 2.02: whoops, was - b (thanks to David Marwood) */
ad = im->alpha[i] - a;
dist = rd * rd + gd * gd + bd * bd + ad * ad;
if (first || (dist < mindist)) {
mindist = dist;
ct = i;
first = 0;
}
}
return ct;
}
/* This code is taken from http://www.acm.org/jgt/papers/SmithLyons96/hwb_rgb.html, an article
* on colour conversion to/from RBG and HWB colour systems.
* It has been modified to return the converted value as a * parameter.
*/
#define RETURN_HWB(h, w, b) {HWB->H = h; HWB->W = w; HWB->B = b; return HWB;}
#define RETURN_RGB(r, g, b) {RGB->R = r; RGB->G = g; RGB->B = b; return RGB;}
#define HWB_UNDEFINED -1
#define SETUP_RGB(s, r, g, b) {s.R = r/255.0f; s.G = g/255.0f; s.B = b/255.0f;}
#ifndef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#endif
#define MIN3(a,b,c) ((a)<(b)?(MIN(a,c)):(MIN(b,c)))
#ifndef MAX
#define MAX(a,b) ((a)<(b)?(b):(a))
#endif
#define MAX3(a,b,c) ((a)<(b)?(MAX(b,c)):(MAX(a,c)))
/*
* Theoretically, hue 0 (pure red) is identical to hue 6 in these transforms. Pure
* red always maps to 6 in this implementation. Therefore UNDEFINED can be
* defined as 0 in situations where only unsigned numbers are desired.
*/
typedef struct
{
float R, G, B;
}
RGBType;
typedef struct
{
float H, W, B;
}
HWBType;
static HWBType * RGB_to_HWB (RGBType RGB, HWBType * HWB)
{
/*
* RGB are each on [0, 1]. W and B are returned on [0, 1] and H is
* returned on [0, 6]. Exception: H is returned UNDEFINED if W == 1 - B.
*/
float R = RGB.R, G = RGB.G, B = RGB.B, w, v, b, f;
int i;
w = MIN3 (R, G, B);
v = MAX3 (R, G, B);
b = 1 - v;
if (v == w) {
RETURN_HWB(HWB_UNDEFINED, w, b);
}
f = (R == w) ? G - B : ((G == w) ? B - R : R - G);
i = (R == w) ? 3 : ((G == w) ? 5 : 1);
RETURN_HWB(i - f / (v - w), w, b);
}
static float HWB_Diff (int r1, int g1, int b1, int r2, int g2, int b2)
{
RGBType RGB1, RGB2;
HWBType HWB1, HWB2;
float diff;
SETUP_RGB(RGB1, r1, g1, b1);
SETUP_RGB(RGB2, r2, g2, b2);
RGB_to_HWB(RGB1, &HWB1);
RGB_to_HWB(RGB2, &HWB2);
/*
* I made this bit up; it seems to produce OK results, and it is certainly
* more visually correct than the current RGB metric. (PJW)
*/
if ((HWB1.H == HWB_UNDEFINED) || (HWB2.H == HWB_UNDEFINED)) {
diff = 0.0f; /* Undefined hues always match... */
} else {
diff = fabsf(HWB1.H - HWB2.H);
if (diff > 3.0f) {
diff = 6.0f - diff; /* Remember, it's a colour circle */
}
}
diff = diff * diff + (HWB1.W - HWB2.W) * (HWB1.W - HWB2.W) + (HWB1.B - HWB2.B) * (HWB1.B - HWB2.B);
return diff;
}
#if 0
/*
* This is not actually used, but is here for completeness, in case someone wants to
* use the HWB stuff for anything else...
*/
static RGBType * HWB_to_RGB (HWBType HWB, RGBType * RGB)
{
/*
* H is given on [0, 6] or UNDEFINED. W and B are given on [0, 1].
* RGB are each returned on [0, 1].
*/
float h = HWB.H, w = HWB.W, b = HWB.B, v, n, f;
int i;
v = 1 - b;
if (h == HWB_UNDEFINED) {
RETURN_RGB(v, v, v);
}
i = floor(h);
f = h - i;
if (i & 1) {
f = 1 - f; /* if i is odd */
}
n = w + f * (v - w); /* linear interpolation between w and v */
switch (i) {
case 6:
case 0:
RETURN_RGB(v, n, w);
case 1:
RETURN_RGB(n, v, w);
case 2:
RETURN_RGB(w, v, n);
case 3:
RETURN_RGB(w, n, v);
case 4:
RETURN_RGB(n, w, v);
case 5:
RETURN_RGB(v, w, n);
}
return RGB;
}
#endif
int gdImageColorClosestHWB (gdImagePtr im, int r, int g, int b)
{
int i;
/* long rd, gd, bd; */
int ct = (-1);
int first = 1;
float mindist = 0;
if (im->trueColor) {
return gdTrueColor(r, g, b);
}
for (i = 0; i < im->colorsTotal; i++) {
float dist;
if (im->open[i]) {
continue;
}
dist = HWB_Diff(im->red[i], im->green[i], im->blue[i], r, g, b);
if (first || (dist < mindist)) {
mindist = dist;
ct = i;
first = 0;
}
}
return ct;
}
int gdImageColorExact (gdImagePtr im, int r, int g, int b)
{
return gdImageColorExactAlpha (im, r, g, b, gdAlphaOpaque);
}
int gdImageColorExactAlpha (gdImagePtr im, int r, int g, int b, int a)
{
int i;
if (im->trueColor) {
return gdTrueColorAlpha(r, g, b, a);
}
for (i = 0; i < im->colorsTotal; i++) {
if (im->open[i]) {
continue;
}
if ((im->red[i] == r) && (im->green[i] == g) && (im->blue[i] == b) && (im->alpha[i] == a)) {
return i;
}
}
return -1;
}
int gdImageColorAllocate (gdImagePtr im, int r, int g, int b)
{
return gdImageColorAllocateAlpha (im, r, g, b, gdAlphaOpaque);
}
int gdImageColorAllocateAlpha (gdImagePtr im, int r, int g, int b, int a)
{
int i;
int ct = (-1);
if (im->trueColor) {
return gdTrueColorAlpha(r, g, b, a);
}
for (i = 0; i < im->colorsTotal; i++) {
if (im->open[i]) {
ct = i;
break;
}
}
if (ct == (-1)) {
ct = im->colorsTotal;
if (ct == gdMaxColors) {
return -1;
}
im->colorsTotal++;
}
im->red[ct] = r;
im->green[ct] = g;
im->blue[ct] = b;
im->alpha[ct] = a;
im->open[ct] = 0;
return ct;
}
/*
* gdImageColorResolve is an alternative for the code fragment:
*
* if ((color=gdImageColorExact(im,R,G,B)) < 0)
* if ((color=gdImageColorAllocate(im,R,G,B)) < 0)
* color=gdImageColorClosest(im,R,G,B);
*
* in a single function. Its advantage is that it is guaranteed to
* return a color index in one search over the color table.
*/
int gdImageColorResolve (gdImagePtr im, int r, int g, int b)
{
return gdImageColorResolveAlpha(im, r, g, b, gdAlphaOpaque);
}
int gdImageColorResolveAlpha (gdImagePtr im, int r, int g, int b, int a)
{
int c;
int ct = -1;
int op = -1;
long rd, gd, bd, ad, dist;
long mindist = 4 * 255 * 255; /* init to max poss dist */
if (im->trueColor)
{
return gdTrueColorAlpha (r, g, b, a);
}
for (c = 0; c < im->colorsTotal; c++)
{
if (im->open[c])
{
op = c; /* Save open slot */
continue; /* Color not in use */
}
if (c == im->transparent)
{
/* don't ever resolve to the color that has
* been designated as the transparent color */
continue;
}
rd = (long) (im->red[c] - r);
gd = (long) (im->green[c] - g);
bd = (long) (im->blue[c] - b);
ad = (long) (im->alpha[c] - a);
dist = rd * rd + gd * gd + bd * bd + ad * ad;
if (dist < mindist)
{
if (dist == 0)
{
return c; /* Return exact match color */
}
mindist = dist;
ct = c;
}
}
/* no exact match. We now know closest, but first try to allocate exact */
if (op == -1)
{
op = im->colorsTotal;
if (op == gdMaxColors)
{ /* No room for more colors */
return ct; /* Return closest available color */
}
im->colorsTotal++;
}
im->red[op] = r;
im->green[op] = g;
im->blue[op] = b;
im->alpha[op] = a;
im->open[op] = 0;
return op; /* Return newly allocated color */
}
void gdImageColorDeallocate (gdImagePtr im, int color)
{
if (im->trueColor) {
return;
}
/* Mark it open. */
im->open[color] = 1;
}
void gdImageColorTransparent (gdImagePtr im, int color)
{
if (color < 0) {
return;
}
if (!im->trueColor) {
if((color >= im->colorsTotal)) {
return;
}
/* Make the old transparent color opaque again */
if (im->transparent != -1) {
im->alpha[im->transparent] = gdAlphaOpaque;
}
im->alpha[color] = gdAlphaTransparent;
}
im->transparent = color;
}
void gdImagePaletteCopy (gdImagePtr to, gdImagePtr from)
{
int i;
int x, y, p;
int xlate[256];
if (to->trueColor || from->trueColor) {
return;
}
for (i = 0; i < 256; i++) {
xlate[i] = -1;
}
for (y = 0; y < to->sy; y++) {
for (x = 0; x < to->sx; x++) {
p = gdImageGetPixel(to, x, y);
if (xlate[p] == -1) {
/* This ought to use HWB, but we don't have an alpha-aware version of that yet. */
xlate[p] = gdImageColorClosestAlpha (from, to->red[p], to->green[p], to->blue[p], to->alpha[p]);
}
gdImageSetPixel(to, x, y, xlate[p]);
}
}
for (i = 0; i < from->colorsTotal; i++) {
to->red[i] = from->red[i];
to->blue[i] = from->blue[i];
to->green[i] = from->green[i];
to->alpha[i] = from->alpha[i];
to->open[i] = 0;
}
for (i = from->colorsTotal; i < to->colorsTotal; i++) {
to->open[i] = 1;
}
to->colorsTotal = from->colorsTotal;
}
/* 2.0.10: before the drawing routines, some code to clip points that are
* outside the drawing window. Nick Atty (nick@canalplan.org.uk)
*
* This is the Sutherland Hodgman Algorithm, as implemented by
* Duvanenko, Robbins and Gyurcsik - SH(DRG) for short. See Dr Dobb's
* Journal, January 1996, pp107-110 and 116-117
*
* Given the end points of a line, and a bounding rectangle (which we
* know to be from (0,0) to (SX,SY)), adjust the endpoints to be on
* the edges of the rectangle if the line should be drawn at all,
* otherwise return a failure code
*/
/* this does "one-dimensional" clipping: note that the second time it
* is called, all the x parameters refer to height and the y to width
* - the comments ignore this (if you can understand it when it's
* looking at the X parameters, it should become clear what happens on
* the second call!) The code is simplified from that in the article,
* as we know that gd images always start at (0,0)
*/
static int clip_1d(int *x0, int *y0, int *x1, int *y1, int maxdim) {
double m; /* gradient of line */
if (*x0 < 0) { /* start of line is left of window */
if(*x1 < 0) { /* as is the end, so the line never cuts the window */
return 0;
}
m = (*y1 - *y0)/(double)(*x1 - *x0); /* calculate the slope of the line */
/* adjust x0 to be on the left boundary (ie to be zero), and y0 to match */
*y0 -= (int)(m * *x0);
*x0 = 0;
/* now, perhaps, adjust the far end of the line as well */
if (*x1 > maxdim) {
*y1 += (int)(m * (maxdim - *x1));
*x1 = maxdim;
}
return 1;
}
if (*x0 > maxdim) { /* start of line is right of window - complement of above */
if (*x1 > maxdim) { /* as is the end, so the line misses the window */
return 0;
}
m = (*y1 - *y0)/(double)(*x1 - *x0); /* calculate the slope of the line */
*y0 += (int)(m * (maxdim - *x0)); /* adjust so point is on the right boundary */
*x0 = maxdim;
/* now, perhaps, adjust the end of the line */
if (*x1 < 0) {
*y1 -= (int)(m * *x1);
*x1 = 0;
}
return 1;
}
/* the final case - the start of the line is inside the window */
if (*x1 > maxdim) { /* other end is outside to the right */
m = (*y1 - *y0)/(double)(*x1 - *x0); /* calculate the slope of the line */
*y1 += (int)(m * (maxdim - *x1));
*x1 = maxdim;
return 1;
}
if (*x1 < 0) { /* other end is outside to the left */
m = (*y1 - *y0)/(double)(*x1 - *x0); /* calculate the slope of the line */
*y1 -= (int)(m * *x1);
*x1 = 0;
return 1;
}
/* only get here if both points are inside the window */
return 1;
}
void gdImageSetPixel (gdImagePtr im, int x, int y, int color)
{
int p;
switch (color) {
case gdStyled:
if (!im->style) {
/* Refuse to draw if no style is set. */
return;
} else {
p = im->style[im->stylePos++];
}
if (p != gdTransparent) {
gdImageSetPixel(im, x, y, p);
}
im->stylePos = im->stylePos % im->styleLength;
break;
case gdStyledBrushed:
if (!im->style) {
/* Refuse to draw if no style is set. */
return;
}
p = im->style[im->stylePos++];
if (p != gdTransparent && p != 0) {
gdImageSetPixel(im, x, y, gdBrushed);
}
im->stylePos = im->stylePos % im->styleLength;
break;
case gdBrushed:
gdImageBrushApply(im, x, y);
break;
case gdTiled:
gdImageTileApply(im, x, y);
break;
case gdAntiAliased:
gdImageAntiAliasedApply(im, x, y);
break;
default:
if (gdImageBoundsSafe(im, x, y)) {
if (im->trueColor) {
switch (im->alphaBlendingFlag) {
default:
case gdEffectReplace:
im->tpixels[y][x] = color;
break;
case gdEffectAlphaBlend:
im->tpixels[y][x] = gdAlphaBlend(im->tpixels[y][x], color);
break;
case gdEffectNormal:
im->tpixels[y][x] = gdAlphaBlend(im->tpixels[y][x], color);
break;
case gdEffectOverlay :
im->tpixels[y][x] = gdLayerOverlay(im->tpixels[y][x], color);
break;
}
} else {
im->pixels[y][x] = color;
}
}
break;
}
}
int gdImageGetTrueColorPixel (gdImagePtr im, int x, int y)
{
int p = gdImageGetPixel(im, x, y);
if (!im->trueColor) {
return gdTrueColorAlpha(im->red[p], im->green[p], im->blue[p], (im->transparent == p) ? gdAlphaTransparent : im->alpha[p]);
} else {
return p;
}
}
static void gdImageBrushApply (gdImagePtr im, int x, int y)
{
int lx, ly;
int hy, hx;
int x1, y1, x2, y2;
int srcx, srcy;
if (!im->brush) {
return;
}
hy = gdImageSY(im->brush) / 2;
y1 = y - hy;
y2 = y1 + gdImageSY(im->brush);
hx = gdImageSX(im->brush) / 2;
x1 = x - hx;
x2 = x1 + gdImageSX(im->brush);
srcy = 0;
if (im->trueColor) {
if (im->brush->trueColor) {
for (ly = y1; ly < y2; ly++) {
srcx = 0;
for (lx = x1; (lx < x2); lx++) {
int p;
p = gdImageGetTrueColorPixel(im->brush, srcx, srcy);
/* 2.0.9, Thomas Winzig: apply simple full transparency */
if (p != gdImageGetTransparent(im->brush)) {
gdImageSetPixel(im, lx, ly, p);
}
srcx++;
}
srcy++;
}
} else {
/* 2.0.12: Brush palette, image truecolor (thanks to Thorben Kundinger for pointing out the issue) */
for (ly = y1; ly < y2; ly++) {
srcx = 0;
for (lx = x1; lx < x2; lx++) {
int p, tc;
p = gdImageGetPixel(im->brush, srcx, srcy);
tc = gdImageGetTrueColorPixel(im->brush, srcx, srcy);
/* 2.0.9, Thomas Winzig: apply simple full transparency */
if (p != gdImageGetTransparent(im->brush)) {
gdImageSetPixel(im, lx, ly, tc);
}
srcx++;
}
srcy++;
}
}
} else {
for (ly = y1; ly < y2; ly++) {
srcx = 0;
for (lx = x1; lx < x2; lx++) {
int p;
p = gdImageGetPixel(im->brush, srcx, srcy);
/* Allow for non-square brushes! */
if (p != gdImageGetTransparent(im->brush)) {
/* Truecolor brush. Very slow on a palette destination. */
if (im->brush->trueColor) {
gdImageSetPixel(im, lx, ly, gdImageColorResolveAlpha(im, gdTrueColorGetRed(p),
gdTrueColorGetGreen(p),
gdTrueColorGetBlue(p),
gdTrueColorGetAlpha(p)));
} else {
gdImageSetPixel(im, lx, ly, im->brushColorMap[p]);
}
}
srcx++;
}
srcy++;
}
}
}
static void gdImageTileApply (gdImagePtr im, int x, int y)
{
gdImagePtr tile = im->tile;
int srcx, srcy;
int p;
if (!tile) {
return;
}
srcx = x % gdImageSX(tile);
srcy = y % gdImageSY(tile);
if (im->trueColor) {
p = gdImageGetPixel(tile, srcx, srcy);
if (p != gdImageGetTransparent (tile)) {
if (!tile->trueColor) {
p = gdTrueColorAlpha(tile->red[p], tile->green[p], tile->blue[p], tile->alpha[p]);
}
gdImageSetPixel(im, x, y, p);
}
} else {
p = gdImageGetPixel(tile, srcx, srcy);
/* Allow for transparency */
if (p != gdImageGetTransparent(tile)) {
if (tile->trueColor) {
/* Truecolor tile. Very slow on a palette destination. */
gdImageSetPixel(im, x, y, gdImageColorResolveAlpha(im,
gdTrueColorGetRed(p),
gdTrueColorGetGreen(p),
gdTrueColorGetBlue(p),
gdTrueColorGetAlpha(p)));
} else {
gdImageSetPixel(im, x, y, im->tileColorMap[p]);
}
}
}
}
static int gdImageTileGet (gdImagePtr im, int x, int y)
{
int srcx, srcy;
int tileColor,p;
if (!im->tile) {
return -1;
}
srcx = x % gdImageSX(im->tile);
srcy = y % gdImageSY(im->tile);
p = gdImageGetPixel(im->tile, srcx, srcy);
if (im->trueColor) {
if (im->tile->trueColor) {
tileColor = p;
} else {
tileColor = gdTrueColorAlpha( gdImageRed(im->tile,p), gdImageGreen(im->tile,p), gdImageBlue (im->tile,p), gdImageAlpha (im->tile,p));
}
} else {
if (im->tile->trueColor) {
tileColor = gdImageColorResolveAlpha(im, gdTrueColorGetRed (p), gdTrueColorGetGreen (p), gdTrueColorGetBlue (p), gdTrueColorGetAlpha (p));
} else {
tileColor = p;
tileColor = gdImageColorResolveAlpha(im, gdImageRed (im->tile,p), gdImageGreen (im->tile,p), gdImageBlue (im->tile,p), gdImageAlpha (im->tile,p));
}
}
return tileColor;
}
static void gdImageAntiAliasedApply (gdImagePtr im, int px, int py)
{
float p_dist, p_alpha;
unsigned char opacity;
/*
* Find the perpendicular distance from point C (px, py) to the line
* segment AB that is being drawn. (Adapted from an algorithm from the
* comp.graphics.algorithms FAQ.)
*/
int LAC_2, LBC_2;
int Ax_Cx = im->AAL_x1 - px;
int Ay_Cy = im->AAL_y1 - py;
int Bx_Cx = im->AAL_x2 - px;
int By_Cy = im->AAL_y2 - py;
/* 2.0.13: bounds check! AA_opacity is just as capable of
* overflowing as the main pixel array. Arne Jorgensen.
* 2.0.14: typo fixed. 2.0.15: moved down below declarations
* to satisfy non-C++ compilers.
*/
if (!gdImageBoundsSafe(im, px, py)) {
return;
}
/* Get the squares of the lengths of the segemnts AC and BC. */
LAC_2 = (Ax_Cx * Ax_Cx) + (Ay_Cy * Ay_Cy);
LBC_2 = (Bx_Cx * Bx_Cx) + (By_Cy * By_Cy);
if (((im->AAL_LAB_2 + LAC_2) >= LBC_2) && ((im->AAL_LAB_2 + LBC_2) >= LAC_2)) {
/* The two angles are acute. The point lies inside the portion of the
* plane spanned by the line segment.
*/
p_dist = fabs ((float) ((Ay_Cy * im->AAL_Bx_Ax) - (Ax_Cx * im->AAL_By_Ay)) / im->AAL_LAB);
} else {
/* The point is past an end of the line segment. It's length from the
* segment is the shorter of the lengths from the endpoints, but call
* the distance -1, so as not to compute the alpha nor draw the pixel.
*/
p_dist = -1;
}
if ((p_dist >= 0) && (p_dist <= (float) (im->thick))) {
p_alpha = pow (1.0 - (p_dist / 1.5), 2);
if (p_alpha > 0) {
if (p_alpha >= 1) {
opacity = 255;
} else {
opacity = (unsigned char) (p_alpha * 255.0);
}
if (!im->AA_polygon || (im->AA_opacity[py][px] < opacity)) {
im->AA_opacity[py][px] = opacity;
}
}
}
}
int gdImageGetPixel (gdImagePtr im, int x, int y)
{
if (gdImageBoundsSafe(im, x, y)) {
if (im->trueColor) {
return im->tpixels[y][x];
} else {
return im->pixels[y][x];
}
} else {
return 0;
}
}
void gdImageAABlend (gdImagePtr im)
{
float p_alpha, old_alpha;
int color = im->AA_color, color_red, color_green, color_blue;
int old_color, old_red, old_green, old_blue;
int p_color, p_red, p_green, p_blue;
int px, py;
color_red = gdImageRed(im, color);
color_green = gdImageGreen(im, color);
color_blue = gdImageBlue(im, color);
/* Impose the anti-aliased drawing on the image. */
for (py = 0; py < im->sy; py++) {
for (px = 0; px < im->sx; px++) {
if (im->AA_opacity[py][px] != 0) {
old_color = gdImageGetPixel(im, px, py);
if ((old_color != color) && ((old_color != im->AA_dont_blend) || (im->AA_opacity[py][px] == 255))) {
/* Only blend with different colors that aren't the dont_blend color. */
p_alpha = (float) (im->AA_opacity[py][px]) / 255.0;
old_alpha = 1.0 - p_alpha;
if (p_alpha >= 1.0) {
p_color = color;
} else {
old_red = gdImageRed(im, old_color);
old_green = gdImageGreen(im, old_color);
old_blue = gdImageBlue(im, old_color);
p_red = (int) (((float) color_red * p_alpha) + ((float) old_red * old_alpha));
p_green = (int) (((float) color_green * p_alpha) + ((float) old_green * old_alpha));
p_blue = (int) (((float) color_blue * p_alpha) + ((float) old_blue * old_alpha));
p_color = gdImageColorResolve(im, p_red, p_green, p_blue);
}
gdImageSetPixel(im, px, py, p_color);
}
}
}
/* Clear the AA_opacity array behind us. */
memset(im->AA_opacity[py], 0, im->sx);
}
}
static void _gdImageFilledHRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color);
static void gdImageHLine(gdImagePtr im, int y, int x1, int x2, int col)
{
if (im->thick > 1) {
int thickhalf = im->thick >> 1;
_gdImageFilledHRectangle(im, x1, y - thickhalf, x2, y + im->thick - thickhalf - 1, col);
} else {
if (x2 < x1) {
int t = x2;
x2 = x1;
x1 = t;
}
for (;x1 <= x2; x1++) {
gdImageSetPixel(im, x1, y, col);
}
}
return;
}
static void gdImageVLine(gdImagePtr im, int x, int y1, int y2, int col)
{
if (im->thick > 1) {
int thickhalf = im->thick >> 1;
gdImageFilledRectangle(im, x - thickhalf, y1, x + im->thick - thickhalf - 1, y2, col);
} else {
if (y2 < y1) {
int t = y1;
y1 = y2;
y2 = t;
}
for (;y1 <= y2; y1++) {
gdImageSetPixel(im, x, y1, col);
}
}
return;
}
/* Bresenham as presented in Foley & Van Dam */
void gdImageLine (gdImagePtr im, int x1, int y1, int x2, int y2, int color)
{
int dx, dy, incr1, incr2, d, x, y, xend, yend, xdirflag, ydirflag;
int wid;
int w, wstart;
int thick = im->thick;
if (color == gdAntiAliased) {
/*
gdAntiAliased passed as color: use the much faster, much cheaper
and equally attractive gdImageAALine implementation. That
clips too, so don't clip twice.
*/
gdImageAALine(im, x1, y1, x2, y2, im->AA_color);
return;
}
/* 2.0.10: Nick Atty: clip to edges of drawing rectangle, return if no points need to be drawn */
if (!clip_1d(&x1,&y1,&x2,&y2,gdImageSX(im)-1) || !clip_1d(&y1,&x1,&y2,&x2,gdImageSY(im)-1)) {
return;
}
dx = abs (x2 - x1);
dy = abs (y2 - y1);
if (dx == 0) {
gdImageVLine(im, x1, y1, y2, color);
return;
} else if (dy == 0) {
gdImageHLine(im, y1, x1, x2, color);
return;
}
if (dy <= dx) {
/* More-or-less horizontal. use wid for vertical stroke */
/* Doug Claar: watch out for NaN in atan2 (2.0.5) */
if ((dx == 0) && (dy == 0)) {
wid = 1;
} else {
/* 2.0.12: Michael Schwartz: divide rather than multiply;
TBB: but watch out for /0! */
double ac = cos (atan2 (dy, dx));
if (ac != 0) {
wid = thick / ac;
} else {
wid = 1;
}
if (wid == 0) {
wid = 1;
}
}
d = 2 * dy - dx;
incr1 = 2 * dy;
incr2 = 2 * (dy - dx);
if (x1 > x2) {
x = x2;
y = y2;
ydirflag = (-1);
xend = x1;
} else {
x = x1;
y = y1;
ydirflag = 1;
xend = x2;
}
/* Set up line thickness */
wstart = y - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel(im, x, w, color);
}
if (((y2 - y1) * ydirflag) > 0) {
while (x < xend) {
x++;
if (d < 0) {
d += incr1;
} else {
y++;
d += incr2;
}
wstart = y - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel (im, x, w, color);
}
}
} else {
while (x < xend) {
x++;
if (d < 0) {
d += incr1;
} else {
y--;
d += incr2;
}
wstart = y - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel (im, x, w, color);
}
}
}
} else {
/* More-or-less vertical. use wid for horizontal stroke */
/* 2.0.12: Michael Schwartz: divide rather than multiply;
TBB: but watch out for /0! */
double as = sin (atan2 (dy, dx));
if (as != 0) {
wid = thick / as;
} else {
wid = 1;
}
if (wid == 0) {
wid = 1;
}
d = 2 * dx - dy;
incr1 = 2 * dx;
incr2 = 2 * (dx - dy);
if (y1 > y2) {
y = y2;
x = x2;
yend = y1;
xdirflag = (-1);
} else {
y = y1;
x = x1;
yend = y2;
xdirflag = 1;
}
/* Set up line thickness */
wstart = x - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel (im, w, y, color);
}
if (((x2 - x1) * xdirflag) > 0) {
while (y < yend) {
y++;
if (d < 0) {
d += incr1;
} else {
x++;
d += incr2;
}
wstart = x - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel (im, w, y, color);
}
}
} else {
while (y < yend) {
y++;
if (d < 0) {
d += incr1;
} else {
x--;
d += incr2;
}
wstart = x - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel (im, w, y, color);
}
}
}
}
}
/*
* Added on 2003/12 by Pierre-Alain Joye (pajoye@pearfr.org)
* */
#define BLEND_COLOR(a, nc, c, cc) \
nc = (cc) + (((((c) - (cc)) * (a)) + ((((c) - (cc)) * (a)) >> 8) + 0x80) >> 8);
inline static void gdImageSetAAPixelColor(gdImagePtr im, int x, int y, int color, int t)
{
int dr,dg,db,p,r,g,b;
dr = gdTrueColorGetRed(color);
dg = gdTrueColorGetGreen(color);
db = gdTrueColorGetBlue(color);
p = gdImageGetPixel(im,x,y);
r = gdTrueColorGetRed(p);
g = gdTrueColorGetGreen(p);
b = gdTrueColorGetBlue(p);
BLEND_COLOR(t, dr, r, dr);
BLEND_COLOR(t, dg, g, dg);
BLEND_COLOR(t, db, b, db);
im->tpixels[y][x]=gdTrueColorAlpha(dr, dg, db, gdAlphaOpaque);
}
/*
* Added on 2003/12 by Pierre-Alain Joye (pajoye@pearfr.org)
**/
void gdImageAALine (gdImagePtr im, int x1, int y1, int x2, int y2, int col)
{
/* keep them as 32bits */
long x, y, inc, frac;
long dx, dy,tmp;
/* 2.0.10: Nick Atty: clip to edges of drawing rectangle, return if no points need to be drawn */
if (!clip_1d(&x1,&y1,&x2,&y2,gdImageSX(im)-1) || !clip_1d(&y1,&x1,&y2,&x2,gdImageSY(im)-1)) {
return;
}
dx = x2 - x1;
dy = y2 - y1;
if (dx == 0 && dy == 0) {
return;
}
if (abs(dx) > abs(dy)) {
if (dx < 0) {
tmp = x1;
x1 = x2;
x2 = tmp;
tmp = y1;
y1 = y2;
y2 = tmp;
dx = x2 - x1;
dy = y2 - y1;
}
y = y1;
inc = (dy * 65536) / dx;
frac = 0;
for (x = x1; x <= x2; x++) {
gdImageSetAAPixelColor(im, x, y, col, (frac >> 8) & 0xFF);
if (y + 1 < im->sy) {
gdImageSetAAPixelColor(im, x, y + 1, col, (~frac >> 8) & 0xFF);
}
frac += inc;
if (frac >= 65536) {
frac -= 65536;
y++;
} else if (frac < 0) {
frac += 65536;
y--;
}
}
} else {
if (dy < 0) {
tmp = x1;
x1 = x2;
x2 = tmp;
tmp = y1;
y1 = y2;
y2 = tmp;
dx = x2 - x1;
dy = y2 - y1;
}
x = x1;
inc = (dx * 65536) / dy;
frac = 0;
for (y = y1; y <= y2; y++) {
gdImageSetAAPixelColor(im, x, y, col, (frac >> 8) & 0xFF);
if (x + 1 < im->sx) {
gdImageSetAAPixelColor(im, x + 1, y, col, (~frac >> 8) & 0xFF);
}
frac += inc;
if (frac >= 65536) {
frac -= 65536;
x++;
} else if (frac < 0) {
frac += 65536;
x--;
}
}
}
}
static void dashedSet (gdImagePtr im, int x, int y, int color, int *onP, int *dashStepP, int wid, int vert);
void gdImageDashedLine (gdImagePtr im, int x1, int y1, int x2, int y2, int color)
{
int dx, dy, incr1, incr2, d, x, y, xend, yend, xdirflag, ydirflag;
int dashStep = 0;
int on = 1;
int wid;
int vert;
int thick = im->thick;
dx = abs(x2 - x1);
dy = abs(y2 - y1);
if (dy <= dx) {
/* More-or-less horizontal. use wid for vertical stroke */
/* 2.0.12: Michael Schwartz: divide rather than multiply;
TBB: but watch out for /0! */
double as = sin(atan2(dy, dx));
if (as != 0) {
wid = thick / as;
} else {
wid = 1;
}
wid = (int)(thick * sin(atan2(dy, dx)));
vert = 1;
d = 2 * dy - dx;
incr1 = 2 * dy;
incr2 = 2 * (dy - dx);
if (x1 > x2) {
x = x2;
y = y2;
ydirflag = (-1);
xend = x1;
} else {
x = x1;
y = y1;
ydirflag = 1;
xend = x2;
}
dashedSet(im, x, y, color, &on, &dashStep, wid, vert);
if (((y2 - y1) * ydirflag) > 0) {
while (x < xend) {
x++;
if (d < 0) {
d += incr1;
} else {
y++;
d += incr2;
}
dashedSet(im, x, y, color, &on, &dashStep, wid, vert);
}
} else {
while (x < xend) {
x++;
if (d < 0) {
d += incr1;
} else {
y--;
d += incr2;
}
dashedSet(im, x, y, color, &on, &dashStep, wid, vert);
}
}
} else {
/* 2.0.12: Michael Schwartz: divide rather than multiply;
TBB: but watch out for /0! */
double as = sin (atan2 (dy, dx));
if (as != 0) {
wid = thick / as;
} else {
wid = 1;
}
vert = 0;
d = 2 * dx - dy;
incr1 = 2 * dx;
incr2 = 2 * (dx - dy);
if (y1 > y2) {
y = y2;
x = x2;
yend = y1;
xdirflag = (-1);
} else {
y = y1;
x = x1;
yend = y2;
xdirflag = 1;
}
dashedSet(im, x, y, color, &on, &dashStep, wid, vert);
if (((x2 - x1) * xdirflag) > 0) {
while (y < yend) {
y++;
if (d < 0) {
d += incr1;
} else {
x++;
d += incr2;
}
dashedSet(im, x, y, color, &on, &dashStep, wid, vert);
}
} else {
while (y < yend) {
y++;
if (d < 0) {
d += incr1;
} else {
x--;
d += incr2;
}
dashedSet(im, x, y, color, &on, &dashStep, wid, vert);
}
}
}
}
static void dashedSet (gdImagePtr im, int x, int y, int color, int *onP, int *dashStepP, int wid, int vert)
{
int dashStep = *dashStepP;
int on = *onP;
int w, wstart;
dashStep++;
if (dashStep == gdDashSize) {
dashStep = 0;
on = !on;
}
if (on) {
if (vert) {
wstart = y - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel(im, x, w, color);
}
} else {
wstart = x - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel(im, w, y, color);
}
}
}
*dashStepP = dashStep;
*onP = on;
}
void gdImageChar (gdImagePtr im, gdFontPtr f, int x, int y, int c, int color)
{
int cx, cy;
int px, py;
int fline;
cx = 0;
cy = 0;
#ifdef CHARSET_EBCDIC
c = ASC (c);
#endif /*CHARSET_EBCDIC */
if ((c < f->offset) || (c >= (f->offset + f->nchars))) {
return;
}
fline = (c - f->offset) * f->h * f->w;
for (py = y; (py < (y + f->h)); py++) {
for (px = x; (px < (x + f->w)); px++) {
if (f->data[fline + cy * f->w + cx]) {
gdImageSetPixel(im, px, py, color);
}
cx++;
}
cx = 0;
cy++;
}
}
void gdImageCharUp (gdImagePtr im, gdFontPtr f, int x, int y, int c, int color)
{
int cx, cy;
int px, py;
int fline;
cx = 0;
cy = 0;
#ifdef CHARSET_EBCDIC
c = ASC (c);
#endif /*CHARSET_EBCDIC */
if ((c < f->offset) || (c >= (f->offset + f->nchars))) {
return;
}
fline = (c - f->offset) * f->h * f->w;
for (py = y; py > (y - f->w); py--) {
for (px = x; px < (x + f->h); px++) {
if (f->data[fline + cy * f->w + cx]) {
gdImageSetPixel(im, px, py, color);
}
cy++;
}
cy = 0;
cx++;
}
}
void gdImageString (gdImagePtr im, gdFontPtr f, int x, int y, unsigned char *s, int color)
{
int i;
int l;
l = strlen ((char *) s);
for (i = 0; (i < l); i++) {
gdImageChar(im, f, x, y, s[i], color);
x += f->w;
}
}
void gdImageStringUp (gdImagePtr im, gdFontPtr f, int x, int y, unsigned char *s, int color)
{
int i;
int l;
l = strlen ((char *) s);
for (i = 0; (i < l); i++) {
gdImageCharUp(im, f, x, y, s[i], color);
y -= f->w;
}
}
static int strlen16 (unsigned short *s);
void gdImageString16 (gdImagePtr im, gdFontPtr f, int x, int y, unsigned short *s, int color)
{
int i;
int l;
l = strlen16(s);
for (i = 0; (i < l); i++) {
gdImageChar(im, f, x, y, s[i], color);
x += f->w;
}
}
void gdImageStringUp16 (gdImagePtr im, gdFontPtr f, int x, int y, unsigned short *s, int color)
{
int i;
int l;
l = strlen16(s);
for (i = 0; i < l; i++) {
gdImageCharUp(im, f, x, y, s[i], color);
y -= f->w;
}
}
static int strlen16 (unsigned short *s)
{
int len = 0;
while (*s) {
s++;
len++;
}
return len;
}
#ifndef HAVE_LSQRT
/* If you don't have a nice square root function for longs, you can use
** this hack
*/
long lsqrt (long n)
{
long result = (long) sqrt ((double) n);
return result;
}
#endif
/* s and e are integers modulo 360 (degrees), with 0 degrees
being the rightmost extreme and degrees changing clockwise.
cx and cy are the center in pixels; w and h are the horizontal
and vertical diameter in pixels. */
void gdImageArc (gdImagePtr im, int cx, int cy, int w, int h, int s, int e, int color)
{
gdImageFilledArc(im, cx, cy, w, h, s, e, color, gdNoFill);
}
void gdImageFilledArc (gdImagePtr im, int cx, int cy, int w, int h, int s, int e, int color, int style)
{
gdPoint pts[363];
int i, pti;
int lx = 0, ly = 0;
int fx = 0, fy = 0;
if ((s % 360) == (e % 360)) {
s = 0; e = 360;
} else {
if (s > 360) {
s = s % 360;
}
if (e > 360) {
e = e % 360;
}
while (s < 0) {
s += 360;
}
while (e < s) {
e += 360;
}
if (s == e) {
s = 0; e = 360;
}
}
for (i = s, pti = 1; i <= e; i++, pti++) {
int x, y;
x = ((long) gdCosT[i % 360] * (long) w / (2 * 1024)) + cx;
y = ((long) gdSinT[i % 360] * (long) h / (2 * 1024)) + cy;
if (i != s) {
if (!(style & gdChord)) {
if (style & gdNoFill) {
gdImageLine(im, lx, ly, x, y, color);
} else {
if (y == ly) {
pti--; /* don't add this point */
if (((i > 270 || i < 90) && x > lx) || ((i > 90 && i < 270) && x < lx)) {
/* replace the old x coord, if increasing on the
right side or decreasing on the left side */
pts[pti].x = x;
}
} else {
pts[pti].x = x;
pts[pti].y = y;
}
}
}
} else {
fx = x;
fy = y;
if (!(style & (gdChord | gdNoFill))) {
pts[0].x = cx;
pts[0].y = cy;
pts[pti].x = x;
pts[pti].y = y;
}
}
lx = x;
ly = y;
}
if (style & gdChord) {
if (style & gdNoFill) {
if (style & gdEdged) {
gdImageLine(im, cx, cy, lx, ly, color);
gdImageLine(im, cx, cy, fx, fy, color);
}
gdImageLine(im, fx, fy, lx, ly, color);
} else {
pts[0].x = fx;
pts[0].y = fy;
pts[1].x = lx;
pts[1].y = ly;
pts[2].x = cx;
pts[2].y = cy;
gdImageFilledPolygon(im, pts, 3, color);
}
} else {
if (style & gdNoFill) {
if (style & gdEdged) {
gdImageLine(im, cx, cy, lx, ly, color);
gdImageLine(im, cx, cy, fx, fy, color);
}
} else {
pts[pti].x = cx;
pts[pti].y = cy;
gdImageFilledPolygon(im, pts, pti+1, color);
}
}
}
void gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color)
{
int lastBorder;
/* Seek left */
int leftLimit = -1, rightLimit;
int i, restoreAlphaBlending = 0;
if (border < 0 || color < 0) {
/* Refuse to fill to a non-solid border */
return;
}
if (!im->trueColor) {
if ((color > (im->colorsTotal - 1)) || (border > (im->colorsTotal - 1)) || (color < 0)) {
return;
}
}
restoreAlphaBlending = im->alphaBlendingFlag;
im->alphaBlendingFlag = 0;
if (x >= im->sx) {
x = im->sx - 1;
} else if (x < 0) {
x = 0;
}
if (y >= im->sy) {
y = im->sy - 1;
} else if (y < 0) {
y = 0;
}
for (i = x; i >= 0; i--) {
if (gdImageGetPixel(im, i, y) == border) {
break;
}
gdImageSetPixel(im, i, y, color);
leftLimit = i;
}
if (leftLimit == -1) {
im->alphaBlendingFlag = restoreAlphaBlending;
return;
}
/* Seek right */
rightLimit = x;
for (i = (x + 1); i < im->sx; i++) {
if (gdImageGetPixel(im, i, y) == border) {
break;
}
gdImageSetPixel(im, i, y, color);
rightLimit = i;
}
/* Look at lines above and below and start paints */
/* Above */
if (y > 0) {
lastBorder = 1;
for (i = leftLimit; i <= rightLimit; i++) {
int c = gdImageGetPixel(im, i, y - 1);
if (lastBorder) {
if ((c != border) && (c != color)) {
gdImageFillToBorder(im, i, y - 1, border, color);
lastBorder = 0;
}
} else if ((c == border) || (c == color)) {
lastBorder = 1;
}
}
}
/* Below */
if (y < ((im->sy) - 1)) {
lastBorder = 1;
for (i = leftLimit; i <= rightLimit; i++) {
int c = gdImageGetPixel(im, i, y + 1);
if (lastBorder) {
if ((c != border) && (c != color)) {
gdImageFillToBorder(im, i, y + 1, border, color);
lastBorder = 0;
}
} else if ((c == border) || (c == color)) {
lastBorder = 1;
}
}
}
im->alphaBlendingFlag = restoreAlphaBlending;
}
/*
* set the pixel at (x,y) and its 4-connected neighbors
* with the same pixel value to the new pixel value nc (new color).
* A 4-connected neighbor: pixel above, below, left, or right of a pixel.
* ideas from comp.graphics discussions.
* For tiled fill, the use of a flag buffer is mandatory. As the tile image can
* contain the same color as the color to fill. To do not bloat normal filling
* code I added a 2nd private function.
*/
/* horizontal segment of scan line y */
struct seg {int y, xl, xr, dy;};
/* max depth of stack */
#define FILL_MAX ((int)(im->sy*im->sx)/4)
#define FILL_PUSH(Y, XL, XR, DY) \
if (sp<stack+FILL_MAX && Y+(DY)>=0 && Y+(DY)<wy2) \
{sp->y = Y; sp->xl = XL; sp->xr = XR; sp->dy = DY; sp++;}
#define FILL_POP(Y, XL, XR, DY) \
{sp--; Y = sp->y+(DY = sp->dy); XL = sp->xl; XR = sp->xr;}
static void _gdImageFillTiled(gdImagePtr im, int x, int y, int nc);
void gdImageFill(gdImagePtr im, int x, int y, int nc)
{
int l, x1, x2, dy;
int oc; /* old pixel value */
int wx2,wy2;
int alphablending_bak;
/* stack of filled segments */
/* struct seg stack[FILL_MAX],*sp = stack;; */
struct seg *stack = NULL;
struct seg *sp;
if (!im->trueColor && nc > (im->colorsTotal -1)) {
return;
}
alphablending_bak = im->alphaBlendingFlag;
im->alphaBlendingFlag = 0;
if (nc==gdTiled){
_gdImageFillTiled(im,x,y,nc);
im->alphaBlendingFlag = alphablending_bak;
return;
}
wx2=im->sx;wy2=im->sy;
oc = gdImageGetPixel(im, x, y);
if (oc==nc || x<0 || x>wx2 || y<0 || y>wy2) {
im->alphaBlendingFlag = alphablending_bak;
return;
}
/* Do not use the 4 neighbors implementation with
* small images
*/
if (im->sx < 4) {
int ix = x, iy = y, c;
do {
do {
c = gdImageGetPixel(im, ix, iy);
if (c != oc) {
goto done;
}
gdImageSetPixel(im, ix, iy, nc);
} while(ix++ < (im->sx -1));
ix = x;
} while(iy++ < (im->sy -1));
goto done;
}
stack = (struct seg *)safe_emalloc(sizeof(struct seg), ((int)(im->sy*im->sx)/4), 1);
sp = stack;
/* required! */
FILL_PUSH(y,x,x,1);
/* seed segment (popped 1st) */
FILL_PUSH(y+1, x, x, -1);
while (sp>stack) {
FILL_POP(y, x1, x2, dy);
for (x=x1; x>=0 && gdImageGetPixel(im,x, y)==oc; x--) {
gdImageSetPixel(im,x, y, nc);
}
if (x>=x1) {
goto skip;
}
l = x+1;
/* leak on left? */
if (l<x1) {
FILL_PUSH(y, l, x1-1, -dy);
}
x = x1+1;
do {
for (; x<=wx2 && gdImageGetPixel(im,x, y)==oc; x++) {
gdImageSetPixel(im, x, y, nc);
}
FILL_PUSH(y, l, x-1, dy);
/* leak on right? */
if (x>x2+1) {
FILL_PUSH(y, x2+1, x-1, -dy);
}
skip: for (x++; x<=x2 && (gdImageGetPixel(im, x, y)!=oc); x++);
l = x;
} while (x<=x2);
}
efree(stack);
done:
im->alphaBlendingFlag = alphablending_bak;
}
static void _gdImageFillTiled(gdImagePtr im, int x, int y, int nc)
{
int i, l, x1, x2, dy;
int oc; /* old pixel value */
int wx2,wy2;
/* stack of filled segments */
struct seg *stack;
struct seg *sp;
char **pts;
if (!im->tile) {
return;
}
wx2=im->sx;wy2=im->sy;
nc = gdImageTileGet(im,x,y);
pts = (char **) ecalloc(im->sy + 1, sizeof(char *));
for (i = 0; i < im->sy + 1; i++) {
pts[i] = (char *) ecalloc(im->sx + 1, sizeof(char));
}
stack = (struct seg *)safe_emalloc(sizeof(struct seg), ((int)(im->sy*im->sx)/4), 1);
sp = stack;
oc = gdImageGetPixel(im, x, y);
/* required! */
FILL_PUSH(y,x,x,1);
/* seed segment (popped 1st) */
FILL_PUSH(y+1, x, x, -1);
while (sp>stack) {
FILL_POP(y, x1, x2, dy);
for (x=x1; x>=0 && (!pts[y][x] && gdImageGetPixel(im,x,y)==oc); x--) {
nc = gdImageTileGet(im,x,y);
pts[y][x] = 1;
gdImageSetPixel(im,x, y, nc);
}
if (x>=x1) {
goto skip;
}
l = x+1;
/* leak on left? */
if (l<x1) {
FILL_PUSH(y, l, x1-1, -dy);
}
x = x1+1;
do {
for(; x<wx2 && (!pts[y][x] && gdImageGetPixel(im,x, y)==oc); x++) {
nc = gdImageTileGet(im,x,y);
pts[y][x] = 1;
gdImageSetPixel(im, x, y, nc);
}
FILL_PUSH(y, l, x-1, dy);
/* leak on right? */
if (x>x2+1) {
FILL_PUSH(y, x2+1, x-1, -dy);
}
skip: for(x++; x<=x2 && (pts[y][x] || gdImageGetPixel(im,x, y)!=oc); x++);
l = x;
} while (x<=x2);
}
for(i = 0; i < im->sy + 1; i++) {
efree(pts[i]);
}
efree(pts);
efree(stack);
}
void gdImageRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color)
{
int x1h = x1, x1v = x1, y1h = y1, y1v = y1, x2h = x2, x2v = x2, y2h = y2, y2v = y2;
int thick = im->thick;
int t;
if (x1 == x2 && y1 == y2 && thick == 1) {
gdImageSetPixel(im, x1, y1, color);
return;
}
if (y2 < y1) {
t=y1;
y1 = y2;
y2 = t;
}
if (x2 < x1) {
t = x1;
x1 = x2;
x2 = t;
}
x1h = x1; x1v = x1; y1h = y1; y1v = y1; x2h = x2; x2v = x2; y2h = y2; y2v = y2;
if (thick > 1) {
int cx, cy, x1ul, y1ul, x2lr, y2lr;
int half = thick >> 1;
x1ul = x1 - half;
y1ul = y1 - half;
x2lr = x2 + half;
y2lr = y2 + half;
cy = y1ul + thick;
while (cy-- > y1ul) {
cx = x1ul - 1;
while (cx++ < x2lr) {
gdImageSetPixel(im, cx, cy, color);
}
}
cy = y2lr - thick;
while (cy++ < y2lr) {
cx = x1ul - 1;
while (cx++ < x2lr) {
gdImageSetPixel(im, cx, cy, color);
}
}
cy = y1ul + thick - 1;
while (cy++ < y2lr -thick) {
cx = x1ul - 1;
while (cx++ < x1ul + thick) {
gdImageSetPixel(im, cx, cy, color);
}
}
cy = y1ul + thick - 1;
while (cy++ < y2lr -thick) {
cx = x2lr - thick - 1;
while (cx++ < x2lr) {
gdImageSetPixel(im, cx, cy, color);
}
}
return;
} else {
if (x1 == x2 || y1 == y2) {
gdImageLine(im, x1, y1, x2, y2, color);
} else {
y1v = y1h + 1;
y2v = y2h - 1;
gdImageLine(im, x1h, y1h, x2h, y1h, color);
gdImageLine(im, x1h, y2h, x2h, y2h, color);
gdImageLine(im, x1v, y1v, x1v, y2v, color);
gdImageLine(im, x2v, y1v, x2v, y2v, color);
}
}
}
static void _gdImageFilledHRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color)
{
int x, y;
if (x1 == x2 && y1 == y2) {
gdImageSetPixel(im, x1, y1, color);
return;
}
if (x1 > x2) {
x = x1;
x1 = x2;
x2 = x;
}
if (y1 > y2) {
y = y1;
y1 = y2;
y2 = y;
}
if (x1 < 0) {
x1 = 0;
}
if (x2 >= gdImageSX(im)) {
x2 = gdImageSX(im) - 1;
}
if (y1 < 0) {
y1 = 0;
}
if (y2 >= gdImageSY(im)) {
y2 = gdImageSY(im) - 1;
}
for (x = x1; (x <= x2); x++) {
for (y = y1; (y <= y2); y++) {
gdImageSetPixel (im, x, y, color);
}
}
}
static void _gdImageFilledVRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color)
{
int x, y;
if (x1 == x2 && y1 == y2) {
gdImageSetPixel(im, x1, y1, color);
return;
}
if (x1 > x2) {
x = x1;
x1 = x2;
x2 = x;
}
if (y1 > y2) {
y = y1;
y1 = y2;
y2 = y;
}
if (x1 < 0) {
x1 = 0;
}
if (x2 >= gdImageSX(im)) {
x2 = gdImageSX(im) - 1;
}
if (y1 < 0) {
y1 = 0;
}
if (y2 >= gdImageSY(im)) {
y2 = gdImageSY(im) - 1;
}
for (y = y1; (y <= y2); y++) {
for (x = x1; (x <= x2); x++) {
gdImageSetPixel (im, x, y, color);
}
}
}
void gdImageFilledRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color)
{
_gdImageFilledVRectangle(im, x1, y1, x2, y2, color);
}
void gdImageCopy (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h)
{
int c;
int x, y;
int tox, toy;
int i;
int colorMap[gdMaxColors];
if (dst->trueColor) {
/* 2.0: much easier when the destination is truecolor. */
/* 2.0.10: needs a transparent-index check that is still valid if
* the source is not truecolor. Thanks to Frank Warmerdam.
*/
if (src->trueColor) {
for (y = 0; (y < h); y++) {
for (x = 0; (x < w); x++) {
int c = gdImageGetTrueColorPixel (src, srcX + x, srcY + y);
if (c != src->transparent) {
gdImageSetPixel (dst, dstX + x, dstY + y, c);
}
}
}
} else {
/* source is palette based */
for (y = 0; (y < h); y++) {
for (x = 0; (x < w); x++) {
int c = gdImageGetPixel (src, srcX + x, srcY + y);
if (c != src->transparent) {
gdImageSetPixel(dst, dstX + x, dstY + y, gdTrueColorAlpha(src->red[c], src->green[c], src->blue[c], src->alpha[c]));
}
}
}
}
return;
}
/* Palette based to palette based */
for (i = 0; i < gdMaxColors; i++) {
colorMap[i] = (-1);
}
toy = dstY;
for (y = srcY; y < (srcY + h); y++) {
tox = dstX;
for (x = srcX; x < (srcX + w); x++) {
int nc;
int mapTo;
c = gdImageGetPixel (src, x, y);
/* Added 7/24/95: support transparent copies */
if (gdImageGetTransparent (src) == c) {
tox++;
continue;
}
/* Have we established a mapping for this color? */
if (src->trueColor) {
/* 2.05: remap to the palette available in the destination image. This is slow and
* works badly, but it beats crashing! Thanks to Padhrig McCarthy.
*/
mapTo = gdImageColorResolveAlpha (dst, gdTrueColorGetRed (c), gdTrueColorGetGreen (c), gdTrueColorGetBlue (c), gdTrueColorGetAlpha (c));
} else if (colorMap[c] == (-1)) {
/* If it's the same image, mapping is trivial */
if (dst == src) {
nc = c;
} else {
/* Get best match possible. This function never returns error. */
nc = gdImageColorResolveAlpha (dst, src->red[c], src->green[c], src->blue[c], src->alpha[c]);
}
colorMap[c] = nc;
mapTo = colorMap[c];
} else {
mapTo = colorMap[c];
}
gdImageSetPixel (dst, tox, toy, mapTo);
tox++;
}
toy++;
}
}
/* This function is a substitute for real alpha channel operations,
so it doesn't pay attention to the alpha channel. */
void gdImageCopyMerge (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct)
{
int c, dc;
int x, y;
int tox, toy;
int ncR, ncG, ncB;
toy = dstY;
for (y = srcY; y < (srcY + h); y++) {
tox = dstX;
for (x = srcX; x < (srcX + w); x++) {
int nc;
c = gdImageGetPixel(src, x, y);
/* Added 7/24/95: support transparent copies */
if (gdImageGetTransparent(src) == c) {
tox++;
continue;
}
/* If it's the same image, mapping is trivial */
if (dst == src) {
nc = c;
} else {
dc = gdImageGetPixel(dst, tox, toy);
ncR = (int)(gdImageRed (src, c) * (pct / 100.0) + gdImageRed (dst, dc) * ((100 - pct) / 100.0));
ncG = (int)(gdImageGreen (src, c) * (pct / 100.0) + gdImageGreen (dst, dc) * ((100 - pct) / 100.0));
ncB = (int)(gdImageBlue (src, c) * (pct / 100.0) + gdImageBlue (dst, dc) * ((100 - pct) / 100.0));
/* Find a reasonable color */
nc = gdImageColorResolve (dst, ncR, ncG, ncB);
}
gdImageSetPixel (dst, tox, toy, nc);
tox++;
}
toy++;
}
}
/* This function is a substitute for real alpha channel operations,
so it doesn't pay attention to the alpha channel. */
void gdImageCopyMergeGray (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct)
{
int c, dc;
int x, y;
int tox, toy;
int ncR, ncG, ncB;
float g;
toy = dstY;
for (y = srcY; (y < (srcY + h)); y++) {
tox = dstX;
for (x = srcX; (x < (srcX + w)); x++) {
int nc;
c = gdImageGetPixel (src, x, y);
/* Added 7/24/95: support transparent copies */
if (gdImageGetTransparent(src) == c) {
tox++;
continue;
}
/*
* If it's the same image, mapping is NOT trivial since we
* merge with greyscale target, but if pct is 100, the grey
* value is not used, so it becomes trivial. pjw 2.0.12.
*/
if (dst == src && pct == 100) {
nc = c;
} else {
dc = gdImageGetPixel(dst, tox, toy);
g = (0.29900f * gdImageRed(dst, dc)) + (0.58700f * gdImageGreen(dst, dc)) + (0.11400f * gdImageBlue(dst, dc));
ncR = (int)(gdImageRed (src, c) * (pct / 100.0f) + g * ((100 - pct) / 100.0));
ncG = (int)(gdImageGreen (src, c) * (pct / 100.0f) + g * ((100 - pct) / 100.0));
ncB = (int)(gdImageBlue (src, c) * (pct / 100.0f) + g * ((100 - pct) / 100.0));
/* First look for an exact match */
nc = gdImageColorExact(dst, ncR, ncG, ncB);
if (nc == (-1)) {
/* No, so try to allocate it */
nc = gdImageColorAllocate(dst, ncR, ncG, ncB);
/* If we're out of colors, go for the closest color */
if (nc == (-1)) {
nc = gdImageColorClosest(dst, ncR, ncG, ncB);
}
}
}
gdImageSetPixel(dst, tox, toy, nc);
tox++;
}
toy++;
}
}
void gdImageCopyResized (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)
{
int c;
int x, y;
int tox, toy;
int ydest;
int i;
int colorMap[gdMaxColors];
/* Stretch vectors */
int *stx, *sty;
if (overflow2(sizeof(int), srcW)) {
return;
}
if (overflow2(sizeof(int), srcH)) {
return;
}
stx = (int *) gdMalloc (sizeof (int) * srcW);
sty = (int *) gdMalloc (sizeof (int) * srcH);
/* Fixed by Mao Morimoto 2.0.16 */
for (i = 0; (i < srcW); i++) {
stx[i] = dstW * (i+1) / srcW - dstW * i / srcW ;
}
for (i = 0; (i < srcH); i++) {
sty[i] = dstH * (i+1) / srcH - dstH * i / srcH ;
}
for (i = 0; (i < gdMaxColors); i++) {
colorMap[i] = (-1);
}
toy = dstY;
for (y = srcY; (y < (srcY + srcH)); y++) {
for (ydest = 0; (ydest < sty[y - srcY]); ydest++) {
tox = dstX;
for (x = srcX; (x < (srcX + srcW)); x++) {
int nc = 0;
int mapTo;
if (!stx[x - srcX]) {
continue;
}
if (dst->trueColor) {
/* 2.0.9: Thorben Kundinger: Maybe the source image is not a truecolor image */
if (!src->trueColor) {
int tmp = gdImageGetPixel (src, x, y);
mapTo = gdImageGetTrueColorPixel (src, x, y);
if (gdImageGetTransparent (src) == tmp) {
/* 2.0.21, TK: not tox++ */
tox += stx[x - srcX];
continue;
}
} else {
/* TK: old code follows */
mapTo = gdImageGetTrueColorPixel (src, x, y);
/* Added 7/24/95: support transparent copies */
if (gdImageGetTransparent (src) == mapTo) {
/* 2.0.21, TK: not tox++ */
tox += stx[x - srcX];
continue;
}
}
} else {
c = gdImageGetPixel (src, x, y);
/* Added 7/24/95: support transparent copies */
if (gdImageGetTransparent (src) == c) {
tox += stx[x - srcX];
continue;
}
if (src->trueColor) {
/* Remap to the palette available in the destination image. This is slow and works badly. */
mapTo = gdImageColorResolveAlpha(dst, gdTrueColorGetRed(c),
gdTrueColorGetGreen(c),
gdTrueColorGetBlue(c),
gdTrueColorGetAlpha (c));
} else {
/* Have we established a mapping for this color? */
if (colorMap[c] == (-1)) {
/* If it's the same image, mapping is trivial */
if (dst == src) {
nc = c;
} else {
/* Find or create the best match */
/* 2.0.5: can't use gdTrueColorGetRed, etc with palette */
nc = gdImageColorResolveAlpha(dst, gdImageRed(src, c),
gdImageGreen(src, c),
gdImageBlue(src, c),
gdImageAlpha(src, c));
}
colorMap[c] = nc;
}
mapTo = colorMap[c];
}
}
for (i = 0; (i < stx[x - srcX]); i++) {
gdImageSetPixel (dst, tox, toy, mapTo);
tox++;
}
}
toy++;
}
}
gdFree (stx);
gdFree (sty);
}
/* When gd 1.x was first created, floating point was to be avoided.
These days it is often faster than table lookups or integer
arithmetic. The routine below is shamelessly, gloriously
floating point. TBB */
void gdImageCopyResampled (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)
{
int x, y;
double sy1, sy2, sx1, sx2;
if (!dst->trueColor) {
gdImageCopyResized (dst, src, dstX, dstY, srcX, srcY, dstW, dstH, srcW, srcH);
return;
}
for (y = dstY; (y < dstY + dstH); y++) {
sy1 = ((double) y - (double) dstY) * (double) srcH / (double) dstH;
sy2 = ((double) (y + 1) - (double) dstY) * (double) srcH / (double) dstH;
for (x = dstX; (x < dstX + dstW); x++) {
double sx, sy;
double spixels = 0;
double red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0;
double alpha_factor, alpha_sum = 0.0, contrib_sum = 0.0;
sx1 = ((double) x - (double) dstX) * (double) srcW / dstW;
sx2 = ((double) (x + 1) - (double) dstX) * (double) srcW / dstW;
sy = sy1;
do {
double yportion;
if (floor_cast(sy) == floor_cast(sy1)) {
yportion = 1.0f - (sy - floor_cast(sy));
if (yportion > sy2 - sy1) {
yportion = sy2 - sy1;
}
sy = floor_cast(sy);
} else if (sy == floorf(sy2)) {
yportion = sy2 - floor_cast(sy2);
} else {
yportion = 1.0f;
}
sx = sx1;
do {
double xportion;
double pcontribution;
int p;
if (floorf(sx) == floor_cast(sx1)) {
xportion = 1.0f - (sx - floor_cast(sx));
if (xportion > sx2 - sx1) {
xportion = sx2 - sx1;
}
sx = floor_cast(sx);
} else if (sx == floorf(sx2)) {
xportion = sx2 - floor_cast(sx2);
} else {
xportion = 1.0f;
}
pcontribution = xportion * yportion;
p = gdImageGetTrueColorPixel(src, (int) sx + srcX, (int) sy + srcY);
alpha_factor = ((gdAlphaMax - gdTrueColorGetAlpha(p))) * pcontribution;
red += gdTrueColorGetRed (p) * alpha_factor;
green += gdTrueColorGetGreen (p) * alpha_factor;
blue += gdTrueColorGetBlue (p) * alpha_factor;
alpha += gdTrueColorGetAlpha (p) * pcontribution;
alpha_sum += alpha_factor;
contrib_sum += pcontribution;
spixels += xportion * yportion;
sx += 1.0f;
}
while (sx < sx2);
sy += 1.0f;
}
while (sy < sy2);
if (spixels != 0.0f) {
red /= spixels;
green /= spixels;
blue /= spixels;
alpha /= spixels;
alpha += 0.5;
}
if ( alpha_sum != 0.0f) {
if( contrib_sum != 0.0f) {
alpha_sum /= contrib_sum;
}
red /= alpha_sum;
green /= alpha_sum;
blue /= alpha_sum;
}
/* Clamping to allow for rounding errors above */
if (red > 255.0f) {
red = 255.0f;
}
if (green > 255.0f) {
green = 255.0f;
}
if (blue > 255.0f) {
blue = 255.0f;
}
if (alpha > gdAlphaMax) {
alpha = gdAlphaMax;
}
gdImageSetPixel(dst, x, y, gdTrueColorAlpha ((int) red, (int) green, (int) blue, (int) alpha));
}
}
}
void gdImagePolygon (gdImagePtr im, gdPointPtr p, int n, int c)
{
int i;
int lx, ly;
typedef void (*image_line)(gdImagePtr im, int x1, int y1, int x2, int y2, int color);
image_line draw_line;
if (n <= 0) {
return;
}
/* Let it be known that we are drawing a polygon so that the opacity
* mask doesn't get cleared after each line.
*/
if (c == gdAntiAliased) {
im->AA_polygon = 1;
}
if ( im->antialias) {
draw_line = gdImageAALine;
} else {
draw_line = gdImageLine;
}
lx = p->x;
ly = p->y;
draw_line(im, lx, ly, p[n - 1].x, p[n - 1].y, c);
for (i = 1; i < n; i++) {
p++;
draw_line(im, lx, ly, p->x, p->y, c);
lx = p->x;
ly = p->y;
}
if (c == gdAntiAliased) {
im->AA_polygon = 0;
gdImageAABlend(im);
}
}
int gdCompareInt (const void *a, const void *b);
/* THANKS to Kirsten Schulz for the polygon fixes! */
/* The intersection finding technique of this code could be improved
* by remembering the previous intertersection, and by using the slope.
* That could help to adjust intersections to produce a nice
* interior_extrema.
*/
void gdImageFilledPolygon (gdImagePtr im, gdPointPtr p, int n, int c)
{
int i;
int y;
int miny, maxy, pmaxy;
int x1, y1;
int x2, y2;
int ind1, ind2;
int ints;
int fill_color;
if (n <= 0) {
return;
}
if (overflow2(sizeof(int), n)) {
return;
}
if (c == gdAntiAliased) {
fill_color = im->AA_color;
} else {
fill_color = c;
}
if (!im->polyAllocated) {
im->polyInts = (int *) gdMalloc(sizeof(int) * n);
im->polyAllocated = n;
}
if (im->polyAllocated < n) {
while (im->polyAllocated < n) {
im->polyAllocated *= 2;
}
if (overflow2(sizeof(int), im->polyAllocated)) {
return;
}
im->polyInts = (int *) gdRealloc(im->polyInts, sizeof(int) * im->polyAllocated);
}
miny = p[0].y;
maxy = p[0].y;
for (i = 1; i < n; i++) {
if (p[i].y < miny) {
miny = p[i].y;
}
if (p[i].y > maxy) {
maxy = p[i].y;
}
}
/* necessary special case: horizontal line */
if (n > 1 && miny == maxy) {
x1 = x2 = p[0].x;
for (i = 1; (i < n); i++) {
if (p[i].x < x1) {
x1 = p[i].x;
} else if (p[i].x > x2) {
x2 = p[i].x;
}
}
gdImageLine(im, x1, miny, x2, miny, c);
return;
}
pmaxy = maxy;
/* 2.0.16: Optimization by Ilia Chipitsine -- don't waste time offscreen */
if (miny < 0) {
miny = 0;
}
if (maxy >= gdImageSY(im)) {
maxy = gdImageSY(im) - 1;
}
/* Fix in 1.3: count a vertex only once */
for (y = miny; y <= maxy; y++) {
/*1.4 int interLast = 0; */
/* int dirLast = 0; */
/* int interFirst = 1; */
ints = 0;
for (i = 0; i < n; i++) {
if (!i) {
ind1 = n - 1;
ind2 = 0;
} else {
ind1 = i - 1;
ind2 = i;
}
y1 = p[ind1].y;
y2 = p[ind2].y;
if (y1 < y2) {
x1 = p[ind1].x;
x2 = p[ind2].x;
} else if (y1 > y2) {
y2 = p[ind1].y;
y1 = p[ind2].y;
x2 = p[ind1].x;
x1 = p[ind2].x;
} else {
continue;
}
/* Do the following math as float intermediately, and round to ensure
* that Polygon and FilledPolygon for the same set of points have the
* same footprint.
*/
if (y >= y1 && y < y2) {
im->polyInts[ints++] = (float) ((y - y1) * (x2 - x1)) / (float) (y2 - y1) + 0.5 + x1;
} else if (y == pmaxy && y == y2) {
im->polyInts[ints++] = x2;
}
}
qsort(im->polyInts, ints, sizeof(int), gdCompareInt);
for (i = 0; i < ints - 1; i += 2) {
gdImageLine(im, im->polyInts[i], y, im->polyInts[i + 1], y, fill_color);
}
}
/* If we are drawing this AA, then redraw the border with AA lines. */
if (c == gdAntiAliased) {
gdImagePolygon(im, p, n, c);
}
}
int gdCompareInt (const void *a, const void *b)
{
return (*(const int *) a) - (*(const int *) b);
}
void gdImageSetStyle (gdImagePtr im, int *style, int noOfPixels)
{
if (im->style) {
gdFree(im->style);
}
im->style = (int *) gdMalloc(sizeof(int) * noOfPixels);
memcpy(im->style, style, sizeof(int) * noOfPixels);
im->styleLength = noOfPixels;
im->stylePos = 0;
}
void gdImageSetThickness (gdImagePtr im, int thickness)
{
im->thick = thickness;
}
void gdImageSetBrush (gdImagePtr im, gdImagePtr brush)
{
int i;
im->brush = brush;
if (!im->trueColor && !im->brush->trueColor) {
for (i = 0; i < gdImageColorsTotal(brush); i++) {
int index;
index = gdImageColorResolveAlpha(im, gdImageRed(brush, i), gdImageGreen(brush, i), gdImageBlue(brush, i), gdImageAlpha(brush, i));
im->brushColorMap[i] = index;
}
}
}
void gdImageSetTile (gdImagePtr im, gdImagePtr tile)
{
int i;
im->tile = tile;
if (!im->trueColor && !im->tile->trueColor) {
for (i = 0; i < gdImageColorsTotal(tile); i++) {
int index;
index = gdImageColorResolveAlpha(im, gdImageRed(tile, i), gdImageGreen(tile, i), gdImageBlue(tile, i), gdImageAlpha(tile, i));
im->tileColorMap[i] = index;
}
}
}
void gdImageSetAntiAliased (gdImagePtr im, int c)
{
im->AA = 1;
im->AA_color = c;
im->AA_dont_blend = -1;
}
void gdImageSetAntiAliasedDontBlend (gdImagePtr im, int c, int dont_blend)
{
im->AA = 1;
im->AA_color = c;
im->AA_dont_blend = dont_blend;
}
void gdImageInterlace (gdImagePtr im, int interlaceArg)
{
im->interlace = interlaceArg;
}
int gdImageCompare (gdImagePtr im1, gdImagePtr im2)
{
int x, y;
int p1, p2;
int cmpStatus = 0;
int sx, sy;
if (im1->interlace != im2->interlace) {
cmpStatus |= GD_CMP_INTERLACE;
}
if (im1->transparent != im2->transparent) {
cmpStatus |= GD_CMP_TRANSPARENT;
}
if (im1->trueColor != im2->trueColor) {
cmpStatus |= GD_CMP_TRUECOLOR;
}
sx = im1->sx;
if (im1->sx != im2->sx) {
cmpStatus |= GD_CMP_SIZE_X + GD_CMP_IMAGE;
if (im2->sx < im1->sx) {
sx = im2->sx;
}
}
sy = im1->sy;
if (im1->sy != im2->sy) {
cmpStatus |= GD_CMP_SIZE_Y + GD_CMP_IMAGE;
if (im2->sy < im1->sy) {
sy = im2->sy;
}
}
if (im1->colorsTotal != im2->colorsTotal) {
cmpStatus |= GD_CMP_NUM_COLORS;
}
for (y = 0; y < sy; y++) {
for (x = 0; x < sx; x++) {
p1 = im1->trueColor ? gdImageTrueColorPixel(im1, x, y) : gdImagePalettePixel(im1, x, y);
p2 = im2->trueColor ? gdImageTrueColorPixel(im2, x, y) : gdImagePalettePixel(im2, x, y);
if (gdImageRed(im1, p1) != gdImageRed(im2, p2)) {
cmpStatus |= GD_CMP_COLOR + GD_CMP_IMAGE;
break;
}
if (gdImageGreen(im1, p1) != gdImageGreen(im2, p2)) {
cmpStatus |= GD_CMP_COLOR + GD_CMP_IMAGE;
break;
}
if (gdImageBlue(im1, p1) != gdImageBlue(im2, p2)) {
cmpStatus |= GD_CMP_COLOR + GD_CMP_IMAGE;
break;
}
#if 0
/* Soon we'll add alpha channel to palettes */
if (gdImageAlpha(im1, p1) != gdImageAlpha(im2, p2)) {
cmpStatus |= GD_CMP_COLOR + GD_CMP_IMAGE;
break;
}
#endif
}
if (cmpStatus & GD_CMP_COLOR) {
break;
}
}
return cmpStatus;
}
int
gdAlphaBlendOld (int dst, int src)
{
/* 2.0.12: TBB: alpha in the destination should be a
* component of the result. Thanks to Frank Warmerdam for
* pointing out the issue.
*/
return ((((gdTrueColorGetAlpha (src) *
gdTrueColorGetAlpha (dst)) / gdAlphaMax) << 24) +
((((gdAlphaTransparent - gdTrueColorGetAlpha (src)) *
gdTrueColorGetRed (src) / gdAlphaMax) +
(gdTrueColorGetAlpha (src) *
gdTrueColorGetRed (dst)) / gdAlphaMax) << 16) +
((((gdAlphaTransparent - gdTrueColorGetAlpha (src)) *
gdTrueColorGetGreen (src) / gdAlphaMax) +
(gdTrueColorGetAlpha (src) *
gdTrueColorGetGreen (dst)) / gdAlphaMax) << 8) +
(((gdAlphaTransparent - gdTrueColorGetAlpha (src)) *
gdTrueColorGetBlue (src) / gdAlphaMax) +
(gdTrueColorGetAlpha (src) *
gdTrueColorGetBlue (dst)) / gdAlphaMax));
}
int gdAlphaBlend (int dst, int src) {
int src_alpha = gdTrueColorGetAlpha(src);
int dst_alpha, alpha, red, green, blue;
int src_weight, dst_weight, tot_weight;
/* -------------------------------------------------------------------- */
/* Simple cases we want to handle fast. */
/* -------------------------------------------------------------------- */
if( src_alpha == gdAlphaOpaque )
return src;
dst_alpha = gdTrueColorGetAlpha(dst);
if( src_alpha == gdAlphaTransparent )
return dst;
if( dst_alpha == gdAlphaTransparent )
return src;
/* -------------------------------------------------------------------- */
/* What will the source and destination alphas be? Note that */
/* the destination weighting is substantially reduced as the */
/* overlay becomes quite opaque. */
/* -------------------------------------------------------------------- */
src_weight = gdAlphaTransparent - src_alpha;
dst_weight = (gdAlphaTransparent - dst_alpha) * src_alpha / gdAlphaMax;
tot_weight = src_weight + dst_weight;
/* -------------------------------------------------------------------- */
/* What red, green and blue result values will we use? */
/* -------------------------------------------------------------------- */
alpha = src_alpha * dst_alpha / gdAlphaMax;
red = (gdTrueColorGetRed(src) * src_weight
+ gdTrueColorGetRed(dst) * dst_weight) / tot_weight;
green = (gdTrueColorGetGreen(src) * src_weight
+ gdTrueColorGetGreen(dst) * dst_weight) / tot_weight;
blue = (gdTrueColorGetBlue(src) * src_weight
+ gdTrueColorGetBlue(dst) * dst_weight) / tot_weight;
/* -------------------------------------------------------------------- */
/* Return merged result. */
/* -------------------------------------------------------------------- */
return ((alpha << 24) + (red << 16) + (green << 8) + blue);
}
void gdImageAlphaBlending (gdImagePtr im, int alphaBlendingArg)
{
im->alphaBlendingFlag = alphaBlendingArg;
}
void gdImageAntialias (gdImagePtr im, int antialias)
{
if (im->trueColor){
im->antialias = antialias;
}
}
void gdImageSaveAlpha (gdImagePtr im, int saveAlphaArg)
{
im->saveAlphaFlag = saveAlphaArg;
}
static int gdLayerOverlay (int dst, int src)
{
int a1, a2;
a1 = gdAlphaMax - gdTrueColorGetAlpha(dst);
a2 = gdAlphaMax - gdTrueColorGetAlpha(src);
return ( ((gdAlphaMax - a1*a2/gdAlphaMax) << 24) +
(gdAlphaOverlayColor( gdTrueColorGetRed(src), gdTrueColorGetRed(dst), gdRedMax ) << 16) +
(gdAlphaOverlayColor( gdTrueColorGetGreen(src), gdTrueColorGetGreen(dst), gdGreenMax ) << 8) +
(gdAlphaOverlayColor( gdTrueColorGetBlue(src), gdTrueColorGetBlue(dst), gdBlueMax ))
);
}
static int gdAlphaOverlayColor (int src, int dst, int max )
{
/* this function implements the algorithm
*
* for dst[rgb] < 0.5,
* c[rgb] = 2.src[rgb].dst[rgb]
* and for dst[rgb] > 0.5,
* c[rgb] = -2.src[rgb].dst[rgb] + 2.dst[rgb] + 2.src[rgb] - 1
*
*/
dst = dst << 1;
if( dst > max ) {
/* in the "light" zone */
return dst + (src << 1) - (dst * src / max) - max;
} else {
/* in the "dark" zone */
return dst * src / max;
}
}
void gdImageSetClip (gdImagePtr im, int x1, int y1, int x2, int y2)
{
if (x1 < 0) {
x1 = 0;
}
if (x1 >= im->sx) {
x1 = im->sx - 1;
}
if (x2 < 0) {
x2 = 0;
}
if (x2 >= im->sx) {
x2 = im->sx - 1;
}
if (y1 < 0) {
y1 = 0;
}
if (y1 >= im->sy) {
y1 = im->sy - 1;
}
if (y2 < 0) {
y2 = 0;
}
if (y2 >= im->sy) {
y2 = im->sy - 1;
}
im->cx1 = x1;
im->cy1 = y1;
im->cx2 = x2;
im->cy2 = y2;
}
void gdImageGetClip (gdImagePtr im, int *x1P, int *y1P, int *x2P, int *y2P)
{
*x1P = im->cx1;
*y1P = im->cy1;
*x2P = im->cx2;
*y2P = im->cy2;
}
/* convert a palette image to true color */
int gdImagePaletteToTrueColor(gdImagePtr src)
{
unsigned int y;
unsigned int yy;
if (src == NULL) {
return 0;
}
if (src->trueColor == 1) {
return 1;
} else {
unsigned int x;
const unsigned int sy = gdImageSY(src);
const unsigned int sx = gdImageSX(src);
src->tpixels = (int **) gdMalloc(sizeof(int *) * sy);
if (src->tpixels == NULL) {
return 0;
}
for (y = 0; y < sy; y++) {
const unsigned char *src_row = src->pixels[y];
int * dst_row;
/* no need to calloc it, we overwrite all pxl anyway */
src->tpixels[y] = (int *) gdMalloc(sx * sizeof(int));
if (src->tpixels[y] == NULL) {
goto clean_on_error;
}
dst_row = src->tpixels[y];
for (x = 0; x < sx; x++) {
const unsigned char c = *(src_row + x);
if (c == src->transparent) {
*(dst_row + x) = gdTrueColorAlpha(0, 0, 0, 127);
} else {
*(dst_row + x) = gdTrueColorAlpha(src->red[c], src->green[c], src->blue[c], src->alpha[c]);
}
}
}
}
/* free old palette buffer (y is sy) */
for (yy = 0; yy < y; yy++) {
gdFree(src->pixels[yy]);
}
gdFree(src->pixels);
src->trueColor = 1;
src->pixels = NULL;
src->alphaBlendingFlag = 0;
src->saveAlphaFlag = 1;
if (src->transparent >= 0) {
const unsigned char c = src->transparent;
src->transparent = gdTrueColorAlpha(src->red[c], src->green[c], src->blue[c], src->alpha[c]);
}
return 1;
clean_on_error:
if (y > 0) {
for (yy = y; yy >= yy - 1; y--) {
gdFree(src->tpixels[y]);
}
gdFree(src->tpixels);
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5513_0 |
crossvul-cpp_data_good_734_1 | /* This file is part of libmspack.
* (C) 2003-2018 Stuart Caie.
*
* libmspack is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License (LGPL) version 2.1
*
* For further details, see the file COPYING.LIB distributed with libmspack
*/
/* CHM decompression implementation */
#include <system.h>
#include <chm.h>
/* prototypes */
static struct mschmd_header * chmd_open(
struct mschm_decompressor *base, const char *filename);
static struct mschmd_header * chmd_fast_open(
struct mschm_decompressor *base, const char *filename);
static struct mschmd_header *chmd_real_open(
struct mschm_decompressor *base, const char *filename, int entire);
static void chmd_close(
struct mschm_decompressor *base, struct mschmd_header *chm);
static int chmd_read_headers(
struct mspack_system *sys, struct mspack_file *fh,
struct mschmd_header *chm, int entire);
static int chmd_fast_find(
struct mschm_decompressor *base, struct mschmd_header *chm,
const char *filename, struct mschmd_file *f_ptr, int f_size);
static unsigned char *read_chunk(
struct mschm_decompressor_p *self, struct mschmd_header *chm,
struct mspack_file *fh, unsigned int chunk);
static int search_chunk(
struct mschmd_header *chm, const unsigned char *chunk, const char *filename,
const unsigned char **result, const unsigned char **result_end);
static inline int compare(
const char *s1, const char *s2, int l1, int l2);
static int chmd_extract(
struct mschm_decompressor *base, struct mschmd_file *file,
const char *filename);
static int chmd_sys_write(
struct mspack_file *file, void *buffer, int bytes);
static int chmd_init_decomp(
struct mschm_decompressor_p *self, struct mschmd_file *file);
static int read_reset_table(
struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec,
int entry, off_t *length_ptr, off_t *offset_ptr);
static int read_spaninfo(
struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec,
off_t *length_ptr);
static int find_sys_file(
struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec,
struct mschmd_file **f_ptr, const char *name);
static unsigned char *read_sys_file(
struct mschm_decompressor_p *self, struct mschmd_file *file);
static int chmd_error(
struct mschm_decompressor *base);
static int read_off64(
off_t *var, unsigned char *mem, struct mspack_system *sys,
struct mspack_file *fh);
/* filenames of the system files used for decompression.
* Content and ControlData are essential.
* ResetTable is preferred, but SpanInfo can be used if not available
*/
static const char *content_name = "::DataSpace/Storage/MSCompressed/Content";
static const char *control_name = "::DataSpace/Storage/MSCompressed/ControlData";
static const char *spaninfo_name = "::DataSpace/Storage/MSCompressed/SpanInfo";
static const char *rtable_name = "::DataSpace/Storage/MSCompressed/Transform/"
"{7FC28940-9D31-11D0-9B27-00A0C91E9C7C}/InstanceData/ResetTable";
/***************************************
* MSPACK_CREATE_CHM_DECOMPRESSOR
***************************************
* constructor
*/
struct mschm_decompressor *
mspack_create_chm_decompressor(struct mspack_system *sys)
{
struct mschm_decompressor_p *self = NULL;
if (!sys) sys = mspack_default_system;
if (!mspack_valid_system(sys)) return NULL;
if ((self = (struct mschm_decompressor_p *) sys->alloc(sys, sizeof(struct mschm_decompressor_p)))) {
self->base.open = &chmd_open;
self->base.close = &chmd_close;
self->base.extract = &chmd_extract;
self->base.last_error = &chmd_error;
self->base.fast_open = &chmd_fast_open;
self->base.fast_find = &chmd_fast_find;
self->system = sys;
self->error = MSPACK_ERR_OK;
self->d = NULL;
}
return (struct mschm_decompressor *) self;
}
/***************************************
* MSPACK_DESTROY_CAB_DECOMPRESSOR
***************************************
* destructor
*/
void mspack_destroy_chm_decompressor(struct mschm_decompressor *base) {
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base;
if (self) {
struct mspack_system *sys = self->system;
if (self->d) {
if (self->d->infh) sys->close(self->d->infh);
if (self->d->state) lzxd_free(self->d->state);
sys->free(self->d);
}
sys->free(self);
}
}
/***************************************
* CHMD_OPEN
***************************************
* opens a file and tries to read it as a CHM file.
* Calls chmd_real_open() with entire=1.
*/
static struct mschmd_header *chmd_open(struct mschm_decompressor *base,
const char *filename)
{
return chmd_real_open(base, filename, 1);
}
/***************************************
* CHMD_FAST_OPEN
***************************************
* opens a file and tries to read it as a CHM file, but does not read
* the file headers. Calls chmd_real_open() with entire=0
*/
static struct mschmd_header *chmd_fast_open(struct mschm_decompressor *base,
const char *filename)
{
return chmd_real_open(base, filename, 0);
}
/***************************************
* CHMD_REAL_OPEN
***************************************
* the real implementation of chmd_open() and chmd_fast_open(). It simply
* passes the "entire" parameter to chmd_read_headers(), which will then
* either read all headers, or a bare mininum.
*/
static struct mschmd_header *chmd_real_open(struct mschm_decompressor *base,
const char *filename, int entire)
{
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base;
struct mschmd_header *chm = NULL;
struct mspack_system *sys;
struct mspack_file *fh;
int error;
if (!base) return NULL;
sys = self->system;
if ((fh = sys->open(sys, filename, MSPACK_SYS_OPEN_READ))) {
if ((chm = (struct mschmd_header *) sys->alloc(sys, sizeof(struct mschmd_header)))) {
chm->filename = filename;
error = chmd_read_headers(sys, fh, chm, entire);
if (error) {
/* if the error is DATAFORMAT, and there are some results, return
* partial results with a warning, rather than nothing */
if (error == MSPACK_ERR_DATAFORMAT && (chm->files || chm->sysfiles)) {
sys->message(fh, "WARNING; contents are corrupt");
error = MSPACK_ERR_OK;
}
else {
chmd_close(base, chm);
chm = NULL;
}
}
self->error = error;
}
else {
self->error = MSPACK_ERR_NOMEMORY;
}
sys->close(fh);
}
else {
self->error = MSPACK_ERR_OPEN;
}
return chm;
}
/***************************************
* CHMD_CLOSE
***************************************
* frees all memory associated with a given mschmd_header
*/
static void chmd_close(struct mschm_decompressor *base,
struct mschmd_header *chm)
{
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base;
struct mschmd_file *fi, *nfi;
struct mspack_system *sys;
unsigned int i;
if (!base) return;
sys = self->system;
self->error = MSPACK_ERR_OK;
/* free files */
for (fi = chm->files; fi; fi = nfi) {
nfi = fi->next;
sys->free(fi);
}
for (fi = chm->sysfiles; fi; fi = nfi) {
nfi = fi->next;
sys->free(fi);
}
/* if this CHM was being decompressed, free decompression state */
if (self->d && (self->d->chm == chm)) {
if (self->d->infh) sys->close(self->d->infh);
if (self->d->state) lzxd_free(self->d->state);
sys->free(self->d);
self->d = NULL;
}
/* if this CHM had a chunk cache, free it and contents */
if (chm->chunk_cache) {
for (i = 0; i < chm->num_chunks; i++) sys->free(chm->chunk_cache[i]);
sys->free(chm->chunk_cache);
}
sys->free(chm);
}
/***************************************
* CHMD_READ_HEADERS
***************************************
* reads the basic CHM file headers. If the "entire" parameter is
* non-zero, all file entries will also be read. fills out a pre-existing
* mschmd_header structure, allocates memory for files as necessary
*/
/* The GUIDs found in CHM headers */
static const unsigned char guids[32] = {
/* {7C01FD10-7BAA-11D0-9E0C-00A0-C922-E6EC} */
0x10, 0xFD, 0x01, 0x7C, 0xAA, 0x7B, 0xD0, 0x11,
0x9E, 0x0C, 0x00, 0xA0, 0xC9, 0x22, 0xE6, 0xEC,
/* {7C01FD11-7BAA-11D0-9E0C-00A0-C922-E6EC} */
0x11, 0xFD, 0x01, 0x7C, 0xAA, 0x7B, 0xD0, 0x11,
0x9E, 0x0C, 0x00, 0xA0, 0xC9, 0x22, 0xE6, 0xEC
};
/* reads an encoded integer into a variable; 7 bits of data per byte,
* the high bit is used to indicate that there is another byte */
#define READ_ENCINT(var) do { \
(var) = 0; \
do { \
if (p >= end) goto chunk_end; \
(var) = ((var) << 7) | (*p & 0x7F); \
} while (*p++ & 0x80); \
} while (0)
static int chmd_read_headers(struct mspack_system *sys, struct mspack_file *fh,
struct mschmd_header *chm, int entire)
{
unsigned int section, name_len, x, errors, num_chunks;
unsigned char buf[0x54], *chunk = NULL, *name, *p, *end;
struct mschmd_file *fi, *link = NULL;
off_t offset, length;
int num_entries;
/* initialise pointers */
chm->files = NULL;
chm->sysfiles = NULL;
chm->chunk_cache = NULL;
chm->sec0.base.chm = chm;
chm->sec0.base.id = 0;
chm->sec1.base.chm = chm;
chm->sec1.base.id = 1;
chm->sec1.content = NULL;
chm->sec1.control = NULL;
chm->sec1.spaninfo = NULL;
chm->sec1.rtable = NULL;
/* read the first header */
if (sys->read(fh, &buf[0], chmhead_SIZEOF) != chmhead_SIZEOF) {
return MSPACK_ERR_READ;
}
/* check ITSF signature */
if (EndGetI32(&buf[chmhead_Signature]) != 0x46535449) {
return MSPACK_ERR_SIGNATURE;
}
/* check both header GUIDs */
if (memcmp(&buf[chmhead_GUID1], &guids[0], 32L) != 0) {
D(("incorrect GUIDs"))
return MSPACK_ERR_SIGNATURE;
}
chm->version = EndGetI32(&buf[chmhead_Version]);
chm->timestamp = EndGetM32(&buf[chmhead_Timestamp]);
chm->language = EndGetI32(&buf[chmhead_LanguageID]);
if (chm->version > 3) {
sys->message(fh, "WARNING; CHM version > 3");
}
/* read the header section table */
if (sys->read(fh, &buf[0], chmhst3_SIZEOF) != chmhst3_SIZEOF) {
return MSPACK_ERR_READ;
}
/* chmhst3_OffsetCS0 does not exist in version 1 or 2 CHM files.
* The offset will be corrected later, once HS1 is read.
*/
if (read_off64(&offset, &buf[chmhst_OffsetHS0], sys, fh) ||
read_off64(&chm->dir_offset, &buf[chmhst_OffsetHS1], sys, fh) ||
read_off64(&chm->sec0.offset, &buf[chmhst3_OffsetCS0], sys, fh))
{
return MSPACK_ERR_DATAFORMAT;
}
/* seek to header section 0 */
if (sys->seek(fh, offset, MSPACK_SYS_SEEK_START)) {
return MSPACK_ERR_SEEK;
}
/* read header section 0 */
if (sys->read(fh, &buf[0], chmhs0_SIZEOF) != chmhs0_SIZEOF) {
return MSPACK_ERR_READ;
}
if (read_off64(&chm->length, &buf[chmhs0_FileLen], sys, fh)) {
return MSPACK_ERR_DATAFORMAT;
}
/* seek to header section 1 */
if (sys->seek(fh, chm->dir_offset, MSPACK_SYS_SEEK_START)) {
return MSPACK_ERR_SEEK;
}
/* read header section 1 */
if (sys->read(fh, &buf[0], chmhs1_SIZEOF) != chmhs1_SIZEOF) {
return MSPACK_ERR_READ;
}
chm->dir_offset = sys->tell(fh);
chm->chunk_size = EndGetI32(&buf[chmhs1_ChunkSize]);
chm->density = EndGetI32(&buf[chmhs1_Density]);
chm->depth = EndGetI32(&buf[chmhs1_Depth]);
chm->index_root = EndGetI32(&buf[chmhs1_IndexRoot]);
chm->num_chunks = EndGetI32(&buf[chmhs1_NumChunks]);
chm->first_pmgl = EndGetI32(&buf[chmhs1_FirstPMGL]);
chm->last_pmgl = EndGetI32(&buf[chmhs1_LastPMGL]);
if (chm->version < 3) {
/* versions before 3 don't have chmhst3_OffsetCS0 */
chm->sec0.offset = chm->dir_offset + (chm->chunk_size * chm->num_chunks);
}
/* check if content offset or file size is wrong */
if (chm->sec0.offset > chm->length) {
D(("content section begins after file has ended"))
return MSPACK_ERR_DATAFORMAT;
}
/* ensure there are chunks and that chunk size is
* large enough for signature and num_entries */
if (chm->chunk_size < (pmgl_Entries + 2)) {
D(("chunk size not large enough"))
return MSPACK_ERR_DATAFORMAT;
}
if (chm->num_chunks == 0) {
D(("no chunks"))
return MSPACK_ERR_DATAFORMAT;
}
/* The chunk_cache data structure is not great; large values for num_chunks
* or num_chunks*chunk_size can exhaust all memory. Until a better chunk
* cache is implemented, put arbitrary limits on num_chunks and chunk size.
*/
if (chm->num_chunks > 100000) {
D(("more than 100,000 chunks"))
return MSPACK_ERR_DATAFORMAT;
}
if ((off_t)chm->chunk_size * (off_t)chm->num_chunks > chm->length) {
D(("chunks larger than entire file"))
return MSPACK_ERR_DATAFORMAT;
}
/* common sense checks on header section 1 fields */
if ((chm->chunk_size & (chm->chunk_size - 1)) != 0) {
sys->message(fh, "WARNING; chunk size is not a power of two");
}
if (chm->first_pmgl != 0) {
sys->message(fh, "WARNING; first PMGL chunk is not zero");
}
if (chm->first_pmgl > chm->last_pmgl) {
D(("first pmgl chunk is after last pmgl chunk"))
return MSPACK_ERR_DATAFORMAT;
}
if (chm->index_root != 0xFFFFFFFF && chm->index_root >= chm->num_chunks) {
D(("index_root outside valid range"))
return MSPACK_ERR_DATAFORMAT;
}
/* if we are doing a quick read, stop here! */
if (!entire) {
return MSPACK_ERR_OK;
}
/* seek to the first PMGL chunk, and reduce the number of chunks to read */
if ((x = chm->first_pmgl) != 0) {
if (sys->seek(fh,(off_t) (x * chm->chunk_size), MSPACK_SYS_SEEK_CUR)) {
return MSPACK_ERR_SEEK;
}
}
num_chunks = chm->last_pmgl - x + 1;
if (!(chunk = (unsigned char *) sys->alloc(sys, (size_t)chm->chunk_size))) {
return MSPACK_ERR_NOMEMORY;
}
/* read and process all chunks from FirstPMGL to LastPMGL */
errors = 0;
while (num_chunks--) {
/* read next chunk */
if (sys->read(fh, chunk, (int)chm->chunk_size) != (int)chm->chunk_size) {
sys->free(chunk);
return MSPACK_ERR_READ;
}
/* process only directory (PMGL) chunks */
if (EndGetI32(&chunk[pmgl_Signature]) != 0x4C474D50) continue;
if (EndGetI32(&chunk[pmgl_QuickRefSize]) < 2) {
sys->message(fh, "WARNING; PMGL quickref area is too small");
}
if (EndGetI32(&chunk[pmgl_QuickRefSize]) >
((int)chm->chunk_size - pmgl_Entries))
{
sys->message(fh, "WARNING; PMGL quickref area is too large");
}
p = &chunk[pmgl_Entries];
end = &chunk[chm->chunk_size - 2];
num_entries = EndGetI16(end);
while (num_entries--) {
READ_ENCINT(name_len);
if (name_len > (unsigned int) (end - p)) goto chunk_end;
name = p; p += name_len;
READ_ENCINT(section);
READ_ENCINT(offset);
READ_ENCINT(length);
/* ignore blank or one-char (e.g. "/") filenames we'd return as blank */
if (name_len < 2 || !name[0] || !name[1]) continue;
/* empty files and directory names are stored as a file entry at
* offset 0 with length 0. We want to keep empty files, but not
* directory names, which end with a "/" */
if ((offset == 0) && (length == 0)) {
if ((name_len > 0) && (name[name_len-1] == '/')) continue;
}
if (section > 1) {
sys->message(fh, "invalid section number '%u'.", section);
continue;
}
if (!(fi = (struct mschmd_file *) sys->alloc(sys, sizeof(struct mschmd_file) + name_len + 1))) {
sys->free(chunk);
return MSPACK_ERR_NOMEMORY;
}
fi->next = NULL;
fi->filename = (char *) &fi[1];
fi->section = ((section == 0) ? (struct mschmd_section *) (&chm->sec0)
: (struct mschmd_section *) (&chm->sec1));
fi->offset = offset;
fi->length = length;
sys->copy(name, fi->filename, (size_t) name_len);
fi->filename[name_len] = '\0';
if (name[0] == ':' && name[1] == ':') {
/* system file */
if (name_len == 40 && memcmp(name, content_name, 40) == 0) {
chm->sec1.content = fi;
}
else if (name_len == 44 && memcmp(name, control_name, 44) == 0) {
chm->sec1.control = fi;
}
else if (name_len == 41 && memcmp(name, spaninfo_name, 41) == 0) {
chm->sec1.spaninfo = fi;
}
else if (name_len == 105 && memcmp(name, rtable_name, 105) == 0) {
chm->sec1.rtable = fi;
}
fi->next = chm->sysfiles;
chm->sysfiles = fi;
}
else {
/* normal file */
if (link) link->next = fi; else chm->files = fi;
link = fi;
}
}
/* this is reached either when num_entries runs out, or if
* reading data from the chunk reached a premature end of chunk */
chunk_end:
if (num_entries >= 0) {
D(("chunk ended before all entries could be read"))
errors++;
}
}
sys->free(chunk);
return (errors > 0) ? MSPACK_ERR_DATAFORMAT : MSPACK_ERR_OK;
}
/***************************************
* CHMD_FAST_FIND
***************************************
* uses PMGI index chunks and quickref data to quickly locate a file
* directly from the on-disk index.
*
* TODO: protect against infinite loops in chunks (where pgml_NextChunk
* or a PMGI index entry point to an already visited chunk)
*/
static int chmd_fast_find(struct mschm_decompressor *base,
struct mschmd_header *chm, const char *filename,
struct mschmd_file *f_ptr, int f_size)
{
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base;
struct mspack_system *sys;
struct mspack_file *fh;
/* p and end are initialised to prevent MSVC warning about "potentially"
* uninitialised usage. This is provably untrue, but MS won't fix:
* https://developercommunity.visualstudio.com/content/problem/363489/c4701-false-positive-warning.html */
const unsigned char *chunk, *p = NULL, *end = NULL;
int err = MSPACK_ERR_OK, result = -1;
unsigned int n, sec;
if (!self || !chm || !f_ptr || (f_size != sizeof(struct mschmd_file))) {
return MSPACK_ERR_ARGS;
}
sys = self->system;
/* clear the results structure */
memset(f_ptr, 0, f_size);
if (!(fh = sys->open(sys, chm->filename, MSPACK_SYS_OPEN_READ))) {
return MSPACK_ERR_OPEN;
}
/* go through PMGI chunk hierarchy to reach PMGL chunk */
if (chm->index_root < chm->num_chunks) {
n = chm->index_root;
for (;;) {
if (!(chunk = read_chunk(self, chm, fh, n))) {
sys->close(fh);
return self->error;
}
/* search PMGI/PMGL chunk. exit early if no entry found */
if ((result = search_chunk(chm, chunk, filename, &p, &end)) <= 0) {
break;
}
/* found result. loop around for next chunk if this is PMGI */
if (chunk[3] == 0x4C) break; else READ_ENCINT(n);
}
}
else {
/* PMGL chunks only, search from first_pmgl to last_pmgl */
for (n = chm->first_pmgl; n <= chm->last_pmgl;
n = EndGetI32(&chunk[pmgl_NextChunk]))
{
if (!(chunk = read_chunk(self, chm, fh, n))) {
err = self->error;
break;
}
/* search PMGL chunk. exit if file found */
if ((result = search_chunk(chm, chunk, filename, &p, &end)) > 0) {
break;
}
/* stop simple infinite loops: can't visit the same chunk twice */
if ((int)n == EndGetI32(&chunk[pmgl_NextChunk])) {
break;
}
}
}
/* if we found a file, read it */
if (result > 0) {
READ_ENCINT(sec);
f_ptr->section = (sec == 0) ? (struct mschmd_section *) &chm->sec0
: (struct mschmd_section *) &chm->sec1;
READ_ENCINT(f_ptr->offset);
READ_ENCINT(f_ptr->length);
}
else if (result < 0) {
err = MSPACK_ERR_DATAFORMAT;
}
sys->close(fh);
return self->error = err;
chunk_end:
D(("read beyond end of chunk entries"))
sys->close(fh);
return self->error = MSPACK_ERR_DATAFORMAT;
}
/* reads the given chunk into memory, storing it in a chunk cache
* so it doesn't need to be read from disk more than once
*/
static unsigned char *read_chunk(struct mschm_decompressor_p *self,
struct mschmd_header *chm,
struct mspack_file *fh,
unsigned int chunk_num)
{
struct mspack_system *sys = self->system;
unsigned char *buf;
/* check arguments - most are already checked by chmd_fast_find */
if (chunk_num >= chm->num_chunks) return NULL;
/* ensure chunk cache is available */
if (!chm->chunk_cache) {
size_t size = sizeof(unsigned char *) * chm->num_chunks;
if (!(chm->chunk_cache = (unsigned char **) sys->alloc(sys, size))) {
self->error = MSPACK_ERR_NOMEMORY;
return NULL;
}
memset(chm->chunk_cache, 0, size);
}
/* try to answer out of chunk cache */
if (chm->chunk_cache[chunk_num]) return chm->chunk_cache[chunk_num];
/* need to read chunk - allocate memory for it */
if (!(buf = (unsigned char *) sys->alloc(sys, chm->chunk_size))) {
self->error = MSPACK_ERR_NOMEMORY;
return NULL;
}
/* seek to block and read it */
if (sys->seek(fh, (off_t) (chm->dir_offset + (chunk_num * chm->chunk_size)),
MSPACK_SYS_SEEK_START))
{
self->error = MSPACK_ERR_SEEK;
sys->free(buf);
return NULL;
}
if (sys->read(fh, buf, (int)chm->chunk_size) != (int)chm->chunk_size) {
self->error = MSPACK_ERR_READ;
sys->free(buf);
return NULL;
}
/* check the signature. Is is PMGL or PMGI? */
if (!((buf[0] == 0x50) && (buf[1] == 0x4D) && (buf[2] == 0x47) &&
((buf[3] == 0x4C) || (buf[3] == 0x49))))
{
self->error = MSPACK_ERR_SEEK;
sys->free(buf);
return NULL;
}
/* all OK. Store chunk in cache and return it */
return chm->chunk_cache[chunk_num] = buf;
}
/* searches a PMGI/PMGL chunk for a given filename entry. Returns -1 on
* data format error, 0 if entry definitely not found, 1 if entry
* found. In the latter case, *result and *result_end are set pointing
* to that entry's data (either the "next chunk" ENCINT for a PMGI or
* the section, offset and length ENCINTs for a PMGL).
*
* In the case of PMGL chunks, the entry has definitely been
* found. In the case of PMGI chunks, the entry which points to the
* chunk that may eventually contain that entry has been found.
*/
static int search_chunk(struct mschmd_header *chm,
const unsigned char *chunk,
const char *filename,
const unsigned char **result,
const unsigned char **result_end)
{
const unsigned char *start, *end, *p;
unsigned int qr_size, num_entries, qr_entries, qr_density, name_len;
unsigned int L, R, M, fname_len, entries_off, is_pmgl;
int cmp;
fname_len = strlen(filename);
/* PMGL chunk or PMGI chunk? (note: read_chunk() has already
* checked the rest of the characters in the chunk signature) */
if (chunk[3] == 0x4C) {
is_pmgl = 1;
entries_off = pmgl_Entries;
}
else {
is_pmgl = 0;
entries_off = pmgi_Entries;
}
/* Step 1: binary search first filename of each QR entry
* - target filename == entry
* found file
* - target filename < all entries
* file not found
* - target filename > all entries
* proceed to step 2 using final entry
* - target filename between two searched entries
* proceed to step 2
*/
qr_size = EndGetI32(&chunk[pmgl_QuickRefSize]);
start = &chunk[chm->chunk_size - 2];
end = &chunk[chm->chunk_size - qr_size];
num_entries = EndGetI16(start);
qr_density = 1 + (1 << chm->density);
qr_entries = (num_entries + qr_density-1) / qr_density;
if (num_entries == 0) {
D(("chunk has no entries"))
return -1;
}
if (qr_size > chm->chunk_size) {
D(("quickref size > chunk size"))
return -1;
}
*result_end = end;
if (((int)qr_entries * 2) > (start - end)) {
D(("WARNING; more quickrefs than quickref space"))
qr_entries = 0; /* but we can live with it */
}
if (qr_entries > 0) {
L = 0;
R = qr_entries - 1;
do {
/* pick new midpoint */
M = (L + R) >> 1;
/* compare filename with entry QR points to */
p = &chunk[entries_off + (M ? EndGetI16(start - (M << 1)) : 0)];
READ_ENCINT(name_len);
if (name_len > (unsigned int) (end - p)) goto chunk_end;
cmp = compare(filename, (char *)p, fname_len, name_len);
if (cmp == 0) break;
else if (cmp < 0) { if (M) R = M - 1; else return 0; }
else if (cmp > 0) L = M + 1;
} while (L <= R);
M = (L + R) >> 1;
if (cmp == 0) {
/* exact match! */
p += name_len;
*result = p;
return 1;
}
/* otherwise, read the group of entries for QR entry M */
p = &chunk[entries_off + (M ? EndGetI16(start - (M << 1)) : 0)];
num_entries -= (M * qr_density);
if (num_entries > qr_density) num_entries = qr_density;
}
else {
p = &chunk[entries_off];
}
/* Step 2: linear search through the set of entries reached in step 1.
* - filename == any entry
* found entry
* - filename < all entries (PMGI) or any entry (PMGL)
* entry not found, stop now
* - filename > all entries
* entry not found (PMGL) / maybe found (PMGI)
* -
*/
*result = NULL;
while (num_entries-- > 0) {
READ_ENCINT(name_len);
if (name_len > (unsigned int) (end - p)) goto chunk_end;
cmp = compare(filename, (char *)p, fname_len, name_len);
p += name_len;
if (cmp == 0) {
/* entry found */
*result = p;
return 1;
}
if (cmp < 0) {
/* entry not found (PMGL) / maybe found (PMGI) */
break;
}
/* read and ignore the rest of this entry */
if (is_pmgl) {
READ_ENCINT(R); /* skip section */
READ_ENCINT(R); /* skip offset */
READ_ENCINT(R); /* skip length */
}
else {
*result = p; /* store potential final result */
READ_ENCINT(R); /* skip chunk number */
}
}
/* PMGL? not found. PMGI? maybe found */
return (is_pmgl) ? 0 : (*result ? 1 : 0);
chunk_end:
D(("reached end of chunk data while searching"))
return -1;
}
#if HAVE_TOWLOWER
# include <wctype.h>
# define TOLOWER(x) towlower(x)
#else
# include <ctype.h>
# define TOLOWER(x) tolower(x)
#endif
/* decodes a UTF-8 character from s[] into c. Will not read past e.
* doesn't test that extension bytes are %10xxxxxx.
* allows some overlong encodings.
*/
#define GET_UTF8_CHAR(s, e, c) do { \
unsigned char x = *s++; \
if (x < 0x80) c = x; \
else if (x >= 0xC2 && x < 0xE0 && s < e) { \
c = (x & 0x1F) << 6 | (*s++ & 0x3F); \
} \
else if (x >= 0xE0 && x < 0xF0 && s+1 < e) { \
c = (x & 0x0F) << 12 | (s[0] & 0x3F) << 6 | (s[1] & 0x3F); \
s += 2; \
} \
else if (x >= 0xF0 && x <= 0xF5 && s+2 < e) { \
c = (x & 0x07) << 18 | (s[0] & 0x3F) << 12 | \
(s[1] & 0x3F) << 6 | (s[2] & 0x3F); \
if (c > 0x10FFFF) c = 0xFFFD; \
s += 3; \
} \
else c = 0xFFFD; \
} while (0)
/* case-insensitively compares two UTF8 encoded strings. String length for
* both strings must be provided, null bytes are not terminators */
static inline int compare(const char *s1, const char *s2, int l1, int l2) {
register const unsigned char *p1 = (const unsigned char *) s1;
register const unsigned char *p2 = (const unsigned char *) s2;
register const unsigned char *e1 = p1 + l1, *e2 = p2 + l2;
int c1, c2;
while (p1 < e1 && p2 < e2) {
GET_UTF8_CHAR(p1, e1, c1);
GET_UTF8_CHAR(p2, e2, c2);
if (c1 == c2) continue;
c1 = TOLOWER(c1);
c2 = TOLOWER(c2);
if (c1 != c2) return c1 - c2;
}
return l1 - l2;
}
/***************************************
* CHMD_EXTRACT
***************************************
* extracts a file from a CHM helpfile
*/
static int chmd_extract(struct mschm_decompressor *base,
struct mschmd_file *file, const char *filename)
{
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base;
struct mspack_system *sys;
struct mschmd_header *chm;
struct mspack_file *fh;
off_t bytes;
if (!self) return MSPACK_ERR_ARGS;
if (!file || !file->section) return self->error = MSPACK_ERR_ARGS;
sys = self->system;
chm = file->section->chm;
/* create decompression state if it doesn't exist */
if (!self->d) {
self->d = (struct mschmd_decompress_state *) sys->alloc(sys, sizeof(struct mschmd_decompress_state));
if (!self->d) return self->error = MSPACK_ERR_NOMEMORY;
self->d->chm = chm;
self->d->offset = 0;
self->d->state = NULL;
self->d->sys = *sys;
self->d->sys.write = &chmd_sys_write;
self->d->infh = NULL;
self->d->outfh = NULL;
}
/* open input chm file if not open, or the open one is a different chm */
if (!self->d->infh || (self->d->chm != chm)) {
if (self->d->infh) sys->close(self->d->infh);
if (self->d->state) lzxd_free(self->d->state);
self->d->chm = chm;
self->d->offset = 0;
self->d->state = NULL;
self->d->infh = sys->open(sys, chm->filename, MSPACK_SYS_OPEN_READ);
if (!self->d->infh) return self->error = MSPACK_ERR_OPEN;
}
/* open file for output */
if (!(fh = sys->open(sys, filename, MSPACK_SYS_OPEN_WRITE))) {
return self->error = MSPACK_ERR_OPEN;
}
/* if file is empty, simply creating it is enough */
if (!file->length) {
sys->close(fh);
return self->error = MSPACK_ERR_OK;
}
self->error = MSPACK_ERR_OK;
switch (file->section->id) {
case 0: /* Uncompressed section file */
/* simple seek + copy */
if (sys->seek(self->d->infh, file->section->chm->sec0.offset
+ file->offset, MSPACK_SYS_SEEK_START))
{
self->error = MSPACK_ERR_SEEK;
}
else {
unsigned char buf[512];
off_t length = file->length;
while (length > 0) {
int run = sizeof(buf);
if ((off_t)run > length) run = (int)length;
if (sys->read(self->d->infh, &buf[0], run) != run) {
self->error = MSPACK_ERR_READ;
break;
}
if (sys->write(fh, &buf[0], run) != run) {
self->error = MSPACK_ERR_WRITE;
break;
}
length -= run;
}
}
break;
case 1: /* MSCompressed section file */
/* (re)initialise compression state if we it is not yet initialised,
* or we have advanced too far and have to backtrack
*/
if (!self->d->state || (file->offset < self->d->offset)) {
if (self->d->state) {
lzxd_free(self->d->state);
self->d->state = NULL;
}
if (chmd_init_decomp(self, file)) break;
}
/* seek to input data */
if (sys->seek(self->d->infh, self->d->inoffset, MSPACK_SYS_SEEK_START)) {
self->error = MSPACK_ERR_SEEK;
break;
}
/* get to correct offset. */
self->d->outfh = NULL;
if ((bytes = file->offset - self->d->offset)) {
self->error = lzxd_decompress(self->d->state, bytes);
}
/* if getting to the correct offset was error free, unpack file */
if (!self->error) {
self->d->outfh = fh;
self->error = lzxd_decompress(self->d->state, file->length);
}
/* save offset in input source stream, in case there is a section 0
* file between now and the next section 1 file extracted */
self->d->inoffset = sys->tell(self->d->infh);
/* if an LZX error occured, the LZX decompressor is now useless */
if (self->error) {
if (self->d->state) lzxd_free(self->d->state);
self->d->state = NULL;
}
break;
}
sys->close(fh);
return self->error;
}
/***************************************
* CHMD_SYS_WRITE
***************************************
* chmd_sys_write is the internal writer function which the decompressor
* uses. If either writes data to disk (self->d->outfh) with the real
* sys->write() function, or does nothing with the data when
* self->d->outfh == NULL. advances self->d->offset.
*/
static int chmd_sys_write(struct mspack_file *file, void *buffer, int bytes) {
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) file;
self->d->offset += bytes;
if (self->d->outfh) {
return self->system->write(self->d->outfh, buffer, bytes);
}
return bytes;
}
/***************************************
* CHMD_INIT_DECOMP
***************************************
* Initialises the LZX decompressor to decompress the compressed stream,
* from the nearest reset offset and length that is needed for the given
* file.
*/
static int chmd_init_decomp(struct mschm_decompressor_p *self,
struct mschmd_file *file)
{
int window_size, window_bits, reset_interval, entry, err;
struct mspack_system *sys = self->system;
struct mschmd_sec_mscompressed *sec;
unsigned char *data;
off_t length, offset;
sec = (struct mschmd_sec_mscompressed *) file->section;
/* ensure we have a mscompressed content section */
err = find_sys_file(self, sec, &sec->content, content_name);
if (err) return self->error = err;
/* ensure we have a ControlData file */
err = find_sys_file(self, sec, &sec->control, control_name);
if (err) return self->error = err;
/* read ControlData */
if (sec->control->length < lzxcd_SIZEOF) {
D(("ControlData file is too short"))
return self->error = MSPACK_ERR_DATAFORMAT;
}
if (!(data = read_sys_file(self, sec->control))) {
D(("can't read mscompressed control data file"))
return self->error;
}
/* check LZXC signature */
if (EndGetI32(&data[lzxcd_Signature]) != 0x43585A4C) {
sys->free(data);
return self->error = MSPACK_ERR_SIGNATURE;
}
/* read reset_interval and window_size and validate version number */
switch (EndGetI32(&data[lzxcd_Version])) {
case 1:
reset_interval = EndGetI32(&data[lzxcd_ResetInterval]);
window_size = EndGetI32(&data[lzxcd_WindowSize]);
break;
case 2:
reset_interval = EndGetI32(&data[lzxcd_ResetInterval]) * LZX_FRAME_SIZE;
window_size = EndGetI32(&data[lzxcd_WindowSize]) * LZX_FRAME_SIZE;
break;
default:
D(("bad controldata version"))
sys->free(data);
return self->error = MSPACK_ERR_DATAFORMAT;
}
/* free ControlData */
sys->free(data);
/* find window_bits from window_size */
switch (window_size) {
case 0x008000: window_bits = 15; break;
case 0x010000: window_bits = 16; break;
case 0x020000: window_bits = 17; break;
case 0x040000: window_bits = 18; break;
case 0x080000: window_bits = 19; break;
case 0x100000: window_bits = 20; break;
case 0x200000: window_bits = 21; break;
default:
D(("bad controldata window size"))
return self->error = MSPACK_ERR_DATAFORMAT;
}
/* validate reset_interval */
if (reset_interval == 0 || reset_interval % LZX_FRAME_SIZE) {
D(("bad controldata reset interval"))
return self->error = MSPACK_ERR_DATAFORMAT;
}
/* which reset table entry would we like? */
entry = file->offset / reset_interval;
/* convert from reset interval multiple (usually 64k) to 32k frames */
entry *= reset_interval / LZX_FRAME_SIZE;
/* read the reset table entry */
if (read_reset_table(self, sec, entry, &length, &offset)) {
/* the uncompressed length given in the reset table is dishonest.
* the uncompressed data is always padded out from the given
* uncompressed length up to the next reset interval */
length += reset_interval - 1;
length &= -reset_interval;
}
else {
/* if we can't read the reset table entry, just start from
* the beginning. Use spaninfo to get the uncompressed length */
entry = 0;
offset = 0;
err = read_spaninfo(self, sec, &length);
}
if (err) return self->error = err;
/* get offset of compressed data stream:
* = offset of uncompressed section from start of file
* + offset of compressed stream from start of uncompressed section
* + offset of chosen reset interval from start of compressed stream */
self->d->inoffset = file->section->chm->sec0.offset + sec->content->offset + offset;
/* set start offset and overall remaining stream length */
self->d->offset = entry * LZX_FRAME_SIZE;
length -= self->d->offset;
/* initialise LZX stream */
self->d->state = lzxd_init(&self->d->sys, self->d->infh,
(struct mspack_file *) self, window_bits,
reset_interval / LZX_FRAME_SIZE,
4096, length, 0);
if (!self->d->state) self->error = MSPACK_ERR_NOMEMORY;
return self->error;
}
/***************************************
* READ_RESET_TABLE
***************************************
* Reads one entry out of the reset table. Also reads the uncompressed
* data length. Writes these to offset_ptr and length_ptr respectively.
* Returns non-zero for success, zero for failure.
*/
static int read_reset_table(struct mschm_decompressor_p *self,
struct mschmd_sec_mscompressed *sec,
int entry, off_t *length_ptr, off_t *offset_ptr)
{
struct mspack_system *sys = self->system;
unsigned char *data;
unsigned int pos, entrysize;
/* do we have a ResetTable file? */
int err = find_sys_file(self, sec, &sec->rtable, rtable_name);
if (err) return 0;
/* read ResetTable file */
if (sec->rtable->length < lzxrt_headerSIZEOF) {
D(("ResetTable file is too short"))
return 0;
}
if (!(data = read_sys_file(self, sec->rtable))) {
D(("can't read reset table"))
return 0;
}
/* check sanity of reset table */
if (EndGetI32(&data[lzxrt_FrameLen]) != LZX_FRAME_SIZE) {
D(("bad reset table frame length"))
sys->free(data);
return 0;
}
/* get the uncompressed length of the LZX stream */
if (read_off64(length_ptr, &data[lzxrt_UncompLen], sys, self->d->infh)) {
sys->free(data);
return 0;
}
entrysize = EndGetI32(&data[lzxrt_EntrySize]);
pos = EndGetI32(&data[lzxrt_TableOffset]) + (entry * entrysize);
/* ensure reset table entry for this offset exists */
if (entry < EndGetI32(&data[lzxrt_NumEntries]) &&
pos <= (sec->rtable->length - entrysize))
{
switch (entrysize) {
case 4:
*offset_ptr = EndGetI32(&data[pos]);
err = 0;
break;
case 8:
err = read_off64(offset_ptr, &data[pos], sys, self->d->infh);
break;
default:
D(("reset table entry size neither 4 nor 8"))
err = 1;
break;
}
}
else {
D(("bad reset interval"))
err = 1;
}
/* free the reset table */
sys->free(data);
/* return success */
return (err == 0);
}
/***************************************
* READ_SPANINFO
***************************************
* Reads the uncompressed data length from the spaninfo file.
* Returns zero for success or a non-zero error code for failure.
*/
static int read_spaninfo(struct mschm_decompressor_p *self,
struct mschmd_sec_mscompressed *sec,
off_t *length_ptr)
{
struct mspack_system *sys = self->system;
unsigned char *data;
/* find SpanInfo file */
int err = find_sys_file(self, sec, &sec->spaninfo, spaninfo_name);
if (err) return MSPACK_ERR_DATAFORMAT;
/* check it's large enough */
if (sec->spaninfo->length != 8) {
D(("SpanInfo file is wrong size"))
return MSPACK_ERR_DATAFORMAT;
}
/* read the SpanInfo file */
if (!(data = read_sys_file(self, sec->spaninfo))) {
D(("can't read SpanInfo file"))
return self->error;
}
/* get the uncompressed length of the LZX stream */
err = read_off64(length_ptr, data, sys, self->d->infh);
sys->free(data);
if (err) return MSPACK_ERR_DATAFORMAT;
if (*length_ptr <= 0) {
D(("output length is invalid"))
return MSPACK_ERR_DATAFORMAT;
}
return MSPACK_ERR_OK;
}
/***************************************
* FIND_SYS_FILE
***************************************
* Uses chmd_fast_find to locate a system file, and fills out that system
* file's entry and links it into the list of system files. Returns zero
* for success, non-zero for both failure and the file not existing.
*/
static int find_sys_file(struct mschm_decompressor_p *self,
struct mschmd_sec_mscompressed *sec,
struct mschmd_file **f_ptr, const char *name)
{
struct mspack_system *sys = self->system;
struct mschmd_file result;
/* already loaded */
if (*f_ptr) return MSPACK_ERR_OK;
/* try using fast_find to find the file - return DATAFORMAT error if
* it fails, or successfully doesn't find the file */
if (chmd_fast_find((struct mschm_decompressor *) self, sec->base.chm,
name, &result, (int)sizeof(result)) || !result.section)
{
return MSPACK_ERR_DATAFORMAT;
}
if (!(*f_ptr = (struct mschmd_file *) sys->alloc(sys, sizeof(result)))) {
return MSPACK_ERR_NOMEMORY;
}
/* copy result */
*(*f_ptr) = result;
(*f_ptr)->filename = (char *) name;
/* link file into sysfiles list */
(*f_ptr)->next = sec->base.chm->sysfiles;
sec->base.chm->sysfiles = *f_ptr;
return MSPACK_ERR_OK;
}
/***************************************
* READ_SYS_FILE
***************************************
* Allocates memory for a section 0 (uncompressed) file and reads it into
* memory.
*/
static unsigned char *read_sys_file(struct mschm_decompressor_p *self,
struct mschmd_file *file)
{
struct mspack_system *sys = self->system;
unsigned char *data = NULL;
int len;
if (!file || !file->section || (file->section->id != 0)) {
self->error = MSPACK_ERR_DATAFORMAT;
return NULL;
}
len = (int) file->length;
if (!(data = (unsigned char *) sys->alloc(sys, (size_t) len))) {
self->error = MSPACK_ERR_NOMEMORY;
return NULL;
}
if (sys->seek(self->d->infh, file->section->chm->sec0.offset
+ file->offset, MSPACK_SYS_SEEK_START))
{
self->error = MSPACK_ERR_SEEK;
sys->free(data);
return NULL;
}
if (sys->read(self->d->infh, data, len) != len) {
self->error = MSPACK_ERR_READ;
sys->free(data);
return NULL;
}
return data;
}
/***************************************
* CHMD_ERROR
***************************************
* returns the last error that occurred
*/
static int chmd_error(struct mschm_decompressor *base) {
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base;
return (self) ? self->error : MSPACK_ERR_ARGS;
}
/***************************************
* READ_OFF64
***************************************
* Reads a 64-bit signed integer from memory in Intel byte order.
* If running on a system with a 64-bit off_t, this is simply done.
* If running on a system with a 32-bit off_t, offsets up to 0x7FFFFFFF
* are accepted, offsets beyond that cause an error message.
*/
static int read_off64(off_t *var, unsigned char *mem,
struct mspack_system *sys, struct mspack_file *fh)
{
#if LARGEFILE_SUPPORT
*var = EndGetI64(mem);
#else
*var = EndGetI32(mem);
if ((*var & 0x80000000) || EndGetI32(mem+4)) {
sys->message(fh, (char *)largefile_msg);
return 1;
}
#endif
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_734_1 |
crossvul-cpp_data_bad_4779_2 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP DDDD BBBB %
% P P D D B B %
% PPPP D D BBBB %
% P D D B B %
% P DDDD BBBB %
% %
% %
% Read/Write Palm Database ImageViewer Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
% 20071202 TS * rewrote RLE decoder - old version could cause buffer overflows
% * failure of RLE decoding now thows error RLEDecoderError
% * fixed bug in RLE decoding - now all rows are decoded, not just
% the first one
% * fixed bug in reader - record offsets now handled correctly
% * fixed bug in reader - only bits 0..2 indicate compression type
% * in writer: now using image color count instead of depth
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/colormap-private.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/constitute.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Typedef declarations.
*/
typedef struct _PDBInfo
{
char
name[32];
short int
attributes,
version;
size_t
create_time,
modify_time,
archive_time,
modify_number,
application_info,
sort_info;
char
type[4], /* database type identifier "vIMG" */
id[4]; /* database creator identifier "View" */
size_t
seed,
next_record;
short int
number_records;
} PDBInfo;
typedef struct _PDBImage
{
char
name[32],
version;
size_t
reserved_1,
note;
short int
x_last,
y_last;
size_t
reserved_2;
short int
width,
height;
unsigned char
type;
unsigned short
x_anchor,
y_anchor;
} PDBImage;
/*
Forward declarations.
*/
static MagickBooleanType
WritePDBImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e c o d e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DecodeImage unpacks the packed image pixels into runlength-encoded
% pixel packets.
%
% The format of the DecodeImage method is:
%
% MagickBooleanType DecodeImage(Image *image,unsigned char *pixels,
% const size_t length)
%
% A description of each parameter follows:
%
% o image: the address of a structure of type Image.
%
% o pixels: The address of a byte (8 bits) array of pixel data created by
% the decoding process.
%
% o length: Number of bytes to read into buffer 'pixels'.
%
*/
static MagickBooleanType DecodeImage(Image *image, unsigned char *pixels,
const size_t length)
{
#define RLE_MODE_NONE -1
#define RLE_MODE_COPY 0
#define RLE_MODE_RUN 1
int data = 0, count = 0;
unsigned char *p;
int mode = RLE_MODE_NONE;
for (p = pixels; p < pixels + length; p++) {
if (0 == count) {
data = ReadBlobByte( image );
if (-1 == data) return MagickFalse;
if (data > 128) {
mode = RLE_MODE_RUN;
count = data - 128 + 1;
data = ReadBlobByte( image );
if (-1 == data) return MagickFalse;
} else {
mode = RLE_MODE_COPY;
count = data + 1;
}
}
if (RLE_MODE_COPY == mode) {
data = ReadBlobByte( image );
if (-1 == data) return MagickFalse;
}
*p = (unsigned char)data;
--count;
}
return MagickTrue;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P D B %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPDB() returns MagickTrue if the image format type, identified by the
% magick string, is PDB.
%
% The format of the ReadPDBImage method is:
%
% MagickBooleanType IsPDB(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsPDB(const unsigned char *magick,const size_t length)
{
if (length < 68)
return(MagickFalse);
if (memcmp(magick+60,"vIMGView",8) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P D B I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPDBImage() reads an Pilot image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadPDBImage method is:
%
% Image *ReadPDBImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadPDBImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
unsigned char
attributes,
tag[3];
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
PDBImage
pdb_image;
PDBInfo
pdb_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register unsigned char
*p;
size_t
bits_per_pixel,
num_pad_bytes,
one,
packets;
ssize_t
count,
img_offset,
comment_offset = 0,
y;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Determine if this a PDB image file.
*/
count=ReadBlob(image,sizeof(pdb_info.name),(unsigned char *) pdb_info.name);
if (count != sizeof(pdb_info.name))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
pdb_info.attributes=(short) ReadBlobMSBShort(image);
pdb_info.version=(short) ReadBlobMSBShort(image);
pdb_info.create_time=ReadBlobMSBLong(image);
pdb_info.modify_time=ReadBlobMSBLong(image);
pdb_info.archive_time=ReadBlobMSBLong(image);
pdb_info.modify_number=ReadBlobMSBLong(image);
pdb_info.application_info=ReadBlobMSBLong(image);
pdb_info.sort_info=ReadBlobMSBLong(image);
(void) ReadBlob(image,4,(unsigned char *) pdb_info.type);
(void) ReadBlob(image,4,(unsigned char *) pdb_info.id);
pdb_info.seed=ReadBlobMSBLong(image);
pdb_info.next_record=ReadBlobMSBLong(image);
pdb_info.number_records=(short) ReadBlobMSBShort(image);
if ((memcmp(pdb_info.type,"vIMG",4) != 0) ||
(memcmp(pdb_info.id,"View",4) != 0))
if (pdb_info.next_record != 0)
ThrowReaderException(CoderError,"MultipleRecordListNotSupported");
/*
Read record header.
*/
img_offset=(ssize_t) ReadBlobMSBSignedLong(image);
attributes=(unsigned char) (ReadBlobByte(image));
(void) attributes;
count=ReadBlob(image,3,(unsigned char *) tag);
if (count != 3 || memcmp(tag,"\x6f\x80\x00",3) != 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
if (pdb_info.number_records > 1)
{
comment_offset=(ssize_t) ReadBlobMSBSignedLong(image);
attributes=(unsigned char) (ReadBlobByte(image));
count=ReadBlob(image,3,(unsigned char *) tag);
if (count != 3 || memcmp(tag,"\x6f\x80\x01",3) != 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
}
num_pad_bytes = (size_t) (img_offset - TellBlob( image ));
while (num_pad_bytes-- != 0)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
}
/*
Read image header.
*/
count=ReadBlob(image,sizeof(pdb_image.name),(unsigned char *) pdb_image.name);
if (count != sizeof(pdb_image.name))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
pdb_image.version=ReadBlobByte(image);
pdb_image.type=(unsigned char) ReadBlobByte(image);
pdb_image.reserved_1=ReadBlobMSBLong(image);
pdb_image.note=ReadBlobMSBLong(image);
pdb_image.x_last=(short) ReadBlobMSBShort(image);
pdb_image.y_last=(short) ReadBlobMSBShort(image);
pdb_image.reserved_2=ReadBlobMSBLong(image);
pdb_image.x_anchor=ReadBlobMSBShort(image);
pdb_image.y_anchor=ReadBlobMSBShort(image);
pdb_image.width=(short) ReadBlobMSBShort(image);
pdb_image.height=(short) ReadBlobMSBShort(image);
/*
Initialize image structure.
*/
image->columns=(size_t) pdb_image.width;
image->rows=(size_t) pdb_image.height;
image->depth=8;
image->storage_class=PseudoClass;
bits_per_pixel=pdb_image.type == 0 ? 2UL : pdb_image.type == 2 ? 4UL : 1UL;
one=1;
if (AcquireImageColormap(image,one << bits_per_pixel) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
packets=(bits_per_pixel*image->columns+7)/8;
pixels=(unsigned char *) AcquireQuantumMemory(packets+257UL,image->rows*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
switch (pdb_image.version & 0x07)
{
case 0:
{
image->compression=NoCompression;
count=(ssize_t) ReadBlob(image, packets * image -> rows, pixels);
break;
}
case 1:
{
image->compression=RLECompression;
if (!DecodeImage(image, pixels, packets * image -> rows))
ThrowReaderException( CorruptImageError, "RLEDecoderError" );
break;
}
default:
ThrowReaderException(CorruptImageError,
"UnrecognizedImageCompressionType" );
}
p=pixels;
switch (bits_per_pixel)
{
case 1:
{
int
bit;
/*
Read 1-bit PDB image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=(IndexPacket) (*p & (0x80 >> bit) ? 0x00 : 0x01);
SetPixelIndex(indexes+x+bit,index);
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
break;
}
case 2:
{
/*
Read 2-bit PDB image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns-3; x+=4)
{
index=ConstrainColormapIndex(image,3UL-((*p >> 6) & 0x03));
SetPixelIndex(indexes+x,index);
index=ConstrainColormapIndex(image,3UL-((*p >> 4) & 0x03));
SetPixelIndex(indexes+x+1,index);
index=ConstrainColormapIndex(image,3UL-((*p >> 2) & 0x03));
SetPixelIndex(indexes+x+2,index);
index=ConstrainColormapIndex(image,3UL-((*p) & 0x03));
SetPixelIndex(indexes+x+3,index);
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
break;
}
case 4:
{
/*
Read 4-bit PDB image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns-1; x+=2)
{
index=ConstrainColormapIndex(image,15UL-((*p >> 4) & 0x0f));
SetPixelIndex(indexes+x,index);
index=ConstrainColormapIndex(image,15UL-((*p) & 0x0f));
SetPixelIndex(indexes+x+1,index);
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
break;
}
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
if (pdb_info.number_records > 1)
{
char
*comment;
int
c;
register char
*p;
size_t
length;
num_pad_bytes = (size_t) (comment_offset - TellBlob( image ));
while (num_pad_bytes--) ReadBlobByte( image );
/*
Read comment.
*/
c=ReadBlobByte(image);
length=MaxTextExtent;
comment=AcquireString((char *) NULL);
for (p=comment; c != EOF; p++)
{
if ((size_t) (p-comment+MaxTextExtent) >= length)
{
*p='\0';
length<<=1;
length+=MaxTextExtent;
comment=(char *) ResizeQuantumMemory(comment,length+MaxTextExtent,
sizeof(*comment));
if (comment == (char *) NULL)
break;
p=comment+strlen(comment);
}
*p=c;
c=ReadBlobByte(image);
}
*p='\0';
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P D B I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPDBImage() adds properties for the PDB image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterPDBImage method is:
%
% size_t RegisterPDBImage(void)
%
*/
ModuleExport size_t RegisterPDBImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("PDB");
entry->decoder=(DecodeImageHandler *) ReadPDBImage;
entry->encoder=(EncodeImageHandler *) WritePDBImage;
entry->magick=(IsImageFormatHandler *) IsPDB;
entry->description=ConstantString("Palm Database ImageViewer Format");
entry->module=ConstantString("PDB");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P D B I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPDBImage() removes format registrations made by the
% PDB module from the list of supported formats.
%
% The format of the UnregisterPDBImage method is:
%
% UnregisterPDBImage(void)
%
*/
ModuleExport void UnregisterPDBImage(void)
{
(void) UnregisterMagickInfo("PDB");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P D B I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePDBImage() writes an image
%
% The format of the WritePDBImage method is:
%
% MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
%
*/
static unsigned char *EncodeRLE(unsigned char *destination,
unsigned char *source,size_t literal,size_t repeat)
{
if (literal > 0)
*destination++=(unsigned char) (literal-1);
(void) CopyMagickMemory(destination,source,literal);
destination+=literal;
if (repeat > 0)
{
*destination++=(unsigned char) (0x80 | (repeat-1));
*destination++=source[literal];
}
return(destination);
}
static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image)
{
const char
*comment;
int
bits;
MagickBooleanType
status;
PDBImage
pdb_image;
PDBInfo
pdb_info;
QuantumInfo
*quantum_info;
register const PixelPacket
*p;
register ssize_t
x;
register unsigned char
*q;
size_t
bits_per_pixel,
literal,
packets,
packet_size,
repeat;
ssize_t
y;
unsigned char
*buffer,
*runlength,
*scanline;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
if ((image -> colors <= 2 ) ||
(GetImageType(image,&image->exception ) == BilevelType)) {
bits_per_pixel=1;
} else if (image->colors <= 4) {
bits_per_pixel=2;
} else if (image->colors <= 8) {
bits_per_pixel=3;
} else {
bits_per_pixel=4;
}
(void) ResetMagickMemory(&pdb_info,0,sizeof(pdb_info));
(void) CopyMagickString(pdb_info.name,image_info->filename,
sizeof(pdb_info.name));
pdb_info.attributes=0;
pdb_info.version=0;
pdb_info.create_time=time(NULL);
pdb_info.modify_time=pdb_info.create_time;
pdb_info.archive_time=0;
pdb_info.modify_number=0;
pdb_info.application_info=0;
pdb_info.sort_info=0;
(void) CopyMagickMemory(pdb_info.type,"vIMG",4);
(void) CopyMagickMemory(pdb_info.id,"View",4);
pdb_info.seed=0;
pdb_info.next_record=0;
comment=GetImageProperty(image,"comment");
pdb_info.number_records=(comment == (const char *) NULL ? 1 : 2);
(void) WriteBlob(image,sizeof(pdb_info.name),(unsigned char *) pdb_info.name);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_info.attributes);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_info.version);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.create_time);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_time);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.archive_time);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_number);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.application_info);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.sort_info);
(void) WriteBlob(image,4,(unsigned char *) pdb_info.type);
(void) WriteBlob(image,4,(unsigned char *) pdb_info.id);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.seed);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.next_record);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_info.number_records);
(void) CopyMagickString(pdb_image.name,pdb_info.name,sizeof(pdb_image.name));
pdb_image.version=1; /* RLE Compressed */
switch (bits_per_pixel)
{
case 1: pdb_image.type=(unsigned char) 0xff; break; /* monochrome */
case 2: pdb_image.type=(unsigned char) 0x00; break; /* 2 bit gray */
default: pdb_image.type=(unsigned char) 0x02; /* 4 bit gray */
}
pdb_image.reserved_1=0;
pdb_image.note=0;
pdb_image.x_last=0;
pdb_image.y_last=0;
pdb_image.reserved_2=0;
pdb_image.x_anchor=(unsigned short) 0xffff;
pdb_image.y_anchor=(unsigned short) 0xffff;
pdb_image.width=(short) image->columns;
if (image->columns % 16)
pdb_image.width=(short) (16*(image->columns/16+1));
pdb_image.height=(short) image->rows;
packets=((bits_per_pixel*image->columns+7)/8);
runlength=(unsigned char *) AcquireQuantumMemory(9UL*packets,
image->rows*sizeof(*runlength));
if (runlength == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
buffer=(unsigned char *) AcquireQuantumMemory(512,sizeof(*buffer));
if (buffer == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
packet_size=(size_t) (image->depth > 8 ? 2: 1);
scanline=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Convert to GRAY raster scanline.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
bits=8/(int) bits_per_pixel-1; /* start at most significant bits */
literal=0;
repeat=0;
q=runlength;
buffer[0]=0x00;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info,
GrayQuantum,scanline,&image->exception);
for (x=0; x < (ssize_t) pdb_image.width; x++)
{
if (x < (ssize_t) image->columns)
buffer[literal+repeat]|=(0xff-scanline[x*packet_size]) >>
(8-bits_per_pixel) << bits*bits_per_pixel;
bits--;
if (bits < 0)
{
if (((literal+repeat) > 0) &&
(buffer[literal+repeat] == buffer[literal+repeat-1]))
{
if (repeat == 0)
{
literal--;
repeat++;
}
repeat++;
if (0x7f < repeat)
{
q=EncodeRLE(q,buffer,literal,repeat);
literal=0;
repeat=0;
}
}
else
{
if (repeat >= 2)
literal+=repeat;
else
{
q=EncodeRLE(q,buffer,literal,repeat);
buffer[0]=buffer[literal+repeat];
literal=0;
}
literal++;
repeat=0;
if (0x7f < literal)
{
q=EncodeRLE(q,buffer,(literal < 0x80 ? literal : 0x80),0);
(void) CopyMagickMemory(buffer,buffer+literal+repeat,0x80);
literal-=0x80;
}
}
bits=8/(int) bits_per_pixel-1;
buffer[literal+repeat]=0x00;
}
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
q=EncodeRLE(q,buffer,literal,repeat);
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
quantum_info=DestroyQuantumInfo(quantum_info);
/*
Write the Image record header.
*/
(void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8*
pdb_info.number_records));
(void) WriteBlobByte(image,0x40);
(void) WriteBlobByte(image,0x6f);
(void) WriteBlobByte(image,0x80);
(void) WriteBlobByte(image,0);
if (pdb_info.number_records > 1)
{
/*
Write the comment record header.
*/
(void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8+58+q-
runlength));
(void) WriteBlobByte(image,0x40);
(void) WriteBlobByte(image,0x6f);
(void) WriteBlobByte(image,0x80);
(void) WriteBlobByte(image,1);
}
/*
Write the Image data.
*/
(void) WriteBlob(image,sizeof(pdb_image.name),(unsigned char *)
pdb_image.name);
(void) WriteBlobByte(image,(unsigned char) pdb_image.version);
(void) WriteBlobByte(image,pdb_image.type);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_1);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_image.note);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_image.x_last);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_image.y_last);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_2);
(void) WriteBlobMSBShort(image,pdb_image.x_anchor);
(void) WriteBlobMSBShort(image,pdb_image.y_anchor);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_image.width);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_image.height);
(void) WriteBlob(image,(size_t) (q-runlength),runlength);
runlength=(unsigned char *) RelinquishMagickMemory(runlength);
if (pdb_info.number_records > 1)
(void) WriteBlobString(image,comment);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4779_2 |
crossvul-cpp_data_good_4907_0 | /**
* eCryptfs: Linux filesystem encryption layer
*
* Copyright (C) 2008 International Business Machines Corp.
* Author(s): Michael A. Halcrow <mahalcro@us.ibm.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/slab.h>
#include <linux/wait.h>
#include <linux/mount.h>
#include <linux/file.h>
#include "ecryptfs_kernel.h"
struct ecryptfs_open_req {
struct file **lower_file;
struct path path;
struct completion done;
struct list_head kthread_ctl_list;
};
static struct ecryptfs_kthread_ctl {
#define ECRYPTFS_KTHREAD_ZOMBIE 0x00000001
u32 flags;
struct mutex mux;
struct list_head req_list;
wait_queue_head_t wait;
} ecryptfs_kthread_ctl;
static struct task_struct *ecryptfs_kthread;
/**
* ecryptfs_threadfn
* @ignored: ignored
*
* The eCryptfs kernel thread that has the responsibility of getting
* the lower file with RW permissions.
*
* Returns zero on success; non-zero otherwise
*/
static int ecryptfs_threadfn(void *ignored)
{
set_freezable();
while (1) {
struct ecryptfs_open_req *req;
wait_event_freezable(
ecryptfs_kthread_ctl.wait,
(!list_empty(&ecryptfs_kthread_ctl.req_list)
|| kthread_should_stop()));
mutex_lock(&ecryptfs_kthread_ctl.mux);
if (ecryptfs_kthread_ctl.flags & ECRYPTFS_KTHREAD_ZOMBIE) {
mutex_unlock(&ecryptfs_kthread_ctl.mux);
goto out;
}
while (!list_empty(&ecryptfs_kthread_ctl.req_list)) {
req = list_first_entry(&ecryptfs_kthread_ctl.req_list,
struct ecryptfs_open_req,
kthread_ctl_list);
list_del(&req->kthread_ctl_list);
*req->lower_file = dentry_open(&req->path,
(O_RDWR | O_LARGEFILE), current_cred());
complete(&req->done);
}
mutex_unlock(&ecryptfs_kthread_ctl.mux);
}
out:
return 0;
}
int __init ecryptfs_init_kthread(void)
{
int rc = 0;
mutex_init(&ecryptfs_kthread_ctl.mux);
init_waitqueue_head(&ecryptfs_kthread_ctl.wait);
INIT_LIST_HEAD(&ecryptfs_kthread_ctl.req_list);
ecryptfs_kthread = kthread_run(&ecryptfs_threadfn, NULL,
"ecryptfs-kthread");
if (IS_ERR(ecryptfs_kthread)) {
rc = PTR_ERR(ecryptfs_kthread);
printk(KERN_ERR "%s: Failed to create kernel thread; rc = [%d]"
"\n", __func__, rc);
}
return rc;
}
void ecryptfs_destroy_kthread(void)
{
struct ecryptfs_open_req *req, *tmp;
mutex_lock(&ecryptfs_kthread_ctl.mux);
ecryptfs_kthread_ctl.flags |= ECRYPTFS_KTHREAD_ZOMBIE;
list_for_each_entry_safe(req, tmp, &ecryptfs_kthread_ctl.req_list,
kthread_ctl_list) {
list_del(&req->kthread_ctl_list);
*req->lower_file = ERR_PTR(-EIO);
complete(&req->done);
}
mutex_unlock(&ecryptfs_kthread_ctl.mux);
kthread_stop(ecryptfs_kthread);
wake_up(&ecryptfs_kthread_ctl.wait);
}
/**
* ecryptfs_privileged_open
* @lower_file: Result of dentry_open by root on lower dentry
* @lower_dentry: Lower dentry for file to open
* @lower_mnt: Lower vfsmount for file to open
*
* This function gets a r/w file opened againt the lower dentry.
*
* Returns zero on success; non-zero otherwise
*/
int ecryptfs_privileged_open(struct file **lower_file,
struct dentry *lower_dentry,
struct vfsmount *lower_mnt,
const struct cred *cred)
{
struct ecryptfs_open_req req;
int flags = O_LARGEFILE;
int rc = 0;
init_completion(&req.done);
req.lower_file = lower_file;
req.path.dentry = lower_dentry;
req.path.mnt = lower_mnt;
/* Corresponding dput() and mntput() are done when the
* lower file is fput() when all eCryptfs files for the inode are
* released. */
flags |= IS_RDONLY(d_inode(lower_dentry)) ? O_RDONLY : O_RDWR;
(*lower_file) = dentry_open(&req.path, flags, cred);
if (!IS_ERR(*lower_file))
goto have_file;
if ((flags & O_ACCMODE) == O_RDONLY) {
rc = PTR_ERR((*lower_file));
goto out;
}
mutex_lock(&ecryptfs_kthread_ctl.mux);
if (ecryptfs_kthread_ctl.flags & ECRYPTFS_KTHREAD_ZOMBIE) {
rc = -EIO;
mutex_unlock(&ecryptfs_kthread_ctl.mux);
printk(KERN_ERR "%s: We are in the middle of shutting down; "
"aborting privileged request to open lower file\n",
__func__);
goto out;
}
list_add_tail(&req.kthread_ctl_list, &ecryptfs_kthread_ctl.req_list);
mutex_unlock(&ecryptfs_kthread_ctl.mux);
wake_up(&ecryptfs_kthread_ctl.wait);
wait_for_completion(&req.done);
if (IS_ERR(*lower_file)) {
rc = PTR_ERR(*lower_file);
goto out;
}
have_file:
if ((*lower_file)->f_op->mmap == NULL) {
fput(*lower_file);
*lower_file = NULL;
rc = -EMEDIUMTYPE;
}
out:
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4907_0 |
crossvul-cpp_data_bad_2986_0 | /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
* Copyright (c) 2016 Facebook
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/bpf.h>
#include <linux/bpf_verifier.h>
#include <linux/filter.h>
#include <net/netlink.h>
#include <linux/file.h>
#include <linux/vmalloc.h>
#include <linux/stringify.h>
#include "disasm.h"
static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
#define BPF_PROG_TYPE(_id, _name) \
[_id] = & _name ## _verifier_ops,
#define BPF_MAP_TYPE(_id, _ops)
#include <linux/bpf_types.h>
#undef BPF_PROG_TYPE
#undef BPF_MAP_TYPE
};
/* bpf_check() is a static code analyzer that walks eBPF program
* instruction by instruction and updates register/stack state.
* All paths of conditional branches are analyzed until 'bpf_exit' insn.
*
* The first pass is depth-first-search to check that the program is a DAG.
* It rejects the following programs:
* - larger than BPF_MAXINSNS insns
* - if loop is present (detected via back-edge)
* - unreachable insns exist (shouldn't be a forest. program = one function)
* - out of bounds or malformed jumps
* The second pass is all possible path descent from the 1st insn.
* Since it's analyzing all pathes through the program, the length of the
* analysis is limited to 64k insn, which may be hit even if total number of
* insn is less then 4K, but there are too many branches that change stack/regs.
* Number of 'branches to be analyzed' is limited to 1k
*
* On entry to each instruction, each register has a type, and the instruction
* changes the types of the registers depending on instruction semantics.
* If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
* copied to R1.
*
* All registers are 64-bit.
* R0 - return register
* R1-R5 argument passing registers
* R6-R9 callee saved registers
* R10 - frame pointer read-only
*
* At the start of BPF program the register R1 contains a pointer to bpf_context
* and has type PTR_TO_CTX.
*
* Verifier tracks arithmetic operations on pointers in case:
* BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
* BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
* 1st insn copies R10 (which has FRAME_PTR) type into R1
* and 2nd arithmetic instruction is pattern matched to recognize
* that it wants to construct a pointer to some element within stack.
* So after 2nd insn, the register R1 has type PTR_TO_STACK
* (and -20 constant is saved for further stack bounds checking).
* Meaning that this reg is a pointer to stack plus known immediate constant.
*
* Most of the time the registers have SCALAR_VALUE type, which
* means the register has some value, but it's not a valid pointer.
* (like pointer plus pointer becomes SCALAR_VALUE type)
*
* When verifier sees load or store instructions the type of base register
* can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer
* types recognized by check_mem_access() function.
*
* PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
* and the range of [ptr, ptr + map's value_size) is accessible.
*
* registers used to pass values to function calls are checked against
* function argument constraints.
*
* ARG_PTR_TO_MAP_KEY is one of such argument constraints.
* It means that the register type passed to this function must be
* PTR_TO_STACK and it will be used inside the function as
* 'pointer to map element key'
*
* For example the argument constraints for bpf_map_lookup_elem():
* .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
* .arg1_type = ARG_CONST_MAP_PTR,
* .arg2_type = ARG_PTR_TO_MAP_KEY,
*
* ret_type says that this function returns 'pointer to map elem value or null'
* function expects 1st argument to be a const pointer to 'struct bpf_map' and
* 2nd argument should be a pointer to stack, which will be used inside
* the helper function as a pointer to map element key.
*
* On the kernel side the helper function looks like:
* u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
* {
* struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
* void *key = (void *) (unsigned long) r2;
* void *value;
*
* here kernel can access 'key' and 'map' pointers safely, knowing that
* [key, key + map->key_size) bytes are valid and were initialized on
* the stack of eBPF program.
* }
*
* Corresponding eBPF program may look like:
* BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
* BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
* BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
* BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
* here verifier looks at prototype of map_lookup_elem() and sees:
* .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
* Now verifier knows that this map has key of R1->map_ptr->key_size bytes
*
* Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
* Now verifier checks that [R2, R2 + map's key_size) are within stack limits
* and were initialized prior to this call.
* If it's ok, then verifier allows this BPF_CALL insn and looks at
* .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
* R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
* returns ether pointer to map value or NULL.
*
* When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
* insn, the register holding that pointer in the true branch changes state to
* PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
* branch. See check_cond_jmp_op().
*
* After the call R0 is set to return type of the function and registers R1-R5
* are set to NOT_INIT to indicate that they are no longer readable.
*/
/* verifier_state + insn_idx are pushed to stack when branch is encountered */
struct bpf_verifier_stack_elem {
/* verifer state is 'st'
* before processing instruction 'insn_idx'
* and after processing instruction 'prev_insn_idx'
*/
struct bpf_verifier_state st;
int insn_idx;
int prev_insn_idx;
struct bpf_verifier_stack_elem *next;
};
#define BPF_COMPLEXITY_LIMIT_INSNS 131072
#define BPF_COMPLEXITY_LIMIT_STACK 1024
#define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA)
struct bpf_call_arg_meta {
struct bpf_map *map_ptr;
bool raw_mode;
bool pkt_access;
int regno;
int access_size;
};
static DEFINE_MUTEX(bpf_verifier_lock);
/* log_level controls verbosity level of eBPF verifier.
* verbose() is used to dump the verification trace to the log, so the user
* can figure out what's wrong with the program
*/
static __printf(2, 3) void verbose(struct bpf_verifier_env *env,
const char *fmt, ...)
{
struct bpf_verifer_log *log = &env->log;
unsigned int n;
va_list args;
if (!log->level || !log->ubuf || bpf_verifier_log_full(log))
return;
va_start(args, fmt);
n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
va_end(args);
WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
"verifier log line truncated - local buffer too short\n");
n = min(log->len_total - log->len_used - 1, n);
log->kbuf[n] = '\0';
if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
log->len_used += n;
else
log->ubuf = NULL;
}
static bool type_is_pkt_pointer(enum bpf_reg_type type)
{
return type == PTR_TO_PACKET ||
type == PTR_TO_PACKET_META;
}
/* string representation of 'enum bpf_reg_type' */
static const char * const reg_type_str[] = {
[NOT_INIT] = "?",
[SCALAR_VALUE] = "inv",
[PTR_TO_CTX] = "ctx",
[CONST_PTR_TO_MAP] = "map_ptr",
[PTR_TO_MAP_VALUE] = "map_value",
[PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
[PTR_TO_STACK] = "fp",
[PTR_TO_PACKET] = "pkt",
[PTR_TO_PACKET_META] = "pkt_meta",
[PTR_TO_PACKET_END] = "pkt_end",
};
static void print_verifier_state(struct bpf_verifier_env *env,
struct bpf_verifier_state *state)
{
struct bpf_reg_state *reg;
enum bpf_reg_type t;
int i;
for (i = 0; i < MAX_BPF_REG; i++) {
reg = &state->regs[i];
t = reg->type;
if (t == NOT_INIT)
continue;
verbose(env, " R%d=%s", i, reg_type_str[t]);
if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
tnum_is_const(reg->var_off)) {
/* reg->off should be 0 for SCALAR_VALUE */
verbose(env, "%lld", reg->var_off.value + reg->off);
} else {
verbose(env, "(id=%d", reg->id);
if (t != SCALAR_VALUE)
verbose(env, ",off=%d", reg->off);
if (type_is_pkt_pointer(t))
verbose(env, ",r=%d", reg->range);
else if (t == CONST_PTR_TO_MAP ||
t == PTR_TO_MAP_VALUE ||
t == PTR_TO_MAP_VALUE_OR_NULL)
verbose(env, ",ks=%d,vs=%d",
reg->map_ptr->key_size,
reg->map_ptr->value_size);
if (tnum_is_const(reg->var_off)) {
/* Typically an immediate SCALAR_VALUE, but
* could be a pointer whose offset is too big
* for reg->off
*/
verbose(env, ",imm=%llx", reg->var_off.value);
} else {
if (reg->smin_value != reg->umin_value &&
reg->smin_value != S64_MIN)
verbose(env, ",smin_value=%lld",
(long long)reg->smin_value);
if (reg->smax_value != reg->umax_value &&
reg->smax_value != S64_MAX)
verbose(env, ",smax_value=%lld",
(long long)reg->smax_value);
if (reg->umin_value != 0)
verbose(env, ",umin_value=%llu",
(unsigned long long)reg->umin_value);
if (reg->umax_value != U64_MAX)
verbose(env, ",umax_value=%llu",
(unsigned long long)reg->umax_value);
if (!tnum_is_unknown(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, ",var_off=%s", tn_buf);
}
}
verbose(env, ")");
}
}
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] == STACK_SPILL)
verbose(env, " fp%d=%s",
-MAX_BPF_STACK + i * BPF_REG_SIZE,
reg_type_str[state->stack[i].spilled_ptr.type]);
}
verbose(env, "\n");
}
static int copy_stack_state(struct bpf_verifier_state *dst,
const struct bpf_verifier_state *src)
{
if (!src->stack)
return 0;
if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) {
/* internal bug, make state invalid to reject the program */
memset(dst, 0, sizeof(*dst));
return -EFAULT;
}
memcpy(dst->stack, src->stack,
sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE));
return 0;
}
/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
* make it consume minimal amount of memory. check_stack_write() access from
* the program calls into realloc_verifier_state() to grow the stack size.
* Note there is a non-zero 'parent' pointer inside bpf_verifier_state
* which this function copies over. It points to previous bpf_verifier_state
* which is never reallocated
*/
static int realloc_verifier_state(struct bpf_verifier_state *state, int size,
bool copy_old)
{
u32 old_size = state->allocated_stack;
struct bpf_stack_state *new_stack;
int slot = size / BPF_REG_SIZE;
if (size <= old_size || !size) {
if (copy_old)
return 0;
state->allocated_stack = slot * BPF_REG_SIZE;
if (!size && old_size) {
kfree(state->stack);
state->stack = NULL;
}
return 0;
}
new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state),
GFP_KERNEL);
if (!new_stack)
return -ENOMEM;
if (copy_old) {
if (state->stack)
memcpy(new_stack, state->stack,
sizeof(*new_stack) * (old_size / BPF_REG_SIZE));
memset(new_stack + old_size / BPF_REG_SIZE, 0,
sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE);
}
state->allocated_stack = slot * BPF_REG_SIZE;
kfree(state->stack);
state->stack = new_stack;
return 0;
}
static void free_verifier_state(struct bpf_verifier_state *state,
bool free_self)
{
kfree(state->stack);
if (free_self)
kfree(state);
}
/* copy verifier state from src to dst growing dst stack space
* when necessary to accommodate larger src stack
*/
static int copy_verifier_state(struct bpf_verifier_state *dst,
const struct bpf_verifier_state *src)
{
int err;
err = realloc_verifier_state(dst, src->allocated_stack, false);
if (err)
return err;
memcpy(dst, src, offsetof(struct bpf_verifier_state, allocated_stack));
return copy_stack_state(dst, src);
}
static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
int *insn_idx)
{
struct bpf_verifier_state *cur = env->cur_state;
struct bpf_verifier_stack_elem *elem, *head = env->head;
int err;
if (env->head == NULL)
return -ENOENT;
if (cur) {
err = copy_verifier_state(cur, &head->st);
if (err)
return err;
}
if (insn_idx)
*insn_idx = head->insn_idx;
if (prev_insn_idx)
*prev_insn_idx = head->prev_insn_idx;
elem = head->next;
free_verifier_state(&head->st, false);
kfree(head);
env->head = elem;
env->stack_size--;
return 0;
}
static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
int insn_idx, int prev_insn_idx)
{
struct bpf_verifier_state *cur = env->cur_state;
struct bpf_verifier_stack_elem *elem;
int err;
elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
if (!elem)
goto err;
elem->insn_idx = insn_idx;
elem->prev_insn_idx = prev_insn_idx;
elem->next = env->head;
env->head = elem;
env->stack_size++;
err = copy_verifier_state(&elem->st, cur);
if (err)
goto err;
if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
verbose(env, "BPF program is too complex\n");
goto err;
}
return &elem->st;
err:
/* pop all elements and return */
while (!pop_stack(env, NULL, NULL));
return NULL;
}
#define CALLER_SAVED_REGS 6
static const int caller_saved[CALLER_SAVED_REGS] = {
BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
};
static void __mark_reg_not_init(struct bpf_reg_state *reg);
/* Mark the unknown part of a register (variable offset or scalar value) as
* known to have the value @imm.
*/
static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
{
reg->id = 0;
reg->var_off = tnum_const(imm);
reg->smin_value = (s64)imm;
reg->smax_value = (s64)imm;
reg->umin_value = imm;
reg->umax_value = imm;
}
/* Mark the 'variable offset' part of a register as zero. This should be
* used only on registers holding a pointer type.
*/
static void __mark_reg_known_zero(struct bpf_reg_state *reg)
{
__mark_reg_known(reg, 0);
}
static void mark_reg_known_zero(struct bpf_verifier_env *env,
struct bpf_reg_state *regs, u32 regno)
{
if (WARN_ON(regno >= MAX_BPF_REG)) {
verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
/* Something bad happened, let's kill all regs */
for (regno = 0; regno < MAX_BPF_REG; regno++)
__mark_reg_not_init(regs + regno);
return;
}
__mark_reg_known_zero(regs + regno);
}
static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
{
return type_is_pkt_pointer(reg->type);
}
static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
{
return reg_is_pkt_pointer(reg) ||
reg->type == PTR_TO_PACKET_END;
}
/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
enum bpf_reg_type which)
{
/* The register can already have a range from prior markings.
* This is fine as long as it hasn't been advanced from its
* origin.
*/
return reg->type == which &&
reg->id == 0 &&
reg->off == 0 &&
tnum_equals_const(reg->var_off, 0);
}
/* Attempts to improve min/max values based on var_off information */
static void __update_reg_bounds(struct bpf_reg_state *reg)
{
/* min signed is max(sign bit) | min(other bits) */
reg->smin_value = max_t(s64, reg->smin_value,
reg->var_off.value | (reg->var_off.mask & S64_MIN));
/* max signed is min(sign bit) | max(other bits) */
reg->smax_value = min_t(s64, reg->smax_value,
reg->var_off.value | (reg->var_off.mask & S64_MAX));
reg->umin_value = max(reg->umin_value, reg->var_off.value);
reg->umax_value = min(reg->umax_value,
reg->var_off.value | reg->var_off.mask);
}
/* Uses signed min/max values to inform unsigned, and vice-versa */
static void __reg_deduce_bounds(struct bpf_reg_state *reg)
{
/* Learn sign from signed bounds.
* If we cannot cross the sign boundary, then signed and unsigned bounds
* are the same, so combine. This works even in the negative case, e.g.
* -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
*/
if (reg->smin_value >= 0 || reg->smax_value < 0) {
reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
reg->umin_value);
reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
reg->umax_value);
return;
}
/* Learn sign from unsigned bounds. Signed bounds cross the sign
* boundary, so we must be careful.
*/
if ((s64)reg->umax_value >= 0) {
/* Positive. We can't learn anything from the smin, but smax
* is positive, hence safe.
*/
reg->smin_value = reg->umin_value;
reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
reg->umax_value);
} else if ((s64)reg->umin_value < 0) {
/* Negative. We can't learn anything from the smax, but smin
* is negative, hence safe.
*/
reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
reg->umin_value);
reg->smax_value = reg->umax_value;
}
}
/* Attempts to improve var_off based on unsigned min/max information */
static void __reg_bound_offset(struct bpf_reg_state *reg)
{
reg->var_off = tnum_intersect(reg->var_off,
tnum_range(reg->umin_value,
reg->umax_value));
}
/* Reset the min/max bounds of a register */
static void __mark_reg_unbounded(struct bpf_reg_state *reg)
{
reg->smin_value = S64_MIN;
reg->smax_value = S64_MAX;
reg->umin_value = 0;
reg->umax_value = U64_MAX;
}
/* Mark a register as having a completely unknown (scalar) value. */
static void __mark_reg_unknown(struct bpf_reg_state *reg)
{
reg->type = SCALAR_VALUE;
reg->id = 0;
reg->off = 0;
reg->var_off = tnum_unknown;
__mark_reg_unbounded(reg);
}
static void mark_reg_unknown(struct bpf_verifier_env *env,
struct bpf_reg_state *regs, u32 regno)
{
if (WARN_ON(regno >= MAX_BPF_REG)) {
verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
/* Something bad happened, let's kill all regs */
for (regno = 0; regno < MAX_BPF_REG; regno++)
__mark_reg_not_init(regs + regno);
return;
}
__mark_reg_unknown(regs + regno);
}
static void __mark_reg_not_init(struct bpf_reg_state *reg)
{
__mark_reg_unknown(reg);
reg->type = NOT_INIT;
}
static void mark_reg_not_init(struct bpf_verifier_env *env,
struct bpf_reg_state *regs, u32 regno)
{
if (WARN_ON(regno >= MAX_BPF_REG)) {
verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
/* Something bad happened, let's kill all regs */
for (regno = 0; regno < MAX_BPF_REG; regno++)
__mark_reg_not_init(regs + regno);
return;
}
__mark_reg_not_init(regs + regno);
}
static void init_reg_state(struct bpf_verifier_env *env,
struct bpf_reg_state *regs)
{
int i;
for (i = 0; i < MAX_BPF_REG; i++) {
mark_reg_not_init(env, regs, i);
regs[i].live = REG_LIVE_NONE;
}
/* frame pointer */
regs[BPF_REG_FP].type = PTR_TO_STACK;
mark_reg_known_zero(env, regs, BPF_REG_FP);
/* 1st arg to a function */
regs[BPF_REG_1].type = PTR_TO_CTX;
mark_reg_known_zero(env, regs, BPF_REG_1);
}
enum reg_arg_type {
SRC_OP, /* register is used as source operand */
DST_OP, /* register is used as destination operand */
DST_OP_NO_MARK /* same as above, check only, don't mark */
};
static void mark_reg_read(const struct bpf_verifier_state *state, u32 regno)
{
struct bpf_verifier_state *parent = state->parent;
if (regno == BPF_REG_FP)
/* We don't need to worry about FP liveness because it's read-only */
return;
while (parent) {
/* if read wasn't screened by an earlier write ... */
if (state->regs[regno].live & REG_LIVE_WRITTEN)
break;
/* ... then we depend on parent's value */
parent->regs[regno].live |= REG_LIVE_READ;
state = parent;
parent = state->parent;
}
}
static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
enum reg_arg_type t)
{
struct bpf_reg_state *regs = env->cur_state->regs;
if (regno >= MAX_BPF_REG) {
verbose(env, "R%d is invalid\n", regno);
return -EINVAL;
}
if (t == SRC_OP) {
/* check whether register used as source operand can be read */
if (regs[regno].type == NOT_INIT) {
verbose(env, "R%d !read_ok\n", regno);
return -EACCES;
}
mark_reg_read(env->cur_state, regno);
} else {
/* check whether register used as dest operand can be written to */
if (regno == BPF_REG_FP) {
verbose(env, "frame pointer is read only\n");
return -EACCES;
}
regs[regno].live |= REG_LIVE_WRITTEN;
if (t == DST_OP)
mark_reg_unknown(env, regs, regno);
}
return 0;
}
static bool is_spillable_regtype(enum bpf_reg_type type)
{
switch (type) {
case PTR_TO_MAP_VALUE:
case PTR_TO_MAP_VALUE_OR_NULL:
case PTR_TO_STACK:
case PTR_TO_CTX:
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
case PTR_TO_PACKET_END:
case CONST_PTR_TO_MAP:
return true;
default:
return false;
}
}
/* check_stack_read/write functions track spill/fill of registers,
* stack boundary and alignment are checked in check_mem_access()
*/
static int check_stack_write(struct bpf_verifier_env *env,
struct bpf_verifier_state *state, int off,
int size, int value_regno)
{
int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
err = realloc_verifier_state(state, round_up(slot + 1, BPF_REG_SIZE),
true);
if (err)
return err;
/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
* so it's aligned access and [off, off + size) are within stack limits
*/
if (!env->allow_ptr_leaks &&
state->stack[spi].slot_type[0] == STACK_SPILL &&
size != BPF_REG_SIZE) {
verbose(env, "attempt to corrupt spilled pointer on stack\n");
return -EACCES;
}
if (value_regno >= 0 &&
is_spillable_regtype(state->regs[value_regno].type)) {
/* register containing pointer is being spilled into stack */
if (size != BPF_REG_SIZE) {
verbose(env, "invalid size of register spill\n");
return -EACCES;
}
/* save register state */
state->stack[spi].spilled_ptr = state->regs[value_regno];
state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
for (i = 0; i < BPF_REG_SIZE; i++)
state->stack[spi].slot_type[i] = STACK_SPILL;
} else {
/* regular write of data into stack */
state->stack[spi].spilled_ptr = (struct bpf_reg_state) {};
for (i = 0; i < size; i++)
state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
STACK_MISC;
}
return 0;
}
static void mark_stack_slot_read(const struct bpf_verifier_state *state, int slot)
{
struct bpf_verifier_state *parent = state->parent;
while (parent) {
/* if read wasn't screened by an earlier write ... */
if (state->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN)
break;
/* ... then we depend on parent's value */
parent->stack[slot].spilled_ptr.live |= REG_LIVE_READ;
state = parent;
parent = state->parent;
}
}
static int check_stack_read(struct bpf_verifier_env *env,
struct bpf_verifier_state *state, int off, int size,
int value_regno)
{
int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
u8 *stype;
if (state->allocated_stack <= slot) {
verbose(env, "invalid read from stack off %d+0 size %d\n",
off, size);
return -EACCES;
}
stype = state->stack[spi].slot_type;
if (stype[0] == STACK_SPILL) {
if (size != BPF_REG_SIZE) {
verbose(env, "invalid size of register spill\n");
return -EACCES;
}
for (i = 1; i < BPF_REG_SIZE; i++) {
if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
verbose(env, "corrupted spill memory\n");
return -EACCES;
}
}
if (value_regno >= 0) {
/* restore register state from stack */
state->regs[value_regno] = state->stack[spi].spilled_ptr;
mark_stack_slot_read(state, spi);
}
return 0;
} else {
for (i = 0; i < size; i++) {
if (stype[(slot - i) % BPF_REG_SIZE] != STACK_MISC) {
verbose(env, "invalid read from stack off %d+%d size %d\n",
off, i, size);
return -EACCES;
}
}
if (value_regno >= 0)
/* have read misc data from the stack */
mark_reg_unknown(env, state->regs, value_regno);
return 0;
}
}
/* check read/write into map element returned by bpf_map_lookup_elem() */
static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
int size, bool zero_size_allowed)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_map *map = regs[regno].map_ptr;
if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
off + size > map->value_size) {
verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
map->value_size, off, size);
return -EACCES;
}
return 0;
}
/* check read/write into a map element with possible variable offset */
static int check_map_access(struct bpf_verifier_env *env, u32 regno,
int off, int size, bool zero_size_allowed)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_reg_state *reg = &state->regs[regno];
int err;
/* We may have adjusted the register to this map value, so we
* need to try adding each of min_value and max_value to off
* to make sure our theoretical access will be safe.
*/
if (env->log.level)
print_verifier_state(env, state);
/* The minimum value is only important with signed
* comparisons where we can't assume the floor of a
* value is 0. If we are using signed variables for our
* index'es we need to make sure that whatever we use
* will have a set floor within our range.
*/
if (reg->smin_value < 0) {
verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
regno);
return -EACCES;
}
err = __check_map_access(env, regno, reg->smin_value + off, size,
zero_size_allowed);
if (err) {
verbose(env, "R%d min value is outside of the array range\n",
regno);
return err;
}
/* If we haven't set a max value then we need to bail since we can't be
* sure we won't do bad things.
* If reg->umax_value + off could overflow, treat that as unbounded too.
*/
if (reg->umax_value >= BPF_MAX_VAR_OFF) {
verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
regno);
return -EACCES;
}
err = __check_map_access(env, regno, reg->umax_value + off, size,
zero_size_allowed);
if (err)
verbose(env, "R%d max value is outside of the array range\n",
regno);
return err;
}
#define MAX_PACKET_OFF 0xffff
static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
const struct bpf_call_arg_meta *meta,
enum bpf_access_type t)
{
switch (env->prog->type) {
case BPF_PROG_TYPE_LWT_IN:
case BPF_PROG_TYPE_LWT_OUT:
/* dst_input() and dst_output() can't write for now */
if (t == BPF_WRITE)
return false;
/* fallthrough */
case BPF_PROG_TYPE_SCHED_CLS:
case BPF_PROG_TYPE_SCHED_ACT:
case BPF_PROG_TYPE_XDP:
case BPF_PROG_TYPE_LWT_XMIT:
case BPF_PROG_TYPE_SK_SKB:
if (meta)
return meta->pkt_access;
env->seen_direct_write = true;
return true;
default:
return false;
}
}
static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
int off, int size, bool zero_size_allowed)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_reg_state *reg = ®s[regno];
if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
(u64)off + size > reg->range) {
verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
off, size, regno, reg->id, reg->off, reg->range);
return -EACCES;
}
return 0;
}
static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
int size, bool zero_size_allowed)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_reg_state *reg = ®s[regno];
int err;
/* We may have added a variable offset to the packet pointer; but any
* reg->range we have comes after that. We are only checking the fixed
* offset.
*/
/* We don't allow negative numbers, because we aren't tracking enough
* detail to prove they're safe.
*/
if (reg->smin_value < 0) {
verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
regno);
return -EACCES;
}
err = __check_packet_access(env, regno, off, size, zero_size_allowed);
if (err) {
verbose(env, "R%d offset is outside of the packet\n", regno);
return err;
}
return err;
}
/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
enum bpf_access_type t, enum bpf_reg_type *reg_type)
{
struct bpf_insn_access_aux info = {
.reg_type = *reg_type,
};
if (env->ops->is_valid_access &&
env->ops->is_valid_access(off, size, t, &info)) {
/* A non zero info.ctx_field_size indicates that this field is a
* candidate for later verifier transformation to load the whole
* field and then apply a mask when accessed with a narrower
* access than actual ctx access size. A zero info.ctx_field_size
* will only allow for whole field access and rejects any other
* type of narrower access.
*/
*reg_type = info.reg_type;
env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
/* remember the offset of last byte accessed in ctx */
if (env->prog->aux->max_ctx_offset < off + size)
env->prog->aux->max_ctx_offset = off + size;
return 0;
}
verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
return -EACCES;
}
static bool __is_pointer_value(bool allow_ptr_leaks,
const struct bpf_reg_state *reg)
{
if (allow_ptr_leaks)
return false;
return reg->type != SCALAR_VALUE;
}
static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
{
return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno);
}
static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
int off, int size, bool strict)
{
struct tnum reg_off;
int ip_align;
/* Byte size accesses are always allowed. */
if (!strict || size == 1)
return 0;
/* For platforms that do not have a Kconfig enabling
* CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
* NET_IP_ALIGN is universally set to '2'. And on platforms
* that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
* to this code only in strict mode where we want to emulate
* the NET_IP_ALIGN==2 checking. Therefore use an
* unconditional IP align value of '2'.
*/
ip_align = 2;
reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
if (!tnum_is_aligned(reg_off, size)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env,
"misaligned packet access off %d+%s+%d+%d size %d\n",
ip_align, tn_buf, reg->off, off, size);
return -EACCES;
}
return 0;
}
static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
const char *pointer_desc,
int off, int size, bool strict)
{
struct tnum reg_off;
/* Byte size accesses are always allowed. */
if (!strict || size == 1)
return 0;
reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
if (!tnum_is_aligned(reg_off, size)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
pointer_desc, tn_buf, reg->off, off, size);
return -EACCES;
}
return 0;
}
static int check_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
int off, int size)
{
bool strict = env->strict_alignment;
const char *pointer_desc = "";
switch (reg->type) {
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
/* Special case, because of NET_IP_ALIGN. Given metadata sits
* right in front, treat it the very same way.
*/
return check_pkt_ptr_alignment(env, reg, off, size, strict);
case PTR_TO_MAP_VALUE:
pointer_desc = "value ";
break;
case PTR_TO_CTX:
pointer_desc = "context ";
break;
case PTR_TO_STACK:
pointer_desc = "stack ";
/* The stack spill tracking logic in check_stack_write()
* and check_stack_read() relies on stack accesses being
* aligned.
*/
strict = true;
break;
default:
break;
}
return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
strict);
}
/* truncate register to smaller size (in bytes)
* must be called with size < BPF_REG_SIZE
*/
static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
{
u64 mask;
/* clear high bits in bit representation */
reg->var_off = tnum_cast(reg->var_off, size);
/* fix arithmetic bounds */
mask = ((u64)1 << (size * 8)) - 1;
if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
reg->umin_value &= mask;
reg->umax_value &= mask;
} else {
reg->umin_value = 0;
reg->umax_value = mask;
}
reg->smin_value = reg->umin_value;
reg->smax_value = reg->umax_value;
}
/* check whether memory at (regno + off) is accessible for t = (read | write)
* if t==write, value_regno is a register which value is stored into memory
* if t==read, value_regno is a register which will receive the value from memory
* if t==write && value_regno==-1, some unknown value is stored into memory
* if t==read && value_regno==-1, don't care what we read from memory
*/
static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, int off,
int bpf_size, enum bpf_access_type t,
int value_regno)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_reg_state *reg = regs + regno;
int size, err = 0;
size = bpf_size_to_bytes(bpf_size);
if (size < 0)
return size;
/* alignment checks will add in reg->off themselves */
err = check_ptr_alignment(env, reg, off, size);
if (err)
return err;
/* for access checks, reg->off is just part of off */
off += reg->off;
if (reg->type == PTR_TO_MAP_VALUE) {
if (t == BPF_WRITE && value_regno >= 0 &&
is_pointer_value(env, value_regno)) {
verbose(env, "R%d leaks addr into map\n", value_regno);
return -EACCES;
}
err = check_map_access(env, regno, off, size, false);
if (!err && t == BPF_READ && value_regno >= 0)
mark_reg_unknown(env, regs, value_regno);
} else if (reg->type == PTR_TO_CTX) {
enum bpf_reg_type reg_type = SCALAR_VALUE;
if (t == BPF_WRITE && value_regno >= 0 &&
is_pointer_value(env, value_regno)) {
verbose(env, "R%d leaks addr into ctx\n", value_regno);
return -EACCES;
}
/* ctx accesses must be at a fixed offset, so that we can
* determine what type of data were returned.
*/
if (reg->off) {
verbose(env,
"dereference of modified ctx ptr R%d off=%d+%d, ctx+const is allowed, ctx+const+const is not\n",
regno, reg->off, off - reg->off);
return -EACCES;
}
if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env,
"variable ctx access var_off=%s off=%d size=%d",
tn_buf, off, size);
return -EACCES;
}
err = check_ctx_access(env, insn_idx, off, size, t, ®_type);
if (!err && t == BPF_READ && value_regno >= 0) {
/* ctx access returns either a scalar, or a
* PTR_TO_PACKET[_META,_END]. In the latter
* case, we know the offset is zero.
*/
if (reg_type == SCALAR_VALUE)
mark_reg_unknown(env, regs, value_regno);
else
mark_reg_known_zero(env, regs,
value_regno);
regs[value_regno].id = 0;
regs[value_regno].off = 0;
regs[value_regno].range = 0;
regs[value_regno].type = reg_type;
}
} else if (reg->type == PTR_TO_STACK) {
/* stack accesses must be at a fixed offset, so that we can
* determine what type of data were returned.
* See check_stack_read().
*/
if (!tnum_is_const(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "variable stack access var_off=%s off=%d size=%d",
tn_buf, off, size);
return -EACCES;
}
off += reg->var_off.value;
if (off >= 0 || off < -MAX_BPF_STACK) {
verbose(env, "invalid stack off=%d size=%d\n", off,
size);
return -EACCES;
}
if (env->prog->aux->stack_depth < -off)
env->prog->aux->stack_depth = -off;
if (t == BPF_WRITE)
err = check_stack_write(env, state, off, size,
value_regno);
else
err = check_stack_read(env, state, off, size,
value_regno);
} else if (reg_is_pkt_pointer(reg)) {
if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
verbose(env, "cannot write into packet\n");
return -EACCES;
}
if (t == BPF_WRITE && value_regno >= 0 &&
is_pointer_value(env, value_regno)) {
verbose(env, "R%d leaks addr into packet\n",
value_regno);
return -EACCES;
}
err = check_packet_access(env, regno, off, size, false);
if (!err && t == BPF_READ && value_regno >= 0)
mark_reg_unknown(env, regs, value_regno);
} else {
verbose(env, "R%d invalid mem access '%s'\n", regno,
reg_type_str[reg->type]);
return -EACCES;
}
if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
regs[value_regno].type == SCALAR_VALUE) {
/* b/h/w load zero-extends, mark upper bits as known 0 */
coerce_reg_to_size(®s[value_regno], size);
}
return err;
}
static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
{
int err;
if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
insn->imm != 0) {
verbose(env, "BPF_XADD uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->src_reg)) {
verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
return -EACCES;
}
/* check whether atomic_add can read the memory */
err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_READ, -1);
if (err)
return err;
/* check whether atomic_add can write into the same memory */
return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE, -1);
}
/* Does this register contain a constant zero? */
static bool register_is_null(struct bpf_reg_state reg)
{
return reg.type == SCALAR_VALUE && tnum_equals_const(reg.var_off, 0);
}
/* when register 'regno' is passed into function that will read 'access_size'
* bytes from that pointer, make sure that it's within stack boundary
* and all elements of stack are initialized.
* Unlike most pointer bounds-checking functions, this one doesn't take an
* 'off' argument, so it has to add in reg->off itself.
*/
static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
int access_size, bool zero_size_allowed,
struct bpf_call_arg_meta *meta)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_reg_state *regs = state->regs;
int off, i, slot, spi;
if (regs[regno].type != PTR_TO_STACK) {
/* Allow zero-byte read from NULL, regardless of pointer type */
if (zero_size_allowed && access_size == 0 &&
register_is_null(regs[regno]))
return 0;
verbose(env, "R%d type=%s expected=%s\n", regno,
reg_type_str[regs[regno].type],
reg_type_str[PTR_TO_STACK]);
return -EACCES;
}
/* Only allow fixed-offset stack reads */
if (!tnum_is_const(regs[regno].var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), regs[regno].var_off);
verbose(env, "invalid variable stack read R%d var_off=%s\n",
regno, tn_buf);
return -EACCES;
}
off = regs[regno].off + regs[regno].var_off.value;
if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
regno, off, access_size);
return -EACCES;
}
if (env->prog->aux->stack_depth < -off)
env->prog->aux->stack_depth = -off;
if (meta && meta->raw_mode) {
meta->access_size = access_size;
meta->regno = regno;
return 0;
}
for (i = 0; i < access_size; i++) {
slot = -(off + i) - 1;
spi = slot / BPF_REG_SIZE;
if (state->allocated_stack <= slot ||
state->stack[spi].slot_type[slot % BPF_REG_SIZE] !=
STACK_MISC) {
verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
off, i, access_size);
return -EACCES;
}
}
return 0;
}
static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
int access_size, bool zero_size_allowed,
struct bpf_call_arg_meta *meta)
{
struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
switch (reg->type) {
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
return check_packet_access(env, regno, reg->off, access_size,
zero_size_allowed);
case PTR_TO_MAP_VALUE:
return check_map_access(env, regno, reg->off, access_size,
zero_size_allowed);
default: /* scalar_value|ptr_to_stack or invalid ptr */
return check_stack_boundary(env, regno, access_size,
zero_size_allowed, meta);
}
}
static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
enum bpf_arg_type arg_type,
struct bpf_call_arg_meta *meta)
{
struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
enum bpf_reg_type expected_type, type = reg->type;
int err = 0;
if (arg_type == ARG_DONTCARE)
return 0;
err = check_reg_arg(env, regno, SRC_OP);
if (err)
return err;
if (arg_type == ARG_ANYTHING) {
if (is_pointer_value(env, regno)) {
verbose(env, "R%d leaks addr into helper function\n",
regno);
return -EACCES;
}
return 0;
}
if (type_is_pkt_pointer(type) &&
!may_access_direct_pkt_data(env, meta, BPF_READ)) {
verbose(env, "helper access to the packet is not allowed\n");
return -EACCES;
}
if (arg_type == ARG_PTR_TO_MAP_KEY ||
arg_type == ARG_PTR_TO_MAP_VALUE) {
expected_type = PTR_TO_STACK;
if (!type_is_pkt_pointer(type) &&
type != expected_type)
goto err_type;
} else if (arg_type == ARG_CONST_SIZE ||
arg_type == ARG_CONST_SIZE_OR_ZERO) {
expected_type = SCALAR_VALUE;
if (type != expected_type)
goto err_type;
} else if (arg_type == ARG_CONST_MAP_PTR) {
expected_type = CONST_PTR_TO_MAP;
if (type != expected_type)
goto err_type;
} else if (arg_type == ARG_PTR_TO_CTX) {
expected_type = PTR_TO_CTX;
if (type != expected_type)
goto err_type;
} else if (arg_type == ARG_PTR_TO_MEM ||
arg_type == ARG_PTR_TO_MEM_OR_NULL ||
arg_type == ARG_PTR_TO_UNINIT_MEM) {
expected_type = PTR_TO_STACK;
/* One exception here. In case function allows for NULL to be
* passed in as argument, it's a SCALAR_VALUE type. Final test
* happens during stack boundary checking.
*/
if (register_is_null(*reg) &&
arg_type == ARG_PTR_TO_MEM_OR_NULL)
/* final test in check_stack_boundary() */;
else if (!type_is_pkt_pointer(type) &&
type != PTR_TO_MAP_VALUE &&
type != expected_type)
goto err_type;
meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
} else {
verbose(env, "unsupported arg_type %d\n", arg_type);
return -EFAULT;
}
if (arg_type == ARG_CONST_MAP_PTR) {
/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
meta->map_ptr = reg->map_ptr;
} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
/* bpf_map_xxx(..., map_ptr, ..., key) call:
* check that [key, key + map->key_size) are within
* stack limits and initialized
*/
if (!meta->map_ptr) {
/* in function declaration map_ptr must come before
* map_key, so that it's verified and known before
* we have to check map_key here. Otherwise it means
* that kernel subsystem misconfigured verifier
*/
verbose(env, "invalid map_ptr to access map->key\n");
return -EACCES;
}
if (type_is_pkt_pointer(type))
err = check_packet_access(env, regno, reg->off,
meta->map_ptr->key_size,
false);
else
err = check_stack_boundary(env, regno,
meta->map_ptr->key_size,
false, NULL);
} else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
/* bpf_map_xxx(..., map_ptr, ..., value) call:
* check [value, value + map->value_size) validity
*/
if (!meta->map_ptr) {
/* kernel subsystem misconfigured verifier */
verbose(env, "invalid map_ptr to access map->value\n");
return -EACCES;
}
if (type_is_pkt_pointer(type))
err = check_packet_access(env, regno, reg->off,
meta->map_ptr->value_size,
false);
else
err = check_stack_boundary(env, regno,
meta->map_ptr->value_size,
false, NULL);
} else if (arg_type == ARG_CONST_SIZE ||
arg_type == ARG_CONST_SIZE_OR_ZERO) {
bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
/* bpf_xxx(..., buf, len) call will access 'len' bytes
* from stack pointer 'buf'. Check it
* note: regno == len, regno - 1 == buf
*/
if (regno == 0) {
/* kernel subsystem misconfigured verifier */
verbose(env,
"ARG_CONST_SIZE cannot be first argument\n");
return -EACCES;
}
/* The register is SCALAR_VALUE; the access check
* happens using its boundaries.
*/
if (!tnum_is_const(reg->var_off))
/* For unprivileged variable accesses, disable raw
* mode so that the program is required to
* initialize all the memory that the helper could
* just partially fill up.
*/
meta = NULL;
if (reg->smin_value < 0) {
verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
regno);
return -EACCES;
}
if (reg->umin_value == 0) {
err = check_helper_mem_access(env, regno - 1, 0,
zero_size_allowed,
meta);
if (err)
return err;
}
if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
regno);
return -EACCES;
}
err = check_helper_mem_access(env, regno - 1,
reg->umax_value,
zero_size_allowed, meta);
}
return err;
err_type:
verbose(env, "R%d type=%s expected=%s\n", regno,
reg_type_str[type], reg_type_str[expected_type]);
return -EACCES;
}
static int check_map_func_compatibility(struct bpf_verifier_env *env,
struct bpf_map *map, int func_id)
{
if (!map)
return 0;
/* We need a two way check, first is from map perspective ... */
switch (map->map_type) {
case BPF_MAP_TYPE_PROG_ARRAY:
if (func_id != BPF_FUNC_tail_call)
goto error;
break;
case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
if (func_id != BPF_FUNC_perf_event_read &&
func_id != BPF_FUNC_perf_event_output &&
func_id != BPF_FUNC_perf_event_read_value)
goto error;
break;
case BPF_MAP_TYPE_STACK_TRACE:
if (func_id != BPF_FUNC_get_stackid)
goto error;
break;
case BPF_MAP_TYPE_CGROUP_ARRAY:
if (func_id != BPF_FUNC_skb_under_cgroup &&
func_id != BPF_FUNC_current_task_under_cgroup)
goto error;
break;
/* devmap returns a pointer to a live net_device ifindex that we cannot
* allow to be modified from bpf side. So do not allow lookup elements
* for now.
*/
case BPF_MAP_TYPE_DEVMAP:
if (func_id != BPF_FUNC_redirect_map)
goto error;
break;
/* Restrict bpf side of cpumap, open when use-cases appear */
case BPF_MAP_TYPE_CPUMAP:
if (func_id != BPF_FUNC_redirect_map)
goto error;
break;
case BPF_MAP_TYPE_ARRAY_OF_MAPS:
case BPF_MAP_TYPE_HASH_OF_MAPS:
if (func_id != BPF_FUNC_map_lookup_elem)
goto error;
break;
case BPF_MAP_TYPE_SOCKMAP:
if (func_id != BPF_FUNC_sk_redirect_map &&
func_id != BPF_FUNC_sock_map_update &&
func_id != BPF_FUNC_map_delete_elem)
goto error;
break;
default:
break;
}
/* ... and second from the function itself. */
switch (func_id) {
case BPF_FUNC_tail_call:
if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
goto error;
break;
case BPF_FUNC_perf_event_read:
case BPF_FUNC_perf_event_output:
case BPF_FUNC_perf_event_read_value:
if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
goto error;
break;
case BPF_FUNC_get_stackid:
if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
goto error;
break;
case BPF_FUNC_current_task_under_cgroup:
case BPF_FUNC_skb_under_cgroup:
if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
goto error;
break;
case BPF_FUNC_redirect_map:
if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
map->map_type != BPF_MAP_TYPE_CPUMAP)
goto error;
break;
case BPF_FUNC_sk_redirect_map:
if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
goto error;
break;
case BPF_FUNC_sock_map_update:
if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
goto error;
break;
default:
break;
}
return 0;
error:
verbose(env, "cannot pass map_type %d into func %s#%d\n",
map->map_type, func_id_name(func_id), func_id);
return -EINVAL;
}
static int check_raw_mode(const struct bpf_func_proto *fn)
{
int count = 0;
if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
count++;
return count > 1 ? -EINVAL : 0;
}
/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
* are now invalid, so turn them into unknown SCALAR_VALUE.
*/
static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_reg_state *regs = state->regs, *reg;
int i;
for (i = 0; i < MAX_BPF_REG; i++)
if (reg_is_pkt_pointer_any(®s[i]))
mark_reg_unknown(env, regs, i);
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
reg = &state->stack[i].spilled_ptr;
if (reg_is_pkt_pointer_any(reg))
__mark_reg_unknown(reg);
}
}
static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
{
const struct bpf_func_proto *fn = NULL;
struct bpf_reg_state *regs;
struct bpf_call_arg_meta meta;
bool changes_data;
int i, err;
/* find function prototype */
if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
func_id);
return -EINVAL;
}
if (env->ops->get_func_proto)
fn = env->ops->get_func_proto(func_id);
if (!fn) {
verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
func_id);
return -EINVAL;
}
/* eBPF programs must be GPL compatible to use GPL-ed functions */
if (!env->prog->gpl_compatible && fn->gpl_only) {
verbose(env, "cannot call GPL only function from proprietary program\n");
return -EINVAL;
}
/* With LD_ABS/IND some JITs save/restore skb from r1. */
changes_data = bpf_helper_changes_pkt_data(fn->func);
if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
func_id_name(func_id), func_id);
return -EINVAL;
}
memset(&meta, 0, sizeof(meta));
meta.pkt_access = fn->pkt_access;
/* We only support one arg being in raw mode at the moment, which
* is sufficient for the helper functions we have right now.
*/
err = check_raw_mode(fn);
if (err) {
verbose(env, "kernel subsystem misconfigured func %s#%d\n",
func_id_name(func_id), func_id);
return err;
}
/* check args */
err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
if (err)
return err;
/* Mark slots with STACK_MISC in case of raw mode, stack offset
* is inferred from register state.
*/
for (i = 0; i < meta.access_size; i++) {
err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, BPF_WRITE, -1);
if (err)
return err;
}
regs = cur_regs(env);
/* reset caller saved regs */
for (i = 0; i < CALLER_SAVED_REGS; i++) {
mark_reg_not_init(env, regs, caller_saved[i]);
check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
}
/* update return register (already marked as written above) */
if (fn->ret_type == RET_INTEGER) {
/* sets type to SCALAR_VALUE */
mark_reg_unknown(env, regs, BPF_REG_0);
} else if (fn->ret_type == RET_VOID) {
regs[BPF_REG_0].type = NOT_INIT;
} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
struct bpf_insn_aux_data *insn_aux;
regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
/* There is no offset yet applied, variable or fixed */
mark_reg_known_zero(env, regs, BPF_REG_0);
regs[BPF_REG_0].off = 0;
/* remember map_ptr, so that check_map_access()
* can check 'value_size' boundary of memory access
* to map element returned from bpf_map_lookup_elem()
*/
if (meta.map_ptr == NULL) {
verbose(env,
"kernel subsystem misconfigured verifier\n");
return -EINVAL;
}
regs[BPF_REG_0].map_ptr = meta.map_ptr;
regs[BPF_REG_0].id = ++env->id_gen;
insn_aux = &env->insn_aux_data[insn_idx];
if (!insn_aux->map_ptr)
insn_aux->map_ptr = meta.map_ptr;
else if (insn_aux->map_ptr != meta.map_ptr)
insn_aux->map_ptr = BPF_MAP_PTR_POISON;
} else {
verbose(env, "unknown return type %d of func %s#%d\n",
fn->ret_type, func_id_name(func_id), func_id);
return -EINVAL;
}
err = check_map_func_compatibility(env, meta.map_ptr, func_id);
if (err)
return err;
if (changes_data)
clear_all_pkt_pointers(env);
return 0;
}
static bool signed_add_overflows(s64 a, s64 b)
{
/* Do the add in u64, where overflow is well-defined */
s64 res = (s64)((u64)a + (u64)b);
if (b < 0)
return res > a;
return res < a;
}
static bool signed_sub_overflows(s64 a, s64 b)
{
/* Do the sub in u64, where overflow is well-defined */
s64 res = (s64)((u64)a - (u64)b);
if (b < 0)
return res < a;
return res > a;
}
/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
* Caller should also handle BPF_MOV case separately.
* If we return -EACCES, caller may want to try again treating pointer as a
* scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
*/
static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn,
const struct bpf_reg_state *ptr_reg,
const struct bpf_reg_state *off_reg)
{
struct bpf_reg_state *regs = cur_regs(env), *dst_reg;
bool known = tnum_is_const(off_reg->var_off);
s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
u8 opcode = BPF_OP(insn->code);
u32 dst = insn->dst_reg;
dst_reg = ®s[dst];
if (WARN_ON_ONCE(known && (smin_val != smax_val))) {
print_verifier_state(env, env->cur_state);
verbose(env,
"verifier internal error: known but bad sbounds\n");
return -EINVAL;
}
if (WARN_ON_ONCE(known && (umin_val != umax_val))) {
print_verifier_state(env, env->cur_state);
verbose(env,
"verifier internal error: known but bad ubounds\n");
return -EINVAL;
}
if (BPF_CLASS(insn->code) != BPF_ALU64) {
/* 32-bit ALU ops on pointers produce (meaningless) scalars */
if (!env->allow_ptr_leaks)
verbose(env,
"R%d 32-bit pointer arithmetic prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
dst);
return -EACCES;
}
if (ptr_reg->type == CONST_PTR_TO_MAP) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_PACKET_END) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
dst);
return -EACCES;
}
/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
* The id may be overwritten later if we create a new variable offset.
*/
dst_reg->type = ptr_reg->type;
dst_reg->id = ptr_reg->id;
switch (opcode) {
case BPF_ADD:
/* We can take a fixed offset as long as it doesn't overflow
* the s32 'off' field
*/
if (known && (ptr_reg->off + smin_val ==
(s64)(s32)(ptr_reg->off + smin_val))) {
/* pointer += K. Accumulate it into fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->off = ptr_reg->off + smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. Note that off_reg->off
* == 0, since it's a scalar.
* dst_reg gets the pointer type and since some positive
* integer value was added to the pointer, give it a new 'id'
* if it's a PTR_TO_PACKET.
* this creates a new 'base' pointer, off_reg (variable) gets
* added into the variable offset, and we copy the fixed offset
* from ptr_reg.
*/
if (signed_add_overflows(smin_ptr, smin_val) ||
signed_add_overflows(smax_ptr, smax_val)) {
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr + smin_val;
dst_reg->smax_value = smax_ptr + smax_val;
}
if (umin_ptr + umin_val < umin_ptr ||
umax_ptr + umax_val < umax_ptr) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value = umin_ptr + umin_val;
dst_reg->umax_value = umax_ptr + umax_val;
}
dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
dst_reg->range = 0;
}
break;
case BPF_SUB:
if (dst_reg == off_reg) {
/* scalar -= pointer. Creates an unknown scalar */
if (!env->allow_ptr_leaks)
verbose(env, "R%d tried to subtract pointer from scalar\n",
dst);
return -EACCES;
}
/* We don't allow subtraction from FP, because (according to
* test_verifier.c test "invalid fp arithmetic", JITs might not
* be able to deal with it.
*/
if (ptr_reg->type == PTR_TO_STACK) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d subtraction from stack pointer prohibited\n",
dst);
return -EACCES;
}
if (known && (ptr_reg->off - smin_val ==
(s64)(s32)(ptr_reg->off - smin_val))) {
/* pointer -= K. Subtract it from fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->id = ptr_reg->id;
dst_reg->off = ptr_reg->off - smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. If the subtrahend is known
* nonnegative, then any reg->range we had before is still good.
*/
if (signed_sub_overflows(smin_ptr, smax_val) ||
signed_sub_overflows(smax_ptr, smin_val)) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr - smax_val;
dst_reg->smax_value = smax_ptr - smin_val;
}
if (umin_ptr < 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 = umin_ptr - umax_val;
dst_reg->umax_value = umax_ptr - umin_val;
}
dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
if (smin_val < 0)
dst_reg->range = 0;
}
break;
case BPF_AND:
case BPF_OR:
case BPF_XOR:
/* bitwise ops on pointers are troublesome, prohibit for now.
* (However, in principle we could allow some cases, e.g.
* ptr &= ~3 which would reduce min_value by 3.)
*/
if (!env->allow_ptr_leaks)
verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
default:
/* other operators (e.g. MUL,LSH) produce non-pointer results */
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
}
__update_reg_bounds(dst_reg);
__reg_deduce_bounds(dst_reg);
__reg_bound_offset(dst_reg);
return 0;
}
/* WARNING: This function does calculations on 64-bit values, but the actual
* execution may occur on 32-bit values. Therefore, things like bitshifts
* need extra checks in the 32-bit case.
*/
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);
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;
}
if (src_known)
dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
else
dst_reg->var_off = tnum_lshift(tnum_unknown, 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;
if (src_known)
dst_reg->var_off = tnum_rshift(dst_reg->var_off,
umin_val);
else
dst_reg->var_off = tnum_rshift(tnum_unknown, 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;
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;
}
/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
* and var_off.
*/
static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env), *dst_reg, *src_reg;
struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
u8 opcode = BPF_OP(insn->code);
int rc;
dst_reg = ®s[insn->dst_reg];
src_reg = NULL;
if (dst_reg->type != SCALAR_VALUE)
ptr_reg = dst_reg;
if (BPF_SRC(insn->code) == BPF_X) {
src_reg = ®s[insn->src_reg];
if (src_reg->type != SCALAR_VALUE) {
if (dst_reg->type != SCALAR_VALUE) {
/* Combining two pointers by any ALU op yields
* an arbitrary scalar.
*/
if (!env->allow_ptr_leaks) {
verbose(env, "R%d pointer %s pointer prohibited\n",
insn->dst_reg,
bpf_alu_string[opcode >> 4]);
return -EACCES;
}
mark_reg_unknown(env, regs, insn->dst_reg);
return 0;
} else {
/* scalar += pointer
* This is legal, but we have to reverse our
* src/dest handling in computing the range
*/
rc = adjust_ptr_min_max_vals(env, insn,
src_reg, dst_reg);
if (rc == -EACCES && env->allow_ptr_leaks) {
/* scalar += unknown scalar */
__mark_reg_unknown(&off_reg);
return adjust_scalar_min_max_vals(
env, insn,
dst_reg, off_reg);
}
return rc;
}
} else if (ptr_reg) {
/* pointer += scalar */
rc = adjust_ptr_min_max_vals(env, insn,
dst_reg, src_reg);
if (rc == -EACCES && env->allow_ptr_leaks) {
/* unknown scalar += scalar */
__mark_reg_unknown(dst_reg);
return adjust_scalar_min_max_vals(
env, insn, dst_reg, *src_reg);
}
return rc;
}
} else {
/* Pretend the src is a reg with a known value, since we only
* need to be able to read from this state.
*/
off_reg.type = SCALAR_VALUE;
__mark_reg_known(&off_reg, insn->imm);
src_reg = &off_reg;
if (ptr_reg) { /* pointer += K */
rc = adjust_ptr_min_max_vals(env, insn,
ptr_reg, src_reg);
if (rc == -EACCES && env->allow_ptr_leaks) {
/* unknown scalar += K */
__mark_reg_unknown(dst_reg);
return adjust_scalar_min_max_vals(
env, insn, dst_reg, off_reg);
}
return rc;
}
}
/* Got here implies adding two SCALAR_VALUEs */
if (WARN_ON_ONCE(ptr_reg)) {
print_verifier_state(env, env->cur_state);
verbose(env, "verifier internal error: unexpected ptr_reg\n");
return -EINVAL;
}
if (WARN_ON(!src_reg)) {
print_verifier_state(env, env->cur_state);
verbose(env, "verifier internal error: no src_reg\n");
return -EINVAL;
}
return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
}
/* check validity of 32-bit and 64-bit arithmetic operations */
static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 opcode = BPF_OP(insn->code);
int err;
if (opcode == BPF_END || opcode == BPF_NEG) {
if (opcode == BPF_NEG) {
if (BPF_SRC(insn->code) != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->off != 0 || insn->imm != 0) {
verbose(env, "BPF_NEG uses reserved fields\n");
return -EINVAL;
}
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
(insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
BPF_CLASS(insn->code) == BPF_ALU64) {
verbose(env, "BPF_END uses reserved fields\n");
return -EINVAL;
}
}
/* check src operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->dst_reg)) {
verbose(env, "R%d pointer arithmetic prohibited\n",
insn->dst_reg);
return -EACCES;
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
} else if (opcode == BPF_MOV) {
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
if (BPF_SRC(insn->code) == BPF_X) {
if (BPF_CLASS(insn->code) == BPF_ALU64) {
/* case: R1 = R2
* copy register state to dest reg
*/
regs[insn->dst_reg] = regs[insn->src_reg];
regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
} else {
/* R1 = (u32) R2 */
if (is_pointer_value(env, insn->src_reg)) {
verbose(env,
"R%d partial copy of pointer\n",
insn->src_reg);
return -EACCES;
}
mark_reg_unknown(env, regs, insn->dst_reg);
coerce_reg_to_size(®s[insn->dst_reg], 4);
}
} else {
/* case: R = imm
* remember the value we stored into this reg
*/
regs[insn->dst_reg].type = SCALAR_VALUE;
if (BPF_CLASS(insn->code) == BPF_ALU64) {
__mark_reg_known(regs + insn->dst_reg,
insn->imm);
} else {
__mark_reg_known(regs + insn->dst_reg,
(u32)insn->imm);
}
}
} else if (opcode > BPF_END) {
verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
return -EINVAL;
} else { /* all other ALU ops: and, sub, xor, add, ... */
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
}
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
verbose(env, "div by zero\n");
return -EINVAL;
}
if ((opcode == BPF_LSH || opcode == BPF_RSH ||
opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
if (insn->imm < 0 || insn->imm >= size) {
verbose(env, "invalid shift %d\n", insn->imm);
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
return adjust_reg_min_max_vals(env, insn);
}
return 0;
}
static void find_good_pkt_pointers(struct bpf_verifier_state *state,
struct bpf_reg_state *dst_reg,
enum bpf_reg_type type,
bool range_right_open)
{
struct bpf_reg_state *regs = state->regs, *reg;
u16 new_range;
int i;
if (dst_reg->off < 0 ||
(dst_reg->off == 0 && range_right_open))
/* This doesn't give us any range */
return;
if (dst_reg->umax_value > MAX_PACKET_OFF ||
dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
/* Risk of overflow. For instance, ptr + (1<<63) may be less
* than pkt_end, but that's because it's also less than pkt.
*/
return;
new_range = dst_reg->off;
if (range_right_open)
new_range--;
/* Examples for register markings:
*
* pkt_data in dst register:
*
* r2 = r3;
* r2 += 8;
* if (r2 > pkt_end) goto <handle exception>
* <access okay>
*
* r2 = r3;
* r2 += 8;
* if (r2 < pkt_end) goto <access okay>
* <handle exception>
*
* Where:
* r2 == dst_reg, pkt_end == src_reg
* r2=pkt(id=n,off=8,r=0)
* r3=pkt(id=n,off=0,r=0)
*
* pkt_data in src register:
*
* r2 = r3;
* r2 += 8;
* if (pkt_end >= r2) goto <access okay>
* <handle exception>
*
* r2 = r3;
* r2 += 8;
* if (pkt_end <= r2) goto <handle exception>
* <access okay>
*
* Where:
* pkt_end == dst_reg, r2 == src_reg
* r2=pkt(id=n,off=8,r=0)
* r3=pkt(id=n,off=0,r=0)
*
* Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
* or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
* and [r3, r3 + 8-1) respectively is safe to access depending on
* the check.
*/
/* If our ids match, then we must have the same max_value. And we
* don't care about the other reg's fixed offset, since if it's too big
* the range won't allow anything.
* dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
*/
for (i = 0; i < MAX_BPF_REG; i++)
if (regs[i].type == type && regs[i].id == dst_reg->id)
/* keep the maximum range already checked */
regs[i].range = max(regs[i].range, new_range);
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
reg = &state->stack[i].spilled_ptr;
if (reg->type == type && reg->id == dst_reg->id)
reg->range = max(reg->range, new_range);
}
}
/* Adjusts the register min/max values in the case that the dst_reg is the
* variable register that we are working on, and src_reg is a constant or we're
* simply doing a BPF_K check.
* In JEQ/JNE cases we also adjust the var_off values.
*/
static void reg_set_min_max(struct bpf_reg_state *true_reg,
struct bpf_reg_state *false_reg, u64 val,
u8 opcode)
{
/* If the dst_reg is a pointer, we can't learn anything about its
* variable offset from the compare (unless src_reg were a pointer into
* the same object, but we don't bother with that.
* Since false_reg and true_reg have the same type by construction, we
* only need to check one of them for pointerness.
*/
if (__is_pointer_value(false, false_reg))
return;
switch (opcode) {
case BPF_JEQ:
/* If this is false then we know nothing Jon Snow, but if it is
* true then we know for sure.
*/
__mark_reg_known(true_reg, val);
break;
case BPF_JNE:
/* If this is true we know nothing Jon Snow, but if it is false
* we know the value for sure;
*/
__mark_reg_known(false_reg, val);
break;
case BPF_JGT:
false_reg->umax_value = min(false_reg->umax_value, val);
true_reg->umin_value = max(true_reg->umin_value, val + 1);
break;
case BPF_JSGT:
false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
break;
case BPF_JLT:
false_reg->umin_value = max(false_reg->umin_value, val);
true_reg->umax_value = min(true_reg->umax_value, val - 1);
break;
case BPF_JSLT:
false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
break;
case BPF_JGE:
false_reg->umax_value = min(false_reg->umax_value, val - 1);
true_reg->umin_value = max(true_reg->umin_value, val);
break;
case BPF_JSGE:
false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
break;
case BPF_JLE:
false_reg->umin_value = max(false_reg->umin_value, val + 1);
true_reg->umax_value = min(true_reg->umax_value, val);
break;
case BPF_JSLE:
false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
break;
default:
break;
}
__reg_deduce_bounds(false_reg);
__reg_deduce_bounds(true_reg);
/* We might have learned some bits from the bounds. */
__reg_bound_offset(false_reg);
__reg_bound_offset(true_reg);
/* Intersecting with the old var_off might have improved our bounds
* slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
* then new var_off is (0; 0x7f...fc) which improves our umax.
*/
__update_reg_bounds(false_reg);
__update_reg_bounds(true_reg);
}
/* Same as above, but for the case that dst_reg holds a constant and src_reg is
* the variable reg.
*/
static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
struct bpf_reg_state *false_reg, u64 val,
u8 opcode)
{
if (__is_pointer_value(false, false_reg))
return;
switch (opcode) {
case BPF_JEQ:
/* If this is false then we know nothing Jon Snow, but if it is
* true then we know for sure.
*/
__mark_reg_known(true_reg, val);
break;
case BPF_JNE:
/* If this is true we know nothing Jon Snow, but if it is false
* we know the value for sure;
*/
__mark_reg_known(false_reg, val);
break;
case BPF_JGT:
true_reg->umax_value = min(true_reg->umax_value, val - 1);
false_reg->umin_value = max(false_reg->umin_value, val);
break;
case BPF_JSGT:
true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
break;
case BPF_JLT:
true_reg->umin_value = max(true_reg->umin_value, val + 1);
false_reg->umax_value = min(false_reg->umax_value, val);
break;
case BPF_JSLT:
true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
break;
case BPF_JGE:
true_reg->umax_value = min(true_reg->umax_value, val);
false_reg->umin_value = max(false_reg->umin_value, val + 1);
break;
case BPF_JSGE:
true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
break;
case BPF_JLE:
true_reg->umin_value = max(true_reg->umin_value, val);
false_reg->umax_value = min(false_reg->umax_value, val - 1);
break;
case BPF_JSLE:
true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
break;
default:
break;
}
__reg_deduce_bounds(false_reg);
__reg_deduce_bounds(true_reg);
/* We might have learned some bits from the bounds. */
__reg_bound_offset(false_reg);
__reg_bound_offset(true_reg);
/* Intersecting with the old var_off might have improved our bounds
* slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
* then new var_off is (0; 0x7f...fc) which improves our umax.
*/
__update_reg_bounds(false_reg);
__update_reg_bounds(true_reg);
}
/* Regs are known to be equal, so intersect their min/max/var_off */
static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
struct bpf_reg_state *dst_reg)
{
src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
dst_reg->umin_value);
src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
dst_reg->umax_value);
src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
dst_reg->smin_value);
src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
dst_reg->smax_value);
src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
dst_reg->var_off);
/* We might have learned new bounds from the var_off. */
__update_reg_bounds(src_reg);
__update_reg_bounds(dst_reg);
/* We might have learned something about the sign bit. */
__reg_deduce_bounds(src_reg);
__reg_deduce_bounds(dst_reg);
/* We might have learned some bits from the bounds. */
__reg_bound_offset(src_reg);
__reg_bound_offset(dst_reg);
/* Intersecting with the old var_off might have improved our bounds
* slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
* then new var_off is (0; 0x7f...fc) which improves our umax.
*/
__update_reg_bounds(src_reg);
__update_reg_bounds(dst_reg);
}
static void reg_combine_min_max(struct bpf_reg_state *true_src,
struct bpf_reg_state *true_dst,
struct bpf_reg_state *false_src,
struct bpf_reg_state *false_dst,
u8 opcode)
{
switch (opcode) {
case BPF_JEQ:
__reg_combine_min_max(true_src, true_dst);
break;
case BPF_JNE:
__reg_combine_min_max(false_src, false_dst);
break;
}
}
static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
bool is_null)
{
struct bpf_reg_state *reg = ®s[regno];
if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
/* Old offset (both fixed and variable parts) should
* have been known-zero, because we don't allow pointer
* arithmetic on pointers that might be NULL.
*/
if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
!tnum_equals_const(reg->var_off, 0) ||
reg->off)) {
__mark_reg_known_zero(reg);
reg->off = 0;
}
if (is_null) {
reg->type = SCALAR_VALUE;
} else if (reg->map_ptr->inner_map_meta) {
reg->type = CONST_PTR_TO_MAP;
reg->map_ptr = reg->map_ptr->inner_map_meta;
} else {
reg->type = PTR_TO_MAP_VALUE;
}
/* We don't need id from this point onwards anymore, thus we
* should better reset it, so that state pruning has chances
* to take effect.
*/
reg->id = 0;
}
}
/* The logic is similar to find_good_pkt_pointers(), both could eventually
* be folded together at some point.
*/
static void mark_map_regs(struct bpf_verifier_state *state, u32 regno,
bool is_null)
{
struct bpf_reg_state *regs = state->regs;
u32 id = regs[regno].id;
int i;
for (i = 0; i < MAX_BPF_REG; i++)
mark_map_reg(regs, i, id, is_null);
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
}
}
static bool try_match_pkt_pointers(const struct bpf_insn *insn,
struct bpf_reg_state *dst_reg,
struct bpf_reg_state *src_reg,
struct bpf_verifier_state *this_branch,
struct bpf_verifier_state *other_branch)
{
if (BPF_SRC(insn->code) != BPF_X)
return false;
switch (BPF_OP(insn->code)) {
case BPF_JGT:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
find_good_pkt_pointers(this_branch, dst_reg,
dst_reg->type, false);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end > pkt_data', pkt_data > pkt_meta' */
find_good_pkt_pointers(other_branch, src_reg,
src_reg->type, true);
} else {
return false;
}
break;
case BPF_JLT:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
find_good_pkt_pointers(other_branch, dst_reg,
dst_reg->type, true);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end < pkt_data', pkt_data > pkt_meta' */
find_good_pkt_pointers(this_branch, src_reg,
src_reg->type, false);
} else {
return false;
}
break;
case BPF_JGE:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
find_good_pkt_pointers(this_branch, dst_reg,
dst_reg->type, true);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
find_good_pkt_pointers(other_branch, src_reg,
src_reg->type, false);
} else {
return false;
}
break;
case BPF_JLE:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
find_good_pkt_pointers(other_branch, dst_reg,
dst_reg->type, false);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
find_good_pkt_pointers(this_branch, src_reg,
src_reg->type, true);
} else {
return false;
}
break;
default:
return false;
}
return true;
}
static int check_cond_jmp_op(struct bpf_verifier_env *env,
struct bpf_insn *insn, int *insn_idx)
{
struct bpf_verifier_state *other_branch, *this_branch = env->cur_state;
struct bpf_reg_state *regs = this_branch->regs, *dst_reg;
u8 opcode = BPF_OP(insn->code);
int err;
if (opcode > BPF_JSLE) {
verbose(env, "invalid BPF_JMP opcode %x\n", opcode);
return -EINVAL;
}
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0) {
verbose(env, "BPF_JMP uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->src_reg)) {
verbose(env, "R%d pointer comparison prohibited\n",
insn->src_reg);
return -EACCES;
}
} else {
if (insn->src_reg != BPF_REG_0) {
verbose(env, "BPF_JMP uses reserved fields\n");
return -EINVAL;
}
}
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
dst_reg = ®s[insn->dst_reg];
/* detect if R == 0 where R was initialized to zero earlier */
if (BPF_SRC(insn->code) == BPF_K &&
(opcode == BPF_JEQ || opcode == BPF_JNE) &&
dst_reg->type == SCALAR_VALUE &&
tnum_equals_const(dst_reg->var_off, insn->imm)) {
if (opcode == BPF_JEQ) {
/* if (imm == imm) goto pc+off;
* only follow the goto, ignore fall-through
*/
*insn_idx += insn->off;
return 0;
} else {
/* if (imm != imm) goto pc+off;
* only follow fall-through branch, since
* that's where the program will go
*/
return 0;
}
}
other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
if (!other_branch)
return -EFAULT;
/* detect if we are comparing against a constant value so we can adjust
* our min/max values for our dst register.
* this is only legit if both are scalars (or pointers to the same
* object, I suppose, but we don't support that right now), because
* otherwise the different base pointers mean the offsets aren't
* comparable.
*/
if (BPF_SRC(insn->code) == BPF_X) {
if (dst_reg->type == SCALAR_VALUE &&
regs[insn->src_reg].type == SCALAR_VALUE) {
if (tnum_is_const(regs[insn->src_reg].var_off))
reg_set_min_max(&other_branch->regs[insn->dst_reg],
dst_reg, regs[insn->src_reg].var_off.value,
opcode);
else if (tnum_is_const(dst_reg->var_off))
reg_set_min_max_inv(&other_branch->regs[insn->src_reg],
®s[insn->src_reg],
dst_reg->var_off.value, opcode);
else if (opcode == BPF_JEQ || opcode == BPF_JNE)
/* Comparing for equality, we can combine knowledge */
reg_combine_min_max(&other_branch->regs[insn->src_reg],
&other_branch->regs[insn->dst_reg],
®s[insn->src_reg],
®s[insn->dst_reg], opcode);
}
} else if (dst_reg->type == SCALAR_VALUE) {
reg_set_min_max(&other_branch->regs[insn->dst_reg],
dst_reg, insn->imm, opcode);
}
/* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
if (BPF_SRC(insn->code) == BPF_K &&
insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
/* Mark all identical map registers in each branch as either
* safe or unknown depending R == 0 or R != 0 conditional.
*/
mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
} else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
this_branch, other_branch) &&
is_pointer_value(env, insn->dst_reg)) {
verbose(env, "R%d pointer comparison prohibited\n",
insn->dst_reg);
return -EACCES;
}
if (env->log.level)
print_verifier_state(env, this_branch);
return 0;
}
/* return the map pointer stored inside BPF_LD_IMM64 instruction */
static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
{
u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
return (struct bpf_map *) (unsigned long) imm64;
}
/* verify BPF_LD_IMM64 instruction */
static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
int err;
if (BPF_SIZE(insn->code) != BPF_DW) {
verbose(env, "invalid BPF_LD_IMM insn\n");
return -EINVAL;
}
if (insn->off != 0) {
verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
return -EINVAL;
}
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
if (insn->src_reg == 0) {
u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
regs[insn->dst_reg].type = SCALAR_VALUE;
__mark_reg_known(®s[insn->dst_reg], imm);
return 0;
}
/* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
return 0;
}
static bool may_access_skb(enum bpf_prog_type type)
{
switch (type) {
case BPF_PROG_TYPE_SOCKET_FILTER:
case BPF_PROG_TYPE_SCHED_CLS:
case BPF_PROG_TYPE_SCHED_ACT:
return true;
default:
return false;
}
}
/* verify safety of LD_ABS|LD_IND instructions:
* - they can only appear in the programs where ctx == skb
* - since they are wrappers of function calls, they scratch R1-R5 registers,
* preserve R6-R9, and store return value into R0
*
* Implicit input:
* ctx == skb == R6 == CTX
*
* Explicit input:
* SRC == any register
* IMM == 32-bit immediate
*
* Output:
* R0 - 8/16/32-bit skb data converted to cpu endianness
*/
static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 mode = BPF_MODE(insn->code);
int i, err;
if (!may_access_skb(env->prog->type)) {
verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
return -EINVAL;
}
if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
BPF_SIZE(insn->code) == BPF_DW ||
(mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
return -EINVAL;
}
/* check whether implicit source operand (register R6) is readable */
err = check_reg_arg(env, BPF_REG_6, SRC_OP);
if (err)
return err;
if (regs[BPF_REG_6].type != PTR_TO_CTX) {
verbose(env,
"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
return -EINVAL;
}
if (mode == BPF_IND) {
/* check explicit source operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
}
/* reset caller saved regs to unreadable */
for (i = 0; i < CALLER_SAVED_REGS; i++) {
mark_reg_not_init(env, regs, caller_saved[i]);
check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
}
/* mark destination R0 register as readable, since it contains
* the value fetched from the packet.
* Already marked as written above.
*/
mark_reg_unknown(env, regs, BPF_REG_0);
return 0;
}
static int check_return_code(struct bpf_verifier_env *env)
{
struct bpf_reg_state *reg;
struct tnum range = tnum_range(0, 1);
switch (env->prog->type) {
case BPF_PROG_TYPE_CGROUP_SKB:
case BPF_PROG_TYPE_CGROUP_SOCK:
case BPF_PROG_TYPE_SOCK_OPS:
case BPF_PROG_TYPE_CGROUP_DEVICE:
break;
default:
return 0;
}
reg = cur_regs(env) + BPF_REG_0;
if (reg->type != SCALAR_VALUE) {
verbose(env, "At program exit the register R0 is not a known value (%s)\n",
reg_type_str[reg->type]);
return -EINVAL;
}
if (!tnum_in(range, reg->var_off)) {
verbose(env, "At program exit the register R0 ");
if (!tnum_is_unknown(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "has value %s", tn_buf);
} else {
verbose(env, "has unknown scalar value");
}
verbose(env, " should have been 0 or 1\n");
return -EINVAL;
}
return 0;
}
/* non-recursive DFS pseudo code
* 1 procedure DFS-iterative(G,v):
* 2 label v as discovered
* 3 let S be a stack
* 4 S.push(v)
* 5 while S is not empty
* 6 t <- S.pop()
* 7 if t is what we're looking for:
* 8 return t
* 9 for all edges e in G.adjacentEdges(t) do
* 10 if edge e is already labelled
* 11 continue with the next edge
* 12 w <- G.adjacentVertex(t,e)
* 13 if vertex w is not discovered and not explored
* 14 label e as tree-edge
* 15 label w as discovered
* 16 S.push(w)
* 17 continue at 5
* 18 else if vertex w is discovered
* 19 label e as back-edge
* 20 else
* 21 // vertex w is explored
* 22 label e as forward- or cross-edge
* 23 label t as explored
* 24 S.pop()
*
* convention:
* 0x10 - discovered
* 0x11 - discovered and fall-through edge labelled
* 0x12 - discovered and fall-through and branch edges labelled
* 0x20 - explored
*/
enum {
DISCOVERED = 0x10,
EXPLORED = 0x20,
FALLTHROUGH = 1,
BRANCH = 2,
};
#define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
static int *insn_stack; /* stack of insns to process */
static int cur_stack; /* current stack index */
static int *insn_state;
/* t, w, e - match pseudo-code above:
* t - index of current instruction
* w - next instruction
* e - edge
*/
static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
{
if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
return 0;
if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
return 0;
if (w < 0 || w >= env->prog->len) {
verbose(env, "jump out of range from insn %d to %d\n", t, w);
return -EINVAL;
}
if (e == BRANCH)
/* mark branch target for state pruning */
env->explored_states[w] = STATE_LIST_MARK;
if (insn_state[w] == 0) {
/* tree-edge */
insn_state[t] = DISCOVERED | e;
insn_state[w] = DISCOVERED;
if (cur_stack >= env->prog->len)
return -E2BIG;
insn_stack[cur_stack++] = w;
return 1;
} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
verbose(env, "back-edge from insn %d to %d\n", t, w);
return -EINVAL;
} else if (insn_state[w] == EXPLORED) {
/* forward- or cross-edge */
insn_state[t] = DISCOVERED | e;
} else {
verbose(env, "insn state internal bug\n");
return -EFAULT;
}
return 0;
}
/* non-recursive depth-first-search to detect loops in BPF program
* loop == back-edge in directed graph
*/
static int check_cfg(struct bpf_verifier_env *env)
{
struct bpf_insn *insns = env->prog->insnsi;
int insn_cnt = env->prog->len;
int ret = 0;
int i, t;
insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
if (!insn_state)
return -ENOMEM;
insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
if (!insn_stack) {
kfree(insn_state);
return -ENOMEM;
}
insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
insn_stack[0] = 0; /* 0 is the first instruction */
cur_stack = 1;
peek_stack:
if (cur_stack == 0)
goto check_state;
t = insn_stack[cur_stack - 1];
if (BPF_CLASS(insns[t].code) == BPF_JMP) {
u8 opcode = BPF_OP(insns[t].code);
if (opcode == BPF_EXIT) {
goto mark_explored;
} else if (opcode == BPF_CALL) {
ret = push_insn(t, t + 1, FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
if (t + 1 < insn_cnt)
env->explored_states[t + 1] = STATE_LIST_MARK;
} else if (opcode == BPF_JA) {
if (BPF_SRC(insns[t].code) != BPF_K) {
ret = -EINVAL;
goto err_free;
}
/* unconditional jump with single edge */
ret = push_insn(t, t + insns[t].off + 1,
FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
/* tell verifier to check for equivalent states
* after every call and jump
*/
if (t + 1 < insn_cnt)
env->explored_states[t + 1] = STATE_LIST_MARK;
} else {
/* conditional jump with two edges */
env->explored_states[t] = STATE_LIST_MARK;
ret = push_insn(t, t + 1, FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
}
} else {
/* all other non-branch instructions with single
* fall-through edge
*/
ret = push_insn(t, t + 1, FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
}
mark_explored:
insn_state[t] = EXPLORED;
if (cur_stack-- <= 0) {
verbose(env, "pop stack internal bug\n");
ret = -EFAULT;
goto err_free;
}
goto peek_stack;
check_state:
for (i = 0; i < insn_cnt; i++) {
if (insn_state[i] != EXPLORED) {
verbose(env, "unreachable insn %d\n", i);
ret = -EINVAL;
goto err_free;
}
}
ret = 0; /* cfg looks good */
err_free:
kfree(insn_state);
kfree(insn_stack);
return ret;
}
/* check %cur's range satisfies %old's */
static bool range_within(struct bpf_reg_state *old,
struct bpf_reg_state *cur)
{
return old->umin_value <= cur->umin_value &&
old->umax_value >= cur->umax_value &&
old->smin_value <= cur->smin_value &&
old->smax_value >= cur->smax_value;
}
/* Maximum number of register states that can exist at once */
#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
struct idpair {
u32 old;
u32 cur;
};
/* If in the old state two registers had the same id, then they need to have
* the same id in the new state as well. But that id could be different from
* the old state, so we need to track the mapping from old to new ids.
* Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
* regs with old id 5 must also have new id 9 for the new state to be safe. But
* regs with a different old id could still have new id 9, we don't care about
* that.
* So we look through our idmap to see if this old id has been seen before. If
* so, we require the new id to match; otherwise, we add the id pair to the map.
*/
static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
{
unsigned int i;
for (i = 0; i < ID_MAP_SIZE; i++) {
if (!idmap[i].old) {
/* Reached an empty slot; haven't seen this id before */
idmap[i].old = old_id;
idmap[i].cur = cur_id;
return true;
}
if (idmap[i].old == old_id)
return idmap[i].cur == cur_id;
}
/* We ran out of idmap slots, which should be impossible */
WARN_ON_ONCE(1);
return false;
}
/* Returns true if (rold safe implies rcur safe) */
static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
struct idpair *idmap)
{
if (!(rold->live & REG_LIVE_READ))
/* explored state didn't use this */
return true;
if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0)
return true;
if (rold->type == NOT_INIT)
/* explored state can't have used this */
return true;
if (rcur->type == NOT_INIT)
return false;
switch (rold->type) {
case SCALAR_VALUE:
if (rcur->type == SCALAR_VALUE) {
/* new val must satisfy old val knowledge */
return range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
} else {
/* if we knew anything about the old value, we're not
* equal, because we can't know anything about the
* scalar value of the pointer in the new value.
*/
return rold->umin_value == 0 &&
rold->umax_value == U64_MAX &&
rold->smin_value == S64_MIN &&
rold->smax_value == S64_MAX &&
tnum_is_unknown(rold->var_off);
}
case PTR_TO_MAP_VALUE:
/* If the new min/max/var_off satisfy the old ones and
* everything else matches, we are OK.
* We don't care about the 'id' value, because nothing
* uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
*/
return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_MAP_VALUE_OR_NULL:
/* a PTR_TO_MAP_VALUE could be safe to use as a
* PTR_TO_MAP_VALUE_OR_NULL into the same map.
* However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
* checked, doing so could have affected others with the same
* id, and we can't check for that because we lost the id when
* we converted to a PTR_TO_MAP_VALUE.
*/
if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
return false;
if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
return false;
/* Check our ids match any regs they're supposed to */
return check_ids(rold->id, rcur->id, idmap);
case PTR_TO_PACKET_META:
case PTR_TO_PACKET:
if (rcur->type != rold->type)
return false;
/* We must have at least as much range as the old ptr
* did, so that any accesses which were safe before are
* still safe. This is true even if old range < old off,
* since someone could have accessed through (ptr - k), or
* even done ptr -= k in a register, to get a safe access.
*/
if (rold->range > rcur->range)
return false;
/* If the offsets don't match, we can't trust our alignment;
* nor can we be sure that we won't fall out of range.
*/
if (rold->off != rcur->off)
return false;
/* id relations must be preserved */
if (rold->id && !check_ids(rold->id, rcur->id, idmap))
return false;
/* new val must satisfy old val knowledge */
return range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_CTX:
case CONST_PTR_TO_MAP:
case PTR_TO_STACK:
case PTR_TO_PACKET_END:
/* Only valid matches are exact, which memcmp() above
* would have accepted
*/
default:
/* Don't know what's going on, just say it's not safe */
return false;
}
/* Shouldn't get here; if we do, say it's not safe */
WARN_ON_ONCE(1);
return false;
}
static bool stacksafe(struct bpf_verifier_state *old,
struct bpf_verifier_state *cur,
struct idpair *idmap)
{
int i, spi;
/* if explored stack has more populated slots than current stack
* such stacks are not equivalent
*/
if (old->allocated_stack > cur->allocated_stack)
return false;
/* walk slots of the explored stack and ignore any additional
* slots in the current stack, since explored(safe) state
* didn't use them
*/
for (i = 0; i < old->allocated_stack; i++) {
spi = i / BPF_REG_SIZE;
if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
continue;
if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
cur->stack[spi].slot_type[i % BPF_REG_SIZE])
/* Ex: old explored (safe) state has STACK_SPILL in
* this stack slot, but current has has STACK_MISC ->
* this verifier states are not equivalent,
* return false to continue verification of this path
*/
return false;
if (i % BPF_REG_SIZE)
continue;
if (old->stack[spi].slot_type[0] != STACK_SPILL)
continue;
if (!regsafe(&old->stack[spi].spilled_ptr,
&cur->stack[spi].spilled_ptr,
idmap))
/* when explored and current stack slot are both storing
* spilled registers, check that stored pointers types
* are the same as well.
* Ex: explored safe path could have stored
* (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
* but current path has stored:
* (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
* such verifier states are not equivalent.
* return false to continue verification of this path
*/
return false;
}
return true;
}
/* compare two verifier states
*
* all states stored in state_list are known to be valid, since
* verifier reached 'bpf_exit' instruction through them
*
* this function is called when verifier exploring different branches of
* execution popped from the state stack. If it sees an old state that has
* more strict register state and more strict stack state then this execution
* branch doesn't need to be explored further, since verifier already
* concluded that more strict state leads to valid finish.
*
* Therefore two states are equivalent if register state is more conservative
* and explored stack state is more conservative than the current one.
* Example:
* explored current
* (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
* (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
*
* In other words if current stack state (one being explored) has more
* valid slots than old one that already passed validation, it means
* the verifier can stop exploring and conclude that current state is valid too
*
* Similarly with registers. If explored state has register type as invalid
* whereas register type in current state is meaningful, it means that
* the current state will reach 'bpf_exit' instruction safely
*/
static bool states_equal(struct bpf_verifier_env *env,
struct bpf_verifier_state *old,
struct bpf_verifier_state *cur)
{
struct idpair *idmap;
bool ret = false;
int i;
idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
/* If we failed to allocate the idmap, just say it's not safe */
if (!idmap)
return false;
for (i = 0; i < MAX_BPF_REG; i++) {
if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
goto out_free;
}
if (!stacksafe(old, cur, idmap))
goto out_free;
ret = true;
out_free:
kfree(idmap);
return ret;
}
/* A write screens off any subsequent reads; but write marks come from the
* straight-line code between a state and its parent. When we arrive at a
* jump target (in the first iteration of the propagate_liveness() loop),
* we didn't arrive by the straight-line code, so read marks in state must
* propagate to parent regardless of state's write marks.
*/
static bool do_propagate_liveness(const struct bpf_verifier_state *state,
struct bpf_verifier_state *parent)
{
bool writes = parent == state->parent; /* Observe write marks */
bool touched = false; /* any changes made? */
int i;
if (!parent)
return touched;
/* Propagate read liveness of registers... */
BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
/* We don't need to worry about FP liveness because it's read-only */
for (i = 0; i < BPF_REG_FP; i++) {
if (parent->regs[i].live & REG_LIVE_READ)
continue;
if (writes && (state->regs[i].live & REG_LIVE_WRITTEN))
continue;
if (state->regs[i].live & REG_LIVE_READ) {
parent->regs[i].live |= REG_LIVE_READ;
touched = true;
}
}
/* ... and stack slots */
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
i < parent->allocated_stack / BPF_REG_SIZE; i++) {
if (parent->stack[i].slot_type[0] != STACK_SPILL)
continue;
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
continue;
if (writes &&
(state->stack[i].spilled_ptr.live & REG_LIVE_WRITTEN))
continue;
if (state->stack[i].spilled_ptr.live & REG_LIVE_READ) {
parent->stack[i].spilled_ptr.live |= REG_LIVE_READ;
touched = true;
}
}
return touched;
}
/* "parent" is "a state from which we reach the current state", but initially
* it is not the state->parent (i.e. "the state whose straight-line code leads
* to the current state"), instead it is the state that happened to arrive at
* a (prunable) equivalent of the current state. See comment above
* do_propagate_liveness() for consequences of this.
* This function is just a more efficient way of calling mark_reg_read() or
* mark_stack_slot_read() on each reg in "parent" that is read in "state",
* though it requires that parent != state->parent in the call arguments.
*/
static void propagate_liveness(const struct bpf_verifier_state *state,
struct bpf_verifier_state *parent)
{
while (do_propagate_liveness(state, parent)) {
/* Something changed, so we need to feed those changes onward */
state = parent;
parent = state->parent;
}
}
static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
{
struct bpf_verifier_state_list *new_sl;
struct bpf_verifier_state_list *sl;
struct bpf_verifier_state *cur = env->cur_state;
int i, err;
sl = env->explored_states[insn_idx];
if (!sl)
/* this 'insn_idx' instruction wasn't marked, so we will not
* be doing state search here
*/
return 0;
while (sl != STATE_LIST_MARK) {
if (states_equal(env, &sl->state, cur)) {
/* reached equivalent register/stack state,
* prune the search.
* Registers read by the continuation are read by us.
* If we have any write marks in env->cur_state, they
* will prevent corresponding reads in the continuation
* from reaching our parent (an explored_state). Our
* own state will get the read marks recorded, but
* they'll be immediately forgotten as we're pruning
* this state and will pop a new one.
*/
propagate_liveness(&sl->state, cur);
return 1;
}
sl = sl->next;
}
/* there were no equivalent states, remember current one.
* technically the current state is not proven to be safe yet,
* but it will either reach bpf_exit (which means it's safe) or
* it will be rejected. Since there are no loops, we won't be
* seeing this 'insn_idx' instruction again on the way to bpf_exit
*/
new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
if (!new_sl)
return -ENOMEM;
/* add new state to the head of linked list */
err = copy_verifier_state(&new_sl->state, cur);
if (err) {
free_verifier_state(&new_sl->state, false);
kfree(new_sl);
return err;
}
new_sl->next = env->explored_states[insn_idx];
env->explored_states[insn_idx] = new_sl;
/* connect new state to parentage chain */
cur->parent = &new_sl->state;
/* clear write marks in current state: the writes we did are not writes
* our child did, so they don't screen off its reads from us.
* (There are no read marks in current state, because reads always mark
* their parent and current state never has children yet. Only
* explored_states can get read marks.)
*/
for (i = 0; i < BPF_REG_FP; i++)
cur->regs[i].live = REG_LIVE_NONE;
for (i = 0; i < cur->allocated_stack / BPF_REG_SIZE; i++)
if (cur->stack[i].slot_type[0] == STACK_SPILL)
cur->stack[i].spilled_ptr.live = REG_LIVE_NONE;
return 0;
}
static int ext_analyzer_insn_hook(struct bpf_verifier_env *env,
int insn_idx, int prev_insn_idx)
{
if (env->dev_ops && env->dev_ops->insn_hook)
return env->dev_ops->insn_hook(env, insn_idx, prev_insn_idx);
return 0;
}
static int do_check(struct bpf_verifier_env *env)
{
struct bpf_verifier_state *state;
struct bpf_insn *insns = env->prog->insnsi;
struct bpf_reg_state *regs;
int insn_cnt = env->prog->len;
int insn_idx, prev_insn_idx = 0;
int insn_processed = 0;
bool do_print_state = false;
state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
if (!state)
return -ENOMEM;
env->cur_state = state;
init_reg_state(env, state->regs);
state->parent = NULL;
insn_idx = 0;
for (;;) {
struct bpf_insn *insn;
u8 class;
int err;
if (insn_idx >= insn_cnt) {
verbose(env, "invalid insn idx %d insn_cnt %d\n",
insn_idx, insn_cnt);
return -EFAULT;
}
insn = &insns[insn_idx];
class = BPF_CLASS(insn->code);
if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
verbose(env,
"BPF program is too large. Processed %d insn\n",
insn_processed);
return -E2BIG;
}
err = is_state_visited(env, insn_idx);
if (err < 0)
return err;
if (err == 1) {
/* found equivalent state, can prune the search */
if (env->log.level) {
if (do_print_state)
verbose(env, "\nfrom %d to %d: safe\n",
prev_insn_idx, insn_idx);
else
verbose(env, "%d: safe\n", insn_idx);
}
goto process_bpf_exit;
}
if (need_resched())
cond_resched();
if (env->log.level > 1 || (env->log.level && do_print_state)) {
if (env->log.level > 1)
verbose(env, "%d:", insn_idx);
else
verbose(env, "\nfrom %d to %d:",
prev_insn_idx, insn_idx);
print_verifier_state(env, state);
do_print_state = false;
}
if (env->log.level) {
verbose(env, "%d: ", insn_idx);
print_bpf_insn(verbose, env, insn,
env->allow_ptr_leaks);
}
err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);
if (err)
return err;
regs = cur_regs(env);
env->insn_aux_data[insn_idx].seen = true;
if (class == BPF_ALU || class == BPF_ALU64) {
err = check_alu_op(env, insn);
if (err)
return err;
} else if (class == BPF_LDX) {
enum bpf_reg_type *prev_src_type, src_reg_type;
/* check for reserved fields is already done */
/* check src operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
src_reg_type = regs[insn->src_reg].type;
/* check that memory (src_reg + off) is readable,
* the state of dst_reg will be updated by this func
*/
err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
BPF_SIZE(insn->code), BPF_READ,
insn->dst_reg);
if (err)
return err;
prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
if (*prev_src_type == NOT_INIT) {
/* saw a valid insn
* dst_reg = *(u32 *)(src_reg + off)
* save type to validate intersecting paths
*/
*prev_src_type = src_reg_type;
} else if (src_reg_type != *prev_src_type &&
(src_reg_type == PTR_TO_CTX ||
*prev_src_type == PTR_TO_CTX)) {
/* ABuser program is trying to use the same insn
* dst_reg = *(u32*) (src_reg + off)
* with different pointer types:
* src_reg == ctx in one branch and
* src_reg == stack|map in some other branch.
* Reject it.
*/
verbose(env, "same insn cannot be used with different pointers\n");
return -EINVAL;
}
} else if (class == BPF_STX) {
enum bpf_reg_type *prev_dst_type, dst_reg_type;
if (BPF_MODE(insn->code) == BPF_XADD) {
err = check_xadd(env, insn_idx, insn);
if (err)
return err;
insn_idx++;
continue;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
dst_reg_type = regs[insn->dst_reg].type;
/* check that memory (dst_reg + off) is writeable */
err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE,
insn->src_reg);
if (err)
return err;
prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
if (*prev_dst_type == NOT_INIT) {
*prev_dst_type = dst_reg_type;
} else if (dst_reg_type != *prev_dst_type &&
(dst_reg_type == PTR_TO_CTX ||
*prev_dst_type == PTR_TO_CTX)) {
verbose(env, "same insn cannot be used with different pointers\n");
return -EINVAL;
}
} else if (class == BPF_ST) {
if (BPF_MODE(insn->code) != BPF_MEM ||
insn->src_reg != BPF_REG_0) {
verbose(env, "BPF_ST uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
/* check that memory (dst_reg + off) is writeable */
err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE,
-1);
if (err)
return err;
} else if (class == BPF_JMP) {
u8 opcode = BPF_OP(insn->code);
if (opcode == BPF_CALL) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->off != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_CALL uses reserved fields\n");
return -EINVAL;
}
err = check_call(env, insn->imm, insn_idx);
if (err)
return err;
} else if (opcode == BPF_JA) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->imm != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_JA uses reserved fields\n");
return -EINVAL;
}
insn_idx += insn->off + 1;
continue;
} else if (opcode == BPF_EXIT) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->imm != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_EXIT uses reserved fields\n");
return -EINVAL;
}
/* eBPF calling convetion is such that R0 is used
* to return the value from eBPF program.
* Make sure that it's readable at this time
* of bpf_exit, which means that program wrote
* something into it earlier
*/
err = check_reg_arg(env, BPF_REG_0, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, BPF_REG_0)) {
verbose(env, "R0 leaks addr as return value\n");
return -EACCES;
}
err = check_return_code(env);
if (err)
return err;
process_bpf_exit:
err = pop_stack(env, &prev_insn_idx, &insn_idx);
if (err < 0) {
if (err != -ENOENT)
return err;
break;
} else {
do_print_state = true;
continue;
}
} else {
err = check_cond_jmp_op(env, insn, &insn_idx);
if (err)
return err;
}
} else if (class == BPF_LD) {
u8 mode = BPF_MODE(insn->code);
if (mode == BPF_ABS || mode == BPF_IND) {
err = check_ld_abs(env, insn);
if (err)
return err;
} else if (mode == BPF_IMM) {
err = check_ld_imm(env, insn);
if (err)
return err;
insn_idx++;
env->insn_aux_data[insn_idx].seen = true;
} else {
verbose(env, "invalid BPF_LD mode\n");
return -EINVAL;
}
} else {
verbose(env, "unknown insn class %d\n", class);
return -EINVAL;
}
insn_idx++;
}
verbose(env, "processed %d insns, stack depth %d\n", insn_processed,
env->prog->aux->stack_depth);
return 0;
}
static int check_map_prealloc(struct bpf_map *map)
{
return (map->map_type != BPF_MAP_TYPE_HASH &&
map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
!(map->map_flags & BPF_F_NO_PREALLOC);
}
static int check_map_prog_compatibility(struct bpf_verifier_env *env,
struct bpf_map *map,
struct bpf_prog *prog)
{
/* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
* preallocated hash maps, since doing memory allocation
* in overflow_handler can crash depending on where nmi got
* triggered.
*/
if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
if (!check_map_prealloc(map)) {
verbose(env, "perf_event programs can only use preallocated hash map\n");
return -EINVAL;
}
if (map->inner_map_meta &&
!check_map_prealloc(map->inner_map_meta)) {
verbose(env, "perf_event programs can only use preallocated inner hash map\n");
return -EINVAL;
}
}
return 0;
}
/* look for pseudo eBPF instructions that access map FDs and
* replace them with actual map pointers
*/
static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
{
struct bpf_insn *insn = env->prog->insnsi;
int insn_cnt = env->prog->len;
int i, j, err;
err = bpf_prog_calc_tag(env->prog);
if (err)
return err;
for (i = 0; i < insn_cnt; i++, insn++) {
if (BPF_CLASS(insn->code) == BPF_LDX &&
(BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
verbose(env, "BPF_LDX uses reserved fields\n");
return -EINVAL;
}
if (BPF_CLASS(insn->code) == BPF_STX &&
((BPF_MODE(insn->code) != BPF_MEM &&
BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
verbose(env, "BPF_STX uses reserved fields\n");
return -EINVAL;
}
if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
struct bpf_map *map;
struct fd f;
if (i == insn_cnt - 1 || insn[1].code != 0 ||
insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
insn[1].off != 0) {
verbose(env, "invalid bpf_ld_imm64 insn\n");
return -EINVAL;
}
if (insn->src_reg == 0)
/* valid generic load 64-bit imm */
goto next_insn;
if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
verbose(env,
"unrecognized bpf_ld_imm64 insn\n");
return -EINVAL;
}
f = fdget(insn->imm);
map = __bpf_map_get(f);
if (IS_ERR(map)) {
verbose(env, "fd %d is not pointing to valid bpf_map\n",
insn->imm);
return PTR_ERR(map);
}
err = check_map_prog_compatibility(env, map, env->prog);
if (err) {
fdput(f);
return err;
}
/* store map pointer inside BPF_LD_IMM64 instruction */
insn[0].imm = (u32) (unsigned long) map;
insn[1].imm = ((u64) (unsigned long) map) >> 32;
/* check whether we recorded this map already */
for (j = 0; j < env->used_map_cnt; j++)
if (env->used_maps[j] == map) {
fdput(f);
goto next_insn;
}
if (env->used_map_cnt >= MAX_USED_MAPS) {
fdput(f);
return -E2BIG;
}
/* hold the map. If the program is rejected by verifier,
* the map will be released by release_maps() or it
* will be used by the valid program until it's unloaded
* and all maps are released in free_bpf_prog_info()
*/
map = bpf_map_inc(map, false);
if (IS_ERR(map)) {
fdput(f);
return PTR_ERR(map);
}
env->used_maps[env->used_map_cnt++] = map;
fdput(f);
next_insn:
insn++;
i++;
}
}
/* now all pseudo BPF_LD_IMM64 instructions load valid
* 'struct bpf_map *' into a register instead of user map_fd.
* These pointers will be used later by verifier to validate map access.
*/
return 0;
}
/* drop refcnt of maps used by the rejected program */
static void release_maps(struct bpf_verifier_env *env)
{
int i;
for (i = 0; i < env->used_map_cnt; i++)
bpf_map_put(env->used_maps[i]);
}
/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
{
struct bpf_insn *insn = env->prog->insnsi;
int insn_cnt = env->prog->len;
int i;
for (i = 0; i < insn_cnt; i++, insn++)
if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
insn->src_reg = 0;
}
/* single env->prog->insni[off] instruction was replaced with the range
* insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
* [0, off) and [off, end) to new locations, so the patched range stays zero
*/
static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
u32 off, u32 cnt)
{
struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
int i;
if (cnt == 1)
return 0;
new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
if (!new_data)
return -ENOMEM;
memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
memcpy(new_data + off + cnt - 1, old_data + off,
sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
for (i = off; i < off + cnt - 1; i++)
new_data[i].seen = true;
env->insn_aux_data = new_data;
vfree(old_data);
return 0;
}
static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
const struct bpf_insn *patch, u32 len)
{
struct bpf_prog *new_prog;
new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
if (!new_prog)
return NULL;
if (adjust_insn_aux_data(env, new_prog->len, off, len))
return NULL;
return new_prog;
}
/* The verifier does more data flow analysis than llvm and will not explore
* branches that are dead at run time. Malicious programs can have dead code
* too. Therefore replace all dead at-run-time code with nops.
*/
static void sanitize_dead_code(struct bpf_verifier_env *env)
{
struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
struct bpf_insn nop = BPF_MOV64_REG(BPF_REG_0, BPF_REG_0);
struct bpf_insn *insn = env->prog->insnsi;
const int insn_cnt = env->prog->len;
int i;
for (i = 0; i < insn_cnt; i++) {
if (aux_data[i].seen)
continue;
memcpy(insn + i, &nop, sizeof(nop));
}
}
/* convert load instructions that access fields of 'struct __sk_buff'
* into sequence of instructions that access fields of 'struct sk_buff'
*/
static int convert_ctx_accesses(struct bpf_verifier_env *env)
{
const struct bpf_verifier_ops *ops = env->ops;
int i, cnt, size, ctx_field_size, delta = 0;
const int insn_cnt = env->prog->len;
struct bpf_insn insn_buf[16], *insn;
struct bpf_prog *new_prog;
enum bpf_access_type type;
bool is_narrower_load;
u32 target_size;
if (ops->gen_prologue) {
cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
env->prog);
if (cnt >= ARRAY_SIZE(insn_buf)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
} else if (cnt) {
new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
env->prog = new_prog;
delta += cnt - 1;
}
}
if (!ops->convert_ctx_access)
return 0;
insn = env->prog->insnsi + delta;
for (i = 0; i < insn_cnt; i++, insn++) {
if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
type = BPF_READ;
else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
insn->code == (BPF_STX | BPF_MEM | BPF_DW))
type = BPF_WRITE;
else
continue;
if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
continue;
ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
size = BPF_LDST_BYTES(insn);
/* If the read access is a narrower load of the field,
* convert to a 4/8-byte load, to minimum program type specific
* convert_ctx_access changes. If conversion is successful,
* we will apply proper mask to the result.
*/
is_narrower_load = size < ctx_field_size;
if (is_narrower_load) {
u32 off = insn->off;
u8 size_code;
if (type == BPF_WRITE) {
verbose(env, "bpf verifier narrow ctx access misconfigured\n");
return -EINVAL;
}
size_code = BPF_H;
if (ctx_field_size == 4)
size_code = BPF_W;
else if (ctx_field_size == 8)
size_code = BPF_DW;
insn->off = off & ~(ctx_field_size - 1);
insn->code = BPF_LDX | BPF_MEM | size_code;
}
target_size = 0;
cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
&target_size);
if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
(ctx_field_size && !target_size)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
}
if (is_narrower_load && size < target_size) {
if (ctx_field_size <= 4)
insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
(1 << size * 8) - 1);
else
insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
(1 << size * 8) - 1);
}
new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
/* keep walking new program and skip insns we just inserted */
env->prog = new_prog;
insn = new_prog->insnsi + i + delta;
}
return 0;
}
/* fixup insn->imm field of bpf_call instructions
* and inline eligible helpers as explicit sequence of BPF instructions
*
* this function is called after eBPF program passed verification
*/
static int fixup_bpf_calls(struct bpf_verifier_env *env)
{
struct bpf_prog *prog = env->prog;
struct bpf_insn *insn = prog->insnsi;
const struct bpf_func_proto *fn;
const int insn_cnt = prog->len;
struct bpf_insn insn_buf[16];
struct bpf_prog *new_prog;
struct bpf_map *map_ptr;
int i, cnt, delta = 0;
for (i = 0; i < insn_cnt; i++, insn++) {
if (insn->code != (BPF_JMP | BPF_CALL))
continue;
if (insn->imm == BPF_FUNC_get_route_realm)
prog->dst_needed = 1;
if (insn->imm == BPF_FUNC_get_prandom_u32)
bpf_user_rnd_init_once();
if (insn->imm == BPF_FUNC_tail_call) {
/* If we tail call into other programs, we
* cannot make any assumptions since they can
* be replaced dynamically during runtime in
* the program array.
*/
prog->cb_access = 1;
env->prog->aux->stack_depth = MAX_BPF_STACK;
/* mark bpf_tail_call as different opcode to avoid
* conditional branch in the interpeter for every normal
* call and to prevent accidental JITing by JIT compiler
* that doesn't support bpf_tail_call yet
*/
insn->imm = 0;
insn->code = BPF_JMP | BPF_TAIL_CALL;
continue;
}
/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
* handlers are currently limited to 64 bit only.
*/
if (ebpf_jit_enabled() && BITS_PER_LONG == 64 &&
insn->imm == BPF_FUNC_map_lookup_elem) {
map_ptr = env->insn_aux_data[i + delta].map_ptr;
if (map_ptr == BPF_MAP_PTR_POISON ||
!map_ptr->ops->map_gen_lookup)
goto patch_call_imm;
cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf);
if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
}
new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
/* keep walking new program and skip insns we just inserted */
env->prog = prog = new_prog;
insn = new_prog->insnsi + i + delta;
continue;
}
if (insn->imm == BPF_FUNC_redirect_map) {
/* Note, we cannot use prog directly as imm as subsequent
* rewrites would still change the prog pointer. The only
* stable address we can use is aux, which also works with
* prog clones during blinding.
*/
u64 addr = (unsigned long)prog->aux;
struct bpf_insn r4_ld[] = {
BPF_LD_IMM64(BPF_REG_4, addr),
*insn,
};
cnt = ARRAY_SIZE(r4_ld);
new_prog = bpf_patch_insn_data(env, i + delta, r4_ld, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
env->prog = prog = new_prog;
insn = new_prog->insnsi + i + delta;
}
patch_call_imm:
fn = env->ops->get_func_proto(insn->imm);
/* all functions that have prototype and verifier allowed
* programs to call them, must be real in-kernel functions
*/
if (!fn->func) {
verbose(env,
"kernel subsystem misconfigured func %s#%d\n",
func_id_name(insn->imm), insn->imm);
return -EFAULT;
}
insn->imm = fn->func - __bpf_call_base;
}
return 0;
}
static void free_states(struct bpf_verifier_env *env)
{
struct bpf_verifier_state_list *sl, *sln;
int i;
if (!env->explored_states)
return;
for (i = 0; i < env->prog->len; i++) {
sl = env->explored_states[i];
if (sl)
while (sl != STATE_LIST_MARK) {
sln = sl->next;
free_verifier_state(&sl->state, false);
kfree(sl);
sl = sln;
}
}
kfree(env->explored_states);
}
int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
{
struct bpf_verifier_env *env;
struct bpf_verifer_log *log;
int ret = -EINVAL;
/* no program is valid */
if (ARRAY_SIZE(bpf_verifier_ops) == 0)
return -EINVAL;
/* 'struct bpf_verifier_env' can be global, but since it's not small,
* allocate/free it every time bpf_check() is called
*/
env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
if (!env)
return -ENOMEM;
log = &env->log;
env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
(*prog)->len);
ret = -ENOMEM;
if (!env->insn_aux_data)
goto err_free_env;
env->prog = *prog;
env->ops = bpf_verifier_ops[env->prog->type];
/* grab the mutex to protect few globals used by verifier */
mutex_lock(&bpf_verifier_lock);
if (attr->log_level || attr->log_buf || attr->log_size) {
/* user requested verbose verifier output
* and supplied buffer to store the verification trace
*/
log->level = attr->log_level;
log->ubuf = (char __user *) (unsigned long) attr->log_buf;
log->len_total = attr->log_size;
ret = -EINVAL;
/* log attributes have to be sane */
if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
!log->level || !log->ubuf)
goto err_unlock;
}
env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
env->strict_alignment = true;
if (env->prog->aux->offload) {
ret = bpf_prog_offload_verifier_prep(env);
if (ret)
goto err_unlock;
}
ret = replace_map_fd_with_map_ptr(env);
if (ret < 0)
goto skip_full_check;
env->explored_states = kcalloc(env->prog->len,
sizeof(struct bpf_verifier_state_list *),
GFP_USER);
ret = -ENOMEM;
if (!env->explored_states)
goto skip_full_check;
ret = check_cfg(env);
if (ret < 0)
goto skip_full_check;
env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
ret = do_check(env);
if (env->cur_state) {
free_verifier_state(env->cur_state, true);
env->cur_state = NULL;
}
skip_full_check:
while (!pop_stack(env, NULL, NULL));
free_states(env);
if (ret == 0)
sanitize_dead_code(env);
if (ret == 0)
/* program is valid, convert *(u32*)(ctx + off) accesses */
ret = convert_ctx_accesses(env);
if (ret == 0)
ret = fixup_bpf_calls(env);
if (log->level && bpf_verifier_log_full(log))
ret = -ENOSPC;
if (log->level && !log->ubuf) {
ret = -EFAULT;
goto err_release_maps;
}
if (ret == 0 && env->used_map_cnt) {
/* if program passed verifier, update used_maps in bpf_prog_info */
env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
sizeof(env->used_maps[0]),
GFP_KERNEL);
if (!env->prog->aux->used_maps) {
ret = -ENOMEM;
goto err_release_maps;
}
memcpy(env->prog->aux->used_maps, env->used_maps,
sizeof(env->used_maps[0]) * env->used_map_cnt);
env->prog->aux->used_map_cnt = env->used_map_cnt;
/* program is valid. Convert pseudo bpf_ld_imm64 into generic
* bpf_ld_imm64 instructions
*/
convert_pseudo_ld_imm64(env);
}
err_release_maps:
if (!env->prog->aux->used_maps)
/* if we didn't copy map pointers into bpf_prog_info, release
* them now. Otherwise free_bpf_prog_info() will release them.
*/
release_maps(env);
*prog = env->prog;
err_unlock:
mutex_unlock(&bpf_verifier_lock);
vfree(env->insn_aux_data);
err_free_env:
kfree(env);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2986_0 |
crossvul-cpp_data_bad_4907_2 | /*
* kernel/sched/core.c
*
* Kernel scheduler and related syscalls
*
* Copyright (C) 1991-2002 Linus Torvalds
*
* 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
* make semaphores SMP safe
* 1998-11-19 Implemented schedule_timeout() and related stuff
* by Andrea Arcangeli
* 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
* hybrid priority-list and round-robin design with
* an array-switch method of distributing timeslices
* and per-CPU runqueues. Cleanups and useful suggestions
* by Davide Libenzi, preemptible kernel bits by Robert Love.
* 2003-09-03 Interactivity tuning by Con Kolivas.
* 2004-04-02 Scheduler domains code by Nick Piggin
* 2007-04-15 Work begun on replacing all interactivity tuning with a
* fair scheduling design by Con Kolivas.
* 2007-05-05 Load balancing (smp-nice) and other improvements
* by Peter Williams
* 2007-05-06 Interactivity improvements to CFS by Mike Galbraith
* 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri
* 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins,
* Thomas Gleixner, Mike Kravetz
*/
#include <linux/kasan.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/nmi.h>
#include <linux/init.h>
#include <linux/uaccess.h>
#include <linux/highmem.h>
#include <linux/mmu_context.h>
#include <linux/interrupt.h>
#include <linux/capability.h>
#include <linux/completion.h>
#include <linux/kernel_stat.h>
#include <linux/debug_locks.h>
#include <linux/perf_event.h>
#include <linux/security.h>
#include <linux/notifier.h>
#include <linux/profile.h>
#include <linux/freezer.h>
#include <linux/vmalloc.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/pid_namespace.h>
#include <linux/smp.h>
#include <linux/threads.h>
#include <linux/timer.h>
#include <linux/rcupdate.h>
#include <linux/cpu.h>
#include <linux/cpuset.h>
#include <linux/percpu.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/sysctl.h>
#include <linux/syscalls.h>
#include <linux/times.h>
#include <linux/tsacct_kern.h>
#include <linux/kprobes.h>
#include <linux/delayacct.h>
#include <linux/unistd.h>
#include <linux/pagemap.h>
#include <linux/hrtimer.h>
#include <linux/tick.h>
#include <linux/ctype.h>
#include <linux/ftrace.h>
#include <linux/slab.h>
#include <linux/init_task.h>
#include <linux/context_tracking.h>
#include <linux/compiler.h>
#include <linux/frame.h>
#include <asm/switch_to.h>
#include <asm/tlb.h>
#include <asm/irq_regs.h>
#include <asm/mutex.h>
#ifdef CONFIG_PARAVIRT
#include <asm/paravirt.h>
#endif
#include "sched.h"
#include "../workqueue_internal.h"
#include "../smpboot.h"
#define CREATE_TRACE_POINTS
#include <trace/events/sched.h>
DEFINE_MUTEX(sched_domains_mutex);
DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
static void update_rq_clock_task(struct rq *rq, s64 delta);
void update_rq_clock(struct rq *rq)
{
s64 delta;
lockdep_assert_held(&rq->lock);
if (rq->clock_skip_update & RQCF_ACT_SKIP)
return;
delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
if (delta < 0)
return;
rq->clock += delta;
update_rq_clock_task(rq, delta);
}
/*
* Debugging: various feature bits
*/
#define SCHED_FEAT(name, enabled) \
(1UL << __SCHED_FEAT_##name) * enabled |
const_debug unsigned int sysctl_sched_features =
#include "features.h"
0;
#undef SCHED_FEAT
/*
* Number of tasks to iterate in a single balance run.
* Limited because this is done with IRQs disabled.
*/
const_debug unsigned int sysctl_sched_nr_migrate = 32;
/*
* period over which we average the RT time consumption, measured
* in ms.
*
* default: 1s
*/
const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
/*
* period over which we measure -rt task cpu usage in us.
* default: 1s
*/
unsigned int sysctl_sched_rt_period = 1000000;
__read_mostly int scheduler_running;
/*
* part of the period that we allow rt tasks to run in us.
* default: 0.95s
*/
int sysctl_sched_rt_runtime = 950000;
/* cpus with isolated domains */
cpumask_var_t cpu_isolated_map;
/*
* this_rq_lock - lock this runqueue and disable interrupts.
*/
static struct rq *this_rq_lock(void)
__acquires(rq->lock)
{
struct rq *rq;
local_irq_disable();
rq = this_rq();
raw_spin_lock(&rq->lock);
return rq;
}
/*
* __task_rq_lock - lock the rq @p resides on.
*/
struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
__acquires(rq->lock)
{
struct rq *rq;
lockdep_assert_held(&p->pi_lock);
for (;;) {
rq = task_rq(p);
raw_spin_lock(&rq->lock);
if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
rf->cookie = lockdep_pin_lock(&rq->lock);
return rq;
}
raw_spin_unlock(&rq->lock);
while (unlikely(task_on_rq_migrating(p)))
cpu_relax();
}
}
/*
* task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
*/
struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
__acquires(p->pi_lock)
__acquires(rq->lock)
{
struct rq *rq;
for (;;) {
raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
rq = task_rq(p);
raw_spin_lock(&rq->lock);
/*
* move_queued_task() task_rq_lock()
*
* ACQUIRE (rq->lock)
* [S] ->on_rq = MIGRATING [L] rq = task_rq()
* WMB (__set_task_cpu()) ACQUIRE (rq->lock);
* [S] ->cpu = new_cpu [L] task_rq()
* [L] ->on_rq
* RELEASE (rq->lock)
*
* If we observe the old cpu in task_rq_lock, the acquire of
* the old rq->lock will fully serialize against the stores.
*
* If we observe the new cpu in task_rq_lock, the acquire will
* pair with the WMB to ensure we must then also see migrating.
*/
if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
rf->cookie = lockdep_pin_lock(&rq->lock);
return rq;
}
raw_spin_unlock(&rq->lock);
raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
while (unlikely(task_on_rq_migrating(p)))
cpu_relax();
}
}
#ifdef CONFIG_SCHED_HRTICK
/*
* Use HR-timers to deliver accurate preemption points.
*/
static void hrtick_clear(struct rq *rq)
{
if (hrtimer_active(&rq->hrtick_timer))
hrtimer_cancel(&rq->hrtick_timer);
}
/*
* High-resolution timer tick.
* Runs from hardirq context with interrupts disabled.
*/
static enum hrtimer_restart hrtick(struct hrtimer *timer)
{
struct rq *rq = container_of(timer, struct rq, hrtick_timer);
WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
raw_spin_lock(&rq->lock);
update_rq_clock(rq);
rq->curr->sched_class->task_tick(rq, rq->curr, 1);
raw_spin_unlock(&rq->lock);
return HRTIMER_NORESTART;
}
#ifdef CONFIG_SMP
static void __hrtick_restart(struct rq *rq)
{
struct hrtimer *timer = &rq->hrtick_timer;
hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
}
/*
* called from hardirq (IPI) context
*/
static void __hrtick_start(void *arg)
{
struct rq *rq = arg;
raw_spin_lock(&rq->lock);
__hrtick_restart(rq);
rq->hrtick_csd_pending = 0;
raw_spin_unlock(&rq->lock);
}
/*
* Called to set the hrtick timer state.
*
* called with rq->lock held and irqs disabled
*/
void hrtick_start(struct rq *rq, u64 delay)
{
struct hrtimer *timer = &rq->hrtick_timer;
ktime_t time;
s64 delta;
/*
* Don't schedule slices shorter than 10000ns, that just
* doesn't make sense and can cause timer DoS.
*/
delta = max_t(s64, delay, 10000LL);
time = ktime_add_ns(timer->base->get_time(), delta);
hrtimer_set_expires(timer, time);
if (rq == this_rq()) {
__hrtick_restart(rq);
} else if (!rq->hrtick_csd_pending) {
smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
rq->hrtick_csd_pending = 1;
}
}
#else
/*
* Called to set the hrtick timer state.
*
* called with rq->lock held and irqs disabled
*/
void hrtick_start(struct rq *rq, u64 delay)
{
/*
* Don't schedule slices shorter than 10000ns, that just
* doesn't make sense. Rely on vruntime for fairness.
*/
delay = max_t(u64, delay, 10000LL);
hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
HRTIMER_MODE_REL_PINNED);
}
#endif /* CONFIG_SMP */
static void init_rq_hrtick(struct rq *rq)
{
#ifdef CONFIG_SMP
rq->hrtick_csd_pending = 0;
rq->hrtick_csd.flags = 0;
rq->hrtick_csd.func = __hrtick_start;
rq->hrtick_csd.info = rq;
#endif
hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
rq->hrtick_timer.function = hrtick;
}
#else /* CONFIG_SCHED_HRTICK */
static inline void hrtick_clear(struct rq *rq)
{
}
static inline void init_rq_hrtick(struct rq *rq)
{
}
#endif /* CONFIG_SCHED_HRTICK */
/*
* cmpxchg based fetch_or, macro so it works for different integer types
*/
#define fetch_or(ptr, mask) \
({ \
typeof(ptr) _ptr = (ptr); \
typeof(mask) _mask = (mask); \
typeof(*_ptr) _old, _val = *_ptr; \
\
for (;;) { \
_old = cmpxchg(_ptr, _val, _val | _mask); \
if (_old == _val) \
break; \
_val = _old; \
} \
_old; \
})
#if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
/*
* Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
* this avoids any races wrt polling state changes and thereby avoids
* spurious IPIs.
*/
static bool set_nr_and_not_polling(struct task_struct *p)
{
struct thread_info *ti = task_thread_info(p);
return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
}
/*
* Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
*
* If this returns true, then the idle task promises to call
* sched_ttwu_pending() and reschedule soon.
*/
static bool set_nr_if_polling(struct task_struct *p)
{
struct thread_info *ti = task_thread_info(p);
typeof(ti->flags) old, val = READ_ONCE(ti->flags);
for (;;) {
if (!(val & _TIF_POLLING_NRFLAG))
return false;
if (val & _TIF_NEED_RESCHED)
return true;
old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
if (old == val)
break;
val = old;
}
return true;
}
#else
static bool set_nr_and_not_polling(struct task_struct *p)
{
set_tsk_need_resched(p);
return true;
}
#ifdef CONFIG_SMP
static bool set_nr_if_polling(struct task_struct *p)
{
return false;
}
#endif
#endif
void wake_q_add(struct wake_q_head *head, struct task_struct *task)
{
struct wake_q_node *node = &task->wake_q;
/*
* Atomically grab the task, if ->wake_q is !nil already it means
* its already queued (either by us or someone else) and will get the
* wakeup due to that.
*
* This cmpxchg() implies a full barrier, which pairs with the write
* barrier implied by the wakeup in wake_up_q().
*/
if (cmpxchg(&node->next, NULL, WAKE_Q_TAIL))
return;
get_task_struct(task);
/*
* The head is context local, there can be no concurrency.
*/
*head->lastp = node;
head->lastp = &node->next;
}
void wake_up_q(struct wake_q_head *head)
{
struct wake_q_node *node = head->first;
while (node != WAKE_Q_TAIL) {
struct task_struct *task;
task = container_of(node, struct task_struct, wake_q);
BUG_ON(!task);
/* task can safely be re-inserted now */
node = node->next;
task->wake_q.next = NULL;
/*
* wake_up_process() implies a wmb() to pair with the queueing
* in wake_q_add() so as not to miss wakeups.
*/
wake_up_process(task);
put_task_struct(task);
}
}
/*
* resched_curr - mark rq's current task 'to be rescheduled now'.
*
* On UP this means the setting of the need_resched flag, on SMP it
* might also involve a cross-CPU call to trigger the scheduler on
* the target CPU.
*/
void resched_curr(struct rq *rq)
{
struct task_struct *curr = rq->curr;
int cpu;
lockdep_assert_held(&rq->lock);
if (test_tsk_need_resched(curr))
return;
cpu = cpu_of(rq);
if (cpu == smp_processor_id()) {
set_tsk_need_resched(curr);
set_preempt_need_resched();
return;
}
if (set_nr_and_not_polling(curr))
smp_send_reschedule(cpu);
else
trace_sched_wake_idle_without_ipi(cpu);
}
void resched_cpu(int cpu)
{
struct rq *rq = cpu_rq(cpu);
unsigned long flags;
if (!raw_spin_trylock_irqsave(&rq->lock, flags))
return;
resched_curr(rq);
raw_spin_unlock_irqrestore(&rq->lock, flags);
}
#ifdef CONFIG_SMP
#ifdef CONFIG_NO_HZ_COMMON
/*
* In the semi idle case, use the nearest busy cpu for migrating timers
* from an idle cpu. This is good for power-savings.
*
* We don't do similar optimization for completely idle system, as
* selecting an idle cpu will add more delays to the timers than intended
* (as that cpu's timer base may not be uptodate wrt jiffies etc).
*/
int get_nohz_timer_target(void)
{
int i, cpu = smp_processor_id();
struct sched_domain *sd;
if (!idle_cpu(cpu) && is_housekeeping_cpu(cpu))
return cpu;
rcu_read_lock();
for_each_domain(cpu, sd) {
for_each_cpu(i, sched_domain_span(sd)) {
if (cpu == i)
continue;
if (!idle_cpu(i) && is_housekeeping_cpu(i)) {
cpu = i;
goto unlock;
}
}
}
if (!is_housekeeping_cpu(cpu))
cpu = housekeeping_any_cpu();
unlock:
rcu_read_unlock();
return cpu;
}
/*
* When add_timer_on() enqueues a timer into the timer wheel of an
* idle CPU then this timer might expire before the next timer event
* which is scheduled to wake up that CPU. In case of a completely
* idle system the next event might even be infinite time into the
* future. wake_up_idle_cpu() ensures that the CPU is woken up and
* leaves the inner idle loop so the newly added timer is taken into
* account when the CPU goes back to idle and evaluates the timer
* wheel for the next timer event.
*/
static void wake_up_idle_cpu(int cpu)
{
struct rq *rq = cpu_rq(cpu);
if (cpu == smp_processor_id())
return;
if (set_nr_and_not_polling(rq->idle))
smp_send_reschedule(cpu);
else
trace_sched_wake_idle_without_ipi(cpu);
}
static bool wake_up_full_nohz_cpu(int cpu)
{
/*
* We just need the target to call irq_exit() and re-evaluate
* the next tick. The nohz full kick at least implies that.
* If needed we can still optimize that later with an
* empty IRQ.
*/
if (tick_nohz_full_cpu(cpu)) {
if (cpu != smp_processor_id() ||
tick_nohz_tick_stopped())
tick_nohz_full_kick_cpu(cpu);
return true;
}
return false;
}
void wake_up_nohz_cpu(int cpu)
{
if (!wake_up_full_nohz_cpu(cpu))
wake_up_idle_cpu(cpu);
}
static inline bool got_nohz_idle_kick(void)
{
int cpu = smp_processor_id();
if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
return false;
if (idle_cpu(cpu) && !need_resched())
return true;
/*
* We can't run Idle Load Balance on this CPU for this time so we
* cancel it and clear NOHZ_BALANCE_KICK
*/
clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
return false;
}
#else /* CONFIG_NO_HZ_COMMON */
static inline bool got_nohz_idle_kick(void)
{
return false;
}
#endif /* CONFIG_NO_HZ_COMMON */
#ifdef CONFIG_NO_HZ_FULL
bool sched_can_stop_tick(struct rq *rq)
{
int fifo_nr_running;
/* Deadline tasks, even if single, need the tick */
if (rq->dl.dl_nr_running)
return false;
/*
* If there are more than one RR tasks, we need the tick to effect the
* actual RR behaviour.
*/
if (rq->rt.rr_nr_running) {
if (rq->rt.rr_nr_running == 1)
return true;
else
return false;
}
/*
* If there's no RR tasks, but FIFO tasks, we can skip the tick, no
* forced preemption between FIFO tasks.
*/
fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
if (fifo_nr_running)
return true;
/*
* If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
* if there's more than one we need the tick for involuntary
* preemption.
*/
if (rq->nr_running > 1)
return false;
return true;
}
#endif /* CONFIG_NO_HZ_FULL */
void sched_avg_update(struct rq *rq)
{
s64 period = sched_avg_period();
while ((s64)(rq_clock(rq) - rq->age_stamp) > period) {
/*
* Inline assembly required to prevent the compiler
* optimising this loop into a divmod call.
* See __iter_div_u64_rem() for another example of this.
*/
asm("" : "+rm" (rq->age_stamp));
rq->age_stamp += period;
rq->rt_avg /= 2;
}
}
#endif /* CONFIG_SMP */
#if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
(defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
/*
* Iterate task_group tree rooted at *from, calling @down when first entering a
* node and @up when leaving it for the final time.
*
* Caller must hold rcu_lock or sufficient equivalent.
*/
int walk_tg_tree_from(struct task_group *from,
tg_visitor down, tg_visitor up, void *data)
{
struct task_group *parent, *child;
int ret;
parent = from;
down:
ret = (*down)(parent, data);
if (ret)
goto out;
list_for_each_entry_rcu(child, &parent->children, siblings) {
parent = child;
goto down;
up:
continue;
}
ret = (*up)(parent, data);
if (ret || parent == from)
goto out;
child = parent;
parent = parent->parent;
if (parent)
goto up;
out:
return ret;
}
int tg_nop(struct task_group *tg, void *data)
{
return 0;
}
#endif
static void set_load_weight(struct task_struct *p)
{
int prio = p->static_prio - MAX_RT_PRIO;
struct load_weight *load = &p->se.load;
/*
* SCHED_IDLE tasks get minimal weight:
*/
if (idle_policy(p->policy)) {
load->weight = scale_load(WEIGHT_IDLEPRIO);
load->inv_weight = WMULT_IDLEPRIO;
return;
}
load->weight = scale_load(sched_prio_to_weight[prio]);
load->inv_weight = sched_prio_to_wmult[prio];
}
static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
{
update_rq_clock(rq);
if (!(flags & ENQUEUE_RESTORE))
sched_info_queued(rq, p);
p->sched_class->enqueue_task(rq, p, flags);
}
static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
{
update_rq_clock(rq);
if (!(flags & DEQUEUE_SAVE))
sched_info_dequeued(rq, p);
p->sched_class->dequeue_task(rq, p, flags);
}
void activate_task(struct rq *rq, struct task_struct *p, int flags)
{
if (task_contributes_to_load(p))
rq->nr_uninterruptible--;
enqueue_task(rq, p, flags);
}
void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
{
if (task_contributes_to_load(p))
rq->nr_uninterruptible++;
dequeue_task(rq, p, flags);
}
static void update_rq_clock_task(struct rq *rq, s64 delta)
{
/*
* In theory, the compile should just see 0 here, and optimize out the call
* to sched_rt_avg_update. But I don't trust it...
*/
#if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
s64 steal = 0, irq_delta = 0;
#endif
#ifdef CONFIG_IRQ_TIME_ACCOUNTING
irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
/*
* Since irq_time is only updated on {soft,}irq_exit, we might run into
* this case when a previous update_rq_clock() happened inside a
* {soft,}irq region.
*
* When this happens, we stop ->clock_task and only update the
* prev_irq_time stamp to account for the part that fit, so that a next
* update will consume the rest. This ensures ->clock_task is
* monotonic.
*
* It does however cause some slight miss-attribution of {soft,}irq
* time, a more accurate solution would be to update the irq_time using
* the current rq->clock timestamp, except that would require using
* atomic ops.
*/
if (irq_delta > delta)
irq_delta = delta;
rq->prev_irq_time += irq_delta;
delta -= irq_delta;
#endif
#ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
if (static_key_false((¶virt_steal_rq_enabled))) {
steal = paravirt_steal_clock(cpu_of(rq));
steal -= rq->prev_steal_time_rq;
if (unlikely(steal > delta))
steal = delta;
rq->prev_steal_time_rq += steal;
delta -= steal;
}
#endif
rq->clock_task += delta;
#if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
sched_rt_avg_update(rq, irq_delta + steal);
#endif
}
void sched_set_stop_task(int cpu, struct task_struct *stop)
{
struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
struct task_struct *old_stop = cpu_rq(cpu)->stop;
if (stop) {
/*
* Make it appear like a SCHED_FIFO task, its something
* userspace knows about and won't get confused about.
*
* Also, it will make PI more or less work without too
* much confusion -- but then, stop work should not
* rely on PI working anyway.
*/
sched_setscheduler_nocheck(stop, SCHED_FIFO, ¶m);
stop->sched_class = &stop_sched_class;
}
cpu_rq(cpu)->stop = stop;
if (old_stop) {
/*
* Reset it back to a normal scheduling class so that
* it can die in pieces.
*/
old_stop->sched_class = &rt_sched_class;
}
}
/*
* __normal_prio - return the priority that is based on the static prio
*/
static inline int __normal_prio(struct task_struct *p)
{
return p->static_prio;
}
/*
* Calculate the expected normal priority: i.e. priority
* without taking RT-inheritance into account. Might be
* boosted by interactivity modifiers. Changes upon fork,
* setprio syscalls, and whenever the interactivity
* estimator recalculates.
*/
static inline int normal_prio(struct task_struct *p)
{
int prio;
if (task_has_dl_policy(p))
prio = MAX_DL_PRIO-1;
else if (task_has_rt_policy(p))
prio = MAX_RT_PRIO-1 - p->rt_priority;
else
prio = __normal_prio(p);
return prio;
}
/*
* Calculate the current priority, i.e. the priority
* taken into account by the scheduler. This value might
* be boosted by RT tasks, or might be boosted by
* interactivity modifiers. Will be RT if the task got
* RT-boosted. If not then it returns p->normal_prio.
*/
static int effective_prio(struct task_struct *p)
{
p->normal_prio = normal_prio(p);
/*
* If we are RT tasks or we were boosted to RT priority,
* keep the priority unchanged. Otherwise, update priority
* to the normal priority:
*/
if (!rt_prio(p->prio))
return p->normal_prio;
return p->prio;
}
/**
* task_curr - is this task currently executing on a CPU?
* @p: the task in question.
*
* Return: 1 if the task is currently executing. 0 otherwise.
*/
inline int task_curr(const struct task_struct *p)
{
return cpu_curr(task_cpu(p)) == p;
}
/*
* switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
* use the balance_callback list if you want balancing.
*
* this means any call to check_class_changed() must be followed by a call to
* balance_callback().
*/
static inline void check_class_changed(struct rq *rq, struct task_struct *p,
const struct sched_class *prev_class,
int oldprio)
{
if (prev_class != p->sched_class) {
if (prev_class->switched_from)
prev_class->switched_from(rq, p);
p->sched_class->switched_to(rq, p);
} else if (oldprio != p->prio || dl_task(p))
p->sched_class->prio_changed(rq, p, oldprio);
}
void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
{
const struct sched_class *class;
if (p->sched_class == rq->curr->sched_class) {
rq->curr->sched_class->check_preempt_curr(rq, p, flags);
} else {
for_each_class(class) {
if (class == rq->curr->sched_class)
break;
if (class == p->sched_class) {
resched_curr(rq);
break;
}
}
}
/*
* A queue event has occurred, and we're going to schedule. In
* this case, we can save a useless back to back clock update.
*/
if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
rq_clock_skip_update(rq, true);
}
#ifdef CONFIG_SMP
/*
* This is how migration works:
*
* 1) we invoke migration_cpu_stop() on the target CPU using
* stop_one_cpu().
* 2) stopper starts to run (implicitly forcing the migrated thread
* off the CPU)
* 3) it checks whether the migrated task is still in the wrong runqueue.
* 4) if it's in the wrong runqueue then the migration thread removes
* it and puts it into the right queue.
* 5) stopper completes and stop_one_cpu() returns and the migration
* is done.
*/
/*
* move_queued_task - move a queued task to new rq.
*
* Returns (locked) new rq. Old rq's lock is released.
*/
static struct rq *move_queued_task(struct rq *rq, struct task_struct *p, int new_cpu)
{
lockdep_assert_held(&rq->lock);
p->on_rq = TASK_ON_RQ_MIGRATING;
dequeue_task(rq, p, 0);
set_task_cpu(p, new_cpu);
raw_spin_unlock(&rq->lock);
rq = cpu_rq(new_cpu);
raw_spin_lock(&rq->lock);
BUG_ON(task_cpu(p) != new_cpu);
enqueue_task(rq, p, 0);
p->on_rq = TASK_ON_RQ_QUEUED;
check_preempt_curr(rq, p, 0);
return rq;
}
struct migration_arg {
struct task_struct *task;
int dest_cpu;
};
/*
* Move (not current) task off this cpu, onto dest cpu. We're doing
* this because either it can't run here any more (set_cpus_allowed()
* away from this CPU, or CPU going down), or because we're
* attempting to rebalance this task on exec (sched_exec).
*
* So we race with normal scheduler movements, but that's OK, as long
* as the task is no longer on this CPU.
*/
static struct rq *__migrate_task(struct rq *rq, struct task_struct *p, int dest_cpu)
{
if (unlikely(!cpu_active(dest_cpu)))
return rq;
/* Affinity changed (again). */
if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
return rq;
rq = move_queued_task(rq, p, dest_cpu);
return rq;
}
/*
* migration_cpu_stop - this will be executed by a highprio stopper thread
* and performs thread migration by bumping thread off CPU then
* 'pushing' onto another runqueue.
*/
static int migration_cpu_stop(void *data)
{
struct migration_arg *arg = data;
struct task_struct *p = arg->task;
struct rq *rq = this_rq();
/*
* The original target cpu might have gone down and we might
* be on another cpu but it doesn't matter.
*/
local_irq_disable();
/*
* We need to explicitly wake pending tasks before running
* __migrate_task() such that we will not miss enforcing cpus_allowed
* during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
*/
sched_ttwu_pending();
raw_spin_lock(&p->pi_lock);
raw_spin_lock(&rq->lock);
/*
* If task_rq(p) != rq, it cannot be migrated here, because we're
* holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
* we're holding p->pi_lock.
*/
if (task_rq(p) == rq && task_on_rq_queued(p))
rq = __migrate_task(rq, p, arg->dest_cpu);
raw_spin_unlock(&rq->lock);
raw_spin_unlock(&p->pi_lock);
local_irq_enable();
return 0;
}
/*
* sched_class::set_cpus_allowed must do the below, but is not required to
* actually call this function.
*/
void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
{
cpumask_copy(&p->cpus_allowed, new_mask);
p->nr_cpus_allowed = cpumask_weight(new_mask);
}
void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
{
struct rq *rq = task_rq(p);
bool queued, running;
lockdep_assert_held(&p->pi_lock);
queued = task_on_rq_queued(p);
running = task_current(rq, p);
if (queued) {
/*
* Because __kthread_bind() calls this on blocked tasks without
* holding rq->lock.
*/
lockdep_assert_held(&rq->lock);
dequeue_task(rq, p, DEQUEUE_SAVE);
}
if (running)
put_prev_task(rq, p);
p->sched_class->set_cpus_allowed(p, new_mask);
if (running)
p->sched_class->set_curr_task(rq);
if (queued)
enqueue_task(rq, p, ENQUEUE_RESTORE);
}
/*
* Change a given task's CPU affinity. Migrate the thread to a
* proper CPU and schedule it away if the CPU it's executing on
* is removed from the allowed bitmask.
*
* NOTE: the caller must have a valid reference to the task, the
* task must not exit() & deallocate itself prematurely. The
* call is not atomic; no spinlocks may be held.
*/
static int __set_cpus_allowed_ptr(struct task_struct *p,
const struct cpumask *new_mask, bool check)
{
const struct cpumask *cpu_valid_mask = cpu_active_mask;
unsigned int dest_cpu;
struct rq_flags rf;
struct rq *rq;
int ret = 0;
rq = task_rq_lock(p, &rf);
if (p->flags & PF_KTHREAD) {
/*
* Kernel threads are allowed on online && !active CPUs
*/
cpu_valid_mask = cpu_online_mask;
}
/*
* Must re-check here, to close a race against __kthread_bind(),
* sched_setaffinity() is not guaranteed to observe the flag.
*/
if (check && (p->flags & PF_NO_SETAFFINITY)) {
ret = -EINVAL;
goto out;
}
if (cpumask_equal(&p->cpus_allowed, new_mask))
goto out;
if (!cpumask_intersects(new_mask, cpu_valid_mask)) {
ret = -EINVAL;
goto out;
}
do_set_cpus_allowed(p, new_mask);
if (p->flags & PF_KTHREAD) {
/*
* For kernel threads that do indeed end up on online &&
* !active we want to ensure they are strict per-cpu threads.
*/
WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
!cpumask_intersects(new_mask, cpu_active_mask) &&
p->nr_cpus_allowed != 1);
}
/* Can the task run on the task's current CPU? If so, we're done */
if (cpumask_test_cpu(task_cpu(p), new_mask))
goto out;
dest_cpu = cpumask_any_and(cpu_valid_mask, new_mask);
if (task_running(rq, p) || p->state == TASK_WAKING) {
struct migration_arg arg = { p, dest_cpu };
/* Need help from migration thread: drop lock and wait. */
task_rq_unlock(rq, p, &rf);
stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
tlb_migrate_finish(p->mm);
return 0;
} else if (task_on_rq_queued(p)) {
/*
* OK, since we're going to drop the lock immediately
* afterwards anyway.
*/
lockdep_unpin_lock(&rq->lock, rf.cookie);
rq = move_queued_task(rq, p, dest_cpu);
lockdep_repin_lock(&rq->lock, rf.cookie);
}
out:
task_rq_unlock(rq, p, &rf);
return ret;
}
int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
{
return __set_cpus_allowed_ptr(p, new_mask, false);
}
EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
{
#ifdef CONFIG_SCHED_DEBUG
/*
* We should never call set_task_cpu() on a blocked task,
* ttwu() will sort out the placement.
*/
WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
!p->on_rq);
/*
* Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
* because schedstat_wait_{start,end} rebase migrating task's wait_start
* time relying on p->on_rq.
*/
WARN_ON_ONCE(p->state == TASK_RUNNING &&
p->sched_class == &fair_sched_class &&
(p->on_rq && !task_on_rq_migrating(p)));
#ifdef CONFIG_LOCKDEP
/*
* The caller should hold either p->pi_lock or rq->lock, when changing
* a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
*
* sched_move_task() holds both and thus holding either pins the cgroup,
* see task_group().
*
* Furthermore, all task_rq users should acquire both locks, see
* task_rq_lock().
*/
WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
lockdep_is_held(&task_rq(p)->lock)));
#endif
#endif
trace_sched_migrate_task(p, new_cpu);
if (task_cpu(p) != new_cpu) {
if (p->sched_class->migrate_task_rq)
p->sched_class->migrate_task_rq(p);
p->se.nr_migrations++;
perf_event_task_migrate(p);
}
__set_task_cpu(p, new_cpu);
}
static void __migrate_swap_task(struct task_struct *p, int cpu)
{
if (task_on_rq_queued(p)) {
struct rq *src_rq, *dst_rq;
src_rq = task_rq(p);
dst_rq = cpu_rq(cpu);
p->on_rq = TASK_ON_RQ_MIGRATING;
deactivate_task(src_rq, p, 0);
set_task_cpu(p, cpu);
activate_task(dst_rq, p, 0);
p->on_rq = TASK_ON_RQ_QUEUED;
check_preempt_curr(dst_rq, p, 0);
} else {
/*
* Task isn't running anymore; make it appear like we migrated
* it before it went to sleep. This means on wakeup we make the
* previous cpu our targer instead of where it really is.
*/
p->wake_cpu = cpu;
}
}
struct migration_swap_arg {
struct task_struct *src_task, *dst_task;
int src_cpu, dst_cpu;
};
static int migrate_swap_stop(void *data)
{
struct migration_swap_arg *arg = data;
struct rq *src_rq, *dst_rq;
int ret = -EAGAIN;
if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
return -EAGAIN;
src_rq = cpu_rq(arg->src_cpu);
dst_rq = cpu_rq(arg->dst_cpu);
double_raw_lock(&arg->src_task->pi_lock,
&arg->dst_task->pi_lock);
double_rq_lock(src_rq, dst_rq);
if (task_cpu(arg->dst_task) != arg->dst_cpu)
goto unlock;
if (task_cpu(arg->src_task) != arg->src_cpu)
goto unlock;
if (!cpumask_test_cpu(arg->dst_cpu, tsk_cpus_allowed(arg->src_task)))
goto unlock;
if (!cpumask_test_cpu(arg->src_cpu, tsk_cpus_allowed(arg->dst_task)))
goto unlock;
__migrate_swap_task(arg->src_task, arg->dst_cpu);
__migrate_swap_task(arg->dst_task, arg->src_cpu);
ret = 0;
unlock:
double_rq_unlock(src_rq, dst_rq);
raw_spin_unlock(&arg->dst_task->pi_lock);
raw_spin_unlock(&arg->src_task->pi_lock);
return ret;
}
/*
* Cross migrate two tasks
*/
int migrate_swap(struct task_struct *cur, struct task_struct *p)
{
struct migration_swap_arg arg;
int ret = -EINVAL;
arg = (struct migration_swap_arg){
.src_task = cur,
.src_cpu = task_cpu(cur),
.dst_task = p,
.dst_cpu = task_cpu(p),
};
if (arg.src_cpu == arg.dst_cpu)
goto out;
/*
* These three tests are all lockless; this is OK since all of them
* will be re-checked with proper locks held further down the line.
*/
if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
goto out;
if (!cpumask_test_cpu(arg.dst_cpu, tsk_cpus_allowed(arg.src_task)))
goto out;
if (!cpumask_test_cpu(arg.src_cpu, tsk_cpus_allowed(arg.dst_task)))
goto out;
trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
out:
return ret;
}
/*
* wait_task_inactive - wait for a thread to unschedule.
*
* If @match_state is nonzero, it's the @p->state value just checked and
* not expected to change. If it changes, i.e. @p might have woken up,
* then return zero. When we succeed in waiting for @p to be off its CPU,
* we return a positive number (its total switch count). If a second call
* a short while later returns the same number, the caller can be sure that
* @p has remained unscheduled the whole time.
*
* The caller must ensure that the task *will* unschedule sometime soon,
* else this function might spin for a *long* time. This function can't
* be called with interrupts off, or it may introduce deadlock with
* smp_call_function() if an IPI is sent by the same process we are
* waiting to become inactive.
*/
unsigned long wait_task_inactive(struct task_struct *p, long match_state)
{
int running, queued;
struct rq_flags rf;
unsigned long ncsw;
struct rq *rq;
for (;;) {
/*
* We do the initial early heuristics without holding
* any task-queue locks at all. We'll only try to get
* the runqueue lock when things look like they will
* work out!
*/
rq = task_rq(p);
/*
* If the task is actively running on another CPU
* still, just relax and busy-wait without holding
* any locks.
*
* NOTE! Since we don't hold any locks, it's not
* even sure that "rq" stays as the right runqueue!
* But we don't care, since "task_running()" will
* return false if the runqueue has changed and p
* is actually now running somewhere else!
*/
while (task_running(rq, p)) {
if (match_state && unlikely(p->state != match_state))
return 0;
cpu_relax();
}
/*
* Ok, time to look more closely! We need the rq
* lock now, to be *sure*. If we're wrong, we'll
* just go back and repeat.
*/
rq = task_rq_lock(p, &rf);
trace_sched_wait_task(p);
running = task_running(rq, p);
queued = task_on_rq_queued(p);
ncsw = 0;
if (!match_state || p->state == match_state)
ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
task_rq_unlock(rq, p, &rf);
/*
* If it changed from the expected state, bail out now.
*/
if (unlikely(!ncsw))
break;
/*
* Was it really running after all now that we
* checked with the proper locks actually held?
*
* Oops. Go back and try again..
*/
if (unlikely(running)) {
cpu_relax();
continue;
}
/*
* It's not enough that it's not actively running,
* it must be off the runqueue _entirely_, and not
* preempted!
*
* So if it was still runnable (but just not actively
* running right now), it's preempted, and we should
* yield - it could be a while.
*/
if (unlikely(queued)) {
ktime_t to = ktime_set(0, NSEC_PER_SEC/HZ);
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_hrtimeout(&to, HRTIMER_MODE_REL);
continue;
}
/*
* Ahh, all good. It wasn't running, and it wasn't
* runnable, which means that it will never become
* running in the future either. We're all done!
*/
break;
}
return ncsw;
}
/***
* kick_process - kick a running thread to enter/exit the kernel
* @p: the to-be-kicked thread
*
* Cause a process which is running on another CPU to enter
* kernel-mode, without any delay. (to get signals handled.)
*
* NOTE: this function doesn't have to take the runqueue lock,
* because all it wants to ensure is that the remote task enters
* the kernel. If the IPI races and the task has been migrated
* to another CPU then no harm is done and the purpose has been
* achieved as well.
*/
void kick_process(struct task_struct *p)
{
int cpu;
preempt_disable();
cpu = task_cpu(p);
if ((cpu != smp_processor_id()) && task_curr(p))
smp_send_reschedule(cpu);
preempt_enable();
}
EXPORT_SYMBOL_GPL(kick_process);
/*
* ->cpus_allowed is protected by both rq->lock and p->pi_lock
*
* A few notes on cpu_active vs cpu_online:
*
* - cpu_active must be a subset of cpu_online
*
* - on cpu-up we allow per-cpu kthreads on the online && !active cpu,
* see __set_cpus_allowed_ptr(). At this point the newly online
* cpu isn't yet part of the sched domains, and balancing will not
* see it.
*
* - on cpu-down we clear cpu_active() to mask the sched domains and
* avoid the load balancer to place new tasks on the to be removed
* cpu. Existing tasks will remain running there and will be taken
* off.
*
* This means that fallback selection must not select !active CPUs.
* And can assume that any active CPU must be online. Conversely
* select_task_rq() below may allow selection of !active CPUs in order
* to satisfy the above rules.
*/
static int select_fallback_rq(int cpu, struct task_struct *p)
{
int nid = cpu_to_node(cpu);
const struct cpumask *nodemask = NULL;
enum { cpuset, possible, fail } state = cpuset;
int dest_cpu;
/*
* If the node that the cpu is on has been offlined, cpu_to_node()
* will return -1. There is no cpu on the node, and we should
* select the cpu on the other node.
*/
if (nid != -1) {
nodemask = cpumask_of_node(nid);
/* Look for allowed, online CPU in same node. */
for_each_cpu(dest_cpu, nodemask) {
if (!cpu_active(dest_cpu))
continue;
if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
return dest_cpu;
}
}
for (;;) {
/* Any allowed, online CPU? */
for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) {
if (!cpu_active(dest_cpu))
continue;
goto out;
}
/* No more Mr. Nice Guy. */
switch (state) {
case cpuset:
if (IS_ENABLED(CONFIG_CPUSETS)) {
cpuset_cpus_allowed_fallback(p);
state = possible;
break;
}
/* fall-through */
case possible:
do_set_cpus_allowed(p, cpu_possible_mask);
state = fail;
break;
case fail:
BUG();
break;
}
}
out:
if (state != cpuset) {
/*
* Don't tell them about moving exiting tasks or
* kernel threads (both mm NULL), since they never
* leave kernel.
*/
if (p->mm && printk_ratelimit()) {
printk_deferred("process %d (%s) no longer affine to cpu%d\n",
task_pid_nr(p), p->comm, cpu);
}
}
return dest_cpu;
}
/*
* The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
*/
static inline
int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
{
lockdep_assert_held(&p->pi_lock);
if (tsk_nr_cpus_allowed(p) > 1)
cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
else
cpu = cpumask_any(tsk_cpus_allowed(p));
/*
* In order not to call set_task_cpu() on a blocking task we need
* to rely on ttwu() to place the task on a valid ->cpus_allowed
* cpu.
*
* Since this is common to all placement strategies, this lives here.
*
* [ this allows ->select_task() to simply return task_cpu(p) and
* not worry about this generic constraint ]
*/
if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) ||
!cpu_online(cpu)))
cpu = select_fallback_rq(task_cpu(p), p);
return cpu;
}
static void update_avg(u64 *avg, u64 sample)
{
s64 diff = sample - *avg;
*avg += diff >> 3;
}
#else
static inline int __set_cpus_allowed_ptr(struct task_struct *p,
const struct cpumask *new_mask, bool check)
{
return set_cpus_allowed_ptr(p, new_mask);
}
#endif /* CONFIG_SMP */
static void
ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
{
#ifdef CONFIG_SCHEDSTATS
struct rq *rq = this_rq();
#ifdef CONFIG_SMP
int this_cpu = smp_processor_id();
if (cpu == this_cpu) {
schedstat_inc(rq, ttwu_local);
schedstat_inc(p, se.statistics.nr_wakeups_local);
} else {
struct sched_domain *sd;
schedstat_inc(p, se.statistics.nr_wakeups_remote);
rcu_read_lock();
for_each_domain(this_cpu, sd) {
if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
schedstat_inc(sd, ttwu_wake_remote);
break;
}
}
rcu_read_unlock();
}
if (wake_flags & WF_MIGRATED)
schedstat_inc(p, se.statistics.nr_wakeups_migrate);
#endif /* CONFIG_SMP */
schedstat_inc(rq, ttwu_count);
schedstat_inc(p, se.statistics.nr_wakeups);
if (wake_flags & WF_SYNC)
schedstat_inc(p, se.statistics.nr_wakeups_sync);
#endif /* CONFIG_SCHEDSTATS */
}
static inline void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
{
activate_task(rq, p, en_flags);
p->on_rq = TASK_ON_RQ_QUEUED;
/* if a worker is waking up, notify workqueue */
if (p->flags & PF_WQ_WORKER)
wq_worker_waking_up(p, cpu_of(rq));
}
/*
* Mark the task runnable and perform wakeup-preemption.
*/
static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
struct pin_cookie cookie)
{
check_preempt_curr(rq, p, wake_flags);
p->state = TASK_RUNNING;
trace_sched_wakeup(p);
#ifdef CONFIG_SMP
if (p->sched_class->task_woken) {
/*
* Our task @p is fully woken up and running; so its safe to
* drop the rq->lock, hereafter rq is only used for statistics.
*/
lockdep_unpin_lock(&rq->lock, cookie);
p->sched_class->task_woken(rq, p);
lockdep_repin_lock(&rq->lock, cookie);
}
if (rq->idle_stamp) {
u64 delta = rq_clock(rq) - rq->idle_stamp;
u64 max = 2*rq->max_idle_balance_cost;
update_avg(&rq->avg_idle, delta);
if (rq->avg_idle > max)
rq->avg_idle = max;
rq->idle_stamp = 0;
}
#endif
}
static void
ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
struct pin_cookie cookie)
{
int en_flags = ENQUEUE_WAKEUP;
lockdep_assert_held(&rq->lock);
#ifdef CONFIG_SMP
if (p->sched_contributes_to_load)
rq->nr_uninterruptible--;
if (wake_flags & WF_MIGRATED)
en_flags |= ENQUEUE_MIGRATED;
#endif
ttwu_activate(rq, p, en_flags);
ttwu_do_wakeup(rq, p, wake_flags, cookie);
}
/*
* Called in case the task @p isn't fully descheduled from its runqueue,
* in this case we must do a remote wakeup. Its a 'light' wakeup though,
* since all we need to do is flip p->state to TASK_RUNNING, since
* the task is still ->on_rq.
*/
static int ttwu_remote(struct task_struct *p, int wake_flags)
{
struct rq_flags rf;
struct rq *rq;
int ret = 0;
rq = __task_rq_lock(p, &rf);
if (task_on_rq_queued(p)) {
/* check_preempt_curr() may use rq clock */
update_rq_clock(rq);
ttwu_do_wakeup(rq, p, wake_flags, rf.cookie);
ret = 1;
}
__task_rq_unlock(rq, &rf);
return ret;
}
#ifdef CONFIG_SMP
void sched_ttwu_pending(void)
{
struct rq *rq = this_rq();
struct llist_node *llist = llist_del_all(&rq->wake_list);
struct pin_cookie cookie;
struct task_struct *p;
unsigned long flags;
if (!llist)
return;
raw_spin_lock_irqsave(&rq->lock, flags);
cookie = lockdep_pin_lock(&rq->lock);
while (llist) {
int wake_flags = 0;
p = llist_entry(llist, struct task_struct, wake_entry);
llist = llist_next(llist);
if (p->sched_remote_wakeup)
wake_flags = WF_MIGRATED;
ttwu_do_activate(rq, p, wake_flags, cookie);
}
lockdep_unpin_lock(&rq->lock, cookie);
raw_spin_unlock_irqrestore(&rq->lock, flags);
}
void scheduler_ipi(void)
{
/*
* Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
* TIF_NEED_RESCHED remotely (for the first time) will also send
* this IPI.
*/
preempt_fold_need_resched();
if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
return;
/*
* Not all reschedule IPI handlers call irq_enter/irq_exit, since
* traditionally all their work was done from the interrupt return
* path. Now that we actually do some work, we need to make sure
* we do call them.
*
* Some archs already do call them, luckily irq_enter/exit nest
* properly.
*
* Arguably we should visit all archs and update all handlers,
* however a fair share of IPIs are still resched only so this would
* somewhat pessimize the simple resched case.
*/
irq_enter();
sched_ttwu_pending();
/*
* Check if someone kicked us for doing the nohz idle load balance.
*/
if (unlikely(got_nohz_idle_kick())) {
this_rq()->idle_balance = 1;
raise_softirq_irqoff(SCHED_SOFTIRQ);
}
irq_exit();
}
static void ttwu_queue_remote(struct task_struct *p, int cpu, int wake_flags)
{
struct rq *rq = cpu_rq(cpu);
p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
if (!set_nr_if_polling(rq->idle))
smp_send_reschedule(cpu);
else
trace_sched_wake_idle_without_ipi(cpu);
}
}
void wake_up_if_idle(int cpu)
{
struct rq *rq = cpu_rq(cpu);
unsigned long flags;
rcu_read_lock();
if (!is_idle_task(rcu_dereference(rq->curr)))
goto out;
if (set_nr_if_polling(rq->idle)) {
trace_sched_wake_idle_without_ipi(cpu);
} else {
raw_spin_lock_irqsave(&rq->lock, flags);
if (is_idle_task(rq->curr))
smp_send_reschedule(cpu);
/* Else cpu is not in idle, do nothing here */
raw_spin_unlock_irqrestore(&rq->lock, flags);
}
out:
rcu_read_unlock();
}
bool cpus_share_cache(int this_cpu, int that_cpu)
{
return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
}
#endif /* CONFIG_SMP */
static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
{
struct rq *rq = cpu_rq(cpu);
struct pin_cookie cookie;
#if defined(CONFIG_SMP)
if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
sched_clock_cpu(cpu); /* sync clocks x-cpu */
ttwu_queue_remote(p, cpu, wake_flags);
return;
}
#endif
raw_spin_lock(&rq->lock);
cookie = lockdep_pin_lock(&rq->lock);
ttwu_do_activate(rq, p, wake_flags, cookie);
lockdep_unpin_lock(&rq->lock, cookie);
raw_spin_unlock(&rq->lock);
}
/*
* Notes on Program-Order guarantees on SMP systems.
*
* MIGRATION
*
* The basic program-order guarantee on SMP systems is that when a task [t]
* migrates, all its activity on its old cpu [c0] happens-before any subsequent
* execution on its new cpu [c1].
*
* For migration (of runnable tasks) this is provided by the following means:
*
* A) UNLOCK of the rq(c0)->lock scheduling out task t
* B) migration for t is required to synchronize *both* rq(c0)->lock and
* rq(c1)->lock (if not at the same time, then in that order).
* C) LOCK of the rq(c1)->lock scheduling in task
*
* Transitivity guarantees that B happens after A and C after B.
* Note: we only require RCpc transitivity.
* Note: the cpu doing B need not be c0 or c1
*
* Example:
*
* CPU0 CPU1 CPU2
*
* LOCK rq(0)->lock
* sched-out X
* sched-in Y
* UNLOCK rq(0)->lock
*
* LOCK rq(0)->lock // orders against CPU0
* dequeue X
* UNLOCK rq(0)->lock
*
* LOCK rq(1)->lock
* enqueue X
* UNLOCK rq(1)->lock
*
* LOCK rq(1)->lock // orders against CPU2
* sched-out Z
* sched-in X
* UNLOCK rq(1)->lock
*
*
* BLOCKING -- aka. SLEEP + WAKEUP
*
* For blocking we (obviously) need to provide the same guarantee as for
* migration. However the means are completely different as there is no lock
* chain to provide order. Instead we do:
*
* 1) smp_store_release(X->on_cpu, 0)
* 2) smp_cond_acquire(!X->on_cpu)
*
* Example:
*
* CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
*
* LOCK rq(0)->lock LOCK X->pi_lock
* dequeue X
* sched-out X
* smp_store_release(X->on_cpu, 0);
*
* smp_cond_acquire(!X->on_cpu);
* X->state = WAKING
* set_task_cpu(X,2)
*
* LOCK rq(2)->lock
* enqueue X
* X->state = RUNNING
* UNLOCK rq(2)->lock
*
* LOCK rq(2)->lock // orders against CPU1
* sched-out Z
* sched-in X
* UNLOCK rq(2)->lock
*
* UNLOCK X->pi_lock
* UNLOCK rq(0)->lock
*
*
* However; for wakeups there is a second guarantee we must provide, namely we
* must observe the state that lead to our wakeup. That is, not only must our
* task observe its own prior state, it must also observe the stores prior to
* its wakeup.
*
* This means that any means of doing remote wakeups must order the CPU doing
* the wakeup against the CPU the task is going to end up running on. This,
* however, is already required for the regular Program-Order guarantee above,
* since the waking CPU is the one issueing the ACQUIRE (smp_cond_acquire).
*
*/
/**
* try_to_wake_up - wake up a thread
* @p: the thread to be awakened
* @state: the mask of task states that can be woken
* @wake_flags: wake modifier flags (WF_*)
*
* Put it on the run-queue if it's not already there. The "current"
* thread is always on the run-queue (except when the actual
* re-schedule is in progress), and as such you're allowed to do
* the simpler "current->state = TASK_RUNNING" to mark yourself
* runnable without the overhead of this.
*
* Return: %true if @p was woken up, %false if it was already running.
* or @state didn't match @p's state.
*/
static int
try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
{
unsigned long flags;
int cpu, success = 0;
/*
* If we are going to wake up a thread waiting for CONDITION we
* need to ensure that CONDITION=1 done by the caller can not be
* reordered with p->state check below. This pairs with mb() in
* set_current_state() the waiting thread does.
*/
smp_mb__before_spinlock();
raw_spin_lock_irqsave(&p->pi_lock, flags);
if (!(p->state & state))
goto out;
trace_sched_waking(p);
success = 1; /* we're going to change ->state */
cpu = task_cpu(p);
if (p->on_rq && ttwu_remote(p, wake_flags))
goto stat;
#ifdef CONFIG_SMP
/*
* Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
* possible to, falsely, observe p->on_cpu == 0.
*
* One must be running (->on_cpu == 1) in order to remove oneself
* from the runqueue.
*
* [S] ->on_cpu = 1; [L] ->on_rq
* UNLOCK rq->lock
* RMB
* LOCK rq->lock
* [S] ->on_rq = 0; [L] ->on_cpu
*
* Pairs with the full barrier implied in the UNLOCK+LOCK on rq->lock
* from the consecutive calls to schedule(); the first switching to our
* task, the second putting it to sleep.
*/
smp_rmb();
/*
* If the owning (remote) cpu is still in the middle of schedule() with
* this task as prev, wait until its done referencing the task.
*
* Pairs with the smp_store_release() in finish_lock_switch().
*
* This ensures that tasks getting woken will be fully ordered against
* their previous state and preserve Program Order.
*/
smp_cond_acquire(!p->on_cpu);
p->sched_contributes_to_load = !!task_contributes_to_load(p);
p->state = TASK_WAKING;
cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
if (task_cpu(p) != cpu) {
wake_flags |= WF_MIGRATED;
set_task_cpu(p, cpu);
}
#endif /* CONFIG_SMP */
ttwu_queue(p, cpu, wake_flags);
stat:
if (schedstat_enabled())
ttwu_stat(p, cpu, wake_flags);
out:
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
return success;
}
/**
* try_to_wake_up_local - try to wake up a local task with rq lock held
* @p: the thread to be awakened
*
* Put @p on the run-queue if it's not already there. The caller must
* ensure that this_rq() is locked, @p is bound to this_rq() and not
* the current task.
*/
static void try_to_wake_up_local(struct task_struct *p, struct pin_cookie cookie)
{
struct rq *rq = task_rq(p);
if (WARN_ON_ONCE(rq != this_rq()) ||
WARN_ON_ONCE(p == current))
return;
lockdep_assert_held(&rq->lock);
if (!raw_spin_trylock(&p->pi_lock)) {
/*
* This is OK, because current is on_cpu, which avoids it being
* picked for load-balance and preemption/IRQs are still
* disabled avoiding further scheduler activity on it and we've
* not yet picked a replacement task.
*/
lockdep_unpin_lock(&rq->lock, cookie);
raw_spin_unlock(&rq->lock);
raw_spin_lock(&p->pi_lock);
raw_spin_lock(&rq->lock);
lockdep_repin_lock(&rq->lock, cookie);
}
if (!(p->state & TASK_NORMAL))
goto out;
trace_sched_waking(p);
if (!task_on_rq_queued(p))
ttwu_activate(rq, p, ENQUEUE_WAKEUP);
ttwu_do_wakeup(rq, p, 0, cookie);
if (schedstat_enabled())
ttwu_stat(p, smp_processor_id(), 0);
out:
raw_spin_unlock(&p->pi_lock);
}
/**
* wake_up_process - Wake up a specific process
* @p: The process to be woken up.
*
* Attempt to wake up the nominated process and move it to the set of runnable
* processes.
*
* Return: 1 if the process was woken up, 0 if it was already running.
*
* It may be assumed that this function implies a write memory barrier before
* changing the task state if and only if any tasks are woken up.
*/
int wake_up_process(struct task_struct *p)
{
return try_to_wake_up(p, TASK_NORMAL, 0);
}
EXPORT_SYMBOL(wake_up_process);
int wake_up_state(struct task_struct *p, unsigned int state)
{
return try_to_wake_up(p, state, 0);
}
/*
* This function clears the sched_dl_entity static params.
*/
void __dl_clear_params(struct task_struct *p)
{
struct sched_dl_entity *dl_se = &p->dl;
dl_se->dl_runtime = 0;
dl_se->dl_deadline = 0;
dl_se->dl_period = 0;
dl_se->flags = 0;
dl_se->dl_bw = 0;
dl_se->dl_throttled = 0;
dl_se->dl_yielded = 0;
}
/*
* Perform scheduler related setup for a newly forked process p.
* p is forked by current.
*
* __sched_fork() is basic setup used by init_idle() too:
*/
static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
{
p->on_rq = 0;
p->se.on_rq = 0;
p->se.exec_start = 0;
p->se.sum_exec_runtime = 0;
p->se.prev_sum_exec_runtime = 0;
p->se.nr_migrations = 0;
p->se.vruntime = 0;
INIT_LIST_HEAD(&p->se.group_node);
#ifdef CONFIG_FAIR_GROUP_SCHED
p->se.cfs_rq = NULL;
#endif
#ifdef CONFIG_SCHEDSTATS
/* Even if schedstat is disabled, there should not be garbage */
memset(&p->se.statistics, 0, sizeof(p->se.statistics));
#endif
RB_CLEAR_NODE(&p->dl.rb_node);
init_dl_task_timer(&p->dl);
__dl_clear_params(p);
INIT_LIST_HEAD(&p->rt.run_list);
p->rt.timeout = 0;
p->rt.time_slice = sched_rr_timeslice;
p->rt.on_rq = 0;
p->rt.on_list = 0;
#ifdef CONFIG_PREEMPT_NOTIFIERS
INIT_HLIST_HEAD(&p->preempt_notifiers);
#endif
#ifdef CONFIG_NUMA_BALANCING
if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
p->mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
p->mm->numa_scan_seq = 0;
}
if (clone_flags & CLONE_VM)
p->numa_preferred_nid = current->numa_preferred_nid;
else
p->numa_preferred_nid = -1;
p->node_stamp = 0ULL;
p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
p->numa_scan_period = sysctl_numa_balancing_scan_delay;
p->numa_work.next = &p->numa_work;
p->numa_faults = NULL;
p->last_task_numa_placement = 0;
p->last_sum_exec_runtime = 0;
p->numa_group = NULL;
#endif /* CONFIG_NUMA_BALANCING */
}
DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
#ifdef CONFIG_NUMA_BALANCING
void set_numabalancing_state(bool enabled)
{
if (enabled)
static_branch_enable(&sched_numa_balancing);
else
static_branch_disable(&sched_numa_balancing);
}
#ifdef CONFIG_PROC_SYSCTL
int sysctl_numa_balancing(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
struct ctl_table t;
int err;
int state = static_branch_likely(&sched_numa_balancing);
if (write && !capable(CAP_SYS_ADMIN))
return -EPERM;
t = *table;
t.data = &state;
err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
if (err < 0)
return err;
if (write)
set_numabalancing_state(state);
return err;
}
#endif
#endif
#ifdef CONFIG_SCHEDSTATS
DEFINE_STATIC_KEY_FALSE(sched_schedstats);
static bool __initdata __sched_schedstats = false;
static void set_schedstats(bool enabled)
{
if (enabled)
static_branch_enable(&sched_schedstats);
else
static_branch_disable(&sched_schedstats);
}
void force_schedstat_enabled(void)
{
if (!schedstat_enabled()) {
pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
static_branch_enable(&sched_schedstats);
}
}
static int __init setup_schedstats(char *str)
{
int ret = 0;
if (!str)
goto out;
/*
* This code is called before jump labels have been set up, so we can't
* change the static branch directly just yet. Instead set a temporary
* variable so init_schedstats() can do it later.
*/
if (!strcmp(str, "enable")) {
__sched_schedstats = true;
ret = 1;
} else if (!strcmp(str, "disable")) {
__sched_schedstats = false;
ret = 1;
}
out:
if (!ret)
pr_warn("Unable to parse schedstats=\n");
return ret;
}
__setup("schedstats=", setup_schedstats);
static void __init init_schedstats(void)
{
set_schedstats(__sched_schedstats);
}
#ifdef CONFIG_PROC_SYSCTL
int sysctl_schedstats(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
struct ctl_table t;
int err;
int state = static_branch_likely(&sched_schedstats);
if (write && !capable(CAP_SYS_ADMIN))
return -EPERM;
t = *table;
t.data = &state;
err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
if (err < 0)
return err;
if (write)
set_schedstats(state);
return err;
}
#endif /* CONFIG_PROC_SYSCTL */
#else /* !CONFIG_SCHEDSTATS */
static inline void init_schedstats(void) {}
#endif /* CONFIG_SCHEDSTATS */
/*
* fork()/clone()-time setup:
*/
int sched_fork(unsigned long clone_flags, struct task_struct *p)
{
unsigned long flags;
int cpu = get_cpu();
__sched_fork(clone_flags, p);
/*
* We mark the process as running here. This guarantees that
* nobody will actually run it, and a signal or other external
* event cannot wake it up and insert it on the runqueue either.
*/
p->state = TASK_RUNNING;
/*
* Make sure we do not leak PI boosting priority to the child.
*/
p->prio = current->normal_prio;
/*
* Revert to default priority/policy on fork if requested.
*/
if (unlikely(p->sched_reset_on_fork)) {
if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
p->policy = SCHED_NORMAL;
p->static_prio = NICE_TO_PRIO(0);
p->rt_priority = 0;
} else if (PRIO_TO_NICE(p->static_prio) < 0)
p->static_prio = NICE_TO_PRIO(0);
p->prio = p->normal_prio = __normal_prio(p);
set_load_weight(p);
/*
* We don't need the reset flag anymore after the fork. It has
* fulfilled its duty:
*/
p->sched_reset_on_fork = 0;
}
if (dl_prio(p->prio)) {
put_cpu();
return -EAGAIN;
} else if (rt_prio(p->prio)) {
p->sched_class = &rt_sched_class;
} else {
p->sched_class = &fair_sched_class;
}
if (p->sched_class->task_fork)
p->sched_class->task_fork(p);
/*
* The child is not yet in the pid-hash so no cgroup attach races,
* and the cgroup is pinned to this child due to cgroup_fork()
* is ran before sched_fork().
*
* Silence PROVE_RCU.
*/
raw_spin_lock_irqsave(&p->pi_lock, flags);
set_task_cpu(p, cpu);
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
#ifdef CONFIG_SCHED_INFO
if (likely(sched_info_on()))
memset(&p->sched_info, 0, sizeof(p->sched_info));
#endif
#if defined(CONFIG_SMP)
p->on_cpu = 0;
#endif
init_task_preempt_count(p);
#ifdef CONFIG_SMP
plist_node_init(&p->pushable_tasks, MAX_PRIO);
RB_CLEAR_NODE(&p->pushable_dl_tasks);
#endif
put_cpu();
return 0;
}
unsigned long to_ratio(u64 period, u64 runtime)
{
if (runtime == RUNTIME_INF)
return 1ULL << 20;
/*
* Doing this here saves a lot of checks in all
* the calling paths, and returning zero seems
* safe for them anyway.
*/
if (period == 0)
return 0;
return div64_u64(runtime << 20, period);
}
#ifdef CONFIG_SMP
inline struct dl_bw *dl_bw_of(int i)
{
RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
"sched RCU must be held");
return &cpu_rq(i)->rd->dl_bw;
}
static inline int dl_bw_cpus(int i)
{
struct root_domain *rd = cpu_rq(i)->rd;
int cpus = 0;
RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
"sched RCU must be held");
for_each_cpu_and(i, rd->span, cpu_active_mask)
cpus++;
return cpus;
}
#else
inline struct dl_bw *dl_bw_of(int i)
{
return &cpu_rq(i)->dl.dl_bw;
}
static inline int dl_bw_cpus(int i)
{
return 1;
}
#endif
/*
* We must be sure that accepting a new task (or allowing changing the
* parameters of an existing one) is consistent with the bandwidth
* constraints. If yes, this function also accordingly updates the currently
* allocated bandwidth to reflect the new situation.
*
* This function is called while holding p's rq->lock.
*
* XXX we should delay bw change until the task's 0-lag point, see
* __setparam_dl().
*/
static int dl_overflow(struct task_struct *p, int policy,
const struct sched_attr *attr)
{
struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
u64 period = attr->sched_period ?: attr->sched_deadline;
u64 runtime = attr->sched_runtime;
u64 new_bw = dl_policy(policy) ? to_ratio(period, runtime) : 0;
int cpus, err = -1;
/* !deadline task may carry old deadline bandwidth */
if (new_bw == p->dl.dl_bw && task_has_dl_policy(p))
return 0;
/*
* Either if a task, enters, leave, or stays -deadline but changes
* its parameters, we may need to update accordingly the total
* allocated bandwidth of the container.
*/
raw_spin_lock(&dl_b->lock);
cpus = dl_bw_cpus(task_cpu(p));
if (dl_policy(policy) && !task_has_dl_policy(p) &&
!__dl_overflow(dl_b, cpus, 0, new_bw)) {
__dl_add(dl_b, new_bw);
err = 0;
} else if (dl_policy(policy) && task_has_dl_policy(p) &&
!__dl_overflow(dl_b, cpus, p->dl.dl_bw, new_bw)) {
__dl_clear(dl_b, p->dl.dl_bw);
__dl_add(dl_b, new_bw);
err = 0;
} else if (!dl_policy(policy) && task_has_dl_policy(p)) {
__dl_clear(dl_b, p->dl.dl_bw);
err = 0;
}
raw_spin_unlock(&dl_b->lock);
return err;
}
extern void init_dl_bw(struct dl_bw *dl_b);
/*
* wake_up_new_task - wake up a newly created task for the first time.
*
* This function will do some initial scheduler statistics housekeeping
* that must be done for every newly created context, then puts the task
* on the runqueue and wakes it.
*/
void wake_up_new_task(struct task_struct *p)
{
struct rq_flags rf;
struct rq *rq;
/* Initialize new task's runnable average */
init_entity_runnable_average(&p->se);
raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
#ifdef CONFIG_SMP
/*
* Fork balancing, do it here and not earlier because:
* - cpus_allowed can change in the fork path
* - any previously selected cpu might disappear through hotplug
*/
set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
#endif
/* Post initialize new task's util average when its cfs_rq is set */
post_init_entity_util_avg(&p->se);
rq = __task_rq_lock(p, &rf);
activate_task(rq, p, 0);
p->on_rq = TASK_ON_RQ_QUEUED;
trace_sched_wakeup_new(p);
check_preempt_curr(rq, p, WF_FORK);
#ifdef CONFIG_SMP
if (p->sched_class->task_woken) {
/*
* Nothing relies on rq->lock after this, so its fine to
* drop it.
*/
lockdep_unpin_lock(&rq->lock, rf.cookie);
p->sched_class->task_woken(rq, p);
lockdep_repin_lock(&rq->lock, rf.cookie);
}
#endif
task_rq_unlock(rq, p, &rf);
}
#ifdef CONFIG_PREEMPT_NOTIFIERS
static struct static_key preempt_notifier_key = STATIC_KEY_INIT_FALSE;
void preempt_notifier_inc(void)
{
static_key_slow_inc(&preempt_notifier_key);
}
EXPORT_SYMBOL_GPL(preempt_notifier_inc);
void preempt_notifier_dec(void)
{
static_key_slow_dec(&preempt_notifier_key);
}
EXPORT_SYMBOL_GPL(preempt_notifier_dec);
/**
* preempt_notifier_register - tell me when current is being preempted & rescheduled
* @notifier: notifier struct to register
*/
void preempt_notifier_register(struct preempt_notifier *notifier)
{
if (!static_key_false(&preempt_notifier_key))
WARN(1, "registering preempt_notifier while notifiers disabled\n");
hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
}
EXPORT_SYMBOL_GPL(preempt_notifier_register);
/**
* preempt_notifier_unregister - no longer interested in preemption notifications
* @notifier: notifier struct to unregister
*
* This is *not* safe to call from within a preemption notifier.
*/
void preempt_notifier_unregister(struct preempt_notifier *notifier)
{
hlist_del(¬ifier->link);
}
EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
{
struct preempt_notifier *notifier;
hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
notifier->ops->sched_in(notifier, raw_smp_processor_id());
}
static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
{
if (static_key_false(&preempt_notifier_key))
__fire_sched_in_preempt_notifiers(curr);
}
static void
__fire_sched_out_preempt_notifiers(struct task_struct *curr,
struct task_struct *next)
{
struct preempt_notifier *notifier;
hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
notifier->ops->sched_out(notifier, next);
}
static __always_inline void
fire_sched_out_preempt_notifiers(struct task_struct *curr,
struct task_struct *next)
{
if (static_key_false(&preempt_notifier_key))
__fire_sched_out_preempt_notifiers(curr, next);
}
#else /* !CONFIG_PREEMPT_NOTIFIERS */
static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
{
}
static inline void
fire_sched_out_preempt_notifiers(struct task_struct *curr,
struct task_struct *next)
{
}
#endif /* CONFIG_PREEMPT_NOTIFIERS */
/**
* prepare_task_switch - prepare to switch tasks
* @rq: the runqueue preparing to switch
* @prev: the current task that is being switched out
* @next: the task we are going to switch to.
*
* This is called with the rq lock held and interrupts off. It must
* be paired with a subsequent finish_task_switch after the context
* switch.
*
* prepare_task_switch sets up locking and calls architecture specific
* hooks.
*/
static inline void
prepare_task_switch(struct rq *rq, struct task_struct *prev,
struct task_struct *next)
{
sched_info_switch(rq, prev, next);
perf_event_task_sched_out(prev, next);
fire_sched_out_preempt_notifiers(prev, next);
prepare_lock_switch(rq, next);
prepare_arch_switch(next);
}
/**
* finish_task_switch - clean up after a task-switch
* @prev: the thread we just switched away from.
*
* finish_task_switch must be called after the context switch, paired
* with a prepare_task_switch call before the context switch.
* finish_task_switch will reconcile locking set up by prepare_task_switch,
* and do any other architecture-specific cleanup actions.
*
* Note that we may have delayed dropping an mm in context_switch(). If
* so, we finish that here outside of the runqueue lock. (Doing it
* with the lock held can cause deadlocks; see schedule() for
* details.)
*
* The context switch have flipped the stack from under us and restored the
* local variables which were saved when this task called schedule() in the
* past. prev == current is still correct but we need to recalculate this_rq
* because prev may have moved to another CPU.
*/
static struct rq *finish_task_switch(struct task_struct *prev)
__releases(rq->lock)
{
struct rq *rq = this_rq();
struct mm_struct *mm = rq->prev_mm;
long prev_state;
/*
* The previous task will have left us with a preempt_count of 2
* because it left us after:
*
* schedule()
* preempt_disable(); // 1
* __schedule()
* raw_spin_lock_irq(&rq->lock) // 2
*
* Also, see FORK_PREEMPT_COUNT.
*/
if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
"corrupted preempt_count: %s/%d/0x%x\n",
current->comm, current->pid, preempt_count()))
preempt_count_set(FORK_PREEMPT_COUNT);
rq->prev_mm = NULL;
/*
* A task struct has one reference for the use as "current".
* If a task dies, then it sets TASK_DEAD in tsk->state and calls
* schedule one last time. The schedule call will never return, and
* the scheduled task must drop that reference.
*
* We must observe prev->state before clearing prev->on_cpu (in
* finish_lock_switch), otherwise a concurrent wakeup can get prev
* running on another CPU and we could rave with its RUNNING -> DEAD
* transition, resulting in a double drop.
*/
prev_state = prev->state;
vtime_task_switch(prev);
perf_event_task_sched_in(prev, current);
finish_lock_switch(rq, prev);
finish_arch_post_lock_switch();
fire_sched_in_preempt_notifiers(current);
if (mm)
mmdrop(mm);
if (unlikely(prev_state == TASK_DEAD)) {
if (prev->sched_class->task_dead)
prev->sched_class->task_dead(prev);
/*
* Remove function-return probe instances associated with this
* task and put them back on the free list.
*/
kprobe_flush_task(prev);
put_task_struct(prev);
}
tick_nohz_task_switch();
return rq;
}
#ifdef CONFIG_SMP
/* rq->lock is NOT held, but preemption is disabled */
static void __balance_callback(struct rq *rq)
{
struct callback_head *head, *next;
void (*func)(struct rq *rq);
unsigned long flags;
raw_spin_lock_irqsave(&rq->lock, flags);
head = rq->balance_callback;
rq->balance_callback = NULL;
while (head) {
func = (void (*)(struct rq *))head->func;
next = head->next;
head->next = NULL;
head = next;
func(rq);
}
raw_spin_unlock_irqrestore(&rq->lock, flags);
}
static inline void balance_callback(struct rq *rq)
{
if (unlikely(rq->balance_callback))
__balance_callback(rq);
}
#else
static inline void balance_callback(struct rq *rq)
{
}
#endif
/**
* schedule_tail - first thing a freshly forked thread must call.
* @prev: the thread we just switched away from.
*/
asmlinkage __visible void schedule_tail(struct task_struct *prev)
__releases(rq->lock)
{
struct rq *rq;
/*
* New tasks start with FORK_PREEMPT_COUNT, see there and
* finish_task_switch() for details.
*
* finish_task_switch() will drop rq->lock() and lower preempt_count
* and the preempt_enable() will end up enabling preemption (on
* PREEMPT_COUNT kernels).
*/
rq = finish_task_switch(prev);
balance_callback(rq);
preempt_enable();
if (current->set_child_tid)
put_user(task_pid_vnr(current), current->set_child_tid);
}
/*
* context_switch - switch to the new MM and the new thread's register state.
*/
static __always_inline struct rq *
context_switch(struct rq *rq, struct task_struct *prev,
struct task_struct *next, struct pin_cookie cookie)
{
struct mm_struct *mm, *oldmm;
prepare_task_switch(rq, prev, next);
mm = next->mm;
oldmm = prev->active_mm;
/*
* For paravirt, this is coupled with an exit in switch_to to
* combine the page table reload and the switch backend into
* one hypercall.
*/
arch_start_context_switch(prev);
if (!mm) {
next->active_mm = oldmm;
atomic_inc(&oldmm->mm_count);
enter_lazy_tlb(oldmm, next);
} else
switch_mm_irqs_off(oldmm, mm, next);
if (!prev->mm) {
prev->active_mm = NULL;
rq->prev_mm = oldmm;
}
/*
* Since the runqueue lock will be released by the next
* task (which is an invalid locking op but in the case
* of the scheduler it's an obvious special-case), so we
* do an early lockdep release here:
*/
lockdep_unpin_lock(&rq->lock, cookie);
spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
/* Here we just switch the register state and the stack. */
switch_to(prev, next, prev);
barrier();
return finish_task_switch(prev);
}
/*
* nr_running and nr_context_switches:
*
* externally visible scheduler statistics: current number of runnable
* threads, total number of context switches performed since bootup.
*/
unsigned long nr_running(void)
{
unsigned long i, sum = 0;
for_each_online_cpu(i)
sum += cpu_rq(i)->nr_running;
return sum;
}
/*
* Check if only the current task is running on the cpu.
*
* Caution: this function does not check that the caller has disabled
* preemption, thus the result might have a time-of-check-to-time-of-use
* race. The caller is responsible to use it correctly, for example:
*
* - from a non-preemptable section (of course)
*
* - from a thread that is bound to a single CPU
*
* - in a loop with very short iterations (e.g. a polling loop)
*/
bool single_task_running(void)
{
return raw_rq()->nr_running == 1;
}
EXPORT_SYMBOL(single_task_running);
unsigned long long nr_context_switches(void)
{
int i;
unsigned long long sum = 0;
for_each_possible_cpu(i)
sum += cpu_rq(i)->nr_switches;
return sum;
}
unsigned long nr_iowait(void)
{
unsigned long i, sum = 0;
for_each_possible_cpu(i)
sum += atomic_read(&cpu_rq(i)->nr_iowait);
return sum;
}
unsigned long nr_iowait_cpu(int cpu)
{
struct rq *this = cpu_rq(cpu);
return atomic_read(&this->nr_iowait);
}
void get_iowait_load(unsigned long *nr_waiters, unsigned long *load)
{
struct rq *rq = this_rq();
*nr_waiters = atomic_read(&rq->nr_iowait);
*load = rq->load.weight;
}
#ifdef CONFIG_SMP
/*
* sched_exec - execve() is a valuable balancing opportunity, because at
* this point the task has the smallest effective memory and cache footprint.
*/
void sched_exec(void)
{
struct task_struct *p = current;
unsigned long flags;
int dest_cpu;
raw_spin_lock_irqsave(&p->pi_lock, flags);
dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
if (dest_cpu == smp_processor_id())
goto unlock;
if (likely(cpu_active(dest_cpu))) {
struct migration_arg arg = { p, dest_cpu };
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
return;
}
unlock:
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
}
#endif
DEFINE_PER_CPU(struct kernel_stat, kstat);
DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
EXPORT_PER_CPU_SYMBOL(kstat);
EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
/*
* Return accounted runtime for the task.
* In case the task is currently running, return the runtime plus current's
* pending runtime that have not been accounted yet.
*/
unsigned long long task_sched_runtime(struct task_struct *p)
{
struct rq_flags rf;
struct rq *rq;
u64 ns;
#if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
/*
* 64-bit doesn't need locks to atomically read a 64bit value.
* So we have a optimization chance when the task's delta_exec is 0.
* Reading ->on_cpu is racy, but this is ok.
*
* If we race with it leaving cpu, we'll take a lock. So we're correct.
* If we race with it entering cpu, unaccounted time is 0. This is
* indistinguishable from the read occurring a few cycles earlier.
* If we see ->on_cpu without ->on_rq, the task is leaving, and has
* been accounted, so we're correct here as well.
*/
if (!p->on_cpu || !task_on_rq_queued(p))
return p->se.sum_exec_runtime;
#endif
rq = task_rq_lock(p, &rf);
/*
* Must be ->curr _and_ ->on_rq. If dequeued, we would
* project cycles that may never be accounted to this
* thread, breaking clock_gettime().
*/
if (task_current(rq, p) && task_on_rq_queued(p)) {
update_rq_clock(rq);
p->sched_class->update_curr(rq);
}
ns = p->se.sum_exec_runtime;
task_rq_unlock(rq, p, &rf);
return ns;
}
/*
* This function gets called by the timer code, with HZ frequency.
* We call it with interrupts disabled.
*/
void scheduler_tick(void)
{
int cpu = smp_processor_id();
struct rq *rq = cpu_rq(cpu);
struct task_struct *curr = rq->curr;
sched_clock_tick();
raw_spin_lock(&rq->lock);
update_rq_clock(rq);
curr->sched_class->task_tick(rq, curr, 0);
cpu_load_update_active(rq);
calc_global_load_tick(rq);
raw_spin_unlock(&rq->lock);
perf_event_task_tick();
#ifdef CONFIG_SMP
rq->idle_balance = idle_cpu(cpu);
trigger_load_balance(rq);
#endif
rq_last_tick_reset(rq);
}
#ifdef CONFIG_NO_HZ_FULL
/**
* scheduler_tick_max_deferment
*
* Keep at least one tick per second when a single
* active task is running because the scheduler doesn't
* yet completely support full dynticks environment.
*
* This makes sure that uptime, CFS vruntime, load
* balancing, etc... continue to move forward, even
* with a very low granularity.
*
* Return: Maximum deferment in nanoseconds.
*/
u64 scheduler_tick_max_deferment(void)
{
struct rq *rq = this_rq();
unsigned long next, now = READ_ONCE(jiffies);
next = rq->last_sched_tick + HZ;
if (time_before_eq(next, now))
return 0;
return jiffies_to_nsecs(next - now);
}
#endif
#if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
defined(CONFIG_PREEMPT_TRACER))
/*
* If the value passed in is equal to the current preempt count
* then we just disabled preemption. Start timing the latency.
*/
static inline void preempt_latency_start(int val)
{
if (preempt_count() == val) {
unsigned long ip = get_lock_parent_ip();
#ifdef CONFIG_DEBUG_PREEMPT
current->preempt_disable_ip = ip;
#endif
trace_preempt_off(CALLER_ADDR0, ip);
}
}
void preempt_count_add(int val)
{
#ifdef CONFIG_DEBUG_PREEMPT
/*
* Underflow?
*/
if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
return;
#endif
__preempt_count_add(val);
#ifdef CONFIG_DEBUG_PREEMPT
/*
* Spinlock count overflowing soon?
*/
DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
PREEMPT_MASK - 10);
#endif
preempt_latency_start(val);
}
EXPORT_SYMBOL(preempt_count_add);
NOKPROBE_SYMBOL(preempt_count_add);
/*
* If the value passed in equals to the current preempt count
* then we just enabled preemption. Stop timing the latency.
*/
static inline void preempt_latency_stop(int val)
{
if (preempt_count() == val)
trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
}
void preempt_count_sub(int val)
{
#ifdef CONFIG_DEBUG_PREEMPT
/*
* Underflow?
*/
if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
return;
/*
* Is the spinlock portion underflowing?
*/
if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
!(preempt_count() & PREEMPT_MASK)))
return;
#endif
preempt_latency_stop(val);
__preempt_count_sub(val);
}
EXPORT_SYMBOL(preempt_count_sub);
NOKPROBE_SYMBOL(preempt_count_sub);
#else
static inline void preempt_latency_start(int val) { }
static inline void preempt_latency_stop(int val) { }
#endif
/*
* Print scheduling while atomic bug:
*/
static noinline void __schedule_bug(struct task_struct *prev)
{
if (oops_in_progress)
return;
printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
prev->comm, prev->pid, preempt_count());
debug_show_held_locks(prev);
print_modules();
if (irqs_disabled())
print_irqtrace_events(prev);
#ifdef CONFIG_DEBUG_PREEMPT
if (in_atomic_preempt_off()) {
pr_err("Preemption disabled at:");
print_ip_sym(current->preempt_disable_ip);
pr_cont("\n");
}
#endif
dump_stack();
add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
}
/*
* Various schedule()-time debugging checks and statistics:
*/
static inline void schedule_debug(struct task_struct *prev)
{
#ifdef CONFIG_SCHED_STACK_END_CHECK
BUG_ON(task_stack_end_corrupted(prev));
#endif
if (unlikely(in_atomic_preempt_off())) {
__schedule_bug(prev);
preempt_count_set(PREEMPT_DISABLED);
}
rcu_sleep_check();
profile_hit(SCHED_PROFILING, __builtin_return_address(0));
schedstat_inc(this_rq(), sched_count);
}
/*
* Pick up the highest-prio task:
*/
static inline struct task_struct *
pick_next_task(struct rq *rq, struct task_struct *prev, struct pin_cookie cookie)
{
const struct sched_class *class = &fair_sched_class;
struct task_struct *p;
/*
* Optimization: we know that if all tasks are in
* the fair class we can call that function directly:
*/
if (likely(prev->sched_class == class &&
rq->nr_running == rq->cfs.h_nr_running)) {
p = fair_sched_class.pick_next_task(rq, prev, cookie);
if (unlikely(p == RETRY_TASK))
goto again;
/* assumes fair_sched_class->next == idle_sched_class */
if (unlikely(!p))
p = idle_sched_class.pick_next_task(rq, prev, cookie);
return p;
}
again:
for_each_class(class) {
p = class->pick_next_task(rq, prev, cookie);
if (p) {
if (unlikely(p == RETRY_TASK))
goto again;
return p;
}
}
BUG(); /* the idle class will always have a runnable task */
}
/*
* __schedule() is the main scheduler function.
*
* The main means of driving the scheduler and thus entering this function are:
*
* 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
*
* 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
* paths. For example, see arch/x86/entry_64.S.
*
* To drive preemption between tasks, the scheduler sets the flag in timer
* interrupt handler scheduler_tick().
*
* 3. Wakeups don't really cause entry into schedule(). They add a
* task to the run-queue and that's it.
*
* Now, if the new task added to the run-queue preempts the current
* task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
* called on the nearest possible occasion:
*
* - If the kernel is preemptible (CONFIG_PREEMPT=y):
*
* - in syscall or exception context, at the next outmost
* preempt_enable(). (this might be as soon as the wake_up()'s
* spin_unlock()!)
*
* - in IRQ context, return from interrupt-handler to
* preemptible context
*
* - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
* then at the next:
*
* - cond_resched() call
* - explicit schedule() call
* - return from syscall or exception to user-space
* - return from interrupt-handler to user-space
*
* WARNING: must be called with preemption disabled!
*/
static void __sched notrace __schedule(bool preempt)
{
struct task_struct *prev, *next;
unsigned long *switch_count;
struct pin_cookie cookie;
struct rq *rq;
int cpu;
cpu = smp_processor_id();
rq = cpu_rq(cpu);
prev = rq->curr;
/*
* do_exit() calls schedule() with preemption disabled as an exception;
* however we must fix that up, otherwise the next task will see an
* inconsistent (higher) preempt count.
*
* It also avoids the below schedule_debug() test from complaining
* about this.
*/
if (unlikely(prev->state == TASK_DEAD))
preempt_enable_no_resched_notrace();
schedule_debug(prev);
if (sched_feat(HRTICK))
hrtick_clear(rq);
local_irq_disable();
rcu_note_context_switch();
/*
* Make sure that signal_pending_state()->signal_pending() below
* can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
* done by the caller to avoid the race with signal_wake_up().
*/
smp_mb__before_spinlock();
raw_spin_lock(&rq->lock);
cookie = lockdep_pin_lock(&rq->lock);
rq->clock_skip_update <<= 1; /* promote REQ to ACT */
switch_count = &prev->nivcsw;
if (!preempt && prev->state) {
if (unlikely(signal_pending_state(prev->state, prev))) {
prev->state = TASK_RUNNING;
} else {
deactivate_task(rq, prev, DEQUEUE_SLEEP);
prev->on_rq = 0;
/*
* If a worker went to sleep, notify and ask workqueue
* whether it wants to wake up a task to maintain
* concurrency.
*/
if (prev->flags & PF_WQ_WORKER) {
struct task_struct *to_wakeup;
to_wakeup = wq_worker_sleeping(prev);
if (to_wakeup)
try_to_wake_up_local(to_wakeup, cookie);
}
}
switch_count = &prev->nvcsw;
}
if (task_on_rq_queued(prev))
update_rq_clock(rq);
next = pick_next_task(rq, prev, cookie);
clear_tsk_need_resched(prev);
clear_preempt_need_resched();
rq->clock_skip_update = 0;
if (likely(prev != next)) {
rq->nr_switches++;
rq->curr = next;
++*switch_count;
trace_sched_switch(preempt, prev, next);
rq = context_switch(rq, prev, next, cookie); /* unlocks the rq */
} else {
lockdep_unpin_lock(&rq->lock, cookie);
raw_spin_unlock_irq(&rq->lock);
}
balance_callback(rq);
}
STACK_FRAME_NON_STANDARD(__schedule); /* switch_to() */
static inline void sched_submit_work(struct task_struct *tsk)
{
if (!tsk->state || tsk_is_pi_blocked(tsk))
return;
/*
* If we are going to sleep and we have plugged IO queued,
* make sure to submit it to avoid deadlocks.
*/
if (blk_needs_flush_plug(tsk))
blk_schedule_flush_plug(tsk);
}
asmlinkage __visible void __sched schedule(void)
{
struct task_struct *tsk = current;
sched_submit_work(tsk);
do {
preempt_disable();
__schedule(false);
sched_preempt_enable_no_resched();
} while (need_resched());
}
EXPORT_SYMBOL(schedule);
#ifdef CONFIG_CONTEXT_TRACKING
asmlinkage __visible void __sched schedule_user(void)
{
/*
* If we come here after a random call to set_need_resched(),
* or we have been woken up remotely but the IPI has not yet arrived,
* we haven't yet exited the RCU idle mode. Do it here manually until
* we find a better solution.
*
* NB: There are buggy callers of this function. Ideally we
* should warn if prev_state != CONTEXT_USER, but that will trigger
* too frequently to make sense yet.
*/
enum ctx_state prev_state = exception_enter();
schedule();
exception_exit(prev_state);
}
#endif
/**
* schedule_preempt_disabled - called with preemption disabled
*
* Returns with preemption disabled. Note: preempt_count must be 1
*/
void __sched schedule_preempt_disabled(void)
{
sched_preempt_enable_no_resched();
schedule();
preempt_disable();
}
static void __sched notrace preempt_schedule_common(void)
{
do {
/*
* Because the function tracer can trace preempt_count_sub()
* and it also uses preempt_enable/disable_notrace(), if
* NEED_RESCHED is set, the preempt_enable_notrace() called
* by the function tracer will call this function again and
* cause infinite recursion.
*
* Preemption must be disabled here before the function
* tracer can trace. Break up preempt_disable() into two
* calls. One to disable preemption without fear of being
* traced. The other to still record the preemption latency,
* which can also be traced by the function tracer.
*/
preempt_disable_notrace();
preempt_latency_start(1);
__schedule(true);
preempt_latency_stop(1);
preempt_enable_no_resched_notrace();
/*
* Check again in case we missed a preemption opportunity
* between schedule and now.
*/
} while (need_resched());
}
#ifdef CONFIG_PREEMPT
/*
* this is the entry point to schedule() from in-kernel preemption
* off of preempt_enable. Kernel preemptions off return from interrupt
* occur there and call schedule directly.
*/
asmlinkage __visible void __sched notrace preempt_schedule(void)
{
/*
* If there is a non-zero preempt_count or interrupts are disabled,
* we do not want to preempt the current task. Just return..
*/
if (likely(!preemptible()))
return;
preempt_schedule_common();
}
NOKPROBE_SYMBOL(preempt_schedule);
EXPORT_SYMBOL(preempt_schedule);
/**
* preempt_schedule_notrace - preempt_schedule called by tracing
*
* The tracing infrastructure uses preempt_enable_notrace to prevent
* recursion and tracing preempt enabling caused by the tracing
* infrastructure itself. But as tracing can happen in areas coming
* from userspace or just about to enter userspace, a preempt enable
* can occur before user_exit() is called. This will cause the scheduler
* to be called when the system is still in usermode.
*
* To prevent this, the preempt_enable_notrace will use this function
* instead of preempt_schedule() to exit user context if needed before
* calling the scheduler.
*/
asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
{
enum ctx_state prev_ctx;
if (likely(!preemptible()))
return;
do {
/*
* Because the function tracer can trace preempt_count_sub()
* and it also uses preempt_enable/disable_notrace(), if
* NEED_RESCHED is set, the preempt_enable_notrace() called
* by the function tracer will call this function again and
* cause infinite recursion.
*
* Preemption must be disabled here before the function
* tracer can trace. Break up preempt_disable() into two
* calls. One to disable preemption without fear of being
* traced. The other to still record the preemption latency,
* which can also be traced by the function tracer.
*/
preempt_disable_notrace();
preempt_latency_start(1);
/*
* Needs preempt disabled in case user_exit() is traced
* and the tracer calls preempt_enable_notrace() causing
* an infinite recursion.
*/
prev_ctx = exception_enter();
__schedule(true);
exception_exit(prev_ctx);
preempt_latency_stop(1);
preempt_enable_no_resched_notrace();
} while (need_resched());
}
EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
#endif /* CONFIG_PREEMPT */
/*
* this is the entry point to schedule() from kernel preemption
* off of irq context.
* Note, that this is called and return with irqs disabled. This will
* protect us against recursive calling from irq.
*/
asmlinkage __visible void __sched preempt_schedule_irq(void)
{
enum ctx_state prev_state;
/* Catch callers which need to be fixed */
BUG_ON(preempt_count() || !irqs_disabled());
prev_state = exception_enter();
do {
preempt_disable();
local_irq_enable();
__schedule(true);
local_irq_disable();
sched_preempt_enable_no_resched();
} while (need_resched());
exception_exit(prev_state);
}
int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
void *key)
{
return try_to_wake_up(curr->private, mode, wake_flags);
}
EXPORT_SYMBOL(default_wake_function);
#ifdef CONFIG_RT_MUTEXES
/*
* rt_mutex_setprio - set the current priority of a task
* @p: task
* @prio: prio value (kernel-internal form)
*
* This function changes the 'effective' priority of a task. It does
* not touch ->normal_prio like __setscheduler().
*
* Used by the rt_mutex code to implement priority inheritance
* logic. Call site only calls if the priority of the task changed.
*/
void rt_mutex_setprio(struct task_struct *p, int prio)
{
int oldprio, queued, running, queue_flag = DEQUEUE_SAVE | DEQUEUE_MOVE;
const struct sched_class *prev_class;
struct rq_flags rf;
struct rq *rq;
BUG_ON(prio > MAX_PRIO);
rq = __task_rq_lock(p, &rf);
/*
* Idle task boosting is a nono in general. There is one
* exception, when PREEMPT_RT and NOHZ is active:
*
* The idle task calls get_next_timer_interrupt() and holds
* the timer wheel base->lock on the CPU and another CPU wants
* to access the timer (probably to cancel it). We can safely
* ignore the boosting request, as the idle CPU runs this code
* with interrupts disabled and will complete the lock
* protected section without being interrupted. So there is no
* real need to boost.
*/
if (unlikely(p == rq->idle)) {
WARN_ON(p != rq->curr);
WARN_ON(p->pi_blocked_on);
goto out_unlock;
}
trace_sched_pi_setprio(p, prio);
oldprio = p->prio;
if (oldprio == prio)
queue_flag &= ~DEQUEUE_MOVE;
prev_class = p->sched_class;
queued = task_on_rq_queued(p);
running = task_current(rq, p);
if (queued)
dequeue_task(rq, p, queue_flag);
if (running)
put_prev_task(rq, p);
/*
* Boosting condition are:
* 1. -rt task is running and holds mutex A
* --> -dl task blocks on mutex A
*
* 2. -dl task is running and holds mutex A
* --> -dl task blocks on mutex A and could preempt the
* running task
*/
if (dl_prio(prio)) {
struct task_struct *pi_task = rt_mutex_get_top_task(p);
if (!dl_prio(p->normal_prio) ||
(pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
p->dl.dl_boosted = 1;
queue_flag |= ENQUEUE_REPLENISH;
} else
p->dl.dl_boosted = 0;
p->sched_class = &dl_sched_class;
} else if (rt_prio(prio)) {
if (dl_prio(oldprio))
p->dl.dl_boosted = 0;
if (oldprio < prio)
queue_flag |= ENQUEUE_HEAD;
p->sched_class = &rt_sched_class;
} else {
if (dl_prio(oldprio))
p->dl.dl_boosted = 0;
if (rt_prio(oldprio))
p->rt.timeout = 0;
p->sched_class = &fair_sched_class;
}
p->prio = prio;
if (running)
p->sched_class->set_curr_task(rq);
if (queued)
enqueue_task(rq, p, queue_flag);
check_class_changed(rq, p, prev_class, oldprio);
out_unlock:
preempt_disable(); /* avoid rq from going away on us */
__task_rq_unlock(rq, &rf);
balance_callback(rq);
preempt_enable();
}
#endif
void set_user_nice(struct task_struct *p, long nice)
{
int old_prio, delta, queued;
struct rq_flags rf;
struct rq *rq;
if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
return;
/*
* We have to be careful, if called from sys_setpriority(),
* the task might be in the middle of scheduling on another CPU.
*/
rq = task_rq_lock(p, &rf);
/*
* The RT priorities are set via sched_setscheduler(), but we still
* allow the 'normal' nice value to be set - but as expected
* it wont have any effect on scheduling until the task is
* SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
*/
if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
p->static_prio = NICE_TO_PRIO(nice);
goto out_unlock;
}
queued = task_on_rq_queued(p);
if (queued)
dequeue_task(rq, p, DEQUEUE_SAVE);
p->static_prio = NICE_TO_PRIO(nice);
set_load_weight(p);
old_prio = p->prio;
p->prio = effective_prio(p);
delta = p->prio - old_prio;
if (queued) {
enqueue_task(rq, p, ENQUEUE_RESTORE);
/*
* If the task increased its priority or is running and
* lowered its priority, then reschedule its CPU:
*/
if (delta < 0 || (delta > 0 && task_running(rq, p)))
resched_curr(rq);
}
out_unlock:
task_rq_unlock(rq, p, &rf);
}
EXPORT_SYMBOL(set_user_nice);
/*
* can_nice - check if a task can reduce its nice value
* @p: task
* @nice: nice value
*/
int can_nice(const struct task_struct *p, const int nice)
{
/* convert nice value [19,-20] to rlimit style value [1,40] */
int nice_rlim = nice_to_rlimit(nice);
return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
capable(CAP_SYS_NICE));
}
#ifdef __ARCH_WANT_SYS_NICE
/*
* sys_nice - change the priority of the current process.
* @increment: priority increment
*
* sys_setpriority is a more generic, but much slower function that
* does similar things.
*/
SYSCALL_DEFINE1(nice, int, increment)
{
long nice, retval;
/*
* Setpriority might change our priority at the same moment.
* We don't have to worry. Conceptually one call occurs first
* and we have a single winner.
*/
increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
nice = task_nice(current) + increment;
nice = clamp_val(nice, MIN_NICE, MAX_NICE);
if (increment < 0 && !can_nice(current, nice))
return -EPERM;
retval = security_task_setnice(current, nice);
if (retval)
return retval;
set_user_nice(current, nice);
return 0;
}
#endif
/**
* task_prio - return the priority value of a given task.
* @p: the task in question.
*
* Return: The priority value as seen by users in /proc.
* RT tasks are offset by -200. Normal tasks are centered
* around 0, value goes from -16 to +15.
*/
int task_prio(const struct task_struct *p)
{
return p->prio - MAX_RT_PRIO;
}
/**
* idle_cpu - is a given cpu idle currently?
* @cpu: the processor in question.
*
* Return: 1 if the CPU is currently idle. 0 otherwise.
*/
int idle_cpu(int cpu)
{
struct rq *rq = cpu_rq(cpu);
if (rq->curr != rq->idle)
return 0;
if (rq->nr_running)
return 0;
#ifdef CONFIG_SMP
if (!llist_empty(&rq->wake_list))
return 0;
#endif
return 1;
}
/**
* idle_task - return the idle task for a given cpu.
* @cpu: the processor in question.
*
* Return: The idle task for the cpu @cpu.
*/
struct task_struct *idle_task(int cpu)
{
return cpu_rq(cpu)->idle;
}
/**
* find_process_by_pid - find a process with a matching PID value.
* @pid: the pid in question.
*
* The task of @pid, if found. %NULL otherwise.
*/
static struct task_struct *find_process_by_pid(pid_t pid)
{
return pid ? find_task_by_vpid(pid) : current;
}
/*
* This function initializes the sched_dl_entity of a newly becoming
* SCHED_DEADLINE task.
*
* Only the static values are considered here, the actual runtime and the
* absolute deadline will be properly calculated when the task is enqueued
* for the first time with its new policy.
*/
static void
__setparam_dl(struct task_struct *p, const struct sched_attr *attr)
{
struct sched_dl_entity *dl_se = &p->dl;
dl_se->dl_runtime = attr->sched_runtime;
dl_se->dl_deadline = attr->sched_deadline;
dl_se->dl_period = attr->sched_period ?: dl_se->dl_deadline;
dl_se->flags = attr->sched_flags;
dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime);
/*
* Changing the parameters of a task is 'tricky' and we're not doing
* the correct thing -- also see task_dead_dl() and switched_from_dl().
*
* What we SHOULD do is delay the bandwidth release until the 0-lag
* point. This would include retaining the task_struct until that time
* and change dl_overflow() to not immediately decrement the current
* amount.
*
* Instead we retain the current runtime/deadline and let the new
* parameters take effect after the current reservation period lapses.
* This is safe (albeit pessimistic) because the 0-lag point is always
* before the current scheduling deadline.
*
* We can still have temporary overloads because we do not delay the
* change in bandwidth until that time; so admission control is
* not on the safe side. It does however guarantee tasks will never
* consume more than promised.
*/
}
/*
* sched_setparam() passes in -1 for its policy, to let the functions
* it calls know not to change it.
*/
#define SETPARAM_POLICY -1
static void __setscheduler_params(struct task_struct *p,
const struct sched_attr *attr)
{
int policy = attr->sched_policy;
if (policy == SETPARAM_POLICY)
policy = p->policy;
p->policy = policy;
if (dl_policy(policy))
__setparam_dl(p, attr);
else if (fair_policy(policy))
p->static_prio = NICE_TO_PRIO(attr->sched_nice);
/*
* __sched_setscheduler() ensures attr->sched_priority == 0 when
* !rt_policy. Always setting this ensures that things like
* getparam()/getattr() don't report silly values for !rt tasks.
*/
p->rt_priority = attr->sched_priority;
p->normal_prio = normal_prio(p);
set_load_weight(p);
}
/* Actually do priority change: must hold pi & rq lock. */
static void __setscheduler(struct rq *rq, struct task_struct *p,
const struct sched_attr *attr, bool keep_boost)
{
__setscheduler_params(p, attr);
/*
* Keep a potential priority boosting if called from
* sched_setscheduler().
*/
if (keep_boost)
p->prio = rt_mutex_get_effective_prio(p, normal_prio(p));
else
p->prio = normal_prio(p);
if (dl_prio(p->prio))
p->sched_class = &dl_sched_class;
else if (rt_prio(p->prio))
p->sched_class = &rt_sched_class;
else
p->sched_class = &fair_sched_class;
}
static void
__getparam_dl(struct task_struct *p, struct sched_attr *attr)
{
struct sched_dl_entity *dl_se = &p->dl;
attr->sched_priority = p->rt_priority;
attr->sched_runtime = dl_se->dl_runtime;
attr->sched_deadline = dl_se->dl_deadline;
attr->sched_period = dl_se->dl_period;
attr->sched_flags = dl_se->flags;
}
/*
* This function validates the new parameters of a -deadline task.
* We ask for the deadline not being zero, and greater or equal
* than the runtime, as well as the period of being zero or
* greater than deadline. Furthermore, we have to be sure that
* user parameters are above the internal resolution of 1us (we
* check sched_runtime only since it is always the smaller one) and
* below 2^63 ns (we have to check both sched_deadline and
* sched_period, as the latter can be zero).
*/
static bool
__checkparam_dl(const struct sched_attr *attr)
{
/* deadline != 0 */
if (attr->sched_deadline == 0)
return false;
/*
* Since we truncate DL_SCALE bits, make sure we're at least
* that big.
*/
if (attr->sched_runtime < (1ULL << DL_SCALE))
return false;
/*
* Since we use the MSB for wrap-around and sign issues, make
* sure it's not set (mind that period can be equal to zero).
*/
if (attr->sched_deadline & (1ULL << 63) ||
attr->sched_period & (1ULL << 63))
return false;
/* runtime <= deadline <= period (if period != 0) */
if ((attr->sched_period != 0 &&
attr->sched_period < attr->sched_deadline) ||
attr->sched_deadline < attr->sched_runtime)
return false;
return true;
}
/*
* check the target process has a UID that matches the current process's
*/
static bool check_same_owner(struct task_struct *p)
{
const struct cred *cred = current_cred(), *pcred;
bool match;
rcu_read_lock();
pcred = __task_cred(p);
match = (uid_eq(cred->euid, pcred->euid) ||
uid_eq(cred->euid, pcred->uid));
rcu_read_unlock();
return match;
}
static bool dl_param_changed(struct task_struct *p,
const struct sched_attr *attr)
{
struct sched_dl_entity *dl_se = &p->dl;
if (dl_se->dl_runtime != attr->sched_runtime ||
dl_se->dl_deadline != attr->sched_deadline ||
dl_se->dl_period != attr->sched_period ||
dl_se->flags != attr->sched_flags)
return true;
return false;
}
static int __sched_setscheduler(struct task_struct *p,
const struct sched_attr *attr,
bool user, bool pi)
{
int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
MAX_RT_PRIO - 1 - attr->sched_priority;
int retval, oldprio, oldpolicy = -1, queued, running;
int new_effective_prio, policy = attr->sched_policy;
const struct sched_class *prev_class;
struct rq_flags rf;
int reset_on_fork;
int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE;
struct rq *rq;
/* may grab non-irq protected spin_locks */
BUG_ON(in_interrupt());
recheck:
/* double check policy once rq lock held */
if (policy < 0) {
reset_on_fork = p->sched_reset_on_fork;
policy = oldpolicy = p->policy;
} else {
reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
if (!valid_policy(policy))
return -EINVAL;
}
if (attr->sched_flags & ~(SCHED_FLAG_RESET_ON_FORK))
return -EINVAL;
/*
* Valid priorities for SCHED_FIFO and SCHED_RR are
* 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
* SCHED_BATCH and SCHED_IDLE is 0.
*/
if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
(!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
return -EINVAL;
if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
(rt_policy(policy) != (attr->sched_priority != 0)))
return -EINVAL;
/*
* Allow unprivileged RT tasks to decrease priority:
*/
if (user && !capable(CAP_SYS_NICE)) {
if (fair_policy(policy)) {
if (attr->sched_nice < task_nice(p) &&
!can_nice(p, attr->sched_nice))
return -EPERM;
}
if (rt_policy(policy)) {
unsigned long rlim_rtprio =
task_rlimit(p, RLIMIT_RTPRIO);
/* can't set/change the rt policy */
if (policy != p->policy && !rlim_rtprio)
return -EPERM;
/* can't increase priority */
if (attr->sched_priority > p->rt_priority &&
attr->sched_priority > rlim_rtprio)
return -EPERM;
}
/*
* Can't set/change SCHED_DEADLINE policy at all for now
* (safest behavior); in the future we would like to allow
* unprivileged DL tasks to increase their relative deadline
* or reduce their runtime (both ways reducing utilization)
*/
if (dl_policy(policy))
return -EPERM;
/*
* Treat SCHED_IDLE as nice 20. Only allow a switch to
* SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
*/
if (idle_policy(p->policy) && !idle_policy(policy)) {
if (!can_nice(p, task_nice(p)))
return -EPERM;
}
/* can't change other user's priorities */
if (!check_same_owner(p))
return -EPERM;
/* Normal users shall not reset the sched_reset_on_fork flag */
if (p->sched_reset_on_fork && !reset_on_fork)
return -EPERM;
}
if (user) {
retval = security_task_setscheduler(p);
if (retval)
return retval;
}
/*
* make sure no PI-waiters arrive (or leave) while we are
* changing the priority of the task:
*
* To be able to change p->policy safely, the appropriate
* runqueue lock must be held.
*/
rq = task_rq_lock(p, &rf);
/*
* Changing the policy of the stop threads its a very bad idea
*/
if (p == rq->stop) {
task_rq_unlock(rq, p, &rf);
return -EINVAL;
}
/*
* If not changing anything there's no need to proceed further,
* but store a possible modification of reset_on_fork.
*/
if (unlikely(policy == p->policy)) {
if (fair_policy(policy) && attr->sched_nice != task_nice(p))
goto change;
if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
goto change;
if (dl_policy(policy) && dl_param_changed(p, attr))
goto change;
p->sched_reset_on_fork = reset_on_fork;
task_rq_unlock(rq, p, &rf);
return 0;
}
change:
if (user) {
#ifdef CONFIG_RT_GROUP_SCHED
/*
* Do not allow realtime tasks into groups that have no runtime
* assigned.
*/
if (rt_bandwidth_enabled() && rt_policy(policy) &&
task_group(p)->rt_bandwidth.rt_runtime == 0 &&
!task_group_is_autogroup(task_group(p))) {
task_rq_unlock(rq, p, &rf);
return -EPERM;
}
#endif
#ifdef CONFIG_SMP
if (dl_bandwidth_enabled() && dl_policy(policy)) {
cpumask_t *span = rq->rd->span;
/*
* Don't allow tasks with an affinity mask smaller than
* the entire root_domain to become SCHED_DEADLINE. We
* will also fail if there's no bandwidth available.
*/
if (!cpumask_subset(span, &p->cpus_allowed) ||
rq->rd->dl_bw.bw == 0) {
task_rq_unlock(rq, p, &rf);
return -EPERM;
}
}
#endif
}
/* recheck policy now with rq lock held */
if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
policy = oldpolicy = -1;
task_rq_unlock(rq, p, &rf);
goto recheck;
}
/*
* If setscheduling to SCHED_DEADLINE (or changing the parameters
* of a SCHED_DEADLINE task) we need to check if enough bandwidth
* is available.
*/
if ((dl_policy(policy) || dl_task(p)) && dl_overflow(p, policy, attr)) {
task_rq_unlock(rq, p, &rf);
return -EBUSY;
}
p->sched_reset_on_fork = reset_on_fork;
oldprio = p->prio;
if (pi) {
/*
* Take priority boosted tasks into account. If the new
* effective priority is unchanged, we just store the new
* normal parameters and do not touch the scheduler class and
* the runqueue. This will be done when the task deboost
* itself.
*/
new_effective_prio = rt_mutex_get_effective_prio(p, newprio);
if (new_effective_prio == oldprio)
queue_flags &= ~DEQUEUE_MOVE;
}
queued = task_on_rq_queued(p);
running = task_current(rq, p);
if (queued)
dequeue_task(rq, p, queue_flags);
if (running)
put_prev_task(rq, p);
prev_class = p->sched_class;
__setscheduler(rq, p, attr, pi);
if (running)
p->sched_class->set_curr_task(rq);
if (queued) {
/*
* We enqueue to tail when the priority of a task is
* increased (user space view).
*/
if (oldprio < p->prio)
queue_flags |= ENQUEUE_HEAD;
enqueue_task(rq, p, queue_flags);
}
check_class_changed(rq, p, prev_class, oldprio);
preempt_disable(); /* avoid rq from going away on us */
task_rq_unlock(rq, p, &rf);
if (pi)
rt_mutex_adjust_pi(p);
/*
* Run balance callbacks after we've adjusted the PI chain.
*/
balance_callback(rq);
preempt_enable();
return 0;
}
static int _sched_setscheduler(struct task_struct *p, int policy,
const struct sched_param *param, bool check)
{
struct sched_attr attr = {
.sched_policy = policy,
.sched_priority = param->sched_priority,
.sched_nice = PRIO_TO_NICE(p->static_prio),
};
/* Fixup the legacy SCHED_RESET_ON_FORK hack. */
if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
policy &= ~SCHED_RESET_ON_FORK;
attr.sched_policy = policy;
}
return __sched_setscheduler(p, &attr, check, true);
}
/**
* sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
* @p: the task in question.
* @policy: new policy.
* @param: structure containing the new RT priority.
*
* Return: 0 on success. An error code otherwise.
*
* NOTE that the task may be already dead.
*/
int sched_setscheduler(struct task_struct *p, int policy,
const struct sched_param *param)
{
return _sched_setscheduler(p, policy, param, true);
}
EXPORT_SYMBOL_GPL(sched_setscheduler);
int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
{
return __sched_setscheduler(p, attr, true, true);
}
EXPORT_SYMBOL_GPL(sched_setattr);
/**
* sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
* @p: the task in question.
* @policy: new policy.
* @param: structure containing the new RT priority.
*
* Just like sched_setscheduler, only don't bother checking if the
* current context has permission. For example, this is needed in
* stop_machine(): we create temporary high priority worker threads,
* but our caller might not have that capability.
*
* Return: 0 on success. An error code otherwise.
*/
int sched_setscheduler_nocheck(struct task_struct *p, int policy,
const struct sched_param *param)
{
return _sched_setscheduler(p, policy, param, false);
}
EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
static int
do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
{
struct sched_param lparam;
struct task_struct *p;
int retval;
if (!param || pid < 0)
return -EINVAL;
if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
return -EFAULT;
rcu_read_lock();
retval = -ESRCH;
p = find_process_by_pid(pid);
if (p != NULL)
retval = sched_setscheduler(p, policy, &lparam);
rcu_read_unlock();
return retval;
}
/*
* Mimics kernel/events/core.c perf_copy_attr().
*/
static int sched_copy_attr(struct sched_attr __user *uattr,
struct sched_attr *attr)
{
u32 size;
int ret;
if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
return -EFAULT;
/*
* zero the full structure, so that a short copy will be nice.
*/
memset(attr, 0, sizeof(*attr));
ret = get_user(size, &uattr->size);
if (ret)
return ret;
if (size > PAGE_SIZE) /* silly large */
goto err_size;
if (!size) /* abi compat */
size = SCHED_ATTR_SIZE_VER0;
if (size < SCHED_ATTR_SIZE_VER0)
goto err_size;
/*
* If we're handed a bigger struct than we know of,
* ensure all the unknown bits are 0 - i.e. new
* user-space does not rely on any kernel feature
* extensions we dont know about yet.
*/
if (size > sizeof(*attr)) {
unsigned char __user *addr;
unsigned char __user *end;
unsigned char val;
addr = (void __user *)uattr + sizeof(*attr);
end = (void __user *)uattr + size;
for (; addr < end; addr++) {
ret = get_user(val, addr);
if (ret)
return ret;
if (val)
goto err_size;
}
size = sizeof(*attr);
}
ret = copy_from_user(attr, uattr, size);
if (ret)
return -EFAULT;
/*
* XXX: do we want to be lenient like existing syscalls; or do we want
* to be strict and return an error on out-of-bounds values?
*/
attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
return 0;
err_size:
put_user(sizeof(*attr), &uattr->size);
return -E2BIG;
}
/**
* sys_sched_setscheduler - set/change the scheduler policy and RT priority
* @pid: the pid in question.
* @policy: new policy.
* @param: structure containing the new RT priority.
*
* Return: 0 on success. An error code otherwise.
*/
SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
struct sched_param __user *, param)
{
/* negative values for policy are not valid */
if (policy < 0)
return -EINVAL;
return do_sched_setscheduler(pid, policy, param);
}
/**
* sys_sched_setparam - set/change the RT priority of a thread
* @pid: the pid in question.
* @param: structure containing the new RT priority.
*
* Return: 0 on success. An error code otherwise.
*/
SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
{
return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
}
/**
* sys_sched_setattr - same as above, but with extended sched_attr
* @pid: the pid in question.
* @uattr: structure containing the extended parameters.
* @flags: for future extension.
*/
SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
unsigned int, flags)
{
struct sched_attr attr;
struct task_struct *p;
int retval;
if (!uattr || pid < 0 || flags)
return -EINVAL;
retval = sched_copy_attr(uattr, &attr);
if (retval)
return retval;
if ((int)attr.sched_policy < 0)
return -EINVAL;
rcu_read_lock();
retval = -ESRCH;
p = find_process_by_pid(pid);
if (p != NULL)
retval = sched_setattr(p, &attr);
rcu_read_unlock();
return retval;
}
/**
* sys_sched_getscheduler - get the policy (scheduling class) of a thread
* @pid: the pid in question.
*
* Return: On success, the policy of the thread. Otherwise, a negative error
* code.
*/
SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
{
struct task_struct *p;
int retval;
if (pid < 0)
return -EINVAL;
retval = -ESRCH;
rcu_read_lock();
p = find_process_by_pid(pid);
if (p) {
retval = security_task_getscheduler(p);
if (!retval)
retval = p->policy
| (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
}
rcu_read_unlock();
return retval;
}
/**
* sys_sched_getparam - get the RT priority of a thread
* @pid: the pid in question.
* @param: structure containing the RT priority.
*
* Return: On success, 0 and the RT priority is in @param. Otherwise, an error
* code.
*/
SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
{
struct sched_param lp = { .sched_priority = 0 };
struct task_struct *p;
int retval;
if (!param || pid < 0)
return -EINVAL;
rcu_read_lock();
p = find_process_by_pid(pid);
retval = -ESRCH;
if (!p)
goto out_unlock;
retval = security_task_getscheduler(p);
if (retval)
goto out_unlock;
if (task_has_rt_policy(p))
lp.sched_priority = p->rt_priority;
rcu_read_unlock();
/*
* This one might sleep, we cannot do it with a spinlock held ...
*/
retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
return retval;
out_unlock:
rcu_read_unlock();
return retval;
}
static int sched_read_attr(struct sched_attr __user *uattr,
struct sched_attr *attr,
unsigned int usize)
{
int ret;
if (!access_ok(VERIFY_WRITE, uattr, usize))
return -EFAULT;
/*
* If we're handed a smaller struct than we know of,
* ensure all the unknown bits are 0 - i.e. old
* user-space does not get uncomplete information.
*/
if (usize < sizeof(*attr)) {
unsigned char *addr;
unsigned char *end;
addr = (void *)attr + usize;
end = (void *)attr + sizeof(*attr);
for (; addr < end; addr++) {
if (*addr)
return -EFBIG;
}
attr->size = usize;
}
ret = copy_to_user(uattr, attr, attr->size);
if (ret)
return -EFAULT;
return 0;
}
/**
* sys_sched_getattr - similar to sched_getparam, but with sched_attr
* @pid: the pid in question.
* @uattr: structure containing the extended parameters.
* @size: sizeof(attr) for fwd/bwd comp.
* @flags: for future extension.
*/
SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
unsigned int, size, unsigned int, flags)
{
struct sched_attr attr = {
.size = sizeof(struct sched_attr),
};
struct task_struct *p;
int retval;
if (!uattr || pid < 0 || size > PAGE_SIZE ||
size < SCHED_ATTR_SIZE_VER0 || flags)
return -EINVAL;
rcu_read_lock();
p = find_process_by_pid(pid);
retval = -ESRCH;
if (!p)
goto out_unlock;
retval = security_task_getscheduler(p);
if (retval)
goto out_unlock;
attr.sched_policy = p->policy;
if (p->sched_reset_on_fork)
attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
if (task_has_dl_policy(p))
__getparam_dl(p, &attr);
else if (task_has_rt_policy(p))
attr.sched_priority = p->rt_priority;
else
attr.sched_nice = task_nice(p);
rcu_read_unlock();
retval = sched_read_attr(uattr, &attr, size);
return retval;
out_unlock:
rcu_read_unlock();
return retval;
}
long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
{
cpumask_var_t cpus_allowed, new_mask;
struct task_struct *p;
int retval;
rcu_read_lock();
p = find_process_by_pid(pid);
if (!p) {
rcu_read_unlock();
return -ESRCH;
}
/* Prevent p going away */
get_task_struct(p);
rcu_read_unlock();
if (p->flags & PF_NO_SETAFFINITY) {
retval = -EINVAL;
goto out_put_task;
}
if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
retval = -ENOMEM;
goto out_put_task;
}
if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
retval = -ENOMEM;
goto out_free_cpus_allowed;
}
retval = -EPERM;
if (!check_same_owner(p)) {
rcu_read_lock();
if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
rcu_read_unlock();
goto out_free_new_mask;
}
rcu_read_unlock();
}
retval = security_task_setscheduler(p);
if (retval)
goto out_free_new_mask;
cpuset_cpus_allowed(p, cpus_allowed);
cpumask_and(new_mask, in_mask, cpus_allowed);
/*
* Since bandwidth control happens on root_domain basis,
* if admission test is enabled, we only admit -deadline
* tasks allowed to run on all the CPUs in the task's
* root_domain.
*/
#ifdef CONFIG_SMP
if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
rcu_read_lock();
if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
retval = -EBUSY;
rcu_read_unlock();
goto out_free_new_mask;
}
rcu_read_unlock();
}
#endif
again:
retval = __set_cpus_allowed_ptr(p, new_mask, true);
if (!retval) {
cpuset_cpus_allowed(p, cpus_allowed);
if (!cpumask_subset(new_mask, cpus_allowed)) {
/*
* We must have raced with a concurrent cpuset
* update. Just reset the cpus_allowed to the
* cpuset's cpus_allowed
*/
cpumask_copy(new_mask, cpus_allowed);
goto again;
}
}
out_free_new_mask:
free_cpumask_var(new_mask);
out_free_cpus_allowed:
free_cpumask_var(cpus_allowed);
out_put_task:
put_task_struct(p);
return retval;
}
static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
struct cpumask *new_mask)
{
if (len < cpumask_size())
cpumask_clear(new_mask);
else if (len > cpumask_size())
len = cpumask_size();
return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
}
/**
* sys_sched_setaffinity - set the cpu affinity of a process
* @pid: pid of the process
* @len: length in bytes of the bitmask pointed to by user_mask_ptr
* @user_mask_ptr: user-space pointer to the new cpu mask
*
* Return: 0 on success. An error code otherwise.
*/
SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
unsigned long __user *, user_mask_ptr)
{
cpumask_var_t new_mask;
int retval;
if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
return -ENOMEM;
retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
if (retval == 0)
retval = sched_setaffinity(pid, new_mask);
free_cpumask_var(new_mask);
return retval;
}
long sched_getaffinity(pid_t pid, struct cpumask *mask)
{
struct task_struct *p;
unsigned long flags;
int retval;
rcu_read_lock();
retval = -ESRCH;
p = find_process_by_pid(pid);
if (!p)
goto out_unlock;
retval = security_task_getscheduler(p);
if (retval)
goto out_unlock;
raw_spin_lock_irqsave(&p->pi_lock, flags);
cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
out_unlock:
rcu_read_unlock();
return retval;
}
/**
* sys_sched_getaffinity - get the cpu affinity of a process
* @pid: pid of the process
* @len: length in bytes of the bitmask pointed to by user_mask_ptr
* @user_mask_ptr: user-space pointer to hold the current cpu mask
*
* Return: 0 on success. An error code otherwise.
*/
SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
unsigned long __user *, user_mask_ptr)
{
int ret;
cpumask_var_t mask;
if ((len * BITS_PER_BYTE) < nr_cpu_ids)
return -EINVAL;
if (len & (sizeof(unsigned long)-1))
return -EINVAL;
if (!alloc_cpumask_var(&mask, GFP_KERNEL))
return -ENOMEM;
ret = sched_getaffinity(pid, mask);
if (ret == 0) {
size_t retlen = min_t(size_t, len, cpumask_size());
if (copy_to_user(user_mask_ptr, mask, retlen))
ret = -EFAULT;
else
ret = retlen;
}
free_cpumask_var(mask);
return ret;
}
/**
* sys_sched_yield - yield the current processor to other threads.
*
* This function yields the current CPU to other tasks. If there are no
* other threads running on this CPU then this function will return.
*
* Return: 0.
*/
SYSCALL_DEFINE0(sched_yield)
{
struct rq *rq = this_rq_lock();
schedstat_inc(rq, yld_count);
current->sched_class->yield_task(rq);
/*
* Since we are going to call schedule() anyway, there's
* no need to preempt or enable interrupts:
*/
__release(rq->lock);
spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
do_raw_spin_unlock(&rq->lock);
sched_preempt_enable_no_resched();
schedule();
return 0;
}
int __sched _cond_resched(void)
{
if (should_resched(0)) {
preempt_schedule_common();
return 1;
}
return 0;
}
EXPORT_SYMBOL(_cond_resched);
/*
* __cond_resched_lock() - if a reschedule is pending, drop the given lock,
* call schedule, and on return reacquire the lock.
*
* This works OK both with and without CONFIG_PREEMPT. We do strange low-level
* operations here to prevent schedule() from being called twice (once via
* spin_unlock(), once by hand).
*/
int __cond_resched_lock(spinlock_t *lock)
{
int resched = should_resched(PREEMPT_LOCK_OFFSET);
int ret = 0;
lockdep_assert_held(lock);
if (spin_needbreak(lock) || resched) {
spin_unlock(lock);
if (resched)
preempt_schedule_common();
else
cpu_relax();
ret = 1;
spin_lock(lock);
}
return ret;
}
EXPORT_SYMBOL(__cond_resched_lock);
int __sched __cond_resched_softirq(void)
{
BUG_ON(!in_softirq());
if (should_resched(SOFTIRQ_DISABLE_OFFSET)) {
local_bh_enable();
preempt_schedule_common();
local_bh_disable();
return 1;
}
return 0;
}
EXPORT_SYMBOL(__cond_resched_softirq);
/**
* yield - yield the current processor to other threads.
*
* Do not ever use this function, there's a 99% chance you're doing it wrong.
*
* The scheduler is at all times free to pick the calling task as the most
* eligible task to run, if removing the yield() call from your code breaks
* it, its already broken.
*
* Typical broken usage is:
*
* while (!event)
* yield();
*
* where one assumes that yield() will let 'the other' process run that will
* make event true. If the current task is a SCHED_FIFO task that will never
* happen. Never use yield() as a progress guarantee!!
*
* If you want to use yield() to wait for something, use wait_event().
* If you want to use yield() to be 'nice' for others, use cond_resched().
* If you still want to use yield(), do not!
*/
void __sched yield(void)
{
set_current_state(TASK_RUNNING);
sys_sched_yield();
}
EXPORT_SYMBOL(yield);
/**
* yield_to - yield the current processor to another thread in
* your thread group, or accelerate that thread toward the
* processor it's on.
* @p: target task
* @preempt: whether task preemption is allowed or not
*
* It's the caller's job to ensure that the target task struct
* can't go away on us before we can do any checks.
*
* Return:
* true (>0) if we indeed boosted the target task.
* false (0) if we failed to boost the target.
* -ESRCH if there's no task to yield to.
*/
int __sched yield_to(struct task_struct *p, bool preempt)
{
struct task_struct *curr = current;
struct rq *rq, *p_rq;
unsigned long flags;
int yielded = 0;
local_irq_save(flags);
rq = this_rq();
again:
p_rq = task_rq(p);
/*
* If we're the only runnable task on the rq and target rq also
* has only one task, there's absolutely no point in yielding.
*/
if (rq->nr_running == 1 && p_rq->nr_running == 1) {
yielded = -ESRCH;
goto out_irq;
}
double_rq_lock(rq, p_rq);
if (task_rq(p) != p_rq) {
double_rq_unlock(rq, p_rq);
goto again;
}
if (!curr->sched_class->yield_to_task)
goto out_unlock;
if (curr->sched_class != p->sched_class)
goto out_unlock;
if (task_running(p_rq, p) || p->state)
goto out_unlock;
yielded = curr->sched_class->yield_to_task(rq, p, preempt);
if (yielded) {
schedstat_inc(rq, yld_count);
/*
* Make p's CPU reschedule; pick_next_entity takes care of
* fairness.
*/
if (preempt && rq != p_rq)
resched_curr(p_rq);
}
out_unlock:
double_rq_unlock(rq, p_rq);
out_irq:
local_irq_restore(flags);
if (yielded > 0)
schedule();
return yielded;
}
EXPORT_SYMBOL_GPL(yield_to);
/*
* This task is about to go to sleep on IO. Increment rq->nr_iowait so
* that process accounting knows that this is a task in IO wait state.
*/
long __sched io_schedule_timeout(long timeout)
{
int old_iowait = current->in_iowait;
struct rq *rq;
long ret;
current->in_iowait = 1;
blk_schedule_flush_plug(current);
delayacct_blkio_start();
rq = raw_rq();
atomic_inc(&rq->nr_iowait);
ret = schedule_timeout(timeout);
current->in_iowait = old_iowait;
atomic_dec(&rq->nr_iowait);
delayacct_blkio_end();
return ret;
}
EXPORT_SYMBOL(io_schedule_timeout);
/**
* sys_sched_get_priority_max - return maximum RT priority.
* @policy: scheduling class.
*
* Return: On success, this syscall returns the maximum
* rt_priority that can be used by a given scheduling class.
* On failure, a negative error code is returned.
*/
SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
{
int ret = -EINVAL;
switch (policy) {
case SCHED_FIFO:
case SCHED_RR:
ret = MAX_USER_RT_PRIO-1;
break;
case SCHED_DEADLINE:
case SCHED_NORMAL:
case SCHED_BATCH:
case SCHED_IDLE:
ret = 0;
break;
}
return ret;
}
/**
* sys_sched_get_priority_min - return minimum RT priority.
* @policy: scheduling class.
*
* Return: On success, this syscall returns the minimum
* rt_priority that can be used by a given scheduling class.
* On failure, a negative error code is returned.
*/
SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
{
int ret = -EINVAL;
switch (policy) {
case SCHED_FIFO:
case SCHED_RR:
ret = 1;
break;
case SCHED_DEADLINE:
case SCHED_NORMAL:
case SCHED_BATCH:
case SCHED_IDLE:
ret = 0;
}
return ret;
}
/**
* sys_sched_rr_get_interval - return the default timeslice of a process.
* @pid: pid of the process.
* @interval: userspace pointer to the timeslice value.
*
* this syscall writes the default timeslice value of a given process
* into the user-space timespec buffer. A value of '0' means infinity.
*
* Return: On success, 0 and the timeslice is in @interval. Otherwise,
* an error code.
*/
SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
struct timespec __user *, interval)
{
struct task_struct *p;
unsigned int time_slice;
struct rq_flags rf;
struct timespec t;
struct rq *rq;
int retval;
if (pid < 0)
return -EINVAL;
retval = -ESRCH;
rcu_read_lock();
p = find_process_by_pid(pid);
if (!p)
goto out_unlock;
retval = security_task_getscheduler(p);
if (retval)
goto out_unlock;
rq = task_rq_lock(p, &rf);
time_slice = 0;
if (p->sched_class->get_rr_interval)
time_slice = p->sched_class->get_rr_interval(rq, p);
task_rq_unlock(rq, p, &rf);
rcu_read_unlock();
jiffies_to_timespec(time_slice, &t);
retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
return retval;
out_unlock:
rcu_read_unlock();
return retval;
}
static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
void sched_show_task(struct task_struct *p)
{
unsigned long free = 0;
int ppid;
unsigned long state = p->state;
if (state)
state = __ffs(state) + 1;
printk(KERN_INFO "%-15.15s %c", p->comm,
state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
#if BITS_PER_LONG == 32
if (state == TASK_RUNNING)
printk(KERN_CONT " running ");
else
printk(KERN_CONT " %08lx ", thread_saved_pc(p));
#else
if (state == TASK_RUNNING)
printk(KERN_CONT " running task ");
else
printk(KERN_CONT " %016lx ", thread_saved_pc(p));
#endif
#ifdef CONFIG_DEBUG_STACK_USAGE
free = stack_not_used(p);
#endif
ppid = 0;
rcu_read_lock();
if (pid_alive(p))
ppid = task_pid_nr(rcu_dereference(p->real_parent));
rcu_read_unlock();
printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
task_pid_nr(p), ppid,
(unsigned long)task_thread_info(p)->flags);
print_worker_info(KERN_INFO, p);
show_stack(p, NULL);
}
void show_state_filter(unsigned long state_filter)
{
struct task_struct *g, *p;
#if BITS_PER_LONG == 32
printk(KERN_INFO
" task PC stack pid father\n");
#else
printk(KERN_INFO
" task PC stack pid father\n");
#endif
rcu_read_lock();
for_each_process_thread(g, p) {
/*
* reset the NMI-timeout, listing all files on a slow
* console might take a lot of time:
*/
touch_nmi_watchdog();
if (!state_filter || (p->state & state_filter))
sched_show_task(p);
}
touch_all_softlockup_watchdogs();
#ifdef CONFIG_SCHED_DEBUG
if (!state_filter)
sysrq_sched_debug_show();
#endif
rcu_read_unlock();
/*
* Only show locks if all tasks are dumped:
*/
if (!state_filter)
debug_show_all_locks();
}
void init_idle_bootup_task(struct task_struct *idle)
{
idle->sched_class = &idle_sched_class;
}
/**
* init_idle - set up an idle thread for a given CPU
* @idle: task in question
* @cpu: cpu the idle task belongs to
*
* NOTE: this function does not set the idle thread's NEED_RESCHED
* flag, to make booting more robust.
*/
void init_idle(struct task_struct *idle, int cpu)
{
struct rq *rq = cpu_rq(cpu);
unsigned long flags;
raw_spin_lock_irqsave(&idle->pi_lock, flags);
raw_spin_lock(&rq->lock);
__sched_fork(0, idle);
idle->state = TASK_RUNNING;
idle->se.exec_start = sched_clock();
kasan_unpoison_task_stack(idle);
#ifdef CONFIG_SMP
/*
* Its possible that init_idle() gets called multiple times on a task,
* in that case do_set_cpus_allowed() will not do the right thing.
*
* And since this is boot we can forgo the serialization.
*/
set_cpus_allowed_common(idle, cpumask_of(cpu));
#endif
/*
* We're having a chicken and egg problem, even though we are
* holding rq->lock, the cpu isn't yet set to this cpu so the
* lockdep check in task_group() will fail.
*
* Similar case to sched_fork(). / Alternatively we could
* use task_rq_lock() here and obtain the other rq->lock.
*
* Silence PROVE_RCU
*/
rcu_read_lock();
__set_task_cpu(idle, cpu);
rcu_read_unlock();
rq->curr = rq->idle = idle;
idle->on_rq = TASK_ON_RQ_QUEUED;
#ifdef CONFIG_SMP
idle->on_cpu = 1;
#endif
raw_spin_unlock(&rq->lock);
raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
/* Set the preempt count _outside_ the spinlocks! */
init_idle_preempt_count(idle, cpu);
/*
* The idle tasks have their own, simple scheduling class:
*/
idle->sched_class = &idle_sched_class;
ftrace_graph_init_idle_task(idle, cpu);
vtime_init_idle(idle, cpu);
#ifdef CONFIG_SMP
sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
#endif
}
int cpuset_cpumask_can_shrink(const struct cpumask *cur,
const struct cpumask *trial)
{
int ret = 1, trial_cpus;
struct dl_bw *cur_dl_b;
unsigned long flags;
if (!cpumask_weight(cur))
return ret;
rcu_read_lock_sched();
cur_dl_b = dl_bw_of(cpumask_any(cur));
trial_cpus = cpumask_weight(trial);
raw_spin_lock_irqsave(&cur_dl_b->lock, flags);
if (cur_dl_b->bw != -1 &&
cur_dl_b->bw * trial_cpus < cur_dl_b->total_bw)
ret = 0;
raw_spin_unlock_irqrestore(&cur_dl_b->lock, flags);
rcu_read_unlock_sched();
return ret;
}
int task_can_attach(struct task_struct *p,
const struct cpumask *cs_cpus_allowed)
{
int ret = 0;
/*
* Kthreads which disallow setaffinity shouldn't be moved
* to a new cpuset; we don't want to change their cpu
* affinity and isolating such threads by their set of
* allowed nodes is unnecessary. Thus, cpusets are not
* applicable for such threads. This prevents checking for
* success of set_cpus_allowed_ptr() on all attached tasks
* before cpus_allowed may be changed.
*/
if (p->flags & PF_NO_SETAFFINITY) {
ret = -EINVAL;
goto out;
}
#ifdef CONFIG_SMP
if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
cs_cpus_allowed)) {
unsigned int dest_cpu = cpumask_any_and(cpu_active_mask,
cs_cpus_allowed);
struct dl_bw *dl_b;
bool overflow;
int cpus;
unsigned long flags;
rcu_read_lock_sched();
dl_b = dl_bw_of(dest_cpu);
raw_spin_lock_irqsave(&dl_b->lock, flags);
cpus = dl_bw_cpus(dest_cpu);
overflow = __dl_overflow(dl_b, cpus, 0, p->dl.dl_bw);
if (overflow)
ret = -EBUSY;
else {
/*
* We reserve space for this task in the destination
* root_domain, as we can't fail after this point.
* We will free resources in the source root_domain
* later on (see set_cpus_allowed_dl()).
*/
__dl_add(dl_b, p->dl.dl_bw);
}
raw_spin_unlock_irqrestore(&dl_b->lock, flags);
rcu_read_unlock_sched();
}
#endif
out:
return ret;
}
#ifdef CONFIG_SMP
static bool sched_smp_initialized __read_mostly;
#ifdef CONFIG_NUMA_BALANCING
/* Migrate current task p to target_cpu */
int migrate_task_to(struct task_struct *p, int target_cpu)
{
struct migration_arg arg = { p, target_cpu };
int curr_cpu = task_cpu(p);
if (curr_cpu == target_cpu)
return 0;
if (!cpumask_test_cpu(target_cpu, tsk_cpus_allowed(p)))
return -EINVAL;
/* TODO: This is not properly updating schedstats */
trace_sched_move_numa(p, curr_cpu, target_cpu);
return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
}
/*
* Requeue a task on a given node and accurately track the number of NUMA
* tasks on the runqueues
*/
void sched_setnuma(struct task_struct *p, int nid)
{
bool queued, running;
struct rq_flags rf;
struct rq *rq;
rq = task_rq_lock(p, &rf);
queued = task_on_rq_queued(p);
running = task_current(rq, p);
if (queued)
dequeue_task(rq, p, DEQUEUE_SAVE);
if (running)
put_prev_task(rq, p);
p->numa_preferred_nid = nid;
if (running)
p->sched_class->set_curr_task(rq);
if (queued)
enqueue_task(rq, p, ENQUEUE_RESTORE);
task_rq_unlock(rq, p, &rf);
}
#endif /* CONFIG_NUMA_BALANCING */
#ifdef CONFIG_HOTPLUG_CPU
/*
* Ensures that the idle task is using init_mm right before its cpu goes
* offline.
*/
void idle_task_exit(void)
{
struct mm_struct *mm = current->active_mm;
BUG_ON(cpu_online(smp_processor_id()));
if (mm != &init_mm) {
switch_mm_irqs_off(mm, &init_mm, current);
finish_arch_post_lock_switch();
}
mmdrop(mm);
}
/*
* Since this CPU is going 'away' for a while, fold any nr_active delta
* we might have. Assumes we're called after migrate_tasks() so that the
* nr_active count is stable.
*
* Also see the comment "Global load-average calculations".
*/
static void calc_load_migrate(struct rq *rq)
{
long delta = calc_load_fold_active(rq);
if (delta)
atomic_long_add(delta, &calc_load_tasks);
}
static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
{
}
static const struct sched_class fake_sched_class = {
.put_prev_task = put_prev_task_fake,
};
static struct task_struct fake_task = {
/*
* Avoid pull_{rt,dl}_task()
*/
.prio = MAX_PRIO + 1,
.sched_class = &fake_sched_class,
};
/*
* Migrate all tasks from the rq, sleeping tasks will be migrated by
* try_to_wake_up()->select_task_rq().
*
* Called with rq->lock held even though we'er in stop_machine() and
* there's no concurrency possible, we hold the required locks anyway
* because of lock validation efforts.
*/
static void migrate_tasks(struct rq *dead_rq)
{
struct rq *rq = dead_rq;
struct task_struct *next, *stop = rq->stop;
struct pin_cookie cookie;
int dest_cpu;
/*
* Fudge the rq selection such that the below task selection loop
* doesn't get stuck on the currently eligible stop task.
*
* We're currently inside stop_machine() and the rq is either stuck
* in the stop_machine_cpu_stop() loop, or we're executing this code,
* either way we should never end up calling schedule() until we're
* done here.
*/
rq->stop = NULL;
/*
* put_prev_task() and pick_next_task() sched
* class method both need to have an up-to-date
* value of rq->clock[_task]
*/
update_rq_clock(rq);
for (;;) {
/*
* There's this thread running, bail when that's the only
* remaining thread.
*/
if (rq->nr_running == 1)
break;
/*
* pick_next_task assumes pinned rq->lock.
*/
cookie = lockdep_pin_lock(&rq->lock);
next = pick_next_task(rq, &fake_task, cookie);
BUG_ON(!next);
next->sched_class->put_prev_task(rq, next);
/*
* Rules for changing task_struct::cpus_allowed are holding
* both pi_lock and rq->lock, such that holding either
* stabilizes the mask.
*
* Drop rq->lock is not quite as disastrous as it usually is
* because !cpu_active at this point, which means load-balance
* will not interfere. Also, stop-machine.
*/
lockdep_unpin_lock(&rq->lock, cookie);
raw_spin_unlock(&rq->lock);
raw_spin_lock(&next->pi_lock);
raw_spin_lock(&rq->lock);
/*
* Since we're inside stop-machine, _nothing_ should have
* changed the task, WARN if weird stuff happened, because in
* that case the above rq->lock drop is a fail too.
*/
if (WARN_ON(task_rq(next) != rq || !task_on_rq_queued(next))) {
raw_spin_unlock(&next->pi_lock);
continue;
}
/* Find suitable destination for @next, with force if needed. */
dest_cpu = select_fallback_rq(dead_rq->cpu, next);
rq = __migrate_task(rq, next, dest_cpu);
if (rq != dead_rq) {
raw_spin_unlock(&rq->lock);
rq = dead_rq;
raw_spin_lock(&rq->lock);
}
raw_spin_unlock(&next->pi_lock);
}
rq->stop = stop;
}
#endif /* CONFIG_HOTPLUG_CPU */
static void set_rq_online(struct rq *rq)
{
if (!rq->online) {
const struct sched_class *class;
cpumask_set_cpu(rq->cpu, rq->rd->online);
rq->online = 1;
for_each_class(class) {
if (class->rq_online)
class->rq_online(rq);
}
}
}
static void set_rq_offline(struct rq *rq)
{
if (rq->online) {
const struct sched_class *class;
for_each_class(class) {
if (class->rq_offline)
class->rq_offline(rq);
}
cpumask_clear_cpu(rq->cpu, rq->rd->online);
rq->online = 0;
}
}
static void set_cpu_rq_start_time(unsigned int cpu)
{
struct rq *rq = cpu_rq(cpu);
rq->age_stamp = sched_clock_cpu(cpu);
}
static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */
#ifdef CONFIG_SCHED_DEBUG
static __read_mostly int sched_debug_enabled;
static int __init sched_debug_setup(char *str)
{
sched_debug_enabled = 1;
return 0;
}
early_param("sched_debug", sched_debug_setup);
static inline bool sched_debug(void)
{
return sched_debug_enabled;
}
static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
struct cpumask *groupmask)
{
struct sched_group *group = sd->groups;
cpumask_clear(groupmask);
printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
if (!(sd->flags & SD_LOAD_BALANCE)) {
printk("does not load-balance\n");
if (sd->parent)
printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
" has parent");
return -1;
}
printk(KERN_CONT "span %*pbl level %s\n",
cpumask_pr_args(sched_domain_span(sd)), sd->name);
if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
printk(KERN_ERR "ERROR: domain->span does not contain "
"CPU%d\n", cpu);
}
if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
printk(KERN_ERR "ERROR: domain->groups does not contain"
" CPU%d\n", cpu);
}
printk(KERN_DEBUG "%*s groups:", level + 1, "");
do {
if (!group) {
printk("\n");
printk(KERN_ERR "ERROR: group is NULL\n");
break;
}
if (!cpumask_weight(sched_group_cpus(group))) {
printk(KERN_CONT "\n");
printk(KERN_ERR "ERROR: empty group\n");
break;
}
if (!(sd->flags & SD_OVERLAP) &&
cpumask_intersects(groupmask, sched_group_cpus(group))) {
printk(KERN_CONT "\n");
printk(KERN_ERR "ERROR: repeated CPUs\n");
break;
}
cpumask_or(groupmask, groupmask, sched_group_cpus(group));
printk(KERN_CONT " %*pbl",
cpumask_pr_args(sched_group_cpus(group)));
if (group->sgc->capacity != SCHED_CAPACITY_SCALE) {
printk(KERN_CONT " (cpu_capacity = %d)",
group->sgc->capacity);
}
group = group->next;
} while (group != sd->groups);
printk(KERN_CONT "\n");
if (!cpumask_equal(sched_domain_span(sd), groupmask))
printk(KERN_ERR "ERROR: groups don't span domain->span\n");
if (sd->parent &&
!cpumask_subset(groupmask, sched_domain_span(sd->parent)))
printk(KERN_ERR "ERROR: parent span is not a superset "
"of domain->span\n");
return 0;
}
static void sched_domain_debug(struct sched_domain *sd, int cpu)
{
int level = 0;
if (!sched_debug_enabled)
return;
if (!sd) {
printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
return;
}
printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
for (;;) {
if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
break;
level++;
sd = sd->parent;
if (!sd)
break;
}
}
#else /* !CONFIG_SCHED_DEBUG */
# define sched_domain_debug(sd, cpu) do { } while (0)
static inline bool sched_debug(void)
{
return false;
}
#endif /* CONFIG_SCHED_DEBUG */
static int sd_degenerate(struct sched_domain *sd)
{
if (cpumask_weight(sched_domain_span(sd)) == 1)
return 1;
/* Following flags need at least 2 groups */
if (sd->flags & (SD_LOAD_BALANCE |
SD_BALANCE_NEWIDLE |
SD_BALANCE_FORK |
SD_BALANCE_EXEC |
SD_SHARE_CPUCAPACITY |
SD_SHARE_PKG_RESOURCES |
SD_SHARE_POWERDOMAIN)) {
if (sd->groups != sd->groups->next)
return 0;
}
/* Following flags don't use groups */
if (sd->flags & (SD_WAKE_AFFINE))
return 0;
return 1;
}
static int
sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
{
unsigned long cflags = sd->flags, pflags = parent->flags;
if (sd_degenerate(parent))
return 1;
if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
return 0;
/* Flags needing groups don't count if only 1 group in parent */
if (parent->groups == parent->groups->next) {
pflags &= ~(SD_LOAD_BALANCE |
SD_BALANCE_NEWIDLE |
SD_BALANCE_FORK |
SD_BALANCE_EXEC |
SD_SHARE_CPUCAPACITY |
SD_SHARE_PKG_RESOURCES |
SD_PREFER_SIBLING |
SD_SHARE_POWERDOMAIN);
if (nr_node_ids == 1)
pflags &= ~SD_SERIALIZE;
}
if (~cflags & pflags)
return 0;
return 1;
}
static void free_rootdomain(struct rcu_head *rcu)
{
struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
cpupri_cleanup(&rd->cpupri);
cpudl_cleanup(&rd->cpudl);
free_cpumask_var(rd->dlo_mask);
free_cpumask_var(rd->rto_mask);
free_cpumask_var(rd->online);
free_cpumask_var(rd->span);
kfree(rd);
}
static void rq_attach_root(struct rq *rq, struct root_domain *rd)
{
struct root_domain *old_rd = NULL;
unsigned long flags;
raw_spin_lock_irqsave(&rq->lock, flags);
if (rq->rd) {
old_rd = rq->rd;
if (cpumask_test_cpu(rq->cpu, old_rd->online))
set_rq_offline(rq);
cpumask_clear_cpu(rq->cpu, old_rd->span);
/*
* If we dont want to free the old_rd yet then
* set old_rd to NULL to skip the freeing later
* in this function:
*/
if (!atomic_dec_and_test(&old_rd->refcount))
old_rd = NULL;
}
atomic_inc(&rd->refcount);
rq->rd = rd;
cpumask_set_cpu(rq->cpu, rd->span);
if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
set_rq_online(rq);
raw_spin_unlock_irqrestore(&rq->lock, flags);
if (old_rd)
call_rcu_sched(&old_rd->rcu, free_rootdomain);
}
static int init_rootdomain(struct root_domain *rd)
{
memset(rd, 0, sizeof(*rd));
if (!zalloc_cpumask_var(&rd->span, GFP_KERNEL))
goto out;
if (!zalloc_cpumask_var(&rd->online, GFP_KERNEL))
goto free_span;
if (!zalloc_cpumask_var(&rd->dlo_mask, GFP_KERNEL))
goto free_online;
if (!zalloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
goto free_dlo_mask;
init_dl_bw(&rd->dl_bw);
if (cpudl_init(&rd->cpudl) != 0)
goto free_dlo_mask;
if (cpupri_init(&rd->cpupri) != 0)
goto free_rto_mask;
return 0;
free_rto_mask:
free_cpumask_var(rd->rto_mask);
free_dlo_mask:
free_cpumask_var(rd->dlo_mask);
free_online:
free_cpumask_var(rd->online);
free_span:
free_cpumask_var(rd->span);
out:
return -ENOMEM;
}
/*
* By default the system creates a single root-domain with all cpus as
* members (mimicking the global state we have today).
*/
struct root_domain def_root_domain;
static void init_defrootdomain(void)
{
init_rootdomain(&def_root_domain);
atomic_set(&def_root_domain.refcount, 1);
}
static struct root_domain *alloc_rootdomain(void)
{
struct root_domain *rd;
rd = kmalloc(sizeof(*rd), GFP_KERNEL);
if (!rd)
return NULL;
if (init_rootdomain(rd) != 0) {
kfree(rd);
return NULL;
}
return rd;
}
static void free_sched_groups(struct sched_group *sg, int free_sgc)
{
struct sched_group *tmp, *first;
if (!sg)
return;
first = sg;
do {
tmp = sg->next;
if (free_sgc && atomic_dec_and_test(&sg->sgc->ref))
kfree(sg->sgc);
kfree(sg);
sg = tmp;
} while (sg != first);
}
static void free_sched_domain(struct rcu_head *rcu)
{
struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
/*
* If its an overlapping domain it has private groups, iterate and
* nuke them all.
*/
if (sd->flags & SD_OVERLAP) {
free_sched_groups(sd->groups, 1);
} else if (atomic_dec_and_test(&sd->groups->ref)) {
kfree(sd->groups->sgc);
kfree(sd->groups);
}
kfree(sd);
}
static void destroy_sched_domain(struct sched_domain *sd, int cpu)
{
call_rcu(&sd->rcu, free_sched_domain);
}
static void destroy_sched_domains(struct sched_domain *sd, int cpu)
{
for (; sd; sd = sd->parent)
destroy_sched_domain(sd, cpu);
}
/*
* Keep a special pointer to the highest sched_domain that has
* SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this
* allows us to avoid some pointer chasing select_idle_sibling().
*
* Also keep a unique ID per domain (we use the first cpu number in
* the cpumask of the domain), this allows us to quickly tell if
* two cpus are in the same cache domain, see cpus_share_cache().
*/
DEFINE_PER_CPU(struct sched_domain *, sd_llc);
DEFINE_PER_CPU(int, sd_llc_size);
DEFINE_PER_CPU(int, sd_llc_id);
DEFINE_PER_CPU(struct sched_domain *, sd_numa);
DEFINE_PER_CPU(struct sched_domain *, sd_busy);
DEFINE_PER_CPU(struct sched_domain *, sd_asym);
static void update_top_cache_domain(int cpu)
{
struct sched_domain *sd;
struct sched_domain *busy_sd = NULL;
int id = cpu;
int size = 1;
sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES);
if (sd) {
id = cpumask_first(sched_domain_span(sd));
size = cpumask_weight(sched_domain_span(sd));
busy_sd = sd->parent; /* sd_busy */
}
rcu_assign_pointer(per_cpu(sd_busy, cpu), busy_sd);
rcu_assign_pointer(per_cpu(sd_llc, cpu), sd);
per_cpu(sd_llc_size, cpu) = size;
per_cpu(sd_llc_id, cpu) = id;
sd = lowest_flag_domain(cpu, SD_NUMA);
rcu_assign_pointer(per_cpu(sd_numa, cpu), sd);
sd = highest_flag_domain(cpu, SD_ASYM_PACKING);
rcu_assign_pointer(per_cpu(sd_asym, cpu), sd);
}
/*
* Attach the domain 'sd' to 'cpu' as its base domain. Callers must
* hold the hotplug lock.
*/
static void
cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
{
struct rq *rq = cpu_rq(cpu);
struct sched_domain *tmp;
/* Remove the sched domains which do not contribute to scheduling. */
for (tmp = sd; tmp; ) {
struct sched_domain *parent = tmp->parent;
if (!parent)
break;
if (sd_parent_degenerate(tmp, parent)) {
tmp->parent = parent->parent;
if (parent->parent)
parent->parent->child = tmp;
/*
* Transfer SD_PREFER_SIBLING down in case of a
* degenerate parent; the spans match for this
* so the property transfers.
*/
if (parent->flags & SD_PREFER_SIBLING)
tmp->flags |= SD_PREFER_SIBLING;
destroy_sched_domain(parent, cpu);
} else
tmp = tmp->parent;
}
if (sd && sd_degenerate(sd)) {
tmp = sd;
sd = sd->parent;
destroy_sched_domain(tmp, cpu);
if (sd)
sd->child = NULL;
}
sched_domain_debug(sd, cpu);
rq_attach_root(rq, rd);
tmp = rq->sd;
rcu_assign_pointer(rq->sd, sd);
destroy_sched_domains(tmp, cpu);
update_top_cache_domain(cpu);
}
/* Setup the mask of cpus configured for isolated domains */
static int __init isolated_cpu_setup(char *str)
{
int ret;
alloc_bootmem_cpumask_var(&cpu_isolated_map);
ret = cpulist_parse(str, cpu_isolated_map);
if (ret) {
pr_err("sched: Error, all isolcpus= values must be between 0 and %d\n", nr_cpu_ids);
return 0;
}
return 1;
}
__setup("isolcpus=", isolated_cpu_setup);
struct s_data {
struct sched_domain ** __percpu sd;
struct root_domain *rd;
};
enum s_alloc {
sa_rootdomain,
sa_sd,
sa_sd_storage,
sa_none,
};
/*
* Build an iteration mask that can exclude certain CPUs from the upwards
* domain traversal.
*
* Asymmetric node setups can result in situations where the domain tree is of
* unequal depth, make sure to skip domains that already cover the entire
* range.
*
* In that case build_sched_domains() will have terminated the iteration early
* and our sibling sd spans will be empty. Domains should always include the
* cpu they're built on, so check that.
*
*/
static void build_group_mask(struct sched_domain *sd, struct sched_group *sg)
{
const struct cpumask *span = sched_domain_span(sd);
struct sd_data *sdd = sd->private;
struct sched_domain *sibling;
int i;
for_each_cpu(i, span) {
sibling = *per_cpu_ptr(sdd->sd, i);
if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
continue;
cpumask_set_cpu(i, sched_group_mask(sg));
}
}
/*
* Return the canonical balance cpu for this group, this is the first cpu
* of this group that's also in the iteration mask.
*/
int group_balance_cpu(struct sched_group *sg)
{
return cpumask_first_and(sched_group_cpus(sg), sched_group_mask(sg));
}
static int
build_overlap_sched_groups(struct sched_domain *sd, int cpu)
{
struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg;
const struct cpumask *span = sched_domain_span(sd);
struct cpumask *covered = sched_domains_tmpmask;
struct sd_data *sdd = sd->private;
struct sched_domain *sibling;
int i;
cpumask_clear(covered);
for_each_cpu(i, span) {
struct cpumask *sg_span;
if (cpumask_test_cpu(i, covered))
continue;
sibling = *per_cpu_ptr(sdd->sd, i);
/* See the comment near build_group_mask(). */
if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
continue;
sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
GFP_KERNEL, cpu_to_node(cpu));
if (!sg)
goto fail;
sg_span = sched_group_cpus(sg);
if (sibling->child)
cpumask_copy(sg_span, sched_domain_span(sibling->child));
else
cpumask_set_cpu(i, sg_span);
cpumask_or(covered, covered, sg_span);
sg->sgc = *per_cpu_ptr(sdd->sgc, i);
if (atomic_inc_return(&sg->sgc->ref) == 1)
build_group_mask(sd, sg);
/*
* Initialize sgc->capacity such that even if we mess up the
* domains and no possible iteration will get us here, we won't
* die on a /0 trap.
*/
sg->sgc->capacity = SCHED_CAPACITY_SCALE * cpumask_weight(sg_span);
/*
* Make sure the first group of this domain contains the
* canonical balance cpu. Otherwise the sched_domain iteration
* breaks. See update_sg_lb_stats().
*/
if ((!groups && cpumask_test_cpu(cpu, sg_span)) ||
group_balance_cpu(sg) == cpu)
groups = sg;
if (!first)
first = sg;
if (last)
last->next = sg;
last = sg;
last->next = first;
}
sd->groups = groups;
return 0;
fail:
free_sched_groups(first, 0);
return -ENOMEM;
}
static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg)
{
struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
struct sched_domain *child = sd->child;
if (child)
cpu = cpumask_first(sched_domain_span(child));
if (sg) {
*sg = *per_cpu_ptr(sdd->sg, cpu);
(*sg)->sgc = *per_cpu_ptr(sdd->sgc, cpu);
atomic_set(&(*sg)->sgc->ref, 1); /* for claim_allocations */
}
return cpu;
}
/*
* build_sched_groups will build a circular linked list of the groups
* covered by the given span, and will set each group's ->cpumask correctly,
* and ->cpu_capacity to 0.
*
* Assumes the sched_domain tree is fully constructed
*/
static int
build_sched_groups(struct sched_domain *sd, int cpu)
{
struct sched_group *first = NULL, *last = NULL;
struct sd_data *sdd = sd->private;
const struct cpumask *span = sched_domain_span(sd);
struct cpumask *covered;
int i;
get_group(cpu, sdd, &sd->groups);
atomic_inc(&sd->groups->ref);
if (cpu != cpumask_first(span))
return 0;
lockdep_assert_held(&sched_domains_mutex);
covered = sched_domains_tmpmask;
cpumask_clear(covered);
for_each_cpu(i, span) {
struct sched_group *sg;
int group, j;
if (cpumask_test_cpu(i, covered))
continue;
group = get_group(i, sdd, &sg);
cpumask_setall(sched_group_mask(sg));
for_each_cpu(j, span) {
if (get_group(j, sdd, NULL) != group)
continue;
cpumask_set_cpu(j, covered);
cpumask_set_cpu(j, sched_group_cpus(sg));
}
if (!first)
first = sg;
if (last)
last->next = sg;
last = sg;
}
last->next = first;
return 0;
}
/*
* Initialize sched groups cpu_capacity.
*
* cpu_capacity indicates the capacity of sched group, which is used while
* distributing the load between different sched groups in a sched domain.
* Typically cpu_capacity for all the groups in a sched domain will be same
* unless there are asymmetries in the topology. If there are asymmetries,
* group having more cpu_capacity will pickup more load compared to the
* group having less cpu_capacity.
*/
static void init_sched_groups_capacity(int cpu, struct sched_domain *sd)
{
struct sched_group *sg = sd->groups;
WARN_ON(!sg);
do {
sg->group_weight = cpumask_weight(sched_group_cpus(sg));
sg = sg->next;
} while (sg != sd->groups);
if (cpu != group_balance_cpu(sg))
return;
update_group_capacity(sd, cpu);
atomic_set(&sg->sgc->nr_busy_cpus, sg->group_weight);
}
/*
* Initializers for schedule domains
* Non-inlined to reduce accumulated stack pressure in build_sched_domains()
*/
static int default_relax_domain_level = -1;
int sched_domain_level_max;
static int __init setup_relax_domain_level(char *str)
{
if (kstrtoint(str, 0, &default_relax_domain_level))
pr_warn("Unable to set relax_domain_level\n");
return 1;
}
__setup("relax_domain_level=", setup_relax_domain_level);
static void set_domain_attribute(struct sched_domain *sd,
struct sched_domain_attr *attr)
{
int request;
if (!attr || attr->relax_domain_level < 0) {
if (default_relax_domain_level < 0)
return;
else
request = default_relax_domain_level;
} else
request = attr->relax_domain_level;
if (request < sd->level) {
/* turn off idle balance on this domain */
sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
} else {
/* turn on idle balance on this domain */
sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
}
}
static void __sdt_free(const struct cpumask *cpu_map);
static int __sdt_alloc(const struct cpumask *cpu_map);
static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
const struct cpumask *cpu_map)
{
switch (what) {
case sa_rootdomain:
if (!atomic_read(&d->rd->refcount))
free_rootdomain(&d->rd->rcu); /* fall through */
case sa_sd:
free_percpu(d->sd); /* fall through */
case sa_sd_storage:
__sdt_free(cpu_map); /* fall through */
case sa_none:
break;
}
}
static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
const struct cpumask *cpu_map)
{
memset(d, 0, sizeof(*d));
if (__sdt_alloc(cpu_map))
return sa_sd_storage;
d->sd = alloc_percpu(struct sched_domain *);
if (!d->sd)
return sa_sd_storage;
d->rd = alloc_rootdomain();
if (!d->rd)
return sa_sd;
return sa_rootdomain;
}
/*
* NULL the sd_data elements we've used to build the sched_domain and
* sched_group structure so that the subsequent __free_domain_allocs()
* will not free the data we're using.
*/
static void claim_allocations(int cpu, struct sched_domain *sd)
{
struct sd_data *sdd = sd->private;
WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
*per_cpu_ptr(sdd->sd, cpu) = NULL;
if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
*per_cpu_ptr(sdd->sg, cpu) = NULL;
if (atomic_read(&(*per_cpu_ptr(sdd->sgc, cpu))->ref))
*per_cpu_ptr(sdd->sgc, cpu) = NULL;
}
#ifdef CONFIG_NUMA
static int sched_domains_numa_levels;
enum numa_topology_type sched_numa_topology_type;
static int *sched_domains_numa_distance;
int sched_max_numa_distance;
static struct cpumask ***sched_domains_numa_masks;
static int sched_domains_curr_level;
#endif
/*
* SD_flags allowed in topology descriptions.
*
* SD_SHARE_CPUCAPACITY - describes SMT topologies
* SD_SHARE_PKG_RESOURCES - describes shared caches
* SD_NUMA - describes NUMA topologies
* SD_SHARE_POWERDOMAIN - describes shared power domain
*
* Odd one out:
* SD_ASYM_PACKING - describes SMT quirks
*/
#define TOPOLOGY_SD_FLAGS \
(SD_SHARE_CPUCAPACITY | \
SD_SHARE_PKG_RESOURCES | \
SD_NUMA | \
SD_ASYM_PACKING | \
SD_SHARE_POWERDOMAIN)
static struct sched_domain *
sd_init(struct sched_domain_topology_level *tl, int cpu)
{
struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu);
int sd_weight, sd_flags = 0;
#ifdef CONFIG_NUMA
/*
* Ugly hack to pass state to sd_numa_mask()...
*/
sched_domains_curr_level = tl->numa_level;
#endif
sd_weight = cpumask_weight(tl->mask(cpu));
if (tl->sd_flags)
sd_flags = (*tl->sd_flags)();
if (WARN_ONCE(sd_flags & ~TOPOLOGY_SD_FLAGS,
"wrong sd_flags in topology description\n"))
sd_flags &= ~TOPOLOGY_SD_FLAGS;
*sd = (struct sched_domain){
.min_interval = sd_weight,
.max_interval = 2*sd_weight,
.busy_factor = 32,
.imbalance_pct = 125,
.cache_nice_tries = 0,
.busy_idx = 0,
.idle_idx = 0,
.newidle_idx = 0,
.wake_idx = 0,
.forkexec_idx = 0,
.flags = 1*SD_LOAD_BALANCE
| 1*SD_BALANCE_NEWIDLE
| 1*SD_BALANCE_EXEC
| 1*SD_BALANCE_FORK
| 0*SD_BALANCE_WAKE
| 1*SD_WAKE_AFFINE
| 0*SD_SHARE_CPUCAPACITY
| 0*SD_SHARE_PKG_RESOURCES
| 0*SD_SERIALIZE
| 0*SD_PREFER_SIBLING
| 0*SD_NUMA
| sd_flags
,
.last_balance = jiffies,
.balance_interval = sd_weight,
.smt_gain = 0,
.max_newidle_lb_cost = 0,
.next_decay_max_lb_cost = jiffies,
#ifdef CONFIG_SCHED_DEBUG
.name = tl->name,
#endif
};
/*
* Convert topological properties into behaviour.
*/
if (sd->flags & SD_SHARE_CPUCAPACITY) {
sd->flags |= SD_PREFER_SIBLING;
sd->imbalance_pct = 110;
sd->smt_gain = 1178; /* ~15% */
} else if (sd->flags & SD_SHARE_PKG_RESOURCES) {
sd->imbalance_pct = 117;
sd->cache_nice_tries = 1;
sd->busy_idx = 2;
#ifdef CONFIG_NUMA
} else if (sd->flags & SD_NUMA) {
sd->cache_nice_tries = 2;
sd->busy_idx = 3;
sd->idle_idx = 2;
sd->flags |= SD_SERIALIZE;
if (sched_domains_numa_distance[tl->numa_level] > RECLAIM_DISTANCE) {
sd->flags &= ~(SD_BALANCE_EXEC |
SD_BALANCE_FORK |
SD_WAKE_AFFINE);
}
#endif
} else {
sd->flags |= SD_PREFER_SIBLING;
sd->cache_nice_tries = 1;
sd->busy_idx = 2;
sd->idle_idx = 1;
}
sd->private = &tl->data;
return sd;
}
/*
* Topology list, bottom-up.
*/
static struct sched_domain_topology_level default_topology[] = {
#ifdef CONFIG_SCHED_SMT
{ cpu_smt_mask, cpu_smt_flags, SD_INIT_NAME(SMT) },
#endif
#ifdef CONFIG_SCHED_MC
{ cpu_coregroup_mask, cpu_core_flags, SD_INIT_NAME(MC) },
#endif
{ cpu_cpu_mask, SD_INIT_NAME(DIE) },
{ NULL, },
};
static struct sched_domain_topology_level *sched_domain_topology =
default_topology;
#define for_each_sd_topology(tl) \
for (tl = sched_domain_topology; tl->mask; tl++)
void set_sched_topology(struct sched_domain_topology_level *tl)
{
sched_domain_topology = tl;
}
#ifdef CONFIG_NUMA
static const struct cpumask *sd_numa_mask(int cpu)
{
return sched_domains_numa_masks[sched_domains_curr_level][cpu_to_node(cpu)];
}
static void sched_numa_warn(const char *str)
{
static int done = false;
int i,j;
if (done)
return;
done = true;
printk(KERN_WARNING "ERROR: %s\n\n", str);
for (i = 0; i < nr_node_ids; i++) {
printk(KERN_WARNING " ");
for (j = 0; j < nr_node_ids; j++)
printk(KERN_CONT "%02d ", node_distance(i,j));
printk(KERN_CONT "\n");
}
printk(KERN_WARNING "\n");
}
bool find_numa_distance(int distance)
{
int i;
if (distance == node_distance(0, 0))
return true;
for (i = 0; i < sched_domains_numa_levels; i++) {
if (sched_domains_numa_distance[i] == distance)
return true;
}
return false;
}
/*
* A system can have three types of NUMA topology:
* NUMA_DIRECT: all nodes are directly connected, or not a NUMA system
* NUMA_GLUELESS_MESH: some nodes reachable through intermediary nodes
* NUMA_BACKPLANE: nodes can reach other nodes through a backplane
*
* The difference between a glueless mesh topology and a backplane
* topology lies in whether communication between not directly
* connected nodes goes through intermediary nodes (where programs
* could run), or through backplane controllers. This affects
* placement of programs.
*
* The type of topology can be discerned with the following tests:
* - If the maximum distance between any nodes is 1 hop, the system
* is directly connected.
* - If for two nodes A and B, located N > 1 hops away from each other,
* there is an intermediary node C, which is < N hops away from both
* nodes A and B, the system is a glueless mesh.
*/
static void init_numa_topology_type(void)
{
int a, b, c, n;
n = sched_max_numa_distance;
if (sched_domains_numa_levels <= 1) {
sched_numa_topology_type = NUMA_DIRECT;
return;
}
for_each_online_node(a) {
for_each_online_node(b) {
/* Find two nodes furthest removed from each other. */
if (node_distance(a, b) < n)
continue;
/* Is there an intermediary node between a and b? */
for_each_online_node(c) {
if (node_distance(a, c) < n &&
node_distance(b, c) < n) {
sched_numa_topology_type =
NUMA_GLUELESS_MESH;
return;
}
}
sched_numa_topology_type = NUMA_BACKPLANE;
return;
}
}
}
static void sched_init_numa(void)
{
int next_distance, curr_distance = node_distance(0, 0);
struct sched_domain_topology_level *tl;
int level = 0;
int i, j, k;
sched_domains_numa_distance = kzalloc(sizeof(int) * nr_node_ids, GFP_KERNEL);
if (!sched_domains_numa_distance)
return;
/*
* O(nr_nodes^2) deduplicating selection sort -- in order to find the
* unique distances in the node_distance() table.
*
* Assumes node_distance(0,j) includes all distances in
* node_distance(i,j) in order to avoid cubic time.
*/
next_distance = curr_distance;
for (i = 0; i < nr_node_ids; i++) {
for (j = 0; j < nr_node_ids; j++) {
for (k = 0; k < nr_node_ids; k++) {
int distance = node_distance(i, k);
if (distance > curr_distance &&
(distance < next_distance ||
next_distance == curr_distance))
next_distance = distance;
/*
* While not a strong assumption it would be nice to know
* about cases where if node A is connected to B, B is not
* equally connected to A.
*/
if (sched_debug() && node_distance(k, i) != distance)
sched_numa_warn("Node-distance not symmetric");
if (sched_debug() && i && !find_numa_distance(distance))
sched_numa_warn("Node-0 not representative");
}
if (next_distance != curr_distance) {
sched_domains_numa_distance[level++] = next_distance;
sched_domains_numa_levels = level;
curr_distance = next_distance;
} else break;
}
/*
* In case of sched_debug() we verify the above assumption.
*/
if (!sched_debug())
break;
}
if (!level)
return;
/*
* 'level' contains the number of unique distances, excluding the
* identity distance node_distance(i,i).
*
* The sched_domains_numa_distance[] array includes the actual distance
* numbers.
*/
/*
* Here, we should temporarily reset sched_domains_numa_levels to 0.
* If it fails to allocate memory for array sched_domains_numa_masks[][],
* the array will contain less then 'level' members. This could be
* dangerous when we use it to iterate array sched_domains_numa_masks[][]
* in other functions.
*
* We reset it to 'level' at the end of this function.
*/
sched_domains_numa_levels = 0;
sched_domains_numa_masks = kzalloc(sizeof(void *) * level, GFP_KERNEL);
if (!sched_domains_numa_masks)
return;
/*
* Now for each level, construct a mask per node which contains all
* cpus of nodes that are that many hops away from us.
*/
for (i = 0; i < level; i++) {
sched_domains_numa_masks[i] =
kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL);
if (!sched_domains_numa_masks[i])
return;
for (j = 0; j < nr_node_ids; j++) {
struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL);
if (!mask)
return;
sched_domains_numa_masks[i][j] = mask;
for_each_node(k) {
if (node_distance(j, k) > sched_domains_numa_distance[i])
continue;
cpumask_or(mask, mask, cpumask_of_node(k));
}
}
}
/* Compute default topology size */
for (i = 0; sched_domain_topology[i].mask; i++);
tl = kzalloc((i + level + 1) *
sizeof(struct sched_domain_topology_level), GFP_KERNEL);
if (!tl)
return;
/*
* Copy the default topology bits..
*/
for (i = 0; sched_domain_topology[i].mask; i++)
tl[i] = sched_domain_topology[i];
/*
* .. and append 'j' levels of NUMA goodness.
*/
for (j = 0; j < level; i++, j++) {
tl[i] = (struct sched_domain_topology_level){
.mask = sd_numa_mask,
.sd_flags = cpu_numa_flags,
.flags = SDTL_OVERLAP,
.numa_level = j,
SD_INIT_NAME(NUMA)
};
}
sched_domain_topology = tl;
sched_domains_numa_levels = level;
sched_max_numa_distance = sched_domains_numa_distance[level - 1];
init_numa_topology_type();
}
static void sched_domains_numa_masks_set(unsigned int cpu)
{
int node = cpu_to_node(cpu);
int i, j;
for (i = 0; i < sched_domains_numa_levels; i++) {
for (j = 0; j < nr_node_ids; j++) {
if (node_distance(j, node) <= sched_domains_numa_distance[i])
cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]);
}
}
}
static void sched_domains_numa_masks_clear(unsigned int cpu)
{
int i, j;
for (i = 0; i < sched_domains_numa_levels; i++) {
for (j = 0; j < nr_node_ids; j++)
cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]);
}
}
#else
static inline void sched_init_numa(void) { }
static void sched_domains_numa_masks_set(unsigned int cpu) { }
static void sched_domains_numa_masks_clear(unsigned int cpu) { }
#endif /* CONFIG_NUMA */
static int __sdt_alloc(const struct cpumask *cpu_map)
{
struct sched_domain_topology_level *tl;
int j;
for_each_sd_topology(tl) {
struct sd_data *sdd = &tl->data;
sdd->sd = alloc_percpu(struct sched_domain *);
if (!sdd->sd)
return -ENOMEM;
sdd->sg = alloc_percpu(struct sched_group *);
if (!sdd->sg)
return -ENOMEM;
sdd->sgc = alloc_percpu(struct sched_group_capacity *);
if (!sdd->sgc)
return -ENOMEM;
for_each_cpu(j, cpu_map) {
struct sched_domain *sd;
struct sched_group *sg;
struct sched_group_capacity *sgc;
sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
GFP_KERNEL, cpu_to_node(j));
if (!sd)
return -ENOMEM;
*per_cpu_ptr(sdd->sd, j) = sd;
sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
GFP_KERNEL, cpu_to_node(j));
if (!sg)
return -ENOMEM;
sg->next = sg;
*per_cpu_ptr(sdd->sg, j) = sg;
sgc = kzalloc_node(sizeof(struct sched_group_capacity) + cpumask_size(),
GFP_KERNEL, cpu_to_node(j));
if (!sgc)
return -ENOMEM;
*per_cpu_ptr(sdd->sgc, j) = sgc;
}
}
return 0;
}
static void __sdt_free(const struct cpumask *cpu_map)
{
struct sched_domain_topology_level *tl;
int j;
for_each_sd_topology(tl) {
struct sd_data *sdd = &tl->data;
for_each_cpu(j, cpu_map) {
struct sched_domain *sd;
if (sdd->sd) {
sd = *per_cpu_ptr(sdd->sd, j);
if (sd && (sd->flags & SD_OVERLAP))
free_sched_groups(sd->groups, 0);
kfree(*per_cpu_ptr(sdd->sd, j));
}
if (sdd->sg)
kfree(*per_cpu_ptr(sdd->sg, j));
if (sdd->sgc)
kfree(*per_cpu_ptr(sdd->sgc, j));
}
free_percpu(sdd->sd);
sdd->sd = NULL;
free_percpu(sdd->sg);
sdd->sg = NULL;
free_percpu(sdd->sgc);
sdd->sgc = NULL;
}
}
struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
const struct cpumask *cpu_map, struct sched_domain_attr *attr,
struct sched_domain *child, int cpu)
{
struct sched_domain *sd = sd_init(tl, cpu);
if (!sd)
return child;
cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
if (child) {
sd->level = child->level + 1;
sched_domain_level_max = max(sched_domain_level_max, sd->level);
child->parent = sd;
sd->child = child;
if (!cpumask_subset(sched_domain_span(child),
sched_domain_span(sd))) {
pr_err("BUG: arch topology borken\n");
#ifdef CONFIG_SCHED_DEBUG
pr_err(" the %s domain not a subset of the %s domain\n",
child->name, sd->name);
#endif
/* Fixup, ensure @sd has at least @child cpus. */
cpumask_or(sched_domain_span(sd),
sched_domain_span(sd),
sched_domain_span(child));
}
}
set_domain_attribute(sd, attr);
return sd;
}
/*
* Build sched domains for a given set of cpus and attach the sched domains
* to the individual cpus
*/
static int build_sched_domains(const struct cpumask *cpu_map,
struct sched_domain_attr *attr)
{
enum s_alloc alloc_state;
struct sched_domain *sd;
struct s_data d;
int i, ret = -ENOMEM;
alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
if (alloc_state != sa_rootdomain)
goto error;
/* Set up domains for cpus specified by the cpu_map. */
for_each_cpu(i, cpu_map) {
struct sched_domain_topology_level *tl;
sd = NULL;
for_each_sd_topology(tl) {
sd = build_sched_domain(tl, cpu_map, attr, sd, i);
if (tl == sched_domain_topology)
*per_cpu_ptr(d.sd, i) = sd;
if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP))
sd->flags |= SD_OVERLAP;
if (cpumask_equal(cpu_map, sched_domain_span(sd)))
break;
}
}
/* Build the groups for the domains */
for_each_cpu(i, cpu_map) {
for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
sd->span_weight = cpumask_weight(sched_domain_span(sd));
if (sd->flags & SD_OVERLAP) {
if (build_overlap_sched_groups(sd, i))
goto error;
} else {
if (build_sched_groups(sd, i))
goto error;
}
}
}
/* Calculate CPU capacity for physical packages and nodes */
for (i = nr_cpumask_bits-1; i >= 0; i--) {
if (!cpumask_test_cpu(i, cpu_map))
continue;
for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
claim_allocations(i, sd);
init_sched_groups_capacity(i, sd);
}
}
/* Attach the domains */
rcu_read_lock();
for_each_cpu(i, cpu_map) {
sd = *per_cpu_ptr(d.sd, i);
cpu_attach_domain(sd, d.rd, i);
}
rcu_read_unlock();
ret = 0;
error:
__free_domain_allocs(&d, alloc_state, cpu_map);
return ret;
}
static cpumask_var_t *doms_cur; /* current sched domains */
static int ndoms_cur; /* number of sched domains in 'doms_cur' */
static struct sched_domain_attr *dattr_cur;
/* attribues of custom domains in 'doms_cur' */
/*
* Special case: If a kmalloc of a doms_cur partition (array of
* cpumask) fails, then fallback to a single sched domain,
* as determined by the single cpumask fallback_doms.
*/
static cpumask_var_t fallback_doms;
/*
* arch_update_cpu_topology lets virtualized architectures update the
* cpu core maps. It is supposed to return 1 if the topology changed
* or 0 if it stayed the same.
*/
int __weak arch_update_cpu_topology(void)
{
return 0;
}
cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
{
int i;
cpumask_var_t *doms;
doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
if (!doms)
return NULL;
for (i = 0; i < ndoms; i++) {
if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
free_sched_domains(doms, i);
return NULL;
}
}
return doms;
}
void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
{
unsigned int i;
for (i = 0; i < ndoms; i++)
free_cpumask_var(doms[i]);
kfree(doms);
}
/*
* Set up scheduler domains and groups. Callers must hold the hotplug lock.
* For now this just excludes isolated cpus, but could be used to
* exclude other special cases in the future.
*/
static int init_sched_domains(const struct cpumask *cpu_map)
{
int err;
arch_update_cpu_topology();
ndoms_cur = 1;
doms_cur = alloc_sched_domains(ndoms_cur);
if (!doms_cur)
doms_cur = &fallback_doms;
cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
err = build_sched_domains(doms_cur[0], NULL);
register_sched_domain_sysctl();
return err;
}
/*
* Detach sched domains from a group of cpus specified in cpu_map
* These cpus will now be attached to the NULL domain
*/
static void detach_destroy_domains(const struct cpumask *cpu_map)
{
int i;
rcu_read_lock();
for_each_cpu(i, cpu_map)
cpu_attach_domain(NULL, &def_root_domain, i);
rcu_read_unlock();
}
/* handle null as "default" */
static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
struct sched_domain_attr *new, int idx_new)
{
struct sched_domain_attr tmp;
/* fast path */
if (!new && !cur)
return 1;
tmp = SD_ATTR_INIT;
return !memcmp(cur ? (cur + idx_cur) : &tmp,
new ? (new + idx_new) : &tmp,
sizeof(struct sched_domain_attr));
}
/*
* Partition sched domains as specified by the 'ndoms_new'
* cpumasks in the array doms_new[] of cpumasks. This compares
* doms_new[] to the current sched domain partitioning, doms_cur[].
* It destroys each deleted domain and builds each new domain.
*
* 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
* The masks don't intersect (don't overlap.) We should setup one
* sched domain for each mask. CPUs not in any of the cpumasks will
* not be load balanced. If the same cpumask appears both in the
* current 'doms_cur' domains and in the new 'doms_new', we can leave
* it as it is.
*
* The passed in 'doms_new' should be allocated using
* alloc_sched_domains. This routine takes ownership of it and will
* free_sched_domains it when done with it. If the caller failed the
* alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
* and partition_sched_domains() will fallback to the single partition
* 'fallback_doms', it also forces the domains to be rebuilt.
*
* If doms_new == NULL it will be replaced with cpu_online_mask.
* ndoms_new == 0 is a special case for destroying existing domains,
* and it will not create the default domain.
*
* Call with hotplug lock held
*/
void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
struct sched_domain_attr *dattr_new)
{
int i, j, n;
int new_topology;
mutex_lock(&sched_domains_mutex);
/* always unregister in case we don't destroy any domains */
unregister_sched_domain_sysctl();
/* Let architecture update cpu core mappings. */
new_topology = arch_update_cpu_topology();
n = doms_new ? ndoms_new : 0;
/* Destroy deleted domains */
for (i = 0; i < ndoms_cur; i++) {
for (j = 0; j < n && !new_topology; j++) {
if (cpumask_equal(doms_cur[i], doms_new[j])
&& dattrs_equal(dattr_cur, i, dattr_new, j))
goto match1;
}
/* no match - a current sched domain not in new doms_new[] */
detach_destroy_domains(doms_cur[i]);
match1:
;
}
n = ndoms_cur;
if (doms_new == NULL) {
n = 0;
doms_new = &fallback_doms;
cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
WARN_ON_ONCE(dattr_new);
}
/* Build new domains */
for (i = 0; i < ndoms_new; i++) {
for (j = 0; j < n && !new_topology; j++) {
if (cpumask_equal(doms_new[i], doms_cur[j])
&& dattrs_equal(dattr_new, i, dattr_cur, j))
goto match2;
}
/* no match - add a new doms_new */
build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
match2:
;
}
/* Remember the new sched domains */
if (doms_cur != &fallback_doms)
free_sched_domains(doms_cur, ndoms_cur);
kfree(dattr_cur); /* kfree(NULL) is safe */
doms_cur = doms_new;
dattr_cur = dattr_new;
ndoms_cur = ndoms_new;
register_sched_domain_sysctl();
mutex_unlock(&sched_domains_mutex);
}
static int num_cpus_frozen; /* used to mark begin/end of suspend/resume */
/*
* Update cpusets according to cpu_active mask. If cpusets are
* disabled, cpuset_update_active_cpus() becomes a simple wrapper
* around partition_sched_domains().
*
* If we come here as part of a suspend/resume, don't touch cpusets because we
* want to restore it back to its original state upon resume anyway.
*/
static void cpuset_cpu_active(void)
{
if (cpuhp_tasks_frozen) {
/*
* num_cpus_frozen tracks how many CPUs are involved in suspend
* resume sequence. As long as this is not the last online
* operation in the resume sequence, just build a single sched
* domain, ignoring cpusets.
*/
num_cpus_frozen--;
if (likely(num_cpus_frozen)) {
partition_sched_domains(1, NULL, NULL);
return;
}
/*
* This is the last CPU online operation. So fall through and
* restore the original sched domains by considering the
* cpuset configurations.
*/
}
cpuset_update_active_cpus(true);
}
static int cpuset_cpu_inactive(unsigned int cpu)
{
unsigned long flags;
struct dl_bw *dl_b;
bool overflow;
int cpus;
if (!cpuhp_tasks_frozen) {
rcu_read_lock_sched();
dl_b = dl_bw_of(cpu);
raw_spin_lock_irqsave(&dl_b->lock, flags);
cpus = dl_bw_cpus(cpu);
overflow = __dl_overflow(dl_b, cpus, 0, 0);
raw_spin_unlock_irqrestore(&dl_b->lock, flags);
rcu_read_unlock_sched();
if (overflow)
return -EBUSY;
cpuset_update_active_cpus(false);
} else {
num_cpus_frozen++;
partition_sched_domains(1, NULL, NULL);
}
return 0;
}
int sched_cpu_activate(unsigned int cpu)
{
struct rq *rq = cpu_rq(cpu);
unsigned long flags;
set_cpu_active(cpu, true);
if (sched_smp_initialized) {
sched_domains_numa_masks_set(cpu);
cpuset_cpu_active();
}
/*
* Put the rq online, if not already. This happens:
*
* 1) In the early boot process, because we build the real domains
* after all cpus have been brought up.
*
* 2) At runtime, if cpuset_cpu_active() fails to rebuild the
* domains.
*/
raw_spin_lock_irqsave(&rq->lock, flags);
if (rq->rd) {
BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
set_rq_online(rq);
}
raw_spin_unlock_irqrestore(&rq->lock, flags);
update_max_interval();
return 0;
}
int sched_cpu_deactivate(unsigned int cpu)
{
int ret;
set_cpu_active(cpu, false);
/*
* We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
* users of this state to go away such that all new such users will
* observe it.
*
* For CONFIG_PREEMPT we have preemptible RCU and its sync_rcu() might
* not imply sync_sched(), so wait for both.
*
* Do sync before park smpboot threads to take care the rcu boost case.
*/
if (IS_ENABLED(CONFIG_PREEMPT))
synchronize_rcu_mult(call_rcu, call_rcu_sched);
else
synchronize_rcu();
if (!sched_smp_initialized)
return 0;
ret = cpuset_cpu_inactive(cpu);
if (ret) {
set_cpu_active(cpu, true);
return ret;
}
sched_domains_numa_masks_clear(cpu);
return 0;
}
static void sched_rq_cpu_starting(unsigned int cpu)
{
struct rq *rq = cpu_rq(cpu);
rq->calc_load_update = calc_load_update;
account_reset_rq(rq);
update_max_interval();
}
int sched_cpu_starting(unsigned int cpu)
{
set_cpu_rq_start_time(cpu);
sched_rq_cpu_starting(cpu);
return 0;
}
#ifdef CONFIG_HOTPLUG_CPU
int sched_cpu_dying(unsigned int cpu)
{
struct rq *rq = cpu_rq(cpu);
unsigned long flags;
/* Handle pending wakeups and then migrate everything off */
sched_ttwu_pending();
raw_spin_lock_irqsave(&rq->lock, flags);
if (rq->rd) {
BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
set_rq_offline(rq);
}
migrate_tasks(rq);
BUG_ON(rq->nr_running != 1);
raw_spin_unlock_irqrestore(&rq->lock, flags);
calc_load_migrate(rq);
update_max_interval();
nohz_balance_exit_idle(cpu);
hrtick_clear(rq);
return 0;
}
#endif
void __init sched_init_smp(void)
{
cpumask_var_t non_isolated_cpus;
alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
sched_init_numa();
/*
* There's no userspace yet to cause hotplug operations; hence all the
* cpu masks are stable and all blatant races in the below code cannot
* happen.
*/
mutex_lock(&sched_domains_mutex);
init_sched_domains(cpu_active_mask);
cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
if (cpumask_empty(non_isolated_cpus))
cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
mutex_unlock(&sched_domains_mutex);
/* Move init over to a non-isolated CPU */
if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
BUG();
sched_init_granularity();
free_cpumask_var(non_isolated_cpus);
init_sched_rt_class();
init_sched_dl_class();
sched_smp_initialized = true;
}
static int __init migration_init(void)
{
sched_rq_cpu_starting(smp_processor_id());
return 0;
}
early_initcall(migration_init);
#else
void __init sched_init_smp(void)
{
sched_init_granularity();
}
#endif /* CONFIG_SMP */
int in_sched_functions(unsigned long addr)
{
return in_lock_functions(addr) ||
(addr >= (unsigned long)__sched_text_start
&& addr < (unsigned long)__sched_text_end);
}
#ifdef CONFIG_CGROUP_SCHED
/*
* Default task group.
* Every task in system belongs to this group at bootup.
*/
struct task_group root_task_group;
LIST_HEAD(task_groups);
/* Cacheline aligned slab cache for task_group */
static struct kmem_cache *task_group_cache __read_mostly;
#endif
DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
void __init sched_init(void)
{
int i, j;
unsigned long alloc_size = 0, ptr;
#ifdef CONFIG_FAIR_GROUP_SCHED
alloc_size += 2 * nr_cpu_ids * sizeof(void **);
#endif
#ifdef CONFIG_RT_GROUP_SCHED
alloc_size += 2 * nr_cpu_ids * sizeof(void **);
#endif
if (alloc_size) {
ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
#ifdef CONFIG_FAIR_GROUP_SCHED
root_task_group.se = (struct sched_entity **)ptr;
ptr += nr_cpu_ids * sizeof(void **);
root_task_group.cfs_rq = (struct cfs_rq **)ptr;
ptr += nr_cpu_ids * sizeof(void **);
#endif /* CONFIG_FAIR_GROUP_SCHED */
#ifdef CONFIG_RT_GROUP_SCHED
root_task_group.rt_se = (struct sched_rt_entity **)ptr;
ptr += nr_cpu_ids * sizeof(void **);
root_task_group.rt_rq = (struct rt_rq **)ptr;
ptr += nr_cpu_ids * sizeof(void **);
#endif /* CONFIG_RT_GROUP_SCHED */
}
#ifdef CONFIG_CPUMASK_OFFSTACK
for_each_possible_cpu(i) {
per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
cpumask_size(), GFP_KERNEL, cpu_to_node(i));
}
#endif /* CONFIG_CPUMASK_OFFSTACK */
init_rt_bandwidth(&def_rt_bandwidth,
global_rt_period(), global_rt_runtime());
init_dl_bandwidth(&def_dl_bandwidth,
global_rt_period(), global_rt_runtime());
#ifdef CONFIG_SMP
init_defrootdomain();
#endif
#ifdef CONFIG_RT_GROUP_SCHED
init_rt_bandwidth(&root_task_group.rt_bandwidth,
global_rt_period(), global_rt_runtime());
#endif /* CONFIG_RT_GROUP_SCHED */
#ifdef CONFIG_CGROUP_SCHED
task_group_cache = KMEM_CACHE(task_group, 0);
list_add(&root_task_group.list, &task_groups);
INIT_LIST_HEAD(&root_task_group.children);
INIT_LIST_HEAD(&root_task_group.siblings);
autogroup_init(&init_task);
#endif /* CONFIG_CGROUP_SCHED */
for_each_possible_cpu(i) {
struct rq *rq;
rq = cpu_rq(i);
raw_spin_lock_init(&rq->lock);
rq->nr_running = 0;
rq->calc_load_active = 0;
rq->calc_load_update = jiffies + LOAD_FREQ;
init_cfs_rq(&rq->cfs);
init_rt_rq(&rq->rt);
init_dl_rq(&rq->dl);
#ifdef CONFIG_FAIR_GROUP_SCHED
root_task_group.shares = ROOT_TASK_GROUP_LOAD;
INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
/*
* How much cpu bandwidth does root_task_group get?
*
* In case of task-groups formed thr' the cgroup filesystem, it
* gets 100% of the cpu resources in the system. This overall
* system cpu resource is divided among the tasks of
* root_task_group and its child task-groups in a fair manner,
* based on each entity's (task or task-group's) weight
* (se->load.weight).
*
* In other words, if root_task_group has 10 tasks of weight
* 1024) and two child groups A0 and A1 (of weight 1024 each),
* then A0's share of the cpu resource is:
*
* A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
*
* We achieve this by letting root_task_group's tasks sit
* directly in rq->cfs (i.e root_task_group->se[] = NULL).
*/
init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
#endif /* CONFIG_FAIR_GROUP_SCHED */
rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
#ifdef CONFIG_RT_GROUP_SCHED
init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
#endif
for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
rq->cpu_load[j] = 0;
#ifdef CONFIG_SMP
rq->sd = NULL;
rq->rd = NULL;
rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
rq->balance_callback = NULL;
rq->active_balance = 0;
rq->next_balance = jiffies;
rq->push_cpu = 0;
rq->cpu = i;
rq->online = 0;
rq->idle_stamp = 0;
rq->avg_idle = 2*sysctl_sched_migration_cost;
rq->max_idle_balance_cost = sysctl_sched_migration_cost;
INIT_LIST_HEAD(&rq->cfs_tasks);
rq_attach_root(rq, &def_root_domain);
#ifdef CONFIG_NO_HZ_COMMON
rq->last_load_update_tick = jiffies;
rq->nohz_flags = 0;
#endif
#ifdef CONFIG_NO_HZ_FULL
rq->last_sched_tick = 0;
#endif
#endif /* CONFIG_SMP */
init_rq_hrtick(rq);
atomic_set(&rq->nr_iowait, 0);
}
set_load_weight(&init_task);
#ifdef CONFIG_PREEMPT_NOTIFIERS
INIT_HLIST_HEAD(&init_task.preempt_notifiers);
#endif
/*
* The boot idle thread does lazy MMU switching as well:
*/
atomic_inc(&init_mm.mm_count);
enter_lazy_tlb(&init_mm, current);
/*
* During early bootup we pretend to be a normal task:
*/
current->sched_class = &fair_sched_class;
/*
* Make us the idle thread. Technically, schedule() should not be
* called from this thread, however somewhere below it might be,
* but because we are the idle thread, we just pick up running again
* when this runqueue becomes "idle".
*/
init_idle(current, smp_processor_id());
calc_load_update = jiffies + LOAD_FREQ;
#ifdef CONFIG_SMP
zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
/* May be allocated at isolcpus cmdline parse time */
if (cpu_isolated_map == NULL)
zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
idle_thread_set_boot_cpu();
set_cpu_rq_start_time(smp_processor_id());
#endif
init_sched_fair_class();
init_schedstats();
scheduler_running = 1;
}
#ifdef CONFIG_DEBUG_ATOMIC_SLEEP
static inline int preempt_count_equals(int preempt_offset)
{
int nested = preempt_count() + rcu_preempt_depth();
return (nested == preempt_offset);
}
void __might_sleep(const char *file, int line, int preempt_offset)
{
/*
* Blocking primitives will set (and therefore destroy) current->state,
* since we will exit with TASK_RUNNING make sure we enter with it,
* otherwise we will destroy state.
*/
WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
"do not call blocking ops when !TASK_RUNNING; "
"state=%lx set at [<%p>] %pS\n",
current->state,
(void *)current->task_state_change,
(void *)current->task_state_change);
___might_sleep(file, line, preempt_offset);
}
EXPORT_SYMBOL(__might_sleep);
void ___might_sleep(const char *file, int line, int preempt_offset)
{
static unsigned long prev_jiffy; /* ratelimiting */
rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */
if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
!is_idle_task(current)) ||
system_state != SYSTEM_RUNNING || oops_in_progress)
return;
if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
return;
prev_jiffy = jiffies;
printk(KERN_ERR
"BUG: sleeping function called from invalid context at %s:%d\n",
file, line);
printk(KERN_ERR
"in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
in_atomic(), irqs_disabled(),
current->pid, current->comm);
if (task_stack_end_corrupted(current))
printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
debug_show_held_locks(current);
if (irqs_disabled())
print_irqtrace_events(current);
#ifdef CONFIG_DEBUG_PREEMPT
if (!preempt_count_equals(preempt_offset)) {
pr_err("Preemption disabled at:");
print_ip_sym(current->preempt_disable_ip);
pr_cont("\n");
}
#endif
dump_stack();
}
EXPORT_SYMBOL(___might_sleep);
#endif
#ifdef CONFIG_MAGIC_SYSRQ
void normalize_rt_tasks(void)
{
struct task_struct *g, *p;
struct sched_attr attr = {
.sched_policy = SCHED_NORMAL,
};
read_lock(&tasklist_lock);
for_each_process_thread(g, p) {
/*
* Only normalize user tasks:
*/
if (p->flags & PF_KTHREAD)
continue;
p->se.exec_start = 0;
#ifdef CONFIG_SCHEDSTATS
p->se.statistics.wait_start = 0;
p->se.statistics.sleep_start = 0;
p->se.statistics.block_start = 0;
#endif
if (!dl_task(p) && !rt_task(p)) {
/*
* Renice negative nice level userspace
* tasks back to 0:
*/
if (task_nice(p) < 0)
set_user_nice(p, 0);
continue;
}
__sched_setscheduler(p, &attr, false, false);
}
read_unlock(&tasklist_lock);
}
#endif /* CONFIG_MAGIC_SYSRQ */
#if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
/*
* These functions are only useful for the IA64 MCA handling, or kdb.
*
* They can only be called when the whole system has been
* stopped - every CPU needs to be quiescent, and no scheduling
* activity can take place. Using them for anything else would
* be a serious bug, and as a result, they aren't even visible
* under any other configuration.
*/
/**
* curr_task - return the current task for a given cpu.
* @cpu: the processor in question.
*
* ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
*
* Return: The current task for @cpu.
*/
struct task_struct *curr_task(int cpu)
{
return cpu_curr(cpu);
}
#endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
#ifdef CONFIG_IA64
/**
* set_curr_task - set the current task for a given cpu.
* @cpu: the processor in question.
* @p: the task pointer to set.
*
* Description: This function must only be used when non-maskable interrupts
* are serviced on a separate stack. It allows the architecture to switch the
* notion of the current task on a cpu in a non-blocking manner. This function
* must be called with all CPU's synchronized, and interrupts disabled, the
* and caller must save the original value of the current task (see
* curr_task() above) and restore that value before reenabling interrupts and
* re-starting the system.
*
* ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
*/
void set_curr_task(int cpu, struct task_struct *p)
{
cpu_curr(cpu) = p;
}
#endif
#ifdef CONFIG_CGROUP_SCHED
/* task_group_lock serializes the addition/removal of task groups */
static DEFINE_SPINLOCK(task_group_lock);
static void sched_free_group(struct task_group *tg)
{
free_fair_sched_group(tg);
free_rt_sched_group(tg);
autogroup_free(tg);
kmem_cache_free(task_group_cache, tg);
}
/* allocate runqueue etc for a new task group */
struct task_group *sched_create_group(struct task_group *parent)
{
struct task_group *tg;
tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
if (!tg)
return ERR_PTR(-ENOMEM);
if (!alloc_fair_sched_group(tg, parent))
goto err;
if (!alloc_rt_sched_group(tg, parent))
goto err;
return tg;
err:
sched_free_group(tg);
return ERR_PTR(-ENOMEM);
}
void sched_online_group(struct task_group *tg, struct task_group *parent)
{
unsigned long flags;
spin_lock_irqsave(&task_group_lock, flags);
list_add_rcu(&tg->list, &task_groups);
WARN_ON(!parent); /* root should already exist */
tg->parent = parent;
INIT_LIST_HEAD(&tg->children);
list_add_rcu(&tg->siblings, &parent->children);
spin_unlock_irqrestore(&task_group_lock, flags);
}
/* rcu callback to free various structures associated with a task group */
static void sched_free_group_rcu(struct rcu_head *rhp)
{
/* now it should be safe to free those cfs_rqs */
sched_free_group(container_of(rhp, struct task_group, rcu));
}
void sched_destroy_group(struct task_group *tg)
{
/* wait for possible concurrent references to cfs_rqs complete */
call_rcu(&tg->rcu, sched_free_group_rcu);
}
void sched_offline_group(struct task_group *tg)
{
unsigned long flags;
/* end participation in shares distribution */
unregister_fair_sched_group(tg);
spin_lock_irqsave(&task_group_lock, flags);
list_del_rcu(&tg->list);
list_del_rcu(&tg->siblings);
spin_unlock_irqrestore(&task_group_lock, flags);
}
/* change task's runqueue when it moves between groups.
* The caller of this function should have put the task in its new group
* by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
* reflect its new group.
*/
void sched_move_task(struct task_struct *tsk)
{
struct task_group *tg;
int queued, running;
struct rq_flags rf;
struct rq *rq;
rq = task_rq_lock(tsk, &rf);
running = task_current(rq, tsk);
queued = task_on_rq_queued(tsk);
if (queued)
dequeue_task(rq, tsk, DEQUEUE_SAVE | DEQUEUE_MOVE);
if (unlikely(running))
put_prev_task(rq, tsk);
/*
* All callers are synchronized by task_rq_lock(); we do not use RCU
* which is pointless here. Thus, we pass "true" to task_css_check()
* to prevent lockdep warnings.
*/
tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
struct task_group, css);
tg = autogroup_task_group(tsk, tg);
tsk->sched_task_group = tg;
#ifdef CONFIG_FAIR_GROUP_SCHED
if (tsk->sched_class->task_move_group)
tsk->sched_class->task_move_group(tsk);
else
#endif
set_task_rq(tsk, task_cpu(tsk));
if (unlikely(running))
tsk->sched_class->set_curr_task(rq);
if (queued)
enqueue_task(rq, tsk, ENQUEUE_RESTORE | ENQUEUE_MOVE);
task_rq_unlock(rq, tsk, &rf);
}
#endif /* CONFIG_CGROUP_SCHED */
#ifdef CONFIG_RT_GROUP_SCHED
/*
* Ensure that the real time constraints are schedulable.
*/
static DEFINE_MUTEX(rt_constraints_mutex);
/* Must be called with tasklist_lock held */
static inline int tg_has_rt_tasks(struct task_group *tg)
{
struct task_struct *g, *p;
/*
* Autogroups do not have RT tasks; see autogroup_create().
*/
if (task_group_is_autogroup(tg))
return 0;
for_each_process_thread(g, p) {
if (rt_task(p) && task_group(p) == tg)
return 1;
}
return 0;
}
struct rt_schedulable_data {
struct task_group *tg;
u64 rt_period;
u64 rt_runtime;
};
static int tg_rt_schedulable(struct task_group *tg, void *data)
{
struct rt_schedulable_data *d = data;
struct task_group *child;
unsigned long total, sum = 0;
u64 period, runtime;
period = ktime_to_ns(tg->rt_bandwidth.rt_period);
runtime = tg->rt_bandwidth.rt_runtime;
if (tg == d->tg) {
period = d->rt_period;
runtime = d->rt_runtime;
}
/*
* Cannot have more runtime than the period.
*/
if (runtime > period && runtime != RUNTIME_INF)
return -EINVAL;
/*
* Ensure we don't starve existing RT tasks.
*/
if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
return -EBUSY;
total = to_ratio(period, runtime);
/*
* Nobody can have more than the global setting allows.
*/
if (total > to_ratio(global_rt_period(), global_rt_runtime()))
return -EINVAL;
/*
* The sum of our children's runtime should not exceed our own.
*/
list_for_each_entry_rcu(child, &tg->children, siblings) {
period = ktime_to_ns(child->rt_bandwidth.rt_period);
runtime = child->rt_bandwidth.rt_runtime;
if (child == d->tg) {
period = d->rt_period;
runtime = d->rt_runtime;
}
sum += to_ratio(period, runtime);
}
if (sum > total)
return -EINVAL;
return 0;
}
static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
{
int ret;
struct rt_schedulable_data data = {
.tg = tg,
.rt_period = period,
.rt_runtime = runtime,
};
rcu_read_lock();
ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data);
rcu_read_unlock();
return ret;
}
static int tg_set_rt_bandwidth(struct task_group *tg,
u64 rt_period, u64 rt_runtime)
{
int i, err = 0;
/*
* Disallowing the root group RT runtime is BAD, it would disallow the
* kernel creating (and or operating) RT threads.
*/
if (tg == &root_task_group && rt_runtime == 0)
return -EINVAL;
/* No period doesn't make any sense. */
if (rt_period == 0)
return -EINVAL;
mutex_lock(&rt_constraints_mutex);
read_lock(&tasklist_lock);
err = __rt_schedulable(tg, rt_period, rt_runtime);
if (err)
goto unlock;
raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
tg->rt_bandwidth.rt_runtime = rt_runtime;
for_each_possible_cpu(i) {
struct rt_rq *rt_rq = tg->rt_rq[i];
raw_spin_lock(&rt_rq->rt_runtime_lock);
rt_rq->rt_runtime = rt_runtime;
raw_spin_unlock(&rt_rq->rt_runtime_lock);
}
raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
unlock:
read_unlock(&tasklist_lock);
mutex_unlock(&rt_constraints_mutex);
return err;
}
static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
{
u64 rt_runtime, rt_period;
rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
if (rt_runtime_us < 0)
rt_runtime = RUNTIME_INF;
return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
}
static long sched_group_rt_runtime(struct task_group *tg)
{
u64 rt_runtime_us;
if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
return -1;
rt_runtime_us = tg->rt_bandwidth.rt_runtime;
do_div(rt_runtime_us, NSEC_PER_USEC);
return rt_runtime_us;
}
static int sched_group_set_rt_period(struct task_group *tg, u64 rt_period_us)
{
u64 rt_runtime, rt_period;
rt_period = rt_period_us * NSEC_PER_USEC;
rt_runtime = tg->rt_bandwidth.rt_runtime;
return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
}
static long sched_group_rt_period(struct task_group *tg)
{
u64 rt_period_us;
rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
do_div(rt_period_us, NSEC_PER_USEC);
return rt_period_us;
}
#endif /* CONFIG_RT_GROUP_SCHED */
#ifdef CONFIG_RT_GROUP_SCHED
static int sched_rt_global_constraints(void)
{
int ret = 0;
mutex_lock(&rt_constraints_mutex);
read_lock(&tasklist_lock);
ret = __rt_schedulable(NULL, 0, 0);
read_unlock(&tasklist_lock);
mutex_unlock(&rt_constraints_mutex);
return ret;
}
static int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
{
/* Don't accept realtime tasks when there is no way for them to run */
if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
return 0;
return 1;
}
#else /* !CONFIG_RT_GROUP_SCHED */
static int sched_rt_global_constraints(void)
{
unsigned long flags;
int i;
raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
for_each_possible_cpu(i) {
struct rt_rq *rt_rq = &cpu_rq(i)->rt;
raw_spin_lock(&rt_rq->rt_runtime_lock);
rt_rq->rt_runtime = global_rt_runtime();
raw_spin_unlock(&rt_rq->rt_runtime_lock);
}
raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
return 0;
}
#endif /* CONFIG_RT_GROUP_SCHED */
static int sched_dl_global_validate(void)
{
u64 runtime = global_rt_runtime();
u64 period = global_rt_period();
u64 new_bw = to_ratio(period, runtime);
struct dl_bw *dl_b;
int cpu, ret = 0;
unsigned long flags;
/*
* Here we want to check the bandwidth not being set to some
* value smaller than the currently allocated bandwidth in
* any of the root_domains.
*
* FIXME: Cycling on all the CPUs is overdoing, but simpler than
* cycling on root_domains... Discussion on different/better
* solutions is welcome!
*/
for_each_possible_cpu(cpu) {
rcu_read_lock_sched();
dl_b = dl_bw_of(cpu);
raw_spin_lock_irqsave(&dl_b->lock, flags);
if (new_bw < dl_b->total_bw)
ret = -EBUSY;
raw_spin_unlock_irqrestore(&dl_b->lock, flags);
rcu_read_unlock_sched();
if (ret)
break;
}
return ret;
}
static void sched_dl_do_global(void)
{
u64 new_bw = -1;
struct dl_bw *dl_b;
int cpu;
unsigned long flags;
def_dl_bandwidth.dl_period = global_rt_period();
def_dl_bandwidth.dl_runtime = global_rt_runtime();
if (global_rt_runtime() != RUNTIME_INF)
new_bw = to_ratio(global_rt_period(), global_rt_runtime());
/*
* FIXME: As above...
*/
for_each_possible_cpu(cpu) {
rcu_read_lock_sched();
dl_b = dl_bw_of(cpu);
raw_spin_lock_irqsave(&dl_b->lock, flags);
dl_b->bw = new_bw;
raw_spin_unlock_irqrestore(&dl_b->lock, flags);
rcu_read_unlock_sched();
}
}
static int sched_rt_global_validate(void)
{
if (sysctl_sched_rt_period <= 0)
return -EINVAL;
if ((sysctl_sched_rt_runtime != RUNTIME_INF) &&
(sysctl_sched_rt_runtime > sysctl_sched_rt_period))
return -EINVAL;
return 0;
}
static void sched_rt_do_global(void)
{
def_rt_bandwidth.rt_runtime = global_rt_runtime();
def_rt_bandwidth.rt_period = ns_to_ktime(global_rt_period());
}
int sched_rt_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int old_period, old_runtime;
static DEFINE_MUTEX(mutex);
int ret;
mutex_lock(&mutex);
old_period = sysctl_sched_rt_period;
old_runtime = sysctl_sched_rt_runtime;
ret = proc_dointvec(table, write, buffer, lenp, ppos);
if (!ret && write) {
ret = sched_rt_global_validate();
if (ret)
goto undo;
ret = sched_dl_global_validate();
if (ret)
goto undo;
ret = sched_rt_global_constraints();
if (ret)
goto undo;
sched_rt_do_global();
sched_dl_do_global();
}
if (0) {
undo:
sysctl_sched_rt_period = old_period;
sysctl_sched_rt_runtime = old_runtime;
}
mutex_unlock(&mutex);
return ret;
}
int sched_rr_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int ret;
static DEFINE_MUTEX(mutex);
mutex_lock(&mutex);
ret = proc_dointvec(table, write, buffer, lenp, ppos);
/* make sure that internally we keep jiffies */
/* also, writing zero resets timeslice to default */
if (!ret && write) {
sched_rr_timeslice = sched_rr_timeslice <= 0 ?
RR_TIMESLICE : msecs_to_jiffies(sched_rr_timeslice);
}
mutex_unlock(&mutex);
return ret;
}
#ifdef CONFIG_CGROUP_SCHED
static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
{
return css ? container_of(css, struct task_group, css) : NULL;
}
static struct cgroup_subsys_state *
cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
{
struct task_group *parent = css_tg(parent_css);
struct task_group *tg;
if (!parent) {
/* This is early initialization for the top cgroup */
return &root_task_group.css;
}
tg = sched_create_group(parent);
if (IS_ERR(tg))
return ERR_PTR(-ENOMEM);
sched_online_group(tg, parent);
return &tg->css;
}
static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
{
struct task_group *tg = css_tg(css);
sched_offline_group(tg);
}
static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
{
struct task_group *tg = css_tg(css);
/*
* Relies on the RCU grace period between css_released() and this.
*/
sched_free_group(tg);
}
static void cpu_cgroup_fork(struct task_struct *task)
{
sched_move_task(task);
}
static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
{
struct task_struct *task;
struct cgroup_subsys_state *css;
cgroup_taskset_for_each(task, css, tset) {
#ifdef CONFIG_RT_GROUP_SCHED
if (!sched_rt_can_attach(css_tg(css), task))
return -EINVAL;
#else
/* We don't support RT-tasks being in separate groups */
if (task->sched_class != &fair_sched_class)
return -EINVAL;
#endif
}
return 0;
}
static void cpu_cgroup_attach(struct cgroup_taskset *tset)
{
struct task_struct *task;
struct cgroup_subsys_state *css;
cgroup_taskset_for_each(task, css, tset)
sched_move_task(task);
}
#ifdef CONFIG_FAIR_GROUP_SCHED
static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
struct cftype *cftype, u64 shareval)
{
return sched_group_set_shares(css_tg(css), scale_load(shareval));
}
static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
struct cftype *cft)
{
struct task_group *tg = css_tg(css);
return (u64) scale_load_down(tg->shares);
}
#ifdef CONFIG_CFS_BANDWIDTH
static DEFINE_MUTEX(cfs_constraints_mutex);
const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
{
int i, ret = 0, runtime_enabled, runtime_was_enabled;
struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
if (tg == &root_task_group)
return -EINVAL;
/*
* Ensure we have at some amount of bandwidth every period. This is
* to prevent reaching a state of large arrears when throttled via
* entity_tick() resulting in prolonged exit starvation.
*/
if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
return -EINVAL;
/*
* Likewise, bound things on the otherside by preventing insane quota
* periods. This also allows us to normalize in computing quota
* feasibility.
*/
if (period > max_cfs_quota_period)
return -EINVAL;
/*
* Prevent race between setting of cfs_rq->runtime_enabled and
* unthrottle_offline_cfs_rqs().
*/
get_online_cpus();
mutex_lock(&cfs_constraints_mutex);
ret = __cfs_schedulable(tg, period, quota);
if (ret)
goto out_unlock;
runtime_enabled = quota != RUNTIME_INF;
runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
/*
* If we need to toggle cfs_bandwidth_used, off->on must occur
* before making related changes, and on->off must occur afterwards
*/
if (runtime_enabled && !runtime_was_enabled)
cfs_bandwidth_usage_inc();
raw_spin_lock_irq(&cfs_b->lock);
cfs_b->period = ns_to_ktime(period);
cfs_b->quota = quota;
__refill_cfs_bandwidth_runtime(cfs_b);
/* restart the period timer (if active) to handle new period expiry */
if (runtime_enabled)
start_cfs_bandwidth(cfs_b);
raw_spin_unlock_irq(&cfs_b->lock);
for_each_online_cpu(i) {
struct cfs_rq *cfs_rq = tg->cfs_rq[i];
struct rq *rq = cfs_rq->rq;
raw_spin_lock_irq(&rq->lock);
cfs_rq->runtime_enabled = runtime_enabled;
cfs_rq->runtime_remaining = 0;
if (cfs_rq->throttled)
unthrottle_cfs_rq(cfs_rq);
raw_spin_unlock_irq(&rq->lock);
}
if (runtime_was_enabled && !runtime_enabled)
cfs_bandwidth_usage_dec();
out_unlock:
mutex_unlock(&cfs_constraints_mutex);
put_online_cpus();
return ret;
}
int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
{
u64 quota, period;
period = ktime_to_ns(tg->cfs_bandwidth.period);
if (cfs_quota_us < 0)
quota = RUNTIME_INF;
else
quota = (u64)cfs_quota_us * NSEC_PER_USEC;
return tg_set_cfs_bandwidth(tg, period, quota);
}
long tg_get_cfs_quota(struct task_group *tg)
{
u64 quota_us;
if (tg->cfs_bandwidth.quota == RUNTIME_INF)
return -1;
quota_us = tg->cfs_bandwidth.quota;
do_div(quota_us, NSEC_PER_USEC);
return quota_us;
}
int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
{
u64 quota, period;
period = (u64)cfs_period_us * NSEC_PER_USEC;
quota = tg->cfs_bandwidth.quota;
return tg_set_cfs_bandwidth(tg, period, quota);
}
long tg_get_cfs_period(struct task_group *tg)
{
u64 cfs_period_us;
cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
do_div(cfs_period_us, NSEC_PER_USEC);
return cfs_period_us;
}
static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
struct cftype *cft)
{
return tg_get_cfs_quota(css_tg(css));
}
static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
struct cftype *cftype, s64 cfs_quota_us)
{
return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
}
static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
struct cftype *cft)
{
return tg_get_cfs_period(css_tg(css));
}
static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
struct cftype *cftype, u64 cfs_period_us)
{
return tg_set_cfs_period(css_tg(css), cfs_period_us);
}
struct cfs_schedulable_data {
struct task_group *tg;
u64 period, quota;
};
/*
* normalize group quota/period to be quota/max_period
* note: units are usecs
*/
static u64 normalize_cfs_quota(struct task_group *tg,
struct cfs_schedulable_data *d)
{
u64 quota, period;
if (tg == d->tg) {
period = d->period;
quota = d->quota;
} else {
period = tg_get_cfs_period(tg);
quota = tg_get_cfs_quota(tg);
}
/* note: these should typically be equivalent */
if (quota == RUNTIME_INF || quota == -1)
return RUNTIME_INF;
return to_ratio(period, quota);
}
static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
{
struct cfs_schedulable_data *d = data;
struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
s64 quota = 0, parent_quota = -1;
if (!tg->parent) {
quota = RUNTIME_INF;
} else {
struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
quota = normalize_cfs_quota(tg, d);
parent_quota = parent_b->hierarchical_quota;
/*
* ensure max(child_quota) <= parent_quota, inherit when no
* limit is set
*/
if (quota == RUNTIME_INF)
quota = parent_quota;
else if (parent_quota != RUNTIME_INF && quota > parent_quota)
return -EINVAL;
}
cfs_b->hierarchical_quota = quota;
return 0;
}
static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
{
int ret;
struct cfs_schedulable_data data = {
.tg = tg,
.period = period,
.quota = quota,
};
if (quota != RUNTIME_INF) {
do_div(data.period, NSEC_PER_USEC);
do_div(data.quota, NSEC_PER_USEC);
}
rcu_read_lock();
ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
rcu_read_unlock();
return ret;
}
static int cpu_stats_show(struct seq_file *sf, void *v)
{
struct task_group *tg = css_tg(seq_css(sf));
struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
return 0;
}
#endif /* CONFIG_CFS_BANDWIDTH */
#endif /* CONFIG_FAIR_GROUP_SCHED */
#ifdef CONFIG_RT_GROUP_SCHED
static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
struct cftype *cft, s64 val)
{
return sched_group_set_rt_runtime(css_tg(css), val);
}
static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
struct cftype *cft)
{
return sched_group_rt_runtime(css_tg(css));
}
static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
struct cftype *cftype, u64 rt_period_us)
{
return sched_group_set_rt_period(css_tg(css), rt_period_us);
}
static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
struct cftype *cft)
{
return sched_group_rt_period(css_tg(css));
}
#endif /* CONFIG_RT_GROUP_SCHED */
static struct cftype cpu_files[] = {
#ifdef CONFIG_FAIR_GROUP_SCHED
{
.name = "shares",
.read_u64 = cpu_shares_read_u64,
.write_u64 = cpu_shares_write_u64,
},
#endif
#ifdef CONFIG_CFS_BANDWIDTH
{
.name = "cfs_quota_us",
.read_s64 = cpu_cfs_quota_read_s64,
.write_s64 = cpu_cfs_quota_write_s64,
},
{
.name = "cfs_period_us",
.read_u64 = cpu_cfs_period_read_u64,
.write_u64 = cpu_cfs_period_write_u64,
},
{
.name = "stat",
.seq_show = cpu_stats_show,
},
#endif
#ifdef CONFIG_RT_GROUP_SCHED
{
.name = "rt_runtime_us",
.read_s64 = cpu_rt_runtime_read,
.write_s64 = cpu_rt_runtime_write,
},
{
.name = "rt_period_us",
.read_u64 = cpu_rt_period_read_uint,
.write_u64 = cpu_rt_period_write_uint,
},
#endif
{ } /* terminate */
};
struct cgroup_subsys cpu_cgrp_subsys = {
.css_alloc = cpu_cgroup_css_alloc,
.css_released = cpu_cgroup_css_released,
.css_free = cpu_cgroup_css_free,
.fork = cpu_cgroup_fork,
.can_attach = cpu_cgroup_can_attach,
.attach = cpu_cgroup_attach,
.legacy_cftypes = cpu_files,
.early_init = true,
};
#endif /* CONFIG_CGROUP_SCHED */
void dump_cpu_task(int cpu)
{
pr_info("Task dump for CPU %d:\n", cpu);
sched_show_task(cpu_curr(cpu));
}
/*
* Nice levels are multiplicative, with a gentle 10% change for every
* nice level changed. I.e. when a CPU-bound task goes from nice 0 to
* nice 1, it will get ~10% less CPU time than another CPU-bound task
* that remained on nice 0.
*
* The "10% effect" is relative and cumulative: from _any_ nice level,
* if you go up 1 level, it's -10% CPU usage, if you go down 1 level
* it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
* If a task goes up by ~10% and another task goes down by ~10% then
* the relative distance between them is ~25%.)
*/
const int sched_prio_to_weight[40] = {
/* -20 */ 88761, 71755, 56483, 46273, 36291,
/* -15 */ 29154, 23254, 18705, 14949, 11916,
/* -10 */ 9548, 7620, 6100, 4904, 3906,
/* -5 */ 3121, 2501, 1991, 1586, 1277,
/* 0 */ 1024, 820, 655, 526, 423,
/* 5 */ 335, 272, 215, 172, 137,
/* 10 */ 110, 87, 70, 56, 45,
/* 15 */ 36, 29, 23, 18, 15,
};
/*
* Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
*
* In cases where the weight does not change often, we can use the
* precalculated inverse to speed up arithmetics by turning divisions
* into multiplications:
*/
const u32 sched_prio_to_wmult[40] = {
/* -20 */ 48388, 59856, 76040, 92818, 118348,
/* -15 */ 147320, 184698, 229616, 287308, 360437,
/* -10 */ 449829, 563644, 704093, 875809, 1099582,
/* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
/* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
/* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
/* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
/* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4907_2 |
crossvul-cpp_data_good_4421_0 | // SPDX-License-Identifier: BSD-2-Clause
/*
Copyright (c) 2012-2016, Matthias Schiffer <mschiffer@universe-factory.net>
All rights reserved.
*/
/**
\file
Functions for receiving and handling packets
*/
#include "fastd.h"
#include "handshake.h"
#include "hash.h"
#include "peer.h"
#include "peer_hashtable.h"
#include <sys/uio.h>
/** Handles the ancillary control messages of received packets */
static inline void
handle_socket_control(struct msghdr *message, const fastd_socket_t *sock, fastd_peer_address_t *local_addr) {
memset(local_addr, 0, sizeof(fastd_peer_address_t));
const uint8_t *end = (const uint8_t *)message->msg_control + message->msg_controllen;
struct cmsghdr *cmsg;
for (cmsg = CMSG_FIRSTHDR(message); cmsg; cmsg = CMSG_NXTHDR(message, cmsg)) {
if ((const uint8_t *)cmsg + sizeof(*cmsg) > end)
return;
#ifdef USE_PKTINFO
if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_PKTINFO) {
struct in_pktinfo pktinfo;
if ((const uint8_t *)CMSG_DATA(cmsg) + sizeof(pktinfo) > end)
return;
memcpy(&pktinfo, CMSG_DATA(cmsg), sizeof(pktinfo));
local_addr->in.sin_family = AF_INET;
local_addr->in.sin_addr = pktinfo.ipi_addr;
local_addr->in.sin_port = fastd_peer_address_get_port(sock->bound_addr);
return;
}
#endif
if (cmsg->cmsg_level == IPPROTO_IPV6 && cmsg->cmsg_type == IPV6_PKTINFO) {
struct in6_pktinfo pktinfo;
if ((uint8_t *)CMSG_DATA(cmsg) + sizeof(pktinfo) > end)
return;
memcpy(&pktinfo, CMSG_DATA(cmsg), sizeof(pktinfo));
local_addr->in6.sin6_family = AF_INET6;
local_addr->in6.sin6_addr = pktinfo.ipi6_addr;
local_addr->in6.sin6_port = fastd_peer_address_get_port(sock->bound_addr);
if (IN6_IS_ADDR_LINKLOCAL(&local_addr->in6.sin6_addr))
local_addr->in6.sin6_scope_id = pktinfo.ipi6_ifindex;
return;
}
}
}
/** Initializes the hashtables used to keep track of handshakes sent to unknown peers */
void fastd_receive_unknown_init(void) {
size_t i, j;
for (i = 0; i < UNKNOWN_TABLES; i++) {
ctx.unknown_handshakes[i] = fastd_new0_array(UNKNOWN_ENTRIES, fastd_handshake_timeout_t);
for (j = 0; j < UNKNOWN_ENTRIES; j++)
ctx.unknown_handshakes[i][j].timeout = ctx.now;
}
fastd_random_bytes(&ctx.unknown_handshake_seed, sizeof(ctx.unknown_handshake_seed), false);
}
/** Frees the hashtables used to keep track of handshakes sent to unknown peers */
void fastd_receive_unknown_free(void) {
size_t i;
for (i = 0; i < UNKNOWN_TABLES; i++)
free(ctx.unknown_handshakes[i]);
}
/** Returns the i'th hash bucket for a peer address */
fastd_handshake_timeout_t *unknown_hash_entry(int64_t base, size_t i, const fastd_peer_address_t *addr) {
int64_t slice = base - i;
uint32_t hash = ctx.unknown_handshake_seed;
fastd_hash(&hash, &slice, sizeof(slice));
fastd_peer_address_hash(&hash, addr);
fastd_hash_final(&hash);
return &ctx.unknown_handshakes[(size_t)slice % UNKNOWN_TABLES][hash % UNKNOWN_ENTRIES];
}
/**
Checks if a handshake should be sent after an unexpected payload packet has been received
backoff_unknown() tries to avoid flooding hosts with handshakes.
*/
static bool backoff_unknown(const fastd_peer_address_t *addr) {
static const size_t table_interval = MIN_HANDSHAKE_INTERVAL / (UNKNOWN_TABLES - 1);
int64_t base = ctx.now / table_interval;
size_t first_empty = UNKNOWN_TABLES, i;
for (i = 0; i < UNKNOWN_TABLES; i++) {
const fastd_handshake_timeout_t *t = unknown_hash_entry(base, i, addr);
if (fastd_timed_out(t->timeout)) {
if (first_empty == UNKNOWN_TABLES)
first_empty = i;
continue;
}
if (!fastd_peer_address_equal(addr, &t->address))
continue;
pr_debug2("sent a handshake to unknown address %I a short time ago, not sending again", addr);
return true;
}
/* We didn't find the address in any of the hashtables, now insert it */
if (first_empty == UNKNOWN_TABLES)
first_empty = fastd_rand(0, UNKNOWN_TABLES);
fastd_handshake_timeout_t *t = unknown_hash_entry(base, first_empty, addr);
t->address = *addr;
t->timeout = ctx.now + MIN_HANDSHAKE_INTERVAL - first_empty * table_interval;
return false;
}
/** Handles a packet received from a known peer address */
static inline void handle_socket_receive_known(
fastd_socket_t *sock, const fastd_peer_address_t *local_addr, const fastd_peer_address_t *remote_addr,
fastd_peer_t *peer, fastd_buffer_t *buffer) {
if (!fastd_peer_may_connect(peer)) {
fastd_buffer_free(buffer);
return;
}
const uint8_t *packet_type = buffer->data;
switch (*packet_type) {
case PACKET_DATA:
if (!fastd_peer_is_established(peer) || !fastd_peer_address_equal(&peer->local_address, local_addr)) {
fastd_buffer_free(buffer);
if (!backoff_unknown(remote_addr)) {
pr_debug("unexpectedly received payload data from %P[%I]", peer, remote_addr);
conf.protocol->handshake_init(sock, local_addr, remote_addr, NULL);
}
return;
}
conf.protocol->handle_recv(peer, buffer);
break;
case PACKET_HANDSHAKE:
fastd_handshake_handle(sock, local_addr, remote_addr, peer, buffer);
break;
default:
fastd_buffer_free(buffer);
pr_debug("received packet with invalid type from %P[%I]", peer, remote_addr);
}
}
/** Determines if packets from known addresses are accepted */
static inline bool allow_unknown_peers(void) {
return ctx.has_floating || fastd_allow_verify();
}
/** Handles a packet received from an unknown address */
static inline void handle_socket_receive_unknown(
fastd_socket_t *sock, const fastd_peer_address_t *local_addr, const fastd_peer_address_t *remote_addr,
fastd_buffer_t *buffer) {
const uint8_t *packet_type = buffer->data;
switch (*packet_type) {
case PACKET_DATA:
fastd_buffer_free(buffer);
if (!backoff_unknown(remote_addr)) {
pr_debug("unexpectedly received payload data from unknown address %I", remote_addr);
conf.protocol->handshake_init(sock, local_addr, remote_addr, NULL);
}
break;
case PACKET_HANDSHAKE:
fastd_handshake_handle(sock, local_addr, remote_addr, NULL, buffer);
break;
default:
fastd_buffer_free(buffer);
pr_debug("received packet with invalid type from unknown address %I", remote_addr);
}
}
/** Handles a packet read from a socket */
static inline void handle_socket_receive(
fastd_socket_t *sock, const fastd_peer_address_t *local_addr, const fastd_peer_address_t *remote_addr,
fastd_buffer_t *buffer) {
fastd_peer_t *peer = NULL;
if (sock->peer) {
if (!fastd_peer_address_equal(&sock->peer->address, remote_addr)) {
fastd_buffer_free(buffer);
return;
}
peer = sock->peer;
} else {
peer = fastd_peer_hashtable_lookup(remote_addr);
}
if (peer) {
handle_socket_receive_known(sock, local_addr, remote_addr, peer, buffer);
} else if (allow_unknown_peers()) {
handle_socket_receive_unknown(sock, local_addr, remote_addr, buffer);
} else {
pr_debug("received packet from unknown peer %I", remote_addr);
fastd_buffer_free(buffer);
}
}
/** Reads a packet from a socket */
void fastd_receive(fastd_socket_t *sock) {
size_t max_len = max_size_t(fastd_max_payload(ctx.max_mtu) + conf.overhead, MAX_HANDSHAKE_SIZE);
fastd_buffer_t *buffer = fastd_buffer_alloc(max_len, conf.decrypt_headroom);
fastd_peer_address_t local_addr;
fastd_peer_address_t recvaddr;
struct iovec buffer_vec = { .iov_base = buffer->data, .iov_len = buffer->len };
uint8_t cbuf[1024] __attribute__((aligned(8)));
struct msghdr message = {
.msg_name = &recvaddr,
.msg_namelen = sizeof(recvaddr),
.msg_iov = &buffer_vec,
.msg_iovlen = 1,
.msg_control = cbuf,
.msg_controllen = sizeof(cbuf),
};
ssize_t len = recvmsg(sock->fd.fd, &message, 0);
if (len <= 0) {
if (len < 0)
pr_warn_errno("recvmsg");
fastd_buffer_free(buffer);
return;
}
buffer->len = len;
handle_socket_control(&message, sock, &local_addr);
#ifdef USE_PKTINFO
if (!local_addr.sa.sa_family) {
pr_error("received packet without packet info");
fastd_buffer_free(buffer);
return;
}
#endif
fastd_peer_address_simplify(&local_addr);
fastd_peer_address_simplify(&recvaddr);
handle_socket_receive(sock, &local_addr, &recvaddr, buffer);
}
/** Handles a received and decrypted payload packet */
void fastd_handle_receive(fastd_peer_t *peer, fastd_buffer_t *buffer, bool reordered) {
if (conf.mode == MODE_TAP) {
if (buffer->len < sizeof(fastd_eth_header_t)) {
pr_debug("received truncated packet");
fastd_buffer_free(buffer);
return;
}
fastd_eth_addr_t src_addr = fastd_buffer_source_address(buffer);
if (fastd_eth_addr_is_unicast(src_addr))
fastd_peer_eth_addr_add(peer, src_addr);
}
fastd_stats_add(peer, STAT_RX, buffer->len);
if (reordered)
fastd_stats_add(peer, STAT_RX_REORDERED, buffer->len);
fastd_iface_write(peer->iface, buffer);
if (conf.mode == MODE_TAP && conf.forward) {
/*
Misaligned buffers come from the null method, as it uses a 1-byte header
rather than (16*n+8)-byte like all other methods. When such a buffer enters
the transmit path again through fastd's forward feature, it will violate
the fastd_block128_t alignment.
*/
buffer = fastd_buffer_align(buffer, conf.encrypt_headroom);
fastd_send_data(buffer, peer, NULL);
return;
}
fastd_buffer_free(buffer);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4421_0 |
crossvul-cpp_data_good_3287_0 | /*
** Copyright (C) 2004-2017 Erik de Castro Lopo <erikd@mega-nerd.com>
** Copyright (C) 2004 Tobias Gehrig <tgehrig@ira.uka.de>
**
** This program is free software ; you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation ; either version 2.1 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY ; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program ; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "sfconfig.h"
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include "sndfile.h"
#include "common.h"
#if HAVE_EXTERNAL_XIPH_LIBS
#include <FLAC/stream_decoder.h>
#include <FLAC/stream_encoder.h>
#include <FLAC/metadata.h>
/*------------------------------------------------------------------------------
** Private static functions.
*/
#define FLAC_DEFAULT_COMPRESSION_LEVEL 5
#define ENC_BUFFER_SIZE 8192
typedef enum
{ PFLAC_PCM_SHORT = 50,
PFLAC_PCM_INT = 51,
PFLAC_PCM_FLOAT = 52,
PFLAC_PCM_DOUBLE = 53
} PFLAC_PCM ;
typedef struct
{
FLAC__StreamDecoder *fsd ;
FLAC__StreamEncoder *fse ;
PFLAC_PCM pcmtype ;
void* ptr ;
unsigned pos, len, remain ;
FLAC__StreamMetadata *metadata ;
const int32_t * const * wbuffer ;
int32_t * rbuffer [FLAC__MAX_CHANNELS] ;
int32_t* encbuffer ;
unsigned bufferpos ;
const FLAC__Frame *frame ;
unsigned compression ;
} FLAC_PRIVATE ;
typedef struct
{ const char *tag ;
int type ;
} FLAC_TAG ;
static sf_count_t flac_seek (SF_PRIVATE *psf, int mode, sf_count_t offset) ;
static int flac_byterate (SF_PRIVATE *psf) ;
static int flac_close (SF_PRIVATE *psf) ;
static int flac_enc_init (SF_PRIVATE *psf) ;
static int flac_read_header (SF_PRIVATE *psf) ;
static sf_count_t flac_read_flac2s (SF_PRIVATE *psf, short *ptr, sf_count_t len) ;
static sf_count_t flac_read_flac2i (SF_PRIVATE *psf, int *ptr, sf_count_t len) ;
static sf_count_t flac_read_flac2f (SF_PRIVATE *psf, float *ptr, sf_count_t len) ;
static sf_count_t flac_read_flac2d (SF_PRIVATE *psf, double *ptr, sf_count_t len) ;
static sf_count_t flac_write_s2flac (SF_PRIVATE *psf, const short *ptr, sf_count_t len) ;
static sf_count_t flac_write_i2flac (SF_PRIVATE *psf, const int *ptr, sf_count_t len) ;
static sf_count_t flac_write_f2flac (SF_PRIVATE *psf, const float *ptr, sf_count_t len) ;
static sf_count_t flac_write_d2flac (SF_PRIVATE *psf, const double *ptr, sf_count_t len) ;
static void f2flac8_array (const float *src, int32_t *dest, int count, int normalize) ;
static void f2flac16_array (const float *src, int32_t *dest, int count, int normalize) ;
static void f2flac24_array (const float *src, int32_t *dest, int count, int normalize) ;
static void f2flac8_clip_array (const float *src, int32_t *dest, int count, int normalize) ;
static void f2flac16_clip_array (const float *src, int32_t *dest, int count, int normalize) ;
static void f2flac24_clip_array (const float *src, int32_t *dest, int count, int normalize) ;
static void d2flac8_array (const double *src, int32_t *dest, int count, int normalize) ;
static void d2flac16_array (const double *src, int32_t *dest, int count, int normalize) ;
static void d2flac24_array (const double *src, int32_t *dest, int count, int normalize) ;
static void d2flac8_clip_array (const double *src, int32_t *dest, int count, int normalize) ;
static void d2flac16_clip_array (const double *src, int32_t *dest, int count, int normalize) ;
static void d2flac24_clip_array (const double *src, int32_t *dest, int count, int normalize) ;
static int flac_command (SF_PRIVATE *psf, int command, void *data, int datasize) ;
/* Decoder Callbacks */
static FLAC__StreamDecoderReadStatus sf_flac_read_callback (const FLAC__StreamDecoder *decoder, FLAC__byte buffer [], size_t *bytes, void *client_data) ;
static FLAC__StreamDecoderSeekStatus sf_flac_seek_callback (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data) ;
static FLAC__StreamDecoderTellStatus sf_flac_tell_callback (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data) ;
static FLAC__StreamDecoderLengthStatus sf_flac_length_callback (const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data) ;
static FLAC__bool sf_flac_eof_callback (const FLAC__StreamDecoder *decoder, void *client_data) ;
static FLAC__StreamDecoderWriteStatus sf_flac_write_callback (const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32_t * const buffer [], void *client_data) ;
static void sf_flac_meta_callback (const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data) ;
static void sf_flac_error_callback (const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data) ;
/* Encoder Callbacks */
static FLAC__StreamEncoderSeekStatus sf_flac_enc_seek_callback (const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data) ;
static FLAC__StreamEncoderTellStatus sf_flac_enc_tell_callback (const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data) ;
static FLAC__StreamEncoderWriteStatus sf_flac_enc_write_callback (const FLAC__StreamEncoder *encoder, const FLAC__byte buffer [], size_t bytes, unsigned samples, unsigned current_frame, void *client_data) ;
static void
s2flac8_array (const short *src, int32_t *dest, int count)
{ while (--count >= 0)
dest [count] = src [count] >> 8 ;
} /* s2flac8_array */
static void
s2flac16_array (const short *src, int32_t *dest, int count)
{ while (--count >= 0)
dest [count] = src [count] ;
} /* s2flac16_array */
static void
s2flac24_array (const short *src, int32_t *dest, int count)
{ while (--count >= 0)
dest [count] = src [count] << 8 ;
} /* s2flac24_array */
static void
i2flac8_array (const int *src, int32_t *dest, int count)
{ while (--count >= 0)
dest [count] = src [count] >> 24 ;
} /* i2flac8_array */
static void
i2flac16_array (const int *src, int32_t *dest, int count)
{
while (--count >= 0)
dest [count] = src [count] >> 16 ;
} /* i2flac16_array */
static void
i2flac24_array (const int *src, int32_t *dest, int count)
{ while (--count >= 0)
dest [count] = src [count] >> 8 ;
} /* i2flac24_array */
static sf_count_t
flac_buffer_copy (SF_PRIVATE *psf)
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
const FLAC__Frame *frame = pflac->frame ;
const int32_t* const *buffer = pflac->wbuffer ;
unsigned i = 0, j, offset, channels, len ;
/*
** frame->header.blocksize is variable and we're using a constant blocksize
** of FLAC__MAX_BLOCK_SIZE.
** Check our assumptions here.
*/
if (frame->header.blocksize > FLAC__MAX_BLOCK_SIZE)
{ psf_log_printf (psf, "Ooops : frame->header.blocksize (%d) > FLAC__MAX_BLOCK_SIZE (%d)\n", __func__, __LINE__, frame->header.blocksize, FLAC__MAX_BLOCK_SIZE) ;
psf->error = SFE_INTERNAL ;
return 0 ;
} ;
if (frame->header.channels > FLAC__MAX_CHANNELS)
psf_log_printf (psf, "Ooops : frame->header.channels (%d) > FLAC__MAX_BLOCK_SIZE (%d)\n", __func__, __LINE__, frame->header.channels, FLAC__MAX_CHANNELS) ;
channels = SF_MIN (frame->header.channels, FLAC__MAX_CHANNELS) ;
if (pflac->ptr == NULL)
{ /*
** This pointer is reset to NULL each time the current frame has been
** decoded. Somehow its used during encoding and decoding.
*/
for (i = 0 ; i < channels ; i++)
{
if (pflac->rbuffer [i] == NULL)
pflac->rbuffer [i] = calloc (FLAC__MAX_BLOCK_SIZE, sizeof (int32_t)) ;
memcpy (pflac->rbuffer [i], buffer [i], frame->header.blocksize * sizeof (int32_t)) ;
} ;
pflac->wbuffer = (const int32_t* const*) pflac->rbuffer ;
return 0 ;
} ;
len = SF_MIN (pflac->len, frame->header.blocksize) ;
if (pflac->remain % channels != 0)
{ psf_log_printf (psf, "Error: pflac->remain %u channels %u\n", pflac->remain, channels) ;
return 0 ;
} ;
switch (pflac->pcmtype)
{ case PFLAC_PCM_SHORT :
{ short *retpcm = (short*) pflac->ptr ;
int shift = 16 - frame->header.bits_per_sample ;
if (shift < 0)
{ shift = abs (shift) ;
for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = buffer [j][pflac->bufferpos] >> shift ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
}
}
else
{ for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = ((uint16_t) buffer [j][pflac->bufferpos]) << shift ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
} ;
} ;
} ;
break ;
case PFLAC_PCM_INT :
{ int *retpcm = (int*) pflac->ptr ;
int shift = 32 - frame->header.bits_per_sample ;
for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = ((uint32_t) buffer [j][pflac->bufferpos]) << shift ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
} ;
} ;
break ;
case PFLAC_PCM_FLOAT :
{ float *retpcm = (float*) pflac->ptr ;
float norm = (psf->norm_float == SF_TRUE) ? 1.0 / (1 << (frame->header.bits_per_sample - 1)) : 1.0 ;
for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = buffer [j][pflac->bufferpos] * norm ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
} ;
} ;
break ;
case PFLAC_PCM_DOUBLE :
{ double *retpcm = (double*) pflac->ptr ;
double norm = (psf->norm_double == SF_TRUE) ? 1.0 / (1 << (frame->header.bits_per_sample - 1)) : 1.0 ;
for (i = 0 ; i < len && pflac->remain > 0 ; i++)
{ offset = pflac->pos + i * channels ;
if (pflac->bufferpos >= frame->header.blocksize)
break ;
if (offset + channels > pflac->len)
break ;
for (j = 0 ; j < channels ; j++)
retpcm [offset + j] = buffer [j][pflac->bufferpos] * norm ;
pflac->remain -= channels ;
pflac->bufferpos++ ;
} ;
} ;
break ;
default :
return 0 ;
} ;
offset = i * channels ;
pflac->pos += i * channels ;
return offset ;
} /* flac_buffer_copy */
static FLAC__StreamDecoderReadStatus
sf_flac_read_callback (const FLAC__StreamDecoder * UNUSED (decoder), FLAC__byte buffer [], size_t *bytes, void *client_data)
{ SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
*bytes = psf_fread (buffer, 1, *bytes, psf) ;
if (*bytes > 0 && psf->error == 0)
return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE ;
return FLAC__STREAM_DECODER_READ_STATUS_ABORT ;
} /* sf_flac_read_callback */
static FLAC__StreamDecoderSeekStatus
sf_flac_seek_callback (const FLAC__StreamDecoder * UNUSED (decoder), FLAC__uint64 absolute_byte_offset, void *client_data)
{ SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
psf_fseek (psf, absolute_byte_offset, SEEK_SET) ;
if (psf->error)
return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR ;
return FLAC__STREAM_DECODER_SEEK_STATUS_OK ;
} /* sf_flac_seek_callback */
static FLAC__StreamDecoderTellStatus
sf_flac_tell_callback (const FLAC__StreamDecoder * UNUSED (decoder), FLAC__uint64 *absolute_byte_offset, void *client_data)
{ SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
*absolute_byte_offset = psf_ftell (psf) ;
if (psf->error)
return FLAC__STREAM_DECODER_TELL_STATUS_ERROR ;
return FLAC__STREAM_DECODER_TELL_STATUS_OK ;
} /* sf_flac_tell_callback */
static FLAC__StreamDecoderLengthStatus
sf_flac_length_callback (const FLAC__StreamDecoder * UNUSED (decoder), FLAC__uint64 *stream_length, void *client_data)
{ SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
if ((*stream_length = psf->filelength) == 0)
return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR ;
return FLAC__STREAM_DECODER_LENGTH_STATUS_OK ;
} /* sf_flac_length_callback */
static FLAC__bool
sf_flac_eof_callback (const FLAC__StreamDecoder *UNUSED (decoder), void *client_data)
{ SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
if (psf_ftell (psf) == psf->filelength)
return SF_TRUE ;
return SF_FALSE ;
} /* sf_flac_eof_callback */
static FLAC__StreamDecoderWriteStatus
sf_flac_write_callback (const FLAC__StreamDecoder * UNUSED (decoder), const FLAC__Frame *frame, const int32_t * const buffer [], void *client_data)
{ SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
pflac->frame = frame ;
pflac->bufferpos = 0 ;
pflac->wbuffer = buffer ;
flac_buffer_copy (psf) ;
return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE ;
} /* sf_flac_write_callback */
static void
sf_flac_meta_get_vorbiscomments (SF_PRIVATE *psf, const FLAC__StreamMetadata *metadata)
{ static FLAC_TAG tags [] =
{ { "title", SF_STR_TITLE },
{ "copyright", SF_STR_COPYRIGHT },
{ "software", SF_STR_SOFTWARE },
{ "artist", SF_STR_ARTIST },
{ "comment", SF_STR_COMMENT },
{ "date", SF_STR_DATE },
{ "album", SF_STR_ALBUM },
{ "license", SF_STR_LICENSE },
{ "tracknumber", SF_STR_TRACKNUMBER },
{ "genre", SF_STR_GENRE }
} ;
const char *value, *cptr ;
int k, tag_num ;
for (k = 0 ; k < ARRAY_LEN (tags) ; k++)
{ tag_num = FLAC__metadata_object_vorbiscomment_find_entry_from (metadata, 0, tags [k].tag) ;
if (tag_num < 0)
continue ;
value = (const char*) metadata->data.vorbis_comment.comments [tag_num].entry ;
if ((cptr = strchr (value, '=')) != NULL)
value = cptr + 1 ;
psf_log_printf (psf, " %-12s : %s\n", tags [k].tag, value) ;
psf_store_string (psf, tags [k].type, value) ;
} ;
return ;
} /* sf_flac_meta_get_vorbiscomments */
static void
sf_flac_meta_callback (const FLAC__StreamDecoder * UNUSED (decoder), const FLAC__StreamMetadata *metadata, void *client_data)
{ SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
int bitwidth = 0, i ;
switch (metadata->type)
{ case FLAC__METADATA_TYPE_STREAMINFO :
psf->sf.channels = metadata->data.stream_info.channels ;
psf->sf.samplerate = metadata->data.stream_info.sample_rate ;
psf->sf.frames = metadata->data.stream_info.total_samples ;
psf_log_printf (psf, "FLAC Stream Metadata\n Channels : %d\n Sample rate : %d\n", psf->sf.channels, psf->sf.samplerate) ;
if (psf->sf.frames == 0)
{ psf_log_printf (psf, " Frames : 0 (bumping to SF_COUNT_MAX)\n") ;
psf->sf.frames = SF_COUNT_MAX ;
}
else
psf_log_printf (psf, " Frames : %D\n", psf->sf.frames) ;
switch (metadata->data.stream_info.bits_per_sample)
{ case 8 :
psf->sf.format |= SF_FORMAT_PCM_S8 ;
bitwidth = 8 ;
break ;
case 16 :
psf->sf.format |= SF_FORMAT_PCM_16 ;
bitwidth = 16 ;
break ;
case 24 :
psf->sf.format |= SF_FORMAT_PCM_24 ;
bitwidth = 24 ;
break ;
default :
psf_log_printf (psf, "sf_flac_meta_callback : bits_per_sample %d not yet implemented.\n", metadata->data.stream_info.bits_per_sample) ;
break ;
} ;
if (bitwidth > 0)
psf_log_printf (psf, " Bit width : %d\n", bitwidth) ;
for (i = 0 ; i < psf->sf.channels ; i++)
pflac->rbuffer [i] = calloc (FLAC__MAX_BLOCK_SIZE, sizeof (int32_t)) ;
pflac->wbuffer = (const int32_t* const*) pflac->rbuffer ;
break ;
case FLAC__METADATA_TYPE_VORBIS_COMMENT :
psf_log_printf (psf, "Vorbis Comment Metadata\n") ;
sf_flac_meta_get_vorbiscomments (psf, metadata) ;
break ;
case FLAC__METADATA_TYPE_PADDING :
psf_log_printf (psf, "Padding Metadata\n") ;
break ;
case FLAC__METADATA_TYPE_APPLICATION :
psf_log_printf (psf, "Application Metadata\n") ;
break ;
case FLAC__METADATA_TYPE_SEEKTABLE :
psf_log_printf (psf, "Seektable Metadata\n") ;
break ;
case FLAC__METADATA_TYPE_CUESHEET :
psf_log_printf (psf, "Cuesheet Metadata\n") ;
break ;
case FLAC__METADATA_TYPE_PICTURE :
psf_log_printf (psf, "Picture Metadata\n") ;
break ;
case FLAC__METADATA_TYPE_UNDEFINED :
psf_log_printf (psf, "Undefined Metadata\n") ;
break ;
default :
psf_log_printf (psf, "sf_flac_meta_callback : metadata-type %d not yet implemented.\n", metadata->type) ;
break ;
} ;
return ;
} /* sf_flac_meta_callback */
static void
sf_flac_error_callback (const FLAC__StreamDecoder * UNUSED (decoder), FLAC__StreamDecoderErrorStatus status, void *client_data)
{ SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
psf_log_printf (psf, "ERROR : %s\n", FLAC__StreamDecoderErrorStatusString [status]) ;
switch (status)
{ case FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC :
psf->error = SFE_FLAC_LOST_SYNC ;
break ;
case FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER :
psf->error = SFE_FLAC_BAD_HEADER ;
break ;
default :
psf->error = SFE_FLAC_UNKOWN_ERROR ;
break ;
} ;
return ;
} /* sf_flac_error_callback */
static FLAC__StreamEncoderSeekStatus
sf_flac_enc_seek_callback (const FLAC__StreamEncoder * UNUSED (encoder), FLAC__uint64 absolute_byte_offset, void *client_data)
{ SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
psf_fseek (psf, absolute_byte_offset, SEEK_SET) ;
if (psf->error)
return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR ;
return FLAC__STREAM_ENCODER_SEEK_STATUS_OK ;
} /* sf_flac_enc_seek_callback */
static FLAC__StreamEncoderTellStatus
sf_flac_enc_tell_callback (const FLAC__StreamEncoder *UNUSED (encoder), FLAC__uint64 *absolute_byte_offset, void *client_data)
{ SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
*absolute_byte_offset = psf_ftell (psf) ;
if (psf->error)
return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR ;
return FLAC__STREAM_ENCODER_TELL_STATUS_OK ;
} /* sf_flac_enc_tell_callback */
static FLAC__StreamEncoderWriteStatus
sf_flac_enc_write_callback (const FLAC__StreamEncoder * UNUSED (encoder), const FLAC__byte buffer [], size_t bytes, unsigned UNUSED (samples), unsigned UNUSED (current_frame), void *client_data)
{ SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
if (psf_fwrite (buffer, 1, bytes, psf) == (sf_count_t) bytes && psf->error == 0)
return FLAC__STREAM_ENCODER_WRITE_STATUS_OK ;
return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR ;
} /* sf_flac_enc_write_callback */
static void
flac_write_strings (SF_PRIVATE *psf, FLAC_PRIVATE* pflac)
{ FLAC__StreamMetadata_VorbisComment_Entry entry ;
int k, string_count = 0 ;
for (k = 0 ; k < SF_MAX_STRINGS ; k++)
{ if (psf->strings.data [k].type != 0)
string_count ++ ;
} ;
if (string_count == 0)
return ;
if (pflac->metadata == NULL && (pflac->metadata = FLAC__metadata_object_new (FLAC__METADATA_TYPE_VORBIS_COMMENT)) == NULL)
{ psf_log_printf (psf, "FLAC__metadata_object_new returned NULL\n") ;
return ;
} ;
for (k = 0 ; k < SF_MAX_STRINGS && psf->strings.data [k].type != 0 ; k++)
{ const char * key, * value ;
switch (psf->strings.data [k].type)
{ case SF_STR_SOFTWARE :
key = "software" ;
break ;
case SF_STR_TITLE :
key = "title" ;
break ;
case SF_STR_COPYRIGHT :
key = "copyright" ;
break ;
case SF_STR_ARTIST :
key = "artist" ;
break ;
case SF_STR_COMMENT :
key = "comment" ;
break ;
case SF_STR_DATE :
key = "date" ;
break ;
case SF_STR_ALBUM :
key = "album" ;
break ;
case SF_STR_LICENSE :
key = "license" ;
break ;
case SF_STR_TRACKNUMBER :
key = "tracknumber" ;
break ;
case SF_STR_GENRE :
key = "genre" ;
break ;
default :
continue ;
} ;
value = psf->strings.storage + psf->strings.data [k].offset ;
FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair (&entry, key, value) ;
FLAC__metadata_object_vorbiscomment_append_comment (pflac->metadata, entry, /* copy */ SF_FALSE) ;
} ;
if (! FLAC__stream_encoder_set_metadata (pflac->fse, &pflac->metadata, 1))
{ printf ("%s %d : fail\n", __func__, __LINE__) ;
return ;
} ;
return ;
} /* flac_write_strings */
static int
flac_write_header (SF_PRIVATE *psf, int UNUSED (calc_length))
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
int err ;
flac_write_strings (psf, pflac) ;
if ((err = FLAC__stream_encoder_init_stream (pflac->fse, sf_flac_enc_write_callback, sf_flac_enc_seek_callback, sf_flac_enc_tell_callback, NULL, psf)) != FLAC__STREAM_DECODER_INIT_STATUS_OK)
{ psf_log_printf (psf, "Error : FLAC encoder init returned error : %s\n", FLAC__StreamEncoderInitStatusString [err]) ;
return SFE_FLAC_INIT_DECODER ;
} ;
if (psf->error == 0)
psf->dataoffset = psf_ftell (psf) ;
pflac->encbuffer = calloc (ENC_BUFFER_SIZE, sizeof (int32_t)) ;
return psf->error ;
} /* flac_write_header */
/*------------------------------------------------------------------------------
** Public function.
*/
int
flac_open (SF_PRIVATE *psf)
{ int subformat ;
int error = 0 ;
FLAC_PRIVATE* pflac = calloc (1, sizeof (FLAC_PRIVATE)) ;
psf->codec_data = pflac ;
/* Set the default value here. Over-ridden later if necessary. */
pflac->compression = FLAC_DEFAULT_COMPRESSION_LEVEL ;
if (psf->file.mode == SFM_RDWR)
return SFE_BAD_MODE_RW ;
if (psf->file.mode == SFM_READ)
{ if ((error = flac_read_header (psf)))
return error ;
} ;
subformat = SF_CODEC (psf->sf.format) ;
if (psf->file.mode == SFM_WRITE)
{ if ((SF_CONTAINER (psf->sf.format)) != SF_FORMAT_FLAC)
return SFE_BAD_OPEN_FORMAT ;
psf->endian = SF_ENDIAN_BIG ;
psf->sf.seekable = 0 ;
psf->strings.flags = SF_STR_ALLOW_START ;
if ((error = flac_enc_init (psf)))
return error ;
/* In an ideal world we would write the header at this point. Unfortunately
** that would prevent string metadata being added so we have to hold off.
*/
psf->write_header = flac_write_header ;
} ;
psf->datalength = psf->filelength ;
psf->dataoffset = 0 ;
psf->container_close = flac_close ;
psf->seek = flac_seek ;
psf->byterate = flac_byterate ;
psf->command = flac_command ;
switch (subformat)
{ case SF_FORMAT_PCM_S8 : /* 8-bit FLAC. */
case SF_FORMAT_PCM_16 : /* 16-bit FLAC. */
case SF_FORMAT_PCM_24 : /* 24-bit FLAC. */
error = flac_init (psf) ;
break ;
default : return SFE_UNIMPLEMENTED ;
} ;
return error ;
} /* flac_open */
/*------------------------------------------------------------------------------
*/
static int
flac_close (SF_PRIVATE *psf)
{ FLAC_PRIVATE* pflac ;
int k ;
if ((pflac = (FLAC_PRIVATE*) psf->codec_data) == NULL)
return 0 ;
if (pflac->metadata != NULL)
FLAC__metadata_object_delete (pflac->metadata) ;
if (psf->file.mode == SFM_WRITE)
{ FLAC__stream_encoder_finish (pflac->fse) ;
FLAC__stream_encoder_delete (pflac->fse) ;
free (pflac->encbuffer) ;
} ;
if (psf->file.mode == SFM_READ)
{ FLAC__stream_decoder_finish (pflac->fsd) ;
FLAC__stream_decoder_delete (pflac->fsd) ;
} ;
for (k = 0 ; k < ARRAY_LEN (pflac->rbuffer) ; k++)
free (pflac->rbuffer [k]) ;
free (pflac) ;
psf->codec_data = NULL ;
return 0 ;
} /* flac_close */
static int
flac_enc_init (SF_PRIVATE *psf)
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
unsigned bps ;
/* To cite the flac FAQ at
** http://flac.sourceforge.net/faq.html#general__samples
** "FLAC supports linear sample rates from 1Hz - 655350Hz in 1Hz
** increments."
*/
if (psf->sf.samplerate < 1 || psf->sf.samplerate > 655350)
{ psf_log_printf (psf, "flac sample rate out of range.\n", psf->sf.samplerate) ;
return SFE_FLAC_BAD_SAMPLE_RATE ;
} ;
psf_fseek (psf, 0, SEEK_SET) ;
switch (SF_CODEC (psf->sf.format))
{ case SF_FORMAT_PCM_S8 :
bps = 8 ;
break ;
case SF_FORMAT_PCM_16 :
bps = 16 ;
break ;
case SF_FORMAT_PCM_24 :
bps = 24 ;
break ;
default :
bps = 0 ;
break ;
} ;
if (pflac->fse)
FLAC__stream_encoder_delete (pflac->fse) ;
if ((pflac->fse = FLAC__stream_encoder_new ()) == NULL)
return SFE_FLAC_NEW_DECODER ;
if (! FLAC__stream_encoder_set_channels (pflac->fse, psf->sf.channels))
{ psf_log_printf (psf, "FLAC__stream_encoder_set_channels (%d) return false.\n", psf->sf.channels) ;
return SFE_FLAC_INIT_DECODER ;
} ;
if (! FLAC__stream_encoder_set_sample_rate (pflac->fse, psf->sf.samplerate))
{ psf_log_printf (psf, "FLAC__stream_encoder_set_sample_rate (%d) returned false.\n", psf->sf.samplerate) ;
return SFE_FLAC_BAD_SAMPLE_RATE ;
} ;
if (! FLAC__stream_encoder_set_bits_per_sample (pflac->fse, bps))
{ psf_log_printf (psf, "FLAC__stream_encoder_set_bits_per_sample (%d) return false.\n", bps) ;
return SFE_FLAC_INIT_DECODER ;
} ;
if (! FLAC__stream_encoder_set_compression_level (pflac->fse, pflac->compression))
{ psf_log_printf (psf, "FLAC__stream_encoder_set_compression_level (%d) return false.\n", pflac->compression) ;
return SFE_FLAC_INIT_DECODER ;
} ;
return 0 ;
} /* flac_enc_init */
static int
flac_read_header (SF_PRIVATE *psf)
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
psf_fseek (psf, 0, SEEK_SET) ;
if (pflac->fsd)
FLAC__stream_decoder_delete (pflac->fsd) ;
if ((pflac->fsd = FLAC__stream_decoder_new ()) == NULL)
return SFE_FLAC_NEW_DECODER ;
FLAC__stream_decoder_set_metadata_respond_all (pflac->fsd) ;
if (FLAC__stream_decoder_init_stream (pflac->fsd, sf_flac_read_callback, sf_flac_seek_callback, sf_flac_tell_callback, sf_flac_length_callback, sf_flac_eof_callback, sf_flac_write_callback, sf_flac_meta_callback, sf_flac_error_callback, psf) != FLAC__STREAM_DECODER_INIT_STATUS_OK)
return SFE_FLAC_INIT_DECODER ;
FLAC__stream_decoder_process_until_end_of_metadata (pflac->fsd) ;
psf_log_printf (psf, "End\n") ;
if (psf->error == 0)
{ FLAC__uint64 position ;
FLAC__stream_decoder_get_decode_position (pflac->fsd, &position) ;
psf->dataoffset = position ;
} ;
return psf->error ;
} /* flac_read_header */
static int
flac_command (SF_PRIVATE * psf, int command, void * data, int datasize)
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
double quality ;
switch (command)
{ case SFC_SET_COMPRESSION_LEVEL :
if (data == NULL || datasize != sizeof (double))
return SF_FALSE ;
if (psf->have_written)
return SF_FALSE ;
/* FLAC compression level is in the range [0, 8] while libsndfile takes
** values in the range [0.0, 1.0]. Massage the libsndfile value here.
*/
quality = (*((double *) data)) * 8.0 ;
/* Clip range. */
pflac->compression = lrint (SF_MAX (0.0, SF_MIN (8.0, quality))) ;
psf_log_printf (psf, "%s : Setting SFC_SET_COMPRESSION_LEVEL to %u.\n", __func__, pflac->compression) ;
if (flac_enc_init (psf))
return SF_FALSE ;
return SF_TRUE ;
default :
return SF_FALSE ;
} ;
return SF_FALSE ;
} /* flac_command */
int
flac_init (SF_PRIVATE *psf)
{
if (psf->file.mode == SFM_RDWR)
return SFE_BAD_MODE_RW ;
if (psf->file.mode == SFM_READ)
{ psf->read_short = flac_read_flac2s ;
psf->read_int = flac_read_flac2i ;
psf->read_float = flac_read_flac2f ;
psf->read_double = flac_read_flac2d ;
} ;
if (psf->file.mode == SFM_WRITE)
{ psf->write_short = flac_write_s2flac ;
psf->write_int = flac_write_i2flac ;
psf->write_float = flac_write_f2flac ;
psf->write_double = flac_write_d2flac ;
} ;
if (psf->filelength > psf->dataoffset)
psf->datalength = (psf->dataend) ? psf->dataend - psf->dataoffset : psf->filelength - psf->dataoffset ;
else
psf->datalength = 0 ;
return 0 ;
} /* flac_init */
static unsigned
flac_read_loop (SF_PRIVATE *psf, unsigned len)
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
FLAC__StreamDecoderState state ;
pflac->pos = 0 ;
pflac->len = len ;
pflac->remain = len ;
state = FLAC__stream_decoder_get_state (pflac->fsd) ;
if (state > FLAC__STREAM_DECODER_END_OF_STREAM)
{ psf_log_printf (psf, "FLAC__stream_decoder_get_state returned %s\n", FLAC__StreamDecoderStateString [state]) ;
/* Current frame is busted, so NULL the pointer. */
pflac->frame = NULL ;
} ;
/* First copy data that has already been decoded and buffered. */
if (pflac->frame != NULL && pflac->bufferpos < pflac->frame->header.blocksize)
flac_buffer_copy (psf) ;
/* Decode some more. */
while (pflac->pos < pflac->len)
{ if (FLAC__stream_decoder_process_single (pflac->fsd) == 0)
break ;
state = FLAC__stream_decoder_get_state (pflac->fsd) ;
if (state >= FLAC__STREAM_DECODER_END_OF_STREAM)
{ psf_log_printf (psf, "FLAC__stream_decoder_get_state returned %s\n", FLAC__StreamDecoderStateString [state]) ;
/* Current frame is busted, so NULL the pointer. */
pflac->frame = NULL ;
break ;
} ;
} ;
pflac->ptr = NULL ;
return pflac->pos ;
} /* flac_read_loop */
static sf_count_t
flac_read_flac2s (SF_PRIVATE *psf, short *ptr, sf_count_t len)
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
sf_count_t total = 0, current ;
unsigned readlen ;
pflac->pcmtype = PFLAC_PCM_SHORT ;
while (total < len)
{ pflac->ptr = ptr + total ;
readlen = (len - total > 0x1000000) ? 0x1000000 : (unsigned) (len - total) ;
current = flac_read_loop (psf, readlen) ;
if (current == 0)
break ;
total += current ;
} ;
return total ;
} /* flac_read_flac2s */
static sf_count_t
flac_read_flac2i (SF_PRIVATE *psf, int *ptr, sf_count_t len)
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
sf_count_t total = 0, current ;
unsigned readlen ;
pflac->pcmtype = PFLAC_PCM_INT ;
while (total < len)
{ pflac->ptr = ptr + total ;
readlen = (len - total > 0x1000000) ? 0x1000000 : (unsigned) (len - total) ;
current = flac_read_loop (psf, readlen) ;
if (current == 0)
break ;
total += current ;
} ;
return total ;
} /* flac_read_flac2i */
static sf_count_t
flac_read_flac2f (SF_PRIVATE *psf, float *ptr, sf_count_t len)
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
sf_count_t total = 0, current ;
unsigned readlen ;
pflac->pcmtype = PFLAC_PCM_FLOAT ;
while (total < len)
{ pflac->ptr = ptr + total ;
readlen = (len - total > 0x1000000) ? 0x1000000 : (unsigned) (len - total) ;
current = flac_read_loop (psf, readlen) ;
if (current == 0)
break ;
total += current ;
} ;
return total ;
} /* flac_read_flac2f */
static sf_count_t
flac_read_flac2d (SF_PRIVATE *psf, double *ptr, sf_count_t len)
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
sf_count_t total = 0, current ;
unsigned readlen ;
pflac->pcmtype = PFLAC_PCM_DOUBLE ;
while (total < len)
{ pflac->ptr = ptr + total ;
readlen = (len - total > 0x1000000) ? 0x1000000 : (unsigned) (len - total) ;
current = flac_read_loop (psf, readlen) ;
if (current == 0)
break ;
total += current ;
} ;
return total ;
} /* flac_read_flac2d */
static sf_count_t
flac_write_s2flac (SF_PRIVATE *psf, const short *ptr, sf_count_t len)
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
void (*convert) (const short *, int32_t *, int) ;
int bufferlen, writecount, thiswrite ;
sf_count_t total = 0 ;
int32_t* buffer = pflac->encbuffer ;
switch (SF_CODEC (psf->sf.format))
{ case SF_FORMAT_PCM_S8 :
convert = s2flac8_array ;
break ;
case SF_FORMAT_PCM_16 :
convert = s2flac16_array ;
break ;
case SF_FORMAT_PCM_24 :
convert = s2flac24_array ;
break ;
default :
return -1 ;
} ;
bufferlen = ENC_BUFFER_SIZE / (sizeof (int32_t) * psf->sf.channels) ;
bufferlen *= psf->sf.channels ;
while (len > 0)
{ writecount = (len >= bufferlen) ? bufferlen : (int) len ;
convert (ptr + total, buffer, writecount) ;
if (FLAC__stream_encoder_process_interleaved (pflac->fse, buffer, writecount / psf->sf.channels))
thiswrite = writecount ;
else
break ;
total += thiswrite ;
if (thiswrite < writecount)
break ;
len -= thiswrite ;
} ;
return total ;
} /* flac_write_s2flac */
static sf_count_t
flac_write_i2flac (SF_PRIVATE *psf, const int *ptr, sf_count_t len)
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
void (*convert) (const int *, int32_t *, int) ;
int bufferlen, writecount, thiswrite ;
sf_count_t total = 0 ;
int32_t* buffer = pflac->encbuffer ;
switch (SF_CODEC (psf->sf.format))
{ case SF_FORMAT_PCM_S8 :
convert = i2flac8_array ;
break ;
case SF_FORMAT_PCM_16 :
convert = i2flac16_array ;
break ;
case SF_FORMAT_PCM_24 :
convert = i2flac24_array ;
break ;
default :
return -1 ;
} ;
bufferlen = ENC_BUFFER_SIZE / (sizeof (int32_t) * psf->sf.channels) ;
bufferlen *= psf->sf.channels ;
while (len > 0)
{ writecount = (len >= bufferlen) ? bufferlen : (int) len ;
convert (ptr + total, buffer, writecount) ;
if (FLAC__stream_encoder_process_interleaved (pflac->fse, buffer, writecount / psf->sf.channels))
thiswrite = writecount ;
else
break ;
total += thiswrite ;
if (thiswrite < writecount)
break ;
len -= thiswrite ;
} ;
return total ;
} /* flac_write_i2flac */
static sf_count_t
flac_write_f2flac (SF_PRIVATE *psf, const float *ptr, sf_count_t len)
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
void (*convert) (const float *, int32_t *, int, int) ;
int bufferlen, writecount, thiswrite ;
sf_count_t total = 0 ;
int32_t* buffer = pflac->encbuffer ;
switch (SF_CODEC (psf->sf.format))
{ case SF_FORMAT_PCM_S8 :
convert = (psf->add_clipping) ? f2flac8_clip_array : f2flac8_array ;
break ;
case SF_FORMAT_PCM_16 :
convert = (psf->add_clipping) ? f2flac16_clip_array : f2flac16_array ;
break ;
case SF_FORMAT_PCM_24 :
convert = (psf->add_clipping) ? f2flac24_clip_array : f2flac24_array ;
break ;
default :
return -1 ;
} ;
bufferlen = ENC_BUFFER_SIZE / (sizeof (int32_t) * psf->sf.channels) ;
bufferlen *= psf->sf.channels ;
while (len > 0)
{ writecount = (len >= bufferlen) ? bufferlen : (int) len ;
convert (ptr + total, buffer, writecount, psf->norm_float) ;
if (FLAC__stream_encoder_process_interleaved (pflac->fse, buffer, writecount / psf->sf.channels))
thiswrite = writecount ;
else
break ;
total += thiswrite ;
if (thiswrite < writecount)
break ;
len -= thiswrite ;
} ;
return total ;
} /* flac_write_f2flac */
static void
f2flac8_clip_array (const float *src, int32_t *dest, int count, int normalize)
{ float normfact, scaled_value ;
normfact = normalize ? (8.0 * 0x10) : 1.0 ;
while (--count >= 0)
{ scaled_value = src [count] * normfact ;
if (CPU_CLIPS_POSITIVE == 0 && scaled_value >= (1.0 * 0x7F))
{ dest [count] = 0x7F ;
continue ;
} ;
if (CPU_CLIPS_NEGATIVE == 0 && scaled_value <= (-8.0 * 0x10))
{ dest [count] = 0x80 ;
continue ;
} ;
dest [count] = lrintf (scaled_value) ;
} ;
return ;
} /* f2flac8_clip_array */
static void
f2flac16_clip_array (const float *src, int32_t *dest, int count, int normalize)
{ float normfact, scaled_value ;
normfact = normalize ? (8.0 * 0x1000) : 1.0 ;
while (--count >= 0)
{ scaled_value = src [count] * normfact ;
if (CPU_CLIPS_POSITIVE == 0 && scaled_value >= (1.0 * 0x7FFF))
{ dest [count] = 0x7FFF ;
continue ;
} ;
if (CPU_CLIPS_NEGATIVE == 0 && scaled_value <= (-8.0 * 0x1000))
{ dest [count] = 0x8000 ;
continue ;
} ;
dest [count] = lrintf (scaled_value) ;
} ;
} /* f2flac16_clip_array */
static void
f2flac24_clip_array (const float *src, int32_t *dest, int count, int normalize)
{ float normfact, scaled_value ;
normfact = normalize ? (8.0 * 0x100000) : 1.0 ;
while (--count >= 0)
{ scaled_value = src [count] * normfact ;
if (CPU_CLIPS_POSITIVE == 0 && scaled_value >= (1.0 * 0x7FFFFF))
{ dest [count] = 0x7FFFFF ;
continue ;
} ;
if (CPU_CLIPS_NEGATIVE == 0 && scaled_value <= (-8.0 * 0x100000))
{ dest [count] = 0x800000 ;
continue ;
}
dest [count] = lrintf (scaled_value) ;
} ;
return ;
} /* f2flac24_clip_array */
static void
f2flac8_array (const float *src, int32_t *dest, int count, int normalize)
{ float normfact = normalize ? (1.0 * 0x7F) : 1.0 ;
while (--count >= 0)
dest [count] = lrintf (src [count] * normfact) ;
} /* f2flac8_array */
static void
f2flac16_array (const float *src, int32_t *dest, int count, int normalize)
{ float normfact = normalize ? (1.0 * 0x7FFF) : 1.0 ;
while (--count >= 0)
dest [count] = lrintf (src [count] * normfact) ;
} /* f2flac16_array */
static void
f2flac24_array (const float *src, int32_t *dest, int count, int normalize)
{ float normfact = normalize ? (1.0 * 0x7FFFFF) : 1.0 ;
while (--count >= 0)
dest [count] = lrintf (src [count] * normfact) ;
} /* f2flac24_array */
static sf_count_t
flac_write_d2flac (SF_PRIVATE *psf, const double *ptr, sf_count_t len)
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
void (*convert) (const double *, int32_t *, int, int) ;
int bufferlen, writecount, thiswrite ;
sf_count_t total = 0 ;
int32_t* buffer = pflac->encbuffer ;
switch (SF_CODEC (psf->sf.format))
{ case SF_FORMAT_PCM_S8 :
convert = (psf->add_clipping) ? d2flac8_clip_array : d2flac8_array ;
break ;
case SF_FORMAT_PCM_16 :
convert = (psf->add_clipping) ? d2flac16_clip_array : d2flac16_array ;
break ;
case SF_FORMAT_PCM_24 :
convert = (psf->add_clipping) ? d2flac24_clip_array : d2flac24_array ;
break ;
default :
return -1 ;
} ;
bufferlen = ENC_BUFFER_SIZE / (sizeof (int32_t) * psf->sf.channels) ;
bufferlen *= psf->sf.channels ;
while (len > 0)
{ writecount = (len >= bufferlen) ? bufferlen : (int) len ;
convert (ptr + total, buffer, writecount, psf->norm_double) ;
if (FLAC__stream_encoder_process_interleaved (pflac->fse, buffer, writecount / psf->sf.channels))
thiswrite = writecount ;
else
break ;
total += thiswrite ;
if (thiswrite < writecount)
break ;
len -= thiswrite ;
} ;
return total ;
} /* flac_write_d2flac */
static void
d2flac8_clip_array (const double *src, int32_t *dest, int count, int normalize)
{ double normfact, scaled_value ;
normfact = normalize ? (8.0 * 0x10) : 1.0 ;
while (--count >= 0)
{ scaled_value = src [count] * normfact ;
if (CPU_CLIPS_POSITIVE == 0 && scaled_value >= (1.0 * 0x7F))
{ dest [count] = 0x7F ;
continue ;
} ;
if (CPU_CLIPS_NEGATIVE == 0 && scaled_value <= (-8.0 * 0x10))
{ dest [count] = 0x80 ;
continue ;
} ;
dest [count] = lrint (scaled_value) ;
} ;
return ;
} /* d2flac8_clip_array */
static void
d2flac16_clip_array (const double *src, int32_t *dest, int count, int normalize)
{ double normfact, scaled_value ;
normfact = normalize ? (8.0 * 0x1000) : 1.0 ;
while (--count >= 0)
{ scaled_value = src [count] * normfact ;
if (CPU_CLIPS_POSITIVE == 0 && scaled_value >= (1.0 * 0x7FFF))
{ dest [count] = 0x7FFF ;
continue ;
} ;
if (CPU_CLIPS_NEGATIVE == 0 && scaled_value <= (-8.0 * 0x1000))
{ dest [count] = 0x8000 ;
continue ;
} ;
dest [count] = lrint (scaled_value) ;
} ;
return ;
} /* d2flac16_clip_array */
static void
d2flac24_clip_array (const double *src, int32_t *dest, int count, int normalize)
{ double normfact, scaled_value ;
normfact = normalize ? (8.0 * 0x100000) : 1.0 ;
while (--count >= 0)
{ scaled_value = src [count] * normfact ;
if (CPU_CLIPS_POSITIVE == 0 && scaled_value >= (1.0 * 0x7FFFFF))
{ dest [count] = 0x7FFFFF ;
continue ;
} ;
if (CPU_CLIPS_NEGATIVE == 0 && scaled_value <= (-8.0 * 0x100000))
{ dest [count] = 0x800000 ;
continue ;
} ;
dest [count] = lrint (scaled_value) ;
} ;
return ;
} /* d2flac24_clip_array */
static void
d2flac8_array (const double *src, int32_t *dest, int count, int normalize)
{ double normfact = normalize ? (1.0 * 0x7F) : 1.0 ;
while (--count >= 0)
dest [count] = lrint (src [count] * normfact) ;
} /* d2flac8_array */
static void
d2flac16_array (const double *src, int32_t *dest, int count, int normalize)
{ double normfact = normalize ? (1.0 * 0x7FFF) : 1.0 ;
while (--count >= 0)
dest [count] = lrint (src [count] * normfact) ;
} /* d2flac16_array */
static void
d2flac24_array (const double *src, int32_t *dest, int count, int normalize)
{ double normfact = normalize ? (1.0 * 0x7FFFFF) : 1.0 ;
while (--count >= 0)
dest [count] = lrint (src [count] * normfact) ;
} /* d2flac24_array */
static sf_count_t
flac_seek (SF_PRIVATE *psf, int UNUSED (mode), sf_count_t offset)
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
if (pflac == NULL)
return 0 ;
if (psf->dataoffset < 0)
{ psf->error = SFE_BAD_SEEK ;
return ((sf_count_t) -1) ;
} ;
pflac->frame = NULL ;
if (psf->file.mode == SFM_READ)
{ if (FLAC__stream_decoder_seek_absolute (pflac->fsd, offset))
return offset ;
if (offset == psf->sf.frames)
{ /*
** If we've been asked to seek to the very end of the file, libFLAC
** will return an error. However, we know the length of the file so
** instead of returning an error, we can return the offset.
*/
return offset ;
} ;
psf->error = SFE_BAD_SEEK ;
return ((sf_count_t) -1) ;
} ;
/* Seeking in write mode not yet supported. */
psf->error = SFE_BAD_SEEK ;
return ((sf_count_t) -1) ;
} /* flac_seek */
static int
flac_byterate (SF_PRIVATE *psf)
{
if (psf->file.mode == SFM_READ)
return (psf->datalength * psf->sf.samplerate) / psf->sf.frames ;
return -1 ;
} /* flac_byterate */
#else /* HAVE_EXTERNAL_XIPH_LIBS */
int
flac_open (SF_PRIVATE *psf)
{
psf_log_printf (psf, "This version of libsndfile was compiled without FLAC support.\n") ;
return SFE_UNIMPLEMENTED ;
} /* flac_open */
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3287_0 |
crossvul-cpp_data_good_346_2 | /*
* card-muscle.c: Support for MuscleCard Applet from musclecard.com
*
* Copyright (C) 2006, Identity Alliance, Thomas Harning <support@identityalliance.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include "internal.h"
#include "cardctl.h"
#include "muscle.h"
#include "muscle-filesystem.h"
#include "types.h"
#include "opensc.h"
static struct sc_card_operations muscle_ops;
static const struct sc_card_operations *iso_ops = NULL;
static struct sc_card_driver muscle_drv = {
"MuscleApplet",
"muscle",
&muscle_ops,
NULL, 0, NULL
};
static struct sc_atr_table muscle_atrs[] = {
/* Tyfone JCOP 242R2 cards */
{ "3b:6d:00:00:ff:54:79:66:6f:6e:65:20:32:34:32:52:32", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU, 0, NULL },
/* Aladdin eToken PRO USB 72K Java */
{ "3b:d5:18:00:81:31:3a:7d:80:73:c8:21:10:30", NULL, NULL, SC_CARD_TYPE_MUSCLE_ETOKEN_72K, 0, NULL },
/* JCOP31 v2.4.1 contact interface */
{ "3b:f8:13:00:00:81:31:fe:45:4a:43:4f:50:76:32:34:31:b7", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL },
/* JCOP31 v2.4.1 RF interface */
{ "3b:88:80:01:4a:43:4f:50:76:32:34:31:5e", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
#define MUSCLE_DATA(card) ( (muscle_private_t*)card->drv_data )
#define MUSCLE_FS(card) ( ((muscle_private_t*)card->drv_data)->fs )
typedef struct muscle_private {
sc_security_env_t env;
unsigned short verifiedPins;
mscfs_t *fs;
int rsa_key_ref;
} muscle_private_t;
static int muscle_finish(sc_card_t *card)
{
muscle_private_t *priv = MUSCLE_DATA(card);
mscfs_free(priv->fs);
free(priv);
return 0;
}
static u8 muscleAppletId[] = { 0xA0, 0x00,0x00,0x00, 0x01, 0x01 };
static int muscle_match_card(sc_card_t *card)
{
sc_apdu_t apdu;
u8 response[64];
int r;
/* Since we send an APDU, the card's logout function may be called...
* however it's not always properly nulled out... */
card->ops->logout = NULL;
if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) == 1) {
/* Muscle applet is present, check the protocol version to be sure */
sc_format_apdu(card, &apdu, SC_APDU_CASE_2, 0x3C, 0x00, 0x00);
apdu.cla = 0xB0;
apdu.le = 64;
apdu.resplen = 64;
apdu.resp = response;
r = sc_transmit_apdu(card, &apdu);
if (r == SC_SUCCESS && response[0] == 0x01) {
card->type = SC_CARD_TYPE_MUSCLE_V1;
} else {
card->type = SC_CARD_TYPE_MUSCLE_GENERIC;
}
return 1;
}
return 0;
}
/* Since Musclecard has a different ACL system then PKCS15
* objects need to have their READ/UPDATE/DELETE permissions mapped for files
* and directory ACLS need to be set
* For keys.. they have different ACLS, but are accessed in different locations, so it shouldn't be an issue here
*/
static unsigned short muscle_parse_singleAcl(const sc_acl_entry_t* acl)
{
unsigned short acl_entry = 0;
while(acl) {
int key = acl->key_ref;
int method = acl->method;
switch(method) {
case SC_AC_NEVER:
return 0xFFFF;
/* Ignore... other items overwrite these */
case SC_AC_NONE:
case SC_AC_UNKNOWN:
break;
case SC_AC_CHV:
acl_entry |= (1 << key); /* Assuming key 0 == SO */
break;
case SC_AC_AUT:
case SC_AC_TERM:
case SC_AC_PRO:
default:
/* Ignored */
break;
}
acl = acl->next;
}
return acl_entry;
}
static void muscle_parse_acls(const sc_file_t* file, unsigned short* read_perm, unsigned short* write_perm, unsigned short* delete_perm)
{
assert(read_perm && write_perm && delete_perm);
*read_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_READ));
*write_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_UPDATE));
*delete_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_DELETE));
}
static int muscle_create_directory(sc_card_t *card, sc_file_t *file)
{
mscfs_t *fs = MUSCLE_FS(card);
msc_id objectId;
u8* oid = objectId.id;
unsigned id = file->id;
unsigned short read_perm = 0, write_perm = 0, delete_perm = 0;
int objectSize;
int r;
if(id == 0) /* No null name files */
return SC_ERROR_INVALID_ARGUMENTS;
/* No nesting directories */
if(fs->currentPath[0] != 0x3F || fs->currentPath[1] != 0x00)
return SC_ERROR_NOT_SUPPORTED;
oid[0] = ((id & 0xFF00) >> 8) & 0xFF;
oid[1] = id & 0xFF;
oid[2] = oid[3] = 0;
objectSize = file->size;
muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm);
r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm);
mscfs_clear_cache(fs);
if(r >= 0) return 0;
return r;
}
static int muscle_create_file(sc_card_t *card, sc_file_t *file)
{
mscfs_t *fs = MUSCLE_FS(card);
int objectSize = file->size;
unsigned short read_perm = 0, write_perm = 0, delete_perm = 0;
msc_id objectId;
int r;
if(file->type == SC_FILE_TYPE_DF)
return muscle_create_directory(card, file);
if(file->type != SC_FILE_TYPE_WORKING_EF)
return SC_ERROR_NOT_SUPPORTED;
if(file->id == 0) /* No null name files */
return SC_ERROR_INVALID_ARGUMENTS;
muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm);
mscfs_lookup_local(fs, file->id, &objectId);
r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm);
mscfs_clear_cache(fs);
if(r >= 0) return 0;
return r;
}
static int muscle_read_binary(sc_card_t *card, unsigned int idx, u8* buf, size_t count, unsigned long flags)
{
mscfs_t *fs = MUSCLE_FS(card);
int r;
msc_id objectId;
u8* oid = objectId.id;
mscfs_file_t *file;
r = mscfs_check_selection(fs, -1);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
file = &fs->cache.array[fs->currentFileIndex];
objectId = file->objectId;
/* memcpy(objectId.id, file->objectId.id, 4); */
if(!file->ef) {
oid[0] = oid[2];
oid[1] = oid[3];
oid[2] = oid[3] = 0;
}
r = msc_read_object(card, objectId, idx, buf, count);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
static int muscle_update_binary(sc_card_t *card, unsigned int idx, const u8* buf, size_t count, unsigned long flags)
{
mscfs_t *fs = MUSCLE_FS(card);
int r;
mscfs_file_t *file;
msc_id objectId;
u8* oid = objectId.id;
r = mscfs_check_selection(fs, -1);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
file = &fs->cache.array[fs->currentFileIndex];
objectId = file->objectId;
/* memcpy(objectId.id, file->objectId.id, 4); */
if(!file->ef) {
oid[0] = oid[2];
oid[1] = oid[3];
oid[2] = oid[3] = 0;
}
if(file->size < idx + count) {
int newFileSize = idx + count;
u8* buffer = malloc(newFileSize);
if(buffer == NULL) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
r = msc_read_object(card, objectId, 0, buffer, file->size);
/* TODO: RETRIEVE ACLS */
if(r < 0) goto update_bin_free_buffer;
r = msc_delete_object(card, objectId, 0);
if(r < 0) goto update_bin_free_buffer;
r = msc_create_object(card, objectId, newFileSize, 0,0,0);
if(r < 0) goto update_bin_free_buffer;
memcpy(buffer + idx, buf, count);
r = msc_update_object(card, objectId, 0, buffer, newFileSize);
if(r < 0) goto update_bin_free_buffer;
file->size = newFileSize;
update_bin_free_buffer:
free(buffer);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
} else {
r = msc_update_object(card, objectId, idx, buf, count);
}
/* mscfs_clear_cache(fs); */
return r;
}
/* TODO: Evaluate correctness */
static int muscle_delete_mscfs_file(sc_card_t *card, mscfs_file_t *file_data)
{
mscfs_t *fs = MUSCLE_FS(card);
msc_id id = file_data->objectId;
u8* oid = id.id;
int r;
if(!file_data->ef) {
int x;
mscfs_file_t *childFile;
/* Delete children */
mscfs_check_cache(fs);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"DELETING Children of: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
for(x = 0; x < fs->cache.size; x++) {
msc_id objectId;
childFile = &fs->cache.array[x];
objectId = childFile->objectId;
if(0 == memcmp(oid + 2, objectId.id, 2)) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"DELETING: %02X%02X%02X%02X\n",
objectId.id[0],objectId.id[1],
objectId.id[2],objectId.id[3]);
r = muscle_delete_mscfs_file(card, childFile);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
}
}
oid[0] = oid[2];
oid[1] = oid[3];
oid[2] = oid[3] = 0;
/* ??? objectId = objectId >> 16; */
}
if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4))
|| (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) {
}
r = msc_delete_object(card, id, 1);
/* Check if its the root... this file generally is virtual
* So don't return an error if it fails */
if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4))
|| (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4)))
return 0;
if(r < 0) {
printf("ID: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
}
return 0;
}
static int muscle_delete_file(sc_card_t *card, const sc_path_t *path_in)
{
mscfs_t *fs = MUSCLE_FS(card);
mscfs_file_t *file_data = NULL;
int r = 0;
r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, NULL);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
r = muscle_delete_mscfs_file(card, file_data);
mscfs_clear_cache(fs);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
return 0;
}
static void muscle_load_single_acl(sc_file_t* file, int operation, unsigned short acl)
{
int key;
/* Everybody by default.... */
sc_file_add_acl_entry(file, operation, SC_AC_NONE, 0);
if(acl == 0xFFFF) {
sc_file_add_acl_entry(file, operation, SC_AC_NEVER, 0);
return;
}
for(key = 0; key < 16; key++) {
if(acl >> key & 1) {
sc_file_add_acl_entry(file, operation, SC_AC_CHV, key);
}
}
}
static void muscle_load_file_acls(sc_file_t* file, mscfs_file_t *file_data)
{
muscle_load_single_acl(file, SC_AC_OP_READ, file_data->read);
muscle_load_single_acl(file, SC_AC_OP_WRITE, file_data->write);
muscle_load_single_acl(file, SC_AC_OP_UPDATE, file_data->write);
muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete);
}
static void muscle_load_dir_acls(sc_file_t* file, mscfs_file_t *file_data)
{
muscle_load_single_acl(file, SC_AC_OP_SELECT, 0);
muscle_load_single_acl(file, SC_AC_OP_LIST_FILES, 0);
muscle_load_single_acl(file, SC_AC_OP_LOCK, 0xFFFF);
muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete);
muscle_load_single_acl(file, SC_AC_OP_CREATE, file_data->write);
}
/* Required type = -1 for don't care, 1 for EF, 0 for DF */
static int select_item(sc_card_t *card, const sc_path_t *path_in, sc_file_t ** file_out, int requiredType)
{
mscfs_t *fs = MUSCLE_FS(card);
mscfs_file_t *file_data = NULL;
int pathlen = path_in->len;
int r = 0;
int objectIndex;
u8* oid;
mscfs_check_cache(fs);
r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, &objectIndex);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
/* Check if its the right type */
if(requiredType >= 0 && requiredType != file_data->ef) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
}
oid = file_data->objectId.id;
/* Is it a file or directory */
if(file_data->ef) {
fs->currentPath[0] = oid[0];
fs->currentPath[1] = oid[1];
fs->currentFile[0] = oid[2];
fs->currentFile[1] = oid[3];
} else {
fs->currentPath[0] = oid[pathlen - 2];
fs->currentPath[1] = oid[pathlen - 1];
fs->currentFile[0] = 0;
fs->currentFile[1] = 0;
}
fs->currentFileIndex = objectIndex;
if(file_out) {
sc_file_t *file;
file = sc_file_new();
file->path = *path_in;
file->size = file_data->size;
file->id = (oid[2] << 8) | oid[3];
if(!file_data->ef) {
file->type = SC_FILE_TYPE_DF;
} else {
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_TRANSPARENT;
}
/* Setup ACLS */
if(file_data->ef) {
muscle_load_file_acls(file, file_data);
} else {
muscle_load_dir_acls(file, file_data);
/* Setup directory acls... */
}
file->magic = SC_FILE_MAGIC;
*file_out = file;
}
return 0;
}
static int muscle_select_file(sc_card_t *card, const sc_path_t *path_in,
sc_file_t **file_out)
{
int r;
assert(card != NULL && path_in != NULL);
switch (path_in->type) {
case SC_PATH_TYPE_FILE_ID:
r = select_item(card, path_in, file_out, 1);
break;
case SC_PATH_TYPE_DF_NAME:
r = select_item(card, path_in, file_out, 0);
break;
case SC_PATH_TYPE_PATH:
r = select_item(card, path_in, file_out, -1);
break;
default:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
if(r > 0) r = 0;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
}
static int _listFile(mscfs_file_t *file, int reset, void *udata)
{
int next = reset ? 0x00 : 0x01;
return msc_list_objects( (sc_card_t*)udata, next, file);
}
static int muscle_init(sc_card_t *card)
{
muscle_private_t *priv;
card->name = "MuscleApplet";
card->drv_data = malloc(sizeof(muscle_private_t));
if(!card->drv_data) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
}
memset(card->drv_data, 0, sizeof(muscle_private_t));
priv = MUSCLE_DATA(card);
priv->verifiedPins = 0;
priv->fs = mscfs_new();
if(!priv->fs) {
free(card->drv_data);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
}
priv->fs->udata = card;
priv->fs->listFile = _listFile;
card->cla = 0xB0;
card->flags |= SC_CARD_FLAG_RNG;
card->caps |= SC_CARD_CAP_RNG;
/* Card type detection */
_sc_match_atr(card, muscle_atrs, &card->type);
if(card->type == SC_CARD_TYPE_MUSCLE_ETOKEN_72K) {
card->caps |= SC_CARD_CAP_APDU_EXT;
}
if(card->type == SC_CARD_TYPE_MUSCLE_JCOP241) {
card->caps |= SC_CARD_CAP_APDU_EXT;
}
if (!(card->caps & SC_CARD_CAP_APDU_EXT)) {
card->max_recv_size = 255;
card->max_send_size = 255;
}
if(card->type == SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU) {
/* Tyfone JCOP v242R2 card that doesn't support extended APDUs */
}
/* FIXME: Card type detection */
if (1) {
unsigned long flags;
flags = SC_ALGORITHM_RSA_RAW;
flags |= SC_ALGORITHM_RSA_HASH_NONE;
flags |= SC_ALGORITHM_ONBOARD_KEY_GEN;
_sc_card_add_rsa_alg(card, 1024, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
}
return SC_SUCCESS;
}
static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)
{
muscle_private_t* priv = MUSCLE_DATA(card);
mscfs_t *fs = priv->fs;
int x;
int count = 0;
mscfs_check_cache(priv->fs);
for(x = 0; x < fs->cache.size; x++) {
u8* oid = fs->cache.array[x].objectId.id;
if (bufLen < 2)
break;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"FILE: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
if(0 == memcmp(fs->currentPath, oid, 2)) {
buf[0] = oid[2];
buf[1] = oid[3];
if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */
buf += 2;
count += 2;
bufLen -= 2;
}
}
return count;
}
static int muscle_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *cmd,
int *tries_left)
{
muscle_private_t* priv = MUSCLE_DATA(card);
const int bufferLength = MSC_MAX_PIN_COMMAND_LENGTH;
u8 buffer[MSC_MAX_PIN_COMMAND_LENGTH];
switch(cmd->cmd) {
case SC_PIN_CMD_VERIFY:
switch(cmd->pin_type) {
case SC_AC_CHV: {
sc_apdu_t apdu;
int r;
msc_verify_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len);
cmd->apdu = &apdu;
cmd->pin1.offset = 5;
r = iso_ops->pin_cmd(card, cmd, tries_left);
if(r >= 0)
priv->verifiedPins |= (1 << cmd->pin_reference);
return r;
}
case SC_AC_TERM:
case SC_AC_PRO:
case SC_AC_AUT:
case SC_AC_NONE:
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n");
return SC_ERROR_NOT_SUPPORTED;
}
case SC_PIN_CMD_CHANGE:
switch(cmd->pin_type) {
case SC_AC_CHV: {
sc_apdu_t apdu;
msc_change_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len, cmd->pin2.data, cmd->pin2.len);
cmd->apdu = &apdu;
return iso_ops->pin_cmd(card, cmd, tries_left);
}
case SC_AC_TERM:
case SC_AC_PRO:
case SC_AC_AUT:
case SC_AC_NONE:
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n");
return SC_ERROR_NOT_SUPPORTED;
}
case SC_PIN_CMD_UNBLOCK:
switch(cmd->pin_type) {
case SC_AC_CHV: {
sc_apdu_t apdu;
msc_unblock_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len);
cmd->apdu = &apdu;
return iso_ops->pin_cmd(card, cmd, tries_left);
}
case SC_AC_TERM:
case SC_AC_PRO:
case SC_AC_AUT:
case SC_AC_NONE:
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n");
return SC_ERROR_NOT_SUPPORTED;
}
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported command\n");
return SC_ERROR_NOT_SUPPORTED;
}
}
static int muscle_card_extract_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info)
{
/* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */
switch(info->keyType) {
case 1: /* RSA */
return msc_extract_rsa_public_key(card,
info->keyLocation,
&info->modLength,
&info->modValue,
&info->expLength,
&info->expValue);
default:
return SC_ERROR_NOT_SUPPORTED;
}
}
static int muscle_card_import_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info)
{
/* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */
switch(info->keyType) {
case 0x02: /* RSA_PRIVATE */
case 0x03: /* RSA_PRIVATE_CRT */
return msc_import_key(card,
info->keyLocation,
info);
default:
return SC_ERROR_NOT_SUPPORTED;
}
}
static int muscle_card_generate_key(sc_card_t *card, sc_cardctl_muscle_gen_key_info_t *info)
{
return msc_generate_keypair(card,
info->privateKeyLocation,
info->publicKeyLocation,
info->keyType,
info->keySize,
0);
}
static int muscle_card_verified_pins(sc_card_t *card, sc_cardctl_muscle_verified_pins_info_t *info)
{
muscle_private_t* priv = MUSCLE_DATA(card);
info->verifiedPins = priv->verifiedPins;
return 0;
}
static int muscle_card_ctl(sc_card_t *card, unsigned long request, void *data)
{
switch(request) {
case SC_CARDCTL_MUSCLE_GENERATE_KEY:
return muscle_card_generate_key(card, (sc_cardctl_muscle_gen_key_info_t*) data);
case SC_CARDCTL_MUSCLE_EXTRACT_KEY:
return muscle_card_extract_key(card, (sc_cardctl_muscle_key_info_t*) data);
case SC_CARDCTL_MUSCLE_IMPORT_KEY:
return muscle_card_import_key(card, (sc_cardctl_muscle_key_info_t*) data);
case SC_CARDCTL_MUSCLE_VERIFIED_PINS:
return muscle_card_verified_pins(card, (sc_cardctl_muscle_verified_pins_info_t*) data);
default:
return SC_ERROR_NOT_SUPPORTED; /* Unsupported.. whatever it is */
}
}
static int muscle_set_security_env(sc_card_t *card,
const sc_security_env_t *env,
int se_num)
{
muscle_private_t* priv = MUSCLE_DATA(card);
if (env->operation != SC_SEC_OPERATION_SIGN &&
env->operation != SC_SEC_OPERATION_DECIPHER) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto operation supplied.\n");
return SC_ERROR_NOT_SUPPORTED;
}
if (env->algorithm != SC_ALGORITHM_RSA) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto algorithm supplied.\n");
return SC_ERROR_NOT_SUPPORTED;
}
/* ADJUST FOR PKCS1 padding support for decryption only */
if ((env->algorithm_flags & SC_ALGORITHM_RSA_PADS) ||
(env->algorithm_flags & SC_ALGORITHM_RSA_HASHES)) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card supports only raw RSA.\n");
return SC_ERROR_NOT_SUPPORTED;
}
if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) {
if (env->key_ref_len != 1 ||
(env->key_ref[0] > 0x0F)) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid key reference supplied.\n");
return SC_ERROR_NOT_SUPPORTED;
}
priv->rsa_key_ref = env->key_ref[0];
}
if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Algorithm reference not supported.\n");
return SC_ERROR_NOT_SUPPORTED;
}
/* if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT)
if (memcmp(env->file_ref.value, "\x00\x12", 2) != 0) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File reference is not 0012.\n");
return SC_ERROR_NOT_SUPPORTED;
} */
priv->env = *env;
return 0;
}
static int muscle_restore_security_env(sc_card_t *card, int se_num)
{
muscle_private_t* priv = MUSCLE_DATA(card);
memset(&priv->env, 0, sizeof(priv->env));
return 0;
}
static int muscle_decipher(sc_card_t * card,
const u8 * crgram, size_t crgram_len, u8 * out,
size_t out_len)
{
muscle_private_t* priv = MUSCLE_DATA(card);
u8 key_id;
int r;
/* sanity check */
if (priv->env.operation != SC_SEC_OPERATION_DECIPHER)
return SC_ERROR_INVALID_ARGUMENTS;
key_id = priv->rsa_key_ref * 2; /* Private key */
if (out_len < crgram_len) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small");
return SC_ERROR_BUFFER_TOO_SMALL;
}
r = msc_compute_crypt(card,
key_id,
0x00, /* RSA NO PADDING */
0x04, /* decrypt */
crgram,
out,
crgram_len,
out_len);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed");
return r;
}
static int muscle_compute_signature(sc_card_t *card, const u8 *data,
size_t data_len, u8 * out, size_t outlen)
{
muscle_private_t* priv = MUSCLE_DATA(card);
u8 key_id;
int r;
key_id = priv->rsa_key_ref * 2; /* Private key */
if (outlen < data_len) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small");
return SC_ERROR_BUFFER_TOO_SMALL;
}
r = msc_compute_crypt(card,
key_id,
0x00, /* RSA NO PADDING */
0x04, /* -- decrypt raw... will do what we need since signing isn't yet supported */
data,
out,
data_len,
outlen);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed");
return r;
}
static int muscle_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
{
if (len == 0)
return SC_SUCCESS;
else {
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL,
msc_get_challenge(card, len, 0, NULL, rnd),
"GET CHALLENGE cmd failed");
return (int) len;
}
}
static int muscle_check_sw(sc_card_t * card, unsigned int sw1, unsigned int sw2) {
if(sw1 == 0x9C) {
switch(sw2) {
case 0x01: /* SW_NO_MEMORY_LEFT */
return SC_ERROR_NOT_ENOUGH_MEMORY;
case 0x02: /* SW_AUTH_FAILED */
return SC_ERROR_PIN_CODE_INCORRECT;
case 0x03: /* SW_OPERATION_NOT_ALLOWED */
return SC_ERROR_NOT_ALLOWED;
case 0x05: /* SW_UNSUPPORTED_FEATURE */
return SC_ERROR_NO_CARD_SUPPORT;
case 0x06: /* SW_UNAUTHORIZED */
return SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;
case 0x07: /* SW_OBJECT_NOT_FOUND */
return SC_ERROR_FILE_NOT_FOUND;
case 0x08: /* SW_OBJECT_EXISTS */
return SC_ERROR_FILE_ALREADY_EXISTS;
case 0x09: /* SW_INCORRECT_ALG */
return SC_ERROR_INCORRECT_PARAMETERS;
case 0x0B: /* SW_SIGNATURE_INVALID */
return SC_ERROR_CARD_CMD_FAILED;
case 0x0C: /* SW_IDENTITY_BLOCKED */
return SC_ERROR_AUTH_METHOD_BLOCKED;
case 0x0F: /* SW_INVALID_PARAMETER */
case 0x10: /* SW_INCORRECT_P1 */
case 0x11: /* SW_INCORRECT_P2 */
return SC_ERROR_INCORRECT_PARAMETERS;
}
}
return iso_ops->check_sw(card, sw1, sw2);
}
static int muscle_card_reader_lock_obtained(sc_card_t *card, int was_reset)
{
int r = SC_SUCCESS;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (was_reset > 0) {
if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) != 1) {
r = SC_ERROR_INVALID_CARD;
}
}
LOG_FUNC_RETURN(card->ctx, r);
}
static struct sc_card_driver * sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (iso_ops == NULL)
iso_ops = iso_drv->ops;
muscle_ops = *iso_drv->ops;
muscle_ops.check_sw = muscle_check_sw;
muscle_ops.pin_cmd = muscle_pin_cmd;
muscle_ops.match_card = muscle_match_card;
muscle_ops.init = muscle_init;
muscle_ops.finish = muscle_finish;
muscle_ops.get_challenge = muscle_get_challenge;
muscle_ops.set_security_env = muscle_set_security_env;
muscle_ops.restore_security_env = muscle_restore_security_env;
muscle_ops.compute_signature = muscle_compute_signature;
muscle_ops.decipher = muscle_decipher;
muscle_ops.card_ctl = muscle_card_ctl;
muscle_ops.read_binary = muscle_read_binary;
muscle_ops.update_binary = muscle_update_binary;
muscle_ops.create_file = muscle_create_file;
muscle_ops.select_file = muscle_select_file;
muscle_ops.delete_file = muscle_delete_file;
muscle_ops.list_files = muscle_list_files;
muscle_ops.card_reader_lock_obtained = muscle_card_reader_lock_obtained;
return &muscle_drv;
}
struct sc_card_driver * sc_get_muscle_driver(void)
{
return sc_get_driver();
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_346_2 |
crossvul-cpp_data_good_4787_9 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% CCC U U TTTTT %
% C U U T %
% C U U T %
% C U U T %
% CCC UUU T %
% %
% %
% Read DR Halo Image Format %
% %
% Software Design %
% Jaroslav Fojtik %
% June 2000 %
% %
% %
% Permission is hereby granted, free of charge, to any person obtaining a %
% copy of this software and associated documentation files ("ImageMagick"), %
% to deal in ImageMagick without restriction, including without limitation %
% the rights to use, copy, modify, merge, publish, distribute, sublicense, %
% and/or sell copies of ImageMagick, and to permit persons to whom the %
% ImageMagick is furnished to do so, subject to the following conditions: %
% %
% The above copyright notice and this permission notice shall be included in %
% all copies or substantial portions of ImageMagick. %
% %
% The software is provided "as is", without warranty of any kind, express or %
% implied, including but not limited to the warranties of merchantability, %
% fitness for a particular purpose and noninfringement. In no event shall %
% ImageMagick Studio be liable for any claim, damages or other liability, %
% whether in an action of contract, tort or otherwise, arising from, out of %
% or in connection with ImageMagick or the use or other dealings in %
% ImageMagick. %
% %
% Except as contained in this notice, the name of the ImageMagick Studio %
% shall not be used in advertising or otherwise to promote the sale, use or %
% other dealings in ImageMagick without prior written authorization from the %
% ImageMagick Studio. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colormap-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
#include "magick/utility.h"
#include "magick/utility-private.h"
typedef struct
{
unsigned Width;
unsigned Height;
unsigned Reserved;
} CUTHeader;
typedef struct
{
char FileId[2];
unsigned Version;
unsigned Size;
char FileType;
char SubType;
unsigned BoardID;
unsigned GraphicsMode;
unsigned MaxIndex;
unsigned MaxRed;
unsigned MaxGreen;
unsigned MaxBlue;
char PaletteId[20];
} CUTPalHeader;
static void InsertRow(ssize_t depth,unsigned char *p,ssize_t y,Image *image)
{
ExceptionInfo
*exception;
size_t bit; ssize_t x;
register PixelPacket *q;
IndexPacket index;
register IndexPacket *indexes;
index=(IndexPacket) 0;
exception=(&image->exception);
switch (depth)
{
case 1: /* Convert bitmap scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=(IndexPacket) ((((*p) & (0x80 >> bit)) != 0) ? 0x01 : 0x00);
SetPixelIndex(indexes+x+bit,index);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (image->columns % 8); bit++)
{
index=(IndexPacket) ((((*p) & (0x80 >> bit)) != 0) ? 0x01 : 0x00);
SetPixelIndex(indexes+x+bit,index);
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
break;
}
case 2: /* Convert PseudoColor scanline. */
{
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-1); x+=2)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3);
SetPixelIndex(indexes+x,index);
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3);
SetPixelIndex(indexes+x,index);
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3);
SetPixelIndex(indexes+x,index);
index=ConstrainColormapIndex(image,(*p) & 0x3);
SetPixelIndex(indexes+x+1,index);
p++;
}
if ((image->columns % 4) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3);
SetPixelIndex(indexes+x,index);
if ((image->columns % 4) >= 1)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3);
SetPixelIndex(indexes+x,index);
if ((image->columns % 4) >= 2)
{
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3);
SetPixelIndex(indexes+x,index);
}
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
break;
}
case 4: /* Convert PseudoColor scanline. */
{
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-1); x+=2)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0xf);
SetPixelIndex(indexes+x,index);
index=ConstrainColormapIndex(image,(*p) & 0xf);
SetPixelIndex(indexes+x+1,index);
p++;
}
if ((image->columns % 2) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0xf);
SetPixelIndex(indexes+x,index);
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
break;
}
case 8: /* Convert PseudoColor scanline. */
{
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++)
{
index=ConstrainColormapIndex(image,*p);
SetPixelIndex(indexes+x,index);
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
break;
}
}
/*
Compute the number of colors in Grayed R[i]=G[i]=B[i] image
*/
static int GetCutColors(Image *image)
{
ExceptionInfo
*exception;
Quantum
intensity,
scale_intensity;
register PixelPacket
*q;
ssize_t
x,
y;
exception=(&image->exception);
intensity=0;
scale_intensity=ScaleCharToQuantum(16);
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (intensity < GetPixelRed(q))
intensity=GetPixelRed(q);
if (intensity >= scale_intensity)
return(255);
q++;
}
}
if (intensity < ScaleCharToQuantum(2))
return(2);
if (intensity < ScaleCharToQuantum(16))
return(16);
return((int) intensity);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d C U T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadCUTImage() reads an CUT X image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadCUTImage method is:
%
% Image *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image,*palette;
ImageInfo *clone_info;
MagickBooleanType status;
MagickOffsetType
offset;
size_t EncodedByte;
unsigned char RunCount,RunValue,RunCountMasked;
CUTHeader Header;
CUTPalHeader PalHeader;
ssize_t depth;
ssize_t i,j;
ssize_t ldblk;
unsigned char *BImgBuff=NULL,*ptrB;
PixelPacket *q;
/*
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 CUT image.
*/
palette=NULL;
clone_info=NULL;
Header.Width=ReadBlobLSBShort(image);
Header.Height=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.Width==0 || Header.Height==0 || Header.Reserved!=0)
CUT_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*---This code checks first line of image---*/
EncodedByte=ReadBlobLSBShort(image);
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
ldblk=0;
while((int) RunCountMasked!=0) /*end of line?*/
{
i=1;
if((int) RunCount<0x80) i=(ssize_t) RunCountMasked;
offset=SeekBlob(image,TellBlob(image)+i,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data*/
EncodedByte-=i+1;
ldblk+=(ssize_t) RunCountMasked;
RunCount=(unsigned char) ReadBlobByte(image);
if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data: unexpected eof in line*/
RunCountMasked=RunCount & 0x7F;
}
if(EncodedByte!=1) goto CUT_KO; /*wrong data: size incorrect*/
i=0; /*guess a number of bit planes*/
if(ldblk==(int) Header.Width) i=8;
if(2*ldblk==(int) Header.Width) i=4;
if(8*ldblk==(int) Header.Width) i=1;
if(i==0) goto CUT_KO; /*wrong data: incorrect bit planes*/
depth=i;
image->columns=Header.Width;
image->rows=Header.Height;
image->depth=8;
image->colors=(size_t) (GetQuantumRange(1UL*i)+1);
if (image_info->ping != MagickFalse) goto Finish;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/* ----- Do something with palette ----- */
if ((clone_info=CloneImageInfo(image_info)) == NULL) goto NoPalette;
i=(ssize_t) strlen(clone_info->filename);
j=i;
while(--i>0)
{
if(clone_info->filename[i]=='.')
{
break;
}
if(clone_info->filename[i]=='/' || clone_info->filename[i]=='\\' ||
clone_info->filename[i]==':' )
{
i=j;
break;
}
}
(void) CopyMagickString(clone_info->filename+i,".PAL",(size_t)
(MaxTextExtent-i));
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
(void) CopyMagickString(clone_info->filename+i,".pal",(size_t)
(MaxTextExtent-i));
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
clone_info->filename[i]='\0';
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
clone_info=DestroyImageInfo(clone_info);
clone_info=NULL;
goto NoPalette;
}
}
}
if( (palette=AcquireImage(clone_info))==NULL ) goto NoPalette;
status=OpenBlob(clone_info,palette,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
ErasePalette:
palette=DestroyImage(palette);
palette=NULL;
goto NoPalette;
}
if(palette!=NULL)
{
(void) ReadBlob(palette,2,(unsigned char *) PalHeader.FileId);
if(strncmp(PalHeader.FileId,"AH",2) != 0) goto ErasePalette;
PalHeader.Version=ReadBlobLSBShort(palette);
PalHeader.Size=ReadBlobLSBShort(palette);
PalHeader.FileType=(char) ReadBlobByte(palette);
PalHeader.SubType=(char) ReadBlobByte(palette);
PalHeader.BoardID=ReadBlobLSBShort(palette);
PalHeader.GraphicsMode=ReadBlobLSBShort(palette);
PalHeader.MaxIndex=ReadBlobLSBShort(palette);
PalHeader.MaxRed=ReadBlobLSBShort(palette);
PalHeader.MaxGreen=ReadBlobLSBShort(palette);
PalHeader.MaxBlue=ReadBlobLSBShort(palette);
(void) ReadBlob(palette,20,(unsigned char *) PalHeader.PaletteId);
if(PalHeader.MaxIndex<1) goto ErasePalette;
image->colors=PalHeader.MaxIndex+1;
if (AcquireImageColormap(image,image->colors) == MagickFalse) goto NoMemory;
if(PalHeader.MaxRed==0) PalHeader.MaxRed=(unsigned int) QuantumRange; /*avoid division by 0*/
if(PalHeader.MaxGreen==0) PalHeader.MaxGreen=(unsigned int) QuantumRange;
if(PalHeader.MaxBlue==0) PalHeader.MaxBlue=(unsigned int) QuantumRange;
for(i=0;i<=(int) PalHeader.MaxIndex;i++)
{ /*this may be wrong- I don't know why is palette such strange*/
j=(ssize_t) TellBlob(palette);
if((j % 512)>512-6)
{
j=((j / 512)+1)*512;
offset=SeekBlob(palette,j,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
image->colormap[i].red=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxRed)
{
image->colormap[i].red=ClampToQuantum(((double)
image->colormap[i].red*QuantumRange+(PalHeader.MaxRed>>1))/
PalHeader.MaxRed);
}
image->colormap[i].green=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxGreen)
{
image->colormap[i].green=ClampToQuantum
(((double) image->colormap[i].green*QuantumRange+(PalHeader.MaxGreen>>1))/PalHeader.MaxGreen);
}
image->colormap[i].blue=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxBlue)
{
image->colormap[i].blue=ClampToQuantum
(((double)image->colormap[i].blue*QuantumRange+(PalHeader.MaxBlue>>1))/PalHeader.MaxBlue);
}
}
}
NoPalette:
if(palette==NULL)
{
image->colors=256;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
{
NoMemory:
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t)image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
}
/* ----- Load RLE compressed raster ----- */
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,
sizeof(*BImgBuff)); /*Ldblk was set in the check phase*/
if(BImgBuff==NULL) goto NoMemory;
offset=SeekBlob(image,6 /*sizeof(Header)*/,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
for (i=0; i < (int) Header.Height; i++)
{
EncodedByte=ReadBlobLSBShort(image);
ptrB=BImgBuff;
j=ldblk;
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
while ((int) RunCountMasked != 0)
{
if((ssize_t) RunCountMasked>j)
{ /*Wrong Data*/
RunCountMasked=(unsigned char) j;
if(j==0)
{
break;
}
}
if((int) RunCount>0x80)
{
RunValue=(unsigned char) ReadBlobByte(image);
(void) ResetMagickMemory(ptrB,(int) RunValue,(size_t) RunCountMasked);
}
else {
(void) ReadBlob(image,(size_t) RunCountMasked,ptrB);
}
ptrB+=(int) RunCountMasked;
j-=(int) RunCountMasked;
if (EOFBlob(image) != MagickFalse) goto Finish; /* wrong data: unexpected eof in line */
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
}
InsertRow(depth,BImgBuff,i,image);
}
(void) SyncImage(image);
/*detect monochrome image*/
if(palette==NULL)
{ /*attempt to detect binary (black&white) images*/
if ((image->storage_class == PseudoClass) &&
(IsGrayImage(image,&image->exception) != MagickFalse))
{
if(GetCutColors(image)==2)
{
for (i=0; i < (ssize_t)image->colors; i++)
{
register Quantum
sample;
sample=ScaleCharToQuantum((unsigned char) i);
if(image->colormap[i].red!=sample) goto Finish;
if(image->colormap[i].green!=sample) goto Finish;
if(image->colormap[i].blue!=sample) goto Finish;
}
image->colormap[1].red=image->colormap[1].green=
image->colormap[1].blue=QuantumRange;
for (i=0; i < (ssize_t)image->rows; i++)
{
q=QueueAuthenticPixels(image,0,i,image->columns,1,exception);
for (j=0; j < (ssize_t)image->columns; j++)
{
if (GetPixelRed(q) == ScaleCharToQuantum(1))
{
SetPixelRed(q,QuantumRange);
SetPixelGreen(q,QuantumRange);
SetPixelBlue(q,QuantumRange);
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse) goto Finish;
}
}
}
}
Finish:
if (BImgBuff != NULL)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
if (palette != NULL)
palette=DestroyImage(palette);
if (clone_info != NULL)
clone_info=DestroyImageInfo(clone_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r C U T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterCUTImage() adds attributes for the CUT image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterCUTImage method is:
%
% size_t RegisterCUTImage(void)
%
*/
ModuleExport size_t RegisterCUTImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("CUT");
entry->decoder=(DecodeImageHandler *) ReadCUTImage;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("DR Halo");
entry->module=ConstantString("CUT");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r C U T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterCUTImage() removes format registrations made by the
% CUT module from the list of supported formats.
%
% The format of the UnregisterCUTImage method is:
%
% UnregisterCUTImage(void)
%
*/
ModuleExport void UnregisterCUTImage(void)
{
(void) UnregisterMagickInfo("CUT");
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4787_9 |
crossvul-cpp_data_good_2346_0 | /*
* Copyright (C) 2007-2008 Sourcefire, Inc.
*
* Authors: Alberto Wu, Tomasz Kojm
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
/*
#define _XOPEN_SOURCE 500
*/
#include <stdio.h>
#include <stdlib.h>
#if HAVE_STRING_H
#include <string.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <time.h>
#include <stdarg.h>
#include "cltypes.h"
#include "clamav.h"
#include "others.h"
#include "pe.h"
#include "petite.h"
#include "fsg.h"
#include "spin.h"
#include "upx.h"
#include "yc.h"
#include "aspack.h"
#include "wwunpack.h"
#include "unsp.h"
#include "scanners.h"
#include "str.h"
#include "execs.h"
#include "mew.h"
#include "upack.h"
#include "matcher.h"
#include "matcher-hash.h"
#include "disasm.h"
#include "special.h"
#include "ishield.h"
#include "asn1.h"
#include "json_api.h"
#define DCONF ctx->dconf->pe
#define PE_IMAGE_DOS_SIGNATURE 0x5a4d /* MZ */
#define PE_IMAGE_DOS_SIGNATURE_OLD 0x4d5a /* ZM */
#define PE_IMAGE_NT_SIGNATURE 0x00004550
#define PE32_SIGNATURE 0x010b
#define PE32P_SIGNATURE 0x020b
#define optional_hdr64 pe_opt.opt64
#define optional_hdr32 pe_opt.opt32
#define UPX_NRV2B "\x11\xdb\x11\xc9\x01\xdb\x75\x07\x8b\x1e\x83\xee\xfc\x11\xdb\x11\xc9\x11\xc9\x75\x20\x41\x01\xdb"
#define UPX_NRV2D "\x83\xf0\xff\x74\x78\xd1\xf8\x89\xc5\xeb\x0b\x01\xdb\x75\x07\x8b\x1e\x83\xee\xfc\x11\xdb\x11\xc9"
#define UPX_NRV2E "\xeb\x52\x31\xc9\x83\xe8\x03\x72\x11\xc1\xe0\x08\x8a\x06\x46\x83\xf0\xff\x74\x75\xd1\xf8\x89\xc5"
#define UPX_LZMA1 "\x56\x83\xc3\x04\x53\x50\xc7\x03\x03\x00\x02\x00\x90\x90\x90\x55\x57\x56\x53\x83"
#define UPX_LZMA2 "\x56\x83\xc3\x04\x53\x50\xc7\x03\x03\x00\x02\x00\x90\x90\x90\x90\x90\x55\x57\x56"
#define EC32(x) ((uint32_t)cli_readint32(&(x))) /* Convert little endian to host */
#define EC16(x) ((uint16_t)cli_readint16(&(x)))
/* lower and upper bondary alignment (size vs offset) */
#define PEALIGN(o,a) (((a))?(((o)/(a))*(a)):(o))
#define PESALIGN(o,a) (((a))?(((o)/(a)+((o)%(a)!=0))*(a)):(o))
#define CLI_UNPSIZELIMITS(NAME,CHK) \
if(cli_checklimits(NAME, ctx, (CHK), 0, 0)!=CL_CLEAN) { \
free(exe_sections); \
return CL_CLEAN; \
}
#define CLI_UNPTEMP(NAME,FREEME) \
if(!(tempfile = cli_gentemp(ctx->engine->tmpdir))) { \
cli_multifree FREEME; \
return CL_EMEM; \
} \
if((ndesc = open(tempfile, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) { \
cli_dbgmsg(NAME": Can't create file %s\n", tempfile); \
free(tempfile); \
cli_multifree FREEME; \
return CL_ECREAT; \
}
#define CLI_TMPUNLK() if(!ctx->engine->keeptmp) { \
if (cli_unlink(tempfile)) { \
free(tempfile); \
return CL_EUNLINK; \
} \
}
#ifdef HAVE__INTERNAL__SHA_COLLECT
#define SHA_OFF do { ctx->sha_collect = -1; } while(0)
#define SHA_RESET do { ctx->sha_collect = sha_collect; } while(0)
#else
#define SHA_OFF do {} while(0)
#define SHA_RESET do {} while(0)
#endif
#define FSGCASE(NAME,FREESEC) \
case 0: /* Unpacked and NOT rebuilt */ \
cli_dbgmsg(NAME": Successfully decompressed\n"); \
close(ndesc); \
if (cli_unlink(tempfile)) { \
free(exe_sections); \
free(tempfile); \
FREESEC; \
return CL_EUNLINK; \
} \
free(tempfile); \
FREESEC; \
found = 0; \
upx_success = 1; \
break; /* FSG ONLY! - scan raw data after upx block */
#define SPINCASE() \
case 2: \
free(spinned); \
close(ndesc); \
if (cli_unlink(tempfile)) { \
free(exe_sections); \
free(tempfile); \
return CL_EUNLINK; \
} \
cli_dbgmsg("PESpin: Size exceeded\n"); \
free(tempfile); \
break; \
#define CLI_UNPRESULTS_(NAME,FSGSTUFF,EXPR,GOOD,FREEME) \
switch(EXPR) { \
case GOOD: /* Unpacked and rebuilt */ \
if(ctx->engine->keeptmp) \
cli_dbgmsg(NAME": Unpacked and rebuilt executable saved in %s\n", tempfile); \
else \
cli_dbgmsg(NAME": Unpacked and rebuilt executable\n"); \
cli_multifree FREEME; \
free(exe_sections); \
lseek(ndesc, 0, SEEK_SET); \
cli_dbgmsg("***** Scanning rebuilt PE file *****\n"); \
SHA_OFF; \
if(cli_magic_scandesc(ndesc, ctx) == CL_VIRUS) { \
close(ndesc); \
CLI_TMPUNLK(); \
free(tempfile); \
SHA_RESET; \
return CL_VIRUS; \
} \
SHA_RESET; \
close(ndesc); \
CLI_TMPUNLK(); \
free(tempfile); \
return CL_CLEAN; \
\
FSGSTUFF; \
\
default: \
cli_dbgmsg(NAME": Unpacking failed\n"); \
close(ndesc); \
if (cli_unlink(tempfile)) { \
free(exe_sections); \
free(tempfile); \
cli_multifree FREEME; \
return CL_EUNLINK; \
} \
cli_multifree FREEME; \
free(tempfile); \
}
#define CLI_UNPRESULTS(NAME,EXPR,GOOD,FREEME) CLI_UNPRESULTS_(NAME,(void)0,EXPR,GOOD,FREEME)
#define CLI_UNPRESULTSFSG1(NAME,EXPR,GOOD,FREEME) CLI_UNPRESULTS_(NAME,FSGCASE(NAME,free(sections)),EXPR,GOOD,FREEME)
#define CLI_UNPRESULTSFSG2(NAME,EXPR,GOOD,FREEME) CLI_UNPRESULTS_(NAME,FSGCASE(NAME,(void)0),EXPR,GOOD,FREEME)
#define DETECT_BROKEN_PE (DETECT_BROKEN && !ctx->corrupted_input)
extern const unsigned int hashlen[];
struct offset_list {
uint32_t offset;
struct offset_list *next;
};
static void cli_multifree(void *f, ...) {
void *ff;
va_list ap;
free(f);
va_start(ap, f);
while((ff=va_arg(ap, void*))) free(ff);
va_end(ap);
}
struct vinfo_list {
uint32_t rvas[16];
unsigned int count;
};
static int versioninfo_cb(void *opaque, uint32_t type, uint32_t name, uint32_t lang, uint32_t rva) {
struct vinfo_list *vlist = (struct vinfo_list *)opaque;
cli_dbgmsg("versioninfo_cb: type: %x, name: %x, lang: %x, rva: %x\n", type, name, lang, rva);
vlist->rvas[vlist->count] = rva;
if(++vlist->count == sizeof(vlist->rvas) / sizeof(vlist->rvas[0]))
return 1;
return 0;
}
uint32_t cli_rawaddr(uint32_t rva, const struct cli_exe_section *shp, uint16_t nos, unsigned int *err, size_t fsize, uint32_t hdr_size)
{
int i, found = 0;
uint32_t ret;
if (rva<hdr_size) { /* Out of section EP - mapped to imagebase+rva */
if (rva >= fsize) {
*err=1;
return 0;
}
*err=0;
return rva;
}
for(i = nos-1; i >= 0; i--) {
if(shp[i].rsz && shp[i].rva <= rva && shp[i].rsz > rva - shp[i].rva) {
found = 1;
break;
}
}
if(!found) {
*err = 1;
return 0;
}
ret = rva - shp[i].rva + shp[i].raw;
*err = 0;
return ret;
}
/*
static int cli_ddump(int desc, int offset, int size, const char *file) {
int pos, ndesc, bread, sum = 0;
char buff[FILEBUFF];
cli_dbgmsg("in ddump()\n");
if((pos = lseek(desc, 0, SEEK_CUR)) == -1) {
cli_dbgmsg("Invalid descriptor\n");
return -1;
}
if(lseek(desc, offset, SEEK_SET) == -1) {
cli_dbgmsg("lseek() failed\n");
lseek(desc, pos, SEEK_SET);
return -1;
}
if((ndesc = open(file, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) {
cli_dbgmsg("Can't create file %s\n", file);
lseek(desc, pos, SEEK_SET);
return -1;
}
while((bread = cli_readn(desc, buff, FILEBUFF)) > 0) {
if(sum + bread >= size) {
if(write(ndesc, buff, size - sum) == -1) {
cli_dbgmsg("Can't write to file\n");
lseek(desc, pos, SEEK_SET);
close(ndesc);
cli_unlink(file);
return -1;
}
break;
} else {
if(write(ndesc, buff, bread) == -1) {
cli_dbgmsg("Can't write to file\n");
lseek(desc, pos, SEEK_SET);
close(ndesc);
cli_unlink(file);
return -1;
}
}
sum += bread;
}
close(ndesc);
lseek(desc, pos, SEEK_SET);
return 0;
}
*/
/*
void findres(uint32_t by_type, uint32_t by_name, uint32_t res_rva, cli_ctx *ctx, struct cli_exe_section *exe_sections, uint16_t nsections, uint32_t hdr_size, int (*cb)(void *, uint32_t, uint32_t, uint32_t, uint32_t), void *opaque)
callback based res lookup
by_type: lookup type
by_name: lookup name or (unsigned)-1 to look for any name
res_rva: base resource rva (i.e. dirs[2].VirtualAddress)
ctx, exe_sections, nsections, hdr_size: same as in scanpe
cb: the callback function executed on each successful match
opaque: an opaque pointer passed to the callback
the callback proto is
int pe_res_cballback (void *opaque, uint32_t type, uint32_t name, uint32_t lang, uint32_t rva);
the callback shall return 0 to continue the lookup or 1 to abort
*/
void findres(uint32_t by_type, uint32_t by_name, uint32_t res_rva, fmap_t *map, struct cli_exe_section *exe_sections, uint16_t nsections, uint32_t hdr_size, int (*cb)(void *, uint32_t, uint32_t, uint32_t, uint32_t), void *opaque) {
unsigned int err = 0;
uint32_t type, type_offs, name, name_offs, lang, lang_offs;
const uint8_t *resdir, *type_entry, *name_entry, *lang_entry ;
uint16_t type_cnt, name_cnt, lang_cnt;
if (!(resdir = fmap_need_off_once(map, cli_rawaddr(res_rva, exe_sections, nsections, &err, map->len, hdr_size), 16)) || err)
return;
type_cnt = (uint16_t)cli_readint16(resdir+12);
type_entry = resdir+16;
if(!(by_type>>31)) {
type_entry += type_cnt * 8;
type_cnt = (uint16_t)cli_readint16(resdir+14);
}
while(type_cnt--) {
if(!fmap_need_ptr_once(map, type_entry, 8))
return;
type = cli_readint32(type_entry);
type_offs = cli_readint32(type_entry+4);
if(type == by_type && (type_offs>>31)) {
type_offs &= 0x7fffffff;
if (!(resdir = fmap_need_off_once(map, cli_rawaddr(res_rva + type_offs, exe_sections, nsections, &err, map->len, hdr_size), 16)) || err)
return;
name_cnt = (uint16_t)cli_readint16(resdir+12);
name_entry = resdir+16;
if(by_name == 0xffffffff)
name_cnt += (uint16_t)cli_readint16(resdir+14);
else if(!(by_name>>31)) {
name_entry += name_cnt * 8;
name_cnt = (uint16_t)cli_readint16(resdir+14);
}
while(name_cnt--) {
if(!fmap_need_ptr_once(map, name_entry, 8))
return;
name = cli_readint32(name_entry);
name_offs = cli_readint32(name_entry+4);
if((by_name == 0xffffffff || name == by_name) && (name_offs>>31)) {
name_offs &= 0x7fffffff;
if (!(resdir = fmap_need_off_once(map, cli_rawaddr(res_rva + name_offs, exe_sections, nsections, &err, map->len, hdr_size), 16)) || err)
return;
lang_cnt = (uint16_t)cli_readint16(resdir+12) + (uint16_t)cli_readint16(resdir+14);
lang_entry = resdir+16;
while(lang_cnt--) {
if(!fmap_need_ptr_once(map, lang_entry, 8))
return;
lang = cli_readint32(lang_entry);
lang_offs = cli_readint32(lang_entry+4);
if(!(lang_offs >>31)) {
if(cb(opaque, type, name, lang, res_rva + lang_offs))
return;
}
lang_entry += 8;
}
}
name_entry += 8;
}
return; /* FIXME: unless we want to find ALL types */
}
type_entry += 8;
}
}
static void cli_parseres_special(uint32_t base, uint32_t rva, fmap_t *map, struct cli_exe_section *exe_sections, uint16_t nsections, size_t fsize, uint32_t hdr_size, unsigned int level, uint32_t type, unsigned int *maxres, struct swizz_stats *stats) {
unsigned int err = 0, i;
const uint8_t *resdir;
const uint8_t *entry, *oentry;
uint16_t named, unnamed;
uint32_t rawaddr = cli_rawaddr(rva, exe_sections, nsections, &err, fsize, hdr_size);
uint32_t entries;
if(level>2 || !*maxres) return;
*maxres-=1;
if(err || !(resdir = fmap_need_off_once(map, rawaddr, 16)))
return;
named = (uint16_t)cli_readint16(resdir+12);
unnamed = (uint16_t)cli_readint16(resdir+14);
entries = /*named+*/unnamed;
if (!entries)
return;
rawaddr += named*8; /* skip named */
/* this is just used in a heuristic detection, so don't give error on failure */
if(!(entry = fmap_need_off(map, rawaddr+16, entries*8))) {
cli_dbgmsg("cli_parseres_special: failed to read resource directory at:%lu\n", (unsigned long)rawaddr+16);
return;
}
oentry = entry;
/*for (i=0; i<named; i++) {
uint32_t id, offs;
id = cli_readint32(entry);
offs = cli_readint32(entry+4);
if(offs>>31)
cli_parseres( base, base + (offs&0x7fffffff), srcfd, exe_sections, nsections, fsize, hdr_size, level+1, type, maxres, stats);
entry+=8;
}*/
for (i=0; i<unnamed; i++, entry += 8) {
uint32_t id, offs;
if (stats->errors >= SWIZZ_MAXERRORS) {
cli_dbgmsg("cli_parseres_special: resources broken, ignoring\n");
return;
}
id = cli_readint32(entry)&0x7fffffff;
if(level==0) {
type = 0;
switch(id) {
case 4: /* menu */
case 5: /* dialog */
case 6: /* string */
case 11:/* msgtable */
type = id;
break;
case 16:
type = id;
/* 14: version */
stats->has_version = 1;
break;
case 24: /* manifest */
stats->has_manifest = 1;
break;
/* otherwise keep it 0, we don't want it */
}
}
if (!type) {
/* if we are not interested in this type, skip */
continue;
}
offs = cli_readint32(entry+4);
if(offs>>31)
cli_parseres_special(base, base + (offs&0x7fffffff), map, exe_sections, nsections, fsize, hdr_size, level+1, type, maxres, stats);
else {
offs = cli_readint32(entry+4);
rawaddr = cli_rawaddr(base + offs, exe_sections, nsections, &err, fsize, hdr_size);
if (!err && (resdir = fmap_need_off_once(map, rawaddr, 16))) {
uint32_t isz = cli_readint32(resdir+4);
const uint8_t *str;
rawaddr = cli_rawaddr(cli_readint32(resdir), exe_sections, nsections, &err, fsize, hdr_size);
if (err || !isz || isz >= fsize || rawaddr+isz >= fsize) {
cli_dbgmsg("cli_parseres_special: invalid resource table entry: %lu + %lu\n",
(unsigned long)rawaddr,
(unsigned long)isz);
stats->errors++;
continue;
}
if ((id&0xff) != 0x09) /* english res only */
continue;
if((str = fmap_need_off_once(map, rawaddr, isz)))
cli_detect_swizz_str(str, isz, stats, type);
}
}
}
fmap_unneed_ptr(map, oentry, entries*8);
}
static unsigned int cli_hashsect(fmap_t *map, struct cli_exe_section *s, unsigned char **digest, int * foundhash, int * foundwild)
{
const void *hashme;
if (s->rsz > CLI_MAX_ALLOCATION) {
cli_dbgmsg("cli_hashsect: skipping hash calculation for too big section\n");
return 0;
}
if(!s->rsz) return 0;
if(!(hashme=fmap_need_off_once(map, s->raw, s->rsz))) {
cli_dbgmsg("cli_hashsect: unable to read section data\n");
return 0;
}
if(foundhash[CLI_HASH_MD5] || foundwild[CLI_HASH_MD5])
cl_hash_data("md5", hashme, s->rsz, digest[CLI_HASH_MD5], NULL);
if(foundhash[CLI_HASH_SHA1] || foundwild[CLI_HASH_SHA1])
cl_sha1(hashme, s->rsz, digest[CLI_HASH_SHA1], NULL);
if(foundhash[CLI_HASH_SHA256] || foundwild[CLI_HASH_SHA256])
cl_sha256(hashme, s->rsz, digest[CLI_HASH_SHA256], NULL);
return 1;
}
/* check hash section sigs */
static int scan_pe_mdb (cli_ctx * ctx, struct cli_exe_section *exe_section)
{
struct cli_matcher * mdb_sect = ctx->engine->hm_mdb;
unsigned char * hashset[CLI_HASH_AVAIL_TYPES];
const char * virname = NULL;
int foundsize[CLI_HASH_AVAIL_TYPES];
int foundwild[CLI_HASH_AVAIL_TYPES];
enum CLI_HASH_TYPE type;
int ret = CL_CLEAN;
unsigned char * md5 = NULL;
/* pick hashtypes to generate */
for(type = CLI_HASH_MD5; type < CLI_HASH_AVAIL_TYPES; type++) {
foundsize[type] = cli_hm_have_size(mdb_sect, type, exe_section->rsz);
foundwild[type] = cli_hm_have_wild(mdb_sect, type);
if(foundsize[type] || foundwild[type]) {
hashset[type] = cli_malloc(hashlen[type]);
if(!hashset[type]) {
cli_errmsg("scan_pe: cli_malloc failed!\n");
for(; type > 0;)
free(hashset[--type]);
return CL_EMEM;
}
}
else {
hashset[type] = NULL;
}
}
/* Generate hashes */
cli_hashsect(*ctx->fmap, exe_section, hashset, foundsize, foundwild);
/* Print hash */
if (cli_debug_flag) {
md5 = hashset[CLI_HASH_MD5];
if (md5) {
cli_dbgmsg("MDB: %u:%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n",
exe_section->rsz, md5[0], md5[1], md5[2], md5[3], md5[4], md5[5], md5[6], md5[7],
md5[8], md5[9], md5[10], md5[11], md5[12], md5[13], md5[14], md5[15]);
} else if (cli_always_gen_section_hash) {
const void *hashme = fmap_need_off_once(*ctx->fmap, exe_section->raw, exe_section->rsz);
if (!(hashme)) {
cli_errmsg("scan_pe_mdb: unable to read section data\n");
ret = CL_EREAD;
goto end;
}
md5 = cli_malloc(16);
if (!(md5)) {
cli_errmsg("scan_pe_mdb: cli_malloc failed!\n");
ret = CL_EMEM;
goto end;
}
cl_hash_data("md5", hashme, exe_section->rsz, md5, NULL);
cli_dbgmsg("MDB: %u:%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n",
exe_section->rsz, md5[0], md5[1], md5[2], md5[3], md5[4], md5[5], md5[6], md5[7],
md5[8], md5[9], md5[10], md5[11], md5[12], md5[13], md5[14], md5[15]);
free(md5);
} else {
cli_dbgmsg("MDB: %u:notgenerated\n", exe_section->rsz);
}
}
/* Do scans */
for(type = CLI_HASH_MD5; type < CLI_HASH_AVAIL_TYPES; type++) {
if(foundsize[type] && cli_hm_scan(hashset[type], exe_section->rsz, &virname, mdb_sect, type) == CL_VIRUS) {
cli_append_virus(ctx, virname);
ret = CL_VIRUS;
if (!SCAN_ALL) {
break;
}
}
if(foundwild[type] && cli_hm_scan_wild(hashset[type], &virname, mdb_sect, type) == CL_VIRUS) {
cli_append_virus(ctx, virname);
ret = CL_VIRUS;
if (!SCAN_ALL) {
break;
}
}
}
end:
for(type = CLI_HASH_AVAIL_TYPES; type > 0;)
free(hashset[--type]);
return ret;
}
#if HAVE_JSON
static struct json_object *get_pe_property(cli_ctx *ctx)
{
struct json_object *pe;
if (!(ctx) || !(ctx->wrkproperty))
return NULL;
if (!json_object_object_get_ex(ctx->wrkproperty, "PE", &pe)) {
pe = json_object_new_object();
if (!(pe))
return NULL;
json_object_object_add(ctx->wrkproperty, "PE", pe);
}
return pe;
}
static void pe_add_heuristic_property(cli_ctx *ctx, const char *key)
{
struct json_object *heuristics;
struct json_object *pe;
struct json_object *str;
pe = get_pe_property(ctx);
if (!(pe))
return;
if (!json_object_object_get_ex(pe, "Heuristics", &heuristics)) {
heuristics = json_object_new_array();
if (!(heuristics))
return;
json_object_object_add(pe, "Heuristics", heuristics);
}
str = json_object_new_string(key);
if (!(str))
return;
json_object_array_add(heuristics, str);
}
static struct json_object *get_section_json(cli_ctx *ctx)
{
struct json_object *pe;
struct json_object *section;
pe = get_pe_property(ctx);
if (!(pe))
return NULL;
if (!json_object_object_get_ex(pe, "Sections", §ion)) {
section = json_object_new_array();
if (!(section))
return NULL;
json_object_object_add(pe, "Sections", section);
}
return section;
}
static void add_section_info(cli_ctx *ctx, struct cli_exe_section *s)
{
struct json_object *sections, *section, *obj;
char address[16];
sections = get_section_json(ctx);
if (!(sections))
return;
section = json_object_new_object();
if (!(section))
return;
obj = json_object_new_int((int32_t)(s->rsz));
if (!(obj))
return;
json_object_object_add(section, "RawSize", obj);
obj = json_object_new_int((int32_t)(s->raw));
if (!(obj))
return;
json_object_object_add(section, "RawOffset", obj);
snprintf(address, sizeof(address), "0x%08x", s->rva);
obj = json_object_new_string(address);
if (!(obj))
return;
json_object_object_add(section, "VirtualAddress", obj);
obj = json_object_new_boolean((s->chr & 0x20000000) == 0x20000000);
if ((obj))
json_object_object_add(section, "Executable", obj);
obj = json_object_new_boolean((s->chr & 0x80000000) == 0x80000000);
if ((obj))
json_object_object_add(section, "Writable", obj);
obj = json_object_new_boolean(s->urva>>31 || s->uvsz>>31 || (s->rsz && s->uraw>>31) || s->ursz>>31);
if ((obj))
json_object_object_add(section, "Signed", obj);
json_object_array_add(sections, section);
}
#endif
int cli_scanpe(cli_ctx *ctx)
{
uint16_t e_magic; /* DOS signature ("MZ") */
uint16_t nsections;
uint32_t e_lfanew; /* address of new exe header */
uint32_t ep, vep; /* entry point (raw, virtual) */
uint8_t polipos = 0;
time_t timestamp;
struct pe_image_file_hdr file_hdr;
union {
struct pe_image_optional_hdr64 opt64;
struct pe_image_optional_hdr32 opt32;
} pe_opt;
struct pe_image_section_hdr *section_hdr;
char sname[9], epbuff[4096], *tempfile;
uint32_t epsize;
ssize_t bytes, at;
unsigned int i, j, found, upx_success = 0, min = 0, max = 0, err, overlays = 0, rescan = 1;
unsigned int ssize = 0, dsize = 0, dll = 0, pe_plus = 0, corrupted_cur;
int (*upxfn)(const char *, uint32_t, char *, uint32_t *, uint32_t, uint32_t, uint32_t) = NULL;
const char *src = NULL;
char *dest = NULL;
int ndesc, ret = CL_CLEAN, upack = 0, native=0;
size_t fsize;
uint32_t valign, falign, hdr_size;
struct cli_exe_section *exe_sections;
char timestr[32];
struct pe_image_data_dir *dirs;
struct cli_bc_ctx *bc_ctx;
fmap_t *map;
struct cli_pe_hook_data pedata;
#ifdef HAVE__INTERNAL__SHA_COLLECT
int sha_collect = ctx->sha_collect;
#endif
const char *archtype=NULL, *subsystem=NULL;
uint32_t viruses_found = 0;
#if HAVE_JSON
int toval = 0;
struct json_object *pe_json=NULL;
char jsonbuf[128];
#endif
if(!ctx) {
cli_errmsg("cli_scanpe: ctx == NULL\n");
return CL_ENULLARG;
}
#if HAVE_JSON
if (cli_json_timeout_cycle_check(ctx, &toval) != CL_SUCCESS) {
return CL_ETIMEOUT;
}
if (ctx->options & CL_SCAN_FILE_PROPERTIES) {
pe_json = get_pe_property(ctx);
}
#endif
map = *ctx->fmap;
if(fmap_readn(map, &e_magic, 0, sizeof(e_magic)) != sizeof(e_magic)) {
cli_dbgmsg("Can't read DOS signature\n");
return CL_CLEAN;
}
if(EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE && EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE_OLD) {
cli_dbgmsg("Invalid DOS signature\n");
return CL_CLEAN;
}
if(fmap_readn(map, &e_lfanew, 58 + sizeof(e_magic), sizeof(e_lfanew)) != sizeof(e_lfanew)) {
cli_dbgmsg("Can't read new header address\n");
/* truncated header? */
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
e_lfanew = EC32(e_lfanew);
cli_dbgmsg("e_lfanew == %d\n", e_lfanew);
if(!e_lfanew) {
cli_dbgmsg("Not a PE file\n");
return CL_CLEAN;
}
if(fmap_readn(map, &file_hdr, e_lfanew, sizeof(struct pe_image_file_hdr)) != sizeof(struct pe_image_file_hdr)) {
/* bad information in e_lfanew - probably not a PE file */
cli_dbgmsg("Can't read file header\n");
return CL_CLEAN;
}
if(EC32(file_hdr.Magic) != PE_IMAGE_NT_SIGNATURE) {
cli_dbgmsg("Invalid PE signature (probably NE file)\n");
return CL_CLEAN;
}
if(EC16(file_hdr.Characteristics) & 0x2000) {
#if HAVE_JSON
if ((pe_json))
cli_jsonstr(pe_json, "Type", "DLL");
#endif
cli_dbgmsg("File type: DLL\n");
dll = 1;
} else if(EC16(file_hdr.Characteristics) & 0x01) {
#if HAVE_JSON
if ((pe_json))
cli_jsonstr(pe_json, "Type", "EXE");
#endif
cli_dbgmsg("File type: Executable\n");
}
switch(EC16(file_hdr.Machine)) {
case 0x0:
archtype = "Unknown";
break;
case 0x14c:
archtype = "80386";
break;
case 0x14d:
archtype = "80486";
break;
case 0x14e:
archtype = "80586";
break;
case 0x160:
archtype = "R30000 (big-endian)";
break;
case 0x162:
archtype = "R3000";
break;
case 0x166:
archtype = "R4000";
break;
case 0x168:
archtype = "R10000";
break;
case 0x184:
archtype = "DEC Alpha AXP";
break;
case 0x284:
archtype = "DEC Alpha AXP 64bit";
break;
case 0x1f0:
archtype = "PowerPC";
break;
case 0x200:
archtype = "IA64";
break;
case 0x268:
archtype = "M68k";
break;
case 0x266:
archtype = "MIPS16";
break;
case 0x366:
archtype = "MIPS+FPU";
break;
case 0x466:
archtype = "MIPS16+FPU";
break;
case 0x1a2:
archtype = "Hitachi SH3";
break;
case 0x1a3:
archtype = "Hitachi SH3-DSP";
break;
case 0x1a4:
archtype = "Hitachi SH3-E";
break;
case 0x1a6:
archtype = "Hitachi SH4";
break;
case 0x1a8:
archtype = "Hitachi SH5";
break;
case 0x1c0:
archtype = "ARM";
break;
case 0x1c2:
archtype = "THUMB";
break;
case 0x1d3:
archtype = "AM33";
break;
case 0x520:
archtype = "Infineon TriCore";
break;
case 0xcef:
archtype = "CEF";
break;
case 0xebc:
archtype = "EFI Byte Code";
break;
case 0x9041:
archtype = "M32R";
break;
case 0xc0ee:
archtype = "CEEE";
break;
case 0x8664:
archtype = "AMD64";
break;
default:
archtype = "Unknown";
}
if ((archtype)) {
cli_dbgmsg("Machine type: %s\n", archtype);
#if HAVE_JSON
cli_jsonstr(pe_json, "ArchType", archtype);
#endif
}
nsections = EC16(file_hdr.NumberOfSections);
if(nsections < 1 || nsections > 96) {
#if HAVE_JSON
pe_add_heuristic_property(ctx, "BadNumberOfSections");
#endif
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
if(!ctx->corrupted_input) {
if(nsections)
cli_warnmsg("PE file contains %d sections\n", nsections);
else
cli_warnmsg("PE file contains no sections\n");
}
return CL_CLEAN;
}
cli_dbgmsg("NumberOfSections: %d\n", nsections);
timestamp = (time_t) EC32(file_hdr.TimeDateStamp);
cli_dbgmsg("TimeDateStamp: %s", cli_ctime(×tamp, timestr, sizeof(timestr)));
#if HAVE_JSON
cli_jsonstr(pe_json, "TimeDateStamp", cli_ctime(×tamp, timestr, sizeof(timestr)));
#endif
cli_dbgmsg("SizeOfOptionalHeader: %x\n", EC16(file_hdr.SizeOfOptionalHeader));
#if HAVE_JSON
cli_jsonint(pe_json, "SizeOfOptionalHeader", EC16(file_hdr.SizeOfOptionalHeader));
#endif
if (EC16(file_hdr.SizeOfOptionalHeader) < sizeof(struct pe_image_optional_hdr32)) {
#if HAVE_JSON
pe_add_heuristic_property(ctx, "BadOptionalHeaderSize");
#endif
cli_dbgmsg("SizeOfOptionalHeader too small\n");
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
at = e_lfanew + sizeof(struct pe_image_file_hdr);
if(fmap_readn(map, &optional_hdr32, at, sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr32)) {
cli_dbgmsg("Can't read optional file header\n");
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
at += sizeof(struct pe_image_optional_hdr32);
/* This will be a chicken and egg problem until we drop 9x */
if(EC16(optional_hdr64.Magic)==PE32P_SIGNATURE) {
#if HAVE_JSON
pe_add_heuristic_property(ctx, "BadOptionalHeaderSizePE32Plus");
#endif
if(EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr64)) {
/* FIXME: need to play around a bit more with xp64 */
cli_dbgmsg("Incorrect SizeOfOptionalHeader for PE32+\n");
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
pe_plus = 1;
}
if(!pe_plus) { /* PE */
if (EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr32)) {
/* Seek to the end of the long header */
at += EC16(file_hdr.SizeOfOptionalHeader)-sizeof(struct pe_image_optional_hdr32);
}
if(DCONF & PE_CONF_UPACK)
upack = (EC16(file_hdr.SizeOfOptionalHeader)==0x148);
vep = EC32(optional_hdr32.AddressOfEntryPoint);
hdr_size = EC32(optional_hdr32.SizeOfHeaders);
cli_dbgmsg("File format: PE\n");
cli_dbgmsg("MajorLinkerVersion: %d\n", optional_hdr32.MajorLinkerVersion);
cli_dbgmsg("MinorLinkerVersion: %d\n", optional_hdr32.MinorLinkerVersion);
cli_dbgmsg("SizeOfCode: 0x%x\n", EC32(optional_hdr32.SizeOfCode));
cli_dbgmsg("SizeOfInitializedData: 0x%x\n", EC32(optional_hdr32.SizeOfInitializedData));
cli_dbgmsg("SizeOfUninitializedData: 0x%x\n", EC32(optional_hdr32.SizeOfUninitializedData));
cli_dbgmsg("AddressOfEntryPoint: 0x%x\n", vep);
cli_dbgmsg("BaseOfCode: 0x%x\n", EC32(optional_hdr32.BaseOfCode));
cli_dbgmsg("SectionAlignment: 0x%x\n", EC32(optional_hdr32.SectionAlignment));
cli_dbgmsg("FileAlignment: 0x%x\n", EC32(optional_hdr32.FileAlignment));
cli_dbgmsg("MajorSubsystemVersion: %d\n", EC16(optional_hdr32.MajorSubsystemVersion));
cli_dbgmsg("MinorSubsystemVersion: %d\n", EC16(optional_hdr32.MinorSubsystemVersion));
cli_dbgmsg("SizeOfImage: 0x%x\n", EC32(optional_hdr32.SizeOfImage));
cli_dbgmsg("SizeOfHeaders: 0x%x\n", hdr_size);
cli_dbgmsg("NumberOfRvaAndSizes: %d\n", EC32(optional_hdr32.NumberOfRvaAndSizes));
dirs = optional_hdr32.DataDirectory;
#if HAVE_JSON
cli_jsonint(pe_json, "MajorLinkerVersion", optional_hdr32.MajorLinkerVersion);
cli_jsonint(pe_json, "MinorLinkerVersion", optional_hdr32.MinorLinkerVersion);
cli_jsonint(pe_json, "SizeOfCode", EC32(optional_hdr32.SizeOfCode));
cli_jsonint(pe_json, "SizeOfInitializedData", EC32(optional_hdr32.SizeOfInitializedData));
cli_jsonint(pe_json, "SizeOfUninitializedData", EC32(optional_hdr32.SizeOfUninitializedData));
cli_jsonint(pe_json, "NumberOfRvaAndSizes", EC32(optional_hdr32.NumberOfRvaAndSizes));
cli_jsonint(pe_json, "MajorSubsystemVersion", EC16(optional_hdr32.MajorSubsystemVersion));
cli_jsonint(pe_json, "MinorSubsystemVersion", EC16(optional_hdr32.MinorSubsystemVersion));
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", EC32(optional_hdr32.BaseOfCode));
cli_jsonstr(pe_json, "BaseOfCode", jsonbuf);
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", EC32(optional_hdr32.SectionAlignment));
cli_jsonstr(pe_json, "SectionAlignment", jsonbuf);
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", EC32(optional_hdr32.FileAlignment));
cli_jsonstr(pe_json, "FileAlignment", jsonbuf);
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", EC32(optional_hdr32.SizeOfImage));
cli_jsonstr(pe_json, "SizeOfImage", jsonbuf);
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", hdr_size);
cli_jsonstr(pe_json, "SizeOfHeaders", jsonbuf);
#endif
} else { /* PE+ */
/* read the remaining part of the header */
if(fmap_readn(map, &optional_hdr32 + 1, at, sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) {
cli_dbgmsg("Can't read optional file header\n");
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
at += sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32);
vep = EC32(optional_hdr64.AddressOfEntryPoint);
hdr_size = EC32(optional_hdr64.SizeOfHeaders);
cli_dbgmsg("File format: PE32+\n");
cli_dbgmsg("MajorLinkerVersion: %d\n", optional_hdr64.MajorLinkerVersion);
cli_dbgmsg("MinorLinkerVersion: %d\n", optional_hdr64.MinorLinkerVersion);
cli_dbgmsg("SizeOfCode: 0x%x\n", EC32(optional_hdr64.SizeOfCode));
cli_dbgmsg("SizeOfInitializedData: 0x%x\n", EC32(optional_hdr64.SizeOfInitializedData));
cli_dbgmsg("SizeOfUninitializedData: 0x%x\n", EC32(optional_hdr64.SizeOfUninitializedData));
cli_dbgmsg("AddressOfEntryPoint: 0x%x\n", vep);
cli_dbgmsg("BaseOfCode: 0x%x\n", EC32(optional_hdr64.BaseOfCode));
cli_dbgmsg("SectionAlignment: 0x%x\n", EC32(optional_hdr64.SectionAlignment));
cli_dbgmsg("FileAlignment: 0x%x\n", EC32(optional_hdr64.FileAlignment));
cli_dbgmsg("MajorSubsystemVersion: %d\n", EC16(optional_hdr64.MajorSubsystemVersion));
cli_dbgmsg("MinorSubsystemVersion: %d\n", EC16(optional_hdr64.MinorSubsystemVersion));
cli_dbgmsg("SizeOfImage: 0x%x\n", EC32(optional_hdr64.SizeOfImage));
cli_dbgmsg("SizeOfHeaders: 0x%x\n", hdr_size);
cli_dbgmsg("NumberOfRvaAndSizes: %d\n", EC32(optional_hdr64.NumberOfRvaAndSizes));
dirs = optional_hdr64.DataDirectory;
#if HAVE_JSON
cli_jsonint(pe_json, "MajorLinkerVersion", optional_hdr64.MajorLinkerVersion);
cli_jsonint(pe_json, "MinorLinkerVersion", optional_hdr64.MinorLinkerVersion);
cli_jsonint(pe_json, "SizeOfCode", EC32(optional_hdr64.SizeOfCode));
cli_jsonint(pe_json, "SizeOfInitializedData", EC32(optional_hdr64.SizeOfInitializedData));
cli_jsonint(pe_json, "SizeOfUninitializedData", EC32(optional_hdr64.SizeOfUninitializedData));
cli_jsonint(pe_json, "NumberOfRvaAndSizes", EC32(optional_hdr64.NumberOfRvaAndSizes));
cli_jsonint(pe_json, "MajorSubsystemVersion", EC16(optional_hdr64.MajorSubsystemVersion));
cli_jsonint(pe_json, "MinorSubsystemVersion", EC16(optional_hdr64.MinorSubsystemVersion));
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", EC32(optional_hdr64.BaseOfCode));
cli_jsonstr(pe_json, "BaseOfCode", jsonbuf);
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", EC32(optional_hdr64.SectionAlignment));
cli_jsonstr(pe_json, "SectionAlignment", jsonbuf);
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", EC32(optional_hdr64.FileAlignment));
cli_jsonstr(pe_json, "FileAlignment", jsonbuf);
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", EC32(optional_hdr64.SizeOfImage));
cli_jsonstr(pe_json, "SizeOfImage", jsonbuf);
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", hdr_size);
cli_jsonstr(pe_json, "SizeOfHeaders", jsonbuf);
#endif
}
#if HAVE_JSON
if (ctx->options & CL_SCAN_FILE_PROPERTIES) {
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", vep);
cli_jsonstr(pe_json, "EntryPoint", jsonbuf);
}
#endif
switch(pe_plus ? EC16(optional_hdr64.Subsystem) : EC16(optional_hdr32.Subsystem)) {
case 0:
subsystem = "Unknown";
break;
case 1:
subsystem = "Native (svc)";
native = 1;
break;
case 2:
subsystem = "Win32 GUI";
break;
case 3:
subsystem = "Win32 console";
break;
case 5:
subsystem = "OS/2 console";
break;
case 7:
subsystem = "POSIX console";
break;
case 8:
subsystem = "Native Win9x driver";
break;
case 9:
subsystem = "WinCE GUI";
break;
case 10:
subsystem = "EFI application";
break;
case 11:
subsystem = "EFI driver";
break;
case 12:
subsystem = "EFI runtime driver";
break;
case 13:
subsystem = "EFI ROM image";
break;
case 14:
subsystem = "Xbox";
break;
case 16:
subsystem = "Boot application";
break;
default:
subsystem = "Unknown";
}
cli_dbgmsg("Subsystem: %s\n", subsystem);
#if HAVE_JSON
cli_jsonstr(pe_json, "Subsystem", subsystem);
#endif
cli_dbgmsg("------------------------------------\n");
if (DETECT_BROKEN_PE && !native && (!(pe_plus?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment)) || (pe_plus?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment))%0x1000)) {
cli_dbgmsg("Bad virtual alignemnt\n");
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
if (DETECT_BROKEN_PE && !native && (!(pe_plus?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment)) || (pe_plus?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment))%0x200)) {
cli_dbgmsg("Bad file alignemnt\n");
cli_append_virus(ctx, "Heuristics.Broken.Executable");
return CL_VIRUS;
}
fsize = map->len;
section_hdr = (struct pe_image_section_hdr *) cli_calloc(nsections, sizeof(struct pe_image_section_hdr));
if(!section_hdr) {
cli_dbgmsg("Can't allocate memory for section headers\n");
return CL_EMEM;
}
exe_sections = (struct cli_exe_section *) cli_calloc(nsections, sizeof(struct cli_exe_section));
if(!exe_sections) {
cli_dbgmsg("Can't allocate memory for section headers\n");
free(section_hdr);
return CL_EMEM;
}
valign = (pe_plus)?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment);
falign = (pe_plus)?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment);
if(fmap_readn(map, section_hdr, at, sizeof(struct pe_image_section_hdr)*nsections) != (int)(nsections*sizeof(struct pe_image_section_hdr))) {
cli_dbgmsg("Can't read section header\n");
cli_dbgmsg("Possibly broken PE file\n");
free(section_hdr);
free(exe_sections);
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
at += sizeof(struct pe_image_section_hdr)*nsections;
for(i = 0; falign!=0x200 && i<nsections; i++) {
/* file alignment fallback mode - blah */
if (falign && section_hdr[i].SizeOfRawData && EC32(section_hdr[i].PointerToRawData)%falign && !(EC32(section_hdr[i].PointerToRawData)%0x200)) {
cli_dbgmsg("Found misaligned section, using 0x200\n");
falign = 0x200;
}
}
hdr_size = PESALIGN(hdr_size, valign); /* Aligned headers virtual size */
#if HAVE_JSON
cli_jsonint(pe_json, "NumberOfSections", nsections);
#endif
while (rescan==1) {
rescan=0;
for (i=0; i < nsections; i++) {
exe_sections[i].rva = PEALIGN(EC32(section_hdr[i].VirtualAddress), valign);
exe_sections[i].vsz = PESALIGN(EC32(section_hdr[i].VirtualSize), valign);
exe_sections[i].raw = PEALIGN(EC32(section_hdr[i].PointerToRawData), falign);
exe_sections[i].rsz = PESALIGN(EC32(section_hdr[i].SizeOfRawData), falign);
exe_sections[i].chr = EC32(section_hdr[i].Characteristics);
exe_sections[i].urva = EC32(section_hdr[i].VirtualAddress); /* Just in case */
exe_sections[i].uvsz = EC32(section_hdr[i].VirtualSize);
exe_sections[i].uraw = EC32(section_hdr[i].PointerToRawData);
exe_sections[i].ursz = EC32(section_hdr[i].SizeOfRawData);
if (exe_sections[i].rsz) { /* Don't bother with virtual only sections */
if (!CLI_ISCONTAINED(0, fsize, exe_sections[i].uraw, exe_sections[i].ursz)
|| exe_sections[i].raw >= fsize) {
cli_dbgmsg("Broken PE file - Section %d starts or exists beyond the end of file (Offset@ %lu, Total filesize %lu)\n", i, (unsigned long)exe_sections[i].raw, (unsigned long)fsize);
if (nsections == 1) {
free(section_hdr);
free(exe_sections);
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx, "Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN; /* no ninjas to see here! move along! */
}
for (j=i; j < nsections-1; j++)
memcpy(&exe_sections[j], &exe_sections[j+1], sizeof(struct cli_exe_section));
for (j=i; j < nsections-1; j++)
memcpy(§ion_hdr[j], §ion_hdr[j+1], sizeof(struct pe_image_section_hdr));
nsections--;
rescan=1;
break;
}
}
}
}
for(i = 0; i < nsections; i++) {
strncpy(sname, (char *) section_hdr[i].Name, 8);
sname[8] = 0;
#if HAVE_JSON
add_section_info(ctx, &exe_sections[i]);
if (cli_json_timeout_cycle_check(ctx, &toval) != CL_SUCCESS) {
free(section_hdr);
free(exe_sections);
return CL_ETIMEOUT;
}
#endif
if (!exe_sections[i].vsz && exe_sections[i].rsz)
exe_sections[i].vsz=PESALIGN(exe_sections[i].ursz, valign);
if (exe_sections[i].rsz && fsize>exe_sections[i].raw && !CLI_ISCONTAINED(0, (uint32_t) fsize, exe_sections[i].raw, exe_sections[i].rsz))
exe_sections[i].rsz = fsize - exe_sections[i].raw;
cli_dbgmsg("Section %d\n", i);
cli_dbgmsg("Section name: %s\n", sname);
cli_dbgmsg("Section data (from headers - in memory)\n");
cli_dbgmsg("VirtualSize: 0x%x 0x%x\n", exe_sections[i].uvsz, exe_sections[i].vsz);
cli_dbgmsg("VirtualAddress: 0x%x 0x%x\n", exe_sections[i].urva, exe_sections[i].rva);
cli_dbgmsg("SizeOfRawData: 0x%x 0x%x\n", exe_sections[i].ursz, exe_sections[i].rsz);
cli_dbgmsg("PointerToRawData: 0x%x 0x%x\n", exe_sections[i].uraw, exe_sections[i].raw);
if(exe_sections[i].chr & 0x20) {
cli_dbgmsg("Section contains executable code\n");
if(exe_sections[i].vsz < exe_sections[i].rsz) {
cli_dbgmsg("Section contains free space\n");
/*
cli_dbgmsg("Dumping %d bytes\n", section_hdr.SizeOfRawData - section_hdr.VirtualSize);
ddump(desc, section_hdr.PointerToRawData + section_hdr.VirtualSize, section_hdr.SizeOfRawData - section_hdr.VirtualSize, cli_gentemp(NULL));
*/
}
}
if(exe_sections[i].chr & 0x20000000)
cli_dbgmsg("Section's memory is executable\n");
if(exe_sections[i].chr & 0x80000000)
cli_dbgmsg("Section's memory is writeable\n");
if (DETECT_BROKEN_PE && (!valign || (exe_sections[i].urva % valign))) { /* Bad virtual alignment */
cli_dbgmsg("VirtualAddress is misaligned\n");
cli_dbgmsg("------------------------------------\n");
cli_append_virus(ctx, "Heuristics.Broken.Executable");
free(section_hdr);
free(exe_sections);
return CL_VIRUS;
}
if (exe_sections[i].rsz) { /* Don't bother with virtual only sections */
if(SCAN_ALGO && (DCONF & PE_CONF_POLIPOS) && !*sname && exe_sections[i].vsz > 40000 && exe_sections[i].vsz < 70000 && exe_sections[i].chr == 0xe0000060) polipos = i;
/* check hash section sigs */
if((DCONF & PE_CONF_MD5SECT) && ctx->engine->hm_mdb) {
ret = scan_pe_mdb(ctx, &exe_sections[i]);
if (ret != CL_CLEAN) {
if (ret != CL_VIRUS)
cli_errmsg("scan_pe: scan_pe_mdb failed: %s!\n", cl_strerror(ret));
cli_dbgmsg("------------------------------------\n");
free(section_hdr);
free(exe_sections);
return ret;
}
}
}
cli_dbgmsg("------------------------------------\n");
if (exe_sections[i].urva>>31 || exe_sections[i].uvsz>>31 || (exe_sections[i].rsz && exe_sections[i].uraw>>31) || exe_sections[i].ursz>>31) {
cli_dbgmsg("Found PE values with sign bit set\n");
free(section_hdr);
free(exe_sections);
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx, "Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
if(!i) {
if (DETECT_BROKEN_PE && exe_sections[i].urva!=hdr_size) { /* Bad first section RVA */
cli_dbgmsg("First section is in the wrong place\n");
cli_append_virus(ctx, "Heuristics.Broken.Executable");
free(section_hdr);
free(exe_sections);
return CL_VIRUS;
}
min = exe_sections[i].rva;
max = exe_sections[i].rva + exe_sections[i].rsz;
} else {
if (DETECT_BROKEN_PE && exe_sections[i].urva - exe_sections[i-1].urva != exe_sections[i-1].vsz) { /* No holes, no overlapping, no virtual disorder */
cli_dbgmsg("Virtually misplaced section (wrong order, overlapping, non contiguous)\n");
cli_append_virus(ctx, "Heuristics.Broken.Executable");
free(section_hdr);
free(exe_sections);
return CL_VIRUS;
}
if(exe_sections[i].rva < min)
min = exe_sections[i].rva;
if(exe_sections[i].rva + exe_sections[i].rsz > max) {
max = exe_sections[i].rva + exe_sections[i].rsz;
overlays = exe_sections[i].raw + exe_sections[i].rsz;
}
}
}
free(section_hdr);
if(!(ep = cli_rawaddr(vep, exe_sections, nsections, &err, fsize, hdr_size)) && err) {
cli_dbgmsg("EntryPoint out of file\n");
free(exe_sections);
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
#if HAVE_JSON
cli_jsonint(pe_json, "EntryPointOffset", ep);
if (cli_json_timeout_cycle_check(ctx, &toval) != CL_SUCCESS) {
return CL_ETIMEOUT;
}
#endif
cli_dbgmsg("EntryPoint offset: 0x%x (%d)\n", ep, ep);
if(pe_plus) { /* Do not continue for PE32+ files */
free(exe_sections);
return CL_CLEAN;
}
epsize = fmap_readn(map, epbuff, ep, 4096);
/* Disasm scan disabled since it's now handled by the bytecode */
/* CLI_UNPTEMP("DISASM",(exe_sections,0)); */
/* if(disasmbuf((unsigned char*)epbuff, epsize, ndesc)) */
/* ret = cli_scandesc(ndesc, ctx, CL_TYPE_PE_DISASM, 1, NULL, AC_SCAN_VIR); */
/* close(ndesc); */
/* CLI_TMPUNLK(); */
/* free(tempfile); */
/* if(ret == CL_VIRUS) { */
/* free(exe_sections); */
/* return ret; */
/* } */
if(overlays) {
int overlays_sz = fsize - overlays;
if(overlays_sz > 0) {
ret = cli_scanishield(ctx, overlays, overlays_sz);
if(ret != CL_CLEAN) {
free(exe_sections);
return ret;
}
}
}
pedata.nsections = nsections;
pedata.ep = ep;
pedata.offset = 0;
memcpy(&pedata.file_hdr, &file_hdr, sizeof(file_hdr));
memcpy(&pedata.opt32, &pe_opt.opt32, sizeof(pe_opt.opt32));
memcpy(&pedata.opt64, &pe_opt.opt64, sizeof(pe_opt.opt64));
memcpy(&pedata.dirs, dirs, sizeof(pedata.dirs));
pedata.e_lfanew = e_lfanew;
pedata.overlays = overlays;
pedata.overlays_sz = fsize - overlays;
pedata.hdr_size = hdr_size;
/* Bytecode BC_PE_ALL hook */
bc_ctx = cli_bytecode_context_alloc();
if (!bc_ctx) {
cli_errmsg("cli_scanpe: can't allocate memory for bc_ctx\n");
free(exe_sections);
return CL_EMEM;
}
cli_bytecode_context_setpe(bc_ctx, &pedata, exe_sections);
cli_bytecode_context_setctx(bc_ctx, ctx);
ret = cli_bytecode_runhook(ctx, ctx->engine, bc_ctx, BC_PE_ALL, map);
switch (ret) {
case CL_ENULLARG:
cli_warnmsg("cli_scanpe: NULL argument supplied\n");
break;
case CL_VIRUS:
case CL_BREAK:
free(exe_sections);
cli_bytecode_context_destroy(bc_ctx);
return ret == CL_VIRUS ? CL_VIRUS : CL_CLEAN;
}
cli_bytecode_context_destroy(bc_ctx);
/* Attempt to detect some popular polymorphic viruses */
/* W32.Parite.B */
if(SCAN_ALGO && (DCONF & PE_CONF_PARITE) && !dll && epsize == 4096 && ep == exe_sections[nsections - 1].raw) {
const char *pt = cli_memstr(epbuff, 4040, "\x47\x65\x74\x50\x72\x6f\x63\x41\x64\x64\x72\x65\x73\x73\x00", 15);
if(pt) {
pt += 15;
if((((uint32_t)cli_readint32(pt) ^ (uint32_t)cli_readint32(pt + 4)) == 0x505a4f) && (((uint32_t)cli_readint32(pt + 8) ^ (uint32_t)cli_readint32(pt + 12)) == 0xffffb) && (((uint32_t)cli_readint32(pt + 16) ^ (uint32_t)cli_readint32(pt + 20)) == 0xb8)) {
cli_append_virus(ctx,"Heuristics.W32.Parite.B");
if (!SCAN_ALL) {
free(exe_sections);
return CL_VIRUS;
}
viruses_found++;
}
}
}
/* Kriz */
if(SCAN_ALGO && (DCONF & PE_CONF_KRIZ) && epsize >= 200 && CLI_ISCONTAINED(exe_sections[nsections - 1].raw, exe_sections[nsections - 1].rsz, ep, 0x0fd2) && epbuff[1]=='\x9c' && epbuff[2]=='\x60') {
enum {KZSTRASH,KZSCDELTA,KZSPDELTA,KZSGETSIZE,KZSXORPRFX,KZSXOR,KZSDDELTA,KZSLOOP,KZSTOP};
uint8_t kzs[] = {KZSTRASH,KZSCDELTA,KZSPDELTA,KZSGETSIZE,KZSTRASH,KZSXORPRFX,KZSXOR,KZSTRASH,KZSDDELTA,KZSTRASH,KZSLOOP,KZSTOP};
uint8_t *kzstate = kzs;
uint8_t *kzcode = (uint8_t *)epbuff + 3;
uint8_t kzdptr=0xff, kzdsize=0xff;
int kzlen = 197, kzinitlen=0xffff, kzxorlen=-1;
cli_dbgmsg("in kriz\n");
while(*kzstate!=KZSTOP) {
uint8_t op;
if(kzlen<=6) break;
op = *kzcode++;
kzlen--;
switch (*kzstate) {
case KZSTRASH: case KZSGETSIZE: {
int opsz=0;
switch(op) {
case 0x81:
kzcode+=5;
kzlen-=5;
break;
case 0xb8: case 0xb9: case 0xba: case 0xbb: case 0xbd: case 0xbe: case 0xbf:
if(*kzstate==KZSGETSIZE && cli_readint32(kzcode)==0x0fd2) {
kzinitlen = kzlen-5;
kzdsize=op-0xb8;
kzstate++;
op=4; /* fake the register to avoid breaking out */
cli_dbgmsg("kriz: using #%d as size counter\n", kzdsize);
}
opsz=4;
case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4d: case 0x4e: case 0x4f:
op&=7;
if(op!=kzdptr && op!=kzdsize) {
kzcode+=opsz;
kzlen-=opsz;
break;
}
default:
kzcode--;
kzlen++;
kzstate++;
}
break;
}
case KZSCDELTA:
if(op==0xe8 && (uint32_t)cli_readint32(kzcode) < 0xff) {
kzlen-=*kzcode+4;
kzcode+=*kzcode+4;
kzstate++;
} else *kzstate=KZSTOP;
break;
case KZSPDELTA:
if((op&0xf8)==0x58 && (kzdptr=op-0x58)!=4) {
kzstate++;
cli_dbgmsg("kriz: using #%d as pointer\n", kzdptr);
} else *kzstate=KZSTOP;
break;
case KZSXORPRFX:
kzstate++;
if(op==0x3e) break;
case KZSXOR:
if (op==0x80 && *kzcode==kzdptr+0xb0) {
kzxorlen=kzlen;
kzcode+=+6;
kzlen-=+6;
kzstate++;
} else *kzstate=KZSTOP;
break;
case KZSDDELTA:
if (op==kzdptr+0x48) kzstate++;
else *kzstate=KZSTOP;
break;
case KZSLOOP:
if (op==kzdsize+0x48 && *kzcode==0x75 && kzlen-(int8_t)kzcode[1]-3<=kzinitlen && kzlen-(int8_t)kzcode[1]>=kzxorlen) {
cli_append_virus(ctx,"Heuristics.W32.Kriz");
if (!SCAN_ALL) {
free(exe_sections);
return CL_VIRUS;
}
viruses_found++;
}
cli_dbgmsg("kriz: loop out of bounds, corrupted sample?\n");
kzstate++;
}
}
}
/* W32.Magistr.A/B */
if(SCAN_ALGO && (DCONF & PE_CONF_MAGISTR) && !dll && (nsections>1) && (exe_sections[nsections - 1].chr & 0x80000000)) {
uint32_t rsize, vsize, dam = 0;
vsize = exe_sections[nsections - 1].uvsz;
rsize = exe_sections[nsections - 1].rsz;
if(rsize < exe_sections[nsections - 1].ursz) {
rsize = exe_sections[nsections - 1].ursz;
dam = 1;
}
if(vsize >= 0x612c && rsize >= 0x612c && ((vsize & 0xff) == 0xec)) {
int bw = rsize < 0x7000 ? rsize : 0x7000;
const char *tbuff;
if((tbuff = fmap_need_off_once(map, exe_sections[nsections - 1].raw + rsize - bw, 4096))) {
if(cli_memstr(tbuff, 4091, "\xe8\x2c\x61\x00\x00", 5)) {
cli_append_virus(ctx, dam ? "Heuristics.W32.Magistr.A.dam" : "Heuristics.W32.Magistr.A");
if (!SCAN_ALL) {
free(exe_sections);
return CL_VIRUS;
}
viruses_found++;
}
}
} else if(rsize >= 0x7000 && vsize >= 0x7000 && ((vsize & 0xff) == 0xed)) {
int bw = rsize < 0x8000 ? rsize : 0x8000;
const char *tbuff;
if((tbuff = fmap_need_off_once(map, exe_sections[nsections - 1].raw + rsize - bw, 4096))) {
if(cli_memstr(tbuff, 4091, "\xe8\x04\x72\x00\x00", 5)) {
cli_append_virus(ctx,dam ? "Heuristics.W32.Magistr.B.dam" : "Heuristics.W32.Magistr.B");
if (!SCAN_ALL) {
free(exe_sections);
return CL_VIRUS;
}
viruses_found++;
}
}
}
}
/* W32.Polipos.A */
while(polipos && !dll && nsections > 2 && nsections < 13 && e_lfanew <= 0x800 && (EC16(optional_hdr32.Subsystem) == 2 || EC16(optional_hdr32.Subsystem) == 3) && EC16(file_hdr.Machine) == 0x14c && optional_hdr32.SizeOfStackReserve >= 0x80000) {
uint32_t jump, jold, *jumps = NULL;
const uint8_t *code;
unsigned int xsjs = 0;
if(exe_sections[0].rsz > CLI_MAX_ALLOCATION) break;
if(!exe_sections[0].rsz) break;
if(!(code=fmap_need_off_once(map, exe_sections[0].raw, exe_sections[0].rsz))) break;
for(i=0; i<exe_sections[0].rsz - 5; i++) {
if((uint8_t)(code[i]-0xe8) > 1) continue;
jump = cli_rawaddr(exe_sections[0].rva+i+5+cli_readint32(&code[i+1]), exe_sections, nsections, &err, fsize, hdr_size);
if(err || !CLI_ISCONTAINED(exe_sections[polipos].raw, exe_sections[polipos].rsz, jump, 9)) continue;
if(xsjs % 128 == 0) {
if(xsjs == 1280) break;
if(!(jumps=(uint32_t *)cli_realloc2(jumps, (xsjs+128)*sizeof(uint32_t)))) {
free(exe_sections);
return CL_EMEM;
}
}
j=0;
for(; j<xsjs; j++) {
if(jumps[j]<jump) continue;
if(jumps[j]==jump) {
xsjs--;
break;
}
jold=jumps[j];
jumps[j]=jump;
jump=jold;
}
jumps[j]=jump;
xsjs++;
}
if(!xsjs) break;
cli_dbgmsg("Polipos: Checking %d xsect jump(s)\n", xsjs);
for(i=0;i<xsjs;i++) {
if(!(code = fmap_need_off_once(map, jumps[i], 9))) continue;
if((jump=cli_readint32(code))==0x60ec8b55 || (code[4]==0x0ec && ((jump==0x83ec8b55 && code[6]==0x60) || (jump==0x81ec8b55 && !code[7] && !code[8])))) {
cli_append_virus(ctx,"Heuristics.W32.Polipos.A");
if (!SCAN_ALL) {
free(jumps);
free(exe_sections);
return CL_VIRUS;
}
viruses_found++;
}
}
free(jumps);
break;
}
/* Trojan.Swizzor.Gen */
if (SCAN_ALGO && (DCONF & PE_CONF_SWIZZOR) && nsections > 1 && fsize > 64*1024 && fsize < 4*1024*1024) {
if(dirs[2].Size) {
struct swizz_stats *stats = cli_calloc(1, sizeof(*stats));
unsigned int m = 1000;
ret = CL_CLEAN;
if (!stats)
ret = CL_EMEM;
else {
cli_parseres_special(EC32(dirs[2].VirtualAddress), EC32(dirs[2].VirtualAddress), map, exe_sections, nsections, fsize, hdr_size, 0, 0, &m, stats);
if ((ret = cli_detect_swizz(stats)) == CL_VIRUS) {
cli_append_virus(ctx,"Heuristics.Trojan.Swizzor.Gen");
}
free(stats);
}
if (ret != CL_CLEAN) {
if (!(ret == CL_VIRUS && SCAN_ALL)) {
free(exe_sections);
return ret;
}
viruses_found++;
}
}
}
/* !!!!!!!!!!!!!! PACKERS START HERE !!!!!!!!!!!!!! */
corrupted_cur = ctx->corrupted_input;
ctx->corrupted_input = 2; /* caller will reset on return */
/* UPX, FSG, MEW support */
/* try to find the first section with physical size == 0 */
found = 0;
if(DCONF & (PE_CONF_UPX | PE_CONF_FSG | PE_CONF_MEW)) {
for(i = 0; i < (unsigned int) nsections - 1; i++) {
if(!exe_sections[i].rsz && exe_sections[i].vsz && exe_sections[i + 1].rsz && exe_sections[i + 1].vsz) {
found = 1;
cli_dbgmsg("UPX/FSG/MEW: empty section found - assuming compression\n");
#if HAVE_JSON
cli_jsonbool(pe_json, "HasEmptySection", 1);
#endif
break;
}
}
}
/* MEW support */
if (found && (DCONF & PE_CONF_MEW) && epsize>=16 && epbuff[0]=='\xe9') {
uint32_t fileoffset;
const char *tbuff;
fileoffset = (vep + cli_readint32(epbuff + 1) + 5);
while (fileoffset == 0x154 || fileoffset == 0x158) {
char *src;
uint32_t offdiff, uselzma;
cli_dbgmsg ("MEW: found MEW characteristics %08X + %08X + 5 = %08X\n",
cli_readint32(epbuff + 1), vep, cli_readint32(epbuff + 1) + vep + 5);
if(!(tbuff = fmap_need_off_once(map, fileoffset, 0xb0)))
break;
if (fileoffset == 0x154) cli_dbgmsg("MEW: Win9x compatibility was set!\n");
else cli_dbgmsg("MEW: Win9x compatibility was NOT set!\n");
if((offdiff = cli_readint32(tbuff+1) - EC32(optional_hdr32.ImageBase)) <= exe_sections[i + 1].rva || offdiff >= exe_sections[i + 1].rva + exe_sections[i + 1].raw - 4) {
cli_dbgmsg("MEW: ESI is not in proper section\n");
break;
}
offdiff -= exe_sections[i + 1].rva;
if(!exe_sections[i + 1].rsz) {
cli_dbgmsg("MEW: mew section is empty\n");
break;
}
ssize = exe_sections[i + 1].vsz;
dsize = exe_sections[i].vsz;
cli_dbgmsg("MEW: ssize %08x dsize %08x offdiff: %08x\n", ssize, dsize, offdiff);
CLI_UNPSIZELIMITS("MEW", MAX(ssize, dsize));
CLI_UNPSIZELIMITS("MEW", MAX(ssize + dsize, exe_sections[i + 1].rsz));
if (exe_sections[i + 1].rsz < offdiff + 12 || exe_sections[i + 1].rsz > ssize) {
cli_dbgmsg("MEW: Size mismatch: %08x\n", exe_sections[i + 1].rsz);
break;
}
/* allocate needed buffer */
if (!(src = cli_calloc (ssize + dsize, sizeof(char)))) {
free(exe_sections);
return CL_EMEM;
}
if((bytes = fmap_readn(map, src + dsize, exe_sections[i + 1].raw, exe_sections[i + 1].rsz)) != exe_sections[i + 1].rsz) {
cli_dbgmsg("MEW: Can't read %d bytes [read: %lu]\n", exe_sections[i + 1].rsz, (unsigned long)bytes);
free(exe_sections);
free(src);
return CL_EREAD;
}
cli_dbgmsg("MEW: %u (%08x) bytes read\n", (unsigned int)bytes, (unsigned int)bytes);
/* count offset to lzma proc, if lzma used, 0xe8 -> call */
if (tbuff[0x7b] == '\xe8') {
if (!CLI_ISCONTAINED(exe_sections[1].rva, exe_sections[1].vsz, cli_readint32(tbuff + 0x7c) + fileoffset + 0x80, 4)) {
cli_dbgmsg("MEW: lzma proc out of bounds!\n");
free(src);
break; /* to next unpacker in chain */
}
uselzma = cli_readint32(tbuff + 0x7c) - (exe_sections[0].rva - fileoffset - 0x80);
} else {
uselzma = 0;
}
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "MEW");
#endif
CLI_UNPTEMP("MEW",(src,exe_sections,0));
CLI_UNPRESULTS("MEW",(unmew11(src, offdiff, ssize, dsize, EC32(optional_hdr32.ImageBase), exe_sections[0].rva, uselzma, ndesc)),1,(src,0));
break;
}
}
if(epsize<168) {
free(exe_sections);
return CL_CLEAN;
}
if (found || upack) {
/* Check EP for UPX vs. FSG vs. Upack */
/* Upack 0.39 produces 2 types of executables
* 3 sections: | 2 sections (one empty, I don't chech found if !upack, since it's in OR above):
* mov esi, value | pusha
* lodsd | call $+0x9
* push eax |
*
* Upack 1.1/1.2 Beta produces [based on 2 samples (sUx) provided by aCaB]:
* 2 sections
* mov esi, value
* loads
* mov edi, eax
*
* Upack unknown [sample 0297729]
* 3 sections
* mov esi, value
* push [esi]
* jmp
*
*/
/* upack 0.39-3s + sample 0151477*/
while(((upack && nsections == 3) && /* 3 sections */
((
epbuff[0] == '\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > min && /* mov esi */
epbuff[5] == '\xad' && epbuff[6] == '\x50' /* lodsd; push eax */
)
||
/* based on 0297729 sample from aCaB */
(epbuff[0] == '\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > min && /* mov esi */
epbuff[5] == '\xff' && epbuff[6] == '\x36' /* push [esi] */
)
))
||
((!upack && nsections == 2) && /* 2 sections */
(( /* upack 0.39-2s */
epbuff[0] == '\x60' && epbuff[1] == '\xe8' && cli_readint32(epbuff+2) == 0x9 /* pusha; call+9 */
)
||
( /* upack 1.1/1.2, based on 2 samples */
epbuff[0] == '\xbe' && cli_readint32(epbuff+1) - EC32(optional_hdr32.ImageBase) < min && /* mov esi */
cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > 0 &&
epbuff[5] == '\xad' && epbuff[6] == '\x8b' && epbuff[7] == '\xf8' /* loads; mov edi, eax */
)
))
) {
uint32_t vma, off;
int a,b,c;
cli_dbgmsg("Upack characteristics found.\n");
a = exe_sections[0].vsz;
b = exe_sections[1].vsz;
if (upack) {
cli_dbgmsg("Upack: var set\n");
c = exe_sections[2].vsz;
ssize = exe_sections[0].ursz + exe_sections[0].uraw;
off = exe_sections[0].rva;
vma = EC32(optional_hdr32.ImageBase) + exe_sections[0].rva;
} else {
cli_dbgmsg("Upack: var NOT set\n");
c = exe_sections[1].rva;
ssize = exe_sections[1].uraw;
off = 0;
vma = exe_sections[1].rva - exe_sections[1].uraw;
}
dsize = a+b+c;
CLI_UNPSIZELIMITS("Upack", MAX(MAX(dsize, ssize), exe_sections[1].ursz));
if (!CLI_ISCONTAINED(0, dsize, exe_sections[1].rva - off, exe_sections[1].ursz) || (upack && !CLI_ISCONTAINED(0, dsize, exe_sections[2].rva - exe_sections[0].rva, ssize)) || ssize > dsize) {
cli_dbgmsg("Upack: probably malformed pe-header, skipping to next unpacker\n");
break;
}
if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
free(exe_sections);
return CL_EMEM;
}
if((unsigned int)fmap_readn(map, dest, 0, ssize) != ssize) {
cli_dbgmsg("Upack: Can't read raw data of section 0\n");
free(dest);
break;
}
if(upack) memmove(dest + exe_sections[2].rva - exe_sections[0].rva, dest, ssize);
if((unsigned int)fmap_readn(map, dest + exe_sections[1].rva - off, exe_sections[1].uraw, exe_sections[1].ursz) != exe_sections[1].ursz) {
cli_dbgmsg("Upack: Can't read raw data of section 1\n");
free(dest);
break;
}
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "Upack");
#endif
CLI_UNPTEMP("Upack",(dest,exe_sections,0));
CLI_UNPRESULTS("Upack",(unupack(upack, dest, dsize, epbuff, vma, ep, EC32(optional_hdr32.ImageBase), exe_sections[0].rva, ndesc)),1,(dest,0));
break;
}
}
while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\x87' && epbuff[1] == '\x25') {
const char *dst;
/* FSG v2.0 support - thanks to aCaB ! */
uint32_t newesi, newedi, newebx, newedx;
ssize = exe_sections[i + 1].rsz;
dsize = exe_sections[i].vsz;
CLI_UNPSIZELIMITS("FSG", MAX(dsize, ssize));
if(ssize <= 0x19 || dsize <= ssize) {
cli_dbgmsg("FSG: Size mismatch (ssize: %d, dsize: %d)\n", ssize, dsize);
free(exe_sections);
return CL_CLEAN;
}
newedx = cli_readint32(epbuff + 2) - EC32(optional_hdr32.ImageBase);
if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newedx, 4)) {
cli_dbgmsg("FSG: xchg out of bounds (%x), giving up\n", newedx);
break;
}
if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) {
cli_dbgmsg("Can't read raw data of section %d\n", i + 1);
free(exe_sections);
return CL_ESEEK;
}
dst = src + newedx - exe_sections[i + 1].rva;
if(newedx < exe_sections[i + 1].rva || !CLI_ISCONTAINED(src, ssize, dst, 4)) {
cli_dbgmsg("FSG: New ESP out of bounds\n");
break;
}
newedx = cli_readint32(dst) - EC32(optional_hdr32.ImageBase);
if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newedx, 4)) {
cli_dbgmsg("FSG: New ESP (%x) is wrong\n", newedx);
break;
}
dst = src + newedx - exe_sections[i + 1].rva;
if(!CLI_ISCONTAINED(src, ssize, dst, 32)) {
cli_dbgmsg("FSG: New stack out of bounds\n");
break;
}
newedi = cli_readint32(dst) - EC32(optional_hdr32.ImageBase);
newesi = cli_readint32(dst + 4) - EC32(optional_hdr32.ImageBase);
newebx = cli_readint32(dst + 16) - EC32(optional_hdr32.ImageBase);
newedx = cli_readint32(dst + 20);
if(newedi != exe_sections[i].rva) {
cli_dbgmsg("FSG: Bad destination buffer (edi is %x should be %x)\n", newedi, exe_sections[i].rva);
break;
}
if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].rsz) {
cli_dbgmsg("FSG: Source buffer out of section bounds\n");
break;
}
if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newebx, 16)) {
cli_dbgmsg("FSG: Array of functions out of bounds\n");
break;
}
newedx=cli_readint32(newebx + 12 - exe_sections[i + 1].rva + src) - EC32(optional_hdr32.ImageBase);
cli_dbgmsg("FSG: found old EP @%x\n",newedx);
if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
free(exe_sections);
return CL_EMEM;
}
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "FSG");
#endif
CLI_UNPTEMP("FSG",(dest,exe_sections,0));
CLI_UNPRESULTSFSG2("FSG",(unfsg_200(newesi - exe_sections[i + 1].rva + src, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, newedi, EC32(optional_hdr32.ImageBase), newedx, ndesc)),1,(dest,0));
break;
}
while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) < min) {
/* FSG support - v. 1.33 (thx trog for the many samples) */
int sectcnt = 0;
const char *support;
uint32_t newesi, newedi, oldep, gp, t;
struct cli_exe_section *sections;
ssize = exe_sections[i + 1].rsz;
dsize = exe_sections[i].vsz;
CLI_UNPSIZELIMITS("FSG", MAX(dsize, ssize));
if(ssize <= 0x19 || dsize <= ssize) {
cli_dbgmsg("FSG: Size mismatch (ssize: %d, dsize: %d)\n", ssize, dsize);
free(exe_sections);
return CL_CLEAN;
}
if(!(t = cli_rawaddr(cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase), NULL, 0 , &err, fsize, hdr_size)) && err ) {
cli_dbgmsg("FSG: Support data out of padding area\n");
break;
}
gp = exe_sections[i + 1].raw - t;
CLI_UNPSIZELIMITS("FSG", gp);
if(!(support = fmap_need_off_once(map, t, gp))) {
cli_dbgmsg("Can't read %d bytes from padding area\n", gp);
free(exe_sections);
return CL_EREAD;
}
/* newebx = cli_readint32(support) - EC32(optional_hdr32.ImageBase); Unused */
newedi = cli_readint32(support + 4) - EC32(optional_hdr32.ImageBase); /* 1st dest */
newesi = cli_readint32(support + 8) - EC32(optional_hdr32.ImageBase); /* Source */
if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].rsz) {
cli_dbgmsg("FSG: Source buffer out of section bounds\n");
break;
}
if(newedi != exe_sections[i].rva) {
cli_dbgmsg("FSG: Bad destination (is %x should be %x)\n", newedi, exe_sections[i].rva);
break;
}
/* Counting original sections */
for(t = 12; t < gp - 4; t += 4) {
uint32_t rva = cli_readint32(support+t);
if(!rva)
break;
rva -= EC32(optional_hdr32.ImageBase)+1;
sectcnt++;
if(rva % 0x1000) cli_dbgmsg("FSG: Original section %d is misaligned\n", sectcnt);
if(rva < exe_sections[i].rva || rva - exe_sections[i].rva >= exe_sections[i].vsz) {
cli_dbgmsg("FSG: Original section %d is out of bounds\n", sectcnt);
break;
}
}
if(t >= gp - 4 || cli_readint32(support + t)) {
break;
}
if((sections = (struct cli_exe_section *) cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) {
cli_errmsg("FSG: Unable to allocate memory for sections %lu\n", (sectcnt + 1) * sizeof(struct cli_exe_section));
free(exe_sections);
return CL_EMEM;
}
sections[0].rva = newedi;
for(t = 1; t <= (uint32_t)sectcnt; t++)
sections[t].rva = cli_readint32(support + 8 + t * 4) - 1 - EC32(optional_hdr32.ImageBase);
if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) {
cli_dbgmsg("Can't read raw data of section %d\n", i);
free(exe_sections);
free(sections);
return CL_EREAD;
}
if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
free(exe_sections);
free(sections);
return CL_EMEM;
}
oldep = vep + 161 + 6 + cli_readint32(epbuff+163);
cli_dbgmsg("FSG: found old EP @%x\n", oldep);
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "FSG");
#endif
CLI_UNPTEMP("FSG",(dest,sections,exe_sections,0));
CLI_UNPRESULTSFSG1("FSG",(unfsg_133(src + newesi - exe_sections[i + 1].rva, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, sections, sectcnt, EC32(optional_hdr32.ImageBase), oldep, ndesc)),1,(dest,sections,0));
break; /* were done with 1.33 */
}
while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\xbb' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) < min && epbuff[5] == '\xbf' && epbuff[10] == '\xbe' && vep >= exe_sections[i + 1].rva && vep - exe_sections[i + 1].rva > exe_sections[i + 1].rva - 0xe0 ) {
/* FSG support - v. 1.31 */
int sectcnt = 0;
uint32_t gp, t = cli_rawaddr(cli_readint32(epbuff+1) - EC32(optional_hdr32.ImageBase), NULL, 0 , &err, fsize, hdr_size);
const char *support;
uint32_t newesi = cli_readint32(epbuff+11) - EC32(optional_hdr32.ImageBase);
uint32_t newedi = cli_readint32(epbuff+6) - EC32(optional_hdr32.ImageBase);
uint32_t oldep = vep - exe_sections[i + 1].rva;
struct cli_exe_section *sections;
ssize = exe_sections[i + 1].rsz;
dsize = exe_sections[i].vsz;
if(err) {
cli_dbgmsg("FSG: Support data out of padding area\n");
break;
}
if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].raw) {
cli_dbgmsg("FSG: Source buffer out of section bounds\n");
break;
}
if(newedi != exe_sections[i].rva) {
cli_dbgmsg("FSG: Bad destination (is %x should be %x)\n", newedi, exe_sections[i].rva);
break;
}
CLI_UNPSIZELIMITS("FSG", MAX(dsize, ssize));
if(ssize <= 0x19 || dsize <= ssize) {
cli_dbgmsg("FSG: Size mismatch (ssize: %d, dsize: %d)\n", ssize, dsize);
free(exe_sections);
return CL_CLEAN;
}
gp = exe_sections[i + 1].raw - t;
CLI_UNPSIZELIMITS("FSG", gp)
if(!(support = fmap_need_off_once(map, t, gp))) {
cli_dbgmsg("Can't read %d bytes from padding area\n", gp);
free(exe_sections);
return CL_EREAD;
}
/* Counting original sections */
for(t = 0; t < gp - 2; t += 2) {
uint32_t rva = support[t]|(support[t+1]<<8);
if (rva == 2 || rva == 1)
break;
rva = ((rva-2)<<12) - EC32(optional_hdr32.ImageBase);
sectcnt++;
if(rva < exe_sections[i].rva || rva - exe_sections[i].rva >= exe_sections[i].vsz) {
cli_dbgmsg("FSG: Original section %d is out of bounds\n", sectcnt);
break;
}
}
if(t >= gp-10 || cli_readint32(support + t + 6) != 2) {
break;
}
if((sections = (struct cli_exe_section *) cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) {
cli_errmsg("FSG: Unable to allocate memory for sections %lu\n", (sectcnt + 1) * sizeof(struct cli_exe_section));
free(exe_sections);
return CL_EMEM;
}
sections[0].rva = newedi;
for(t = 0; t <= (uint32_t)sectcnt - 1; t++) {
sections[t+1].rva = (((support[t*2]|(support[t*2+1]<<8))-2)<<12)-EC32(optional_hdr32.ImageBase);
}
if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) {
cli_dbgmsg("FSG: Can't read raw data of section %d\n", i);
free(exe_sections);
free(sections);
return CL_EREAD;
}
if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
free(exe_sections);
free(sections);
return CL_EMEM;
}
gp = 0xda + 6*(epbuff[16]=='\xe8');
oldep = vep + gp + 6 + cli_readint32(src+gp+2+oldep);
cli_dbgmsg("FSG: found old EP @%x\n", oldep);
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "FSG");
#endif
CLI_UNPTEMP("FSG",(dest,sections,exe_sections,0));
CLI_UNPRESULTSFSG1("FSG",(unfsg_133(src + newesi - exe_sections[i + 1].rva, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, sections, sectcnt, EC32(optional_hdr32.ImageBase), oldep, ndesc)),1,(dest,sections,0));
break; /* were done with 1.31 */
}
if(found && (DCONF & PE_CONF_UPX)) {
/* UPX support */
/* we assume (i + 1) is UPX1 */
ssize = exe_sections[i + 1].rsz;
dsize = exe_sections[i].vsz + exe_sections[i + 1].vsz;
/* cli_dbgmsg("UPX: ssize %u dsize %u\n", ssize, dsize); */
CLI_UNPSIZELIMITS("UPX", MAX(dsize, ssize));
if(ssize <= 0x19 || dsize <= ssize || dsize > CLI_MAX_ALLOCATION ) {
cli_dbgmsg("UPX: Size mismatch or dsize too big (ssize: %d, dsize: %d)\n", ssize, dsize);
free(exe_sections);
return CL_CLEAN;
}
if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) {
cli_dbgmsg("UPX: Can't read raw data of section %d\n", i+1);
free(exe_sections);
return CL_EREAD;
}
if((dest = (char *) cli_calloc(dsize + 8192, sizeof(char))) == NULL) {
free(exe_sections);
return CL_EMEM;
}
/* try to detect UPX code */
if(cli_memstr(UPX_NRV2B, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2B, 24, epbuff + 0x69 + 8, 13)) {
cli_dbgmsg("UPX: Looks like a NRV2B decompression routine\n");
upxfn = upx_inflate2b;
} else if(cli_memstr(UPX_NRV2D, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2D, 24, epbuff + 0x69 + 8, 13)) {
cli_dbgmsg("UPX: Looks like a NRV2D decompression routine\n");
upxfn = upx_inflate2d;
} else if(cli_memstr(UPX_NRV2E, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2E, 24, epbuff + 0x69 + 8, 13)) {
cli_dbgmsg("UPX: Looks like a NRV2E decompression routine\n");
upxfn = upx_inflate2e;
}
if(upxfn) {
int skew = cli_readint32(epbuff + 2) - EC32(optional_hdr32.ImageBase) - exe_sections[i + 1].rva;
if(epbuff[1] != '\xbe' || skew <= 0 || skew > 0xfff) { /* FIXME: legit skews?? */
skew = 0;
} else if ((unsigned int)skew > ssize) {
/* Ignore suggested skew larger than section size */
skew = 0;
} else {
cli_dbgmsg("UPX: UPX1 seems skewed by %d bytes\n", skew);
}
/* Try skewed first (skew may be zero) */
if(upxfn(src + skew, ssize - skew, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep-skew) >= 0) {
upx_success = 1;
}
/* If skew not successful and non-zero, try no skew */
else if(skew && (upxfn(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >= 0)) {
upx_success = 1;
}
if(upx_success)
cli_dbgmsg("UPX: Successfully decompressed\n");
else
cli_dbgmsg("UPX: Preferred decompressor failed\n");
}
if(!upx_success && upxfn != upx_inflate2b) {
if(upx_inflate2b(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2b(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) {
cli_dbgmsg("UPX: NRV2B decompressor failed\n");
} else {
upx_success = 1;
cli_dbgmsg("UPX: Successfully decompressed with NRV2B\n");
}
}
if(!upx_success && upxfn != upx_inflate2d) {
if(upx_inflate2d(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2d(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) {
cli_dbgmsg("UPX: NRV2D decompressor failed\n");
} else {
upx_success = 1;
cli_dbgmsg("UPX: Successfully decompressed with NRV2D\n");
}
}
if(!upx_success && upxfn != upx_inflate2e) {
if(upx_inflate2e(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2e(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) {
cli_dbgmsg("UPX: NRV2E decompressor failed\n");
} else {
upx_success = 1;
cli_dbgmsg("UPX: Successfully decompressed with NRV2E\n");
}
}
if(cli_memstr(UPX_LZMA2, 20, epbuff + 0x2f, 20)) {
uint32_t strictdsize=cli_readint32(epbuff+0x21), skew = 0;
if(ssize > 0x15 && epbuff[0] == '\x60' && epbuff[1] == '\xbe') {
skew = cli_readint32(epbuff+2) - exe_sections[i + 1].rva - optional_hdr32.ImageBase;
if(skew!=0x15) skew = 0;
}
if(strictdsize<=dsize)
upx_success = upx_inflatelzma(src+skew, ssize-skew, dest, &strictdsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >=0;
} else if (cli_memstr(UPX_LZMA1, 20, epbuff + 0x39, 20)) {
uint32_t strictdsize=cli_readint32(epbuff+0x2b), skew = 0;
if(ssize > 0x15 && epbuff[0] == '\x60' && epbuff[1] == '\xbe') {
skew = cli_readint32(epbuff+2) - exe_sections[i + 1].rva - optional_hdr32.ImageBase;
if(skew!=0x15) skew = 0;
}
if(strictdsize<=dsize)
upx_success = upx_inflatelzma(src+skew, ssize-skew, dest, &strictdsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >=0;
}
if(!upx_success) {
cli_dbgmsg("UPX: All decompressors failed\n");
free(dest);
}
}
if(upx_success) {
free(exe_sections);
CLI_UNPTEMP("UPX/FSG",(dest,0));
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "UPX");
#endif
if((unsigned int) write(ndesc, dest, dsize) != dsize) {
cli_dbgmsg("UPX/FSG: Can't write %d bytes\n", dsize);
free(tempfile);
free(dest);
close(ndesc);
return CL_EWRITE;
}
free(dest);
if (lseek(ndesc, 0, SEEK_SET) == -1) {
cli_dbgmsg("UPX/FSG: lseek() failed\n");
close(ndesc);
CLI_TMPUNLK();
free(tempfile);
SHA_RESET;
return CL_ESEEK;
}
if(ctx->engine->keeptmp)
cli_dbgmsg("UPX/FSG: Decompressed data saved in %s\n", tempfile);
cli_dbgmsg("***** Scanning decompressed file *****\n");
SHA_OFF;
if((ret = cli_magic_scandesc(ndesc, ctx)) == CL_VIRUS) {
close(ndesc);
CLI_TMPUNLK();
free(tempfile);
SHA_RESET;
return CL_VIRUS;
}
SHA_RESET;
close(ndesc);
CLI_TMPUNLK();
free(tempfile);
return ret;
}
/* Petite */
if(epsize<200) {
free(exe_sections);
return CL_CLEAN;
}
found = 2;
if(epbuff[0] != '\xb8' || (uint32_t) cli_readint32(epbuff + 1) != exe_sections[nsections - 1].rva + EC32(optional_hdr32.ImageBase)) {
if(nsections < 2 || epbuff[0] != '\xb8' || (uint32_t) cli_readint32(epbuff + 1) != exe_sections[nsections - 2].rva + EC32(optional_hdr32.ImageBase))
found = 0;
else
found = 1;
}
if(found && (DCONF & PE_CONF_PETITE)) {
cli_dbgmsg("Petite: v2.%d compression detected\n", found);
if(cli_readint32(epbuff + 0x80) == 0x163c988d) {
cli_dbgmsg("Petite: level zero compression is not supported yet\n");
} else {
dsize = max - min;
CLI_UNPSIZELIMITS("Petite", dsize);
if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
cli_dbgmsg("Petite: Can't allocate %d bytes\n", dsize);
free(exe_sections);
return CL_EMEM;
}
for(i = 0 ; i < nsections; i++) {
if(exe_sections[i].raw) {
if(!exe_sections[i].rsz || (unsigned int)fmap_readn(map, dest + exe_sections[i].rva - min, exe_sections[i].raw, exe_sections[i].ursz) != exe_sections[i].ursz) {
free(exe_sections);
free(dest);
return CL_CLEAN;
}
}
}
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "Petite");
#endif
CLI_UNPTEMP("Petite",(dest,exe_sections,0));
CLI_UNPRESULTS("Petite",(petite_inflate2x_1to9(dest, min, max - min, exe_sections, nsections - (found == 1 ? 1 : 0), EC32(optional_hdr32.ImageBase),vep, ndesc, found, EC32(optional_hdr32.DataDirectory[2].VirtualAddress),EC32(optional_hdr32.DataDirectory[2].Size))),0,(dest,0));
}
}
/* PESpin 1.1 */
if((DCONF & PE_CONF_PESPIN) && nsections > 1 &&
vep >= exe_sections[nsections - 1].rva &&
vep < exe_sections[nsections - 1].rva + exe_sections[nsections - 1].rsz - 0x3217 - 4 &&
memcmp(epbuff+4, "\xe8\x00\x00\x00\x00\x8b\x1c\x24\x83\xc3", 10) == 0) {
char *spinned;
CLI_UNPSIZELIMITS("PEspin", fsize);
if((spinned = (char *) cli_malloc(fsize)) == NULL) {
cli_errmsg("PESping: Unable to allocate memory for spinned %lu\n", (unsigned long)fsize);
free(exe_sections);
return CL_EMEM;
}
if((size_t) fmap_readn(map, spinned, 0, fsize) != fsize) {
cli_dbgmsg("PESpin: Can't read %lu bytes\n", (unsigned long)fsize);
free(spinned);
free(exe_sections);
return CL_EREAD;
}
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "PEspin");
#endif
CLI_UNPTEMP("PESpin",(spinned,exe_sections,0));
CLI_UNPRESULTS_("PEspin",SPINCASE(),(unspin(spinned, fsize, exe_sections, nsections - 1, vep, ndesc, ctx)),0,(spinned,0));
}
/* yC 1.3 & variants */
if((DCONF & PE_CONF_YC) && nsections > 1 &&
(EC32(optional_hdr32.AddressOfEntryPoint) == exe_sections[nsections - 1].rva + 0x60)) {
uint32_t ecx = 0;
int16_t offset;
/* yC 1.3 */
if (!memcmp(epbuff, "\x55\x8B\xEC\x53\x56\x57\x60\xE8\x00\x00\x00\x00\x5D\x81\xED", 15) &&
!memcmp(epbuff+0x26, "\x8D\x3A\x8B\xF7\x33\xC0\xEB\x04\x90\xEB\x01\xC2\xAC", 13) &&
((uint8_t)epbuff[0x13] == 0xB9) &&
((uint16_t)(cli_readint16(epbuff+0x18)) == 0xE981) &&
!memcmp(epbuff+0x1e,"\x8B\xD5\x81\xC2", 4)) {
offset = 0;
if (0x6c - cli_readint32(epbuff+0xf) + cli_readint32(epbuff+0x22) == 0xC6)
ecx = cli_readint32(epbuff+0x14) - cli_readint32(epbuff+0x1a);
}
/* yC 1.3 variant */
if (!ecx && !memcmp(epbuff, "\x55\x8B\xEC\x83\xEC\x40\x53\x56\x57", 9) &&
!memcmp(epbuff+0x17, "\xe8\x00\x00\x00\x00\x5d\x81\xed", 8) &&
((uint8_t)epbuff[0x23] == 0xB9)) {
offset = 0x10;
if (0x6c - cli_readint32(epbuff+0x1f) + cli_readint32(epbuff+0x32) == 0xC6)
ecx = cli_readint32(epbuff+0x24) - cli_readint32(epbuff+0x2a);
}
/* yC 1.x/modified */
if (!ecx && !memcmp(epbuff, "\x60\xe8\x00\x00\x00\x00\x5d\x81\xed",9) &&
((uint8_t)epbuff[0xd] == 0xb9) &&
((uint16_t)cli_readint16(epbuff + 0x12)== 0xbd8d) &&
!memcmp(epbuff+0x18, "\x8b\xf7\xac", 3)) {
offset = -0x18;
if (0x66 - cli_readint32(epbuff+0x9) + cli_readint32(epbuff+0x14) == 0xae)
ecx = cli_readint32(epbuff+0xe);
}
if (ecx > 0x800 && ecx < 0x2000 &&
!memcmp(epbuff+0x63+offset, "\xaa\xe2\xcc", 3) &&
(fsize >= exe_sections[nsections-1].raw + 0xC6 + ecx + offset)) {
char *spinned;
if((spinned = (char *) cli_malloc(fsize)) == NULL) {
cli_errmsg("yC: Unable to allocate memory for spinned %lu\n", (unsigned long)fsize);
free(exe_sections);
return CL_EMEM;
}
if((size_t) fmap_readn(map, spinned, 0, fsize) != fsize) {
cli_dbgmsg("yC: Can't read %lu bytes\n", (unsigned long)fsize);
free(spinned);
free(exe_sections);
return CL_EREAD;
}
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "yC");
#endif
cli_dbgmsg("%d,%d,%d,%d\n", nsections-1, e_lfanew, ecx, offset);
CLI_UNPTEMP("yC",(spinned,exe_sections,0));
CLI_UNPRESULTS("yC",(yc_decrypt(spinned, fsize, exe_sections, nsections-1, e_lfanew, ndesc, ecx, offset)),0,(spinned,0));
}
}
/* WWPack */
while ((DCONF & PE_CONF_WWPACK) && nsections > 1 &&
vep == exe_sections[nsections - 1].rva &&
memcmp(epbuff, "\x53\x55\x8b\xe8\x33\xdb\xeb", 7) == 0 &&
memcmp(epbuff+0x68, "\xe8\x00\x00\x00\x00\x58\x2d\x6d\x00\x00\x00\x50\x60\x33\xc9\x50\x58\x50\x50", 19) == 0) {
uint32_t head = exe_sections[nsections - 1].raw;
uint8_t *packer;
char *src;
ssize = 0;
for(i=0 ; ; i++) {
if(exe_sections[i].raw<head)
head=exe_sections[i].raw;
if(i+1==nsections) break;
if(ssize<exe_sections[i].rva+exe_sections[i].vsz)
ssize=exe_sections[i].rva+exe_sections[i].vsz;
}
if(!head || !ssize || head>ssize) break;
CLI_UNPSIZELIMITS("WWPack", ssize);
if(!(src=(char *)cli_calloc(ssize, sizeof(char)))) {
free(exe_sections);
return CL_EMEM;
}
if((size_t) fmap_readn(map, src, 0, head) != head) {
cli_dbgmsg("WWPack: Can't read %d bytes from headers\n", head);
free(src);
free(exe_sections);
return CL_EREAD;
}
for(i = 0 ; i < (unsigned int)nsections-1; i++) {
if(!exe_sections[i].rsz) continue;
if(!CLI_ISCONTAINED(src, ssize, src+exe_sections[i].rva, exe_sections[i].rsz)) break;
if((unsigned int)fmap_readn(map, src+exe_sections[i].rva, exe_sections[i].raw, exe_sections[i].rsz)!=exe_sections[i].rsz) break;
}
if(i+1!=nsections) {
cli_dbgmsg("WWpack: Probably hacked/damaged file.\n");
free(src);
break;
}
if((packer = (uint8_t *) cli_calloc(exe_sections[nsections - 1].rsz, sizeof(char))) == NULL) {
free(src);
free(exe_sections);
return CL_EMEM;
}
if(!exe_sections[nsections - 1].rsz || (size_t) fmap_readn(map, packer, exe_sections[nsections - 1].raw, exe_sections[nsections - 1].rsz) != exe_sections[nsections - 1].rsz) {
cli_dbgmsg("WWPack: Can't read %d bytes from wwpack sect\n", exe_sections[nsections - 1].rsz);
free(src);
free(packer);
free(exe_sections);
return CL_EREAD;
}
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "WWPack");
#endif
CLI_UNPTEMP("WWPack",(src,packer,exe_sections,0));
CLI_UNPRESULTS("WWPack",(wwunpack((uint8_t *)src, ssize, packer, exe_sections, nsections-1, e_lfanew, ndesc)),0,(src,packer,0));
break;
}
/* ASPACK support */
while((DCONF & PE_CONF_ASPACK) && ep+58+0x70e < fsize && !memcmp(epbuff,"\x60\xe8\x03\x00\x00\x00\xe9\xeb",8)) {
char *src;
if(epsize<0x3bf || memcmp(epbuff+0x3b9, "\x68\x00\x00\x00\x00\xc3",6)) break;
ssize = 0;
for(i=0 ; i< nsections ; i++)
if(ssize<exe_sections[i].rva+exe_sections[i].vsz)
ssize=exe_sections[i].rva+exe_sections[i].vsz;
if(!ssize) break;
CLI_UNPSIZELIMITS("Aspack", ssize);
if(!(src=(char *)cli_calloc(ssize, sizeof(char)))) {
free(exe_sections);
return CL_EMEM;
}
for(i = 0 ; i < (unsigned int)nsections; i++) {
if(!exe_sections[i].rsz) continue;
if(!CLI_ISCONTAINED(src, ssize, src+exe_sections[i].rva, exe_sections[i].rsz)) break;
if((unsigned int)fmap_readn(map, src+exe_sections[i].rva, exe_sections[i].raw, exe_sections[i].rsz)!=exe_sections[i].rsz) break;
}
if(i!=nsections) {
cli_dbgmsg("Aspack: Probably hacked/damaged Aspack file.\n");
free(src);
break;
}
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "Aspack");
#endif
CLI_UNPTEMP("Aspack",(src,exe_sections,0));
CLI_UNPRESULTS("Aspack",(unaspack212((uint8_t *)src, ssize, exe_sections, nsections, vep-1, EC32(optional_hdr32.ImageBase), ndesc)),1,(src,0));
break;
}
/* NsPack */
while (DCONF & PE_CONF_NSPACK) {
uint32_t eprva = vep;
uint32_t start_of_stuff, rep = ep;
unsigned int nowinldr;
const char *nbuff;
src=epbuff;
if (*epbuff=='\xe9') { /* bitched headers */
eprva = cli_readint32(epbuff+1)+vep+5;
if (!(rep = cli_rawaddr(eprva, exe_sections, nsections, &err, fsize, hdr_size)) && err) break;
if (!(nbuff = fmap_need_off_once(map, rep, 24))) break;
src = nbuff;
}
if (memcmp(src, "\x9c\x60\xe8\x00\x00\x00\x00\x5d\xb8\x07\x00\x00\x00", 13)) break;
nowinldr = 0x54-cli_readint32(src+17);
cli_dbgmsg("NsPack: Found *start_of_stuff @delta-%x\n", nowinldr);
if(!(nbuff = fmap_need_off_once(map, rep-nowinldr, 4))) break;
start_of_stuff=rep+cli_readint32(nbuff);
if(!(nbuff = fmap_need_off_once(map, start_of_stuff, 20))) break;
src = nbuff;
if (!cli_readint32(nbuff)) {
start_of_stuff+=4; /* FIXME: more to do */
src+=4;
}
ssize = cli_readint32(src+5)|0xff;
dsize = cli_readint32(src+9);
CLI_UNPSIZELIMITS("NsPack", MAX(ssize,dsize));
if (!ssize || !dsize || dsize != exe_sections[0].vsz) break;
if (!(dest=cli_malloc(dsize))) {
cli_errmsg("NsPack: Unable to allocate memory for dest %u\n", dsize);
break;
}
/* memset(dest, 0xfc, dsize); */
if(!(src = fmap_need_off(map, start_of_stuff, ssize))) {
free(dest);
break;
}
/* memset(src, 0x00, ssize); */
eprva+=0x27a;
if (!(rep = cli_rawaddr(eprva, exe_sections, nsections, &err, fsize, hdr_size)) && err) {
free(dest);
break;
}
if(!(nbuff = fmap_need_off_once(map, rep, 5))) {
free(dest);
break;
}
fmap_unneed_off(map, start_of_stuff, ssize);
eprva=eprva+5+cli_readint32(nbuff+1);
cli_dbgmsg("NsPack: OEP = %08x\n", eprva);
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "NsPack");
#endif
CLI_UNPTEMP("NsPack",(dest,exe_sections,0));
CLI_UNPRESULTS("NsPack",(unspack(src, dest, ctx, exe_sections[0].rva, EC32(optional_hdr32.ImageBase), eprva, ndesc)),0,(dest,0));
break;
}
/* to be continued ... */
/* !!!!!!!!!!!!!! PACKERS END HERE !!!!!!!!!!!!!! */
ctx->corrupted_input = corrupted_cur;
/* Bytecode BC_PE_UNPACKER hook */
bc_ctx = cli_bytecode_context_alloc();
if (!bc_ctx) {
cli_errmsg("cli_scanpe: can't allocate memory for bc_ctx\n");
return CL_EMEM;
}
cli_bytecode_context_setpe(bc_ctx, &pedata, exe_sections);
cli_bytecode_context_setctx(bc_ctx, ctx);
ret = cli_bytecode_runhook(ctx, ctx->engine, bc_ctx, BC_PE_UNPACKER, map);
switch (ret) {
case CL_VIRUS:
free(exe_sections);
cli_bytecode_context_destroy(bc_ctx);
return CL_VIRUS;
case CL_SUCCESS:
ndesc = cli_bytecode_context_getresult_file(bc_ctx, &tempfile);
cli_bytecode_context_destroy(bc_ctx);
if (ndesc != -1 && tempfile) {
CLI_UNPRESULTS("bytecode PE hook", 1, 1, (0));
}
break;
default:
cli_bytecode_context_destroy(bc_ctx);
}
free(exe_sections);
#if HAVE_JSON
if (cli_json_timeout_cycle_check(ctx, &toval) != CL_SUCCESS) {
return CL_ETIMEOUT;
}
#endif
if (SCAN_ALL && viruses_found)
return CL_VIRUS;
return CL_CLEAN;
}
int cli_peheader(fmap_t *map, struct cli_exe_info *peinfo)
{
uint16_t e_magic; /* DOS signature ("MZ") */
uint32_t e_lfanew; /* address of new exe header */
/* Obsolete - see below
uint32_t min = 0, max = 0;
*/
struct pe_image_file_hdr file_hdr;
union {
struct pe_image_optional_hdr64 opt64;
struct pe_image_optional_hdr32 opt32;
} pe_opt;
struct pe_image_section_hdr *section_hdr;
unsigned int i;
unsigned int err, pe_plus = 0;
uint32_t valign, falign, hdr_size;
size_t fsize;
ssize_t at;
struct pe_image_data_dir *dirs;
cli_dbgmsg("in cli_peheader\n");
fsize = map->len - peinfo->offset;
if(fmap_readn(map, &e_magic, peinfo->offset, sizeof(e_magic)) != sizeof(e_magic)) {
cli_dbgmsg("Can't read DOS signature\n");
return -1;
}
if(EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE && EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE_OLD) {
cli_dbgmsg("Invalid DOS signature\n");
return -1;
}
if(fmap_readn(map, &e_lfanew, peinfo->offset + 58 + sizeof(e_magic), sizeof(e_lfanew)) != sizeof(e_lfanew)) {
/* truncated header? */
return -1;
}
e_lfanew = EC32(e_lfanew);
if(!e_lfanew) {
cli_dbgmsg("Not a PE file\n");
return -1;
}
if(fmap_readn(map, &file_hdr, peinfo->offset + e_lfanew, sizeof(struct pe_image_file_hdr)) != sizeof(struct pe_image_file_hdr)) {
/* bad information in e_lfanew - probably not a PE file */
cli_dbgmsg("Can't read file header\n");
return -1;
}
if(EC32(file_hdr.Magic) != PE_IMAGE_NT_SIGNATURE) {
cli_dbgmsg("Invalid PE signature (probably NE file)\n");
return -1;
}
if ( (peinfo->nsections = EC16(file_hdr.NumberOfSections)) < 1 || peinfo->nsections > 96 ) return -1;
if (EC16(file_hdr.SizeOfOptionalHeader) < sizeof(struct pe_image_optional_hdr32)) {
cli_dbgmsg("SizeOfOptionalHeader too small\n");
return -1;
}
at = peinfo->offset + e_lfanew + sizeof(struct pe_image_file_hdr);
if(fmap_readn(map, &optional_hdr32, at, sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr32)) {
cli_dbgmsg("Can't read optional file header\n");
return -1;
}
at += sizeof(struct pe_image_optional_hdr32);
if(EC16(optional_hdr64.Magic)==PE32P_SIGNATURE) { /* PE+ */
if(EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr64)) {
cli_dbgmsg("Incorrect SizeOfOptionalHeader for PE32+\n");
return -1;
}
if(fmap_readn(map, &optional_hdr32 + 1, at, sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) {
cli_dbgmsg("Can't read optional file header\n");
return -1;
}
at += sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32);
hdr_size = EC32(optional_hdr64.SizeOfHeaders);
pe_plus=1;
} else { /* PE */
if (EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr32)) {
/* Seek to the end of the long header */
at += EC16(file_hdr.SizeOfOptionalHeader)-sizeof(struct pe_image_optional_hdr32);
}
hdr_size = EC32(optional_hdr32.SizeOfHeaders);
}
valign = (pe_plus)?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment);
falign = (pe_plus)?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment);
peinfo->hdr_size = hdr_size = PESALIGN(hdr_size, valign);
peinfo->section = (struct cli_exe_section *) cli_calloc(peinfo->nsections, sizeof(struct cli_exe_section));
if(!peinfo->section) {
cli_dbgmsg("Can't allocate memory for section headers\n");
return -1;
}
section_hdr = (struct pe_image_section_hdr *) cli_calloc(peinfo->nsections, sizeof(struct pe_image_section_hdr));
if(!section_hdr) {
cli_dbgmsg("Can't allocate memory for section headers\n");
free(peinfo->section);
peinfo->section = NULL;
return -1;
}
if(fmap_readn(map, section_hdr, at, peinfo->nsections * sizeof(struct pe_image_section_hdr)) != peinfo->nsections * sizeof(struct pe_image_section_hdr)) {
cli_dbgmsg("Can't read section header\n");
cli_dbgmsg("Possibly broken PE file\n");
free(section_hdr);
free(peinfo->section);
peinfo->section = NULL;
return -1;
}
at += sizeof(struct pe_image_section_hdr)*peinfo->nsections;
for(i = 0; falign!=0x200 && i<peinfo->nsections; i++) {
/* file alignment fallback mode - blah */
if (falign && section_hdr[i].SizeOfRawData && EC32(section_hdr[i].PointerToRawData)%falign && !(EC32(section_hdr[i].PointerToRawData)%0x200)) {
falign = 0x200;
}
}
for(i = 0; i < peinfo->nsections; i++) {
peinfo->section[i].rva = PEALIGN(EC32(section_hdr[i].VirtualAddress), valign);
peinfo->section[i].vsz = PESALIGN(EC32(section_hdr[i].VirtualSize), valign);
peinfo->section[i].raw = PEALIGN(EC32(section_hdr[i].PointerToRawData), falign);
peinfo->section[i].rsz = PESALIGN(EC32(section_hdr[i].SizeOfRawData), falign);
if (!peinfo->section[i].vsz && peinfo->section[i].rsz)
peinfo->section[i].vsz=PESALIGN(EC32(section_hdr[i].SizeOfRawData), valign);
if (peinfo->section[i].rsz && !CLI_ISCONTAINED(0, (uint32_t) fsize, peinfo->section[i].raw, peinfo->section[i].rsz))
peinfo->section[i].rsz = (fsize - peinfo->section[i].raw)*(fsize>peinfo->section[i].raw);
}
if(pe_plus) {
peinfo->ep = EC32(optional_hdr64.AddressOfEntryPoint);
dirs = optional_hdr64.DataDirectory;
} else {
peinfo->ep = EC32(optional_hdr32.AddressOfEntryPoint);
dirs = optional_hdr32.DataDirectory;
}
if(!(peinfo->ep = cli_rawaddr(peinfo->ep, peinfo->section, peinfo->nsections, &err, fsize, hdr_size)) && err) {
cli_dbgmsg("Broken PE file\n");
free(section_hdr);
free(peinfo->section);
peinfo->section = NULL;
return -1;
}
if(EC16(file_hdr.Characteristics) & 0x2000 || !dirs[2].Size)
peinfo->res_addr = 0;
else
peinfo->res_addr = EC32(dirs[2].VirtualAddress);
while(dirs[2].Size) {
struct vinfo_list vlist;
const uint8_t *vptr, *baseptr;
uint32_t rva, res_sz;
memset(&vlist, 0, sizeof(vlist));
findres(0x10, 0xffffffff, EC32(dirs[2].VirtualAddress), map, peinfo->section, peinfo->nsections, hdr_size, versioninfo_cb, &vlist);
if(!vlist.count) break; /* No version_information */
if(cli_hashset_init(&peinfo->vinfo, 32, 80)) {
cli_errmsg("cli_peheader: Unable to init vinfo hashset\n");
free(section_hdr);
free(peinfo->section);
peinfo->section = NULL;
return -1;
}
err = 0;
for(i=0; i<vlist.count; i++) { /* enum all version_information res - RESUMABLE */
cli_dbgmsg("cli_peheader: parsing version info @ rva %x (%u/%u)\n", vlist.rvas[i], i+1, vlist.count);
rva = cli_rawaddr(vlist.rvas[i], peinfo->section, peinfo->nsections, &err, fsize, hdr_size);
if(err)
continue;
if(!(vptr = fmap_need_off_once(map, rva, 16)))
continue;
baseptr = vptr - rva;
/* parse resource */
rva = cli_readint32(vptr); /* ptr to version_info */
res_sz = cli_readint32(vptr+4); /* sizeof(resource) */
rva = cli_rawaddr(rva, peinfo->section, peinfo->nsections, &err, fsize, hdr_size);
if(err)
continue;
if(!(vptr = fmap_need_off_once(map, rva, res_sz)))
continue;
while(res_sz>4) { /* look for version_info - NOT RESUMABLE (expecting exactly one versioninfo) */
uint32_t vinfo_sz, vinfo_val_sz, got_varfileinfo = 0;
vinfo_sz = vinfo_val_sz = cli_readint32(vptr);
vinfo_sz &= 0xffff;
if(vinfo_sz > res_sz)
break; /* the content is larger than the container */
vinfo_val_sz >>= 16;
if(vinfo_sz <= 6 + 0x20 + 2 + 0x34 ||
vinfo_val_sz != 0x34 ||
memcmp(vptr+6, "V\0S\0_\0V\0E\0R\0S\0I\0O\0N\0_\0I\0N\0F\0O\0\0\0", 0x20) ||
(unsigned int)cli_readint32(vptr + 0x28) != 0xfeef04bd) {
/* - there should be enough room for the header(6), the key "VS_VERSION_INFO"(20), the padding(2) and the value(34)
* - the value should be sizeof(fixedfileinfo)
* - the key should match
* - there should be some proper magic for fixedfileinfo */
break; /* there's no point in looking further */
}
/* move to the end of fixedfileinfo where the child elements are located */
vptr += 6 + 0x20 + 2 + 0x34;
vinfo_sz -= 6 + 0x20 + 2 + 0x34;
while(vinfo_sz > 6) { /* look for stringfileinfo - NOT RESUMABLE (expecting at most one stringfileinfo) */
uint32_t sfi_sz = cli_readint32(vptr) & 0xffff;
if(sfi_sz > vinfo_sz)
break; /* the content is larger than the container */
if(!got_varfileinfo && sfi_sz > 6 + 0x18 && !memcmp(vptr+6, "V\0a\0r\0F\0i\0l\0e\0I\0n\0f\0o\0\0\0", 0x18)) {
/* skip varfileinfo as it sometimes appear before stringtableinfo */
vptr += sfi_sz;
vinfo_sz -= sfi_sz;
got_varfileinfo = 1;
continue;
}
if(sfi_sz <= 6 + 0x1e || memcmp(vptr+6, "S\0t\0r\0i\0n\0g\0F\0i\0l\0e\0I\0n\0f\0o\0\0\0", 0x1e)) {
/* - there should be enough room for the header(6) and the key "StringFileInfo"(1e)
* - the key should match */
break; /* this is an implicit hard fail: parent is not resumable */
}
/* move to the end of stringfileinfo where the child elements are located */
vptr += 6 + 0x1e;
sfi_sz -= 6 + 0x1e;
while(sfi_sz > 6) { /* enum all stringtables - RESUMABLE */
uint32_t st_sz = cli_readint32(vptr) & 0xffff;
const uint8_t *next_vptr = vptr + st_sz;
uint32_t next_sfi_sz = sfi_sz - st_sz;
if(st_sz > sfi_sz || st_sz <= 24) {
/* - the content is larger than the container
- there's no room for a stringtables (headers(6) + key(16) + padding(2)) */
break; /* this is an implicit hard fail: parent is not resumable */
}
/* move to the end of stringtable where the child elements are located */
vptr += 24;
st_sz -= 24;
while(st_sz > 6) { /* enum all strings - RESUMABLE */
uint32_t s_sz, s_key_sz, s_val_sz;
s_sz = (cli_readint32(vptr) & 0xffff) + 3;
s_sz &= ~3;
if(s_sz > st_sz || s_sz <= 6 + 2 + 8) {
/* - the content is larger than the container
* - there's no room for a minimal string
* - there's no room for the value */
st_sz = 0;
sfi_sz = 0;
break; /* force a hard fail */
}
/* ~wcstrlen(key) */
for(s_key_sz = 6; s_key_sz+1 < s_sz; s_key_sz += 2) {
if(vptr[s_key_sz] || vptr[s_key_sz+1]) continue;
s_key_sz += 2;
break;
}
s_key_sz += 3;
s_key_sz &= ~3;
if(s_key_sz >= s_sz) {
/* key overflow */
vptr += s_sz;
st_sz -= s_sz;
continue;
}
s_val_sz = s_sz - s_key_sz;
s_key_sz -= 6;
if(s_val_sz <= 2) {
/* skip unset value */
vptr += s_sz;
st_sz -= s_sz;
continue;
}
if(cli_hashset_addkey(&peinfo->vinfo, (uint32_t)(vptr - baseptr + 6))) {
cli_errmsg("cli_peheader: Unable to add rva to vinfo hashset\n");
cli_hashset_destroy(&peinfo->vinfo);
free(section_hdr);
free(peinfo->section);
peinfo->section = NULL;
return -1;
}
if(cli_debug_flag) {
char *k, *v, *s;
/* FIXME: skip too long strings */
k = cli_utf16toascii((const char*)vptr + 6, s_key_sz);
if(k) {
v = cli_utf16toascii((const char*)vptr + s_key_sz + 6, s_val_sz);
if(v) {
s = cli_str2hex((const char*)vptr + 6, s_key_sz + s_val_sz - 6);
if(s) {
cli_dbgmsg("VersionInfo (%x): '%s'='%s' - VI:%s\n", (uint32_t)(vptr - baseptr + 6), k, v, s);
free(s);
}
free(v);
}
free(k);
}
}
vptr += s_sz;
st_sz -= s_sz;
} /* enum all strings - RESUMABLE */
vptr = next_vptr;
sfi_sz = next_sfi_sz * (sfi_sz != 0);
} /* enum all stringtables - RESUMABLE */
break;
} /* look for stringfileinfo - NOT RESUMABLE */
break;
} /* look for version_info - NOT RESUMABLE */
} /* enum all version_information res - RESUMABLE */
break;
} /* while(dirs[2].Size) */
free(section_hdr);
return 0;
}
static int sort_sects(const void *first, const void *second) {
const struct cli_exe_section *a = first, *b = second;
return (a->raw - b->raw);
}
int cli_checkfp_pe(cli_ctx *ctx, uint8_t *authsha1, stats_section_t *hashes, uint32_t flags) {
uint16_t e_magic; /* DOS signature ("MZ") */
uint16_t nsections;
uint32_t e_lfanew; /* address of new exe header */
struct pe_image_file_hdr file_hdr;
union {
struct pe_image_optional_hdr64 opt64;
struct pe_image_optional_hdr32 opt32;
} pe_opt;
const struct pe_image_section_hdr *section_hdr;
ssize_t at;
unsigned int i, pe_plus = 0, hlen;
size_t fsize;
uint32_t valign, falign, hdr_size;
struct cli_exe_section *exe_sections;
struct pe_image_data_dir *dirs;
fmap_t *map = *ctx->fmap;
void *hashctx=NULL;
if (flags & CL_CHECKFP_PE_FLAG_STATS)
if (!(hashes))
return CL_EFORMAT;
if (flags == CL_CHECKFP_PE_FLAG_NONE)
return CL_VIRUS;
if(!(DCONF & PE_CONF_CATALOG))
return CL_EFORMAT;
if(fmap_readn(map, &e_magic, 0, sizeof(e_magic)) != sizeof(e_magic))
return CL_EFORMAT;
if(EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE && EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE_OLD)
return CL_EFORMAT;
if(fmap_readn(map, &e_lfanew, 58 + sizeof(e_magic), sizeof(e_lfanew)) != sizeof(e_lfanew))
return CL_EFORMAT;
e_lfanew = EC32(e_lfanew);
if(!e_lfanew)
return CL_EFORMAT;
if(fmap_readn(map, &file_hdr, e_lfanew, sizeof(struct pe_image_file_hdr)) != sizeof(struct pe_image_file_hdr))
return CL_EFORMAT;
if(EC32(file_hdr.Magic) != PE_IMAGE_NT_SIGNATURE)
return CL_EFORMAT;
nsections = EC16(file_hdr.NumberOfSections);
if(nsections < 1 || nsections > 96)
return CL_EFORMAT;
if(EC16(file_hdr.SizeOfOptionalHeader) < sizeof(struct pe_image_optional_hdr32))
return CL_EFORMAT;
at = e_lfanew + sizeof(struct pe_image_file_hdr);
if(fmap_readn(map, &optional_hdr32, at, sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr32))
return CL_EFORMAT;
at += sizeof(struct pe_image_optional_hdr32);
/* This will be a chicken and egg problem until we drop 9x */
if(EC16(optional_hdr64.Magic)==PE32P_SIGNATURE) {
if(EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr64))
return CL_EFORMAT;
pe_plus = 1;
}
if(!pe_plus) { /* PE */
if (EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr32)) {
/* Seek to the end of the long header */
at += EC16(file_hdr.SizeOfOptionalHeader)-sizeof(struct pe_image_optional_hdr32);
}
hdr_size = EC32(optional_hdr32.SizeOfHeaders);
dirs = optional_hdr32.DataDirectory;
} else { /* PE+ */
size_t readlen = sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32);
/* read the remaining part of the header */
if((size_t)fmap_readn(map, &optional_hdr32 + 1, at, readlen) != readlen)
return CL_EFORMAT;
at += sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32);
hdr_size = EC32(optional_hdr64.SizeOfHeaders);
dirs = optional_hdr64.DataDirectory;
}
fsize = map->len;
valign = (pe_plus)?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment);
falign = (pe_plus)?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment);
section_hdr = fmap_need_off_once(map, at, sizeof(*section_hdr) * nsections);
if(!section_hdr)
return CL_EFORMAT;
at += sizeof(*section_hdr) * nsections;
exe_sections = (struct cli_exe_section *) cli_calloc(nsections, sizeof(struct cli_exe_section));
if(!exe_sections)
return CL_EMEM;
for(i = 0; falign!=0x200 && i<nsections; i++) {
/* file alignment fallback mode - blah */
if (falign && section_hdr[i].SizeOfRawData && EC32(section_hdr[i].PointerToRawData)%falign && !(EC32(section_hdr[i].PointerToRawData)%0x200))
falign = 0x200;
}
hdr_size = PESALIGN(hdr_size, falign); /* Aligned headers virtual size */
if (flags & CL_CHECKFP_PE_FLAG_STATS) {
hashes->nsections = nsections;
hashes->sections = cli_calloc(nsections, sizeof(struct cli_section_hash));
if (!(hashes->sections)) {
free(exe_sections);
return CL_EMEM;
}
}
for(i = 0; i < nsections; i++) {
exe_sections[i].rva = PEALIGN(EC32(section_hdr[i].VirtualAddress), valign);
exe_sections[i].vsz = PESALIGN(EC32(section_hdr[i].VirtualSize), valign);
exe_sections[i].raw = PEALIGN(EC32(section_hdr[i].PointerToRawData), falign);
exe_sections[i].rsz = PESALIGN(EC32(section_hdr[i].SizeOfRawData), falign);
if (!exe_sections[i].vsz && exe_sections[i].rsz)
exe_sections[i].vsz=PESALIGN(exe_sections[i].ursz, valign);
if (exe_sections[i].rsz && fsize>exe_sections[i].raw && !CLI_ISCONTAINED(0, (uint32_t) fsize, exe_sections[i].raw, exe_sections[i].rsz))
exe_sections[i].rsz = fsize - exe_sections[i].raw;
if (exe_sections[i].rsz && exe_sections[i].raw >= fsize) {
free(exe_sections);
return CL_EFORMAT;
}
if (exe_sections[i].urva>>31 || exe_sections[i].uvsz>>31 || (exe_sections[i].rsz && exe_sections[i].uraw>>31) || exe_sections[i].ursz>>31) {
free(exe_sections);
return CL_EFORMAT;
}
}
cli_qsort(exe_sections, nsections, sizeof(*exe_sections), sort_sects);
hashctx = cl_hash_init("sha1");
if (!(hashctx)) {
if (flags & CL_CHECKFP_PE_FLAG_AUTHENTICODE)
flags ^= CL_CHECKFP_PE_FLAG_AUTHENTICODE;
}
if (flags & CL_CHECKFP_PE_FLAG_AUTHENTICODE) {
/* Check to see if we have a security section. */
if(!cli_hm_have_size(ctx->engine->hm_fp, CLI_HASH_SHA1, 2) && dirs[4].Size < 8) {
if (flags & CL_CHECKFP_PE_FLAG_STATS) {
/* If stats is enabled, continue parsing the sample */
flags ^= CL_CHECKFP_PE_FLAG_AUTHENTICODE;
} else {
if (hashctx)
cl_hash_destroy(hashctx);
return CL_BREAK;
}
}
}
#define hash_chunk(where, size, isStatAble, section) \
do { \
const uint8_t *hptr; \
if(!(size)) break; \
if(!(hptr = fmap_need_off_once(map, where, size))){ \
free(exe_sections); \
if (hashctx) \
cl_hash_destroy(hashctx); \
return CL_EFORMAT; \
} \
if (flags & CL_CHECKFP_PE_FLAG_AUTHENTICODE && hashctx) \
cl_update_hash(hashctx, (void *)hptr, size); \
if (isStatAble && flags & CL_CHECKFP_PE_FLAG_STATS) { \
void *md5ctx; \
md5ctx = cl_hash_init("md5"); \
if (md5ctx) { \
cl_update_hash(md5ctx, (void *)hptr, size); \
cl_finish_hash(md5ctx, hashes->sections[section].md5); \
} \
} \
} while(0)
while (flags & CL_CHECKFP_PE_FLAG_AUTHENTICODE) {
/* MZ to checksum */
at = 0;
hlen = e_lfanew + sizeof(struct pe_image_file_hdr) + (pe_plus ? offsetof(struct pe_image_optional_hdr64, CheckSum) : offsetof(struct pe_image_optional_hdr32, CheckSum));
hash_chunk(0, hlen, 0, 0);
at = hlen + 4;
/* Checksum to security */
if(pe_plus)
hlen = offsetof(struct pe_image_optional_hdr64, DataDirectory[4]) - offsetof(struct pe_image_optional_hdr64, CheckSum) - 4;
else
hlen = offsetof(struct pe_image_optional_hdr32, DataDirectory[4]) - offsetof(struct pe_image_optional_hdr32, CheckSum) - 4;
hash_chunk(at, hlen, 0, 0);
at += hlen + 8;
if(at > hdr_size) {
if (flags & CL_CHECKFP_PE_FLAG_STATS) {
flags ^= CL_CHECKFP_PE_FLAG_AUTHENTICODE;
break;
} else {
free(exe_sections);
if (hashctx)
cl_hash_destroy(hashctx);
return CL_EFORMAT;
}
}
/* Security to End of header */
hlen = hdr_size - at;
hash_chunk(at, hlen, 0, 0);
at = hdr_size;
break;
}
/* Hash the sections */
for(i = 0; i < nsections; i++) {
if(!exe_sections[i].rsz)
continue;
hash_chunk(exe_sections[i].raw, exe_sections[i].rsz, 1, i);
if (flags & CL_CHECKFP_PE_FLAG_AUTHENTICODE)
at += exe_sections[i].rsz;
}
while (flags & CL_CHECKFP_PE_FLAG_AUTHENTICODE) {
if((size_t)at < fsize) {
hlen = fsize - at;
if(dirs[4].Size > hlen) {
if (flags & CL_CHECKFP_PE_FLAG_STATS) {
flags ^= CL_CHECKFP_PE_FLAG_AUTHENTICODE;
break;
} else {
free(exe_sections);
if (hashctx)
cl_hash_destroy(hashctx);
return CL_EFORMAT;
}
}
hlen -= dirs[4].Size;
hash_chunk(at, hlen, 0, 0);
at += hlen;
}
break;
} while (0);
free(exe_sections);
if (flags & CL_CHECKFP_PE_FLAG_AUTHENTICODE && hashctx) {
cl_finish_hash(hashctx, authsha1);
if(cli_debug_flag) {
char shatxt[SHA1_HASH_SIZE*2+1];
for(i=0; i<SHA1_HASH_SIZE; i++)
sprintf(&shatxt[i*2], "%02x", authsha1[i]);
cli_dbgmsg("Authenticode: %s\n", shatxt);
}
hlen = dirs[4].Size;
if(hlen < 8)
return CL_VIRUS;
hlen -= 8;
return asn1_check_mscat((struct cl_engine *)(ctx->engine), map, at + 8, hlen, authsha1);
} else {
if (hashctx)
cl_hash_destroy(hashctx);
return CL_VIRUS;
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2346_0 |
crossvul-cpp_data_bad_4785_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT IIIII FFFFF FFFFF %
% T I F F %
% T I FFF FFF %
% T I F F %
% T IIIII F F %
% %
% %
% Read/Write TIFF Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/constitute.h"
#include "magick/draw.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/geometry.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/pixel-private.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantum.h"
#include "magick/quantum-private.h"
#include "magick/resize.h"
#include "magick/resource_.h"
#include "magick/semaphore.h"
#include "magick/splay-tree.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/thread_.h"
#include "magick/token.h"
#include "magick/utility.h"
#if defined(MAGICKCORE_TIFF_DELEGATE)
# if defined(MAGICKCORE_HAVE_TIFFCONF_H)
# include "tiffconf.h"
# endif
# include "tiff.h"
# include "tiffio.h"
# if !defined(COMPRESSION_ADOBE_DEFLATE)
# define COMPRESSION_ADOBE_DEFLATE 8
# endif
# if !defined(PREDICTOR_HORIZONTAL)
# define PREDICTOR_HORIZONTAL 2
# endif
# if !defined(TIFFTAG_COPYRIGHT)
# define TIFFTAG_COPYRIGHT 33432
# endif
# if !defined(TIFFTAG_OPIIMAGEID)
# define TIFFTAG_OPIIMAGEID 32781
# endif
#include "psd-private.h"
/*
Typedef declarations.
*/
typedef enum
{
ReadSingleSampleMethod,
ReadRGBAMethod,
ReadCMYKAMethod,
ReadYCCKMethod,
ReadStripMethod,
ReadTileMethod,
ReadGenericMethod
} TIFFMethodType;
#if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
typedef struct _ExifInfo
{
unsigned int
tag,
type,
variable_length;
const char
*property;
} ExifInfo;
static const ExifInfo
exif_info[] = {
{ EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, 0, "exif:ExposureTime" },
{ EXIFTAG_FNUMBER, TIFF_RATIONAL, 0, "exif:FNumber" },
{ EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, 0, "exif:ExposureProgram" },
{ EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, 0, "exif:SpectralSensitivity" },
{ EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, 1, "exif:ISOSpeedRatings" },
{ EXIFTAG_OECF, TIFF_NOTYPE, 0, "exif:OptoelectricConversionFactor" },
{ EXIFTAG_EXIFVERSION, TIFF_NOTYPE, 0, "exif:ExifVersion" },
{ EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, 0, "exif:DateTimeOriginal" },
{ EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, 0, "exif:DateTimeDigitized" },
{ EXIFTAG_COMPONENTSCONFIGURATION, TIFF_NOTYPE, 0, "exif:ComponentsConfiguration" },
{ EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, 0, "exif:CompressedBitsPerPixel" },
{ EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, 0, "exif:ShutterSpeedValue" },
{ EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, 0, "exif:ApertureValue" },
{ EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, 0, "exif:BrightnessValue" },
{ EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, 0, "exif:ExposureBiasValue" },
{ EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, 0, "exif:MaxApertureValue" },
{ EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, 0, "exif:SubjectDistance" },
{ EXIFTAG_METERINGMODE, TIFF_SHORT, 0, "exif:MeteringMode" },
{ EXIFTAG_LIGHTSOURCE, TIFF_SHORT, 0, "exif:LightSource" },
{ EXIFTAG_FLASH, TIFF_SHORT, 0, "exif:Flash" },
{ EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, 0, "exif:FocalLength" },
{ EXIFTAG_SUBJECTAREA, TIFF_NOTYPE, 0, "exif:SubjectArea" },
{ EXIFTAG_MAKERNOTE, TIFF_NOTYPE, 0, "exif:MakerNote" },
{ EXIFTAG_USERCOMMENT, TIFF_NOTYPE, 0, "exif:UserComment" },
{ EXIFTAG_SUBSECTIME, TIFF_ASCII, 0, "exif:SubSecTime" },
{ EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, 0, "exif:SubSecTimeOriginal" },
{ EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, 0, "exif:SubSecTimeDigitized" },
{ EXIFTAG_FLASHPIXVERSION, TIFF_NOTYPE, 0, "exif:FlashpixVersion" },
{ EXIFTAG_PIXELXDIMENSION, TIFF_LONG, 0, "exif:PixelXDimension" },
{ EXIFTAG_PIXELYDIMENSION, TIFF_LONG, 0, "exif:PixelYDimension" },
{ EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, 0, "exif:RelatedSoundFile" },
{ EXIFTAG_FLASHENERGY, TIFF_RATIONAL, 0, "exif:FlashEnergy" },
{ EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, 0, "exif:SpatialFrequencyResponse" },
{ EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneXResolution" },
{ EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneYResolution" },
{ EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, 0, "exif:FocalPlaneResolutionUnit" },
{ EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, 0, "exif:SubjectLocation" },
{ EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, 0, "exif:ExposureIndex" },
{ EXIFTAG_SENSINGMETHOD, TIFF_SHORT, 0, "exif:SensingMethod" },
{ EXIFTAG_FILESOURCE, TIFF_NOTYPE, 0, "exif:FileSource" },
{ EXIFTAG_SCENETYPE, TIFF_NOTYPE, 0, "exif:SceneType" },
{ EXIFTAG_CFAPATTERN, TIFF_NOTYPE, 0, "exif:CFAPattern" },
{ EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, 0, "exif:CustomRendered" },
{ EXIFTAG_EXPOSUREMODE, TIFF_SHORT, 0, "exif:ExposureMode" },
{ EXIFTAG_WHITEBALANCE, TIFF_SHORT, 0, "exif:WhiteBalance" },
{ EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, 0, "exif:DigitalZoomRatio" },
{ EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, 0, "exif:FocalLengthIn35mmFilm" },
{ EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, 0, "exif:SceneCaptureType" },
{ EXIFTAG_GAINCONTROL, TIFF_RATIONAL, 0, "exif:GainControl" },
{ EXIFTAG_CONTRAST, TIFF_SHORT, 0, "exif:Contrast" },
{ EXIFTAG_SATURATION, TIFF_SHORT, 0, "exif:Saturation" },
{ EXIFTAG_SHARPNESS, TIFF_SHORT, 0, "exif:Sharpness" },
{ EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, 0, "exif:DeviceSettingDescription" },
{ EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, 0, "exif:SubjectDistanceRange" },
{ EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, 0, "exif:ImageUniqueID" },
{ 0, 0, 0, (char *) NULL }
};
#endif
#endif /* MAGICKCORE_TIFF_DELEGATE */
/*
Global declarations.
*/
static MagickThreadKey
tiff_exception;
static SemaphoreInfo
*tiff_semaphore = (SemaphoreInfo *) NULL;
static TIFFErrorHandler
error_handler,
warning_handler;
static volatile MagickBooleanType
instantiate_key = MagickFalse;
/*
Forward declarations.
*/
#if defined(MAGICKCORE_TIFF_DELEGATE)
static Image *
ReadTIFFImage(const ImageInfo *,ExceptionInfo *);
static MagickBooleanType
WriteGROUP4Image(const ImageInfo *,Image *),
WritePTIFImage(const ImageInfo *,Image *),
WriteTIFFImage(const ImageInfo *,Image *);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s T I F F %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsTIFF() returns MagickTrue if the image format type, identified by the
% magick string, is TIFF.
%
% The format of the IsTIFF method is:
%
% MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\115\115\000\052",4) == 0)
return(MagickTrue);
if (memcmp(magick,"\111\111\052\000",4) == 0)
return(MagickTrue);
#if defined(TIFF_VERSION_BIG)
if (length < 8)
return(MagickFalse);
if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0)
return(MagickTrue);
if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0)
return(MagickTrue);
#endif
return(MagickFalse);
}
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d G R O U P 4 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadGROUP4Image() reads a raw CCITT Group 4 image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadGROUP4Image method is:
%
% Image *ReadGROUP4Image(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline size_t WriteLSBLong(FILE *file,const size_t value)
{
unsigned char
buffer[4];
buffer[0]=(unsigned char) value;
buffer[1]=(unsigned char) (value >> 8);
buffer[2]=(unsigned char) (value >> 16);
buffer[3]=(unsigned char) (value >> 24);
return(fwrite(buffer,1,4,file));
}
static Image *ReadGROUP4Image(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
filename[MaxTextExtent];
FILE
*file;
Image
*image;
ImageInfo
*read_info;
int
c,
unique_file;
MagickBooleanType
status;
size_t
length;
ssize_t
offset,
strip_offset;
/*
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);
}
/*
Write raw CCITT Group 4 wrapped as a TIFF image file.
*/
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file);
length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file);
length=fwrite("\000\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->columns);
length=fwrite("\001\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->rows);
length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file);
length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file);
length=fwrite("\021\001\003\000\001\000\000\000",1,8,file);
strip_offset=10+(12*14)+4+8;
length=WriteLSBLong(file,(size_t) strip_offset);
length=fwrite("\022\001\003\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) image_info->orientation);
length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
length=fwrite("\026\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->rows);
length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file);
offset=(ssize_t) ftell(file)-4;
length=fwrite("\032\001\005\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) (strip_offset-8));
length=fwrite("\033\001\005\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) (strip_offset-8));
length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file);
length=fwrite("\000\000\000\000",1,4,file);
length=WriteLSBLong(file,(size_t) (image->x_resolution+0.5));
length=WriteLSBLong(file,1);
status=MagickTrue;
for (length=0; (c=ReadBlobByte(image)) != EOF; length++)
if (fputc(c,file) != c)
status=MagickFalse;
offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET);
length=WriteLSBLong(file,(unsigned int) length);
(void) fclose(file);
(void) CloseBlob(image);
image=DestroyImage(image);
/*
Read TIFF image.
*/
read_info=CloneImageInfo((ImageInfo *) NULL);
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"%s",filename);
image=ReadTIFFImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
if (image != (Image *) NULL)
{
(void) CopyMagickString(image->filename,image_info->filename,
MaxTextExtent);
(void) CopyMagickString(image->magick_filename,image_info->filename,
MaxTextExtent);
(void) CopyMagickString(image->magick,"GROUP4",MaxTextExtent);
}
(void) RelinquishUniqueFileResource(filename);
if (status == MagickFalse)
image=DestroyImage(image);
return(image);
}
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadTIFFImage() reads a Tagged image file and returns it. It allocates the
% memory necessary for the new Image structure and returns a pointer to the
% new image.
%
% The format of the ReadTIFFImage method is:
%
% Image *ReadTIFFImage(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline unsigned char ClampYCC(double value)
{
value=255.0-value;
if (value < 0.0)
return((unsigned char)0);
if (value > 255.0)
return((unsigned char)255);
return((unsigned char)(value));
}
static MagickBooleanType DecodeLabImage(Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
a,
b;
a=QuantumScale*GetPixela(q)+0.5;
if (a > 1.0)
a-=1.0;
b=QuantumScale*GetPixelb(q)+0.5;
if (b > 1.0)
b-=1.0;
SetPixela(q,QuantumRange*a);
SetPixelb(q,QuantumRange*b);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
static MagickBooleanType ReadProfile(Image *image,const char *name,
const unsigned char *datum,ssize_t length)
{
MagickBooleanType
status;
StringInfo
*profile;
if (length < 4)
return(MagickFalse);
profile=BlobToStringInfo(datum,(size_t) length);
if (profile == (StringInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=SetImageProfile(image,name,profile);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
return(MagickTrue);
}
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int TIFFCloseBlob(thandle_t image)
{
(void) CloseBlob((Image *) image);
return(0);
}
static void TIFFErrors(const char *module,const char *format,va_list error)
{
char
message[MaxTextExtent];
ExceptionInfo
*exception;
#if defined(MAGICKCORE_HAVE_VSNPRINTF)
(void) vsnprintf(message,MaxTextExtent,format,error);
#else
(void) vsprintf(message,format,error);
#endif
(void) ConcatenateMagickString(message,".",MaxTextExtent);
exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception);
if (exception != (ExceptionInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,message,
"`%s'",module);
}
static toff_t TIFFGetBlobSize(thandle_t image)
{
return((toff_t) GetBlobSize((Image *) image));
}
static void TIFFGetProfiles(TIFF *tiff,Image *image,MagickBooleanType ping)
{
uint32
length;
unsigned char
*profile;
length=0;
if (ping == MagickFalse)
{
#if defined(TIFFTAG_ICCPROFILE)
if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"icc",profile,(ssize_t) length);
#endif
#if defined(TIFFTAG_PHOTOSHOP)
if ((TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"8bim",profile,(ssize_t) length);
#endif
#if defined(TIFFTAG_RICHTIFFIPTC)
if ((TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
{
if (TIFFIsByteSwapped(tiff) != 0)
TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length);
(void) ReadProfile(image,"iptc",profile,4L*length);
}
#endif
#if defined(TIFFTAG_XMLPACKET)
if ((TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"xmp",profile,(ssize_t) length);
#endif
if ((TIFFGetField(tiff,34118,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length);
}
if ((TIFFGetField(tiff,37724,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length);
}
static void TIFFGetProperties(TIFF *tiff,Image *image)
{
char
message[MaxTextExtent],
*text;
uint32
count,
length,
type;
unsigned long
*tietz;
if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1)
(void) SetImageProperty(image,"tiff:artist",text);
if (TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1)
(void) SetImageProperty(image,"tiff:copyright",text);
if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1)
(void) SetImageProperty(image,"tiff:timestamp",text);
if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1)
(void) SetImageProperty(image,"tiff:document",text);
if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1)
(void) SetImageProperty(image,"tiff:hostcomputer",text);
if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1)
(void) SetImageProperty(image,"comment",text);
if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1)
(void) SetImageProperty(image,"tiff:make",text);
if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1)
(void) SetImageProperty(image,"tiff:model",text);
if (TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1)
{
if (count >= MaxTextExtent)
count=MaxTextExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:image-id",message);
}
if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1)
(void) SetImageProperty(image,"label",text);
if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1)
(void) SetImageProperty(image,"tiff:software",text);
if (TIFFGetField(tiff,33423,&count,&text) == 1)
{
if (count >= MaxTextExtent)
count=MaxTextExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:kodak-33423",message);
}
if (TIFFGetField(tiff,36867,&count,&text) == 1)
{
if (count >= MaxTextExtent)
count=MaxTextExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:kodak-36867",message);
}
if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1)
switch (type)
{
case 0x01:
{
(void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE");
break;
}
case 0x02:
{
(void) SetImageProperty(image,"tiff:subfiletype","PAGE");
break;
}
case 0x04:
{
(void) SetImageProperty(image,"tiff:subfiletype","MASK");
break;
}
default:
break;
}
if (TIFFGetField(tiff,37706,&length,&tietz) == 1)
{
(void) FormatLocaleString(message,MaxTextExtent,"%lu",tietz[0]);
(void) SetImageProperty(image,"tiff:tietz_offset",message);
}
}
static void TIFFGetEXIFProperties(TIFF *tiff,Image *image)
{
#if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
char
value[MaxTextExtent];
register ssize_t
i;
tdir_t
directory;
#if defined(TIFF_VERSION_BIG)
uint64
#else
uint32
#endif
offset;
void
*sans;
/*
Read EXIF properties.
*/
offset=0;
if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) != 1)
return;
directory=TIFFCurrentDirectory(tiff);
if (TIFFReadEXIFDirectory(tiff,offset) != 1)
{
TIFFSetDirectory(tiff,directory);
return;
}
sans=NULL;
for (i=0; exif_info[i].tag != 0; i++)
{
*value='\0';
switch (exif_info[i].type)
{
case TIFF_ASCII:
{
char
*ascii;
ascii=(char *) NULL;
if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,&sans,&sans) == 1) &&
(ascii != (char *) NULL) && (*ascii != '\0'))
(void) CopyMagickString(value,ascii,MaxTextExtent);
break;
}
case TIFF_SHORT:
{
if (exif_info[i].variable_length == 0)
{
uint16
shorty;
shorty=0;
if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans,&sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%d",shorty);
}
else
{
int
tiff_status;
uint16
*shorty;
uint16
shorty_num;
tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty,
&sans,&sans);
if (tiff_status == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%d",
shorty_num != 0 ? shorty[0] : 0);
}
break;
}
case TIFF_LONG:
{
uint32
longy;
longy=0;
if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%d",longy);
break;
}
#if defined(TIFF_VERSION_BIG)
case TIFF_LONG8:
{
uint64
long8y;
long8y=0;
if (TIFFGetField(tiff,exif_info[i].tag,&long8y,&sans,&sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
((MagickOffsetType) long8y));
break;
}
#endif
case TIFF_RATIONAL:
case TIFF_SRATIONAL:
case TIFF_FLOAT:
{
float
floaty;
floaty=0.0;
if (TIFFGetField(tiff,exif_info[i].tag,&floaty,&sans,&sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%g",(double) floaty);
break;
}
case TIFF_DOUBLE:
{
double
doubley;
doubley=0.0;
if (TIFFGetField(tiff,exif_info[i].tag,&doubley,&sans,&sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%g",doubley);
break;
}
default:
break;
}
if (*value != '\0')
(void) SetImageProperty(image,exif_info[i].property,value);
}
TIFFSetDirectory(tiff,directory);
#else
(void) tiff;
(void) image;
#endif
}
static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size)
{
*base=(tdata_t *) GetBlobStreamData((Image *) image);
if (*base != (tdata_t *) NULL)
*size=(toff_t) GetBlobSize((Image *) image);
if (*base != (tdata_t *) NULL)
return(1);
return(0);
}
static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size)
{
tsize_t
count;
count=(tsize_t) ReadBlob((Image *) image,(size_t) size,
(unsigned char *) data);
return(count);
}
static int32 TIFFReadPixels(TIFF *tiff,size_t bits_per_sample,
tsample_t sample,ssize_t row,tdata_t scanline)
{
int32
status;
(void) bits_per_sample;
status=TIFFReadScanline(tiff,scanline,(uint32) row,sample);
return(status);
}
static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence)
{
return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence));
}
static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size)
{
(void) image;
(void) base;
(void) size;
}
static void TIFFWarnings(const char *module,const char *format,va_list warning)
{
char
message[MaxTextExtent];
ExceptionInfo
*exception;
#if defined(MAGICKCORE_HAVE_VSNPRINTF)
(void) vsnprintf(message,MaxTextExtent,format,warning);
#else
(void) vsprintf(message,format,warning);
#endif
(void) ConcatenateMagickString(message,".",MaxTextExtent);
exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception);
if (exception != (ExceptionInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
message,"`%s'",module);
}
static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size)
{
tsize_t
count;
count=(tsize_t) WriteBlob((Image *) image,(size_t) size,
(unsigned char *) data);
return(count);
}
static TIFFMethodType GetJPEGMethod(Image* image,TIFF *tiff,uint16 photometric,
uint16 bits_per_sample,uint16 samples_per_pixel)
{
#define BUFFER_SIZE 2048
MagickOffsetType
position,
offset;
register size_t
i;
TIFFMethodType
method;
#if defined(TIFF_VERSION_BIG)
uint64
#else
uint32
#endif
**value;
unsigned char
buffer[BUFFER_SIZE+32];
unsigned short
length;
/* only support 8 bit for now */
if ((photometric != PHOTOMETRIC_SEPARATED) || (bits_per_sample != 8) ||
(samples_per_pixel != 4))
return(ReadGenericMethod);
/* Search for Adobe APP14 JPEG Marker */
if (!TIFFGetField(tiff,TIFFTAG_STRIPOFFSETS,&value))
return(ReadRGBAMethod);
position=TellBlob(image);
offset=(MagickOffsetType) (value[0]);
if (SeekBlob(image,offset,SEEK_SET) != offset)
return(ReadRGBAMethod);
method=ReadRGBAMethod;
if (ReadBlob(image,BUFFER_SIZE,buffer) == BUFFER_SIZE)
{
for (i=0; i < BUFFER_SIZE; i++)
{
while (i < BUFFER_SIZE)
{
if (buffer[i++] == 255)
break;
}
while (i < BUFFER_SIZE)
{
if (buffer[++i] != 255)
break;
}
if (buffer[i++] == 216) /* JPEG_MARKER_SOI */
continue;
length=(unsigned short) (((unsigned int) (buffer[i] << 8) |
(unsigned int) buffer[i+1]) & 0xffff);
if (i+(size_t) length >= BUFFER_SIZE)
break;
if (buffer[i-1] == 238) /* JPEG_MARKER_APP0+14 */
{
if (length != 14)
break;
/* 0 == CMYK, 1 == YCbCr, 2 = YCCK */
if (buffer[i+13] == 2)
method=ReadYCCKMethod;
break;
}
i+=(size_t) length;
}
}
(void) SeekBlob(image,position,SEEK_SET);
return(method);
}
static void TIFFReadPhotoshopLayers(Image* image,const ImageInfo *image_info,
ExceptionInfo *exception)
{
const char
*option;
const StringInfo
*layer_info;
Image
*layers;
PSDInfo
info;
register ssize_t
i;
if (GetImageListLength(image) != 1)
return;
if ((image_info->number_scenes == 1) && (image_info->scene == 0))
return;
option=GetImageOption(image_info,"tiff:ignore-layers");
if (option != (const char * ) NULL)
return;
layer_info=GetImageProfile(image,"tiff:37724");
if (layer_info == (const StringInfo *) NULL)
return;
for (i=0; i < (ssize_t) layer_info->length-8; i++)
{
if (LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "8BIM" : "MIB8",4) != 0)
continue;
i+=4;
if ((LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "Layr" : "ryaL",4) == 0) ||
(LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "LMsk" : "ksML",4) == 0) ||
(LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "Lr16" : "61rL",4) == 0) ||
(LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "Lr32" : "23rL",4) == 0))
break;
}
i+=4;
if (i >= (ssize_t) (layer_info->length-8))
return;
layers=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
(void) DeleteImageProfile(layers,"tiff:37724");
AttachBlob(layers->blob,layer_info->datum,layer_info->length);
SeekBlob(layers,(MagickOffsetType) i,SEEK_SET);
info.version=1;
info.columns=layers->columns;
info.rows=layers->rows;
/* Setting the mode to a value that won't change the colorspace */
info.mode=10;
if (IsGrayImage(image,&image->exception) != MagickFalse)
info.channels=(image->matte != MagickFalse ? 2UL : 1UL);
else
if (image->storage_class == PseudoClass)
info.channels=(image->matte != MagickFalse ? 2UL : 1UL);
else
{
if (image->colorspace != CMYKColorspace)
info.channels=(image->matte != MagickFalse ? 4UL : 3UL);
else
info.channels=(image->matte != MagickFalse ? 5UL : 4UL);
}
(void) ReadPSDLayers(layers,image_info,&info,MagickFalse,exception);
InheritException(exception,&layers->exception);
DeleteImageFromList(&layers);
if (layers != (Image *) NULL)
{
SetImageArtifact(image,"tiff:has-layers","true");
AppendImageToList(&image,layers);
while (layers != (Image *) NULL)
{
SetImageArtifact(layers,"tiff:has-layers","true");
DetachBlob(layers->blob);
layers=GetNextImageInList(layers);
}
}
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static Image *ReadTIFFImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
const char
*option;
float
*chromaticity,
x_position,
y_position,
x_resolution,
y_resolution;
Image
*image;
int
tiff_status;
MagickBooleanType
status;
MagickSizeType
number_pixels;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
pad;
ssize_t
y;
TIFF
*tiff;
TIFFMethodType
method;
uint16
compress_tag,
bits_per_sample,
endian,
extra_samples,
interlace,
max_sample_value,
min_sample_value,
orientation,
pages,
photometric,
*sample_info,
sample_format,
samples_per_pixel,
units,
value;
uint32
height,
rows_per_strip,
width;
unsigned char
*pixels;
/*
Open image.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) SetMagickThreadValue(tiff_exception,exception);
tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob,
TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
TIFFUnmapBlob);
if (tiff == (TIFF *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (image_info->number_scenes != 0)
{
/*
Generate blank images for subimage specification (e.g. image.tif[4].
We need to check the number of directores because it is possible that
the subimage(s) are stored in the photoshop profile.
*/
if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff))
{
for (i=0; i < (ssize_t) image_info->scene; i++)
{
status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
if (status == MagickFalse)
{
TIFFClose(tiff);
image=DestroyImageList(image);
return((Image *) NULL);
}
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
TIFFClose(tiff);
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
}
}
}
do
{
DisableMSCWarning(4127)
if (0 && (image_info->verbose != MagickFalse))
TIFFPrintDirectory(tiff,stdout,MagickFalse);
RestoreMSCWarning
if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) ||
(TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1))
{
TIFFClose(tiff);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (sample_format == SAMPLEFORMAT_IEEEFP)
(void) SetImageProperty(image,"quantum:format","floating-point");
switch (photometric)
{
case PHOTOMETRIC_MINISBLACK:
{
(void) SetImageProperty(image,"tiff:photometric","min-is-black");
break;
}
case PHOTOMETRIC_MINISWHITE:
{
(void) SetImageProperty(image,"tiff:photometric","min-is-white");
break;
}
case PHOTOMETRIC_PALETTE:
{
(void) SetImageProperty(image,"tiff:photometric","palette");
break;
}
case PHOTOMETRIC_RGB:
{
(void) SetImageProperty(image,"tiff:photometric","RGB");
break;
}
case PHOTOMETRIC_CIELAB:
{
(void) SetImageProperty(image,"tiff:photometric","CIELAB");
break;
}
case PHOTOMETRIC_LOGL:
{
(void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)");
break;
}
case PHOTOMETRIC_LOGLUV:
{
(void) SetImageProperty(image,"tiff:photometric","LOGLUV");
break;
}
#if defined(PHOTOMETRIC_MASK)
case PHOTOMETRIC_MASK:
{
(void) SetImageProperty(image,"tiff:photometric","MASK");
break;
}
#endif
case PHOTOMETRIC_SEPARATED:
{
(void) SetImageProperty(image,"tiff:photometric","separated");
break;
}
case PHOTOMETRIC_YCBCR:
{
(void) SetImageProperty(image,"tiff:photometric","YCBCR");
break;
}
default:
{
(void) SetImageProperty(image,"tiff:photometric","unknown");
break;
}
}
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u",
(unsigned int) width,(unsigned int) height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u",
interlace);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Bits per sample: %u",bits_per_sample);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Min sample value: %u",min_sample_value);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Max sample value: %u",max_sample_value);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric "
"interpretation: %s",GetImageProperty(image,"tiff:photometric"));
}
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=(size_t) bits_per_sample;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g",
(double) image->depth);
image->endian=MSBEndian;
if (endian == FILLORDER_LSB2MSB)
image->endian=LSBEndian;
#if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)
if (TIFFIsBigEndian(tiff) == 0)
{
(void) SetImageProperty(image,"tiff:endian","lsb");
image->endian=LSBEndian;
}
else
{
(void) SetImageProperty(image,"tiff:endian","msb");
image->endian=MSBEndian;
}
#endif
if ((photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
SetImageColorspace(image,GRAYColorspace);
if (photometric == PHOTOMETRIC_SEPARATED)
SetImageColorspace(image,CMYKColorspace);
if (photometric == PHOTOMETRIC_CIELAB)
SetImageColorspace(image,LabColorspace);
TIFFGetProfiles(tiff,image,image_info->ping);
TIFFGetProperties(tiff,image);
option=GetImageOption(image_info,"tiff:exif-properties");
if ((option == (const char *) NULL) ||
(IsMagickTrue(option) != MagickFalse))
TIFFGetEXIFProperties(tiff,image);
if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) &&
(TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1))
{
image->x_resolution=x_resolution;
image->y_resolution=y_resolution;
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1)
{
if (units == RESUNIT_INCH)
image->units=PixelsPerInchResolution;
if (units == RESUNIT_CENTIMETER)
image->units=PixelsPerCentimeterResolution;
}
if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) &&
(TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1))
{
image->page.x=(ssize_t) ceil(x_position*image->x_resolution-0.5);
image->page.y=(ssize_t) ceil(y_position*image->y_resolution-0.5);
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1)
image->orientation=(OrientationType) orientation;
if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1)
{
if (chromaticity != (float *) NULL)
{
image->chromaticity.white_point.x=chromaticity[0];
image->chromaticity.white_point.y=chromaticity[1];
}
}
if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1)
{
if (chromaticity != (float *) NULL)
{
image->chromaticity.red_primary.x=chromaticity[0];
image->chromaticity.red_primary.y=chromaticity[1];
image->chromaticity.green_primary.x=chromaticity[2];
image->chromaticity.green_primary.y=chromaticity[3];
image->chromaticity.blue_primary.x=chromaticity[4];
image->chromaticity.blue_primary.y=chromaticity[5];
}
}
#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
if ((compress_tag != COMPRESSION_NONE) &&
(TIFFIsCODECConfigured(compress_tag) == 0))
{
TIFFClose(tiff);
ThrowReaderException(CoderError,"CompressNotSupported");
}
#endif
switch (compress_tag)
{
case COMPRESSION_NONE: image->compression=NoCompression; break;
case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;
case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;
case COMPRESSION_JPEG:
{
image->compression=JPEGCompression;
#if defined(JPEG_SUPPORT)
{
char
sampling_factor[MaxTextExtent];
int
tiff_status;
uint16
horizontal,
vertical;
tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING,
&horizontal,&vertical);
if (tiff_status == 1)
{
(void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d",
horizontal,vertical);
(void) SetImageProperty(image,"jpeg:sampling-factor",
sampling_factor);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling Factors: %s",sampling_factor);
}
}
#endif
break;
}
case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;
#if defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA: image->compression=LZMACompression; break;
#endif
case COMPRESSION_LZW: image->compression=LZWCompression; break;
case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;
case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;
default: image->compression=RLECompression; break;
}
/*
Allocate memory for the image and pixel buffer.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
if (sample_format == SAMPLEFORMAT_UINT)
status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);
if (sample_format == SAMPLEFORMAT_INT)
status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);
if (sample_format == SAMPLEFORMAT_IEEEFP)
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
{
TIFFClose(tiff);
quantum_info=DestroyQuantumInfo(quantum_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
status=MagickTrue;
switch (photometric)
{
case PHOTOMETRIC_MINISBLACK:
{
quantum_info->min_is_white=MagickFalse;
break;
}
case PHOTOMETRIC_MINISWHITE:
{
quantum_info->min_is_white=MagickTrue;
break;
}
default:
break;
}
tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,
&sample_info);
if (tiff_status == 1)
{
(void) SetImageProperty(image,"tiff:alpha","unspecified");
if (extra_samples == 0)
{
if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))
image->matte=MagickTrue;
}
else
for (i=0; i < extra_samples; i++)
{
image->matte=MagickTrue;
if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)
{
SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);
(void) SetImageProperty(image,"tiff:alpha","associated");
}
else
if (sample_info[i] == EXTRASAMPLE_UNASSALPHA)
(void) SetImageProperty(image,"tiff:alpha","unassociated");
}
}
if ((photometric == PHOTOMETRIC_PALETTE) &&
(pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))
{
size_t
colors;
colors=(size_t) GetQuantumRange(bits_per_sample)+1;
if (AcquireImageColormap(image,colors) == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1)
image->scene=value;
if (image->storage_class == PseudoClass)
{
int
tiff_status;
size_t
range;
uint16
*blue_colormap,
*green_colormap,
*red_colormap;
/*
Initialize colormap.
*/
tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,
&green_colormap,&blue_colormap);
if (tiff_status == 1)
{
if ((red_colormap != (uint16 *) NULL) &&
(green_colormap != (uint16 *) NULL) &&
(blue_colormap != (uint16 *) NULL))
{
range=255; /* might be old style 8-bit colormap */
for (i=0; i < (ssize_t) image->colors; i++)
if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||
(blue_colormap[i] >= 256))
{
range=65535;
break;
}
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ClampToQuantum(((double)
QuantumRange*red_colormap[i])/range);
image->colormap[i].green=ClampToQuantum(((double)
QuantumRange*green_colormap[i])/range);
image->colormap[i].blue=ClampToQuantum(((double)
QuantumRange*blue_colormap[i])/range);
}
}
}
if (image->matte == MagickFalse)
image->depth=GetImageDepth(image,exception);
}
if (image_info->ping != MagickFalse)
{
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
{
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
goto next_tiff_frame;
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
method=ReadGenericMethod;
if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1)
{
char
value[MaxTextExtent];
method=ReadStripMethod;
(void) FormatLocaleString(value,MaxTextExtent,"%u",(unsigned int)
rows_per_strip);
(void) SetImageProperty(image,"tiff:rows-per-strip",value);
}
if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG))
method=ReadRGBAMethod;
if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE))
method=ReadCMYKAMethod;
if ((photometric != PHOTOMETRIC_RGB) &&
(photometric != PHOTOMETRIC_CIELAB) &&
(photometric != PHOTOMETRIC_SEPARATED))
method=ReadGenericMethod;
if (image->storage_class == PseudoClass)
method=ReadSingleSampleMethod;
if ((photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
method=ReadSingleSampleMethod;
if ((photometric != PHOTOMETRIC_SEPARATED) &&
(interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64))
method=ReadGenericMethod;
if (image->compression == JPEGCompression)
method=GetJPEGMethod(image,tiff,photometric,bits_per_sample,
samples_per_pixel);
if (compress_tag == COMPRESSION_JBIG)
method=ReadStripMethod;
if (TIFFIsTiled(tiff) != MagickFalse)
method=ReadTileMethod;
quantum_info->endian=LSBEndian;
quantum_type=RGBQuantum;
pixels=GetQuantumPixels(quantum_info);
switch (method)
{
case ReadSingleSampleMethod:
{
/*
Convert TIFF image to PseudoClass MIFF image.
*/
quantum_type=IndexQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
if (image->matte != MagickFalse)
{
if (image->storage_class != PseudoClass)
{
quantum_type=samples_per_pixel == 1 ? AlphaQuantum :
GrayAlphaQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
}
else
{
quantum_type=IndexAlphaQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
}
}
else
if (image->storage_class != PseudoClass)
{
quantum_type=GrayQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
}
status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
if (status == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register PixelPacket
*magick_restrict q;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadRGBAMethod:
{
/*
Convert TIFF image to DirectClass MIFF image.
*/
pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
{
quantum_type=RGBAQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
}
if (image->colorspace == CMYKColorspace)
{
pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
quantum_type=CMYKQuantum;
if (image->matte != MagickFalse)
{
quantum_type=CMYKAQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);
}
}
status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
if (status == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register PixelPacket
*magick_restrict q;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadCMYKAMethod:
{
/*
Convert TIFF image to DirectClass MIFF image.
*/
for (i=0; i < (ssize_t) samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
int
status;
status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *)
pixels);
if (status == -1)
break;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
if (image->colorspace != CMYKColorspace)
switch (i)
{
case 0: quantum_type=RedQuantum; break;
case 1: quantum_type=GreenQuantum; break;
case 2: quantum_type=BlueQuantum; break;
case 3: quantum_type=AlphaQuantum; break;
default: quantum_type=UndefinedQuantum; break;
}
else
switch (i)
{
case 0: quantum_type=CyanQuantum; break;
case 1: quantum_type=MagentaQuantum; break;
case 2: quantum_type=YellowQuantum; break;
case 3: quantum_type=BlackQuantum; break;
case 4: quantum_type=AlphaQuantum; break;
default: quantum_type=UndefinedQuantum; break;
}
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadYCCKMethod:
{
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register IndexPacket
*indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
unsigned char
*p;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
p=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+
(1.402*(double) *(p+2))-179.456)));
SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p-
(0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+
135.45984)));
SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+
(1.772*(double) *(p+1))-226.816)));
SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3)));
q++;
p+=4;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadStripMethod:
{
register uint32
*p;
/*
Convert stripped TIFF image to DirectClass MIFF image.
*/
i=0;
p=(uint32 *) NULL;
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
if (i == 0)
{
if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0)
break;
i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)
image->rows-y);
}
i--;
p=((uint32 *) pixels)+image->columns*i;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
(TIFFGetR(*p))));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
(TIFFGetG(*p))));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
(TIFFGetB(*p))));
if (image->matte != MagickFalse)
SetPixelOpacity(q,ScaleCharToQuantum((unsigned char)
(TIFFGetA(*p))));
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;
}
}
break;
}
case ReadTileMethod:
{
register uint32
*p;
uint32
*tile_pixels,
columns,
rows;
/*
Convert tiled TIFF image to DirectClass MIFF image.
*/
if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||
(TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))
{
TIFFClose(tiff);
ThrowReaderException(CoderError,"ImageIsNotTiled");
}
(void) SetImageStorageClass(image,DirectClass);
number_pixels=(MagickSizeType) columns*rows;
if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t)
(number_pixels*sizeof(uint32))))
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
tile_pixels=(uint32 *) AcquireQuantumMemory(number_pixels,
sizeof(*tile_pixels));
if (tile_pixels == (uint32 *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (y=0; y < (ssize_t) image->rows; y+=rows)
{
PixelPacket
*tile;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
size_t
columns_remaining,
rows_remaining;
rows_remaining=image->rows-y;
if ((ssize_t) (y+rows) < (ssize_t) image->rows)
rows_remaining=rows;
tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining,
exception);
if (tile == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x+=columns)
{
size_t
column,
row;
if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0)
break;
columns_remaining=image->columns-x;
if ((ssize_t) (x+columns) < (ssize_t) image->columns)
columns_remaining=columns;
p=tile_pixels+(rows-rows_remaining)*columns;
q=tile+(image->columns*(rows_remaining-1)+x);
for (row=rows_remaining; row > 0; row--)
{
if (image->matte != MagickFalse)
for (column=columns_remaining; column > 0; column--)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
TIFFGetR(*p)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
TIFFGetG(*p)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
TIFFGetB(*p)));
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
TIFFGetA(*p)));
q++;
p++;
}
else
for (column=columns_remaining; column > 0; column--)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
TIFFGetR(*p)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
TIFFGetG(*p)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
TIFFGetB(*p)));
q++;
p++;
}
p+=columns-columns_remaining;
q-=(image->columns+columns_remaining);
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels);
break;
}
case ReadGenericMethod:
default:
{
MemoryInfo
*pixel_info;
register uint32
*p;
uint32
*pixels;
/*
Convert TIFF image to DirectClass MIFF image.
*/
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t)
(number_pixels*sizeof(uint32))))
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
sizeof(uint32));
if (pixel_info == (MemoryInfo *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info);
(void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32)
image->rows,(uint32 *) pixels,0);
/*
Convert image to DirectClass pixel packets.
*/
p=pixels+number_pixels-1;
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
q+=image->columns-1;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)));
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)));
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;
}
}
pixel_info=RelinquishVirtualMemory(pixel_info);
break;
}
}
SetQuantumImageType(image,quantum_type);
next_tiff_frame:
quantum_info=DestroyQuantumInfo(quantum_info);
if (photometric == PHOTOMETRIC_CIELAB)
DecodeLabImage(image,exception);
if ((photometric == PHOTOMETRIC_LOGL) ||
(photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
{
image->type=GrayscaleType;
if (bits_per_sample == 1)
image->type=BilevelType;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
if (status != MagickFalse)
{
/*
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,image->scene-1,
image->scene);
if (status == MagickFalse)
break;
}
} while (status != MagickFalse);
TIFFClose(tiff);
TIFFReadPhotoshopLayers(image,image_info,exception);
if (image_info->number_scenes != 0)
{
if (image_info->scene >= GetImageListLength(image))
{
/* Subimage was not found in the Photoshop layer */
image = DestroyImageList(image);
return((Image *)NULL);
}
}
return(GetFirstImageInList(image));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterTIFFImage() adds properties for the TIFF image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterTIFFImage method is:
%
% size_t RegisterTIFFImage(void)
%
*/
#if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
static TIFFExtendProc
tag_extender = (TIFFExtendProc) NULL;
static void TIFFIgnoreTags(TIFF *tiff)
{
char
*q;
const char
*p,
*tags;
Image
*image;
register ssize_t
i;
size_t
count;
TIFFFieldInfo
*ignore;
if (TIFFGetReadProc(tiff) != TIFFReadBlob)
return;
image=(Image *)TIFFClientdata(tiff);
tags=GetImageArtifact(image,"tiff:ignore-tags");
if (tags == (const char *) NULL)
return;
count=0;
p=tags;
while (*p != '\0')
{
while ((isspace((int) ((unsigned char) *p)) != 0))
p++;
(void) strtol(p,&q,10);
if (p == q)
return;
p=q;
count++;
while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
p++;
}
if (count == 0)
return;
i=0;
p=tags;
ignore=(TIFFFieldInfo *) AcquireQuantumMemory(count,sizeof(*ignore));
/* This also sets field_bit to 0 (FIELD_IGNORE) */
ResetMagickMemory(ignore,0,count*sizeof(*ignore));
while (*p != '\0')
{
while ((isspace((int) ((unsigned char) *p)) != 0))
p++;
ignore[i].field_tag=(ttag_t) strtol(p,&q,10);
p=q;
i++;
while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
p++;
}
(void) TIFFMergeFieldInfo(tiff,ignore,(uint32) count);
ignore=(TIFFFieldInfo *) RelinquishMagickMemory(ignore);
}
static void TIFFTagExtender(TIFF *tiff)
{
static const TIFFFieldInfo
TIFFExtensions[] =
{
{ 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
(char *) "PhotoshopLayerData" },
{ 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
(char *) "Microscope" }
};
TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/
sizeof(*TIFFExtensions));
if (tag_extender != (TIFFExtendProc) NULL)
(*tag_extender)(tiff);
TIFFIgnoreTags(tiff);
}
#endif
ModuleExport size_t RegisterTIFFImage(void)
{
#define TIFFDescription "Tagged Image File Format"
char
version[MaxTextExtent];
MagickInfo
*entry;
if (tiff_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&tiff_semaphore);
LockSemaphoreInfo(tiff_semaphore);
if (instantiate_key == MagickFalse)
{
if (CreateMagickThreadKey(&tiff_exception,NULL) == MagickFalse)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
error_handler=TIFFSetErrorHandler(TIFFErrors);
warning_handler=TIFFSetWarningHandler(TIFFWarnings);
#if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
if (tag_extender == (TIFFExtendProc) NULL)
tag_extender=TIFFSetTagExtender(TIFFTagExtender);
#endif
instantiate_key=MagickTrue;
}
UnlockSemaphoreInfo(tiff_semaphore);
*version='\0';
#if defined(TIFF_VERSION)
(void) FormatLocaleString(version,MaxTextExtent,"%d",TIFF_VERSION);
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
{
const char
*p;
register ssize_t
i;
p=TIFFGetVersion();
for (i=0; (i < (MaxTextExtent-1)) && (*p != 0) && (*p != '\n'); i++)
version[i]=(*p++);
version[i]='\0';
}
#endif
entry=SetMagickInfo("GROUP4");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadGROUP4Image;
entry->encoder=(EncodeImageHandler *) WriteGROUP4Image;
#endif
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->adjoin=MagickFalse;
entry->format_type=ImplicitFormatType;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Raw CCITT Group4");
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PTIF");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WritePTIFImage;
#endif
entry->endian_support=MagickTrue;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Pyramid encoded TIFF");
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TIF");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
#endif
entry->endian_support=MagickTrue;
entry->seekable_stream=MagickTrue;
entry->stealth=MagickTrue;
entry->description=ConstantString(TIFFDescription);
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TIFF");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
#endif
entry->magick=(IsImageFormatHandler *) IsTIFF;
entry->endian_support=MagickTrue;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString(TIFFDescription);
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TIFF64");
#if defined(TIFF_VERSION_BIG)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
#endif
entry->adjoin=MagickFalse;
entry->endian_support=MagickTrue;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Tagged Image File Format (64-bit)");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterTIFFImage() removes format registrations made by the TIFF module
% from the list of supported formats.
%
% The format of the UnregisterTIFFImage method is:
%
% UnregisterTIFFImage(void)
%
*/
ModuleExport void UnregisterTIFFImage(void)
{
(void) UnregisterMagickInfo("TIFF64");
(void) UnregisterMagickInfo("TIFF");
(void) UnregisterMagickInfo("TIF");
(void) UnregisterMagickInfo("PTIF");
if (tiff_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&tiff_semaphore);
LockSemaphoreInfo(tiff_semaphore);
if (instantiate_key != MagickFalse)
{
if (DeleteMagickThreadKey(tiff_exception) == MagickFalse)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
#if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
if (tag_extender == (TIFFExtendProc) NULL)
(void) TIFFSetTagExtender(tag_extender);
#endif
(void) TIFFSetWarningHandler(warning_handler);
(void) TIFFSetErrorHandler(error_handler);
instantiate_key=MagickFalse;
}
UnlockSemaphoreInfo(tiff_semaphore);
DestroySemaphoreInfo(&tiff_semaphore);
}
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e G R O U P 4 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format.
%
% The format of the WriteGROUP4Image method is:
%
% MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
Image *image)
{
char
filename[MaxTextExtent];
FILE
*file;
Image
*huffman_image;
ImageInfo
*write_info;
int
unique_file;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
count;
TIFF
*tiff;
toff_t
*byte_count,
strip_size;
unsigned char
*buffer;
/*
Write image as CCITT Group4 TIFF image to a temporary file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
huffman_image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (huffman_image == (Image *) NULL)
{
(void) CloseBlob(image);
return(MagickFalse);
}
huffman_image->endian=MSBEndian;
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
ThrowFileException(&image->exception,FileOpenError,
"UnableToCreateTemporaryFile",filename);
return(MagickFalse);
}
(void) FormatLocaleString(huffman_image->filename,MaxTextExtent,"tiff:%s",
filename);
(void) SetImageType(huffman_image,BilevelType);
write_info=CloneImageInfo((ImageInfo *) NULL);
SetImageInfoFile(write_info,file);
(void) SetImageType(image,BilevelType);
(void) SetImageDepth(image,1);
write_info->compression=Group4Compression;
write_info->type=BilevelType;
(void) SetImageOption(write_info,"quantum:polarity","min-is-white");
status=WriteTIFFImage(write_info,huffman_image);
(void) fflush(file);
write_info=DestroyImageInfo(write_info);
if (status == MagickFalse)
{
InheritException(&image->exception,&huffman_image->exception);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
return(MagickFalse);
}
tiff=TIFFOpen(filename,"rb");
if (tiff == (TIFF *) NULL)
{
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile",
image_info->filename);
return(MagickFalse);
}
/*
Allocate raw strip buffer.
*/
if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1)
{
TIFFClose(tiff);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
return(MagickFalse);
}
strip_size=byte_count[0];
for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
if (byte_count[i] > strip_size)
strip_size=byte_count[i];
buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size,
sizeof(*buffer));
if (buffer == (unsigned char *) NULL)
{
TIFFClose(tiff);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image_info->filename);
}
/*
Compress runlength encoded to 2D Huffman pixels.
*/
for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
{
count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size);
if (WriteBlob(image,(size_t) count,buffer) != count)
status=MagickFalse;
}
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
TIFFClose(tiff);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
(void) CloseBlob(image);
return(status);
}
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P T I F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file
% format.
%
% The format of the WritePTIFImage method is:
%
% MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
Image *image)
{
ExceptionInfo
*exception;
Image
*images,
*next,
*pyramid_image;
ImageInfo
*write_info;
MagickBooleanType
status;
PointInfo
resolution;
size_t
columns,
rows;
/*
Create pyramid-encoded TIFF image.
*/
exception=(&image->exception);
images=NewImageList();
for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
{
Image
*clone_image;
clone_image=CloneImage(next,0,0,MagickFalse,exception);
if (clone_image == (Image *) NULL)
break;
clone_image->previous=NewImageList();
clone_image->next=NewImageList();
(void) SetImageProperty(clone_image,"tiff:subfiletype","none");
AppendImageToList(&images,clone_image);
columns=next->columns;
rows=next->rows;
resolution.x=next->x_resolution;
resolution.y=next->y_resolution;
while ((columns > 64) && (rows > 64))
{
columns/=2;
rows/=2;
resolution.x/=2.0;
resolution.y/=2.0;
pyramid_image=ResizeImage(next,columns,rows,image->filter,image->blur,
exception);
if (pyramid_image == (Image *) NULL)
break;
pyramid_image->x_resolution=resolution.x;
pyramid_image->y_resolution=resolution.y;
(void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE");
AppendImageToList(&images,pyramid_image);
}
}
/*
Write pyramid-encoded TIFF image.
*/
write_info=CloneImageInfo(image_info);
write_info->adjoin=MagickTrue;
status=WriteTIFFImage(write_info,GetFirstImageInList(images));
images=DestroyImageList(images);
write_info=DestroyImageInfo(write_info);
return(status);
}
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% W r i t e T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteTIFFImage() writes an image in the Tagged image file format.
%
% The format of the WriteTIFFImage method is:
%
% MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
*/
typedef struct _TIFFInfo
{
RectangleInfo
tile_geometry;
unsigned char
*scanline,
*scanlines,
*pixels;
} TIFFInfo;
static void DestroyTIFFInfo(TIFFInfo *tiff_info)
{
assert(tiff_info != (TIFFInfo *) NULL);
if (tiff_info->scanlines != (unsigned char *) NULL)
tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory(
tiff_info->scanlines);
if (tiff_info->pixels != (unsigned char *) NULL)
tiff_info->pixels=(unsigned char *) RelinquishMagickMemory(
tiff_info->pixels);
}
static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
a,
b;
a=QuantumScale*GetPixela(q)-0.5;
if (a < 0.0)
a+=1.0;
b=QuantumScale*GetPixelb(q)-0.5;
if (b < 0.0)
b+=1.0;
SetPixela(q,QuantumRange*a);
SetPixelb(q,QuantumRange*b);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,TIFF *tiff,
TIFFInfo *tiff_info)
{
const char
*option;
MagickStatusType
flags;
uint32
tile_columns,
tile_rows;
assert(tiff_info != (TIFFInfo *) NULL);
(void) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info));
option=GetImageOption(image_info,"tiff:tile-geometry");
if (option == (const char *) NULL)
return(MagickTrue);
flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry);
if ((flags & HeightValue) == 0)
tiff_info->tile_geometry.height=tiff_info->tile_geometry.width;
tile_columns=(uint32) tiff_info->tile_geometry.width;
tile_rows=(uint32) tiff_info->tile_geometry.height;
TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows);
(void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns);
(void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows);
tiff_info->tile_geometry.width=tile_columns;
tiff_info->tile_geometry.height=tile_rows;
tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t)
tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines));
tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t)
tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines));
if ((tiff_info->scanlines == (unsigned char *) NULL) ||
(tiff_info->pixels == (unsigned char *) NULL))
{
DestroyTIFFInfo(tiff_info);
return(MagickFalse);
}
return(MagickTrue);
}
static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row,
tsample_t sample,Image *image)
{
int32
status;
register ssize_t
i;
register unsigned char
*p,
*q;
size_t
number_tiles,
tile_width;
ssize_t
bytes_per_pixel,
j,
k,
l;
if (TIFFIsTiled(tiff) == 0)
return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample));
/*
Fill scanlines to tile height.
*/
i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff);
(void) CopyMagickMemory(tiff_info->scanlines+i,(char *) tiff_info->scanline,
(size_t) TIFFScanlineSize(tiff));
if (((size_t) (row % tiff_info->tile_geometry.height) !=
(tiff_info->tile_geometry.height-1)) &&
(row != (ssize_t) (image->rows-1)))
return(0);
/*
Write tile to TIFF image.
*/
status=0;
bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) (tiff_info->tile_geometry.height*
tiff_info->tile_geometry.width);
number_tiles=(image->columns+tiff_info->tile_geometry.width)/
tiff_info->tile_geometry.width;
for (i=0; i < (ssize_t) number_tiles; i++)
{
tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i*
tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width;
for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++)
for (k=0; k < (ssize_t) tile_width; k++)
{
if (bytes_per_pixel == 0)
{
p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
tiff_info->tile_geometry.width+k)/8);
q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8);
*q++=(*p++);
continue;
}
p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
tiff_info->tile_geometry.width+k)*bytes_per_pixel);
q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel);
for (l=0; l < bytes_per_pixel; l++)
*q++=(*p++);
}
if ((i*tiff_info->tile_geometry.width) != image->columns)
status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i*
tiff_info->tile_geometry.width),(uint32) ((row/
tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0,
sample);
if (status < 0)
break;
}
return(status);
}
static void TIFFSetProfiles(TIFF *tiff,Image *image)
{
const char
*name;
const StringInfo
*profile;
if (image->profiles == (void *) NULL)
return;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (GetStringInfoLength(profile) == 0)
{
name=GetNextImageProfile(image);
continue;
}
#if defined(TIFFTAG_XMLPACKET)
if (LocaleCompare(name,"xmp") == 0)
(void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength(
profile),GetStringInfoDatum(profile));
#endif
#if defined(TIFFTAG_ICCPROFILE)
if (LocaleCompare(name,"icc") == 0)
(void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength(
profile),GetStringInfoDatum(profile));
#endif
if (LocaleCompare(name,"iptc") == 0)
{
size_t
length;
StringInfo
*iptc_profile;
iptc_profile=CloneStringInfo(profile);
length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) &
0x03);
SetStringInfoLength(iptc_profile,length);
if (TIFFIsByteSwapped(tiff))
TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile),
(unsigned long) (length/4));
(void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32)
GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile));
iptc_profile=DestroyStringInfo(iptc_profile);
}
#if defined(TIFFTAG_PHOTOSHOP)
if (LocaleCompare(name,"8bim") == 0)
(void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32)
GetStringInfoLength(profile),GetStringInfoDatum(profile));
#endif
if (LocaleCompare(name,"tiff:37724") == 0)
(void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile),
GetStringInfoDatum(profile));
if (LocaleCompare(name,"tiff:34118") == 0)
(void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile),
GetStringInfoDatum(profile));
name=GetNextImageProfile(image);
}
}
static void TIFFSetProperties(TIFF *tiff,const ImageInfo *image_info,
Image *image)
{
const char
*value;
value=GetImageArtifact(image,"tiff:document");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,value);
value=GetImageArtifact(image,"tiff:hostcomputer");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value);
value=GetImageArtifact(image,"tiff:artist");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_ARTIST,value);
value=GetImageArtifact(image,"tiff:timestamp");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_DATETIME,value);
value=GetImageArtifact(image,"tiff:make");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_MAKE,value);
value=GetImageArtifact(image,"tiff:model");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_MODEL,value);
value=GetImageArtifact(image,"tiff:software");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value);
value=GetImageArtifact(image,"tiff:copyright");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value);
value=GetImageArtifact(image,"kodak-33423");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,33423,value);
value=GetImageArtifact(image,"kodak-36867");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,36867,value);
value=GetImageProperty(image,"label");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value);
value=GetImageProperty(image,"comment");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value);
value=GetImageArtifact(image,"tiff:subfiletype");
if (value != (const char *) NULL)
{
if (LocaleCompare(value,"REDUCEDIMAGE") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
else
if (LocaleCompare(value,"PAGE") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
else
if (LocaleCompare(value,"MASK") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_MASK);
}
else
{
uint16
page,
pages;
page=(uint16) image->scene;
pages=(uint16) GetImageListLength(image);
if ((image_info->adjoin != MagickFalse) && (pages > 1))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
}
}
static void TIFFSetEXIFProperties(TIFF *tiff,Image *image)
{
#if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
const char
*value;
register ssize_t
i;
uint32
offset;
/*
Write EXIF properties.
*/
offset=0;
(void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset);
for (i=0; exif_info[i].tag != 0; i++)
{
value=GetImageProperty(image,exif_info[i].property);
if (value == (const char *) NULL)
continue;
switch (exif_info[i].type)
{
case TIFF_ASCII:
{
(void) TIFFSetField(tiff,exif_info[i].tag,value);
break;
}
case TIFF_SHORT:
{
uint16
field;
field=(uint16) StringToLong(value);
(void) TIFFSetField(tiff,exif_info[i].tag,field);
break;
}
case TIFF_LONG:
{
uint16
field;
field=(uint16) StringToLong(value);
(void) TIFFSetField(tiff,exif_info[i].tag,field);
break;
}
case TIFF_RATIONAL:
case TIFF_SRATIONAL:
{
float
field;
field=StringToDouble(value,(char **) NULL);
(void) TIFFSetField(tiff,exif_info[i].tag,field);
break;
}
default:
break;
}
}
/* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */
#else
(void) tiff;
(void) image;
#endif
}
static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
Image *image)
{
#if !defined(TIFFDefaultStripSize)
#define TIFFDefaultStripSize(tiff,request) (8192UL/TIFFScanlineSize(tiff))
#endif
const char
*mode,
*option;
CompressionType
compression;
EndianType
endian_type;
MagickBooleanType
debug,
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
ssize_t
y;
TIFF
*tiff;
TIFFInfo
tiff_info;
uint16
bits_per_sample,
compress_tag,
endian,
photometric;
uint32
rows_per_strip;
unsigned char
*pixels;
/*
Open TIFF file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(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);
scene=0;
debug=IsEventLogging();
(void) debug;
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)
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;
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
case Group4Compression:
{
compress_tag=COMPRESSION_CCITTFAX4;
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;
}
case ZipCompression:
{
compress_tag=COMPRESSION_ADOBE_DEFLATE;
break;
}
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) &&
(photometric != PHOTOMETRIC_MINISWHITE))
{
compress_tag=COMPRESSION_NONE;
endian=FILLORDER_MSB2LSB;
}
else
if ((compress_tag == COMPRESSION_CCITTFAX4) &&
(photometric != PHOTOMETRIC_MINISWHITE))
{
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_ORIENTATION,ORIENTATION_TOPLEFT);
(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);
rows_per_strip=TIFFDefaultStripSize(tiff,0);
option=GetImageOption(image_info,"tiff:rows-per-strip");
if (option != (const char *) NULL)
rows_per_strip=(size_t) strtol(option,(char **) NULL,10);
switch (compress_tag)
{
case COMPRESSION_JPEG:
{
#if defined(JPEG_SUPPORT)
const char
*sampling_factor;
GeometryInfo
geometry_info;
MagickStatusType
flags;
rows_per_strip+=(16-(rows_per_strip % 16));
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);
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;
if (image->colorspace == YCbCrColorspace)
(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:
{
rows_per_strip=(uint32) image->rows;
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_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.
*/
rows_per_strip=(uint32) image->rows;
(void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
break;
}
case COMPRESSION_CCITTFAX4:
{
rows_per_strip=(uint32) image->rows;
break;
}
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
{
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_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_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
break;
}
default:
break;
}
if (rows_per_strip < 1)
rows_per_strip=1;
if ((image->rows/rows_per_strip) >= (1UL << 15))
rows_per_strip=(uint32) (image->rows >> 15);
(void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
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) && (GetImageListLength(image) > 1))
{
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
if (image->scene != 0)
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
GetImageListLength(image));
}
if (image->orientation != UndefinedOrientation)
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
(void) TIFFSetProfiles(tiff,image);
{
uint16
page,
pages;
page=(uint16) scene;
pages=(uint16) GetImageListLength(image);
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))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize TIFF colormap.
*/
(void) ResetMagickMemory(red,0,65536*sizeof(*red));
(void) ResetMagickMemory(green,0,65536*sizeof(*green));
(void) ResetMagickMemory(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);
(void) TIFFWriteDirectory(tiff);
image=SyncNextImageInList(image);
if (image == (Image *) NULL)
break;
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
TIFFClose(tiff);
return(MagickTrue);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4785_0 |
crossvul-cpp_data_bad_252_5 | #define TEST_NO_MAIN
#include "acutest.h"
#include "mutt/base64.h"
#include <string.h>
static const char clear[] = "Hello";
static const char encoded[] = "SGVsbG8=";
void test_base64_encode(void)
{
char buffer[16];
size_t len = mutt_b64_encode(buffer, clear, sizeof(clear) - 1, sizeof(buffer));
if (!TEST_CHECK(len == sizeof(encoded) - 1))
{
TEST_MSG("Expected: %zu", sizeof(encoded) - 1);
TEST_MSG("Actual : %zu", len);
}
if (!TEST_CHECK(strcmp(buffer, encoded) == 0))
{
TEST_MSG("Expected: %zu", encoded);
TEST_MSG("Actual : %zu", buffer);
}
}
void test_base64_decode(void)
{
char buffer[16];
int len = mutt_b64_decode(buffer, encoded);
if (!TEST_CHECK(len == sizeof(clear) - 1))
{
TEST_MSG("Expected: %zu", sizeof(clear) - 1);
TEST_MSG("Actual : %zu", len);
}
buffer[len] = '\0';
if (!TEST_CHECK(strcmp(buffer, clear) == 0))
{
TEST_MSG("Expected: %s", clear);
TEST_MSG("Actual : %s", buffer);
}
}
void test_base64_lengths(void)
{
const char *in = "FuseMuse";
char out1[32];
char out2[32];
size_t enclen;
int declen;
/* Encoding a zero-length string should fail */
enclen = mutt_b64_encode(out1, in, 0, 32);
if (!TEST_CHECK(enclen == 0))
{
TEST_MSG("Expected: %zu", 0);
TEST_MSG("Actual : %zu", enclen);
}
/* Decoding a zero-length string should fail, too */
out1[0] = '\0';
declen = mutt_b64_decode(out2, out1);
if (!TEST_CHECK(declen == -1))
{
TEST_MSG("Expected: %zu", -1);
TEST_MSG("Actual : %zu", declen);
}
/* Encode one to eight bytes, check the lengths of the returned string */
for (size_t i = 1; i <= 8; ++i)
{
enclen = mutt_b64_encode(out1, in, i, 32);
size_t exp = ((i + 2) / 3) << 2;
if (!TEST_CHECK(enclen == exp))
{
TEST_MSG("Expected: %zu", exp);
TEST_MSG("Actual : %zu", enclen);
}
declen = mutt_b64_decode(out2, out1);
if (!TEST_CHECK(declen == i))
{
TEST_MSG("Expected: %zu", i);
TEST_MSG("Actual : %zu", declen);
}
out2[declen] = '\0';
if (!TEST_CHECK(strncmp(out2, in, i) == 0))
{
TEST_MSG("Expected: %s", in);
TEST_MSG("Actual : %s", out2);
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_252_5 |
crossvul-cpp_data_bad_412_2 | /* regcomp.c
*/
/*
* 'A fair jaw-cracker dwarf-language must be.' --Samwise Gamgee
*
* [p.285 of _The Lord of the Rings_, II/iii: "The Ring Goes South"]
*/
/* This file contains functions for compiling a regular expression. See
* also regexec.c which funnily enough, contains functions for executing
* a regular expression.
*
* This file is also copied at build time to ext/re/re_comp.c, where
* it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
* This causes the main functions to be compiled under new names and with
* debugging support added, which makes "use re 'debug'" work.
*/
/* NOTE: this is derived from Henry Spencer's regexp code, and should not
* confused with the original package (see point 3 below). Thanks, Henry!
*/
/* Additional note: this code is very heavily munged from Henry's version
* in places. In some spots I've traded clarity for efficiency, so don't
* blame Henry for some of the lack of readability.
*/
/* The names of the functions have been changed from regcomp and
* regexec to pregcomp and pregexec in order to avoid conflicts
* with the POSIX routines of the same names.
*/
#ifdef PERL_EXT_RE_BUILD
#include "re_top.h"
#endif
/*
* pregcomp and pregexec -- regsub and regerror are not used in perl
*
* Copyright (c) 1986 by University of Toronto.
* Written by Henry Spencer. Not derived from licensed software.
*
* Permission is granted to anyone to use this software for any
* purpose on any computer system, and to redistribute it freely,
* subject to the following restrictions:
*
* 1. The author is not responsible for the consequences of use of
* this software, no matter how awful, even if they arise
* from defects in it.
*
* 2. The origin of this software must not be misrepresented, either
* by explicit claim or by omission.
*
* 3. Altered versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
*
**** Alterations to Henry's code are...
****
**** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
**** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
**** by Larry Wall and others
****
**** You may distribute under the terms of either the GNU General Public
**** License or the Artistic License, as specified in the README file.
*
* Beware that some of this code is subtly aware of the way operator
* precedence is structured in regular expressions. Serious changes in
* regular-expression syntax might require a total rethink.
*/
#include "EXTERN.h"
#define PERL_IN_REGCOMP_C
#include "perl.h"
#ifndef PERL_IN_XSUB_RE
# include "INTERN.h"
#endif
#define REG_COMP_C
#ifdef PERL_IN_XSUB_RE
# include "re_comp.h"
EXTERN_C const struct regexp_engine my_reg_engine;
#else
# include "regcomp.h"
#endif
#include "dquote_inline.h"
#include "invlist_inline.h"
#include "unicode_constants.h"
#define HAS_NONLATIN1_FOLD_CLOSURE(i) \
_HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
#define HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(i) \
_HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
#define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
#define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
#ifndef STATIC
#define STATIC static
#endif
/* this is a chain of data about sub patterns we are processing that
need to be handled separately/specially in study_chunk. Its so
we can simulate recursion without losing state. */
struct scan_frame;
typedef struct scan_frame {
regnode *last_regnode; /* last node to process in this frame */
regnode *next_regnode; /* next node to process when last is reached */
U32 prev_recursed_depth;
I32 stopparen; /* what stopparen do we use */
struct scan_frame *this_prev_frame; /* this previous frame */
struct scan_frame *prev_frame; /* previous frame */
struct scan_frame *next_frame; /* next frame */
} scan_frame;
/* Certain characters are output as a sequence with the first being a
* backslash. */
#define isBACKSLASHED_PUNCT(c) strchr("-[]\\^", c)
struct RExC_state_t {
U32 flags; /* RXf_* are we folding, multilining? */
U32 pm_flags; /* PMf_* stuff from the calling PMOP */
char *precomp; /* uncompiled string. */
char *precomp_end; /* pointer to end of uncompiled string. */
REGEXP *rx_sv; /* The SV that is the regexp. */
regexp *rx; /* perl core regexp structure */
regexp_internal *rxi; /* internal data for regexp object
pprivate field */
char *start; /* Start of input for compile */
char *end; /* End of input for compile */
char *parse; /* Input-scan pointer. */
char *adjusted_start; /* 'start', adjusted. See code use */
STRLEN precomp_adj; /* an offset beyond precomp. See code use */
SSize_t whilem_seen; /* number of WHILEM in this expr */
regnode *emit_start; /* Start of emitted-code area */
regnode *emit_bound; /* First regnode outside of the
allocated space */
regnode *emit; /* Code-emit pointer; if = &emit_dummy,
implies compiling, so don't emit */
regnode_ssc emit_dummy; /* placeholder for emit to point to;
large enough for the largest
non-EXACTish node, so can use it as
scratch in pass1 */
I32 naughty; /* How bad is this pattern? */
I32 sawback; /* Did we see \1, ...? */
U32 seen;
SSize_t size; /* Code size. */
I32 npar; /* Capture buffer count, (OPEN) plus
one. ("par" 0 is the whole
pattern)*/
I32 nestroot; /* root parens we are in - used by
accept */
I32 extralen;
I32 seen_zerolen;
regnode **open_parens; /* pointers to open parens */
regnode **close_parens; /* pointers to close parens */
regnode *end_op; /* END node in program */
I32 utf8; /* whether the pattern is utf8 or not */
I32 orig_utf8; /* whether the pattern was originally in utf8 */
/* XXX use this for future optimisation of case
* where pattern must be upgraded to utf8. */
I32 uni_semantics; /* If a d charset modifier should use unicode
rules, even if the pattern is not in
utf8 */
HV *paren_names; /* Paren names */
regnode **recurse; /* Recurse regops */
I32 recurse_count; /* Number of recurse regops we have generated */
U8 *study_chunk_recursed; /* bitmap of which subs we have moved
through */
U32 study_chunk_recursed_bytes; /* bytes in bitmap */
I32 in_lookbehind;
I32 contains_locale;
I32 override_recoding;
#ifdef EBCDIC
I32 recode_x_to_native;
#endif
I32 in_multi_char_class;
struct reg_code_blocks *code_blocks;/* positions of literal (?{})
within pattern */
int code_index; /* next code_blocks[] slot */
SSize_t maxlen; /* mininum possible number of chars in string to match */
scan_frame *frame_head;
scan_frame *frame_last;
U32 frame_count;
AV *warn_text;
#ifdef ADD_TO_REGEXEC
char *starttry; /* -Dr: where regtry was called. */
#define RExC_starttry (pRExC_state->starttry)
#endif
SV *runtime_code_qr; /* qr with the runtime code blocks */
#ifdef DEBUGGING
const char *lastparse;
I32 lastnum;
AV *paren_name_list; /* idx -> name */
U32 study_chunk_recursed_count;
SV *mysv1;
SV *mysv2;
#define RExC_lastparse (pRExC_state->lastparse)
#define RExC_lastnum (pRExC_state->lastnum)
#define RExC_paren_name_list (pRExC_state->paren_name_list)
#define RExC_study_chunk_recursed_count (pRExC_state->study_chunk_recursed_count)
#define RExC_mysv (pRExC_state->mysv1)
#define RExC_mysv1 (pRExC_state->mysv1)
#define RExC_mysv2 (pRExC_state->mysv2)
#endif
bool seen_unfolded_sharp_s;
bool strict;
bool study_started;
};
#define RExC_flags (pRExC_state->flags)
#define RExC_pm_flags (pRExC_state->pm_flags)
#define RExC_precomp (pRExC_state->precomp)
#define RExC_precomp_adj (pRExC_state->precomp_adj)
#define RExC_adjusted_start (pRExC_state->adjusted_start)
#define RExC_precomp_end (pRExC_state->precomp_end)
#define RExC_rx_sv (pRExC_state->rx_sv)
#define RExC_rx (pRExC_state->rx)
#define RExC_rxi (pRExC_state->rxi)
#define RExC_start (pRExC_state->start)
#define RExC_end (pRExC_state->end)
#define RExC_parse (pRExC_state->parse)
#define RExC_whilem_seen (pRExC_state->whilem_seen)
/* Set during the sizing pass when there is a LATIN SMALL LETTER SHARP S in any
* EXACTF node, hence was parsed under /di rules. If later in the parse,
* something forces the pattern into using /ui rules, the sharp s should be
* folded into the sequence 'ss', which takes up more space than previously
* calculated. This means that the sizing pass needs to be restarted. (The
* node also becomes an EXACTFU_SS.) For all other characters, an EXACTF node
* that gets converted to /ui (and EXACTFU) occupies the same amount of space,
* so there is no need to resize [perl #125990]. */
#define RExC_seen_unfolded_sharp_s (pRExC_state->seen_unfolded_sharp_s)
#ifdef RE_TRACK_PATTERN_OFFSETS
#define RExC_offsets (pRExC_state->rxi->u.offsets) /* I am not like the
others */
#endif
#define RExC_emit (pRExC_state->emit)
#define RExC_emit_dummy (pRExC_state->emit_dummy)
#define RExC_emit_start (pRExC_state->emit_start)
#define RExC_emit_bound (pRExC_state->emit_bound)
#define RExC_sawback (pRExC_state->sawback)
#define RExC_seen (pRExC_state->seen)
#define RExC_size (pRExC_state->size)
#define RExC_maxlen (pRExC_state->maxlen)
#define RExC_npar (pRExC_state->npar)
#define RExC_nestroot (pRExC_state->nestroot)
#define RExC_extralen (pRExC_state->extralen)
#define RExC_seen_zerolen (pRExC_state->seen_zerolen)
#define RExC_utf8 (pRExC_state->utf8)
#define RExC_uni_semantics (pRExC_state->uni_semantics)
#define RExC_orig_utf8 (pRExC_state->orig_utf8)
#define RExC_open_parens (pRExC_state->open_parens)
#define RExC_close_parens (pRExC_state->close_parens)
#define RExC_end_op (pRExC_state->end_op)
#define RExC_paren_names (pRExC_state->paren_names)
#define RExC_recurse (pRExC_state->recurse)
#define RExC_recurse_count (pRExC_state->recurse_count)
#define RExC_study_chunk_recursed (pRExC_state->study_chunk_recursed)
#define RExC_study_chunk_recursed_bytes \
(pRExC_state->study_chunk_recursed_bytes)
#define RExC_in_lookbehind (pRExC_state->in_lookbehind)
#define RExC_contains_locale (pRExC_state->contains_locale)
#ifdef EBCDIC
# define RExC_recode_x_to_native (pRExC_state->recode_x_to_native)
#endif
#define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
#define RExC_frame_head (pRExC_state->frame_head)
#define RExC_frame_last (pRExC_state->frame_last)
#define RExC_frame_count (pRExC_state->frame_count)
#define RExC_strict (pRExC_state->strict)
#define RExC_study_started (pRExC_state->study_started)
#define RExC_warn_text (pRExC_state->warn_text)
/* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
* a flag to disable back-off on the fixed/floating substrings - if it's
* a high complexity pattern we assume the benefit of avoiding a full match
* is worth the cost of checking for the substrings even if they rarely help.
*/
#define RExC_naughty (pRExC_state->naughty)
#define TOO_NAUGHTY (10)
#define MARK_NAUGHTY(add) \
if (RExC_naughty < TOO_NAUGHTY) \
RExC_naughty += (add)
#define MARK_NAUGHTY_EXP(exp, add) \
if (RExC_naughty < TOO_NAUGHTY) \
RExC_naughty += RExC_naughty / (exp) + (add)
#define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
#define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
((*s) == '{' && regcurly(s)))
/*
* Flags to be passed up and down.
*/
#define WORST 0 /* Worst case. */
#define HASWIDTH 0x01 /* Known to match non-null strings. */
/* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
* character. (There needs to be a case: in the switch statement in regexec.c
* for any node marked SIMPLE.) Note that this is not the same thing as
* REGNODE_SIMPLE */
#define SIMPLE 0x02
#define SPSTART 0x04 /* Starts with * or + */
#define POSTPONED 0x08 /* (?1),(?&name), (??{...}) or similar */
#define TRYAGAIN 0x10 /* Weeded out a declaration. */
#define RESTART_PASS1 0x20 /* Need to restart sizing pass */
#define NEED_UTF8 0x40 /* In conjunction with RESTART_PASS1, need to
calcuate sizes as UTF-8 */
#define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
/* whether trie related optimizations are enabled */
#if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
#define TRIE_STUDY_OPT
#define FULL_TRIE_STUDY
#define TRIE_STCLASS
#endif
#define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
#define PBITVAL(paren) (1 << ((paren) & 7))
#define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
#define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
#define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
#define REQUIRE_UTF8(flagp) STMT_START { \
if (!UTF) { \
assert(PASS1); \
*flagp = RESTART_PASS1|NEED_UTF8; \
return NULL; \
} \
} STMT_END
/* Change from /d into /u rules, and restart the parse if we've already seen
* something whose size would increase as a result, by setting *flagp and
* returning 'restart_retval'. RExC_uni_semantics is a flag that indicates
* we've change to /u during the parse. */
#define REQUIRE_UNI_RULES(flagp, restart_retval) \
STMT_START { \
if (DEPENDS_SEMANTICS) { \
assert(PASS1); \
set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET); \
RExC_uni_semantics = 1; \
if (RExC_seen_unfolded_sharp_s) { \
*flagp |= RESTART_PASS1; \
return restart_retval; \
} \
} \
} STMT_END
/* This converts the named class defined in regcomp.h to its equivalent class
* number defined in handy.h. */
#define namedclass_to_classnum(class) ((int) ((class) / 2))
#define classnum_to_namedclass(classnum) ((classnum) * 2)
#define _invlist_union_complement_2nd(a, b, output) \
_invlist_union_maybe_complement_2nd(a, b, TRUE, output)
#define _invlist_intersection_complement_2nd(a, b, output) \
_invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
/* About scan_data_t.
During optimisation we recurse through the regexp program performing
various inplace (keyhole style) optimisations. In addition study_chunk
and scan_commit populate this data structure with information about
what strings MUST appear in the pattern. We look for the longest
string that must appear at a fixed location, and we look for the
longest string that may appear at a floating location. So for instance
in the pattern:
/FOO[xX]A.*B[xX]BAR/
Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
strings (because they follow a .* construct). study_chunk will identify
both FOO and BAR as being the longest fixed and floating strings respectively.
The strings can be composites, for instance
/(f)(o)(o)/
will result in a composite fixed substring 'foo'.
For each string some basic information is maintained:
- min_offset
This is the position the string must appear at, or not before.
It also implicitly (when combined with minlenp) tells us how many
characters must match before the string we are searching for.
Likewise when combined with minlenp and the length of the string it
tells us how many characters must appear after the string we have
found.
- max_offset
Only used for floating strings. This is the rightmost point that
the string can appear at. If set to SSize_t_MAX it indicates that the
string can occur infinitely far to the right.
For fixed strings, it is equal to min_offset.
- minlenp
A pointer to the minimum number of characters of the pattern that the
string was found inside. This is important as in the case of positive
lookahead or positive lookbehind we can have multiple patterns
involved. Consider
/(?=FOO).*F/
The minimum length of the pattern overall is 3, the minimum length
of the lookahead part is 3, but the minimum length of the part that
will actually match is 1. So 'FOO's minimum length is 3, but the
minimum length for the F is 1. This is important as the minimum length
is used to determine offsets in front of and behind the string being
looked for. Since strings can be composites this is the length of the
pattern at the time it was committed with a scan_commit. Note that
the length is calculated by study_chunk, so that the minimum lengths
are not known until the full pattern has been compiled, thus the
pointer to the value.
- lookbehind
In the case of lookbehind the string being searched for can be
offset past the start point of the final matching string.
If this value was just blithely removed from the min_offset it would
invalidate some of the calculations for how many chars must match
before or after (as they are derived from min_offset and minlen and
the length of the string being searched for).
When the final pattern is compiled and the data is moved from the
scan_data_t structure into the regexp structure the information
about lookbehind is factored in, with the information that would
have been lost precalculated in the end_shift field for the
associated string.
The fields pos_min and pos_delta are used to store the minimum offset
and the delta to the maximum offset at the current point in the pattern.
*/
struct scan_data_substrs {
SV *str; /* longest substring found in pattern */
SSize_t min_offset; /* earliest point in string it can appear */
SSize_t max_offset; /* latest point in string it can appear */
SSize_t *minlenp; /* pointer to the minlen relevant to the string */
SSize_t lookbehind; /* is the pos of the string modified by LB */
I32 flags; /* per substring SF_* and SCF_* flags */
};
typedef struct scan_data_t {
/*I32 len_min; unused */
/*I32 len_delta; unused */
SSize_t pos_min;
SSize_t pos_delta;
SV *last_found;
SSize_t last_end; /* min value, <0 unless valid. */
SSize_t last_start_min;
SSize_t last_start_max;
U8 cur_is_floating; /* whether the last_* values should be set as
* the next fixed (0) or floating (1)
* substring */
/* [0] is longest fixed substring so far, [1] is longest float so far */
struct scan_data_substrs substrs[2];
I32 flags; /* common SF_* and SCF_* flags */
I32 whilem_c;
SSize_t *last_closep;
regnode_ssc *start_class;
} scan_data_t;
/*
* Forward declarations for pregcomp()'s friends.
*/
static const scan_data_t zero_scan_data = {
0, 0, NULL, 0, 0, 0, 0,
{
{ NULL, 0, 0, 0, 0, 0 },
{ NULL, 0, 0, 0, 0, 0 },
},
0, 0, NULL, NULL
};
/* study flags */
#define SF_BEFORE_SEOL 0x0001
#define SF_BEFORE_MEOL 0x0002
#define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
#define SF_IS_INF 0x0040
#define SF_HAS_PAR 0x0080
#define SF_IN_PAR 0x0100
#define SF_HAS_EVAL 0x0200
/* SCF_DO_SUBSTR is the flag that tells the regexp analyzer to track the
* longest substring in the pattern. When it is not set the optimiser keeps
* track of position, but does not keep track of the actual strings seen,
*
* So for instance /foo/ will be parsed with SCF_DO_SUBSTR being true, but
* /foo/i will not.
*
* Similarly, /foo.*(blah|erm|huh).*fnorble/ will have "foo" and "fnorble"
* parsed with SCF_DO_SUBSTR on, but while processing the (...) it will be
* turned off because of the alternation (BRANCH). */
#define SCF_DO_SUBSTR 0x0400
#define SCF_DO_STCLASS_AND 0x0800
#define SCF_DO_STCLASS_OR 0x1000
#define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
#define SCF_WHILEM_VISITED_POS 0x2000
#define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
#define SCF_SEEN_ACCEPT 0x8000
#define SCF_TRIE_DOING_RESTUDY 0x10000
#define SCF_IN_DEFINE 0x20000
#define UTF cBOOL(RExC_utf8)
/* The enums for all these are ordered so things work out correctly */
#define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
#define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) \
== REGEX_DEPENDS_CHARSET)
#define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
#define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) \
>= REGEX_UNICODE_CHARSET)
#define ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
== REGEX_ASCII_RESTRICTED_CHARSET)
#define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
>= REGEX_ASCII_RESTRICTED_CHARSET)
#define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags) \
== REGEX_ASCII_MORE_RESTRICTED_CHARSET)
#define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
/* For programs that want to be strictly Unicode compatible by dying if any
* attempt is made to match a non-Unicode code point against a Unicode
* property. */
#define ALWAYS_WARN_SUPER ckDEAD(packWARN(WARN_NON_UNICODE))
#define OOB_NAMEDCLASS -1
/* There is no code point that is out-of-bounds, so this is problematic. But
* its only current use is to initialize a variable that is always set before
* looked at. */
#define OOB_UNICODE 0xDEADBEEF
#define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
/* length of regex to show in messages that don't mark a position within */
#define RegexLengthToShowInErrorMessages 127
/*
* If MARKER[12] are adjusted, be sure to adjust the constants at the top
* of t/op/regmesg.t, the tests in t/op/re_tests, and those in
* op/pragma/warn/regcomp.
*/
#define MARKER1 "<-- HERE" /* marker as it appears in the description */
#define MARKER2 " <-- HERE " /* marker as it appears within the regex */
#define REPORT_LOCATION " in regex; marked by " MARKER1 \
" in m/%" UTF8f MARKER2 "%" UTF8f "/"
/* The code in this file in places uses one level of recursion with parsing
* rebased to an alternate string constructed by us in memory. This can take
* the form of something that is completely different from the input, or
* something that uses the input as part of the alternate. In the first case,
* there should be no possibility of an error, as we are in complete control of
* the alternate string. But in the second case we don't control the input
* portion, so there may be errors in that. Here's an example:
* /[abc\x{DF}def]/ui
* is handled specially because \x{df} folds to a sequence of more than one
* character, 'ss'. What is done is to create and parse an alternate string,
* which looks like this:
* /(?:\x{DF}|[abc\x{DF}def])/ui
* where it uses the input unchanged in the middle of something it constructs,
* which is a branch for the DF outside the character class, and clustering
* parens around the whole thing. (It knows enough to skip the DF inside the
* class while in this substitute parse.) 'abc' and 'def' may have errors that
* need to be reported. The general situation looks like this:
*
* sI tI xI eI
* Input: ----------------------------------------------------
* Constructed: ---------------------------------------------------
* sC tC xC eC EC
*
* The input string sI..eI is the input pattern. The string sC..EC is the
* constructed substitute parse string. The portions sC..tC and eC..EC are
* constructed by us. The portion tC..eC is an exact duplicate of the input
* pattern tI..eI. In the diagram, these are vertically aligned. Suppose that
* while parsing, we find an error at xC. We want to display a message showing
* the real input string. Thus we need to find the point xI in it which
* corresponds to xC. xC >= tC, since the portion of the string sC..tC has
* been constructed by us, and so shouldn't have errors. We get:
*
* xI = sI + (tI - sI) + (xC - tC)
*
* and, the offset into sI is:
*
* (xI - sI) = (tI - sI) + (xC - tC)
*
* When the substitute is constructed, we save (tI -sI) as RExC_precomp_adj,
* and we save tC as RExC_adjusted_start.
*
* During normal processing of the input pattern, everything points to that,
* with RExC_precomp_adj set to 0, and RExC_adjusted_start set to sI.
*/
#define tI_sI RExC_precomp_adj
#define tC RExC_adjusted_start
#define sC RExC_precomp
#define xI_offset(xC) ((IV) (tI_sI + (xC - tC)))
#define xI(xC) (sC + xI_offset(xC))
#define eC RExC_precomp_end
#define REPORT_LOCATION_ARGS(xC) \
UTF8fARG(UTF, \
(xI(xC) > eC) /* Don't run off end */ \
? eC - sC /* Length before the <--HERE */ \
: ( __ASSERT_(xI_offset(xC) >= 0) xI_offset(xC) ), \
sC), /* The input pattern printed up to the <--HERE */ \
UTF8fARG(UTF, \
(xI(xC) > eC) ? 0 : eC - xI(xC), /* Length after <--HERE */ \
(xI(xC) > eC) ? eC : xI(xC)) /* pattern after <--HERE */
/* Used to point after bad bytes for an error message, but avoid skipping
* past a nul byte. */
#define SKIP_IF_CHAR(s) (!*(s) ? 0 : UTF ? UTF8SKIP(s) : 1)
/*
* Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
* arg. Show regex, up to a maximum length. If it's too long, chop and add
* "...".
*/
#define _FAIL(code) STMT_START { \
const char *ellipses = ""; \
IV len = RExC_precomp_end - RExC_precomp; \
\
if (!SIZE_ONLY) \
SAVEFREESV(RExC_rx_sv); \
if (len > RegexLengthToShowInErrorMessages) { \
/* chop 10 shorter than the max, to ensure meaning of "..." */ \
len = RegexLengthToShowInErrorMessages - 10; \
ellipses = "..."; \
} \
code; \
} STMT_END
#define FAIL(msg) _FAIL( \
Perl_croak(aTHX_ "%s in regex m/%" UTF8f "%s/", \
msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
#define FAIL2(msg,arg) _FAIL( \
Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/", \
arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
/*
* Simple_vFAIL -- like FAIL, but marks the current location in the scan
*/
#define Simple_vFAIL(m) STMT_START { \
Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
m, REPORT_LOCATION_ARGS(RExC_parse)); \
} STMT_END
/*
* Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
*/
#define vFAIL(m) STMT_START { \
if (!SIZE_ONLY) \
SAVEFREESV(RExC_rx_sv); \
Simple_vFAIL(m); \
} STMT_END
/*
* Like Simple_vFAIL(), but accepts two arguments.
*/
#define Simple_vFAIL2(m,a1) STMT_START { \
S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
REPORT_LOCATION_ARGS(RExC_parse)); \
} STMT_END
/*
* Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
*/
#define vFAIL2(m,a1) STMT_START { \
if (!SIZE_ONLY) \
SAVEFREESV(RExC_rx_sv); \
Simple_vFAIL2(m, a1); \
} STMT_END
/*
* Like Simple_vFAIL(), but accepts three arguments.
*/
#define Simple_vFAIL3(m, a1, a2) STMT_START { \
S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
REPORT_LOCATION_ARGS(RExC_parse)); \
} STMT_END
/*
* Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
*/
#define vFAIL3(m,a1,a2) STMT_START { \
if (!SIZE_ONLY) \
SAVEFREESV(RExC_rx_sv); \
Simple_vFAIL3(m, a1, a2); \
} STMT_END
/*
* Like Simple_vFAIL(), but accepts four arguments.
*/
#define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, a3, \
REPORT_LOCATION_ARGS(RExC_parse)); \
} STMT_END
#define vFAIL4(m,a1,a2,a3) STMT_START { \
if (!SIZE_ONLY) \
SAVEFREESV(RExC_rx_sv); \
Simple_vFAIL4(m, a1, a2, a3); \
} STMT_END
/* A specialized version of vFAIL2 that works with UTF8f */
#define vFAIL2utf8f(m, a1) STMT_START { \
if (!SIZE_ONLY) \
SAVEFREESV(RExC_rx_sv); \
S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
REPORT_LOCATION_ARGS(RExC_parse)); \
} STMT_END
#define vFAIL3utf8f(m, a1, a2) STMT_START { \
if (!SIZE_ONLY) \
SAVEFREESV(RExC_rx_sv); \
S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
REPORT_LOCATION_ARGS(RExC_parse)); \
} STMT_END
/* These have asserts in them because of [perl #122671] Many warnings in
* regcomp.c can occur twice. If they get output in pass1 and later in that
* pass, the pattern has to be converted to UTF-8 and the pass restarted, they
* would get output again. So they should be output in pass2, and these
* asserts make sure new warnings follow that paradigm. */
/* m is not necessarily a "literal string", in this macro */
#define reg_warn_non_literal_string(loc, m) STMT_START { \
__ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
"%s" REPORT_LOCATION, \
m, REPORT_LOCATION_ARGS(loc)); \
} STMT_END
#define ckWARNreg(loc,m) STMT_START { \
__ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
m REPORT_LOCATION, \
REPORT_LOCATION_ARGS(loc)); \
} STMT_END
#define vWARN(loc, m) STMT_START { \
__ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
m REPORT_LOCATION, \
REPORT_LOCATION_ARGS(loc)); \
} STMT_END
#define vWARN_dep(loc, m) STMT_START { \
__ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_DEPRECATED), \
m REPORT_LOCATION, \
REPORT_LOCATION_ARGS(loc)); \
} STMT_END
#define ckWARNdep(loc,m) STMT_START { \
__ASSERT_(PASS2) Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \
m REPORT_LOCATION, \
REPORT_LOCATION_ARGS(loc)); \
} STMT_END
#define ckWARNregdep(loc,m) STMT_START { \
__ASSERT_(PASS2) Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, \
WARN_REGEXP), \
m REPORT_LOCATION, \
REPORT_LOCATION_ARGS(loc)); \
} STMT_END
#define ckWARN2reg_d(loc,m, a1) STMT_START { \
__ASSERT_(PASS2) Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP), \
m REPORT_LOCATION, \
a1, REPORT_LOCATION_ARGS(loc)); \
} STMT_END
#define ckWARN2reg(loc, m, a1) STMT_START { \
__ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
m REPORT_LOCATION, \
a1, REPORT_LOCATION_ARGS(loc)); \
} STMT_END
#define vWARN3(loc, m, a1, a2) STMT_START { \
__ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
m REPORT_LOCATION, \
a1, a2, REPORT_LOCATION_ARGS(loc)); \
} STMT_END
#define ckWARN3reg(loc, m, a1, a2) STMT_START { \
__ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
m REPORT_LOCATION, \
a1, a2, \
REPORT_LOCATION_ARGS(loc)); \
} STMT_END
#define vWARN4(loc, m, a1, a2, a3) STMT_START { \
__ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
m REPORT_LOCATION, \
a1, a2, a3, \
REPORT_LOCATION_ARGS(loc)); \
} STMT_END
#define ckWARN4reg(loc, m, a1, a2, a3) STMT_START { \
__ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
m REPORT_LOCATION, \
a1, a2, a3, \
REPORT_LOCATION_ARGS(loc)); \
} STMT_END
#define vWARN5(loc, m, a1, a2, a3, a4) STMT_START { \
__ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
m REPORT_LOCATION, \
a1, a2, a3, a4, \
REPORT_LOCATION_ARGS(loc)); \
} STMT_END
/* Macros for recording node offsets. 20001227 mjd@plover.com
* Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
* element 2*n-1 of the array. Element #2n holds the byte length node #n.
* Element 0 holds the number n.
* Position is 1 indexed.
*/
#ifndef RE_TRACK_PATTERN_OFFSETS
#define Set_Node_Offset_To_R(node,byte)
#define Set_Node_Offset(node,byte)
#define Set_Cur_Node_Offset
#define Set_Node_Length_To_R(node,len)
#define Set_Node_Length(node,len)
#define Set_Node_Cur_Length(node,start)
#define Node_Offset(n)
#define Node_Length(n)
#define Set_Node_Offset_Length(node,offset,len)
#define ProgLen(ri) ri->u.proglen
#define SetProgLen(ri,x) ri->u.proglen = x
#else
#define ProgLen(ri) ri->u.offsets[0]
#define SetProgLen(ri,x) ri->u.offsets[0] = x
#define Set_Node_Offset_To_R(node,byte) STMT_START { \
if (! SIZE_ONLY) { \
MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
__LINE__, (int)(node), (int)(byte))); \
if((node) < 0) { \
Perl_croak(aTHX_ "value of node is %d in Offset macro", \
(int)(node)); \
} else { \
RExC_offsets[2*(node)-1] = (byte); \
} \
} \
} STMT_END
#define Set_Node_Offset(node,byte) \
Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
#define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
#define Set_Node_Length_To_R(node,len) STMT_START { \
if (! SIZE_ONLY) { \
MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
__LINE__, (int)(node), (int)(len))); \
if((node) < 0) { \
Perl_croak(aTHX_ "value of node is %d in Length macro", \
(int)(node)); \
} else { \
RExC_offsets[2*(node)] = (len); \
} \
} \
} STMT_END
#define Set_Node_Length(node,len) \
Set_Node_Length_To_R((node)-RExC_emit_start, len)
#define Set_Node_Cur_Length(node, start) \
Set_Node_Length(node, RExC_parse - start)
/* Get offsets and lengths */
#define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
#define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
#define Set_Node_Offset_Length(node,offset,len) STMT_START { \
Set_Node_Offset_To_R((node)-RExC_emit_start, (offset)); \
Set_Node_Length_To_R((node)-RExC_emit_start, (len)); \
} STMT_END
#endif
#if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
#define EXPERIMENTAL_INPLACESCAN
#endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
#ifdef DEBUGGING
int
Perl_re_printf(pTHX_ const char *fmt, ...)
{
va_list ap;
int result;
PerlIO *f= Perl_debug_log;
PERL_ARGS_ASSERT_RE_PRINTF;
va_start(ap, fmt);
result = PerlIO_vprintf(f, fmt, ap);
va_end(ap);
return result;
}
int
Perl_re_indentf(pTHX_ const char *fmt, U32 depth, ...)
{
va_list ap;
int result;
PerlIO *f= Perl_debug_log;
PERL_ARGS_ASSERT_RE_INDENTF;
va_start(ap, depth);
PerlIO_printf(f, "%*s", ( (int)depth % 20 ) * 2, "");
result = PerlIO_vprintf(f, fmt, ap);
va_end(ap);
return result;
}
#endif /* DEBUGGING */
#define DEBUG_RExC_seen() \
DEBUG_OPTIMISE_MORE_r({ \
Perl_re_printf( aTHX_ "RExC_seen: "); \
\
if (RExC_seen & REG_ZERO_LEN_SEEN) \
Perl_re_printf( aTHX_ "REG_ZERO_LEN_SEEN "); \
\
if (RExC_seen & REG_LOOKBEHIND_SEEN) \
Perl_re_printf( aTHX_ "REG_LOOKBEHIND_SEEN "); \
\
if (RExC_seen & REG_GPOS_SEEN) \
Perl_re_printf( aTHX_ "REG_GPOS_SEEN "); \
\
if (RExC_seen & REG_RECURSE_SEEN) \
Perl_re_printf( aTHX_ "REG_RECURSE_SEEN "); \
\
if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN) \
Perl_re_printf( aTHX_ "REG_TOP_LEVEL_BRANCHES_SEEN "); \
\
if (RExC_seen & REG_VERBARG_SEEN) \
Perl_re_printf( aTHX_ "REG_VERBARG_SEEN "); \
\
if (RExC_seen & REG_CUTGROUP_SEEN) \
Perl_re_printf( aTHX_ "REG_CUTGROUP_SEEN "); \
\
if (RExC_seen & REG_RUN_ON_COMMENT_SEEN) \
Perl_re_printf( aTHX_ "REG_RUN_ON_COMMENT_SEEN "); \
\
if (RExC_seen & REG_UNFOLDED_MULTI_SEEN) \
Perl_re_printf( aTHX_ "REG_UNFOLDED_MULTI_SEEN "); \
\
if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) \
Perl_re_printf( aTHX_ "REG_UNBOUNDED_QUANTIFIER_SEEN "); \
\
Perl_re_printf( aTHX_ "\n"); \
});
#define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
if ((flags) & flag) Perl_re_printf( aTHX_ "%s ", #flag)
#ifdef DEBUGGING
static void
S_debug_show_study_flags(pTHX_ U32 flags, const char *open_str,
const char *close_str)
{
if (!flags)
return;
Perl_re_printf( aTHX_ "%s", open_str);
DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_SEOL);
DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_MEOL);
DEBUG_SHOW_STUDY_FLAG(flags, SF_IS_INF);
DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_PAR);
DEBUG_SHOW_STUDY_FLAG(flags, SF_IN_PAR);
DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_EVAL);
DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_SUBSTR);
DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_AND);
DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_OR);
DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS);
DEBUG_SHOW_STUDY_FLAG(flags, SCF_WHILEM_VISITED_POS);
DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_RESTUDY);
DEBUG_SHOW_STUDY_FLAG(flags, SCF_SEEN_ACCEPT);
DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_DOING_RESTUDY);
DEBUG_SHOW_STUDY_FLAG(flags, SCF_IN_DEFINE);
Perl_re_printf( aTHX_ "%s", close_str);
}
static void
S_debug_studydata(pTHX_ const char *where, scan_data_t *data,
U32 depth, int is_inf)
{
GET_RE_DEBUG_FLAGS_DECL;
DEBUG_OPTIMISE_MORE_r({
if (!data)
return;
Perl_re_indentf(aTHX_ "%s: Pos:%" IVdf "/%" IVdf " Flags: 0x%" UVXf,
depth,
where,
(IV)data->pos_min,
(IV)data->pos_delta,
(UV)data->flags
);
S_debug_show_study_flags(aTHX_ data->flags," [","]");
Perl_re_printf( aTHX_
" Whilem_c: %" IVdf " Lcp: %" IVdf " %s",
(IV)data->whilem_c,
(IV)(data->last_closep ? *((data)->last_closep) : -1),
is_inf ? "INF " : ""
);
if (data->last_found) {
int i;
Perl_re_printf(aTHX_
"Last:'%s' %" IVdf ":%" IVdf "/%" IVdf,
SvPVX_const(data->last_found),
(IV)data->last_end,
(IV)data->last_start_min,
(IV)data->last_start_max
);
for (i = 0; i < 2; i++) {
Perl_re_printf(aTHX_
" %s%s: '%s' @ %" IVdf "/%" IVdf,
data->cur_is_floating == i ? "*" : "",
i ? "Float" : "Fixed",
SvPVX_const(data->substrs[i].str),
(IV)data->substrs[i].min_offset,
(IV)data->substrs[i].max_offset
);
S_debug_show_study_flags(aTHX_ data->substrs[i].flags," [","]");
}
}
Perl_re_printf( aTHX_ "\n");
});
}
static void
S_debug_peep(pTHX_ const char *str, const RExC_state_t *pRExC_state,
regnode *scan, U32 depth, U32 flags)
{
GET_RE_DEBUG_FLAGS_DECL;
DEBUG_OPTIMISE_r({
regnode *Next;
if (!scan)
return;
Next = regnext(scan);
regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
Perl_re_indentf( aTHX_ "%s>%3d: %s (%d)",
depth,
str,
REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),
Next ? (REG_NODE_NUM(Next)) : 0 );
S_debug_show_study_flags(aTHX_ flags," [ ","]");
Perl_re_printf( aTHX_ "\n");
});
}
# define DEBUG_STUDYDATA(where, data, depth, is_inf) \
S_debug_studydata(aTHX_ where, data, depth, is_inf)
# define DEBUG_PEEP(str, scan, depth, flags) \
S_debug_peep(aTHX_ str, pRExC_state, scan, depth, flags)
#else
# define DEBUG_STUDYDATA(where, data, depth, is_inf) NOOP
# define DEBUG_PEEP(str, scan, depth, flags) NOOP
#endif
/* =========================================================
* BEGIN edit_distance stuff.
*
* This calculates how many single character changes of any type are needed to
* transform a string into another one. It is taken from version 3.1 of
*
* https://metacpan.org/pod/Text::Levenshtein::Damerau::XS
*/
/* Our unsorted dictionary linked list. */
/* Note we use UVs, not chars. */
struct dictionary{
UV key;
UV value;
struct dictionary* next;
};
typedef struct dictionary item;
PERL_STATIC_INLINE item*
push(UV key,item* curr)
{
item* head;
Newx(head, 1, item);
head->key = key;
head->value = 0;
head->next = curr;
return head;
}
PERL_STATIC_INLINE item*
find(item* head, UV key)
{
item* iterator = head;
while (iterator){
if (iterator->key == key){
return iterator;
}
iterator = iterator->next;
}
return NULL;
}
PERL_STATIC_INLINE item*
uniquePush(item* head,UV key)
{
item* iterator = head;
while (iterator){
if (iterator->key == key) {
return head;
}
iterator = iterator->next;
}
return push(key,head);
}
PERL_STATIC_INLINE void
dict_free(item* head)
{
item* iterator = head;
while (iterator) {
item* temp = iterator;
iterator = iterator->next;
Safefree(temp);
}
head = NULL;
}
/* End of Dictionary Stuff */
/* All calculations/work are done here */
STATIC int
S_edit_distance(const UV* src,
const UV* tgt,
const STRLEN x, /* length of src[] */
const STRLEN y, /* length of tgt[] */
const SSize_t maxDistance
)
{
item *head = NULL;
UV swapCount,swapScore,targetCharCount,i,j;
UV *scores;
UV score_ceil = x + y;
PERL_ARGS_ASSERT_EDIT_DISTANCE;
/* intialize matrix start values */
Newx(scores, ( (x + 2) * (y + 2)), UV);
scores[0] = score_ceil;
scores[1 * (y + 2) + 0] = score_ceil;
scores[0 * (y + 2) + 1] = score_ceil;
scores[1 * (y + 2) + 1] = 0;
head = uniquePush(uniquePush(head,src[0]),tgt[0]);
/* work loops */
/* i = src index */
/* j = tgt index */
for (i=1;i<=x;i++) {
if (i < x)
head = uniquePush(head,src[i]);
scores[(i+1) * (y + 2) + 1] = i;
scores[(i+1) * (y + 2) + 0] = score_ceil;
swapCount = 0;
for (j=1;j<=y;j++) {
if (i == 1) {
if(j < y)
head = uniquePush(head,tgt[j]);
scores[1 * (y + 2) + (j + 1)] = j;
scores[0 * (y + 2) + (j + 1)] = score_ceil;
}
targetCharCount = find(head,tgt[j-1])->value;
swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount;
if (src[i-1] != tgt[j-1]){
scores[(i+1) * (y + 2) + (j + 1)] = MIN(swapScore,(MIN(scores[i * (y + 2) + j], MIN(scores[(i+1) * (y + 2) + j], scores[i * (y + 2) + (j + 1)])) + 1));
}
else {
swapCount = j;
scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore);
}
}
find(head,src[i-1])->value = i;
}
{
IV score = scores[(x+1) * (y + 2) + (y + 1)];
dict_free(head);
Safefree(scores);
return (maxDistance != 0 && maxDistance < score)?(-1):score;
}
}
/* END of edit_distance() stuff
* ========================================================= */
/* is c a control character for which we have a mnemonic? */
#define isMNEMONIC_CNTRL(c) _IS_MNEMONIC_CNTRL_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
STATIC const char *
S_cntrl_to_mnemonic(const U8 c)
{
/* Returns the mnemonic string that represents character 'c', if one
* exists; NULL otherwise. The only ones that exist for the purposes of
* this routine are a few control characters */
switch (c) {
case '\a': return "\\a";
case '\b': return "\\b";
case ESC_NATIVE: return "\\e";
case '\f': return "\\f";
case '\n': return "\\n";
case '\r': return "\\r";
case '\t': return "\\t";
}
return NULL;
}
/* Mark that we cannot extend a found fixed substring at this point.
Update the longest found anchored substring or the longest found
floating substrings if needed. */
STATIC void
S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
SSize_t *minlenp, int is_inf)
{
const STRLEN l = CHR_SVLEN(data->last_found);
SV * const longest_sv = data->substrs[data->cur_is_floating].str;
const STRLEN old_l = CHR_SVLEN(longest_sv);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_SCAN_COMMIT;
if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
const U8 i = data->cur_is_floating;
SvSetMagicSV(longest_sv, data->last_found);
data->substrs[i].min_offset = l ? data->last_start_min : data->pos_min;
if (!i) /* fixed */
data->substrs[0].max_offset = data->substrs[0].min_offset;
else { /* float */
data->substrs[1].max_offset = (l
? data->last_start_max
: (data->pos_delta > SSize_t_MAX - data->pos_min
? SSize_t_MAX
: data->pos_min + data->pos_delta));
if (is_inf
|| (STRLEN)data->substrs[1].max_offset > (STRLEN)SSize_t_MAX)
data->substrs[1].max_offset = SSize_t_MAX;
}
if (data->flags & SF_BEFORE_EOL)
data->substrs[i].flags |= (data->flags & SF_BEFORE_EOL);
else
data->substrs[i].flags &= ~SF_BEFORE_EOL;
data->substrs[i].minlenp = minlenp;
data->substrs[i].lookbehind = 0;
}
SvCUR_set(data->last_found, 0);
{
SV * const sv = data->last_found;
if (SvUTF8(sv) && SvMAGICAL(sv)) {
MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
if (mg)
mg->mg_len = 0;
}
}
data->last_end = -1;
data->flags &= ~SF_BEFORE_EOL;
DEBUG_STUDYDATA("commit", data, 0, is_inf);
}
/* An SSC is just a regnode_charclass_posix with an extra field: the inversion
* list that describes which code points it matches */
STATIC void
S_ssc_anything(pTHX_ regnode_ssc *ssc)
{
/* Set the SSC 'ssc' to match an empty string or any code point */
PERL_ARGS_ASSERT_SSC_ANYTHING;
assert(is_ANYOF_SYNTHETIC(ssc));
/* mortalize so won't leak */
ssc->invlist = sv_2mortal(_add_range_to_invlist(NULL, 0, UV_MAX));
ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING; /* Plus matches empty */
}
STATIC int
S_ssc_is_anything(const regnode_ssc *ssc)
{
/* Returns TRUE if the SSC 'ssc' can match the empty string and any code
* point; FALSE otherwise. Thus, this is used to see if using 'ssc' buys
* us anything: if the function returns TRUE, 'ssc' hasn't been restricted
* in any way, so there's no point in using it */
UV start, end;
bool ret;
PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
assert(is_ANYOF_SYNTHETIC(ssc));
if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
return FALSE;
}
/* See if the list consists solely of the range 0 - Infinity */
invlist_iterinit(ssc->invlist);
ret = invlist_iternext(ssc->invlist, &start, &end)
&& start == 0
&& end == UV_MAX;
invlist_iterfinish(ssc->invlist);
if (ret) {
return TRUE;
}
/* If e.g., both \w and \W are set, matches everything */
if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
int i;
for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
return TRUE;
}
}
}
return FALSE;
}
STATIC void
S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
{
/* Initializes the SSC 'ssc'. This includes setting it to match an empty
* string, any code point, or any posix class under locale */
PERL_ARGS_ASSERT_SSC_INIT;
Zero(ssc, 1, regnode_ssc);
set_ANYOF_SYNTHETIC(ssc);
ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
ssc_anything(ssc);
/* If any portion of the regex is to operate under locale rules that aren't
* fully known at compile time, initialization includes it. The reason
* this isn't done for all regexes is that the optimizer was written under
* the assumption that locale was all-or-nothing. Given the complexity and
* lack of documentation in the optimizer, and that there are inadequate
* test cases for locale, many parts of it may not work properly, it is
* safest to avoid locale unless necessary. */
if (RExC_contains_locale) {
ANYOF_POSIXL_SETALL(ssc);
}
else {
ANYOF_POSIXL_ZERO(ssc);
}
}
STATIC int
S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
const regnode_ssc *ssc)
{
/* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
* to the list of code points matched, and locale posix classes; hence does
* not check its flags) */
UV start, end;
bool ret;
PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
assert(is_ANYOF_SYNTHETIC(ssc));
invlist_iterinit(ssc->invlist);
ret = invlist_iternext(ssc->invlist, &start, &end)
&& start == 0
&& end == UV_MAX;
invlist_iterfinish(ssc->invlist);
if (! ret) {
return FALSE;
}
if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
return FALSE;
}
return TRUE;
}
STATIC SV*
S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
const regnode_charclass* const node)
{
/* Returns a mortal inversion list defining which code points are matched
* by 'node', which is of type ANYOF. Handles complementing the result if
* appropriate. If some code points aren't knowable at this time, the
* returned list must, and will, contain every code point that is a
* possibility. */
SV* invlist = NULL;
SV* only_utf8_locale_invlist = NULL;
unsigned int i;
const U32 n = ARG(node);
bool new_node_has_latin1 = FALSE;
PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
/* Look at the data structure created by S_set_ANYOF_arg() */
if (n != ANYOF_ONLY_HAS_BITMAP) {
SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
AV * const av = MUTABLE_AV(SvRV(rv));
SV **const ary = AvARRAY(av);
assert(RExC_rxi->data->what[n] == 's');
if (ary[1] && ary[1] != &PL_sv_undef) { /* Has compile-time swash */
invlist = sv_2mortal(invlist_clone(_get_swash_invlist(ary[1])));
}
else if (ary[0] && ary[0] != &PL_sv_undef) {
/* Here, no compile-time swash, and there are things that won't be
* known until runtime -- we have to assume it could be anything */
invlist = sv_2mortal(_new_invlist(1));
return _add_range_to_invlist(invlist, 0, UV_MAX);
}
else if (ary[3] && ary[3] != &PL_sv_undef) {
/* Here no compile-time swash, and no run-time only data. Use the
* node's inversion list */
invlist = sv_2mortal(invlist_clone(ary[3]));
}
/* Get the code points valid only under UTF-8 locales */
if ((ANYOF_FLAGS(node) & ANYOFL_FOLD)
&& ary[2] && ary[2] != &PL_sv_undef)
{
only_utf8_locale_invlist = ary[2];
}
}
if (! invlist) {
invlist = sv_2mortal(_new_invlist(0));
}
/* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS
* code points, and an inversion list for the others, but if there are code
* points that should match only conditionally on the target string being
* UTF-8, those are placed in the inversion list, and not the bitmap.
* Since there are circumstances under which they could match, they are
* included in the SSC. But if the ANYOF node is to be inverted, we have
* to exclude them here, so that when we invert below, the end result
* actually does include them. (Think about "\xe0" =~ /[^\xc0]/di;). We
* have to do this here before we add the unconditionally matched code
* points */
if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
_invlist_intersection_complement_2nd(invlist,
PL_UpperLatin1,
&invlist);
}
/* Add in the points from the bit map */
for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
if (ANYOF_BITMAP_TEST(node, i)) {
unsigned int start = i++;
for (; i < NUM_ANYOF_CODE_POINTS && ANYOF_BITMAP_TEST(node, i); ++i) {
/* empty */
}
invlist = _add_range_to_invlist(invlist, start, i-1);
new_node_has_latin1 = TRUE;
}
}
/* If this can match all upper Latin1 code points, have to add them
* as well. But don't add them if inverting, as when that gets done below,
* it would exclude all these characters, including the ones it shouldn't
* that were added just above */
if (! (ANYOF_FLAGS(node) & ANYOF_INVERT) && OP(node) == ANYOFD
&& (ANYOF_FLAGS(node) & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
{
_invlist_union(invlist, PL_UpperLatin1, &invlist);
}
/* Similarly for these */
if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
_invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
}
if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
_invlist_invert(invlist);
}
else if (new_node_has_latin1 && ANYOF_FLAGS(node) & ANYOFL_FOLD) {
/* Under /li, any 0-255 could fold to any other 0-255, depending on the
* locale. We can skip this if there are no 0-255 at all. */
_invlist_union(invlist, PL_Latin1, &invlist);
}
/* Similarly add the UTF-8 locale possible matches. These have to be
* deferred until after the non-UTF-8 locale ones are taken care of just
* above, or it leads to wrong results under ANYOF_INVERT */
if (only_utf8_locale_invlist) {
_invlist_union_maybe_complement_2nd(invlist,
only_utf8_locale_invlist,
ANYOF_FLAGS(node) & ANYOF_INVERT,
&invlist);
}
return invlist;
}
/* These two functions currently do the exact same thing */
#define ssc_init_zero ssc_init
#define ssc_add_cp(ssc, cp) ssc_add_range((ssc), (cp), (cp))
#define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
/* 'AND' a given class with another one. Can create false positives. 'ssc'
* should not be inverted. 'and_with->flags & ANYOF_MATCHES_POSIXL' should be
* 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
STATIC void
S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
const regnode_charclass *and_with)
{
/* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
* another SSC or a regular ANYOF class. Can create false positives. */
SV* anded_cp_list;
U8 anded_flags;
PERL_ARGS_ASSERT_SSC_AND;
assert(is_ANYOF_SYNTHETIC(ssc));
/* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
* the code point inversion list and just the relevant flags */
if (is_ANYOF_SYNTHETIC(and_with)) {
anded_cp_list = ((regnode_ssc *)and_with)->invlist;
anded_flags = ANYOF_FLAGS(and_with);
/* XXX This is a kludge around what appears to be deficiencies in the
* optimizer. If we make S_ssc_anything() add in the WARN_SUPER flag,
* there are paths through the optimizer where it doesn't get weeded
* out when it should. And if we don't make some extra provision for
* it like the code just below, it doesn't get added when it should.
* This solution is to add it only when AND'ing, which is here, and
* only when what is being AND'ed is the pristine, original node
* matching anything. Thus it is like adding it to ssc_anything() but
* only when the result is to be AND'ed. Probably the same solution
* could be adopted for the same problem we have with /l matching,
* which is solved differently in S_ssc_init(), and that would lead to
* fewer false positives than that solution has. But if this solution
* creates bugs, the consequences are only that a warning isn't raised
* that should be; while the consequences for having /l bugs is
* incorrect matches */
if (ssc_is_anything((regnode_ssc *)and_with)) {
anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
}
}
else {
anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
if (OP(and_with) == ANYOFD) {
anded_flags = ANYOF_FLAGS(and_with) & ANYOF_COMMON_FLAGS;
}
else {
anded_flags = ANYOF_FLAGS(and_with)
&( ANYOF_COMMON_FLAGS
|ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
|ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(and_with))) {
anded_flags &=
ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
}
}
}
ANYOF_FLAGS(ssc) &= anded_flags;
/* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
* C2 is the list of code points in 'and-with'; P2, its posix classes.
* 'and_with' may be inverted. When not inverted, we have the situation of
* computing:
* (C1 | P1) & (C2 | P2)
* = (C1 & (C2 | P2)) | (P1 & (C2 | P2))
* = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
* <= ((C1 & C2) | P2)) | ( P1 | (P1 & P2))
* <= ((C1 & C2) | P1 | P2)
* Alternatively, the last few steps could be:
* = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
* <= ((C1 & C2) | C1 ) | ( C2 | (P1 & P2))
* <= (C1 | C2 | (P1 & P2))
* We favor the second approach if either P1 or P2 is non-empty. This is
* because these components are a barrier to doing optimizations, as what
* they match cannot be known until the moment of matching as they are
* dependent on the current locale, 'AND"ing them likely will reduce or
* eliminate them.
* But we can do better if we know that C1,P1 are in their initial state (a
* frequent occurrence), each matching everything:
* (<everything>) & (C2 | P2) = C2 | P2
* Similarly, if C2,P2 are in their initial state (again a frequent
* occurrence), the result is a no-op
* (C1 | P1) & (<everything>) = C1 | P1
*
* Inverted, we have
* (C1 | P1) & ~(C2 | P2) = (C1 | P1) & (~C2 & ~P2)
* = (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
* <= (C1 & ~C2) | (P1 & ~P2)
* */
if ((ANYOF_FLAGS(and_with) & ANYOF_INVERT)
&& ! is_ANYOF_SYNTHETIC(and_with))
{
unsigned int i;
ssc_intersection(ssc,
anded_cp_list,
FALSE /* Has already been inverted */
);
/* If either P1 or P2 is empty, the intersection will be also; can skip
* the loop */
if (! (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL)) {
ANYOF_POSIXL_ZERO(ssc);
}
else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
/* Note that the Posix class component P from 'and_with' actually
* looks like:
* P = Pa | Pb | ... | Pn
* where each component is one posix class, such as in [\w\s].
* Thus
* ~P = ~(Pa | Pb | ... | Pn)
* = ~Pa & ~Pb & ... & ~Pn
* <= ~Pa | ~Pb | ... | ~Pn
* The last is something we can easily calculate, but unfortunately
* is likely to have many false positives. We could do better
* in some (but certainly not all) instances if two classes in
* P have known relationships. For example
* :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
* So
* :lower: & :print: = :lower:
* And similarly for classes that must be disjoint. For example,
* since \s and \w can have no elements in common based on rules in
* the POSIX standard,
* \w & ^\S = nothing
* Unfortunately, some vendor locales do not meet the Posix
* standard, in particular almost everything by Microsoft.
* The loop below just changes e.g., \w into \W and vice versa */
regnode_charclass_posixl temp;
int add = 1; /* To calculate the index of the complement */
Zero(&temp, 1, regnode_charclass_posixl);
ANYOF_POSIXL_ZERO(&temp);
for (i = 0; i < ANYOF_MAX; i++) {
assert(i % 2 != 0
|| ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
|| ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
ANYOF_POSIXL_SET(&temp, i + add);
}
add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
}
ANYOF_POSIXL_AND(&temp, ssc);
} /* else ssc already has no posixes */
} /* else: Not inverted. This routine is a no-op if 'and_with' is an SSC
in its initial state */
else if (! is_ANYOF_SYNTHETIC(and_with)
|| ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
{
/* But if 'ssc' is in its initial state, the result is just 'and_with';
* copy it over 'ssc' */
if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
if (is_ANYOF_SYNTHETIC(and_with)) {
StructCopy(and_with, ssc, regnode_ssc);
}
else {
ssc->invlist = anded_cp_list;
ANYOF_POSIXL_ZERO(ssc);
if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
}
}
}
else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
|| (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL))
{
/* One or the other of P1, P2 is non-empty. */
if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
}
ssc_union(ssc, anded_cp_list, FALSE);
}
else { /* P1 = P2 = empty */
ssc_intersection(ssc, anded_cp_list, FALSE);
}
}
}
STATIC void
S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
const regnode_charclass *or_with)
{
/* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
* another SSC or a regular ANYOF class. Can create false positives if
* 'or_with' is to be inverted. */
SV* ored_cp_list;
U8 ored_flags;
PERL_ARGS_ASSERT_SSC_OR;
assert(is_ANYOF_SYNTHETIC(ssc));
/* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
* the code point inversion list and just the relevant flags */
if (is_ANYOF_SYNTHETIC(or_with)) {
ored_cp_list = ((regnode_ssc*) or_with)->invlist;
ored_flags = ANYOF_FLAGS(or_with);
}
else {
ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
ored_flags = ANYOF_FLAGS(or_with) & ANYOF_COMMON_FLAGS;
if (OP(or_with) != ANYOFD) {
ored_flags
|= ANYOF_FLAGS(or_with)
& ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
|ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(or_with))) {
ored_flags |=
ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
}
}
}
ANYOF_FLAGS(ssc) |= ored_flags;
/* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
* C2 is the list of code points in 'or-with'; P2, its posix classes.
* 'or_with' may be inverted. When not inverted, we have the simple
* situation of computing:
* (C1 | P1) | (C2 | P2) = (C1 | C2) | (P1 | P2)
* If P1|P2 yields a situation with both a class and its complement are
* set, like having both \w and \W, this matches all code points, and we
* can delete these from the P component of the ssc going forward. XXX We
* might be able to delete all the P components, but I (khw) am not certain
* about this, and it is better to be safe.
*
* Inverted, we have
* (C1 | P1) | ~(C2 | P2) = (C1 | P1) | (~C2 & ~P2)
* <= (C1 | P1) | ~C2
* <= (C1 | ~C2) | P1
* (which results in actually simpler code than the non-inverted case)
* */
if ((ANYOF_FLAGS(or_with) & ANYOF_INVERT)
&& ! is_ANYOF_SYNTHETIC(or_with))
{
/* We ignore P2, leaving P1 going forward */
} /* else Not inverted */
else if (ANYOF_FLAGS(or_with) & ANYOF_MATCHES_POSIXL) {
ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
unsigned int i;
for (i = 0; i < ANYOF_MAX; i += 2) {
if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
{
ssc_match_all_cp(ssc);
ANYOF_POSIXL_CLEAR(ssc, i);
ANYOF_POSIXL_CLEAR(ssc, i+1);
}
}
}
}
ssc_union(ssc,
ored_cp_list,
FALSE /* Already has been inverted */
);
}
PERL_STATIC_INLINE void
S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
{
PERL_ARGS_ASSERT_SSC_UNION;
assert(is_ANYOF_SYNTHETIC(ssc));
_invlist_union_maybe_complement_2nd(ssc->invlist,
invlist,
invert2nd,
&ssc->invlist);
}
PERL_STATIC_INLINE void
S_ssc_intersection(pTHX_ regnode_ssc *ssc,
SV* const invlist,
const bool invert2nd)
{
PERL_ARGS_ASSERT_SSC_INTERSECTION;
assert(is_ANYOF_SYNTHETIC(ssc));
_invlist_intersection_maybe_complement_2nd(ssc->invlist,
invlist,
invert2nd,
&ssc->invlist);
}
PERL_STATIC_INLINE void
S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
{
PERL_ARGS_ASSERT_SSC_ADD_RANGE;
assert(is_ANYOF_SYNTHETIC(ssc));
ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
}
PERL_STATIC_INLINE void
S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
{
/* AND just the single code point 'cp' into the SSC 'ssc' */
SV* cp_list = _new_invlist(2);
PERL_ARGS_ASSERT_SSC_CP_AND;
assert(is_ANYOF_SYNTHETIC(ssc));
cp_list = add_cp_to_invlist(cp_list, cp);
ssc_intersection(ssc, cp_list,
FALSE /* Not inverted */
);
SvREFCNT_dec_NN(cp_list);
}
PERL_STATIC_INLINE void
S_ssc_clear_locale(regnode_ssc *ssc)
{
/* Set the SSC 'ssc' to not match any locale things */
PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
assert(is_ANYOF_SYNTHETIC(ssc));
ANYOF_POSIXL_ZERO(ssc);
ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
}
#define NON_OTHER_COUNT NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
STATIC bool
S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
{
/* The synthetic start class is used to hopefully quickly winnow down
* places where a pattern could start a match in the target string. If it
* doesn't really narrow things down that much, there isn't much point to
* having the overhead of using it. This function uses some very crude
* heuristics to decide if to use the ssc or not.
*
* It returns TRUE if 'ssc' rules out more than half what it considers to
* be the "likely" possible matches, but of course it doesn't know what the
* actual things being matched are going to be; these are only guesses
*
* For /l matches, it assumes that the only likely matches are going to be
* in the 0-255 range, uniformly distributed, so half of that is 127
* For /a and /d matches, it assumes that the likely matches will be just
* the ASCII range, so half of that is 63
* For /u and there isn't anything matching above the Latin1 range, it
* assumes that that is the only range likely to be matched, and uses
* half that as the cut-off: 127. If anything matches above Latin1,
* it assumes that all of Unicode could match (uniformly), except for
* non-Unicode code points and things in the General Category "Other"
* (unassigned, private use, surrogates, controls and formats). This
* is a much large number. */
U32 count = 0; /* Running total of number of code points matched by
'ssc' */
UV start, end; /* Start and end points of current range in inversion
list */
const U32 max_code_points = (LOC)
? 256
: (( ! UNI_SEMANTICS
|| invlist_highest(ssc->invlist) < 256)
? 128
: NON_OTHER_COUNT);
const U32 max_match = max_code_points / 2;
PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
invlist_iterinit(ssc->invlist);
while (invlist_iternext(ssc->invlist, &start, &end)) {
if (start >= max_code_points) {
break;
}
end = MIN(end, max_code_points - 1);
count += end - start + 1;
if (count >= max_match) {
invlist_iterfinish(ssc->invlist);
return FALSE;
}
}
return TRUE;
}
STATIC void
S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
{
/* The inversion list in the SSC is marked mortal; now we need a more
* permanent copy, which is stored the same way that is done in a regular
* ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
* map */
SV* invlist = invlist_clone(ssc->invlist);
PERL_ARGS_ASSERT_SSC_FINALIZE;
assert(is_ANYOF_SYNTHETIC(ssc));
/* The code in this file assumes that all but these flags aren't relevant
* to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
* by the time we reach here */
assert(! (ANYOF_FLAGS(ssc)
& ~( ANYOF_COMMON_FLAGS
|ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
|ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist,
NULL, NULL, NULL, FALSE);
/* Make sure is clone-safe */
ssc->invlist = NULL;
if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
}
if (RExC_contains_locale) {
OP(ssc) = ANYOFL;
}
assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
}
#define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
#define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
#define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
#define TRIE_LIST_USED(idx) ( trie->states[state].trans.list \
? (TRIE_LIST_CUR( idx ) - 1) \
: 0 )
#ifdef DEBUGGING
/*
dump_trie(trie,widecharmap,revcharmap)
dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
These routines dump out a trie in a somewhat readable format.
The _interim_ variants are used for debugging the interim
tables that are used to generate the final compressed
representation which is what dump_trie expects.
Part of the reason for their existence is to provide a form
of documentation as to how the different representations function.
*/
/*
Dumps the final compressed table form of the trie to Perl_debug_log.
Used for debugging make_trie().
*/
STATIC void
S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
AV *revcharmap, U32 depth)
{
U32 state;
SV *sv=sv_newmortal();
int colwidth= widecharmap ? 6 : 4;
U16 word;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_DUMP_TRIE;
Perl_re_indentf( aTHX_ "Char : %-6s%-6s%-4s ",
depth+1, "Match","Base","Ofs" );
for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
SV ** const tmp = av_fetch( revcharmap, state, 0);
if ( tmp ) {
Perl_re_printf( aTHX_ "%*s",
colwidth,
pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
PL_colors[0], PL_colors[1],
(SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
PERL_PV_ESCAPE_FIRSTCHAR
)
);
}
}
Perl_re_printf( aTHX_ "\n");
Perl_re_indentf( aTHX_ "State|-----------------------", depth+1);
for( state = 0 ; state < trie->uniquecharcount ; state++ )
Perl_re_printf( aTHX_ "%.*s", colwidth, "--------");
Perl_re_printf( aTHX_ "\n");
for( state = 1 ; state < trie->statecount ; state++ ) {
const U32 base = trie->states[ state ].trans.base;
Perl_re_indentf( aTHX_ "#%4" UVXf "|", depth+1, (UV)state);
if ( trie->states[ state ].wordnum ) {
Perl_re_printf( aTHX_ " W%4X", trie->states[ state ].wordnum );
} else {
Perl_re_printf( aTHX_ "%6s", "" );
}
Perl_re_printf( aTHX_ " @%4" UVXf " ", (UV)base );
if ( base ) {
U32 ofs = 0;
while( ( base + ofs < trie->uniquecharcount ) ||
( base + ofs - trie->uniquecharcount < trie->lasttrans
&& trie->trans[ base + ofs - trie->uniquecharcount ].check
!= state))
ofs++;
Perl_re_printf( aTHX_ "+%2" UVXf "[ ", (UV)ofs);
for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
if ( ( base + ofs >= trie->uniquecharcount )
&& ( base + ofs - trie->uniquecharcount
< trie->lasttrans )
&& trie->trans[ base + ofs
- trie->uniquecharcount ].check == state )
{
Perl_re_printf( aTHX_ "%*" UVXf, colwidth,
(UV)trie->trans[ base + ofs - trie->uniquecharcount ].next
);
} else {
Perl_re_printf( aTHX_ "%*s",colwidth," ." );
}
}
Perl_re_printf( aTHX_ "]");
}
Perl_re_printf( aTHX_ "\n" );
}
Perl_re_indentf( aTHX_ "word_info N:(prev,len)=",
depth);
for (word=1; word <= trie->wordcount; word++) {
Perl_re_printf( aTHX_ " %d:(%d,%d)",
(int)word, (int)(trie->wordinfo[word].prev),
(int)(trie->wordinfo[word].len));
}
Perl_re_printf( aTHX_ "\n" );
}
/*
Dumps a fully constructed but uncompressed trie in list form.
List tries normally only are used for construction when the number of
possible chars (trie->uniquecharcount) is very high.
Used for debugging make_trie().
*/
STATIC void
S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
HV *widecharmap, AV *revcharmap, U32 next_alloc,
U32 depth)
{
U32 state;
SV *sv=sv_newmortal();
int colwidth= widecharmap ? 6 : 4;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
/* print out the table precompression. */
Perl_re_indentf( aTHX_ "State :Word | Transition Data\n",
depth+1 );
Perl_re_indentf( aTHX_ "%s",
depth+1, "------:-----+-----------------\n" );
for( state=1 ; state < next_alloc ; state ++ ) {
U16 charid;
Perl_re_indentf( aTHX_ " %4" UVXf " :",
depth+1, (UV)state );
if ( ! trie->states[ state ].wordnum ) {
Perl_re_printf( aTHX_ "%5s| ","");
} else {
Perl_re_printf( aTHX_ "W%4x| ",
trie->states[ state ].wordnum
);
}
for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
SV ** const tmp = av_fetch( revcharmap,
TRIE_LIST_ITEM(state,charid).forid, 0);
if ( tmp ) {
Perl_re_printf( aTHX_ "%*s:%3X=%4" UVXf " | ",
colwidth,
pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
colwidth,
PL_colors[0], PL_colors[1],
(SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
| PERL_PV_ESCAPE_FIRSTCHAR
) ,
TRIE_LIST_ITEM(state,charid).forid,
(UV)TRIE_LIST_ITEM(state,charid).newstate
);
if (!(charid % 10))
Perl_re_printf( aTHX_ "\n%*s| ",
(int)((depth * 2) + 14), "");
}
}
Perl_re_printf( aTHX_ "\n");
}
}
/*
Dumps a fully constructed but uncompressed trie in table form.
This is the normal DFA style state transition table, with a few
twists to facilitate compression later.
Used for debugging make_trie().
*/
STATIC void
S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
HV *widecharmap, AV *revcharmap, U32 next_alloc,
U32 depth)
{
U32 state;
U16 charid;
SV *sv=sv_newmortal();
int colwidth= widecharmap ? 6 : 4;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
/*
print out the table precompression so that we can do a visual check
that they are identical.
*/
Perl_re_indentf( aTHX_ "Char : ", depth+1 );
for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
SV ** const tmp = av_fetch( revcharmap, charid, 0);
if ( tmp ) {
Perl_re_printf( aTHX_ "%*s",
colwidth,
pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
PL_colors[0], PL_colors[1],
(SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
PERL_PV_ESCAPE_FIRSTCHAR
)
);
}
}
Perl_re_printf( aTHX_ "\n");
Perl_re_indentf( aTHX_ "State+-", depth+1 );
for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
Perl_re_printf( aTHX_ "%.*s", colwidth,"--------");
}
Perl_re_printf( aTHX_ "\n" );
for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
Perl_re_indentf( aTHX_ "%4" UVXf " : ",
depth+1,
(UV)TRIE_NODENUM( state ) );
for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
if (v)
Perl_re_printf( aTHX_ "%*" UVXf, colwidth, v );
else
Perl_re_printf( aTHX_ "%*s", colwidth, "." );
}
if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
Perl_re_printf( aTHX_ " (%4" UVXf ")\n",
(UV)trie->trans[ state ].check );
} else {
Perl_re_printf( aTHX_ " (%4" UVXf ") W%4X\n",
(UV)trie->trans[ state ].check,
trie->states[ TRIE_NODENUM( state ) ].wordnum );
}
}
}
#endif
/* make_trie(startbranch,first,last,tail,word_count,flags,depth)
startbranch: the first branch in the whole branch sequence
first : start branch of sequence of branch-exact nodes.
May be the same as startbranch
last : Thing following the last branch.
May be the same as tail.
tail : item following the branch sequence
count : words in the sequence
flags : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
depth : indent depth
Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
A trie is an N'ary tree where the branches are determined by digital
decomposition of the key. IE, at the root node you look up the 1st character and
follow that branch repeat until you find the end of the branches. Nodes can be
marked as "accepting" meaning they represent a complete word. Eg:
/he|she|his|hers/
would convert into the following structure. Numbers represent states, letters
following numbers represent valid transitions on the letter from that state, if
the number is in square brackets it represents an accepting state, otherwise it
will be in parenthesis.
+-h->+-e->[3]-+-r->(8)-+-s->[9]
| |
| (2)
| |
(1) +-i->(6)-+-s->[7]
|
+-s->(3)-+-h->(4)-+-e->[5]
Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
This shows that when matching against the string 'hers' we will begin at state 1
read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
is also accepting. Thus we know that we can match both 'he' and 'hers' with a
single traverse. We store a mapping from accepting to state to which word was
matched, and then when we have multiple possibilities we try to complete the
rest of the regex in the order in which they occurred in the alternation.
The only prior NFA like behaviour that would be changed by the TRIE support is
the silent ignoring of duplicate alternations which are of the form:
/ (DUPE|DUPE) X? (?{ ... }) Y /x
Thus EVAL blocks following a trie may be called a different number of times with
and without the optimisation. With the optimisations dupes will be silently
ignored. This inconsistent behaviour of EVAL type nodes is well established as
the following demonstrates:
'words'=~/(word|word|word)(?{ print $1 })[xyz]/
which prints out 'word' three times, but
'words'=~/(word|word|word)(?{ print $1 })S/
which doesnt print it out at all. This is due to other optimisations kicking in.
Example of what happens on a structural level:
The regexp /(ac|ad|ab)+/ will produce the following debug output:
1: CURLYM[1] {1,32767}(18)
5: BRANCH(8)
6: EXACT <ac>(16)
8: BRANCH(11)
9: EXACT <ad>(16)
11: BRANCH(14)
12: EXACT <ab>(16)
16: SUCCEED(0)
17: NOTHING(18)
18: END(0)
This would be optimizable with startbranch=5, first=5, last=16, tail=16
and should turn into:
1: CURLYM[1] {1,32767}(18)
5: TRIE(16)
[Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
<ac>
<ad>
<ab>
16: SUCCEED(0)
17: NOTHING(18)
18: END(0)
Cases where tail != last would be like /(?foo|bar)baz/:
1: BRANCH(4)
2: EXACT <foo>(8)
4: BRANCH(7)
5: EXACT <bar>(8)
7: TAIL(8)
8: EXACT <baz>(10)
10: END(0)
which would be optimizable with startbranch=1, first=1, last=7, tail=8
and would end up looking like:
1: TRIE(8)
[Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
<foo>
<bar>
7: TAIL(8)
8: EXACT <baz>(10)
10: END(0)
d = uvchr_to_utf8_flags(d, uv, 0);
is the recommended Unicode-aware way of saying
*(d++) = uv;
*/
#define TRIE_STORE_REVCHAR(val) \
STMT_START { \
if (UTF) { \
SV *zlopp = newSV(UTF8_MAXBYTES); \
unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
unsigned const char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
SvCUR_set(zlopp, kapow - flrbbbbb); \
SvPOK_on(zlopp); \
SvUTF8_on(zlopp); \
av_push(revcharmap, zlopp); \
} else { \
char ooooff = (char)val; \
av_push(revcharmap, newSVpvn(&ooooff, 1)); \
} \
} STMT_END
/* This gets the next character from the input, folding it if not already
* folded. */
#define TRIE_READ_CHAR STMT_START { \
wordlen++; \
if ( UTF ) { \
/* if it is UTF then it is either already folded, or does not need \
* folding */ \
uvc = valid_utf8_to_uvchr( (const U8*) uc, &len); \
} \
else if (folder == PL_fold_latin1) { \
/* This folder implies Unicode rules, which in the range expressible \
* by not UTF is the lower case, with the two exceptions, one of \
* which should have been taken care of before calling this */ \
assert(*uc != LATIN_SMALL_LETTER_SHARP_S); \
uvc = toLOWER_L1(*uc); \
if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU; \
len = 1; \
} else { \
/* raw data, will be folded later if needed */ \
uvc = (U32)*uc; \
len = 1; \
} \
} STMT_END
#define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
U32 ging = TRIE_LIST_LEN( state ) * 2; \
Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
TRIE_LIST_LEN( state ) = ging; \
} \
TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
TRIE_LIST_CUR( state )++; \
} STMT_END
#define TRIE_LIST_NEW(state) STMT_START { \
Newx( trie->states[ state ].trans.list, \
4, reg_trie_trans_le ); \
TRIE_LIST_CUR( state ) = 1; \
TRIE_LIST_LEN( state ) = 4; \
} STMT_END
#define TRIE_HANDLE_WORD(state) STMT_START { \
U16 dupe= trie->states[ state ].wordnum; \
regnode * const noper_next = regnext( noper ); \
\
DEBUG_r({ \
/* store the word for dumping */ \
SV* tmp; \
if (OP(noper) != NOTHING) \
tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
else \
tmp = newSVpvn_utf8( "", 0, UTF ); \
av_push( trie_words, tmp ); \
}); \
\
curword++; \
trie->wordinfo[curword].prev = 0; \
trie->wordinfo[curword].len = wordlen; \
trie->wordinfo[curword].accept = state; \
\
if ( noper_next < tail ) { \
if (!trie->jump) \
trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
sizeof(U16) ); \
trie->jump[curword] = (U16)(noper_next - convert); \
if (!jumper) \
jumper = noper_next; \
if (!nextbranch) \
nextbranch= regnext(cur); \
} \
\
if ( dupe ) { \
/* It's a dupe. Pre-insert into the wordinfo[].prev */\
/* chain, so that when the bits of chain are later */\
/* linked together, the dups appear in the chain */\
trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
trie->wordinfo[dupe].prev = curword; \
} else { \
/* we haven't inserted this word yet. */ \
trie->states[ state ].wordnum = curword; \
} \
} STMT_END
#define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
( ( base + charid >= ucharcount \
&& base + charid < ubound \
&& state == trie->trans[ base - ucharcount + charid ].check \
&& trie->trans[ base - ucharcount + charid ].next ) \
? trie->trans[ base - ucharcount + charid ].next \
: ( state==1 ? special : 0 ) \
)
#define TRIE_BITMAP_SET_FOLDED(trie, uvc, folder) \
STMT_START { \
TRIE_BITMAP_SET(trie, uvc); \
/* store the folded codepoint */ \
if ( folder ) \
TRIE_BITMAP_SET(trie, folder[(U8) uvc ]); \
\
if ( !UTF ) { \
/* store first byte of utf8 representation of */ \
/* variant codepoints */ \
if (! UVCHR_IS_INVARIANT(uvc)) { \
TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc)); \
} \
} \
} STMT_END
#define MADE_TRIE 1
#define MADE_JUMP_TRIE 2
#define MADE_EXACT_TRIE 4
STATIC I32
S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
regnode *first, regnode *last, regnode *tail,
U32 word_count, U32 flags, U32 depth)
{
/* first pass, loop through and scan words */
reg_trie_data *trie;
HV *widecharmap = NULL;
AV *revcharmap = newAV();
regnode *cur;
STRLEN len = 0;
UV uvc = 0;
U16 curword = 0;
U32 next_alloc = 0;
regnode *jumper = NULL;
regnode *nextbranch = NULL;
regnode *convert = NULL;
U32 *prev_states; /* temp array mapping each state to previous one */
/* we just use folder as a flag in utf8 */
const U8 * folder = NULL;
/* in the below add_data call we are storing either 'tu' or 'tuaa'
* which stands for one trie structure, one hash, optionally followed
* by two arrays */
#ifdef DEBUGGING
const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuaa"));
AV *trie_words = NULL;
/* along with revcharmap, this only used during construction but both are
* useful during debugging so we store them in the struct when debugging.
*/
#else
const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
STRLEN trie_charcount=0;
#endif
SV *re_trie_maxbuff;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_MAKE_TRIE;
#ifndef DEBUGGING
PERL_UNUSED_ARG(depth);
#endif
switch (flags) {
case EXACT: case EXACTL: break;
case EXACTFA:
case EXACTFU_SS:
case EXACTFU:
case EXACTFLU8: folder = PL_fold_latin1; break;
case EXACTF: folder = PL_fold; break;
default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
}
trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
trie->refcount = 1;
trie->startstate = 1;
trie->wordcount = word_count;
RExC_rxi->data->data[ data_slot ] = (void*)trie;
trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
if (flags == EXACT || flags == EXACTL)
trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
trie->wordcount+1, sizeof(reg_trie_wordinfo));
DEBUG_r({
trie_words = newAV();
});
re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
assert(re_trie_maxbuff);
if (!SvIOK(re_trie_maxbuff)) {
sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
}
DEBUG_TRIE_COMPILE_r({
Perl_re_indentf( aTHX_
"make_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
depth+1,
REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
});
/* Find the node we are going to overwrite */
if ( first == startbranch && OP( last ) != BRANCH ) {
/* whole branch chain */
convert = first;
} else {
/* branch sub-chain */
convert = NEXTOPER( first );
}
/* -- First loop and Setup --
We first traverse the branches and scan each word to determine if it
contains widechars, and how many unique chars there are, this is
important as we have to build a table with at least as many columns as we
have unique chars.
We use an array of integers to represent the character codes 0..255
(trie->charmap) and we use a an HV* to store Unicode characters. We use
the native representation of the character value as the key and IV's for
the coded index.
*TODO* If we keep track of how many times each character is used we can
remap the columns so that the table compression later on is more
efficient in terms of memory by ensuring the most common value is in the
middle and the least common are on the outside. IMO this would be better
than a most to least common mapping as theres a decent chance the most
common letter will share a node with the least common, meaning the node
will not be compressible. With a middle is most common approach the worst
case is when we have the least common nodes twice.
*/
for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
regnode *noper = NEXTOPER( cur );
const U8 *uc;
const U8 *e;
int foldlen = 0;
U32 wordlen = 0; /* required init */
STRLEN minchars = 0;
STRLEN maxchars = 0;
bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
bitmap?*/
if (OP(noper) == NOTHING) {
/* skip past a NOTHING at the start of an alternation
* eg, /(?:)a|(?:b)/ should be the same as /a|b/
*/
regnode *noper_next= regnext(noper);
if (noper_next < tail)
noper= noper_next;
}
if ( noper < tail &&
(
OP(noper) == flags ||
(
flags == EXACTFU &&
OP(noper) == EXACTFU_SS
)
)
) {
uc= (U8*)STRING(noper);
e= uc + STR_LEN(noper);
} else {
trie->minlen= 0;
continue;
}
if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
regardless of encoding */
if (OP( noper ) == EXACTFU_SS) {
/* false positives are ok, so just set this */
TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
}
}
for ( ; uc < e ; uc += len ) { /* Look at each char in the current
branch */
TRIE_CHARCOUNT(trie)++;
TRIE_READ_CHAR;
/* TRIE_READ_CHAR returns the current character, or its fold if /i
* is in effect. Under /i, this character can match itself, or
* anything that folds to it. If not under /i, it can match just
* itself. Most folds are 1-1, for example k, K, and KELVIN SIGN
* all fold to k, and all are single characters. But some folds
* expand to more than one character, so for example LATIN SMALL
* LIGATURE FFI folds to the three character sequence 'ffi'. If
* the string beginning at 'uc' is 'ffi', it could be matched by
* three characters, or just by the one ligature character. (It
* could also be matched by two characters: LATIN SMALL LIGATURE FF
* followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
* (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
* match.) The trie needs to know the minimum and maximum number
* of characters that could match so that it can use size alone to
* quickly reject many match attempts. The max is simple: it is
* the number of folded characters in this branch (since a fold is
* never shorter than what folds to it. */
maxchars++;
/* And the min is equal to the max if not under /i (indicated by
* 'folder' being NULL), or there are no multi-character folds. If
* there is a multi-character fold, the min is incremented just
* once, for the character that folds to the sequence. Each
* character in the sequence needs to be added to the list below of
* characters in the trie, but we count only the first towards the
* min number of characters needed. This is done through the
* variable 'foldlen', which is returned by the macros that look
* for these sequences as the number of bytes the sequence
* occupies. Each time through the loop, we decrement 'foldlen' by
* how many bytes the current char occupies. Only when it reaches
* 0 do we increment 'minchars' or look for another multi-character
* sequence. */
if (folder == NULL) {
minchars++;
}
else if (foldlen > 0) {
foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
}
else {
minchars++;
/* See if *uc is the beginning of a multi-character fold. If
* so, we decrement the length remaining to look at, to account
* for the current character this iteration. (We can use 'uc'
* instead of the fold returned by TRIE_READ_CHAR because for
* non-UTF, the latin1_safe macro is smart enough to account
* for all the unfolded characters, and because for UTF, the
* string will already have been folded earlier in the
* compilation process */
if (UTF) {
if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
foldlen -= UTF8SKIP(uc);
}
}
else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
foldlen--;
}
}
/* The current character (and any potential folds) should be added
* to the possible matching characters for this position in this
* branch */
if ( uvc < 256 ) {
if ( folder ) {
U8 folded= folder[ (U8) uvc ];
if ( !trie->charmap[ folded ] ) {
trie->charmap[ folded ]=( ++trie->uniquecharcount );
TRIE_STORE_REVCHAR( folded );
}
}
if ( !trie->charmap[ uvc ] ) {
trie->charmap[ uvc ]=( ++trie->uniquecharcount );
TRIE_STORE_REVCHAR( uvc );
}
if ( set_bit ) {
/* store the codepoint in the bitmap, and its folded
* equivalent. */
TRIE_BITMAP_SET_FOLDED(trie, uvc, folder);
set_bit = 0; /* We've done our bit :-) */
}
} else {
/* XXX We could come up with the list of code points that fold
* to this using PL_utf8_foldclosures, except not for
* multi-char folds, as there may be multiple combinations
* there that could work, which needs to wait until runtime to
* resolve (The comment about LIGATURE FFI above is such an
* example */
SV** svpp;
if ( !widecharmap )
widecharmap = newHV();
svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
if ( !svpp )
Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%" UVXf, uvc );
if ( !SvTRUE( *svpp ) ) {
sv_setiv( *svpp, ++trie->uniquecharcount );
TRIE_STORE_REVCHAR(uvc);
}
}
} /* end loop through characters in this branch of the trie */
/* We take the min and max for this branch and combine to find the min
* and max for all branches processed so far */
if( cur == first ) {
trie->minlen = minchars;
trie->maxlen = maxchars;
} else if (minchars < trie->minlen) {
trie->minlen = minchars;
} else if (maxchars > trie->maxlen) {
trie->maxlen = maxchars;
}
} /* end first pass */
DEBUG_TRIE_COMPILE_r(
Perl_re_indentf( aTHX_
"TRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
depth+1,
( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
(int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
(int)trie->minlen, (int)trie->maxlen )
);
/*
We now know what we are dealing with in terms of unique chars and
string sizes so we can calculate how much memory a naive
representation using a flat table will take. If it's over a reasonable
limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
conservative but potentially much slower representation using an array
of lists.
At the end we convert both representations into the same compressed
form that will be used in regexec.c for matching with. The latter
is a form that cannot be used to construct with but has memory
properties similar to the list form and access properties similar
to the table form making it both suitable for fast searches and
small enough that its feasable to store for the duration of a program.
See the comment in the code where the compressed table is produced
inplace from the flat tabe representation for an explanation of how
the compression works.
*/
Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
prev_states[1] = 0;
if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
> SvIV(re_trie_maxbuff) )
{
/*
Second Pass -- Array Of Lists Representation
Each state will be represented by a list of charid:state records
(reg_trie_trans_le) the first such element holds the CUR and LEN
points of the allocated array. (See defines above).
We build the initial structure using the lists, and then convert
it into the compressed table form which allows faster lookups
(but cant be modified once converted).
*/
STRLEN transcount = 1;
DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using list compiler\n",
depth+1));
trie->states = (reg_trie_state *)
PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
sizeof(reg_trie_state) );
TRIE_LIST_NEW(1);
next_alloc = 2;
for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
regnode *noper = NEXTOPER( cur );
U32 state = 1; /* required init */
U16 charid = 0; /* sanity init */
U32 wordlen = 0; /* required init */
if (OP(noper) == NOTHING) {
regnode *noper_next= regnext(noper);
if (noper_next < tail)
noper= noper_next;
}
if ( noper < tail && ( OP(noper) == flags || ( flags == EXACTFU && OP(noper) == EXACTFU_SS ) ) ) {
const U8 *uc= (U8*)STRING(noper);
const U8 *e= uc + STR_LEN(noper);
for ( ; uc < e ; uc += len ) {
TRIE_READ_CHAR;
if ( uvc < 256 ) {
charid = trie->charmap[ uvc ];
} else {
SV** const svpp = hv_fetch( widecharmap,
(char*)&uvc,
sizeof( UV ),
0);
if ( !svpp ) {
charid = 0;
} else {
charid=(U16)SvIV( *svpp );
}
}
/* charid is now 0 if we dont know the char read, or
* nonzero if we do */
if ( charid ) {
U16 check;
U32 newstate = 0;
charid--;
if ( !trie->states[ state ].trans.list ) {
TRIE_LIST_NEW( state );
}
for ( check = 1;
check <= TRIE_LIST_USED( state );
check++ )
{
if ( TRIE_LIST_ITEM( state, check ).forid
== charid )
{
newstate = TRIE_LIST_ITEM( state, check ).newstate;
break;
}
}
if ( ! newstate ) {
newstate = next_alloc++;
prev_states[newstate] = state;
TRIE_LIST_PUSH( state, charid, newstate );
transcount++;
}
state = newstate;
} else {
Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
}
}
}
TRIE_HANDLE_WORD(state);
} /* end second pass */
/* next alloc is the NEXT state to be allocated */
trie->statecount = next_alloc;
trie->states = (reg_trie_state *)
PerlMemShared_realloc( trie->states,
next_alloc
* sizeof(reg_trie_state) );
/* and now dump it out before we compress it */
DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
revcharmap, next_alloc,
depth+1)
);
trie->trans = (reg_trie_trans *)
PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
{
U32 state;
U32 tp = 0;
U32 zp = 0;
for( state=1 ; state < next_alloc ; state ++ ) {
U32 base=0;
/*
DEBUG_TRIE_COMPILE_MORE_r(
Perl_re_printf( aTHX_ "tp: %d zp: %d ",tp,zp)
);
*/
if (trie->states[state].trans.list) {
U16 minid=TRIE_LIST_ITEM( state, 1).forid;
U16 maxid=minid;
U16 idx;
for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
if ( forid < minid ) {
minid=forid;
} else if ( forid > maxid ) {
maxid=forid;
}
}
if ( transcount < tp + maxid - minid + 1) {
transcount *= 2;
trie->trans = (reg_trie_trans *)
PerlMemShared_realloc( trie->trans,
transcount
* sizeof(reg_trie_trans) );
Zero( trie->trans + (transcount / 2),
transcount / 2,
reg_trie_trans );
}
base = trie->uniquecharcount + tp - minid;
if ( maxid == minid ) {
U32 set = 0;
for ( ; zp < tp ; zp++ ) {
if ( ! trie->trans[ zp ].next ) {
base = trie->uniquecharcount + zp - minid;
trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
1).newstate;
trie->trans[ zp ].check = state;
set = 1;
break;
}
}
if ( !set ) {
trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
1).newstate;
trie->trans[ tp ].check = state;
tp++;
zp = tp;
}
} else {
for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
const U32 tid = base
- trie->uniquecharcount
+ TRIE_LIST_ITEM( state, idx ).forid;
trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
idx ).newstate;
trie->trans[ tid ].check = state;
}
tp += ( maxid - minid + 1 );
}
Safefree(trie->states[ state ].trans.list);
}
/*
DEBUG_TRIE_COMPILE_MORE_r(
Perl_re_printf( aTHX_ " base: %d\n",base);
);
*/
trie->states[ state ].trans.base=base;
}
trie->lasttrans = tp + 1;
}
} else {
/*
Second Pass -- Flat Table Representation.
we dont use the 0 slot of either trans[] or states[] so we add 1 to
each. We know that we will need Charcount+1 trans at most to store
the data (one row per char at worst case) So we preallocate both
structures assuming worst case.
We then construct the trie using only the .next slots of the entry
structs.
We use the .check field of the first entry of the node temporarily
to make compression both faster and easier by keeping track of how
many non zero fields are in the node.
Since trans are numbered from 1 any 0 pointer in the table is a FAIL
transition.
There are two terms at use here: state as a TRIE_NODEIDX() which is
a number representing the first entry of the node, and state as a
TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
if there are 2 entrys per node. eg:
A B A B
1. 2 4 1. 3 7
2. 0 3 3. 0 5
3. 0 0 5. 0 0
4. 0 0 7. 0 0
The table is internally in the right hand, idx form. However as we
also have to deal with the states array which is indexed by nodenum
we have to use TRIE_NODENUM() to convert.
*/
DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using table compiler\n",
depth+1));
trie->trans = (reg_trie_trans *)
PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
* trie->uniquecharcount + 1,
sizeof(reg_trie_trans) );
trie->states = (reg_trie_state *)
PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
sizeof(reg_trie_state) );
next_alloc = trie->uniquecharcount + 1;
for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
regnode *noper = NEXTOPER( cur );
U32 state = 1; /* required init */
U16 charid = 0; /* sanity init */
U32 accept_state = 0; /* sanity init */
U32 wordlen = 0; /* required init */
if (OP(noper) == NOTHING) {
regnode *noper_next= regnext(noper);
if (noper_next < tail)
noper= noper_next;
}
if ( noper < tail && ( OP(noper) == flags || ( flags == EXACTFU && OP(noper) == EXACTFU_SS ) ) ) {
const U8 *uc= (U8*)STRING(noper);
const U8 *e= uc + STR_LEN(noper);
for ( ; uc < e ; uc += len ) {
TRIE_READ_CHAR;
if ( uvc < 256 ) {
charid = trie->charmap[ uvc ];
} else {
SV* const * const svpp = hv_fetch( widecharmap,
(char*)&uvc,
sizeof( UV ),
0);
charid = svpp ? (U16)SvIV(*svpp) : 0;
}
if ( charid ) {
charid--;
if ( !trie->trans[ state + charid ].next ) {
trie->trans[ state + charid ].next = next_alloc;
trie->trans[ state ].check++;
prev_states[TRIE_NODENUM(next_alloc)]
= TRIE_NODENUM(state);
next_alloc += trie->uniquecharcount;
}
state = trie->trans[ state + charid ].next;
} else {
Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
}
/* charid is now 0 if we dont know the char read, or
* nonzero if we do */
}
}
accept_state = TRIE_NODENUM( state );
TRIE_HANDLE_WORD(accept_state);
} /* end second pass */
/* and now dump it out before we compress it */
DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
revcharmap,
next_alloc, depth+1));
{
/*
* Inplace compress the table.*
For sparse data sets the table constructed by the trie algorithm will
be mostly 0/FAIL transitions or to put it another way mostly empty.
(Note that leaf nodes will not contain any transitions.)
This algorithm compresses the tables by eliminating most such
transitions, at the cost of a modest bit of extra work during lookup:
- Each states[] entry contains a .base field which indicates the
index in the state[] array wheres its transition data is stored.
- If .base is 0 there are no valid transitions from that node.
- If .base is nonzero then charid is added to it to find an entry in
the trans array.
-If trans[states[state].base+charid].check!=state then the
transition is taken to be a 0/Fail transition. Thus if there are fail
transitions at the front of the node then the .base offset will point
somewhere inside the previous nodes data (or maybe even into a node
even earlier), but the .check field determines if the transition is
valid.
XXX - wrong maybe?
The following process inplace converts the table to the compressed
table: We first do not compress the root node 1,and mark all its
.check pointers as 1 and set its .base pointer as 1 as well. This
allows us to do a DFA construction from the compressed table later,
and ensures that any .base pointers we calculate later are greater
than 0.
- We set 'pos' to indicate the first entry of the second node.
- We then iterate over the columns of the node, finding the first and
last used entry at l and m. We then copy l..m into pos..(pos+m-l),
and set the .check pointers accordingly, and advance pos
appropriately and repreat for the next node. Note that when we copy
the next pointers we have to convert them from the original
NODEIDX form to NODENUM form as the former is not valid post
compression.
- If a node has no transitions used we mark its base as 0 and do not
advance the pos pointer.
- If a node only has one transition we use a second pointer into the
structure to fill in allocated fail transitions from other states.
This pointer is independent of the main pointer and scans forward
looking for null transitions that are allocated to a state. When it
finds one it writes the single transition into the "hole". If the
pointer doesnt find one the single transition is appended as normal.
- Once compressed we can Renew/realloc the structures to release the
excess space.
See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
specifically Fig 3.47 and the associated pseudocode.
demq
*/
const U32 laststate = TRIE_NODENUM( next_alloc );
U32 state, charid;
U32 pos = 0, zp=0;
trie->statecount = laststate;
for ( state = 1 ; state < laststate ; state++ ) {
U8 flag = 0;
const U32 stateidx = TRIE_NODEIDX( state );
const U32 o_used = trie->trans[ stateidx ].check;
U32 used = trie->trans[ stateidx ].check;
trie->trans[ stateidx ].check = 0;
for ( charid = 0;
used && charid < trie->uniquecharcount;
charid++ )
{
if ( flag || trie->trans[ stateidx + charid ].next ) {
if ( trie->trans[ stateidx + charid ].next ) {
if (o_used == 1) {
for ( ; zp < pos ; zp++ ) {
if ( ! trie->trans[ zp ].next ) {
break;
}
}
trie->states[ state ].trans.base
= zp
+ trie->uniquecharcount
- charid ;
trie->trans[ zp ].next
= SAFE_TRIE_NODENUM( trie->trans[ stateidx
+ charid ].next );
trie->trans[ zp ].check = state;
if ( ++zp > pos ) pos = zp;
break;
}
used--;
}
if ( !flag ) {
flag = 1;
trie->states[ state ].trans.base
= pos + trie->uniquecharcount - charid ;
}
trie->trans[ pos ].next
= SAFE_TRIE_NODENUM(
trie->trans[ stateidx + charid ].next );
trie->trans[ pos ].check = state;
pos++;
}
}
}
trie->lasttrans = pos + 1;
trie->states = (reg_trie_state *)
PerlMemShared_realloc( trie->states, laststate
* sizeof(reg_trie_state) );
DEBUG_TRIE_COMPILE_MORE_r(
Perl_re_indentf( aTHX_ "Alloc: %d Orig: %" IVdf " elements, Final:%" IVdf ". Savings of %%%5.2f\n",
depth+1,
(int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
+ 1 ),
(IV)next_alloc,
(IV)pos,
( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
);
} /* end table compress */
}
DEBUG_TRIE_COMPILE_MORE_r(
Perl_re_indentf( aTHX_ "Statecount:%" UVxf " Lasttrans:%" UVxf "\n",
depth+1,
(UV)trie->statecount,
(UV)trie->lasttrans)
);
/* resize the trans array to remove unused space */
trie->trans = (reg_trie_trans *)
PerlMemShared_realloc( trie->trans, trie->lasttrans
* sizeof(reg_trie_trans) );
{ /* Modify the program and insert the new TRIE node */
U8 nodetype =(U8)(flags & 0xFF);
char *str=NULL;
#ifdef DEBUGGING
regnode *optimize = NULL;
#ifdef RE_TRACK_PATTERN_OFFSETS
U32 mjd_offset = 0;
U32 mjd_nodelen = 0;
#endif /* RE_TRACK_PATTERN_OFFSETS */
#endif /* DEBUGGING */
/*
This means we convert either the first branch or the first Exact,
depending on whether the thing following (in 'last') is a branch
or not and whther first is the startbranch (ie is it a sub part of
the alternation or is it the whole thing.)
Assuming its a sub part we convert the EXACT otherwise we convert
the whole branch sequence, including the first.
*/
/* Find the node we are going to overwrite */
if ( first != startbranch || OP( last ) == BRANCH ) {
/* branch sub-chain */
NEXT_OFF( first ) = (U16)(last - first);
#ifdef RE_TRACK_PATTERN_OFFSETS
DEBUG_r({
mjd_offset= Node_Offset((convert));
mjd_nodelen= Node_Length((convert));
});
#endif
/* whole branch chain */
}
#ifdef RE_TRACK_PATTERN_OFFSETS
else {
DEBUG_r({
const regnode *nop = NEXTOPER( convert );
mjd_offset= Node_Offset((nop));
mjd_nodelen= Node_Length((nop));
});
}
DEBUG_OPTIMISE_r(
Perl_re_indentf( aTHX_ "MJD offset:%" UVuf " MJD length:%" UVuf "\n",
depth+1,
(UV)mjd_offset, (UV)mjd_nodelen)
);
#endif
/* But first we check to see if there is a common prefix we can
split out as an EXACT and put in front of the TRIE node. */
trie->startstate= 1;
if ( trie->bitmap && !widecharmap && !trie->jump ) {
/* we want to find the first state that has more than
* one transition, if that state is not the first state
* then we have a common prefix which we can remove.
*/
U32 state;
for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
U32 ofs = 0;
I32 first_ofs = -1; /* keeps track of the ofs of the first
transition, -1 means none */
U32 count = 0;
const U32 base = trie->states[ state ].trans.base;
/* does this state terminate an alternation? */
if ( trie->states[state].wordnum )
count = 1;
for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
if ( ( base + ofs >= trie->uniquecharcount ) &&
( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
{
if ( ++count > 1 ) {
/* we have more than one transition */
SV **tmp;
U8 *ch;
/* if this is the first state there is no common prefix
* to extract, so we can exit */
if ( state == 1 ) break;
tmp = av_fetch( revcharmap, ofs, 0);
ch = (U8*)SvPV_nolen_const( *tmp );
/* if we are on count 2 then we need to initialize the
* bitmap, and store the previous char if there was one
* in it*/
if ( count == 2 ) {
/* clear the bitmap */
Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
DEBUG_OPTIMISE_r(
Perl_re_indentf( aTHX_ "New Start State=%" UVuf " Class: [",
depth+1,
(UV)state));
if (first_ofs >= 0) {
SV ** const tmp = av_fetch( revcharmap, first_ofs, 0);
const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
TRIE_BITMAP_SET_FOLDED(trie,*ch,folder);
DEBUG_OPTIMISE_r(
Perl_re_printf( aTHX_ "%s", (char*)ch)
);
}
}
/* store the current firstchar in the bitmap */
TRIE_BITMAP_SET_FOLDED(trie,*ch,folder);
DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "%s", ch));
}
first_ofs = ofs;
}
}
if ( count == 1 ) {
/* This state has only one transition, its transition is part
* of a common prefix - we need to concatenate the char it
* represents to what we have so far. */
SV **tmp = av_fetch( revcharmap, first_ofs, 0);
STRLEN len;
char *ch = SvPV( *tmp, len );
DEBUG_OPTIMISE_r({
SV *sv=sv_newmortal();
Perl_re_indentf( aTHX_ "Prefix State: %" UVuf " Ofs:%" UVuf " Char='%s'\n",
depth+1,
(UV)state, (UV)first_ofs,
pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
PL_colors[0], PL_colors[1],
(SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
PERL_PV_ESCAPE_FIRSTCHAR
)
);
});
if ( state==1 ) {
OP( convert ) = nodetype;
str=STRING(convert);
STR_LEN(convert)=0;
}
STR_LEN(convert) += len;
while (len--)
*str++ = *ch++;
} else {
#ifdef DEBUGGING
if (state>1)
DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "]\n"));
#endif
break;
}
}
trie->prefixlen = (state-1);
if (str) {
regnode *n = convert+NODE_SZ_STR(convert);
NEXT_OFF(convert) = NODE_SZ_STR(convert);
trie->startstate = state;
trie->minlen -= (state - 1);
trie->maxlen -= (state - 1);
#ifdef DEBUGGING
/* At least the UNICOS C compiler choked on this
* being argument to DEBUG_r(), so let's just have
* it right here. */
if (
#ifdef PERL_EXT_RE_BUILD
1
#else
DEBUG_r_TEST
#endif
) {
regnode *fix = convert;
U32 word = trie->wordcount;
mjd_nodelen++;
Set_Node_Offset_Length(convert, mjd_offset, state - 1);
while( ++fix < n ) {
Set_Node_Offset_Length(fix, 0, 0);
}
while (word--) {
SV ** const tmp = av_fetch( trie_words, word, 0 );
if (tmp) {
if ( STR_LEN(convert) <= SvCUR(*tmp) )
sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
else
sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
}
}
}
#endif
if (trie->maxlen) {
convert = n;
} else {
NEXT_OFF(convert) = (U16)(tail - convert);
DEBUG_r(optimize= n);
}
}
}
if (!jumper)
jumper = last;
if ( trie->maxlen ) {
NEXT_OFF( convert ) = (U16)(tail - convert);
ARG_SET( convert, data_slot );
/* Store the offset to the first unabsorbed branch in
jump[0], which is otherwise unused by the jump logic.
We use this when dumping a trie and during optimisation. */
if (trie->jump)
trie->jump[0] = (U16)(nextbranch - convert);
/* If the start state is not accepting (meaning there is no empty string/NOTHING)
* and there is a bitmap
* and the first "jump target" node we found leaves enough room
* then convert the TRIE node into a TRIEC node, with the bitmap
* embedded inline in the opcode - this is hypothetically faster.
*/
if ( !trie->states[trie->startstate].wordnum
&& trie->bitmap
&& ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
{
OP( convert ) = TRIEC;
Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
PerlMemShared_free(trie->bitmap);
trie->bitmap= NULL;
} else
OP( convert ) = TRIE;
/* store the type in the flags */
convert->flags = nodetype;
DEBUG_r({
optimize = convert
+ NODE_STEP_REGNODE
+ regarglen[ OP( convert ) ];
});
/* XXX We really should free up the resource in trie now,
as we won't use them - (which resources?) dmq */
}
/* needed for dumping*/
DEBUG_r(if (optimize) {
regnode *opt = convert;
while ( ++opt < optimize) {
Set_Node_Offset_Length(opt,0,0);
}
/*
Try to clean up some of the debris left after the
optimisation.
*/
while( optimize < jumper ) {
mjd_nodelen += Node_Length((optimize));
OP( optimize ) = OPTIMIZED;
Set_Node_Offset_Length(optimize,0,0);
optimize++;
}
Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
});
} /* end node insert */
/* Finish populating the prev field of the wordinfo array. Walk back
* from each accept state until we find another accept state, and if
* so, point the first word's .prev field at the second word. If the
* second already has a .prev field set, stop now. This will be the
* case either if we've already processed that word's accept state,
* or that state had multiple words, and the overspill words were
* already linked up earlier.
*/
{
U16 word;
U32 state;
U16 prev;
for (word=1; word <= trie->wordcount; word++) {
prev = 0;
if (trie->wordinfo[word].prev)
continue;
state = trie->wordinfo[word].accept;
while (state) {
state = prev_states[state];
if (!state)
break;
prev = trie->states[state].wordnum;
if (prev)
break;
}
trie->wordinfo[word].prev = prev;
}
Safefree(prev_states);
}
/* and now dump out the compressed format */
DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
#ifdef DEBUGGING
RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
#else
SvREFCNT_dec_NN(revcharmap);
#endif
return trie->jump
? MADE_JUMP_TRIE
: trie->startstate>1
? MADE_EXACT_TRIE
: MADE_TRIE;
}
STATIC regnode *
S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
{
/* The Trie is constructed and compressed now so we can build a fail array if
* it's needed
This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3.32 in the
"Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
Ullman 1985/88
ISBN 0-201-10088-6
We find the fail state for each state in the trie, this state is the longest
proper suffix of the current state's 'word' that is also a proper prefix of
another word in our trie. State 1 represents the word '' and is thus the
default fail state. This allows the DFA not to have to restart after its
tried and failed a word at a given point, it simply continues as though it
had been matching the other word in the first place.
Consider
'abcdgu'=~/abcdefg|cdgu/
When we get to 'd' we are still matching the first word, we would encounter
'g' which would fail, which would bring us to the state representing 'd' in
the second word where we would try 'g' and succeed, proceeding to match
'cdgu'.
*/
/* add a fail transition */
const U32 trie_offset = ARG(source);
reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
U32 *q;
const U32 ucharcount = trie->uniquecharcount;
const U32 numstates = trie->statecount;
const U32 ubound = trie->lasttrans + ucharcount;
U32 q_read = 0;
U32 q_write = 0;
U32 charid;
U32 base = trie->states[ 1 ].trans.base;
U32 *fail;
reg_ac_data *aho;
const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
regnode *stclass;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
PERL_UNUSED_CONTEXT;
#ifndef DEBUGGING
PERL_UNUSED_ARG(depth);
#endif
if ( OP(source) == TRIE ) {
struct regnode_1 *op = (struct regnode_1 *)
PerlMemShared_calloc(1, sizeof(struct regnode_1));
StructCopy(source,op,struct regnode_1);
stclass = (regnode *)op;
} else {
struct regnode_charclass *op = (struct regnode_charclass *)
PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
StructCopy(source,op,struct regnode_charclass);
stclass = (regnode *)op;
}
OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
ARG_SET( stclass, data_slot );
aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
RExC_rxi->data->data[ data_slot ] = (void*)aho;
aho->trie=trie_offset;
aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
Copy( trie->states, aho->states, numstates, reg_trie_state );
Newx( q, numstates, U32);
aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
aho->refcount = 1;
fail = aho->fail;
/* initialize fail[0..1] to be 1 so that we always have
a valid final fail state */
fail[ 0 ] = fail[ 1 ] = 1;
for ( charid = 0; charid < ucharcount ; charid++ ) {
const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
if ( newstate ) {
q[ q_write ] = newstate;
/* set to point at the root */
fail[ q[ q_write++ ] ]=1;
}
}
while ( q_read < q_write) {
const U32 cur = q[ q_read++ % numstates ];
base = trie->states[ cur ].trans.base;
for ( charid = 0 ; charid < ucharcount ; charid++ ) {
const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
if (ch_state) {
U32 fail_state = cur;
U32 fail_base;
do {
fail_state = fail[ fail_state ];
fail_base = aho->states[ fail_state ].trans.base;
} while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
fail[ ch_state ] = fail_state;
if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
{
aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
}
q[ q_write++ % numstates] = ch_state;
}
}
}
/* restore fail[0..1] to 0 so that we "fall out" of the AC loop
when we fail in state 1, this allows us to use the
charclass scan to find a valid start char. This is based on the principle
that theres a good chance the string being searched contains lots of stuff
that cant be a start char.
*/
fail[ 0 ] = fail[ 1 ] = 0;
DEBUG_TRIE_COMPILE_r({
Perl_re_indentf( aTHX_ "Stclass Failtable (%" UVuf " states): 0",
depth, (UV)numstates
);
for( q_read=1; q_read<numstates; q_read++ ) {
Perl_re_printf( aTHX_ ", %" UVuf, (UV)fail[q_read]);
}
Perl_re_printf( aTHX_ "\n");
});
Safefree(q);
/*RExC_seen |= REG_TRIEDFA_SEEN;*/
return stclass;
}
/* The below joins as many adjacent EXACTish nodes as possible into a single
* one. The regop may be changed if the node(s) contain certain sequences that
* require special handling. The joining is only done if:
* 1) there is room in the current conglomerated node to entirely contain the
* next one.
* 2) they are the exact same node type
*
* The adjacent nodes actually may be separated by NOTHING-kind nodes, and
* these get optimized out
*
* XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full
* as possible, even if that means splitting an existing node so that its first
* part is moved to the preceeding node. This would maximise the efficiency of
* memEQ during matching. Elsewhere in this file, khw proposes splitting
* EXACTFish nodes into portions that don't change under folding vs those that
* do. Those portions that don't change may be the only things in the pattern that
* could be used to find fixed and floating strings.
*
* If a node is to match under /i (folded), the number of characters it matches
* can be different than its character length if it contains a multi-character
* fold. *min_subtract is set to the total delta number of characters of the
* input nodes.
*
* And *unfolded_multi_char is set to indicate whether or not the node contains
* an unfolded multi-char fold. This happens when whether the fold is valid or
* not won't be known until runtime; namely for EXACTF nodes that contain LATIN
* SMALL LETTER SHARP S, as only if the target string being matched against
* turns out to be UTF-8 is that fold valid; and also for EXACTFL nodes whose
* folding rules depend on the locale in force at runtime. (Multi-char folds
* whose components are all above the Latin1 range are not run-time locale
* dependent, and have already been folded by the time this function is
* called.)
*
* This is as good a place as any to discuss the design of handling these
* multi-character fold sequences. It's been wrong in Perl for a very long
* time. There are three code points in Unicode whose multi-character folds
* were long ago discovered to mess things up. The previous designs for
* dealing with these involved assigning a special node for them. This
* approach doesn't always work, as evidenced by this example:
* "\xDFs" =~ /s\xDF/ui # Used to fail before these patches
* Both sides fold to "sss", but if the pattern is parsed to create a node that
* would match just the \xDF, it won't be able to handle the case where a
* successful match would have to cross the node's boundary. The new approach
* that hopefully generally solves the problem generates an EXACTFU_SS node
* that is "sss" in this case.
*
* It turns out that there are problems with all multi-character folds, and not
* just these three. Now the code is general, for all such cases. The
* approach taken is:
* 1) This routine examines each EXACTFish node that could contain multi-
* character folded sequences. Since a single character can fold into
* such a sequence, the minimum match length for this node is less than
* the number of characters in the node. This routine returns in
* *min_subtract how many characters to subtract from the the actual
* length of the string to get a real minimum match length; it is 0 if
* there are no multi-char foldeds. This delta is used by the caller to
* adjust the min length of the match, and the delta between min and max,
* so that the optimizer doesn't reject these possibilities based on size
* constraints.
* 2) For the sequence involving the Sharp s (\xDF), the node type EXACTFU_SS
* is used for an EXACTFU node that contains at least one "ss" sequence in
* it. For non-UTF-8 patterns and strings, this is the only case where
* there is a possible fold length change. That means that a regular
* EXACTFU node without UTF-8 involvement doesn't have to concern itself
* with length changes, and so can be processed faster. regexec.c takes
* advantage of this. Generally, an EXACTFish node that is in UTF-8 is
* pre-folded by regcomp.c (except EXACTFL, some of whose folds aren't
* known until runtime). This saves effort in regex matching. However,
* the pre-folding isn't done for non-UTF8 patterns because the fold of
* the MICRO SIGN requires UTF-8, and we don't want to slow things down by
* forcing the pattern into UTF8 unless necessary. Also what EXACTF (and,
* again, EXACTFL) nodes fold to isn't known until runtime. The fold
* possibilities for the non-UTF8 patterns are quite simple, except for
* the sharp s. All the ones that don't involve a UTF-8 target string are
* members of a fold-pair, and arrays are set up for all of them so that
* the other member of the pair can be found quickly. Code elsewhere in
* this file makes sure that in EXACTFU nodes, the sharp s gets folded to
* 'ss', even if the pattern isn't UTF-8. This avoids the issues
* described in the next item.
* 3) A problem remains for unfolded multi-char folds. (These occur when the
* validity of the fold won't be known until runtime, and so must remain
* unfolded for now. This happens for the sharp s in EXACTF and EXACTFA
* nodes when the pattern isn't in UTF-8. (Note, BTW, that there cannot
* be an EXACTF node with a UTF-8 pattern.) They also occur for various
* folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
* The reason this is a problem is that the optimizer part of regexec.c
* (probably unwittingly, in Perl_regexec_flags()) makes an assumption
* that a character in the pattern corresponds to at most a single
* character in the target string. (And I do mean character, and not byte
* here, unlike other parts of the documentation that have never been
* updated to account for multibyte Unicode.) sharp s in EXACTF and
* EXACTFL nodes can match the two character string 'ss'; in EXACTFA nodes
* it can match "\x{17F}\x{17F}". These, along with other ones in EXACTFL
* nodes, violate the assumption, and they are the only instances where it
* is violated. I'm reluctant to try to change the assumption, as the
* code involved is impenetrable to me (khw), so instead the code here
* punts. This routine examines EXACTFL nodes, and (when the pattern
* isn't UTF-8) EXACTF and EXACTFA for such unfolded folds, and returns a
* boolean indicating whether or not the node contains such a fold. When
* it is true, the caller sets a flag that later causes the optimizer in
* this file to not set values for the floating and fixed string lengths,
* and thus avoids the optimizer code in regexec.c that makes the invalid
* assumption. Thus, there is no optimization based on string lengths for
* EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
* EXACTF and EXACTFA nodes that contain the sharp s. (The reason the
* assumption is wrong only in these cases is that all other non-UTF-8
* folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
* their expanded versions. (Again, we can't prefold sharp s to 'ss' in
* EXACTF nodes because we don't know at compile time if it actually
* matches 'ss' or not. For EXACTF nodes it will match iff the target
* string is in UTF-8. This is in contrast to EXACTFU nodes, where it
* always matches; and EXACTFA where it never does. In an EXACTFA node in
* a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
* problem; but in a non-UTF8 pattern, folding it to that above-Latin1
* string would require the pattern to be forced into UTF-8, the overhead
* of which we want to avoid. Similarly the unfolded multi-char folds in
* EXACTFL nodes will match iff the locale at the time of match is a UTF-8
* locale.)
*
* Similarly, the code that generates tries doesn't currently handle
* not-already-folded multi-char folds, and it looks like a pain to change
* that. Therefore, trie generation of EXACTFA nodes with the sharp s
* doesn't work. Instead, such an EXACTFA is turned into a new regnode,
* EXACTFA_NO_TRIE, which the trie code knows not to handle. Most people
* using /iaa matching will be doing so almost entirely with ASCII
* strings, so this should rarely be encountered in practice */
#define JOIN_EXACT(scan,min_subtract,unfolded_multi_char, flags) \
if (PL_regkind[OP(scan)] == EXACT) \
join_exact(pRExC_state,(scan),(min_subtract),unfolded_multi_char, (flags),NULL,depth+1)
STATIC U32
S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
UV *min_subtract, bool *unfolded_multi_char,
U32 flags,regnode *val, U32 depth)
{
/* Merge several consecutive EXACTish nodes into one. */
regnode *n = regnext(scan);
U32 stringok = 1;
regnode *next = scan + NODE_SZ_STR(scan);
U32 merged = 0;
U32 stopnow = 0;
#ifdef DEBUGGING
regnode *stop = scan;
GET_RE_DEBUG_FLAGS_DECL;
#else
PERL_UNUSED_ARG(depth);
#endif
PERL_ARGS_ASSERT_JOIN_EXACT;
#ifndef EXPERIMENTAL_INPLACESCAN
PERL_UNUSED_ARG(flags);
PERL_UNUSED_ARG(val);
#endif
DEBUG_PEEP("join", scan, depth, 0);
/* Look through the subsequent nodes in the chain. Skip NOTHING, merge
* EXACT ones that are mergeable to the current one. */
while (n
&& (PL_regkind[OP(n)] == NOTHING
|| (stringok && OP(n) == OP(scan)))
&& NEXT_OFF(n)
&& NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
{
if (OP(n) == TAIL || n > next)
stringok = 0;
if (PL_regkind[OP(n)] == NOTHING) {
DEBUG_PEEP("skip:", n, depth, 0);
NEXT_OFF(scan) += NEXT_OFF(n);
next = n + NODE_STEP_REGNODE;
#ifdef DEBUGGING
if (stringok)
stop = n;
#endif
n = regnext(n);
}
else if (stringok) {
const unsigned int oldl = STR_LEN(scan);
regnode * const nnext = regnext(n);
/* XXX I (khw) kind of doubt that this works on platforms (should
* Perl ever run on one) where U8_MAX is above 255 because of lots
* of other assumptions */
/* Don't join if the sum can't fit into a single node */
if (oldl + STR_LEN(n) > U8_MAX)
break;
DEBUG_PEEP("merg", n, depth, 0);
merged++;
NEXT_OFF(scan) += NEXT_OFF(n);
STR_LEN(scan) += STR_LEN(n);
next = n + NODE_SZ_STR(n);
/* Now we can overwrite *n : */
Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
#ifdef DEBUGGING
stop = next - 1;
#endif
n = nnext;
if (stopnow) break;
}
#ifdef EXPERIMENTAL_INPLACESCAN
if (flags && !NEXT_OFF(n)) {
DEBUG_PEEP("atch", val, depth, 0);
if (reg_off_by_arg[OP(n)]) {
ARG_SET(n, val - n);
}
else {
NEXT_OFF(n) = val - n;
}
stopnow = 1;
}
#endif
}
*min_subtract = 0;
*unfolded_multi_char = FALSE;
/* Here, all the adjacent mergeable EXACTish nodes have been merged. We
* can now analyze for sequences of problematic code points. (Prior to
* this final joining, sequences could have been split over boundaries, and
* hence missed). The sequences only happen in folding, hence for any
* non-EXACT EXACTish node */
if (OP(scan) != EXACT && OP(scan) != EXACTL) {
U8* s0 = (U8*) STRING(scan);
U8* s = s0;
U8* s_end = s0 + STR_LEN(scan);
int total_count_delta = 0; /* Total delta number of characters that
multi-char folds expand to */
/* One pass is made over the node's string looking for all the
* possibilities. To avoid some tests in the loop, there are two main
* cases, for UTF-8 patterns (which can't have EXACTF nodes) and
* non-UTF-8 */
if (UTF) {
U8* folded = NULL;
if (OP(scan) == EXACTFL) {
U8 *d;
/* An EXACTFL node would already have been changed to another
* node type unless there is at least one character in it that
* is problematic; likely a character whose fold definition
* won't be known until runtime, and so has yet to be folded.
* For all but the UTF-8 locale, folds are 1-1 in length, but
* to handle the UTF-8 case, we need to create a temporary
* folded copy using UTF-8 locale rules in order to analyze it.
* This is because our macros that look to see if a sequence is
* a multi-char fold assume everything is folded (otherwise the
* tests in those macros would be too complicated and slow).
* Note that here, the non-problematic folds will have already
* been done, so we can just copy such characters. We actually
* don't completely fold the EXACTFL string. We skip the
* unfolded multi-char folds, as that would just create work
* below to figure out the size they already are */
Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8);
d = folded;
while (s < s_end) {
STRLEN s_len = UTF8SKIP(s);
if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) {
Copy(s, d, s_len, U8);
d += s_len;
}
else if (is_FOLDS_TO_MULTI_utf8(s)) {
*unfolded_multi_char = TRUE;
Copy(s, d, s_len, U8);
d += s_len;
}
else if (isASCII(*s)) {
*(d++) = toFOLD(*s);
}
else {
STRLEN len;
_toFOLD_utf8_flags(s, s_end, d, &len, FOLD_FLAGS_FULL);
d += len;
}
s += s_len;
}
/* Point the remainder of the routine to look at our temporary
* folded copy */
s = folded;
s_end = d;
} /* End of creating folded copy of EXACTFL string */
/* Examine the string for a multi-character fold sequence. UTF-8
* patterns have all characters pre-folded by the time this code is
* executed */
while (s < s_end - 1) /* Can stop 1 before the end, as minimum
length sequence we are looking for is 2 */
{
int count = 0; /* How many characters in a multi-char fold */
int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end);
if (! len) { /* Not a multi-char fold: get next char */
s += UTF8SKIP(s);
continue;
}
/* Nodes with 'ss' require special handling, except for
* EXACTFA-ish for which there is no multi-char fold to this */
if (len == 2 && *s == 's' && *(s+1) == 's'
&& OP(scan) != EXACTFA
&& OP(scan) != EXACTFA_NO_TRIE)
{
count = 2;
if (OP(scan) != EXACTFL) {
OP(scan) = EXACTFU_SS;
}
s += 2;
}
else { /* Here is a generic multi-char fold. */
U8* multi_end = s + len;
/* Count how many characters are in it. In the case of
* /aa, no folds which contain ASCII code points are
* allowed, so check for those, and skip if found. */
if (OP(scan) != EXACTFA && OP(scan) != EXACTFA_NO_TRIE) {
count = utf8_length(s, multi_end);
s = multi_end;
}
else {
while (s < multi_end) {
if (isASCII(*s)) {
s++;
goto next_iteration;
}
else {
s += UTF8SKIP(s);
}
count++;
}
}
}
/* The delta is how long the sequence is minus 1 (1 is how long
* the character that folds to the sequence is) */
total_count_delta += count - 1;
next_iteration: ;
}
/* We created a temporary folded copy of the string in EXACTFL
* nodes. Therefore we need to be sure it doesn't go below zero,
* as the real string could be shorter */
if (OP(scan) == EXACTFL) {
int total_chars = utf8_length((U8*) STRING(scan),
(U8*) STRING(scan) + STR_LEN(scan));
if (total_count_delta > total_chars) {
total_count_delta = total_chars;
}
}
*min_subtract += total_count_delta;
Safefree(folded);
}
else if (OP(scan) == EXACTFA) {
/* Non-UTF-8 pattern, EXACTFA node. There can't be a multi-char
* fold to the ASCII range (and there are no existing ones in the
* upper latin1 range). But, as outlined in the comments preceding
* this function, we need to flag any occurrences of the sharp s.
* This character forbids trie formation (because of added
* complexity) */
#if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
|| (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
|| UNICODE_DOT_DOT_VERSION > 0)
while (s < s_end) {
if (*s == LATIN_SMALL_LETTER_SHARP_S) {
OP(scan) = EXACTFA_NO_TRIE;
*unfolded_multi_char = TRUE;
break;
}
s++;
}
}
else {
/* Non-UTF-8 pattern, not EXACTFA node. Look for the multi-char
* folds that are all Latin1. As explained in the comments
* preceding this function, we look also for the sharp s in EXACTF
* and EXACTFL nodes; it can be in the final position. Otherwise
* we can stop looking 1 byte earlier because have to find at least
* two characters for a multi-fold */
const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL)
? s_end
: s_end -1;
while (s < upper) {
int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end);
if (! len) { /* Not a multi-char fold. */
if (*s == LATIN_SMALL_LETTER_SHARP_S
&& (OP(scan) == EXACTF || OP(scan) == EXACTFL))
{
*unfolded_multi_char = TRUE;
}
s++;
continue;
}
if (len == 2
&& isALPHA_FOLD_EQ(*s, 's')
&& isALPHA_FOLD_EQ(*(s+1), 's'))
{
/* EXACTF nodes need to know that the minimum length
* changed so that a sharp s in the string can match this
* ss in the pattern, but they remain EXACTF nodes, as they
* won't match this unless the target string is is UTF-8,
* which we don't know until runtime. EXACTFL nodes can't
* transform into EXACTFU nodes */
if (OP(scan) != EXACTF && OP(scan) != EXACTFL) {
OP(scan) = EXACTFU_SS;
}
}
*min_subtract += len - 1;
s += len;
}
#endif
}
}
#ifdef DEBUGGING
/* Allow dumping but overwriting the collection of skipped
* ops and/or strings with fake optimized ops */
n = scan + NODE_SZ_STR(scan);
while (n <= stop) {
OP(n) = OPTIMIZED;
FLAGS(n) = 0;
NEXT_OFF(n) = 0;
n++;
}
#endif
DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl", scan, depth, 0);});
return stopnow;
}
/* REx optimizer. Converts nodes into quicker variants "in place".
Finds fixed substrings. */
/* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
to the position after last scanned or to NULL. */
#define INIT_AND_WITHP \
assert(!and_withp); \
Newx(and_withp,1, regnode_ssc); \
SAVEFREEPV(and_withp)
static void
S_unwind_scan_frames(pTHX_ const void *p)
{
scan_frame *f= (scan_frame *)p;
do {
scan_frame *n= f->next_frame;
Safefree(f);
f= n;
} while (f);
}
STATIC SSize_t
S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
SSize_t *minlenp, SSize_t *deltap,
regnode *last,
scan_data_t *data,
I32 stopparen,
U32 recursed_depth,
regnode_ssc *and_withp,
U32 flags, U32 depth)
/* scanp: Start here (read-write). */
/* deltap: Write maxlen-minlen here. */
/* last: Stop before this one. */
/* data: string data about the pattern */
/* stopparen: treat close N as END */
/* recursed: which subroutines have we recursed into */
/* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
{
/* There must be at least this number of characters to match */
SSize_t min = 0;
I32 pars = 0, code;
regnode *scan = *scanp, *next;
SSize_t delta = 0;
int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
int is_inf_internal = 0; /* The studied chunk is infinite */
I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
scan_data_t data_fake;
SV *re_trie_maxbuff = NULL;
regnode *first_non_open = scan;
SSize_t stopmin = SSize_t_MAX;
scan_frame *frame = NULL;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_STUDY_CHUNK;
RExC_study_started= 1;
Zero(&data_fake, 1, scan_data_t);
if ( depth == 0 ) {
while (first_non_open && OP(first_non_open) == OPEN)
first_non_open=regnext(first_non_open);
}
fake_study_recurse:
DEBUG_r(
RExC_study_chunk_recursed_count++;
);
DEBUG_OPTIMISE_MORE_r(
{
Perl_re_indentf( aTHX_ "study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p",
depth, (long)stopparen,
(unsigned long)RExC_study_chunk_recursed_count,
(unsigned long)depth, (unsigned long)recursed_depth,
scan,
last);
if (recursed_depth) {
U32 i;
U32 j;
for ( j = 0 ; j < recursed_depth ; j++ ) {
for ( i = 0 ; i < (U32)RExC_npar ; i++ ) {
if (
PAREN_TEST(RExC_study_chunk_recursed +
( j * RExC_study_chunk_recursed_bytes), i )
&& (
!j ||
!PAREN_TEST(RExC_study_chunk_recursed +
(( j - 1 ) * RExC_study_chunk_recursed_bytes), i)
)
) {
Perl_re_printf( aTHX_ " %d",(int)i);
break;
}
}
if ( j + 1 < recursed_depth ) {
Perl_re_printf( aTHX_ ",");
}
}
}
Perl_re_printf( aTHX_ "\n");
}
);
while ( scan && OP(scan) != END && scan < last ){
UV min_subtract = 0; /* How mmany chars to subtract from the minimum
node length to get a real minimum (because
the folded version may be shorter) */
bool unfolded_multi_char = FALSE;
/* Peephole optimizer: */
DEBUG_STUDYDATA("Peep", data, depth, is_inf);
DEBUG_PEEP("Peep", scan, depth, flags);
/* The reason we do this here is that we need to deal with things like
* /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT
* parsing code, as each (?:..) is handled by a different invocation of
* reg() -- Yves
*/
JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0);
/* Follow the next-chain of the current node and optimize
away all the NOTHINGs from it. */
if (OP(scan) != CURLYX) {
const int max = (reg_off_by_arg[OP(scan)]
? I32_MAX
/* I32 may be smaller than U16 on CRAYs! */
: (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
int noff;
regnode *n = scan;
/* Skip NOTHING and LONGJMP. */
while ((n = regnext(n))
&& ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
|| ((OP(n) == LONGJMP) && (noff = ARG(n))))
&& off + noff < max)
off += noff;
if (reg_off_by_arg[OP(scan)])
ARG(scan) = off;
else
NEXT_OFF(scan) = off;
}
/* The principal pseudo-switch. Cannot be a switch, since we
look into several different things. */
if ( OP(scan) == DEFINEP ) {
SSize_t minlen = 0;
SSize_t deltanext = 0;
SSize_t fake_last_close = 0;
I32 f = SCF_IN_DEFINE;
StructCopy(&zero_scan_data, &data_fake, scan_data_t);
scan = regnext(scan);
assert( OP(scan) == IFTHEN );
DEBUG_PEEP("expect IFTHEN", scan, depth, flags);
data_fake.last_closep= &fake_last_close;
minlen = *minlenp;
next = regnext(scan);
scan = NEXTOPER(NEXTOPER(scan));
DEBUG_PEEP("scan", scan, depth, flags);
DEBUG_PEEP("next", next, depth, flags);
/* we suppose the run is continuous, last=next...
* NOTE we dont use the return here! */
/* DEFINEP study_chunk() recursion */
(void)study_chunk(pRExC_state, &scan, &minlen,
&deltanext, next, &data_fake, stopparen,
recursed_depth, NULL, f, depth+1);
scan = next;
} else
if (
OP(scan) == BRANCH ||
OP(scan) == BRANCHJ ||
OP(scan) == IFTHEN
) {
next = regnext(scan);
code = OP(scan);
/* The op(next)==code check below is to see if we
* have "BRANCH-BRANCH", "BRANCHJ-BRANCHJ", "IFTHEN-IFTHEN"
* IFTHEN is special as it might not appear in pairs.
* Not sure whether BRANCH-BRANCHJ is possible, regardless
* we dont handle it cleanly. */
if (OP(next) == code || code == IFTHEN) {
/* NOTE - There is similar code to this block below for
* handling TRIE nodes on a re-study. If you change stuff here
* check there too. */
SSize_t max1 = 0, min1 = SSize_t_MAX, num = 0;
regnode_ssc accum;
regnode * const startbranch=scan;
if (flags & SCF_DO_SUBSTR) {
/* Cannot merge strings after this. */
scan_commit(pRExC_state, data, minlenp, is_inf);
}
if (flags & SCF_DO_STCLASS)
ssc_init_zero(pRExC_state, &accum);
while (OP(scan) == code) {
SSize_t deltanext, minnext, fake;
I32 f = 0;
regnode_ssc this_class;
DEBUG_PEEP("Branch", scan, depth, flags);
num++;
StructCopy(&zero_scan_data, &data_fake, scan_data_t);
if (data) {
data_fake.whilem_c = data->whilem_c;
data_fake.last_closep = data->last_closep;
}
else
data_fake.last_closep = &fake;
data_fake.pos_delta = delta;
next = regnext(scan);
scan = NEXTOPER(scan); /* everything */
if (code != BRANCH) /* everything but BRANCH */
scan = NEXTOPER(scan);
if (flags & SCF_DO_STCLASS) {
ssc_init(pRExC_state, &this_class);
data_fake.start_class = &this_class;
f = SCF_DO_STCLASS_AND;
}
if (flags & SCF_WHILEM_VISITED_POS)
f |= SCF_WHILEM_VISITED_POS;
/* we suppose the run is continuous, last=next...*/
/* recurse study_chunk() for each BRANCH in an alternation */
minnext = study_chunk(pRExC_state, &scan, minlenp,
&deltanext, next, &data_fake, stopparen,
recursed_depth, NULL, f,depth+1);
if (min1 > minnext)
min1 = minnext;
if (deltanext == SSize_t_MAX) {
is_inf = is_inf_internal = 1;
max1 = SSize_t_MAX;
} else if (max1 < minnext + deltanext)
max1 = minnext + deltanext;
scan = next;
if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
pars++;
if (data_fake.flags & SCF_SEEN_ACCEPT) {
if ( stopmin > minnext)
stopmin = min + min1;
flags &= ~SCF_DO_SUBSTR;
if (data)
data->flags |= SCF_SEEN_ACCEPT;
}
if (data) {
if (data_fake.flags & SF_HAS_EVAL)
data->flags |= SF_HAS_EVAL;
data->whilem_c = data_fake.whilem_c;
}
if (flags & SCF_DO_STCLASS)
ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class);
}
if (code == IFTHEN && num < 2) /* Empty ELSE branch */
min1 = 0;
if (flags & SCF_DO_SUBSTR) {
data->pos_min += min1;
if (data->pos_delta >= SSize_t_MAX - (max1 - min1))
data->pos_delta = SSize_t_MAX;
else
data->pos_delta += max1 - min1;
if (max1 != min1 || is_inf)
data->cur_is_floating = 1;
}
min += min1;
if (delta == SSize_t_MAX
|| SSize_t_MAX - delta - (max1 - min1) < 0)
delta = SSize_t_MAX;
else
delta += max1 - min1;
if (flags & SCF_DO_STCLASS_OR) {
ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum);
if (min1) {
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
flags &= ~SCF_DO_STCLASS;
}
}
else if (flags & SCF_DO_STCLASS_AND) {
if (min1) {
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
flags &= ~SCF_DO_STCLASS;
}
else {
/* Switch to OR mode: cache the old value of
* data->start_class */
INIT_AND_WITHP;
StructCopy(data->start_class, and_withp, regnode_ssc);
flags &= ~SCF_DO_STCLASS_AND;
StructCopy(&accum, data->start_class, regnode_ssc);
flags |= SCF_DO_STCLASS_OR;
}
}
if (PERL_ENABLE_TRIE_OPTIMISATION &&
OP( startbranch ) == BRANCH )
{
/* demq.
Assuming this was/is a branch we are dealing with: 'scan'
now points at the item that follows the branch sequence,
whatever it is. We now start at the beginning of the
sequence and look for subsequences of
BRANCH->EXACT=>x1
BRANCH->EXACT=>x2
tail
which would be constructed from a pattern like
/A|LIST|OF|WORDS/
If we can find such a subsequence we need to turn the first
element into a trie and then add the subsequent branch exact
strings to the trie.
We have two cases
1. patterns where the whole set of branches can be
converted.
2. patterns where only a subset can be converted.
In case 1 we can replace the whole set with a single regop
for the trie. In case 2 we need to keep the start and end
branches so
'BRANCH EXACT; BRANCH EXACT; BRANCH X'
becomes BRANCH TRIE; BRANCH X;
There is an additional case, that being where there is a
common prefix, which gets split out into an EXACT like node
preceding the TRIE node.
If x(1..n)==tail then we can do a simple trie, if not we make
a "jump" trie, such that when we match the appropriate word
we "jump" to the appropriate tail node. Essentially we turn
a nested if into a case structure of sorts.
*/
int made=0;
if (!re_trie_maxbuff) {
re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
if (!SvIOK(re_trie_maxbuff))
sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
}
if ( SvIV(re_trie_maxbuff)>=0 ) {
regnode *cur;
regnode *first = (regnode *)NULL;
regnode *last = (regnode *)NULL;
regnode *tail = scan;
U8 trietype = 0;
U32 count=0;
/* var tail is used because there may be a TAIL
regop in the way. Ie, the exacts will point to the
thing following the TAIL, but the last branch will
point at the TAIL. So we advance tail. If we
have nested (?:) we may have to move through several
tails.
*/
while ( OP( tail ) == TAIL ) {
/* this is the TAIL generated by (?:) */
tail = regnext( tail );
}
DEBUG_TRIE_COMPILE_r({
regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state);
Perl_re_indentf( aTHX_ "%s %" UVuf ":%s\n",
depth+1,
"Looking for TRIE'able sequences. Tail node is ",
(UV)(tail - RExC_emit_start),
SvPV_nolen_const( RExC_mysv )
);
});
/*
Step through the branches
cur represents each branch,
noper is the first thing to be matched as part
of that branch
noper_next is the regnext() of that node.
We normally handle a case like this
/FOO[xyz]|BAR[pqr]/ via a "jump trie" but we also
support building with NOJUMPTRIE, which restricts
the trie logic to structures like /FOO|BAR/.
If noper is a trieable nodetype then the branch is
a possible optimization target. If we are building
under NOJUMPTRIE then we require that noper_next is
the same as scan (our current position in the regex
program).
Once we have two or more consecutive such branches
we can create a trie of the EXACT's contents and
stitch it in place into the program.
If the sequence represents all of the branches in
the alternation we replace the entire thing with a
single TRIE node.
Otherwise when it is a subsequence we need to
stitch it in place and replace only the relevant
branches. This means the first branch has to remain
as it is used by the alternation logic, and its
next pointer, and needs to be repointed at the item
on the branch chain following the last branch we
have optimized away.
This could be either a BRANCH, in which case the
subsequence is internal, or it could be the item
following the branch sequence in which case the
subsequence is at the end (which does not
necessarily mean the first node is the start of the
alternation).
TRIE_TYPE(X) is a define which maps the optype to a
trietype.
optype | trietype
----------------+-----------
NOTHING | NOTHING
EXACT | EXACT
EXACTFU | EXACTFU
EXACTFU_SS | EXACTFU
EXACTFA | EXACTFA
EXACTL | EXACTL
EXACTFLU8 | EXACTFLU8
*/
#define TRIE_TYPE(X) ( ( NOTHING == (X) ) \
? NOTHING \
: ( EXACT == (X) ) \
? EXACT \
: ( EXACTFU == (X) || EXACTFU_SS == (X) ) \
? EXACTFU \
: ( EXACTFA == (X) ) \
? EXACTFA \
: ( EXACTL == (X) ) \
? EXACTL \
: ( EXACTFLU8 == (X) ) \
? EXACTFLU8 \
: 0 )
/* dont use tail as the end marker for this traverse */
for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
regnode * const noper = NEXTOPER( cur );
U8 noper_type = OP( noper );
U8 noper_trietype = TRIE_TYPE( noper_type );
#if defined(DEBUGGING) || defined(NOJUMPTRIE)
regnode * const noper_next = regnext( noper );
U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0;
#endif
DEBUG_TRIE_COMPILE_r({
regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
Perl_re_indentf( aTHX_ "- %d:%s (%d)",
depth+1,
REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) );
regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state);
Perl_re_printf( aTHX_ " -> %d:%s",
REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv));
if ( noper_next ) {
regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state);
Perl_re_printf( aTHX_ "\t=> %d:%s\t",
REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv));
}
Perl_re_printf( aTHX_ "(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\n",
REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),
PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype]
);
});
/* Is noper a trieable nodetype that can be merged
* with the current trie (if there is one)? */
if ( noper_trietype
&&
(
( noper_trietype == NOTHING )
|| ( trietype == NOTHING )
|| ( trietype == noper_trietype )
)
#ifdef NOJUMPTRIE
&& noper_next >= tail
#endif
&& count < U16_MAX)
{
/* Handle mergable triable node Either we are
* the first node in a new trieable sequence,
* in which case we do some bookkeeping,
* otherwise we update the end pointer. */
if ( !first ) {
first = cur;
if ( noper_trietype == NOTHING ) {
#if !defined(DEBUGGING) && !defined(NOJUMPTRIE)
regnode * const noper_next = regnext( noper );
U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;
#endif
if ( noper_next_trietype ) {
trietype = noper_next_trietype;
} else if (noper_next_type) {
/* a NOTHING regop is 1 regop wide.
* We need at least two for a trie
* so we can't merge this in */
first = NULL;
}
} else {
trietype = noper_trietype;
}
} else {
if ( trietype == NOTHING )
trietype = noper_trietype;
last = cur;
}
if (first)
count++;
} /* end handle mergable triable node */
else {
/* handle unmergable node -
* noper may either be a triable node which can
* not be tried together with the current trie,
* or a non triable node */
if ( last ) {
/* If last is set and trietype is not
* NOTHING then we have found at least two
* triable branch sequences in a row of a
* similar trietype so we can turn them
* into a trie. If/when we allow NOTHING to
* start a trie sequence this condition
* will be required, and it isn't expensive
* so we leave it in for now. */
if ( trietype && trietype != NOTHING )
make_trie( pRExC_state,
startbranch, first, cur, tail,
count, trietype, depth+1 );
last = NULL; /* note: we clear/update
first, trietype etc below,
so we dont do it here */
}
if ( noper_trietype
#ifdef NOJUMPTRIE
&& noper_next >= tail
#endif
){
/* noper is triable, so we can start a new
* trie sequence */
count = 1;
first = cur;
trietype = noper_trietype;
} else if (first) {
/* if we already saw a first but the
* current node is not triable then we have
* to reset the first information. */
count = 0;
first = NULL;
trietype = 0;
}
} /* end handle unmergable node */
} /* loop over branches */
DEBUG_TRIE_COMPILE_r({
regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
Perl_re_indentf( aTHX_ "- %s (%d) <SCAN FINISHED> ",
depth+1, SvPV_nolen_const( RExC_mysv ),REG_NODE_NUM(cur));
Perl_re_printf( aTHX_ "(First==%d, Last==%d, Cur==%d, tt==%s)\n",
REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),
PL_reg_name[trietype]
);
});
if ( last && trietype ) {
if ( trietype != NOTHING ) {
/* the last branch of the sequence was part of
* a trie, so we have to construct it here
* outside of the loop */
made= make_trie( pRExC_state, startbranch,
first, scan, tail, count,
trietype, depth+1 );
#ifdef TRIE_STUDY_OPT
if ( ((made == MADE_EXACT_TRIE &&
startbranch == first)
|| ( first_non_open == first )) &&
depth==0 ) {
flags |= SCF_TRIE_RESTUDY;
if ( startbranch == first
&& scan >= tail )
{
RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN;
}
}
#endif
} else {
/* at this point we know whatever we have is a
* NOTHING sequence/branch AND if 'startbranch'
* is 'first' then we can turn the whole thing
* into a NOTHING
*/
if ( startbranch == first ) {
regnode *opt;
/* the entire thing is a NOTHING sequence,
* something like this: (?:|) So we can
* turn it into a plain NOTHING op. */
DEBUG_TRIE_COMPILE_r({
regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
Perl_re_indentf( aTHX_ "- %s (%d) <NOTHING BRANCH SEQUENCE>\n",
depth+1,
SvPV_nolen_const( RExC_mysv ),REG_NODE_NUM(cur));
});
OP(startbranch)= NOTHING;
NEXT_OFF(startbranch)= tail - startbranch;
for ( opt= startbranch + 1; opt < tail ; opt++ )
OP(opt)= OPTIMIZED;
}
}
} /* end if ( last) */
} /* TRIE_MAXBUF is non zero */
} /* do trie */
}
else if ( code == BRANCHJ ) { /* single branch is optimized. */
scan = NEXTOPER(NEXTOPER(scan));
} else /* single branch is optimized. */
scan = NEXTOPER(scan);
continue;
} else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) {
I32 paren = 0;
regnode *start = NULL;
regnode *end = NULL;
U32 my_recursed_depth= recursed_depth;
if (OP(scan) != SUSPEND) { /* GOSUB */
/* Do setup, note this code has side effects beyond
* the rest of this block. Specifically setting
* RExC_recurse[] must happen at least once during
* study_chunk(). */
paren = ARG(scan);
RExC_recurse[ARG2L(scan)] = scan;
start = RExC_open_parens[paren];
end = RExC_close_parens[paren];
/* NOTE we MUST always execute the above code, even
* if we do nothing with a GOSUB */
if (
( flags & SCF_IN_DEFINE )
||
(
(is_inf_internal || is_inf || (data && data->flags & SF_IS_INF))
&&
( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 )
)
) {
/* no need to do anything here if we are in a define. */
/* or we are after some kind of infinite construct
* so we can skip recursing into this item.
* Since it is infinite we will not change the maxlen
* or delta, and if we miss something that might raise
* the minlen it will merely pessimise a little.
*
* Iow /(?(DEFINE)(?<foo>foo|food))a+(?&foo)/
* might result in a minlen of 1 and not of 4,
* but this doesn't make us mismatch, just try a bit
* harder than we should.
* */
scan= regnext(scan);
continue;
}
if (
!recursed_depth
||
!PAREN_TEST(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), paren)
) {
/* it is quite possible that there are more efficient ways
* to do this. We maintain a bitmap per level of recursion
* of which patterns we have entered so we can detect if a
* pattern creates a possible infinite loop. When we
* recurse down a level we copy the previous levels bitmap
* down. When we are at recursion level 0 we zero the top
* level bitmap. It would be nice to implement a different
* more efficient way of doing this. In particular the top
* level bitmap may be unnecessary.
*/
if (!recursed_depth) {
Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8);
} else {
Copy(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes),
RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes),
RExC_study_chunk_recursed_bytes, U8);
}
/* we havent recursed into this paren yet, so recurse into it */
DEBUG_STUDYDATA("gosub-set", data, depth, is_inf);
PAREN_SET(RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), paren);
my_recursed_depth= recursed_depth + 1;
} else {
DEBUG_STUDYDATA("gosub-inf", data, depth, is_inf);
/* some form of infinite recursion, assume infinite length
* */
if (flags & SCF_DO_SUBSTR) {
scan_commit(pRExC_state, data, minlenp, is_inf);
data->cur_is_floating = 1;
}
is_inf = is_inf_internal = 1;
if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
ssc_anything(data->start_class);
flags &= ~SCF_DO_STCLASS;
start= NULL; /* reset start so we dont recurse later on. */
}
} else {
paren = stopparen;
start = scan + 2;
end = regnext(scan);
}
if (start) {
scan_frame *newframe;
assert(end);
if (!RExC_frame_last) {
Newxz(newframe, 1, scan_frame);
SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe);
RExC_frame_head= newframe;
RExC_frame_count++;
} else if (!RExC_frame_last->next_frame) {
Newxz(newframe,1,scan_frame);
RExC_frame_last->next_frame= newframe;
newframe->prev_frame= RExC_frame_last;
RExC_frame_count++;
} else {
newframe= RExC_frame_last->next_frame;
}
RExC_frame_last= newframe;
newframe->next_regnode = regnext(scan);
newframe->last_regnode = last;
newframe->stopparen = stopparen;
newframe->prev_recursed_depth = recursed_depth;
newframe->this_prev_frame= frame;
DEBUG_STUDYDATA("frame-new", data, depth, is_inf);
DEBUG_PEEP("fnew", scan, depth, flags);
frame = newframe;
scan = start;
stopparen = paren;
last = end;
depth = depth + 1;
recursed_depth= my_recursed_depth;
continue;
}
}
else if (OP(scan) == EXACT || OP(scan) == EXACTL) {
SSize_t l = STR_LEN(scan);
UV uc;
assert(l);
if (UTF) {
const U8 * const s = (U8*)STRING(scan);
uc = utf8_to_uvchr_buf(s, s + l, NULL);
l = utf8_length(s, s + l);
} else {
uc = *((U8*)STRING(scan));
}
min += l;
if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
/* The code below prefers earlier match for fixed
offset, later match for variable offset. */
if (data->last_end == -1) { /* Update the start info. */
data->last_start_min = data->pos_min;
data->last_start_max = is_inf
? SSize_t_MAX : data->pos_min + data->pos_delta;
}
sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
if (UTF)
SvUTF8_on(data->last_found);
{
SV * const sv = data->last_found;
MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
mg_find(sv, PERL_MAGIC_utf8) : NULL;
if (mg && mg->mg_len >= 0)
mg->mg_len += utf8_length((U8*)STRING(scan),
(U8*)STRING(scan)+STR_LEN(scan));
}
data->last_end = data->pos_min + l;
data->pos_min += l; /* As in the first entry. */
data->flags &= ~SF_BEFORE_EOL;
}
/* ANDing the code point leaves at most it, and not in locale, and
* can't match null string */
if (flags & SCF_DO_STCLASS_AND) {
ssc_cp_and(data->start_class, uc);
ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
ssc_clear_locale(data->start_class);
}
else if (flags & SCF_DO_STCLASS_OR) {
ssc_add_cp(data->start_class, uc);
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
/* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
}
flags &= ~SCF_DO_STCLASS;
}
else if (PL_regkind[OP(scan)] == EXACT) {
/* But OP != EXACT!, so is EXACTFish */
SSize_t l = STR_LEN(scan);
const U8 * s = (U8*)STRING(scan);
/* Search for fixed substrings supports EXACT only. */
if (flags & SCF_DO_SUBSTR) {
assert(data);
scan_commit(pRExC_state, data, minlenp, is_inf);
}
if (UTF) {
l = utf8_length(s, s + l);
}
if (unfolded_multi_char) {
RExC_seen |= REG_UNFOLDED_MULTI_SEEN;
}
min += l - min_subtract;
assert (min >= 0);
delta += min_subtract;
if (flags & SCF_DO_SUBSTR) {
data->pos_min += l - min_subtract;
if (data->pos_min < 0) {
data->pos_min = 0;
}
data->pos_delta += min_subtract;
if (min_subtract) {
data->cur_is_floating = 1; /* float */
}
}
if (flags & SCF_DO_STCLASS) {
SV* EXACTF_invlist = _make_exactf_invlist(pRExC_state, scan);
assert(EXACTF_invlist);
if (flags & SCF_DO_STCLASS_AND) {
if (OP(scan) != EXACTFL)
ssc_clear_locale(data->start_class);
ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
ANYOF_POSIXL_ZERO(data->start_class);
ssc_intersection(data->start_class, EXACTF_invlist, FALSE);
}
else { /* SCF_DO_STCLASS_OR */
ssc_union(data->start_class, EXACTF_invlist, FALSE);
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
/* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
}
flags &= ~SCF_DO_STCLASS;
SvREFCNT_dec(EXACTF_invlist);
}
}
else if (REGNODE_VARIES(OP(scan))) {
SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0;
I32 fl = 0, f = flags;
regnode * const oscan = scan;
regnode_ssc this_class;
regnode_ssc *oclass = NULL;
I32 next_is_eval = 0;
switch (PL_regkind[OP(scan)]) {
case WHILEM: /* End of (?:...)* . */
scan = NEXTOPER(scan);
goto finish;
case PLUS:
if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
next = NEXTOPER(scan);
if (OP(next) == EXACT
|| OP(next) == EXACTL
|| (flags & SCF_DO_STCLASS))
{
mincount = 1;
maxcount = REG_INFTY;
next = regnext(scan);
scan = NEXTOPER(scan);
goto do_curly;
}
}
if (flags & SCF_DO_SUBSTR)
data->pos_min++;
min++;
/* FALLTHROUGH */
case STAR:
if (flags & SCF_DO_STCLASS) {
mincount = 0;
maxcount = REG_INFTY;
next = regnext(scan);
scan = NEXTOPER(scan);
goto do_curly;
}
if (flags & SCF_DO_SUBSTR) {
scan_commit(pRExC_state, data, minlenp, is_inf);
/* Cannot extend fixed substrings */
data->cur_is_floating = 1; /* float */
}
is_inf = is_inf_internal = 1;
scan = regnext(scan);
goto optimize_curly_tail;
case CURLY:
if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
&& (scan->flags == stopparen))
{
mincount = 1;
maxcount = 1;
} else {
mincount = ARG1(scan);
maxcount = ARG2(scan);
}
next = regnext(scan);
if (OP(scan) == CURLYX) {
I32 lp = (data ? *(data->last_closep) : 0);
scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
}
scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
next_is_eval = (OP(scan) == EVAL);
do_curly:
if (flags & SCF_DO_SUBSTR) {
if (mincount == 0)
scan_commit(pRExC_state, data, minlenp, is_inf);
/* Cannot extend fixed substrings */
pos_before = data->pos_min;
}
if (data) {
fl = data->flags;
data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
if (is_inf)
data->flags |= SF_IS_INF;
}
if (flags & SCF_DO_STCLASS) {
ssc_init(pRExC_state, &this_class);
oclass = data->start_class;
data->start_class = &this_class;
f |= SCF_DO_STCLASS_AND;
f &= ~SCF_DO_STCLASS_OR;
}
/* Exclude from super-linear cache processing any {n,m}
regops for which the combination of input pos and regex
pos is not enough information to determine if a match
will be possible.
For example, in the regex /foo(bar\s*){4,8}baz/ with the
regex pos at the \s*, the prospects for a match depend not
only on the input position but also on how many (bar\s*)
repeats into the {4,8} we are. */
if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
f &= ~SCF_WHILEM_VISITED_POS;
/* This will finish on WHILEM, setting scan, or on NULL: */
/* recurse study_chunk() on loop bodies */
minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
last, data, stopparen, recursed_depth, NULL,
(mincount == 0
? (f & ~SCF_DO_SUBSTR)
: f)
,depth+1);
if (flags & SCF_DO_STCLASS)
data->start_class = oclass;
if (mincount == 0 || minnext == 0) {
if (flags & SCF_DO_STCLASS_OR) {
ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
}
else if (flags & SCF_DO_STCLASS_AND) {
/* Switch to OR mode: cache the old value of
* data->start_class */
INIT_AND_WITHP;
StructCopy(data->start_class, and_withp, regnode_ssc);
flags &= ~SCF_DO_STCLASS_AND;
StructCopy(&this_class, data->start_class, regnode_ssc);
flags |= SCF_DO_STCLASS_OR;
ANYOF_FLAGS(data->start_class)
|= SSC_MATCHES_EMPTY_STRING;
}
} else { /* Non-zero len */
if (flags & SCF_DO_STCLASS_OR) {
ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
}
else if (flags & SCF_DO_STCLASS_AND)
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
flags &= ~SCF_DO_STCLASS;
}
if (!scan) /* It was not CURLYX, but CURLY. */
scan = next;
if (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR)
/* ? quantifier ok, except for (?{ ... }) */
&& (next_is_eval || !(mincount == 0 && maxcount == 1))
&& (minnext == 0) && (deltanext == 0)
&& data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
&& maxcount <= REG_INFTY/3) /* Complement check for big
count */
{
/* Fatal warnings may leak the regexp without this: */
SAVEFREESV(RExC_rx_sv);
Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
"Quantifier unexpected on zero-length expression "
"in regex m/%" UTF8f "/",
UTF8fARG(UTF, RExC_precomp_end - RExC_precomp,
RExC_precomp));
(void)ReREFCNT_inc(RExC_rx_sv);
}
min += minnext * mincount;
is_inf_internal |= deltanext == SSize_t_MAX
|| (maxcount == REG_INFTY && minnext + deltanext > 0);
is_inf |= is_inf_internal;
if (is_inf) {
delta = SSize_t_MAX;
} else {
delta += (minnext + deltanext) * maxcount
- minnext * mincount;
}
/* Try powerful optimization CURLYX => CURLYN. */
if ( OP(oscan) == CURLYX && data
&& data->flags & SF_IN_PAR
&& !(data->flags & SF_HAS_EVAL)
&& !deltanext && minnext == 1 ) {
/* Try to optimize to CURLYN. */
regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
regnode * const nxt1 = nxt;
#ifdef DEBUGGING
regnode *nxt2;
#endif
/* Skip open. */
nxt = regnext(nxt);
if (!REGNODE_SIMPLE(OP(nxt))
&& !(PL_regkind[OP(nxt)] == EXACT
&& STR_LEN(nxt) == 1))
goto nogo;
#ifdef DEBUGGING
nxt2 = nxt;
#endif
nxt = regnext(nxt);
if (OP(nxt) != CLOSE)
goto nogo;
if (RExC_open_parens) {
RExC_open_parens[ARG(nxt1)]=oscan; /*open->CURLYM*/
RExC_close_parens[ARG(nxt1)]=nxt+2; /*close->while*/
}
/* Now we know that nxt2 is the only contents: */
oscan->flags = (U8)ARG(nxt);
OP(oscan) = CURLYN;
OP(nxt1) = NOTHING; /* was OPEN. */
#ifdef DEBUGGING
OP(nxt1 + 1) = OPTIMIZED; /* was count. */
NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
OP(nxt) = OPTIMIZED; /* was CLOSE. */
OP(nxt + 1) = OPTIMIZED; /* was count. */
NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
#endif
}
nogo:
/* Try optimization CURLYX => CURLYM. */
if ( OP(oscan) == CURLYX && data
&& !(data->flags & SF_HAS_PAR)
&& !(data->flags & SF_HAS_EVAL)
&& !deltanext /* atom is fixed width */
&& minnext != 0 /* CURLYM can't handle zero width */
/* Nor characters whose fold at run-time may be
* multi-character */
&& ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN)
) {
/* XXXX How to optimize if data == 0? */
/* Optimize to a simpler form. */
regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
regnode *nxt2;
OP(oscan) = CURLYM;
while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
&& (OP(nxt2) != WHILEM))
nxt = nxt2;
OP(nxt2) = SUCCEED; /* Whas WHILEM */
/* Need to optimize away parenths. */
if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
/* Set the parenth number. */
regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
oscan->flags = (U8)ARG(nxt);
if (RExC_open_parens) {
RExC_open_parens[ARG(nxt1)]=oscan; /*open->CURLYM*/
RExC_close_parens[ARG(nxt1)]=nxt2+1; /*close->NOTHING*/
}
OP(nxt1) = OPTIMIZED; /* was OPEN. */
OP(nxt) = OPTIMIZED; /* was CLOSE. */
#ifdef DEBUGGING
OP(nxt1 + 1) = OPTIMIZED; /* was count. */
OP(nxt + 1) = OPTIMIZED; /* was count. */
NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
#endif
#if 0
while ( nxt1 && (OP(nxt1) != WHILEM)) {
regnode *nnxt = regnext(nxt1);
if (nnxt == nxt) {
if (reg_off_by_arg[OP(nxt1)])
ARG_SET(nxt1, nxt2 - nxt1);
else if (nxt2 - nxt1 < U16_MAX)
NEXT_OFF(nxt1) = nxt2 - nxt1;
else
OP(nxt) = NOTHING; /* Cannot beautify */
}
nxt1 = nnxt;
}
#endif
/* Optimize again: */
/* recurse study_chunk() on optimised CURLYX => CURLYM */
study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
NULL, stopparen, recursed_depth, NULL, 0,depth+1);
}
else
oscan->flags = 0;
}
else if ((OP(oscan) == CURLYX)
&& (flags & SCF_WHILEM_VISITED_POS)
/* See the comment on a similar expression above.
However, this time it's not a subexpression
we care about, but the expression itself. */
&& (maxcount == REG_INFTY)
&& data) {
/* This stays as CURLYX, we can put the count/of pair. */
/* Find WHILEM (as in regexec.c) */
regnode *nxt = oscan + NEXT_OFF(oscan);
if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
nxt += ARG(nxt);
nxt = PREVOPER(nxt);
if (nxt->flags & 0xf) {
/* we've already set whilem count on this node */
} else if (++data->whilem_c < 16) {
assert(data->whilem_c <= RExC_whilem_seen);
nxt->flags = (U8)(data->whilem_c
| (RExC_whilem_seen << 4)); /* On WHILEM */
}
}
if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
pars++;
if (flags & SCF_DO_SUBSTR) {
SV *last_str = NULL;
STRLEN last_chrs = 0;
int counted = mincount != 0;
if (data->last_end > 0 && mincount != 0) { /* Ends with a
string. */
SSize_t b = pos_before >= data->last_start_min
? pos_before : data->last_start_min;
STRLEN l;
const char * const s = SvPV_const(data->last_found, l);
SSize_t old = b - data->last_start_min;
if (UTF)
old = utf8_hop((U8*)s, old) - (U8*)s;
l -= old;
/* Get the added string: */
last_str = newSVpvn_utf8(s + old, l, UTF);
last_chrs = UTF ? utf8_length((U8*)(s + old),
(U8*)(s + old + l)) : l;
if (deltanext == 0 && pos_before == b) {
/* What was added is a constant string */
if (mincount > 1) {
SvGROW(last_str, (mincount * l) + 1);
repeatcpy(SvPVX(last_str) + l,
SvPVX_const(last_str), l,
mincount - 1);
SvCUR_set(last_str, SvCUR(last_str) * mincount);
/* Add additional parts. */
SvCUR_set(data->last_found,
SvCUR(data->last_found) - l);
sv_catsv(data->last_found, last_str);
{
SV * sv = data->last_found;
MAGIC *mg =
SvUTF8(sv) && SvMAGICAL(sv) ?
mg_find(sv, PERL_MAGIC_utf8) : NULL;
if (mg && mg->mg_len >= 0)
mg->mg_len += last_chrs * (mincount-1);
}
last_chrs *= mincount;
data->last_end += l * (mincount - 1);
}
} else {
/* start offset must point into the last copy */
data->last_start_min += minnext * (mincount - 1);
data->last_start_max =
is_inf
? SSize_t_MAX
: data->last_start_max +
(maxcount - 1) * (minnext + data->pos_delta);
}
}
/* It is counted once already... */
data->pos_min += minnext * (mincount - counted);
#if 0
Perl_re_printf( aTHX_ "counted=%" UVuf " deltanext=%" UVuf
" SSize_t_MAX=%" UVuf " minnext=%" UVuf
" maxcount=%" UVuf " mincount=%" UVuf "\n",
(UV)counted, (UV)deltanext, (UV)SSize_t_MAX, (UV)minnext, (UV)maxcount,
(UV)mincount);
if (deltanext != SSize_t_MAX)
Perl_re_printf( aTHX_ "LHS=%" UVuf " RHS=%" UVuf "\n",
(UV)(-counted * deltanext + (minnext + deltanext) * maxcount
- minnext * mincount), (UV)(SSize_t_MAX - data->pos_delta));
#endif
if (deltanext == SSize_t_MAX
|| -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= SSize_t_MAX - data->pos_delta)
data->pos_delta = SSize_t_MAX;
else
data->pos_delta += - counted * deltanext +
(minnext + deltanext) * maxcount - minnext * mincount;
if (mincount != maxcount) {
/* Cannot extend fixed substrings found inside
the group. */
scan_commit(pRExC_state, data, minlenp, is_inf);
if (mincount && last_str) {
SV * const sv = data->last_found;
MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
mg_find(sv, PERL_MAGIC_utf8) : NULL;
if (mg)
mg->mg_len = -1;
sv_setsv(sv, last_str);
data->last_end = data->pos_min;
data->last_start_min = data->pos_min - last_chrs;
data->last_start_max = is_inf
? SSize_t_MAX
: data->pos_min + data->pos_delta - last_chrs;
}
data->cur_is_floating = 1; /* float */
}
SvREFCNT_dec(last_str);
}
if (data && (fl & SF_HAS_EVAL))
data->flags |= SF_HAS_EVAL;
optimize_curly_tail:
if (OP(oscan) != CURLYX) {
while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
&& NEXT_OFF(next))
NEXT_OFF(oscan) += NEXT_OFF(next);
}
continue;
default:
#ifdef DEBUGGING
Perl_croak(aTHX_ "panic: unexpected varying REx opcode %d",
OP(scan));
#endif
case REF:
case CLUMP:
if (flags & SCF_DO_SUBSTR) {
/* Cannot expect anything... */
scan_commit(pRExC_state, data, minlenp, is_inf);
data->cur_is_floating = 1; /* float */
}
is_inf = is_inf_internal = 1;
if (flags & SCF_DO_STCLASS_OR) {
if (OP(scan) == CLUMP) {
/* Actually is any start char, but very few code points
* aren't start characters */
ssc_match_all_cp(data->start_class);
}
else {
ssc_anything(data->start_class);
}
}
flags &= ~SCF_DO_STCLASS;
break;
}
}
else if (OP(scan) == LNBREAK) {
if (flags & SCF_DO_STCLASS) {
if (flags & SCF_DO_STCLASS_AND) {
ssc_intersection(data->start_class,
PL_XPosix_ptrs[_CC_VERTSPACE], FALSE);
ssc_clear_locale(data->start_class);
ANYOF_FLAGS(data->start_class)
&= ~SSC_MATCHES_EMPTY_STRING;
}
else if (flags & SCF_DO_STCLASS_OR) {
ssc_union(data->start_class,
PL_XPosix_ptrs[_CC_VERTSPACE],
FALSE);
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
/* See commit msg for
* 749e076fceedeb708a624933726e7989f2302f6a */
ANYOF_FLAGS(data->start_class)
&= ~SSC_MATCHES_EMPTY_STRING;
}
flags &= ~SCF_DO_STCLASS;
}
min++;
if (delta != SSize_t_MAX)
delta++; /* Because of the 2 char string cr-lf */
if (flags & SCF_DO_SUBSTR) {
/* Cannot expect anything... */
scan_commit(pRExC_state, data, minlenp, is_inf);
data->pos_min += 1;
data->pos_delta += 1;
data->cur_is_floating = 1; /* float */
}
}
else if (REGNODE_SIMPLE(OP(scan))) {
if (flags & SCF_DO_SUBSTR) {
scan_commit(pRExC_state, data, minlenp, is_inf);
data->pos_min++;
}
min++;
if (flags & SCF_DO_STCLASS) {
bool invert = 0;
SV* my_invlist = NULL;
U8 namedclass;
/* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
/* Some of the logic below assumes that switching
locale on will only add false positives. */
switch (OP(scan)) {
default:
#ifdef DEBUGGING
Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d",
OP(scan));
#endif
case SANY:
if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
ssc_match_all_cp(data->start_class);
break;
case REG_ANY:
{
SV* REG_ANY_invlist = _new_invlist(2);
REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist,
'\n');
if (flags & SCF_DO_STCLASS_OR) {
ssc_union(data->start_class,
REG_ANY_invlist,
TRUE /* TRUE => invert, hence all but \n
*/
);
}
else if (flags & SCF_DO_STCLASS_AND) {
ssc_intersection(data->start_class,
REG_ANY_invlist,
TRUE /* TRUE => invert */
);
ssc_clear_locale(data->start_class);
}
SvREFCNT_dec_NN(REG_ANY_invlist);
}
break;
case ANYOFD:
case ANYOFL:
case ANYOF:
if (flags & SCF_DO_STCLASS_AND)
ssc_and(pRExC_state, data->start_class,
(regnode_charclass *) scan);
else
ssc_or(pRExC_state, data->start_class,
(regnode_charclass *) scan);
break;
case NPOSIXL:
invert = 1;
/* FALLTHROUGH */
case POSIXL:
namedclass = classnum_to_namedclass(FLAGS(scan)) + invert;
if (flags & SCF_DO_STCLASS_AND) {
bool was_there = cBOOL(
ANYOF_POSIXL_TEST(data->start_class,
namedclass));
ANYOF_POSIXL_ZERO(data->start_class);
if (was_there) { /* Do an AND */
ANYOF_POSIXL_SET(data->start_class, namedclass);
}
/* No individual code points can now match */
data->start_class->invlist
= sv_2mortal(_new_invlist(0));
}
else {
int complement = namedclass + ((invert) ? -1 : 1);
assert(flags & SCF_DO_STCLASS_OR);
/* If the complement of this class was already there,
* the result is that they match all code points,
* (\d + \D == everything). Remove the classes from
* future consideration. Locale is not relevant in
* this case */
if (ANYOF_POSIXL_TEST(data->start_class, complement)) {
ssc_match_all_cp(data->start_class);
ANYOF_POSIXL_CLEAR(data->start_class, namedclass);
ANYOF_POSIXL_CLEAR(data->start_class, complement);
}
else { /* The usual case; just add this class to the
existing set */
ANYOF_POSIXL_SET(data->start_class, namedclass);
}
}
break;
case NPOSIXA: /* For these, we always know the exact set of
what's matched */
invert = 1;
/* FALLTHROUGH */
case POSIXA:
if (FLAGS(scan) == _CC_ASCII) {
my_invlist = invlist_clone(PL_XPosix_ptrs[_CC_ASCII]);
}
else {
_invlist_intersection(PL_XPosix_ptrs[FLAGS(scan)],
PL_XPosix_ptrs[_CC_ASCII],
&my_invlist);
}
goto join_posix;
case NPOSIXD:
case NPOSIXU:
invert = 1;
/* FALLTHROUGH */
case POSIXD:
case POSIXU:
my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)]);
/* NPOSIXD matches all upper Latin1 code points unless the
* target string being matched is UTF-8, which is
* unknowable until match time. Since we are going to
* invert, we want to get rid of all of them so that the
* inversion will match all */
if (OP(scan) == NPOSIXD) {
_invlist_subtract(my_invlist, PL_UpperLatin1,
&my_invlist);
}
join_posix:
if (flags & SCF_DO_STCLASS_AND) {
ssc_intersection(data->start_class, my_invlist, invert);
ssc_clear_locale(data->start_class);
}
else {
assert(flags & SCF_DO_STCLASS_OR);
ssc_union(data->start_class, my_invlist, invert);
}
SvREFCNT_dec(my_invlist);
}
if (flags & SCF_DO_STCLASS_OR)
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
flags &= ~SCF_DO_STCLASS;
}
}
else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
data->flags |= (OP(scan) == MEOL
? SF_BEFORE_MEOL
: SF_BEFORE_SEOL);
scan_commit(pRExC_state, data, minlenp, is_inf);
}
else if ( PL_regkind[OP(scan)] == BRANCHJ
/* Lookbehind, or need to calculate parens/evals/stclass: */
&& (scan->flags || data || (flags & SCF_DO_STCLASS))
&& (OP(scan) == IFMATCH || OP(scan) == UNLESSM))
{
if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
|| OP(scan) == UNLESSM )
{
/* Negative Lookahead/lookbehind
In this case we can't do fixed string optimisation.
*/
SSize_t deltanext, minnext, fake = 0;
regnode *nscan;
regnode_ssc intrnl;
int f = 0;
StructCopy(&zero_scan_data, &data_fake, scan_data_t);
if (data) {
data_fake.whilem_c = data->whilem_c;
data_fake.last_closep = data->last_closep;
}
else
data_fake.last_closep = &fake;
data_fake.pos_delta = delta;
if ( flags & SCF_DO_STCLASS && !scan->flags
&& OP(scan) == IFMATCH ) { /* Lookahead */
ssc_init(pRExC_state, &intrnl);
data_fake.start_class = &intrnl;
f |= SCF_DO_STCLASS_AND;
}
if (flags & SCF_WHILEM_VISITED_POS)
f |= SCF_WHILEM_VISITED_POS;
next = regnext(scan);
nscan = NEXTOPER(NEXTOPER(scan));
/* recurse study_chunk() for lookahead body */
minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
last, &data_fake, stopparen,
recursed_depth, NULL, f, depth+1);
if (scan->flags) {
if (deltanext) {
FAIL("Variable length lookbehind not implemented");
}
else if (minnext > (I32)U8_MAX) {
FAIL2("Lookbehind longer than %" UVuf " not implemented",
(UV)U8_MAX);
}
scan->flags = (U8)minnext;
}
if (data) {
if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
pars++;
if (data_fake.flags & SF_HAS_EVAL)
data->flags |= SF_HAS_EVAL;
data->whilem_c = data_fake.whilem_c;
}
if (f & SCF_DO_STCLASS_AND) {
if (flags & SCF_DO_STCLASS_OR) {
/* OR before, AND after: ideally we would recurse with
* data_fake to get the AND applied by study of the
* remainder of the pattern, and then derecurse;
* *** HACK *** for now just treat as "no information".
* See [perl #56690].
*/
ssc_init(pRExC_state, data->start_class);
} else {
/* AND before and after: combine and continue. These
* assertions are zero-length, so can match an EMPTY
* string */
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
ANYOF_FLAGS(data->start_class)
|= SSC_MATCHES_EMPTY_STRING;
}
}
}
#if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
else {
/* Positive Lookahead/lookbehind
In this case we can do fixed string optimisation,
but we must be careful about it. Note in the case of
lookbehind the positions will be offset by the minimum
length of the pattern, something we won't know about
until after the recurse.
*/
SSize_t deltanext, fake = 0;
regnode *nscan;
regnode_ssc intrnl;
int f = 0;
/* We use SAVEFREEPV so that when the full compile
is finished perl will clean up the allocated
minlens when it's all done. This way we don't
have to worry about freeing them when we know
they wont be used, which would be a pain.
*/
SSize_t *minnextp;
Newx( minnextp, 1, SSize_t );
SAVEFREEPV(minnextp);
if (data) {
StructCopy(data, &data_fake, scan_data_t);
if ((flags & SCF_DO_SUBSTR) && data->last_found) {
f |= SCF_DO_SUBSTR;
if (scan->flags)
scan_commit(pRExC_state, &data_fake, minlenp, is_inf);
data_fake.last_found=newSVsv(data->last_found);
}
}
else
data_fake.last_closep = &fake;
data_fake.flags = 0;
data_fake.substrs[0].flags = 0;
data_fake.substrs[1].flags = 0;
data_fake.pos_delta = delta;
if (is_inf)
data_fake.flags |= SF_IS_INF;
if ( flags & SCF_DO_STCLASS && !scan->flags
&& OP(scan) == IFMATCH ) { /* Lookahead */
ssc_init(pRExC_state, &intrnl);
data_fake.start_class = &intrnl;
f |= SCF_DO_STCLASS_AND;
}
if (flags & SCF_WHILEM_VISITED_POS)
f |= SCF_WHILEM_VISITED_POS;
next = regnext(scan);
nscan = NEXTOPER(NEXTOPER(scan));
/* positive lookahead study_chunk() recursion */
*minnextp = study_chunk(pRExC_state, &nscan, minnextp,
&deltanext, last, &data_fake,
stopparen, recursed_depth, NULL,
f,depth+1);
if (scan->flags) {
if (deltanext) {
FAIL("Variable length lookbehind not implemented");
}
else if (*minnextp > (I32)U8_MAX) {
FAIL2("Lookbehind longer than %" UVuf " not implemented",
(UV)U8_MAX);
}
scan->flags = (U8)*minnextp;
}
*minnextp += min;
if (f & SCF_DO_STCLASS_AND) {
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING;
}
if (data) {
if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
pars++;
if (data_fake.flags & SF_HAS_EVAL)
data->flags |= SF_HAS_EVAL;
data->whilem_c = data_fake.whilem_c;
if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
int i;
if (RExC_rx->minlen<*minnextp)
RExC_rx->minlen=*minnextp;
scan_commit(pRExC_state, &data_fake, minnextp, is_inf);
SvREFCNT_dec_NN(data_fake.last_found);
for (i = 0; i < 2; i++) {
if (data_fake.substrs[i].minlenp != minlenp) {
data->substrs[i].min_offset =
data_fake.substrs[i].min_offset;
data->substrs[i].max_offset =
data_fake.substrs[i].max_offset;
data->substrs[i].minlenp =
data_fake.substrs[i].minlenp;
data->substrs[i].lookbehind += scan->flags;
}
}
}
}
}
#endif
}
else if (OP(scan) == OPEN) {
if (stopparen != (I32)ARG(scan))
pars++;
}
else if (OP(scan) == CLOSE) {
if (stopparen == (I32)ARG(scan)) {
break;
}
if ((I32)ARG(scan) == is_par) {
next = regnext(scan);
if ( next && (OP(next) != WHILEM) && next < last)
is_par = 0; /* Disable optimization */
}
if (data)
*(data->last_closep) = ARG(scan);
}
else if (OP(scan) == EVAL) {
if (data)
data->flags |= SF_HAS_EVAL;
}
else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
if (flags & SCF_DO_SUBSTR) {
scan_commit(pRExC_state, data, minlenp, is_inf);
flags &= ~SCF_DO_SUBSTR;
}
if (data && OP(scan)==ACCEPT) {
data->flags |= SCF_SEEN_ACCEPT;
if (stopmin > min)
stopmin = min;
}
}
else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
{
if (flags & SCF_DO_SUBSTR) {
scan_commit(pRExC_state, data, minlenp, is_inf);
data->cur_is_floating = 1; /* float */
}
is_inf = is_inf_internal = 1;
if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
ssc_anything(data->start_class);
flags &= ~SCF_DO_STCLASS;
}
else if (OP(scan) == GPOS) {
if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) &&
!(delta || is_inf || (data && data->pos_delta)))
{
if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR))
RExC_rx->intflags |= PREGf_ANCH_GPOS;
if (RExC_rx->gofs < (STRLEN)min)
RExC_rx->gofs = min;
} else {
RExC_rx->intflags |= PREGf_GPOS_FLOAT;
RExC_rx->gofs = 0;
}
}
#ifdef TRIE_STUDY_OPT
#ifdef FULL_TRIE_STUDY
else if (PL_regkind[OP(scan)] == TRIE) {
/* NOTE - There is similar code to this block above for handling
BRANCH nodes on the initial study. If you change stuff here
check there too. */
regnode *trie_node= scan;
regnode *tail= regnext(scan);
reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
SSize_t max1 = 0, min1 = SSize_t_MAX;
regnode_ssc accum;
if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */
/* Cannot merge strings after this. */
scan_commit(pRExC_state, data, minlenp, is_inf);
}
if (flags & SCF_DO_STCLASS)
ssc_init_zero(pRExC_state, &accum);
if (!trie->jump) {
min1= trie->minlen;
max1= trie->maxlen;
} else {
const regnode *nextbranch= NULL;
U32 word;
for ( word=1 ; word <= trie->wordcount ; word++)
{
SSize_t deltanext=0, minnext=0, f = 0, fake;
regnode_ssc this_class;
StructCopy(&zero_scan_data, &data_fake, scan_data_t);
if (data) {
data_fake.whilem_c = data->whilem_c;
data_fake.last_closep = data->last_closep;
}
else
data_fake.last_closep = &fake;
data_fake.pos_delta = delta;
if (flags & SCF_DO_STCLASS) {
ssc_init(pRExC_state, &this_class);
data_fake.start_class = &this_class;
f = SCF_DO_STCLASS_AND;
}
if (flags & SCF_WHILEM_VISITED_POS)
f |= SCF_WHILEM_VISITED_POS;
if (trie->jump[word]) {
if (!nextbranch)
nextbranch = trie_node + trie->jump[0];
scan= trie_node + trie->jump[word];
/* We go from the jump point to the branch that follows
it. Note this means we need the vestigal unused
branches even though they arent otherwise used. */
/* optimise study_chunk() for TRIE */
minnext = study_chunk(pRExC_state, &scan, minlenp,
&deltanext, (regnode *)nextbranch, &data_fake,
stopparen, recursed_depth, NULL, f,depth+1);
}
if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
nextbranch= regnext((regnode*)nextbranch);
if (min1 > (SSize_t)(minnext + trie->minlen))
min1 = minnext + trie->minlen;
if (deltanext == SSize_t_MAX) {
is_inf = is_inf_internal = 1;
max1 = SSize_t_MAX;
} else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen))
max1 = minnext + deltanext + trie->maxlen;
if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
pars++;
if (data_fake.flags & SCF_SEEN_ACCEPT) {
if ( stopmin > min + min1)
stopmin = min + min1;
flags &= ~SCF_DO_SUBSTR;
if (data)
data->flags |= SCF_SEEN_ACCEPT;
}
if (data) {
if (data_fake.flags & SF_HAS_EVAL)
data->flags |= SF_HAS_EVAL;
data->whilem_c = data_fake.whilem_c;
}
if (flags & SCF_DO_STCLASS)
ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class);
}
}
if (flags & SCF_DO_SUBSTR) {
data->pos_min += min1;
data->pos_delta += max1 - min1;
if (max1 != min1 || is_inf)
data->cur_is_floating = 1; /* float */
}
min += min1;
if (delta != SSize_t_MAX) {
if (SSize_t_MAX - (max1 - min1) >= delta)
delta += max1 - min1;
else
delta = SSize_t_MAX;
}
if (flags & SCF_DO_STCLASS_OR) {
ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum);
if (min1) {
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
flags &= ~SCF_DO_STCLASS;
}
}
else if (flags & SCF_DO_STCLASS_AND) {
if (min1) {
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
flags &= ~SCF_DO_STCLASS;
}
else {
/* Switch to OR mode: cache the old value of
* data->start_class */
INIT_AND_WITHP;
StructCopy(data->start_class, and_withp, regnode_ssc);
flags &= ~SCF_DO_STCLASS_AND;
StructCopy(&accum, data->start_class, regnode_ssc);
flags |= SCF_DO_STCLASS_OR;
}
}
scan= tail;
continue;
}
#else
else if (PL_regkind[OP(scan)] == TRIE) {
reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
U8*bang=NULL;
min += trie->minlen;
delta += (trie->maxlen - trie->minlen);
flags &= ~SCF_DO_STCLASS; /* xxx */
if (flags & SCF_DO_SUBSTR) {
/* Cannot expect anything... */
scan_commit(pRExC_state, data, minlenp, is_inf);
data->pos_min += trie->minlen;
data->pos_delta += (trie->maxlen - trie->minlen);
if (trie->maxlen != trie->minlen)
data->cur_is_floating = 1; /* float */
}
if (trie->jump) /* no more substrings -- for now /grr*/
flags &= ~SCF_DO_SUBSTR;
}
#endif /* old or new */
#endif /* TRIE_STUDY_OPT */
/* Else: zero-length, ignore. */
scan = regnext(scan);
}
finish:
if (frame) {
/* we need to unwind recursion. */
depth = depth - 1;
DEBUG_STUDYDATA("frame-end", data, depth, is_inf);
DEBUG_PEEP("fend", scan, depth, flags);
/* restore previous context */
last = frame->last_regnode;
scan = frame->next_regnode;
stopparen = frame->stopparen;
recursed_depth = frame->prev_recursed_depth;
RExC_frame_last = frame->prev_frame;
frame = frame->this_prev_frame;
goto fake_study_recurse;
}
assert(!frame);
DEBUG_STUDYDATA("pre-fin", data, depth, is_inf);
*scanp = scan;
*deltap = is_inf_internal ? SSize_t_MAX : delta;
if (flags & SCF_DO_SUBSTR && is_inf)
data->pos_delta = SSize_t_MAX - data->pos_min;
if (is_par > (I32)U8_MAX)
is_par = 0;
if (is_par && pars==1 && data) {
data->flags |= SF_IN_PAR;
data->flags &= ~SF_HAS_PAR;
}
else if (pars && data) {
data->flags |= SF_HAS_PAR;
data->flags &= ~SF_IN_PAR;
}
if (flags & SCF_DO_STCLASS_OR)
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
if (flags & SCF_TRIE_RESTUDY)
data->flags |= SCF_TRIE_RESTUDY;
DEBUG_STUDYDATA("post-fin", data, depth, is_inf);
{
SSize_t final_minlen= min < stopmin ? min : stopmin;
if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) {
if (final_minlen > SSize_t_MAX - delta)
RExC_maxlen = SSize_t_MAX;
else if (RExC_maxlen < final_minlen + delta)
RExC_maxlen = final_minlen + delta;
}
return final_minlen;
}
NOT_REACHED; /* NOTREACHED */
}
STATIC U32
S_add_data(RExC_state_t* const pRExC_state, const char* const s, const U32 n)
{
U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
PERL_ARGS_ASSERT_ADD_DATA;
Renewc(RExC_rxi->data,
sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
char, struct reg_data);
if(count)
Renew(RExC_rxi->data->what, count + n, U8);
else
Newx(RExC_rxi->data->what, n, U8);
RExC_rxi->data->count = count + n;
Copy(s, RExC_rxi->data->what + count, n, U8);
return count;
}
/*XXX: todo make this not included in a non debugging perl, but appears to be
* used anyway there, in 'use re' */
#ifndef PERL_IN_XSUB_RE
void
Perl_reginitcolors(pTHX)
{
const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
if (s) {
char *t = savepv(s);
int i = 0;
PL_colors[0] = t;
while (++i < 6) {
t = strchr(t, '\t');
if (t) {
*t = '\0';
PL_colors[i] = ++t;
}
else
PL_colors[i] = t = (char *)"";
}
} else {
int i = 0;
while (i < 6)
PL_colors[i++] = (char *)"";
}
PL_colorset = 1;
}
#endif
#ifdef TRIE_STUDY_OPT
#define CHECK_RESTUDY_GOTO_butfirst(dOsomething) \
STMT_START { \
if ( \
(data.flags & SCF_TRIE_RESTUDY) \
&& ! restudied++ \
) { \
dOsomething; \
goto reStudy; \
} \
} STMT_END
#else
#define CHECK_RESTUDY_GOTO_butfirst
#endif
/*
* pregcomp - compile a regular expression into internal code
*
* Decides which engine's compiler to call based on the hint currently in
* scope
*/
#ifndef PERL_IN_XSUB_RE
/* return the currently in-scope regex engine (or the default if none) */
regexp_engine const *
Perl_current_re_engine(pTHX)
{
if (IN_PERL_COMPILETIME) {
HV * const table = GvHV(PL_hintgv);
SV **ptr;
if (!table || !(PL_hints & HINT_LOCALIZE_HH))
return &PL_core_reg_engine;
ptr = hv_fetchs(table, "regcomp", FALSE);
if ( !(ptr && SvIOK(*ptr) && SvIV(*ptr)))
return &PL_core_reg_engine;
return INT2PTR(regexp_engine*,SvIV(*ptr));
}
else {
SV *ptr;
if (!PL_curcop->cop_hints_hash)
return &PL_core_reg_engine;
ptr = cop_hints_fetch_pvs(PL_curcop, "regcomp", 0);
if ( !(ptr && SvIOK(ptr) && SvIV(ptr)))
return &PL_core_reg_engine;
return INT2PTR(regexp_engine*,SvIV(ptr));
}
}
REGEXP *
Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
{
regexp_engine const *eng = current_re_engine();
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_PREGCOMP;
/* Dispatch a request to compile a regexp to correct regexp engine. */
DEBUG_COMPILE_r({
Perl_re_printf( aTHX_ "Using engine %" UVxf "\n",
PTR2UV(eng));
});
return CALLREGCOMP_ENG(eng, pattern, flags);
}
#endif
/* public(ish) entry point for the perl core's own regex compiling code.
* It's actually a wrapper for Perl_re_op_compile that only takes an SV
* pattern rather than a list of OPs, and uses the internal engine rather
* than the current one */
REGEXP *
Perl_re_compile(pTHX_ SV * const pattern, U32 rx_flags)
{
SV *pat = pattern; /* defeat constness! */
PERL_ARGS_ASSERT_RE_COMPILE;
return Perl_re_op_compile(aTHX_ &pat, 1, NULL,
#ifdef PERL_IN_XSUB_RE
&my_reg_engine,
#else
&PL_core_reg_engine,
#endif
NULL, NULL, rx_flags, 0);
}
static void
S_free_codeblocks(pTHX_ struct reg_code_blocks *cbs)
{
int n;
if (--cbs->refcnt > 0)
return;
for (n = 0; n < cbs->count; n++) {
REGEXP *rx = cbs->cb[n].src_regex;
cbs->cb[n].src_regex = NULL;
SvREFCNT_dec(rx);
}
Safefree(cbs->cb);
Safefree(cbs);
}
static struct reg_code_blocks *
S_alloc_code_blocks(pTHX_ int ncode)
{
struct reg_code_blocks *cbs;
Newx(cbs, 1, struct reg_code_blocks);
cbs->count = ncode;
cbs->refcnt = 1;
SAVEDESTRUCTOR_X(S_free_codeblocks, cbs);
if (ncode)
Newx(cbs->cb, ncode, struct reg_code_block);
else
cbs->cb = NULL;
return cbs;
}
/* upgrade pattern pat_p of length plen_p to UTF8, and if there are code
* blocks, recalculate the indices. Update pat_p and plen_p in-place to
* point to the realloced string and length.
*
* This is essentially a copy of Perl_bytes_to_utf8() with the code index
* stuff added */
static void
S_pat_upgrade_to_utf8(pTHX_ RExC_state_t * const pRExC_state,
char **pat_p, STRLEN *plen_p, int num_code_blocks)
{
U8 *const src = (U8*)*pat_p;
U8 *dst, *d;
int n=0;
STRLEN s = 0;
bool do_end = 0;
GET_RE_DEBUG_FLAGS_DECL;
DEBUG_PARSE_r(Perl_re_printf( aTHX_
"UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
Newx(dst, *plen_p * 2 + 1, U8);
d = dst;
while (s < *plen_p) {
append_utf8_from_native_byte(src[s], &d);
if (n < num_code_blocks) {
assert(pRExC_state->code_blocks);
if (!do_end && pRExC_state->code_blocks->cb[n].start == s) {
pRExC_state->code_blocks->cb[n].start = d - dst - 1;
assert(*(d - 1) == '(');
do_end = 1;
}
else if (do_end && pRExC_state->code_blocks->cb[n].end == s) {
pRExC_state->code_blocks->cb[n].end = d - dst - 1;
assert(*(d - 1) == ')');
do_end = 0;
n++;
}
}
s++;
}
*d = '\0';
*plen_p = d - dst;
*pat_p = (char*) dst;
SAVEFREEPV(*pat_p);
RExC_orig_utf8 = RExC_utf8 = 1;
}
/* S_concat_pat(): concatenate a list of args to the pattern string pat,
* while recording any code block indices, and handling overloading,
* nested qr// objects etc. If pat is null, it will allocate a new
* string, or just return the first arg, if there's only one.
*
* Returns the malloced/updated pat.
* patternp and pat_count is the array of SVs to be concatted;
* oplist is the optional list of ops that generated the SVs;
* recompile_p is a pointer to a boolean that will be set if
* the regex will need to be recompiled.
* delim, if non-null is an SV that will be inserted between each element
*/
static SV*
S_concat_pat(pTHX_ RExC_state_t * const pRExC_state,
SV *pat, SV ** const patternp, int pat_count,
OP *oplist, bool *recompile_p, SV *delim)
{
SV **svp;
int n = 0;
bool use_delim = FALSE;
bool alloced = FALSE;
/* if we know we have at least two args, create an empty string,
* then concatenate args to that. For no args, return an empty string */
if (!pat && pat_count != 1) {
pat = newSVpvs("");
SAVEFREESV(pat);
alloced = TRUE;
}
for (svp = patternp; svp < patternp + pat_count; svp++) {
SV *sv;
SV *rx = NULL;
STRLEN orig_patlen = 0;
bool code = 0;
SV *msv = use_delim ? delim : *svp;
if (!msv) msv = &PL_sv_undef;
/* if we've got a delimiter, we go round the loop twice for each
* svp slot (except the last), using the delimiter the second
* time round */
if (use_delim) {
svp--;
use_delim = FALSE;
}
else if (delim)
use_delim = TRUE;
if (SvTYPE(msv) == SVt_PVAV) {
/* we've encountered an interpolated array within
* the pattern, e.g. /...@a..../. Expand the list of elements,
* then recursively append elements.
* The code in this block is based on S_pushav() */
AV *const av = (AV*)msv;
const SSize_t maxarg = AvFILL(av) + 1;
SV **array;
if (oplist) {
assert(oplist->op_type == OP_PADAV
|| oplist->op_type == OP_RV2AV);
oplist = OpSIBLING(oplist);
}
if (SvRMAGICAL(av)) {
SSize_t i;
Newx(array, maxarg, SV*);
SAVEFREEPV(array);
for (i=0; i < maxarg; i++) {
SV ** const svp = av_fetch(av, i, FALSE);
array[i] = svp ? *svp : &PL_sv_undef;
}
}
else
array = AvARRAY(av);
pat = S_concat_pat(aTHX_ pRExC_state, pat,
array, maxarg, NULL, recompile_p,
/* $" */
GvSV((gv_fetchpvs("\"", GV_ADDMULTI, SVt_PV))));
continue;
}
/* we make the assumption here that each op in the list of
* op_siblings maps to one SV pushed onto the stack,
* except for code blocks, with have both an OP_NULL and
* and OP_CONST.
* This allows us to match up the list of SVs against the
* list of OPs to find the next code block.
*
* Note that PUSHMARK PADSV PADSV ..
* is optimised to
* PADRANGE PADSV PADSV ..
* so the alignment still works. */
if (oplist) {
if (oplist->op_type == OP_NULL
&& (oplist->op_flags & OPf_SPECIAL))
{
assert(n < pRExC_state->code_blocks->count);
pRExC_state->code_blocks->cb[n].start = pat ? SvCUR(pat) : 0;
pRExC_state->code_blocks->cb[n].block = oplist;
pRExC_state->code_blocks->cb[n].src_regex = NULL;
n++;
code = 1;
oplist = OpSIBLING(oplist); /* skip CONST */
assert(oplist);
}
oplist = OpSIBLING(oplist);;
}
/* apply magic and QR overloading to arg */
SvGETMAGIC(msv);
if (SvROK(msv) && SvAMAGIC(msv)) {
SV *sv = AMG_CALLunary(msv, regexp_amg);
if (sv) {
if (SvROK(sv))
sv = SvRV(sv);
if (SvTYPE(sv) != SVt_REGEXP)
Perl_croak(aTHX_ "Overloaded qr did not return a REGEXP");
msv = sv;
}
}
/* try concatenation overload ... */
if (pat && (SvAMAGIC(pat) || SvAMAGIC(msv)) &&
(sv = amagic_call(pat, msv, concat_amg, AMGf_assign)))
{
sv_setsv(pat, sv);
/* overloading involved: all bets are off over literal
* code. Pretend we haven't seen it */
if (n)
pRExC_state->code_blocks->count -= n;
n = 0;
}
else {
/* ... or failing that, try "" overload */
while (SvAMAGIC(msv)
&& (sv = AMG_CALLunary(msv, string_amg))
&& sv != msv
&& !( SvROK(msv)
&& SvROK(sv)
&& SvRV(msv) == SvRV(sv))
) {
msv = sv;
SvGETMAGIC(msv);
}
if (SvROK(msv) && SvTYPE(SvRV(msv)) == SVt_REGEXP)
msv = SvRV(msv);
if (pat) {
/* this is a partially unrolled
* sv_catsv_nomg(pat, msv);
* that allows us to adjust code block indices if
* needed */
STRLEN dlen;
char *dst = SvPV_force_nomg(pat, dlen);
orig_patlen = dlen;
if (SvUTF8(msv) && !SvUTF8(pat)) {
S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &dst, &dlen, n);
sv_setpvn(pat, dst, dlen);
SvUTF8_on(pat);
}
sv_catsv_nomg(pat, msv);
rx = msv;
}
else {
/* We have only one SV to process, but we need to verify
* it is properly null terminated or we will fail asserts
* later. In theory we probably shouldn't get such SV's,
* but if we do we should handle it gracefully. */
if ( SvTYPE(msv) != SVt_PV || (SvLEN(msv) > SvCUR(msv) && *(SvEND(msv)) == 0) ) {
/* not a string, or a string with a trailing null */
pat = msv;
} else {
/* a string with no trailing null, we need to copy it
* so it we have a trailing null */
pat = newSVsv(msv);
}
}
if (code)
pRExC_state->code_blocks->cb[n-1].end = SvCUR(pat)-1;
}
/* extract any code blocks within any embedded qr//'s */
if (rx && SvTYPE(rx) == SVt_REGEXP
&& RX_ENGINE((REGEXP*)rx)->op_comp)
{
RXi_GET_DECL(ReANY((REGEXP *)rx), ri);
if (ri->code_blocks && ri->code_blocks->count) {
int i;
/* the presence of an embedded qr// with code means
* we should always recompile: the text of the
* qr// may not have changed, but it may be a
* different closure than last time */
*recompile_p = 1;
if (pRExC_state->code_blocks) {
int new_count = pRExC_state->code_blocks->count
+ ri->code_blocks->count;
Renew(pRExC_state->code_blocks->cb,
new_count, struct reg_code_block);
pRExC_state->code_blocks->count = new_count;
}
else
pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_
ri->code_blocks->count);
for (i=0; i < ri->code_blocks->count; i++) {
struct reg_code_block *src, *dst;
STRLEN offset = orig_patlen
+ ReANY((REGEXP *)rx)->pre_prefix;
assert(n < pRExC_state->code_blocks->count);
src = &ri->code_blocks->cb[i];
dst = &pRExC_state->code_blocks->cb[n];
dst->start = src->start + offset;
dst->end = src->end + offset;
dst->block = src->block;
dst->src_regex = (REGEXP*) SvREFCNT_inc( (SV*)
src->src_regex
? src->src_regex
: (REGEXP*)rx);
n++;
}
}
}
}
/* avoid calling magic multiple times on a single element e.g. =~ $qr */
if (alloced)
SvSETMAGIC(pat);
return pat;
}
/* see if there are any run-time code blocks in the pattern.
* False positives are allowed */
static bool
S_has_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
char *pat, STRLEN plen)
{
int n = 0;
STRLEN s;
PERL_UNUSED_CONTEXT;
for (s = 0; s < plen; s++) {
if ( pRExC_state->code_blocks
&& n < pRExC_state->code_blocks->count
&& s == pRExC_state->code_blocks->cb[n].start)
{
s = pRExC_state->code_blocks->cb[n].end;
n++;
continue;
}
/* TODO ideally should handle [..], (#..), /#.../x to reduce false
* positives here */
if (pat[s] == '(' && s+2 <= plen && pat[s+1] == '?' &&
(pat[s+2] == '{'
|| (s + 2 <= plen && pat[s+2] == '?' && pat[s+3] == '{'))
)
return 1;
}
return 0;
}
/* Handle run-time code blocks. We will already have compiled any direct
* or indirect literal code blocks. Now, take the pattern 'pat' and make a
* copy of it, but with any literal code blocks blanked out and
* appropriate chars escaped; then feed it into
*
* eval "qr'modified_pattern'"
*
* For example,
*
* a\bc(?{"this was literal"})def'ghi\\jkl(?{"this is runtime"})mno
*
* becomes
*
* qr'a\\bc_______________________def\'ghi\\\\jkl(?{"this is runtime"})mno'
*
* After eval_sv()-ing that, grab any new code blocks from the returned qr
* and merge them with any code blocks of the original regexp.
*
* If the pat is non-UTF8, while the evalled qr is UTF8, don't merge;
* instead, just save the qr and return FALSE; this tells our caller that
* the original pattern needs upgrading to utf8.
*/
static bool
S_compile_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
char *pat, STRLEN plen)
{
SV *qr;
GET_RE_DEBUG_FLAGS_DECL;
if (pRExC_state->runtime_code_qr) {
/* this is the second time we've been called; this should
* only happen if the main pattern got upgraded to utf8
* during compilation; re-use the qr we compiled first time
* round (which should be utf8 too)
*/
qr = pRExC_state->runtime_code_qr;
pRExC_state->runtime_code_qr = NULL;
assert(RExC_utf8 && SvUTF8(qr));
}
else {
int n = 0;
STRLEN s;
char *p, *newpat;
int newlen = plen + 7; /* allow for "qr''xx\0" extra chars */
SV *sv, *qr_ref;
dSP;
/* determine how many extra chars we need for ' and \ escaping */
for (s = 0; s < plen; s++) {
if (pat[s] == '\'' || pat[s] == '\\')
newlen++;
}
Newx(newpat, newlen, char);
p = newpat;
*p++ = 'q'; *p++ = 'r'; *p++ = '\'';
for (s = 0; s < plen; s++) {
if ( pRExC_state->code_blocks
&& n < pRExC_state->code_blocks->count
&& s == pRExC_state->code_blocks->cb[n].start)
{
/* blank out literal code block */
assert(pat[s] == '(');
while (s <= pRExC_state->code_blocks->cb[n].end) {
*p++ = '_';
s++;
}
s--;
n++;
continue;
}
if (pat[s] == '\'' || pat[s] == '\\')
*p++ = '\\';
*p++ = pat[s];
}
*p++ = '\'';
if (pRExC_state->pm_flags & RXf_PMf_EXTENDED) {
*p++ = 'x';
if (pRExC_state->pm_flags & RXf_PMf_EXTENDED_MORE) {
*p++ = 'x';
}
}
*p++ = '\0';
DEBUG_COMPILE_r({
Perl_re_printf( aTHX_
"%sre-parsing pattern for runtime code:%s %s\n",
PL_colors[4],PL_colors[5],newpat);
});
sv = newSVpvn_flags(newpat, p-newpat-1, RExC_utf8 ? SVf_UTF8 : 0);
Safefree(newpat);
ENTER;
SAVETMPS;
save_re_context();
PUSHSTACKi(PERLSI_REQUIRE);
/* G_RE_REPARSING causes the toker to collapse \\ into \ when
* parsing qr''; normally only q'' does this. It also alters
* hints handling */
eval_sv(sv, G_SCALAR|G_RE_REPARSING);
SvREFCNT_dec_NN(sv);
SPAGAIN;
qr_ref = POPs;
PUTBACK;
{
SV * const errsv = ERRSV;
if (SvTRUE_NN(errsv))
/* use croak_sv ? */
Perl_croak_nocontext("%" SVf, SVfARG(errsv));
}
assert(SvROK(qr_ref));
qr = SvRV(qr_ref);
assert(SvTYPE(qr) == SVt_REGEXP && RX_ENGINE((REGEXP*)qr)->op_comp);
/* the leaving below frees the tmp qr_ref.
* Give qr a life of its own */
SvREFCNT_inc(qr);
POPSTACK;
FREETMPS;
LEAVE;
}
if (!RExC_utf8 && SvUTF8(qr)) {
/* first time through; the pattern got upgraded; save the
* qr for the next time through */
assert(!pRExC_state->runtime_code_qr);
pRExC_state->runtime_code_qr = qr;
return 0;
}
/* extract any code blocks within the returned qr// */
/* merge the main (r1) and run-time (r2) code blocks into one */
{
RXi_GET_DECL(ReANY((REGEXP *)qr), r2);
struct reg_code_block *new_block, *dst;
RExC_state_t * const r1 = pRExC_state; /* convenient alias */
int i1 = 0, i2 = 0;
int r1c, r2c;
if (!r2->code_blocks || !r2->code_blocks->count) /* we guessed wrong */
{
SvREFCNT_dec_NN(qr);
return 1;
}
if (!r1->code_blocks)
r1->code_blocks = S_alloc_code_blocks(aTHX_ 0);
r1c = r1->code_blocks->count;
r2c = r2->code_blocks->count;
Newx(new_block, r1c + r2c, struct reg_code_block);
dst = new_block;
while (i1 < r1c || i2 < r2c) {
struct reg_code_block *src;
bool is_qr = 0;
if (i1 == r1c) {
src = &r2->code_blocks->cb[i2++];
is_qr = 1;
}
else if (i2 == r2c)
src = &r1->code_blocks->cb[i1++];
else if ( r1->code_blocks->cb[i1].start
< r2->code_blocks->cb[i2].start)
{
src = &r1->code_blocks->cb[i1++];
assert(src->end < r2->code_blocks->cb[i2].start);
}
else {
assert( r1->code_blocks->cb[i1].start
> r2->code_blocks->cb[i2].start);
src = &r2->code_blocks->cb[i2++];
is_qr = 1;
assert(src->end < r1->code_blocks->cb[i1].start);
}
assert(pat[src->start] == '(');
assert(pat[src->end] == ')');
dst->start = src->start;
dst->end = src->end;
dst->block = src->block;
dst->src_regex = is_qr ? (REGEXP*) SvREFCNT_inc( (SV*) qr)
: src->src_regex;
dst++;
}
r1->code_blocks->count += r2c;
Safefree(r1->code_blocks->cb);
r1->code_blocks->cb = new_block;
}
SvREFCNT_dec_NN(qr);
return 1;
}
STATIC bool
S_setup_longest(pTHX_ RExC_state_t *pRExC_state,
struct reg_substr_datum *rsd,
struct scan_data_substrs *sub,
STRLEN longest_length)
{
/* This is the common code for setting up the floating and fixed length
* string data extracted from Perl_re_op_compile() below. Returns a boolean
* as to whether succeeded or not */
I32 t;
SSize_t ml;
bool eol = cBOOL(sub->flags & SF_BEFORE_EOL);
bool meol = cBOOL(sub->flags & SF_BEFORE_MEOL);
if (! (longest_length
|| (eol /* Can't have SEOL and MULTI */
&& (! meol || (RExC_flags & RXf_PMf_MULTILINE)))
)
/* See comments for join_exact for why REG_UNFOLDED_MULTI_SEEN */
|| (RExC_seen & REG_UNFOLDED_MULTI_SEEN))
{
return FALSE;
}
/* copy the information about the longest from the reg_scan_data
over to the program. */
if (SvUTF8(sub->str)) {
rsd->substr = NULL;
rsd->utf8_substr = sub->str;
} else {
rsd->substr = sub->str;
rsd->utf8_substr = NULL;
}
/* end_shift is how many chars that must be matched that
follow this item. We calculate it ahead of time as once the
lookbehind offset is added in we lose the ability to correctly
calculate it.*/
ml = sub->minlenp ? *(sub->minlenp) : (SSize_t)longest_length;
rsd->end_shift = ml - sub->min_offset
- longest_length
/* XXX SvTAIL is always false here - did you mean FBMcf_TAIL
* intead? - DAPM
+ (SvTAIL(sub->str) != 0)
*/
+ sub->lookbehind;
t = (eol/* Can't have SEOL and MULTI */
&& (! meol || (RExC_flags & RXf_PMf_MULTILINE)));
fbm_compile(sub->str, t ? FBMcf_TAIL : 0);
return TRUE;
}
/*
* Perl_re_op_compile - the perl internal RE engine's function to compile a
* regular expression into internal code.
* The pattern may be passed either as:
* a list of SVs (patternp plus pat_count)
* a list of OPs (expr)
* If both are passed, the SV list is used, but the OP list indicates
* which SVs are actually pre-compiled code blocks
*
* The SVs in the list have magic and qr overloading applied to them (and
* the list may be modified in-place with replacement SVs in the latter
* case).
*
* If the pattern hasn't changed from old_re, then old_re will be
* returned.
*
* eng is the current engine. If that engine has an op_comp method, then
* handle directly (i.e. we assume that op_comp was us); otherwise, just
* do the initial concatenation of arguments and pass on to the external
* engine.
*
* If is_bare_re is not null, set it to a boolean indicating whether the
* arg list reduced (after overloading) to a single bare regex which has
* been returned (i.e. /$qr/).
*
* orig_rx_flags contains RXf_* flags. See perlreapi.pod for more details.
*
* pm_flags contains the PMf_* flags, typically based on those from the
* pm_flags field of the related PMOP. Currently we're only interested in
* PMf_HAS_CV, PMf_IS_QR, PMf_USE_RE_EVAL.
*
* We can't allocate space until we know how big the compiled form will be,
* but we can't compile it (and thus know how big it is) until we've got a
* place to put the code. So we cheat: we compile it twice, once with code
* generation turned off and size counting turned on, and once "for real".
* This also means that we don't allocate space until we are sure that the
* thing really will compile successfully, and we never have to move the
* code and thus invalidate pointers into it. (Note that it has to be in
* one piece because free() must be able to free it all.) [NB: not true in perl]
*
* Beware that the optimization-preparation code in here knows about some
* of the structure of the compiled regexp. [I'll say.]
*/
REGEXP *
Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,
OP *expr, const regexp_engine* eng, REGEXP *old_re,
bool *is_bare_re, U32 orig_rx_flags, U32 pm_flags)
{
REGEXP *rx;
struct regexp *r;
regexp_internal *ri;
STRLEN plen;
char *exp;
regnode *scan;
I32 flags;
SSize_t minlen = 0;
U32 rx_flags;
SV *pat;
SV** new_patternp = patternp;
/* these are all flags - maybe they should be turned
* into a single int with different bit masks */
I32 sawlookahead = 0;
I32 sawplus = 0;
I32 sawopen = 0;
I32 sawminmod = 0;
regex_charset initial_charset = get_regex_charset(orig_rx_flags);
bool recompile = 0;
bool runtime_code = 0;
scan_data_t data;
RExC_state_t RExC_state;
RExC_state_t * const pRExC_state = &RExC_state;
#ifdef TRIE_STUDY_OPT
int restudied = 0;
RExC_state_t copyRExC_state;
#endif
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_RE_OP_COMPILE;
DEBUG_r(if (!PL_colorset) reginitcolors());
/* Initialize these here instead of as-needed, as is quick and avoids
* having to test them each time otherwise */
if (! PL_AboveLatin1) {
#ifdef DEBUGGING
char * dump_len_string;
#endif
PL_AboveLatin1 = _new_invlist_C_array(AboveLatin1_invlist);
PL_Latin1 = _new_invlist_C_array(Latin1_invlist);
PL_UpperLatin1 = _new_invlist_C_array(UpperLatin1_invlist);
PL_utf8_foldable = _new_invlist_C_array(_Perl_Any_Folds_invlist);
PL_HasMultiCharFold =
_new_invlist_C_array(_Perl_Folds_To_Multi_Char_invlist);
/* This is calculated here, because the Perl program that generates the
* static global ones doesn't currently have access to
* NUM_ANYOF_CODE_POINTS */
PL_InBitmap = _new_invlist(2);
PL_InBitmap = _add_range_to_invlist(PL_InBitmap, 0,
NUM_ANYOF_CODE_POINTS - 1);
#ifdef DEBUGGING
dump_len_string = PerlEnv_getenv("PERL_DUMP_RE_MAX_LEN");
if ( ! dump_len_string
|| ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL))
{
PL_dump_re_max_len = 60; /* A reasonable default */
}
#endif
}
pRExC_state->warn_text = NULL;
pRExC_state->code_blocks = NULL;
if (is_bare_re)
*is_bare_re = FALSE;
if (expr && (expr->op_type == OP_LIST ||
(expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) {
/* allocate code_blocks if needed */
OP *o;
int ncode = 0;
for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o))
if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL))
ncode++; /* count of DO blocks */
if (ncode)
pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode);
}
if (!pat_count) {
/* compile-time pattern with just OP_CONSTs and DO blocks */
int n;
OP *o;
/* find how many CONSTs there are */
assert(expr);
n = 0;
if (expr->op_type == OP_CONST)
n = 1;
else
for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
if (o->op_type == OP_CONST)
n++;
}
/* fake up an SV array */
assert(!new_patternp);
Newx(new_patternp, n, SV*);
SAVEFREEPV(new_patternp);
pat_count = n;
n = 0;
if (expr->op_type == OP_CONST)
new_patternp[n] = cSVOPx_sv(expr);
else
for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
if (o->op_type == OP_CONST)
new_patternp[n++] = cSVOPo_sv;
}
}
DEBUG_PARSE_r(Perl_re_printf( aTHX_
"Assembling pattern from %d elements%s\n", pat_count,
orig_rx_flags & RXf_SPLIT ? " for split" : ""));
/* set expr to the first arg op */
if (pRExC_state->code_blocks && pRExC_state->code_blocks->count
&& expr->op_type != OP_CONST)
{
expr = cLISTOPx(expr)->op_first;
assert( expr->op_type == OP_PUSHMARK
|| (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK)
|| expr->op_type == OP_PADRANGE);
expr = OpSIBLING(expr);
}
pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count,
expr, &recompile, NULL);
/* handle bare (possibly after overloading) regex: foo =~ $re */
{
SV *re = pat;
if (SvROK(re))
re = SvRV(re);
if (SvTYPE(re) == SVt_REGEXP) {
if (is_bare_re)
*is_bare_re = TRUE;
SvREFCNT_inc(re);
DEBUG_PARSE_r(Perl_re_printf( aTHX_
"Precompiled pattern%s\n",
orig_rx_flags & RXf_SPLIT ? " for split" : ""));
return (REGEXP*)re;
}
}
exp = SvPV_nomg(pat, plen);
if (!eng->op_comp) {
if ((SvUTF8(pat) && IN_BYTES)
|| SvGMAGICAL(pat) || SvAMAGIC(pat))
{
/* make a temporary copy; either to convert to bytes,
* or to avoid repeating get-magic / overloaded stringify */
pat = newSVpvn_flags(exp, plen, SVs_TEMP |
(IN_BYTES ? 0 : SvUTF8(pat)));
}
return CALLREGCOMP_ENG(eng, pat, orig_rx_flags);
}
/* ignore the utf8ness if the pattern is 0 length */
RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat);
RExC_uni_semantics = 0;
RExC_seen_unfolded_sharp_s = 0;
RExC_contains_locale = 0;
RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT);
RExC_study_started = 0;
pRExC_state->runtime_code_qr = NULL;
RExC_frame_head= NULL;
RExC_frame_last= NULL;
RExC_frame_count= 0;
DEBUG_r({
RExC_mysv1= sv_newmortal();
RExC_mysv2= sv_newmortal();
});
DEBUG_COMPILE_r({
SV *dsv= sv_newmortal();
RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len);
Perl_re_printf( aTHX_ "%sCompiling REx%s %s\n",
PL_colors[4],PL_colors[5],s);
});
redo_first_pass:
/* we jump here if we have to recompile, e.g., from upgrading the pattern
* to utf8 */
if ((pm_flags & PMf_USE_RE_EVAL)
/* this second condition covers the non-regex literal case,
* i.e. $foo =~ '(?{})'. */
|| (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL))
)
runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen);
/* return old regex if pattern hasn't changed */
/* XXX: note in the below we have to check the flags as well as the
* pattern.
*
* Things get a touch tricky as we have to compare the utf8 flag
* independently from the compile flags. */
if ( old_re
&& !recompile
&& !!RX_UTF8(old_re) == !!RExC_utf8
&& ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) )
&& RX_PRECOMP(old_re)
&& RX_PRELEN(old_re) == plen
&& memEQ(RX_PRECOMP(old_re), exp, plen)
&& !runtime_code /* with runtime code, always recompile */ )
{
return old_re;
}
rx_flags = orig_rx_flags;
if ( initial_charset == REGEX_DEPENDS_CHARSET
&& (RExC_utf8 ||RExC_uni_semantics))
{
/* Set to use unicode semantics if the pattern is in utf8 and has the
* 'depends' charset specified, as it means unicode when utf8 */
set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
}
RExC_precomp = exp;
RExC_precomp_adj = 0;
RExC_flags = rx_flags;
RExC_pm_flags = pm_flags;
if (runtime_code) {
assert(TAINTING_get || !TAINT_get);
if (TAINT_get)
Perl_croak(aTHX_ "Eval-group in insecure regular expression");
if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) {
/* whoops, we have a non-utf8 pattern, whilst run-time code
* got compiled as utf8. Try again with a utf8 pattern */
S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
goto redo_first_pass;
}
}
assert(!pRExC_state->runtime_code_qr);
RExC_sawback = 0;
RExC_seen = 0;
RExC_maxlen = 0;
RExC_in_lookbehind = 0;
RExC_seen_zerolen = *exp == '^' ? -1 : 0;
RExC_extralen = 0;
#ifdef EBCDIC
RExC_recode_x_to_native = 0;
#endif
RExC_in_multi_char_class = 0;
/* First pass: determine size, legality. */
RExC_parse = exp;
RExC_start = RExC_adjusted_start = exp;
RExC_end = exp + plen;
RExC_precomp_end = RExC_end;
RExC_naughty = 0;
RExC_npar = 1;
RExC_nestroot = 0;
RExC_size = 0L;
RExC_emit = (regnode *) &RExC_emit_dummy;
RExC_whilem_seen = 0;
RExC_open_parens = NULL;
RExC_close_parens = NULL;
RExC_end_op = NULL;
RExC_paren_names = NULL;
#ifdef DEBUGGING
RExC_paren_name_list = NULL;
#endif
RExC_recurse = NULL;
RExC_study_chunk_recursed = NULL;
RExC_study_chunk_recursed_bytes= 0;
RExC_recurse_count = 0;
pRExC_state->code_index = 0;
/* This NUL is guaranteed because the pattern comes from an SV*, and the sv
* code makes sure the final byte is an uncounted NUL. But should this
* ever not be the case, lots of things could read beyond the end of the
* buffer: loops like
* while(isFOO(*RExC_parse)) RExC_parse++;
* strchr(RExC_parse, "foo");
* etc. So it is worth noting. */
assert(*RExC_end == '\0');
DEBUG_PARSE_r(
Perl_re_printf( aTHX_ "Starting first pass (sizing)\n");
RExC_lastnum=0;
RExC_lastparse=NULL;
);
if (reg(pRExC_state, 0, &flags,1) == NULL) {
/* It's possible to write a regexp in ascii that represents Unicode
codepoints outside of the byte range, such as via \x{100}. If we
detect such a sequence we have to convert the entire pattern to utf8
and then recompile, as our sizing calculation will have been based
on 1 byte == 1 character, but we will need to use utf8 to encode
at least some part of the pattern, and therefore must convert the whole
thing.
-- dmq */
if (flags & RESTART_PASS1) {
if (flags & NEED_UTF8) {
S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
}
else {
DEBUG_PARSE_r(Perl_re_printf( aTHX_
"Need to redo pass 1\n"));
}
goto redo_first_pass;
}
Perl_croak(aTHX_ "panic: reg returned NULL to re_op_compile for sizing pass, flags=%#" UVxf, (UV) flags);
}
DEBUG_PARSE_r({
Perl_re_printf( aTHX_
"Required size %" IVdf " nodes\n"
"Starting second pass (creation)\n",
(IV)RExC_size);
RExC_lastnum=0;
RExC_lastparse=NULL;
});
/* The first pass could have found things that force Unicode semantics */
if ((RExC_utf8 || RExC_uni_semantics)
&& get_regex_charset(rx_flags) == REGEX_DEPENDS_CHARSET)
{
set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
}
/* Small enough for pointer-storage convention?
If extralen==0, this means that we will not need long jumps. */
if (RExC_size >= 0x10000L && RExC_extralen)
RExC_size += RExC_extralen;
else
RExC_extralen = 0;
if (RExC_whilem_seen > 15)
RExC_whilem_seen = 15;
/* Allocate space and zero-initialize. Note, the two step process
of zeroing when in debug mode, thus anything assigned has to
happen after that */
rx = (REGEXP*) newSV_type(SVt_REGEXP);
r = ReANY(rx);
Newxc(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode),
char, regexp_internal);
if ( r == NULL || ri == NULL )
FAIL("Regexp out of space");
#ifdef DEBUGGING
/* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
Zero(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode),
char);
#else
/* bulk initialize base fields with 0. */
Zero(ri, sizeof(regexp_internal), char);
#endif
/* non-zero initialization begins here */
RXi_SET( r, ri );
r->engine= eng;
r->extflags = rx_flags;
RXp_COMPFLAGS(r) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK;
if (pm_flags & PMf_IS_QR) {
ri->code_blocks = pRExC_state->code_blocks;
if (ri->code_blocks)
ri->code_blocks->refcnt++;
}
{
bool has_p = ((r->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
bool has_charset = (get_regex_charset(r->extflags)
!= REGEX_DEPENDS_CHARSET);
/* The caret is output if there are any defaults: if not all the STD
* flags are set, or if no character set specifier is needed */
bool has_default =
(((r->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD)
|| ! has_charset);
bool has_runon = ((RExC_seen & REG_RUN_ON_COMMENT_SEEN)
== REG_RUN_ON_COMMENT_SEEN);
U8 reganch = (U8)((r->extflags & RXf_PMf_STD_PMMOD)
>> RXf_PMf_STD_PMMOD_SHIFT);
const char *fptr = STD_PAT_MODS; /*"msixxn"*/
char *p;
/* We output all the necessary flags; we never output a minus, as all
* those are defaults, so are
* covered by the caret */
const STRLEN wraplen = plen + has_p + has_runon
+ has_default /* If needs a caret */
+ PL_bitcount[reganch] /* 1 char for each set standard flag */
/* If needs a character set specifier */
+ ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0)
+ (sizeof("(?:)") - 1);
/* make sure PL_bitcount bounds not exceeded */
assert(sizeof(STD_PAT_MODS) <= 8);
p = sv_grow(MUTABLE_SV(rx), wraplen + 1); /* +1 for the ending NUL */
SvPOK_on(rx);
if (RExC_utf8)
SvFLAGS(rx) |= SVf_UTF8;
*p++='('; *p++='?';
/* If a default, cover it using the caret */
if (has_default) {
*p++= DEFAULT_PAT_MOD;
}
if (has_charset) {
STRLEN len;
const char* const name = get_regex_charset_name(r->extflags, &len);
Copy(name, p, len, char);
p += len;
}
if (has_p)
*p++ = KEEPCOPY_PAT_MOD; /*'p'*/
{
char ch;
while((ch = *fptr++)) {
if(reganch & 1)
*p++ = ch;
reganch >>= 1;
}
}
*p++ = ':';
Copy(RExC_precomp, p, plen, char);
assert ((RX_WRAPPED(rx) - p) < 16);
r->pre_prefix = p - RX_WRAPPED(rx);
p += plen;
if (has_runon)
*p++ = '\n';
*p++ = ')';
*p = 0;
SvCUR_set(rx, p - RX_WRAPPED(rx));
}
r->intflags = 0;
r->nparens = RExC_npar - 1; /* set early to validate backrefs */
/* Useful during FAIL. */
#ifdef RE_TRACK_PATTERN_OFFSETS
Newxz(ri->u.offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
DEBUG_OFFSETS_r(Perl_re_printf( aTHX_
"%s %" UVuf " bytes for offset annotations.\n",
ri->u.offsets ? "Got" : "Couldn't get",
(UV)((2*RExC_size+1) * sizeof(U32))));
#endif
SetProgLen(ri,RExC_size);
RExC_rx_sv = rx;
RExC_rx = r;
RExC_rxi = ri;
/* Second pass: emit code. */
RExC_flags = rx_flags; /* don't let top level (?i) bleed */
RExC_pm_flags = pm_flags;
RExC_parse = exp;
RExC_end = exp + plen;
RExC_naughty = 0;
RExC_emit_start = ri->program;
RExC_emit = ri->program;
RExC_emit_bound = ri->program + RExC_size + 1;
pRExC_state->code_index = 0;
*((char*) RExC_emit++) = (char) REG_MAGIC;
/* setup various meta data about recursion, this all requires
* RExC_npar to be correctly set, and a bit later on we clear it */
if (RExC_seen & REG_RECURSE_SEEN) {
DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
"%*s%*s Setting up open/close parens\n",
22, "| |", (int)(0 * 2 + 1), ""));
/* setup RExC_open_parens, which holds the address of each
* OPEN tag, and to make things simpler for the 0 index
* the start of the program - this is used later for offsets */
Newxz(RExC_open_parens, RExC_npar,regnode *);
SAVEFREEPV(RExC_open_parens);
RExC_open_parens[0] = RExC_emit;
/* setup RExC_close_parens, which holds the address of each
* CLOSE tag, and to make things simpler for the 0 index
* the end of the program - this is used later for offsets */
Newxz(RExC_close_parens, RExC_npar,regnode *);
SAVEFREEPV(RExC_close_parens);
/* we dont know where end op starts yet, so we dont
* need to set RExC_close_parens[0] like we do RExC_open_parens[0] above */
/* Note, RExC_npar is 1 + the number of parens in a pattern.
* So its 1 if there are no parens. */
RExC_study_chunk_recursed_bytes= (RExC_npar >> 3) +
((RExC_npar & 0x07) != 0);
Newx(RExC_study_chunk_recursed,
RExC_study_chunk_recursed_bytes * RExC_npar, U8);
SAVEFREEPV(RExC_study_chunk_recursed);
}
RExC_npar = 1;
if (reg(pRExC_state, 0, &flags,1) == NULL) {
ReREFCNT_dec(rx);
Perl_croak(aTHX_ "panic: reg returned NULL to re_op_compile for generation pass, flags=%#" UVxf, (UV) flags);
}
DEBUG_OPTIMISE_r(
Perl_re_printf( aTHX_ "Starting post parse optimization\n");
);
/* XXXX To minimize changes to RE engine we always allocate
3-units-long substrs field. */
Newx(r->substrs, 1, struct reg_substr_data);
if (RExC_recurse_count) {
Newx(RExC_recurse,RExC_recurse_count,regnode *);
SAVEFREEPV(RExC_recurse);
}
reStudy:
r->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0;
DEBUG_r(
RExC_study_chunk_recursed_count= 0;
);
Zero(r->substrs, 1, struct reg_substr_data);
if (RExC_study_chunk_recursed) {
Zero(RExC_study_chunk_recursed,
RExC_study_chunk_recursed_bytes * RExC_npar, U8);
}
#ifdef TRIE_STUDY_OPT
if (!restudied) {
StructCopy(&zero_scan_data, &data, scan_data_t);
copyRExC_state = RExC_state;
} else {
U32 seen=RExC_seen;
DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "Restudying\n"));
RExC_state = copyRExC_state;
if (seen & REG_TOP_LEVEL_BRANCHES_SEEN)
RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
else
RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN;
StructCopy(&zero_scan_data, &data, scan_data_t);
}
#else
StructCopy(&zero_scan_data, &data, scan_data_t);
#endif
/* Dig out information for optimizations. */
r->extflags = RExC_flags; /* was pm_op */
/*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
if (UTF)
SvUTF8_on(rx); /* Unicode in it? */
ri->regstclass = NULL;
if (RExC_naughty >= TOO_NAUGHTY) /* Probably an expensive pattern. */
r->intflags |= PREGf_NAUGHTY;
scan = ri->program + 1; /* First BRANCH. */
/* testing for BRANCH here tells us whether there is "must appear"
data in the pattern. If there is then we can use it for optimisations */
if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /* Only one top-level choice.
*/
SSize_t fake;
STRLEN longest_length[2];
regnode_ssc ch_class; /* pointed to by data */
int stclass_flag;
SSize_t last_close = 0; /* pointed to by data */
regnode *first= scan;
regnode *first_next= regnext(first);
int i;
/*
* Skip introductions and multiplicators >= 1
* so that we can extract the 'meat' of the pattern that must
* match in the large if() sequence following.
* NOTE that EXACT is NOT covered here, as it is normally
* picked up by the optimiser separately.
*
* This is unfortunate as the optimiser isnt handling lookahead
* properly currently.
*
*/
while ((OP(first) == OPEN && (sawopen = 1)) ||
/* An OR of *one* alternative - should not happen now. */
(OP(first) == BRANCH && OP(first_next) != BRANCH) ||
/* for now we can't handle lookbehind IFMATCH*/
(OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) ||
(OP(first) == PLUS) ||
(OP(first) == MINMOD) ||
/* An {n,m} with n>0 */
(PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
(OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
{
/*
* the only op that could be a regnode is PLUS, all the rest
* will be regnode_1 or regnode_2.
*
* (yves doesn't think this is true)
*/
if (OP(first) == PLUS)
sawplus = 1;
else {
if (OP(first) == MINMOD)
sawminmod = 1;
first += regarglen[OP(first)];
}
first = NEXTOPER(first);
first_next= regnext(first);
}
/* Starting-point info. */
again:
DEBUG_PEEP("first:", first, 0, 0);
/* Ignore EXACT as we deal with it later. */
if (PL_regkind[OP(first)] == EXACT) {
if (OP(first) == EXACT || OP(first) == EXACTL)
NOOP; /* Empty, get anchored substr later. */
else
ri->regstclass = first;
}
#ifdef TRIE_STCLASS
else if (PL_regkind[OP(first)] == TRIE &&
((reg_trie_data *)ri->data->data[ ARG(first) ])->minlen>0)
{
/* this can happen only on restudy */
ri->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0);
}
#endif
else if (REGNODE_SIMPLE(OP(first)))
ri->regstclass = first;
else if (PL_regkind[OP(first)] == BOUND ||
PL_regkind[OP(first)] == NBOUND)
ri->regstclass = first;
else if (PL_regkind[OP(first)] == BOL) {
r->intflags |= (OP(first) == MBOL
? PREGf_ANCH_MBOL
: PREGf_ANCH_SBOL);
first = NEXTOPER(first);
goto again;
}
else if (OP(first) == GPOS) {
r->intflags |= PREGf_ANCH_GPOS;
first = NEXTOPER(first);
goto again;
}
else if ((!sawopen || !RExC_sawback) &&
!sawlookahead &&
(OP(first) == STAR &&
PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
!(r->intflags & PREGf_ANCH) && !pRExC_state->code_blocks)
{
/* turn .* into ^.* with an implied $*=1 */
const int type =
(OP(NEXTOPER(first)) == REG_ANY)
? PREGf_ANCH_MBOL
: PREGf_ANCH_SBOL;
r->intflags |= (type | PREGf_IMPLICIT);
first = NEXTOPER(first);
goto again;
}
if (sawplus && !sawminmod && !sawlookahead
&& (!sawopen || !RExC_sawback)
&& !pRExC_state->code_blocks) /* May examine pos and $& */
/* x+ must match at the 1st pos of run of x's */
r->intflags |= PREGf_SKIP;
/* Scan is after the zeroth branch, first is atomic matcher. */
#ifdef TRIE_STUDY_OPT
DEBUG_PARSE_r(
if (!restudied)
Perl_re_printf( aTHX_ "first at %" IVdf "\n",
(IV)(first - scan + 1))
);
#else
DEBUG_PARSE_r(
Perl_re_printf( aTHX_ "first at %" IVdf "\n",
(IV)(first - scan + 1))
);
#endif
/*
* If there's something expensive in the r.e., find the
* longest literal string that must appear and make it the
* regmust. Resolve ties in favor of later strings, since
* the regstart check works with the beginning of the r.e.
* and avoiding duplication strengthens checking. Not a
* strong reason, but sufficient in the absence of others.
* [Now we resolve ties in favor of the earlier string if
* it happens that c_offset_min has been invalidated, since the
* earlier string may buy us something the later one won't.]
*/
data.substrs[0].str = newSVpvs("");
data.substrs[1].str = newSVpvs("");
data.last_found = newSVpvs("");
data.cur_is_floating = 0; /* initially any found substring is fixed */
ENTER_with_name("study_chunk");
SAVEFREESV(data.substrs[0].str);
SAVEFREESV(data.substrs[1].str);
SAVEFREESV(data.last_found);
first = scan;
if (!ri->regstclass) {
ssc_init(pRExC_state, &ch_class);
data.start_class = &ch_class;
stclass_flag = SCF_DO_STCLASS_AND;
} else /* XXXX Check for BOUND? */
stclass_flag = 0;
data.last_closep = &last_close;
DEBUG_RExC_seen();
/*
* MAIN ENTRY FOR study_chunk() FOR m/PATTERN/
* (NO top level branches)
*/
minlen = study_chunk(pRExC_state, &first, &minlen, &fake,
scan + RExC_size, /* Up to end */
&data, -1, 0, NULL,
SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag
| (restudied ? SCF_TRIE_DOING_RESTUDY : 0),
0);
CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk"));
if ( RExC_npar == 1 && !data.cur_is_floating
&& data.last_start_min == 0 && data.last_end > 0
&& !RExC_seen_zerolen
&& !(RExC_seen & REG_VERBARG_SEEN)
&& !(RExC_seen & REG_GPOS_SEEN)
){
r->extflags |= RXf_CHECK_ALL;
}
scan_commit(pRExC_state, &data,&minlen,0);
/* XXX this is done in reverse order because that's the way the
* code was before it was parameterised. Don't know whether it
* actually needs doing in reverse order. DAPM */
for (i = 1; i >= 0; i--) {
longest_length[i] = CHR_SVLEN(data.substrs[i].str);
if ( !( i
&& SvCUR(data.substrs[0].str) /* ok to leave SvCUR */
&& data.substrs[0].min_offset
== data.substrs[1].min_offset
&& SvCUR(data.substrs[0].str)
== SvCUR(data.substrs[1].str)
)
&& S_setup_longest (aTHX_ pRExC_state,
&(r->substrs->data[i]),
&(data.substrs[i]),
longest_length[i]))
{
r->substrs->data[i].min_offset =
data.substrs[i].min_offset - data.substrs[i].lookbehind;
r->substrs->data[i].max_offset = data.substrs[i].max_offset;
/* Don't offset infinity */
if (data.substrs[i].max_offset < SSize_t_MAX)
r->substrs->data[i].max_offset -= data.substrs[i].lookbehind;
SvREFCNT_inc_simple_void_NN(data.substrs[i].str);
}
else {
r->substrs->data[i].substr = NULL;
r->substrs->data[i].utf8_substr = NULL;
longest_length[i] = 0;
}
}
LEAVE_with_name("study_chunk");
if (ri->regstclass
&& (OP(ri->regstclass) == REG_ANY || OP(ri->regstclass) == SANY))
ri->regstclass = NULL;
if ((!(r->substrs->data[0].substr || r->substrs->data[0].utf8_substr)
|| r->substrs->data[0].min_offset)
&& stclass_flag
&& ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
&& is_ssc_worth_it(pRExC_state, data.start_class))
{
const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
ssc_finalize(pRExC_state, data.start_class);
Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
StructCopy(data.start_class,
(regnode_ssc*)RExC_rxi->data->data[n],
regnode_ssc);
ri->regstclass = (regnode*)RExC_rxi->data->data[n];
r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
regprop(r, sv, (regnode*)data.start_class, NULL, pRExC_state);
Perl_re_printf( aTHX_
"synthetic stclass \"%s\".\n",
SvPVX_const(sv));});
data.start_class = NULL;
}
/* A temporary algorithm prefers floated substr to fixed one of
* same length to dig more info. */
i = (longest_length[0] <= longest_length[1]);
r->substrs->check_ix = i;
r->check_end_shift = r->substrs->data[i].end_shift;
r->check_substr = r->substrs->data[i].substr;
r->check_utf8 = r->substrs->data[i].utf8_substr;
r->check_offset_min = r->substrs->data[i].min_offset;
r->check_offset_max = r->substrs->data[i].max_offset;
if (!i && (r->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS)))
r->intflags |= PREGf_NOSCAN;
if ((r->check_substr || r->check_utf8) ) {
r->extflags |= RXf_USE_INTUIT;
if (SvTAIL(r->check_substr ? r->check_substr : r->check_utf8))
r->extflags |= RXf_INTUIT_TAIL;
}
/* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
if ( (STRLEN)minlen < longest_length[1] )
minlen= longest_length[1];
if ( (STRLEN)minlen < longest_length[0] )
minlen= longest_length[0];
*/
}
else {
/* Several toplevels. Best we can is to set minlen. */
SSize_t fake;
regnode_ssc ch_class;
SSize_t last_close = 0;
DEBUG_PARSE_r(Perl_re_printf( aTHX_ "\nMulti Top Level\n"));
scan = ri->program + 1;
ssc_init(pRExC_state, &ch_class);
data.start_class = &ch_class;
data.last_closep = &last_close;
DEBUG_RExC_seen();
/*
* MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../
* (patterns WITH top level branches)
*/
minlen = study_chunk(pRExC_state,
&scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL,
SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied
? SCF_TRIE_DOING_RESTUDY
: 0),
0);
CHECK_RESTUDY_GOTO_butfirst(NOOP);
r->check_substr = NULL;
r->check_utf8 = NULL;
r->substrs->data[0].substr = NULL;
r->substrs->data[0].utf8_substr = NULL;
r->substrs->data[1].substr = NULL;
r->substrs->data[1].utf8_substr = NULL;
if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
&& is_ssc_worth_it(pRExC_state, data.start_class))
{
const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
ssc_finalize(pRExC_state, data.start_class);
Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
StructCopy(data.start_class,
(regnode_ssc*)RExC_rxi->data->data[n],
regnode_ssc);
ri->regstclass = (regnode*)RExC_rxi->data->data[n];
r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
regprop(r, sv, (regnode*)data.start_class, NULL, pRExC_state);
Perl_re_printf( aTHX_
"synthetic stclass \"%s\".\n",
SvPVX_const(sv));});
data.start_class = NULL;
}
}
if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) {
r->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN;
r->maxlen = REG_INFTY;
}
else {
r->maxlen = RExC_maxlen;
}
/* Guard against an embedded (?=) or (?<=) with a longer minlen than
the "real" pattern. */
DEBUG_OPTIMISE_r({
Perl_re_printf( aTHX_ "minlen: %" IVdf " r->minlen:%" IVdf " maxlen:%" IVdf "\n",
(IV)minlen, (IV)r->minlen, (IV)RExC_maxlen);
});
r->minlenret = minlen;
if (r->minlen < minlen)
r->minlen = minlen;
if (RExC_seen & REG_RECURSE_SEEN ) {
r->intflags |= PREGf_RECURSE_SEEN;
Newx(r->recurse_locinput, r->nparens + 1, char *);
}
if (RExC_seen & REG_GPOS_SEEN)
r->intflags |= PREGf_GPOS_SEEN;
if (RExC_seen & REG_LOOKBEHIND_SEEN)
r->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the
lookbehind */
if (pRExC_state->code_blocks)
r->extflags |= RXf_EVAL_SEEN;
if (RExC_seen & REG_VERBARG_SEEN)
{
r->intflags |= PREGf_VERBARG_SEEN;
r->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */
}
if (RExC_seen & REG_CUTGROUP_SEEN)
r->intflags |= PREGf_CUTGROUP_SEEN;
if (pm_flags & PMf_USE_RE_EVAL)
r->intflags |= PREGf_USE_RE_EVAL;
if (RExC_paren_names)
RXp_PAREN_NAMES(r) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
else
RXp_PAREN_NAMES(r) = NULL;
/* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED
* so it can be used in pp.c */
if (r->intflags & PREGf_ANCH)
r->extflags |= RXf_IS_ANCHORED;
{
/* this is used to identify "special" patterns that might result
* in Perl NOT calling the regex engine and instead doing the match "itself",
* particularly special cases in split//. By having the regex compiler
* do this pattern matching at a regop level (instead of by inspecting the pattern)
* we avoid weird issues with equivalent patterns resulting in different behavior,
* AND we allow non Perl engines to get the same optimizations by the setting the
* flags appropriately - Yves */
regnode *first = ri->program + 1;
U8 fop = OP(first);
regnode *next = regnext(first);
U8 nop = OP(next);
if (PL_regkind[fop] == NOTHING && nop == END)
r->extflags |= RXf_NULL;
else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END)
/* when fop is SBOL first->flags will be true only when it was
* produced by parsing /\A/, and not when parsing /^/. This is
* very important for the split code as there we want to
* treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m.
* See rt #122761 for more details. -- Yves */
r->extflags |= RXf_START_ONLY;
else if (fop == PLUS
&& PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE
&& nop == END)
r->extflags |= RXf_WHITE;
else if ( r->extflags & RXf_SPLIT
&& (fop == EXACT || fop == EXACTL)
&& STR_LEN(first) == 1
&& *(STRING(first)) == ' '
&& nop == END )
r->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
}
if (RExC_contains_locale) {
RXp_EXTFLAGS(r) |= RXf_TAINTED;
}
#ifdef DEBUGGING
if (RExC_paren_names) {
ri->name_list_idx = add_data( pRExC_state, STR_WITH_LEN("a"));
ri->data->data[ri->name_list_idx]
= (void*)SvREFCNT_inc(RExC_paren_name_list);
} else
#endif
ri->name_list_idx = 0;
while ( RExC_recurse_count > 0 ) {
const regnode *scan = RExC_recurse[ --RExC_recurse_count ];
/*
* This data structure is set up in study_chunk() and is used
* to calculate the distance between a GOSUB regopcode and
* the OPEN/CURLYM (CURLYM's are special and can act like OPEN's)
* it refers to.
*
* If for some reason someone writes code that optimises
* away a GOSUB opcode then the assert should be changed to
* an if(scan) to guard the ARG2L_SET() - Yves
*
*/
assert(scan && OP(scan) == GOSUB);
ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - scan );
}
Newxz(r->offs, RExC_npar, regexp_paren_pair);
/* assume we don't need to swap parens around before we match */
DEBUG_TEST_r({
Perl_re_printf( aTHX_ "study_chunk_recursed_count: %lu\n",
(unsigned long)RExC_study_chunk_recursed_count);
});
DEBUG_DUMP_r({
DEBUG_RExC_seen();
Perl_re_printf( aTHX_ "Final program:\n");
regdump(r);
});
#ifdef RE_TRACK_PATTERN_OFFSETS
DEBUG_OFFSETS_r(if (ri->u.offsets) {
const STRLEN len = ri->u.offsets[0];
STRLEN i;
GET_RE_DEBUG_FLAGS_DECL;
Perl_re_printf( aTHX_
"Offsets: [%" UVuf "]\n\t", (UV)ri->u.offsets[0]);
for (i = 1; i <= len; i++) {
if (ri->u.offsets[i*2-1] || ri->u.offsets[i*2])
Perl_re_printf( aTHX_ "%" UVuf ":%" UVuf "[%" UVuf "] ",
(UV)i, (UV)ri->u.offsets[i*2-1], (UV)ri->u.offsets[i*2]);
}
Perl_re_printf( aTHX_ "\n");
});
#endif
#ifdef USE_ITHREADS
/* under ithreads the ?pat? PMf_USED flag on the pmop is simulated
* by setting the regexp SV to readonly-only instead. If the
* pattern's been recompiled, the USEDness should remain. */
if (old_re && SvREADONLY(old_re))
SvREADONLY_on(rx);
#endif
return rx;
}
SV*
Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
const U32 flags)
{
PERL_ARGS_ASSERT_REG_NAMED_BUFF;
PERL_UNUSED_ARG(value);
if (flags & RXapif_FETCH) {
return reg_named_buff_fetch(rx, key, flags);
} else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
Perl_croak_no_modify();
return NULL;
} else if (flags & RXapif_EXISTS) {
return reg_named_buff_exists(rx, key, flags)
? &PL_sv_yes
: &PL_sv_no;
} else if (flags & RXapif_REGNAMES) {
return reg_named_buff_all(rx, flags);
} else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
return reg_named_buff_scalar(rx, flags);
} else {
Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
return NULL;
}
}
SV*
Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
const U32 flags)
{
PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
PERL_UNUSED_ARG(lastkey);
if (flags & RXapif_FIRSTKEY)
return reg_named_buff_firstkey(rx, flags);
else if (flags & RXapif_NEXTKEY)
return reg_named_buff_nextkey(rx, flags);
else {
Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter",
(int)flags);
return NULL;
}
}
SV*
Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
const U32 flags)
{
SV *ret;
struct regexp *const rx = ReANY(r);
PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
if (rx && RXp_PAREN_NAMES(rx)) {
HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
if (he_str) {
IV i;
SV* sv_dat=HeVAL(he_str);
I32 *nums=(I32*)SvPVX(sv_dat);
AV * const retarray = (flags & RXapif_ALL) ? newAV() : NULL;
for ( i=0; i<SvIVX(sv_dat); i++ ) {
if ((I32)(rx->nparens) >= nums[i]
&& rx->offs[nums[i]].start != -1
&& rx->offs[nums[i]].end != -1)
{
ret = newSVpvs("");
CALLREG_NUMBUF_FETCH(r,nums[i],ret);
if (!retarray)
return ret;
} else {
if (retarray)
ret = newSVsv(&PL_sv_undef);
}
if (retarray)
av_push(retarray, ret);
}
if (retarray)
return newRV_noinc(MUTABLE_SV(retarray));
}
}
return NULL;
}
bool
Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
const U32 flags)
{
struct regexp *const rx = ReANY(r);
PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
if (rx && RXp_PAREN_NAMES(rx)) {
if (flags & RXapif_ALL) {
return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
} else {
SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
if (sv) {
SvREFCNT_dec_NN(sv);
return TRUE;
} else {
return FALSE;
}
}
} else {
return FALSE;
}
}
SV*
Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
{
struct regexp *const rx = ReANY(r);
PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
if ( rx && RXp_PAREN_NAMES(rx) ) {
(void)hv_iterinit(RXp_PAREN_NAMES(rx));
return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
} else {
return FALSE;
}
}
SV*
Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
{
struct regexp *const rx = ReANY(r);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
if (rx && RXp_PAREN_NAMES(rx)) {
HV *hv = RXp_PAREN_NAMES(rx);
HE *temphe;
while ( (temphe = hv_iternext_flags(hv,0)) ) {
IV i;
IV parno = 0;
SV* sv_dat = HeVAL(temphe);
I32 *nums = (I32*)SvPVX(sv_dat);
for ( i = 0; i < SvIVX(sv_dat); i++ ) {
if ((I32)(rx->lastparen) >= nums[i] &&
rx->offs[nums[i]].start != -1 &&
rx->offs[nums[i]].end != -1)
{
parno = nums[i];
break;
}
}
if (parno || flags & RXapif_ALL) {
return newSVhek(HeKEY_hek(temphe));
}
}
}
return NULL;
}
SV*
Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
{
SV *ret;
AV *av;
SSize_t length;
struct regexp *const rx = ReANY(r);
PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
if (rx && RXp_PAREN_NAMES(rx)) {
if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
} else if (flags & RXapif_ONE) {
ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
av = MUTABLE_AV(SvRV(ret));
length = av_tindex(av);
SvREFCNT_dec_NN(ret);
return newSViv(length + 1);
} else {
Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar",
(int)flags);
return NULL;
}
}
return &PL_sv_undef;
}
SV*
Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
{
struct regexp *const rx = ReANY(r);
AV *av = newAV();
PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
if (rx && RXp_PAREN_NAMES(rx)) {
HV *hv= RXp_PAREN_NAMES(rx);
HE *temphe;
(void)hv_iterinit(hv);
while ( (temphe = hv_iternext_flags(hv,0)) ) {
IV i;
IV parno = 0;
SV* sv_dat = HeVAL(temphe);
I32 *nums = (I32*)SvPVX(sv_dat);
for ( i = 0; i < SvIVX(sv_dat); i++ ) {
if ((I32)(rx->lastparen) >= nums[i] &&
rx->offs[nums[i]].start != -1 &&
rx->offs[nums[i]].end != -1)
{
parno = nums[i];
break;
}
}
if (parno || flags & RXapif_ALL) {
av_push(av, newSVhek(HeKEY_hek(temphe)));
}
}
}
return newRV_noinc(MUTABLE_SV(av));
}
void
Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
SV * const sv)
{
struct regexp *const rx = ReANY(r);
char *s = NULL;
SSize_t i = 0;
SSize_t s1, t1;
I32 n = paren;
PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
if ( n == RX_BUFF_IDX_CARET_PREMATCH
|| n == RX_BUFF_IDX_CARET_FULLMATCH
|| n == RX_BUFF_IDX_CARET_POSTMATCH
)
{
bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
if (!keepcopy) {
/* on something like
* $r = qr/.../;
* /$qr/p;
* the KEEPCOPY is set on the PMOP rather than the regex */
if (PL_curpm && r == PM_GETRE(PL_curpm))
keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
}
if (!keepcopy)
goto ret_undef;
}
if (!rx->subbeg)
goto ret_undef;
if (n == RX_BUFF_IDX_CARET_FULLMATCH)
/* no need to distinguish between them any more */
n = RX_BUFF_IDX_FULLMATCH;
if ((n == RX_BUFF_IDX_PREMATCH || n == RX_BUFF_IDX_CARET_PREMATCH)
&& rx->offs[0].start != -1)
{
/* $`, ${^PREMATCH} */
i = rx->offs[0].start;
s = rx->subbeg;
}
else
if ((n == RX_BUFF_IDX_POSTMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH)
&& rx->offs[0].end != -1)
{
/* $', ${^POSTMATCH} */
s = rx->subbeg - rx->suboffset + rx->offs[0].end;
i = rx->sublen + rx->suboffset - rx->offs[0].end;
}
else
if ( 0 <= n && n <= (I32)rx->nparens &&
(s1 = rx->offs[n].start) != -1 &&
(t1 = rx->offs[n].end) != -1)
{
/* $&, ${^MATCH}, $1 ... */
i = t1 - s1;
s = rx->subbeg + s1 - rx->suboffset;
} else {
goto ret_undef;
}
assert(s >= rx->subbeg);
assert((STRLEN)rx->sublen >= (STRLEN)((s - rx->subbeg) + i) );
if (i >= 0) {
#ifdef NO_TAINT_SUPPORT
sv_setpvn(sv, s, i);
#else
const int oldtainted = TAINT_get;
TAINT_NOT;
sv_setpvn(sv, s, i);
TAINT_set(oldtainted);
#endif
if (RXp_MATCH_UTF8(rx))
SvUTF8_on(sv);
else
SvUTF8_off(sv);
if (TAINTING_get) {
if (RXp_MATCH_TAINTED(rx)) {
if (SvTYPE(sv) >= SVt_PVMG) {
MAGIC* const mg = SvMAGIC(sv);
MAGIC* mgt;
TAINT;
SvMAGIC_set(sv, mg->mg_moremagic);
SvTAINT(sv);
if ((mgt = SvMAGIC(sv))) {
mg->mg_moremagic = mgt;
SvMAGIC_set(sv, mg);
}
} else {
TAINT;
SvTAINT(sv);
}
} else
SvTAINTED_off(sv);
}
} else {
ret_undef:
sv_set_undef(sv);
return;
}
}
void
Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
SV const * const value)
{
PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
PERL_UNUSED_ARG(rx);
PERL_UNUSED_ARG(paren);
PERL_UNUSED_ARG(value);
if (!PL_localizing)
Perl_croak_no_modify();
}
I32
Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
const I32 paren)
{
struct regexp *const rx = ReANY(r);
I32 i;
I32 s1, t1;
PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
if ( paren == RX_BUFF_IDX_CARET_PREMATCH
|| paren == RX_BUFF_IDX_CARET_FULLMATCH
|| paren == RX_BUFF_IDX_CARET_POSTMATCH
)
{
bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
if (!keepcopy) {
/* on something like
* $r = qr/.../;
* /$qr/p;
* the KEEPCOPY is set on the PMOP rather than the regex */
if (PL_curpm && r == PM_GETRE(PL_curpm))
keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
}
if (!keepcopy)
goto warn_undef;
}
/* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
switch (paren) {
case RX_BUFF_IDX_CARET_PREMATCH: /* ${^PREMATCH} */
case RX_BUFF_IDX_PREMATCH: /* $` */
if (rx->offs[0].start != -1) {
i = rx->offs[0].start;
if (i > 0) {
s1 = 0;
t1 = i;
goto getlen;
}
}
return 0;
case RX_BUFF_IDX_CARET_POSTMATCH: /* ${^POSTMATCH} */
case RX_BUFF_IDX_POSTMATCH: /* $' */
if (rx->offs[0].end != -1) {
i = rx->sublen - rx->offs[0].end;
if (i > 0) {
s1 = rx->offs[0].end;
t1 = rx->sublen;
goto getlen;
}
}
return 0;
default: /* $& / ${^MATCH}, $1, $2, ... */
if (paren <= (I32)rx->nparens &&
(s1 = rx->offs[paren].start) != -1 &&
(t1 = rx->offs[paren].end) != -1)
{
i = t1 - s1;
goto getlen;
} else {
warn_undef:
if (ckWARN(WARN_UNINITIALIZED))
report_uninit((const SV *)sv);
return 0;
}
}
getlen:
if (i > 0 && RXp_MATCH_UTF8(rx)) {
const char * const s = rx->subbeg - rx->suboffset + s1;
const U8 *ep;
STRLEN el;
i = t1 - s1;
if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
i = el;
}
return i;
}
SV*
Perl_reg_qr_package(pTHX_ REGEXP * const rx)
{
PERL_ARGS_ASSERT_REG_QR_PACKAGE;
PERL_UNUSED_ARG(rx);
if (0)
return NULL;
else
return newSVpvs("Regexp");
}
/* Scans the name of a named buffer from the pattern.
* If flags is REG_RSN_RETURN_NULL returns null.
* If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
* If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
* to the parsed name as looked up in the RExC_paren_names hash.
* If there is an error throws a vFAIL().. type exception.
*/
#define REG_RSN_RETURN_NULL 0
#define REG_RSN_RETURN_NAME 1
#define REG_RSN_RETURN_DATA 2
STATIC SV*
S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
{
char *name_start = RExC_parse;
PERL_ARGS_ASSERT_REG_SCAN_NAME;
assert (RExC_parse <= RExC_end);
if (RExC_parse == RExC_end) NOOP;
else if (isIDFIRST_lazy_if_safe(RExC_parse, RExC_end, UTF)) {
/* Note that the code here assumes well-formed UTF-8. Skip IDFIRST by
* using do...while */
if (UTF)
do {
RExC_parse += UTF8SKIP(RExC_parse);
} while ( RExC_parse < RExC_end
&& isWORDCHAR_utf8_safe((U8*)RExC_parse, (U8*) RExC_end));
else
do {
RExC_parse++;
} while (RExC_parse < RExC_end && isWORDCHAR(*RExC_parse));
} else {
RExC_parse++; /* so the <- from the vFAIL is after the offending
character */
vFAIL("Group name must start with a non-digit word character");
}
if ( flags ) {
SV* sv_name
= newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
SVs_TEMP | (UTF ? SVf_UTF8 : 0));
if ( flags == REG_RSN_RETURN_NAME)
return sv_name;
else if (flags==REG_RSN_RETURN_DATA) {
HE *he_str = NULL;
SV *sv_dat = NULL;
if ( ! sv_name ) /* should not happen*/
Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
if (RExC_paren_names)
he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
if ( he_str )
sv_dat = HeVAL(he_str);
if ( ! sv_dat )
vFAIL("Reference to nonexistent named group");
return sv_dat;
}
else {
Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name",
(unsigned long) flags);
}
NOT_REACHED; /* NOTREACHED */
}
return NULL;
}
#define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \
int num; \
if (RExC_lastparse!=RExC_parse) { \
Perl_re_printf( aTHX_ "%s", \
Perl_pv_pretty(aTHX_ RExC_mysv1, RExC_parse, \
RExC_end - RExC_parse, 16, \
"", "", \
PERL_PV_ESCAPE_UNI_DETECT | \
PERL_PV_PRETTY_ELLIPSES | \
PERL_PV_PRETTY_LTGT | \
PERL_PV_ESCAPE_RE | \
PERL_PV_PRETTY_EXACTSIZE \
) \
); \
} else \
Perl_re_printf( aTHX_ "%16s",""); \
\
if (SIZE_ONLY) \
num = RExC_size + 1; \
else \
num=REG_NODE_NUM(RExC_emit); \
if (RExC_lastnum!=num) \
Perl_re_printf( aTHX_ "|%4d",num); \
else \
Perl_re_printf( aTHX_ "|%4s",""); \
Perl_re_printf( aTHX_ "|%*s%-4s", \
(int)((depth*2)), "", \
(funcname) \
); \
RExC_lastnum=num; \
RExC_lastparse=RExC_parse; \
})
#define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \
DEBUG_PARSE_MSG((funcname)); \
Perl_re_printf( aTHX_ "%4s","\n"); \
})
#define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({\
DEBUG_PARSE_MSG((funcname)); \
Perl_re_printf( aTHX_ fmt "\n",args); \
})
/* This section of code defines the inversion list object and its methods. The
* interfaces are highly subject to change, so as much as possible is static to
* this file. An inversion list is here implemented as a malloc'd C UV array
* as an SVt_INVLIST scalar.
*
* An inversion list for Unicode is an array of code points, sorted by ordinal
* number. Each element gives the code point that begins a range that extends
* up-to but not including the code point given by the next element. The final
* element gives the first code point of a range that extends to the platform's
* infinity. The even-numbered elements (invlist[0], invlist[2], invlist[4],
* ...) give ranges whose code points are all in the inversion list. We say
* that those ranges are in the set. The odd-numbered elements give ranges
* whose code points are not in the inversion list, and hence not in the set.
* Thus, element [0] is the first code point in the list. Element [1]
* is the first code point beyond that not in the list; and element [2] is the
* first code point beyond that that is in the list. In other words, the first
* range is invlist[0]..(invlist[1]-1), and all code points in that range are
* in the inversion list. The second range is invlist[1]..(invlist[2]-1), and
* all code points in that range are not in the inversion list. The third
* range invlist[2]..(invlist[3]-1) gives code points that are in the inversion
* list, and so forth. Thus every element whose index is divisible by two
* gives the beginning of a range that is in the list, and every element whose
* index is not divisible by two gives the beginning of a range not in the
* list. If the final element's index is divisible by two, the inversion list
* extends to the platform's infinity; otherwise the highest code point in the
* inversion list is the contents of that element minus 1.
*
* A range that contains just a single code point N will look like
* invlist[i] == N
* invlist[i+1] == N+1
*
* If N is UV_MAX (the highest representable code point on the machine), N+1 is
* impossible to represent, so element [i+1] is omitted. The single element
* inversion list
* invlist[0] == UV_MAX
* contains just UV_MAX, but is interpreted as matching to infinity.
*
* Taking the complement (inverting) an inversion list is quite simple, if the
* first element is 0, remove it; otherwise add a 0 element at the beginning.
* This implementation reserves an element at the beginning of each inversion
* list to always contain 0; there is an additional flag in the header which
* indicates if the list begins at the 0, or is offset to begin at the next
* element. This means that the inversion list can be inverted without any
* copying; just flip the flag.
*
* More about inversion lists can be found in "Unicode Demystified"
* Chapter 13 by Richard Gillam, published by Addison-Wesley.
*
* The inversion list data structure is currently implemented as an SV pointing
* to an array of UVs that the SV thinks are bytes. This allows us to have an
* array of UV whose memory management is automatically handled by the existing
* facilities for SV's.
*
* Some of the methods should always be private to the implementation, and some
* should eventually be made public */
/* The header definitions are in F<invlist_inline.h> */
#ifndef PERL_IN_XSUB_RE
PERL_STATIC_INLINE UV*
S__invlist_array_init(SV* const invlist, const bool will_have_0)
{
/* Returns a pointer to the first element in the inversion list's array.
* This is called upon initialization of an inversion list. Where the
* array begins depends on whether the list has the code point U+0000 in it
* or not. The other parameter tells it whether the code that follows this
* call is about to put a 0 in the inversion list or not. The first
* element is either the element reserved for 0, if TRUE, or the element
* after it, if FALSE */
bool* offset = get_invlist_offset_addr(invlist);
UV* zero_addr = (UV *) SvPVX(invlist);
PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT;
/* Must be empty */
assert(! _invlist_len(invlist));
*zero_addr = 0;
/* 1^1 = 0; 1^0 = 1 */
*offset = 1 ^ will_have_0;
return zero_addr + *offset;
}
#endif
PERL_STATIC_INLINE void
S_invlist_set_len(pTHX_ SV* const invlist, const UV len, const bool offset)
{
/* Sets the current number of elements stored in the inversion list.
* Updates SvCUR correspondingly */
PERL_UNUSED_CONTEXT;
PERL_ARGS_ASSERT_INVLIST_SET_LEN;
assert(SvTYPE(invlist) == SVt_INVLIST);
SvCUR_set(invlist,
(len == 0)
? 0
: TO_INTERNAL_SIZE(len + offset));
assert(SvLEN(invlist) == 0 || SvCUR(invlist) <= SvLEN(invlist));
}
#ifndef PERL_IN_XSUB_RE
STATIC void
S_invlist_replace_list_destroys_src(pTHX_ SV * dest, SV * src)
{
/* Replaces the inversion list in 'dest' with the one from 'src'. It
* steals the list from 'src', so 'src' is made to have a NULL list. This
* is similar to what SvSetMagicSV() would do, if it were implemented on
* inversion lists, though this routine avoids a copy */
const UV src_len = _invlist_len(src);
const bool src_offset = *get_invlist_offset_addr(src);
const STRLEN src_byte_len = SvLEN(src);
char * array = SvPVX(src);
const int oldtainted = TAINT_get;
PERL_ARGS_ASSERT_INVLIST_REPLACE_LIST_DESTROYS_SRC;
assert(SvTYPE(src) == SVt_INVLIST);
assert(SvTYPE(dest) == SVt_INVLIST);
assert(! invlist_is_iterating(src));
assert(SvCUR(src) == 0 || SvCUR(src) < SvLEN(src));
/* Make sure it ends in the right place with a NUL, as our inversion list
* manipulations aren't careful to keep this true, but sv_usepvn_flags()
* asserts it */
array[src_byte_len - 1] = '\0';
TAINT_NOT; /* Otherwise it breaks */
sv_usepvn_flags(dest,
(char *) array,
src_byte_len - 1,
/* This flag is documented to cause a copy to be avoided */
SV_HAS_TRAILING_NUL);
TAINT_set(oldtainted);
SvPV_set(src, 0);
SvLEN_set(src, 0);
SvCUR_set(src, 0);
/* Finish up copying over the other fields in an inversion list */
*get_invlist_offset_addr(dest) = src_offset;
invlist_set_len(dest, src_len, src_offset);
*get_invlist_previous_index_addr(dest) = 0;
invlist_iterfinish(dest);
}
PERL_STATIC_INLINE IV*
S_get_invlist_previous_index_addr(SV* invlist)
{
/* Return the address of the IV that is reserved to hold the cached index
* */
PERL_ARGS_ASSERT_GET_INVLIST_PREVIOUS_INDEX_ADDR;
assert(SvTYPE(invlist) == SVt_INVLIST);
return &(((XINVLIST*) SvANY(invlist))->prev_index);
}
PERL_STATIC_INLINE IV
S_invlist_previous_index(SV* const invlist)
{
/* Returns cached index of previous search */
PERL_ARGS_ASSERT_INVLIST_PREVIOUS_INDEX;
return *get_invlist_previous_index_addr(invlist);
}
PERL_STATIC_INLINE void
S_invlist_set_previous_index(SV* const invlist, const IV index)
{
/* Caches <index> for later retrieval */
PERL_ARGS_ASSERT_INVLIST_SET_PREVIOUS_INDEX;
assert(index == 0 || index < (int) _invlist_len(invlist));
*get_invlist_previous_index_addr(invlist) = index;
}
PERL_STATIC_INLINE void
S_invlist_trim(SV* invlist)
{
/* Free the not currently-being-used space in an inversion list */
/* But don't free up the space needed for the 0 UV that is always at the
* beginning of the list, nor the trailing NUL */
const UV min_size = TO_INTERNAL_SIZE(1) + 1;
PERL_ARGS_ASSERT_INVLIST_TRIM;
assert(SvTYPE(invlist) == SVt_INVLIST);
SvPV_renew(invlist, MAX(min_size, SvCUR(invlist) + 1));
}
PERL_STATIC_INLINE void
S_invlist_clear(pTHX_ SV* invlist) /* Empty the inversion list */
{
PERL_ARGS_ASSERT_INVLIST_CLEAR;
assert(SvTYPE(invlist) == SVt_INVLIST);
invlist_set_len(invlist, 0, 0);
invlist_trim(invlist);
}
#endif /* ifndef PERL_IN_XSUB_RE */
PERL_STATIC_INLINE bool
S_invlist_is_iterating(SV* const invlist)
{
PERL_ARGS_ASSERT_INVLIST_IS_ITERATING;
return *(get_invlist_iter_addr(invlist)) < (STRLEN) UV_MAX;
}
#ifndef PERL_IN_XSUB_RE
PERL_STATIC_INLINE UV
S_invlist_max(SV* const invlist)
{
/* Returns the maximum number of elements storable in the inversion list's
* array, without having to realloc() */
PERL_ARGS_ASSERT_INVLIST_MAX;
assert(SvTYPE(invlist) == SVt_INVLIST);
/* Assumes worst case, in which the 0 element is not counted in the
* inversion list, so subtracts 1 for that */
return SvLEN(invlist) == 0 /* This happens under _new_invlist_C_array */
? FROM_INTERNAL_SIZE(SvCUR(invlist)) - 1
: FROM_INTERNAL_SIZE(SvLEN(invlist)) - 1;
}
SV*
Perl__new_invlist(pTHX_ IV initial_size)
{
/* Return a pointer to a newly constructed inversion list, with enough
* space to store 'initial_size' elements. If that number is negative, a
* system default is used instead */
SV* new_list;
if (initial_size < 0) {
initial_size = 10;
}
/* Allocate the initial space */
new_list = newSV_type(SVt_INVLIST);
/* First 1 is in case the zero element isn't in the list; second 1 is for
* trailing NUL */
SvGROW(new_list, TO_INTERNAL_SIZE(initial_size + 1) + 1);
invlist_set_len(new_list, 0, 0);
/* Force iterinit() to be used to get iteration to work */
*get_invlist_iter_addr(new_list) = (STRLEN) UV_MAX;
*get_invlist_previous_index_addr(new_list) = 0;
return new_list;
}
SV*
Perl__new_invlist_C_array(pTHX_ const UV* const list)
{
/* Return a pointer to a newly constructed inversion list, initialized to
* point to <list>, which has to be in the exact correct inversion list
* form, including internal fields. Thus this is a dangerous routine that
* should not be used in the wrong hands. The passed in 'list' contains
* several header fields at the beginning that are not part of the
* inversion list body proper */
const STRLEN length = (STRLEN) list[0];
const UV version_id = list[1];
const bool offset = cBOOL(list[2]);
#define HEADER_LENGTH 3
/* If any of the above changes in any way, you must change HEADER_LENGTH
* (if appropriate) and regenerate INVLIST_VERSION_ID by running
* perl -E 'say int(rand 2**31-1)'
*/
#define INVLIST_VERSION_ID 148565664 /* This is a combination of a version and
data structure type, so that one being
passed in can be validated to be an
inversion list of the correct vintage.
*/
SV* invlist = newSV_type(SVt_INVLIST);
PERL_ARGS_ASSERT__NEW_INVLIST_C_ARRAY;
if (version_id != INVLIST_VERSION_ID) {
Perl_croak(aTHX_ "panic: Incorrect version for previously generated inversion list");
}
/* The generated array passed in includes header elements that aren't part
* of the list proper, so start it just after them */
SvPV_set(invlist, (char *) (list + HEADER_LENGTH));
SvLEN_set(invlist, 0); /* Means we own the contents, and the system
shouldn't touch it */
*(get_invlist_offset_addr(invlist)) = offset;
/* The 'length' passed to us is the physical number of elements in the
* inversion list. But if there is an offset the logical number is one
* less than that */
invlist_set_len(invlist, length - offset, offset);
invlist_set_previous_index(invlist, 0);
/* Initialize the iteration pointer. */
invlist_iterfinish(invlist);
SvREADONLY_on(invlist);
return invlist;
}
STATIC void
S_invlist_extend(pTHX_ SV* const invlist, const UV new_max)
{
/* Grow the maximum size of an inversion list */
PERL_ARGS_ASSERT_INVLIST_EXTEND;
assert(SvTYPE(invlist) == SVt_INVLIST);
/* Add one to account for the zero element at the beginning which may not
* be counted by the calling parameters */
SvGROW((SV *)invlist, TO_INTERNAL_SIZE(new_max + 1));
}
STATIC void
S__append_range_to_invlist(pTHX_ SV* const invlist,
const UV start, const UV end)
{
/* Subject to change or removal. Append the range from 'start' to 'end' at
* the end of the inversion list. The range must be above any existing
* ones. */
UV* array;
UV max = invlist_max(invlist);
UV len = _invlist_len(invlist);
bool offset;
PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST;
if (len == 0) { /* Empty lists must be initialized */
offset = start != 0;
array = _invlist_array_init(invlist, ! offset);
}
else {
/* Here, the existing list is non-empty. The current max entry in the
* list is generally the first value not in the set, except when the
* set extends to the end of permissible values, in which case it is
* the first entry in that final set, and so this call is an attempt to
* append out-of-order */
UV final_element = len - 1;
array = invlist_array(invlist);
if ( array[final_element] > start
|| ELEMENT_RANGE_MATCHES_INVLIST(final_element))
{
Perl_croak(aTHX_ "panic: attempting to append to an inversion list, but wasn't at the end of the list, final=%" UVuf ", start=%" UVuf ", match=%c",
array[final_element], start,
ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f');
}
/* Here, it is a legal append. If the new range begins 1 above the end
* of the range below it, it is extending the range below it, so the
* new first value not in the set is one greater than the newly
* extended range. */
offset = *get_invlist_offset_addr(invlist);
if (array[final_element] == start) {
if (end != UV_MAX) {
array[final_element] = end + 1;
}
else {
/* But if the end is the maximum representable on the machine,
* assume that infinity was actually what was meant. Just let
* the range that this would extend to have no end */
invlist_set_len(invlist, len - 1, offset);
}
return;
}
}
/* Here the new range doesn't extend any existing set. Add it */
len += 2; /* Includes an element each for the start and end of range */
/* If wll overflow the existing space, extend, which may cause the array to
* be moved */
if (max < len) {
invlist_extend(invlist, len);
/* Have to set len here to avoid assert failure in invlist_array() */
invlist_set_len(invlist, len, offset);
array = invlist_array(invlist);
}
else {
invlist_set_len(invlist, len, offset);
}
/* The next item on the list starts the range, the one after that is
* one past the new range. */
array[len - 2] = start;
if (end != UV_MAX) {
array[len - 1] = end + 1;
}
else {
/* But if the end is the maximum representable on the machine, just let
* the range have no end */
invlist_set_len(invlist, len - 1, offset);
}
}
SSize_t
Perl__invlist_search(SV* const invlist, const UV cp)
{
/* Searches the inversion list for the entry that contains the input code
* point <cp>. If <cp> is not in the list, -1 is returned. Otherwise, the
* return value is the index into the list's array of the range that
* contains <cp>, that is, 'i' such that
* array[i] <= cp < array[i+1]
*/
IV low = 0;
IV mid;
IV high = _invlist_len(invlist);
const IV highest_element = high - 1;
const UV* array;
PERL_ARGS_ASSERT__INVLIST_SEARCH;
/* If list is empty, return failure. */
if (high == 0) {
return -1;
}
/* (We can't get the array unless we know the list is non-empty) */
array = invlist_array(invlist);
mid = invlist_previous_index(invlist);
assert(mid >=0);
if (mid > highest_element) {
mid = highest_element;
}
/* <mid> contains the cache of the result of the previous call to this
* function (0 the first time). See if this call is for the same result,
* or if it is for mid-1. This is under the theory that calls to this
* function will often be for related code points that are near each other.
* And benchmarks show that caching gives better results. We also test
* here if the code point is within the bounds of the list. These tests
* replace others that would have had to be made anyway to make sure that
* the array bounds were not exceeded, and these give us extra information
* at the same time */
if (cp >= array[mid]) {
if (cp >= array[highest_element]) {
return highest_element;
}
/* Here, array[mid] <= cp < array[highest_element]. This means that
* the final element is not the answer, so can exclude it; it also
* means that <mid> is not the final element, so can refer to 'mid + 1'
* safely */
if (cp < array[mid + 1]) {
return mid;
}
high--;
low = mid + 1;
}
else { /* cp < aray[mid] */
if (cp < array[0]) { /* Fail if outside the array */
return -1;
}
high = mid;
if (cp >= array[mid - 1]) {
goto found_entry;
}
}
/* Binary search. What we are looking for is <i> such that
* array[i] <= cp < array[i+1]
* The loop below converges on the i+1. Note that there may not be an
* (i+1)th element in the array, and things work nonetheless */
while (low < high) {
mid = (low + high) / 2;
assert(mid <= highest_element);
if (array[mid] <= cp) { /* cp >= array[mid] */
low = mid + 1;
/* We could do this extra test to exit the loop early.
if (cp < array[low]) {
return mid;
}
*/
}
else { /* cp < array[mid] */
high = mid;
}
}
found_entry:
high--;
invlist_set_previous_index(invlist, high);
return high;
}
void
Perl__invlist_populate_swatch(SV* const invlist,
const UV start, const UV end, U8* swatch)
{
/* populates a swatch of a swash the same way swatch_get() does in utf8.c,
* but is used when the swash has an inversion list. This makes this much
* faster, as it uses a binary search instead of a linear one. This is
* intimately tied to that function, and perhaps should be in utf8.c,
* except it is intimately tied to inversion lists as well. It assumes
* that <swatch> is all 0's on input */
UV current = start;
const IV len = _invlist_len(invlist);
IV i;
const UV * array;
PERL_ARGS_ASSERT__INVLIST_POPULATE_SWATCH;
if (len == 0) { /* Empty inversion list */
return;
}
array = invlist_array(invlist);
/* Find which element it is */
i = _invlist_search(invlist, start);
/* We populate from <start> to <end> */
while (current < end) {
UV upper;
/* The inversion list gives the results for every possible code point
* after the first one in the list. Only those ranges whose index is
* even are ones that the inversion list matches. For the odd ones,
* and if the initial code point is not in the list, we have to skip
* forward to the next element */
if (i == -1 || ! ELEMENT_RANGE_MATCHES_INVLIST(i)) {
i++;
if (i >= len) { /* Finished if beyond the end of the array */
return;
}
current = array[i];
if (current >= end) { /* Finished if beyond the end of what we
are populating */
if (LIKELY(end < UV_MAX)) {
return;
}
/* We get here when the upper bound is the maximum
* representable on the machine, and we are looking for just
* that code point. Have to special case it */
i = len;
goto join_end_of_list;
}
}
assert(current >= start);
/* The current range ends one below the next one, except don't go past
* <end> */
i++;
upper = (i < len && array[i] < end) ? array[i] : end;
/* Here we are in a range that matches. Populate a bit in the 3-bit U8
* for each code point in it */
for (; current < upper; current++) {
const STRLEN offset = (STRLEN)(current - start);
swatch[offset >> 3] |= 1 << (offset & 7);
}
join_end_of_list:
/* Quit if at the end of the list */
if (i >= len) {
/* But first, have to deal with the highest possible code point on
* the platform. The previous code assumes that <end> is one
* beyond where we want to populate, but that is impossible at the
* platform's infinity, so have to handle it specially */
if (UNLIKELY(end == UV_MAX && ELEMENT_RANGE_MATCHES_INVLIST(len-1)))
{
const STRLEN offset = (STRLEN)(end - start);
swatch[offset >> 3] |= 1 << (offset & 7);
}
return;
}
/* Advance to the next range, which will be for code points not in the
* inversion list */
current = array[i];
}
return;
}
void
Perl__invlist_union_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
const bool complement_b, SV** output)
{
/* Take the union of two inversion lists and point '*output' to it. On
* input, '*output' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
* even 'a' or 'b'). If to an inversion list, the contents of the original
* list will be replaced by the union. The first list, 'a', may be
* NULL, in which case a copy of the second list is placed in '*output'.
* If 'complement_b' is TRUE, the union is taken of the complement
* (inversion) of 'b' instead of b itself.
*
* The basis for this comes from "Unicode Demystified" Chapter 13 by
* Richard Gillam, published by Addison-Wesley, and explained at some
* length there. The preface says to incorporate its examples into your
* code at your own risk.
*
* The algorithm is like a merge sort. */
const UV* array_a; /* a's array */
const UV* array_b;
UV len_a; /* length of a's array */
UV len_b;
SV* u; /* the resulting union */
UV* array_u;
UV len_u = 0;
UV i_a = 0; /* current index into a's array */
UV i_b = 0;
UV i_u = 0;
/* running count, as explained in the algorithm source book; items are
* stopped accumulating and are output when the count changes to/from 0.
* The count is incremented when we start a range that's in an input's set,
* and decremented when we start a range that's not in a set. So this
* variable can be 0, 1, or 2. When it is 0 neither input is in their set,
* and hence nothing goes into the union; 1, just one of the inputs is in
* its set (and its current range gets added to the union); and 2 when both
* inputs are in their sets. */
UV count = 0;
PERL_ARGS_ASSERT__INVLIST_UNION_MAYBE_COMPLEMENT_2ND;
assert(a != b);
assert(*output == NULL || SvTYPE(*output) == SVt_INVLIST);
len_b = _invlist_len(b);
if (len_b == 0) {
/* Here, 'b' is empty, hence it's complement is all possible code
* points. So if the union includes the complement of 'b', it includes
* everything, and we need not even look at 'a'. It's easiest to
* create a new inversion list that matches everything. */
if (complement_b) {
SV* everything = _add_range_to_invlist(NULL, 0, UV_MAX);
if (*output == NULL) { /* If the output didn't exist, just point it
at the new list */
*output = everything;
}
else { /* Otherwise, replace its contents with the new list */
invlist_replace_list_destroys_src(*output, everything);
SvREFCNT_dec_NN(everything);
}
return;
}
/* Here, we don't want the complement of 'b', and since 'b' is empty,
* the union will come entirely from 'a'. If 'a' is NULL or empty, the
* output will be empty */
if (a == NULL || _invlist_len(a) == 0) {
if (*output == NULL) {
*output = _new_invlist(0);
}
else {
invlist_clear(*output);
}
return;
}
/* Here, 'a' is not empty, but 'b' is, so 'a' entirely determines the
* union. We can just return a copy of 'a' if '*output' doesn't point
* to an existing list */
if (*output == NULL) {
*output = invlist_clone(a);
return;
}
/* If the output is to overwrite 'a', we have a no-op, as it's
* already in 'a' */
if (*output == a) {
return;
}
/* Here, '*output' is to be overwritten by 'a' */
u = invlist_clone(a);
invlist_replace_list_destroys_src(*output, u);
SvREFCNT_dec_NN(u);
return;
}
/* Here 'b' is not empty. See about 'a' */
if (a == NULL || ((len_a = _invlist_len(a)) == 0)) {
/* Here, 'a' is empty (and b is not). That means the union will come
* entirely from 'b'. If '*output' is NULL, we can directly return a
* clone of 'b'. Otherwise, we replace the contents of '*output' with
* the clone */
SV ** dest = (*output == NULL) ? output : &u;
*dest = invlist_clone(b);
if (complement_b) {
_invlist_invert(*dest);
}
if (dest == &u) {
invlist_replace_list_destroys_src(*output, u);
SvREFCNT_dec_NN(u);
}
return;
}
/* Here both lists exist and are non-empty */
array_a = invlist_array(a);
array_b = invlist_array(b);
/* If are to take the union of 'a' with the complement of b, set it
* up so are looking at b's complement. */
if (complement_b) {
/* To complement, we invert: if the first element is 0, remove it. To
* do this, we just pretend the array starts one later */
if (array_b[0] == 0) {
array_b++;
len_b--;
}
else {
/* But if the first element is not zero, we pretend the list starts
* at the 0 that is always stored immediately before the array. */
array_b--;
len_b++;
}
}
/* Size the union for the worst case: that the sets are completely
* disjoint */
u = _new_invlist(len_a + len_b);
/* Will contain U+0000 if either component does */
array_u = _invlist_array_init(u, ( len_a > 0 && array_a[0] == 0)
|| (len_b > 0 && array_b[0] == 0));
/* Go through each input list item by item, stopping when have exhausted
* one of them */
while (i_a < len_a && i_b < len_b) {
UV cp; /* The element to potentially add to the union's array */
bool cp_in_set; /* is it in the the input list's set or not */
/* We need to take one or the other of the two inputs for the union.
* Since we are merging two sorted lists, we take the smaller of the
* next items. In case of a tie, we take first the one that is in its
* set. If we first took the one not in its set, it would decrement
* the count, possibly to 0 which would cause it to be output as ending
* the range, and the next time through we would take the same number,
* and output it again as beginning the next range. By doing it the
* opposite way, there is no possibility that the count will be
* momentarily decremented to 0, and thus the two adjoining ranges will
* be seamlessly merged. (In a tie and both are in the set or both not
* in the set, it doesn't matter which we take first.) */
if ( array_a[i_a] < array_b[i_b]
|| ( array_a[i_a] == array_b[i_b]
&& ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
{
cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
cp = array_a[i_a++];
}
else {
cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
cp = array_b[i_b++];
}
/* Here, have chosen which of the two inputs to look at. Only output
* if the running count changes to/from 0, which marks the
* beginning/end of a range that's in the set */
if (cp_in_set) {
if (count == 0) {
array_u[i_u++] = cp;
}
count++;
}
else {
count--;
if (count == 0) {
array_u[i_u++] = cp;
}
}
}
/* The loop above increments the index into exactly one of the input lists
* each iteration, and ends when either index gets to its list end. That
* means the other index is lower than its end, and so something is
* remaining in that one. We decrement 'count', as explained below, if
* that list is in its set. (i_a and i_b each currently index the element
* beyond the one we care about.) */
if ( (i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
|| (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
{
count--;
}
/* Above we decremented 'count' if the list that had unexamined elements in
* it was in its set. This has made it so that 'count' being non-zero
* means there isn't anything left to output; and 'count' equal to 0 means
* that what is left to output is precisely that which is left in the
* non-exhausted input list.
*
* To see why, note first that the exhausted input obviously has nothing
* left to add to the union. If it was in its set at its end, that means
* the set extends from here to the platform's infinity, and hence so does
* the union and the non-exhausted set is irrelevant. The exhausted set
* also contributed 1 to 'count'. If 'count' was 2, it got decremented to
* 1, but if it was 1, the non-exhausted set wasn't in its set, and so
* 'count' remains at 1. This is consistent with the decremented 'count'
* != 0 meaning there's nothing left to add to the union.
*
* But if the exhausted input wasn't in its set, it contributed 0 to
* 'count', and the rest of the union will be whatever the other input is.
* If 'count' was 0, neither list was in its set, and 'count' remains 0;
* otherwise it gets decremented to 0. This is consistent with 'count'
* == 0 meaning the remainder of the union is whatever is left in the
* non-exhausted list. */
if (count != 0) {
len_u = i_u;
}
else {
IV copy_count = len_a - i_a;
if (copy_count > 0) { /* The non-exhausted input is 'a' */
Copy(array_a + i_a, array_u + i_u, copy_count, UV);
}
else { /* The non-exhausted input is b */
copy_count = len_b - i_b;
Copy(array_b + i_b, array_u + i_u, copy_count, UV);
}
len_u = i_u + copy_count;
}
/* Set the result to the final length, which can change the pointer to
* array_u, so re-find it. (Note that it is unlikely that this will
* change, as we are shrinking the space, not enlarging it) */
if (len_u != _invlist_len(u)) {
invlist_set_len(u, len_u, *get_invlist_offset_addr(u));
invlist_trim(u);
array_u = invlist_array(u);
}
if (*output == NULL) { /* Simply return the new inversion list */
*output = u;
}
else {
/* Otherwise, overwrite the inversion list that was in '*output'. We
* could instead free '*output', and then set it to 'u', but experience
* has shown [perl #127392] that if the input is a mortal, we can get a
* huge build-up of these during regex compilation before they get
* freed. */
invlist_replace_list_destroys_src(*output, u);
SvREFCNT_dec_NN(u);
}
return;
}
void
Perl__invlist_intersection_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
const bool complement_b, SV** i)
{
/* Take the intersection of two inversion lists and point '*i' to it. On
* input, '*i' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
* even 'a' or 'b'). If to an inversion list, the contents of the original
* list will be replaced by the intersection. The first list, 'a', may be
* NULL, in which case '*i' will be an empty list. If 'complement_b' is
* TRUE, the result will be the intersection of 'a' and the complement (or
* inversion) of 'b' instead of 'b' directly.
*
* The basis for this comes from "Unicode Demystified" Chapter 13 by
* Richard Gillam, published by Addison-Wesley, and explained at some
* length there. The preface says to incorporate its examples into your
* code at your own risk. In fact, it had bugs
*
* The algorithm is like a merge sort, and is essentially the same as the
* union above
*/
const UV* array_a; /* a's array */
const UV* array_b;
UV len_a; /* length of a's array */
UV len_b;
SV* r; /* the resulting intersection */
UV* array_r;
UV len_r = 0;
UV i_a = 0; /* current index into a's array */
UV i_b = 0;
UV i_r = 0;
/* running count of how many of the two inputs are postitioned at ranges
* that are in their sets. As explained in the algorithm source book,
* items are stopped accumulating and are output when the count changes
* to/from 2. The count is incremented when we start a range that's in an
* input's set, and decremented when we start a range that's not in a set.
* Only when it is 2 are we in the intersection. */
UV count = 0;
PERL_ARGS_ASSERT__INVLIST_INTERSECTION_MAYBE_COMPLEMENT_2ND;
assert(a != b);
assert(*i == NULL || SvTYPE(*i) == SVt_INVLIST);
/* Special case if either one is empty */
len_a = (a == NULL) ? 0 : _invlist_len(a);
if ((len_a == 0) || ((len_b = _invlist_len(b)) == 0)) {
if (len_a != 0 && complement_b) {
/* Here, 'a' is not empty, therefore from the enclosing 'if', 'b'
* must be empty. Here, also we are using 'b's complement, which
* hence must be every possible code point. Thus the intersection
* is simply 'a'. */
if (*i == a) { /* No-op */
return;
}
if (*i == NULL) {
*i = invlist_clone(a);
return;
}
r = invlist_clone(a);
invlist_replace_list_destroys_src(*i, r);
SvREFCNT_dec_NN(r);
return;
}
/* Here, 'a' or 'b' is empty and not using the complement of 'b'. The
* intersection must be empty */
if (*i == NULL) {
*i = _new_invlist(0);
return;
}
invlist_clear(*i);
return;
}
/* Here both lists exist and are non-empty */
array_a = invlist_array(a);
array_b = invlist_array(b);
/* If are to take the intersection of 'a' with the complement of b, set it
* up so are looking at b's complement. */
if (complement_b) {
/* To complement, we invert: if the first element is 0, remove it. To
* do this, we just pretend the array starts one later */
if (array_b[0] == 0) {
array_b++;
len_b--;
}
else {
/* But if the first element is not zero, we pretend the list starts
* at the 0 that is always stored immediately before the array. */
array_b--;
len_b++;
}
}
/* Size the intersection for the worst case: that the intersection ends up
* fragmenting everything to be completely disjoint */
r= _new_invlist(len_a + len_b);
/* Will contain U+0000 iff both components do */
array_r = _invlist_array_init(r, len_a > 0 && array_a[0] == 0
&& len_b > 0 && array_b[0] == 0);
/* Go through each list item by item, stopping when have exhausted one of
* them */
while (i_a < len_a && i_b < len_b) {
UV cp; /* The element to potentially add to the intersection's
array */
bool cp_in_set; /* Is it in the input list's set or not */
/* We need to take one or the other of the two inputs for the
* intersection. Since we are merging two sorted lists, we take the
* smaller of the next items. In case of a tie, we take first the one
* that is not in its set (a difference from the union algorithm). If
* we first took the one in its set, it would increment the count,
* possibly to 2 which would cause it to be output as starting a range
* in the intersection, and the next time through we would take that
* same number, and output it again as ending the set. By doing the
* opposite of this, there is no possibility that the count will be
* momentarily incremented to 2. (In a tie and both are in the set or
* both not in the set, it doesn't matter which we take first.) */
if ( array_a[i_a] < array_b[i_b]
|| ( array_a[i_a] == array_b[i_b]
&& ! ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
{
cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
cp = array_a[i_a++];
}
else {
cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
cp= array_b[i_b++];
}
/* Here, have chosen which of the two inputs to look at. Only output
* if the running count changes to/from 2, which marks the
* beginning/end of a range that's in the intersection */
if (cp_in_set) {
count++;
if (count == 2) {
array_r[i_r++] = cp;
}
}
else {
if (count == 2) {
array_r[i_r++] = cp;
}
count--;
}
}
/* The loop above increments the index into exactly one of the input lists
* each iteration, and ends when either index gets to its list end. That
* means the other index is lower than its end, and so something is
* remaining in that one. We increment 'count', as explained below, if the
* exhausted list was in its set. (i_a and i_b each currently index the
* element beyond the one we care about.) */
if ( (i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
|| (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
{
count++;
}
/* Above we incremented 'count' if the exhausted list was in its set. This
* has made it so that 'count' being below 2 means there is nothing left to
* output; otheriwse what's left to add to the intersection is precisely
* that which is left in the non-exhausted input list.
*
* To see why, note first that the exhausted input obviously has nothing
* left to affect the intersection. If it was in its set at its end, that
* means the set extends from here to the platform's infinity, and hence
* anything in the non-exhausted's list will be in the intersection, and
* anything not in it won't be. Hence, the rest of the intersection is
* precisely what's in the non-exhausted list The exhausted set also
* contributed 1 to 'count', meaning 'count' was at least 1. Incrementing
* it means 'count' is now at least 2. This is consistent with the
* incremented 'count' being >= 2 means to add the non-exhausted list to
* the intersection.
*
* But if the exhausted input wasn't in its set, it contributed 0 to
* 'count', and the intersection can't include anything further; the
* non-exhausted set is irrelevant. 'count' was at most 1, and doesn't get
* incremented. This is consistent with 'count' being < 2 meaning nothing
* further to add to the intersection. */
if (count < 2) { /* Nothing left to put in the intersection. */
len_r = i_r;
}
else { /* copy the non-exhausted list, unchanged. */
IV copy_count = len_a - i_a;
if (copy_count > 0) { /* a is the one with stuff left */
Copy(array_a + i_a, array_r + i_r, copy_count, UV);
}
else { /* b is the one with stuff left */
copy_count = len_b - i_b;
Copy(array_b + i_b, array_r + i_r, copy_count, UV);
}
len_r = i_r + copy_count;
}
/* Set the result to the final length, which can change the pointer to
* array_r, so re-find it. (Note that it is unlikely that this will
* change, as we are shrinking the space, not enlarging it) */
if (len_r != _invlist_len(r)) {
invlist_set_len(r, len_r, *get_invlist_offset_addr(r));
invlist_trim(r);
array_r = invlist_array(r);
}
if (*i == NULL) { /* Simply return the calculated intersection */
*i = r;
}
else { /* Otherwise, replace the existing inversion list in '*i'. We could
instead free '*i', and then set it to 'r', but experience has
shown [perl #127392] that if the input is a mortal, we can get a
huge build-up of these during regex compilation before they get
freed. */
if (len_r) {
invlist_replace_list_destroys_src(*i, r);
}
else {
invlist_clear(*i);
}
SvREFCNT_dec_NN(r);
}
return;
}
SV*
Perl__add_range_to_invlist(pTHX_ SV* invlist, UV start, UV end)
{
/* Add the range from 'start' to 'end' inclusive to the inversion list's
* set. A pointer to the inversion list is returned. This may actually be
* a new list, in which case the passed in one has been destroyed. The
* passed-in inversion list can be NULL, in which case a new one is created
* with just the one range in it. The new list is not necessarily
* NUL-terminated. Space is not freed if the inversion list shrinks as a
* result of this function. The gain would not be large, and in many
* cases, this is called multiple times on a single inversion list, so
* anything freed may almost immediately be needed again.
*
* This used to mostly call the 'union' routine, but that is much more
* heavyweight than really needed for a single range addition */
UV* array; /* The array implementing the inversion list */
UV len; /* How many elements in 'array' */
SSize_t i_s; /* index into the invlist array where 'start'
should go */
SSize_t i_e = 0; /* And the index where 'end' should go */
UV cur_highest; /* The highest code point in the inversion list
upon entry to this function */
/* This range becomes the whole inversion list if none already existed */
if (invlist == NULL) {
invlist = _new_invlist(2);
_append_range_to_invlist(invlist, start, end);
return invlist;
}
/* Likewise, if the inversion list is currently empty */
len = _invlist_len(invlist);
if (len == 0) {
_append_range_to_invlist(invlist, start, end);
return invlist;
}
/* Starting here, we have to know the internals of the list */
array = invlist_array(invlist);
/* If the new range ends higher than the current highest ... */
cur_highest = invlist_highest(invlist);
if (end > cur_highest) {
/* If the whole range is higher, we can just append it */
if (start > cur_highest) {
_append_range_to_invlist(invlist, start, end);
return invlist;
}
/* Otherwise, add the portion that is higher ... */
_append_range_to_invlist(invlist, cur_highest + 1, end);
/* ... and continue on below to handle the rest. As a result of the
* above append, we know that the index of the end of the range is the
* final even numbered one of the array. Recall that the final element
* always starts a range that extends to infinity. If that range is in
* the set (meaning the set goes from here to infinity), it will be an
* even index, but if it isn't in the set, it's odd, and the final
* range in the set is one less, which is even. */
if (end == UV_MAX) {
i_e = len;
}
else {
i_e = len - 2;
}
}
/* We have dealt with appending, now see about prepending. If the new
* range starts lower than the current lowest ... */
if (start < array[0]) {
/* Adding something which has 0 in it is somewhat tricky, and uncommon.
* Let the union code handle it, rather than having to know the
* trickiness in two code places. */
if (UNLIKELY(start == 0)) {
SV* range_invlist;
range_invlist = _new_invlist(2);
_append_range_to_invlist(range_invlist, start, end);
_invlist_union(invlist, range_invlist, &invlist);
SvREFCNT_dec_NN(range_invlist);
return invlist;
}
/* If the whole new range comes before the first entry, and doesn't
* extend it, we have to insert it as an additional range */
if (end < array[0] - 1) {
i_s = i_e = -1;
goto splice_in_new_range;
}
/* Here the new range adjoins the existing first range, extending it
* downwards. */
array[0] = start;
/* And continue on below to handle the rest. We know that the index of
* the beginning of the range is the first one of the array */
i_s = 0;
}
else { /* Not prepending any part of the new range to the existing list.
* Find where in the list it should go. This finds i_s, such that:
* invlist[i_s] <= start < array[i_s+1]
*/
i_s = _invlist_search(invlist, start);
}
/* At this point, any extending before the beginning of the inversion list
* and/or after the end has been done. This has made it so that, in the
* code below, each endpoint of the new range is either in a range that is
* in the set, or is in a gap between two ranges that are. This means we
* don't have to worry about exceeding the array bounds.
*
* Find where in the list the new range ends (but we can skip this if we
* have already determined what it is, or if it will be the same as i_s,
* which we already have computed) */
if (i_e == 0) {
i_e = (start == end)
? i_s
: _invlist_search(invlist, end);
}
/* Here generally invlist[i_e] <= end < array[i_e+1]. But if invlist[i_e]
* is a range that goes to infinity there is no element at invlist[i_e+1],
* so only the first relation holds. */
if ( ! ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
/* Here, the ranges on either side of the beginning of the new range
* are in the set, and this range starts in the gap between them.
*
* The new range extends the range above it downwards if the new range
* ends at or above that range's start */
const bool extends_the_range_above = ( end == UV_MAX
|| end + 1 >= array[i_s+1]);
/* The new range extends the range below it upwards if it begins just
* after where that range ends */
if (start == array[i_s]) {
/* If the new range fills the entire gap between the other ranges,
* they will get merged together. Other ranges may also get
* merged, depending on how many of them the new range spans. In
* the general case, we do the merge later, just once, after we
* figure out how many to merge. But in the case where the new
* range exactly spans just this one gap (possibly extending into
* the one above), we do the merge here, and an early exit. This
* is done here to avoid having to special case later. */
if (i_e - i_s <= 1) {
/* If i_e - i_s == 1, it means that the new range terminates
* within the range above, and hence 'extends_the_range_above'
* must be true. (If the range above it extends to infinity,
* 'i_s+2' will be above the array's limit, but 'len-i_s-2'
* will be 0, so no harm done.) */
if (extends_the_range_above) {
Move(array + i_s + 2, array + i_s, len - i_s - 2, UV);
invlist_set_len(invlist,
len - 2,
*(get_invlist_offset_addr(invlist)));
return invlist;
}
/* Here, i_e must == i_s. We keep them in sync, as they apply
* to the same range, and below we are about to decrement i_s
* */
i_e--;
}
/* Here, the new range is adjacent to the one below. (It may also
* span beyond the range above, but that will get resolved later.)
* Extend the range below to include this one. */
array[i_s] = (end == UV_MAX) ? UV_MAX : end + 1;
i_s--;
start = array[i_s];
}
else if (extends_the_range_above) {
/* Here the new range only extends the range above it, but not the
* one below. It merges with the one above. Again, we keep i_e
* and i_s in sync if they point to the same range */
if (i_e == i_s) {
i_e++;
}
i_s++;
array[i_s] = start;
}
}
/* Here, we've dealt with the new range start extending any adjoining
* existing ranges.
*
* If the new range extends to infinity, it is now the final one,
* regardless of what was there before */
if (UNLIKELY(end == UV_MAX)) {
invlist_set_len(invlist, i_s + 1, *(get_invlist_offset_addr(invlist)));
return invlist;
}
/* If i_e started as == i_s, it has also been dealt with,
* and been updated to the new i_s, which will fail the following if */
if (! ELEMENT_RANGE_MATCHES_INVLIST(i_e)) {
/* Here, the ranges on either side of the end of the new range are in
* the set, and this range ends in the gap between them.
*
* If this range is adjacent to (hence extends) the range above it, it
* becomes part of that range; likewise if it extends the range below,
* it becomes part of that range */
if (end + 1 == array[i_e+1]) {
i_e++;
array[i_e] = start;
}
else if (start <= array[i_e]) {
array[i_e] = end + 1;
i_e--;
}
}
if (i_s == i_e) {
/* If the range fits entirely in an existing range (as possibly already
* extended above), it doesn't add anything new */
if (ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
return invlist;
}
/* Here, no part of the range is in the list. Must add it. It will
* occupy 2 more slots */
splice_in_new_range:
invlist_extend(invlist, len + 2);
array = invlist_array(invlist);
/* Move the rest of the array down two slots. Don't include any
* trailing NUL */
Move(array + i_e + 1, array + i_e + 3, len - i_e - 1, UV);
/* Do the actual splice */
array[i_e+1] = start;
array[i_e+2] = end + 1;
invlist_set_len(invlist, len + 2, *(get_invlist_offset_addr(invlist)));
return invlist;
}
/* Here the new range crossed the boundaries of a pre-existing range. The
* code above has adjusted things so that both ends are in ranges that are
* in the set. This means everything in between must also be in the set.
* Just squash things together */
Move(array + i_e + 1, array + i_s + 1, len - i_e - 1, UV);
invlist_set_len(invlist,
len - i_e + i_s,
*(get_invlist_offset_addr(invlist)));
return invlist;
}
SV*
Perl__setup_canned_invlist(pTHX_ const STRLEN size, const UV element0,
UV** other_elements_ptr)
{
/* Create and return an inversion list whose contents are to be populated
* by the caller. The caller gives the number of elements (in 'size') and
* the very first element ('element0'). This function will set
* '*other_elements_ptr' to an array of UVs, where the remaining elements
* are to be placed.
*
* Obviously there is some trust involved that the caller will properly
* fill in the other elements of the array.
*
* (The first element needs to be passed in, as the underlying code does
* things differently depending on whether it is zero or non-zero) */
SV* invlist = _new_invlist(size);
bool offset;
PERL_ARGS_ASSERT__SETUP_CANNED_INVLIST;
invlist = add_cp_to_invlist(invlist, element0);
offset = *get_invlist_offset_addr(invlist);
invlist_set_len(invlist, size, offset);
*other_elements_ptr = invlist_array(invlist) + 1;
return invlist;
}
#endif
PERL_STATIC_INLINE SV*
S_add_cp_to_invlist(pTHX_ SV* invlist, const UV cp) {
return _add_range_to_invlist(invlist, cp, cp);
}
#ifndef PERL_IN_XSUB_RE
void
Perl__invlist_invert(pTHX_ SV* const invlist)
{
/* Complement the input inversion list. This adds a 0 if the list didn't
* have a zero; removes it otherwise. As described above, the data
* structure is set up so that this is very efficient */
PERL_ARGS_ASSERT__INVLIST_INVERT;
assert(! invlist_is_iterating(invlist));
/* The inverse of matching nothing is matching everything */
if (_invlist_len(invlist) == 0) {
_append_range_to_invlist(invlist, 0, UV_MAX);
return;
}
*get_invlist_offset_addr(invlist) = ! *get_invlist_offset_addr(invlist);
}
#endif
PERL_STATIC_INLINE SV*
S_invlist_clone(pTHX_ SV* const invlist)
{
/* Return a new inversion list that is a copy of the input one, which is
* unchanged. The new list will not be mortal even if the old one was. */
/* Need to allocate extra space to accommodate Perl's addition of a
* trailing NUL to SvPV's, since it thinks they are always strings */
SV* new_invlist = _new_invlist(_invlist_len(invlist) + 1);
STRLEN physical_length = SvCUR(invlist);
bool offset = *(get_invlist_offset_addr(invlist));
PERL_ARGS_ASSERT_INVLIST_CLONE;
*(get_invlist_offset_addr(new_invlist)) = offset;
invlist_set_len(new_invlist, _invlist_len(invlist), offset);
Copy(SvPVX(invlist), SvPVX(new_invlist), physical_length, char);
return new_invlist;
}
PERL_STATIC_INLINE STRLEN*
S_get_invlist_iter_addr(SV* invlist)
{
/* Return the address of the UV that contains the current iteration
* position */
PERL_ARGS_ASSERT_GET_INVLIST_ITER_ADDR;
assert(SvTYPE(invlist) == SVt_INVLIST);
return &(((XINVLIST*) SvANY(invlist))->iterator);
}
PERL_STATIC_INLINE void
S_invlist_iterinit(SV* invlist) /* Initialize iterator for invlist */
{
PERL_ARGS_ASSERT_INVLIST_ITERINIT;
*get_invlist_iter_addr(invlist) = 0;
}
PERL_STATIC_INLINE void
S_invlist_iterfinish(SV* invlist)
{
/* Terminate iterator for invlist. This is to catch development errors.
* Any iteration that is interrupted before completed should call this
* function. Functions that add code points anywhere else but to the end
* of an inversion list assert that they are not in the middle of an
* iteration. If they were, the addition would make the iteration
* problematical: if the iteration hadn't reached the place where things
* were being added, it would be ok */
PERL_ARGS_ASSERT_INVLIST_ITERFINISH;
*get_invlist_iter_addr(invlist) = (STRLEN) UV_MAX;
}
STATIC bool
S_invlist_iternext(SV* invlist, UV* start, UV* end)
{
/* An C<invlist_iterinit> call on <invlist> must be used to set this up.
* This call sets in <*start> and <*end>, the next range in <invlist>.
* Returns <TRUE> if successful and the next call will return the next
* range; <FALSE> if was already at the end of the list. If the latter,
* <*start> and <*end> are unchanged, and the next call to this function
* will start over at the beginning of the list */
STRLEN* pos = get_invlist_iter_addr(invlist);
UV len = _invlist_len(invlist);
UV *array;
PERL_ARGS_ASSERT_INVLIST_ITERNEXT;
if (*pos >= len) {
*pos = (STRLEN) UV_MAX; /* Force iterinit() to be required next time */
return FALSE;
}
array = invlist_array(invlist);
*start = array[(*pos)++];
if (*pos >= len) {
*end = UV_MAX;
}
else {
*end = array[(*pos)++] - 1;
}
return TRUE;
}
PERL_STATIC_INLINE UV
S_invlist_highest(SV* const invlist)
{
/* Returns the highest code point that matches an inversion list. This API
* has an ambiguity, as it returns 0 under either the highest is actually
* 0, or if the list is empty. If this distinction matters to you, check
* for emptiness before calling this function */
UV len = _invlist_len(invlist);
UV *array;
PERL_ARGS_ASSERT_INVLIST_HIGHEST;
if (len == 0) {
return 0;
}
array = invlist_array(invlist);
/* The last element in the array in the inversion list always starts a
* range that goes to infinity. That range may be for code points that are
* matched in the inversion list, or it may be for ones that aren't
* matched. In the latter case, the highest code point in the set is one
* less than the beginning of this range; otherwise it is the final element
* of this range: infinity */
return (ELEMENT_RANGE_MATCHES_INVLIST(len - 1))
? UV_MAX
: array[len - 1] - 1;
}
STATIC SV *
S_invlist_contents(pTHX_ SV* const invlist, const bool traditional_style)
{
/* Get the contents of an inversion list into a string SV so that they can
* be printed out. If 'traditional_style' is TRUE, it uses the format
* traditionally done for debug tracing; otherwise it uses a format
* suitable for just copying to the output, with blanks between ranges and
* a dash between range components */
UV start, end;
SV* output;
const char intra_range_delimiter = (traditional_style ? '\t' : '-');
const char inter_range_delimiter = (traditional_style ? '\n' : ' ');
if (traditional_style) {
output = newSVpvs("\n");
}
else {
output = newSVpvs("");
}
PERL_ARGS_ASSERT_INVLIST_CONTENTS;
assert(! invlist_is_iterating(invlist));
invlist_iterinit(invlist);
while (invlist_iternext(invlist, &start, &end)) {
if (end == UV_MAX) {
Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%cINFINITY%c",
start, intra_range_delimiter,
inter_range_delimiter);
}
else if (end != start) {
Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c%04" UVXf "%c",
start,
intra_range_delimiter,
end, inter_range_delimiter);
}
else {
Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c",
start, inter_range_delimiter);
}
}
if (SvCUR(output) && ! traditional_style) {/* Get rid of trailing blank */
SvCUR_set(output, SvCUR(output) - 1);
}
return output;
}
#ifndef PERL_IN_XSUB_RE
void
Perl__invlist_dump(pTHX_ PerlIO *file, I32 level,
const char * const indent, SV* const invlist)
{
/* Designed to be called only by do_sv_dump(). Dumps out the ranges of the
* inversion list 'invlist' to 'file' at 'level' Each line is prefixed by
* the string 'indent'. The output looks like this:
[0] 0x000A .. 0x000D
[2] 0x0085
[4] 0x2028 .. 0x2029
[6] 0x3104 .. INFINITY
* This means that the first range of code points matched by the list are
* 0xA through 0xD; the second range contains only the single code point
* 0x85, etc. An inversion list is an array of UVs. Two array elements
* are used to define each range (except if the final range extends to
* infinity, only a single element is needed). The array index of the
* first element for the corresponding range is given in brackets. */
UV start, end;
STRLEN count = 0;
PERL_ARGS_ASSERT__INVLIST_DUMP;
if (invlist_is_iterating(invlist)) {
Perl_dump_indent(aTHX_ level, file,
"%sCan't dump inversion list because is in middle of iterating\n",
indent);
return;
}
invlist_iterinit(invlist);
while (invlist_iternext(invlist, &start, &end)) {
if (end == UV_MAX) {
Perl_dump_indent(aTHX_ level, file,
"%s[%" UVuf "] 0x%04" UVXf " .. INFINITY\n",
indent, (UV)count, start);
}
else if (end != start) {
Perl_dump_indent(aTHX_ level, file,
"%s[%" UVuf "] 0x%04" UVXf " .. 0x%04" UVXf "\n",
indent, (UV)count, start, end);
}
else {
Perl_dump_indent(aTHX_ level, file, "%s[%" UVuf "] 0x%04" UVXf "\n",
indent, (UV)count, start);
}
count += 2;
}
}
void
Perl__load_PL_utf8_foldclosures (pTHX)
{
assert(! PL_utf8_foldclosures);
/* If the folds haven't been read in, call a fold function
* to force that */
if (! PL_utf8_tofold) {
U8 dummy[UTF8_MAXBYTES_CASE+1];
const U8 hyphen[] = HYPHEN_UTF8;
/* This string is just a short named one above \xff */
toFOLD_utf8_safe(hyphen, hyphen + sizeof(hyphen) - 1, dummy, NULL);
assert(PL_utf8_tofold); /* Verify that worked */
}
PL_utf8_foldclosures = _swash_inversion_hash(PL_utf8_tofold);
}
#endif
#if defined(PERL_ARGS_ASSERT__INVLISTEQ) && !defined(PERL_IN_XSUB_RE)
bool
Perl__invlistEQ(pTHX_ SV* const a, SV* const b, const bool complement_b)
{
/* Return a boolean as to if the two passed in inversion lists are
* identical. The final argument, if TRUE, says to take the complement of
* the second inversion list before doing the comparison */
const UV* array_a = invlist_array(a);
const UV* array_b = invlist_array(b);
UV len_a = _invlist_len(a);
UV len_b = _invlist_len(b);
PERL_ARGS_ASSERT__INVLISTEQ;
/* If are to compare 'a' with the complement of b, set it
* up so are looking at b's complement. */
if (complement_b) {
/* The complement of nothing is everything, so <a> would have to have
* just one element, starting at zero (ending at infinity) */
if (len_b == 0) {
return (len_a == 1 && array_a[0] == 0);
}
else if (array_b[0] == 0) {
/* Otherwise, to complement, we invert. Here, the first element is
* 0, just remove it. To do this, we just pretend the array starts
* one later */
array_b++;
len_b--;
}
else {
/* But if the first element is not zero, we pretend the list starts
* at the 0 that is always stored immediately before the array. */
array_b--;
len_b++;
}
}
return len_a == len_b
&& memEQ(array_a, array_b, len_a * sizeof(array_a[0]));
}
#endif
/*
* As best we can, determine the characters that can match the start of
* the given EXACTF-ish node.
*
* Returns the invlist as a new SV*; it is the caller's responsibility to
* call SvREFCNT_dec() when done with it.
*/
STATIC SV*
S__make_exactf_invlist(pTHX_ RExC_state_t *pRExC_state, regnode *node)
{
const U8 * s = (U8*)STRING(node);
SSize_t bytelen = STR_LEN(node);
UV uc;
/* Start out big enough for 2 separate code points */
SV* invlist = _new_invlist(4);
PERL_ARGS_ASSERT__MAKE_EXACTF_INVLIST;
if (! UTF) {
uc = *s;
/* We punt and assume can match anything if the node begins
* with a multi-character fold. Things are complicated. For
* example, /ffi/i could match any of:
* "\N{LATIN SMALL LIGATURE FFI}"
* "\N{LATIN SMALL LIGATURE FF}I"
* "F\N{LATIN SMALL LIGATURE FI}"
* plus several other things; and making sure we have all the
* possibilities is hard. */
if (is_MULTI_CHAR_FOLD_latin1_safe(s, s + bytelen)) {
invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
}
else {
/* Any Latin1 range character can potentially match any
* other depending on the locale */
if (OP(node) == EXACTFL) {
_invlist_union(invlist, PL_Latin1, &invlist);
}
else {
/* But otherwise, it matches at least itself. We can
* quickly tell if it has a distinct fold, and if so,
* it matches that as well */
invlist = add_cp_to_invlist(invlist, uc);
if (IS_IN_SOME_FOLD_L1(uc))
invlist = add_cp_to_invlist(invlist, PL_fold_latin1[uc]);
}
/* Some characters match above-Latin1 ones under /i. This
* is true of EXACTFL ones when the locale is UTF-8 */
if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(uc)
&& (! isASCII(uc) || (OP(node) != EXACTFA
&& OP(node) != EXACTFA_NO_TRIE)))
{
add_above_Latin1_folds(pRExC_state, (U8) uc, &invlist);
}
}
}
else { /* Pattern is UTF-8 */
U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
STRLEN foldlen = UTF8SKIP(s);
const U8* e = s + bytelen;
SV** listp;
uc = utf8_to_uvchr_buf(s, s + bytelen, NULL);
/* The only code points that aren't folded in a UTF EXACTFish
* node are are the problematic ones in EXACTFL nodes */
if (OP(node) == EXACTFL && is_PROBLEMATIC_LOCALE_FOLDEDS_START_cp(uc)) {
/* We need to check for the possibility that this EXACTFL
* node begins with a multi-char fold. Therefore we fold
* the first few characters of it so that we can make that
* check */
U8 *d = folded;
int i;
for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < e; i++) {
if (isASCII(*s)) {
*(d++) = (U8) toFOLD(*s);
s++;
}
else {
STRLEN len;
toFOLD_utf8_safe(s, e, d, &len);
d += len;
s += UTF8SKIP(s);
}
}
/* And set up so the code below that looks in this folded
* buffer instead of the node's string */
e = d;
foldlen = UTF8SKIP(folded);
s = folded;
}
/* When we reach here 's' points to the fold of the first
* character(s) of the node; and 'e' points to far enough along
* the folded string to be just past any possible multi-char
* fold. 'foldlen' is the length in bytes of the first
* character in 's'
*
* Unlike the non-UTF-8 case, the macro for determining if a
* string is a multi-char fold requires all the characters to
* already be folded. This is because of all the complications
* if not. Note that they are folded anyway, except in EXACTFL
* nodes. Like the non-UTF case above, we punt if the node
* begins with a multi-char fold */
if (is_MULTI_CHAR_FOLD_utf8_safe(s, e)) {
invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
}
else { /* Single char fold */
/* It matches all the things that fold to it, which are
* found in PL_utf8_foldclosures (including itself) */
invlist = add_cp_to_invlist(invlist, uc);
if (! PL_utf8_foldclosures)
_load_PL_utf8_foldclosures();
if ((listp = hv_fetch(PL_utf8_foldclosures,
(char *) s, foldlen, FALSE)))
{
AV* list = (AV*) *listp;
IV k;
for (k = 0; k <= av_tindex_skip_len_mg(list); k++) {
SV** c_p = av_fetch(list, k, FALSE);
UV c;
assert(c_p);
c = SvUV(*c_p);
/* /aa doesn't allow folds between ASCII and non- */
if ((OP(node) == EXACTFA || OP(node) == EXACTFA_NO_TRIE)
&& isASCII(c) != isASCII(uc))
{
continue;
}
invlist = add_cp_to_invlist(invlist, c);
}
}
}
}
return invlist;
}
#undef HEADER_LENGTH
#undef TO_INTERNAL_SIZE
#undef FROM_INTERNAL_SIZE
#undef INVLIST_VERSION_ID
/* End of inversion list object */
STATIC void
S_parse_lparen_question_flags(pTHX_ RExC_state_t *pRExC_state)
{
/* This parses the flags that are in either the '(?foo)' or '(?foo:bar)'
* constructs, and updates RExC_flags with them. On input, RExC_parse
* should point to the first flag; it is updated on output to point to the
* final ')' or ':'. There needs to be at least one flag, or this will
* abort */
/* for (?g), (?gc), and (?o) warnings; warning
about (?c) will warn about (?g) -- japhy */
#define WASTED_O 0x01
#define WASTED_G 0x02
#define WASTED_C 0x04
#define WASTED_GC (WASTED_G|WASTED_C)
I32 wastedflags = 0x00;
U32 posflags = 0, negflags = 0;
U32 *flagsp = &posflags;
char has_charset_modifier = '\0';
regex_charset cs;
bool has_use_defaults = FALSE;
const char* const seqstart = RExC_parse - 1; /* Point to the '?' */
int x_mod_count = 0;
PERL_ARGS_ASSERT_PARSE_LPAREN_QUESTION_FLAGS;
/* '^' as an initial flag sets certain defaults */
if (UCHARAT(RExC_parse) == '^') {
RExC_parse++;
has_use_defaults = TRUE;
STD_PMMOD_FLAGS_CLEAR(&RExC_flags);
set_regex_charset(&RExC_flags, (RExC_utf8 || RExC_uni_semantics)
? REGEX_UNICODE_CHARSET
: REGEX_DEPENDS_CHARSET);
}
cs = get_regex_charset(RExC_flags);
if (cs == REGEX_DEPENDS_CHARSET
&& (RExC_utf8 || RExC_uni_semantics))
{
cs = REGEX_UNICODE_CHARSET;
}
while (RExC_parse < RExC_end) {
/* && strchr("iogcmsx", *RExC_parse) */
/* (?g), (?gc) and (?o) are useless here
and must be globally applied -- japhy */
switch (*RExC_parse) {
/* Code for the imsxn flags */
CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp, x_mod_count);
case LOCALE_PAT_MOD:
if (has_charset_modifier) {
goto excess_modifier;
}
else if (flagsp == &negflags) {
goto neg_modifier;
}
cs = REGEX_LOCALE_CHARSET;
has_charset_modifier = LOCALE_PAT_MOD;
break;
case UNICODE_PAT_MOD:
if (has_charset_modifier) {
goto excess_modifier;
}
else if (flagsp == &negflags) {
goto neg_modifier;
}
cs = REGEX_UNICODE_CHARSET;
has_charset_modifier = UNICODE_PAT_MOD;
break;
case ASCII_RESTRICT_PAT_MOD:
if (flagsp == &negflags) {
goto neg_modifier;
}
if (has_charset_modifier) {
if (cs != REGEX_ASCII_RESTRICTED_CHARSET) {
goto excess_modifier;
}
/* Doubled modifier implies more restricted */
cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET;
}
else {
cs = REGEX_ASCII_RESTRICTED_CHARSET;
}
has_charset_modifier = ASCII_RESTRICT_PAT_MOD;
break;
case DEPENDS_PAT_MOD:
if (has_use_defaults) {
goto fail_modifiers;
}
else if (flagsp == &negflags) {
goto neg_modifier;
}
else if (has_charset_modifier) {
goto excess_modifier;
}
/* The dual charset means unicode semantics if the
* pattern (or target, not known until runtime) are
* utf8, or something in the pattern indicates unicode
* semantics */
cs = (RExC_utf8 || RExC_uni_semantics)
? REGEX_UNICODE_CHARSET
: REGEX_DEPENDS_CHARSET;
has_charset_modifier = DEPENDS_PAT_MOD;
break;
excess_modifier:
RExC_parse++;
if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) {
vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD);
}
else if (has_charset_modifier == *(RExC_parse - 1)) {
vFAIL2("Regexp modifier \"%c\" may not appear twice",
*(RExC_parse - 1));
}
else {
vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1));
}
NOT_REACHED; /*NOTREACHED*/
neg_modifier:
RExC_parse++;
vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"",
*(RExC_parse - 1));
NOT_REACHED; /*NOTREACHED*/
case ONCE_PAT_MOD: /* 'o' */
case GLOBAL_PAT_MOD: /* 'g' */
if (PASS2 && ckWARN(WARN_REGEXP)) {
const I32 wflagbit = *RExC_parse == 'o'
? WASTED_O
: WASTED_G;
if (! (wastedflags & wflagbit) ) {
wastedflags |= wflagbit;
/* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
vWARN5(
RExC_parse + 1,
"Useless (%s%c) - %suse /%c modifier",
flagsp == &negflags ? "?-" : "?",
*RExC_parse,
flagsp == &negflags ? "don't " : "",
*RExC_parse
);
}
}
break;
case CONTINUE_PAT_MOD: /* 'c' */
if (PASS2 && ckWARN(WARN_REGEXP)) {
if (! (wastedflags & WASTED_C) ) {
wastedflags |= WASTED_GC;
/* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
vWARN3(
RExC_parse + 1,
"Useless (%sc) - %suse /gc modifier",
flagsp == &negflags ? "?-" : "?",
flagsp == &negflags ? "don't " : ""
);
}
}
break;
case KEEPCOPY_PAT_MOD: /* 'p' */
if (flagsp == &negflags) {
if (PASS2)
ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
} else {
*flagsp |= RXf_PMf_KEEPCOPY;
}
break;
case '-':
/* A flag is a default iff it is following a minus, so
* if there is a minus, it means will be trying to
* re-specify a default which is an error */
if (has_use_defaults || flagsp == &negflags) {
goto fail_modifiers;
}
flagsp = &negflags;
wastedflags = 0; /* reset so (?g-c) warns twice */
x_mod_count = 0;
break;
case ':':
case ')':
if ((posflags & (RXf_PMf_EXTENDED|RXf_PMf_EXTENDED_MORE)) == RXf_PMf_EXTENDED) {
negflags |= RXf_PMf_EXTENDED_MORE;
}
RExC_flags |= posflags;
if (negflags & RXf_PMf_EXTENDED) {
negflags |= RXf_PMf_EXTENDED_MORE;
}
RExC_flags &= ~negflags;
set_regex_charset(&RExC_flags, cs);
return;
default:
fail_modifiers:
RExC_parse += SKIP_IF_CHAR(RExC_parse);
/* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
vFAIL2utf8f("Sequence (%" UTF8f "...) not recognized",
UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
NOT_REACHED; /*NOTREACHED*/
}
RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
}
vFAIL("Sequence (?... not terminated");
}
/*
- reg - regular expression, i.e. main body or parenthesized thing
*
* Caller must absorb opening parenthesis.
*
* Combining parenthesis handling with the base level of regular expression
* is a trifle forced, but the need to tie the tails of the branches to what
* follows makes it hard to avoid.
*/
#define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
#ifdef DEBUGGING
#define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
#else
#define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
#endif
PERL_STATIC_INLINE regnode *
S_handle_named_backref(pTHX_ RExC_state_t *pRExC_state,
I32 *flagp,
char * parse_start,
char ch
)
{
regnode *ret;
char* name_start = RExC_parse;
U32 num = 0;
SV *sv_dat = reg_scan_name(pRExC_state, SIZE_ONLY
? REG_RSN_RETURN_NULL
: REG_RSN_RETURN_DATA);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_HANDLE_NAMED_BACKREF;
if (RExC_parse == name_start || *RExC_parse != ch) {
/* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
vFAIL2("Sequence %.3s... not terminated",parse_start);
}
if (!SIZE_ONLY) {
num = add_data( pRExC_state, STR_WITH_LEN("S"));
RExC_rxi->data->data[num]=(void*)sv_dat;
SvREFCNT_inc_simple_void(sv_dat);
}
RExC_sawback = 1;
ret = reganode(pRExC_state,
((! FOLD)
? NREF
: (ASCII_FOLD_RESTRICTED)
? NREFFA
: (AT_LEAST_UNI_SEMANTICS)
? NREFFU
: (LOC)
? NREFFL
: NREFF),
num);
*flagp |= HASWIDTH;
Set_Node_Offset(ret, parse_start+1);
Set_Node_Cur_Length(ret, parse_start);
nextchar(pRExC_state);
return ret;
}
/* Returns NULL, setting *flagp to TRYAGAIN at the end of (?) that only sets
flags. Returns NULL, setting *flagp to RESTART_PASS1 if the sizing scan
needs to be restarted, or'd with NEED_UTF8 if the pattern needs to be
upgraded to UTF-8. Otherwise would only return NULL if regbranch() returns
NULL, which cannot happen. */
STATIC regnode *
S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp,U32 depth)
/* paren: Parenthesized? 0=top; 1,2=inside '(': changed to letter.
* 2 is like 1, but indicates that nextchar() has been called to advance
* RExC_parse beyond the '('. Things like '(?' are indivisible tokens, and
* this flag alerts us to the need to check for that */
{
regnode *ret; /* Will be the head of the group. */
regnode *br;
regnode *lastbr;
regnode *ender = NULL;
I32 parno = 0;
I32 flags;
U32 oregflags = RExC_flags;
bool have_branch = 0;
bool is_open = 0;
I32 freeze_paren = 0;
I32 after_freeze = 0;
I32 num; /* numeric backreferences */
char * parse_start = RExC_parse; /* MJD */
char * const oregcomp_parse = RExC_parse;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REG;
DEBUG_PARSE("reg ");
*flagp = 0; /* Tentatively. */
/* Having this true makes it feasible to have a lot fewer tests for the
* parse pointer being in scope. For example, we can write
* while(isFOO(*RExC_parse)) RExC_parse++;
* instead of
* while(RExC_parse < RExC_end && isFOO(*RExC_parse)) RExC_parse++;
*/
assert(*RExC_end == '\0');
/* Make an OPEN node, if parenthesized. */
if (paren) {
/* Under /x, space and comments can be gobbled up between the '(' and
* here (if paren ==2). The forms '(*VERB' and '(?...' disallow such
* intervening space, as the sequence is a token, and a token should be
* indivisible */
bool has_intervening_patws = paren == 2 && *(RExC_parse - 1) != '(';
if (RExC_parse >= RExC_end) {
vFAIL("Unmatched (");
}
if ( *RExC_parse == '*') { /* (*VERB:ARG) */
char *start_verb = RExC_parse + 1;
STRLEN verb_len;
char *start_arg = NULL;
unsigned char op = 0;
int arg_required = 0;
int internal_argval = -1; /* if >-1 we are not allowed an argument*/
if (has_intervening_patws) {
RExC_parse++; /* past the '*' */
vFAIL("In '(*VERB...)', the '(' and '*' must be adjacent");
}
while (RExC_parse < RExC_end && *RExC_parse != ')' ) {
if ( *RExC_parse == ':' ) {
start_arg = RExC_parse + 1;
break;
}
RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
}
verb_len = RExC_parse - start_verb;
if ( start_arg ) {
if (RExC_parse >= RExC_end) {
goto unterminated_verb_pattern;
}
RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
while ( RExC_parse < RExC_end && *RExC_parse != ')' )
RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
if ( RExC_parse >= RExC_end || *RExC_parse != ')' )
unterminated_verb_pattern:
vFAIL("Unterminated verb pattern argument");
if ( RExC_parse == start_arg )
start_arg = NULL;
} else {
if ( RExC_parse >= RExC_end || *RExC_parse != ')' )
vFAIL("Unterminated verb pattern");
}
/* Here, we know that RExC_parse < RExC_end */
switch ( *start_verb ) {
case 'A': /* (*ACCEPT) */
if ( memEQs(start_verb,verb_len,"ACCEPT") ) {
op = ACCEPT;
internal_argval = RExC_nestroot;
}
break;
case 'C': /* (*COMMIT) */
if ( memEQs(start_verb,verb_len,"COMMIT") )
op = COMMIT;
break;
case 'F': /* (*FAIL) */
if ( verb_len==1 || memEQs(start_verb,verb_len,"FAIL") ) {
op = OPFAIL;
}
break;
case ':': /* (*:NAME) */
case 'M': /* (*MARK:NAME) */
if ( verb_len==0 || memEQs(start_verb,verb_len,"MARK") ) {
op = MARKPOINT;
arg_required = 1;
}
break;
case 'P': /* (*PRUNE) */
if ( memEQs(start_verb,verb_len,"PRUNE") )
op = PRUNE;
break;
case 'S': /* (*SKIP) */
if ( memEQs(start_verb,verb_len,"SKIP") )
op = SKIP;
break;
case 'T': /* (*THEN) */
/* [19:06] <TimToady> :: is then */
if ( memEQs(start_verb,verb_len,"THEN") ) {
op = CUTGROUP;
RExC_seen |= REG_CUTGROUP_SEEN;
}
break;
}
if ( ! op ) {
RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
vFAIL2utf8f(
"Unknown verb pattern '%" UTF8f "'",
UTF8fARG(UTF, verb_len, start_verb));
}
if ( arg_required && !start_arg ) {
vFAIL3("Verb pattern '%.*s' has a mandatory argument",
verb_len, start_verb);
}
if (internal_argval == -1) {
ret = reganode(pRExC_state, op, 0);
} else {
ret = reg2Lanode(pRExC_state, op, 0, internal_argval);
}
RExC_seen |= REG_VERBARG_SEEN;
if ( ! SIZE_ONLY ) {
if (start_arg) {
SV *sv = newSVpvn( start_arg,
RExC_parse - start_arg);
ARG(ret) = add_data( pRExC_state,
STR_WITH_LEN("S"));
RExC_rxi->data->data[ARG(ret)]=(void*)sv;
ret->flags = 1;
} else {
ret->flags = 0;
}
if ( internal_argval != -1 )
ARG2L_SET(ret, internal_argval);
}
nextchar(pRExC_state);
return ret;
}
else if (*RExC_parse == '?') { /* (?...) */
bool is_logical = 0;
const char * const seqstart = RExC_parse;
const char * endptr;
if (has_intervening_patws) {
RExC_parse++;
vFAIL("In '(?...)', the '(' and '?' must be adjacent");
}
RExC_parse++; /* past the '?' */
paren = *RExC_parse; /* might be a trailing NUL, if not
well-formed */
RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
if (RExC_parse > RExC_end) {
paren = '\0';
}
ret = NULL; /* For look-ahead/behind. */
switch (paren) {
case 'P': /* (?P...) variants for those used to PCRE/Python */
paren = *RExC_parse;
if ( paren == '<') { /* (?P<...>) named capture */
RExC_parse++;
if (RExC_parse >= RExC_end) {
vFAIL("Sequence (?P<... not terminated");
}
goto named_capture;
}
else if (paren == '>') { /* (?P>name) named recursion */
RExC_parse++;
if (RExC_parse >= RExC_end) {
vFAIL("Sequence (?P>... not terminated");
}
goto named_recursion;
}
else if (paren == '=') { /* (?P=...) named backref */
RExC_parse++;
return handle_named_backref(pRExC_state, flagp,
parse_start, ')');
}
RExC_parse += SKIP_IF_CHAR(RExC_parse);
/* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
vFAIL3("Sequence (%.*s...) not recognized",
RExC_parse-seqstart, seqstart);
NOT_REACHED; /*NOTREACHED*/
case '<': /* (?<...) */
if (*RExC_parse == '!')
paren = ',';
else if (*RExC_parse != '=')
named_capture:
{ /* (?<...>) */
char *name_start;
SV *svname;
paren= '>';
/* FALLTHROUGH */
case '\'': /* (?'...') */
name_start = RExC_parse;
svname = reg_scan_name(pRExC_state,
SIZE_ONLY /* reverse test from the others */
? REG_RSN_RETURN_NAME
: REG_RSN_RETURN_NULL);
if ( RExC_parse == name_start
|| RExC_parse >= RExC_end
|| *RExC_parse != paren)
{
vFAIL2("Sequence (?%c... not terminated",
paren=='>' ? '<' : paren);
}
if (SIZE_ONLY) {
HE *he_str;
SV *sv_dat = NULL;
if (!svname) /* shouldn't happen */
Perl_croak(aTHX_
"panic: reg_scan_name returned NULL");
if (!RExC_paren_names) {
RExC_paren_names= newHV();
sv_2mortal(MUTABLE_SV(RExC_paren_names));
#ifdef DEBUGGING
RExC_paren_name_list= newAV();
sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
#endif
}
he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
if ( he_str )
sv_dat = HeVAL(he_str);
if ( ! sv_dat ) {
/* croak baby croak */
Perl_croak(aTHX_
"panic: paren_name hash element allocation failed");
} else if ( SvPOK(sv_dat) ) {
/* (?|...) can mean we have dupes so scan to check
its already been stored. Maybe a flag indicating
we are inside such a construct would be useful,
but the arrays are likely to be quite small, so
for now we punt -- dmq */
IV count = SvIV(sv_dat);
I32 *pv = (I32*)SvPVX(sv_dat);
IV i;
for ( i = 0 ; i < count ; i++ ) {
if ( pv[i] == RExC_npar ) {
count = 0;
break;
}
}
if ( count ) {
pv = (I32*)SvGROW(sv_dat,
SvCUR(sv_dat) + sizeof(I32)+1);
SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
pv[count] = RExC_npar;
SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
}
} else {
(void)SvUPGRADE(sv_dat,SVt_PVNV);
sv_setpvn(sv_dat, (char *)&(RExC_npar),
sizeof(I32));
SvIOK_on(sv_dat);
SvIV_set(sv_dat, 1);
}
#ifdef DEBUGGING
/* Yes this does cause a memory leak in debugging Perls
* */
if (!av_store(RExC_paren_name_list,
RExC_npar, SvREFCNT_inc(svname)))
SvREFCNT_dec_NN(svname);
#endif
/*sv_dump(sv_dat);*/
}
nextchar(pRExC_state);
paren = 1;
goto capturing_parens;
}
RExC_seen |= REG_LOOKBEHIND_SEEN;
RExC_in_lookbehind++;
RExC_parse++;
if (RExC_parse >= RExC_end) {
vFAIL("Sequence (?... not terminated");
}
/* FALLTHROUGH */
case '=': /* (?=...) */
RExC_seen_zerolen++;
break;
case '!': /* (?!...) */
RExC_seen_zerolen++;
/* check if we're really just a "FAIL" assertion */
skip_to_be_ignored_text(pRExC_state, &RExC_parse,
FALSE /* Don't force to /x */ );
if (*RExC_parse == ')') {
ret=reganode(pRExC_state, OPFAIL, 0);
nextchar(pRExC_state);
return ret;
}
break;
case '|': /* (?|...) */
/* branch reset, behave like a (?:...) except that
buffers in alternations share the same numbers */
paren = ':';
after_freeze = freeze_paren = RExC_npar;
break;
case ':': /* (?:...) */
case '>': /* (?>...) */
break;
case '$': /* (?$...) */
case '@': /* (?@...) */
vFAIL2("Sequence (?%c...) not implemented", (int)paren);
break;
case '0' : /* (?0) */
case 'R' : /* (?R) */
if (RExC_parse == RExC_end || *RExC_parse != ')')
FAIL("Sequence (?R) not terminated");
num = 0;
RExC_seen |= REG_RECURSE_SEEN;
*flagp |= POSTPONED;
goto gen_recurse_regop;
/*notreached*/
/* named and numeric backreferences */
case '&': /* (?&NAME) */
parse_start = RExC_parse - 1;
named_recursion:
{
SV *sv_dat = reg_scan_name(pRExC_state,
SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
}
if (RExC_parse >= RExC_end || *RExC_parse != ')')
vFAIL("Sequence (?&... not terminated");
goto gen_recurse_regop;
/* NOTREACHED */
case '+':
if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
RExC_parse++;
vFAIL("Illegal pattern");
}
goto parse_recursion;
/* NOTREACHED*/
case '-': /* (?-1) */
if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
RExC_parse--; /* rewind to let it be handled later */
goto parse_flags;
}
/* FALLTHROUGH */
case '1': case '2': case '3': case '4': /* (?1) */
case '5': case '6': case '7': case '8': case '9':
RExC_parse = (char *) seqstart + 1; /* Point to the digit */
parse_recursion:
{
bool is_neg = FALSE;
UV unum;
parse_start = RExC_parse - 1; /* MJD */
if (*RExC_parse == '-') {
RExC_parse++;
is_neg = TRUE;
}
if (grok_atoUV(RExC_parse, &unum, &endptr)
&& unum <= I32_MAX
) {
num = (I32)unum;
RExC_parse = (char*)endptr;
} else
num = I32_MAX;
if (is_neg) {
/* Some limit for num? */
num = -num;
}
}
if (*RExC_parse!=')')
vFAIL("Expecting close bracket");
gen_recurse_regop:
if ( paren == '-' ) {
/*
Diagram of capture buffer numbering.
Top line is the normal capture buffer numbers
Bottom line is the negative indexing as from
the X (the (?-2))
+ 1 2 3 4 5 X 6 7
/(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
- 5 4 3 2 1 X x x
*/
num = RExC_npar + num;
if (num < 1) {
RExC_parse++;
vFAIL("Reference to nonexistent group");
}
} else if ( paren == '+' ) {
num = RExC_npar + num - 1;
}
/* We keep track how many GOSUB items we have produced.
To start off the ARG2L() of the GOSUB holds its "id",
which is used later in conjunction with RExC_recurse
to calculate the offset we need to jump for the GOSUB,
which it will store in the final representation.
We have to defer the actual calculation until much later
as the regop may move.
*/
ret = reg2Lanode(pRExC_state, GOSUB, num, RExC_recurse_count);
if (!SIZE_ONLY) {
if (num > (I32)RExC_rx->nparens) {
RExC_parse++;
vFAIL("Reference to nonexistent group");
}
RExC_recurse_count++;
DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
"%*s%*s Recurse #%" UVuf " to %" IVdf "\n",
22, "| |", (int)(depth * 2 + 1), "",
(UV)ARG(ret), (IV)ARG2L(ret)));
}
RExC_seen |= REG_RECURSE_SEEN;
Set_Node_Length(ret, 1 + regarglen[OP(ret)]); /* MJD */
Set_Node_Offset(ret, parse_start); /* MJD */
*flagp |= POSTPONED;
assert(*RExC_parse == ')');
nextchar(pRExC_state);
return ret;
/* NOTREACHED */
case '?': /* (??...) */
is_logical = 1;
if (*RExC_parse != '{') {
RExC_parse += SKIP_IF_CHAR(RExC_parse);
/* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
vFAIL2utf8f(
"Sequence (%" UTF8f "...) not recognized",
UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
NOT_REACHED; /*NOTREACHED*/
}
*flagp |= POSTPONED;
paren = '{';
RExC_parse++;
/* FALLTHROUGH */
case '{': /* (?{...}) */
{
U32 n = 0;
struct reg_code_block *cb;
RExC_seen_zerolen++;
if ( !pRExC_state->code_blocks
|| pRExC_state->code_index
>= pRExC_state->code_blocks->count
|| pRExC_state->code_blocks->cb[pRExC_state->code_index].start
!= (STRLEN)((RExC_parse -3 - (is_logical ? 1 : 0))
- RExC_start)
) {
if (RExC_pm_flags & PMf_USE_RE_EVAL)
FAIL("panic: Sequence (?{...}): no code block found\n");
FAIL("Eval-group not allowed at runtime, use re 'eval'");
}
/* this is a pre-compiled code block (?{...}) */
cb = &pRExC_state->code_blocks->cb[pRExC_state->code_index];
RExC_parse = RExC_start + cb->end;
if (!SIZE_ONLY) {
OP *o = cb->block;
if (cb->src_regex) {
n = add_data(pRExC_state, STR_WITH_LEN("rl"));
RExC_rxi->data->data[n] =
(void*)SvREFCNT_inc((SV*)cb->src_regex);
RExC_rxi->data->data[n+1] = (void*)o;
}
else {
n = add_data(pRExC_state,
(RExC_pm_flags & PMf_HAS_CV) ? "L" : "l", 1);
RExC_rxi->data->data[n] = (void*)o;
}
}
pRExC_state->code_index++;
nextchar(pRExC_state);
if (is_logical) {
regnode *eval;
ret = reg_node(pRExC_state, LOGICAL);
eval = reg2Lanode(pRExC_state, EVAL,
n,
/* for later propagation into (??{})
* return value */
RExC_flags & RXf_PMf_COMPILETIME
);
if (!SIZE_ONLY) {
ret->flags = 2;
}
REGTAIL(pRExC_state, ret, eval);
/* deal with the length of this later - MJD */
return ret;
}
ret = reg2Lanode(pRExC_state, EVAL, n, 0);
Set_Node_Length(ret, RExC_parse - parse_start + 1);
Set_Node_Offset(ret, parse_start);
return ret;
}
case '(': /* (?(?{...})...) and (?(?=...)...) */
{
int is_define= 0;
const int DEFINE_len = sizeof("DEFINE") - 1;
if (RExC_parse[0] == '?') { /* (?(?...)) */
if ( RExC_parse < RExC_end - 1
&& ( RExC_parse[1] == '='
|| RExC_parse[1] == '!'
|| RExC_parse[1] == '<'
|| RExC_parse[1] == '{')
) { /* Lookahead or eval. */
I32 flag;
regnode *tail;
ret = reg_node(pRExC_state, LOGICAL);
if (!SIZE_ONLY)
ret->flags = 1;
tail = reg(pRExC_state, 1, &flag, depth+1);
if (flag & (RESTART_PASS1|NEED_UTF8)) {
*flagp = flag & (RESTART_PASS1|NEED_UTF8);
return NULL;
}
REGTAIL(pRExC_state, ret, tail);
goto insert_if;
}
/* Fall through to ‘Unknown switch condition’ at the
end of the if/else chain. */
}
else if ( RExC_parse[0] == '<' /* (?(<NAME>)...) */
|| RExC_parse[0] == '\'' ) /* (?('NAME')...) */
{
char ch = RExC_parse[0] == '<' ? '>' : '\'';
char *name_start= RExC_parse++;
U32 num = 0;
SV *sv_dat=reg_scan_name(pRExC_state,
SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
if ( RExC_parse == name_start
|| RExC_parse >= RExC_end
|| *RExC_parse != ch)
{
vFAIL2("Sequence (?(%c... not terminated",
(ch == '>' ? '<' : ch));
}
RExC_parse++;
if (!SIZE_ONLY) {
num = add_data( pRExC_state, STR_WITH_LEN("S"));
RExC_rxi->data->data[num]=(void*)sv_dat;
SvREFCNT_inc_simple_void(sv_dat);
}
ret = reganode(pRExC_state,NGROUPP,num);
goto insert_if_check_paren;
}
else if (memBEGINs(RExC_parse,
(STRLEN) (RExC_end - RExC_parse),
"DEFINE"))
{
ret = reganode(pRExC_state,DEFINEP,0);
RExC_parse += DEFINE_len;
is_define = 1;
goto insert_if_check_paren;
}
else if (RExC_parse[0] == 'R') {
RExC_parse++;
/* parno == 0 => /(?(R)YES|NO)/ "in any form of recursion OR eval"
* parno == 1 => /(?(R0)YES|NO)/ "in GOSUB (?0) / (?R)"
* parno == 2 => /(?(R1)YES|NO)/ "in GOSUB (?1) (parno-1)"
*/
parno = 0;
if (RExC_parse[0] == '0') {
parno = 1;
RExC_parse++;
}
else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
UV uv;
if (grok_atoUV(RExC_parse, &uv, &endptr)
&& uv <= I32_MAX
) {
parno = (I32)uv + 1;
RExC_parse = (char*)endptr;
}
/* else "Switch condition not recognized" below */
} else if (RExC_parse[0] == '&') {
SV *sv_dat;
RExC_parse++;
sv_dat = reg_scan_name(pRExC_state,
SIZE_ONLY
? REG_RSN_RETURN_NULL
: REG_RSN_RETURN_DATA);
/* we should only have a false sv_dat when
* SIZE_ONLY is true, and we always have false
* sv_dat when SIZE_ONLY is true.
* reg_scan_name() will VFAIL() if the name is
* unknown when SIZE_ONLY is false, and otherwise
* will return something, and when SIZE_ONLY is
* true, reg_scan_name() just parses the string,
* and doesnt return anything. (in theory) */
assert(SIZE_ONLY ? !sv_dat : !!sv_dat);
if (sv_dat)
parno = 1 + *((I32 *)SvPVX(sv_dat));
}
ret = reganode(pRExC_state,INSUBP,parno);
goto insert_if_check_paren;
}
else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
/* (?(1)...) */
char c;
UV uv;
if (grok_atoUV(RExC_parse, &uv, &endptr)
&& uv <= I32_MAX
) {
parno = (I32)uv;
RExC_parse = (char*)endptr;
}
else {
vFAIL("panic: grok_atoUV returned FALSE");
}
ret = reganode(pRExC_state, GROUPP, parno);
insert_if_check_paren:
if (UCHARAT(RExC_parse) != ')') {
RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
vFAIL("Switch condition not recognized");
}
nextchar(pRExC_state);
insert_if:
REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
br = regbranch(pRExC_state, &flags, 1,depth+1);
if (br == NULL) {
if (flags & (RESTART_PASS1|NEED_UTF8)) {
*flagp = flags & (RESTART_PASS1|NEED_UTF8);
return NULL;
}
FAIL2("panic: regbranch returned NULL, flags=%#" UVxf,
(UV) flags);
} else
REGTAIL(pRExC_state, br, reganode(pRExC_state,
LONGJMP, 0));
c = UCHARAT(RExC_parse);
nextchar(pRExC_state);
if (flags&HASWIDTH)
*flagp |= HASWIDTH;
if (c == '|') {
if (is_define)
vFAIL("(?(DEFINE)....) does not allow branches");
/* Fake one for optimizer. */
lastbr = reganode(pRExC_state, IFTHEN, 0);
if (!regbranch(pRExC_state, &flags, 1,depth+1)) {
if (flags & (RESTART_PASS1|NEED_UTF8)) {
*flagp = flags & (RESTART_PASS1|NEED_UTF8);
return NULL;
}
FAIL2("panic: regbranch returned NULL, flags=%#" UVxf,
(UV) flags);
}
REGTAIL(pRExC_state, ret, lastbr);
if (flags&HASWIDTH)
*flagp |= HASWIDTH;
c = UCHARAT(RExC_parse);
nextchar(pRExC_state);
}
else
lastbr = NULL;
if (c != ')') {
if (RExC_parse >= RExC_end)
vFAIL("Switch (?(condition)... not terminated");
else
vFAIL("Switch (?(condition)... contains too many branches");
}
ender = reg_node(pRExC_state, TAIL);
REGTAIL(pRExC_state, br, ender);
if (lastbr) {
REGTAIL(pRExC_state, lastbr, ender);
REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
}
else
REGTAIL(pRExC_state, ret, ender);
RExC_size++; /* XXX WHY do we need this?!!
For large programs it seems to be required
but I can't figure out why. -- dmq*/
return ret;
}
RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
vFAIL("Unknown switch condition (?(...))");
}
case '[': /* (?[ ... ]) */
return handle_regex_sets(pRExC_state, NULL, flagp, depth+1,
oregcomp_parse);
case 0: /* A NUL */
RExC_parse--; /* for vFAIL to print correctly */
vFAIL("Sequence (? incomplete");
break;
default: /* e.g., (?i) */
RExC_parse = (char *) seqstart + 1;
parse_flags:
parse_lparen_question_flags(pRExC_state);
if (UCHARAT(RExC_parse) != ':') {
if (RExC_parse < RExC_end)
nextchar(pRExC_state);
*flagp = TRYAGAIN;
return NULL;
}
paren = ':';
nextchar(pRExC_state);
ret = NULL;
goto parse_rest;
} /* end switch */
}
else if (!(RExC_flags & RXf_PMf_NOCAPTURE)) { /* (...) */
capturing_parens:
parno = RExC_npar;
RExC_npar++;
ret = reganode(pRExC_state, OPEN, parno);
if (!SIZE_ONLY ){
if (!RExC_nestroot)
RExC_nestroot = parno;
if (RExC_open_parens && !RExC_open_parens[parno])
{
DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
"%*s%*s Setting open paren #%" IVdf " to %d\n",
22, "| |", (int)(depth * 2 + 1), "",
(IV)parno, REG_NODE_NUM(ret)));
RExC_open_parens[parno]= ret;
}
}
Set_Node_Length(ret, 1); /* MJD */
Set_Node_Offset(ret, RExC_parse); /* MJD */
is_open = 1;
} else {
/* with RXf_PMf_NOCAPTURE treat (...) as (?:...) */
paren = ':';
ret = NULL;
}
}
else /* ! paren */
ret = NULL;
parse_rest:
/* Pick up the branches, linking them together. */
parse_start = RExC_parse; /* MJD */
br = regbranch(pRExC_state, &flags, 1,depth+1);
/* branch_len = (paren != 0); */
if (br == NULL) {
if (flags & (RESTART_PASS1|NEED_UTF8)) {
*flagp = flags & (RESTART_PASS1|NEED_UTF8);
return NULL;
}
FAIL2("panic: regbranch returned NULL, flags=%#" UVxf, (UV) flags);
}
if (*RExC_parse == '|') {
if (!SIZE_ONLY && RExC_extralen) {
reginsert(pRExC_state, BRANCHJ, br, depth+1);
}
else { /* MJD */
reginsert(pRExC_state, BRANCH, br, depth+1);
Set_Node_Length(br, paren != 0);
Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
}
have_branch = 1;
if (SIZE_ONLY)
RExC_extralen += 1; /* For BRANCHJ-BRANCH. */
}
else if (paren == ':') {
*flagp |= flags&SIMPLE;
}
if (is_open) { /* Starts with OPEN. */
REGTAIL(pRExC_state, ret, br); /* OPEN -> first. */
}
else if (paren != '?') /* Not Conditional */
ret = br;
*flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
lastbr = br;
while (*RExC_parse == '|') {
if (!SIZE_ONLY && RExC_extralen) {
ender = reganode(pRExC_state, LONGJMP,0);
/* Append to the previous. */
REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
}
if (SIZE_ONLY)
RExC_extralen += 2; /* Account for LONGJMP. */
nextchar(pRExC_state);
if (freeze_paren) {
if (RExC_npar > after_freeze)
after_freeze = RExC_npar;
RExC_npar = freeze_paren;
}
br = regbranch(pRExC_state, &flags, 0, depth+1);
if (br == NULL) {
if (flags & (RESTART_PASS1|NEED_UTF8)) {
*flagp = flags & (RESTART_PASS1|NEED_UTF8);
return NULL;
}
FAIL2("panic: regbranch returned NULL, flags=%#" UVxf, (UV) flags);
}
REGTAIL(pRExC_state, lastbr, br); /* BRANCH -> BRANCH. */
lastbr = br;
*flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
}
if (have_branch || paren != ':') {
/* Make a closing node, and hook it on the end. */
switch (paren) {
case ':':
ender = reg_node(pRExC_state, TAIL);
break;
case 1: case 2:
ender = reganode(pRExC_state, CLOSE, parno);
if ( RExC_close_parens ) {
DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
"%*s%*s Setting close paren #%" IVdf " to %d\n",
22, "| |", (int)(depth * 2 + 1), "", (IV)parno, REG_NODE_NUM(ender)));
RExC_close_parens[parno]= ender;
if (RExC_nestroot == parno)
RExC_nestroot = 0;
}
Set_Node_Offset(ender,RExC_parse+1); /* MJD */
Set_Node_Length(ender,1); /* MJD */
break;
case '<':
case ',':
case '=':
case '!':
*flagp &= ~HASWIDTH;
/* FALLTHROUGH */
case '>':
ender = reg_node(pRExC_state, SUCCEED);
break;
case 0:
ender = reg_node(pRExC_state, END);
if (!SIZE_ONLY) {
assert(!RExC_end_op); /* there can only be one! */
RExC_end_op = ender;
if (RExC_close_parens) {
DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
"%*s%*s Setting close paren #0 (END) to %d\n",
22, "| |", (int)(depth * 2 + 1), "", REG_NODE_NUM(ender)));
RExC_close_parens[0]= ender;
}
}
break;
}
DEBUG_PARSE_r(if (!SIZE_ONLY) {
DEBUG_PARSE_MSG("lsbr");
regprop(RExC_rx, RExC_mysv1, lastbr, NULL, pRExC_state);
regprop(RExC_rx, RExC_mysv2, ender, NULL, pRExC_state);
Perl_re_printf( aTHX_ "~ tying lastbr %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
SvPV_nolen_const(RExC_mysv1),
(IV)REG_NODE_NUM(lastbr),
SvPV_nolen_const(RExC_mysv2),
(IV)REG_NODE_NUM(ender),
(IV)(ender - lastbr)
);
});
REGTAIL(pRExC_state, lastbr, ender);
if (have_branch && !SIZE_ONLY) {
char is_nothing= 1;
if (depth==1)
RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
/* Hook the tails of the branches to the closing node. */
for (br = ret; br; br = regnext(br)) {
const U8 op = PL_regkind[OP(br)];
if (op == BRANCH) {
REGTAIL_STUDY(pRExC_state, NEXTOPER(br), ender);
if ( OP(NEXTOPER(br)) != NOTHING
|| regnext(NEXTOPER(br)) != ender)
is_nothing= 0;
}
else if (op == BRANCHJ) {
REGTAIL_STUDY(pRExC_state, NEXTOPER(NEXTOPER(br)), ender);
/* for now we always disable this optimisation * /
if ( OP(NEXTOPER(NEXTOPER(br))) != NOTHING
|| regnext(NEXTOPER(NEXTOPER(br))) != ender)
*/
is_nothing= 0;
}
}
if (is_nothing) {
br= PL_regkind[OP(ret)] != BRANCH ? regnext(ret) : ret;
DEBUG_PARSE_r(if (!SIZE_ONLY) {
DEBUG_PARSE_MSG("NADA");
regprop(RExC_rx, RExC_mysv1, ret, NULL, pRExC_state);
regprop(RExC_rx, RExC_mysv2, ender, NULL, pRExC_state);
Perl_re_printf( aTHX_ "~ converting ret %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
SvPV_nolen_const(RExC_mysv1),
(IV)REG_NODE_NUM(ret),
SvPV_nolen_const(RExC_mysv2),
(IV)REG_NODE_NUM(ender),
(IV)(ender - ret)
);
});
OP(br)= NOTHING;
if (OP(ender) == TAIL) {
NEXT_OFF(br)= 0;
RExC_emit= br + 1;
} else {
regnode *opt;
for ( opt= br + 1; opt < ender ; opt++ )
OP(opt)= OPTIMIZED;
NEXT_OFF(br)= ender - br;
}
}
}
}
{
const char *p;
static const char parens[] = "=!<,>";
if (paren && (p = strchr(parens, paren))) {
U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
int flag = (p - parens) > 1;
if (paren == '>')
node = SUSPEND, flag = 0;
reginsert(pRExC_state, node,ret, depth+1);
Set_Node_Cur_Length(ret, parse_start);
Set_Node_Offset(ret, parse_start + 1);
ret->flags = flag;
REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
}
}
/* Check for proper termination. */
if (paren) {
/* restore original flags, but keep (?p) and, if we've changed from /d
* rules to /u, keep the /u */
RExC_flags = oregflags | (RExC_flags & RXf_PMf_KEEPCOPY);
if (DEPENDS_SEMANTICS && RExC_uni_semantics) {
set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
}
if (RExC_parse >= RExC_end || UCHARAT(RExC_parse) != ')') {
RExC_parse = oregcomp_parse;
vFAIL("Unmatched (");
}
nextchar(pRExC_state);
}
else if (!paren && RExC_parse < RExC_end) {
if (*RExC_parse == ')') {
RExC_parse++;
vFAIL("Unmatched )");
}
else
FAIL("Junk on end of regexp"); /* "Can't happen". */
NOT_REACHED; /* NOTREACHED */
}
if (RExC_in_lookbehind) {
RExC_in_lookbehind--;
}
if (after_freeze > RExC_npar)
RExC_npar = after_freeze;
return(ret);
}
/*
- regbranch - one alternative of an | operator
*
* Implements the concatenation operator.
*
* Returns NULL, setting *flagp to RESTART_PASS1 if the sizing scan needs to be
* restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
*/
STATIC regnode *
S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
{
regnode *ret;
regnode *chain = NULL;
regnode *latest;
I32 flags = 0, c = 0;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGBRANCH;
DEBUG_PARSE("brnc");
if (first)
ret = NULL;
else {
if (!SIZE_ONLY && RExC_extralen)
ret = reganode(pRExC_state, BRANCHJ,0);
else {
ret = reg_node(pRExC_state, BRANCH);
Set_Node_Length(ret, 1);
}
}
if (!first && SIZE_ONLY)
RExC_extralen += 1; /* BRANCHJ */
*flagp = WORST; /* Tentatively. */
skip_to_be_ignored_text(pRExC_state, &RExC_parse,
FALSE /* Don't force to /x */ );
while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
flags &= ~TRYAGAIN;
latest = regpiece(pRExC_state, &flags,depth+1);
if (latest == NULL) {
if (flags & TRYAGAIN)
continue;
if (flags & (RESTART_PASS1|NEED_UTF8)) {
*flagp = flags & (RESTART_PASS1|NEED_UTF8);
return NULL;
}
FAIL2("panic: regpiece returned NULL, flags=%#" UVxf, (UV) flags);
}
else if (ret == NULL)
ret = latest;
*flagp |= flags&(HASWIDTH|POSTPONED);
if (chain == NULL) /* First piece. */
*flagp |= flags&SPSTART;
else {
/* FIXME adding one for every branch after the first is probably
* excessive now we have TRIE support. (hv) */
MARK_NAUGHTY(1);
REGTAIL(pRExC_state, chain, latest);
}
chain = latest;
c++;
}
if (chain == NULL) { /* Loop ran zero times. */
chain = reg_node(pRExC_state, NOTHING);
if (ret == NULL)
ret = chain;
}
if (c == 1) {
*flagp |= flags&SIMPLE;
}
return ret;
}
/*
- regpiece - something followed by possible quantifier * + ? {n,m}
*
* Note that the branching code sequences used for ? and the general cases
* of * and + are somewhat optimized: they use the same NOTHING node as
* both the endmarker for their branch list and the body of the last branch.
* It might seem that this node could be dispensed with entirely, but the
* endmarker role is not redundant.
*
* Returns NULL, setting *flagp to TRYAGAIN if regatom() returns NULL with
* TRYAGAIN.
* Returns NULL, setting *flagp to RESTART_PASS1 if the sizing scan needs to be
* restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
*/
STATIC regnode *
S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
{
regnode *ret;
char op;
char *next;
I32 flags;
const char * const origparse = RExC_parse;
I32 min;
I32 max = REG_INFTY;
#ifdef RE_TRACK_PATTERN_OFFSETS
char *parse_start;
#endif
const char *maxpos = NULL;
UV uv;
/* Save the original in case we change the emitted regop to a FAIL. */
regnode * const orig_emit = RExC_emit;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGPIECE;
DEBUG_PARSE("piec");
ret = regatom(pRExC_state, &flags,depth+1);
if (ret == NULL) {
if (flags & (TRYAGAIN|RESTART_PASS1|NEED_UTF8))
*flagp |= flags & (TRYAGAIN|RESTART_PASS1|NEED_UTF8);
else
FAIL2("panic: regatom returned NULL, flags=%#" UVxf, (UV) flags);
return(NULL);
}
op = *RExC_parse;
if (op == '{' && regcurly(RExC_parse)) {
maxpos = NULL;
#ifdef RE_TRACK_PATTERN_OFFSETS
parse_start = RExC_parse; /* MJD */
#endif
next = RExC_parse + 1;
while (isDIGIT(*next) || *next == ',') {
if (*next == ',') {
if (maxpos)
break;
else
maxpos = next;
}
next++;
}
if (*next == '}') { /* got one */
const char* endptr;
if (!maxpos)
maxpos = next;
RExC_parse++;
if (isDIGIT(*RExC_parse)) {
if (!grok_atoUV(RExC_parse, &uv, &endptr))
vFAIL("Invalid quantifier in {,}");
if (uv >= REG_INFTY)
vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
min = (I32)uv;
} else {
min = 0;
}
if (*maxpos == ',')
maxpos++;
else
maxpos = RExC_parse;
if (isDIGIT(*maxpos)) {
if (!grok_atoUV(maxpos, &uv, &endptr))
vFAIL("Invalid quantifier in {,}");
if (uv >= REG_INFTY)
vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
max = (I32)uv;
} else {
max = REG_INFTY; /* meaning "infinity" */
}
RExC_parse = next;
nextchar(pRExC_state);
if (max < min) { /* If can't match, warn and optimize to fail
unconditionally */
reginsert(pRExC_state, OPFAIL, orig_emit, depth+1);
if (PASS2) {
ckWARNreg(RExC_parse, "Quantifier {n,m} with n > m can't match");
NEXT_OFF(orig_emit)= regarglen[OPFAIL] + NODE_STEP_REGNODE;
}
return ret;
}
else if (min == max && *RExC_parse == '?')
{
if (PASS2) {
ckWARN2reg(RExC_parse + 1,
"Useless use of greediness modifier '%c'",
*RExC_parse);
}
}
do_curly:
if ((flags&SIMPLE)) {
if (min == 0 && max == REG_INFTY) {
reginsert(pRExC_state, STAR, ret, depth+1);
MARK_NAUGHTY(4);
RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
goto nest_check;
}
if (min == 1 && max == REG_INFTY) {
reginsert(pRExC_state, PLUS, ret, depth+1);
MARK_NAUGHTY(3);
RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
goto nest_check;
}
MARK_NAUGHTY_EXP(2, 2);
reginsert(pRExC_state, CURLY, ret, depth+1);
Set_Node_Offset(ret, parse_start+1); /* MJD */
Set_Node_Cur_Length(ret, parse_start);
}
else {
regnode * const w = reg_node(pRExC_state, WHILEM);
w->flags = 0;
REGTAIL(pRExC_state, ret, w);
if (!SIZE_ONLY && RExC_extralen) {
reginsert(pRExC_state, LONGJMP,ret, depth+1);
reginsert(pRExC_state, NOTHING,ret, depth+1);
NEXT_OFF(ret) = 3; /* Go over LONGJMP. */
}
reginsert(pRExC_state, CURLYX,ret, depth+1);
/* MJD hk */
Set_Node_Offset(ret, parse_start+1);
Set_Node_Length(ret,
op == '{' ? (RExC_parse - parse_start) : 1);
if (!SIZE_ONLY && RExC_extralen)
NEXT_OFF(ret) = 3; /* Go over NOTHING to LONGJMP. */
REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
if (SIZE_ONLY)
RExC_whilem_seen++, RExC_extralen += 3;
MARK_NAUGHTY_EXP(1, 4); /* compound interest */
}
ret->flags = 0;
if (min > 0)
*flagp = WORST;
if (max > 0)
*flagp |= HASWIDTH;
if (!SIZE_ONLY) {
ARG1_SET(ret, (U16)min);
ARG2_SET(ret, (U16)max);
}
if (max == REG_INFTY)
RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
goto nest_check;
}
}
if (!ISMULT1(op)) {
*flagp = flags;
return(ret);
}
#if 0 /* Now runtime fix should be reliable. */
/* if this is reinstated, don't forget to put this back into perldiag:
=item Regexp *+ operand could be empty at {#} in regex m/%s/
(F) The part of the regexp subject to either the * or + quantifier
could match an empty string. The {#} shows in the regular
expression about where the problem was discovered.
*/
if (!(flags&HASWIDTH) && op != '?')
vFAIL("Regexp *+ operand could be empty");
#endif
#ifdef RE_TRACK_PATTERN_OFFSETS
parse_start = RExC_parse;
#endif
nextchar(pRExC_state);
*flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
if (op == '*') {
min = 0;
goto do_curly;
}
else if (op == '+') {
min = 1;
goto do_curly;
}
else if (op == '?') {
min = 0; max = 1;
goto do_curly;
}
nest_check:
if (!SIZE_ONLY && !(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
SAVEFREESV(RExC_rx_sv); /* in case of fatal warnings */
ckWARN2reg(RExC_parse,
"%" UTF8f " matches null string many times",
UTF8fARG(UTF, (RExC_parse >= origparse
? RExC_parse - origparse
: 0),
origparse));
(void)ReREFCNT_inc(RExC_rx_sv);
}
if (*RExC_parse == '?') {
nextchar(pRExC_state);
reginsert(pRExC_state, MINMOD, ret, depth+1);
REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
}
else if (*RExC_parse == '+') {
regnode *ender;
nextchar(pRExC_state);
ender = reg_node(pRExC_state, SUCCEED);
REGTAIL(pRExC_state, ret, ender);
reginsert(pRExC_state, SUSPEND, ret, depth+1);
ender = reg_node(pRExC_state, TAIL);
REGTAIL(pRExC_state, ret, ender);
}
if (ISMULT2(RExC_parse)) {
RExC_parse++;
vFAIL("Nested quantifiers");
}
return(ret);
}
STATIC bool
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;
}
}
PERL_STATIC_INLINE U8
S_compute_EXACTish(RExC_state_t *pRExC_state)
{
U8 op;
PERL_ARGS_ASSERT_COMPUTE_EXACTISH;
if (! FOLD) {
return (LOC)
? EXACTL
: EXACT;
}
op = get_regex_charset(RExC_flags);
if (op >= REGEX_ASCII_RESTRICTED_CHARSET) {
op--; /* /a is same as /u, and map /aa's offset to what /a's would have
been, so there is no hole */
}
return op + EXACTF;
}
PERL_STATIC_INLINE void
S_alloc_maybe_populate_EXACT(pTHX_ RExC_state_t *pRExC_state,
regnode *node, I32* flagp, STRLEN len, UV code_point,
bool downgradable)
{
/* This knows the details about sizing an EXACTish node, setting flags for
* it (by setting <*flagp>, and potentially populating it with a single
* character.
*
* If <len> (the length in bytes) is non-zero, this function assumes that
* the node has already been populated, and just does the sizing. In this
* case <code_point> should be the final code point that has already been
* placed into the node. This value will be ignored except that under some
* circumstances <*flagp> is set based on it.
*
* If <len> is zero, the function assumes that the node is to contain only
* the single character given by <code_point> and calculates what <len>
* should be. In pass 1, it sizes the node appropriately. In pass 2, it
* additionally will populate the node's STRING with <code_point> or its
* fold if folding.
*
* In both cases <*flagp> is appropriately set
*
* It knows that under FOLD, the Latin Sharp S and UTF characters above
* 255, must be folded (the former only when the rules indicate it can
* match 'ss')
*
* When it does the populating, it looks at the flag 'downgradable'. If
* true with a node that folds, it checks if the single code point
* participates in a fold, and if not downgrades the node to an EXACT.
* This helps the optimizer */
bool len_passed_in = cBOOL(len != 0);
U8 character[UTF8_MAXBYTES_CASE+1];
PERL_ARGS_ASSERT_ALLOC_MAYBE_POPULATE_EXACT;
/* Don't bother to check for downgrading in PASS1, as it doesn't make any
* sizing difference, and is extra work that is thrown away */
if (downgradable && ! PASS2) {
downgradable = FALSE;
}
if (! len_passed_in) {
if (UTF) {
if (UVCHR_IS_INVARIANT(code_point)) {
if (LOC || ! FOLD) { /* /l defers folding until runtime */
*character = (U8) code_point;
}
else { /* Here is /i and not /l. (toFOLD() is defined on just
ASCII, which isn't the same thing as INVARIANT on
EBCDIC, but it works there, as the extra invariants
fold to themselves) */
*character = toFOLD((U8) code_point);
/* We can downgrade to an EXACT node if this character
* isn't a folding one. Note that this assumes that
* nothing above Latin1 folds to some other invariant than
* one of these alphabetics; otherwise we would also have
* to check:
* && (! HAS_NONLATIN1_FOLD_CLOSURE(code_point)
* || ASCII_FOLD_RESTRICTED))
*/
if (downgradable && PL_fold[code_point] == code_point) {
OP(node) = EXACT;
}
}
len = 1;
}
else if (FOLD && (! LOC
|| ! is_PROBLEMATIC_LOCALE_FOLD_cp(code_point)))
{ /* Folding, and ok to do so now */
UV folded = _to_uni_fold_flags(
code_point,
character,
&len,
FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
? FOLD_FLAGS_NOMIX_ASCII
: 0));
if (downgradable
&& folded == code_point /* This quickly rules out many
cases, avoiding the
_invlist_contains_cp() overhead
for those. */
&& ! _invlist_contains_cp(PL_utf8_foldable, code_point))
{
OP(node) = (LOC)
? EXACTL
: EXACT;
}
}
else if (code_point <= MAX_UTF8_TWO_BYTE) {
/* Not folding this cp, and can output it directly */
*character = UTF8_TWO_BYTE_HI(code_point);
*(character + 1) = UTF8_TWO_BYTE_LO(code_point);
len = 2;
}
else {
uvchr_to_utf8( character, code_point);
len = UTF8SKIP(character);
}
} /* Else pattern isn't UTF8. */
else if (! FOLD) {
*character = (U8) code_point;
len = 1;
} /* Else is folded non-UTF8 */
#if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
|| (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
|| UNICODE_DOT_DOT_VERSION > 0)
else if (LIKELY(code_point != LATIN_SMALL_LETTER_SHARP_S)) {
#else
else if (1) {
#endif
/* We don't fold any non-UTF8 except possibly the Sharp s (see
* comments at join_exact()); */
*character = (U8) code_point;
len = 1;
/* Can turn into an EXACT node if we know the fold at compile time,
* and it folds to itself and doesn't particpate in other folds */
if (downgradable
&& ! LOC
&& PL_fold_latin1[code_point] == code_point
&& (! HAS_NONLATIN1_FOLD_CLOSURE(code_point)
|| (isASCII(code_point) && ASCII_FOLD_RESTRICTED)))
{
OP(node) = EXACT;
}
} /* else is Sharp s. May need to fold it */
else if (AT_LEAST_UNI_SEMANTICS && ! ASCII_FOLD_RESTRICTED) {
*character = 's';
*(character + 1) = 's';
len = 2;
}
else {
*character = LATIN_SMALL_LETTER_SHARP_S;
len = 1;
}
}
if (SIZE_ONLY) {
RExC_size += STR_SZ(len);
}
else {
RExC_emit += STR_SZ(len);
STR_LEN(node) = len;
if (! len_passed_in) {
Copy((char *) character, STRING(node), len, char);
}
}
*flagp |= HASWIDTH;
/* A single character node is SIMPLE, except for the special-cased SHARP S
* under /di. */
if ((len == 1 || (UTF && len == UVCHR_SKIP(code_point)))
#if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
|| (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
|| UNICODE_DOT_DOT_VERSION > 0)
&& ( code_point != LATIN_SMALL_LETTER_SHARP_S
|| ! FOLD || ! DEPENDS_SEMANTICS)
#endif
) {
*flagp |= SIMPLE;
}
/* The OP may not be well defined in PASS1 */
if (PASS2 && OP(node) == EXACTFL) {
RExC_contains_locale = 1;
}
}
STATIC bool
S_new_regcurly(const char *s, const char *e)
{
/* This is a temporary function designed to match the most lenient form of
* a {m,n} quantifier we ever envision, with either number omitted, and
* spaces anywhere between/before/after them.
*
* If this function fails, then the string it matches is very unlikely to
* ever be considered a valid quantifier, so we can allow the '{' that
* begins it to be considered as a literal */
bool has_min = FALSE;
bool has_max = FALSE;
PERL_ARGS_ASSERT_NEW_REGCURLY;
if (s >= e || *s++ != '{')
return FALSE;
while (s < e && isSPACE(*s)) {
s++;
}
while (s < e && isDIGIT(*s)) {
has_min = TRUE;
s++;
}
while (s < e && isSPACE(*s)) {
s++;
}
if (*s == ',') {
s++;
while (s < e && isSPACE(*s)) {
s++;
}
while (s < e && isDIGIT(*s)) {
has_max = TRUE;
s++;
}
while (s < e && isSPACE(*s)) {
s++;
}
}
return s < e && *s == '}' && (has_min || has_max);
}
/* Parse backref decimal value, unless it's too big to sensibly be a backref,
* in which case return I32_MAX (rather than possibly 32-bit wrapping) */
static I32
S_backref_value(char *p)
{
const char* endptr;
UV val;
if (grok_atoUV(p, &val, &endptr) && val <= I32_MAX)
return (I32)val;
return I32_MAX;
}
/*
- regatom - the lowest level
Try to identify anything special at the start of the current parse position.
If there is, then handle it as required. This may involve generating a
single regop, such as for an assertion; or it may involve recursing, such as
to handle a () structure.
If the string doesn't start with something special then we gobble up
as much literal text as we can. If we encounter a quantifier, we have to
back off the final literal character, as that quantifier applies to just it
and not to the whole string of literals.
Once we have been able to handle whatever type of thing started the
sequence, we return.
Note: we have to be careful with escapes, as they can be both literal
and special, and in the case of \10 and friends, context determines which.
A summary of the code structure is:
switch (first_byte) {
cases for each special:
handle this special;
break;
case '\\':
switch (2nd byte) {
cases for each unambiguous special:
handle this special;
break;
cases for each ambigous special/literal:
disambiguate;
if (special) handle here
else goto defchar;
default: // unambiguously literal:
goto defchar;
}
default: // is a literal char
// FALL THROUGH
defchar:
create EXACTish node for literal;
while (more input and node isn't full) {
switch (input_byte) {
cases for each special;
make sure parse pointer is set so that the next call to
regatom will see this special first
goto loopdone; // EXACTish node terminated by prev. char
default:
append char to EXACTISH node;
}
get next input byte;
}
loopdone:
}
return the generated node;
Specifically there are two separate switches for handling
escape sequences, with the one for handling literal escapes requiring
a dummy entry for all of the special escapes that are actually handled
by the other.
Returns NULL, setting *flagp to TRYAGAIN if reg() returns NULL with
TRYAGAIN.
Returns NULL, setting *flagp to RESTART_PASS1 if the sizing scan needs to be
restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
Otherwise does not return NULL.
*/
STATIC regnode *
S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
{
regnode *ret = NULL;
I32 flags = 0;
char *parse_start;
U8 op;
int invert = 0;
U8 arg;
GET_RE_DEBUG_FLAGS_DECL;
*flagp = WORST; /* Tentatively. */
DEBUG_PARSE("atom");
PERL_ARGS_ASSERT_REGATOM;
tryagain:
parse_start = RExC_parse;
assert(RExC_parse < RExC_end);
switch ((U8)*RExC_parse) {
case '^':
RExC_seen_zerolen++;
nextchar(pRExC_state);
if (RExC_flags & RXf_PMf_MULTILINE)
ret = reg_node(pRExC_state, MBOL);
else
ret = reg_node(pRExC_state, SBOL);
Set_Node_Length(ret, 1); /* MJD */
break;
case '$':
nextchar(pRExC_state);
if (*RExC_parse)
RExC_seen_zerolen++;
if (RExC_flags & RXf_PMf_MULTILINE)
ret = reg_node(pRExC_state, MEOL);
else
ret = reg_node(pRExC_state, SEOL);
Set_Node_Length(ret, 1); /* MJD */
break;
case '.':
nextchar(pRExC_state);
if (RExC_flags & RXf_PMf_SINGLELINE)
ret = reg_node(pRExC_state, SANY);
else
ret = reg_node(pRExC_state, REG_ANY);
*flagp |= HASWIDTH|SIMPLE;
MARK_NAUGHTY(1);
Set_Node_Length(ret, 1); /* MJD */
break;
case '[':
{
char * const oregcomp_parse = ++RExC_parse;
ret = regclass(pRExC_state, flagp,depth+1,
FALSE, /* means parse the whole char class */
TRUE, /* allow multi-char folds */
FALSE, /* don't silence non-portable warnings. */
(bool) RExC_strict,
TRUE, /* Allow an optimized regnode result */
NULL,
NULL);
if (ret == NULL) {
if (*flagp & (RESTART_PASS1|NEED_UTF8))
return NULL;
FAIL2("panic: regclass returned NULL to regatom, flags=%#" UVxf,
(UV) *flagp);
}
if (*RExC_parse != ']') {
RExC_parse = oregcomp_parse;
vFAIL("Unmatched [");
}
nextchar(pRExC_state);
Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
break;
}
case '(':
nextchar(pRExC_state);
ret = reg(pRExC_state, 2, &flags,depth+1);
if (ret == NULL) {
if (flags & TRYAGAIN) {
if (RExC_parse >= RExC_end) {
/* Make parent create an empty node if needed. */
*flagp |= TRYAGAIN;
return(NULL);
}
goto tryagain;
}
if (flags & (RESTART_PASS1|NEED_UTF8)) {
*flagp = flags & (RESTART_PASS1|NEED_UTF8);
return NULL;
}
FAIL2("panic: reg returned NULL to regatom, flags=%#" UVxf,
(UV) flags);
}
*flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
break;
case '|':
case ')':
if (flags & TRYAGAIN) {
*flagp |= TRYAGAIN;
return NULL;
}
vFAIL("Internal urp");
/* Supposed to be caught earlier. */
break;
case '?':
case '+':
case '*':
RExC_parse++;
vFAIL("Quantifier follows nothing");
break;
case '\\':
/* Special Escapes
This switch handles escape sequences that resolve to some kind
of special regop and not to literal text. Escape sequnces that
resolve to literal text are handled below in the switch marked
"Literal Escapes".
Every entry in this switch *must* have a corresponding entry
in the literal escape switch. However, the opposite is not
required, as the default for this switch is to jump to the
literal text handling code.
*/
RExC_parse++;
switch ((U8)*RExC_parse) {
/* Special Escapes */
case 'A':
RExC_seen_zerolen++;
ret = reg_node(pRExC_state, SBOL);
/* SBOL is shared with /^/ so we set the flags so we can tell
* /\A/ from /^/ in split. We check ret because first pass we
* have no regop struct to set the flags on. */
if (PASS2)
ret->flags = 1;
*flagp |= SIMPLE;
goto finish_meta_pat;
case 'G':
ret = reg_node(pRExC_state, GPOS);
RExC_seen |= REG_GPOS_SEEN;
*flagp |= SIMPLE;
goto finish_meta_pat;
case 'K':
RExC_seen_zerolen++;
ret = reg_node(pRExC_state, KEEPS);
*flagp |= SIMPLE;
/* XXX:dmq : disabling in-place substitution seems to
* be necessary here to avoid cases of memory corruption, as
* with: C<$_="x" x 80; s/x\K/y/> -- rgs
*/
RExC_seen |= REG_LOOKBEHIND_SEEN;
goto finish_meta_pat;
case 'Z':
ret = reg_node(pRExC_state, SEOL);
*flagp |= SIMPLE;
RExC_seen_zerolen++; /* Do not optimize RE away */
goto finish_meta_pat;
case 'z':
ret = reg_node(pRExC_state, EOS);
*flagp |= SIMPLE;
RExC_seen_zerolen++; /* Do not optimize RE away */
goto finish_meta_pat;
case 'C':
vFAIL("\\C no longer supported");
case 'X':
ret = reg_node(pRExC_state, CLUMP);
*flagp |= HASWIDTH;
goto finish_meta_pat;
case 'W':
invert = 1;
/* FALLTHROUGH */
case 'w':
arg = ANYOF_WORDCHAR;
goto join_posix;
case 'B':
invert = 1;
/* FALLTHROUGH */
case 'b':
{
regex_charset charset = get_regex_charset(RExC_flags);
RExC_seen_zerolen++;
RExC_seen |= REG_LOOKBEHIND_SEEN;
op = BOUND + charset;
if (op == BOUNDL) {
RExC_contains_locale = 1;
}
ret = reg_node(pRExC_state, op);
*flagp |= SIMPLE;
if (RExC_parse >= RExC_end || *(RExC_parse + 1) != '{') {
FLAGS(ret) = TRADITIONAL_BOUND;
if (PASS2 && op > BOUNDA) { /* /aa is same as /a */
OP(ret) = BOUNDA;
}
}
else {
STRLEN length;
char name = *RExC_parse;
char * endbrace = NULL;
RExC_parse += 2;
if (RExC_parse < RExC_end) {
endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
}
if (! endbrace) {
vFAIL2("Missing right brace on \\%c{}", name);
}
/* XXX Need to decide whether to take spaces or not. Should be
* consistent with \p{}, but that currently is SPACE, which
* means vertical too, which seems wrong
* while (isBLANK(*RExC_parse)) {
RExC_parse++;
}*/
if (endbrace == RExC_parse) {
RExC_parse++; /* After the '}' */
vFAIL2("Empty \\%c{}", name);
}
length = endbrace - RExC_parse;
/*while (isBLANK(*(RExC_parse + length - 1))) {
length--;
}*/
switch (*RExC_parse) {
case 'g':
if ( length != 1
&& (memNEs(RExC_parse + 1, length - 1, "cb")))
{
goto bad_bound_type;
}
FLAGS(ret) = GCB_BOUND;
break;
case 'l':
if (length != 2 || *(RExC_parse + 1) != 'b') {
goto bad_bound_type;
}
FLAGS(ret) = LB_BOUND;
break;
case 's':
if (length != 2 || *(RExC_parse + 1) != 'b') {
goto bad_bound_type;
}
FLAGS(ret) = SB_BOUND;
break;
case 'w':
if (length != 2 || *(RExC_parse + 1) != 'b') {
goto bad_bound_type;
}
FLAGS(ret) = WB_BOUND;
break;
default:
bad_bound_type:
RExC_parse = endbrace;
vFAIL2utf8f(
"'%" UTF8f "' is an unknown bound type",
UTF8fARG(UTF, length, endbrace - length));
NOT_REACHED; /*NOTREACHED*/
}
RExC_parse = endbrace;
REQUIRE_UNI_RULES(flagp, NULL);
if (PASS2 && op >= BOUNDA) { /* /aa is same as /a */
OP(ret) = BOUNDU;
length += 4;
/* Don't have to worry about UTF-8, in this message because
* to get here the contents of the \b must be ASCII */
ckWARN4reg(RExC_parse + 1, /* Include the '}' in msg */
"Using /u for '%.*s' instead of /%s",
(unsigned) length,
endbrace - length + 1,
(charset == REGEX_ASCII_RESTRICTED_CHARSET)
? ASCII_RESTRICT_PAT_MODS
: ASCII_MORE_RESTRICT_PAT_MODS);
}
}
if (PASS2 && invert) {
OP(ret) += NBOUND - BOUND;
}
goto finish_meta_pat;
}
case 'D':
invert = 1;
/* FALLTHROUGH */
case 'd':
arg = ANYOF_DIGIT;
if (! DEPENDS_SEMANTICS) {
goto join_posix;
}
/* \d doesn't have any matches in the upper Latin1 range, hence /d
* is equivalent to /u. Changing to /u saves some branches at
* runtime */
op = POSIXU;
goto join_posix_op_known;
case 'R':
ret = reg_node(pRExC_state, LNBREAK);
*flagp |= HASWIDTH|SIMPLE;
goto finish_meta_pat;
case 'H':
invert = 1;
/* FALLTHROUGH */
case 'h':
arg = ANYOF_BLANK;
op = POSIXU;
goto join_posix_op_known;
case 'V':
invert = 1;
/* FALLTHROUGH */
case 'v':
arg = ANYOF_VERTWS;
op = POSIXU;
goto join_posix_op_known;
case 'S':
invert = 1;
/* FALLTHROUGH */
case 's':
arg = ANYOF_SPACE;
join_posix:
op = POSIXD + get_regex_charset(RExC_flags);
if (op > POSIXA) { /* /aa is same as /a */
op = POSIXA;
}
else if (op == POSIXL) {
RExC_contains_locale = 1;
}
join_posix_op_known:
if (invert) {
op += NPOSIXD - POSIXD;
}
ret = reg_node(pRExC_state, op);
if (! SIZE_ONLY) {
FLAGS(ret) = namedclass_to_classnum(arg);
}
*flagp |= HASWIDTH|SIMPLE;
/* FALLTHROUGH */
finish_meta_pat:
if ( UCHARAT(RExC_parse + 1) == '{'
&& UNLIKELY(! new_regcurly(RExC_parse + 1, RExC_end)))
{
RExC_parse += 2;
vFAIL("Unescaped left brace in regex is illegal here");
}
nextchar(pRExC_state);
Set_Node_Length(ret, 2); /* MJD */
break;
case 'p':
case 'P':
RExC_parse--;
ret = regclass(pRExC_state, flagp,depth+1,
TRUE, /* means just parse this element */
FALSE, /* don't allow multi-char folds */
FALSE, /* don't silence non-portable warnings. It
would be a bug if these returned
non-portables */
(bool) RExC_strict,
TRUE, /* Allow an optimized regnode result */
NULL,
NULL);
if (*flagp & RESTART_PASS1)
return NULL;
/* regclass() can only return RESTART_PASS1 and NEED_UTF8 if
* multi-char folds are allowed. */
if (!ret)
FAIL2("panic: regclass returned NULL to regatom, flags=%#" UVxf,
(UV) *flagp);
RExC_parse--;
Set_Node_Offset(ret, parse_start);
Set_Node_Cur_Length(ret, parse_start - 2);
nextchar(pRExC_state);
break;
case 'N':
/* Handle \N, \N{} and \N{NAMED SEQUENCE} (the latter meaning the
* \N{...} evaluates to a sequence of more than one code points).
* The function call below returns a regnode, which is our result.
* The parameters cause it to fail if the \N{} evaluates to a
* single code point; we handle those like any other literal. The
* reason that the multicharacter case is handled here and not as
* part of the EXACtish code is because of quantifiers. In
* /\N{BLAH}+/, the '+' applies to the whole thing, and doing it
* this way makes that Just Happen. dmq.
* join_exact() will join this up with adjacent EXACTish nodes
* later on, if appropriate. */
++RExC_parse;
if (grok_bslash_N(pRExC_state,
&ret, /* Want a regnode returned */
NULL, /* Fail if evaluates to a single code
point */
NULL, /* Don't need a count of how many code
points */
flagp,
RExC_strict,
depth)
) {
break;
}
if (*flagp & RESTART_PASS1)
return NULL;
/* Here, evaluates to a single code point. Go get that */
RExC_parse = parse_start;
goto defchar;
case 'k': /* Handle \k<NAME> and \k'NAME' */
parse_named_seq:
{
char ch;
if ( RExC_parse >= RExC_end - 1
|| (( ch = RExC_parse[1]) != '<'
&& ch != '\''
&& ch != '{'))
{
RExC_parse++;
/* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
vFAIL2("Sequence %.2s... not terminated",parse_start);
} else {
RExC_parse += 2;
ret = handle_named_backref(pRExC_state,
flagp,
parse_start,
(ch == '<')
? '>'
: (ch == '{')
? '}'
: '\'');
}
break;
}
case 'g':
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
{
I32 num;
bool hasbrace = 0;
if (*RExC_parse == 'g') {
bool isrel = 0;
RExC_parse++;
if (*RExC_parse == '{') {
RExC_parse++;
hasbrace = 1;
}
if (*RExC_parse == '-') {
RExC_parse++;
isrel = 1;
}
if (hasbrace && !isDIGIT(*RExC_parse)) {
if (isrel) RExC_parse--;
RExC_parse -= 2;
goto parse_named_seq;
}
if (RExC_parse >= RExC_end) {
goto unterminated_g;
}
num = S_backref_value(RExC_parse);
if (num == 0)
vFAIL("Reference to invalid group 0");
else if (num == I32_MAX) {
if (isDIGIT(*RExC_parse))
vFAIL("Reference to nonexistent group");
else
unterminated_g:
vFAIL("Unterminated \\g... pattern");
}
if (isrel) {
num = RExC_npar - num;
if (num < 1)
vFAIL("Reference to nonexistent or unclosed group");
}
}
else {
num = S_backref_value(RExC_parse);
/* bare \NNN might be backref or octal - if it is larger
* than or equal RExC_npar then it is assumed to be an
* octal escape. Note RExC_npar is +1 from the actual
* number of parens. */
/* Note we do NOT check if num == I32_MAX here, as that is
* handled by the RExC_npar check */
if (
/* any numeric escape < 10 is always a backref */
num > 9
/* any numeric escape < RExC_npar is a backref */
&& num >= RExC_npar
/* cannot be an octal escape if it starts with 8 */
&& *RExC_parse != '8'
/* cannot be an octal escape it it starts with 9 */
&& *RExC_parse != '9'
)
{
/* Probably not a backref, instead likely to be an
* octal character escape, e.g. \35 or \777.
* The above logic should make it obvious why using
* octal escapes in patterns is problematic. - Yves */
RExC_parse = parse_start;
goto defchar;
}
}
/* At this point RExC_parse points at a numeric escape like
* \12 or \88 or something similar, which we should NOT treat
* as an octal escape. It may or may not be a valid backref
* escape. For instance \88888888 is unlikely to be a valid
* backref. */
while (isDIGIT(*RExC_parse))
RExC_parse++;
if (hasbrace) {
if (*RExC_parse != '}')
vFAIL("Unterminated \\g{...} pattern");
RExC_parse++;
}
if (!SIZE_ONLY) {
if (num > (I32)RExC_rx->nparens)
vFAIL("Reference to nonexistent group");
}
RExC_sawback = 1;
ret = reganode(pRExC_state,
((! FOLD)
? REF
: (ASCII_FOLD_RESTRICTED)
? REFFA
: (AT_LEAST_UNI_SEMANTICS)
? REFFU
: (LOC)
? REFFL
: REFF),
num);
*flagp |= HASWIDTH;
/* override incorrect value set in reganode MJD */
Set_Node_Offset(ret, parse_start);
Set_Node_Cur_Length(ret, parse_start-1);
skip_to_be_ignored_text(pRExC_state, &RExC_parse,
FALSE /* Don't force to /x */ );
}
break;
case '\0':
if (RExC_parse >= RExC_end)
FAIL("Trailing \\");
/* FALLTHROUGH */
default:
/* Do not generate "unrecognized" warnings here, we fall
back into the quick-grab loop below */
RExC_parse = parse_start;
goto defchar;
} /* end of switch on a \foo sequence */
break;
case '#':
/* '#' comments should have been spaced over before this function was
* called */
assert((RExC_flags & RXf_PMf_EXTENDED) == 0);
/*
if (RExC_flags & RXf_PMf_EXTENDED) {
RExC_parse = reg_skipcomment( pRExC_state, RExC_parse );
if (RExC_parse < RExC_end)
goto tryagain;
}
*/
/* FALLTHROUGH */
default:
defchar: {
/* Here, we have determined that the next thing is probably a
* literal character. RExC_parse points to the first byte of its
* definition. (It still may be an escape sequence that evaluates
* to a single character) */
STRLEN len = 0;
UV ender = 0;
char *p;
char *s;
#define MAX_NODE_STRING_SIZE 127
char foldbuf[MAX_NODE_STRING_SIZE+UTF8_MAXBYTES_CASE];
char *s0;
U8 upper_parse = MAX_NODE_STRING_SIZE;
U8 node_type = compute_EXACTish(pRExC_state);
bool next_is_quantifier;
char * oldp = NULL;
/* We can convert EXACTF nodes to EXACTFU if they contain only
* characters that match identically regardless of the target
* string's UTF8ness. The reason to do this is that EXACTF is not
* trie-able, EXACTFU is.
*
* Similarly, we can convert EXACTFL nodes to EXACTFLU8 if they
* contain only above-Latin1 characters (hence must be in UTF8),
* which don't participate in folds with Latin1-range characters,
* as the latter's folds aren't known until runtime. (We don't
* need to figure this out until pass 2) */
bool maybe_exactfu = PASS2
&& (node_type == EXACTF || node_type == EXACTFL);
/* If a folding node contains only code points that don't
* participate in folds, it can be changed into an EXACT node,
* which allows the optimizer more things to look for */
bool maybe_exact;
ret = reg_node(pRExC_state, node_type);
/* In pass1, folded, we use a temporary buffer instead of the
* actual node, as the node doesn't exist yet */
s = (SIZE_ONLY && FOLD) ? foldbuf : STRING(ret);
s0 = s;
reparse:
/* We look for the EXACTFish to EXACT node optimizaton only if
* folding. (And we don't need to figure this out until pass 2).
* XXX It might actually make sense to split the node into portions
* that are exact and ones that aren't, so that we could later use
* the exact ones to find the longest fixed and floating strings.
* One would want to join them back into a larger node. One could
* use a pseudo regnode like 'EXACT_ORIG_FOLD' */
maybe_exact = FOLD && PASS2;
/* XXX The node can hold up to 255 bytes, yet this only goes to
* 127. I (khw) do not know why. Keeping it somewhat less than
* 255 allows us to not have to worry about overflow due to
* converting to utf8 and fold expansion, but that value is
* 255-UTF8_MAXBYTES_CASE. join_exact() may join adjacent nodes
* split up by this limit into a single one using the real max of
* 255. Even at 127, this breaks under rare circumstances. If
* folding, we do not want to split a node at a character that is a
* non-final in a multi-char fold, as an input string could just
* happen to want to match across the node boundary. The join
* would solve that problem if the join actually happens. But a
* series of more than two nodes in a row each of 127 would cause
* the first join to succeed to get to 254, but then there wouldn't
* be room for the next one, which could at be one of those split
* multi-char folds. I don't know of any fool-proof solution. One
* could back off to end with only a code point that isn't such a
* non-final, but it is possible for there not to be any in the
* entire node. */
assert( ! UTF /* Is at the beginning of a character */
|| UTF8_IS_INVARIANT(UCHARAT(RExC_parse))
|| UTF8_IS_START(UCHARAT(RExC_parse)));
/* Here, we have a literal character. Find the maximal string of
* them in the input that we can fit into a single EXACTish node.
* We quit at the first non-literal or when the node gets full */
for (p = RExC_parse;
len < upper_parse && p < RExC_end;
len++)
{
oldp = p;
/* White space has already been ignored */
assert( (RExC_flags & RXf_PMf_EXTENDED) == 0
|| ! is_PATWS_safe((p), RExC_end, UTF));
switch ((U8)*p) {
case '^':
case '$':
case '.':
case '[':
case '(':
case ')':
case '|':
goto loopdone;
case '\\':
/* Literal Escapes Switch
This switch is meant to handle escape sequences that
resolve to a literal character.
Every escape sequence that represents something
else, like an assertion or a char class, is handled
in the switch marked 'Special Escapes' above in this
routine, but also has an entry here as anything that
isn't explicitly mentioned here will be treated as
an unescaped equivalent literal.
*/
switch ((U8)*++p) {
/* These are all the special escapes. */
case 'A': /* Start assertion */
case 'b': case 'B': /* Word-boundary assertion*/
case 'C': /* Single char !DANGEROUS! */
case 'd': case 'D': /* digit class */
case 'g': case 'G': /* generic-backref, pos assertion */
case 'h': case 'H': /* HORIZWS */
case 'k': case 'K': /* named backref, keep marker */
case 'p': case 'P': /* Unicode property */
case 'R': /* LNBREAK */
case 's': case 'S': /* space class */
case 'v': case 'V': /* VERTWS */
case 'w': case 'W': /* word class */
case 'X': /* eXtended Unicode "combining
character sequence" */
case 'z': case 'Z': /* End of line/string assertion */
--p;
goto loopdone;
/* Anything after here is an escape that resolves to a
literal. (Except digits, which may or may not)
*/
case 'n':
ender = '\n';
p++;
break;
case 'N': /* Handle a single-code point named character. */
RExC_parse = p + 1;
if (! grok_bslash_N(pRExC_state,
NULL, /* Fail if evaluates to
anything other than a
single code point */
&ender, /* The returned single code
point */
NULL, /* Don't need a count of
how many code points */
flagp,
RExC_strict,
depth)
) {
if (*flagp & NEED_UTF8)
FAIL("panic: grok_bslash_N set NEED_UTF8");
if (*flagp & RESTART_PASS1)
return NULL;
/* Here, it wasn't a single code point. Go close
* up this EXACTish node. The switch() prior to
* this switch handles the other cases */
RExC_parse = p = oldp;
goto loopdone;
}
p = RExC_parse;
RExC_parse = parse_start;
if (ender > 0xff) {
REQUIRE_UTF8(flagp);
}
break;
case 'r':
ender = '\r';
p++;
break;
case 't':
ender = '\t';
p++;
break;
case 'f':
ender = '\f';
p++;
break;
case 'e':
ender = ESC_NATIVE;
p++;
break;
case 'a':
ender = '\a';
p++;
break;
case 'o':
{
UV result;
const char* error_msg;
bool valid = grok_bslash_o(&p,
RExC_end,
&result,
&error_msg,
PASS2, /* out warnings */
(bool) RExC_strict,
TRUE, /* Output warnings
for non-
portables */
UTF);
if (! valid) {
RExC_parse = p; /* going to die anyway; point
to exact spot of failure */
vFAIL(error_msg);
}
ender = result;
if (ender > 0xff) {
REQUIRE_UTF8(flagp);
}
break;
}
case 'x':
{
UV result = UV_MAX; /* initialize to erroneous
value */
const char* error_msg;
bool valid = grok_bslash_x(&p,
RExC_end,
&result,
&error_msg,
PASS2, /* out warnings */
(bool) RExC_strict,
TRUE, /* Silence warnings
for non-
portables */
UTF);
if (! valid) {
RExC_parse = p; /* going to die anyway; point
to exact spot of failure */
vFAIL(error_msg);
}
ender = result;
if (ender < 0x100) {
#ifdef EBCDIC
if (RExC_recode_x_to_native) {
ender = LATIN1_TO_NATIVE(ender);
}
#endif
}
else {
REQUIRE_UTF8(flagp);
}
break;
}
case 'c':
p++;
ender = grok_bslash_c(*p++, PASS2);
break;
case '8': case '9': /* must be a backreference */
--p;
/* we have an escape like \8 which cannot be an octal escape
* so we exit the loop, and let the outer loop handle this
* escape which may or may not be a legitimate backref. */
goto loopdone;
case '1': case '2': case '3':case '4':
case '5': case '6': case '7':
/* When we parse backslash escapes there is ambiguity
* between backreferences and octal escapes. Any escape
* from \1 - \9 is a backreference, any multi-digit
* escape which does not start with 0 and which when
* evaluated as decimal could refer to an already
* parsed capture buffer is a back reference. Anything
* else is octal.
*
* Note this implies that \118 could be interpreted as
* 118 OR as "\11" . "8" depending on whether there
* were 118 capture buffers defined already in the
* pattern. */
/* NOTE, RExC_npar is 1 more than the actual number of
* parens we have seen so far, hence the < RExC_npar below. */
if ( !isDIGIT(p[1]) || S_backref_value(p) < RExC_npar)
{ /* Not to be treated as an octal constant, go
find backref */
--p;
goto loopdone;
}
/* FALLTHROUGH */
case '0':
{
I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
STRLEN numlen = 3;
ender = grok_oct(p, &numlen, &flags, NULL);
if (ender > 0xff) {
REQUIRE_UTF8(flagp);
}
p += numlen;
if (PASS2 /* like \08, \178 */
&& numlen < 3
&& isDIGIT(*p) && ckWARN(WARN_REGEXP))
{
reg_warn_non_literal_string(
p + 1,
form_short_octal_warning(p, numlen));
}
}
break;
case '\0':
if (p >= RExC_end)
FAIL("Trailing \\");
/* FALLTHROUGH */
default:
if (!SIZE_ONLY&& isALPHANUMERIC(*p)) {
/* Include any left brace following the alpha to emphasize
* that it could be part of an escape at some point
* in the future */
int len = (isALPHA(*p) && *(p + 1) == '{') ? 2 : 1;
ckWARN3reg(p + len, "Unrecognized escape \\%.*s passed through", len, p);
}
goto normal_default;
} /* End of switch on '\' */
break;
case '{':
/* Currently we allow an lbrace at the start of a construct
* without raising a warning. This is because we think we
* will never want such a brace to be meant to be other
* than taken literally. */
if (len || (p > RExC_start && isALPHA_A(*(p - 1)))) {
/* But, we raise a fatal warning otherwise, as the
* deprecation cycle has come and gone. Except that it
* turns out that some heavily-relied on upstream
* software, notably GNU Autoconf, have failed to fix
* their uses. For these, don't make it fatal unless
* we anticipate using the '{' for something else.
* This happens after any alpha, and for a looser {m,n}
* quantifier specification */
if ( RExC_strict
|| ( p > parse_start + 1
&& isALPHA_A(*(p - 1))
&& *(p - 2) == '\\')
|| new_regcurly(p, RExC_end))
{
RExC_parse = p + 1;
vFAIL("Unescaped left brace in regex is "
"illegal here");
}
if (PASS2) {
ckWARNregdep(p + 1,
"Unescaped left brace in regex is "
"deprecated here (and will be fatal "
"in Perl 5.30), passed through");
}
}
goto normal_default;
case '}':
case ']':
if (PASS2 && p > RExC_parse && RExC_strict) {
ckWARN2reg(p + 1, "Unescaped literal '%c'", *p);
}
/*FALLTHROUGH*/
default: /* A literal character */
normal_default:
if (! UTF8_IS_INVARIANT(*p) && UTF) {
STRLEN numlen;
ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
&numlen, UTF8_ALLOW_DEFAULT);
p += numlen;
}
else
ender = (U8) *p++;
break;
} /* End of switch on the literal */
/* Here, have looked at the literal character and <ender>
* contains its ordinal, <p> points to the character after it.
* We need to check if the next non-ignored thing is a
* quantifier. Move <p> to after anything that should be
* ignored, which, as a side effect, positions <p> for the next
* loop iteration */
skip_to_be_ignored_text(pRExC_state, &p,
FALSE /* Don't force to /x */ );
/* If the next thing is a quantifier, it applies to this
* character only, which means that this character has to be in
* its own node and can't just be appended to the string in an
* existing node, so if there are already other characters in
* the node, close the node with just them, and set up to do
* this character again next time through, when it will be the
* only thing in its new node */
next_is_quantifier = LIKELY(p < RExC_end)
&& UNLIKELY(ISMULT2(p));
if (next_is_quantifier && LIKELY(len)) {
p = oldp;
goto loopdone;
}
/* Ready to add 'ender' to the node */
if (! FOLD) { /* The simple case, just append the literal */
/* In the sizing pass, we need only the size of the
* character we are appending, hence we can delay getting
* its representation until PASS2. */
if (SIZE_ONLY) {
if (UTF && ! UVCHR_IS_INVARIANT(ender)) {
const STRLEN unilen = UVCHR_SKIP(ender);
s += unilen;
/* We have to subtract 1 just below (and again in
* the corresponding PASS2 code) because the loop
* increments <len> each time, as all but this path
* (and one other) through it add a single byte to
* the EXACTish node. But these paths would change
* len to be the correct final value, so cancel out
* the increment that follows */
len += unilen - 1;
}
else {
s++;
}
} else { /* PASS2 */
not_fold_common:
if (UTF && ! UVCHR_IS_INVARIANT(ender)) {
U8 * new_s = uvchr_to_utf8((U8*)s, ender);
len += (char *) new_s - s - 1;
s = (char *) new_s;
}
else {
*(s++) = (char) ender;
}
}
}
else if (LOC && is_PROBLEMATIC_LOCALE_FOLD_cp(ender)) {
/* Here are folding under /l, and the code point is
* problematic. First, we know we can't simplify things */
maybe_exact = FALSE;
maybe_exactfu = FALSE;
/* A problematic code point in this context means that its
* fold isn't known until runtime, so we can't fold it now.
* (The non-problematic code points are the above-Latin1
* ones that fold to also all above-Latin1. Their folds
* don't vary no matter what the locale is.) But here we
* have characters whose fold depends on the locale.
* Unlike the non-folding case above, we have to keep track
* of these in the sizing pass, so that we can make sure we
* don't split too-long nodes in the middle of a potential
* multi-char fold. And unlike the regular fold case
* handled in the else clauses below, we don't actually
* fold and don't have special cases to consider. What we
* do for both passes is the PASS2 code for non-folding */
goto not_fold_common;
}
else /* A regular FOLD code point */
if (! ( UTF
#if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
|| (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
|| UNICODE_DOT_DOT_VERSION > 0)
/* See comments for join_exact() as to why we fold
* this non-UTF at compile time */
|| ( node_type == EXACTFU
&& ender == LATIN_SMALL_LETTER_SHARP_S)
#endif
)) {
/* Here, are folding and are not UTF-8 encoded; therefore
* the character must be in the range 0-255, and is not /l
* (Not /l because we already handled these under /l in
* is_PROBLEMATIC_LOCALE_FOLD_cp) */
if (IS_IN_SOME_FOLD_L1(ender)) {
maybe_exact = FALSE;
/* See if the character's fold differs between /d and
* /u. This includes the multi-char fold SHARP S to
* 'ss' */
if (UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S)) {
RExC_seen_unfolded_sharp_s = 1;
maybe_exactfu = FALSE;
}
else if (maybe_exactfu
&& (PL_fold[ender] != PL_fold_latin1[ender]
#if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
|| (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
|| UNICODE_DOT_DOT_VERSION > 0)
|| ( len > 0
&& isALPHA_FOLD_EQ(ender, 's')
&& isALPHA_FOLD_EQ(*(s-1), 's'))
#endif
)) {
maybe_exactfu = FALSE;
}
}
/* Even when folding, we store just the input character, as
* we have an array that finds its fold quickly */
*(s++) = (char) ender;
}
else { /* FOLD, and UTF (or sharp s) */
/* Unlike the non-fold case, we do actually have to
* calculate the results here in pass 1. This is for two
* reasons, the folded length may be longer than the
* unfolded, and we have to calculate how many EXACTish
* nodes it will take; and we may run out of room in a node
* in the middle of a potential multi-char fold, and have
* to back off accordingly. */
UV folded;
if (isASCII_uni(ender)) {
folded = toFOLD(ender);
*(s)++ = (U8) folded;
}
else {
STRLEN foldlen;
folded = _to_uni_fold_flags(
ender,
(U8 *) s,
&foldlen,
FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
? FOLD_FLAGS_NOMIX_ASCII
: 0));
s += foldlen;
/* The loop increments <len> each time, as all but this
* path (and one other) through it add a single byte to
* the EXACTish node. But this one has changed len to
* be the correct final value, so subtract one to
* cancel out the increment that follows */
len += foldlen - 1;
}
/* If this node only contains non-folding code points so
* far, see if this new one is also non-folding */
if (maybe_exact) {
if (folded != ender) {
maybe_exact = FALSE;
}
else {
/* Here the fold is the original; we have to check
* further to see if anything folds to it */
if (_invlist_contains_cp(PL_utf8_foldable,
ender))
{
maybe_exact = FALSE;
}
}
}
ender = folded;
}
if (next_is_quantifier) {
/* Here, the next input is a quantifier, and to get here,
* the current character is the only one in the node.
* Also, here <len> doesn't include the final byte for this
* character */
len++;
goto loopdone;
}
} /* End of loop through literal characters */
/* Here we have either exhausted the input or ran out of room in
* the node. (If we encountered a character that can't be in the
* node, transfer is made directly to <loopdone>, and so we
* wouldn't have fallen off the end of the loop.) In the latter
* case, we artificially have to split the node into two, because
* we just don't have enough space to hold everything. This
* creates a problem if the final character participates in a
* multi-character fold in the non-final position, as a match that
* should have occurred won't, due to the way nodes are matched,
* and our artificial boundary. So back off until we find a non-
* problematic character -- one that isn't at the beginning or
* middle of such a fold. (Either it doesn't participate in any
* folds, or appears only in the final position of all the folds it
* does participate in.) A better solution with far fewer false
* positives, and that would fill the nodes more completely, would
* be to actually have available all the multi-character folds to
* test against, and to back-off only far enough to be sure that
* this node isn't ending with a partial one. <upper_parse> is set
* further below (if we need to reparse the node) to include just
* up through that final non-problematic character that this code
* identifies, so when it is set to less than the full node, we can
* skip the rest of this */
if (FOLD && p < RExC_end && upper_parse == MAX_NODE_STRING_SIZE) {
const STRLEN full_len = len;
assert(len >= MAX_NODE_STRING_SIZE);
/* Here, <s> points to the final byte of the final character.
* Look backwards through the string until find a non-
* problematic character */
if (! UTF) {
/* This has no multi-char folds to non-UTF characters */
if (ASCII_FOLD_RESTRICTED) {
goto loopdone;
}
while (--s >= s0 && IS_NON_FINAL_FOLD(*s)) { }
len = s - s0 + 1;
}
else {
if (! PL_NonL1NonFinalFold) {
PL_NonL1NonFinalFold = _new_invlist_C_array(
NonL1_Perl_Non_Final_Folds_invlist);
}
/* Point to the first byte of the final character */
s = (char *) utf8_hop((U8 *) s, -1);
while (s >= s0) { /* Search backwards until find
non-problematic char */
if (UTF8_IS_INVARIANT(*s)) {
/* There are no ascii characters that participate
* in multi-char folds under /aa. In EBCDIC, the
* non-ascii invariants are all control characters,
* so don't ever participate in any folds. */
if (ASCII_FOLD_RESTRICTED
|| ! IS_NON_FINAL_FOLD(*s))
{
break;
}
}
else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
if (! IS_NON_FINAL_FOLD(EIGHT_BIT_UTF8_TO_NATIVE(
*s, *(s+1))))
{
break;
}
}
else if (! _invlist_contains_cp(
PL_NonL1NonFinalFold,
valid_utf8_to_uvchr((U8 *) s, NULL)))
{
break;
}
/* Here, the current character is problematic in that
* it does occur in the non-final position of some
* fold, so try the character before it, but have to
* special case the very first byte in the string, so
* we don't read outside the string */
s = (s == s0) ? s -1 : (char *) utf8_hop((U8 *) s, -1);
} /* End of loop backwards through the string */
/* If there were only problematic characters in the string,
* <s> will point to before s0, in which case the length
* should be 0, otherwise include the length of the
* non-problematic character just found */
len = (s < s0) ? 0 : s - s0 + UTF8SKIP(s);
}
/* Here, have found the final character, if any, that is
* non-problematic as far as ending the node without splitting
* it across a potential multi-char fold. <len> contains the
* number of bytes in the node up-to and including that
* character, or is 0 if there is no such character, meaning
* the whole node contains only problematic characters. In
* this case, give up and just take the node as-is. We can't
* do any better */
if (len == 0) {
len = full_len;
/* If the node ends in an 's' we make sure it stays EXACTF,
* as if it turns into an EXACTFU, it could later get
* joined with another 's' that would then wrongly match
* the sharp s */
if (maybe_exactfu && isALPHA_FOLD_EQ(ender, 's'))
{
maybe_exactfu = FALSE;
}
} else {
/* Here, the node does contain some characters that aren't
* problematic. If one such is the final character in the
* node, we are done */
if (len == full_len) {
goto loopdone;
}
else if (len + ((UTF) ? UTF8SKIP(s) : 1) == full_len) {
/* If the final character is problematic, but the
* penultimate is not, back-off that last character to
* later start a new node with it */
p = oldp;
goto loopdone;
}
/* Here, the final non-problematic character is earlier
* in the input than the penultimate character. What we do
* is reparse from the beginning, going up only as far as
* this final ok one, thus guaranteeing that the node ends
* in an acceptable character. The reason we reparse is
* that we know how far in the character is, but we don't
* know how to correlate its position with the input parse.
* An alternate implementation would be to build that
* correlation as we go along during the original parse,
* but that would entail extra work for every node, whereas
* this code gets executed only when the string is too
* large for the node, and the final two characters are
* problematic, an infrequent occurrence. Yet another
* possible strategy would be to save the tail of the
* string, and the next time regatom is called, initialize
* with that. The problem with this is that unless you
* back off one more character, you won't be guaranteed
* regatom will get called again, unless regbranch,
* regpiece ... are also changed. If you do back off that
* extra character, so that there is input guaranteed to
* force calling regatom, you can't handle the case where
* just the first character in the node is acceptable. I
* (khw) decided to try this method which doesn't have that
* pitfall; if performance issues are found, we can do a
* combination of the current approach plus that one */
upper_parse = len;
len = 0;
s = s0;
goto reparse;
}
} /* End of verifying node ends with an appropriate char */
loopdone: /* Jumped to when encounters something that shouldn't be
in the node */
/* I (khw) don't know if you can get here with zero length, but the
* old code handled this situation by creating a zero-length EXACT
* node. Might as well be NOTHING instead */
if (len == 0) {
OP(ret) = NOTHING;
}
else {
if (FOLD) {
/* If 'maybe_exact' is still set here, means there are no
* code points in the node that participate in folds;
* similarly for 'maybe_exactfu' and code points that match
* differently depending on UTF8ness of the target string
* (for /u), or depending on locale for /l */
if (maybe_exact) {
OP(ret) = (LOC)
? EXACTL
: EXACT;
}
else if (maybe_exactfu) {
OP(ret) = (LOC)
? EXACTFLU8
: EXACTFU;
}
}
alloc_maybe_populate_EXACT(pRExC_state, ret, flagp, len, ender,
FALSE /* Don't look to see if could
be turned into an EXACT
node, as we have already
computed that */
);
}
RExC_parse = p - 1;
Set_Node_Cur_Length(ret, parse_start);
RExC_parse = p;
{
/* len is STRLEN which is unsigned, need to copy to signed */
IV iv = len;
if (iv < 0)
vFAIL("Internal disaster");
}
} /* End of label 'defchar:' */
break;
} /* End of giant switch on input character */
/* Position parse to next real character */
skip_to_be_ignored_text(pRExC_state, &RExC_parse,
FALSE /* Don't force to /x */ );
if (PASS2 && *RExC_parse == '{' && OP(ret) != SBOL && ! regcurly(RExC_parse)) {
ckWARNregdep(RExC_parse + 1, "Unescaped left brace in regex is deprecated here (and will be fatal in Perl 5.30), passed through");
}
return(ret);
}
STATIC void
S_populate_ANYOF_from_invlist(pTHX_ regnode *node, SV** invlist_ptr)
{
/* Uses the inversion list '*invlist_ptr' to populate the ANYOF 'node'. It
* sets up the bitmap and any flags, removing those code points from the
* inversion list, setting it to NULL should it become completely empty */
PERL_ARGS_ASSERT_POPULATE_ANYOF_FROM_INVLIST;
assert(PL_regkind[OP(node)] == ANYOF);
ANYOF_BITMAP_ZERO(node);
if (*invlist_ptr) {
/* This gets set if we actually need to modify things */
bool change_invlist = FALSE;
UV start, end;
/* Start looking through *invlist_ptr */
invlist_iterinit(*invlist_ptr);
while (invlist_iternext(*invlist_ptr, &start, &end)) {
UV high;
int i;
if (end == UV_MAX && start <= NUM_ANYOF_CODE_POINTS) {
ANYOF_FLAGS(node) |= ANYOF_MATCHES_ALL_ABOVE_BITMAP;
}
/* Quit if are above what we should change */
if (start >= NUM_ANYOF_CODE_POINTS) {
break;
}
change_invlist = TRUE;
/* Set all the bits in the range, up to the max that we are doing */
high = (end < NUM_ANYOF_CODE_POINTS - 1)
? end
: NUM_ANYOF_CODE_POINTS - 1;
for (i = start; i <= (int) high; i++) {
if (! ANYOF_BITMAP_TEST(node, i)) {
ANYOF_BITMAP_SET(node, i);
}
}
}
invlist_iterfinish(*invlist_ptr);
/* Done with loop; remove any code points that are in the bitmap from
* *invlist_ptr; similarly for code points above the bitmap if we have
* a flag to match all of them anyways */
if (change_invlist) {
_invlist_subtract(*invlist_ptr, PL_InBitmap, invlist_ptr);
}
if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
_invlist_intersection(*invlist_ptr, PL_InBitmap, invlist_ptr);
}
/* If have completely emptied it, remove it completely */
if (_invlist_len(*invlist_ptr) == 0) {
SvREFCNT_dec_NN(*invlist_ptr);
*invlist_ptr = NULL;
}
}
}
/* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
Character classes ([:foo:]) can also be negated ([:^foo:]).
Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
but trigger failures because they are currently unimplemented. */
#define POSIXCC_DONE(c) ((c) == ':')
#define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
#define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
#define MAYBE_POSIXCC(c) (POSIXCC(c) || (c) == '^' || (c) == ';')
#define WARNING_PREFIX "Assuming NOT a POSIX class since "
#define NO_BLANKS_POSIX_WARNING "no blanks are allowed in one"
#define SEMI_COLON_POSIX_WARNING "a semi-colon was found instead of a colon"
#define NOT_MEANT_TO_BE_A_POSIX_CLASS (OOB_NAMEDCLASS - 1)
/* 'posix_warnings' and 'warn_text' are names of variables in the following
* routine. q.v. */
#define ADD_POSIX_WARNING(p, text) STMT_START { \
if (posix_warnings) { \
if (! RExC_warn_text ) RExC_warn_text = (AV *) sv_2mortal((SV *) newAV()); \
av_push(RExC_warn_text, Perl_newSVpvf(aTHX_ \
WARNING_PREFIX \
text \
REPORT_LOCATION, \
REPORT_LOCATION_ARGS(p))); \
} \
} STMT_END
#define CLEAR_POSIX_WARNINGS() \
STMT_START { \
if (posix_warnings && RExC_warn_text) \
av_clear(RExC_warn_text); \
} STMT_END
#define CLEAR_POSIX_WARNINGS_AND_RETURN(ret) \
STMT_START { \
CLEAR_POSIX_WARNINGS(); \
return ret; \
} STMT_END
STATIC int
S_handle_possible_posix(pTHX_ RExC_state_t *pRExC_state,
const char * const s, /* Where the putative posix class begins.
Normally, this is one past the '['. This
parameter exists so it can be somewhere
besides RExC_parse. */
char ** updated_parse_ptr, /* Where to set the updated parse pointer, or
NULL */
AV ** posix_warnings, /* Where to place any generated warnings, or
NULL */
const bool check_only /* Don't die if error */
)
{
/* This parses what the caller thinks may be one of the three POSIX
* constructs:
* 1) a character class, like [:blank:]
* 2) a collating symbol, like [. .]
* 3) an equivalence class, like [= =]
* In the latter two cases, it croaks if it finds a syntactically legal
* one, as these are not handled by Perl.
*
* The main purpose is to look for a POSIX character class. It returns:
* a) the class number
* if it is a completely syntactically and semantically legal class.
* 'updated_parse_ptr', if not NULL, is set to point to just after the
* closing ']' of the class
* b) OOB_NAMEDCLASS
* if it appears that one of the three POSIX constructs was meant, but
* its specification was somehow defective. 'updated_parse_ptr', if
* not NULL, is set to point to the character just after the end
* character of the class. See below for handling of warnings.
* c) NOT_MEANT_TO_BE_A_POSIX_CLASS
* if it doesn't appear that a POSIX construct was intended.
* 'updated_parse_ptr' is not changed. No warnings nor errors are
* raised.
*
* In b) there may be errors or warnings generated. If 'check_only' is
* TRUE, then any errors are discarded. Warnings are returned to the
* caller via an AV* created into '*posix_warnings' if it is not NULL. If
* instead it is NULL, warnings are suppressed. This is done in all
* passes. The reason for this is that the rest of the parsing is heavily
* dependent on whether this routine found a valid posix class or not. If
* it did, the closing ']' is absorbed as part of the class. If no class,
* or an invalid one is found, any ']' will be considered the terminator of
* the outer bracketed character class, leading to very different results.
* In particular, a '(?[ ])' construct will likely have a syntax error if
* the class is parsed other than intended, and this will happen in pass1,
* before the warnings would normally be output. This mechanism allows the
* caller to output those warnings in pass1 just before dieing, giving a
* much better clue as to what is wrong.
*
* The reason for this function, and its complexity is that a bracketed
* character class can contain just about anything. But it's easy to
* mistype the very specific posix class syntax but yielding a valid
* regular bracketed class, so it silently gets compiled into something
* quite unintended.
*
* The solution adopted here maintains backward compatibility except that
* it adds a warning if it looks like a posix class was intended but
* improperly specified. The warning is not raised unless what is input
* very closely resembles one of the 14 legal posix classes. To do this,
* it uses fuzzy parsing. It calculates how many single-character edits it
* would take to transform what was input into a legal posix class. Only
* if that number is quite small does it think that the intention was a
* posix class. Obviously these are heuristics, and there will be cases
* where it errs on one side or another, and they can be tweaked as
* experience informs.
*
* The syntax for a legal posix class is:
*
* qr/(?xa: \[ : \^? [[:lower:]]{4,6} : \] )/
*
* What this routine considers syntactically to be an intended posix class
* is this (the comments indicate some restrictions that the pattern
* doesn't show):
*
* qr/(?x: \[? # The left bracket, possibly
* # omitted
* \h* # possibly followed by blanks
* (?: \^ \h* )? # possibly a misplaced caret
* [:;]? # The opening class character,
* # possibly omitted. A typo
* # semi-colon can also be used.
* \h*
* \^? # possibly a correctly placed
* # caret, but not if there was also
* # a misplaced one
* \h*
* .{3,15} # The class name. If there are
* # deviations from the legal syntax,
* # its edit distance must be close
* # to a real class name in order
* # for it to be considered to be
* # an intended posix class.
* \h*
* [[:punct:]]? # The closing class character,
* # possibly omitted. If not a colon
* # nor semi colon, the class name
* # must be even closer to a valid
* # one
* \h*
* \]? # The right bracket, possibly
* # omitted.
* )/
*
* In the above, \h must be ASCII-only.
*
* These are heuristics, and can be tweaked as field experience dictates.
* There will be cases when someone didn't intend to specify a posix class
* that this warns as being so. The goal is to minimize these, while
* maximizing the catching of things intended to be a posix class that
* aren't parsed as such.
*/
const char* p = s;
const char * const e = RExC_end;
unsigned complement = 0; /* If to complement the class */
bool found_problem = FALSE; /* Assume OK until proven otherwise */
bool has_opening_bracket = FALSE;
bool has_opening_colon = FALSE;
int class_number = OOB_NAMEDCLASS; /* Out-of-bounds until find
valid class */
const char * possible_end = NULL; /* used for a 2nd parse pass */
const char* name_start; /* ptr to class name first char */
/* If the number of single-character typos the input name is away from a
* legal name is no more than this number, it is considered to have meant
* the legal name */
int max_distance = 2;
/* to store the name. The size determines the maximum length before we
* decide that no posix class was intended. Should be at least
* sizeof("alphanumeric") */
UV input_text[15];
STATIC_ASSERT_DECL(C_ARRAY_LENGTH(input_text) >= sizeof "alphanumeric");
PERL_ARGS_ASSERT_HANDLE_POSSIBLE_POSIX;
CLEAR_POSIX_WARNINGS();
if (p >= e) {
return NOT_MEANT_TO_BE_A_POSIX_CLASS;
}
if (*(p - 1) != '[') {
ADD_POSIX_WARNING(p, "it doesn't start with a '['");
found_problem = TRUE;
}
else {
has_opening_bracket = TRUE;
}
/* They could be confused and think you can put spaces between the
* components */
if (isBLANK(*p)) {
found_problem = TRUE;
do {
p++;
} while (p < e && isBLANK(*p));
ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
}
/* For [. .] and [= =]. These are quite different internally from [: :],
* so they are handled separately. */
if (POSIXCC_NOTYET(*p) && p < e - 3) /* 1 for the close, and 1 for the ']'
and 1 for at least one char in it
*/
{
const char open_char = *p;
const char * temp_ptr = p + 1;
/* These two constructs are not handled by perl, and if we find a
* syntactically valid one, we croak. khw, who wrote this code, finds
* this explanation of them very unclear:
* http://pubs.opengroup.org/onlinepubs/009696899/basedefs/xbd_chap09.html
* And searching the rest of the internet wasn't very helpful either.
* It looks like just about any byte can be in these constructs,
* depending on the locale. But unless the pattern is being compiled
* under /l, which is very rare, Perl runs under the C or POSIX locale.
* In that case, it looks like [= =] isn't allowed at all, and that
* [. .] could be any single code point, but for longer strings the
* constituent characters would have to be the ASCII alphabetics plus
* the minus-hyphen. Any sensible locale definition would limit itself
* to these. And any portable one definitely should. Trying to parse
* the general case is a nightmare (see [perl #127604]). So, this code
* looks only for interiors of these constructs that match:
* qr/.|[-\w]{2,}/
* Using \w relaxes the apparent rules a little, without adding much
* danger of mistaking something else for one of these constructs.
*
* [. .] in some implementations described on the internet is usable to
* escape a character that otherwise is special in bracketed character
* classes. For example [.].] means a literal right bracket instead of
* the ending of the class
*
* [= =] can legitimately contain a [. .] construct, but we don't
* handle this case, as that [. .] construct will later get parsed
* itself and croak then. And [= =] is checked for even when not under
* /l, as Perl has long done so.
*
* The code below relies on there being a trailing NUL, so it doesn't
* have to keep checking if the parse ptr < e.
*/
if (temp_ptr[1] == open_char) {
temp_ptr++;
}
else while ( temp_ptr < e
&& (isWORDCHAR(*temp_ptr) || *temp_ptr == '-'))
{
temp_ptr++;
}
if (*temp_ptr == open_char) {
temp_ptr++;
if (*temp_ptr == ']') {
temp_ptr++;
if (! found_problem && ! check_only) {
RExC_parse = (char *) temp_ptr;
vFAIL3("POSIX syntax [%c %c] is reserved for future "
"extensions", open_char, open_char);
}
/* Here, the syntax wasn't completely valid, or else the call
* is to check-only */
if (updated_parse_ptr) {
*updated_parse_ptr = (char *) temp_ptr;
}
CLEAR_POSIX_WARNINGS_AND_RETURN(OOB_NAMEDCLASS);
}
}
/* If we find something that started out to look like one of these
* constructs, but isn't, we continue below so that it can be checked
* for being a class name with a typo of '.' or '=' instead of a colon.
* */
}
/* Here, we think there is a possibility that a [: :] class was meant, and
* we have the first real character. It could be they think the '^' comes
* first */
if (*p == '^') {
found_problem = TRUE;
ADD_POSIX_WARNING(p + 1, "the '^' must come after the colon");
complement = 1;
p++;
if (isBLANK(*p)) {
found_problem = TRUE;
do {
p++;
} while (p < e && isBLANK(*p));
ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
}
}
/* But the first character should be a colon, which they could have easily
* mistyped on a qwerty keyboard as a semi-colon (and which may be hard to
* distinguish from a colon, so treat that as a colon). */
if (*p == ':') {
p++;
has_opening_colon = TRUE;
}
else if (*p == ';') {
found_problem = TRUE;
p++;
ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
has_opening_colon = TRUE;
}
else {
found_problem = TRUE;
ADD_POSIX_WARNING(p, "there must be a starting ':'");
/* Consider an initial punctuation (not one of the recognized ones) to
* be a left terminator */
if (*p != '^' && *p != ']' && isPUNCT(*p)) {
p++;
}
}
/* They may think that you can put spaces between the components */
if (isBLANK(*p)) {
found_problem = TRUE;
do {
p++;
} while (p < e && isBLANK(*p));
ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
}
if (*p == '^') {
/* We consider something like [^:^alnum:]] to not have been intended to
* be a posix class, but XXX maybe we should */
if (complement) {
CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
}
complement = 1;
p++;
}
/* Again, they may think that you can put spaces between the components */
if (isBLANK(*p)) {
found_problem = TRUE;
do {
p++;
} while (p < e && isBLANK(*p));
ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
}
if (*p == ']') {
/* XXX This ']' may be a typo, and something else was meant. But
* treating it as such creates enough complications, that that
* possibility isn't currently considered here. So we assume that the
* ']' is what is intended, and if we've already found an initial '[',
* this leaves this construct looking like [:] or [:^], which almost
* certainly weren't intended to be posix classes */
if (has_opening_bracket) {
CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
}
/* But this function can be called when we parse the colon for
* something like qr/[alpha:]]/, so we back up to look for the
* beginning */
p--;
if (*p == ';') {
found_problem = TRUE;
ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
}
else if (*p != ':') {
/* XXX We are currently very restrictive here, so this code doesn't
* consider the possibility that, say, /[alpha.]]/ was intended to
* be a posix class. */
CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
}
/* Here we have something like 'foo:]'. There was no initial colon,
* and we back up over 'foo. XXX Unlike the going forward case, we
* don't handle typos of non-word chars in the middle */
has_opening_colon = FALSE;
p--;
while (p > RExC_start && isWORDCHAR(*p)) {
p--;
}
p++;
/* Here, we have positioned ourselves to where we think the first
* character in the potential class is */
}
/* Now the interior really starts. There are certain key characters that
* can end the interior, or these could just be typos. To catch both
* cases, we may have to do two passes. In the first pass, we keep on
* going unless we come to a sequence that matches
* qr/ [[:punct:]] [[:blank:]]* \] /xa
* This means it takes a sequence to end the pass, so two typos in a row if
* that wasn't what was intended. If the class is perfectly formed, just
* this one pass is needed. We also stop if there are too many characters
* being accumulated, but this number is deliberately set higher than any
* real class. It is set high enough so that someone who thinks that
* 'alphanumeric' is a correct name would get warned that it wasn't.
* While doing the pass, we keep track of where the key characters were in
* it. If we don't find an end to the class, and one of the key characters
* was found, we redo the pass, but stop when we get to that character.
* Thus the key character was considered a typo in the first pass, but a
* terminator in the second. If two key characters are found, we stop at
* the second one in the first pass. Again this can miss two typos, but
* catches a single one
*
* In the first pass, 'possible_end' starts as NULL, and then gets set to
* point to the first key character. For the second pass, it starts as -1.
* */
name_start = p;
parse_name:
{
bool has_blank = FALSE;
bool has_upper = FALSE;
bool has_terminating_colon = FALSE;
bool has_terminating_bracket = FALSE;
bool has_semi_colon = FALSE;
unsigned int name_len = 0;
int punct_count = 0;
while (p < e) {
/* Squeeze out blanks when looking up the class name below */
if (isBLANK(*p) ) {
has_blank = TRUE;
found_problem = TRUE;
p++;
continue;
}
/* The name will end with a punctuation */
if (isPUNCT(*p)) {
const char * peek = p + 1;
/* Treat any non-']' punctuation followed by a ']' (possibly
* with intervening blanks) as trying to terminate the class.
* ']]' is very likely to mean a class was intended (but
* missing the colon), but the warning message that gets
* generated shows the error position better if we exit the
* loop at the bottom (eventually), so skip it here. */
if (*p != ']') {
if (peek < e && isBLANK(*peek)) {
has_blank = TRUE;
found_problem = TRUE;
do {
peek++;
} while (peek < e && isBLANK(*peek));
}
if (peek < e && *peek == ']') {
has_terminating_bracket = TRUE;
if (*p == ':') {
has_terminating_colon = TRUE;
}
else if (*p == ';') {
has_semi_colon = TRUE;
has_terminating_colon = TRUE;
}
else {
found_problem = TRUE;
}
p = peek + 1;
goto try_posix;
}
}
/* Here we have punctuation we thought didn't end the class.
* Keep track of the position of the key characters that are
* more likely to have been class-enders */
if (*p == ']' || *p == '[' || *p == ':' || *p == ';') {
/* Allow just one such possible class-ender not actually
* ending the class. */
if (possible_end) {
break;
}
possible_end = p;
}
/* If we have too many punctuation characters, no use in
* keeping going */
if (++punct_count > max_distance) {
break;
}
/* Treat the punctuation as a typo. */
input_text[name_len++] = *p;
p++;
}
else if (isUPPER(*p)) { /* Use lowercase for lookup */
input_text[name_len++] = toLOWER(*p);
has_upper = TRUE;
found_problem = TRUE;
p++;
} else if (! UTF || UTF8_IS_INVARIANT(*p)) {
input_text[name_len++] = *p;
p++;
}
else {
input_text[name_len++] = utf8_to_uvchr_buf((U8 *) p, e, NULL);
p+= UTF8SKIP(p);
}
/* The declaration of 'input_text' is how long we allow a potential
* class name to be, before saying they didn't mean a class name at
* all */
if (name_len >= C_ARRAY_LENGTH(input_text)) {
break;
}
}
/* We get to here when the possible class name hasn't been properly
* terminated before:
* 1) we ran off the end of the pattern; or
* 2) found two characters, each of which might have been intended to
* be the name's terminator
* 3) found so many punctuation characters in the purported name,
* that the edit distance to a valid one is exceeded
* 4) we decided it was more characters than anyone could have
* intended to be one. */
found_problem = TRUE;
/* In the final two cases, we know that looking up what we've
* accumulated won't lead to a match, even a fuzzy one. */
if ( name_len >= C_ARRAY_LENGTH(input_text)
|| punct_count > max_distance)
{
/* If there was an intermediate key character that could have been
* an intended end, redo the parse, but stop there */
if (possible_end && possible_end != (char *) -1) {
possible_end = (char *) -1; /* Special signal value to say
we've done a first pass */
p = name_start;
goto parse_name;
}
/* Otherwise, it can't have meant to have been a class */
CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
}
/* If we ran off the end, and the final character was a punctuation
* one, back up one, to look at that final one just below. Later, we
* will restore the parse pointer if appropriate */
if (name_len && p == e && isPUNCT(*(p-1))) {
p--;
name_len--;
}
if (p < e && isPUNCT(*p)) {
if (*p == ']') {
has_terminating_bracket = TRUE;
/* If this is a 2nd ']', and the first one is just below this
* one, consider that to be the real terminator. This gives a
* uniform and better positioning for the warning message */
if ( possible_end
&& possible_end != (char *) -1
&& *possible_end == ']'
&& name_len && input_text[name_len - 1] == ']')
{
name_len--;
p = possible_end;
/* And this is actually equivalent to having done the 2nd
* pass now, so set it to not try again */
possible_end = (char *) -1;
}
}
else {
if (*p == ':') {
has_terminating_colon = TRUE;
}
else if (*p == ';') {
has_semi_colon = TRUE;
has_terminating_colon = TRUE;
}
p++;
}
}
try_posix:
/* Here, we have a class name to look up. We can short circuit the
* stuff below for short names that can't possibly be meant to be a
* class name. (We can do this on the first pass, as any second pass
* will yield an even shorter name) */
if (name_len < 3) {
CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
}
/* Find which class it is. Initially switch on the length of the name.
* */
switch (name_len) {
case 4:
if (memEQs(name_start, 4, "word")) {
/* this is not POSIX, this is the Perl \w */
class_number = ANYOF_WORDCHAR;
}
break;
case 5:
/* Names all of length 5: alnum alpha ascii blank cntrl digit
* graph lower print punct space upper
* Offset 4 gives the best switch position. */
switch (name_start[4]) {
case 'a':
if (memBEGINs(name_start, 5, "alph")) /* alpha */
class_number = ANYOF_ALPHA;
break;
case 'e':
if (memBEGINs(name_start, 5, "spac")) /* space */
class_number = ANYOF_SPACE;
break;
case 'h':
if (memBEGINs(name_start, 5, "grap")) /* graph */
class_number = ANYOF_GRAPH;
break;
case 'i':
if (memBEGINs(name_start, 5, "asci")) /* ascii */
class_number = ANYOF_ASCII;
break;
case 'k':
if (memBEGINs(name_start, 5, "blan")) /* blank */
class_number = ANYOF_BLANK;
break;
case 'l':
if (memBEGINs(name_start, 5, "cntr")) /* cntrl */
class_number = ANYOF_CNTRL;
break;
case 'm':
if (memBEGINs(name_start, 5, "alnu")) /* alnum */
class_number = ANYOF_ALPHANUMERIC;
break;
case 'r':
if (memBEGINs(name_start, 5, "lowe")) /* lower */
class_number = (FOLD) ? ANYOF_CASED : ANYOF_LOWER;
else if (memBEGINs(name_start, 5, "uppe")) /* upper */
class_number = (FOLD) ? ANYOF_CASED : ANYOF_UPPER;
break;
case 't':
if (memBEGINs(name_start, 5, "digi")) /* digit */
class_number = ANYOF_DIGIT;
else if (memBEGINs(name_start, 5, "prin")) /* print */
class_number = ANYOF_PRINT;
else if (memBEGINs(name_start, 5, "punc")) /* punct */
class_number = ANYOF_PUNCT;
break;
}
break;
case 6:
if (memEQs(name_start, 6, "xdigit"))
class_number = ANYOF_XDIGIT;
break;
}
/* If the name exactly matches a posix class name the class number will
* here be set to it, and the input almost certainly was meant to be a
* posix class, so we can skip further checking. If instead the syntax
* is exactly correct, but the name isn't one of the legal ones, we
* will return that as an error below. But if neither of these apply,
* it could be that no posix class was intended at all, or that one
* was, but there was a typo. We tease these apart by doing fuzzy
* matching on the name */
if (class_number == OOB_NAMEDCLASS && found_problem) {
const UV posix_names[][6] = {
{ 'a', 'l', 'n', 'u', 'm' },
{ 'a', 'l', 'p', 'h', 'a' },
{ 'a', 's', 'c', 'i', 'i' },
{ 'b', 'l', 'a', 'n', 'k' },
{ 'c', 'n', 't', 'r', 'l' },
{ 'd', 'i', 'g', 'i', 't' },
{ 'g', 'r', 'a', 'p', 'h' },
{ 'l', 'o', 'w', 'e', 'r' },
{ 'p', 'r', 'i', 'n', 't' },
{ 'p', 'u', 'n', 'c', 't' },
{ 's', 'p', 'a', 'c', 'e' },
{ 'u', 'p', 'p', 'e', 'r' },
{ 'w', 'o', 'r', 'd' },
{ 'x', 'd', 'i', 'g', 'i', 't' }
};
/* The names of the above all have added NULs to make them the same
* size, so we need to also have the real lengths */
const UV posix_name_lengths[] = {
sizeof("alnum") - 1,
sizeof("alpha") - 1,
sizeof("ascii") - 1,
sizeof("blank") - 1,
sizeof("cntrl") - 1,
sizeof("digit") - 1,
sizeof("graph") - 1,
sizeof("lower") - 1,
sizeof("print") - 1,
sizeof("punct") - 1,
sizeof("space") - 1,
sizeof("upper") - 1,
sizeof("word") - 1,
sizeof("xdigit")- 1
};
unsigned int i;
int temp_max = max_distance; /* Use a temporary, so if we
reparse, we haven't changed the
outer one */
/* Use a smaller max edit distance if we are missing one of the
* delimiters */
if ( has_opening_bracket + has_opening_colon < 2
|| has_terminating_bracket + has_terminating_colon < 2)
{
temp_max--;
}
/* See if the input name is close to a legal one */
for (i = 0; i < C_ARRAY_LENGTH(posix_names); i++) {
/* Short circuit call if the lengths are too far apart to be
* able to match */
if (abs( (int) (name_len - posix_name_lengths[i]))
> temp_max)
{
continue;
}
if (edit_distance(input_text,
posix_names[i],
name_len,
posix_name_lengths[i],
temp_max
)
> -1)
{ /* If it is close, it probably was intended to be a class */
goto probably_meant_to_be;
}
}
/* Here the input name is not close enough to a valid class name
* for us to consider it to be intended to be a posix class. If
* we haven't already done so, and the parse found a character that
* could have been terminators for the name, but which we absorbed
* as typos during the first pass, repeat the parse, signalling it
* to stop at that character */
if (possible_end && possible_end != (char *) -1) {
possible_end = (char *) -1;
p = name_start;
goto parse_name;
}
/* Here neither pass found a close-enough class name */
CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
}
probably_meant_to_be:
/* Here we think that a posix specification was intended. Update any
* parse pointer */
if (updated_parse_ptr) {
*updated_parse_ptr = (char *) p;
}
/* If a posix class name was intended but incorrectly specified, we
* output or return the warnings */
if (found_problem) {
/* We set flags for these issues in the parse loop above instead of
* adding them to the list of warnings, because we can parse it
* twice, and we only want one warning instance */
if (has_upper) {
ADD_POSIX_WARNING(p, "the name must be all lowercase letters");
}
if (has_blank) {
ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
}
if (has_semi_colon) {
ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
}
else if (! has_terminating_colon) {
ADD_POSIX_WARNING(p, "there is no terminating ':'");
}
if (! has_terminating_bracket) {
ADD_POSIX_WARNING(p, "there is no terminating ']'");
}
if (posix_warnings && RExC_warn_text && av_top_index(RExC_warn_text) > -1) {
*posix_warnings = RExC_warn_text;
}
}
else if (class_number != OOB_NAMEDCLASS) {
/* If it is a known class, return the class. The class number
* #defines are structured so each complement is +1 to the normal
* one */
CLEAR_POSIX_WARNINGS_AND_RETURN(class_number + complement);
}
else if (! check_only) {
/* Here, it is an unrecognized class. This is an error (unless the
* call is to check only, which we've already handled above) */
const char * const complement_string = (complement)
? "^"
: "";
RExC_parse = (char *) p;
vFAIL3utf8f("POSIX class [:%s%" UTF8f ":] unknown",
complement_string,
UTF8fARG(UTF, RExC_parse - name_start - 2, name_start));
}
}
return OOB_NAMEDCLASS;
}
#undef ADD_POSIX_WARNING
STATIC unsigned int
S_regex_set_precedence(const U8 my_operator) {
/* Returns the precedence in the (?[...]) construct of the input operator,
* specified by its character representation. The precedence follows
* general Perl rules, but it extends this so that ')' and ']' have (low)
* precedence even though they aren't really operators */
switch (my_operator) {
case '!':
return 5;
case '&':
return 4;
case '^':
case '|':
case '+':
case '-':
return 3;
case ')':
return 2;
case ']':
return 1;
}
NOT_REACHED; /* NOTREACHED */
return 0; /* Silence compiler warning */
}
STATIC regnode *
S_handle_regex_sets(pTHX_ RExC_state_t *pRExC_state, SV** return_invlist,
I32 *flagp, U32 depth,
char * const oregcomp_parse)
{
/* Handle the (?[...]) construct to do set operations */
U8 curchar; /* Current character being parsed */
UV start, end; /* End points of code point ranges */
SV* final = NULL; /* The end result inversion list */
SV* result_string; /* 'final' stringified */
AV* stack; /* stack of operators and operands not yet
resolved */
AV* fence_stack = NULL; /* A stack containing the positions in
'stack' of where the undealt-with left
parens would be if they were actually
put there */
/* The 'volatile' is a workaround for an optimiser bug
* in Solaris Studio 12.3. See RT #127455 */
volatile IV fence = 0; /* Position of where most recent undealt-
with left paren in stack is; -1 if none.
*/
STRLEN len; /* Temporary */
regnode* node; /* Temporary, and final regnode returned by
this function */
const bool save_fold = FOLD; /* Temporary */
char *save_end, *save_parse; /* Temporaries */
const bool in_locale = LOC; /* we turn off /l during processing */
AV* posix_warnings = NULL;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_HANDLE_REGEX_SETS;
DEBUG_PARSE("xcls");
if (in_locale) {
set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
}
REQUIRE_UNI_RULES(flagp, NULL); /* The use of this operator implies /u.
This is required so that the compile
time values are valid in all runtime
cases */
/* This will return only an ANYOF regnode, or (unlikely) something smaller
* (such as EXACT). Thus we can skip most everything if just sizing. We
* call regclass to handle '[]' so as to not have to reinvent its parsing
* rules here (throwing away the size it computes each time). And, we exit
* upon an unescaped ']' that isn't one ending a regclass. To do both
* these things, we need to realize that something preceded by a backslash
* is escaped, so we have to keep track of backslashes */
if (SIZE_ONLY) {
UV nest_depth = 0; /* how many nested (?[...]) constructs */
while (RExC_parse < RExC_end) {
SV* current = NULL;
skip_to_be_ignored_text(pRExC_state, &RExC_parse,
TRUE /* Force /x */ );
switch (*RExC_parse) {
case '?':
if (RExC_parse[1] == '[') nest_depth++, RExC_parse++;
/* FALLTHROUGH */
default:
break;
case '\\':
/* Skip past this, so the next character gets skipped, after
* the switch */
RExC_parse++;
if (*RExC_parse == 'c') {
/* Skip the \cX notation for control characters */
RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
}
break;
case '[':
{
/* See if this is a [:posix:] class. */
bool is_posix_class = (OOB_NAMEDCLASS
< handle_possible_posix(pRExC_state,
RExC_parse + 1,
NULL,
NULL,
TRUE /* checking only */));
/* If it is a posix class, leave the parse pointer at the
* '[' to fool regclass() into thinking it is part of a
* '[[:posix:]]'. */
if (! is_posix_class) {
RExC_parse++;
}
/* regclass() can only return RESTART_PASS1 and NEED_UTF8
* if multi-char folds are allowed. */
if (!regclass(pRExC_state, flagp,depth+1,
is_posix_class, /* parse the whole char
class only if not a
posix class */
FALSE, /* don't allow multi-char folds */
TRUE, /* silence non-portable warnings. */
TRUE, /* strict */
FALSE, /* Require return to be an ANYOF */
¤t,
&posix_warnings
))
FAIL2("panic: regclass returned NULL to handle_sets, "
"flags=%#" UVxf, (UV) *flagp);
/* function call leaves parse pointing to the ']', except
* if we faked it */
if (is_posix_class) {
RExC_parse--;
}
SvREFCNT_dec(current); /* In case it returned something */
break;
}
case ']':
if (nest_depth--) break;
RExC_parse++;
if (*RExC_parse == ')') {
node = reganode(pRExC_state, ANYOF, 0);
RExC_size += ANYOF_SKIP;
nextchar(pRExC_state);
Set_Node_Length(node,
RExC_parse - oregcomp_parse + 1); /* MJD */
if (in_locale) {
set_regex_charset(&RExC_flags, REGEX_LOCALE_CHARSET);
}
return node;
}
goto no_close;
}
RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
}
no_close:
/* We output the messages even if warnings are off, because we'll fail
* the very next thing, and these give a likely diagnosis for that */
if (posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0) {
output_or_return_posix_warnings(pRExC_state, posix_warnings, NULL);
}
FAIL("Syntax error in (?[...])");
}
/* Pass 2 only after this. */
Perl_ck_warner_d(aTHX_
packWARN(WARN_EXPERIMENTAL__REGEX_SETS),
"The regex_sets feature is experimental" REPORT_LOCATION,
REPORT_LOCATION_ARGS(RExC_parse));
/* Everything in this construct is a metacharacter. Operands begin with
* either a '\' (for an escape sequence), or a '[' for a bracketed
* character class. Any other character should be an operator, or
* parenthesis for grouping. Both types of operands are handled by calling
* regclass() to parse them. It is called with a parameter to indicate to
* return the computed inversion list. The parsing here is implemented via
* a stack. Each entry on the stack is a single character representing one
* of the operators; or else a pointer to an operand inversion list. */
#define IS_OPERATOR(a) SvIOK(a)
#define IS_OPERAND(a) (! IS_OPERATOR(a))
/* The stack is kept in Łukasiewicz order. (That's pronounced similar
* to luke-a-shave-itch (or -itz), but people who didn't want to bother
* with pronouncing it called it Reverse Polish instead, but now that YOU
* know how to pronounce it you can use the correct term, thus giving due
* credit to the person who invented it, and impressing your geek friends.
* Wikipedia says that the pronounciation of "Ł" has been changing so that
* it is now more like an English initial W (as in wonk) than an L.)
*
* This means that, for example, 'a | b & c' is stored on the stack as
*
* c [4]
* b [3]
* & [2]
* a [1]
* | [0]
*
* where the numbers in brackets give the stack [array] element number.
* In this implementation, parentheses are not stored on the stack.
* Instead a '(' creates a "fence" so that the part of the stack below the
* fence is invisible except to the corresponding ')' (this allows us to
* replace testing for parens, by using instead subtraction of the fence
* position). As new operands are processed they are pushed onto the stack
* (except as noted in the next paragraph). New operators of higher
* precedence than the current final one are inserted on the stack before
* the lhs operand (so that when the rhs is pushed next, everything will be
* in the correct positions shown above. When an operator of equal or
* lower precedence is encountered in parsing, all the stacked operations
* of equal or higher precedence are evaluated, leaving the result as the
* top entry on the stack. This makes higher precedence operations
* evaluate before lower precedence ones, and causes operations of equal
* precedence to left associate.
*
* The only unary operator '!' is immediately pushed onto the stack when
* encountered. When an operand is encountered, if the top of the stack is
* a '!", the complement is immediately performed, and the '!' popped. The
* resulting value is treated as a new operand, and the logic in the
* previous paragraph is executed. Thus in the expression
* [a] + ! [b]
* the stack looks like
*
* !
* a
* +
*
* as 'b' gets parsed, the latter gets evaluated to '!b', and the stack
* becomes
*
* !b
* a
* +
*
* A ')' is treated as an operator with lower precedence than all the
* aforementioned ones, which causes all operations on the stack above the
* corresponding '(' to be evaluated down to a single resultant operand.
* Then the fence for the '(' is removed, and the operand goes through the
* algorithm above, without the fence.
*
* A separate stack is kept of the fence positions, so that the position of
* the latest so-far unbalanced '(' is at the top of it.
*
* The ']' ending the construct is treated as the lowest operator of all,
* so that everything gets evaluated down to a single operand, which is the
* result */
sv_2mortal((SV *)(stack = newAV()));
sv_2mortal((SV *)(fence_stack = newAV()));
while (RExC_parse < RExC_end) {
I32 top_index; /* Index of top-most element in 'stack' */
SV** top_ptr; /* Pointer to top 'stack' element */
SV* current = NULL; /* To contain the current inversion list
operand */
SV* only_to_avoid_leaks;
skip_to_be_ignored_text(pRExC_state, &RExC_parse,
TRUE /* Force /x */ );
if (RExC_parse >= RExC_end) {
Perl_croak(aTHX_ "panic: Read past end of '(?[ ])'");
}
curchar = UCHARAT(RExC_parse);
redo_curchar:
#ifdef ENABLE_REGEX_SETS_DEBUGGING
/* Enable with -Accflags=-DENABLE_REGEX_SETS_DEBUGGING */
DEBUG_U(dump_regex_sets_structures(pRExC_state,
stack, fence, fence_stack));
#endif
top_index = av_tindex_skip_len_mg(stack);
switch (curchar) {
SV** stacked_ptr; /* Ptr to something already on 'stack' */
char stacked_operator; /* The topmost operator on the 'stack'. */
SV* lhs; /* Operand to the left of the operator */
SV* rhs; /* Operand to the right of the operator */
SV* fence_ptr; /* Pointer to top element of the fence
stack */
case '(':
if ( RExC_parse < RExC_end - 1
&& (UCHARAT(RExC_parse + 1) == '?'))
{
/* If is a '(?', could be an embedded '(?flags:(?[...])'.
* This happens when we have some thing like
*
* my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/;
* ...
* qr/(?[ \p{Digit} & $thai_or_lao ])/;
*
* Here we would be handling the interpolated
* '$thai_or_lao'. We handle this by a recursive call to
* ourselves which returns the inversion list the
* interpolated expression evaluates to. We use the flags
* from the interpolated pattern. */
U32 save_flags = RExC_flags;
const char * save_parse;
RExC_parse += 2; /* Skip past the '(?' */
save_parse = RExC_parse;
/* Parse any flags for the '(?' */
parse_lparen_question_flags(pRExC_state);
if (RExC_parse == save_parse /* Makes sure there was at
least one flag (or else
this embedding wasn't
compiled) */
|| RExC_parse >= RExC_end - 4
|| UCHARAT(RExC_parse) != ':'
|| UCHARAT(++RExC_parse) != '('
|| UCHARAT(++RExC_parse) != '?'
|| UCHARAT(++RExC_parse) != '[')
{
/* In combination with the above, this moves the
* pointer to the point just after the first erroneous
* character (or if there are no flags, to where they
* should have been) */
if (RExC_parse >= RExC_end - 4) {
RExC_parse = RExC_end;
}
else if (RExC_parse != save_parse) {
RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
}
vFAIL("Expecting '(?flags:(?[...'");
}
/* Recurse, with the meat of the embedded expression */
RExC_parse++;
(void) handle_regex_sets(pRExC_state, ¤t, flagp,
depth+1, oregcomp_parse);
/* Here, 'current' contains the embedded expression's
* inversion list, and RExC_parse points to the trailing
* ']'; the next character should be the ')' */
RExC_parse++;
assert(UCHARAT(RExC_parse) == ')');
/* Then the ')' matching the original '(' handled by this
* case: statement */
RExC_parse++;
assert(UCHARAT(RExC_parse) == ')');
RExC_parse++;
RExC_flags = save_flags;
goto handle_operand;
}
/* A regular '('. Look behind for illegal syntax */
if (top_index - fence >= 0) {
/* If the top entry on the stack is an operator, it had
* better be a '!', otherwise the entry below the top
* operand should be an operator */
if ( ! (top_ptr = av_fetch(stack, top_index, FALSE))
|| (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) != '!')
|| ( IS_OPERAND(*top_ptr)
&& ( top_index - fence < 1
|| ! (stacked_ptr = av_fetch(stack,
top_index - 1,
FALSE))
|| ! IS_OPERATOR(*stacked_ptr))))
{
RExC_parse++;
vFAIL("Unexpected '(' with no preceding operator");
}
}
/* Stack the position of this undealt-with left paren */
av_push(fence_stack, newSViv(fence));
fence = top_index + 1;
break;
case '\\':
/* regclass() can only return RESTART_PASS1 and NEED_UTF8 if
* multi-char folds are allowed. */
if (!regclass(pRExC_state, flagp,depth+1,
TRUE, /* means parse just the next thing */
FALSE, /* don't allow multi-char folds */
FALSE, /* don't silence non-portable warnings. */
TRUE, /* strict */
FALSE, /* Require return to be an ANYOF */
¤t,
NULL))
{
FAIL2("panic: regclass returned NULL to handle_sets, "
"flags=%#" UVxf, (UV) *flagp);
}
/* regclass() will return with parsing just the \ sequence,
* leaving the parse pointer at the next thing to parse */
RExC_parse--;
goto handle_operand;
case '[': /* Is a bracketed character class */
{
/* See if this is a [:posix:] class. */
bool is_posix_class = (OOB_NAMEDCLASS
< handle_possible_posix(pRExC_state,
RExC_parse + 1,
NULL,
NULL,
TRUE /* checking only */));
/* If it is a posix class, leave the parse pointer at the '['
* to fool regclass() into thinking it is part of a
* '[[:posix:]]'. */
if (! is_posix_class) {
RExC_parse++;
}
/* regclass() can only return RESTART_PASS1 and NEED_UTF8 if
* multi-char folds are allowed. */
if (!regclass(pRExC_state, flagp,depth+1,
is_posix_class, /* parse the whole char
class only if not a
posix class */
FALSE, /* don't allow multi-char folds */
TRUE, /* silence non-portable warnings. */
TRUE, /* strict */
FALSE, /* Require return to be an ANYOF */
¤t,
NULL
))
{
FAIL2("panic: regclass returned NULL to handle_sets, "
"flags=%#" UVxf, (UV) *flagp);
}
/* function call leaves parse pointing to the ']', except if we
* faked it */
if (is_posix_class) {
RExC_parse--;
}
goto handle_operand;
}
case ']':
if (top_index >= 1) {
goto join_operators;
}
/* Only a single operand on the stack: are done */
goto done;
case ')':
if (av_tindex_skip_len_mg(fence_stack) < 0) {
RExC_parse++;
vFAIL("Unexpected ')'");
}
/* If nothing after the fence, is missing an operand */
if (top_index - fence < 0) {
RExC_parse++;
goto bad_syntax;
}
/* If at least two things on the stack, treat this as an
* operator */
if (top_index - fence >= 1) {
goto join_operators;
}
/* Here only a single thing on the fenced stack, and there is a
* fence. Get rid of it */
fence_ptr = av_pop(fence_stack);
assert(fence_ptr);
fence = SvIV(fence_ptr) - 1;
SvREFCNT_dec_NN(fence_ptr);
fence_ptr = NULL;
if (fence < 0) {
fence = 0;
}
/* Having gotten rid of the fence, we pop the operand at the
* stack top and process it as a newly encountered operand */
current = av_pop(stack);
if (IS_OPERAND(current)) {
goto handle_operand;
}
RExC_parse++;
goto bad_syntax;
case '&':
case '|':
case '+':
case '-':
case '^':
/* These binary operators should have a left operand already
* parsed */
if ( top_index - fence < 0
|| top_index - fence == 1
|| ( ! (top_ptr = av_fetch(stack, top_index, FALSE)))
|| ! IS_OPERAND(*top_ptr))
{
goto unexpected_binary;
}
/* If only the one operand is on the part of the stack visible
* to us, we just place this operator in the proper position */
if (top_index - fence < 2) {
/* Place the operator before the operand */
SV* lhs = av_pop(stack);
av_push(stack, newSVuv(curchar));
av_push(stack, lhs);
break;
}
/* But if there is something else on the stack, we need to
* process it before this new operator if and only if the
* stacked operation has equal or higher precedence than the
* new one */
join_operators:
/* The operator on the stack is supposed to be below both its
* operands */
if ( ! (stacked_ptr = av_fetch(stack, top_index - 2, FALSE))
|| IS_OPERAND(*stacked_ptr))
{
/* But if not, it's legal and indicates we are completely
* done if and only if we're currently processing a ']',
* which should be the final thing in the expression */
if (curchar == ']') {
goto done;
}
unexpected_binary:
RExC_parse++;
vFAIL2("Unexpected binary operator '%c' with no "
"preceding operand", curchar);
}
stacked_operator = (char) SvUV(*stacked_ptr);
if (regex_set_precedence(curchar)
> regex_set_precedence(stacked_operator))
{
/* Here, the new operator has higher precedence than the
* stacked one. This means we need to add the new one to
* the stack to await its rhs operand (and maybe more
* stuff). We put it before the lhs operand, leaving
* untouched the stacked operator and everything below it
* */
lhs = av_pop(stack);
assert(IS_OPERAND(lhs));
av_push(stack, newSVuv(curchar));
av_push(stack, lhs);
break;
}
/* Here, the new operator has equal or lower precedence than
* what's already there. This means the operation already
* there should be performed now, before the new one. */
rhs = av_pop(stack);
if (! IS_OPERAND(rhs)) {
/* This can happen when a ! is not followed by an operand,
* like in /(?[\t &!])/ */
goto bad_syntax;
}
lhs = av_pop(stack);
if (! IS_OPERAND(lhs)) {
/* This can happen when there is an empty (), like in
* /(?[[0]+()+])/ */
goto bad_syntax;
}
switch (stacked_operator) {
case '&':
_invlist_intersection(lhs, rhs, &rhs);
break;
case '|':
case '+':
_invlist_union(lhs, rhs, &rhs);
break;
case '-':
_invlist_subtract(lhs, rhs, &rhs);
break;
case '^': /* The union minus the intersection */
{
SV* i = NULL;
SV* u = NULL;
_invlist_union(lhs, rhs, &u);
_invlist_intersection(lhs, rhs, &i);
_invlist_subtract(u, i, &rhs);
SvREFCNT_dec_NN(i);
SvREFCNT_dec_NN(u);
break;
}
}
SvREFCNT_dec(lhs);
/* Here, the higher precedence operation has been done, and the
* result is in 'rhs'. We overwrite the stacked operator with
* the result. Then we redo this code to either push the new
* operator onto the stack or perform any higher precedence
* stacked operation */
only_to_avoid_leaks = av_pop(stack);
SvREFCNT_dec(only_to_avoid_leaks);
av_push(stack, rhs);
goto redo_curchar;
case '!': /* Highest priority, right associative */
/* If what's already at the top of the stack is another '!",
* they just cancel each other out */
if ( (top_ptr = av_fetch(stack, top_index, FALSE))
&& (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) == '!'))
{
only_to_avoid_leaks = av_pop(stack);
SvREFCNT_dec(only_to_avoid_leaks);
}
else { /* Otherwise, since it's right associative, just push
onto the stack */
av_push(stack, newSVuv(curchar));
}
break;
default:
RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
vFAIL("Unexpected character");
handle_operand:
/* Here 'current' is the operand. If something is already on the
* stack, we have to check if it is a !. But first, the code above
* may have altered the stack in the time since we earlier set
* 'top_index'. */
top_index = av_tindex_skip_len_mg(stack);
if (top_index - fence >= 0) {
/* If the top entry on the stack is an operator, it had better
* be a '!', otherwise the entry below the top operand should
* be an operator */
top_ptr = av_fetch(stack, top_index, FALSE);
assert(top_ptr);
if (IS_OPERATOR(*top_ptr)) {
/* The only permissible operator at the top of the stack is
* '!', which is applied immediately to this operand. */
curchar = (char) SvUV(*top_ptr);
if (curchar != '!') {
SvREFCNT_dec(current);
vFAIL2("Unexpected binary operator '%c' with no "
"preceding operand", curchar);
}
_invlist_invert(current);
only_to_avoid_leaks = av_pop(stack);
SvREFCNT_dec(only_to_avoid_leaks);
/* And we redo with the inverted operand. This allows
* handling multiple ! in a row */
goto handle_operand;
}
/* Single operand is ok only for the non-binary ')'
* operator */
else if ((top_index - fence == 0 && curchar != ')')
|| (top_index - fence > 0
&& (! (stacked_ptr = av_fetch(stack,
top_index - 1,
FALSE))
|| IS_OPERAND(*stacked_ptr))))
{
SvREFCNT_dec(current);
vFAIL("Operand with no preceding operator");
}
}
/* Here there was nothing on the stack or the top element was
* another operand. Just add this new one */
av_push(stack, current);
} /* End of switch on next parse token */
RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
} /* End of loop parsing through the construct */
done:
if (av_tindex_skip_len_mg(fence_stack) >= 0) {
vFAIL("Unmatched (");
}
if (av_tindex_skip_len_mg(stack) < 0 /* Was empty */
|| ((final = av_pop(stack)) == NULL)
|| ! IS_OPERAND(final)
|| SvTYPE(final) != SVt_INVLIST
|| av_tindex_skip_len_mg(stack) >= 0) /* More left on stack */
{
bad_syntax:
SvREFCNT_dec(final);
vFAIL("Incomplete expression within '(?[ ])'");
}
/* Here, 'final' is the resultant inversion list from evaluating the
* expression. Return it if so requested */
if (return_invlist) {
*return_invlist = final;
return END;
}
/* Otherwise generate a resultant node, based on 'final'. regclass() is
* expecting a string of ranges and individual code points */
invlist_iterinit(final);
result_string = newSVpvs("");
while (invlist_iternext(final, &start, &end)) {
if (start == end) {
Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}", start);
}
else {
Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}-\\x{%" UVXf "}",
start, end);
}
}
/* About to generate an ANYOF (or similar) node from the inversion list we
* have calculated */
save_parse = RExC_parse;
RExC_parse = SvPV(result_string, len);
save_end = RExC_end;
RExC_end = RExC_parse + len;
/* We turn off folding around the call, as the class we have constructed
* already has all folding taken into consideration, and we don't want
* regclass() to add to that */
RExC_flags &= ~RXf_PMf_FOLD;
/* regclass() can only return RESTART_PASS1 and NEED_UTF8 if multi-char
* folds are allowed. */
node = regclass(pRExC_state, flagp,depth+1,
FALSE, /* means parse the whole char class */
FALSE, /* don't allow multi-char folds */
TRUE, /* silence non-portable warnings. The above may very
well have generated non-portable code points, but
they're valid on this machine */
FALSE, /* similarly, no need for strict */
FALSE, /* Require return to be an ANYOF */
NULL,
NULL
);
if (!node)
FAIL2("panic: regclass returned NULL to handle_sets, flags=%#" UVxf,
PTR2UV(flagp));
/* Fix up the node type if we are in locale. (We have pretended we are
* under /u for the purposes of regclass(), as this construct will only
* work under UTF-8 locales. But now we change the opcode to be ANYOFL (so
* as to cause any warnings about bad locales to be output in regexec.c),
* and add the flag that indicates to check if not in a UTF-8 locale. The
* reason we above forbid optimization into something other than an ANYOF
* node is simply to minimize the number of code changes in regexec.c.
* Otherwise we would have to create new EXACTish node types and deal with
* them. This decision could be revisited should this construct become
* popular.
*
* (One might think we could look at the resulting ANYOF node and suppress
* the flag if everything is above 255, as those would be UTF-8 only,
* but this isn't true, as the components that led to that result could
* have been locale-affected, and just happen to cancel each other out
* under UTF-8 locales.) */
if (in_locale) {
set_regex_charset(&RExC_flags, REGEX_LOCALE_CHARSET);
assert(OP(node) == ANYOF);
OP(node) = ANYOFL;
ANYOF_FLAGS(node)
|= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
}
if (save_fold) {
RExC_flags |= RXf_PMf_FOLD;
}
RExC_parse = save_parse + 1;
RExC_end = save_end;
SvREFCNT_dec_NN(final);
SvREFCNT_dec_NN(result_string);
nextchar(pRExC_state);
Set_Node_Length(node, RExC_parse - oregcomp_parse + 1); /* MJD */
return node;
}
#ifdef ENABLE_REGEX_SETS_DEBUGGING
STATIC void
S_dump_regex_sets_structures(pTHX_ RExC_state_t *pRExC_state,
AV * stack, const IV fence, AV * fence_stack)
{ /* Dumps the stacks in handle_regex_sets() */
const SSize_t stack_top = av_tindex_skip_len_mg(stack);
const SSize_t fence_stack_top = av_tindex_skip_len_mg(fence_stack);
SSize_t i;
PERL_ARGS_ASSERT_DUMP_REGEX_SETS_STRUCTURES;
PerlIO_printf(Perl_debug_log, "\nParse position is:%s\n", RExC_parse);
if (stack_top < 0) {
PerlIO_printf(Perl_debug_log, "Nothing on stack\n");
}
else {
PerlIO_printf(Perl_debug_log, "Stack: (fence=%d)\n", (int) fence);
for (i = stack_top; i >= 0; i--) {
SV ** element_ptr = av_fetch(stack, i, FALSE);
if (! element_ptr) {
}
if (IS_OPERATOR(*element_ptr)) {
PerlIO_printf(Perl_debug_log, "[%d]: %c\n",
(int) i, (int) SvIV(*element_ptr));
}
else {
PerlIO_printf(Perl_debug_log, "[%d] ", (int) i);
sv_dump(*element_ptr);
}
}
}
if (fence_stack_top < 0) {
PerlIO_printf(Perl_debug_log, "Nothing on fence_stack\n");
}
else {
PerlIO_printf(Perl_debug_log, "Fence_stack: \n");
for (i = fence_stack_top; i >= 0; i--) {
SV ** element_ptr = av_fetch(fence_stack, i, FALSE);
if (! element_ptr) {
}
PerlIO_printf(Perl_debug_log, "[%d]: %d\n",
(int) i, (int) SvIV(*element_ptr));
}
}
}
#endif
#undef IS_OPERATOR
#undef IS_OPERAND
STATIC void
S_add_above_Latin1_folds(pTHX_ RExC_state_t *pRExC_state, const U8 cp, SV** invlist)
{
/* This hard-codes the Latin1/above-Latin1 folding rules, so that an
* innocent-looking character class, like /[ks]/i won't have to go out to
* disk to find the possible matches.
*
* This should be called only for a Latin1-range code points, cp, which is
* known to be involved in a simple fold with other code points above
* Latin1. It would give false results if /aa has been specified.
* Multi-char folds are outside the scope of this, and must be handled
* specially.
*
* XXX It would be better to generate these via regen, in case a new
* version of the Unicode standard adds new mappings, though that is not
* really likely, and may be caught by the default: case of the switch
* below. */
PERL_ARGS_ASSERT_ADD_ABOVE_LATIN1_FOLDS;
assert(HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(cp));
switch (cp) {
case 'k':
case 'K':
*invlist =
add_cp_to_invlist(*invlist, KELVIN_SIGN);
break;
case 's':
case 'S':
*invlist = add_cp_to_invlist(*invlist, LATIN_SMALL_LETTER_LONG_S);
break;
case MICRO_SIGN:
*invlist = add_cp_to_invlist(*invlist, GREEK_CAPITAL_LETTER_MU);
*invlist = add_cp_to_invlist(*invlist, GREEK_SMALL_LETTER_MU);
break;
case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE:
case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE:
*invlist = add_cp_to_invlist(*invlist, ANGSTROM_SIGN);
break;
case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
*invlist = add_cp_to_invlist(*invlist,
LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);
break;
#ifdef LATIN_CAPITAL_LETTER_SHARP_S /* not defined in early Unicode releases */
case LATIN_SMALL_LETTER_SHARP_S:
*invlist = add_cp_to_invlist(*invlist, LATIN_CAPITAL_LETTER_SHARP_S);
break;
#endif
#if UNICODE_MAJOR_VERSION < 3 \
|| (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0)
/* In 3.0 and earlier, U+0130 folded simply to 'i'; and in 3.0.1 so did
* U+0131. */
case 'i':
case 'I':
*invlist =
add_cp_to_invlist(*invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
# if UNICODE_DOT_DOT_VERSION == 1
*invlist = add_cp_to_invlist(*invlist, LATIN_SMALL_LETTER_DOTLESS_I);
# endif
break;
#endif
default:
/* Use deprecated warning to increase the chances of this being
* output */
if (PASS2) {
ckWARN2reg_d(RExC_parse, "Perl folding rules are not up-to-date for 0x%02X; please use the perlbug utility to report;", cp);
}
break;
}
}
STATIC void
S_output_or_return_posix_warnings(pTHX_ RExC_state_t *pRExC_state, AV* posix_warnings, AV** return_posix_warnings)
{
/* If the final parameter is NULL, output the elements of the array given
* by '*posix_warnings' as REGEXP warnings. Otherwise, the elements are
* pushed onto it, (creating if necessary) */
SV * msg;
const bool first_is_fatal = ! return_posix_warnings
&& ckDEAD(packWARN(WARN_REGEXP));
PERL_ARGS_ASSERT_OUTPUT_OR_RETURN_POSIX_WARNINGS;
while ((msg = av_shift(posix_warnings)) != &PL_sv_undef) {
if (return_posix_warnings) {
if (! *return_posix_warnings) { /* mortalize to not leak if
warnings are fatal */
*return_posix_warnings = (AV *) sv_2mortal((SV *) newAV());
}
av_push(*return_posix_warnings, msg);
}
else {
if (first_is_fatal) { /* Avoid leaking this */
av_undef(posix_warnings); /* This isn't necessary if the
array is mortal, but is a
fail-safe */
(void) sv_2mortal(msg);
if (PASS2) {
SAVEFREESV(RExC_rx_sv);
}
}
Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s", SvPVX(msg));
SvREFCNT_dec_NN(msg);
}
}
}
STATIC AV *
S_add_multi_match(pTHX_ AV* multi_char_matches, SV* multi_string, const STRLEN cp_count)
{
/* This adds the string scalar <multi_string> to the array
* <multi_char_matches>. <multi_string> is known to have exactly
* <cp_count> code points in it. This is used when constructing a
* bracketed character class and we find something that needs to match more
* than a single character.
*
* <multi_char_matches> is actually an array of arrays. Each top-level
* element is an array that contains all the strings known so far that are
* the same length. And that length (in number of code points) is the same
* as the index of the top-level array. Hence, the [2] element is an
* array, each element thereof is a string containing TWO code points;
* while element [3] is for strings of THREE characters, and so on. Since
* this is for multi-char strings there can never be a [0] nor [1] element.
*
* When we rewrite the character class below, we will do so such that the
* longest strings are written first, so that it prefers the longest
* matching strings first. This is done even if it turns out that any
* quantifier is non-greedy, out of this programmer's (khw) laziness. Tom
* Christiansen has agreed that this is ok. This makes the test for the
* ligature 'ffi' come before the test for 'ff', for example */
AV* this_array;
AV** this_array_ptr;
PERL_ARGS_ASSERT_ADD_MULTI_MATCH;
if (! multi_char_matches) {
multi_char_matches = newAV();
}
if (av_exists(multi_char_matches, cp_count)) {
this_array_ptr = (AV**) av_fetch(multi_char_matches, cp_count, FALSE);
this_array = *this_array_ptr;
}
else {
this_array = newAV();
av_store(multi_char_matches, cp_count,
(SV*) this_array);
}
av_push(this_array, multi_string);
return multi_char_matches;
}
/* The names of properties whose definitions are not known at compile time are
* stored in this SV, after a constant heading. So if the length has been
* changed since initialization, then there is a run-time definition. */
#define HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION \
(SvCUR(listsv) != initial_listsv_len)
/* There is a restricted set of white space characters that are legal when
* ignoring white space in a bracketed character class. This generates the
* code to skip them.
*
* There is a line below that uses the same white space criteria but is outside
* this macro. Both here and there must use the same definition */
#define SKIP_BRACKETED_WHITE_SPACE(do_skip, p) \
STMT_START { \
if (do_skip) { \
while (isBLANK_A(UCHARAT(p))) \
{ \
p++; \
} \
} \
} STMT_END
STATIC regnode *
S_regclass(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth,
const bool stop_at_1, /* Just parse the next thing, don't
look for a full character class */
bool allow_multi_folds,
const bool silence_non_portable, /* Don't output warnings
about too large
characters */
const bool strict,
bool optimizable, /* ? Allow a non-ANYOF return
node */
SV** ret_invlist, /* Return an inversion list, not a node */
AV** return_posix_warnings
)
{
/* parse a bracketed class specification. Most of these will produce an
* ANYOF node; but something like [a] will produce an EXACT node; [aA], an
* EXACTFish node; [[:ascii:]], a POSIXA node; etc. It is more complex
* under /i with multi-character folds: it will be rewritten following the
* paradigm of this example, where the <multi-fold>s are characters which
* fold to multiple character sequences:
* /[abc\x{multi-fold1}def\x{multi-fold2}ghi]/i
* gets effectively rewritten as:
* /(?:\x{multi-fold1}|\x{multi-fold2}|[abcdefghi]/i
* reg() gets called (recursively) on the rewritten version, and this
* function will return what it constructs. (Actually the <multi-fold>s
* aren't physically removed from the [abcdefghi], it's just that they are
* ignored in the recursion by means of a flag:
* <RExC_in_multi_char_class>.)
*
* ANYOF nodes contain a bit map for the first NUM_ANYOF_CODE_POINTS
* characters, with the corresponding bit set if that character is in the
* list. For characters above this, a range list or swash is used. There
* are extra bits for \w, etc. in locale ANYOFs, as what these match is not
* determinable at compile time
*
* Returns NULL, setting *flagp to RESTART_PASS1 if the sizing scan needs
* to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded
* to UTF-8. This can only happen if ret_invlist is non-NULL.
*/
UV prevvalue = OOB_UNICODE, save_prevvalue = OOB_UNICODE;
IV range = 0;
UV value = OOB_UNICODE, save_value = OOB_UNICODE;
regnode *ret;
STRLEN numlen;
int namedclass = OOB_NAMEDCLASS;
char *rangebegin = NULL;
bool need_class = 0;
SV *listsv = NULL;
STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more
than just initialized. */
SV* properties = NULL; /* Code points that match \p{} \P{} */
SV* posixes = NULL; /* Code points that match classes like [:word:],
extended beyond the Latin1 range. These have to
be kept separate from other code points for much
of this function because their handling is
different under /i, and for most classes under
/d as well */
SV* nposixes = NULL; /* Similarly for [:^word:]. These are kept
separate for a while from the non-complemented
versions because of complications with /d
matching */
SV* simple_posixes = NULL; /* But under some conditions, the classes can be
treated more simply than the general case,
leading to less compilation and execution
work */
UV element_count = 0; /* Number of distinct elements in the class.
Optimizations may be possible if this is tiny */
AV * multi_char_matches = NULL; /* Code points that fold to more than one
character; used under /i */
UV n;
char * stop_ptr = RExC_end; /* where to stop parsing */
/* ignore unescaped whitespace? */
const bool skip_white = cBOOL( ret_invlist
|| (RExC_flags & RXf_PMf_EXTENDED_MORE));
/* Unicode properties are stored in a swash; this holds the current one
* being parsed. If this swash is the only above-latin1 component of the
* character class, an optimization is to pass it directly on to the
* execution engine. Otherwise, it is set to NULL to indicate that there
* are other things in the class that have to be dealt with at execution
* time */
SV* swash = NULL; /* Code points that match \p{} \P{} */
/* Set if a component of this character class is user-defined; just passed
* on to the engine */
bool has_user_defined_property = FALSE;
/* inversion list of code points this node matches only when the target
* string is in UTF-8. These are all non-ASCII, < 256. (Because is under
* /d) */
SV* has_upper_latin1_only_utf8_matches = NULL;
/* Inversion list of code points this node matches regardless of things
* like locale, folding, utf8ness of the target string */
SV* cp_list = NULL;
/* Like cp_list, but code points on this list need to be checked for things
* that fold to/from them under /i */
SV* cp_foldable_list = NULL;
/* Like cp_list, but code points on this list are valid only when the
* runtime locale is UTF-8 */
SV* only_utf8_locale_list = NULL;
/* In a range, if one of the endpoints is non-character-set portable,
* meaning that it hard-codes a code point that may mean a different
* charactger in ASCII vs. EBCDIC, as opposed to, say, a literal 'A' or a
* mnemonic '\t' which each mean the same character no matter which
* character set the platform is on. */
unsigned int non_portable_endpoint = 0;
/* Is the range unicode? which means on a platform that isn't 1-1 native
* to Unicode (i.e. non-ASCII), each code point in it should be considered
* to be a Unicode value. */
bool unicode_range = FALSE;
bool invert = FALSE; /* Is this class to be complemented */
bool warn_super = ALWAYS_WARN_SUPER;
regnode * const orig_emit = RExC_emit; /* Save the original RExC_emit in
case we need to change the emitted regop to an EXACT. */
const char * orig_parse = RExC_parse;
const SSize_t orig_size = RExC_size;
bool posixl_matches_all = FALSE; /* Does /l class have both e.g. \W,\w ? */
/* This variable is used to mark where the end in the input is of something
* that looks like a POSIX construct but isn't. During the parse, when
* something looks like it could be such a construct is encountered, it is
* checked for being one, but not if we've already checked this area of the
* input. Only after this position is reached do we check again */
char *not_posix_region_end = RExC_parse - 1;
AV* posix_warnings = NULL;
const bool do_posix_warnings = return_posix_warnings
|| (PASS2 && ckWARN(WARN_REGEXP));
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGCLASS;
#ifndef DEBUGGING
PERL_UNUSED_ARG(depth);
#endif
DEBUG_PARSE("clas");
#if UNICODE_MAJOR_VERSION < 3 /* no multifolds in early Unicode */ \
|| (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0 \
&& UNICODE_DOT_DOT_VERSION == 0)
allow_multi_folds = FALSE;
#endif
/* Assume we are going to generate an ANYOF node. */
ret = reganode(pRExC_state,
(LOC)
? ANYOFL
: ANYOF,
0);
if (SIZE_ONLY) {
RExC_size += ANYOF_SKIP;
listsv = &PL_sv_undef; /* For code scanners: listsv always non-NULL. */
}
else {
ANYOF_FLAGS(ret) = 0;
RExC_emit += ANYOF_SKIP;
listsv = newSVpvs_flags("# comment\n", SVs_TEMP);
initial_listsv_len = SvCUR(listsv);
SvTEMP_off(listsv); /* Grr, TEMPs and mortals are conflated. */
}
SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
assert(RExC_parse <= RExC_end);
if (UCHARAT(RExC_parse) == '^') { /* Complement the class */
RExC_parse++;
invert = TRUE;
allow_multi_folds = FALSE;
MARK_NAUGHTY(1);
SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
}
/* Check that they didn't say [:posix:] instead of [[:posix:]] */
if (! ret_invlist && MAYBE_POSIXCC(UCHARAT(RExC_parse))) {
int maybe_class = handle_possible_posix(pRExC_state,
RExC_parse,
¬_posix_region_end,
NULL,
TRUE /* checking only */);
if (PASS2 && maybe_class >= OOB_NAMEDCLASS && do_posix_warnings) {
SAVEFREESV(RExC_rx_sv);
ckWARN4reg(not_posix_region_end,
"POSIX syntax [%c %c] belongs inside character classes%s",
*RExC_parse, *RExC_parse,
(maybe_class == OOB_NAMEDCLASS)
? ((POSIXCC_NOTYET(*RExC_parse))
? " (but this one isn't implemented)"
: " (but this one isn't fully valid)")
: ""
);
(void)ReREFCNT_inc(RExC_rx_sv);
}
}
/* If the caller wants us to just parse a single element, accomplish this
* by faking the loop ending condition */
if (stop_at_1 && RExC_end > RExC_parse) {
stop_ptr = RExC_parse + 1;
}
/* allow 1st char to be ']' (allowing it to be '-' is dealt with later) */
if (UCHARAT(RExC_parse) == ']')
goto charclassloop;
while (1) {
if ( posix_warnings
&& av_tindex_skip_len_mg(posix_warnings) >= 0
&& RExC_parse > not_posix_region_end)
{
/* Warnings about posix class issues are considered tentative until
* we are far enough along in the parse that we can no longer
* change our mind, at which point we either output them or add
* them, if it has so specified, to what gets returned to the
* caller. This is done each time through the loop so that a later
* class won't zap them before they have been dealt with. */
output_or_return_posix_warnings(pRExC_state, posix_warnings,
return_posix_warnings);
}
if (RExC_parse >= stop_ptr) {
break;
}
SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
if (UCHARAT(RExC_parse) == ']') {
break;
}
charclassloop:
namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
save_value = value;
save_prevvalue = prevvalue;
if (!range) {
rangebegin = RExC_parse;
element_count++;
non_portable_endpoint = 0;
}
if (UTF && ! UTF8_IS_INVARIANT(* RExC_parse)) {
value = utf8n_to_uvchr((U8*)RExC_parse,
RExC_end - RExC_parse,
&numlen, UTF8_ALLOW_DEFAULT);
RExC_parse += numlen;
}
else
value = UCHARAT(RExC_parse++);
if (value == '[') {
char * posix_class_end;
namedclass = handle_possible_posix(pRExC_state,
RExC_parse,
&posix_class_end,
do_posix_warnings ? &posix_warnings : NULL,
FALSE /* die if error */);
if (namedclass > OOB_NAMEDCLASS) {
/* If there was an earlier attempt to parse this particular
* posix class, and it failed, it was a false alarm, as this
* successful one proves */
if ( posix_warnings
&& av_tindex_skip_len_mg(posix_warnings) >= 0
&& not_posix_region_end >= RExC_parse
&& not_posix_region_end <= posix_class_end)
{
av_undef(posix_warnings);
}
RExC_parse = posix_class_end;
}
else if (namedclass == OOB_NAMEDCLASS) {
not_posix_region_end = posix_class_end;
}
else {
namedclass = OOB_NAMEDCLASS;
}
}
else if ( RExC_parse - 1 > not_posix_region_end
&& MAYBE_POSIXCC(value))
{
(void) handle_possible_posix(
pRExC_state,
RExC_parse - 1, /* -1 because parse has already been
advanced */
¬_posix_region_end,
do_posix_warnings ? &posix_warnings : NULL,
TRUE /* checking only */);
}
else if (value == '\\') {
/* Is a backslash; get the code point of the char after it */
if (RExC_parse >= RExC_end) {
vFAIL("Unmatched [");
}
if (UTF && ! UTF8_IS_INVARIANT(UCHARAT(RExC_parse))) {
value = utf8n_to_uvchr((U8*)RExC_parse,
RExC_end - RExC_parse,
&numlen, UTF8_ALLOW_DEFAULT);
RExC_parse += numlen;
}
else
value = UCHARAT(RExC_parse++);
/* Some compilers cannot handle switching on 64-bit integer
* values, therefore value cannot be an UV. Yes, this will
* be a problem later if we want switch on Unicode.
* A similar issue a little bit later when switching on
* namedclass. --jhi */
/* If the \ is escaping white space when white space is being
* skipped, it means that that white space is wanted literally, and
* is already in 'value'. Otherwise, need to translate the escape
* into what it signifies. */
if (! skip_white || ! isBLANK_A(value)) switch ((I32)value) {
case 'w': namedclass = ANYOF_WORDCHAR; break;
case 'W': namedclass = ANYOF_NWORDCHAR; break;
case 's': namedclass = ANYOF_SPACE; break;
case 'S': namedclass = ANYOF_NSPACE; break;
case 'd': namedclass = ANYOF_DIGIT; break;
case 'D': namedclass = ANYOF_NDIGIT; break;
case 'v': namedclass = ANYOF_VERTWS; break;
case 'V': namedclass = ANYOF_NVERTWS; break;
case 'h': namedclass = ANYOF_HORIZWS; break;
case 'H': namedclass = ANYOF_NHORIZWS; break;
case 'N': /* Handle \N{NAME} in class */
{
const char * const backslash_N_beg = RExC_parse - 2;
int cp_count;
if (! grok_bslash_N(pRExC_state,
NULL, /* No regnode */
&value, /* Yes single value */
&cp_count, /* Multiple code pt count */
flagp,
strict,
depth)
) {
if (*flagp & NEED_UTF8)
FAIL("panic: grok_bslash_N set NEED_UTF8");
if (*flagp & RESTART_PASS1)
return NULL;
if (cp_count < 0) {
vFAIL("\\N in a character class must be a named character: \\N{...}");
}
else if (cp_count == 0) {
if (PASS2) {
ckWARNreg(RExC_parse,
"Ignoring zero length \\N{} in character class");
}
}
else { /* cp_count > 1 */
if (! RExC_in_multi_char_class) {
if (invert || range || *RExC_parse == '-') {
if (strict) {
RExC_parse--;
vFAIL("\\N{} in inverted character class or as a range end-point is restricted to one character");
}
else if (PASS2) {
ckWARNreg(RExC_parse, "Using just the first character returned by \\N{} in character class");
}
break; /* <value> contains the first code
point. Drop out of the switch to
process it */
}
else {
SV * multi_char_N = newSVpvn(backslash_N_beg,
RExC_parse - backslash_N_beg);
multi_char_matches
= add_multi_match(multi_char_matches,
multi_char_N,
cp_count);
}
}
} /* End of cp_count != 1 */
/* This element should not be processed further in this
* class */
element_count--;
value = save_value;
prevvalue = save_prevvalue;
continue; /* Back to top of loop to get next char */
}
/* Here, is a single code point, and <value> contains it */
unicode_range = TRUE; /* \N{} are Unicode */
}
break;
case 'p':
case 'P':
{
char *e;
/* We will handle any undefined properties ourselves */
U8 swash_init_flags = _CORE_SWASH_INIT_RETURN_IF_UNDEF
/* And we actually would prefer to get
* the straight inversion list of the
* swash, since we will be accessing it
* anyway, to save a little time */
|_CORE_SWASH_INIT_ACCEPT_INVLIST;
if (RExC_parse >= RExC_end)
vFAIL2("Empty \\%c", (U8)value);
if (*RExC_parse == '{') {
const U8 c = (U8)value;
e = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
if (!e) {
RExC_parse++;
vFAIL2("Missing right brace on \\%c{}", c);
}
RExC_parse++;
while (isSPACE(*RExC_parse)) {
RExC_parse++;
}
if (UCHARAT(RExC_parse) == '^') {
/* toggle. (The rhs xor gets the single bit that
* differs between P and p; the other xor inverts just
* that bit) */
value ^= 'P' ^ 'p';
RExC_parse++;
while (isSPACE(*RExC_parse)) {
RExC_parse++;
}
}
if (e == RExC_parse)
vFAIL2("Empty \\%c{}", c);
n = e - RExC_parse;
while (isSPACE(*(RExC_parse + n - 1)))
n--;
} /* The \p isn't immediately followed by a '{' */
else if (! isALPHA(*RExC_parse)) {
RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
vFAIL2("Character following \\%c must be '{' or a "
"single-character Unicode property name",
(U8) value);
}
else {
e = RExC_parse;
n = 1;
}
if (!SIZE_ONLY) {
SV* invlist;
char* name;
char* base_name; /* name after any packages are stripped */
char* lookup_name = NULL;
const char * const colon_colon = "::";
/* Try to get the definition of the property into
* <invlist>. If /i is in effect, the effective property
* will have its name be <__NAME_i>. The design is
* discussed in commit
* 2f833f5208e26b208886e51e09e2c072b5eabb46 */
name = savepv(Perl_form(aTHX_ "%.*s", (int)n, RExC_parse));
SAVEFREEPV(name);
if (FOLD) {
lookup_name = savepv(Perl_form(aTHX_ "__%s_i", name));
/* The function call just below that uses this can fail
* to return, leaking memory if we don't do this */
SAVEFREEPV(lookup_name);
}
/* Look up the property name, and get its swash and
* inversion list, if the property is found */
SvREFCNT_dec(swash); /* Free any left-overs */
swash = _core_swash_init("utf8",
(lookup_name)
? lookup_name
: name,
&PL_sv_undef,
1, /* binary */
0, /* not tr/// */
NULL, /* No inversion list */
&swash_init_flags
);
if (! swash || ! (invlist = _get_swash_invlist(swash))) {
HV* curpkg = (IN_PERL_COMPILETIME)
? PL_curstash
: CopSTASH(PL_curcop);
UV final_n = n;
bool has_pkg;
if (swash) { /* Got a swash but no inversion list.
Something is likely wrong that will
be sorted-out later */
SvREFCNT_dec_NN(swash);
swash = NULL;
}
/* Here didn't find it. It could be a an error (like a
* typo) in specifying a Unicode property, or it could
* be a user-defined property that will be available at
* run-time. The names of these must begin with 'In'
* or 'Is' (after any packages are stripped off). So
* if not one of those, or if we accept only
* compile-time properties, is an error; otherwise add
* it to the list for run-time look up. */
if ((base_name = rninstr(name, name + n,
colon_colon, colon_colon + 2)))
{ /* Has ::. We know this must be a user-defined
property */
base_name += 2;
final_n -= base_name - name;
has_pkg = TRUE;
}
else {
base_name = name;
has_pkg = FALSE;
}
if ( final_n < 3
|| base_name[0] != 'I'
|| (base_name[1] != 's' && base_name[1] != 'n')
|| ret_invlist)
{
const char * const msg
= (has_pkg)
? "Illegal user-defined property name"
: "Can't find Unicode property definition";
RExC_parse = e + 1;
/* diag_listed_as: Can't find Unicode property definition "%s" */
vFAIL3utf8f("%s \"%" UTF8f "\"",
msg, UTF8fARG(UTF, n, name));
}
/* If the property name doesn't already have a package
* name, add the current one to it so that it can be
* referred to outside it. [perl #121777] */
if (! has_pkg && curpkg) {
char* pkgname = HvNAME(curpkg);
if (memNEs(pkgname, HvNAMELEN(curpkg), "main")) {
char* full_name = Perl_form(aTHX_
"%s::%s",
pkgname,
name);
n = strlen(full_name);
name = savepvn(full_name, n);
SAVEFREEPV(name);
}
}
Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%s%" UTF8f "%s\n",
(value == 'p' ? '+' : '!'),
(FOLD) ? "__" : "",
UTF8fARG(UTF, n, name),
(FOLD) ? "_i" : "");
has_user_defined_property = TRUE;
optimizable = FALSE; /* Will have to leave this an
ANYOF node */
/* We don't know yet what this matches, so have to flag
* it */
ANYOF_FLAGS(ret) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
}
else {
/* Here, did get the swash and its inversion list. If
* the swash is from a user-defined property, then this
* whole character class should be regarded as such */
if (swash_init_flags
& _CORE_SWASH_INIT_USER_DEFINED_PROPERTY)
{
has_user_defined_property = TRUE;
}
else if
/* We warn on matching an above-Unicode code point
* if the match would return true, except don't
* warn for \p{All}, which has exactly one element
* = 0 */
(_invlist_contains_cp(invlist, 0x110000)
&& (! (_invlist_len(invlist) == 1
&& *invlist_array(invlist) == 0)))
{
warn_super = TRUE;
}
/* Invert if asking for the complement */
if (value == 'P') {
_invlist_union_complement_2nd(properties,
invlist,
&properties);
/* The swash can't be used as-is, because we've
* inverted things; delay removing it to here after
* have copied its invlist above */
SvREFCNT_dec_NN(swash);
swash = NULL;
}
else {
_invlist_union(properties, invlist, &properties);
}
}
}
RExC_parse = e + 1;
namedclass = ANYOF_UNIPROP; /* no official name, but it's
named */
/* \p means they want Unicode semantics */
REQUIRE_UNI_RULES(flagp, NULL);
}
break;
case 'n': value = '\n'; break;
case 'r': value = '\r'; break;
case 't': value = '\t'; break;
case 'f': value = '\f'; break;
case 'b': value = '\b'; break;
case 'e': value = ESC_NATIVE; break;
case 'a': value = '\a'; break;
case 'o':
RExC_parse--; /* function expects to be pointed at the 'o' */
{
const char* error_msg;
bool valid = grok_bslash_o(&RExC_parse,
RExC_end,
&value,
&error_msg,
PASS2, /* warnings only in
pass 2 */
strict,
silence_non_portable,
UTF);
if (! valid) {
vFAIL(error_msg);
}
}
non_portable_endpoint++;
break;
case 'x':
RExC_parse--; /* function expects to be pointed at the 'x' */
{
const char* error_msg;
bool valid = grok_bslash_x(&RExC_parse,
RExC_end,
&value,
&error_msg,
PASS2, /* Output warnings */
strict,
silence_non_portable,
UTF);
if (! valid) {
vFAIL(error_msg);
}
}
non_portable_endpoint++;
break;
case 'c':
value = grok_bslash_c(*RExC_parse++, PASS2);
non_portable_endpoint++;
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7':
{
/* Take 1-3 octal digits */
I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
numlen = (strict) ? 4 : 3;
value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
RExC_parse += numlen;
if (numlen != 3) {
if (strict) {
RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
vFAIL("Need exactly 3 octal digits");
}
else if (! SIZE_ONLY /* like \08, \178 */
&& numlen < 3
&& RExC_parse < RExC_end
&& isDIGIT(*RExC_parse)
&& ckWARN(WARN_REGEXP))
{
SAVEFREESV(RExC_rx_sv);
reg_warn_non_literal_string(
RExC_parse + 1,
form_short_octal_warning(RExC_parse, numlen));
(void)ReREFCNT_inc(RExC_rx_sv);
}
}
non_portable_endpoint++;
break;
}
default:
/* Allow \_ to not give an error */
if (!SIZE_ONLY && isWORDCHAR(value) && value != '_') {
if (strict) {
vFAIL2("Unrecognized escape \\%c in character class",
(int)value);
}
else {
SAVEFREESV(RExC_rx_sv);
ckWARN2reg(RExC_parse,
"Unrecognized escape \\%c in character class passed through",
(int)value);
(void)ReREFCNT_inc(RExC_rx_sv);
}
}
break;
} /* End of switch on char following backslash */
} /* end of handling backslash escape sequences */
/* Here, we have the current token in 'value' */
if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
U8 classnum;
/* a bad range like a-\d, a-[:digit:]. The '-' is taken as a
* literal, as is the character that began the false range, i.e.
* the 'a' in the examples */
if (range) {
if (!SIZE_ONLY) {
const int w = (RExC_parse >= rangebegin)
? RExC_parse - rangebegin
: 0;
if (strict) {
vFAIL2utf8f(
"False [] range \"%" UTF8f "\"",
UTF8fARG(UTF, w, rangebegin));
}
else {
SAVEFREESV(RExC_rx_sv); /* in case of fatal warnings */
ckWARN2reg(RExC_parse,
"False [] range \"%" UTF8f "\"",
UTF8fARG(UTF, w, rangebegin));
(void)ReREFCNT_inc(RExC_rx_sv);
cp_list = add_cp_to_invlist(cp_list, '-');
cp_foldable_list = add_cp_to_invlist(cp_foldable_list,
prevvalue);
}
}
range = 0; /* this was not a true range */
element_count += 2; /* So counts for three values */
}
classnum = namedclass_to_classnum(namedclass);
if (LOC && namedclass < ANYOF_POSIXL_MAX
#ifndef HAS_ISASCII
&& classnum != _CC_ASCII
#endif
) {
/* What the Posix classes (like \w, [:space:]) match in locale
* isn't knowable under locale until actual match time. Room
* must be reserved (one time per outer bracketed class) to
* store such classes. The space will contain a bit for each
* named class that is to be matched against. This isn't
* needed for \p{} and pseudo-classes, as they are not affected
* by locale, and hence are dealt with separately */
if (! need_class) {
need_class = 1;
if (SIZE_ONLY) {
RExC_size += ANYOF_POSIXL_SKIP - ANYOF_SKIP;
}
else {
RExC_emit += ANYOF_POSIXL_SKIP - ANYOF_SKIP;
}
ANYOF_FLAGS(ret) |= ANYOF_MATCHES_POSIXL;
ANYOF_POSIXL_ZERO(ret);
/* We can't change this into some other type of node
* (unless this is the only element, in which case there
* are nodes that mean exactly this) as has runtime
* dependencies */
optimizable = FALSE;
}
/* Coverity thinks it is possible for this to be negative; both
* jhi and khw think it's not, but be safer */
assert(! (ANYOF_FLAGS(ret) & ANYOF_MATCHES_POSIXL)
|| (namedclass + ((namedclass % 2) ? -1 : 1)) >= 0);
/* See if it already matches the complement of this POSIX
* class */
if ((ANYOF_FLAGS(ret) & ANYOF_MATCHES_POSIXL)
&& ANYOF_POSIXL_TEST(ret, namedclass + ((namedclass % 2)
? -1
: 1)))
{
posixl_matches_all = TRUE;
break; /* No need to continue. Since it matches both
e.g., \w and \W, it matches everything, and the
bracketed class can be optimized into qr/./s */
}
/* Add this class to those that should be checked at runtime */
ANYOF_POSIXL_SET(ret, namedclass);
/* The above-Latin1 characters are not subject to locale rules.
* Just add them, in the second pass, to the
* unconditionally-matched list */
if (! SIZE_ONLY) {
SV* scratch_list = NULL;
/* Get the list of the above-Latin1 code points this
* matches */
_invlist_intersection_maybe_complement_2nd(PL_AboveLatin1,
PL_XPosix_ptrs[classnum],
/* Odd numbers are complements, like
* NDIGIT, NASCII, ... */
namedclass % 2 != 0,
&scratch_list);
/* Checking if 'cp_list' is NULL first saves an extra
* clone. Its reference count will be decremented at the
* next union, etc, or if this is the only instance, at the
* end of the routine */
if (! cp_list) {
cp_list = scratch_list;
}
else {
_invlist_union(cp_list, scratch_list, &cp_list);
SvREFCNT_dec_NN(scratch_list);
}
continue; /* Go get next character */
}
}
else if (! SIZE_ONLY) {
/* Here, not in pass1 (in that pass we skip calculating the
* contents of this class), and is not /l, or is a POSIX class
* for which /l doesn't matter (or is a Unicode property, which
* is skipped here). */
if (namedclass >= ANYOF_POSIXL_MAX) { /* If a special class */
if (namedclass != ANYOF_UNIPROP) { /* UNIPROP = \p and \P */
/* Here, should be \h, \H, \v, or \V. None of /d, /i
* nor /l make a difference in what these match,
* therefore we just add what they match to cp_list. */
if (classnum != _CC_VERTSPACE) {
assert( namedclass == ANYOF_HORIZWS
|| namedclass == ANYOF_NHORIZWS);
/* It turns out that \h is just a synonym for
* XPosixBlank */
classnum = _CC_BLANK;
}
_invlist_union_maybe_complement_2nd(
cp_list,
PL_XPosix_ptrs[classnum],
namedclass % 2 != 0, /* Complement if odd
(NHORIZWS, NVERTWS)
*/
&cp_list);
}
}
else if ( UNI_SEMANTICS
|| classnum == _CC_ASCII
|| (DEPENDS_SEMANTICS && ( classnum == _CC_DIGIT
|| classnum == _CC_XDIGIT)))
{
/* We usually have to worry about /d and /a affecting what
* POSIX classes match, with special code needed for /d
* because we won't know until runtime what all matches.
* But there is no extra work needed under /u, and
* [:ascii:] is unaffected by /a and /d; and :digit: and
* :xdigit: don't have runtime differences under /d. So we
* can special case these, and avoid some extra work below,
* and at runtime. */
_invlist_union_maybe_complement_2nd(
simple_posixes,
PL_XPosix_ptrs[classnum],
namedclass % 2 != 0,
&simple_posixes);
}
else { /* Garden variety class. If is NUPPER, NALPHA, ...
complement and use nposixes */
SV** posixes_ptr = namedclass % 2 == 0
? &posixes
: &nposixes;
_invlist_union_maybe_complement_2nd(
*posixes_ptr,
PL_XPosix_ptrs[classnum],
namedclass % 2 != 0,
posixes_ptr);
}
}
} /* end of namedclass \blah */
SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
/* If 'range' is set, 'value' is the ending of a range--check its
* validity. (If value isn't a single code point in the case of a
* range, we should have figured that out above in the code that
* catches false ranges). Later, we will handle each individual code
* point in the range. If 'range' isn't set, this could be the
* beginning of a range, so check for that by looking ahead to see if
* the next real character to be processed is the range indicator--the
* minus sign */
if (range) {
#ifdef EBCDIC
/* For unicode ranges, we have to test that the Unicode as opposed
* to the native values are not decreasing. (Above 255, there is
* no difference between native and Unicode) */
if (unicode_range && prevvalue < 255 && value < 255) {
if (NATIVE_TO_LATIN1(prevvalue) > NATIVE_TO_LATIN1(value)) {
goto backwards_range;
}
}
else
#endif
if (prevvalue > value) /* b-a */ {
int w;
#ifdef EBCDIC
backwards_range:
#endif
w = RExC_parse - rangebegin;
vFAIL2utf8f(
"Invalid [] range \"%" UTF8f "\"",
UTF8fARG(UTF, w, rangebegin));
NOT_REACHED; /* NOTREACHED */
}
}
else {
prevvalue = value; /* save the beginning of the potential range */
if (! stop_at_1 /* Can't be a range if parsing just one thing */
&& *RExC_parse == '-')
{
char* next_char_ptr = RExC_parse + 1;
/* Get the next real char after the '-' */
SKIP_BRACKETED_WHITE_SPACE(skip_white, next_char_ptr);
/* If the '-' is at the end of the class (just before the ']',
* it is a literal minus; otherwise it is a range */
if (next_char_ptr < RExC_end && *next_char_ptr != ']') {
RExC_parse = next_char_ptr;
/* a bad range like \w-, [:word:]- ? */
if (namedclass > OOB_NAMEDCLASS) {
if (strict || (PASS2 && ckWARN(WARN_REGEXP))) {
const int w = RExC_parse >= rangebegin
? RExC_parse - rangebegin
: 0;
if (strict) {
vFAIL4("False [] range \"%*.*s\"",
w, w, rangebegin);
}
else if (PASS2) {
vWARN4(RExC_parse,
"False [] range \"%*.*s\"",
w, w, rangebegin);
}
}
if (!SIZE_ONLY) {
cp_list = add_cp_to_invlist(cp_list, '-');
}
element_count++;
} else
range = 1; /* yeah, it's a range! */
continue; /* but do it the next time */
}
}
}
if (namedclass > OOB_NAMEDCLASS) {
continue;
}
/* Here, we have a single value this time through the loop, and
* <prevvalue> is the beginning of the range, if any; or <value> if
* not. */
/* non-Latin1 code point implies unicode semantics. Must be set in
* pass1 so is there for the whole of pass 2 */
if (value > 255) {
REQUIRE_UNI_RULES(flagp, NULL);
}
/* Ready to process either the single value, or the completed range.
* For single-valued non-inverted ranges, we consider the possibility
* of multi-char folds. (We made a conscious decision to not do this
* for the other cases because it can often lead to non-intuitive
* results. For example, you have the peculiar case that:
* "s s" =~ /^[^\xDF]+$/i => Y
* "ss" =~ /^[^\xDF]+$/i => N
*
* See [perl #89750] */
if (FOLD && allow_multi_folds && value == prevvalue) {
if (value == LATIN_SMALL_LETTER_SHARP_S
|| (value > 255 && _invlist_contains_cp(PL_HasMultiCharFold,
value)))
{
/* Here <value> is indeed a multi-char fold. Get what it is */
U8 foldbuf[UTF8_MAXBYTES_CASE];
STRLEN foldlen;
UV folded = _to_uni_fold_flags(
value,
foldbuf,
&foldlen,
FOLD_FLAGS_FULL | (ASCII_FOLD_RESTRICTED
? FOLD_FLAGS_NOMIX_ASCII
: 0)
);
/* Here, <folded> should be the first character of the
* multi-char fold of <value>, with <foldbuf> containing the
* whole thing. But, if this fold is not allowed (because of
* the flags), <fold> will be the same as <value>, and should
* be processed like any other character, so skip the special
* handling */
if (folded != value) {
/* Skip if we are recursed, currently parsing the class
* again. Otherwise add this character to the list of
* multi-char folds. */
if (! RExC_in_multi_char_class) {
STRLEN cp_count = utf8_length(foldbuf,
foldbuf + foldlen);
SV* multi_fold = sv_2mortal(newSVpvs(""));
Perl_sv_catpvf(aTHX_ multi_fold, "\\x{%" UVXf "}", value);
multi_char_matches
= add_multi_match(multi_char_matches,
multi_fold,
cp_count);
}
/* This element should not be processed further in this
* class */
element_count--;
value = save_value;
prevvalue = save_prevvalue;
continue;
}
}
}
if (strict && PASS2 && ckWARN(WARN_REGEXP)) {
if (range) {
/* If the range starts above 255, everything is portable and
* likely to be so for any forseeable character set, so don't
* warn. */
if (unicode_range && non_portable_endpoint && prevvalue < 256) {
vWARN(RExC_parse, "Both or neither range ends should be Unicode");
}
else if (prevvalue != value) {
/* Under strict, ranges that stop and/or end in an ASCII
* printable should have each end point be a portable value
* for it (preferably like 'A', but we don't warn if it is
* a (portable) Unicode name or code point), and the range
* must be be all digits or all letters of the same case.
* Otherwise, the range is non-portable and unclear as to
* what it contains */
if ( (isPRINT_A(prevvalue) || isPRINT_A(value))
&& ( non_portable_endpoint
|| ! ( (isDIGIT_A(prevvalue) && isDIGIT_A(value))
|| (isLOWER_A(prevvalue) && isLOWER_A(value))
|| (isUPPER_A(prevvalue) && isUPPER_A(value))
))) {
vWARN(RExC_parse, "Ranges of ASCII printables should"
" be some subset of \"0-9\","
" \"A-Z\", or \"a-z\"");
}
else if (prevvalue >= 0x660) { /* ARABIC_INDIC_DIGIT_ZERO */
SSize_t index_start;
SSize_t index_final;
/* But the nature of Unicode and languages mean we
* can't do the same checks for above-ASCII ranges,
* except in the case of digit ones. These should
* contain only digits from the same group of 10. The
* ASCII case is handled just above. 0x660 is the
* first digit character beyond ASCII. Hence here, the
* range could be a range of digits. First some
* unlikely special cases. Grandfather in that a range
* ending in 19DA (NEW TAI LUE THAM DIGIT ONE) is bad
* if its starting value is one of the 10 digits prior
* to it. This is because it is an alternate way of
* writing 19D1, and some people may expect it to be in
* that group. But it is bad, because it won't give
* the expected results. In Unicode 5.2 it was
* considered to be in that group (of 11, hence), but
* this was fixed in the next version */
if (UNLIKELY(value == 0x19DA && prevvalue >= 0x19D0)) {
goto warn_bad_digit_range;
}
else if (UNLIKELY( prevvalue >= 0x1D7CE
&& value <= 0x1D7FF))
{
/* This is the only other case currently in Unicode
* where the algorithm below fails. The code
* points just above are the end points of a single
* range containing only decimal digits. It is 5
* different series of 0-9. All other ranges of
* digits currently in Unicode are just a single
* series. (And mktables will notify us if a later
* Unicode version breaks this.)
*
* If the range being checked is at most 9 long,
* and the digit values represented are in
* numerical order, they are from the same series.
* */
if ( value - prevvalue > 9
|| ((( value - 0x1D7CE) % 10)
<= (prevvalue - 0x1D7CE) % 10))
{
goto warn_bad_digit_range;
}
}
else {
/* For all other ranges of digits in Unicode, the
* algorithm is just to check if both end points
* are in the same series, which is the same range.
* */
index_start = _invlist_search(
PL_XPosix_ptrs[_CC_DIGIT],
prevvalue);
/* Warn if the range starts and ends with a digit,
* and they are not in the same group of 10. */
if ( index_start >= 0
&& ELEMENT_RANGE_MATCHES_INVLIST(index_start)
&& (index_final =
_invlist_search(PL_XPosix_ptrs[_CC_DIGIT],
value)) != index_start
&& index_final >= 0
&& ELEMENT_RANGE_MATCHES_INVLIST(index_final))
{
warn_bad_digit_range:
vWARN(RExC_parse, "Ranges of digits should be"
" from the same group of"
" 10");
}
}
}
}
}
if ((! range || prevvalue == value) && non_portable_endpoint) {
if (isPRINT_A(value)) {
char literal[3];
unsigned d = 0;
if (isBACKSLASHED_PUNCT(value)) {
literal[d++] = '\\';
}
literal[d++] = (char) value;
literal[d++] = '\0';
vWARN4(RExC_parse,
"\"%.*s\" is more clearly written simply as \"%s\"",
(int) (RExC_parse - rangebegin),
rangebegin,
literal
);
}
else if isMNEMONIC_CNTRL(value) {
vWARN4(RExC_parse,
"\"%.*s\" is more clearly written simply as \"%s\"",
(int) (RExC_parse - rangebegin),
rangebegin,
cntrl_to_mnemonic((U8) value)
);
}
}
}
/* Deal with this element of the class */
if (! SIZE_ONLY) {
#ifndef EBCDIC
cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
prevvalue, value);
#else
/* On non-ASCII platforms, for ranges that span all of 0..255, and
* ones that don't require special handling, we can just add the
* range like we do for ASCII platforms */
if ((UNLIKELY(prevvalue == 0) && value >= 255)
|| ! (prevvalue < 256
&& (unicode_range
|| (! non_portable_endpoint
&& ((isLOWER_A(prevvalue) && isLOWER_A(value))
|| (isUPPER_A(prevvalue)
&& isUPPER_A(value)))))))
{
cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
prevvalue, value);
}
else {
/* Here, requires special handling. This can be because it is
* a range whose code points are considered to be Unicode, and
* so must be individually translated into native, or because
* its a subrange of 'A-Z' or 'a-z' which each aren't
* contiguous in EBCDIC, but we have defined them to include
* only the "expected" upper or lower case ASCII alphabetics.
* Subranges above 255 are the same in native and Unicode, so
* can be added as a range */
U8 start = NATIVE_TO_LATIN1(prevvalue);
unsigned j;
U8 end = (value < 256) ? NATIVE_TO_LATIN1(value) : 255;
for (j = start; j <= end; j++) {
cp_foldable_list = add_cp_to_invlist(cp_foldable_list, LATIN1_TO_NATIVE(j));
}
if (value > 255) {
cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
256, value);
}
}
#endif
}
range = 0; /* this range (if it was one) is done now */
} /* End of loop through all the text within the brackets */
if ( posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0) {
output_or_return_posix_warnings(pRExC_state, posix_warnings,
return_posix_warnings);
}
/* If anything in the class expands to more than one character, we have to
* deal with them by building up a substitute parse string, and recursively
* calling reg() on it, instead of proceeding */
if (multi_char_matches) {
SV * substitute_parse = newSVpvn_flags("?:", 2, SVs_TEMP);
I32 cp_count;
STRLEN len;
char *save_end = RExC_end;
char *save_parse = RExC_parse;
char *save_start = RExC_start;
STRLEN prefix_end = 0; /* We copy the character class after a
prefix supplied here. This is the size
+ 1 of that prefix */
bool first_time = TRUE; /* First multi-char occurrence doesn't get
a "|" */
I32 reg_flags;
assert(! invert);
assert(RExC_precomp_adj == 0); /* Only one level of recursion allowed */
#if 0 /* Have decided not to deal with multi-char folds in inverted classes,
because too confusing */
if (invert) {
sv_catpv(substitute_parse, "(?:");
}
#endif
/* Look at the longest folds first */
for (cp_count = av_tindex_skip_len_mg(multi_char_matches);
cp_count > 0;
cp_count--)
{
if (av_exists(multi_char_matches, cp_count)) {
AV** this_array_ptr;
SV* this_sequence;
this_array_ptr = (AV**) av_fetch(multi_char_matches,
cp_count, FALSE);
while ((this_sequence = av_pop(*this_array_ptr)) !=
&PL_sv_undef)
{
if (! first_time) {
sv_catpv(substitute_parse, "|");
}
first_time = FALSE;
sv_catpv(substitute_parse, SvPVX(this_sequence));
}
}
}
/* If the character class contains anything else besides these
* multi-character folds, have to include it in recursive parsing */
if (element_count) {
sv_catpv(substitute_parse, "|[");
prefix_end = SvCUR(substitute_parse);
sv_catpvn(substitute_parse, orig_parse, RExC_parse - orig_parse);
/* Put in a closing ']' only if not going off the end, as otherwise
* we are adding something that really isn't there */
if (RExC_parse < RExC_end) {
sv_catpv(substitute_parse, "]");
}
}
sv_catpv(substitute_parse, ")");
#if 0
if (invert) {
/* This is a way to get the parse to skip forward a whole named
* sequence instead of matching the 2nd character when it fails the
* first */
sv_catpv(substitute_parse, "(*THEN)(*SKIP)(*FAIL)|.)");
}
#endif
/* Set up the data structure so that any errors will be properly
* reported. See the comments at the definition of
* REPORT_LOCATION_ARGS for details */
RExC_precomp_adj = orig_parse - RExC_precomp;
RExC_start = RExC_parse = SvPV(substitute_parse, len);
RExC_adjusted_start = RExC_start + prefix_end;
RExC_end = RExC_parse + len;
RExC_in_multi_char_class = 1;
RExC_emit = (regnode *)orig_emit;
ret = reg(pRExC_state, 1, ®_flags, depth+1);
*flagp |= reg_flags&(HASWIDTH|SIMPLE|SPSTART|POSTPONED|RESTART_PASS1|NEED_UTF8);
/* And restore so can parse the rest of the pattern */
RExC_parse = save_parse;
RExC_start = RExC_adjusted_start = save_start;
RExC_precomp_adj = 0;
RExC_end = save_end;
RExC_in_multi_char_class = 0;
SvREFCNT_dec_NN(multi_char_matches);
return ret;
}
/* Here, we've gone through the entire class and dealt with multi-char
* folds. We are now in a position that we can do some checks to see if we
* can optimize this ANYOF node into a simpler one, even in Pass 1.
* Currently we only do two checks:
* 1) is in the unlikely event that the user has specified both, eg. \w and
* \W under /l, then the class matches everything. (This optimization
* is done only to make the optimizer code run later work.)
* 2) if the character class contains only a single element (including a
* single range), we see if there is an equivalent node for it.
* Other checks are possible */
if ( optimizable
&& ! ret_invlist /* Can't optimize if returning the constructed
inversion list */
&& (UNLIKELY(posixl_matches_all) || element_count == 1))
{
U8 op = END;
U8 arg = 0;
if (UNLIKELY(posixl_matches_all)) {
op = SANY;
}
else if (namedclass > OOB_NAMEDCLASS) { /* this is a single named
class, like \w or [:digit:]
or \p{foo} */
/* All named classes are mapped into POSIXish nodes, with its FLAG
* argument giving which class it is */
switch ((I32)namedclass) {
case ANYOF_UNIPROP:
break;
/* These don't depend on the charset modifiers. They always
* match under /u rules */
case ANYOF_NHORIZWS:
case ANYOF_HORIZWS:
namedclass = ANYOF_BLANK + namedclass - ANYOF_HORIZWS;
/* FALLTHROUGH */
case ANYOF_NVERTWS:
case ANYOF_VERTWS:
op = POSIXU;
goto join_posix;
/* The actual POSIXish node for all the rest depends on the
* charset modifier. The ones in the first set depend only on
* ASCII or, if available on this platform, also locale */
case ANYOF_ASCII:
case ANYOF_NASCII:
#ifdef HAS_ISASCII
op = (LOC) ? POSIXL : POSIXA;
#else
op = POSIXA;
#endif
goto join_posix;
/* The following don't have any matches in the upper Latin1
* range, hence /d is equivalent to /u for them. Making it /u
* saves some branches at runtime */
case ANYOF_DIGIT:
case ANYOF_NDIGIT:
case ANYOF_XDIGIT:
case ANYOF_NXDIGIT:
if (! DEPENDS_SEMANTICS) {
goto treat_as_default;
}
op = POSIXU;
goto join_posix;
/* The following change to CASED under /i */
case ANYOF_LOWER:
case ANYOF_NLOWER:
case ANYOF_UPPER:
case ANYOF_NUPPER:
if (FOLD) {
namedclass = ANYOF_CASED + (namedclass % 2);
}
/* FALLTHROUGH */
/* The rest have more possibilities depending on the charset.
* We take advantage of the enum ordering of the charset
* modifiers to get the exact node type, */
default:
treat_as_default:
op = POSIXD + get_regex_charset(RExC_flags);
if (op > POSIXA) { /* /aa is same as /a */
op = POSIXA;
}
join_posix:
/* The odd numbered ones are the complements of the
* next-lower even number one */
if (namedclass % 2 == 1) {
invert = ! invert;
namedclass--;
}
arg = namedclass_to_classnum(namedclass);
break;
}
}
else if (value == prevvalue) {
/* Here, the class consists of just a single code point */
if (invert) {
if (! LOC && value == '\n') {
op = REG_ANY; /* Optimize [^\n] */
*flagp |= HASWIDTH|SIMPLE;
MARK_NAUGHTY(1);
}
}
else if (value < 256 || UTF) {
/* Optimize a single value into an EXACTish node, but not if it
* would require converting the pattern to UTF-8. */
op = compute_EXACTish(pRExC_state);
}
} /* Otherwise is a range */
else if (! LOC) { /* locale could vary these */
if (prevvalue == '0') {
if (value == '9') {
arg = _CC_DIGIT;
op = POSIXA;
}
}
else if (! FOLD || ASCII_FOLD_RESTRICTED) {
/* We can optimize A-Z or a-z, but not if they could match
* something like the KELVIN SIGN under /i. */
if (prevvalue == 'A') {
if (value == 'Z'
#ifdef EBCDIC
&& ! non_portable_endpoint
#endif
) {
arg = (FOLD) ? _CC_ALPHA : _CC_UPPER;
op = POSIXA;
}
}
else if (prevvalue == 'a') {
if (value == 'z'
#ifdef EBCDIC
&& ! non_portable_endpoint
#endif
) {
arg = (FOLD) ? _CC_ALPHA : _CC_LOWER;
op = POSIXA;
}
}
}
}
/* Here, we have changed <op> away from its initial value iff we found
* an optimization */
if (op != END) {
/* Throw away this ANYOF regnode, and emit the calculated one,
* which should correspond to the beginning, not current, state of
* the parse */
const char * cur_parse = RExC_parse;
RExC_parse = (char *)orig_parse;
if ( SIZE_ONLY) {
if (! LOC) {
/* To get locale nodes to not use the full ANYOF size would
* require moving the code above that writes the portions
* of it that aren't in other nodes to after this point.
* e.g. ANYOF_POSIXL_SET */
RExC_size = orig_size;
}
}
else {
RExC_emit = (regnode *)orig_emit;
if (PL_regkind[op] == POSIXD) {
if (op == POSIXL) {
RExC_contains_locale = 1;
}
if (invert) {
op += NPOSIXD - POSIXD;
}
}
}
ret = reg_node(pRExC_state, op);
if (PL_regkind[op] == POSIXD || PL_regkind[op] == NPOSIXD) {
if (! SIZE_ONLY) {
FLAGS(ret) = arg;
}
*flagp |= HASWIDTH|SIMPLE;
}
else if (PL_regkind[op] == EXACT) {
alloc_maybe_populate_EXACT(pRExC_state, ret, flagp, 0, value,
TRUE /* downgradable to EXACT */
);
}
RExC_parse = (char *) cur_parse;
SvREFCNT_dec(posixes);
SvREFCNT_dec(nposixes);
SvREFCNT_dec(simple_posixes);
SvREFCNT_dec(cp_list);
SvREFCNT_dec(cp_foldable_list);
return ret;
}
}
if (SIZE_ONLY)
return ret;
/****** !SIZE_ONLY (Pass 2) AFTER HERE *********/
/* If folding, we calculate all characters that could fold to or from the
* ones already on the list */
if (cp_foldable_list) {
if (FOLD) {
UV start, end; /* End points of code point ranges */
SV* fold_intersection = NULL;
SV** use_list;
/* Our calculated list will be for Unicode rules. For locale
* matching, we have to keep a separate list that is consulted at
* runtime only when the locale indicates Unicode rules. For
* non-locale, we just use the general list */
if (LOC) {
use_list = &only_utf8_locale_list;
}
else {
use_list = &cp_list;
}
/* Only the characters in this class that participate in folds need
* be checked. Get the intersection of this class and all the
* possible characters that are foldable. This can quickly narrow
* down a large class */
_invlist_intersection(PL_utf8_foldable, cp_foldable_list,
&fold_intersection);
/* The folds for all the Latin1 characters are hard-coded into this
* program, but we have to go out to disk to get the others. */
if (invlist_highest(cp_foldable_list) >= 256) {
/* This is a hash that for a particular fold gives all
* characters that are involved in it */
if (! PL_utf8_foldclosures) {
_load_PL_utf8_foldclosures();
}
}
/* Now look at the foldable characters in this class individually */
invlist_iterinit(fold_intersection);
while (invlist_iternext(fold_intersection, &start, &end)) {
UV j;
/* Look at every character in the range */
for (j = start; j <= end; j++) {
U8 foldbuf[UTF8_MAXBYTES_CASE+1];
STRLEN foldlen;
SV** listp;
if (j < 256) {
if (IS_IN_SOME_FOLD_L1(j)) {
/* ASCII is always matched; non-ASCII is matched
* only under Unicode rules (which could happen
* under /l if the locale is a UTF-8 one */
if (isASCII(j) || ! DEPENDS_SEMANTICS) {
*use_list = add_cp_to_invlist(*use_list,
PL_fold_latin1[j]);
}
else {
has_upper_latin1_only_utf8_matches
= add_cp_to_invlist(
has_upper_latin1_only_utf8_matches,
PL_fold_latin1[j]);
}
}
if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(j)
&& (! isASCII(j) || ! ASCII_FOLD_RESTRICTED))
{
add_above_Latin1_folds(pRExC_state,
(U8) j,
use_list);
}
continue;
}
/* Here is an above Latin1 character. We don't have the
* rules hard-coded for it. First, get its fold. This is
* the simple fold, as the multi-character folds have been
* handled earlier and separated out */
_to_uni_fold_flags(j, foldbuf, &foldlen,
(ASCII_FOLD_RESTRICTED)
? FOLD_FLAGS_NOMIX_ASCII
: 0);
/* Single character fold of above Latin1. Add everything in
* its fold closure to the list that this node should match.
* The fold closures data structure is a hash with the keys
* being the UTF-8 of every character that is folded to, like
* 'k', and the values each an array of all code points that
* fold to its key. e.g. [ 'k', 'K', KELVIN_SIGN ].
* Multi-character folds are not included */
if ((listp = hv_fetch(PL_utf8_foldclosures,
(char *) foldbuf, foldlen, FALSE)))
{
AV* list = (AV*) *listp;
IV k;
for (k = 0; k <= av_tindex_skip_len_mg(list); k++) {
SV** c_p = av_fetch(list, k, FALSE);
UV c;
assert(c_p);
c = SvUV(*c_p);
/* /aa doesn't allow folds between ASCII and non- */
if ((ASCII_FOLD_RESTRICTED
&& (isASCII(c) != isASCII(j))))
{
continue;
}
/* Folds under /l which cross the 255/256 boundary
* are added to a separate list. (These are valid
* only when the locale is UTF-8.) */
if (c < 256 && LOC) {
*use_list = add_cp_to_invlist(*use_list, c);
continue;
}
if (isASCII(c) || c > 255 || AT_LEAST_UNI_SEMANTICS)
{
cp_list = add_cp_to_invlist(cp_list, c);
}
else {
/* Similarly folds involving non-ascii Latin1
* characters under /d are added to their list */
has_upper_latin1_only_utf8_matches
= add_cp_to_invlist(
has_upper_latin1_only_utf8_matches,
c);
}
}
}
}
}
SvREFCNT_dec_NN(fold_intersection);
}
/* Now that we have finished adding all the folds, there is no reason
* to keep the foldable list separate */
_invlist_union(cp_list, cp_foldable_list, &cp_list);
SvREFCNT_dec_NN(cp_foldable_list);
}
/* And combine the result (if any) with any inversion lists from posix
* classes. The lists are kept separate up to now because we don't want to
* fold the classes (folding of those is automatically handled by the swash
* fetching code) */
if (simple_posixes) { /* These are the classes known to be unaffected by
/a, /aa, and /d */
if (cp_list) {
_invlist_union(cp_list, simple_posixes, &cp_list);
SvREFCNT_dec_NN(simple_posixes);
}
else {
cp_list = simple_posixes;
}
}
if (posixes || nposixes) {
/* We have to adjust /a and /aa */
if (AT_LEAST_ASCII_RESTRICTED) {
/* Under /a and /aa, nothing above ASCII matches these */
if (posixes) {
_invlist_intersection(posixes,
PL_XPosix_ptrs[_CC_ASCII],
&posixes);
}
/* Under /a and /aa, everything above ASCII matches these
* complements */
if (nposixes) {
_invlist_union_complement_2nd(nposixes,
PL_XPosix_ptrs[_CC_ASCII],
&nposixes);
}
}
if (! DEPENDS_SEMANTICS) {
/* For everything but /d, we can just add the current 'posixes' and
* 'nposixes' to the main list */
if (posixes) {
if (cp_list) {
_invlist_union(cp_list, posixes, &cp_list);
SvREFCNT_dec_NN(posixes);
}
else {
cp_list = posixes;
}
}
if (nposixes) {
if (cp_list) {
_invlist_union(cp_list, nposixes, &cp_list);
SvREFCNT_dec_NN(nposixes);
}
else {
cp_list = nposixes;
}
}
}
else {
/* Under /d, things like \w match upper Latin1 characters only if
* the target string is in UTF-8. But things like \W match all the
* upper Latin1 characters if the target string is not in UTF-8.
*
* Handle the case where there something like \W separately */
if (nposixes) {
SV* only_non_utf8_list = invlist_clone(PL_UpperLatin1);
/* A complemented posix class matches all upper Latin1
* characters if not in UTF-8. And it matches just certain
* ones when in UTF-8. That means those certain ones are
* matched regardless, so can just be added to the
* unconditional list */
if (cp_list) {
_invlist_union(cp_list, nposixes, &cp_list);
SvREFCNT_dec_NN(nposixes);
nposixes = NULL;
}
else {
cp_list = nposixes;
}
/* Likewise for 'posixes' */
_invlist_union(posixes, cp_list, &cp_list);
/* Likewise for anything else in the range that matched only
* under UTF-8 */
if (has_upper_latin1_only_utf8_matches) {
_invlist_union(cp_list,
has_upper_latin1_only_utf8_matches,
&cp_list);
SvREFCNT_dec_NN(has_upper_latin1_only_utf8_matches);
has_upper_latin1_only_utf8_matches = NULL;
}
/* If we don't match all the upper Latin1 characters regardless
* of UTF-8ness, we have to set a flag to match the rest when
* not in UTF-8 */
_invlist_subtract(only_non_utf8_list, cp_list,
&only_non_utf8_list);
if (_invlist_len(only_non_utf8_list) != 0) {
ANYOF_FLAGS(ret) |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
}
}
else {
/* Here there were no complemented posix classes. That means
* the upper Latin1 characters in 'posixes' match only when the
* target string is in UTF-8. So we have to add them to the
* list of those types of code points, while adding the
* remainder to the unconditional list.
*
* First calculate what they are */
SV* nonascii_but_latin1_properties = NULL;
_invlist_intersection(posixes, PL_UpperLatin1,
&nonascii_but_latin1_properties);
/* And add them to the final list of such characters. */
_invlist_union(has_upper_latin1_only_utf8_matches,
nonascii_but_latin1_properties,
&has_upper_latin1_only_utf8_matches);
/* Remove them from what now becomes the unconditional list */
_invlist_subtract(posixes, nonascii_but_latin1_properties,
&posixes);
/* And add those unconditional ones to the final list */
if (cp_list) {
_invlist_union(cp_list, posixes, &cp_list);
SvREFCNT_dec_NN(posixes);
posixes = NULL;
}
else {
cp_list = posixes;
}
SvREFCNT_dec(nonascii_but_latin1_properties);
/* Get rid of any characters that we now know are matched
* unconditionally from the conditional list, which may make
* that list empty */
_invlist_subtract(has_upper_latin1_only_utf8_matches,
cp_list,
&has_upper_latin1_only_utf8_matches);
if (_invlist_len(has_upper_latin1_only_utf8_matches) == 0) {
SvREFCNT_dec_NN(has_upper_latin1_only_utf8_matches);
has_upper_latin1_only_utf8_matches = NULL;
}
}
}
}
/* And combine the result (if any) with any inversion list from properties.
* The lists are kept separate up to now so that we can distinguish the two
* in regards to matching above-Unicode. A run-time warning is generated
* if a Unicode property is matched against a non-Unicode code point. But,
* we allow user-defined properties to match anything, without any warning,
* and we also suppress the warning if there is a portion of the character
* class that isn't a Unicode property, and which matches above Unicode, \W
* or [\x{110000}] for example.
* (Note that in this case, unlike the Posix one above, there is no
* <has_upper_latin1_only_utf8_matches>, because having a Unicode property
* forces Unicode semantics */
if (properties) {
if (cp_list) {
/* If it matters to the final outcome, see if a non-property
* component of the class matches above Unicode. If so, the
* warning gets suppressed. This is true even if just a single
* such code point is specified, as, though not strictly correct if
* another such code point is matched against, the fact that they
* are using above-Unicode code points indicates they should know
* the issues involved */
if (warn_super) {
warn_super = ! (invert
^ (invlist_highest(cp_list) > PERL_UNICODE_MAX));
}
_invlist_union(properties, cp_list, &cp_list);
SvREFCNT_dec_NN(properties);
}
else {
cp_list = properties;
}
if (warn_super) {
ANYOF_FLAGS(ret)
|= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
/* Because an ANYOF node is the only one that warns, this node
* can't be optimized into something else */
optimizable = FALSE;
}
}
/* Here, we have calculated what code points should be in the character
* class.
*
* Now we can see about various optimizations. Fold calculation (which we
* did above) needs to take place before inversion. Otherwise /[^k]/i
* would invert to include K, which under /i would match k, which it
* shouldn't. Therefore we can't invert folded locale now, as it won't be
* folded until runtime */
/* If we didn't do folding, it's because some information isn't available
* until runtime; set the run-time fold flag for these. (We don't have to
* worry about properties folding, as that is taken care of by the swash
* fetching). We know to set the flag if we have a non-NULL list for UTF-8
* locales, or the class matches at least one 0-255 range code point */
if (LOC && FOLD) {
/* Some things on the list might be unconditionally included because of
* other components. Remove them, and clean up the list if it goes to
* 0 elements */
if (only_utf8_locale_list && cp_list) {
_invlist_subtract(only_utf8_locale_list, cp_list,
&only_utf8_locale_list);
if (_invlist_len(only_utf8_locale_list) == 0) {
SvREFCNT_dec_NN(only_utf8_locale_list);
only_utf8_locale_list = NULL;
}
}
if (only_utf8_locale_list) {
ANYOF_FLAGS(ret)
|= ANYOFL_FOLD
|ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
}
else if (cp_list) { /* Look to see if a 0-255 code point is in list */
UV start, end;
invlist_iterinit(cp_list);
if (invlist_iternext(cp_list, &start, &end) && start < 256) {
ANYOF_FLAGS(ret) |= ANYOFL_FOLD;
}
invlist_iterfinish(cp_list);
}
}
else if ( DEPENDS_SEMANTICS
&& ( has_upper_latin1_only_utf8_matches
|| (ANYOF_FLAGS(ret) & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)))
{
OP(ret) = ANYOFD;
optimizable = FALSE;
}
/* Optimize inverted simple patterns (e.g. [^a-z]) when everything is known
* at compile time. Besides not inverting folded locale now, we can't
* invert if there are things such as \w, which aren't known until runtime
* */
if (cp_list
&& invert
&& OP(ret) != ANYOFD
&& ! (ANYOF_FLAGS(ret) & (ANYOF_LOCALE_FLAGS))
&& ! HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
{
_invlist_invert(cp_list);
/* Any swash can't be used as-is, because we've inverted things */
if (swash) {
SvREFCNT_dec_NN(swash);
swash = NULL;
}
/* Clear the invert flag since have just done it here */
invert = FALSE;
}
if (ret_invlist) {
assert(cp_list);
*ret_invlist = cp_list;
SvREFCNT_dec(swash);
/* Discard the generated node */
if (SIZE_ONLY) {
RExC_size = orig_size;
}
else {
RExC_emit = orig_emit;
}
return orig_emit;
}
/* Some character classes are equivalent to other nodes. Such nodes take
* up less room and generally fewer operations to execute than ANYOF nodes.
* Above, we checked for and optimized into some such equivalents for
* certain common classes that are easy to test. Getting to this point in
* the code means that the class didn't get optimized there. Since this
* code is only executed in Pass 2, it is too late to save space--it has
* been allocated in Pass 1, and currently isn't given back. But turning
* things into an EXACTish node can allow the optimizer to join it to any
* adjacent such nodes. And if the class is equivalent to things like /./,
* expensive run-time swashes can be avoided. Now that we have more
* complete information, we can find things necessarily missed by the
* earlier code. Another possible "optimization" that isn't done is that
* something like [Ee] could be changed into an EXACTFU. khw tried this
* and found that the ANYOF is faster, including for code points not in the
* bitmap. This still might make sense to do, provided it got joined with
* an adjacent node(s) to create a longer EXACTFU one. This could be
* accomplished by creating a pseudo ANYOF_EXACTFU node type that the join
* routine would know is joinable. If that didn't happen, the node type
* could then be made a straight ANYOF */
if (optimizable && cp_list && ! invert) {
UV start, end;
U8 op = END; /* The optimzation node-type */
int posix_class = -1; /* Illegal value */
const char * cur_parse= RExC_parse;
invlist_iterinit(cp_list);
if (! invlist_iternext(cp_list, &start, &end)) {
/* Here, the list is empty. This happens, for example, when a
* Unicode property that doesn't match anything is the only element
* in the character class (perluniprops.pod notes such properties).
* */
op = OPFAIL;
*flagp |= HASWIDTH|SIMPLE;
}
else if (start == end) { /* The range is a single code point */
if (! invlist_iternext(cp_list, &start, &end)
/* Don't do this optimization if it would require changing
* the pattern to UTF-8 */
&& (start < 256 || UTF))
{
/* Here, the list contains a single code point. Can optimize
* into an EXACTish node */
value = start;
if (! FOLD) {
op = (LOC)
? EXACTL
: EXACT;
}
else if (LOC) {
/* A locale node under folding with one code point can be
* an EXACTFL, as its fold won't be calculated until
* runtime */
op = EXACTFL;
}
else {
/* Here, we are generally folding, but there is only one
* code point to match. If we have to, we use an EXACT
* node, but it would be better for joining with adjacent
* nodes in the optimization pass if we used the same
* EXACTFish node that any such are likely to be. We can
* do this iff the code point doesn't participate in any
* folds. For example, an EXACTF of a colon is the same as
* an EXACT one, since nothing folds to or from a colon. */
if (value < 256) {
if (IS_IN_SOME_FOLD_L1(value)) {
op = EXACT;
}
}
else {
if (_invlist_contains_cp(PL_utf8_foldable, value)) {
op = EXACT;
}
}
/* If we haven't found the node type, above, it means we
* can use the prevailing one */
if (op == END) {
op = compute_EXACTish(pRExC_state);
}
}
}
} /* End of first range contains just a single code point */
else if (start == 0) {
if (end == UV_MAX) {
op = SANY;
*flagp |= HASWIDTH|SIMPLE;
MARK_NAUGHTY(1);
}
else if (end == '\n' - 1
&& invlist_iternext(cp_list, &start, &end)
&& start == '\n' + 1 && end == UV_MAX)
{
op = REG_ANY;
*flagp |= HASWIDTH|SIMPLE;
MARK_NAUGHTY(1);
}
}
invlist_iterfinish(cp_list);
if (op == END) {
const UV cp_list_len = _invlist_len(cp_list);
const UV* cp_list_array = invlist_array(cp_list);
/* Here, didn't find an optimization. See if this matches any of
* the POSIX classes. These run slightly faster for above-Unicode
* code points, so don't bother with POSIXA ones nor the 2 that
* have no above-Unicode matches. We can avoid these checks unless
* the ANYOF matches at least as high as the lowest POSIX one
* (which was manually found to be \v. The actual code point may
* increase in later Unicode releases, if a higher code point is
* assigned to be \v, but this code will never break. It would
* just mean we could execute the checks for posix optimizations
* unnecessarily) */
if (cp_list_array[cp_list_len-1] > 0x2029) {
for (posix_class = 0;
posix_class <= _HIGHEST_REGCOMP_DOT_H_SYNC;
posix_class++)
{
int try_inverted;
if (posix_class == _CC_ASCII || posix_class == _CC_CNTRL) {
continue;
}
for (try_inverted = 0; try_inverted < 2; try_inverted++) {
/* Check if matches normal or inverted */
if (_invlistEQ(cp_list,
PL_XPosix_ptrs[posix_class],
try_inverted))
{
op = (try_inverted)
? NPOSIXU
: POSIXU;
*flagp |= HASWIDTH|SIMPLE;
goto found_posix;
}
}
}
found_posix: ;
}
}
if (op != END) {
RExC_parse = (char *)orig_parse;
RExC_emit = (regnode *)orig_emit;
if (regarglen[op]) {
ret = reganode(pRExC_state, op, 0);
} else {
ret = reg_node(pRExC_state, op);
}
RExC_parse = (char *)cur_parse;
if (PL_regkind[op] == EXACT) {
alloc_maybe_populate_EXACT(pRExC_state, ret, flagp, 0, value,
TRUE /* downgradable to EXACT */
);
}
else if (PL_regkind[op] == POSIXD || PL_regkind[op] == NPOSIXD) {
FLAGS(ret) = posix_class;
}
SvREFCNT_dec_NN(cp_list);
return ret;
}
}
/* Here, <cp_list> contains all the code points we can determine at
* compile time that match under all conditions. Go through it, and
* for things that belong in the bitmap, put them there, and delete from
* <cp_list>. While we are at it, see if everything above 255 is in the
* list, and if so, set a flag to speed up execution */
populate_ANYOF_from_invlist(ret, &cp_list);
if (invert) {
ANYOF_FLAGS(ret) |= ANYOF_INVERT;
}
/* Here, the bitmap has been populated with all the Latin1 code points that
* always match. Can now add to the overall list those that match only
* when the target string is UTF-8 (<has_upper_latin1_only_utf8_matches>).
* */
if (has_upper_latin1_only_utf8_matches) {
if (cp_list) {
_invlist_union(cp_list,
has_upper_latin1_only_utf8_matches,
&cp_list);
SvREFCNT_dec_NN(has_upper_latin1_only_utf8_matches);
}
else {
cp_list = has_upper_latin1_only_utf8_matches;
}
ANYOF_FLAGS(ret) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
}
/* If there is a swash and more than one element, we can't use the swash in
* the optimization below. */
if (swash && element_count > 1) {
SvREFCNT_dec_NN(swash);
swash = NULL;
}
/* Note that the optimization of using 'swash' if it is the only thing in
* the class doesn't have us change swash at all, so it can include things
* that are also in the bitmap; otherwise we have purposely deleted that
* duplicate information */
set_ANYOF_arg(pRExC_state, ret, cp_list,
(HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
? listsv : NULL,
only_utf8_locale_list,
swash, has_user_defined_property);
*flagp |= HASWIDTH|SIMPLE;
if (ANYOF_FLAGS(ret) & ANYOF_LOCALE_FLAGS) {
RExC_contains_locale = 1;
}
return ret;
}
#undef HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION
STATIC void
S_set_ANYOF_arg(pTHX_ RExC_state_t* const pRExC_state,
regnode* const node,
SV* const cp_list,
SV* const runtime_defns,
SV* const only_utf8_locale_list,
SV* const swash,
const bool has_user_defined_property)
{
/* Sets the arg field of an ANYOF-type node 'node', using information about
* the node passed-in. If there is nothing outside the node's bitmap, the
* arg is set to ANYOF_ONLY_HAS_BITMAP. Otherwise, it sets the argument to
* the count returned by add_data(), having allocated and stored an array,
* av, that that count references, as follows:
* av[0] stores the character class description in its textual form.
* This is used later (regexec.c:Perl_regclass_swash()) to
* initialize the appropriate swash, and is also useful for dumping
* the regnode. This is set to &PL_sv_undef if the textual
* description is not needed at run-time (as happens if the other
* elements completely define the class)
* av[1] if &PL_sv_undef, is a placeholder to later contain the swash
* computed from av[0]. But if no further computation need be done,
* the swash is stored here now (and av[0] is &PL_sv_undef).
* av[2] stores the inversion list of code points that match only if the
* current locale is UTF-8
* av[3] stores the cp_list inversion list for use in addition or instead
* of av[0]; used only if cp_list exists and av[1] is &PL_sv_undef.
* (Otherwise everything needed is already in av[0] and av[1])
* av[4] is set if any component of the class is from a user-defined
* property; used only if av[3] exists */
UV n;
PERL_ARGS_ASSERT_SET_ANYOF_ARG;
if (! cp_list && ! runtime_defns && ! only_utf8_locale_list) {
assert(! (ANYOF_FLAGS(node)
& ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP));
ARG_SET(node, ANYOF_ONLY_HAS_BITMAP);
}
else {
AV * const av = newAV();
SV *rv;
av_store(av, 0, (runtime_defns)
? SvREFCNT_inc(runtime_defns) : &PL_sv_undef);
if (swash) {
assert(cp_list);
av_store(av, 1, swash);
SvREFCNT_dec_NN(cp_list);
}
else {
av_store(av, 1, &PL_sv_undef);
if (cp_list) {
av_store(av, 3, cp_list);
av_store(av, 4, newSVuv(has_user_defined_property));
}
}
if (only_utf8_locale_list) {
av_store(av, 2, only_utf8_locale_list);
}
else {
av_store(av, 2, &PL_sv_undef);
}
rv = newRV_noinc(MUTABLE_SV(av));
n = add_data(pRExC_state, STR_WITH_LEN("s"));
RExC_rxi->data->data[n] = (void*)rv;
ARG_SET(node, n);
}
}
#if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
SV *
Perl__get_regclass_nonbitmap_data(pTHX_ const regexp *prog,
const regnode* node,
bool doinit,
SV** listsvp,
SV** only_utf8_locale_ptr,
SV** output_invlist)
{
/* For internal core use only.
* Returns the swash for the input 'node' in the regex 'prog'.
* If <doinit> is 'true', will attempt to create the swash if not already
* done.
* If <listsvp> is non-null, will return the printable contents of the
* swash. This can be used to get debugging information even before the
* swash exists, by calling this function with 'doinit' set to false, in
* which case the components that will be used to eventually create the
* swash are returned (in a printable form).
* If <only_utf8_locale_ptr> is not NULL, it is where this routine is to
* store an inversion list of code points that should match only if the
* execution-time locale is a UTF-8 one.
* If <output_invlist> is not NULL, it is where this routine is to store an
* inversion list of the code points that would be instead returned in
* <listsvp> if this were NULL. Thus, what gets output in <listsvp>
* when this parameter is used, is just the non-code point data that
* will go into creating the swash. This currently should be just
* user-defined properties whose definitions were not known at compile
* time. Using this parameter allows for easier manipulation of the
* swash's data by the caller. It is illegal to call this function with
* this parameter set, but not <listsvp>
*
* Tied intimately to how S_set_ANYOF_arg sets up the data structure. Note
* that, in spite of this function's name, the swash it returns may include
* the bitmap data as well */
SV *sw = NULL;
SV *si = NULL; /* Input swash initialization string */
SV* invlist = NULL;
RXi_GET_DECL(prog,progi);
const struct reg_data * const data = prog ? progi->data : NULL;
PERL_ARGS_ASSERT__GET_REGCLASS_NONBITMAP_DATA;
assert(! output_invlist || listsvp);
if (data && data->count) {
const U32 n = ARG(node);
if (data->what[n] == 's') {
SV * const rv = MUTABLE_SV(data->data[n]);
AV * const av = MUTABLE_AV(SvRV(rv));
SV **const ary = AvARRAY(av);
U8 swash_init_flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
si = *ary; /* ary[0] = the string to initialize the swash with */
if (av_tindex_skip_len_mg(av) >= 2) {
if (only_utf8_locale_ptr
&& ary[2]
&& ary[2] != &PL_sv_undef)
{
*only_utf8_locale_ptr = ary[2];
}
else {
assert(only_utf8_locale_ptr);
*only_utf8_locale_ptr = NULL;
}
/* Elements 3 and 4 are either both present or both absent. [3]
* is any inversion list generated at compile time; [4]
* indicates if that inversion list has any user-defined
* properties in it. */
if (av_tindex_skip_len_mg(av) >= 3) {
invlist = ary[3];
if (SvUV(ary[4])) {
swash_init_flags |= _CORE_SWASH_INIT_USER_DEFINED_PROPERTY;
}
}
else {
invlist = NULL;
}
}
/* Element [1] is reserved for the set-up swash. If already there,
* return it; if not, create it and store it there */
if (ary[1] && SvROK(ary[1])) {
sw = ary[1];
}
else if (doinit && ((si && si != &PL_sv_undef)
|| (invlist && invlist != &PL_sv_undef))) {
assert(si);
sw = _core_swash_init("utf8", /* the utf8 package */
"", /* nameless */
si,
1, /* binary */
0, /* not from tr/// */
invlist,
&swash_init_flags);
(void)av_store(av, 1, sw);
}
}
}
/* If requested, return a printable version of what this swash matches */
if (listsvp) {
SV* matches_string = NULL;
/* The swash should be used, if possible, to get the data, as it
* contains the resolved data. But this function can be called at
* compile-time, before everything gets resolved, in which case we
* return the currently best available information, which is the string
* that will eventually be used to do that resolving, 'si' */
if ((! sw || (invlist = _get_swash_invlist(sw)) == NULL)
&& (si && si != &PL_sv_undef))
{
/* Here, we only have 'si' (and possibly some passed-in data in
* 'invlist', which is handled below) If the caller only wants
* 'si', use that. */
if (! output_invlist) {
matches_string = newSVsv(si);
}
else {
/* But if the caller wants an inversion list of the node, we
* need to parse 'si' and place as much as possible in the
* desired output inversion list, making 'matches_string' only
* contain the currently unresolvable things */
const char *si_string = SvPVX(si);
STRLEN remaining = SvCUR(si);
UV prev_cp = 0;
U8 count = 0;
/* Ignore everything before the first new-line */
while (*si_string != '\n' && remaining > 0) {
si_string++;
remaining--;
}
assert(remaining > 0);
si_string++;
remaining--;
while (remaining > 0) {
/* The data consists of just strings defining user-defined
* property names, but in prior incarnations, and perhaps
* somehow from pluggable regex engines, it could still
* hold hex code point definitions. Each component of a
* range would be separated by a tab, and each range by a
* new-line. If these are found, instead add them to the
* inversion list */
I32 grok_flags = PERL_SCAN_SILENT_ILLDIGIT
|PERL_SCAN_SILENT_NON_PORTABLE;
STRLEN len = remaining;
UV cp = grok_hex(si_string, &len, &grok_flags, NULL);
/* If the hex decode routine found something, it should go
* up to the next \n */
if ( *(si_string + len) == '\n') {
if (count) { /* 2nd code point on line */
*output_invlist = _add_range_to_invlist(*output_invlist, prev_cp, cp);
}
else {
*output_invlist = add_cp_to_invlist(*output_invlist, cp);
}
count = 0;
goto prepare_for_next_iteration;
}
/* If the hex decode was instead for the lower range limit,
* save it, and go parse the upper range limit */
if (*(si_string + len) == '\t') {
assert(count == 0);
prev_cp = cp;
count = 1;
prepare_for_next_iteration:
si_string += len + 1;
remaining -= len + 1;
continue;
}
/* Here, didn't find a legal hex number. Just add it from
* here to the next \n */
remaining -= len;
while (*(si_string + len) != '\n' && remaining > 0) {
remaining--;
len++;
}
if (*(si_string + len) == '\n') {
len++;
remaining--;
}
if (matches_string) {
sv_catpvn(matches_string, si_string, len - 1);
}
else {
matches_string = newSVpvn(si_string, len - 1);
}
si_string += len;
sv_catpvs(matches_string, " ");
} /* end of loop through the text */
assert(matches_string);
if (SvCUR(matches_string)) { /* Get rid of trailing blank */
SvCUR_set(matches_string, SvCUR(matches_string) - 1);
}
} /* end of has an 'si' but no swash */
}
/* If we have a swash in place, its equivalent inversion list was above
* placed into 'invlist'. If not, this variable may contain a stored
* inversion list which is information beyond what is in 'si' */
if (invlist) {
/* Again, if the caller doesn't want the output inversion list, put
* everything in 'matches-string' */
if (! output_invlist) {
if ( ! matches_string) {
matches_string = newSVpvs("\n");
}
sv_catsv(matches_string, invlist_contents(invlist,
TRUE /* traditional style */
));
}
else if (! *output_invlist) {
*output_invlist = invlist_clone(invlist);
}
else {
_invlist_union(*output_invlist, invlist, output_invlist);
}
}
*listsvp = matches_string;
}
return sw;
}
#endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
/* reg_skipcomment()
Absorbs an /x style # comment from the input stream,
returning a pointer to the first character beyond the comment, or if the
comment terminates the pattern without anything following it, this returns
one past the final character of the pattern (in other words, RExC_end) and
sets the REG_RUN_ON_COMMENT_SEEN flag.
Note it's the callers responsibility to ensure that we are
actually in /x mode
*/
PERL_STATIC_INLINE char*
S_reg_skipcomment(RExC_state_t *pRExC_state, char* p)
{
PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
assert(*p == '#');
while (p < RExC_end) {
if (*(++p) == '\n') {
return p+1;
}
}
/* we ran off the end of the pattern without ending the comment, so we have
* to add an \n when wrapping */
RExC_seen |= REG_RUN_ON_COMMENT_SEEN;
return p;
}
STATIC void
S_skip_to_be_ignored_text(pTHX_ RExC_state_t *pRExC_state,
char ** p,
const bool force_to_xmod
)
{
/* If the text at the current parse position '*p' is a '(?#...)' comment,
* or if we are under /x or 'force_to_xmod' is TRUE, and the text at '*p'
* is /x whitespace, advance '*p' so that on exit it points to the first
* byte past all such white space and comments */
const bool use_xmod = force_to_xmod || (RExC_flags & RXf_PMf_EXTENDED);
PERL_ARGS_ASSERT_SKIP_TO_BE_IGNORED_TEXT;
assert( ! UTF || UTF8_IS_INVARIANT(**p) || UTF8_IS_START(**p));
for (;;) {
if (RExC_end - (*p) >= 3
&& *(*p) == '('
&& *(*p + 1) == '?'
&& *(*p + 2) == '#')
{
while (*(*p) != ')') {
if ((*p) == RExC_end)
FAIL("Sequence (?#... not terminated");
(*p)++;
}
(*p)++;
continue;
}
if (use_xmod) {
const char * save_p = *p;
while ((*p) < RExC_end) {
STRLEN len;
if ((len = is_PATWS_safe((*p), RExC_end, UTF))) {
(*p) += len;
}
else if (*(*p) == '#') {
(*p) = reg_skipcomment(pRExC_state, (*p));
}
else {
break;
}
}
if (*p != save_p) {
continue;
}
}
break;
}
return;
}
/* nextchar()
Advances the parse position by one byte, unless that byte is the beginning
of a '(?#...)' style comment, or is /x whitespace and /x is in effect. In
those two cases, the parse position is advanced beyond all such comments and
white space.
This is the UTF, (?#...), and /x friendly way of saying RExC_parse++.
*/
STATIC void
S_nextchar(pTHX_ RExC_state_t *pRExC_state)
{
PERL_ARGS_ASSERT_NEXTCHAR;
if (RExC_parse < RExC_end) {
assert( ! UTF
|| UTF8_IS_INVARIANT(*RExC_parse)
|| UTF8_IS_START(*RExC_parse));
RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
skip_to_be_ignored_text(pRExC_state, &RExC_parse,
FALSE /* Don't force /x */ );
}
}
STATIC regnode *
S_regnode_guts(pTHX_ RExC_state_t *pRExC_state, const U8 op, const STRLEN extra_size, const char* const name)
{
/* Allocate a regnode for 'op' and returns it, with 'extra_size' extra
* space. In pass1, it aligns and increments RExC_size; in pass2,
* RExC_emit */
regnode * const ret = RExC_emit;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGNODE_GUTS;
assert(extra_size >= regarglen[op]);
if (SIZE_ONLY) {
SIZE_ALIGN(RExC_size);
RExC_size += 1 + extra_size;
return(ret);
}
if (RExC_emit >= RExC_emit_bound)
Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %d, %p>=%p",
op, (void*)RExC_emit, (void*)RExC_emit_bound);
NODE_ALIGN_FILL(ret);
#ifndef RE_TRACK_PATTERN_OFFSETS
PERL_UNUSED_ARG(name);
#else
if (RExC_offsets) { /* MJD */
MJD_OFFSET_DEBUG(
("%s:%d: (op %s) %s %" UVuf " (len %" UVuf ") (max %" UVuf ").\n",
name, __LINE__,
PL_reg_name[op],
(UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0]
? "Overwriting end of array!\n" : "OK",
(UV)(RExC_emit - RExC_emit_start),
(UV)(RExC_parse - RExC_start),
(UV)RExC_offsets[0]));
Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
}
#endif
return(ret);
}
/*
- reg_node - emit a node
*/
STATIC regnode * /* Location. */
S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
{
regnode * const ret = regnode_guts(pRExC_state, op, regarglen[op], "reg_node");
PERL_ARGS_ASSERT_REG_NODE;
assert(regarglen[op] == 0);
if (PASS2) {
regnode *ptr = ret;
FILL_ADVANCE_NODE(ptr, op);
RExC_emit = ptr;
}
return(ret);
}
/*
- reganode - emit a node with an argument
*/
STATIC regnode * /* Location. */
S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
{
regnode * const ret = regnode_guts(pRExC_state, op, regarglen[op], "reganode");
PERL_ARGS_ASSERT_REGANODE;
assert(regarglen[op] == 1);
if (PASS2) {
regnode *ptr = ret;
FILL_ADVANCE_NODE_ARG(ptr, op, arg);
RExC_emit = ptr;
}
return(ret);
}
STATIC regnode *
S_reg2Lanode(pTHX_ RExC_state_t *pRExC_state, const U8 op, const U32 arg1, const I32 arg2)
{
/* emit a node with U32 and I32 arguments */
regnode * const ret = regnode_guts(pRExC_state, op, regarglen[op], "reg2Lanode");
PERL_ARGS_ASSERT_REG2LANODE;
assert(regarglen[op] == 2);
if (PASS2) {
regnode *ptr = ret;
FILL_ADVANCE_NODE_2L_ARG(ptr, op, arg1, arg2);
RExC_emit = ptr;
}
return(ret);
}
/*
- reginsert - insert an operator in front of already-emitted operand
*
* Means relocating the operand.
*
* IMPORTANT NOTE - it is the *callers* responsibility to correctly
* set up NEXT_OFF() of the inserted node if needed. Something like this:
*
* reginsert(pRExC, OPFAIL, orig_emit, depth+1);
* if (PASS2)
* NEXT_OFF(orig_emit) = regarglen[OPFAIL] + NODE_STEP_REGNODE;
*
* ALSO NOTE - operand->flags will be set to 0 as well.
*/
STATIC void
S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *operand, U32 depth)
{
regnode *src;
regnode *dst;
regnode *place;
const int offset = regarglen[(U8)op];
const int size = NODE_STEP_REGNODE + offset;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGINSERT;
PERL_UNUSED_CONTEXT;
PERL_UNUSED_ARG(depth);
/* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
DEBUG_PARSE_FMT("inst"," - %s",PL_reg_name[op]);
if (SIZE_ONLY) {
RExC_size += size;
return;
}
assert(!RExC_study_started); /* I believe we should never use reginsert once we have started
studying. If this is wrong then we need to adjust RExC_recurse
below like we do with RExC_open_parens/RExC_close_parens. */
src = RExC_emit;
RExC_emit += size;
dst = RExC_emit;
if (RExC_open_parens) {
int paren;
/*DEBUG_PARSE_FMT("inst"," - %" IVdf, (IV)RExC_npar);*/
/* remember that RExC_npar is rex->nparens + 1,
* iow it is 1 more than the number of parens seen in
* the pattern so far. */
for ( paren=0 ; paren < RExC_npar ; paren++ ) {
/* note, RExC_open_parens[0] is the start of the
* regex, it can't move. RExC_close_parens[0] is the end
* of the regex, it *can* move. */
if ( paren && RExC_open_parens[paren] >= operand ) {
/*DEBUG_PARSE_FMT("open"," - %d",size);*/
RExC_open_parens[paren] += size;
} else {
/*DEBUG_PARSE_FMT("open"," - %s","ok");*/
}
if ( RExC_close_parens[paren] >= operand ) {
/*DEBUG_PARSE_FMT("close"," - %d",size);*/
RExC_close_parens[paren] += size;
} else {
/*DEBUG_PARSE_FMT("close"," - %s","ok");*/
}
}
}
if (RExC_end_op)
RExC_end_op += size;
while (src > operand) {
StructCopy(--src, --dst, regnode);
#ifdef RE_TRACK_PATTERN_OFFSETS
if (RExC_offsets) { /* MJD 20010112 */
MJD_OFFSET_DEBUG(
("%s(%d): (op %s) %s copy %" UVuf " -> %" UVuf " (max %" UVuf ").\n",
"reg_insert",
__LINE__,
PL_reg_name[op],
(UV)(dst - RExC_emit_start) > RExC_offsets[0]
? "Overwriting end of array!\n" : "OK",
(UV)(src - RExC_emit_start),
(UV)(dst - RExC_emit_start),
(UV)RExC_offsets[0]));
Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
}
#endif
}
place = operand; /* Op node, where operand used to be. */
#ifdef RE_TRACK_PATTERN_OFFSETS
if (RExC_offsets) { /* MJD */
MJD_OFFSET_DEBUG(
("%s(%d): (op %s) %s %" UVuf " <- %" UVuf " (max %" UVuf ").\n",
"reginsert",
__LINE__,
PL_reg_name[op],
(UV)(place - RExC_emit_start) > RExC_offsets[0]
? "Overwriting end of array!\n" : "OK",
(UV)(place - RExC_emit_start),
(UV)(RExC_parse - RExC_start),
(UV)RExC_offsets[0]));
Set_Node_Offset(place, RExC_parse);
Set_Node_Length(place, 1);
}
#endif
src = NEXTOPER(place);
place->flags = 0;
FILL_ADVANCE_NODE(place, op);
Zero(src, offset, regnode);
}
/*
- regtail - set the next-pointer at the end of a node chain of p to val.
- SEE ALSO: regtail_study
*/
STATIC void
S_regtail(pTHX_ RExC_state_t * pRExC_state,
const regnode * const p,
const regnode * const val,
const U32 depth)
{
regnode *scan;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGTAIL;
#ifndef DEBUGGING
PERL_UNUSED_ARG(depth);
#endif
if (SIZE_ONLY)
return;
/* Find last node. */
scan = (regnode *) p;
for (;;) {
regnode * const temp = regnext(scan);
DEBUG_PARSE_r({
DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
Perl_re_printf( aTHX_ "~ %s (%d) %s %s\n",
SvPV_nolen_const(RExC_mysv), REG_NODE_NUM(scan),
(temp == NULL ? "->" : ""),
(temp == NULL ? PL_reg_name[OP(val)] : "")
);
});
if (temp == NULL)
break;
scan = temp;
}
if (reg_off_by_arg[OP(scan)]) {
ARG_SET(scan, val - scan);
}
else {
NEXT_OFF(scan) = val - scan;
}
}
#ifdef DEBUGGING
/*
- regtail_study - set the next-pointer at the end of a node chain of p to val.
- Look for optimizable sequences at the same time.
- currently only looks for EXACT chains.
This is experimental code. The idea is to use this routine to perform
in place optimizations on branches and groups as they are constructed,
with the long term intention of removing optimization from study_chunk so
that it is purely analytical.
Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
to control which is which.
*/
/* TODO: All four parms should be const */
STATIC U8
S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode *p,
const regnode *val,U32 depth)
{
regnode *scan;
U8 exact = PSEUDO;
#ifdef EXPERIMENTAL_INPLACESCAN
I32 min = 0;
#endif
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGTAIL_STUDY;
if (SIZE_ONLY)
return exact;
/* Find last node. */
scan = p;
for (;;) {
regnode * const temp = regnext(scan);
#ifdef EXPERIMENTAL_INPLACESCAN
if (PL_regkind[OP(scan)] == EXACT) {
bool unfolded_multi_char; /* Unexamined in this routine */
if (join_exact(pRExC_state, scan, &min,
&unfolded_multi_char, 1, val, depth+1))
return EXACT;
}
#endif
if ( exact ) {
switch (OP(scan)) {
case EXACT:
case EXACTL:
case EXACTF:
case EXACTFA_NO_TRIE:
case EXACTFA:
case EXACTFU:
case EXACTFLU8:
case EXACTFU_SS:
case EXACTFL:
if( exact == PSEUDO )
exact= OP(scan);
else if ( exact != OP(scan) )
exact= 0;
case NOTHING:
break;
default:
exact= 0;
}
}
DEBUG_PARSE_r({
DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
Perl_re_printf( aTHX_ "~ %s (%d) -> %s\n",
SvPV_nolen_const(RExC_mysv),
REG_NODE_NUM(scan),
PL_reg_name[exact]);
});
if (temp == NULL)
break;
scan = temp;
}
DEBUG_PARSE_r({
DEBUG_PARSE_MSG("");
regprop(RExC_rx, RExC_mysv, val, NULL, pRExC_state);
Perl_re_printf( aTHX_
"~ attach to %s (%" IVdf ") offset to %" IVdf "\n",
SvPV_nolen_const(RExC_mysv),
(IV)REG_NODE_NUM(val),
(IV)(val - scan)
);
});
if (reg_off_by_arg[OP(scan)]) {
ARG_SET(scan, val - scan);
}
else {
NEXT_OFF(scan) = val - scan;
}
return exact;
}
#endif
/*
- regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
*/
#ifdef DEBUGGING
static void
S_regdump_intflags(pTHX_ const char *lead, const U32 flags)
{
int bit;
int set=0;
ASSUME(REG_INTFLAGS_NAME_SIZE <= sizeof(flags)*8);
for (bit=0; bit<REG_INTFLAGS_NAME_SIZE; bit++) {
if (flags & (1<<bit)) {
if (!set++ && lead)
Perl_re_printf( aTHX_ "%s",lead);
Perl_re_printf( aTHX_ "%s ",PL_reg_intflags_name[bit]);
}
}
if (lead) {
if (set)
Perl_re_printf( aTHX_ "\n");
else
Perl_re_printf( aTHX_ "%s[none-set]\n",lead);
}
}
static void
S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
{
int bit;
int set=0;
regex_charset cs;
ASSUME(REG_EXTFLAGS_NAME_SIZE <= sizeof(flags)*8);
for (bit=0; bit<REG_EXTFLAGS_NAME_SIZE; bit++) {
if (flags & (1<<bit)) {
if ((1<<bit) & RXf_PMf_CHARSET) { /* Output separately, below */
continue;
}
if (!set++ && lead)
Perl_re_printf( aTHX_ "%s",lead);
Perl_re_printf( aTHX_ "%s ",PL_reg_extflags_name[bit]);
}
}
if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) {
if (!set++ && lead) {
Perl_re_printf( aTHX_ "%s",lead);
}
switch (cs) {
case REGEX_UNICODE_CHARSET:
Perl_re_printf( aTHX_ "UNICODE");
break;
case REGEX_LOCALE_CHARSET:
Perl_re_printf( aTHX_ "LOCALE");
break;
case REGEX_ASCII_RESTRICTED_CHARSET:
Perl_re_printf( aTHX_ "ASCII-RESTRICTED");
break;
case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
Perl_re_printf( aTHX_ "ASCII-MORE_RESTRICTED");
break;
default:
Perl_re_printf( aTHX_ "UNKNOWN CHARACTER SET");
break;
}
}
if (lead) {
if (set)
Perl_re_printf( aTHX_ "\n");
else
Perl_re_printf( aTHX_ "%s[none-set]\n",lead);
}
}
#endif
void
Perl_regdump(pTHX_ const regexp *r)
{
#ifdef DEBUGGING
int i;
SV * const sv = sv_newmortal();
SV *dsv= sv_newmortal();
RXi_GET_DECL(r,ri);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGDUMP;
(void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
/* Header fields of interest. */
for (i = 0; i < 2; i++) {
if (r->substrs->data[i].substr) {
RE_PV_QUOTED_DECL(s, 0, dsv,
SvPVX_const(r->substrs->data[i].substr),
RE_SV_DUMPLEN(r->substrs->data[i].substr),
PL_dump_re_max_len);
Perl_re_printf( aTHX_
"%s %s%s at %" IVdf "..%" UVuf " ",
i ? "floating" : "anchored",
s,
RE_SV_TAIL(r->substrs->data[i].substr),
(IV)r->substrs->data[i].min_offset,
(UV)r->substrs->data[i].max_offset);
}
else if (r->substrs->data[i].utf8_substr) {
RE_PV_QUOTED_DECL(s, 1, dsv,
SvPVX_const(r->substrs->data[i].utf8_substr),
RE_SV_DUMPLEN(r->substrs->data[i].utf8_substr),
30);
Perl_re_printf( aTHX_
"%s utf8 %s%s at %" IVdf "..%" UVuf " ",
i ? "floating" : "anchored",
s,
RE_SV_TAIL(r->substrs->data[i].utf8_substr),
(IV)r->substrs->data[i].min_offset,
(UV)r->substrs->data[i].max_offset);
}
}
if (r->check_substr || r->check_utf8)
Perl_re_printf( aTHX_
(const char *)
( r->check_substr == r->substrs->data[1].substr
&& r->check_utf8 == r->substrs->data[1].utf8_substr
? "(checking floating" : "(checking anchored"));
if (r->intflags & PREGf_NOSCAN)
Perl_re_printf( aTHX_ " noscan");
if (r->extflags & RXf_CHECK_ALL)
Perl_re_printf( aTHX_ " isall");
if (r->check_substr || r->check_utf8)
Perl_re_printf( aTHX_ ") ");
if (ri->regstclass) {
regprop(r, sv, ri->regstclass, NULL, NULL);
Perl_re_printf( aTHX_ "stclass %s ", SvPVX_const(sv));
}
if (r->intflags & PREGf_ANCH) {
Perl_re_printf( aTHX_ "anchored");
if (r->intflags & PREGf_ANCH_MBOL)
Perl_re_printf( aTHX_ "(MBOL)");
if (r->intflags & PREGf_ANCH_SBOL)
Perl_re_printf( aTHX_ "(SBOL)");
if (r->intflags & PREGf_ANCH_GPOS)
Perl_re_printf( aTHX_ "(GPOS)");
Perl_re_printf( aTHX_ " ");
}
if (r->intflags & PREGf_GPOS_SEEN)
Perl_re_printf( aTHX_ "GPOS:%" UVuf " ", (UV)r->gofs);
if (r->intflags & PREGf_SKIP)
Perl_re_printf( aTHX_ "plus ");
if (r->intflags & PREGf_IMPLICIT)
Perl_re_printf( aTHX_ "implicit ");
Perl_re_printf( aTHX_ "minlen %" IVdf " ", (IV)r->minlen);
if (r->extflags & RXf_EVAL_SEEN)
Perl_re_printf( aTHX_ "with eval ");
Perl_re_printf( aTHX_ "\n");
DEBUG_FLAGS_r({
regdump_extflags("r->extflags: ",r->extflags);
regdump_intflags("r->intflags: ",r->intflags);
});
#else
PERL_ARGS_ASSERT_REGDUMP;
PERL_UNUSED_CONTEXT;
PERL_UNUSED_ARG(r);
#endif /* DEBUGGING */
}
/* Should be synchronized with ANYOF_ #defines in regcomp.h */
#ifdef DEBUGGING
# if _CC_WORDCHAR != 0 || _CC_DIGIT != 1 || _CC_ALPHA != 2 \
|| _CC_LOWER != 3 || _CC_UPPER != 4 || _CC_PUNCT != 5 \
|| _CC_PRINT != 6 || _CC_ALPHANUMERIC != 7 || _CC_GRAPH != 8 \
|| _CC_CASED != 9 || _CC_SPACE != 10 || _CC_BLANK != 11 \
|| _CC_XDIGIT != 12 || _CC_CNTRL != 13 || _CC_ASCII != 14 \
|| _CC_VERTSPACE != 15
# error Need to adjust order of anyofs[]
# endif
static const char * const anyofs[] = {
"\\w",
"\\W",
"\\d",
"\\D",
"[:alpha:]",
"[:^alpha:]",
"[:lower:]",
"[:^lower:]",
"[:upper:]",
"[:^upper:]",
"[:punct:]",
"[:^punct:]",
"[:print:]",
"[:^print:]",
"[:alnum:]",
"[:^alnum:]",
"[:graph:]",
"[:^graph:]",
"[:cased:]",
"[:^cased:]",
"\\s",
"\\S",
"[:blank:]",
"[:^blank:]",
"[:xdigit:]",
"[:^xdigit:]",
"[:cntrl:]",
"[:^cntrl:]",
"[:ascii:]",
"[:^ascii:]",
"\\v",
"\\V"
};
#endif
/*
- regprop - printable representation of opcode, with run time support
*/
void
Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o, const regmatch_info *reginfo, const RExC_state_t *pRExC_state)
{
#ifdef DEBUGGING
int k;
RXi_GET_DECL(prog,progi);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGPROP;
SvPVCLEAR(sv);
if (OP(o) > REGNODE_MAX) /* regnode.type is unsigned */
/* It would be nice to FAIL() here, but this may be called from
regexec.c, and it would be hard to supply pRExC_state. */
Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
(int)OP(o), (int)REGNODE_MAX);
sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
k = PL_regkind[OP(o)];
if (k == EXACT) {
sv_catpvs(sv, " ");
/* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
* is a crude hack but it may be the best for now since
* we have no flag "this EXACTish node was UTF-8"
* --jhi */
pv_pretty(sv, STRING(o), STR_LEN(o), PL_dump_re_max_len,
PL_colors[0], PL_colors[1],
PERL_PV_ESCAPE_UNI_DETECT |
PERL_PV_ESCAPE_NONASCII |
PERL_PV_PRETTY_ELLIPSES |
PERL_PV_PRETTY_LTGT |
PERL_PV_PRETTY_NOCLEAR
);
} else if (k == TRIE) {
/* print the details of the trie in dumpuntil instead, as
* progi->data isn't available here */
const char op = OP(o);
const U32 n = ARG(o);
const reg_ac_data * const ac = IS_TRIE_AC(op) ?
(reg_ac_data *)progi->data->data[n] :
NULL;
const reg_trie_data * const trie
= (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
Perl_sv_catpvf(aTHX_ sv, "-%s",PL_reg_name[o->flags]);
DEBUG_TRIE_COMPILE_r({
if (trie->jump)
sv_catpvs(sv, "(JUMP)");
Perl_sv_catpvf(aTHX_ sv,
"<S:%" UVuf "/%" IVdf " W:%" UVuf " L:%" UVuf "/%" UVuf " C:%" UVuf "/%" UVuf ">",
(UV)trie->startstate,
(IV)trie->statecount-1, /* -1 because of the unused 0 element */
(UV)trie->wordcount,
(UV)trie->minlen,
(UV)trie->maxlen,
(UV)TRIE_CHARCOUNT(trie),
(UV)trie->uniquecharcount
);
});
if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
sv_catpvs(sv, "[");
(void) put_charclass_bitmap_innards(sv,
((IS_ANYOF_TRIE(op))
? ANYOF_BITMAP(o)
: TRIE_BITMAP(trie)),
NULL,
NULL,
NULL,
FALSE
);
sv_catpvs(sv, "]");
}
} else if (k == CURLY) {
U32 lo = ARG1(o), hi = ARG2(o);
if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
Perl_sv_catpvf(aTHX_ sv, "{%u,", (unsigned) lo);
if (hi == REG_INFTY)
sv_catpvs(sv, "INFTY");
else
Perl_sv_catpvf(aTHX_ sv, "%u", (unsigned) hi);
sv_catpvs(sv, "}");
}
else if (k == WHILEM && o->flags) /* Ordinal/of */
Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
else if (k == REF || k == OPEN || k == CLOSE
|| k == GROUPP || OP(o)==ACCEPT)
{
AV *name_list= NULL;
U32 parno= OP(o) == ACCEPT ? (U32)ARG2L(o) : ARG(o);
Perl_sv_catpvf(aTHX_ sv, "%" UVuf, (UV)parno); /* Parenth number */
if ( RXp_PAREN_NAMES(prog) ) {
name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
} else if ( pRExC_state ) {
name_list= RExC_paren_name_list;
}
if (name_list) {
if ( k != REF || (OP(o) < NREF)) {
SV **name= av_fetch(name_list, parno, 0 );
if (name)
Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
}
else {
SV *sv_dat= MUTABLE_SV(progi->data->data[ parno ]);
I32 *nums=(I32*)SvPVX(sv_dat);
SV **name= av_fetch(name_list, nums[0], 0 );
I32 n;
if (name) {
for ( n=0; n<SvIVX(sv_dat); n++ ) {
Perl_sv_catpvf(aTHX_ sv, "%s%" IVdf,
(n ? "," : ""), (IV)nums[n]);
}
Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
}
}
}
if ( k == REF && reginfo) {
U32 n = ARG(o); /* which paren pair */
I32 ln = prog->offs[n].start;
if (prog->lastparen < n || ln == -1)
Perl_sv_catpvf(aTHX_ sv, ": FAIL");
else if (ln == prog->offs[n].end)
Perl_sv_catpvf(aTHX_ sv, ": ACCEPT - EMPTY STRING");
else {
const char *s = reginfo->strbeg + ln;
Perl_sv_catpvf(aTHX_ sv, ": ");
Perl_pv_pretty( aTHX_ sv, s, prog->offs[n].end - prog->offs[n].start, 32, 0, 0,
PERL_PV_ESCAPE_UNI_DETECT|PERL_PV_PRETTY_NOCLEAR|PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE );
}
}
} else if (k == GOSUB) {
AV *name_list= NULL;
if ( RXp_PAREN_NAMES(prog) ) {
name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
} else if ( pRExC_state ) {
name_list= RExC_paren_name_list;
}
/* Paren and offset */
Perl_sv_catpvf(aTHX_ sv, "%d[%+d:%d]", (int)ARG(o),(int)ARG2L(o),
(int)((o + (int)ARG2L(o)) - progi->program) );
if (name_list) {
SV **name= av_fetch(name_list, ARG(o), 0 );
if (name)
Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
}
}
else if (k == LOGICAL)
/* 2: embedded, otherwise 1 */
Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);
else if (k == ANYOF) {
const U8 flags = ANYOF_FLAGS(o);
bool do_sep = FALSE; /* Do we need to separate various components of
the output? */
/* Set if there is still an unresolved user-defined property */
SV *unresolved = NULL;
/* Things that are ignored except when the runtime locale is UTF-8 */
SV *only_utf8_locale_invlist = NULL;
/* Code points that don't fit in the bitmap */
SV *nonbitmap_invlist = NULL;
/* And things that aren't in the bitmap, but are small enough to be */
SV* bitmap_range_not_in_bitmap = NULL;
const bool inverted = flags & ANYOF_INVERT;
if (OP(o) == ANYOFL) {
if (ANYOFL_UTF8_LOCALE_REQD(flags)) {
sv_catpvs(sv, "{utf8-locale-reqd}");
}
if (flags & ANYOFL_FOLD) {
sv_catpvs(sv, "{i}");
}
}
/* If there is stuff outside the bitmap, get it */
if (ARG(o) != ANYOF_ONLY_HAS_BITMAP) {
(void) _get_regclass_nonbitmap_data(prog, o, FALSE,
&unresolved,
&only_utf8_locale_invlist,
&nonbitmap_invlist);
/* The non-bitmap data may contain stuff that could fit in the
* bitmap. This could come from a user-defined property being
* finally resolved when this call was done; or much more likely
* because there are matches that require UTF-8 to be valid, and so
* aren't in the bitmap. This is teased apart later */
_invlist_intersection(nonbitmap_invlist,
PL_InBitmap,
&bitmap_range_not_in_bitmap);
/* Leave just the things that don't fit into the bitmap */
_invlist_subtract(nonbitmap_invlist,
PL_InBitmap,
&nonbitmap_invlist);
}
/* Obey this flag to add all above-the-bitmap code points */
if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist,
NUM_ANYOF_CODE_POINTS,
UV_MAX);
}
/* Ready to start outputting. First, the initial left bracket */
Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
/* Then all the things that could fit in the bitmap */
do_sep = put_charclass_bitmap_innards(sv,
ANYOF_BITMAP(o),
bitmap_range_not_in_bitmap,
only_utf8_locale_invlist,
o,
/* Can't try inverting for a
* better display if there are
* things that haven't been
* resolved */
unresolved != NULL);
SvREFCNT_dec(bitmap_range_not_in_bitmap);
/* If there are user-defined properties which haven't been defined yet,
* output them. If the result is not to be inverted, it is clearest to
* output them in a separate [] from the bitmap range stuff. If the
* result is to be complemented, we have to show everything in one [],
* as the inversion applies to the whole thing. Use {braces} to
* separate them from anything in the bitmap and anything above the
* bitmap. */
if (unresolved) {
if (inverted) {
if (! do_sep) { /* If didn't output anything in the bitmap */
sv_catpvs(sv, "^");
}
sv_catpvs(sv, "{");
}
else if (do_sep) {
Perl_sv_catpvf(aTHX_ sv,"%s][%s",PL_colors[1],PL_colors[0]);
}
sv_catsv(sv, unresolved);
if (inverted) {
sv_catpvs(sv, "}");
}
do_sep = ! inverted;
}
/* And, finally, add the above-the-bitmap stuff */
if (nonbitmap_invlist && _invlist_len(nonbitmap_invlist)) {
SV* contents;
/* See if truncation size is overridden */
const STRLEN dump_len = (PL_dump_re_max_len > 256)
? PL_dump_re_max_len
: 256;
/* This is output in a separate [] */
if (do_sep) {
Perl_sv_catpvf(aTHX_ sv,"%s][%s",PL_colors[1],PL_colors[0]);
}
/* And, for easy of understanding, it is shown in the
* uncomplemented form if possible. The one exception being if
* there are unresolved items, where the inversion has to be
* delayed until runtime */
if (inverted && ! unresolved) {
_invlist_invert(nonbitmap_invlist);
_invlist_subtract(nonbitmap_invlist, PL_InBitmap, &nonbitmap_invlist);
}
contents = invlist_contents(nonbitmap_invlist,
FALSE /* output suitable for catsv */
);
/* If the output is shorter than the permissible maximum, just do it. */
if (SvCUR(contents) <= dump_len) {
sv_catsv(sv, contents);
}
else {
const char * contents_string = SvPVX(contents);
STRLEN i = dump_len;
/* Otherwise, start at the permissible max and work back to the
* first break possibility */
while (i > 0 && contents_string[i] != ' ') {
i--;
}
if (i == 0) { /* Fail-safe. Use the max if we couldn't
find a legal break */
i = dump_len;
}
sv_catpvn(sv, contents_string, i);
sv_catpvs(sv, "...");
}
SvREFCNT_dec_NN(contents);
SvREFCNT_dec_NN(nonbitmap_invlist);
}
/* And finally the matching, closing ']' */
Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
SvREFCNT_dec(unresolved);
}
else if (k == POSIXD || k == NPOSIXD) {
U8 index = FLAGS(o) * 2;
if (index < C_ARRAY_LENGTH(anyofs)) {
if (*anyofs[index] != '[') {
sv_catpv(sv, "[");
}
sv_catpv(sv, anyofs[index]);
if (*anyofs[index] != '[') {
sv_catpv(sv, "]");
}
}
else {
Perl_sv_catpvf(aTHX_ sv, "[illegal type=%d])", index);
}
}
else if (k == BOUND || k == NBOUND) {
/* Must be synced with order of 'bound_type' in regcomp.h */
const char * const bounds[] = {
"", /* Traditional */
"{gcb}",
"{lb}",
"{sb}",
"{wb}"
};
assert(FLAGS(o) < C_ARRAY_LENGTH(bounds));
sv_catpv(sv, bounds[FLAGS(o)]);
}
else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
else if (OP(o) == SBOL)
Perl_sv_catpvf(aTHX_ sv, " /%s/", o->flags ? "\\A" : "^");
/* add on the verb argument if there is one */
if ( ( k == VERB || OP(o) == ACCEPT || OP(o) == OPFAIL ) && o->flags) {
if ( ARG(o) )
Perl_sv_catpvf(aTHX_ sv, ":%" SVf,
SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
else
sv_catpvs(sv, ":NULL");
}
#else
PERL_UNUSED_CONTEXT;
PERL_UNUSED_ARG(sv);
PERL_UNUSED_ARG(o);
PERL_UNUSED_ARG(prog);
PERL_UNUSED_ARG(reginfo);
PERL_UNUSED_ARG(pRExC_state);
#endif /* DEBUGGING */
}
SV *
Perl_re_intuit_string(pTHX_ REGEXP * const r)
{ /* Assume that RE_INTUIT is set */
struct regexp *const prog = ReANY(r);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_RE_INTUIT_STRING;
PERL_UNUSED_CONTEXT;
DEBUG_COMPILE_r(
{
const char * const s = SvPV_nolen_const(RX_UTF8(r)
? prog->check_utf8 : prog->check_substr);
if (!PL_colorset) reginitcolors();
Perl_re_printf( aTHX_
"%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
PL_colors[4],
RX_UTF8(r) ? "utf8 " : "",
PL_colors[5],PL_colors[0],
s,
PL_colors[1],
(strlen(s) > PL_dump_re_max_len ? "..." : ""));
} );
/* use UTF8 check substring if regexp pattern itself is in UTF8 */
return RX_UTF8(r) ? prog->check_utf8 : prog->check_substr;
}
/*
pregfree()
handles refcounting and freeing the perl core regexp structure. When
it is necessary to actually free the structure the first thing it
does is call the 'free' method of the regexp_engine associated to
the regexp, allowing the handling of the void *pprivate; member
first. (This routine is not overridable by extensions, which is why
the extensions free is called first.)
See regdupe and regdupe_internal if you change anything here.
*/
#ifndef PERL_IN_XSUB_RE
void
Perl_pregfree(pTHX_ REGEXP *r)
{
SvREFCNT_dec(r);
}
void
Perl_pregfree2(pTHX_ REGEXP *rx)
{
struct regexp *const r = ReANY(rx);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_PREGFREE2;
if (r->mother_re) {
ReREFCNT_dec(r->mother_re);
} else {
CALLREGFREE_PVT(rx); /* free the private data */
SvREFCNT_dec(RXp_PAREN_NAMES(r));
}
if (r->substrs) {
int i;
for (i = 0; i < 2; i++) {
SvREFCNT_dec(r->substrs->data[i].substr);
SvREFCNT_dec(r->substrs->data[i].utf8_substr);
}
Safefree(r->substrs);
}
RX_MATCH_COPY_FREE(rx);
#ifdef PERL_ANY_COW
SvREFCNT_dec(r->saved_copy);
#endif
Safefree(r->offs);
SvREFCNT_dec(r->qr_anoncv);
if (r->recurse_locinput)
Safefree(r->recurse_locinput);
}
/* reg_temp_copy()
Copy ssv to dsv, both of which should of type SVt_REGEXP or SVt_PVLV,
except that dsv will be created if NULL.
This function is used in two main ways. First to implement
$r = qr/....; $s = $$r;
Secondly, it is used as a hacky workaround to the structural issue of
match results
being stored in the regexp structure which is in turn stored in
PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
could be PL_curpm in multiple contexts, and could require multiple
result sets being associated with the pattern simultaneously, such
as when doing a recursive match with (??{$qr})
The solution is to make a lightweight copy of the regexp structure
when a qr// is returned from the code executed by (??{$qr}) this
lightweight copy doesn't actually own any of its data except for
the starp/end and the actual regexp structure itself.
*/
REGEXP *
Perl_reg_temp_copy(pTHX_ REGEXP *dsv, REGEXP *ssv)
{
struct regexp *drx;
struct regexp *const srx = ReANY(ssv);
const bool islv = dsv && SvTYPE(dsv) == SVt_PVLV;
PERL_ARGS_ASSERT_REG_TEMP_COPY;
if (!dsv)
dsv = (REGEXP*) newSV_type(SVt_REGEXP);
else {
SvOK_off((SV *)dsv);
if (islv) {
/* For PVLVs, the head (sv_any) points to an XPVLV, while
* the LV's xpvlenu_rx will point to a regexp body, which
* we allocate here */
REGEXP *temp = (REGEXP *)newSV_type(SVt_REGEXP);
assert(!SvPVX(dsv));
((XPV*)SvANY(dsv))->xpv_len_u.xpvlenu_rx = temp->sv_any;
temp->sv_any = NULL;
SvFLAGS(temp) = (SvFLAGS(temp) & ~SVTYPEMASK) | SVt_NULL;
SvREFCNT_dec_NN(temp);
/* SvCUR still resides in the xpvlv struct, so the regexp copy-
ing below will not set it. */
SvCUR_set(dsv, SvCUR(ssv));
}
}
/* This ensures that SvTHINKFIRST(sv) is true, and hence that
sv_force_normal(sv) is called. */
SvFAKE_on(dsv);
drx = ReANY(dsv);
SvFLAGS(dsv) |= SvFLAGS(ssv) & (SVf_POK|SVp_POK|SVf_UTF8);
SvPV_set(dsv, RX_WRAPPED(ssv));
/* We share the same string buffer as the original regexp, on which we
hold a reference count, incremented when mother_re is set below.
The string pointer is copied here, being part of the regexp struct.
*/
memcpy(&(drx->xpv_cur), &(srx->xpv_cur),
sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
if (!islv)
SvLEN_set(dsv, 0);
if (srx->offs) {
const I32 npar = srx->nparens+1;
Newx(drx->offs, npar, regexp_paren_pair);
Copy(srx->offs, drx->offs, npar, regexp_paren_pair);
}
if (srx->substrs) {
int i;
Newx(drx->substrs, 1, struct reg_substr_data);
StructCopy(srx->substrs, drx->substrs, struct reg_substr_data);
for (i = 0; i < 2; i++) {
SvREFCNT_inc_void(drx->substrs->data[i].substr);
SvREFCNT_inc_void(drx->substrs->data[i].utf8_substr);
}
/* check_substr and check_utf8, if non-NULL, point to either their
anchored or float namesakes, and don't hold a second reference. */
}
RX_MATCH_COPIED_off(dsv);
#ifdef PERL_ANY_COW
drx->saved_copy = NULL;
#endif
drx->mother_re = ReREFCNT_inc(srx->mother_re ? srx->mother_re : ssv);
SvREFCNT_inc_void(drx->qr_anoncv);
if (srx->recurse_locinput)
Newx(drx->recurse_locinput,srx->nparens + 1,char *);
return dsv;
}
#endif
/* regfree_internal()
Free the private data in a regexp. This is overloadable by
extensions. Perl takes care of the regexp structure in pregfree(),
this covers the *pprivate pointer which technically perl doesn't
know about, however of course we have to handle the
regexp_internal structure when no extension is in use.
Note this is called before freeing anything in the regexp
structure.
*/
void
Perl_regfree_internal(pTHX_ REGEXP * const rx)
{
struct regexp *const r = ReANY(rx);
RXi_GET_DECL(r,ri);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGFREE_INTERNAL;
DEBUG_COMPILE_r({
if (!PL_colorset)
reginitcolors();
{
SV *dsv= sv_newmortal();
RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
dsv, RX_PRECOMP(rx), RX_PRELEN(rx), PL_dump_re_max_len);
Perl_re_printf( aTHX_ "%sFreeing REx:%s %s\n",
PL_colors[4],PL_colors[5],s);
}
});
#ifdef RE_TRACK_PATTERN_OFFSETS
if (ri->u.offsets)
Safefree(ri->u.offsets); /* 20010421 MJD */
#endif
if (ri->code_blocks)
S_free_codeblocks(aTHX_ ri->code_blocks);
if (ri->data) {
int n = ri->data->count;
while (--n >= 0) {
/* If you add a ->what type here, update the comment in regcomp.h */
switch (ri->data->what[n]) {
case 'a':
case 'r':
case 's':
case 'S':
case 'u':
SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
break;
case 'f':
Safefree(ri->data->data[n]);
break;
case 'l':
case 'L':
break;
case 'T':
{ /* Aho Corasick add-on structure for a trie node.
Used in stclass optimization only */
U32 refcount;
reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
#ifdef USE_ITHREADS
dVAR;
#endif
OP_REFCNT_LOCK;
refcount = --aho->refcount;
OP_REFCNT_UNLOCK;
if ( !refcount ) {
PerlMemShared_free(aho->states);
PerlMemShared_free(aho->fail);
/* do this last!!!! */
PerlMemShared_free(ri->data->data[n]);
/* we should only ever get called once, so
* assert as much, and also guard the free
* which /might/ happen twice. At the least
* it will make code anlyzers happy and it
* doesn't cost much. - Yves */
assert(ri->regstclass);
if (ri->regstclass) {
PerlMemShared_free(ri->regstclass);
ri->regstclass = 0;
}
}
}
break;
case 't':
{
/* trie structure. */
U32 refcount;
reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
#ifdef USE_ITHREADS
dVAR;
#endif
OP_REFCNT_LOCK;
refcount = --trie->refcount;
OP_REFCNT_UNLOCK;
if ( !refcount ) {
PerlMemShared_free(trie->charmap);
PerlMemShared_free(trie->states);
PerlMemShared_free(trie->trans);
if (trie->bitmap)
PerlMemShared_free(trie->bitmap);
if (trie->jump)
PerlMemShared_free(trie->jump);
PerlMemShared_free(trie->wordinfo);
/* do this last!!!! */
PerlMemShared_free(ri->data->data[n]);
}
}
break;
default:
Perl_croak(aTHX_ "panic: regfree data code '%c'",
ri->data->what[n]);
}
}
Safefree(ri->data->what);
Safefree(ri->data);
}
Safefree(ri);
}
#define av_dup_inc(s,t) MUTABLE_AV(sv_dup_inc((const SV *)s,t))
#define hv_dup_inc(s,t) MUTABLE_HV(sv_dup_inc((const SV *)s,t))
#define SAVEPVN(p,n) ((p) ? savepvn(p,n) : NULL)
/*
re_dup_guts - duplicate a regexp.
This routine is expected to clone a given regexp structure. It is only
compiled under USE_ITHREADS.
After all of the core data stored in struct regexp is duplicated
the regexp_engine.dupe method is used to copy any private data
stored in the *pprivate pointer. This allows extensions to handle
any duplication it needs to do.
See pregfree() and regfree_internal() if you change anything here.
*/
#if defined(USE_ITHREADS)
#ifndef PERL_IN_XSUB_RE
void
Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
{
dVAR;
I32 npar;
const struct regexp *r = ReANY(sstr);
struct regexp *ret = ReANY(dstr);
PERL_ARGS_ASSERT_RE_DUP_GUTS;
npar = r->nparens+1;
Newx(ret->offs, npar, regexp_paren_pair);
Copy(r->offs, ret->offs, npar, regexp_paren_pair);
if (ret->substrs) {
/* Do it this way to avoid reading from *r after the StructCopy().
That way, if any of the sv_dup_inc()s dislodge *r from the L1
cache, it doesn't matter. */
int i;
const bool anchored = r->check_substr
? r->check_substr == r->substrs->data[0].substr
: r->check_utf8 == r->substrs->data[0].utf8_substr;
Newx(ret->substrs, 1, struct reg_substr_data);
StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
for (i = 0; i < 2; i++) {
ret->substrs->data[i].substr =
sv_dup_inc(ret->substrs->data[i].substr, param);
ret->substrs->data[i].utf8_substr =
sv_dup_inc(ret->substrs->data[i].utf8_substr, param);
}
/* check_substr and check_utf8, if non-NULL, point to either their
anchored or float namesakes, and don't hold a second reference. */
if (ret->check_substr) {
if (anchored) {
assert(r->check_utf8 == r->substrs->data[0].utf8_substr);
ret->check_substr = ret->substrs->data[0].substr;
ret->check_utf8 = ret->substrs->data[0].utf8_substr;
} else {
assert(r->check_substr == r->substrs->data[1].substr);
assert(r->check_utf8 == r->substrs->data[1].utf8_substr);
ret->check_substr = ret->substrs->data[1].substr;
ret->check_utf8 = ret->substrs->data[1].utf8_substr;
}
} else if (ret->check_utf8) {
if (anchored) {
ret->check_utf8 = ret->substrs->data[0].utf8_substr;
} else {
ret->check_utf8 = ret->substrs->data[1].utf8_substr;
}
}
}
RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
ret->qr_anoncv = MUTABLE_CV(sv_dup_inc((const SV *)ret->qr_anoncv, param));
if (r->recurse_locinput)
Newx(ret->recurse_locinput,r->nparens + 1,char *);
if (ret->pprivate)
RXi_SET(ret,CALLREGDUPE_PVT(dstr,param));
if (RX_MATCH_COPIED(dstr))
ret->subbeg = SAVEPVN(ret->subbeg, ret->sublen);
else
ret->subbeg = NULL;
#ifdef PERL_ANY_COW
ret->saved_copy = NULL;
#endif
/* Whether mother_re be set or no, we need to copy the string. We
cannot refrain from copying it when the storage points directly to
our mother regexp, because that's
1: a buffer in a different thread
2: something we no longer hold a reference on
so we need to copy it locally. */
RX_WRAPPED(dstr) = SAVEPVN(RX_WRAPPED_const(sstr), SvCUR(sstr)+1);
ret->mother_re = NULL;
}
#endif /* PERL_IN_XSUB_RE */
/*
regdupe_internal()
This is the internal complement to regdupe() which is used to copy
the structure pointed to by the *pprivate pointer in the regexp.
This is the core version of the extension overridable cloning hook.
The regexp structure being duplicated will be copied by perl prior
to this and will be provided as the regexp *r argument, however
with the /old/ structures pprivate pointer value. Thus this routine
may override any copying normally done by perl.
It returns a pointer to the new regexp_internal structure.
*/
void *
Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
{
dVAR;
struct regexp *const r = ReANY(rx);
regexp_internal *reti;
int len;
RXi_GET_DECL(r,ri);
PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
len = ProgLen(ri);
Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode),
char, regexp_internal);
Copy(ri->program, reti->program, len+1, regnode);
if (ri->code_blocks) {
int n;
Newx(reti->code_blocks, 1, struct reg_code_blocks);
Newx(reti->code_blocks->cb, ri->code_blocks->count,
struct reg_code_block);
Copy(ri->code_blocks->cb, reti->code_blocks->cb,
ri->code_blocks->count, struct reg_code_block);
for (n = 0; n < ri->code_blocks->count; n++)
reti->code_blocks->cb[n].src_regex = (REGEXP*)
sv_dup_inc((SV*)(ri->code_blocks->cb[n].src_regex), param);
reti->code_blocks->count = ri->code_blocks->count;
reti->code_blocks->refcnt = 1;
}
else
reti->code_blocks = NULL;
reti->regstclass = NULL;
if (ri->data) {
struct reg_data *d;
const int count = ri->data->count;
int i;
Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
char, struct reg_data);
Newx(d->what, count, U8);
d->count = count;
for (i = 0; i < count; i++) {
d->what[i] = ri->data->what[i];
switch (d->what[i]) {
/* see also regcomp.h and regfree_internal() */
case 'a': /* actually an AV, but the dup function is identical.
values seem to be "plain sv's" generally. */
case 'r': /* a compiled regex (but still just another SV) */
case 's': /* an RV (currently only used for an RV to an AV by the ANYOF code)
this use case should go away, the code could have used
'a' instead - see S_set_ANYOF_arg() for array contents. */
case 'S': /* actually an SV, but the dup function is identical. */
case 'u': /* actually an HV, but the dup function is identical.
values are "plain sv's" */
d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
break;
case 'f':
/* Synthetic Start Class - "Fake" charclass we generate to optimize
* patterns which could start with several different things. Pre-TRIE
* this was more important than it is now, however this still helps
* in some places, for instance /x?a+/ might produce a SSC equivalent
* to [xa]. This is used by Perl_re_intuit_start() and S_find_byclass()
* in regexec.c
*/
/* This is cheating. */
Newx(d->data[i], 1, regnode_ssc);
StructCopy(ri->data->data[i], d->data[i], regnode_ssc);
reti->regstclass = (regnode*)d->data[i];
break;
case 'T':
/* AHO-CORASICK fail table */
/* Trie stclasses are readonly and can thus be shared
* without duplication. We free the stclass in pregfree
* when the corresponding reg_ac_data struct is freed.
*/
reti->regstclass= ri->regstclass;
/* FALLTHROUGH */
case 't':
/* TRIE transition table */
OP_REFCNT_LOCK;
((reg_trie_data*)ri->data->data[i])->refcount++;
OP_REFCNT_UNLOCK;
/* FALLTHROUGH */
case 'l': /* (?{...}) or (??{ ... }) code (cb->block) */
case 'L': /* same when RExC_pm_flags & PMf_HAS_CV and code
is not from another regexp */
d->data[i] = ri->data->data[i];
break;
default:
Perl_croak(aTHX_ "panic: re_dup_guts unknown data code '%c'",
ri->data->what[i]);
}
}
reti->data = d;
}
else
reti->data = NULL;
reti->name_list_idx = ri->name_list_idx;
#ifdef RE_TRACK_PATTERN_OFFSETS
if (ri->u.offsets) {
Newx(reti->u.offsets, 2*len+1, U32);
Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
}
#else
SetProgLen(reti,len);
#endif
return (void*)reti;
}
#endif /* USE_ITHREADS */
#ifndef PERL_IN_XSUB_RE
/*
- regnext - dig the "next" pointer out of a node
*/
regnode *
Perl_regnext(pTHX_ regnode *p)
{
I32 offset;
if (!p)
return(NULL);
if (OP(p) > REGNODE_MAX) { /* regnode.type is unsigned */
Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
(int)OP(p), (int)REGNODE_MAX);
}
offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
if (offset == 0)
return(NULL);
return(p+offset);
}
#endif
STATIC void
S_re_croak2(pTHX_ bool utf8, const char* pat1,const char* pat2,...)
{
va_list args;
STRLEN l1 = strlen(pat1);
STRLEN l2 = strlen(pat2);
char buf[512];
SV *msv;
const char *message;
PERL_ARGS_ASSERT_RE_CROAK2;
if (l1 > 510)
l1 = 510;
if (l1 + l2 > 510)
l2 = 510 - l1;
Copy(pat1, buf, l1 , char);
Copy(pat2, buf + l1, l2 , char);
buf[l1 + l2] = '\n';
buf[l1 + l2 + 1] = '\0';
va_start(args, pat2);
msv = vmess(buf, &args);
va_end(args);
message = SvPV_const(msv,l1);
if (l1 > 512)
l1 = 512;
Copy(message, buf, l1 , char);
/* l1-1 to avoid \n */
Perl_croak(aTHX_ "%" UTF8f, UTF8fARG(utf8, l1-1, buf));
}
/* XXX Here's a total kludge. But we need to re-enter for swash routines. */
#ifndef PERL_IN_XSUB_RE
void
Perl_save_re_context(pTHX)
{
I32 nparens = -1;
I32 i;
/* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
if (PL_curpm) {
const REGEXP * const rx = PM_GETRE(PL_curpm);
if (rx)
nparens = RX_NPARENS(rx);
}
/* RT #124109. This is a complete hack; in the SWASHNEW case we know
* that PL_curpm will be null, but that utf8.pm and the modules it
* loads will only use $1..$3.
* The t/porting/re_context.t test file checks this assumption.
*/
if (nparens == -1)
nparens = 3;
for (i = 1; i <= nparens; i++) {
char digits[TYPE_CHARS(long)];
const STRLEN len = my_snprintf(digits, sizeof(digits),
"%lu", (long)i);
GV *const *const gvp
= (GV**)hv_fetch(PL_defstash, digits, len, 0);
if (gvp) {
GV * const gv = *gvp;
if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
save_scalar(gv);
}
}
}
#endif
#ifdef DEBUGGING
STATIC void
S_put_code_point(pTHX_ SV *sv, UV c)
{
PERL_ARGS_ASSERT_PUT_CODE_POINT;
if (c > 255) {
Perl_sv_catpvf(aTHX_ sv, "\\x{%04" UVXf "}", c);
}
else if (isPRINT(c)) {
const char string = (char) c;
/* We use {phrase} as metanotation in the class, so also escape literal
* braces */
if (isBACKSLASHED_PUNCT(c) || c == '{' || c == '}')
sv_catpvs(sv, "\\");
sv_catpvn(sv, &string, 1);
}
else if (isMNEMONIC_CNTRL(c)) {
Perl_sv_catpvf(aTHX_ sv, "%s", cntrl_to_mnemonic((U8) c));
}
else {
Perl_sv_catpvf(aTHX_ sv, "\\x%02X", (U8) c);
}
}
#define MAX_PRINT_A MAX_PRINT_A_FOR_USE_ONLY_BY_REGCOMP_DOT_C
STATIC void
S_put_range(pTHX_ SV *sv, UV start, const UV end, const bool allow_literals)
{
/* Appends to 'sv' a displayable version of the range of code points from
* 'start' to 'end'. Mnemonics (like '\r') are used for the few controls
* that have them, when they occur at the beginning or end of the range.
* It uses hex to output the remaining code points, unless 'allow_literals'
* is true, in which case the printable ASCII ones are output as-is (though
* some of these will be escaped by put_code_point()).
*
* NOTE: This is designed only for printing ranges of code points that fit
* inside an ANYOF bitmap. Higher code points are simply suppressed
*/
const unsigned int min_range_count = 3;
assert(start <= end);
PERL_ARGS_ASSERT_PUT_RANGE;
while (start <= end) {
UV this_end;
const char * format;
if (end - start < min_range_count) {
/* Output chars individually when they occur in short ranges */
for (; start <= end; start++) {
put_code_point(sv, start);
}
break;
}
/* If permitted by the input options, and there is a possibility that
* this range contains a printable literal, look to see if there is
* one. */
if (allow_literals && start <= MAX_PRINT_A) {
/* If the character at the beginning of the range isn't an ASCII
* printable, effectively split the range into two parts:
* 1) the portion before the first such printable,
* 2) the rest
* and output them separately. */
if (! isPRINT_A(start)) {
UV temp_end = start + 1;
/* There is no point looking beyond the final possible
* printable, in MAX_PRINT_A */
UV max = MIN(end, MAX_PRINT_A);
while (temp_end <= max && ! isPRINT_A(temp_end)) {
temp_end++;
}
/* Here, temp_end points to one beyond the first printable if
* found, or to one beyond 'max' if not. If none found, make
* sure that we use the entire range */
if (temp_end > MAX_PRINT_A) {
temp_end = end + 1;
}
/* Output the first part of the split range: the part that
* doesn't have printables, with the parameter set to not look
* for literals (otherwise we would infinitely recurse) */
put_range(sv, start, temp_end - 1, FALSE);
/* The 2nd part of the range (if any) starts here. */
start = temp_end;
/* We do a continue, instead of dropping down, because even if
* the 2nd part is non-empty, it could be so short that we want
* to output it as individual characters, as tested for at the
* top of this loop. */
continue;
}
/* Here, 'start' is a printable ASCII. If it is an alphanumeric,
* output a sub-range of just the digits or letters, then process
* the remaining portion as usual. */
if (isALPHANUMERIC_A(start)) {
UV mask = (isDIGIT_A(start))
? _CC_DIGIT
: isUPPER_A(start)
? _CC_UPPER
: _CC_LOWER;
UV temp_end = start + 1;
/* Find the end of the sub-range that includes just the
* characters in the same class as the first character in it */
while (temp_end <= end && _generic_isCC_A(temp_end, mask)) {
temp_end++;
}
temp_end--;
/* For short ranges, don't duplicate the code above to output
* them; just call recursively */
if (temp_end - start < min_range_count) {
put_range(sv, start, temp_end, FALSE);
}
else { /* Output as a range */
put_code_point(sv, start);
sv_catpvs(sv, "-");
put_code_point(sv, temp_end);
}
start = temp_end + 1;
continue;
}
/* We output any other printables as individual characters */
if (isPUNCT_A(start) || isSPACE_A(start)) {
while (start <= end && (isPUNCT_A(start)
|| isSPACE_A(start)))
{
put_code_point(sv, start);
start++;
}
continue;
}
} /* End of looking for literals */
/* Here is not to output as a literal. Some control characters have
* mnemonic names. Split off any of those at the beginning and end of
* the range to print mnemonically. It isn't possible for many of
* these to be in a row, so this won't overwhelm with output */
if ( start <= end
&& (isMNEMONIC_CNTRL(start) || isMNEMONIC_CNTRL(end)))
{
while (isMNEMONIC_CNTRL(start) && start <= end) {
put_code_point(sv, start);
start++;
}
/* If this didn't take care of the whole range ... */
if (start <= end) {
/* Look backwards from the end to find the final non-mnemonic
* */
UV temp_end = end;
while (isMNEMONIC_CNTRL(temp_end)) {
temp_end--;
}
/* And separately output the interior range that doesn't start
* or end with mnemonics */
put_range(sv, start, temp_end, FALSE);
/* Then output the mnemonic trailing controls */
start = temp_end + 1;
while (start <= end) {
put_code_point(sv, start);
start++;
}
break;
}
}
/* As a final resort, output the range or subrange as hex. */
this_end = (end < NUM_ANYOF_CODE_POINTS)
? end
: NUM_ANYOF_CODE_POINTS - 1;
#if NUM_ANYOF_CODE_POINTS > 256
format = (this_end < 256)
? "\\x%02" UVXf "-\\x%02" UVXf
: "\\x{%04" UVXf "}-\\x{%04" UVXf "}";
#else
format = "\\x%02" UVXf "-\\x%02" UVXf;
#endif
GCC_DIAG_IGNORE(-Wformat-nonliteral);
Perl_sv_catpvf(aTHX_ sv, format, start, this_end);
GCC_DIAG_RESTORE;
break;
}
}
STATIC void
S_put_charclass_bitmap_innards_invlist(pTHX_ SV *sv, SV* invlist)
{
/* Concatenate onto the PV in 'sv' a displayable form of the inversion list
* 'invlist' */
UV start, end;
bool allow_literals = TRUE;
PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_INVLIST;
/* Generally, it is more readable if printable characters are output as
* literals, but if a range (nearly) spans all of them, it's best to output
* it as a single range. This code will use a single range if all but 2
* ASCII printables are in it */
invlist_iterinit(invlist);
while (invlist_iternext(invlist, &start, &end)) {
/* If the range starts beyond the final printable, it doesn't have any
* in it */
if (start > MAX_PRINT_A) {
break;
}
/* In both ASCII and EBCDIC, a SPACE is the lowest printable. To span
* all but two, the range must start and end no later than 2 from
* either end */
if (start < ' ' + 2 && end > MAX_PRINT_A - 2) {
if (end > MAX_PRINT_A) {
end = MAX_PRINT_A;
}
if (start < ' ') {
start = ' ';
}
if (end - start >= MAX_PRINT_A - ' ' - 2) {
allow_literals = FALSE;
}
break;
}
}
invlist_iterfinish(invlist);
/* Here we have figured things out. Output each range */
invlist_iterinit(invlist);
while (invlist_iternext(invlist, &start, &end)) {
if (start >= NUM_ANYOF_CODE_POINTS) {
break;
}
put_range(sv, start, end, allow_literals);
}
invlist_iterfinish(invlist);
return;
}
STATIC SV*
S_put_charclass_bitmap_innards_common(pTHX_
SV* invlist, /* The bitmap */
SV* posixes, /* Under /l, things like [:word:], \S */
SV* only_utf8, /* Under /d, matches iff the target is UTF-8 */
SV* not_utf8, /* /d, matches iff the target isn't UTF-8 */
SV* only_utf8_locale, /* Under /l, matches if the locale is UTF-8 */
const bool invert /* Is the result to be inverted? */
)
{
/* Create and return an SV containing a displayable version of the bitmap
* and associated information determined by the input parameters. If the
* output would have been only the inversion indicator '^', NULL is instead
* returned. */
SV * output;
PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_COMMON;
if (invert) {
output = newSVpvs("^");
}
else {
output = newSVpvs("");
}
/* First, the code points in the bitmap that are unconditionally there */
put_charclass_bitmap_innards_invlist(output, invlist);
/* Traditionally, these have been placed after the main code points */
if (posixes) {
sv_catsv(output, posixes);
}
if (only_utf8 && _invlist_len(only_utf8)) {
Perl_sv_catpvf(aTHX_ output, "%s{utf8}%s", PL_colors[1], PL_colors[0]);
put_charclass_bitmap_innards_invlist(output, only_utf8);
}
if (not_utf8 && _invlist_len(not_utf8)) {
Perl_sv_catpvf(aTHX_ output, "%s{not utf8}%s", PL_colors[1], PL_colors[0]);
put_charclass_bitmap_innards_invlist(output, not_utf8);
}
if (only_utf8_locale && _invlist_len(only_utf8_locale)) {
Perl_sv_catpvf(aTHX_ output, "%s{utf8 locale}%s", PL_colors[1], PL_colors[0]);
put_charclass_bitmap_innards_invlist(output, only_utf8_locale);
/* This is the only list in this routine that can legally contain code
* points outside the bitmap range. The call just above to
* 'put_charclass_bitmap_innards_invlist' will simply suppress them, so
* output them here. There's about a half-dozen possible, and none in
* contiguous ranges longer than 2 */
if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
UV start, end;
SV* above_bitmap = NULL;
_invlist_subtract(only_utf8_locale, PL_InBitmap, &above_bitmap);
invlist_iterinit(above_bitmap);
while (invlist_iternext(above_bitmap, &start, &end)) {
UV i;
for (i = start; i <= end; i++) {
put_code_point(output, i);
}
}
invlist_iterfinish(above_bitmap);
SvREFCNT_dec_NN(above_bitmap);
}
}
if (invert && SvCUR(output) == 1) {
return NULL;
}
return output;
}
STATIC bool
S_put_charclass_bitmap_innards(pTHX_ SV *sv,
char *bitmap,
SV *nonbitmap_invlist,
SV *only_utf8_locale_invlist,
const regnode * const node,
const bool force_as_is_display)
{
/* Appends to 'sv' a displayable version of the innards of the bracketed
* character class defined by the other arguments:
* 'bitmap' points to the bitmap.
* 'nonbitmap_invlist' is an inversion list of the code points that are in
* the bitmap range, but for some reason aren't in the bitmap; NULL if
* none. The reasons for this could be that they require some
* condition such as the target string being or not being in UTF-8
* (under /d), or because they came from a user-defined property that
* was not resolved at the time of the regex compilation (under /u)
* 'only_utf8_locale_invlist' is an inversion list of the code points that
* are valid only if the runtime locale is a UTF-8 one; NULL if none
* 'node' is the regex pattern node. It is needed only when the above two
* parameters are not null, and is passed so that this routine can
* tease apart the various reasons for them.
* 'force_as_is_display' is TRUE if this routine should definitely NOT try
* to invert things to see if that leads to a cleaner display. If
* FALSE, this routine is free to use its judgment about doing this.
*
* It returns TRUE if there was actually something output. (It may be that
* the bitmap, etc is empty.)
*
* When called for outputting the bitmap of a non-ANYOF node, just pass the
* bitmap, with the succeeding parameters set to NULL, and the final one to
* FALSE.
*/
/* In general, it tries to display the 'cleanest' representation of the
* innards, choosing whether to display them inverted or not, regardless of
* whether the class itself is to be inverted. However, there are some
* cases where it can't try inverting, as what actually matches isn't known
* until runtime, and hence the inversion isn't either. */
bool inverting_allowed = ! force_as_is_display;
int i;
STRLEN orig_sv_cur = SvCUR(sv);
SV* invlist; /* Inversion list we accumulate of code points that
are unconditionally matched */
SV* only_utf8 = NULL; /* Under /d, list of matches iff the target is
UTF-8 */
SV* not_utf8 = NULL; /* /d, list of matches iff the target isn't UTF-8
*/
SV* posixes = NULL; /* Under /l, string of things like [:word:], \D */
SV* only_utf8_locale = NULL; /* Under /l, list of matches if the locale
is UTF-8 */
SV* as_is_display; /* The output string when we take the inputs
literally */
SV* inverted_display; /* The output string when we invert the inputs */
U8 flags = (node) ? ANYOF_FLAGS(node) : 0;
bool invert = cBOOL(flags & ANYOF_INVERT); /* Is the input to be inverted
to match? */
/* We are biased in favor of displaying things without them being inverted,
* as that is generally easier to understand */
const int bias = 5;
PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS;
/* Start off with whatever code points are passed in. (We clone, so we
* don't change the caller's list) */
if (nonbitmap_invlist) {
assert(invlist_highest(nonbitmap_invlist) < NUM_ANYOF_CODE_POINTS);
invlist = invlist_clone(nonbitmap_invlist);
}
else { /* Worst case size is every other code point is matched */
invlist = _new_invlist(NUM_ANYOF_CODE_POINTS / 2);
}
if (flags) {
if (OP(node) == ANYOFD) {
/* This flag indicates that the code points below 0x100 in the
* nonbitmap list are precisely the ones that match only when the
* target is UTF-8 (they should all be non-ASCII). */
if (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
{
_invlist_intersection(invlist, PL_UpperLatin1, &only_utf8);
_invlist_subtract(invlist, only_utf8, &invlist);
}
/* And this flag for matching all non-ASCII 0xFF and below */
if (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
{
not_utf8 = invlist_clone(PL_UpperLatin1);
}
}
else if (OP(node) == ANYOFL) {
/* If either of these flags are set, what matches isn't
* determinable except during execution, so don't know enough here
* to invert */
if (flags & (ANYOFL_FOLD|ANYOF_MATCHES_POSIXL)) {
inverting_allowed = FALSE;
}
/* What the posix classes match also varies at runtime, so these
* will be output symbolically. */
if (ANYOF_POSIXL_TEST_ANY_SET(node)) {
int i;
posixes = newSVpvs("");
for (i = 0; i < ANYOF_POSIXL_MAX; i++) {
if (ANYOF_POSIXL_TEST(node,i)) {
sv_catpv(posixes, anyofs[i]);
}
}
}
}
}
/* Accumulate the bit map into the unconditional match list */
for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
if (BITMAP_TEST(bitmap, i)) {
int start = i++;
for (; i < NUM_ANYOF_CODE_POINTS && BITMAP_TEST(bitmap, i); i++) {
/* empty */
}
invlist = _add_range_to_invlist(invlist, start, i-1);
}
}
/* Make sure that the conditional match lists don't have anything in them
* that match unconditionally; otherwise the output is quite confusing.
* This could happen if the code that populates these misses some
* duplication. */
if (only_utf8) {
_invlist_subtract(only_utf8, invlist, &only_utf8);
}
if (not_utf8) {
_invlist_subtract(not_utf8, invlist, ¬_utf8);
}
if (only_utf8_locale_invlist) {
/* Since this list is passed in, we have to make a copy before
* modifying it */
only_utf8_locale = invlist_clone(only_utf8_locale_invlist);
_invlist_subtract(only_utf8_locale, invlist, &only_utf8_locale);
/* And, it can get really weird for us to try outputting an inverted
* form of this list when it has things above the bitmap, so don't even
* try */
if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
inverting_allowed = FALSE;
}
}
/* Calculate what the output would be if we take the input as-is */
as_is_display = put_charclass_bitmap_innards_common(invlist,
posixes,
only_utf8,
not_utf8,
only_utf8_locale,
invert);
/* If have to take the output as-is, just do that */
if (! inverting_allowed) {
if (as_is_display) {
sv_catsv(sv, as_is_display);
SvREFCNT_dec_NN(as_is_display);
}
}
else { /* But otherwise, create the output again on the inverted input, and
use whichever version is shorter */
int inverted_bias, as_is_bias;
/* We will apply our bias to whichever of the the results doesn't have
* the '^' */
if (invert) {
invert = FALSE;
as_is_bias = bias;
inverted_bias = 0;
}
else {
invert = TRUE;
as_is_bias = 0;
inverted_bias = bias;
}
/* Now invert each of the lists that contribute to the output,
* excluding from the result things outside the possible range */
/* For the unconditional inversion list, we have to add in all the
* conditional code points, so that when inverted, they will be gone
* from it */
_invlist_union(only_utf8, invlist, &invlist);
_invlist_union(not_utf8, invlist, &invlist);
_invlist_union(only_utf8_locale, invlist, &invlist);
_invlist_invert(invlist);
_invlist_intersection(invlist, PL_InBitmap, &invlist);
if (only_utf8) {
_invlist_invert(only_utf8);
_invlist_intersection(only_utf8, PL_UpperLatin1, &only_utf8);
}
else if (not_utf8) {
/* If a code point matches iff the target string is not in UTF-8,
* then complementing the result has it not match iff not in UTF-8,
* which is the same thing as matching iff it is UTF-8. */
only_utf8 = not_utf8;
not_utf8 = NULL;
}
if (only_utf8_locale) {
_invlist_invert(only_utf8_locale);
_invlist_intersection(only_utf8_locale,
PL_InBitmap,
&only_utf8_locale);
}
inverted_display = put_charclass_bitmap_innards_common(
invlist,
posixes,
only_utf8,
not_utf8,
only_utf8_locale, invert);
/* Use the shortest representation, taking into account our bias
* against showing it inverted */
if ( inverted_display
&& ( ! as_is_display
|| ( SvCUR(inverted_display) + inverted_bias
< SvCUR(as_is_display) + as_is_bias)))
{
sv_catsv(sv, inverted_display);
}
else if (as_is_display) {
sv_catsv(sv, as_is_display);
}
SvREFCNT_dec(as_is_display);
SvREFCNT_dec(inverted_display);
}
SvREFCNT_dec_NN(invlist);
SvREFCNT_dec(only_utf8);
SvREFCNT_dec(not_utf8);
SvREFCNT_dec(posixes);
SvREFCNT_dec(only_utf8_locale);
return SvCUR(sv) > orig_sv_cur;
}
#define CLEAR_OPTSTART \
if (optstart) STMT_START { \
DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ \
" (%" IVdf " nodes)\n", (IV)(node - optstart))); \
optstart=NULL; \
} STMT_END
#define DUMPUNTIL(b,e) \
CLEAR_OPTSTART; \
node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
STATIC const regnode *
S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
const regnode *last, const regnode *plast,
SV* sv, I32 indent, U32 depth)
{
U8 op = PSEUDO; /* Arbitrary non-END op. */
const regnode *next;
const regnode *optstart= NULL;
RXi_GET_DECL(r,ri);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_DUMPUNTIL;
#ifdef DEBUG_DUMPUNTIL
Perl_re_printf( aTHX_ "--- %d : %d - %d - %d\n",indent,node-start,
last ? last-start : 0,plast ? plast-start : 0);
#endif
if (plast && plast < last)
last= plast;
while (PL_regkind[op] != END && (!last || node < last)) {
assert(node);
/* While that wasn't END last time... */
NODE_ALIGN(node);
op = OP(node);
if (op == CLOSE || op == WHILEM)
indent--;
next = regnext((regnode *)node);
/* Where, what. */
if (OP(node) == OPTIMIZED) {
if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
optstart = node;
else
goto after_print;
} else
CLEAR_OPTSTART;
regprop(r, sv, node, NULL, NULL);
Perl_re_printf( aTHX_ "%4" IVdf ":%*s%s", (IV)(node - start),
(int)(2*indent + 1), "", SvPVX_const(sv));
if (OP(node) != OPTIMIZED) {
if (next == NULL) /* Next ptr. */
Perl_re_printf( aTHX_ " (0)");
else if (PL_regkind[(U8)op] == BRANCH
&& PL_regkind[OP(next)] != BRANCH )
Perl_re_printf( aTHX_ " (FAIL)");
else
Perl_re_printf( aTHX_ " (%" IVdf ")", (IV)(next - start));
Perl_re_printf( aTHX_ "\n");
}
after_print:
if (PL_regkind[(U8)op] == BRANCHJ) {
assert(next);
{
const regnode *nnode = (OP(next) == LONGJMP
? regnext((regnode *)next)
: next);
if (last && nnode > last)
nnode = last;
DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
}
}
else if (PL_regkind[(U8)op] == BRANCH) {
assert(next);
DUMPUNTIL(NEXTOPER(node), next);
}
else if ( PL_regkind[(U8)op] == TRIE ) {
const regnode *this_trie = node;
const char op = OP(node);
const U32 n = ARG(node);
const reg_ac_data * const ac = op>=AHOCORASICK ?
(reg_ac_data *)ri->data->data[n] :
NULL;
const reg_trie_data * const trie =
(reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
#ifdef DEBUGGING
AV *const trie_words
= MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
#endif
const regnode *nextbranch= NULL;
I32 word_idx;
SvPVCLEAR(sv);
for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
SV ** const elem_ptr = av_fetch(trie_words,word_idx,0);
Perl_re_indentf( aTHX_ "%s ",
indent+3,
elem_ptr
? pv_pretty(sv, SvPV_nolen_const(*elem_ptr),
SvCUR(*elem_ptr), PL_dump_re_max_len,
PL_colors[0], PL_colors[1],
(SvUTF8(*elem_ptr)
? PERL_PV_ESCAPE_UNI
: 0)
| PERL_PV_PRETTY_ELLIPSES
| PERL_PV_PRETTY_LTGT
)
: "???"
);
if (trie->jump) {
U16 dist= trie->jump[word_idx+1];
Perl_re_printf( aTHX_ "(%" UVuf ")\n",
(UV)((dist ? this_trie + dist : next) - start));
if (dist) {
if (!nextbranch)
nextbranch= this_trie + trie->jump[0];
DUMPUNTIL(this_trie + dist, nextbranch);
}
if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
nextbranch= regnext((regnode *)nextbranch);
} else {
Perl_re_printf( aTHX_ "\n");
}
}
if (last && next > last)
node= last;
else
node= next;
}
else if ( op == CURLY ) { /* "next" might be very big: optimizer */
DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
}
else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
assert(next);
DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
}
else if ( op == PLUS || op == STAR) {
DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
}
else if (PL_regkind[(U8)op] == ANYOF) {
/* arglen 1 + class block */
node += 1 + ((ANYOF_FLAGS(node) & ANYOF_MATCHES_POSIXL)
? ANYOF_POSIXL_SKIP
: ANYOF_SKIP);
node = NEXTOPER(node);
}
else if (PL_regkind[(U8)op] == EXACT) {
/* Literal string, where present. */
node += NODE_SZ_STR(node) - 1;
node = NEXTOPER(node);
}
else {
node = NEXTOPER(node);
node += regarglen[(U8)op];
}
if (op == CURLYX || op == OPEN)
indent++;
}
CLEAR_OPTSTART;
#ifdef DEBUG_DUMPUNTIL
Perl_re_printf( aTHX_ "--- %d\n", (int)indent);
#endif
return node;
}
#endif /* DEBUGGING */
/*
* ex: set ts=8 sts=4 sw=4 et:
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_412_2 |
crossvul-cpp_data_bad_128_0 | #include <math.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>
#include "lua.h"
#include "lauxlib.h"
#define LUACMSGPACK_NAME "cmsgpack"
#define LUACMSGPACK_SAFE_NAME "cmsgpack_safe"
#define LUACMSGPACK_VERSION "lua-cmsgpack 0.4.0"
#define LUACMSGPACK_COPYRIGHT "Copyright (C) 2012, Salvatore Sanfilippo"
#define LUACMSGPACK_DESCRIPTION "MessagePack C implementation for Lua"
/* Allows a preprocessor directive to override MAX_NESTING */
#ifndef LUACMSGPACK_MAX_NESTING
#define LUACMSGPACK_MAX_NESTING 16 /* Max tables nesting. */
#endif
/* Check if float or double can be an integer without loss of precision */
#define IS_INT_TYPE_EQUIVALENT(x, T) (!isinf(x) && (T)(x) == (x))
#define IS_INT64_EQUIVALENT(x) IS_INT_TYPE_EQUIVALENT(x, int64_t)
#define IS_INT_EQUIVALENT(x) IS_INT_TYPE_EQUIVALENT(x, int)
/* If size of pointer is equal to a 4 byte integer, we're on 32 bits. */
#if UINTPTR_MAX == UINT_MAX
#define BITS_32 1
#else
#define BITS_32 0
#endif
#if BITS_32
#define lua_pushunsigned(L, n) lua_pushnumber(L, n)
#else
#define lua_pushunsigned(L, n) lua_pushinteger(L, n)
#endif
/* =============================================================================
* MessagePack implementation and bindings for Lua 5.1/5.2.
* Copyright(C) 2012 Salvatore Sanfilippo <antirez@gmail.com>
*
* http://github.com/antirez/lua-cmsgpack
*
* For MessagePack specification check the following web site:
* http://wiki.msgpack.org/display/MSGPACK/Format+specification
*
* See Copyright Notice at the end of this file.
*
* CHANGELOG:
* 19-Feb-2012 (ver 0.1.0): Initial release.
* 20-Feb-2012 (ver 0.2.0): Tables encoding improved.
* 20-Feb-2012 (ver 0.2.1): Minor bug fixing.
* 20-Feb-2012 (ver 0.3.0): Module renamed lua-cmsgpack (was lua-msgpack).
* 04-Apr-2014 (ver 0.3.1): Lua 5.2 support and minor bug fix.
* 07-Apr-2014 (ver 0.4.0): Multiple pack/unpack, lua allocator, efficiency.
* ========================================================================== */
/* -------------------------- Endian conversion --------------------------------
* We use it only for floats and doubles, all the other conversions performed
* in an endian independent fashion. So the only thing we need is a function
* that swaps a binary string if arch is little endian (and left it untouched
* otherwise). */
/* Reverse memory bytes if arch is little endian. Given the conceptual
* simplicity of the Lua build system we prefer check for endianess at runtime.
* The performance difference should be acceptable. */
void memrevifle(void *ptr, size_t len) {
unsigned char *p = (unsigned char *)ptr,
*e = (unsigned char *)p+len-1,
aux;
int test = 1;
unsigned char *testp = (unsigned char*) &test;
if (testp[0] == 0) return; /* Big endian, nothing to do. */
len /= 2;
while(len--) {
aux = *p;
*p = *e;
*e = aux;
p++;
e--;
}
}
/* ---------------------------- String buffer ----------------------------------
* This is a simple implementation of string buffers. The only operation
* supported is creating empty buffers and appending bytes to it.
* The string buffer uses 2x preallocation on every realloc for O(N) append
* behavior. */
typedef struct mp_buf {
unsigned char *b;
size_t len, free;
} mp_buf;
void *mp_realloc(lua_State *L, void *target, size_t osize,size_t nsize) {
void *(*local_realloc) (void *, void *, size_t osize, size_t nsize) = NULL;
void *ud;
local_realloc = lua_getallocf(L, &ud);
return local_realloc(ud, target, osize, nsize);
}
mp_buf *mp_buf_new(lua_State *L) {
mp_buf *buf = NULL;
/* Old size = 0; new size = sizeof(*buf) */
buf = (mp_buf*)mp_realloc(L, NULL, 0, sizeof(*buf));
buf->b = NULL;
buf->len = buf->free = 0;
return buf;
}
void mp_buf_append(lua_State *L, mp_buf *buf, const unsigned char *s, size_t len) {
if (buf->free < len) {
size_t newsize = (buf->len+len)*2;
buf->b = (unsigned char*)mp_realloc(L, buf->b, buf->len + buf->free, newsize);
buf->free = newsize - buf->len;
}
memcpy(buf->b+buf->len,s,len);
buf->len += len;
buf->free -= len;
}
void mp_buf_free(lua_State *L, mp_buf *buf) {
mp_realloc(L, buf->b, buf->len + buf->free, 0); /* realloc to 0 = free */
mp_realloc(L, buf, sizeof(*buf), 0);
}
/* ---------------------------- String cursor ----------------------------------
* This simple data structure is used for parsing. Basically you create a cursor
* using a string pointer and a length, then it is possible to access the
* current string position with cursor->p, check the remaining length
* in cursor->left, and finally consume more string using
* mp_cur_consume(cursor,len), to advance 'p' and subtract 'left'.
* An additional field cursor->error is set to zero on initialization and can
* be used to report errors. */
#define MP_CUR_ERROR_NONE 0
#define MP_CUR_ERROR_EOF 1 /* Not enough data to complete operation. */
#define MP_CUR_ERROR_BADFMT 2 /* Bad data format */
typedef struct mp_cur {
const unsigned char *p;
size_t left;
int err;
} mp_cur;
void mp_cur_init(mp_cur *cursor, const unsigned char *s, size_t len) {
cursor->p = s;
cursor->left = len;
cursor->err = MP_CUR_ERROR_NONE;
}
#define mp_cur_consume(_c,_len) do { _c->p += _len; _c->left -= _len; } while(0)
/* When there is not enough room we set an error in the cursor and return. This
* is very common across the code so we have a macro to make the code look
* a bit simpler. */
#define mp_cur_need(_c,_len) do { \
if (_c->left < _len) { \
_c->err = MP_CUR_ERROR_EOF; \
return; \
} \
} while(0)
/* ------------------------- Low level MP encoding -------------------------- */
void mp_encode_bytes(lua_State *L, mp_buf *buf, const unsigned char *s, size_t len) {
unsigned char hdr[5];
int hdrlen;
if (len < 32) {
hdr[0] = 0xa0 | (len&0xff); /* fix raw */
hdrlen = 1;
} else if (len <= 0xff) {
hdr[0] = 0xd9;
hdr[1] = len;
hdrlen = 2;
} else if (len <= 0xffff) {
hdr[0] = 0xda;
hdr[1] = (len&0xff00)>>8;
hdr[2] = len&0xff;
hdrlen = 3;
} else {
hdr[0] = 0xdb;
hdr[1] = (len&0xff000000)>>24;
hdr[2] = (len&0xff0000)>>16;
hdr[3] = (len&0xff00)>>8;
hdr[4] = len&0xff;
hdrlen = 5;
}
mp_buf_append(L,buf,hdr,hdrlen);
mp_buf_append(L,buf,s,len);
}
/* we assume IEEE 754 internal format for single and double precision floats. */
void mp_encode_double(lua_State *L, mp_buf *buf, double d) {
unsigned char b[9];
float f = d;
assert(sizeof(f) == 4 && sizeof(d) == 8);
if (d == (double)f) {
b[0] = 0xca; /* float IEEE 754 */
memcpy(b+1,&f,4);
memrevifle(b+1,4);
mp_buf_append(L,buf,b,5);
} else if (sizeof(d) == 8) {
b[0] = 0xcb; /* double IEEE 754 */
memcpy(b+1,&d,8);
memrevifle(b+1,8);
mp_buf_append(L,buf,b,9);
}
}
void mp_encode_int(lua_State *L, mp_buf *buf, int64_t n) {
unsigned char b[9];
int enclen;
if (n >= 0) {
if (n <= 127) {
b[0] = n & 0x7f; /* positive fixnum */
enclen = 1;
} else if (n <= 0xff) {
b[0] = 0xcc; /* uint 8 */
b[1] = n & 0xff;
enclen = 2;
} else if (n <= 0xffff) {
b[0] = 0xcd; /* uint 16 */
b[1] = (n & 0xff00) >> 8;
b[2] = n & 0xff;
enclen = 3;
} else if (n <= 0xffffffffLL) {
b[0] = 0xce; /* uint 32 */
b[1] = (n & 0xff000000) >> 24;
b[2] = (n & 0xff0000) >> 16;
b[3] = (n & 0xff00) >> 8;
b[4] = n & 0xff;
enclen = 5;
} else {
b[0] = 0xcf; /* uint 64 */
b[1] = (n & 0xff00000000000000LL) >> 56;
b[2] = (n & 0xff000000000000LL) >> 48;
b[3] = (n & 0xff0000000000LL) >> 40;
b[4] = (n & 0xff00000000LL) >> 32;
b[5] = (n & 0xff000000) >> 24;
b[6] = (n & 0xff0000) >> 16;
b[7] = (n & 0xff00) >> 8;
b[8] = n & 0xff;
enclen = 9;
}
} else {
if (n >= -32) {
b[0] = ((signed char)n); /* negative fixnum */
enclen = 1;
} else if (n >= -128) {
b[0] = 0xd0; /* int 8 */
b[1] = n & 0xff;
enclen = 2;
} else if (n >= -32768) {
b[0] = 0xd1; /* int 16 */
b[1] = (n & 0xff00) >> 8;
b[2] = n & 0xff;
enclen = 3;
} else if (n >= -2147483648LL) {
b[0] = 0xd2; /* int 32 */
b[1] = (n & 0xff000000) >> 24;
b[2] = (n & 0xff0000) >> 16;
b[3] = (n & 0xff00) >> 8;
b[4] = n & 0xff;
enclen = 5;
} else {
b[0] = 0xd3; /* int 64 */
b[1] = (n & 0xff00000000000000LL) >> 56;
b[2] = (n & 0xff000000000000LL) >> 48;
b[3] = (n & 0xff0000000000LL) >> 40;
b[4] = (n & 0xff00000000LL) >> 32;
b[5] = (n & 0xff000000) >> 24;
b[6] = (n & 0xff0000) >> 16;
b[7] = (n & 0xff00) >> 8;
b[8] = n & 0xff;
enclen = 9;
}
}
mp_buf_append(L,buf,b,enclen);
}
void mp_encode_array(lua_State *L, mp_buf *buf, int64_t n) {
unsigned char b[5];
int enclen;
if (n <= 15) {
b[0] = 0x90 | (n & 0xf); /* fix array */
enclen = 1;
} else if (n <= 65535) {
b[0] = 0xdc; /* array 16 */
b[1] = (n & 0xff00) >> 8;
b[2] = n & 0xff;
enclen = 3;
} else {
b[0] = 0xdd; /* array 32 */
b[1] = (n & 0xff000000) >> 24;
b[2] = (n & 0xff0000) >> 16;
b[3] = (n & 0xff00) >> 8;
b[4] = n & 0xff;
enclen = 5;
}
mp_buf_append(L,buf,b,enclen);
}
void mp_encode_map(lua_State *L, mp_buf *buf, int64_t n) {
unsigned char b[5];
int enclen;
if (n <= 15) {
b[0] = 0x80 | (n & 0xf); /* fix map */
enclen = 1;
} else if (n <= 65535) {
b[0] = 0xde; /* map 16 */
b[1] = (n & 0xff00) >> 8;
b[2] = n & 0xff;
enclen = 3;
} else {
b[0] = 0xdf; /* map 32 */
b[1] = (n & 0xff000000) >> 24;
b[2] = (n & 0xff0000) >> 16;
b[3] = (n & 0xff00) >> 8;
b[4] = n & 0xff;
enclen = 5;
}
mp_buf_append(L,buf,b,enclen);
}
/* --------------------------- Lua types encoding --------------------------- */
void mp_encode_lua_string(lua_State *L, mp_buf *buf) {
size_t len;
const char *s;
s = lua_tolstring(L,-1,&len);
mp_encode_bytes(L,buf,(const unsigned char*)s,len);
}
void mp_encode_lua_bool(lua_State *L, mp_buf *buf) {
unsigned char b = lua_toboolean(L,-1) ? 0xc3 : 0xc2;
mp_buf_append(L,buf,&b,1);
}
/* Lua 5.3 has a built in 64-bit integer type */
void mp_encode_lua_integer(lua_State *L, mp_buf *buf) {
#if (LUA_VERSION_NUM < 503) && BITS_32
lua_Number i = lua_tonumber(L,-1);
#else
lua_Integer i = lua_tointeger(L,-1);
#endif
mp_encode_int(L, buf, (int64_t)i);
}
/* Lua 5.2 and lower only has 64-bit doubles, so we need to
* detect if the double may be representable as an int
* for Lua < 5.3 */
void mp_encode_lua_number(lua_State *L, mp_buf *buf) {
lua_Number n = lua_tonumber(L,-1);
if (IS_INT64_EQUIVALENT(n)) {
mp_encode_lua_integer(L, buf);
} else {
mp_encode_double(L,buf,(double)n);
}
}
void mp_encode_lua_type(lua_State *L, mp_buf *buf, int level);
/* Convert a lua table into a message pack list. */
void mp_encode_lua_table_as_array(lua_State *L, mp_buf *buf, int level) {
#if LUA_VERSION_NUM < 502
size_t len = lua_objlen(L,-1), j;
#else
size_t len = lua_rawlen(L,-1), j;
#endif
mp_encode_array(L,buf,len);
for (j = 1; j <= len; j++) {
lua_pushnumber(L,j);
lua_gettable(L,-2);
mp_encode_lua_type(L,buf,level+1);
}
}
/* Convert a lua table into a message pack key-value map. */
void mp_encode_lua_table_as_map(lua_State *L, mp_buf *buf, int level) {
size_t len = 0;
/* First step: count keys into table. No other way to do it with the
* Lua API, we need to iterate a first time. Note that an alternative
* would be to do a single run, and then hack the buffer to insert the
* map opcodes for message pack. Too hackish for this lib. */
lua_pushnil(L);
while(lua_next(L,-2)) {
lua_pop(L,1); /* remove value, keep key for next iteration. */
len++;
}
/* Step two: actually encoding of the map. */
mp_encode_map(L,buf,len);
lua_pushnil(L);
while(lua_next(L,-2)) {
/* Stack: ... key value */
lua_pushvalue(L,-2); /* Stack: ... key value key */
mp_encode_lua_type(L,buf,level+1); /* encode key */
mp_encode_lua_type(L,buf,level+1); /* encode val */
}
}
/* Returns true if the Lua table on top of the stack is exclusively composed
* of keys from numerical keys from 1 up to N, with N being the total number
* of elements, without any hole in the middle. */
int table_is_an_array(lua_State *L) {
int count = 0, max = 0;
#if LUA_VERSION_NUM < 503
lua_Number n;
#else
lua_Integer n;
#endif
/* Stack top on function entry */
int stacktop;
stacktop = lua_gettop(L);
lua_pushnil(L);
while(lua_next(L,-2)) {
/* Stack: ... key value */
lua_pop(L,1); /* Stack: ... key */
/* The <= 0 check is valid here because we're comparing indexes. */
#if LUA_VERSION_NUM < 503
if ((LUA_TNUMBER != lua_type(L,-1)) || (n = lua_tonumber(L, -1)) <= 0 ||
!IS_INT_EQUIVALENT(n))
#else
if (!lua_isinteger(L,-1) || (n = lua_tointeger(L, -1)) <= 0)
#endif
{
lua_settop(L, stacktop);
return 0;
}
max = (n > max ? n : max);
count++;
}
/* We have the total number of elements in "count". Also we have
* the max index encountered in "max". We can't reach this code
* if there are indexes <= 0. If you also note that there can not be
* repeated keys into a table, you have that if max==count you are sure
* that there are all the keys form 1 to count (both included). */
lua_settop(L, stacktop);
return max == count;
}
/* If the length operator returns non-zero, that is, there is at least
* an object at key '1', we serialize to message pack list. Otherwise
* we use a map. */
void mp_encode_lua_table(lua_State *L, mp_buf *buf, int level) {
if (table_is_an_array(L))
mp_encode_lua_table_as_array(L,buf,level);
else
mp_encode_lua_table_as_map(L,buf,level);
}
void mp_encode_lua_null(lua_State *L, mp_buf *buf) {
unsigned char b[1];
b[0] = 0xc0;
mp_buf_append(L,buf,b,1);
}
void mp_encode_lua_type(lua_State *L, mp_buf *buf, int level) {
int t = lua_type(L,-1);
/* Limit the encoding of nested tables to a specified maximum depth, so that
* we survive when called against circular references in tables. */
if (t == LUA_TTABLE && level == LUACMSGPACK_MAX_NESTING) t = LUA_TNIL;
switch(t) {
case LUA_TSTRING: mp_encode_lua_string(L,buf); break;
case LUA_TBOOLEAN: mp_encode_lua_bool(L,buf); break;
case LUA_TNUMBER:
#if LUA_VERSION_NUM < 503
mp_encode_lua_number(L,buf); break;
#else
if (lua_isinteger(L, -1)) {
mp_encode_lua_integer(L, buf);
} else {
mp_encode_lua_number(L, buf);
}
break;
#endif
case LUA_TTABLE: mp_encode_lua_table(L,buf,level); break;
default: mp_encode_lua_null(L,buf); break;
}
lua_pop(L,1);
}
/*
* Packs all arguments as a stream for multiple upacking later.
* Returns error if no arguments provided.
*/
int mp_pack(lua_State *L) {
int nargs = lua_gettop(L);
int i;
mp_buf *buf;
if (nargs == 0)
return luaL_argerror(L, 0, "MessagePack pack needs input.");
buf = mp_buf_new(L);
for(i = 1; i <= nargs; i++) {
/* Copy argument i to top of stack for _encode processing;
* the encode function pops it from the stack when complete. */
lua_pushvalue(L, i);
mp_encode_lua_type(L,buf,0);
lua_pushlstring(L,(char*)buf->b,buf->len);
/* Reuse the buffer for the next operation by
* setting its free count to the total buffer size
* and the current position to zero. */
buf->free += buf->len;
buf->len = 0;
}
mp_buf_free(L, buf);
/* Concatenate all nargs buffers together */
lua_concat(L, nargs);
return 1;
}
/* ------------------------------- Decoding --------------------------------- */
void mp_decode_to_lua_type(lua_State *L, mp_cur *c);
void mp_decode_to_lua_array(lua_State *L, mp_cur *c, size_t len) {
assert(len <= UINT_MAX);
int index = 1;
lua_newtable(L);
while(len--) {
lua_pushnumber(L,index++);
mp_decode_to_lua_type(L,c);
if (c->err) return;
lua_settable(L,-3);
}
}
void mp_decode_to_lua_hash(lua_State *L, mp_cur *c, size_t len) {
assert(len <= UINT_MAX);
lua_newtable(L);
while(len--) {
mp_decode_to_lua_type(L,c); /* key */
if (c->err) return;
mp_decode_to_lua_type(L,c); /* value */
if (c->err) return;
lua_settable(L,-3);
}
}
/* Decode a Message Pack raw object pointed by the string cursor 'c' to
* a Lua type, that is left as the only result on the stack. */
void mp_decode_to_lua_type(lua_State *L, mp_cur *c) {
mp_cur_need(c,1);
/* If we return more than 18 elements, we must resize the stack to
* fit all our return values. But, there is no way to
* determine how many objects a msgpack will unpack to up front, so
* we request a +1 larger stack on each iteration (noop if stack is
* big enough, and when stack does require resize it doubles in size) */
luaL_checkstack(L, 1,
"too many return values at once; "
"use unpack_one or unpack_limit instead.");
switch(c->p[0]) {
case 0xcc: /* uint 8 */
mp_cur_need(c,2);
lua_pushunsigned(L,c->p[1]);
mp_cur_consume(c,2);
break;
case 0xd0: /* int 8 */
mp_cur_need(c,2);
lua_pushinteger(L,(signed char)c->p[1]);
mp_cur_consume(c,2);
break;
case 0xcd: /* uint 16 */
mp_cur_need(c,3);
lua_pushunsigned(L,
(c->p[1] << 8) |
c->p[2]);
mp_cur_consume(c,3);
break;
case 0xd1: /* int 16 */
mp_cur_need(c,3);
lua_pushinteger(L,(int16_t)
(c->p[1] << 8) |
c->p[2]);
mp_cur_consume(c,3);
break;
case 0xce: /* uint 32 */
mp_cur_need(c,5);
lua_pushunsigned(L,
((uint32_t)c->p[1] << 24) |
((uint32_t)c->p[2] << 16) |
((uint32_t)c->p[3] << 8) |
(uint32_t)c->p[4]);
mp_cur_consume(c,5);
break;
case 0xd2: /* int 32 */
mp_cur_need(c,5);
lua_pushinteger(L,
((int32_t)c->p[1] << 24) |
((int32_t)c->p[2] << 16) |
((int32_t)c->p[3] << 8) |
(int32_t)c->p[4]);
mp_cur_consume(c,5);
break;
case 0xcf: /* uint 64 */
mp_cur_need(c,9);
lua_pushunsigned(L,
((uint64_t)c->p[1] << 56) |
((uint64_t)c->p[2] << 48) |
((uint64_t)c->p[3] << 40) |
((uint64_t)c->p[4] << 32) |
((uint64_t)c->p[5] << 24) |
((uint64_t)c->p[6] << 16) |
((uint64_t)c->p[7] << 8) |
(uint64_t)c->p[8]);
mp_cur_consume(c,9);
break;
case 0xd3: /* int 64 */
mp_cur_need(c,9);
#if LUA_VERSION_NUM < 503
lua_pushnumber(L,
#else
lua_pushinteger(L,
#endif
((int64_t)c->p[1] << 56) |
((int64_t)c->p[2] << 48) |
((int64_t)c->p[3] << 40) |
((int64_t)c->p[4] << 32) |
((int64_t)c->p[5] << 24) |
((int64_t)c->p[6] << 16) |
((int64_t)c->p[7] << 8) |
(int64_t)c->p[8]);
mp_cur_consume(c,9);
break;
case 0xc0: /* nil */
lua_pushnil(L);
mp_cur_consume(c,1);
break;
case 0xc3: /* true */
lua_pushboolean(L,1);
mp_cur_consume(c,1);
break;
case 0xc2: /* false */
lua_pushboolean(L,0);
mp_cur_consume(c,1);
break;
case 0xca: /* float */
mp_cur_need(c,5);
assert(sizeof(float) == 4);
{
float f;
memcpy(&f,c->p+1,4);
memrevifle(&f,4);
lua_pushnumber(L,f);
mp_cur_consume(c,5);
}
break;
case 0xcb: /* double */
mp_cur_need(c,9);
assert(sizeof(double) == 8);
{
double d;
memcpy(&d,c->p+1,8);
memrevifle(&d,8);
lua_pushnumber(L,d);
mp_cur_consume(c,9);
}
break;
case 0xd9: /* raw 8 */
mp_cur_need(c,2);
{
size_t l = c->p[1];
mp_cur_need(c,2+l);
lua_pushlstring(L,(char*)c->p+2,l);
mp_cur_consume(c,2+l);
}
break;
case 0xda: /* raw 16 */
mp_cur_need(c,3);
{
size_t l = (c->p[1] << 8) | c->p[2];
mp_cur_need(c,3+l);
lua_pushlstring(L,(char*)c->p+3,l);
mp_cur_consume(c,3+l);
}
break;
case 0xdb: /* raw 32 */
mp_cur_need(c,5);
{
size_t l = ((size_t)c->p[1] << 24) |
((size_t)c->p[2] << 16) |
((size_t)c->p[3] << 8) |
(size_t)c->p[4];
mp_cur_consume(c,5);
mp_cur_need(c,l);
lua_pushlstring(L,(char*)c->p,l);
mp_cur_consume(c,l);
}
break;
case 0xdc: /* array 16 */
mp_cur_need(c,3);
{
size_t l = (c->p[1] << 8) | c->p[2];
mp_cur_consume(c,3);
mp_decode_to_lua_array(L,c,l);
}
break;
case 0xdd: /* array 32 */
mp_cur_need(c,5);
{
size_t l = ((size_t)c->p[1] << 24) |
((size_t)c->p[2] << 16) |
((size_t)c->p[3] << 8) |
(size_t)c->p[4];
mp_cur_consume(c,5);
mp_decode_to_lua_array(L,c,l);
}
break;
case 0xde: /* map 16 */
mp_cur_need(c,3);
{
size_t l = (c->p[1] << 8) | c->p[2];
mp_cur_consume(c,3);
mp_decode_to_lua_hash(L,c,l);
}
break;
case 0xdf: /* map 32 */
mp_cur_need(c,5);
{
size_t l = ((size_t)c->p[1] << 24) |
((size_t)c->p[2] << 16) |
((size_t)c->p[3] << 8) |
(size_t)c->p[4];
mp_cur_consume(c,5);
mp_decode_to_lua_hash(L,c,l);
}
break;
default: /* types that can't be idenitified by first byte value. */
if ((c->p[0] & 0x80) == 0) { /* positive fixnum */
lua_pushunsigned(L,c->p[0]);
mp_cur_consume(c,1);
} else if ((c->p[0] & 0xe0) == 0xe0) { /* negative fixnum */
lua_pushinteger(L,(signed char)c->p[0]);
mp_cur_consume(c,1);
} else if ((c->p[0] & 0xe0) == 0xa0) { /* fix raw */
size_t l = c->p[0] & 0x1f;
mp_cur_need(c,1+l);
lua_pushlstring(L,(char*)c->p+1,l);
mp_cur_consume(c,1+l);
} else if ((c->p[0] & 0xf0) == 0x90) { /* fix map */
size_t l = c->p[0] & 0xf;
mp_cur_consume(c,1);
mp_decode_to_lua_array(L,c,l);
} else if ((c->p[0] & 0xf0) == 0x80) { /* fix map */
size_t l = c->p[0] & 0xf;
mp_cur_consume(c,1);
mp_decode_to_lua_hash(L,c,l);
} else {
c->err = MP_CUR_ERROR_BADFMT;
}
}
}
int mp_unpack_full(lua_State *L, int limit, int offset) {
size_t len;
const char *s;
mp_cur c;
int cnt; /* Number of objects unpacked */
int decode_all = (!limit && !offset);
s = luaL_checklstring(L,1,&len); /* if no match, exits */
if (offset < 0 || limit < 0) /* requesting negative off or lim is invalid */
return luaL_error(L,
"Invalid request to unpack with offset of %d and limit of %d.",
offset, len);
else if (offset > len)
return luaL_error(L,
"Start offset %d greater than input length %d.", offset, len);
if (decode_all) limit = INT_MAX;
mp_cur_init(&c,(const unsigned char *)s+offset,len-offset);
/* We loop over the decode because this could be a stream
* of multiple top-level values serialized together */
for(cnt = 0; c.left > 0 && cnt < limit; cnt++) {
mp_decode_to_lua_type(L,&c);
if (c.err == MP_CUR_ERROR_EOF) {
return luaL_error(L,"Missing bytes in input.");
} else if (c.err == MP_CUR_ERROR_BADFMT) {
return luaL_error(L,"Bad data format in input.");
}
}
if (!decode_all) {
/* c->left is the remaining size of the input buffer.
* subtract the entire buffer size from the unprocessed size
* to get our next start offset */
int offset = len - c.left;
/* Return offset -1 when we have have processed the entire buffer. */
lua_pushinteger(L, c.left == 0 ? -1 : offset);
/* Results are returned with the arg elements still
* in place. Lua takes care of only returning
* elements above the args for us.
* In this case, we have one arg on the stack
* for this function, so we insert our first return
* value at position 2. */
lua_insert(L, 2);
cnt += 1; /* increase return count by one to make room for offset */
}
return cnt;
}
int mp_unpack(lua_State *L) {
return mp_unpack_full(L, 0, 0);
}
int mp_unpack_one(lua_State *L) {
int offset = luaL_optinteger(L, 2, 0);
/* Variable pop because offset may not exist */
lua_pop(L, lua_gettop(L)-1);
return mp_unpack_full(L, 1, offset);
}
int mp_unpack_limit(lua_State *L) {
int limit = luaL_checkinteger(L, 2);
int offset = luaL_optinteger(L, 3, 0);
/* Variable pop because offset may not exist */
lua_pop(L, lua_gettop(L)-1);
return mp_unpack_full(L, limit, offset);
}
int mp_safe(lua_State *L) {
int argc, err, total_results;
argc = lua_gettop(L);
/* This adds our function to the bottom of the stack
* (the "call this function" position) */
lua_pushvalue(L, lua_upvalueindex(1));
lua_insert(L, 1);
err = lua_pcall(L, argc, LUA_MULTRET, 0);
total_results = lua_gettop(L);
if (!err) {
return total_results;
} else {
lua_pushnil(L);
lua_insert(L,-2);
return 2;
}
}
/* -------------------------------------------------------------------------- */
const struct luaL_Reg cmds[] = {
{"pack", mp_pack},
{"unpack", mp_unpack},
{"unpack_one", mp_unpack_one},
{"unpack_limit", mp_unpack_limit},
{0}
};
int luaopen_create(lua_State *L) {
int i;
/* Manually construct our module table instead of
* relying on _register or _newlib */
lua_newtable(L);
for (i = 0; i < (sizeof(cmds)/sizeof(*cmds) - 1); i++) {
lua_pushcfunction(L, cmds[i].func);
lua_setfield(L, -2, cmds[i].name);
}
/* Add metadata */
lua_pushliteral(L, LUACMSGPACK_NAME);
lua_setfield(L, -2, "_NAME");
lua_pushliteral(L, LUACMSGPACK_VERSION);
lua_setfield(L, -2, "_VERSION");
lua_pushliteral(L, LUACMSGPACK_COPYRIGHT);
lua_setfield(L, -2, "_COPYRIGHT");
lua_pushliteral(L, LUACMSGPACK_DESCRIPTION);
lua_setfield(L, -2, "_DESCRIPTION");
return 1;
}
LUALIB_API int luaopen_cmsgpack(lua_State *L) {
luaopen_create(L);
#if LUA_VERSION_NUM < 502
/* Register name globally for 5.1 */
lua_pushvalue(L, -1);
lua_setglobal(L, LUACMSGPACK_NAME);
#endif
return 1;
}
LUALIB_API int luaopen_cmsgpack_safe(lua_State *L) {
int i;
luaopen_cmsgpack(L);
/* Wrap all functions in the safe handler */
for (i = 0; i < (sizeof(cmds)/sizeof(*cmds) - 1); i++) {
lua_getfield(L, -1, cmds[i].name);
lua_pushcclosure(L, mp_safe, 1);
lua_setfield(L, -2, cmds[i].name);
}
#if LUA_VERSION_NUM < 502
/* Register name globally for 5.1 */
lua_pushvalue(L, -1);
lua_setglobal(L, LUACMSGPACK_SAFE_NAME);
#endif
return 1;
}
/******************************************************************************
* Copyright (C) 2012 Salvatore Sanfilippo. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************************/
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_128_0 |
crossvul-cpp_data_bad_2767_0 | #include "../fbuffer/fbuffer.h"
#include "generator.h"
#ifdef HAVE_RUBY_ENCODING_H
static VALUE CEncoding_UTF_8;
static ID i_encoding, i_encode;
#endif
static VALUE mJSON, mExt, mGenerator, cState, mGeneratorMethods, mObject,
mHash, mArray,
#ifdef RUBY_INTEGER_UNIFICATION
mInteger,
#else
mFixnum, mBignum,
#endif
mFloat, mString, mString_Extend,
mTrueClass, mFalseClass, mNilClass, eGeneratorError,
eNestingError, CRegexp_MULTILINE, CJSON_SAFE_STATE_PROTOTYPE,
i_SAFE_STATE_PROTOTYPE;
static ID i_to_s, i_to_json, i_new, i_indent, i_space, i_space_before,
i_object_nl, i_array_nl, i_max_nesting, i_allow_nan, i_ascii_only,
i_pack, i_unpack, i_create_id, i_extend, i_key_p,
i_aref, i_send, i_respond_to_p, i_match, i_keys, i_depth,
i_buffer_initial_length, i_dup;
/*
* Copyright 2001-2004 Unicode, Inc.
*
* Disclaimer
*
* This source code is provided as is by Unicode, Inc. No claims are
* made as to fitness for any particular purpose. No warranties of any
* kind are expressed or implied. The recipient agrees to determine
* applicability of information provided. If this file has been
* purchased on magnetic or optical media from Unicode, Inc., the
* sole remedy for any claim will be exchange of defective media
* within 90 days of receipt.
*
* Limitations on Rights to Redistribute This Code
*
* Unicode, Inc. hereby grants the right to freely use the information
* supplied in this file in the creation of products supporting the
* Unicode Standard, and to make copies of this file in any form
* for internal or external distribution as long as this notice
* remains attached.
*/
/*
* Index into the table below with the first byte of a UTF-8 sequence to
* get the number of trailing bytes that are supposed to follow it.
* Note that *legal* UTF-8 values can't have 4 or 5-bytes. The table is
* left as-is for anyone who may want to do such conversion, which was
* allowed in earlier algorithms.
*/
static const char trailingBytesForUTF8[256] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
};
/*
* Magic values subtracted from a buffer value during UTF8 conversion.
* This table contains as many values as there might be trailing bytes
* in a UTF-8 sequence.
*/
static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL,
0x03C82080UL, 0xFA082080UL, 0x82082080UL };
/*
* Utility routine to tell whether a sequence of bytes is legal UTF-8.
* This must be called with the length pre-determined by the first byte.
* If not calling this from ConvertUTF8to*, then the length can be set by:
* length = trailingBytesForUTF8[*source]+1;
* and the sequence is illegal right away if there aren't that many bytes
* available.
* If presented with a length > 4, this returns 0. The Unicode
* definition of UTF-8 goes up to 4-byte sequences.
*/
static unsigned char isLegalUTF8(const UTF8 *source, unsigned long length)
{
UTF8 a;
const UTF8 *srcptr = source+length;
switch (length) {
default: return 0;
/* Everything else falls through when "1"... */
case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0;
case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0;
case 2: if ((a = (*--srcptr)) > 0xBF) return 0;
switch (*source) {
/* no fall-through in this inner switch */
case 0xE0: if (a < 0xA0) return 0; break;
case 0xED: if (a > 0x9F) return 0; break;
case 0xF0: if (a < 0x90) return 0; break;
case 0xF4: if (a > 0x8F) return 0; break;
default: if (a < 0x80) return 0;
}
case 1: if (*source >= 0x80 && *source < 0xC2) return 0;
}
if (*source > 0xF4) return 0;
return 1;
}
/* Escapes the UTF16 character and stores the result in the buffer buf. */
static void unicode_escape(char *buf, UTF16 character)
{
const char *digits = "0123456789abcdef";
buf[2] = digits[character >> 12];
buf[3] = digits[(character >> 8) & 0xf];
buf[4] = digits[(character >> 4) & 0xf];
buf[5] = digits[character & 0xf];
}
/* Escapes the UTF16 character and stores the result in the buffer buf, then
* the buffer buf is appended to the FBuffer buffer. */
static void unicode_escape_to_buffer(FBuffer *buffer, char buf[6], UTF16
character)
{
unicode_escape(buf, character);
fbuffer_append(buffer, buf, 6);
}
/* Converts string to a JSON string in FBuffer buffer, where all but the ASCII
* and control characters are JSON escaped. */
static void convert_UTF8_to_JSON_ASCII(FBuffer *buffer, VALUE string)
{
const UTF8 *source = (UTF8 *) RSTRING_PTR(string);
const UTF8 *sourceEnd = source + RSTRING_LEN(string);
char buf[6] = { '\\', 'u' };
while (source < sourceEnd) {
UTF32 ch = 0;
unsigned short extraBytesToRead = trailingBytesForUTF8[*source];
if (source + extraBytesToRead >= sourceEnd) {
rb_raise(rb_path2class("JSON::GeneratorError"),
"partial character in source, but hit end");
}
if (!isLegalUTF8(source, extraBytesToRead+1)) {
rb_raise(rb_path2class("JSON::GeneratorError"),
"source sequence is illegal/malformed utf-8");
}
/*
* The cases all fall through. See "Note A" below.
*/
switch (extraBytesToRead) {
case 5: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */
case 4: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */
case 3: ch += *source++; ch <<= 6;
case 2: ch += *source++; ch <<= 6;
case 1: ch += *source++; ch <<= 6;
case 0: ch += *source++;
}
ch -= offsetsFromUTF8[extraBytesToRead];
if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */
/* UTF-16 surrogate values are illegal in UTF-32 */
if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
#if UNI_STRICT_CONVERSION
source -= (extraBytesToRead+1); /* return to the illegal value itself */
rb_raise(rb_path2class("JSON::GeneratorError"),
"source sequence is illegal/malformed utf-8");
#else
unicode_escape_to_buffer(buffer, buf, UNI_REPLACEMENT_CHAR);
#endif
} else {
/* normal case */
if (ch >= 0x20 && ch <= 0x7f) {
switch (ch) {
case '\\':
fbuffer_append(buffer, "\\\\", 2);
break;
case '"':
fbuffer_append(buffer, "\\\"", 2);
break;
default:
fbuffer_append_char(buffer, (char)ch);
break;
}
} else {
switch (ch) {
case '\n':
fbuffer_append(buffer, "\\n", 2);
break;
case '\r':
fbuffer_append(buffer, "\\r", 2);
break;
case '\t':
fbuffer_append(buffer, "\\t", 2);
break;
case '\f':
fbuffer_append(buffer, "\\f", 2);
break;
case '\b':
fbuffer_append(buffer, "\\b", 2);
break;
default:
unicode_escape_to_buffer(buffer, buf, (UTF16) ch);
break;
}
}
}
} else if (ch > UNI_MAX_UTF16) {
#if UNI_STRICT_CONVERSION
source -= (extraBytesToRead+1); /* return to the start */
rb_raise(rb_path2class("JSON::GeneratorError"),
"source sequence is illegal/malformed utf8");
#else
unicode_escape_to_buffer(buffer, buf, UNI_REPLACEMENT_CHAR);
#endif
} else {
/* target is a character in range 0xFFFF - 0x10FFFF. */
ch -= halfBase;
unicode_escape_to_buffer(buffer, buf, (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START));
unicode_escape_to_buffer(buffer, buf, (UTF16)((ch & halfMask) + UNI_SUR_LOW_START));
}
}
RB_GC_GUARD(string);
}
/* Converts string to a JSON string in FBuffer buffer, where only the
* characters required by the JSON standard are JSON escaped. The remaining
* characters (should be UTF8) are just passed through and appended to the
* result. */
static void convert_UTF8_to_JSON(FBuffer *buffer, VALUE string)
{
const char *ptr = RSTRING_PTR(string), *p;
unsigned long len = RSTRING_LEN(string), start = 0, end = 0;
const char *escape = NULL;
int escape_len;
unsigned char c;
char buf[6] = { '\\', 'u' };
for (start = 0, end = 0; end < len;) {
p = ptr + end;
c = (unsigned char) *p;
if (c < 0x20) {
switch (c) {
case '\n':
escape = "\\n";
escape_len = 2;
break;
case '\r':
escape = "\\r";
escape_len = 2;
break;
case '\t':
escape = "\\t";
escape_len = 2;
break;
case '\f':
escape = "\\f";
escape_len = 2;
break;
case '\b':
escape = "\\b";
escape_len = 2;
break;
default:
unicode_escape(buf, (UTF16) *p);
escape = buf;
escape_len = 6;
break;
}
} else {
switch (c) {
case '\\':
escape = "\\\\";
escape_len = 2;
break;
case '"':
escape = "\\\"";
escape_len = 2;
break;
default:
{
unsigned short clen = trailingBytesForUTF8[c] + 1;
if (end + clen > len) {
rb_raise(rb_path2class("JSON::GeneratorError"),
"partial character in source, but hit end");
}
if (!isLegalUTF8((UTF8 *) p, clen)) {
rb_raise(rb_path2class("JSON::GeneratorError"),
"source sequence is illegal/malformed utf-8");
}
end += clen;
}
continue;
break;
}
}
fbuffer_append(buffer, ptr + start, end - start);
fbuffer_append(buffer, escape, escape_len);
start = ++end;
escape = NULL;
}
fbuffer_append(buffer, ptr + start, end - start);
}
static char *fstrndup(const char *ptr, unsigned long len) {
char *result;
if (len <= 0) return NULL;
result = ALLOC_N(char, len);
memccpy(result, ptr, 0, len);
return result;
}
/*
* Document-module: JSON::Ext::Generator
*
* This is the JSON generator implemented as a C extension. It can be
* configured to be used by setting
*
* JSON.generator = JSON::Ext::Generator
*
* with the method generator= in JSON.
*
*/
/*
* call-seq: to_json(state = nil)
*
* Returns a JSON string containing a JSON object, that is generated from
* this Hash instance.
* _state_ is a JSON::State object, that can also be used to configure the
* produced JSON string output further.
*/
static VALUE mHash_to_json(int argc, VALUE *argv, VALUE self)
{
GENERATE_JSON(object);
}
/*
* call-seq: to_json(state = nil)
*
* Returns a JSON string containing a JSON array, that is generated from
* this Array instance.
* _state_ is a JSON::State object, that can also be used to configure the
* produced JSON string output further.
*/
static VALUE mArray_to_json(int argc, VALUE *argv, VALUE self) {
GENERATE_JSON(array);
}
#ifdef RUBY_INTEGER_UNIFICATION
/*
* call-seq: to_json(*)
*
* Returns a JSON string representation for this Integer number.
*/
static VALUE mInteger_to_json(int argc, VALUE *argv, VALUE self)
{
GENERATE_JSON(integer);
}
#else
/*
* call-seq: to_json(*)
*
* Returns a JSON string representation for this Integer number.
*/
static VALUE mFixnum_to_json(int argc, VALUE *argv, VALUE self)
{
GENERATE_JSON(fixnum);
}
/*
* call-seq: to_json(*)
*
* Returns a JSON string representation for this Integer number.
*/
static VALUE mBignum_to_json(int argc, VALUE *argv, VALUE self)
{
GENERATE_JSON(bignum);
}
#endif
/*
* call-seq: to_json(*)
*
* Returns a JSON string representation for this Float number.
*/
static VALUE mFloat_to_json(int argc, VALUE *argv, VALUE self)
{
GENERATE_JSON(float);
}
/*
* call-seq: String.included(modul)
*
* Extends _modul_ with the String::Extend module.
*/
static VALUE mString_included_s(VALUE self, VALUE modul) {
VALUE result = rb_funcall(modul, i_extend, 1, mString_Extend);
return result;
}
/*
* call-seq: to_json(*)
*
* This string should be encoded with UTF-8 A call to this method
* returns a JSON string encoded with UTF16 big endian characters as
* \u????.
*/
static VALUE mString_to_json(int argc, VALUE *argv, VALUE self)
{
GENERATE_JSON(string);
}
/*
* call-seq: to_json_raw_object()
*
* This method creates a raw object hash, that can be nested into
* other data structures and will be generated as a raw string. This
* method should be used, if you want to convert raw strings to JSON
* instead of UTF-8 strings, e. g. binary data.
*/
static VALUE mString_to_json_raw_object(VALUE self)
{
VALUE ary;
VALUE result = rb_hash_new();
rb_hash_aset(result, rb_funcall(mJSON, i_create_id, 0), rb_class_name(rb_obj_class(self)));
ary = rb_funcall(self, i_unpack, 1, rb_str_new2("C*"));
rb_hash_aset(result, rb_str_new2("raw"), ary);
return result;
}
/*
* call-seq: to_json_raw(*args)
*
* This method creates a JSON text from the result of a call to
* to_json_raw_object of this String.
*/
static VALUE mString_to_json_raw(int argc, VALUE *argv, VALUE self)
{
VALUE obj = mString_to_json_raw_object(self);
Check_Type(obj, T_HASH);
return mHash_to_json(argc, argv, obj);
}
/*
* call-seq: json_create(o)
*
* Raw Strings are JSON Objects (the raw bytes are stored in an array for the
* key "raw"). The Ruby String can be created by this module method.
*/
static VALUE mString_Extend_json_create(VALUE self, VALUE o)
{
VALUE ary;
Check_Type(o, T_HASH);
ary = rb_hash_aref(o, rb_str_new2("raw"));
return rb_funcall(ary, i_pack, 1, rb_str_new2("C*"));
}
/*
* call-seq: to_json(*)
*
* Returns a JSON string for true: 'true'.
*/
static VALUE mTrueClass_to_json(int argc, VALUE *argv, VALUE self)
{
GENERATE_JSON(true);
}
/*
* call-seq: to_json(*)
*
* Returns a JSON string for false: 'false'.
*/
static VALUE mFalseClass_to_json(int argc, VALUE *argv, VALUE self)
{
GENERATE_JSON(false);
}
/*
* call-seq: to_json(*)
*
* Returns a JSON string for nil: 'null'.
*/
static VALUE mNilClass_to_json(int argc, VALUE *argv, VALUE self)
{
GENERATE_JSON(null);
}
/*
* call-seq: to_json(*)
*
* Converts this object to a string (calling #to_s), converts
* it to a JSON string, and returns the result. This is a fallback, if no
* special method #to_json was defined for some object.
*/
static VALUE mObject_to_json(int argc, VALUE *argv, VALUE self)
{
VALUE state;
VALUE string = rb_funcall(self, i_to_s, 0);
rb_scan_args(argc, argv, "01", &state);
Check_Type(string, T_STRING);
state = cState_from_state_s(cState, state);
return cState_partial_generate(state, string);
}
static void State_free(void *ptr)
{
JSON_Generator_State *state = ptr;
if (state->indent) ruby_xfree(state->indent);
if (state->space) ruby_xfree(state->space);
if (state->space_before) ruby_xfree(state->space_before);
if (state->object_nl) ruby_xfree(state->object_nl);
if (state->array_nl) ruby_xfree(state->array_nl);
if (state->array_delim) fbuffer_free(state->array_delim);
if (state->object_delim) fbuffer_free(state->object_delim);
if (state->object_delim2) fbuffer_free(state->object_delim2);
ruby_xfree(state);
}
static size_t State_memsize(const void *ptr)
{
const JSON_Generator_State *state = ptr;
size_t size = sizeof(*state);
if (state->indent) size += state->indent_len + 1;
if (state->space) size += state->space_len + 1;
if (state->space_before) size += state->space_before_len + 1;
if (state->object_nl) size += state->object_nl_len + 1;
if (state->array_nl) size += state->array_nl_len + 1;
if (state->array_delim) size += FBUFFER_CAPA(state->array_delim);
if (state->object_delim) size += FBUFFER_CAPA(state->object_delim);
if (state->object_delim2) size += FBUFFER_CAPA(state->object_delim2);
return size;
}
#ifdef NEW_TYPEDDATA_WRAPPER
static const rb_data_type_t JSON_Generator_State_type = {
"JSON/Generator/State",
{NULL, State_free, State_memsize,},
#ifdef RUBY_TYPED_FREE_IMMEDIATELY
0, 0,
RUBY_TYPED_FREE_IMMEDIATELY,
#endif
};
#endif
static VALUE cState_s_allocate(VALUE klass)
{
JSON_Generator_State *state;
return TypedData_Make_Struct(klass, JSON_Generator_State,
&JSON_Generator_State_type, state);
}
/*
* call-seq: configure(opts)
*
* Configure this State instance with the Hash _opts_, and return
* itself.
*/
static VALUE cState_configure(VALUE self, VALUE opts)
{
VALUE tmp;
GET_STATE(self);
tmp = rb_check_convert_type(opts, T_HASH, "Hash", "to_hash");
if (NIL_P(tmp)) tmp = rb_convert_type(opts, T_HASH, "Hash", "to_h");
opts = tmp;
tmp = rb_hash_aref(opts, ID2SYM(i_indent));
if (RTEST(tmp)) {
unsigned long len;
Check_Type(tmp, T_STRING);
len = RSTRING_LEN(tmp);
state->indent = fstrndup(RSTRING_PTR(tmp), len + 1);
state->indent_len = len;
}
tmp = rb_hash_aref(opts, ID2SYM(i_space));
if (RTEST(tmp)) {
unsigned long len;
Check_Type(tmp, T_STRING);
len = RSTRING_LEN(tmp);
state->space = fstrndup(RSTRING_PTR(tmp), len + 1);
state->space_len = len;
}
tmp = rb_hash_aref(opts, ID2SYM(i_space_before));
if (RTEST(tmp)) {
unsigned long len;
Check_Type(tmp, T_STRING);
len = RSTRING_LEN(tmp);
state->space_before = fstrndup(RSTRING_PTR(tmp), len + 1);
state->space_before_len = len;
}
tmp = rb_hash_aref(opts, ID2SYM(i_array_nl));
if (RTEST(tmp)) {
unsigned long len;
Check_Type(tmp, T_STRING);
len = RSTRING_LEN(tmp);
state->array_nl = fstrndup(RSTRING_PTR(tmp), len + 1);
state->array_nl_len = len;
}
tmp = rb_hash_aref(opts, ID2SYM(i_object_nl));
if (RTEST(tmp)) {
unsigned long len;
Check_Type(tmp, T_STRING);
len = RSTRING_LEN(tmp);
state->object_nl = fstrndup(RSTRING_PTR(tmp), len + 1);
state->object_nl_len = len;
}
tmp = ID2SYM(i_max_nesting);
state->max_nesting = 100;
if (option_given_p(opts, tmp)) {
VALUE max_nesting = rb_hash_aref(opts, tmp);
if (RTEST(max_nesting)) {
Check_Type(max_nesting, T_FIXNUM);
state->max_nesting = FIX2LONG(max_nesting);
} else {
state->max_nesting = 0;
}
}
tmp = ID2SYM(i_depth);
state->depth = 0;
if (option_given_p(opts, tmp)) {
VALUE depth = rb_hash_aref(opts, tmp);
if (RTEST(depth)) {
Check_Type(depth, T_FIXNUM);
state->depth = FIX2LONG(depth);
} else {
state->depth = 0;
}
}
tmp = ID2SYM(i_buffer_initial_length);
if (option_given_p(opts, tmp)) {
VALUE buffer_initial_length = rb_hash_aref(opts, tmp);
if (RTEST(buffer_initial_length)) {
long initial_length;
Check_Type(buffer_initial_length, T_FIXNUM);
initial_length = FIX2LONG(buffer_initial_length);
if (initial_length > 0) state->buffer_initial_length = initial_length;
}
}
tmp = rb_hash_aref(opts, ID2SYM(i_allow_nan));
state->allow_nan = RTEST(tmp);
tmp = rb_hash_aref(opts, ID2SYM(i_ascii_only));
state->ascii_only = RTEST(tmp);
return self;
}
static void set_state_ivars(VALUE hash, VALUE state)
{
VALUE ivars = rb_obj_instance_variables(state);
int i = 0;
for (i = 0; i < RARRAY_LEN(ivars); i++) {
VALUE key = rb_funcall(rb_ary_entry(ivars, i), i_to_s, 0);
long key_len = RSTRING_LEN(key);
VALUE value = rb_iv_get(state, StringValueCStr(key));
rb_hash_aset(hash, rb_str_intern(rb_str_substr(key, 1, key_len - 1)), value);
}
}
/*
* call-seq: to_h
*
* Returns the configuration instance variables as a hash, that can be
* passed to the configure method.
*/
static VALUE cState_to_h(VALUE self)
{
VALUE result = rb_hash_new();
GET_STATE(self);
set_state_ivars(result, self);
rb_hash_aset(result, ID2SYM(i_indent), rb_str_new(state->indent, state->indent_len));
rb_hash_aset(result, ID2SYM(i_space), rb_str_new(state->space, state->space_len));
rb_hash_aset(result, ID2SYM(i_space_before), rb_str_new(state->space_before, state->space_before_len));
rb_hash_aset(result, ID2SYM(i_object_nl), rb_str_new(state->object_nl, state->object_nl_len));
rb_hash_aset(result, ID2SYM(i_array_nl), rb_str_new(state->array_nl, state->array_nl_len));
rb_hash_aset(result, ID2SYM(i_allow_nan), state->allow_nan ? Qtrue : Qfalse);
rb_hash_aset(result, ID2SYM(i_ascii_only), state->ascii_only ? Qtrue : Qfalse);
rb_hash_aset(result, ID2SYM(i_max_nesting), LONG2FIX(state->max_nesting));
rb_hash_aset(result, ID2SYM(i_depth), LONG2FIX(state->depth));
rb_hash_aset(result, ID2SYM(i_buffer_initial_length), LONG2FIX(state->buffer_initial_length));
return result;
}
/*
* call-seq: [](name)
*
* Returns the value returned by method +name+.
*/
static VALUE cState_aref(VALUE self, VALUE name)
{
name = rb_funcall(name, i_to_s, 0);
if (RTEST(rb_funcall(self, i_respond_to_p, 1, name))) {
return rb_funcall(self, i_send, 1, name);
} else {
return rb_ivar_get(self, rb_intern_str(rb_str_concat(rb_str_new2("@"), name)));
}
}
/*
* call-seq: []=(name, value)
*
* Sets the attribute name to value.
*/
static VALUE cState_aset(VALUE self, VALUE name, VALUE value)
{
VALUE name_writer;
name = rb_funcall(name, i_to_s, 0);
name_writer = rb_str_cat2(rb_str_dup(name), "=");
if (RTEST(rb_funcall(self, i_respond_to_p, 1, name_writer))) {
return rb_funcall(self, i_send, 2, name_writer, value);
} else {
rb_ivar_set(self, rb_intern_str(rb_str_concat(rb_str_new2("@"), name)), value);
}
return Qnil;
}
static void generate_json_object(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
{
char *object_nl = state->object_nl;
long object_nl_len = state->object_nl_len;
char *indent = state->indent;
long indent_len = state->indent_len;
long max_nesting = state->max_nesting;
char *delim = FBUFFER_PTR(state->object_delim);
long delim_len = FBUFFER_LEN(state->object_delim);
char *delim2 = FBUFFER_PTR(state->object_delim2);
long delim2_len = FBUFFER_LEN(state->object_delim2);
long depth = ++state->depth;
int i, j;
VALUE key, key_to_s, keys;
if (max_nesting != 0 && depth > max_nesting) {
fbuffer_free(buffer);
rb_raise(eNestingError, "nesting of %ld is too deep", --state->depth);
}
fbuffer_append_char(buffer, '{');
keys = rb_funcall(obj, i_keys, 0);
for(i = 0; i < RARRAY_LEN(keys); i++) {
if (i > 0) fbuffer_append(buffer, delim, delim_len);
if (object_nl) {
fbuffer_append(buffer, object_nl, object_nl_len);
}
if (indent) {
for (j = 0; j < depth; j++) {
fbuffer_append(buffer, indent, indent_len);
}
}
key = rb_ary_entry(keys, i);
key_to_s = rb_funcall(key, i_to_s, 0);
Check_Type(key_to_s, T_STRING);
generate_json(buffer, Vstate, state, key_to_s);
fbuffer_append(buffer, delim2, delim2_len);
generate_json(buffer, Vstate, state, rb_hash_aref(obj, key));
}
depth = --state->depth;
if (object_nl) {
fbuffer_append(buffer, object_nl, object_nl_len);
if (indent) {
for (j = 0; j < depth; j++) {
fbuffer_append(buffer, indent, indent_len);
}
}
}
fbuffer_append_char(buffer, '}');
}
static void generate_json_array(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
{
char *array_nl = state->array_nl;
long array_nl_len = state->array_nl_len;
char *indent = state->indent;
long indent_len = state->indent_len;
long max_nesting = state->max_nesting;
char *delim = FBUFFER_PTR(state->array_delim);
long delim_len = FBUFFER_LEN(state->array_delim);
long depth = ++state->depth;
int i, j;
if (max_nesting != 0 && depth > max_nesting) {
fbuffer_free(buffer);
rb_raise(eNestingError, "nesting of %ld is too deep", --state->depth);
}
fbuffer_append_char(buffer, '[');
if (array_nl) fbuffer_append(buffer, array_nl, array_nl_len);
for(i = 0; i < RARRAY_LEN(obj); i++) {
if (i > 0) fbuffer_append(buffer, delim, delim_len);
if (indent) {
for (j = 0; j < depth; j++) {
fbuffer_append(buffer, indent, indent_len);
}
}
generate_json(buffer, Vstate, state, rb_ary_entry(obj, i));
}
state->depth = --depth;
if (array_nl) {
fbuffer_append(buffer, array_nl, array_nl_len);
if (indent) {
for (j = 0; j < depth; j++) {
fbuffer_append(buffer, indent, indent_len);
}
}
}
fbuffer_append_char(buffer, ']');
}
static void generate_json_string(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
{
fbuffer_append_char(buffer, '"');
#ifdef HAVE_RUBY_ENCODING_H
obj = rb_funcall(obj, i_encode, 1, CEncoding_UTF_8);
#endif
if (state->ascii_only) {
convert_UTF8_to_JSON_ASCII(buffer, obj);
} else {
convert_UTF8_to_JSON(buffer, obj);
}
fbuffer_append_char(buffer, '"');
}
static void generate_json_null(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
{
fbuffer_append(buffer, "null", 4);
}
static void generate_json_false(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
{
fbuffer_append(buffer, "false", 5);
}
static void generate_json_true(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
{
fbuffer_append(buffer, "true", 4);
}
static void generate_json_fixnum(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
{
fbuffer_append_long(buffer, FIX2LONG(obj));
}
static void generate_json_bignum(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
{
VALUE tmp = rb_funcall(obj, i_to_s, 0);
fbuffer_append_str(buffer, tmp);
}
#ifdef RUBY_INTEGER_UNIFICATION
static void generate_json_integer(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
{
if (FIXNUM_P(obj))
generate_json_fixnum(buffer, Vstate, state, obj);
else
generate_json_bignum(buffer, Vstate, state, obj);
}
#endif
static void generate_json_float(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
{
double value = RFLOAT_VALUE(obj);
char allow_nan = state->allow_nan;
VALUE tmp = rb_funcall(obj, i_to_s, 0);
if (!allow_nan) {
if (isinf(value)) {
fbuffer_free(buffer);
rb_raise(eGeneratorError, "%u: %"PRIsVALUE" not allowed in JSON", __LINE__, RB_OBJ_STRING(tmp));
} else if (isnan(value)) {
fbuffer_free(buffer);
rb_raise(eGeneratorError, "%u: %"PRIsVALUE" not allowed in JSON", __LINE__, RB_OBJ_STRING(tmp));
}
}
fbuffer_append_str(buffer, tmp);
}
static void generate_json(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
{
VALUE tmp;
VALUE klass = CLASS_OF(obj);
if (klass == rb_cHash) {
generate_json_object(buffer, Vstate, state, obj);
} else if (klass == rb_cArray) {
generate_json_array(buffer, Vstate, state, obj);
} else if (klass == rb_cString) {
generate_json_string(buffer, Vstate, state, obj);
} else if (obj == Qnil) {
generate_json_null(buffer, Vstate, state, obj);
} else if (obj == Qfalse) {
generate_json_false(buffer, Vstate, state, obj);
} else if (obj == Qtrue) {
generate_json_true(buffer, Vstate, state, obj);
} else if (FIXNUM_P(obj)) {
generate_json_fixnum(buffer, Vstate, state, obj);
} else if (RB_TYPE_P(obj, T_BIGNUM)) {
generate_json_bignum(buffer, Vstate, state, obj);
} else if (klass == rb_cFloat) {
generate_json_float(buffer, Vstate, state, obj);
} else if (rb_respond_to(obj, i_to_json)) {
tmp = rb_funcall(obj, i_to_json, 1, Vstate);
Check_Type(tmp, T_STRING);
fbuffer_append_str(buffer, tmp);
} else {
tmp = rb_funcall(obj, i_to_s, 0);
Check_Type(tmp, T_STRING);
generate_json_string(buffer, Vstate, state, tmp);
}
}
static FBuffer *cState_prepare_buffer(VALUE self)
{
FBuffer *buffer;
GET_STATE(self);
buffer = fbuffer_alloc(state->buffer_initial_length);
if (state->object_delim) {
fbuffer_clear(state->object_delim);
} else {
state->object_delim = fbuffer_alloc(16);
}
fbuffer_append_char(state->object_delim, ',');
if (state->object_delim2) {
fbuffer_clear(state->object_delim2);
} else {
state->object_delim2 = fbuffer_alloc(16);
}
if (state->space_before) fbuffer_append(state->object_delim2, state->space_before, state->space_before_len);
fbuffer_append_char(state->object_delim2, ':');
if (state->space) fbuffer_append(state->object_delim2, state->space, state->space_len);
if (state->array_delim) {
fbuffer_clear(state->array_delim);
} else {
state->array_delim = fbuffer_alloc(16);
}
fbuffer_append_char(state->array_delim, ',');
if (state->array_nl) fbuffer_append(state->array_delim, state->array_nl, state->array_nl_len);
return buffer;
}
static VALUE cState_partial_generate(VALUE self, VALUE obj)
{
FBuffer *buffer = cState_prepare_buffer(self);
GET_STATE(self);
generate_json(buffer, self, state, obj);
return fbuffer_to_s(buffer);
}
/*
* call-seq: generate(obj)
*
* Generates a valid JSON document from object +obj+ and returns the
* result. If no valid JSON document can be created this method raises a
* GeneratorError exception.
*/
static VALUE cState_generate(VALUE self, VALUE obj)
{
VALUE result = cState_partial_generate(self, obj);
GET_STATE(self);
(void)state;
return result;
}
/*
* call-seq: new(opts = {})
*
* Instantiates a new State object, configured by _opts_.
*
* _opts_ can have the following keys:
*
* * *indent*: a string used to indent levels (default: ''),
* * *space*: a string that is put after, a : or , delimiter (default: ''),
* * *space_before*: a string that is put before a : pair delimiter (default: ''),
* * *object_nl*: a string that is put at the end of a JSON object (default: ''),
* * *array_nl*: a string that is put at the end of a JSON array (default: ''),
* * *allow_nan*: true if NaN, Infinity, and -Infinity should be
* generated, otherwise an exception is thrown, if these values are
* encountered. This options defaults to false.
* * *buffer_initial_length*: sets the initial length of the generator's
* internal buffer.
*/
static VALUE cState_initialize(int argc, VALUE *argv, VALUE self)
{
VALUE opts;
GET_STATE(self);
state->max_nesting = 100;
state->buffer_initial_length = FBUFFER_INITIAL_LENGTH_DEFAULT;
rb_scan_args(argc, argv, "01", &opts);
if (!NIL_P(opts)) cState_configure(self, opts);
return self;
}
/*
* call-seq: initialize_copy(orig)
*
* Initializes this object from orig if it can be duplicated/cloned and returns
* it.
*/
static VALUE cState_init_copy(VALUE obj, VALUE orig)
{
JSON_Generator_State *objState, *origState;
if (obj == orig) return obj;
GET_STATE_TO(obj, objState);
GET_STATE_TO(orig, origState);
if (!objState) rb_raise(rb_eArgError, "unallocated JSON::State");
MEMCPY(objState, origState, JSON_Generator_State, 1);
objState->indent = fstrndup(origState->indent, origState->indent_len);
objState->space = fstrndup(origState->space, origState->space_len);
objState->space_before = fstrndup(origState->space_before, origState->space_before_len);
objState->object_nl = fstrndup(origState->object_nl, origState->object_nl_len);
objState->array_nl = fstrndup(origState->array_nl, origState->array_nl_len);
if (origState->array_delim) objState->array_delim = fbuffer_dup(origState->array_delim);
if (origState->object_delim) objState->object_delim = fbuffer_dup(origState->object_delim);
if (origState->object_delim2) objState->object_delim2 = fbuffer_dup(origState->object_delim2);
return obj;
}
/*
* call-seq: from_state(opts)
*
* Creates a State object from _opts_, which ought to be Hash to create a
* new State instance configured by _opts_, something else to create an
* unconfigured instance. If _opts_ is a State object, it is just returned.
*/
static VALUE cState_from_state_s(VALUE self, VALUE opts)
{
if (rb_obj_is_kind_of(opts, self)) {
return opts;
} else if (rb_obj_is_kind_of(opts, rb_cHash)) {
return rb_funcall(self, i_new, 1, opts);
} else {
if (NIL_P(CJSON_SAFE_STATE_PROTOTYPE)) {
CJSON_SAFE_STATE_PROTOTYPE = rb_const_get(mJSON, i_SAFE_STATE_PROTOTYPE);
}
return rb_funcall(CJSON_SAFE_STATE_PROTOTYPE, i_dup, 0);
}
}
/*
* call-seq: indent()
*
* Returns the string that is used to indent levels in the JSON text.
*/
static VALUE cState_indent(VALUE self)
{
GET_STATE(self);
return state->indent ? rb_str_new(state->indent, state->indent_len) : rb_str_new2("");
}
/*
* call-seq: indent=(indent)
*
* Sets the string that is used to indent levels in the JSON text.
*/
static VALUE cState_indent_set(VALUE self, VALUE indent)
{
unsigned long len;
GET_STATE(self);
Check_Type(indent, T_STRING);
len = RSTRING_LEN(indent);
if (len == 0) {
if (state->indent) {
ruby_xfree(state->indent);
state->indent = NULL;
state->indent_len = 0;
}
} else {
if (state->indent) ruby_xfree(state->indent);
state->indent = strdup(RSTRING_PTR(indent));
state->indent_len = len;
}
return Qnil;
}
/*
* call-seq: space()
*
* Returns the string that is used to insert a space between the tokens in a JSON
* string.
*/
static VALUE cState_space(VALUE self)
{
GET_STATE(self);
return state->space ? rb_str_new(state->space, state->space_len) : rb_str_new2("");
}
/*
* call-seq: space=(space)
*
* Sets _space_ to the string that is used to insert a space between the tokens in a JSON
* string.
*/
static VALUE cState_space_set(VALUE self, VALUE space)
{
unsigned long len;
GET_STATE(self);
Check_Type(space, T_STRING);
len = RSTRING_LEN(space);
if (len == 0) {
if (state->space) {
ruby_xfree(state->space);
state->space = NULL;
state->space_len = 0;
}
} else {
if (state->space) ruby_xfree(state->space);
state->space = strdup(RSTRING_PTR(space));
state->space_len = len;
}
return Qnil;
}
/*
* call-seq: space_before()
*
* Returns the string that is used to insert a space before the ':' in JSON objects.
*/
static VALUE cState_space_before(VALUE self)
{
GET_STATE(self);
return state->space_before ? rb_str_new(state->space_before, state->space_before_len) : rb_str_new2("");
}
/*
* call-seq: space_before=(space_before)
*
* Sets the string that is used to insert a space before the ':' in JSON objects.
*/
static VALUE cState_space_before_set(VALUE self, VALUE space_before)
{
unsigned long len;
GET_STATE(self);
Check_Type(space_before, T_STRING);
len = RSTRING_LEN(space_before);
if (len == 0) {
if (state->space_before) {
ruby_xfree(state->space_before);
state->space_before = NULL;
state->space_before_len = 0;
}
} else {
if (state->space_before) ruby_xfree(state->space_before);
state->space_before = strdup(RSTRING_PTR(space_before));
state->space_before_len = len;
}
return Qnil;
}
/*
* call-seq: object_nl()
*
* This string is put at the end of a line that holds a JSON object (or
* Hash).
*/
static VALUE cState_object_nl(VALUE self)
{
GET_STATE(self);
return state->object_nl ? rb_str_new(state->object_nl, state->object_nl_len) : rb_str_new2("");
}
/*
* call-seq: object_nl=(object_nl)
*
* This string is put at the end of a line that holds a JSON object (or
* Hash).
*/
static VALUE cState_object_nl_set(VALUE self, VALUE object_nl)
{
unsigned long len;
GET_STATE(self);
Check_Type(object_nl, T_STRING);
len = RSTRING_LEN(object_nl);
if (len == 0) {
if (state->object_nl) {
ruby_xfree(state->object_nl);
state->object_nl = NULL;
}
} else {
if (state->object_nl) ruby_xfree(state->object_nl);
state->object_nl = strdup(RSTRING_PTR(object_nl));
state->object_nl_len = len;
}
return Qnil;
}
/*
* call-seq: array_nl()
*
* This string is put at the end of a line that holds a JSON array.
*/
static VALUE cState_array_nl(VALUE self)
{
GET_STATE(self);
return state->array_nl ? rb_str_new(state->array_nl, state->array_nl_len) : rb_str_new2("");
}
/*
* call-seq: array_nl=(array_nl)
*
* This string is put at the end of a line that holds a JSON array.
*/
static VALUE cState_array_nl_set(VALUE self, VALUE array_nl)
{
unsigned long len;
GET_STATE(self);
Check_Type(array_nl, T_STRING);
len = RSTRING_LEN(array_nl);
if (len == 0) {
if (state->array_nl) {
ruby_xfree(state->array_nl);
state->array_nl = NULL;
}
} else {
if (state->array_nl) ruby_xfree(state->array_nl);
state->array_nl = strdup(RSTRING_PTR(array_nl));
state->array_nl_len = len;
}
return Qnil;
}
/*
* call-seq: check_circular?
*
* Returns true, if circular data structures should be checked,
* otherwise returns false.
*/
static VALUE cState_check_circular_p(VALUE self)
{
GET_STATE(self);
return state->max_nesting ? Qtrue : Qfalse;
}
/*
* call-seq: max_nesting
*
* This integer returns the maximum level of data structure nesting in
* the generated JSON, max_nesting = 0 if no maximum is checked.
*/
static VALUE cState_max_nesting(VALUE self)
{
GET_STATE(self);
return LONG2FIX(state->max_nesting);
}
/*
* call-seq: max_nesting=(depth)
*
* This sets the maximum level of data structure nesting in the generated JSON
* to the integer depth, max_nesting = 0 if no maximum should be checked.
*/
static VALUE cState_max_nesting_set(VALUE self, VALUE depth)
{
GET_STATE(self);
Check_Type(depth, T_FIXNUM);
return state->max_nesting = FIX2LONG(depth);
}
/*
* call-seq: allow_nan?
*
* Returns true, if NaN, Infinity, and -Infinity should be generated, otherwise
* returns false.
*/
static VALUE cState_allow_nan_p(VALUE self)
{
GET_STATE(self);
return state->allow_nan ? Qtrue : Qfalse;
}
/*
* call-seq: ascii_only?
*
* Returns true, if NaN, Infinity, and -Infinity should be generated, otherwise
* returns false.
*/
static VALUE cState_ascii_only_p(VALUE self)
{
GET_STATE(self);
return state->ascii_only ? Qtrue : Qfalse;
}
/*
* call-seq: depth
*
* This integer returns the current depth of data structure nesting.
*/
static VALUE cState_depth(VALUE self)
{
GET_STATE(self);
return LONG2FIX(state->depth);
}
/*
* call-seq: depth=(depth)
*
* This sets the maximum level of data structure nesting in the generated JSON
* to the integer depth, max_nesting = 0 if no maximum should be checked.
*/
static VALUE cState_depth_set(VALUE self, VALUE depth)
{
GET_STATE(self);
Check_Type(depth, T_FIXNUM);
state->depth = FIX2LONG(depth);
return Qnil;
}
/*
* call-seq: buffer_initial_length
*
* This integer returns the current initial length of the buffer.
*/
static VALUE cState_buffer_initial_length(VALUE self)
{
GET_STATE(self);
return LONG2FIX(state->buffer_initial_length);
}
/*
* call-seq: buffer_initial_length=(length)
*
* This sets the initial length of the buffer to +length+, if +length+ > 0,
* otherwise its value isn't changed.
*/
static VALUE cState_buffer_initial_length_set(VALUE self, VALUE buffer_initial_length)
{
long initial_length;
GET_STATE(self);
Check_Type(buffer_initial_length, T_FIXNUM);
initial_length = FIX2LONG(buffer_initial_length);
if (initial_length > 0) {
state->buffer_initial_length = initial_length;
}
return Qnil;
}
/*
*
*/
void Init_generator(void)
{
rb_require("json/common");
mJSON = rb_define_module("JSON");
mExt = rb_define_module_under(mJSON, "Ext");
mGenerator = rb_define_module_under(mExt, "Generator");
eGeneratorError = rb_path2class("JSON::GeneratorError");
eNestingError = rb_path2class("JSON::NestingError");
cState = rb_define_class_under(mGenerator, "State", rb_cObject);
rb_define_alloc_func(cState, cState_s_allocate);
rb_define_singleton_method(cState, "from_state", cState_from_state_s, 1);
rb_define_method(cState, "initialize", cState_initialize, -1);
rb_define_method(cState, "initialize_copy", cState_init_copy, 1);
rb_define_method(cState, "indent", cState_indent, 0);
rb_define_method(cState, "indent=", cState_indent_set, 1);
rb_define_method(cState, "space", cState_space, 0);
rb_define_method(cState, "space=", cState_space_set, 1);
rb_define_method(cState, "space_before", cState_space_before, 0);
rb_define_method(cState, "space_before=", cState_space_before_set, 1);
rb_define_method(cState, "object_nl", cState_object_nl, 0);
rb_define_method(cState, "object_nl=", cState_object_nl_set, 1);
rb_define_method(cState, "array_nl", cState_array_nl, 0);
rb_define_method(cState, "array_nl=", cState_array_nl_set, 1);
rb_define_method(cState, "max_nesting", cState_max_nesting, 0);
rb_define_method(cState, "max_nesting=", cState_max_nesting_set, 1);
rb_define_method(cState, "check_circular?", cState_check_circular_p, 0);
rb_define_method(cState, "allow_nan?", cState_allow_nan_p, 0);
rb_define_method(cState, "ascii_only?", cState_ascii_only_p, 0);
rb_define_method(cState, "depth", cState_depth, 0);
rb_define_method(cState, "depth=", cState_depth_set, 1);
rb_define_method(cState, "buffer_initial_length", cState_buffer_initial_length, 0);
rb_define_method(cState, "buffer_initial_length=", cState_buffer_initial_length_set, 1);
rb_define_method(cState, "configure", cState_configure, 1);
rb_define_alias(cState, "merge", "configure");
rb_define_method(cState, "to_h", cState_to_h, 0);
rb_define_alias(cState, "to_hash", "to_h");
rb_define_method(cState, "[]", cState_aref, 1);
rb_define_method(cState, "[]=", cState_aset, 2);
rb_define_method(cState, "generate", cState_generate, 1);
mGeneratorMethods = rb_define_module_under(mGenerator, "GeneratorMethods");
mObject = rb_define_module_under(mGeneratorMethods, "Object");
rb_define_method(mObject, "to_json", mObject_to_json, -1);
mHash = rb_define_module_under(mGeneratorMethods, "Hash");
rb_define_method(mHash, "to_json", mHash_to_json, -1);
mArray = rb_define_module_under(mGeneratorMethods, "Array");
rb_define_method(mArray, "to_json", mArray_to_json, -1);
#ifdef RUBY_INTEGER_UNIFICATION
mInteger = rb_define_module_under(mGeneratorMethods, "Integer");
rb_define_method(mInteger, "to_json", mInteger_to_json, -1);
#else
mFixnum = rb_define_module_under(mGeneratorMethods, "Fixnum");
rb_define_method(mFixnum, "to_json", mFixnum_to_json, -1);
mBignum = rb_define_module_under(mGeneratorMethods, "Bignum");
rb_define_method(mBignum, "to_json", mBignum_to_json, -1);
#endif
mFloat = rb_define_module_under(mGeneratorMethods, "Float");
rb_define_method(mFloat, "to_json", mFloat_to_json, -1);
mString = rb_define_module_under(mGeneratorMethods, "String");
rb_define_singleton_method(mString, "included", mString_included_s, 1);
rb_define_method(mString, "to_json", mString_to_json, -1);
rb_define_method(mString, "to_json_raw", mString_to_json_raw, -1);
rb_define_method(mString, "to_json_raw_object", mString_to_json_raw_object, 0);
mString_Extend = rb_define_module_under(mString, "Extend");
rb_define_method(mString_Extend, "json_create", mString_Extend_json_create, 1);
mTrueClass = rb_define_module_under(mGeneratorMethods, "TrueClass");
rb_define_method(mTrueClass, "to_json", mTrueClass_to_json, -1);
mFalseClass = rb_define_module_under(mGeneratorMethods, "FalseClass");
rb_define_method(mFalseClass, "to_json", mFalseClass_to_json, -1);
mNilClass = rb_define_module_under(mGeneratorMethods, "NilClass");
rb_define_method(mNilClass, "to_json", mNilClass_to_json, -1);
CRegexp_MULTILINE = rb_const_get(rb_cRegexp, rb_intern("MULTILINE"));
i_to_s = rb_intern("to_s");
i_to_json = rb_intern("to_json");
i_new = rb_intern("new");
i_indent = rb_intern("indent");
i_space = rb_intern("space");
i_space_before = rb_intern("space_before");
i_object_nl = rb_intern("object_nl");
i_array_nl = rb_intern("array_nl");
i_max_nesting = rb_intern("max_nesting");
i_allow_nan = rb_intern("allow_nan");
i_ascii_only = rb_intern("ascii_only");
i_depth = rb_intern("depth");
i_buffer_initial_length = rb_intern("buffer_initial_length");
i_pack = rb_intern("pack");
i_unpack = rb_intern("unpack");
i_create_id = rb_intern("create_id");
i_extend = rb_intern("extend");
i_key_p = rb_intern("key?");
i_aref = rb_intern("[]");
i_send = rb_intern("__send__");
i_respond_to_p = rb_intern("respond_to?");
i_match = rb_intern("match");
i_keys = rb_intern("keys");
i_dup = rb_intern("dup");
#ifdef HAVE_RUBY_ENCODING_H
CEncoding_UTF_8 = rb_funcall(rb_path2class("Encoding"), rb_intern("find"), 1, rb_str_new2("utf-8"));
i_encoding = rb_intern("encoding");
i_encode = rb_intern("encode");
#endif
i_SAFE_STATE_PROTOTYPE = rb_intern("SAFE_STATE_PROTOTYPE");
CJSON_SAFE_STATE_PROTOTYPE = Qnil;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2767_0 |
crossvul-cpp_data_good_2560_0 | /*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2002,2003,2004,2006,2007,2008,2009,2010 Free Software Foundation, Inc.
*
* GRUB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GRUB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <grub/disk.h>
#include <grub/err.h>
#include <grub/mm.h>
#include <grub/types.h>
#include <grub/partition.h>
#include <grub/misc.h>
#include <grub/time.h>
#include <grub/file.h>
GRUB_EXPORT(grub_disk_dev_register);
GRUB_EXPORT(grub_disk_dev_unregister);
GRUB_EXPORT(grub_disk_dev_iterate);
GRUB_EXPORT(grub_disk_open);
GRUB_EXPORT(grub_disk_close);
GRUB_EXPORT(grub_disk_read);
GRUB_EXPORT(grub_disk_read_ex);
GRUB_EXPORT(grub_disk_write);
GRUB_EXPORT(grub_disk_get_size);
GRUB_EXPORT(grub_disk_firmware_fini);
GRUB_EXPORT(grub_disk_firmware_is_tainted);
GRUB_EXPORT(grub_disk_ata_pass_through);
#define GRUB_CACHE_TIMEOUT 2
/* The last time the disk was used. */
static grub_uint64_t grub_last_time = 0;
/* Disk cache. */
struct grub_disk_cache
{
enum grub_disk_dev_id dev_id;
unsigned long disk_id;
grub_disk_addr_t sector;
char *data;
int lock;
};
static struct grub_disk_cache grub_disk_cache_table[GRUB_DISK_CACHE_NUM];
void (*grub_disk_firmware_fini) (void);
int grub_disk_firmware_is_tainted;
grub_err_t (* grub_disk_ata_pass_through) (grub_disk_t,
struct grub_disk_ata_pass_through_parms *);
#if 0
static unsigned long grub_disk_cache_hits;
static unsigned long grub_disk_cache_misses;
void
grub_disk_cache_get_performance (unsigned long *hits, unsigned long *misses)
{
*hits = grub_disk_cache_hits;
*misses = grub_disk_cache_misses;
}
#endif
static unsigned
grub_disk_cache_get_index (unsigned long dev_id, unsigned long disk_id,
grub_disk_addr_t sector)
{
return ((dev_id * 524287UL + disk_id * 2606459UL
+ ((unsigned) (sector >> GRUB_DISK_CACHE_BITS)))
% GRUB_DISK_CACHE_NUM);
}
static void
grub_disk_cache_invalidate (unsigned long dev_id, unsigned long disk_id,
grub_disk_addr_t sector)
{
unsigned index;
struct grub_disk_cache *cache;
sector &= ~(GRUB_DISK_CACHE_SIZE - 1);
index = grub_disk_cache_get_index (dev_id, disk_id, sector);
cache = grub_disk_cache_table + index;
if (cache->dev_id == dev_id && cache->disk_id == disk_id
&& cache->sector == sector && cache->data)
{
cache->lock = 1;
grub_free (cache->data);
cache->data = 0;
cache->lock = 0;
}
}
void
grub_disk_cache_invalidate_all (void)
{
unsigned i;
for (i = 0; i < GRUB_DISK_CACHE_NUM; i++)
{
struct grub_disk_cache *cache = grub_disk_cache_table + i;
if (cache->data && ! cache->lock)
{
grub_free (cache->data);
cache->data = 0;
}
}
}
static char *
grub_disk_cache_fetch (unsigned long dev_id, unsigned long disk_id,
grub_disk_addr_t sector)
{
struct grub_disk_cache *cache;
unsigned index;
index = grub_disk_cache_get_index (dev_id, disk_id, sector);
cache = grub_disk_cache_table + index;
if (cache->dev_id == dev_id && cache->disk_id == disk_id
&& cache->sector == sector)
{
cache->lock = 1;
#if 0
grub_disk_cache_hits++;
#endif
return cache->data;
}
#if 0
grub_disk_cache_misses++;
#endif
return 0;
}
static void
grub_disk_cache_unlock (unsigned long dev_id, unsigned long disk_id,
grub_disk_addr_t sector)
{
struct grub_disk_cache *cache;
unsigned index;
index = grub_disk_cache_get_index (dev_id, disk_id, sector);
cache = grub_disk_cache_table + index;
if (cache->dev_id == dev_id && cache->disk_id == disk_id
&& cache->sector == sector)
cache->lock = 0;
}
static grub_err_t
grub_disk_cache_store (unsigned long dev_id, unsigned long disk_id,
grub_disk_addr_t sector, const char *data)
{
unsigned index;
struct grub_disk_cache *cache;
index = grub_disk_cache_get_index (dev_id, disk_id, sector);
cache = grub_disk_cache_table + index;
cache->lock = 1;
grub_free (cache->data);
cache->data = 0;
cache->lock = 0;
cache->data = grub_malloc (GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS);
if (! cache->data)
return grub_errno;
grub_memcpy (cache->data, data,
GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS);
cache->dev_id = dev_id;
cache->disk_id = disk_id;
cache->sector = sector;
return GRUB_ERR_NONE;
}
static grub_disk_dev_t grub_disk_dev_list;
void
grub_disk_dev_register (grub_disk_dev_t dev)
{
dev->next = grub_disk_dev_list;
grub_disk_dev_list = dev;
}
void
grub_disk_dev_unregister (grub_disk_dev_t dev)
{
grub_disk_dev_t *p, q;
for (p = &grub_disk_dev_list, q = *p; q; p = &(q->next), q = q->next)
if (q == dev)
{
*p = q->next;
break;
}
}
int
grub_disk_dev_iterate (int (*hook) (const char *name, void *closure),
void *closure)
{
grub_disk_dev_t p;
for (p = grub_disk_dev_list; p; p = p->next)
if (p->iterate && (p->iterate) (hook, closure))
return 1;
return 0;
}
/* Return the location of the first ',', if any, which is not
escaped by a '\'. */
static const char *
find_part_sep (const char *name)
{
const char *p = name;
char c;
while ((c = *p++) != '\0')
{
if (c == '\\' && *p == ',')
p++;
else if (c == ',')
return p - 1;
}
return NULL;
}
grub_disk_t
grub_disk_open (const char *name)
{
const char *p;
grub_disk_t disk;
grub_disk_dev_t dev;
char *raw = (char *) name;
grub_uint64_t current_time;
grub_dprintf ("disk", "Opening `%s'...\n", name);
disk = (grub_disk_t) grub_zalloc (sizeof (*disk));
if (! disk)
return 0;
disk->name = grub_strdup (name);
if (! disk->name)
goto fail;
p = find_part_sep (name);
if (p)
{
grub_size_t len = p - name;
raw = grub_malloc (len + 1);
if (! raw)
goto fail;
grub_memcpy (raw, name, len);
raw[len] = '\0';
}
for (dev = grub_disk_dev_list; dev; dev = dev->next)
{
if ((dev->open) (raw, disk) == GRUB_ERR_NONE)
break;
else if (grub_errno == GRUB_ERR_UNKNOWN_DEVICE)
grub_errno = GRUB_ERR_NONE;
else
goto fail;
}
if (! dev)
{
grub_error (GRUB_ERR_UNKNOWN_DEVICE, "no such disk");
goto fail;
}
if (p && ! disk->has_partitions)
{
grub_error (GRUB_ERR_BAD_DEVICE, "no partition on this disk");
goto fail;
}
disk->dev = dev;
if (p)
{
disk->partition = grub_partition_probe (disk, p + 1);
if (! disk->partition)
{
grub_error (GRUB_ERR_UNKNOWN_DEVICE, "no such partition");
goto fail;
}
}
/* The cache will be invalidated about 2 seconds after a device was
closed. */
current_time = grub_get_time_ms ();
if (current_time > (grub_last_time
+ GRUB_CACHE_TIMEOUT * 1000))
grub_disk_cache_invalidate_all ();
grub_last_time = current_time;
fail:
if (raw && raw != name)
grub_free (raw);
if (grub_errno != GRUB_ERR_NONE)
{
grub_error_push ();
grub_dprintf ("disk", "Opening `%s' failed.\n", name);
grub_error_pop ();
grub_disk_close (disk);
return 0;
}
return disk;
}
void
grub_disk_close (grub_disk_t disk)
{
grub_partition_t part;
grub_dprintf ("disk", "Closing `%s'.\n", disk->name);
if (disk->dev && disk->dev->close)
(disk->dev->close) (disk);
/* Reset the timer. */
grub_last_time = grub_get_time_ms ();
while (disk->partition)
{
part = disk->partition->parent;
grub_free (disk->partition);
disk->partition = part;
}
grub_free ((void *) disk->name);
grub_free (disk);
}
/* This function performs three tasks:
- Make sectors disk relative from partition relative.
- Normalize offset to be less than the sector size.
- Verify that the range is inside the partition. */
static grub_err_t
grub_disk_adjust_range (grub_disk_t disk, grub_disk_addr_t *sector,
grub_off_t *offset, grub_size_t size)
{
*sector += *offset >> GRUB_DISK_SECTOR_BITS;
*offset &= GRUB_DISK_SECTOR_SIZE - 1;
/*
grub_partition_t part;
for (part = disk->partition; part; part = part->parent)
{
grub_disk_addr_t start;
grub_uint64_t len;
start = part->start;
len = part->len;
if (*sector >= len
|| len - *sector < ((*offset + size + GRUB_DISK_SECTOR_SIZE - 1)
>> GRUB_DISK_SECTOR_BITS))
return grub_error (GRUB_ERR_OUT_OF_RANGE, "out of partition");
*sector += start;
}
if (disk->total_sectors <= *sector
|| ((*offset + size + GRUB_DISK_SECTOR_SIZE - 1)
>> GRUB_DISK_SECTOR_BITS) > disk->total_sectors - *sector)
return grub_error (GRUB_ERR_OUT_OF_RANGE, "out of disk");
*/
return GRUB_ERR_NONE;
}
/* Read data from the disk. */
grub_err_t
grub_disk_read (grub_disk_t disk, grub_disk_addr_t sector,
grub_off_t offset, grub_size_t size, void *buf)
{
char *tmp_buf;
unsigned real_offset;
/* First of all, check if the region is within the disk. */
if (grub_disk_adjust_range (disk, §or, &offset, size) != GRUB_ERR_NONE)
{
grub_error_push ();
grub_dprintf ("disk", "Read out of range: sector 0x%llx (%s).\n",
(unsigned long long) sector, grub_errmsg);
grub_error_pop ();
return grub_errno;
}
real_offset = offset;
/* Allocate a temporary buffer. */
tmp_buf = grub_malloc (GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS);
if (! tmp_buf)
return grub_errno;
/* Until SIZE is zero... */
while (size)
{
char *data;
grub_disk_addr_t start_sector;
grub_size_t len;
grub_size_t pos;
/* For reading bulk data. */
start_sector = sector & ~(GRUB_DISK_CACHE_SIZE - 1);
pos = (sector - start_sector) << GRUB_DISK_SECTOR_BITS;
len = ((GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS)
- pos - real_offset);
if (len > size)
len = size;
/* Fetch the cache. */
data = grub_disk_cache_fetch (disk->dev->id, disk->id, start_sector);
if (data)
{
/* Just copy it! */
if (buf) {
if (pos + real_offset + len >= size) {
// prevent read overflow
grub_errno = GRUB_ERR_BAD_FS;
return grub_errno;
}
grub_memcpy (buf, data + pos + real_offset, len);
}
grub_disk_cache_unlock (disk->dev->id, disk->id, start_sector);
}
else
{
/* Otherwise read data from the disk actually. */
if (start_sector + GRUB_DISK_CACHE_SIZE > disk->total_sectors
|| (disk->dev->read) (disk, start_sector,
GRUB_DISK_CACHE_SIZE, tmp_buf)
!= GRUB_ERR_NONE)
{
/* Uggh... Failed. Instead, just read necessary data. */
unsigned num;
char *p;
grub_errno = GRUB_ERR_NONE;
num = ((size + real_offset + GRUB_DISK_SECTOR_SIZE - 1)
>> GRUB_DISK_SECTOR_BITS);
p = grub_realloc (tmp_buf, num << GRUB_DISK_SECTOR_BITS);
if (!p)
goto finish;
tmp_buf = p;
if ((disk->dev->read) (disk, sector, num, tmp_buf))
{
grub_error_push ();
grub_dprintf ("disk", "%s read failed\n", disk->name);
grub_error_pop ();
goto finish;
}
if (buf)
grub_memcpy (buf, tmp_buf + real_offset, size);
/* Call the read hook, if any. */
if (disk->read_hook)
while (size)
{
grub_size_t to_read;
to_read = size;
if (real_offset + to_read > GRUB_DISK_SECTOR_SIZE)
to_read = GRUB_DISK_SECTOR_SIZE - real_offset;
(disk->read_hook) (sector, real_offset,
to_read, disk->closure);
if (grub_errno != GRUB_ERR_NONE)
goto finish;
sector++;
size -= to_read;
real_offset = 0;
}
/* This must be the end. */
goto finish;
}
/* Copy it and store it in the disk cache. */
if (buf)
grub_memcpy (buf, tmp_buf + pos + real_offset, len);
grub_disk_cache_store (disk->dev->id, disk->id,
start_sector, tmp_buf);
}
/* Call the read hook, if any. */
if (disk->read_hook)
{
grub_disk_addr_t s = sector;
grub_size_t l = len;
while (l)
{
(disk->read_hook) (s, real_offset,
((l > GRUB_DISK_SECTOR_SIZE)
? GRUB_DISK_SECTOR_SIZE
: l), disk->closure);
if (l < GRUB_DISK_SECTOR_SIZE - real_offset)
break;
s++;
l -= GRUB_DISK_SECTOR_SIZE - real_offset;
real_offset = 0;
}
}
sector = start_sector + GRUB_DISK_CACHE_SIZE;
if (buf)
buf = (char *) buf + len;
size -= len;
real_offset = 0;
}
finish:
grub_free (tmp_buf);
return grub_errno;
}
grub_err_t
grub_disk_read_ex (grub_disk_t disk, grub_disk_addr_t sector,
grub_off_t offset, grub_size_t size, void *buf, int flags)
{
unsigned real_offset;
if (! flags)
return grub_disk_read (disk, sector, offset, size, buf);
if (grub_disk_adjust_range (disk, §or, &offset, size) != GRUB_ERR_NONE)
return grub_errno;
real_offset = offset;
while (size)
{
char tmp_buf[GRUB_DISK_SECTOR_SIZE];
grub_size_t len;
if ((real_offset != 0) || (size < GRUB_DISK_SECTOR_SIZE))
{
len = GRUB_DISK_SECTOR_SIZE - real_offset;
if (len > size)
len = size;
if (buf)
{
if ((disk->dev->read) (disk, sector, 1, tmp_buf) != GRUB_ERR_NONE)
break;
grub_memcpy (buf, tmp_buf + real_offset, len);
}
if (disk->read_hook)
(disk->read_hook) (sector, real_offset, len, disk->closure);
sector++;
real_offset = 0;
}
else
{
grub_size_t n;
len = size & ~(GRUB_DISK_SECTOR_SIZE - 1);
n = size >> GRUB_DISK_SECTOR_BITS;
if ((buf) &&
((disk->dev->read) (disk, sector, n, buf) != GRUB_ERR_NONE))
break;
if (disk->read_hook)
{
while (n)
{
(disk->read_hook) (sector++, 0, GRUB_DISK_SECTOR_SIZE,
disk->closure);
n--;
}
}
else
sector += n;
}
if (buf)
buf = (char *) buf + len;
size -= len;
}
return grub_errno;
}
grub_err_t
grub_disk_write (grub_disk_t disk, grub_disk_addr_t sector,
grub_off_t offset, grub_size_t size, const void *buf)
{
unsigned real_offset;
grub_dprintf ("disk", "Writing `%s'...\n", disk->name);
if (grub_disk_adjust_range (disk, §or, &offset, size) != GRUB_ERR_NONE)
return grub_errno;
real_offset = offset;
while (size)
{
if (real_offset != 0 || (size < GRUB_DISK_SECTOR_SIZE && size != 0))
{
char tmp_buf[GRUB_DISK_SECTOR_SIZE];
grub_size_t len;
grub_partition_t part;
part = disk->partition;
disk->partition = 0;
if (grub_disk_read (disk, sector, 0, GRUB_DISK_SECTOR_SIZE, tmp_buf)
!= GRUB_ERR_NONE)
{
disk->partition = part;
goto finish;
}
disk->partition = part;
len = GRUB_DISK_SECTOR_SIZE - real_offset;
if (len > size)
len = size;
grub_memcpy (tmp_buf + real_offset, buf, len);
grub_disk_cache_invalidate (disk->dev->id, disk->id, sector);
if ((disk->dev->write) (disk, sector, 1, tmp_buf) != GRUB_ERR_NONE)
goto finish;
sector++;
buf = (char *) buf + len;
size -= len;
real_offset = 0;
}
else
{
grub_size_t len;
grub_size_t n;
len = size & ~(GRUB_DISK_SECTOR_SIZE - 1);
n = size >> GRUB_DISK_SECTOR_BITS;
if ((disk->dev->write) (disk, sector, n, buf) != GRUB_ERR_NONE)
goto finish;
while (n--)
grub_disk_cache_invalidate (disk->dev->id, disk->id, sector++);
buf = (char *) buf + len;
size -= len;
}
}
finish:
return grub_errno;
}
grub_uint64_t
grub_disk_get_size (grub_disk_t disk)
{
if (disk->partition)
return grub_partition_get_len (disk->partition);
else
return disk->total_sectors;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2560_0 |
crossvul-cpp_data_bad_5053_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD RRRR AAA W W %
% D D R R A A W W %
% D D RRRR AAAAA W W W %
% D D R RN A A WW WW %
% DDDD R R A A W W %
% %
% %
% MagickCore Image Drawing Methods %
% %
% %
% Software Design %
% Cristy %
% July 1998 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Bill Radcliffe of Corbis (www.corbis.com) contributed the polygon
% rendering code based on Paul Heckbert's "Concave Polygon Scan Conversion",
% Graphics Gems, 1990. Leonard Rosenthal and David Harr of Appligent
% (www.appligent.com) contributed the dash pattern, linecap stroking
% algorithm, and minor rendering improvements.
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/annotate.h"
#include "MagickCore/artifact.h"
#include "MagickCore/blob.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/color.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/draw.h"
#include "MagickCore/draw-private.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/paint.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/property.h"
#include "MagickCore/resample.h"
#include "MagickCore/resample-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/token.h"
#include "MagickCore/transform-private.h"
#include "MagickCore/utility.h"
/*
Define declarations.
*/
#define BezierQuantum 200
/*
Typedef declarations.
*/
typedef struct _EdgeInfo
{
SegmentInfo
bounds;
double
scanline;
PointInfo
*points;
size_t
number_points;
ssize_t
direction;
MagickBooleanType
ghostline;
size_t
highwater;
} EdgeInfo;
typedef struct _ElementInfo
{
double
cx,
cy,
major,
minor,
angle;
} ElementInfo;
typedef struct _PolygonInfo
{
EdgeInfo
*edges;
size_t
number_edges;
} PolygonInfo;
typedef enum
{
MoveToCode,
OpenCode,
GhostlineCode,
LineToCode,
EndCode
} PathInfoCode;
typedef struct _PathInfo
{
PointInfo
point;
PathInfoCode
code;
} PathInfo;
/*
Forward declarations.
*/
static MagickBooleanType
DrawStrokePolygon(Image *,const DrawInfo *,const PrimitiveInfo *,
ExceptionInfo *);
static PrimitiveInfo
*TraceStrokePolygon(const DrawInfo *,const PrimitiveInfo *);
static size_t
TracePath(PrimitiveInfo *,const char *);
static void
TraceArc(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo),
TraceArcPath(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo,
const double,const MagickBooleanType,const MagickBooleanType),
TraceBezier(PrimitiveInfo *,const size_t),
TraceCircle(PrimitiveInfo *,const PointInfo,const PointInfo),
TraceEllipse(PrimitiveInfo *,const PointInfo,const PointInfo,
const PointInfo),
TraceLine(PrimitiveInfo *,const PointInfo,const PointInfo),
TraceRectangle(PrimitiveInfo *,const PointInfo,const PointInfo),
TraceRoundRectangle(PrimitiveInfo *,const PointInfo,const PointInfo,
PointInfo),
TraceSquareLinecap(PrimitiveInfo *,const size_t,const double);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireDrawInfo() returns a DrawInfo structure properly initialized.
%
% The format of the AcquireDrawInfo method is:
%
% DrawInfo *AcquireDrawInfo(void)
%
*/
MagickExport DrawInfo *AcquireDrawInfo(void)
{
DrawInfo
*draw_info;
draw_info=(DrawInfo *) AcquireMagickMemory(sizeof(*draw_info));
if (draw_info == (DrawInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
GetDrawInfo((ImageInfo *) NULL,draw_info);
return(draw_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneDrawInfo() makes a copy of the given draw_info structure. If NULL
% is specified, a new DrawInfo structure is created initialized to default
% values.
%
% The format of the CloneDrawInfo method is:
%
% DrawInfo *CloneDrawInfo(const ImageInfo *image_info,
% const DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o draw_info: the draw info.
%
*/
MagickExport DrawInfo *CloneDrawInfo(const ImageInfo *image_info,
const DrawInfo *draw_info)
{
DrawInfo
*clone_info;
ExceptionInfo
*exception;
clone_info=(DrawInfo *) AcquireMagickMemory(sizeof(*clone_info));
if (clone_info == (DrawInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
GetDrawInfo(image_info,clone_info);
if (draw_info == (DrawInfo *) NULL)
return(clone_info);
exception=AcquireExceptionInfo();
if (clone_info->primitive != (char *) NULL)
(void) CloneString(&clone_info->primitive,draw_info->primitive);
if (draw_info->geometry != (char *) NULL)
(void) CloneString(&clone_info->geometry,draw_info->geometry);
clone_info->viewbox=draw_info->viewbox;
clone_info->affine=draw_info->affine;
clone_info->gravity=draw_info->gravity;
clone_info->fill=draw_info->fill;
clone_info->stroke=draw_info->stroke;
clone_info->stroke_width=draw_info->stroke_width;
if (draw_info->fill_pattern != (Image *) NULL)
clone_info->fill_pattern=CloneImage(draw_info->fill_pattern,0,0,MagickTrue,
exception);
if (draw_info->stroke_pattern != (Image *) NULL)
clone_info->stroke_pattern=CloneImage(draw_info->stroke_pattern,0,0,
MagickTrue,exception);
clone_info->stroke_antialias=draw_info->stroke_antialias;
clone_info->text_antialias=draw_info->text_antialias;
clone_info->fill_rule=draw_info->fill_rule;
clone_info->linecap=draw_info->linecap;
clone_info->linejoin=draw_info->linejoin;
clone_info->miterlimit=draw_info->miterlimit;
clone_info->dash_offset=draw_info->dash_offset;
clone_info->decorate=draw_info->decorate;
clone_info->compose=draw_info->compose;
if (draw_info->text != (char *) NULL)
(void) CloneString(&clone_info->text,draw_info->text);
if (draw_info->font != (char *) NULL)
(void) CloneString(&clone_info->font,draw_info->font);
if (draw_info->metrics != (char *) NULL)
(void) CloneString(&clone_info->metrics,draw_info->metrics);
if (draw_info->family != (char *) NULL)
(void) CloneString(&clone_info->family,draw_info->family);
clone_info->style=draw_info->style;
clone_info->stretch=draw_info->stretch;
clone_info->weight=draw_info->weight;
if (draw_info->encoding != (char *) NULL)
(void) CloneString(&clone_info->encoding,draw_info->encoding);
clone_info->pointsize=draw_info->pointsize;
clone_info->kerning=draw_info->kerning;
clone_info->interline_spacing=draw_info->interline_spacing;
clone_info->interword_spacing=draw_info->interword_spacing;
clone_info->direction=draw_info->direction;
if (draw_info->density != (char *) NULL)
(void) CloneString(&clone_info->density,draw_info->density);
clone_info->align=draw_info->align;
clone_info->undercolor=draw_info->undercolor;
clone_info->border_color=draw_info->border_color;
if (draw_info->server_name != (char *) NULL)
(void) CloneString(&clone_info->server_name,draw_info->server_name);
if (draw_info->dash_pattern != (double *) NULL)
{
register ssize_t
x;
for (x=0; draw_info->dash_pattern[x] != 0.0; x++) ;
clone_info->dash_pattern=(double *) AcquireQuantumMemory((size_t) x+1UL,
sizeof(*clone_info->dash_pattern));
if (clone_info->dash_pattern == (double *) NULL)
ThrowFatalException(ResourceLimitFatalError,
"UnableToAllocateDashPattern");
(void) CopyMagickMemory(clone_info->dash_pattern,draw_info->dash_pattern,
(size_t) (x+1)*sizeof(*clone_info->dash_pattern));
}
clone_info->gradient=draw_info->gradient;
if (draw_info->gradient.stops != (StopInfo *) NULL)
{
size_t
number_stops;
number_stops=clone_info->gradient.number_stops;
clone_info->gradient.stops=(StopInfo *) AcquireQuantumMemory((size_t)
number_stops,sizeof(*clone_info->gradient.stops));
if (clone_info->gradient.stops == (StopInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,
"UnableToAllocateDashPattern");
(void) CopyMagickMemory(clone_info->gradient.stops,
draw_info->gradient.stops,(size_t) number_stops*
sizeof(*clone_info->gradient.stops));
}
if (draw_info->clip_mask != (char *) NULL)
(void) CloneString(&clone_info->clip_mask,draw_info->clip_mask);
clone_info->bounds=draw_info->bounds;
clone_info->clip_units=draw_info->clip_units;
clone_info->render=draw_info->render;
clone_info->alpha=draw_info->alpha;
clone_info->element_reference=draw_info->element_reference;
clone_info->debug=IsEventLogging();
exception=DestroyExceptionInfo(exception);
return(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n v e r t P a t h T o P o l y g o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConvertPathToPolygon() converts a path to the more efficient sorted
% rendering form.
%
% The format of the ConvertPathToPolygon method is:
%
% PolygonInfo *ConvertPathToPolygon(const DrawInfo *draw_info,
% const PathInfo *path_info)
%
% A description of each parameter follows:
%
% o Method ConvertPathToPolygon returns the path in a more efficient sorted
% rendering form of type PolygonInfo.
%
% o draw_info: Specifies a pointer to an DrawInfo structure.
%
% o path_info: Specifies a pointer to an PathInfo structure.
%
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int CompareEdges(const void *x,const void *y)
{
register const EdgeInfo
*p,
*q;
/*
Compare two edges.
*/
p=(const EdgeInfo *) x;
q=(const EdgeInfo *) y;
if ((p->points[0].y-MagickEpsilon) > q->points[0].y)
return(1);
if ((p->points[0].y+MagickEpsilon) < q->points[0].y)
return(-1);
if ((p->points[0].x-MagickEpsilon) > q->points[0].x)
return(1);
if ((p->points[0].x+MagickEpsilon) < q->points[0].x)
return(-1);
if (((p->points[1].x-p->points[0].x)*(q->points[1].y-q->points[0].y)-
(p->points[1].y-p->points[0].y)*(q->points[1].x-q->points[0].x)) > 0.0)
return(1);
return(-1);
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static void LogPolygonInfo(const PolygonInfo *polygon_info)
{
register EdgeInfo
*p;
register ssize_t
i,
j;
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin active-edge");
p=polygon_info->edges;
for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
{
(void) LogMagickEvent(DrawEvent,GetMagickModule()," edge %.20g:",
(double) i);
(void) LogMagickEvent(DrawEvent,GetMagickModule()," direction: %s",
p->direction != MagickFalse ? "down" : "up");
(void) LogMagickEvent(DrawEvent,GetMagickModule()," ghostline: %s",
p->ghostline != MagickFalse ? "transparent" : "opaque");
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" bounds: %g %g - %g %g",p->bounds.x1,p->bounds.y1,
p->bounds.x2,p->bounds.y2);
for (j=0; j < (ssize_t) p->number_points; j++)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," %g %g",
p->points[j].x,p->points[j].y);
p++;
}
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end active-edge");
}
static void ReversePoints(PointInfo *points,const size_t number_points)
{
PointInfo
point;
register ssize_t
i;
for (i=0; i < (ssize_t) (number_points >> 1); i++)
{
point=points[i];
points[i]=points[number_points-(i+1)];
points[number_points-(i+1)]=point;
}
}
static PolygonInfo *ConvertPathToPolygon(const PathInfo *path_info)
{
long
direction,
next_direction;
PointInfo
point,
*points;
PolygonInfo
*polygon_info;
SegmentInfo
bounds;
register ssize_t
i,
n;
MagickBooleanType
ghostline;
size_t
edge,
number_edges,
number_points;
/*
Convert a path to the more efficient sorted rendering form.
*/
polygon_info=(PolygonInfo *) AcquireMagickMemory(sizeof(*polygon_info));
if (polygon_info == (PolygonInfo *) NULL)
return((PolygonInfo *) NULL);
number_edges=16;
polygon_info->edges=(EdgeInfo *) AcquireQuantumMemory((size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
direction=0;
edge=0;
ghostline=MagickFalse;
n=0;
number_points=0;
points=(PointInfo *) NULL;
(void) ResetMagickMemory(&point,0,sizeof(point));
(void) ResetMagickMemory(&bounds,0,sizeof(bounds));
for (i=0; path_info[i].code != EndCode; i++)
{
if ((path_info[i].code == MoveToCode) || (path_info[i].code == OpenCode) ||
(path_info[i].code == GhostlineCode))
{
/*
Move to.
*/
if ((points != (PointInfo *) NULL) && (n >= 2))
{
if (edge == number_edges)
{
number_edges<<=1;
polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
polygon_info->edges,(size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
}
polygon_info->edges[edge].number_points=(size_t) n;
polygon_info->edges[edge].scanline=(-1.0);
polygon_info->edges[edge].highwater=0;
polygon_info->edges[edge].ghostline=ghostline;
polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
if (direction < 0)
ReversePoints(points,(size_t) n);
polygon_info->edges[edge].points=points;
polygon_info->edges[edge].bounds=bounds;
polygon_info->edges[edge].bounds.y1=points[0].y;
polygon_info->edges[edge].bounds.y2=points[n-1].y;
points=(PointInfo *) NULL;
ghostline=MagickFalse;
edge++;
}
if (points == (PointInfo *) NULL)
{
number_points=16;
points=(PointInfo *) AcquireQuantumMemory((size_t) number_points,
sizeof(*points));
if (points == (PointInfo *) NULL)
return((PolygonInfo *) NULL);
}
ghostline=path_info[i].code == GhostlineCode ? MagickTrue : MagickFalse;
point=path_info[i].point;
points[0]=point;
bounds.x1=point.x;
bounds.x2=point.x;
direction=0;
n=1;
continue;
}
/*
Line to.
*/
next_direction=((path_info[i].point.y > point.y) ||
((path_info[i].point.y == point.y) &&
(path_info[i].point.x > point.x))) ? 1 : -1;
if ((points != (PointInfo *) NULL) && (direction != 0) &&
(direction != next_direction))
{
/*
New edge.
*/
point=points[n-1];
if (edge == number_edges)
{
number_edges<<=1;
polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
polygon_info->edges,(size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
}
polygon_info->edges[edge].number_points=(size_t) n;
polygon_info->edges[edge].scanline=(-1.0);
polygon_info->edges[edge].highwater=0;
polygon_info->edges[edge].ghostline=ghostline;
polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
if (direction < 0)
ReversePoints(points,(size_t) n);
polygon_info->edges[edge].points=points;
polygon_info->edges[edge].bounds=bounds;
polygon_info->edges[edge].bounds.y1=points[0].y;
polygon_info->edges[edge].bounds.y2=points[n-1].y;
number_points=16;
points=(PointInfo *) AcquireQuantumMemory((size_t) number_points,
sizeof(*points));
if (points == (PointInfo *) NULL)
return((PolygonInfo *) NULL);
n=1;
ghostline=MagickFalse;
points[0]=point;
bounds.x1=point.x;
bounds.x2=point.x;
edge++;
}
direction=next_direction;
if (points == (PointInfo *) NULL)
continue;
if (n == (ssize_t) number_points)
{
number_points<<=1;
points=(PointInfo *) ResizeQuantumMemory(points,(size_t) number_points,
sizeof(*points));
if (points == (PointInfo *) NULL)
return((PolygonInfo *) NULL);
}
point=path_info[i].point;
points[n]=point;
if (point.x < bounds.x1)
bounds.x1=point.x;
if (point.x > bounds.x2)
bounds.x2=point.x;
n++;
}
if (points != (PointInfo *) NULL)
{
if (n < 2)
points=(PointInfo *) RelinquishMagickMemory(points);
else
{
if (edge == number_edges)
{
number_edges<<=1;
polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
polygon_info->edges,(size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
}
polygon_info->edges[edge].number_points=(size_t) n;
polygon_info->edges[edge].scanline=(-1.0);
polygon_info->edges[edge].highwater=0;
polygon_info->edges[edge].ghostline=ghostline;
polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
if (direction < 0)
ReversePoints(points,(size_t) n);
polygon_info->edges[edge].points=points;
polygon_info->edges[edge].bounds=bounds;
polygon_info->edges[edge].bounds.y1=points[0].y;
polygon_info->edges[edge].bounds.y2=points[n-1].y;
ghostline=MagickFalse;
edge++;
}
}
polygon_info->number_edges=edge;
qsort(polygon_info->edges,(size_t) polygon_info->number_edges,
sizeof(*polygon_info->edges),CompareEdges);
if (IsEventLogging() != MagickFalse)
LogPolygonInfo(polygon_info);
return(polygon_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n v e r t P r i m i t i v e T o P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConvertPrimitiveToPath() converts a PrimitiveInfo structure into a vector
% path structure.
%
% The format of the ConvertPrimitiveToPath method is:
%
% PathInfo *ConvertPrimitiveToPath(const DrawInfo *draw_info,
% const PrimitiveInfo *primitive_info)
%
% A description of each parameter follows:
%
% o Method ConvertPrimitiveToPath returns a vector path structure of type
% PathInfo.
%
% o draw_info: a structure of type DrawInfo.
%
% o primitive_info: Specifies a pointer to an PrimitiveInfo structure.
%
%
*/
static void LogPathInfo(const PathInfo *path_info)
{
register const PathInfo
*p;
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin vector-path");
for (p=path_info; p->code != EndCode; p++)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" %g %g %s",p->point.x,p->point.y,p->code == GhostlineCode ?
"moveto ghostline" : p->code == OpenCode ? "moveto open" :
p->code == MoveToCode ? "moveto" : p->code == LineToCode ? "lineto" :
"?");
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end vector-path");
}
static PathInfo *ConvertPrimitiveToPath(const PrimitiveInfo *primitive_info)
{
PathInfo
*path_info;
PathInfoCode
code;
PointInfo
p,
q;
register ssize_t
i,
n;
ssize_t
coordinates,
start;
/*
Converts a PrimitiveInfo structure into a vector path structure.
*/
switch (primitive_info->primitive)
{
case AlphaPrimitive:
case ColorPrimitive:
case ImagePrimitive:
case PointPrimitive:
case TextPrimitive:
return((PathInfo *) NULL);
default:
break;
}
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
path_info=(PathInfo *) AcquireQuantumMemory((size_t) (2UL*i+3UL),
sizeof(*path_info));
if (path_info == (PathInfo *) NULL)
return((PathInfo *) NULL);
coordinates=0;
n=0;
p.x=(-1.0);
p.y=(-1.0);
q.x=(-1.0);
q.y=(-1.0);
start=0;
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
{
code=LineToCode;
if (coordinates <= 0)
{
coordinates=(ssize_t) primitive_info[i].coordinates;
p=primitive_info[i].point;
start=n;
code=MoveToCode;
}
coordinates--;
/*
Eliminate duplicate points.
*/
if ((i == 0) || (fabs(q.x-primitive_info[i].point.x) >= MagickEpsilon) ||
(fabs(q.y-primitive_info[i].point.y) >= MagickEpsilon))
{
path_info[n].code=code;
path_info[n].point=primitive_info[i].point;
q=primitive_info[i].point;
n++;
}
if (coordinates > 0)
continue;
if ((fabs(p.x-primitive_info[i].point.x) < MagickEpsilon) &&
(fabs(p.y-primitive_info[i].point.y) < MagickEpsilon))
continue;
/*
Mark the p point as open if it does not match the q.
*/
path_info[start].code=OpenCode;
path_info[n].code=GhostlineCode;
path_info[n].point=primitive_info[i].point;
n++;
path_info[n].code=LineToCode;
path_info[n].point=p;
n++;
}
path_info[n].code=EndCode;
path_info[n].point.x=0.0;
path_info[n].point.y=0.0;
if (IsEventLogging() != MagickFalse)
LogPathInfo(path_info);
return(path_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyDrawInfo() deallocates memory associated with an DrawInfo
% structure.
%
% The format of the DestroyDrawInfo method is:
%
% DrawInfo *DestroyDrawInfo(DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o draw_info: the draw info.
%
*/
MagickExport DrawInfo *DestroyDrawInfo(DrawInfo *draw_info)
{
if (draw_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if (draw_info->primitive != (char *) NULL)
draw_info->primitive=DestroyString(draw_info->primitive);
if (draw_info->text != (char *) NULL)
draw_info->text=DestroyString(draw_info->text);
if (draw_info->geometry != (char *) NULL)
draw_info->geometry=DestroyString(draw_info->geometry);
if (draw_info->fill_pattern != (Image *) NULL)
draw_info->fill_pattern=DestroyImage(draw_info->fill_pattern);
if (draw_info->stroke_pattern != (Image *) NULL)
draw_info->stroke_pattern=DestroyImage(draw_info->stroke_pattern);
if (draw_info->font != (char *) NULL)
draw_info->font=DestroyString(draw_info->font);
if (draw_info->metrics != (char *) NULL)
draw_info->metrics=DestroyString(draw_info->metrics);
if (draw_info->family != (char *) NULL)
draw_info->family=DestroyString(draw_info->family);
if (draw_info->encoding != (char *) NULL)
draw_info->encoding=DestroyString(draw_info->encoding);
if (draw_info->density != (char *) NULL)
draw_info->density=DestroyString(draw_info->density);
if (draw_info->server_name != (char *) NULL)
draw_info->server_name=(char *)
RelinquishMagickMemory(draw_info->server_name);
if (draw_info->dash_pattern != (double *) NULL)
draw_info->dash_pattern=(double *) RelinquishMagickMemory(
draw_info->dash_pattern);
if (draw_info->gradient.stops != (StopInfo *) NULL)
draw_info->gradient.stops=(StopInfo *) RelinquishMagickMemory(
draw_info->gradient.stops);
if (draw_info->clip_mask != (char *) NULL)
draw_info->clip_mask=DestroyString(draw_info->clip_mask);
draw_info->signature=(~MagickCoreSignature);
draw_info=(DrawInfo *) RelinquishMagickMemory(draw_info);
return(draw_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y E d g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyEdge() destroys the specified polygon edge.
%
% The format of the DestroyEdge method is:
%
% ssize_t DestroyEdge(PolygonInfo *polygon_info,const int edge)
%
% A description of each parameter follows:
%
% o polygon_info: Specifies a pointer to an PolygonInfo structure.
%
% o edge: the polygon edge number to destroy.
%
*/
static size_t DestroyEdge(PolygonInfo *polygon_info,
const size_t edge)
{
assert(edge < polygon_info->number_edges);
polygon_info->edges[edge].points=(PointInfo *) RelinquishMagickMemory(
polygon_info->edges[edge].points);
polygon_info->number_edges--;
if (edge < polygon_info->number_edges)
(void) CopyMagickMemory(polygon_info->edges+edge,polygon_info->edges+edge+1,
(size_t) (polygon_info->number_edges-edge)*sizeof(*polygon_info->edges));
return(polygon_info->number_edges);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y P o l y g o n I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyPolygonInfo() destroys the PolygonInfo data structure.
%
% The format of the DestroyPolygonInfo method is:
%
% PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info)
%
% A description of each parameter follows:
%
% o polygon_info: Specifies a pointer to an PolygonInfo structure.
%
*/
static PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info)
{
register ssize_t
i;
for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
polygon_info->edges[i].points=(PointInfo *)
RelinquishMagickMemory(polygon_info->edges[i].points);
polygon_info->edges=(EdgeInfo *) RelinquishMagickMemory(polygon_info->edges);
return((PolygonInfo *) RelinquishMagickMemory(polygon_info));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w A f f i n e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawAffineImage() composites the source over the destination image as
% dictated by the affine transform.
%
% The format of the DrawAffineImage method is:
%
% MagickBooleanType DrawAffineImage(Image *image,const Image *source,
% const AffineMatrix *affine,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o source: the source image.
%
% o affine: the affine transform.
%
% o exception: return any errors or warnings in this structure.
%
*/
static SegmentInfo AffineEdge(const Image *image,const AffineMatrix *affine,
const double y,const SegmentInfo *edge)
{
double
intercept,
z;
register double
x;
SegmentInfo
inverse_edge;
/*
Determine left and right edges.
*/
inverse_edge.x1=edge->x1;
inverse_edge.y1=edge->y1;
inverse_edge.x2=edge->x2;
inverse_edge.y2=edge->y2;
z=affine->ry*y+affine->tx;
if (affine->sx >= MagickEpsilon)
{
intercept=(-z/affine->sx);
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z+(double) image->columns)/affine->sx;
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if (affine->sx < -MagickEpsilon)
{
intercept=(-z+(double) image->columns)/affine->sx;
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z/affine->sx);
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->columns))
{
inverse_edge.x2=edge->x1;
return(inverse_edge);
}
/*
Determine top and bottom edges.
*/
z=affine->sy*y+affine->ty;
if (affine->rx >= MagickEpsilon)
{
intercept=(-z/affine->rx);
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z+(double) image->rows)/affine->rx;
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if (affine->rx < -MagickEpsilon)
{
intercept=(-z+(double) image->rows)/affine->rx;
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z/affine->rx);
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->rows))
{
inverse_edge.x2=edge->x2;
return(inverse_edge);
}
return(inverse_edge);
}
static AffineMatrix InverseAffineMatrix(const AffineMatrix *affine)
{
AffineMatrix
inverse_affine;
double
determinant;
determinant=PerceptibleReciprocal(affine->sx*affine->sy-affine->rx*
affine->ry);
inverse_affine.sx=determinant*affine->sy;
inverse_affine.rx=determinant*(-affine->rx);
inverse_affine.ry=determinant*(-affine->ry);
inverse_affine.sy=determinant*affine->sx;
inverse_affine.tx=(-affine->tx)*inverse_affine.sx-affine->ty*
inverse_affine.ry;
inverse_affine.ty=(-affine->tx)*inverse_affine.rx-affine->ty*
inverse_affine.sy;
return(inverse_affine);
}
MagickExport MagickBooleanType DrawAffineImage(Image *image,
const Image *source,const AffineMatrix *affine,ExceptionInfo *exception)
{
AffineMatrix
inverse_affine;
CacheView
*image_view,
*source_view;
MagickBooleanType
status;
PixelInfo
zero;
PointInfo
extent[4],
min,
max;
register ssize_t
i;
SegmentInfo
edge;
ssize_t
start,
stop,
y;
/*
Determine bounding box.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(source != (const Image *) NULL);
assert(source->signature == MagickCoreSignature);
assert(affine != (AffineMatrix *) NULL);
extent[0].x=0.0;
extent[0].y=0.0;
extent[1].x=(double) source->columns-1.0;
extent[1].y=0.0;
extent[2].x=(double) source->columns-1.0;
extent[2].y=(double) source->rows-1.0;
extent[3].x=0.0;
extent[3].y=(double) source->rows-1.0;
for (i=0; i < 4; i++)
{
PointInfo
point;
point=extent[i];
extent[i].x=point.x*affine->sx+point.y*affine->ry+affine->tx;
extent[i].y=point.x*affine->rx+point.y*affine->sy+affine->ty;
}
min=extent[0];
max=extent[0];
for (i=1; i < 4; i++)
{
if (min.x > extent[i].x)
min.x=extent[i].x;
if (min.y > extent[i].y)
min.y=extent[i].y;
if (max.x < extent[i].x)
max.x=extent[i].x;
if (max.y < extent[i].y)
max.y=extent[i].y;
}
/*
Affine transform image.
*/
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
edge.x1=MagickMax(min.x,0.0);
edge.y1=MagickMax(min.y,0.0);
edge.x2=MagickMin(max.x,(double) image->columns-1.0);
edge.y2=MagickMin(max.y,(double) image->rows-1.0);
inverse_affine=InverseAffineMatrix(affine);
GetPixelInfo(image,&zero);
start=(ssize_t) ceil(edge.y1-0.5);
stop=(ssize_t) floor(edge.y2+0.5);
source_view=AcquireVirtualCacheView(source,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(source,image,1,1)
#endif
for (y=start; y <= stop; y++)
{
PixelInfo
composite,
pixel;
PointInfo
point;
register ssize_t
x;
register Quantum
*magick_restrict q;
SegmentInfo
inverse_edge;
ssize_t
x_offset;
inverse_edge=AffineEdge(source,&inverse_affine,(double) y,&edge);
if (inverse_edge.x2 < inverse_edge.x1)
continue;
q=GetCacheViewAuthenticPixels(image_view,(ssize_t) ceil(inverse_edge.x1-
0.5),y,(size_t) (floor(inverse_edge.x2+0.5)-ceil(inverse_edge.x1-0.5)+1),
1,exception);
if (q == (Quantum *) NULL)
continue;
pixel=zero;
composite=zero;
x_offset=0;
for (x=(ssize_t) ceil(inverse_edge.x1-0.5); x <= (ssize_t) floor(inverse_edge.x2+0.5); x++)
{
point.x=(double) x*inverse_affine.sx+y*inverse_affine.ry+
inverse_affine.tx;
point.y=(double) x*inverse_affine.rx+y*inverse_affine.sy+
inverse_affine.ty;
(void) InterpolatePixelInfo(source,source_view,UndefinedInterpolatePixel,
point.x,point.y,&pixel,exception);
GetPixelInfoPixel(image,q,&composite);
CompositePixelInfoOver(&pixel,pixel.alpha,&composite,composite.alpha,
&composite);
SetPixelViaPixelInfo(image,&composite,q);
x_offset++;
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
source_view=DestroyCacheView(source_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w B o u n d i n g R e c t a n g l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawBoundingRectangles() draws the bounding rectangles on the image. This
% is only useful for developers debugging the rendering algorithm.
%
% The format of the DrawBoundingRectangles method is:
%
% void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info,
% PolygonInfo *polygon_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o polygon_info: Specifies a pointer to a PolygonInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info,
const PolygonInfo *polygon_info,ExceptionInfo *exception)
{
DrawInfo
*clone_info;
double
mid;
PointInfo
end,
resolution,
start;
PrimitiveInfo
primitive_info[6];
register ssize_t
i;
SegmentInfo
bounds;
ssize_t
coordinates;
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) QueryColorCompliance("#0000",AllCompliance,&clone_info->fill,
exception);
resolution.x=DefaultResolution;
resolution.y=DefaultResolution;
if (clone_info->density != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(clone_info->density,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == MagickFalse)
resolution.y=resolution.x;
}
mid=(resolution.x/72.0)*ExpandAffine(&clone_info->affine)*
clone_info->stroke_width/2.0;
bounds.x1=0.0;
bounds.y1=0.0;
bounds.x2=0.0;
bounds.y2=0.0;
if (polygon_info != (PolygonInfo *) NULL)
{
bounds=polygon_info->edges[0].bounds;
for (i=1; i < (ssize_t) polygon_info->number_edges; i++)
{
if (polygon_info->edges[i].bounds.x1 < (double) bounds.x1)
bounds.x1=polygon_info->edges[i].bounds.x1;
if (polygon_info->edges[i].bounds.y1 < (double) bounds.y1)
bounds.y1=polygon_info->edges[i].bounds.y1;
if (polygon_info->edges[i].bounds.x2 > (double) bounds.x2)
bounds.x2=polygon_info->edges[i].bounds.x2;
if (polygon_info->edges[i].bounds.y2 > (double) bounds.y2)
bounds.y2=polygon_info->edges[i].bounds.y2;
}
bounds.x1-=mid;
bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double)
image->columns ? (double) image->columns-1 : bounds.x1;
bounds.y1-=mid;
bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double)
image->rows ? (double) image->rows-1 : bounds.y1;
bounds.x2+=mid;
bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double)
image->columns ? (double) image->columns-1 : bounds.x2;
bounds.y2+=mid;
bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double)
image->rows ? (double) image->rows-1 : bounds.y2;
for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
{
if (polygon_info->edges[i].direction != 0)
(void) QueryColorCompliance("red",AllCompliance,&clone_info->stroke,
exception);
else
(void) QueryColorCompliance("green",AllCompliance,&clone_info->stroke,
exception);
start.x=(double) (polygon_info->edges[i].bounds.x1-mid);
start.y=(double) (polygon_info->edges[i].bounds.y1-mid);
end.x=(double) (polygon_info->edges[i].bounds.x2+mid);
end.y=(double) (polygon_info->edges[i].bounds.y2+mid);
primitive_info[0].primitive=RectanglePrimitive;
TraceRectangle(primitive_info,start,end);
primitive_info[0].method=ReplaceMethod;
coordinates=(ssize_t) primitive_info[0].coordinates;
primitive_info[coordinates].primitive=UndefinedPrimitive;
(void) DrawPrimitive(image,clone_info,primitive_info,exception);
}
}
(void) QueryColorCompliance("blue",AllCompliance,&clone_info->stroke,
exception);
start.x=(double) (bounds.x1-mid);
start.y=(double) (bounds.y1-mid);
end.x=(double) (bounds.x2+mid);
end.y=(double) (bounds.y2+mid);
primitive_info[0].primitive=RectanglePrimitive;
TraceRectangle(primitive_info,start,end);
primitive_info[0].method=ReplaceMethod;
coordinates=(ssize_t) primitive_info[0].coordinates;
primitive_info[coordinates].primitive=UndefinedPrimitive;
(void) DrawPrimitive(image,clone_info,primitive_info,exception);
clone_info=DestroyDrawInfo(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w C l i p P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawClipPath() draws the clip path on the image mask.
%
% The format of the DrawClipPath method is:
%
% MagickBooleanType DrawClipPath(Image *image,const DrawInfo *draw_info,
% const char *name,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o name: the name of the clip path.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType DrawClipPath(Image *image,
const DrawInfo *draw_info,const char *name,ExceptionInfo *exception)
{
char
filename[MagickPathExtent];
Image
*clip_mask;
const char
*value;
DrawInfo
*clone_info;
MagickStatusType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (const DrawInfo *) NULL);
(void) FormatLocaleString(filename,MagickPathExtent,"%s",name);
value=GetImageArtifact(image,filename);
if (value == (const char *) NULL)
return(MagickFalse);
clip_mask=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if (clip_mask == (Image *) NULL)
return(MagickFalse);
(void) QueryColorCompliance("#0000",AllCompliance,
&clip_mask->background_color,exception);
clip_mask->background_color.alpha=(Quantum) TransparentAlpha;
(void) SetImageBackgroundColor(clip_mask,exception);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin clip-path %s",
draw_info->clip_mask);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) CloneString(&clone_info->primitive,value);
(void) QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill,
exception);
clone_info->clip_mask=(char *) NULL;
status=NegateImage(clip_mask,MagickFalse,exception);
(void) SetImageMask(image,ReadPixelMask,clip_mask,exception);
clip_mask=DestroyImage(clip_mask);
status&=DrawImage(image,clone_info,exception);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"end clip-path");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w D a s h P o l y g o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawDashPolygon() draws a dashed polygon (line, rectangle, ellipse) on the
% image while respecting the dash offset and dash pattern attributes.
%
% The format of the DrawDashPolygon method is:
%
% MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,
% const PrimitiveInfo *primitive_info,Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info,Image *image,ExceptionInfo *exception)
{
DrawInfo
*clone_info;
double
length,
maximum_length,
offset,
scale,
total_length;
MagickStatusType
status;
PrimitiveInfo
*dash_polygon;
register ssize_t
i;
register double
dx,
dy;
size_t
number_vertices;
ssize_t
j,
n;
assert(draw_info != (const DrawInfo *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-dash");
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
number_vertices=(size_t) i;
dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
(2UL*number_vertices+1UL),sizeof(*dash_polygon));
if (dash_polygon == (PrimitiveInfo *) NULL)
return(MagickFalse);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->miterlimit=0;
dash_polygon[0]=primitive_info[0];
scale=ExpandAffine(&draw_info->affine);
length=scale*(draw_info->dash_pattern[0]-0.5);
offset=draw_info->dash_offset != 0.0 ? scale*draw_info->dash_offset : 0.0;
j=1;
for (n=0; offset > 0.0; j=0)
{
if (draw_info->dash_pattern[n] <= 0.0)
break;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
if (offset > length)
{
offset-=length;
n++;
length=scale*(draw_info->dash_pattern[n]+0.5);
continue;
}
if (offset < length)
{
length-=offset;
offset=0.0;
break;
}
offset=0.0;
n++;
}
status=MagickTrue;
maximum_length=0.0;
total_length=0.0;
for (i=1; (i < number_vertices) && (length >= 0.0); i++)
{
dx=primitive_info[i].point.x-primitive_info[i-1].point.x;
dy=primitive_info[i].point.y-primitive_info[i-1].point.y;
maximum_length=hypot((double) dx,dy);
if (length == 0.0)
{
n++;
if (draw_info->dash_pattern[n] == 0.0)
n=0;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
}
for (total_length=0.0; (length >= 0.0) && (maximum_length >= (total_length+length)); )
{
total_length+=length;
if ((n & 0x01) != 0)
{
dash_polygon[0]=primitive_info[0];
dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx*
total_length/maximum_length);
dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy*
total_length/maximum_length);
j=1;
}
else
{
if ((j+1) > (ssize_t) (2*number_vertices))
break;
dash_polygon[j]=primitive_info[i-1];
dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx*
total_length/maximum_length);
dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy*
total_length/maximum_length);
dash_polygon[j].coordinates=1;
j++;
dash_polygon[0].coordinates=(size_t) j;
dash_polygon[j].primitive=UndefinedPrimitive;
status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception);
}
n++;
if (draw_info->dash_pattern[n] == 0.0)
n=0;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
}
length-=(maximum_length-total_length);
if ((n & 0x01) != 0)
continue;
dash_polygon[j]=primitive_info[i];
dash_polygon[j].coordinates=1;
j++;
}
if ((total_length <= maximum_length) && ((n & 0x01) == 0) && (j > 1))
{
dash_polygon[j]=primitive_info[i-1];
dash_polygon[j].point.x+=MagickEpsilon;
dash_polygon[j].point.y+=MagickEpsilon;
dash_polygon[j].coordinates=1;
j++;
dash_polygon[0].coordinates=(size_t) j;
dash_polygon[j].primitive=UndefinedPrimitive;
status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception);
}
dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-dash");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawImage() draws a graphic primitive on your image. The primitive
% may be represented as a string or filename. Precede the filename with an
% "at" sign (@) and the contents of the file are drawn on the image. You
% can affect how text is drawn by setting one or more members of the draw
% info structure.
%
% The format of the DrawImage method is:
%
% MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline MagickBooleanType IsPoint(const char *point)
{
char
*p;
double
value;
value=StringToDouble(point,&p);
return((value == 0.0) && (p == point) ? MagickFalse : MagickTrue);
}
static inline void TracePoint(PrimitiveInfo *primitive_info,
const PointInfo point)
{
primitive_info->coordinates=1;
primitive_info->point=point;
}
MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info,
ExceptionInfo *exception)
{
#define RenderImageTag "Render/Image"
AffineMatrix
affine,
current;
char
keyword[MagickPathExtent],
geometry[MagickPathExtent],
pattern[MagickPathExtent],
*primitive,
*token;
const char
*q;
DrawInfo
**graphic_context;
MagickBooleanType
proceed;
MagickStatusType
status;
double
angle,
factor,
primitive_extent;
PointInfo
point;
PrimitiveInfo
*primitive_info;
PrimitiveType
primitive_type;
register const char
*p;
register ssize_t
i,
x;
SegmentInfo
bounds;
size_t
extent,
length,
number_points,
number_stops;
ssize_t
j,
k,
n;
StopInfo
*stops;
/*
Ensure the annotation info is valid.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
if ((draw_info->primitive == (char *) NULL) ||
(*draw_info->primitive == '\0'))
return(MagickFalse);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"begin draw-image");
if (*draw_info->primitive != '@')
primitive=AcquireString(draw_info->primitive);
else
primitive=FileToString(draw_info->primitive+1,~0UL,exception);
if (primitive == (char *) NULL)
return(MagickFalse);
primitive_extent=(double) strlen(primitive);
(void) SetImageArtifact(image,"MVG",primitive);
n=0;
number_stops=0;
stops=(StopInfo *) NULL;
/*
Allocate primitive info memory.
*/
graphic_context=(DrawInfo **) AcquireMagickMemory(
sizeof(*graphic_context));
if (graphic_context == (DrawInfo **) NULL)
{
primitive=DestroyString(primitive);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
number_points=6553;
primitive_info=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_points,
sizeof(*primitive_info));
if (primitive_info == (PrimitiveInfo *) NULL)
{
primitive=DestroyString(primitive);
for ( ; n >= 0; n--)
graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,draw_info);
graphic_context[n]->viewbox=image->page;
if ((image->page.width == 0) || (image->page.height == 0))
{
graphic_context[n]->viewbox.width=image->columns;
graphic_context[n]->viewbox.height=image->rows;
}
token=AcquireString(primitive);
extent=strlen(token)+MagickPathExtent;
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
for (q=primitive; *q != '\0'; )
{
/*
Interpret graphic primitive.
*/
GetNextToken(q,&q,extent,keyword);
if (*keyword == '\0')
break;
if (*keyword == '#')
{
/*
Comment.
*/
while ((*q != '\n') && (*q != '\0'))
q++;
continue;
}
p=q-strlen(keyword)-1;
primitive_type=UndefinedPrimitive;
current=graphic_context[n]->affine;
GetAffineMatrix(&affine);
switch (*keyword)
{
case ';':
break;
case 'a':
case 'A':
{
if (LocaleCompare("affine",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
affine.sx=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.rx=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.ry=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.sy=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.tx=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.ty=StringToDouble(token,(char **) NULL);
break;
}
if (LocaleCompare("alpha",keyword) == 0)
{
primitive_type=AlphaPrimitive;
break;
}
if (LocaleCompare("arc",keyword) == 0)
{
primitive_type=ArcPrimitive;
break;
}
status=MagickFalse;
break;
}
case 'b':
case 'B':
{
if (LocaleCompare("bezier",keyword) == 0)
{
primitive_type=BezierPrimitive;
break;
}
if (LocaleCompare("border-color",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) QueryColorCompliance(token,AllCompliance,
&graphic_context[n]->border_color,exception);
break;
}
status=MagickFalse;
break;
}
case 'c':
case 'C':
{
if (LocaleCompare("clip-path",keyword) == 0)
{
/*
Create clip mask.
*/
GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->clip_mask,token);
(void) DrawClipPath(image,graphic_context[n],
graphic_context[n]->clip_mask,exception);
break;
}
if (LocaleCompare("clip-rule",keyword) == 0)
{
ssize_t
fill_rule;
GetNextToken(q,&q,extent,token);
fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse,
token);
if (fill_rule == -1)
status=MagickFalse;
else
graphic_context[n]->fill_rule=(FillRule) fill_rule;
break;
}
if (LocaleCompare("clip-units",keyword) == 0)
{
ssize_t
clip_units;
GetNextToken(q,&q,extent,token);
clip_units=ParseCommandOption(MagickClipPathOptions,MagickFalse,
token);
if (clip_units == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->clip_units=(ClipPathUnits) clip_units;
if (clip_units == ObjectBoundingBox)
{
GetAffineMatrix(¤t);
affine.sx=draw_info->bounds.x2;
affine.sy=draw_info->bounds.y2;
affine.tx=draw_info->bounds.x1;
affine.ty=draw_info->bounds.y1;
break;
}
break;
}
if (LocaleCompare("circle",keyword) == 0)
{
primitive_type=CirclePrimitive;
break;
}
if (LocaleCompare("color",keyword) == 0)
{
primitive_type=ColorPrimitive;
break;
}
status=MagickFalse;
break;
}
case 'd':
case 'D':
{
if (LocaleCompare("decorate",keyword) == 0)
{
ssize_t
decorate;
GetNextToken(q,&q,extent,token);
decorate=ParseCommandOption(MagickDecorateOptions,MagickFalse,
token);
if (decorate == -1)
status=MagickFalse;
else
graphic_context[n]->decorate=(DecorationType) decorate;
break;
}
if (LocaleCompare("density",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->density,token);
break;
}
if (LocaleCompare("direction",keyword) == 0)
{
ssize_t
direction;
GetNextToken(q,&q,extent,token);
direction=ParseCommandOption(MagickDirectionOptions,MagickFalse,
token);
if (direction == -1)
status=MagickFalse;
else
graphic_context[n]->direction=(DirectionType) direction;
break;
}
status=MagickFalse;
break;
}
case 'e':
case 'E':
{
if (LocaleCompare("ellipse",keyword) == 0)
{
primitive_type=EllipsePrimitive;
break;
}
if (LocaleCompare("encoding",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->encoding,token);
break;
}
status=MagickFalse;
break;
}
case 'f':
case 'F':
{
if (LocaleCompare("fill",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(pattern,MagickPathExtent,"%s",token);
if (GetImageArtifact(image,pattern) != (const char *) NULL)
(void) DrawPatternPath(image,draw_info,token,
&graphic_context[n]->fill_pattern,exception);
else
{
status&=QueryColorCompliance(token,AllCompliance,
&graphic_context[n]->fill,exception);
if (status == MagickFalse)
{
ImageInfo
*pattern_info;
pattern_info=AcquireImageInfo();
(void) CopyMagickString(pattern_info->filename,token,
MagickPathExtent);
graphic_context[n]->fill_pattern=ReadImage(pattern_info,
exception);
CatchException(exception);
pattern_info=DestroyImageInfo(pattern_info);
}
}
break;
}
if (LocaleCompare("fill-opacity",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
graphic_context[n]->fill.alpha=(double) QuantumRange*
factor*StringToDouble(token,(char **) NULL);
break;
}
if (LocaleCompare("fill-rule",keyword) == 0)
{
ssize_t
fill_rule;
GetNextToken(q,&q,extent,token);
fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse,
token);
if (fill_rule == -1)
status=MagickFalse;
else
graphic_context[n]->fill_rule=(FillRule) fill_rule;
break;
}
if (LocaleCompare("font",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->font,token);
if (LocaleCompare("none",token) == 0)
graphic_context[n]->font=(char *)
RelinquishMagickMemory(graphic_context[n]->font);
break;
}
if (LocaleCompare("font-family",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->family,token);
break;
}
if (LocaleCompare("font-size",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->pointsize=StringToDouble(token,(char **) NULL);
break;
}
if (LocaleCompare("font-stretch",keyword) == 0)
{
ssize_t
stretch;
GetNextToken(q,&q,extent,token);
stretch=ParseCommandOption(MagickStretchOptions,MagickFalse,token);
if (stretch == -1)
status=MagickFalse;
else
graphic_context[n]->stretch=(StretchType) stretch;
break;
}
if (LocaleCompare("font-style",keyword) == 0)
{
ssize_t
style;
GetNextToken(q,&q,extent,token);
style=ParseCommandOption(MagickStyleOptions,MagickFalse,token);
if (style == -1)
status=MagickFalse;
else
graphic_context[n]->style=(StyleType) style;
break;
}
if (LocaleCompare("font-weight",keyword) == 0)
{
ssize_t
weight;
GetNextToken(q,&q,extent,token);
weight=ParseCommandOption(MagickWeightOptions,MagickFalse,token);
if (weight == -1)
weight=StringToUnsignedLong(token);
graphic_context[n]->weight=(size_t) weight;
break;
}
status=MagickFalse;
break;
}
case 'g':
case 'G':
{
if (LocaleCompare("gradient-units",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("gravity",keyword) == 0)
{
ssize_t
gravity;
GetNextToken(q,&q,extent,token);
gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,token);
if (gravity == -1)
status=MagickFalse;
else
graphic_context[n]->gravity=(GravityType) gravity;
break;
}
status=MagickFalse;
break;
}
case 'i':
case 'I':
{
if (LocaleCompare("image",keyword) == 0)
{
ssize_t
compose;
primitive_type=ImagePrimitive;
GetNextToken(q,&q,extent,token);
compose=ParseCommandOption(MagickComposeOptions,MagickFalse,token);
if (compose == -1)
status=MagickFalse;
else
graphic_context[n]->compose=(CompositeOperator) compose;
break;
}
if (LocaleCompare("interline-spacing",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->interline_spacing=StringToDouble(token,
(char **) NULL);
break;
}
if (LocaleCompare("interword-spacing",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->interword_spacing=StringToDouble(token,
(char **) NULL);
break;
}
status=MagickFalse;
break;
}
case 'k':
case 'K':
{
if (LocaleCompare("kerning",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->kerning=StringToDouble(token,(char **) NULL);
break;
}
status=MagickFalse;
break;
}
case 'l':
case 'L':
{
if (LocaleCompare("line",keyword) == 0)
primitive_type=LinePrimitive;
else
status=MagickFalse;
break;
}
case 'o':
case 'O':
{
if (LocaleCompare("offset",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("opacity",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
graphic_context[n]->alpha=ClampToQuantum(QuantumRange*(1.0-((1.0-
QuantumScale*graphic_context[n]->alpha)*factor*
StringToDouble(token,(char **) NULL))));
graphic_context[n]->fill.alpha=(double) graphic_context[n]->alpha;
graphic_context[n]->stroke.alpha=(double) graphic_context[n]->alpha;
break;
}
status=MagickFalse;
break;
}
case 'p':
case 'P':
{
if (LocaleCompare("path",keyword) == 0)
{
primitive_type=PathPrimitive;
break;
}
if (LocaleCompare("point",keyword) == 0)
{
primitive_type=PointPrimitive;
break;
}
if (LocaleCompare("polyline",keyword) == 0)
{
primitive_type=PolylinePrimitive;
break;
}
if (LocaleCompare("polygon",keyword) == 0)
{
primitive_type=PolygonPrimitive;
break;
}
if (LocaleCompare("pop",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare("clip-path",token) == 0)
break;
if (LocaleCompare("defs",token) == 0)
break;
if (LocaleCompare("gradient",token) == 0)
break;
if (LocaleCompare("graphic-context",token) == 0)
{
if (n <= 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),
DrawError,"UnbalancedGraphicContextPushPop","`%s'",token);
n=0;
break;
}
if (graphic_context[n]->clip_mask != (char *) NULL)
if (LocaleCompare(graphic_context[n]->clip_mask,
graphic_context[n-1]->clip_mask) != 0)
(void) SetImageMask(image,ReadPixelMask,(Image *) NULL,
exception);
graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
n--;
break;
}
if (LocaleCompare("pattern",token) == 0)
break;
status=MagickFalse;
break;
}
if (LocaleCompare("push",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare("clip-path",token) == 0)
{
char
name[MagickPathExtent];
GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(name,MagickPathExtent,"%s",token);
for (p=q; *q != '\0'; )
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare(token,"pop") != 0)
continue;
GetNextToken(q,(const char **) NULL,extent,token);
if (LocaleCompare(token,"clip-path") != 0)
continue;
break;
}
(void) CopyMagickString(token,p,(size_t) (q-p-4+1));
(void) SetImageArtifact(image,name,token);
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("gradient",token) == 0)
{
char
key[2*MagickPathExtent],
name[MagickPathExtent],
type[MagickPathExtent];
SegmentInfo
segment;
GetNextToken(q,&q,extent,token);
(void) CopyMagickString(name,token,MagickPathExtent);
GetNextToken(q,&q,extent,token);
(void) CopyMagickString(type,token,MagickPathExtent);
GetNextToken(q,&q,extent,token);
segment.x1=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
segment.y1=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
segment.x2=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
segment.y2=StringToDouble(token,(char **) NULL);
if (LocaleCompare(type,"radial") == 0)
{
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
}
for (p=q; *q != '\0'; )
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare(token,"pop") != 0)
continue;
GetNextToken(q,(const char **) NULL,extent,token);
if (LocaleCompare(token,"gradient") != 0)
continue;
break;
}
(void) CopyMagickString(token,p,(size_t) (q-p-4+1));
bounds.x1=graphic_context[n]->affine.sx*segment.x1+
graphic_context[n]->affine.ry*segment.y1+
graphic_context[n]->affine.tx;
bounds.y1=graphic_context[n]->affine.rx*segment.x1+
graphic_context[n]->affine.sy*segment.y1+
graphic_context[n]->affine.ty;
bounds.x2=graphic_context[n]->affine.sx*segment.x2+
graphic_context[n]->affine.ry*segment.y2+
graphic_context[n]->affine.tx;
bounds.y2=graphic_context[n]->affine.rx*segment.x2+
graphic_context[n]->affine.sy*segment.y2+
graphic_context[n]->affine.ty;
(void) FormatLocaleString(key,MagickPathExtent,"%s",name);
(void) SetImageArtifact(image,key,token);
(void) FormatLocaleString(key,MagickPathExtent,"%s-type",name);
(void) SetImageArtifact(image,key,type);
(void) FormatLocaleString(key,MagickPathExtent,"%s-geometry",name);
(void) FormatLocaleString(geometry,MagickPathExtent,
"%gx%g%+.15g%+.15g",
MagickMax(fabs(bounds.x2-bounds.x1+1.0),1.0),
MagickMax(fabs(bounds.y2-bounds.y1+1.0),1.0),
bounds.x1,bounds.y1);
(void) SetImageArtifact(image,key,geometry);
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("pattern",token) == 0)
{
char
key[2*MagickPathExtent],
name[MagickPathExtent];
RectangleInfo
pattern_bounds;
GetNextToken(q,&q,extent,token);
(void) CopyMagickString(name,token,MagickPathExtent);
GetNextToken(q,&q,extent,token);
pattern_bounds.x=(ssize_t) ceil(StringToDouble(token,
(char **) NULL)-0.5);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
pattern_bounds.y=(ssize_t) ceil(StringToDouble(token,
(char **) NULL)-0.5);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
pattern_bounds.width=(size_t) floor(StringToDouble(token,
(char **) NULL)+0.5);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
pattern_bounds.height=(size_t) floor(StringToDouble(token,
(char **) NULL)+0.5);
for (p=q; *q != '\0'; )
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare(token,"pop") != 0)
continue;
GetNextToken(q,(const char **) NULL,extent,token);
if (LocaleCompare(token,"pattern") != 0)
continue;
break;
}
(void) CopyMagickString(token,p,(size_t) (q-p-4+1));
(void) FormatLocaleString(key,MagickPathExtent,"%s",name);
(void) SetImageArtifact(image,key,token);
(void) FormatLocaleString(key,MagickPathExtent,"%s-geometry",
name);
(void) FormatLocaleString(geometry,MagickPathExtent,
"%.20gx%.20g%+.20g%+.20g",(double)pattern_bounds.width,
(double)pattern_bounds.height,(double)pattern_bounds.x,
(double)pattern_bounds.y);
(void) SetImageArtifact(image,key,geometry);
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("graphic-context",token) == 0)
{
n++;
graphic_context=(DrawInfo **) ResizeQuantumMemory(
graphic_context,(size_t) (n+1),sizeof(*graphic_context));
if (graphic_context == (DrawInfo **) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
break;
}
graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,
graphic_context[n-1]);
break;
}
if (LocaleCompare("defs",token) == 0)
break;
status=MagickFalse;
break;
}
status=MagickFalse;
break;
}
case 'r':
case 'R':
{
if (LocaleCompare("rectangle",keyword) == 0)
{
primitive_type=RectanglePrimitive;
break;
}
if (LocaleCompare("rotate",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
angle=StringToDouble(token,(char **) NULL);
affine.sx=cos(DegreesToRadians(fmod((double) angle,360.0)));
affine.rx=sin(DegreesToRadians(fmod((double) angle,360.0)));
affine.ry=(-sin(DegreesToRadians(fmod((double) angle,360.0))));
affine.sy=cos(DegreesToRadians(fmod((double) angle,360.0)));
break;
}
if (LocaleCompare("roundRectangle",keyword) == 0)
{
primitive_type=RoundRectanglePrimitive;
break;
}
status=MagickFalse;
break;
}
case 's':
case 'S':
{
if (LocaleCompare("scale",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
affine.sx=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.sy=StringToDouble(token,(char **) NULL);
break;
}
if (LocaleCompare("skewX",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
angle=StringToDouble(token,(char **) NULL);
affine.ry=sin(DegreesToRadians(angle));
break;
}
if (LocaleCompare("skewY",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
angle=StringToDouble(token,(char **) NULL);
affine.rx=(-tan(DegreesToRadians(angle)/2.0));
break;
}
if (LocaleCompare("stop-color",keyword) == 0)
{
PixelInfo
stop_color;
number_stops++;
if (number_stops == 1)
stops=(StopInfo *) AcquireQuantumMemory(2,sizeof(*stops));
else if (number_stops > 2)
stops=(StopInfo *) ResizeQuantumMemory(stops,number_stops,
sizeof(*stops));
if (stops == (StopInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
break;
}
GetNextToken(q,&q,extent,token);
(void) QueryColorCompliance(token,AllCompliance,&stop_color,
exception);
stops[number_stops-1].color=stop_color;
GetNextToken(q,&q,extent,token);
stops[number_stops-1].offset=StringToDouble(token,(char **) NULL);
break;
}
if (LocaleCompare("stroke",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(pattern,MagickPathExtent,"%s",token);
if (GetImageArtifact(image,pattern) != (const char *) NULL)
(void) DrawPatternPath(image,draw_info,token,
&graphic_context[n]->stroke_pattern,exception);
else
{
status&=QueryColorCompliance(token,AllCompliance,
&graphic_context[n]->stroke,exception);
if (status == MagickFalse)
{
ImageInfo
*pattern_info;
pattern_info=AcquireImageInfo();
(void) CopyMagickString(pattern_info->filename,token,
MagickPathExtent);
graphic_context[n]->stroke_pattern=ReadImage(pattern_info,
exception);
CatchException(exception);
pattern_info=DestroyImageInfo(pattern_info);
}
}
break;
}
if (LocaleCompare("stroke-antialias",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->stroke_antialias=
StringToLong(token) != 0 ? MagickTrue : MagickFalse;
break;
}
if (LocaleCompare("stroke-dasharray",keyword) == 0)
{
if (graphic_context[n]->dash_pattern != (double *) NULL)
graphic_context[n]->dash_pattern=(double *)
RelinquishMagickMemory(graphic_context[n]->dash_pattern);
if (IsPoint(q) != MagickFalse)
{
const char
*r;
r=q;
GetNextToken(r,&r,extent,token);
if (*token == ',')
GetNextToken(r,&r,extent,token);
for (x=0; IsPoint(token) != MagickFalse; x++)
{
GetNextToken(r,&r,extent,token);
if (*token == ',')
GetNextToken(r,&r,extent,token);
}
graphic_context[n]->dash_pattern=(double *)
AcquireQuantumMemory((size_t) (2UL*x+1UL),
sizeof(*graphic_context[n]->dash_pattern));
if (graphic_context[n]->dash_pattern == (double *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
break;
}
for (j=0; j < x; j++)
{
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
graphic_context[n]->dash_pattern[j]=StringToDouble(token,
(char **) NULL);
if (graphic_context[n]->dash_pattern[j] < 0.0)
status=MagickFalse;
}
if ((x & 0x01) != 0)
for ( ; j < (2*x); j++)
graphic_context[n]->dash_pattern[j]=
graphic_context[n]->dash_pattern[j-x];
graphic_context[n]->dash_pattern[j]=0.0;
break;
}
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("stroke-dashoffset",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->dash_offset=StringToDouble(token,
(char **) NULL);
break;
}
if (LocaleCompare("stroke-linecap",keyword) == 0)
{
ssize_t
linecap;
GetNextToken(q,&q,extent,token);
linecap=ParseCommandOption(MagickLineCapOptions,MagickFalse,token);
if (linecap == -1)
status=MagickFalse;
else
graphic_context[n]->linecap=(LineCap) linecap;
break;
}
if (LocaleCompare("stroke-linejoin",keyword) == 0)
{
ssize_t
linejoin;
GetNextToken(q,&q,extent,token);
linejoin=ParseCommandOption(MagickLineJoinOptions,MagickFalse,
token);
if (linejoin == -1)
status=MagickFalse;
else
graphic_context[n]->linejoin=(LineJoin) linejoin;
break;
}
if (LocaleCompare("stroke-miterlimit",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->miterlimit=StringToUnsignedLong(token);
break;
}
if (LocaleCompare("stroke-opacity",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
graphic_context[n]->stroke.alpha=(double) QuantumRange*
factor*StringToDouble(token,(char **) NULL);
break;
}
if (LocaleCompare("stroke-width",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->stroke_width=StringToDouble(token,
(char **) NULL);
break;
}
status=MagickFalse;
break;
}
case 't':
case 'T':
{
if (LocaleCompare("text",keyword) == 0)
{
primitive_type=TextPrimitive;
break;
}
if (LocaleCompare("text-align",keyword) == 0)
{
ssize_t
align;
GetNextToken(q,&q,extent,token);
align=ParseCommandOption(MagickAlignOptions,MagickFalse,token);
if (align == -1)
status=MagickFalse;
else
graphic_context[n]->align=(AlignType) align;
break;
}
if (LocaleCompare("text-anchor",keyword) == 0)
{
ssize_t
align;
GetNextToken(q,&q,extent,token);
align=ParseCommandOption(MagickAlignOptions,MagickFalse,token);
if (align == -1)
status=MagickFalse;
else
graphic_context[n]->align=(AlignType) align;
break;
}
if (LocaleCompare("text-antialias",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->text_antialias=
StringToLong(token) != 0 ? MagickTrue : MagickFalse;
break;
}
if (LocaleCompare("text-undercolor",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) QueryColorCompliance(token,AllCompliance,
&graphic_context[n]->undercolor,exception);
break;
}
if (LocaleCompare("translate",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
affine.tx=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.ty=StringToDouble(token,(char **) NULL);
break;
}
status=MagickFalse;
break;
}
case 'v':
case 'V':
{
if (LocaleCompare("viewbox",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.x=(ssize_t) ceil(StringToDouble(token,
(char **) NULL)-0.5);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.y=(ssize_t) ceil(StringToDouble(token,
(char **) NULL)-0.5);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.width=(size_t) floor(StringToDouble(
token,(char **) NULL)+0.5);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.height=(size_t) floor(StringToDouble(
token,(char **) NULL)+0.5);
break;
}
status=MagickFalse;
break;
}
default:
{
status=MagickFalse;
break;
}
}
if (status == MagickFalse)
break;
if ((affine.sx != 1.0) || (affine.rx != 0.0) || (affine.ry != 0.0) ||
(affine.sy != 1.0) || (affine.tx != 0.0) || (affine.ty != 0.0))
{
graphic_context[n]->affine.sx=current.sx*affine.sx+current.ry*affine.rx;
graphic_context[n]->affine.rx=current.rx*affine.sx+current.sy*affine.rx;
graphic_context[n]->affine.ry=current.sx*affine.ry+current.ry*affine.sy;
graphic_context[n]->affine.sy=current.rx*affine.ry+current.sy*affine.sy;
graphic_context[n]->affine.tx=current.sx*affine.tx+current.ry*affine.ty+
current.tx;
graphic_context[n]->affine.ty=current.rx*affine.tx+current.sy*affine.ty+
current.ty;
}
if (primitive_type == UndefinedPrimitive)
{
if (*q == '\0')
{
if (number_stops > 1)
{
GradientType
type;
type=LinearGradient;
if (draw_info->gradient.type == RadialGradient)
type=RadialGradient;
(void) GradientImage(image,type,PadSpread,stops,number_stops,
exception);
}
if (number_stops > 0)
stops=(StopInfo *) RelinquishMagickMemory(stops);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",
(int) (q-p),p);
continue;
}
/*
Parse the primitive attributes.
*/
i=0;
j=0;
primitive_info[0].point.x=0.0;
primitive_info[0].point.y=0.0;
for (x=0; *q != '\0'; x++)
{
/*
Define points.
*/
if (IsPoint(q) == MagickFalse)
break;
GetNextToken(q,&q,extent,token);
point.x=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
point.y=StringToDouble(token,(char **) NULL);
GetNextToken(q,(const char **) NULL,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
primitive_info[i].primitive=primitive_type;
primitive_info[i].point=point;
primitive_info[i].coordinates=0;
primitive_info[i].method=FloodfillMethod;
i++;
if (i < (ssize_t) number_points)
continue;
number_points<<=1;
primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info,
(size_t) number_points,sizeof(*primitive_info));
if (primitive_info == (PrimitiveInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
break;
}
}
primitive_info[j].primitive=primitive_type;
primitive_info[j].coordinates=(size_t) x;
primitive_info[j].method=FloodfillMethod;
primitive_info[j].text=(char *) NULL;
/*
Circumscribe primitive within a circle.
*/
bounds.x1=primitive_info[j].point.x;
bounds.y1=primitive_info[j].point.y;
bounds.x2=primitive_info[j].point.x;
bounds.y2=primitive_info[j].point.y;
for (k=1; k < (ssize_t) primitive_info[j].coordinates; k++)
{
point=primitive_info[j+k].point;
if (point.x < bounds.x1)
bounds.x1=point.x;
if (point.y < bounds.y1)
bounds.y1=point.y;
if (point.x > bounds.x2)
bounds.x2=point.x;
if (point.y > bounds.y2)
bounds.y2=point.y;
}
/*
Speculate how many points our primitive might consume.
*/
length=primitive_info[j].coordinates;
switch (primitive_type)
{
case RectanglePrimitive:
{
length*=5;
break;
}
case RoundRectanglePrimitive:
{
double
alpha,
beta,
radius;
alpha=bounds.x2-bounds.x1;
beta=bounds.y2-bounds.y1;
radius=hypot((double) alpha,(double) beta);
length*=5;
length+=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360;
break;
}
case BezierPrimitive:
{
if (primitive_info[j].coordinates > 107)
(void) ThrowMagickException(exception,GetMagickModule(),DrawError,
"TooManyBezierCoordinates","`%s'",token);
length=BezierQuantum*primitive_info[j].coordinates;
break;
}
case PathPrimitive:
{
char
*s,
*t;
GetNextToken(q,&q,extent,token);
length=1;
t=token;
for (s=token; *s != '\0'; s=t)
{
double
value;
value=StringToDouble(s,&t);
(void) value;
if (s == t)
{
t++;
continue;
}
length++;
}
length=length*BezierQuantum/2;
break;
}
case CirclePrimitive:
case ArcPrimitive:
case EllipsePrimitive:
{
double
alpha,
beta,
radius;
alpha=bounds.x2-bounds.x1;
beta=bounds.y2-bounds.y1;
radius=hypot((double) alpha,(double) beta);
length=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360;
break;
}
default:
break;
}
if ((size_t) (i+length) >= number_points)
{
/*
Resize based on speculative points required by primitive.
*/
number_points+=length+1;
primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info,
(size_t) number_points,sizeof(*primitive_info));
if (primitive_info == (PrimitiveInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
break;
}
}
switch (primitive_type)
{
case PointPrimitive:
default:
{
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
TracePoint(primitive_info+j,primitive_info[j].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case LinePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
TraceLine(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case RectanglePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
TraceRectangle(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case RoundRectanglePrimitive:
{
if (primitive_info[j].coordinates != 3)
{
status=MagickFalse;
break;
}
TraceRoundRectangle(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point,primitive_info[j+2].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case ArcPrimitive:
{
if (primitive_info[j].coordinates != 3)
{
primitive_type=UndefinedPrimitive;
break;
}
TraceArc(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point,primitive_info[j+2].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case EllipsePrimitive:
{
if (primitive_info[j].coordinates != 3)
{
status=MagickFalse;
break;
}
TraceEllipse(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point,primitive_info[j+2].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case CirclePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
TraceCircle(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case PolylinePrimitive:
break;
case PolygonPrimitive:
{
primitive_info[i]=primitive_info[j];
primitive_info[i].coordinates=0;
primitive_info[j].coordinates++;
i++;
break;
}
case BezierPrimitive:
{
if (primitive_info[j].coordinates < 3)
{
status=MagickFalse;
break;
}
TraceBezier(primitive_info+j,primitive_info[j].coordinates);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case PathPrimitive:
{
i=(ssize_t) (j+TracePath(primitive_info+j,token));
break;
}
case AlphaPrimitive:
case ColorPrimitive:
{
ssize_t
method;
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
GetNextToken(q,&q,extent,token);
method=ParseCommandOption(MagickMethodOptions,MagickFalse,token);
if (method == -1)
status=MagickFalse;
else
primitive_info[j].method=(PaintMethod) method;
break;
}
case TextPrimitive:
{
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
if (*token != ',')
GetNextToken(q,&q,extent,token);
primitive_info[j].text=AcquireString(token);
break;
}
case ImagePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
GetNextToken(q,&q,extent,token);
primitive_info[j].text=AcquireString(token);
break;
}
}
if (primitive_info == (PrimitiveInfo *) NULL)
break;
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p),p);
if (status == MagickFalse)
break;
primitive_info[i].primitive=UndefinedPrimitive;
if (i == 0)
continue;
/*
Transform points.
*/
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
{
point=primitive_info[i].point;
primitive_info[i].point.x=graphic_context[n]->affine.sx*point.x+
graphic_context[n]->affine.ry*point.y+graphic_context[n]->affine.tx;
primitive_info[i].point.y=graphic_context[n]->affine.rx*point.x+
graphic_context[n]->affine.sy*point.y+graphic_context[n]->affine.ty;
point=primitive_info[i].point;
if (point.x < graphic_context[n]->bounds.x1)
graphic_context[n]->bounds.x1=point.x;
if (point.y < graphic_context[n]->bounds.y1)
graphic_context[n]->bounds.y1=point.y;
if (point.x > graphic_context[n]->bounds.x2)
graphic_context[n]->bounds.x2=point.x;
if (point.y > graphic_context[n]->bounds.y2)
graphic_context[n]->bounds.y2=point.y;
if (primitive_info[i].primitive == ImagePrimitive)
break;
if (i >= (ssize_t) number_points)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
}
if (graphic_context[n]->render != MagickFalse)
{
if ((n != 0) && (graphic_context[n]->clip_mask != (char *) NULL) &&
(LocaleCompare(graphic_context[n]->clip_mask,
graphic_context[n-1]->clip_mask) != 0))
status&=DrawClipPath(image,graphic_context[n],
graphic_context[n]->clip_mask,exception);
status&=DrawPrimitive(image,graphic_context[n],primitive_info,
exception);
}
if (primitive_info->text != (char *) NULL)
primitive_info->text=(char *) RelinquishMagickMemory(
primitive_info->text);
proceed=SetImageProgress(image,RenderImageTag,q-primitive,(MagickSizeType)
primitive_extent);
if (proceed == MagickFalse)
break;
if (status == 0)
break;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"end draw-image");
/*
Relinquish resources.
*/
token=DestroyString(token);
if (primitive_info != (PrimitiveInfo *) NULL)
primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info);
primitive=DestroyString(primitive);
for ( ; n >= 0; n--)
graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context);
if (status == MagickFalse)
ThrowBinaryException(DrawError,"NonconformingDrawingPrimitiveDefinition",
keyword);
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w G r a d i e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawGradientImage() draws a linear gradient on the image.
%
% The format of the DrawGradientImage method is:
%
% MagickBooleanType DrawGradientImage(Image *image,
% const DrawInfo *draw_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double GetStopColorOffset(const GradientInfo *gradient,
const ssize_t x,const ssize_t y)
{
switch (gradient->type)
{
case UndefinedGradient:
case LinearGradient:
{
double
gamma,
length,
offset,
scale;
PointInfo
p,
q;
const SegmentInfo
*gradient_vector;
gradient_vector=(&gradient->gradient_vector);
p.x=gradient_vector->x2-gradient_vector->x1;
p.y=gradient_vector->y2-gradient_vector->y1;
q.x=(double) x-gradient_vector->x1;
q.y=(double) y-gradient_vector->y1;
length=sqrt(q.x*q.x+q.y*q.y);
gamma=sqrt(p.x*p.x+p.y*p.y)*length;
gamma=PerceptibleReciprocal(gamma);
scale=p.x*q.x+p.y*q.y;
offset=gamma*scale*length;
return(offset);
}
case RadialGradient:
{
PointInfo
v;
if (gradient->spread == RepeatSpread)
{
v.x=(double) x-gradient->center.x;
v.y=(double) y-gradient->center.y;
return(sqrt(v.x*v.x+v.y*v.y));
}
v.x=(double) (((x-gradient->center.x)*cos(DegreesToRadians(
gradient->angle)))+((y-gradient->center.y)*sin(DegreesToRadians(
gradient->angle))))/gradient->radii.x;
v.y=(double) (((x-gradient->center.x)*sin(DegreesToRadians(
gradient->angle)))-((y-gradient->center.y)*cos(DegreesToRadians(
gradient->angle))))/gradient->radii.y;
return(sqrt(v.x*v.x+v.y*v.y));
}
}
return(0.0);
}
static int StopInfoCompare(const void *x,const void *y)
{
StopInfo
*stop_1,
*stop_2;
stop_1=(StopInfo *) x;
stop_2=(StopInfo *) y;
if (stop_1->offset > stop_2->offset)
return(1);
if (fabs(stop_1->offset-stop_2->offset) <= MagickEpsilon)
return(0);
return(-1);
}
MagickExport MagickBooleanType DrawGradientImage(Image *image,
const DrawInfo *draw_info,ExceptionInfo *exception)
{
CacheView
*image_view;
const GradientInfo
*gradient;
const SegmentInfo
*gradient_vector;
double
length;
MagickBooleanType
status;
PixelInfo
zero;
PointInfo
point;
RectangleInfo
bounding_box;
ssize_t
y;
/*
Draw linear or radial gradient on image.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (const DrawInfo *) NULL);
gradient=(&draw_info->gradient);
qsort(gradient->stops,gradient->number_stops,sizeof(StopInfo),
StopInfoCompare);
gradient_vector=(&gradient->gradient_vector);
point.x=gradient_vector->x2-gradient_vector->x1;
point.y=gradient_vector->y2-gradient_vector->y1;
length=sqrt(point.x*point.x+point.y*point.y);
bounding_box=gradient->bounding_box;
status=MagickTrue;
GetPixelInfo(image,&zero);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,1,1)
#endif
for (y=bounding_box.y; y < (ssize_t) bounding_box.height; y++)
{
PixelInfo
composite,
pixel;
double
alpha,
offset;
register Quantum
*magick_restrict q;
register ssize_t
i,
x;
ssize_t
j;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
pixel=zero;
composite=zero;
offset=GetStopColorOffset(gradient,0,y);
if (gradient->type != RadialGradient)
offset/=length;
for (x=bounding_box.x; x < (ssize_t) bounding_box.width; x++)
{
GetPixelInfoPixel(image,q,&pixel);
switch (gradient->spread)
{
case UndefinedSpread:
case PadSpread:
{
if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
(y != (ssize_t) ceil(gradient_vector->y1-0.5)))
{
offset=GetStopColorOffset(gradient,x,y);
if (gradient->type != RadialGradient)
offset/=length;
}
for (i=0; i < (ssize_t) gradient->number_stops; i++)
if (offset < gradient->stops[i].offset)
break;
if ((offset < 0.0) || (i == 0))
composite=gradient->stops[0].color;
else
if ((offset > 1.0) || (i == (ssize_t) gradient->number_stops))
composite=gradient->stops[gradient->number_stops-1].color;
else
{
j=i;
i--;
alpha=(offset-gradient->stops[i].offset)/
(gradient->stops[j].offset-gradient->stops[i].offset);
CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,
&gradient->stops[j].color,alpha,&composite);
}
break;
}
case ReflectSpread:
{
if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
(y != (ssize_t) ceil(gradient_vector->y1-0.5)))
{
offset=GetStopColorOffset(gradient,x,y);
if (gradient->type != RadialGradient)
offset/=length;
}
if (offset < 0.0)
offset=(-offset);
if ((ssize_t) fmod(offset,2.0) == 0)
offset=fmod(offset,1.0);
else
offset=1.0-fmod(offset,1.0);
for (i=0; i < (ssize_t) gradient->number_stops; i++)
if (offset < gradient->stops[i].offset)
break;
if (i == 0)
composite=gradient->stops[0].color;
else
if (i == (ssize_t) gradient->number_stops)
composite=gradient->stops[gradient->number_stops-1].color;
else
{
j=i;
i--;
alpha=(offset-gradient->stops[i].offset)/
(gradient->stops[j].offset-gradient->stops[i].offset);
CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,
&gradient->stops[j].color,alpha,&composite);
}
break;
}
case RepeatSpread:
{
MagickBooleanType
antialias;
double
repeat;
antialias=MagickFalse;
repeat=0.0;
if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
(y != (ssize_t) ceil(gradient_vector->y1-0.5)))
{
offset=GetStopColorOffset(gradient,x,y);
if (gradient->type == LinearGradient)
{
repeat=fmod(offset,length);
if (repeat < 0.0)
repeat=length-fmod(-repeat,length);
else
repeat=fmod(offset,length);
antialias=(repeat < length) && ((repeat+1.0) > length) ?
MagickTrue : MagickFalse;
offset=repeat/length;
}
else
{
repeat=fmod(offset,gradient->radius);
if (repeat < 0.0)
repeat=gradient->radius-fmod(-repeat,gradient->radius);
else
repeat=fmod(offset,gradient->radius);
antialias=repeat+1.0 > gradient->radius ? MagickTrue :
MagickFalse;
offset=repeat/gradient->radius;
}
}
for (i=0; i < (ssize_t) gradient->number_stops; i++)
if (offset < gradient->stops[i].offset)
break;
if (i == 0)
composite=gradient->stops[0].color;
else
if (i == (ssize_t) gradient->number_stops)
composite=gradient->stops[gradient->number_stops-1].color;
else
{
j=i;
i--;
alpha=(offset-gradient->stops[i].offset)/
(gradient->stops[j].offset-gradient->stops[i].offset);
if (antialias != MagickFalse)
{
if (gradient->type == LinearGradient)
alpha=length-repeat;
else
alpha=gradient->radius-repeat;
i=0;
j=(ssize_t) gradient->number_stops-1L;
}
CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,
&gradient->stops[j].color,alpha,&composite);
}
break;
}
}
CompositePixelInfoOver(&composite,composite.alpha,&pixel,pixel.alpha,
&pixel);
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w P a t t e r n P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawPatternPath() draws a pattern.
%
% The format of the DrawPatternPath method is:
%
% MagickBooleanType DrawPatternPath(Image *image,const DrawInfo *draw_info,
% const char *name,Image **pattern,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o name: the pattern name.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType DrawPatternPath(Image *image,
const DrawInfo *draw_info,const char *name,Image **pattern,
ExceptionInfo *exception)
{
char
property[MagickPathExtent];
const char
*geometry,
*path,
*type;
DrawInfo
*clone_info;
ImageInfo
*image_info;
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (const DrawInfo *) NULL);
assert(name != (const char *) NULL);
(void) FormatLocaleString(property,MagickPathExtent,"%s",name);
path=GetImageArtifact(image,property);
if (path == (const char *) NULL)
return(MagickFalse);
(void) FormatLocaleString(property,MagickPathExtent,"%s-geometry",name);
geometry=GetImageArtifact(image,property);
if (geometry == (const char *) NULL)
return(MagickFalse);
if ((*pattern) != (Image *) NULL)
*pattern=DestroyImage(*pattern);
image_info=AcquireImageInfo();
image_info->size=AcquireString(geometry);
*pattern=AcquireImage(image_info,exception);
image_info=DestroyImageInfo(image_info);
(void) QueryColorCompliance("#000000ff",AllCompliance,
&(*pattern)->background_color,exception);
(void) SetImageBackgroundColor(*pattern,exception);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"begin pattern-path %s %s",name,geometry);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->fill_pattern=NewImageList();
clone_info->stroke_pattern=NewImageList();
(void) FormatLocaleString(property,MagickPathExtent,"%s-type",name);
type=GetImageArtifact(image,property);
if (type != (const char *) NULL)
clone_info->gradient.type=(GradientType) ParseCommandOption(
MagickGradientOptions,MagickFalse,type);
(void) CloneString(&clone_info->primitive,path);
status=DrawImage(*pattern,clone_info,exception);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"end pattern-path");
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w P o l y g o n P r i m i t i v e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawPolygonPrimitive() draws a polygon on the image.
%
% The format of the DrawPolygonPrimitive method is:
%
% MagickBooleanType DrawPolygonPrimitive(Image *image,
% const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static PolygonInfo **DestroyPolygonThreadSet(PolygonInfo **polygon_info)
{
register ssize_t
i;
assert(polygon_info != (PolygonInfo **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (polygon_info[i] != (PolygonInfo *) NULL)
polygon_info[i]=DestroyPolygonInfo(polygon_info[i]);
polygon_info=(PolygonInfo **) RelinquishMagickMemory(polygon_info);
return(polygon_info);
}
static PolygonInfo **AcquirePolygonThreadSet(
const PrimitiveInfo *primitive_info)
{
PathInfo
*magick_restrict path_info;
PolygonInfo
**polygon_info;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
polygon_info=(PolygonInfo **) AcquireQuantumMemory(number_threads,
sizeof(*polygon_info));
if (polygon_info == (PolygonInfo **) NULL)
return((PolygonInfo **) NULL);
(void) ResetMagickMemory(polygon_info,0,number_threads*sizeof(*polygon_info));
path_info=ConvertPrimitiveToPath(primitive_info);
if (path_info == (PathInfo *) NULL)
return(DestroyPolygonThreadSet(polygon_info));
for (i=0; i < (ssize_t) number_threads; i++)
{
polygon_info[i]=ConvertPathToPolygon(path_info);
if (polygon_info[i] == (PolygonInfo *) NULL)
return(DestroyPolygonThreadSet(polygon_info));
}
path_info=(PathInfo *) RelinquishMagickMemory(path_info);
return(polygon_info);
}
static double GetFillAlpha(PolygonInfo *polygon_info,const double mid,
const MagickBooleanType fill,const FillRule fill_rule,const ssize_t x,
const ssize_t y,double *stroke_alpha)
{
double
alpha,
beta,
distance,
subpath_alpha;
PointInfo
delta;
register const PointInfo
*q;
register EdgeInfo
*p;
register ssize_t
i;
ssize_t
j,
winding_number;
/*
Compute fill & stroke opacity for this (x,y) point.
*/
*stroke_alpha=0.0;
subpath_alpha=0.0;
p=polygon_info->edges;
for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++)
{
if ((double) y <= (p->bounds.y1-mid-0.5))
break;
if ((double) y > (p->bounds.y2+mid+0.5))
{
(void) DestroyEdge(polygon_info,(size_t) j);
continue;
}
if (((double) x <= (p->bounds.x1-mid-0.5)) ||
((double) x > (p->bounds.x2+mid+0.5)))
continue;
i=(ssize_t) MagickMax((double) p->highwater,1.0);
for ( ; i < (ssize_t) p->number_points; i++)
{
if ((double) y <= (p->points[i-1].y-mid-0.5))
break;
if ((double) y > (p->points[i].y+mid+0.5))
continue;
if (p->scanline != (double) y)
{
p->scanline=(double) y;
p->highwater=(size_t) i;
}
/*
Compute distance between a point and an edge.
*/
q=p->points+i-1;
delta.x=(q+1)->x-q->x;
delta.y=(q+1)->y-q->y;
beta=delta.x*(x-q->x)+delta.y*(y-q->y);
if (beta < 0.0)
{
delta.x=(double) x-q->x;
delta.y=(double) y-q->y;
distance=delta.x*delta.x+delta.y*delta.y;
}
else
{
alpha=delta.x*delta.x+delta.y*delta.y;
if (beta > alpha)
{
delta.x=(double) x-(q+1)->x;
delta.y=(double) y-(q+1)->y;
distance=delta.x*delta.x+delta.y*delta.y;
}
else
{
alpha=1.0/alpha;
beta=delta.x*(y-q->y)-delta.y*(x-q->x);
distance=alpha*beta*beta;
}
}
/*
Compute stroke & subpath opacity.
*/
beta=0.0;
if (p->ghostline == MagickFalse)
{
alpha=mid+0.5;
if ((*stroke_alpha < 1.0) &&
(distance <= ((alpha+0.25)*(alpha+0.25))))
{
alpha=mid-0.5;
if (distance <= ((alpha+0.25)*(alpha+0.25)))
*stroke_alpha=1.0;
else
{
beta=1.0;
if (distance != 1.0)
beta=sqrt((double) distance);
alpha=beta-mid-0.5;
if (*stroke_alpha < ((alpha-0.25)*(alpha-0.25)))
*stroke_alpha=(alpha-0.25)*(alpha-0.25);
}
}
}
if ((fill == MagickFalse) || (distance > 1.0) || (subpath_alpha >= 1.0))
continue;
if (distance <= 0.0)
{
subpath_alpha=1.0;
continue;
}
if (distance > 1.0)
continue;
if (beta == 0.0)
{
beta=1.0;
if (distance != 1.0)
beta=sqrt(distance);
}
alpha=beta-1.0;
if (subpath_alpha < (alpha*alpha))
subpath_alpha=alpha*alpha;
}
}
/*
Compute fill opacity.
*/
if (fill == MagickFalse)
return(0.0);
if (subpath_alpha >= 1.0)
return(1.0);
/*
Determine winding number.
*/
winding_number=0;
p=polygon_info->edges;
for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++)
{
if ((double) y <= p->bounds.y1)
break;
if (((double) y > p->bounds.y2) || ((double) x <= p->bounds.x1))
continue;
if ((double) x > p->bounds.x2)
{
winding_number+=p->direction ? 1 : -1;
continue;
}
i=(ssize_t) MagickMax((double) p->highwater,1.0);
for ( ; i < (ssize_t) p->number_points; i++)
if ((double) y <= p->points[i].y)
break;
q=p->points+i-1;
if ((((q+1)->x-q->x)*(y-q->y)) <= (((q+1)->y-q->y)*(x-q->x)))
winding_number+=p->direction ? 1 : -1;
}
if (fill_rule != NonZeroRule)
{
if ((MagickAbsoluteValue(winding_number) & 0x01) != 0)
return(1.0);
}
else
if (MagickAbsoluteValue(winding_number) != 0)
return(1.0);
return(subpath_alpha);
}
static MagickBooleanType DrawPolygonPrimitive(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
fill,
status;
double
mid;
PolygonInfo
**magick_restrict polygon_info;
register EdgeInfo
*p;
register ssize_t
i;
SegmentInfo
bounds;
ssize_t
start_y,
stop_y,
y;
/*
Compute bounding box.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
assert(primitive_info != (PrimitiveInfo *) NULL);
if (primitive_info->coordinates == 0)
return(MagickTrue);
polygon_info=AcquirePolygonThreadSet(primitive_info);
if (polygon_info == (PolygonInfo **) NULL)
return(MagickFalse);
DisableMSCWarning(4127)
if (0)
DrawBoundingRectangles(image,draw_info,polygon_info[0],exception);
RestoreMSCWarning
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-polygon");
fill=(primitive_info->method == FillToBorderMethod) ||
(primitive_info->method == FloodfillMethod) ? MagickTrue : MagickFalse;
mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
bounds=polygon_info[0]->edges[0].bounds;
for (i=1; i < (ssize_t) polygon_info[0]->number_edges; i++)
{
p=polygon_info[0]->edges+i;
if (p->bounds.x1 < bounds.x1)
bounds.x1=p->bounds.x1;
if (p->bounds.y1 < bounds.y1)
bounds.y1=p->bounds.y1;
if (p->bounds.x2 > bounds.x2)
bounds.x2=p->bounds.x2;
if (p->bounds.y2 > bounds.y2)
bounds.y2=p->bounds.y2;
}
bounds.x1-=(mid+1.0);
bounds.x1=bounds.x1 < 0.0 ? 0.0 : (size_t) ceil(bounds.x1-0.5) >=
image->columns ? (double) image->columns-1 : bounds.x1;
bounds.y1-=(mid+1.0);
bounds.y1=bounds.y1 < 0.0 ? 0.0 : (size_t) ceil(bounds.y1-0.5) >=
image->rows ? (double) image->rows-1 : bounds.y1;
bounds.x2+=(mid+1.0);
bounds.x2=bounds.x2 < 0.0 ? 0.0 : (size_t) floor(bounds.x2+0.5) >=
image->columns ? (double) image->columns-1 : bounds.x2;
bounds.y2+=(mid+1.0);
bounds.y2=bounds.y2 < 0.0 ? 0.0 : (size_t) floor(bounds.y2+0.5) >=
image->rows ? (double) image->rows-1 : bounds.y2;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
if ((primitive_info->coordinates == 1) ||
(polygon_info[0]->number_edges == 0))
{
/*
Draw point.
*/
start_y=(ssize_t) ceil(bounds.y1-0.5);
stop_y=(ssize_t) floor(bounds.y2+0.5);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,1,1)
#endif
for (y=start_y; y <= stop_y; y++)
{
MagickBooleanType
sync;
PixelInfo
pixel;
register ssize_t
x;
register Quantum
*magick_restrict q;
ssize_t
start_x,
stop_x;
if (status == MagickFalse)
continue;
start_x=(ssize_t) ceil(bounds.x1-0.5);
stop_x=(ssize_t) floor(bounds.x2+0.5);
x=start_x;
q=GetCacheViewAuthenticPixels(image_view,x,y,(size_t) (stop_x-x+1),1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
GetPixelInfo(image,&pixel);
for ( ; x <= stop_x; x++)
{
if ((x == (ssize_t) ceil(primitive_info->point.x-0.5)) &&
(y == (ssize_t) ceil(primitive_info->point.y-0.5)))
{
GetFillColor(draw_info,x-start_x,y-start_y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
}
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
polygon_info=DestroyPolygonThreadSet(polygon_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" end draw-polygon");
return(status);
}
/*
Draw polygon or line.
*/
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
start_y=(ssize_t) ceil(bounds.y1-0.5);
stop_y=(ssize_t) floor(bounds.y2+0.5);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,1,1)
#endif
for (y=start_y; y <= stop_y; y++)
{
const int
id = GetOpenMPThreadId();
double
fill_alpha,
stroke_alpha;
PixelInfo
fill_color,
stroke_color;
register Quantum
*magick_restrict q;
register ssize_t
x;
ssize_t
start_x,
stop_x;
if (status == MagickFalse)
continue;
start_x=(ssize_t) ceil(bounds.x1-0.5);
stop_x=(ssize_t) floor(bounds.x2+0.5);
q=GetCacheViewAuthenticPixels(image_view,start_x,y,(size_t) (stop_x-start_x+1),1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=start_x; x <= stop_x; x++)
{
/*
Fill and/or stroke.
*/
fill_alpha=GetFillAlpha(polygon_info[id],mid,fill,draw_info->fill_rule,
x,y,&stroke_alpha);
if (draw_info->stroke_antialias == MagickFalse)
{
fill_alpha=fill_alpha > 0.25 ? 1.0 : 0.0;
stroke_alpha=stroke_alpha > 0.25 ? 1.0 : 0.0;
}
GetFillColor(draw_info,x-start_x,y-start_y,&fill_color,exception);
fill_alpha=fill_alpha*fill_color.alpha;
CompositePixelOver(image,&fill_color,fill_alpha,q,(double)
GetPixelAlpha(image,q),q);
GetStrokeColor(draw_info,x-start_x,y-start_y,&stroke_color,exception);
stroke_alpha=stroke_alpha*stroke_color.alpha;
CompositePixelOver(image,&stroke_color,stroke_alpha,q,(double)
GetPixelAlpha(image,q),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
polygon_info=DestroyPolygonThreadSet(polygon_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-polygon");
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w P r i m i t i v e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawPrimitive() draws a primitive (line, rectangle, ellipse) on the image.
%
% The format of the DrawPrimitive method is:
%
% MagickBooleanType DrawPrimitive(Image *image,const DrawInfo *draw_info,
% PrimitiveInfo *primitive_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static void LogPrimitiveInfo(const PrimitiveInfo *primitive_info)
{
const char
*methods[] =
{
"point",
"replace",
"floodfill",
"filltoborder",
"reset",
"?"
};
PointInfo
p,
q,
point;
register ssize_t
i,
x;
ssize_t
coordinates,
y;
x=(ssize_t) ceil(primitive_info->point.x-0.5);
y=(ssize_t) ceil(primitive_info->point.y-0.5);
switch (primitive_info->primitive)
{
case AlphaPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"AlphaPrimitive %.20g,%.20g %s",(double) x,(double) y,
methods[primitive_info->method]);
return;
}
case ColorPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"ColorPrimitive %.20g,%.20g %s",(double) x,(double) y,
methods[primitive_info->method]);
return;
}
case ImagePrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"ImagePrimitive %.20g,%.20g",(double) x,(double) y);
return;
}
case PointPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"PointPrimitive %.20g,%.20g %s",(double) x,(double) y,
methods[primitive_info->method]);
return;
}
case TextPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"TextPrimitive %.20g,%.20g",(double) x,(double) y);
return;
}
default:
break;
}
coordinates=0;
p=primitive_info[0].point;
q.x=(-1.0);
q.y=(-1.0);
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
{
point=primitive_info[i].point;
if (coordinates <= 0)
{
coordinates=(ssize_t) primitive_info[i].coordinates;
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin open (%.20g)",(double) coordinates);
p=point;
}
point=primitive_info[i].point;
if ((fabs(q.x-point.x) >= MagickEpsilon) ||
(fabs(q.y-point.y) >= MagickEpsilon))
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" %.20g: %.18g,%.18g",(double) coordinates,point.x,point.y);
else
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" %.20g: %g %g (duplicate)",(double) coordinates,point.x,point.y);
q=point;
coordinates--;
if (coordinates > 0)
continue;
if ((fabs(p.x-point.x) >= MagickEpsilon) ||
(fabs(p.y-point.y) >= MagickEpsilon))
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end last (%.20g)",
(double) coordinates);
else
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end open (%.20g)",
(double) coordinates);
}
}
MagickExport MagickBooleanType DrawPrimitive(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickStatusType
status;
register ssize_t
i,
x;
ssize_t
y;
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin draw-primitive");
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" affine: %g %g %g %g %g %g",draw_info->affine.sx,
draw_info->affine.rx,draw_info->affine.ry,draw_info->affine.sy,
draw_info->affine.tx,draw_info->affine.ty);
}
if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
((IsPixelInfoGray(&draw_info->fill) == MagickFalse) ||
(IsPixelInfoGray(&draw_info->stroke) == MagickFalse)))
(void) SetImageColorspace(image,sRGBColorspace,exception);
status=MagickTrue;
x=(ssize_t) ceil(primitive_info->point.x-0.5);
y=(ssize_t) ceil(primitive_info->point.y-0.5);
image_view=AcquireAuthenticCacheView(image,exception);
switch (primitive_info->primitive)
{
case AlphaPrimitive:
{
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
switch (primitive_info->method)
{
case PointMethod:
default:
{
PixelInfo
pixel;
register Quantum
*q;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (Quantum *) NULL)
break;
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case ReplaceMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel,
target;
(void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,
exception);
GetPixelInfo(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,q,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)
{
q+=GetPixelChannels(image);
continue;
}
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
case FloodfillMethod:
case FillToBorderMethod:
{
ChannelType
channel_mask;
PixelInfo
target;
(void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,
&target,exception);
if (primitive_info->method == FillToBorderMethod)
{
target.red=(double) draw_info->border_color.red;
target.green=(double) draw_info->border_color.green;
target.blue=(double) draw_info->border_color.blue;
}
channel_mask=SetImageChannelMask(image,AlphaChannel);
status&=FloodfillPaintImage(image,draw_info,&target,x,y,
primitive_info->method == FloodfillMethod ? MagickFalse :
MagickTrue,exception);
(void) SetImageChannelMask(image,channel_mask);
break;
}
case ResetMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel;
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
}
break;
}
case ColorPrimitive:
{
switch (primitive_info->method)
{
case PointMethod:
default:
{
PixelInfo
pixel;
register Quantum
*q;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (Quantum *) NULL)
break;
GetPixelInfo(image,&pixel);
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case ReplaceMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel,
target;
(void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,
exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,q,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)
{
q+=GetPixelChannels(image);
continue;
}
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
case FloodfillMethod:
case FillToBorderMethod:
{
PixelInfo
target;
(void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,
&target,exception);
if (primitive_info->method == FillToBorderMethod)
{
target.red=(double) draw_info->border_color.red;
target.green=(double) draw_info->border_color.green;
target.blue=(double) draw_info->border_color.blue;
}
status&=FloodfillPaintImage(image,draw_info,&target,x,y,
primitive_info->method == FloodfillMethod ? MagickFalse :
MagickTrue,exception);
break;
}
case ResetMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel;
GetPixelInfo(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
}
break;
}
case ImagePrimitive:
{
AffineMatrix
affine;
char
composite_geometry[MagickPathExtent];
Image
*composite_image;
ImageInfo
*clone_info;
RectangleInfo
geometry;
ssize_t
x1,
y1;
if (primitive_info->text == (char *) NULL)
break;
clone_info=AcquireImageInfo();
if (LocaleNCompare(primitive_info->text,"data:",5) == 0)
composite_image=ReadInlineImage(clone_info,primitive_info->text,
exception);
else
{
(void) CopyMagickString(clone_info->filename,primitive_info->text,
MagickPathExtent);
composite_image=ReadImage(clone_info,exception);
}
clone_info=DestroyImageInfo(clone_info);
if (composite_image == (Image *) NULL)
break;
(void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor)
NULL,(void *) NULL);
x1=(ssize_t) ceil(primitive_info[1].point.x-0.5);
y1=(ssize_t) ceil(primitive_info[1].point.y-0.5);
if (((x1 != 0L) && (x1 != (ssize_t) composite_image->columns)) ||
((y1 != 0L) && (y1 != (ssize_t) composite_image->rows)))
{
/*
Resize image.
*/
(void) FormatLocaleString(composite_geometry,MagickPathExtent,
"%gx%g!",primitive_info[1].point.x,primitive_info[1].point.y);
composite_image->filter=image->filter;
(void) TransformImage(&composite_image,(char *) NULL,
composite_geometry,exception);
}
if (composite_image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel,
exception);
if (draw_info->alpha != OpaqueAlpha)
(void) SetImageAlpha(composite_image,draw_info->alpha,exception);
SetGeometry(image,&geometry);
image->gravity=draw_info->gravity;
geometry.x=x;
geometry.y=y;
(void) FormatLocaleString(composite_geometry,MagickPathExtent,
"%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns,(double)
composite_image->rows,(double) geometry.x,(double) geometry.y);
(void) ParseGravityGeometry(image,composite_geometry,&geometry,exception);
affine=draw_info->affine;
affine.tx=(double) geometry.x;
affine.ty=(double) geometry.y;
composite_image->interpolate=image->interpolate;
if (draw_info->compose == OverCompositeOp)
(void) DrawAffineImage(image,composite_image,&affine,exception);
else
(void) CompositeImage(image,composite_image,draw_info->compose,
MagickTrue,geometry.x,geometry.y,exception);
composite_image=DestroyImage(composite_image);
break;
}
case PointPrimitive:
{
PixelInfo
fill_color;
register Quantum
*q;
if ((y < 0) || (y >= (ssize_t) image->rows))
break;
if ((x < 0) || (x >= (ssize_t) image->columns))
break;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (Quantum *) NULL)
break;
GetFillColor(draw_info,x,y,&fill_color,exception);
CompositePixelOver(image,&fill_color,(double) fill_color.alpha,q,
(double) GetPixelAlpha(image,q),q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case TextPrimitive:
{
char
geometry[MagickPathExtent];
DrawInfo
*clone_info;
if (primitive_info->text == (char *) NULL)
break;
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) CloneString(&clone_info->text,primitive_info->text);
(void) FormatLocaleString(geometry,MagickPathExtent,"%+f%+f",
primitive_info->point.x,primitive_info->point.y);
(void) CloneString(&clone_info->geometry,geometry);
status&=AnnotateImage(image,clone_info,exception);
clone_info=DestroyDrawInfo(clone_info);
break;
}
default:
{
double
mid,
scale;
DrawInfo
*clone_info;
if (IsEventLogging() != MagickFalse)
LogPrimitiveInfo(primitive_info);
scale=ExpandAffine(&draw_info->affine);
if ((draw_info->dash_pattern != (double *) NULL) &&
(draw_info->dash_pattern[0] != 0.0) &&
((scale*draw_info->stroke_width) >= MagickEpsilon) &&
(draw_info->stroke.alpha != (Quantum) TransparentAlpha))
{
/*
Draw dash polygon.
*/
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->stroke_width=0.0;
clone_info->stroke.alpha=(Quantum) TransparentAlpha;
status&=DrawPolygonPrimitive(image,clone_info,primitive_info,
exception);
clone_info=DestroyDrawInfo(clone_info);
(void) DrawDashPolygon(draw_info,primitive_info,image,exception);
break;
}
mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
if ((mid > 1.0) &&
((draw_info->stroke.alpha != (Quantum) TransparentAlpha) ||
(draw_info->stroke_pattern != (Image *) NULL)))
{
MagickBooleanType
closed_path;
/*
Draw strokes while respecting line cap/join attributes.
*/
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
closed_path=
(primitive_info[i-1].point.x == primitive_info[0].point.x) &&
(primitive_info[i-1].point.y == primitive_info[0].point.y) ?
MagickTrue : MagickFalse;
i=(ssize_t) primitive_info[0].coordinates;
if ((((draw_info->linecap == RoundCap) ||
(closed_path != MagickFalse)) &&
(draw_info->linejoin == RoundJoin)) ||
(primitive_info[i].primitive != UndefinedPrimitive))
{
(void) DrawPolygonPrimitive(image,draw_info,primitive_info,
exception);
break;
}
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->stroke_width=0.0;
clone_info->stroke.alpha=(Quantum) TransparentAlpha;
status&=DrawPolygonPrimitive(image,clone_info,primitive_info,
exception);
clone_info=DestroyDrawInfo(clone_info);
status&=DrawStrokePolygon(image,draw_info,primitive_info,exception);
break;
}
status&=DrawPolygonPrimitive(image,draw_info,primitive_info,exception);
break;
}
}
image_view=DestroyCacheView(image_view);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-primitive");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w S t r o k e P o l y g o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawStrokePolygon() draws a stroked polygon (line, rectangle, ellipse) on
% the image while respecting the line cap and join attributes.
%
% The format of the DrawStrokePolygon method is:
%
% MagickBooleanType DrawStrokePolygon(Image *image,
% const DrawInfo *draw_info,const PrimitiveInfo *primitive_info)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
%
*/
static void DrawRoundLinecap(Image *image,const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info,ExceptionInfo *exception)
{
PrimitiveInfo
linecap[5];
register ssize_t
i;
for (i=0; i < 4; i++)
linecap[i]=(*primitive_info);
linecap[0].coordinates=4;
linecap[1].point.x+=(double) (10.0*MagickEpsilon);
linecap[2].point.x+=(double) (10.0*MagickEpsilon);
linecap[2].point.y+=(double) (10.0*MagickEpsilon);
linecap[3].point.y+=(double) (10.0*MagickEpsilon);
linecap[4].primitive=UndefinedPrimitive;
(void) DrawPolygonPrimitive(image,draw_info,linecap,exception);
}
static MagickBooleanType DrawStrokePolygon(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
ExceptionInfo *exception)
{
DrawInfo
*clone_info;
MagickBooleanType
closed_path;
MagickStatusType
status;
PrimitiveInfo
*stroke_polygon;
register const PrimitiveInfo
*p,
*q;
/*
Draw stroked polygon.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin draw-stroke-polygon");
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->fill=draw_info->stroke;
if (clone_info->fill_pattern != (Image *) NULL)
clone_info->fill_pattern=DestroyImage(clone_info->fill_pattern);
if (clone_info->stroke_pattern != (Image *) NULL)
clone_info->fill_pattern=CloneImage(clone_info->stroke_pattern,0,0,
MagickTrue,exception);
clone_info->stroke.alpha=(Quantum) TransparentAlpha;
clone_info->stroke_width=0.0;
clone_info->fill_rule=NonZeroRule;
status=MagickTrue;
for (p=primitive_info; p->primitive != UndefinedPrimitive; p+=p->coordinates)
{
stroke_polygon=TraceStrokePolygon(draw_info,p);
status&=DrawPolygonPrimitive(image,clone_info,stroke_polygon,exception);
if (status == 0)
break;
stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon);
q=p+p->coordinates-1;
closed_path=(q->point.x == p->point.x) && (q->point.y == p->point.y) ?
MagickTrue : MagickFalse;
if ((draw_info->linecap == RoundCap) && (closed_path == MagickFalse))
{
DrawRoundLinecap(image,draw_info,p,exception);
DrawRoundLinecap(image,draw_info,q,exception);
}
}
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" end draw-stroke-polygon");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t A f f i n e M a t r i x %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAffineMatrix() returns an AffineMatrix initialized to the identity
% matrix.
%
% The format of the GetAffineMatrix method is:
%
% void GetAffineMatrix(AffineMatrix *affine_matrix)
%
% A description of each parameter follows:
%
% o affine_matrix: the affine matrix.
%
*/
MagickExport void GetAffineMatrix(AffineMatrix *affine_matrix)
{
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(affine_matrix != (AffineMatrix *) NULL);
(void) ResetMagickMemory(affine_matrix,0,sizeof(*affine_matrix));
affine_matrix->sx=1.0;
affine_matrix->sy=1.0;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetDrawInfo() initializes draw_info to default values from image_info.
%
% The format of the GetDrawInfo method is:
%
% void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o image_info: the image info..
%
% o draw_info: the draw info.
%
*/
MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)
{
const char
*option;
ExceptionInfo
*exception;
ImageInfo
*clone_info;
/*
Initialize draw attributes.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(draw_info != (DrawInfo *) NULL);
(void) ResetMagickMemory(draw_info,0,sizeof(*draw_info));
clone_info=CloneImageInfo(image_info);
GetAffineMatrix(&draw_info->affine);
exception=AcquireExceptionInfo();
(void) QueryColorCompliance("#000F",AllCompliance,&draw_info->fill,
exception);
(void) QueryColorCompliance("#0000",AllCompliance,&draw_info->stroke,
exception);
draw_info->stroke_width=1.0;
draw_info->alpha=OpaqueAlpha;
draw_info->fill_rule=EvenOddRule;
draw_info->linecap=ButtCap;
draw_info->linejoin=MiterJoin;
draw_info->miterlimit=10;
draw_info->decorate=NoDecoration;
draw_info->pointsize=12.0;
draw_info->undercolor.alpha=(Quantum) TransparentAlpha;
draw_info->compose=OverCompositeOp;
draw_info->render=MagickTrue;
draw_info->debug=IsEventLogging();
draw_info->stroke_antialias=clone_info->antialias;
if (clone_info->font != (char *) NULL)
draw_info->font=AcquireString(clone_info->font);
if (clone_info->density != (char *) NULL)
draw_info->density=AcquireString(clone_info->density);
draw_info->text_antialias=clone_info->antialias;
if (clone_info->pointsize != 0.0)
draw_info->pointsize=clone_info->pointsize;
draw_info->border_color=clone_info->border_color;
if (clone_info->server_name != (char *) NULL)
draw_info->server_name=AcquireString(clone_info->server_name);
option=GetImageOption(clone_info,"direction");
if (option != (const char *) NULL)
draw_info->direction=(DirectionType) ParseCommandOption(
MagickDirectionOptions,MagickFalse,option);
else
draw_info->direction=UndefinedDirection;
option=GetImageOption(clone_info,"encoding");
if (option != (const char *) NULL)
(void) CloneString(&draw_info->encoding,option);
option=GetImageOption(clone_info,"family");
if (option != (const char *) NULL)
(void) CloneString(&draw_info->family,option);
option=GetImageOption(clone_info,"fill");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&draw_info->fill,
exception);
option=GetImageOption(clone_info,"gravity");
if (option != (const char *) NULL)
draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions,
MagickFalse,option);
option=GetImageOption(clone_info,"interline-spacing");
if (option != (const char *) NULL)
draw_info->interline_spacing=StringToDouble(option,(char **) NULL);
option=GetImageOption(clone_info,"interword-spacing");
if (option != (const char *) NULL)
draw_info->interword_spacing=StringToDouble(option,(char **) NULL);
option=GetImageOption(clone_info,"kerning");
if (option != (const char *) NULL)
draw_info->kerning=StringToDouble(option,(char **) NULL);
option=GetImageOption(clone_info,"stroke");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&draw_info->stroke,
exception);
option=GetImageOption(clone_info,"strokewidth");
if (option != (const char *) NULL)
draw_info->stroke_width=StringToDouble(option,(char **) NULL);
option=GetImageOption(clone_info,"style");
if (option != (const char *) NULL)
draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions,
MagickFalse,option);
option=GetImageOption(clone_info,"undercolor");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&draw_info->undercolor,
exception);
option=GetImageOption(clone_info,"weight");
if (option != (const char *) NULL)
{
ssize_t
weight;
weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option);
if (weight == -1)
weight=StringToUnsignedLong(option);
draw_info->weight=(size_t) weight;
}
exception=DestroyExceptionInfo(exception);
draw_info->signature=MagickCoreSignature;
clone_info=DestroyImageInfo(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ P e r m u t a t e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Permutate() returns the permuation of the (n,k).
%
% The format of the Permutate method is:
%
% void Permutate(ssize_t n,ssize_t k)
%
% A description of each parameter follows:
%
% o n:
%
% o k:
%
%
*/
static inline double Permutate(const ssize_t n,const ssize_t k)
{
double
r;
register ssize_t
i;
r=1.0;
for (i=k+1; i <= n; i++)
r*=i;
for (i=1; i <= (n-k); i++)
r/=i;
return(r);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ T r a c e P r i m i t i v e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TracePrimitive is a collection of methods for generating graphic
% primitives such as arcs, ellipses, paths, etc.
%
*/
static void TraceArc(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end,const PointInfo degrees)
{
PointInfo
center,
radii;
center.x=0.5*(end.x+start.x);
center.y=0.5*(end.y+start.y);
radii.x=fabs(center.x-start.x);
radii.y=fabs(center.y-start.y);
TraceEllipse(primitive_info,center,radii,degrees);
}
static void TraceArcPath(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end,const PointInfo arc,const double angle,
const MagickBooleanType large_arc,const MagickBooleanType sweep)
{
double
alpha,
beta,
delta,
factor,
gamma,
theta;
PointInfo
center,
points[3],
radii;
register double
cosine,
sine;
register PrimitiveInfo
*p;
register ssize_t
i;
size_t
arc_segments;
if ((start.x == end.x) && (start.y == end.y))
{
TracePoint(primitive_info,end);
return;
}
radii.x=fabs(arc.x);
radii.y=fabs(arc.y);
if ((radii.x == 0.0) || (radii.y == 0.0))
{
TraceLine(primitive_info,start,end);
return;
}
cosine=cos(DegreesToRadians(fmod((double) angle,360.0)));
sine=sin(DegreesToRadians(fmod((double) angle,360.0)));
center.x=(double) (cosine*(end.x-start.x)/2+sine*(end.y-start.y)/2);
center.y=(double) (cosine*(end.y-start.y)/2-sine*(end.x-start.x)/2);
delta=(center.x*center.x)/(radii.x*radii.x)+(center.y*center.y)/
(radii.y*radii.y);
if (delta < MagickEpsilon)
{
TraceLine(primitive_info,start,end);
return;
}
if (delta > 1.0)
{
radii.x*=sqrt((double) delta);
radii.y*=sqrt((double) delta);
}
points[0].x=(double) (cosine*start.x/radii.x+sine*start.y/radii.x);
points[0].y=(double) (cosine*start.y/radii.y-sine*start.x/radii.y);
points[1].x=(double) (cosine*end.x/radii.x+sine*end.y/radii.x);
points[1].y=(double) (cosine*end.y/radii.y-sine*end.x/radii.y);
alpha=points[1].x-points[0].x;
beta=points[1].y-points[0].y;
factor=PerceptibleReciprocal(alpha*alpha+beta*beta)-0.25;
if (factor <= 0.0)
factor=0.0;
else
{
factor=sqrt((double) factor);
if (sweep == large_arc)
factor=(-factor);
}
center.x=(double) ((points[0].x+points[1].x)/2-factor*beta);
center.y=(double) ((points[0].y+points[1].y)/2+factor*alpha);
alpha=atan2(points[0].y-center.y,points[0].x-center.x);
theta=atan2(points[1].y-center.y,points[1].x-center.x)-alpha;
if ((theta < 0.0) && (sweep != MagickFalse))
theta+=(double) (2.0*MagickPI);
else
if ((theta > 0.0) && (sweep == MagickFalse))
theta-=(double) (2.0*MagickPI);
arc_segments=(size_t) ceil(fabs((double) (theta/(0.5*MagickPI+
MagickEpsilon))));
p=primitive_info;
for (i=0; i < (ssize_t) arc_segments; i++)
{
beta=0.5*((alpha+(i+1)*theta/arc_segments)-(alpha+i*theta/arc_segments));
gamma=(8.0/3.0)*sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))*
sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))/
sin(fmod((double) beta,DegreesToRadians(360.0)));
points[0].x=(double) (center.x+cos(fmod((double) (alpha+(double) i*theta/
arc_segments),DegreesToRadians(360.0)))-gamma*sin(fmod((double) (alpha+
(double) i*theta/arc_segments),DegreesToRadians(360.0))));
points[0].y=(double) (center.y+sin(fmod((double) (alpha+(double) i*theta/
arc_segments),DegreesToRadians(360.0)))+gamma*cos(fmod((double) (alpha+
(double) i*theta/arc_segments),DegreesToRadians(360.0))));
points[2].x=(double) (center.x+cos(fmod((double) (alpha+(double) (i+1)*
theta/arc_segments),DegreesToRadians(360.0))));
points[2].y=(double) (center.y+sin(fmod((double) (alpha+(double) (i+1)*
theta/arc_segments),DegreesToRadians(360.0))));
points[1].x=(double) (points[2].x+gamma*sin(fmod((double) (alpha+(double)
(i+1)*theta/arc_segments),DegreesToRadians(360.0))));
points[1].y=(double) (points[2].y-gamma*cos(fmod((double) (alpha+(double)
(i+1)*theta/arc_segments),DegreesToRadians(360.0))));
p->point.x=(p == primitive_info) ? start.x : (p-1)->point.x;
p->point.y=(p == primitive_info) ? start.y : (p-1)->point.y;
(p+1)->point.x=(double) (cosine*radii.x*points[0].x-sine*radii.y*
points[0].y);
(p+1)->point.y=(double) (sine*radii.x*points[0].x+cosine*radii.y*
points[0].y);
(p+2)->point.x=(double) (cosine*radii.x*points[1].x-sine*radii.y*
points[1].y);
(p+2)->point.y=(double) (sine*radii.x*points[1].x+cosine*radii.y*
points[1].y);
(p+3)->point.x=(double) (cosine*radii.x*points[2].x-sine*radii.y*
points[2].y);
(p+3)->point.y=(double) (sine*radii.x*points[2].x+cosine*radii.y*
points[2].y);
if (i == (ssize_t) (arc_segments-1))
(p+3)->point=end;
TraceBezier(p,4);
p+=p->coordinates;
}
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceBezier(PrimitiveInfo *primitive_info,
const size_t number_coordinates)
{
double
alpha,
*coefficients,
weight;
PointInfo
end,
point,
*points;
register PrimitiveInfo
*p;
register ssize_t
i,
j;
size_t
control_points,
quantum;
/*
Allocate coeficients.
*/
quantum=number_coordinates;
for (i=0; i < (ssize_t) number_coordinates; i++)
{
for (j=i+1; j < (ssize_t) number_coordinates; j++)
{
alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x);
if (alpha > (double) quantum)
quantum=(size_t) alpha;
alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y);
if (alpha > (double) quantum)
quantum=(size_t) alpha;
}
}
quantum=(size_t) MagickMin((double) quantum/number_coordinates,
(double) BezierQuantum);
control_points=quantum*number_coordinates;
coefficients=(double *) AcquireQuantumMemory((size_t)
number_coordinates,sizeof(*coefficients));
points=(PointInfo *) AcquireQuantumMemory((size_t) control_points,
sizeof(*points));
if ((coefficients == (double *) NULL) ||
(points == (PointInfo *) NULL))
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
/*
Compute bezier points.
*/
end=primitive_info[number_coordinates-1].point;
for (i=0; i < (ssize_t) number_coordinates; i++)
coefficients[i]=Permutate((ssize_t) number_coordinates-1,i);
weight=0.0;
for (i=0; i < (ssize_t) control_points; i++)
{
p=primitive_info;
point.x=0.0;
point.y=0.0;
alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0);
for (j=0; j < (ssize_t) number_coordinates; j++)
{
point.x+=alpha*coefficients[j]*p->point.x;
point.y+=alpha*coefficients[j]*p->point.y;
alpha*=weight/(1.0-weight);
p++;
}
points[i]=point;
weight+=1.0/control_points;
}
/*
Bezier curves are just short segmented polys.
*/
p=primitive_info;
for (i=0; i < (ssize_t) control_points; i++)
{
TracePoint(p,points[i]);
p+=p->coordinates;
}
TracePoint(p,end);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
points=(PointInfo *) RelinquishMagickMemory(points);
coefficients=(double *) RelinquishMagickMemory(coefficients);
}
static void TraceCircle(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end)
{
double
alpha,
beta,
radius;
PointInfo
offset,
degrees;
alpha=end.x-start.x;
beta=end.y-start.y;
radius=hypot((double) alpha,(double) beta);
offset.x=(double) radius;
offset.y=(double) radius;
degrees.x=0.0;
degrees.y=360.0;
TraceEllipse(primitive_info,start,offset,degrees);
}
static void TraceEllipse(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo stop,const PointInfo degrees)
{
double
delta,
step,
y;
PointInfo
angle,
point;
register PrimitiveInfo
*p;
register ssize_t
i;
/*
Ellipses are just short segmented polys.
*/
if ((stop.x == 0.0) && (stop.y == 0.0))
{
TracePoint(primitive_info,start);
return;
}
delta=2.0/MagickMax(stop.x,stop.y);
step=(double) (MagickPI/8.0);
if ((delta >= 0.0) && (delta < (double) (MagickPI/8.0)))
step=(double) (MagickPI/(4*(MagickPI/delta/2+0.5)));
angle.x=DegreesToRadians(degrees.x);
y=degrees.y;
while (y < degrees.x)
y+=360.0;
angle.y=(double) DegreesToRadians(y);
for (p=primitive_info; angle.x < angle.y; angle.x+=step)
{
point.x=cos(fmod(angle.x,DegreesToRadians(360.0)))*stop.x+start.x;
point.y=sin(fmod(angle.x,DegreesToRadians(360.0)))*stop.y+start.y;
TracePoint(p,point);
p+=p->coordinates;
}
point.x=cos(fmod(angle.y,DegreesToRadians(360.0)))*stop.x+start.x;
point.y=sin(fmod(angle.y,DegreesToRadians(360.0)))*stop.y+start.y;
TracePoint(p,point);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceLine(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end)
{
TracePoint(primitive_info,start);
if ((fabs(start.x-end.x) < MagickEpsilon) &&
(fabs(start.y-end.y) < MagickEpsilon))
{
primitive_info->primitive=PointPrimitive;
primitive_info->coordinates=1;
return;
}
TracePoint(primitive_info+1,end);
(primitive_info+1)->primitive=primitive_info->primitive;
primitive_info->coordinates=2;
}
static size_t TracePath(PrimitiveInfo *primitive_info,const char *path)
{
char
token[MagickPathExtent];
const char
*p;
int
attribute,
last_attribute;
double
x,
y;
PointInfo
end = {0.0, 0.0},
points[4] = { {0.0,0.0}, {0.0,0.0}, {0.0,0.0}, {0.0,0.0} },
point = {0.0, 0.0},
start = {0.0, 0.0};
PrimitiveType
primitive_type;
register PrimitiveInfo
*q;
register ssize_t
i;
size_t
number_coordinates,
z_count;
attribute=0;
number_coordinates=0;
z_count=0;
primitive_type=primitive_info->primitive;
q=primitive_info;
for (p=path; *p != '\0'; )
{
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == '\0')
break;
last_attribute=attribute;
attribute=(int) (*p++);
switch (attribute)
{
case 'a':
case 'A':
{
MagickBooleanType
large_arc,
sweep;
double
angle;
PointInfo
arc;
/*
Compute arc points.
*/
do
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
arc.x=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
arc.y=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
angle=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse;
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse;
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,(char **) NULL);
end.x=(double) (attribute == (int) 'A' ? x : point.x+x);
end.y=(double) (attribute == (int) 'A' ? y : point.y+y);
TraceArcPath(q,point,end,arc,angle,large_arc,sweep);
q+=q->coordinates;
point=end;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'c':
case 'C':
{
/*
Compute bezier points.
*/
do
{
points[0]=point;
for (i=1; i < 4; i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,(char **) NULL);
end.x=(double) (attribute == (int) 'C' ? x : point.x+x);
end.y=(double) (attribute == (int) 'C' ? y : point.y+y);
points[i]=end;
}
for (i=0; i < 4; i++)
(q+i)->point=points[i];
TraceBezier(q,4);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'H':
case 'h':
{
do
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,(char **) NULL);
point.x=(double) (attribute == (int) 'H' ? x: point.x+x);
TracePoint(q,point);
q+=q->coordinates;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'l':
case 'L':
{
do
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,(char **) NULL);
point.x=(double) (attribute == (int) 'L' ? x : point.x+x);
point.y=(double) (attribute == (int) 'L' ? y : point.y+y);
TracePoint(q,point);
q+=q->coordinates;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'M':
case 'm':
{
if (q != primitive_info)
{
primitive_info->coordinates=(size_t) (q-primitive_info);
number_coordinates+=primitive_info->coordinates;
primitive_info=q;
}
i=0;
do
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,(char **) NULL);
point.x=(double) (attribute == (int) 'M' ? x : point.x+x);
point.y=(double) (attribute == (int) 'M' ? y : point.y+y);
if (i == 0)
start=point;
i++;
TracePoint(q,point);
q+=q->coordinates;
if ((i != 0) && (attribute == (int) 'M'))
{
TracePoint(q,point);
q+=q->coordinates;
}
} while (IsPoint(p) != MagickFalse);
break;
}
case 'q':
case 'Q':
{
/*
Compute bezier points.
*/
do
{
points[0]=point;
for (i=1; i < 3; i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,(char **) NULL);
if (*p == ',')
p++;
end.x=(double) (attribute == (int) 'Q' ? x : point.x+x);
end.y=(double) (attribute == (int) 'Q' ? y : point.y+y);
points[i]=end;
}
for (i=0; i < 3; i++)
(q+i)->point=points[i];
TraceBezier(q,3);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 's':
case 'S':
{
/*
Compute bezier points.
*/
do
{
points[0]=points[3];
points[1].x=2.0*points[3].x-points[2].x;
points[1].y=2.0*points[3].y-points[2].y;
for (i=2; i < 4; i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,(char **) NULL);
if (*p == ',')
p++;
end.x=(double) (attribute == (int) 'S' ? x : point.x+x);
end.y=(double) (attribute == (int) 'S' ? y : point.y+y);
points[i]=end;
}
if (strchr("CcSs",last_attribute) == (char *) NULL)
{
points[0]=point;
points[1]=point;
}
for (i=0; i < 4; i++)
(q+i)->point=points[i];
TraceBezier(q,4);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 't':
case 'T':
{
/*
Compute bezier points.
*/
do
{
points[0]=points[2];
points[1].x=2.0*points[2].x-points[1].x;
points[1].y=2.0*points[2].y-points[1].y;
for (i=2; i < 3; i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,(char **) NULL);
end.x=(double) (attribute == (int) 'T' ? x : point.x+x);
end.y=(double) (attribute == (int) 'T' ? y : point.y+y);
points[i]=end;
}
if (strchr("QqTt",last_attribute) == (char *) NULL)
{
points[0]=point;
points[1]=point;
}
for (i=0; i < 3; i++)
(q+i)->point=points[i];
TraceBezier(q,3);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'v':
case 'V':
{
do
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,(char **) NULL);
point.y=(double) (attribute == (int) 'V' ? y : point.y+y);
TracePoint(q,point);
q+=q->coordinates;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'z':
case 'Z':
{
point=start;
TracePoint(q,point);
q+=q->coordinates;
primitive_info->coordinates=(size_t) (q-primitive_info);
number_coordinates+=primitive_info->coordinates;
primitive_info=q;
z_count++;
break;
}
default:
{
if (isalpha((int) ((unsigned char) attribute)) != 0)
(void) FormatLocaleFile(stderr,"attribute not recognized: %c\n",
attribute);
break;
}
}
}
primitive_info->coordinates=(size_t) (q-primitive_info);
number_coordinates+=primitive_info->coordinates;
for (i=0; i < (ssize_t) number_coordinates; i++)
{
q--;
q->primitive=primitive_type;
if (z_count > 1)
q->method=FillToBorderMethod;
}
q=primitive_info;
return(number_coordinates);
}
static void TraceRectangle(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end)
{
PointInfo
point;
register PrimitiveInfo
*p;
register ssize_t
i;
p=primitive_info;
TracePoint(p,start);
p+=p->coordinates;
point.x=start.x;
point.y=end.y;
TracePoint(p,point);
p+=p->coordinates;
TracePoint(p,end);
p+=p->coordinates;
point.x=end.x;
point.y=start.y;
TracePoint(p,point);
p+=p->coordinates;
TracePoint(p,start);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceRoundRectangle(PrimitiveInfo *primitive_info,
const PointInfo start,const PointInfo end,PointInfo arc)
{
PointInfo
degrees,
offset,
point;
register PrimitiveInfo
*p;
register ssize_t
i;
p=primitive_info;
offset.x=fabs(end.x-start.x);
offset.y=fabs(end.y-start.y);
if (arc.x > (0.5*offset.x))
arc.x=0.5*offset.x;
if (arc.y > (0.5*offset.y))
arc.y=0.5*offset.y;
point.x=start.x+offset.x-arc.x;
point.y=start.y+arc.y;
degrees.x=270.0;
degrees.y=360.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
point.x=start.x+offset.x-arc.x;
point.y=start.y+offset.y-arc.y;
degrees.x=0.0;
degrees.y=90.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
point.x=start.x+arc.x;
point.y=start.y+offset.y-arc.y;
degrees.x=90.0;
degrees.y=180.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
point.x=start.x+arc.x;
point.y=start.y+arc.y;
degrees.x=180.0;
degrees.y=270.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
TracePoint(p,primitive_info->point);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceSquareLinecap(PrimitiveInfo *primitive_info,
const size_t number_vertices,const double offset)
{
double
distance;
register double
dx,
dy;
register ssize_t
i;
ssize_t
j;
dx=0.0;
dy=0.0;
for (i=1; i < (ssize_t) number_vertices; i++)
{
dx=primitive_info[0].point.x-primitive_info[i].point.x;
dy=primitive_info[0].point.y-primitive_info[i].point.y;
if ((fabs((double) dx) >= MagickEpsilon) ||
(fabs((double) dy) >= MagickEpsilon))
break;
}
if (i == (ssize_t) number_vertices)
i=(ssize_t) number_vertices-1L;
distance=hypot((double) dx,(double) dy);
primitive_info[0].point.x=(double) (primitive_info[i].point.x+
dx*(distance+offset)/distance);
primitive_info[0].point.y=(double) (primitive_info[i].point.y+
dy*(distance+offset)/distance);
for (j=(ssize_t) number_vertices-2; j >= 0; j--)
{
dx=primitive_info[number_vertices-1].point.x-primitive_info[j].point.x;
dy=primitive_info[number_vertices-1].point.y-primitive_info[j].point.y;
if ((fabs((double) dx) >= MagickEpsilon) ||
(fabs((double) dy) >= MagickEpsilon))
break;
}
distance=hypot((double) dx,(double) dy);
primitive_info[number_vertices-1].point.x=(double) (primitive_info[j].point.x+
dx*(distance+offset)/distance);
primitive_info[number_vertices-1].point.y=(double) (primitive_info[j].point.y+
dy*(distance+offset)/distance);
}
static inline double DrawEpsilonReciprocal(const double x)
{
#define DrawEpsilon (1.0e-6)
double sign = x < 0.0 ? -1.0 : 1.0;
return((sign*x) >= DrawEpsilon ? 1.0/x : sign*(1.0/DrawEpsilon));
}
static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info)
{
typedef struct _LineSegment
{
double
p,
q;
} LineSegment;
LineSegment
dx,
dy,
inverse_slope,
slope,
theta;
MagickBooleanType
closed_path;
double
delta_theta,
dot_product,
mid,
miterlimit;
PointInfo
box_p[5],
box_q[5],
center,
offset,
*path_p,
*path_q;
PrimitiveInfo
*polygon_primitive,
*stroke_polygon;
register ssize_t
i;
size_t
arc_segments,
max_strokes,
number_vertices;
ssize_t
j,
n,
p,
q;
/*
Allocate paths.
*/
number_vertices=primitive_info->coordinates;
max_strokes=2*number_vertices+6*BezierQuantum+360;
path_p=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,
sizeof(*path_p));
path_q=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,
sizeof(*path_q));
polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
number_vertices+2UL,sizeof(*polygon_primitive));
if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL) ||
(polygon_primitive == (PrimitiveInfo *) NULL))
return((PrimitiveInfo *) NULL);
(void) CopyMagickMemory(polygon_primitive,primitive_info,(size_t)
number_vertices*sizeof(*polygon_primitive));
closed_path=
(primitive_info[number_vertices-1].point.x == primitive_info[0].point.x) &&
(primitive_info[number_vertices-1].point.y == primitive_info[0].point.y) ?
MagickTrue : MagickFalse;
if ((draw_info->linejoin == RoundJoin) ||
((draw_info->linejoin == MiterJoin) && (closed_path != MagickFalse)))
{
polygon_primitive[number_vertices]=primitive_info[1];
number_vertices++;
}
polygon_primitive[number_vertices].primitive=UndefinedPrimitive;
/*
Compute the slope for the first line segment, p.
*/
dx.p=0.0;
dy.p=0.0;
for (n=1; n < (ssize_t) number_vertices; n++)
{
dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x;
dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y;
if ((fabs(dx.p) >= MagickEpsilon) || (fabs(dy.p) >= MagickEpsilon))
break;
}
if (n == (ssize_t) number_vertices)
n=(ssize_t) number_vertices-1L;
slope.p=DrawEpsilonReciprocal(dx.p)*dy.p;
inverse_slope.p=(-1.0*DrawEpsilonReciprocal(slope.p));
mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit*
mid*mid);
if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse))
TraceSquareLinecap(polygon_primitive,number_vertices,mid);
offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0)));
offset.y=(double) (offset.x*inverse_slope.p);
if ((dy.p*offset.x-dx.p*offset.y) > 0.0)
{
box_p[0].x=polygon_primitive[0].point.x-offset.x;
box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p;
box_p[1].x=polygon_primitive[n].point.x-offset.x;
box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p;
box_q[0].x=polygon_primitive[0].point.x+offset.x;
box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p;
box_q[1].x=polygon_primitive[n].point.x+offset.x;
box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p;
}
else
{
box_p[0].x=polygon_primitive[0].point.x+offset.x;
box_p[0].y=polygon_primitive[0].point.y+offset.y;
box_p[1].x=polygon_primitive[n].point.x+offset.x;
box_p[1].y=polygon_primitive[n].point.y+offset.y;
box_q[0].x=polygon_primitive[0].point.x-offset.x;
box_q[0].y=polygon_primitive[0].point.y-offset.y;
box_q[1].x=polygon_primitive[n].point.x-offset.x;
box_q[1].y=polygon_primitive[n].point.y-offset.y;
}
/*
Create strokes for the line join attribute: bevel, miter, round.
*/
p=0;
q=0;
path_q[p++]=box_q[0];
path_p[q++]=box_p[0];
for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++)
{
/*
Compute the slope for this line segment, q.
*/
dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x;
dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y;
dot_product=dx.q*dx.q+dy.q*dy.q;
if (dot_product < 0.25)
continue;
slope.q=DrawEpsilonReciprocal(dx.q)*dy.q;
inverse_slope.q=(-1.0*DrawEpsilonReciprocal(slope.q));
offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0)));
offset.y=(double) (offset.x*inverse_slope.q);
dot_product=dy.q*offset.x-dx.q*offset.y;
if (dot_product > 0.0)
{
box_p[2].x=polygon_primitive[n].point.x-offset.x;
box_p[2].y=polygon_primitive[n].point.y-offset.y;
box_p[3].x=polygon_primitive[i].point.x-offset.x;
box_p[3].y=polygon_primitive[i].point.y-offset.y;
box_q[2].x=polygon_primitive[n].point.x+offset.x;
box_q[2].y=polygon_primitive[n].point.y+offset.y;
box_q[3].x=polygon_primitive[i].point.x+offset.x;
box_q[3].y=polygon_primitive[i].point.y+offset.y;
}
else
{
box_p[2].x=polygon_primitive[n].point.x+offset.x;
box_p[2].y=polygon_primitive[n].point.y+offset.y;
box_p[3].x=polygon_primitive[i].point.x+offset.x;
box_p[3].y=polygon_primitive[i].point.y+offset.y;
box_q[2].x=polygon_primitive[n].point.x-offset.x;
box_q[2].y=polygon_primitive[n].point.y-offset.y;
box_q[3].x=polygon_primitive[i].point.x-offset.x;
box_q[3].y=polygon_primitive[i].point.y-offset.y;
}
if (fabs((double) (slope.p-slope.q)) < MagickEpsilon)
{
box_p[4]=box_p[1];
box_q[4]=box_q[1];
}
else
{
box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+
box_p[3].y)/(slope.p-slope.q));
box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y);
box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+
box_q[3].y)/(slope.p-slope.q));
box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y);
}
if (q >= (ssize_t) (max_strokes-6*BezierQuantum-360))
{
max_strokes+=6*BezierQuantum+360;
path_p=(PointInfo *) ResizeQuantumMemory(path_p,(size_t) max_strokes,
sizeof(*path_p));
path_q=(PointInfo *) ResizeQuantumMemory(path_q,(size_t) max_strokes,
sizeof(*path_q));
if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL))
{
polygon_primitive=(PrimitiveInfo *)
RelinquishMagickMemory(polygon_primitive);
return((PrimitiveInfo *) NULL);
}
}
dot_product=dx.q*dy.p-dx.p*dy.q;
if (dot_product <= 0.0)
switch (draw_info->linejoin)
{
case BevelJoin:
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_p[p++]=box_p[4];
else
{
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
break;
}
case MiterJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
{
path_q[q++]=box_q[4];
path_p[p++]=box_p[4];
}
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
break;
}
case RoundJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_p[p++]=box_p[4];
else
{
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
center=polygon_primitive[n].point;
theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x);
theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x);
if (theta.q < theta.p)
theta.q+=(double) (2.0*MagickPI);
arc_segments=(size_t) ceil((double) ((theta.q-theta.p)/
(2.0*sqrt((double) (1.0/mid)))));
path_q[q].x=box_q[1].x;
path_q[q].y=box_q[1].y;
q++;
for (j=1; j < (ssize_t) arc_segments; j++)
{
delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);
path_q[q].x=(double) (center.x+mid*cos(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
path_q[q].y=(double) (center.y+mid*sin(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
q++;
}
path_q[q++]=box_q[2];
break;
}
default:
break;
}
else
switch (draw_info->linejoin)
{
case BevelJoin:
{
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_q[q++]=box_q[4];
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
}
break;
}
case MiterJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
{
path_q[q++]=box_q[4];
path_p[p++]=box_p[4];
}
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
break;
}
case RoundJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_q[q++]=box_q[4];
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
}
center=polygon_primitive[n].point;
theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x);
theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x);
if (theta.p < theta.q)
theta.p+=(double) (2.0*MagickPI);
arc_segments=(size_t) ceil((double) ((theta.p-theta.q)/
(2.0*sqrt((double) (1.0/mid)))));
path_p[p++]=box_p[1];
for (j=1; j < (ssize_t) arc_segments; j++)
{
delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);
path_p[p].x=(double) (center.x+mid*cos(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
path_p[p].y=(double) (center.y+mid*sin(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
p++;
}
path_p[p++]=box_p[2];
break;
}
default:
break;
}
slope.p=slope.q;
inverse_slope.p=inverse_slope.q;
box_p[0]=box_p[2];
box_p[1]=box_p[3];
box_q[0]=box_q[2];
box_q[1]=box_q[3];
dx.p=dx.q;
dy.p=dy.q;
n=i;
}
path_p[p++]=box_p[1];
path_q[q++]=box_q[1];
/*
Trace stroked polygon.
*/
stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
(p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon));
if (stroke_polygon != (PrimitiveInfo *) NULL)
{
for (i=0; i < (ssize_t) p; i++)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=path_p[i];
}
if (closed_path != MagickFalse)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=stroke_polygon[0].point;
i++;
}
for ( ; i < (ssize_t) (p+q+closed_path); i++)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=path_q[p+q+closed_path-(i+1)];
}
if (closed_path != MagickFalse)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=stroke_polygon[p+closed_path].point;
i++;
}
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=stroke_polygon[0].point;
i++;
stroke_polygon[i].primitive=UndefinedPrimitive;
stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1);
}
path_p=(PointInfo *) RelinquishMagickMemory(path_p);
path_q=(PointInfo *) RelinquishMagickMemory(path_q);
polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive);
return(stroke_polygon);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5053_1 |
crossvul-cpp_data_good_1030_1 | /*
** FAAD2 - Freeware Advanced Audio (AAC) Decoder including SBR decoding
** Copyright (C) 2003-2005 M. Bakker, Nero AG, http://www.nero.com
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
**
** Any non-GPL usage of this software or parts of this software is strictly
** forbidden.
**
** The "appropriate copyright message" mentioned in section 2c of the GPLv2
** must read: "Code from FAAD2 is copyright (c) Nero AG, www.nero.com"
**
** Commercial non-GPL licensing of this software is possible.
** For more info contact Nero AG through Mpeg4AAClicense@nero.com.
**
** $Id: syntax.c,v 1.93 2009/01/26 23:51:15 menno Exp $
**/
/*
Reads the AAC bitstream as defined in 14496-3 (MPEG-4 Audio)
*/
#include "common.h"
#include "structs.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "syntax.h"
#include "specrec.h"
#include "huffman.h"
#include "bits.h"
#include "pulse.h"
#include "analysis.h"
#include "drc.h"
#ifdef ERROR_RESILIENCE
#include "rvlc.h"
#endif
#ifdef SBR_DEC
#include "sbr_syntax.h"
#endif
#include "mp4.h"
/* static function declarations */
static void decode_sce_lfe(NeAACDecStruct *hDecoder, NeAACDecFrameInfo *hInfo, bitfile *ld,
uint8_t id_syn_ele);
static void decode_cpe(NeAACDecStruct *hDecoder, NeAACDecFrameInfo *hInfo, bitfile *ld,
uint8_t id_syn_ele);
static uint8_t single_lfe_channel_element(NeAACDecStruct *hDecoder, bitfile *ld,
uint8_t channel, uint8_t *tag);
static uint8_t channel_pair_element(NeAACDecStruct *hDecoder, bitfile *ld,
uint8_t channel, uint8_t *tag);
#ifdef COUPLING_DEC
static uint8_t coupling_channel_element(NeAACDecStruct *hDecoder, bitfile *ld);
#endif
static uint16_t data_stream_element(NeAACDecStruct *hDecoder, bitfile *ld);
static uint8_t program_config_element(program_config *pce, bitfile *ld);
static uint8_t fill_element(NeAACDecStruct *hDecoder, bitfile *ld, drc_info *drc
#ifdef SBR_DEC
,uint8_t sbr_ele
#endif
);
static uint8_t individual_channel_stream(NeAACDecStruct *hDecoder, element *ele,
bitfile *ld, ic_stream *ics, uint8_t scal_flag,
int16_t *spec_data);
static uint8_t ics_info(NeAACDecStruct *hDecoder, ic_stream *ics, bitfile *ld,
uint8_t common_window);
static uint8_t section_data(NeAACDecStruct *hDecoder, ic_stream *ics, bitfile *ld);
static uint8_t scale_factor_data(NeAACDecStruct *hDecoder, ic_stream *ics, bitfile *ld);
#ifdef SSR_DEC
static void gain_control_data(bitfile *ld, ic_stream *ics);
#endif
static uint8_t spectral_data(NeAACDecStruct *hDecoder, ic_stream *ics, bitfile *ld,
int16_t *spectral_data);
static uint16_t extension_payload(bitfile *ld, drc_info *drc, uint16_t count);
static uint8_t pulse_data(ic_stream *ics, pulse_info *pul, bitfile *ld);
static void tns_data(ic_stream *ics, tns_info *tns, bitfile *ld);
#ifdef LTP_DEC
static uint8_t ltp_data(NeAACDecStruct *hDecoder, ic_stream *ics, ltp_info *ltp, bitfile *ld);
#endif
static uint8_t adts_fixed_header(adts_header *adts, bitfile *ld);
static void adts_variable_header(adts_header *adts, bitfile *ld);
static void adts_error_check(adts_header *adts, bitfile *ld);
static uint8_t dynamic_range_info(bitfile *ld, drc_info *drc);
static uint8_t excluded_channels(bitfile *ld, drc_info *drc);
static uint8_t side_info(NeAACDecStruct *hDecoder, element *ele,
bitfile *ld, ic_stream *ics, uint8_t scal_flag);
#ifdef DRM
static int8_t DRM_aac_scalable_main_header(NeAACDecStruct *hDecoder, ic_stream *ics1, ic_stream *ics2,
bitfile *ld, uint8_t this_layer_stereo);
#endif
/* Table 4.4.1 */
int8_t GASpecificConfig(bitfile *ld, mp4AudioSpecificConfig *mp4ASC,
program_config *pce_out)
{
program_config pce;
/* 1024 or 960 */
mp4ASC->frameLengthFlag = faad_get1bit(ld
DEBUGVAR(1,138,"GASpecificConfig(): FrameLengthFlag"));
#ifndef ALLOW_SMALL_FRAMELENGTH
if (mp4ASC->frameLengthFlag == 1)
return -3;
#endif
mp4ASC->dependsOnCoreCoder = faad_get1bit(ld
DEBUGVAR(1,139,"GASpecificConfig(): DependsOnCoreCoder"));
if (mp4ASC->dependsOnCoreCoder == 1)
{
mp4ASC->coreCoderDelay = (uint16_t)faad_getbits(ld, 14
DEBUGVAR(1,140,"GASpecificConfig(): CoreCoderDelay"));
}
mp4ASC->extensionFlag = faad_get1bit(ld DEBUGVAR(1,141,"GASpecificConfig(): ExtensionFlag"));
if (mp4ASC->channelsConfiguration == 0)
{
if (program_config_element(&pce, ld))
return -3;
//mp4ASC->channelsConfiguration = pce.channels;
if (pce_out != NULL)
memcpy(pce_out, &pce, sizeof(program_config));
/*
if (pce.num_valid_cc_elements)
return -3;
*/
}
#ifdef ERROR_RESILIENCE
if (mp4ASC->extensionFlag == 1)
{
/* Error resilience not supported yet */
if (mp4ASC->objectTypeIndex >= ER_OBJECT_START)
{
mp4ASC->aacSectionDataResilienceFlag = faad_get1bit(ld
DEBUGVAR(1,144,"GASpecificConfig(): aacSectionDataResilienceFlag"));
mp4ASC->aacScalefactorDataResilienceFlag = faad_get1bit(ld
DEBUGVAR(1,145,"GASpecificConfig(): aacScalefactorDataResilienceFlag"));
mp4ASC->aacSpectralDataResilienceFlag = faad_get1bit(ld
DEBUGVAR(1,146,"GASpecificConfig(): aacSpectralDataResilienceFlag"));
}
/* 1 bit: extensionFlag3 */
faad_getbits(ld, 1);
}
#endif
return 0;
}
/* Table 4.4.2 */
/* An MPEG-4 Audio decoder is only required to follow the Program
Configuration Element in GASpecificConfig(). The decoder shall ignore
any Program Configuration Elements that may occur in raw data blocks.
PCEs transmitted in raw data blocks cannot be used to convey decoder
configuration information.
*/
static uint8_t program_config_element(program_config *pce, bitfile *ld)
{
uint8_t i;
memset(pce, 0, sizeof(program_config));
pce->channels = 0;
pce->element_instance_tag = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,10,"program_config_element(): element_instance_tag"));
pce->object_type = (uint8_t)faad_getbits(ld, 2
DEBUGVAR(1,11,"program_config_element(): object_type"));
pce->sf_index = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,12,"program_config_element(): sf_index"));
pce->num_front_channel_elements = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,13,"program_config_element(): num_front_channel_elements"));
pce->num_side_channel_elements = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,14,"program_config_element(): num_side_channel_elements"));
pce->num_back_channel_elements = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,15,"program_config_element(): num_back_channel_elements"));
pce->num_lfe_channel_elements = (uint8_t)faad_getbits(ld, 2
DEBUGVAR(1,16,"program_config_element(): num_lfe_channel_elements"));
pce->num_assoc_data_elements = (uint8_t)faad_getbits(ld, 3
DEBUGVAR(1,17,"program_config_element(): num_assoc_data_elements"));
pce->num_valid_cc_elements = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,18,"program_config_element(): num_valid_cc_elements"));
pce->mono_mixdown_present = faad_get1bit(ld
DEBUGVAR(1,19,"program_config_element(): mono_mixdown_present"));
if (pce->mono_mixdown_present == 1)
{
pce->mono_mixdown_element_number = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,20,"program_config_element(): mono_mixdown_element_number"));
}
pce->stereo_mixdown_present = faad_get1bit(ld
DEBUGVAR(1,21,"program_config_element(): stereo_mixdown_present"));
if (pce->stereo_mixdown_present == 1)
{
pce->stereo_mixdown_element_number = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,22,"program_config_element(): stereo_mixdown_element_number"));
}
pce->matrix_mixdown_idx_present = faad_get1bit(ld
DEBUGVAR(1,23,"program_config_element(): matrix_mixdown_idx_present"));
if (pce->matrix_mixdown_idx_present == 1)
{
pce->matrix_mixdown_idx = (uint8_t)faad_getbits(ld, 2
DEBUGVAR(1,24,"program_config_element(): matrix_mixdown_idx"));
pce->pseudo_surround_enable = faad_get1bit(ld
DEBUGVAR(1,25,"program_config_element(): pseudo_surround_enable"));
}
for (i = 0; i < pce->num_front_channel_elements; i++)
{
pce->front_element_is_cpe[i] = faad_get1bit(ld
DEBUGVAR(1,26,"program_config_element(): front_element_is_cpe"));
pce->front_element_tag_select[i] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,27,"program_config_element(): front_element_tag_select"));
if (pce->front_element_is_cpe[i] & 1)
{
pce->cpe_channel[pce->front_element_tag_select[i]] = pce->channels;
pce->num_front_channels += 2;
pce->channels += 2;
} else {
pce->sce_channel[pce->front_element_tag_select[i]] = pce->channels;
pce->num_front_channels++;
pce->channels++;
}
}
for (i = 0; i < pce->num_side_channel_elements; i++)
{
pce->side_element_is_cpe[i] = faad_get1bit(ld
DEBUGVAR(1,28,"program_config_element(): side_element_is_cpe"));
pce->side_element_tag_select[i] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,29,"program_config_element(): side_element_tag_select"));
if (pce->side_element_is_cpe[i] & 1)
{
pce->cpe_channel[pce->side_element_tag_select[i]] = pce->channels;
pce->num_side_channels += 2;
pce->channels += 2;
} else {
pce->sce_channel[pce->side_element_tag_select[i]] = pce->channels;
pce->num_side_channels++;
pce->channels++;
}
}
for (i = 0; i < pce->num_back_channel_elements; i++)
{
pce->back_element_is_cpe[i] = faad_get1bit(ld
DEBUGVAR(1,30,"program_config_element(): back_element_is_cpe"));
pce->back_element_tag_select[i] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,31,"program_config_element(): back_element_tag_select"));
if (pce->back_element_is_cpe[i] & 1)
{
pce->cpe_channel[pce->back_element_tag_select[i]] = pce->channels;
pce->channels += 2;
pce->num_back_channels += 2;
} else {
pce->sce_channel[pce->back_element_tag_select[i]] = pce->channels;
pce->num_back_channels++;
pce->channels++;
}
}
for (i = 0; i < pce->num_lfe_channel_elements; i++)
{
pce->lfe_element_tag_select[i] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,32,"program_config_element(): lfe_element_tag_select"));
pce->sce_channel[pce->lfe_element_tag_select[i]] = pce->channels;
pce->num_lfe_channels++;
pce->channels++;
}
for (i = 0; i < pce->num_assoc_data_elements; i++)
pce->assoc_data_element_tag_select[i] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,33,"program_config_element(): assoc_data_element_tag_select"));
for (i = 0; i < pce->num_valid_cc_elements; i++)
{
pce->cc_element_is_ind_sw[i] = faad_get1bit(ld
DEBUGVAR(1,34,"program_config_element(): cc_element_is_ind_sw"));
pce->valid_cc_element_tag_select[i] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,35,"program_config_element(): valid_cc_element_tag_select"));
}
faad_byte_align(ld);
pce->comment_field_bytes = (uint8_t)faad_getbits(ld, 8
DEBUGVAR(1,36,"program_config_element(): comment_field_bytes"));
for (i = 0; i < pce->comment_field_bytes; i++)
{
pce->comment_field_data[i] = (uint8_t)faad_getbits(ld, 8
DEBUGVAR(1,37,"program_config_element(): comment_field_data"));
}
pce->comment_field_data[i] = 0;
if (pce->channels > MAX_CHANNELS)
return 22;
return 0;
}
static void decode_sce_lfe(NeAACDecStruct *hDecoder,
NeAACDecFrameInfo *hInfo, bitfile *ld,
uint8_t id_syn_ele)
{
uint8_t channels = hDecoder->fr_channels;
uint8_t tag = 0;
if (channels+1 > MAX_CHANNELS)
{
hInfo->error = 12;
return;
}
if (hDecoder->fr_ch_ele+1 > MAX_SYNTAX_ELEMENTS)
{
hInfo->error = 13;
return;
}
/* for SCE hDecoder->element_output_channels[] is not set here because this
can become 2 when some form of Parametric Stereo coding is used
*/
if (hDecoder->frame && hDecoder->element_id[hDecoder->fr_ch_ele] != id_syn_ele) {
/* element inconsistency */
hInfo->error = 21;
return;
}
/* save the syntax element id */
hDecoder->element_id[hDecoder->fr_ch_ele] = id_syn_ele;
/* decode the element */
hInfo->error = single_lfe_channel_element(hDecoder, ld, channels, &tag);
/* map output channels position to internal data channels */
if (hDecoder->element_output_channels[hDecoder->fr_ch_ele] == 2)
{
/* this might be faulty when pce_set is true */
hDecoder->internal_channel[channels] = channels;
hDecoder->internal_channel[channels+1] = channels+1;
} else {
if (hDecoder->pce_set)
hDecoder->internal_channel[hDecoder->pce.sce_channel[tag]] = channels;
else
hDecoder->internal_channel[channels] = channels;
}
hDecoder->fr_channels += hDecoder->element_output_channels[hDecoder->fr_ch_ele];
hDecoder->fr_ch_ele++;
}
static void decode_cpe(NeAACDecStruct *hDecoder, NeAACDecFrameInfo *hInfo, bitfile *ld,
uint8_t id_syn_ele)
{
uint8_t channels = hDecoder->fr_channels;
uint8_t tag = 0;
if (channels+2 > MAX_CHANNELS)
{
hInfo->error = 12;
return;
}
if (hDecoder->fr_ch_ele+1 > MAX_SYNTAX_ELEMENTS)
{
hInfo->error = 13;
return;
}
/* for CPE the number of output channels is always 2 */
if (hDecoder->element_output_channels[hDecoder->fr_ch_ele] == 0)
{
/* element_output_channels not set yet */
hDecoder->element_output_channels[hDecoder->fr_ch_ele] = 2;
} else if (hDecoder->element_output_channels[hDecoder->fr_ch_ele] != 2) {
/* element inconsistency */
hInfo->error = 21;
return;
}
if (hDecoder->frame && hDecoder->element_id[hDecoder->fr_ch_ele] != id_syn_ele) {
/* element inconsistency */
hInfo->error = 21;
return;
}
/* save the syntax element id */
hDecoder->element_id[hDecoder->fr_ch_ele] = id_syn_ele;
/* decode the element */
hInfo->error = channel_pair_element(hDecoder, ld, channels, &tag);
/* map output channel position to internal data channels */
if (hDecoder->pce_set)
{
hDecoder->internal_channel[hDecoder->pce.cpe_channel[tag]] = channels;
hDecoder->internal_channel[hDecoder->pce.cpe_channel[tag]+1] = channels+1;
} else {
hDecoder->internal_channel[channels] = channels;
hDecoder->internal_channel[channels+1] = channels+1;
}
hDecoder->fr_channels += 2;
hDecoder->fr_ch_ele++;
}
void raw_data_block(NeAACDecStruct *hDecoder, NeAACDecFrameInfo *hInfo,
bitfile *ld, program_config *pce, drc_info *drc)
{
uint8_t id_syn_ele;
uint8_t ele_this_frame = 0;
hDecoder->fr_channels = 0;
hDecoder->fr_ch_ele = 0;
hDecoder->first_syn_ele = 25;
hDecoder->has_lfe = 0;
#ifdef ERROR_RESILIENCE
if (hDecoder->object_type < ER_OBJECT_START)
{
#endif
/* Table 4.4.3: raw_data_block() */
while ((id_syn_ele = (uint8_t)faad_getbits(ld, LEN_SE_ID
DEBUGVAR(1,4,"NeAACDecDecode(): id_syn_ele"))) != ID_END)
{
switch (id_syn_ele) {
case ID_SCE:
ele_this_frame++;
if (hDecoder->first_syn_ele == 25) hDecoder->first_syn_ele = id_syn_ele;
decode_sce_lfe(hDecoder, hInfo, ld, id_syn_ele);
if (hInfo->error > 0)
return;
break;
case ID_CPE:
ele_this_frame++;
if (hDecoder->first_syn_ele == 25) hDecoder->first_syn_ele = id_syn_ele;
decode_cpe(hDecoder, hInfo, ld, id_syn_ele);
if (hInfo->error > 0)
return;
break;
case ID_LFE:
#ifdef DRM
hInfo->error = 32;
#else
ele_this_frame++;
hDecoder->has_lfe++;
decode_sce_lfe(hDecoder, hInfo, ld, id_syn_ele);
#endif
if (hInfo->error > 0)
return;
break;
case ID_CCE: /* not implemented yet, but skip the bits */
#ifdef DRM
hInfo->error = 32;
#else
ele_this_frame++;
#ifdef COUPLING_DEC
hInfo->error = coupling_channel_element(hDecoder, ld);
#else
hInfo->error = 6;
#endif
#endif
if (hInfo->error > 0)
return;
break;
case ID_DSE:
ele_this_frame++;
data_stream_element(hDecoder, ld);
break;
case ID_PCE:
if (ele_this_frame != 0)
{
hInfo->error = 31;
return;
}
ele_this_frame++;
/* 14496-4: 5.6.4.1.2.1.3: */
/* program_configuration_element()'s in access units shall be ignored */
program_config_element(pce, ld);
//if ((hInfo->error = program_config_element(pce, ld)) > 0)
// return;
//hDecoder->pce_set = 1;
break;
case ID_FIL:
ele_this_frame++;
/* one sbr_info describes a channel_element not a channel! */
/* if we encounter SBR data here: error */
/* SBR data will be read directly in the SCE/LFE/CPE element */
if ((hInfo->error = fill_element(hDecoder, ld, drc
#ifdef SBR_DEC
, INVALID_SBR_ELEMENT
#endif
)) > 0)
return;
break;
}
}
#ifdef ERROR_RESILIENCE
} else {
/* Table 262: er_raw_data_block() */
switch (hDecoder->channelConfiguration)
{
case 1:
decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
if (hInfo->error > 0)
return;
break;
case 2:
decode_cpe(hDecoder, hInfo, ld, ID_CPE);
if (hInfo->error > 0)
return;
break;
case 3:
decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
decode_cpe(hDecoder, hInfo, ld, ID_CPE);
if (hInfo->error > 0)
return;
break;
case 4:
decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
decode_cpe(hDecoder, hInfo, ld, ID_CPE);
decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
if (hInfo->error > 0)
return;
break;
case 5:
decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
decode_cpe(hDecoder, hInfo, ld, ID_CPE);
decode_cpe(hDecoder, hInfo, ld, ID_CPE);
if (hInfo->error > 0)
return;
break;
case 6:
decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
decode_cpe(hDecoder, hInfo, ld, ID_CPE);
decode_cpe(hDecoder, hInfo, ld, ID_CPE);
decode_sce_lfe(hDecoder, hInfo, ld, ID_LFE);
if (hInfo->error > 0)
return;
break;
case 7: /* 8 channels */
decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
decode_cpe(hDecoder, hInfo, ld, ID_CPE);
decode_cpe(hDecoder, hInfo, ld, ID_CPE);
decode_cpe(hDecoder, hInfo, ld, ID_CPE);
decode_sce_lfe(hDecoder, hInfo, ld, ID_LFE);
if (hInfo->error > 0)
return;
break;
default:
hInfo->error = 7;
return;
}
#if 0
cnt = bits_to_decode() / 8;
while (cnt >= 1)
{
cnt -= extension_payload(cnt);
}
#endif
}
#endif
/* new in corrigendum 14496-3:2002 */
#ifdef DRM
if (hDecoder->object_type != DRM_ER_LC
#if 0
&& !hDecoder->latm_header_present
#endif
)
#endif
{
faad_byte_align(ld);
}
return;
}
/* Table 4.4.4 and */
/* Table 4.4.9 */
static uint8_t single_lfe_channel_element(NeAACDecStruct *hDecoder, bitfile *ld,
uint8_t channel, uint8_t *tag)
{
uint8_t retval = 0;
element sce = {0};
ic_stream *ics = &(sce.ics1);
ALIGN int16_t spec_data[1024] = {0};
sce.element_instance_tag = (uint8_t)faad_getbits(ld, LEN_TAG
DEBUGVAR(1,38,"single_lfe_channel_element(): element_instance_tag"));
*tag = sce.element_instance_tag;
sce.channel = channel;
sce.paired_channel = -1;
retval = individual_channel_stream(hDecoder, &sce, ld, ics, 0, spec_data);
if (retval > 0)
return retval;
/* IS not allowed in single channel */
if (ics->is_used)
return 32;
#ifdef SBR_DEC
/* check if next bitstream element is a fill element */
/* if so, read it now so SBR decoding can be done in case of a file with SBR */
if (faad_showbits(ld, LEN_SE_ID) == ID_FIL)
{
faad_flushbits(ld, LEN_SE_ID);
/* one sbr_info describes a channel_element not a channel! */
if ((retval = fill_element(hDecoder, ld, hDecoder->drc, hDecoder->fr_ch_ele)) > 0)
{
return retval;
}
}
#endif
/* noiseless coding is done, spectral reconstruction is done now */
retval = reconstruct_single_channel(hDecoder, ics, &sce, spec_data);
if (retval > 0)
return retval;
return 0;
}
/* Table 4.4.5 */
static uint8_t channel_pair_element(NeAACDecStruct *hDecoder, bitfile *ld,
uint8_t channels, uint8_t *tag)
{
ALIGN int16_t spec_data1[1024] = {0};
ALIGN int16_t spec_data2[1024] = {0};
element cpe = {0};
ic_stream *ics1 = &(cpe.ics1);
ic_stream *ics2 = &(cpe.ics2);
uint8_t result;
cpe.channel = channels;
cpe.paired_channel = channels+1;
cpe.element_instance_tag = (uint8_t)faad_getbits(ld, LEN_TAG
DEBUGVAR(1,39,"channel_pair_element(): element_instance_tag"));
*tag = cpe.element_instance_tag;
if ((cpe.common_window = faad_get1bit(ld
DEBUGVAR(1,40,"channel_pair_element(): common_window"))) & 1)
{
/* both channels have common ics information */
if ((result = ics_info(hDecoder, ics1, ld, cpe.common_window)) > 0)
return result;
ics1->ms_mask_present = (uint8_t)faad_getbits(ld, 2
DEBUGVAR(1,41,"channel_pair_element(): ms_mask_present"));
if (ics1->ms_mask_present == 3)
{
/* bitstream error */
return 32;
}
if (ics1->ms_mask_present == 1)
{
uint8_t g, sfb;
for (g = 0; g < ics1->num_window_groups; g++)
{
for (sfb = 0; sfb < ics1->max_sfb; sfb++)
{
ics1->ms_used[g][sfb] = faad_get1bit(ld
DEBUGVAR(1,42,"channel_pair_element(): faad_get1bit"));
}
}
}
#ifdef ERROR_RESILIENCE
if ((hDecoder->object_type >= ER_OBJECT_START) && (ics1->predictor_data_present))
{
if ((
#ifdef LTP_DEC
ics1->ltp.data_present =
#endif
faad_get1bit(ld DEBUGVAR(1,50,"channel_pair_element(): ltp.data_present"))) & 1)
{
#ifdef LTP_DEC
if ((result = ltp_data(hDecoder, ics1, &(ics1->ltp), ld)) > 0)
{
return result;
}
#else
return 26;
#endif
}
}
#endif
memcpy(ics2, ics1, sizeof(ic_stream));
} else {
ics1->ms_mask_present = 0;
}
if ((result = individual_channel_stream(hDecoder, &cpe, ld, ics1,
0, spec_data1)) > 0)
{
return result;
}
#ifdef ERROR_RESILIENCE
if (cpe.common_window && (hDecoder->object_type >= ER_OBJECT_START) &&
(ics1->predictor_data_present))
{
if ((
#ifdef LTP_DEC
ics1->ltp2.data_present =
#endif
faad_get1bit(ld DEBUGVAR(1,50,"channel_pair_element(): ltp.data_present"))) & 1)
{
#ifdef LTP_DEC
if ((result = ltp_data(hDecoder, ics1, &(ics1->ltp2), ld)) > 0)
{
return result;
}
#else
return 26;
#endif
}
}
#endif
if ((result = individual_channel_stream(hDecoder, &cpe, ld, ics2,
0, spec_data2)) > 0)
{
return result;
}
#ifdef SBR_DEC
/* check if next bitstream element is a fill element */
/* if so, read it now so SBR decoding can be done in case of a file with SBR */
if (faad_showbits(ld, LEN_SE_ID) == ID_FIL)
{
faad_flushbits(ld, LEN_SE_ID);
/* one sbr_info describes a channel_element not a channel! */
if ((result = fill_element(hDecoder, ld, hDecoder->drc, hDecoder->fr_ch_ele)) > 0)
{
return result;
}
}
#endif
/* noiseless coding is done, spectral reconstruction is done now */
if ((result = reconstruct_channel_pair(hDecoder, ics1, ics2, &cpe,
spec_data1, spec_data2)) > 0)
{
return result;
}
return 0;
}
/* Table 4.4.6 */
static uint8_t ics_info(NeAACDecStruct *hDecoder, ic_stream *ics, bitfile *ld,
uint8_t common_window)
{
uint8_t retval = 0;
uint8_t ics_reserved_bit;
ics_reserved_bit = faad_get1bit(ld
DEBUGVAR(1,43,"ics_info(): ics_reserved_bit"));
if (ics_reserved_bit != 0)
return 32;
ics->window_sequence = (uint8_t)faad_getbits(ld, 2
DEBUGVAR(1,44,"ics_info(): window_sequence"));
ics->window_shape = faad_get1bit(ld
DEBUGVAR(1,45,"ics_info(): window_shape"));
#ifdef LD_DEC
/* No block switching in LD */
if ((hDecoder->object_type == LD) && (ics->window_sequence != ONLY_LONG_SEQUENCE))
return 32;
#endif
if (ics->window_sequence == EIGHT_SHORT_SEQUENCE)
{
ics->max_sfb = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,46,"ics_info(): max_sfb (short)"));
ics->scale_factor_grouping = (uint8_t)faad_getbits(ld, 7
DEBUGVAR(1,47,"ics_info(): scale_factor_grouping"));
} else {
ics->max_sfb = (uint8_t)faad_getbits(ld, 6
DEBUGVAR(1,48,"ics_info(): max_sfb (long)"));
}
/* get the grouping information */
if ((retval = window_grouping_info(hDecoder, ics)) > 0)
return retval;
/* should be an error */
/* check the range of max_sfb */
if (ics->max_sfb > ics->num_swb)
return 16;
if (ics->window_sequence != EIGHT_SHORT_SEQUENCE)
{
if ((ics->predictor_data_present = faad_get1bit(ld
DEBUGVAR(1,49,"ics_info(): predictor_data_present"))) & 1)
{
if (hDecoder->object_type == MAIN) /* MPEG2 style AAC predictor */
{
uint8_t sfb;
uint8_t limit = min(ics->max_sfb, max_pred_sfb(hDecoder->sf_index));
#ifdef MAIN_DEC
ics->pred.limit = limit;
#endif
if ((
#ifdef MAIN_DEC
ics->pred.predictor_reset =
#endif
faad_get1bit(ld DEBUGVAR(1,53,"ics_info(): pred.predictor_reset"))) & 1)
{
#ifdef MAIN_DEC
ics->pred.predictor_reset_group_number =
#endif
(uint8_t)faad_getbits(ld, 5 DEBUGVAR(1,54,"ics_info(): pred.predictor_reset_group_number"));
}
for (sfb = 0; sfb < limit; sfb++)
{
#ifdef MAIN_DEC
ics->pred.prediction_used[sfb] =
#endif
faad_get1bit(ld DEBUGVAR(1,55,"ics_info(): pred.prediction_used"));
}
}
#ifdef LTP_DEC
else { /* Long Term Prediction */
if (hDecoder->object_type < ER_OBJECT_START)
{
if ((ics->ltp.data_present = faad_get1bit(ld
DEBUGVAR(1,50,"ics_info(): ltp.data_present"))) & 1)
{
if ((retval = ltp_data(hDecoder, ics, &(ics->ltp), ld)) > 0)
{
return retval;
}
}
if (common_window)
{
if ((ics->ltp2.data_present = faad_get1bit(ld
DEBUGVAR(1,51,"ics_info(): ltp2.data_present"))) & 1)
{
if ((retval = ltp_data(hDecoder, ics, &(ics->ltp2), ld)) > 0)
{
return retval;
}
}
}
}
#ifdef ERROR_RESILIENCE
if (!common_window && (hDecoder->object_type >= ER_OBJECT_START))
{
if ((ics->ltp.data_present = faad_get1bit(ld
DEBUGVAR(1,50,"ics_info(): ltp.data_present"))) & 1)
{
ltp_data(hDecoder, ics, &(ics->ltp), ld);
}
}
#endif
}
#endif
}
}
return retval;
}
/* Table 4.4.7 */
static uint8_t pulse_data(ic_stream *ics, pulse_info *pul, bitfile *ld)
{
uint8_t i;
pul->number_pulse = (uint8_t)faad_getbits(ld, 2
DEBUGVAR(1,56,"pulse_data(): number_pulse"));
pul->pulse_start_sfb = (uint8_t)faad_getbits(ld, 6
DEBUGVAR(1,57,"pulse_data(): pulse_start_sfb"));
/* check the range of pulse_start_sfb */
if (pul->pulse_start_sfb > ics->num_swb)
return 16;
for (i = 0; i < pul->number_pulse+1; i++)
{
pul->pulse_offset[i] = (uint8_t)faad_getbits(ld, 5
DEBUGVAR(1,58,"pulse_data(): pulse_offset"));
#if 0
printf("%d\n", pul->pulse_offset[i]);
#endif
pul->pulse_amp[i] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,59,"pulse_data(): pulse_amp"));
#if 0
printf("%d\n", pul->pulse_amp[i]);
#endif
}
return 0;
}
#ifdef COUPLING_DEC
/* Table 4.4.8: Currently just for skipping the bits... */
static uint8_t coupling_channel_element(NeAACDecStruct *hDecoder, bitfile *ld)
{
uint8_t c, result = 0;
uint8_t ind_sw_cce_flag = 0;
uint8_t num_gain_element_lists = 0;
uint8_t num_coupled_elements = 0;
element el_empty = {0};
ic_stream ics_empty = {0};
int16_t sh_data[1024];
c = faad_getbits(ld, LEN_TAG
DEBUGVAR(1,900,"coupling_channel_element(): element_instance_tag"));
ind_sw_cce_flag = faad_get1bit(ld
DEBUGVAR(1,901,"coupling_channel_element(): ind_sw_cce_flag"));
num_coupled_elements = faad_getbits(ld, 3
DEBUGVAR(1,902,"coupling_channel_element(): num_coupled_elements"));
for (c = 0; c < num_coupled_elements + 1; c++)
{
uint8_t cc_target_is_cpe, cc_target_tag_select;
num_gain_element_lists++;
cc_target_is_cpe = faad_get1bit(ld
DEBUGVAR(1,903,"coupling_channel_element(): cc_target_is_cpe"));
cc_target_tag_select = faad_getbits(ld, 4
DEBUGVAR(1,904,"coupling_channel_element(): cc_target_tag_select"));
if (cc_target_is_cpe)
{
uint8_t cc_l = faad_get1bit(ld
DEBUGVAR(1,905,"coupling_channel_element(): cc_l"));
uint8_t cc_r = faad_get1bit(ld
DEBUGVAR(1,906,"coupling_channel_element(): cc_r"));
if (cc_l && cc_r)
num_gain_element_lists++;
}
}
faad_get1bit(ld
DEBUGVAR(1,907,"coupling_channel_element(): cc_domain"));
faad_get1bit(ld
DEBUGVAR(1,908,"coupling_channel_element(): gain_element_sign"));
faad_getbits(ld, 2
DEBUGVAR(1,909,"coupling_channel_element(): gain_element_scale"));
if ((result = individual_channel_stream(hDecoder, &el_empty, ld, &ics_empty,
0, sh_data)) > 0)
{
return result;
}
/* IS not allowed in single channel */
if (ics->is_used)
return 32;
for (c = 1; c < num_gain_element_lists; c++)
{
uint8_t cge;
if (ind_sw_cce_flag)
{
cge = 1;
} else {
cge = faad_get1bit(ld
DEBUGVAR(1,910,"coupling_channel_element(): common_gain_element_present"));
}
if (cge)
{
huffman_scale_factor(ld);
} else {
uint8_t g, sfb;
for (g = 0; g < ics_empty.num_window_groups; g++)
{
for (sfb = 0; sfb < ics_empty.max_sfb; sfb++)
{
if (ics_empty.sfb_cb[g][sfb] != ZERO_HCB)
huffman_scale_factor(ld);
}
}
}
}
return 0;
}
#endif
/* Table 4.4.10 */
static uint16_t data_stream_element(NeAACDecStruct *hDecoder, bitfile *ld)
{
uint8_t byte_aligned;
uint16_t i, count;
/* element_instance_tag = */ faad_getbits(ld, LEN_TAG
DEBUGVAR(1,60,"data_stream_element(): element_instance_tag"));
byte_aligned = faad_get1bit(ld
DEBUGVAR(1,61,"data_stream_element(): byte_aligned"));
count = (uint16_t)faad_getbits(ld, 8
DEBUGVAR(1,62,"data_stream_element(): count"));
if (count == 255)
{
count += (uint16_t)faad_getbits(ld, 8
DEBUGVAR(1,63,"data_stream_element(): extra count"));
}
if (byte_aligned)
faad_byte_align(ld);
for (i = 0; i < count; i++)
{
faad_getbits(ld, LEN_BYTE
DEBUGVAR(1,64,"data_stream_element(): data_stream_byte"));
}
return count;
}
/* Table 4.4.11 */
static uint8_t fill_element(NeAACDecStruct *hDecoder, bitfile *ld, drc_info *drc
#ifdef SBR_DEC
,uint8_t sbr_ele
#endif
)
{
uint16_t count;
#ifdef SBR_DEC
uint8_t bs_extension_type;
#endif
count = (uint16_t)faad_getbits(ld, 4
DEBUGVAR(1,65,"fill_element(): count"));
if (count == 15)
{
count += (uint16_t)faad_getbits(ld, 8
DEBUGVAR(1,66,"fill_element(): extra count")) - 1;
}
if (count > 0)
{
#ifdef SBR_DEC
bs_extension_type = (uint8_t)faad_showbits(ld, 4);
if ((bs_extension_type == EXT_SBR_DATA) ||
(bs_extension_type == EXT_SBR_DATA_CRC))
{
if (sbr_ele == INVALID_SBR_ELEMENT)
return 24;
if (!hDecoder->sbr[sbr_ele])
{
hDecoder->sbr[sbr_ele] = sbrDecodeInit(hDecoder->frameLength,
hDecoder->element_id[sbr_ele], 2*get_sample_rate(hDecoder->sf_index),
hDecoder->downSampledSBR
#ifdef DRM
, 0
#endif
);
}
hDecoder->sbr_present_flag = 1;
/* parse the SBR data */
hDecoder->sbr[sbr_ele]->ret = sbr_extension_data(ld, hDecoder->sbr[sbr_ele], count,
hDecoder->postSeekResetFlag);
#if 0
if (hDecoder->sbr[sbr_ele]->ret > 0)
{
printf("%s\n", NeAACDecGetErrorMessage(hDecoder->sbr[sbr_ele]->ret));
}
#endif
#if (defined(PS_DEC) || defined(DRM_PS))
if (hDecoder->sbr[sbr_ele]->ps_used)
{
hDecoder->ps_used[sbr_ele] = 1;
/* set element independent flag to 1 as well */
hDecoder->ps_used_global = 1;
}
#endif
} else {
#endif
#ifndef DRM
while (count > 0)
{
count -= extension_payload(ld, drc, count);
}
#else
return 30;
#endif
#ifdef SBR_DEC
}
#endif
}
return 0;
}
/* Table 4.4.12 */
#ifdef SSR_DEC
static void gain_control_data(bitfile *ld, ic_stream *ics)
{
uint8_t bd, wd, ad;
ssr_info *ssr = &(ics->ssr);
ssr->max_band = (uint8_t)faad_getbits(ld, 2
DEBUGVAR(1,1000,"gain_control_data(): max_band"));
if (ics->window_sequence == ONLY_LONG_SEQUENCE)
{
for (bd = 1; bd <= ssr->max_band; bd++)
{
for (wd = 0; wd < 1; wd++)
{
ssr->adjust_num[bd][wd] = (uint8_t)faad_getbits(ld, 3
DEBUGVAR(1,1001,"gain_control_data(): adjust_num"));
for (ad = 0; ad < ssr->adjust_num[bd][wd]; ad++)
{
ssr->alevcode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,1002,"gain_control_data(): alevcode"));
ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 5
DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
}
}
}
} else if (ics->window_sequence == LONG_START_SEQUENCE) {
for (bd = 1; bd <= ssr->max_band; bd++)
{
for (wd = 0; wd < 2; wd++)
{
ssr->adjust_num[bd][wd] = (uint8_t)faad_getbits(ld, 3
DEBUGVAR(1,1001,"gain_control_data(): adjust_num"));
for (ad = 0; ad < ssr->adjust_num[bd][wd]; ad++)
{
ssr->alevcode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,1002,"gain_control_data(): alevcode"));
if (wd == 0)
{
ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
} else {
ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 2
DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
}
}
}
}
} else if (ics->window_sequence == EIGHT_SHORT_SEQUENCE) {
for (bd = 1; bd <= ssr->max_band; bd++)
{
for (wd = 0; wd < 8; wd++)
{
ssr->adjust_num[bd][wd] = (uint8_t)faad_getbits(ld, 3
DEBUGVAR(1,1001,"gain_control_data(): adjust_num"));
for (ad = 0; ad < ssr->adjust_num[bd][wd]; ad++)
{
ssr->alevcode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,1002,"gain_control_data(): alevcode"));
ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 2
DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
}
}
}
} else if (ics->window_sequence == LONG_STOP_SEQUENCE) {
for (bd = 1; bd <= ssr->max_band; bd++)
{
for (wd = 0; wd < 2; wd++)
{
ssr->adjust_num[bd][wd] = (uint8_t)faad_getbits(ld, 3
DEBUGVAR(1,1001,"gain_control_data(): adjust_num"));
for (ad = 0; ad < ssr->adjust_num[bd][wd]; ad++)
{
ssr->alevcode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,1002,"gain_control_data(): alevcode"));
if (wd == 0)
{
ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
} else {
ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 5
DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
}
}
}
}
}
}
#endif
#ifdef DRM
/* Table 4.4.13 ASME */
void DRM_aac_scalable_main_element(NeAACDecStruct *hDecoder, NeAACDecFrameInfo *hInfo,
bitfile *ld, program_config *pce, drc_info *drc)
{
uint8_t retval = 0;
uint8_t channels = hDecoder->fr_channels = 0;
uint8_t ch;
uint8_t this_layer_stereo = (hDecoder->channelConfiguration > 1) ? 1 : 0;
element cpe = {0};
ic_stream *ics1 = &(cpe.ics1);
ic_stream *ics2 = &(cpe.ics2);
int16_t *spec_data;
ALIGN int16_t spec_data1[1024] = {0};
ALIGN int16_t spec_data2[1024] = {0};
hDecoder->fr_ch_ele = 0;
hInfo->error = DRM_aac_scalable_main_header(hDecoder, ics1, ics2, ld, this_layer_stereo);
if (hInfo->error > 0)
return;
cpe.common_window = 1;
if (this_layer_stereo)
{
hDecoder->element_id[0] = ID_CPE;
if (hDecoder->element_output_channels[hDecoder->fr_ch_ele] == 0)
hDecoder->element_output_channels[hDecoder->fr_ch_ele] = 2;
} else {
hDecoder->element_id[0] = ID_SCE;
}
if (this_layer_stereo)
{
cpe.channel = 0;
cpe.paired_channel = 1;
}
/* Stereo2 / Mono1 */
ics1->tns_data_present = faad_get1bit(ld);
#if defined(LTP_DEC)
ics1->ltp.data_present = faad_get1bit(ld);
#elif defined (DRM)
if(faad_get1bit(ld)) {
hInfo->error = 26;
return;
}
#else
faad_get1bit(ld);
#endif
hInfo->error = side_info(hDecoder, &cpe, ld, ics1, 1);
if (hInfo->error > 0)
return;
if (this_layer_stereo)
{
/* Stereo3 */
ics2->tns_data_present = faad_get1bit(ld);
#ifdef LTP_DEC
ics1->ltp.data_present =
#endif
faad_get1bit(ld);
hInfo->error = side_info(hDecoder, &cpe, ld, ics2, 1);
if (hInfo->error > 0)
return;
}
/* Stereo4 / Mono2 */
if (ics1->tns_data_present)
tns_data(ics1, &(ics1->tns), ld);
if (this_layer_stereo)
{
/* Stereo5 */
if (ics2->tns_data_present)
tns_data(ics2, &(ics2->tns), ld);
}
#ifdef DRM
/* CRC check */
if (hDecoder->object_type == DRM_ER_LC)
{
if ((hInfo->error = (uint8_t)faad_check_CRC(ld, (uint16_t)faad_get_processed_bits(ld) - 8)) > 0)
return;
}
#endif
/* Stereo6 / Mono3 */
/* error resilient spectral data decoding */
if ((hInfo->error = reordered_spectral_data(hDecoder, ics1, ld, spec_data1)) > 0)
{
return;
}
if (this_layer_stereo)
{
/* Stereo7 */
/* error resilient spectral data decoding */
if ((hInfo->error = reordered_spectral_data(hDecoder, ics2, ld, spec_data2)) > 0)
{
return;
}
}
#ifdef DRM
#ifdef SBR_DEC
/* In case of DRM we need to read the SBR info before channel reconstruction */
if ((hDecoder->sbr_present_flag == 1) && (hDecoder->object_type == DRM_ER_LC))
{
bitfile ld_sbr = {0};
uint32_t i;
uint16_t count = 0;
uint8_t *revbuffer;
uint8_t *prevbufstart;
uint8_t *pbufend;
/* all forward bitreading should be finished at this point */
uint32_t bitsconsumed = faad_get_processed_bits(ld);
uint32_t buffer_size = faad_origbitbuffer_size(ld);
uint8_t *buffer = (uint8_t*)faad_origbitbuffer(ld);
if (bitsconsumed + 8 > buffer_size*8)
{
hInfo->error = 14;
return;
}
if (!hDecoder->sbr[0])
{
hDecoder->sbr[0] = sbrDecodeInit(hDecoder->frameLength, hDecoder->element_id[0],
2*get_sample_rate(hDecoder->sf_index), 0 /* ds SBR */, 1);
}
/* Reverse bit reading of SBR data in DRM audio frame */
revbuffer = (uint8_t*)faad_malloc(buffer_size*sizeof(uint8_t));
prevbufstart = revbuffer;
pbufend = &buffer[buffer_size - 1];
for (i = 0; i < buffer_size; i++)
*prevbufstart++ = tabFlipbits[*pbufend--];
/* Set SBR data */
/* consider 8 bits from AAC-CRC */
/* SBR buffer size is original buffer size minus AAC buffer size */
count = (uint16_t)bit2byte(buffer_size*8 - bitsconsumed);
faad_initbits(&ld_sbr, revbuffer, count);
hDecoder->sbr[0]->sample_rate = get_sample_rate(hDecoder->sf_index);
hDecoder->sbr[0]->sample_rate *= 2;
faad_getbits(&ld_sbr, 8); /* Skip 8-bit CRC */
hDecoder->sbr[0]->ret = sbr_extension_data(&ld_sbr, hDecoder->sbr[0], count, hDecoder->postSeekResetFlag);
#if (defined(PS_DEC) || defined(DRM_PS))
if (hDecoder->sbr[0]->ps_used)
{
hDecoder->ps_used[0] = 1;
hDecoder->ps_used_global = 1;
}
#endif
if (ld_sbr.error)
{
hDecoder->sbr[0]->ret = 1;
}
/* check CRC */
/* no need to check it if there was already an error */
if (hDecoder->sbr[0]->ret == 0)
hDecoder->sbr[0]->ret = (uint8_t)faad_check_CRC(&ld_sbr, (uint16_t)faad_get_processed_bits(&ld_sbr) - 8);
/* SBR data was corrupted, disable it until the next header */
if (hDecoder->sbr[0]->ret != 0)
{
hDecoder->sbr[0]->header_count = 0;
}
faad_endbits(&ld_sbr);
if (revbuffer)
faad_free(revbuffer);
}
#endif
#endif
if (this_layer_stereo)
{
hInfo->error = reconstruct_channel_pair(hDecoder, ics1, ics2, &cpe, spec_data1, spec_data2);
if (hInfo->error > 0)
return;
} else {
hInfo->error = reconstruct_single_channel(hDecoder, ics1, &cpe, spec_data1);
if (hInfo->error > 0)
return;
}
/* map output channels position to internal data channels */
if (hDecoder->element_output_channels[hDecoder->fr_ch_ele] == 2)
{
/* this might be faulty when pce_set is true */
hDecoder->internal_channel[channels] = channels;
hDecoder->internal_channel[channels+1] = channels+1;
} else {
hDecoder->internal_channel[channels] = channels;
}
hDecoder->fr_channels += hDecoder->element_output_channels[hDecoder->fr_ch_ele];
hDecoder->fr_ch_ele++;
return;
}
/* Table 4.4.15 */
static int8_t DRM_aac_scalable_main_header(NeAACDecStruct *hDecoder, ic_stream *ics1, ic_stream *ics2,
bitfile *ld, uint8_t this_layer_stereo)
{
uint8_t retval = 0;
uint8_t ch;
ic_stream *ics;
uint8_t ics_reserved_bit;
ics_reserved_bit = faad_get1bit(ld
DEBUGVAR(1,300,"aac_scalable_main_header(): ics_reserved_bits"));
if (ics_reserved_bit != 0)
return 32;
ics1->window_sequence = (uint8_t)faad_getbits(ld, 2
DEBUGVAR(1,301,"aac_scalable_main_header(): window_sequence"));
ics1->window_shape = faad_get1bit(ld
DEBUGVAR(1,302,"aac_scalable_main_header(): window_shape"));
if (ics1->window_sequence == EIGHT_SHORT_SEQUENCE)
{
ics1->max_sfb = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,303,"aac_scalable_main_header(): max_sfb (short)"));
ics1->scale_factor_grouping = (uint8_t)faad_getbits(ld, 7
DEBUGVAR(1,304,"aac_scalable_main_header(): scale_factor_grouping"));
} else {
ics1->max_sfb = (uint8_t)faad_getbits(ld, 6
DEBUGVAR(1,305,"aac_scalable_main_header(): max_sfb (long)"));
}
/* get the grouping information */
if ((retval = window_grouping_info(hDecoder, ics1)) > 0)
return retval;
/* should be an error */
/* check the range of max_sfb */
if (ics1->max_sfb > ics1->num_swb)
return 16;
if (this_layer_stereo)
{
ics1->ms_mask_present = (uint8_t)faad_getbits(ld, 2
DEBUGVAR(1,306,"aac_scalable_main_header(): ms_mask_present"));
if (ics1->ms_mask_present == 3)
{
/* bitstream error */
return 32;
}
if (ics1->ms_mask_present == 1)
{
uint8_t g, sfb;
for (g = 0; g < ics1->num_window_groups; g++)
{
for (sfb = 0; sfb < ics1->max_sfb; sfb++)
{
ics1->ms_used[g][sfb] = faad_get1bit(ld
DEBUGVAR(1,307,"aac_scalable_main_header(): faad_get1bit"));
}
}
}
memcpy(ics2, ics1, sizeof(ic_stream));
} else {
ics1->ms_mask_present = 0;
}
return 0;
}
#endif
static uint8_t side_info(NeAACDecStruct *hDecoder, element *ele,
bitfile *ld, ic_stream *ics, uint8_t scal_flag)
{
uint8_t result;
ics->global_gain = (uint8_t)faad_getbits(ld, 8
DEBUGVAR(1,67,"individual_channel_stream(): global_gain"));
if (!ele->common_window && !scal_flag)
{
if ((result = ics_info(hDecoder, ics, ld, ele->common_window)) > 0)
return result;
}
if ((result = section_data(hDecoder, ics, ld)) > 0)
return result;
if ((result = scale_factor_data(hDecoder, ics, ld)) > 0)
return result;
if (!scal_flag)
{
/**
** NOTE: It could be that pulse data is available in scalable AAC too,
** as said in Amendment 1, this could be only the case for ER AAC,
** though. (have to check this out later)
**/
/* get pulse data */
if ((ics->pulse_data_present = faad_get1bit(ld
DEBUGVAR(1,68,"individual_channel_stream(): pulse_data_present"))) & 1)
{
if ((result = pulse_data(ics, &(ics->pul), ld)) > 0)
return result;
}
/* get tns data */
if ((ics->tns_data_present = faad_get1bit(ld
DEBUGVAR(1,69,"individual_channel_stream(): tns_data_present"))) & 1)
{
#ifdef ERROR_RESILIENCE
if (hDecoder->object_type < ER_OBJECT_START)
#endif
tns_data(ics, &(ics->tns), ld);
}
/* get gain control data */
if ((ics->gain_control_data_present = faad_get1bit(ld
DEBUGVAR(1,70,"individual_channel_stream(): gain_control_data_present"))) & 1)
{
#ifdef SSR_DEC
if (hDecoder->object_type != SSR)
return 1;
else
gain_control_data(ld, ics);
#else
return 1;
#endif
}
}
#ifdef ERROR_RESILIENCE
if (hDecoder->aacSpectralDataResilienceFlag)
{
ics->length_of_reordered_spectral_data = (uint16_t)faad_getbits(ld, 14
DEBUGVAR(1,147,"individual_channel_stream(): length_of_reordered_spectral_data"));
if (hDecoder->channelConfiguration == 2)
{
if (ics->length_of_reordered_spectral_data > 6144)
ics->length_of_reordered_spectral_data = 6144;
} else {
if (ics->length_of_reordered_spectral_data > 12288)
ics->length_of_reordered_spectral_data = 12288;
}
ics->length_of_longest_codeword = (uint8_t)faad_getbits(ld, 6
DEBUGVAR(1,148,"individual_channel_stream(): length_of_longest_codeword"));
if (ics->length_of_longest_codeword >= 49)
ics->length_of_longest_codeword = 49;
}
/* RVLC spectral data is put here */
if (hDecoder->aacScalefactorDataResilienceFlag)
{
if ((result = rvlc_decode_scale_factors(ics, ld)) > 0)
return result;
}
#endif
return 0;
}
/* Table 4.4.24 */
static uint8_t individual_channel_stream(NeAACDecStruct *hDecoder, element *ele,
bitfile *ld, ic_stream *ics, uint8_t scal_flag,
int16_t *spec_data)
{
uint8_t result;
result = side_info(hDecoder, ele, ld, ics, scal_flag);
if (result > 0)
return result;
if (hDecoder->object_type >= ER_OBJECT_START)
{
if (ics->tns_data_present)
tns_data(ics, &(ics->tns), ld);
}
#ifdef DRM
/* CRC check */
if (hDecoder->object_type == DRM_ER_LC)
{
if ((result = (uint8_t)faad_check_CRC(ld, (uint16_t)faad_get_processed_bits(ld) - 8)) > 0)
return result;
}
#endif
#ifdef ERROR_RESILIENCE
if (hDecoder->aacSpectralDataResilienceFlag)
{
/* error resilient spectral data decoding */
if ((result = reordered_spectral_data(hDecoder, ics, ld, spec_data)) > 0)
{
return result;
}
} else {
#endif
/* decode the spectral data */
if ((result = spectral_data(hDecoder, ics, ld, spec_data)) > 0)
{
return result;
}
#ifdef ERROR_RESILIENCE
}
#endif
/* pulse coding reconstruction */
if (ics->pulse_data_present)
{
if (ics->window_sequence != EIGHT_SHORT_SEQUENCE)
{
if ((result = pulse_decode(ics, spec_data, hDecoder->frameLength)) > 0)
return result;
} else {
return 2; /* pulse coding not allowed for short blocks */
}
}
return 0;
}
/* Table 4.4.25 */
static uint8_t section_data(NeAACDecStruct *hDecoder, ic_stream *ics, bitfile *ld)
{
uint8_t g;
uint8_t sect_esc_val, sect_bits;
if (ics->window_sequence == EIGHT_SHORT_SEQUENCE)
sect_bits = 3;
else
sect_bits = 5;
sect_esc_val = (1<<sect_bits) - 1;
#if 0
printf("\ntotal sfb %d\n", ics->max_sfb);
printf(" sect top cb\n");
#endif
for (g = 0; g < ics->num_window_groups; g++)
{
uint8_t k = 0;
uint8_t i = 0;
while (k < ics->max_sfb)
{
#ifdef ERROR_RESILIENCE
uint8_t vcb11 = 0;
#endif
uint8_t sfb;
uint8_t sect_len_incr;
uint16_t sect_len = 0;
uint8_t sect_cb_bits = 4;
/* if "faad_getbits" detects error and returns "0", "k" is never
incremented and we cannot leave the while loop */
if (ld->error != 0)
return 14;
#ifdef ERROR_RESILIENCE
if (hDecoder->aacSectionDataResilienceFlag)
sect_cb_bits = 5;
#endif
ics->sect_cb[g][i] = (uint8_t)faad_getbits(ld, sect_cb_bits
DEBUGVAR(1,71,"section_data(): sect_cb"));
if (ics->sect_cb[g][i] == 12)
return 32;
#if 0
printf("%d\n", ics->sect_cb[g][i]);
#endif
#ifndef DRM
if (ics->sect_cb[g][i] == NOISE_HCB)
ics->noise_used = 1;
#else
/* PNS not allowed in DRM */
if (ics->sect_cb[g][i] == NOISE_HCB)
return 29;
#endif
if (ics->sect_cb[g][i] == INTENSITY_HCB2 || ics->sect_cb[g][i] == INTENSITY_HCB)
ics->is_used = 1;
#ifdef ERROR_RESILIENCE
if (hDecoder->aacSectionDataResilienceFlag)
{
if ((ics->sect_cb[g][i] == 11) ||
((ics->sect_cb[g][i] >= 16) && (ics->sect_cb[g][i] <= 32)))
{
vcb11 = 1;
}
}
if (vcb11)
{
sect_len_incr = 1;
} else {
#endif
sect_len_incr = (uint8_t)faad_getbits(ld, sect_bits
DEBUGVAR(1,72,"section_data(): sect_len_incr"));
#ifdef ERROR_RESILIENCE
}
#endif
while ((sect_len_incr == sect_esc_val) /* &&
(k+sect_len < ics->max_sfb)*/)
{
sect_len += sect_len_incr;
sect_len_incr = (uint8_t)faad_getbits(ld, sect_bits
DEBUGVAR(1,72,"section_data(): sect_len_incr"));
}
sect_len += sect_len_incr;
ics->sect_start[g][i] = k;
ics->sect_end[g][i] = k + sect_len;
#if 0
printf("%d\n", ics->sect_start[g][i]);
#endif
#if 0
printf("%d\n", ics->sect_end[g][i]);
#endif
if (ics->window_sequence == EIGHT_SHORT_SEQUENCE)
{
if (k + sect_len > 8*15)
return 15;
if (i >= 8*15)
return 15;
} else {
if (k + sect_len > MAX_SFB)
return 15;
if (i >= MAX_SFB)
return 15;
}
for (sfb = k; sfb < k + sect_len; sfb++)
{
ics->sfb_cb[g][sfb] = ics->sect_cb[g][i];
#if 0
printf("%d\n", ics->sfb_cb[g][sfb]);
#endif
}
#if 0
printf(" %6d %6d %6d\n",
i,
ics->sect_end[g][i],
ics->sect_cb[g][i]);
#endif
k += sect_len;
i++;
}
ics->num_sec[g] = i;
/* the sum of all sect_len_incr elements for a given window
* group shall equal max_sfb */
if (k != ics->max_sfb)
{
return 32;
}
#if 0
printf("%d\n", ics->num_sec[g]);
#endif
}
#if 0
printf("\n");
#endif
return 0;
}
/*
* decode_scale_factors()
* decodes the scalefactors from the bitstream
*/
/*
* All scalefactors (and also the stereo positions and pns energies) are
* transmitted using Huffman coded DPCM relative to the previous active
* scalefactor (respectively previous stereo position or previous pns energy,
* see subclause 4.6.2 and 4.6.3). The first active scalefactor is
* differentially coded relative to the global gain.
*/
static uint8_t decode_scale_factors(ic_stream *ics, bitfile *ld)
{
uint8_t g, sfb;
int16_t t;
int8_t noise_pcm_flag = 1;
int16_t scale_factor = ics->global_gain;
int16_t is_position = 0;
int16_t noise_energy = ics->global_gain - 90;
for (g = 0; g < ics->num_window_groups; g++)
{
for (sfb = 0; sfb < ics->max_sfb; sfb++)
{
switch (ics->sfb_cb[g][sfb])
{
case ZERO_HCB: /* zero book */
ics->scale_factors[g][sfb] = 0;
//#define SF_PRINT
#ifdef SF_PRINT
printf("%d\n", ics->scale_factors[g][sfb]);
#endif
break;
case INTENSITY_HCB: /* intensity books */
case INTENSITY_HCB2:
/* decode intensity position */
t = huffman_scale_factor(ld);
is_position += (t - 60);
ics->scale_factors[g][sfb] = is_position;
#ifdef SF_PRINT
printf("%d\n", ics->scale_factors[g][sfb]);
#endif
break;
case NOISE_HCB: /* noise books */
#ifndef DRM
/* decode noise energy */
if (noise_pcm_flag)
{
noise_pcm_flag = 0;
t = (int16_t)faad_getbits(ld, 9
DEBUGVAR(1,73,"scale_factor_data(): first noise")) - 256;
} else {
t = huffman_scale_factor(ld);
t -= 60;
}
noise_energy += t;
ics->scale_factors[g][sfb] = noise_energy;
#ifdef SF_PRINT
printf("%d\n", ics->scale_factors[g][sfb]);
#endif
#else
/* PNS not allowed in DRM */
return 29;
#endif
break;
default: /* spectral books */
/* ics->scale_factors[g][sfb] must be between 0 and 255 */
ics->scale_factors[g][sfb] = 0;
/* decode scale factor */
t = huffman_scale_factor(ld);
scale_factor += (t - 60);
if (scale_factor < 0 || scale_factor > 255)
return 4;
ics->scale_factors[g][sfb] = scale_factor;
#ifdef SF_PRINT
printf("%d\n", ics->scale_factors[g][sfb]);
#endif
break;
}
}
}
return 0;
}
/* Table 4.4.26 */
static uint8_t scale_factor_data(NeAACDecStruct *hDecoder, ic_stream *ics, bitfile *ld)
{
uint8_t ret = 0;
#ifdef PROFILE
int64_t count = faad_get_ts();
#endif
#ifdef ERROR_RESILIENCE
if (!hDecoder->aacScalefactorDataResilienceFlag)
{
#endif
ret = decode_scale_factors(ics, ld);
#ifdef ERROR_RESILIENCE
} else {
/* In ER AAC the parameters for RVLC are seperated from the actual
data that holds the scale_factors.
Strangely enough, 2 parameters for HCR are put inbetween them.
*/
ret = rvlc_scale_factor_data(ics, ld);
}
#endif
#ifdef PROFILE
count = faad_get_ts() - count;
hDecoder->scalefac_cycles += count;
#endif
return ret;
}
/* Table 4.4.27 */
static void tns_data(ic_stream *ics, tns_info *tns, bitfile *ld)
{
uint8_t w, filt, i, start_coef_bits, coef_bits;
uint8_t n_filt_bits = 2;
uint8_t length_bits = 6;
uint8_t order_bits = 5;
if (ics->window_sequence == EIGHT_SHORT_SEQUENCE)
{
n_filt_bits = 1;
length_bits = 4;
order_bits = 3;
}
for (w = 0; w < ics->num_windows; w++)
{
tns->n_filt[w] = (uint8_t)faad_getbits(ld, n_filt_bits
DEBUGVAR(1,74,"tns_data(): n_filt"));
#if 0
printf("%d\n", tns->n_filt[w]);
#endif
if (tns->n_filt[w])
{
if ((tns->coef_res[w] = faad_get1bit(ld
DEBUGVAR(1,75,"tns_data(): coef_res"))) & 1)
{
start_coef_bits = 4;
} else {
start_coef_bits = 3;
}
#if 0
printf("%d\n", tns->coef_res[w]);
#endif
}
for (filt = 0; filt < tns->n_filt[w]; filt++)
{
tns->length[w][filt] = (uint8_t)faad_getbits(ld, length_bits
DEBUGVAR(1,76,"tns_data(): length"));
#if 0
printf("%d\n", tns->length[w][filt]);
#endif
tns->order[w][filt] = (uint8_t)faad_getbits(ld, order_bits
DEBUGVAR(1,77,"tns_data(): order"));
#if 0
printf("%d\n", tns->order[w][filt]);
#endif
if (tns->order[w][filt])
{
tns->direction[w][filt] = faad_get1bit(ld
DEBUGVAR(1,78,"tns_data(): direction"));
#if 0
printf("%d\n", tns->direction[w][filt]);
#endif
tns->coef_compress[w][filt] = faad_get1bit(ld
DEBUGVAR(1,79,"tns_data(): coef_compress"));
#if 0
printf("%d\n", tns->coef_compress[w][filt]);
#endif
coef_bits = start_coef_bits - tns->coef_compress[w][filt];
for (i = 0; i < tns->order[w][filt]; i++)
{
tns->coef[w][filt][i] = (uint8_t)faad_getbits(ld, coef_bits
DEBUGVAR(1,80,"tns_data(): coef"));
#if 0
printf("%d\n", tns->coef[w][filt][i]);
#endif
}
}
}
}
}
#ifdef LTP_DEC
/* Table 4.4.28 */
static uint8_t ltp_data(NeAACDecStruct *hDecoder, ic_stream *ics, ltp_info *ltp, bitfile *ld)
{
uint8_t sfb, w;
ltp->lag = 0;
#ifdef LD_DEC
if (hDecoder->object_type == LD)
{
ltp->lag_update = (uint8_t)faad_getbits(ld, 1
DEBUGVAR(1,142,"ltp_data(): lag_update"));
if (ltp->lag_update)
{
ltp->lag = (uint16_t)faad_getbits(ld, 10
DEBUGVAR(1,81,"ltp_data(): lag"));
}
} else {
#endif
ltp->lag = (uint16_t)faad_getbits(ld, 11
DEBUGVAR(1,81,"ltp_data(): lag"));
#ifdef LD_DEC
}
#endif
/* Check length of lag */
if (ltp->lag > (hDecoder->frameLength << 1))
return 18;
ltp->coef = (uint8_t)faad_getbits(ld, 3
DEBUGVAR(1,82,"ltp_data(): coef"));
if (ics->window_sequence == EIGHT_SHORT_SEQUENCE)
{
for (w = 0; w < ics->num_windows; w++)
{
if ((ltp->short_used[w] = faad_get1bit(ld
DEBUGVAR(1,83,"ltp_data(): short_used"))) & 1)
{
ltp->short_lag_present[w] = faad_get1bit(ld
DEBUGVAR(1,84,"ltp_data(): short_lag_present"));
if (ltp->short_lag_present[w])
{
ltp->short_lag[w] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,85,"ltp_data(): short_lag"));
}
}
}
} else {
ltp->last_band = (ics->max_sfb < MAX_LTP_SFB ? ics->max_sfb : MAX_LTP_SFB);
for (sfb = 0; sfb < ltp->last_band; sfb++)
{
ltp->long_used[sfb] = faad_get1bit(ld
DEBUGVAR(1,86,"ltp_data(): long_used"));
}
}
return 0;
}
#endif
/* Table 4.4.29 */
static uint8_t spectral_data(NeAACDecStruct *hDecoder, ic_stream *ics, bitfile *ld,
int16_t *spectral_data)
{
int8_t i;
uint8_t g;
uint16_t inc, k, p = 0;
uint8_t groups = 0;
uint8_t sect_cb;
uint8_t result;
uint16_t nshort = hDecoder->frameLength/8;
#ifdef PROFILE
int64_t count = faad_get_ts();
#endif
for(g = 0; g < ics->num_window_groups; g++)
{
p = groups*nshort;
for (i = 0; i < ics->num_sec[g]; i++)
{
sect_cb = ics->sect_cb[g][i];
inc = (sect_cb >= FIRST_PAIR_HCB) ? 2 : 4;
switch (sect_cb)
{
case ZERO_HCB:
case NOISE_HCB:
case INTENSITY_HCB:
case INTENSITY_HCB2:
//#define SD_PRINT
#ifdef SD_PRINT
{
int j;
for (j = ics->sect_sfb_offset[g][ics->sect_start[g][i]]; j < ics->sect_sfb_offset[g][ics->sect_end[g][i]]; j++)
{
printf("%d\n", 0);
}
}
#endif
//#define SFBO_PRINT
#ifdef SFBO_PRINT
printf("%d\n", ics->sect_sfb_offset[g][ics->sect_start[g][i]]);
#endif
p += (ics->sect_sfb_offset[g][ics->sect_end[g][i]] -
ics->sect_sfb_offset[g][ics->sect_start[g][i]]);
break;
default:
#ifdef SFBO_PRINT
printf("%d\n", ics->sect_sfb_offset[g][ics->sect_start[g][i]]);
#endif
for (k = ics->sect_sfb_offset[g][ics->sect_start[g][i]];
k < ics->sect_sfb_offset[g][ics->sect_end[g][i]]; k += inc)
{
if ((result = huffman_spectral_data(sect_cb, ld, &spectral_data[p])) > 0)
return result;
#ifdef SD_PRINT
{
int j;
for (j = p; j < p+inc; j++)
{
printf("%d\n", spectral_data[j]);
}
}
#endif
p += inc;
}
break;
}
}
groups += ics->window_group_length[g];
}
#ifdef PROFILE
count = faad_get_ts() - count;
hDecoder->spectral_cycles += count;
#endif
return 0;
}
/* Table 4.4.30 */
static uint16_t extension_payload(bitfile *ld, drc_info *drc, uint16_t count)
{
uint16_t i, n, dataElementLength;
uint8_t dataElementLengthPart;
uint8_t align = 4, data_element_version, loopCounter;
uint8_t extension_type = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,87,"extension_payload(): extension_type"));
switch (extension_type)
{
case EXT_DYNAMIC_RANGE:
drc->present = 1;
n = dynamic_range_info(ld, drc);
return n;
case EXT_FILL_DATA:
/* fill_nibble = */ faad_getbits(ld, 4
DEBUGVAR(1,136,"extension_payload(): fill_nibble")); /* must be �0000� */
for (i = 0; i < count-1; i++)
{
/* fill_byte[i] = */ faad_getbits(ld, 8
DEBUGVAR(1,88,"extension_payload(): fill_byte")); /* must be �10100101� */
}
return count;
case EXT_DATA_ELEMENT:
data_element_version = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,400,"extension_payload(): data_element_version"));
switch (data_element_version)
{
case ANC_DATA:
loopCounter = 0;
dataElementLength = 0;
do {
dataElementLengthPart = (uint8_t)faad_getbits(ld, 8
DEBUGVAR(1,401,"extension_payload(): dataElementLengthPart"));
dataElementLength += dataElementLengthPart;
loopCounter++;
} while (dataElementLengthPart == 255);
for (i = 0; i < dataElementLength; i++)
{
/* data_element_byte[i] = */ faad_getbits(ld, 8
DEBUGVAR(1,402,"extension_payload(): data_element_byte"));
return (dataElementLength+loopCounter+1);
}
default:
align = 0;
}
case EXT_FIL:
default:
faad_getbits(ld, align
DEBUGVAR(1,88,"extension_payload(): fill_nibble"));
for (i = 0; i < count-1; i++)
{
/* other_bits[i] = */ faad_getbits(ld, 8
DEBUGVAR(1,89,"extension_payload(): fill_bit"));
}
return count;
}
}
/* Table 4.4.31 */
static uint8_t dynamic_range_info(bitfile *ld, drc_info *drc)
{
uint8_t i, n = 1;
uint8_t band_incr;
drc->num_bands = 1;
if (faad_get1bit(ld
DEBUGVAR(1,90,"dynamic_range_info(): has instance_tag")) & 1)
{
drc->pce_instance_tag = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,91,"dynamic_range_info(): pce_instance_tag"));
/* drc->drc_tag_reserved_bits = */ faad_getbits(ld, 4
DEBUGVAR(1,92,"dynamic_range_info(): drc_tag_reserved_bits"));
n++;
}
drc->excluded_chns_present = faad_get1bit(ld
DEBUGVAR(1,93,"dynamic_range_info(): excluded_chns_present"));
if (drc->excluded_chns_present == 1)
{
n += excluded_channels(ld, drc);
}
if (faad_get1bit(ld
DEBUGVAR(1,94,"dynamic_range_info(): has bands data")) & 1)
{
band_incr = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,95,"dynamic_range_info(): band_incr"));
/* drc->drc_bands_reserved_bits = */ faad_getbits(ld, 4
DEBUGVAR(1,96,"dynamic_range_info(): drc_bands_reserved_bits"));
n++;
drc->num_bands += band_incr;
for (i = 0; i < drc->num_bands; i++)
{
drc->band_top[i] = (uint8_t)faad_getbits(ld, 8
DEBUGVAR(1,97,"dynamic_range_info(): band_top"));
n++;
}
}
if (faad_get1bit(ld
DEBUGVAR(1,98,"dynamic_range_info(): has prog_ref_level")) & 1)
{
drc->prog_ref_level = (uint8_t)faad_getbits(ld, 7
DEBUGVAR(1,99,"dynamic_range_info(): prog_ref_level"));
/* drc->prog_ref_level_reserved_bits = */ faad_get1bit(ld
DEBUGVAR(1,100,"dynamic_range_info(): prog_ref_level_reserved_bits"));
n++;
}
for (i = 0; i < drc->num_bands; i++)
{
drc->dyn_rng_sgn[i] = faad_get1bit(ld
DEBUGVAR(1,101,"dynamic_range_info(): dyn_rng_sgn"));
drc->dyn_rng_ctl[i] = (uint8_t)faad_getbits(ld, 7
DEBUGVAR(1,102,"dynamic_range_info(): dyn_rng_ctl"));
n++;
}
return n;
}
/* Table 4.4.32 */
static uint8_t excluded_channels(bitfile *ld, drc_info *drc)
{
uint8_t i, n = 0;
uint8_t num_excl_chan = 7;
for (i = 0; i < 7; i++)
{
drc->exclude_mask[i] = faad_get1bit(ld
DEBUGVAR(1,103,"excluded_channels(): exclude_mask"));
}
n++;
while ((drc->additional_excluded_chns[n-1] = faad_get1bit(ld
DEBUGVAR(1,104,"excluded_channels(): additional_excluded_chns"))) == 1)
{
if (i >= MAX_CHANNELS - num_excl_chan - 7)
return n;
for (i = num_excl_chan; i < num_excl_chan+7; i++)
{
drc->exclude_mask[i] = faad_get1bit(ld
DEBUGVAR(1,105,"excluded_channels(): exclude_mask"));
}
n++;
num_excl_chan += 7;
}
return n;
}
/* Annex A: Audio Interchange Formats */
/* Table 1.A.2 */
void get_adif_header(adif_header *adif, bitfile *ld)
{
uint8_t i;
/* adif_id[0] = */ faad_getbits(ld, 8
DEBUGVAR(1,106,"get_adif_header(): adif_id[0]"));
/* adif_id[1] = */ faad_getbits(ld, 8
DEBUGVAR(1,107,"get_adif_header(): adif_id[1]"));
/* adif_id[2] = */ faad_getbits(ld, 8
DEBUGVAR(1,108,"get_adif_header(): adif_id[2]"));
/* adif_id[3] = */ faad_getbits(ld, 8
DEBUGVAR(1,109,"get_adif_header(): adif_id[3]"));
adif->copyright_id_present = faad_get1bit(ld
DEBUGVAR(1,110,"get_adif_header(): copyright_id_present"));
if(adif->copyright_id_present)
{
for (i = 0; i < 72/8; i++)
{
adif->copyright_id[i] = (int8_t)faad_getbits(ld, 8
DEBUGVAR(1,111,"get_adif_header(): copyright_id"));
}
adif->copyright_id[i] = 0;
}
adif->original_copy = faad_get1bit(ld
DEBUGVAR(1,112,"get_adif_header(): original_copy"));
adif->home = faad_get1bit(ld
DEBUGVAR(1,113,"get_adif_header(): home"));
adif->bitstream_type = faad_get1bit(ld
DEBUGVAR(1,114,"get_adif_header(): bitstream_type"));
adif->bitrate = faad_getbits(ld, 23
DEBUGVAR(1,115,"get_adif_header(): bitrate"));
adif->num_program_config_elements = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,116,"get_adif_header(): num_program_config_elements"));
for (i = 0; i < adif->num_program_config_elements + 1; i++)
{
if(adif->bitstream_type == 0)
{
adif->adif_buffer_fullness = faad_getbits(ld, 20
DEBUGVAR(1,117,"get_adif_header(): adif_buffer_fullness"));
} else {
adif->adif_buffer_fullness = 0;
}
program_config_element(&adif->pce[i], ld);
}
}
/* Table 1.A.5 */
uint8_t adts_frame(adts_header *adts, bitfile *ld)
{
/* faad_byte_align(ld); */
if (adts_fixed_header(adts, ld))
return 5;
adts_variable_header(adts, ld);
adts_error_check(adts, ld);
return 0;
}
/* Table 1.A.6 */
static uint8_t adts_fixed_header(adts_header *adts, bitfile *ld)
{
uint16_t i;
uint8_t sync_err = 1;
/* try to recover from sync errors */
for (i = 0; i < 768; i++)
{
adts->syncword = (uint16_t)faad_showbits(ld, 12);
if (adts->syncword != 0xFFF)
{
faad_getbits(ld, 8
DEBUGVAR(0,0,""));
} else {
sync_err = 0;
faad_getbits(ld, 12
DEBUGVAR(1,118,"adts_fixed_header(): syncword"));
break;
}
}
if (sync_err)
return 5;
adts->id = faad_get1bit(ld
DEBUGVAR(1,119,"adts_fixed_header(): id"));
adts->layer = (uint8_t)faad_getbits(ld, 2
DEBUGVAR(1,120,"adts_fixed_header(): layer"));
adts->protection_absent = faad_get1bit(ld
DEBUGVAR(1,121,"adts_fixed_header(): protection_absent"));
adts->profile = (uint8_t)faad_getbits(ld, 2
DEBUGVAR(1,122,"adts_fixed_header(): profile"));
adts->sf_index = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,123,"adts_fixed_header(): sf_index"));
adts->private_bit = faad_get1bit(ld
DEBUGVAR(1,124,"adts_fixed_header(): private_bit"));
adts->channel_configuration = (uint8_t)faad_getbits(ld, 3
DEBUGVAR(1,125,"adts_fixed_header(): channel_configuration"));
adts->original = faad_get1bit(ld
DEBUGVAR(1,126,"adts_fixed_header(): original"));
adts->home = faad_get1bit(ld
DEBUGVAR(1,127,"adts_fixed_header(): home"));
if (adts->old_format == 1)
{
/* Removed in corrigendum 14496-3:2002 */
if (adts->id == 0)
{
adts->emphasis = (uint8_t)faad_getbits(ld, 2
DEBUGVAR(1,128,"adts_fixed_header(): emphasis"));
}
}
return 0;
}
/* Table 1.A.7 */
static void adts_variable_header(adts_header *adts, bitfile *ld)
{
adts->copyright_identification_bit = faad_get1bit(ld
DEBUGVAR(1,129,"adts_variable_header(): copyright_identification_bit"));
adts->copyright_identification_start = faad_get1bit(ld
DEBUGVAR(1,130,"adts_variable_header(): copyright_identification_start"));
adts->aac_frame_length = (uint16_t)faad_getbits(ld, 13
DEBUGVAR(1,131,"adts_variable_header(): aac_frame_length"));
adts->adts_buffer_fullness = (uint16_t)faad_getbits(ld, 11
DEBUGVAR(1,132,"adts_variable_header(): adts_buffer_fullness"));
adts->no_raw_data_blocks_in_frame = (uint8_t)faad_getbits(ld, 2
DEBUGVAR(1,133,"adts_variable_header(): no_raw_data_blocks_in_frame"));
}
/* Table 1.A.8 */
static void adts_error_check(adts_header *adts, bitfile *ld)
{
if (adts->protection_absent == 0)
{
adts->crc_check = (uint16_t)faad_getbits(ld, 16
DEBUGVAR(1,134,"adts_error_check(): crc_check"));
}
}
/* LATM parsing functions */
static uint32_t latm_get_value(bitfile *ld)
{
uint32_t l, value;
uint8_t bytesForValue;
bytesForValue = (uint8_t)faad_getbits(ld, 2);
value = 0;
for(l=0; l<bytesForValue; l++)
value = (value << 8) | (uint8_t)faad_getbits(ld, 8);
return value;
}
static uint32_t latmParsePayload(latm_header *latm, bitfile *ld)
{
//assuming there's only one program with a single layer and 1 subFrame,
//allStreamsSametimeframing is set,
uint32_t framelen;
uint8_t tmp;
//this should be the payload length field for the current configuration
framelen = 0;
if(latm->framelen_type==0)
{
do
{
tmp = (uint8_t)faad_getbits(ld, 8);
framelen += tmp;
} while(tmp==0xff);
}
else if(latm->framelen_type==1)
framelen=latm->frameLength;
return framelen;
}
static uint32_t latmAudioMuxElement(latm_header *latm, bitfile *ld)
{
uint32_t ascLen, asc_bits=0;
uint32_t x1, y1, m, n, i;
program_config pce;
mp4AudioSpecificConfig mp4ASC;
latm->useSameStreamMux = (uint8_t)faad_getbits(ld, 1);
if(!latm->useSameStreamMux)
{
//parseSameStreamMuxConfig
latm->version = (uint8_t) faad_getbits(ld, 1);
if(latm->version)
latm->versionA = (uint8_t) faad_getbits(ld, 1);
if(latm->versionA)
{
//dunno the payload format for versionA
fprintf(stderr, "versionA not supported\n");
return 0;
}
if(latm->version) //read taraBufferFullness
latm_get_value(ld);
latm->allStreamsSameTimeFraming = (uint8_t)faad_getbits(ld, 1);
latm->numSubFrames = (uint8_t)faad_getbits(ld, 6) + 1;
latm->numPrograms = (uint8_t)faad_getbits(ld, 4) + 1;
latm->numLayers = faad_getbits(ld, 3) + 1;
if(latm->numPrograms>1 || !latm->allStreamsSameTimeFraming || latm->numSubFrames>1 || latm->numLayers>1)
{
fprintf(stderr, "\r\nUnsupported LATM configuration: %d programs/ %d subframes, %d layers, allstreams: %d\n",
latm->numPrograms, latm->numSubFrames, latm->numLayers, latm->allStreamsSameTimeFraming);
return 0;
}
ascLen = 0;
if(latm->version)
ascLen = latm_get_value(ld);
x1 = faad_get_processed_bits(ld);
if(AudioSpecificConfigFromBitfile(ld, &mp4ASC, &pce, 0, 1) < 0)
return 0;
//horrid hack to unread the ASC bits and store them in latm->ASC
//the correct code would rely on an ideal faad_ungetbits()
y1 = faad_get_processed_bits(ld);
if((y1-x1) <= MAX_ASC_BYTES*8)
{
faad_rewindbits(ld);
m = x1;
while(m>0)
{
n = min(m, 32);
faad_getbits(ld, n);
m -= n;
}
i = 0;
m = latm->ASCbits = y1 - x1;
while(m > 0)
{
n = min(m, 8);
latm->ASC[i++] = (uint8_t) faad_getbits(ld, n);
m -= n;
}
}
asc_bits = y1-x1;
if(ascLen>asc_bits)
faad_getbits(ld, ascLen-asc_bits);
latm->framelen_type = (uint8_t) faad_getbits(ld, 3);
if(latm->framelen_type == 0)
{
latm->frameLength = 0;
faad_getbits(ld, 8); //buffer fullness for frame_len_type==0, useless
}
else if(latm->framelen_type == 1)
{
latm->frameLength = faad_getbits(ld, 9);
if(latm->frameLength==0)
{
fprintf(stderr, "Invalid frameLength: 0\r\n");
return 0;
}
latm->frameLength = (latm->frameLength+20)*8;
}
else
{ //hellish CELP or HCVX stuff, discard
fprintf(stderr, "Unsupported CELP/HCVX framelentype: %d\n", latm->framelen_type);
return 0;
}
latm->otherDataLenBits = 0;
if(faad_getbits(ld, 1))
{ //other data present
int esc, tmp;
if(latm->version)
latm->otherDataLenBits = latm_get_value(ld);
else do
{
esc = faad_getbits(ld, 1);
tmp = faad_getbits(ld, 8);
latm->otherDataLenBits = (latm->otherDataLenBits << 8) + tmp;
} while(esc);
}
if(faad_getbits(ld, 1)) //crc
faad_getbits(ld, 8);
latm->inited = 1;
}
//read payload
if(latm->inited)
return latmParsePayload(latm, ld);
else
return 0;
}
uint32_t faad_latm_frame(latm_header *latm, bitfile *ld)
{
uint16_t len;
uint32_t initpos, endpos, firstpos, ret;
firstpos = faad_get_processed_bits(ld);
while (ld->bytes_left)
{
faad_byte_align(ld);
if(faad_showbits(ld, 11) != 0x2B7)
{
faad_getbits(ld, 8);
continue;
}
faad_getbits(ld, 11);
len = faad_getbits(ld, 13);
if(!len)
continue;
initpos = faad_get_processed_bits(ld);
ret = latmAudioMuxElement(latm, ld);
endpos = faad_get_processed_bits(ld);
if(ret>0)
return (len*8)-(endpos-initpos);
//faad_getbits(ld, initpos-endpos); //go back to initpos, but is valid a getbits(-N) ?
}
return -1U;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_1030_1 |
crossvul-cpp_data_bad_3318_0 | /*
* Copyright (c) 2002 Petko Manolov (petkan@users.sourceforge.net)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*/
#include <linux/signal.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/mii.h>
#include <linux/ethtool.h>
#include <linux/usb.h>
#include <linux/uaccess.h>
/* Version Information */
#define DRIVER_VERSION "v0.6.2 (2004/08/27)"
#define DRIVER_AUTHOR "Petko Manolov <petkan@users.sourceforge.net>"
#define DRIVER_DESC "rtl8150 based usb-ethernet driver"
#define IDR 0x0120
#define MAR 0x0126
#define CR 0x012e
#define TCR 0x012f
#define RCR 0x0130
#define TSR 0x0132
#define RSR 0x0133
#define CON0 0x0135
#define CON1 0x0136
#define MSR 0x0137
#define PHYADD 0x0138
#define PHYDAT 0x0139
#define PHYCNT 0x013b
#define GPPC 0x013d
#define BMCR 0x0140
#define BMSR 0x0142
#define ANAR 0x0144
#define ANLP 0x0146
#define AER 0x0148
#define CSCR 0x014C /* This one has the link status */
#define CSCR_LINK_STATUS (1 << 3)
#define IDR_EEPROM 0x1202
#define PHY_READ 0
#define PHY_WRITE 0x20
#define PHY_GO 0x40
#define MII_TIMEOUT 10
#define INTBUFSIZE 8
#define RTL8150_REQT_READ 0xc0
#define RTL8150_REQT_WRITE 0x40
#define RTL8150_REQ_GET_REGS 0x05
#define RTL8150_REQ_SET_REGS 0x05
/* Transmit status register errors */
#define TSR_ECOL (1<<5)
#define TSR_LCOL (1<<4)
#define TSR_LOSS_CRS (1<<3)
#define TSR_JBR (1<<2)
#define TSR_ERRORS (TSR_ECOL | TSR_LCOL | TSR_LOSS_CRS | TSR_JBR)
/* Receive status register errors */
#define RSR_CRC (1<<2)
#define RSR_FAE (1<<1)
#define RSR_ERRORS (RSR_CRC | RSR_FAE)
/* Media status register definitions */
#define MSR_DUPLEX (1<<4)
#define MSR_SPEED (1<<3)
#define MSR_LINK (1<<2)
/* Interrupt pipe data */
#define INT_TSR 0x00
#define INT_RSR 0x01
#define INT_MSR 0x02
#define INT_WAKSR 0x03
#define INT_TXOK_CNT 0x04
#define INT_RXLOST_CNT 0x05
#define INT_CRERR_CNT 0x06
#define INT_COL_CNT 0x07
#define RTL8150_MTU 1540
#define RTL8150_TX_TIMEOUT (HZ)
#define RX_SKB_POOL_SIZE 4
/* rtl8150 flags */
#define RTL8150_HW_CRC 0
#define RX_REG_SET 1
#define RTL8150_UNPLUG 2
#define RX_URB_FAIL 3
/* Define these values to match your device */
#define VENDOR_ID_REALTEK 0x0bda
#define VENDOR_ID_MELCO 0x0411
#define VENDOR_ID_MICRONET 0x3980
#define VENDOR_ID_LONGSHINE 0x07b8
#define VENDOR_ID_OQO 0x1557
#define VENDOR_ID_ZYXEL 0x0586
#define PRODUCT_ID_RTL8150 0x8150
#define PRODUCT_ID_LUAKTX 0x0012
#define PRODUCT_ID_LCS8138TX 0x401a
#define PRODUCT_ID_SP128AR 0x0003
#define PRODUCT_ID_PRESTIGE 0x401a
#undef EEPROM_WRITE
/* table of devices that work with this driver */
static struct usb_device_id rtl8150_table[] = {
{USB_DEVICE(VENDOR_ID_REALTEK, PRODUCT_ID_RTL8150)},
{USB_DEVICE(VENDOR_ID_MELCO, PRODUCT_ID_LUAKTX)},
{USB_DEVICE(VENDOR_ID_MICRONET, PRODUCT_ID_SP128AR)},
{USB_DEVICE(VENDOR_ID_LONGSHINE, PRODUCT_ID_LCS8138TX)},
{USB_DEVICE(VENDOR_ID_OQO, PRODUCT_ID_RTL8150)},
{USB_DEVICE(VENDOR_ID_ZYXEL, PRODUCT_ID_PRESTIGE)},
{}
};
MODULE_DEVICE_TABLE(usb, rtl8150_table);
struct rtl8150 {
unsigned long flags;
struct usb_device *udev;
struct tasklet_struct tl;
struct net_device *netdev;
struct urb *rx_urb, *tx_urb, *intr_urb;
struct sk_buff *tx_skb, *rx_skb;
struct sk_buff *rx_skb_pool[RX_SKB_POOL_SIZE];
spinlock_t rx_pool_lock;
struct usb_ctrlrequest dr;
int intr_interval;
u8 *intr_buff;
u8 phy;
};
typedef struct rtl8150 rtl8150_t;
struct async_req {
struct usb_ctrlrequest dr;
u16 rx_creg;
};
static const char driver_name [] = "rtl8150";
/*
**
** device related part of the code
**
*/
static int get_registers(rtl8150_t * dev, u16 indx, u16 size, void *data)
{
return usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0),
RTL8150_REQ_GET_REGS, RTL8150_REQT_READ,
indx, 0, data, size, 500);
}
static int set_registers(rtl8150_t * dev, u16 indx, u16 size, void *data)
{
return usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0),
RTL8150_REQ_SET_REGS, RTL8150_REQT_WRITE,
indx, 0, data, size, 500);
}
static void async_set_reg_cb(struct urb *urb)
{
struct async_req *req = (struct async_req *)urb->context;
int status = urb->status;
if (status < 0)
dev_dbg(&urb->dev->dev, "%s failed with %d", __func__, status);
kfree(req);
usb_free_urb(urb);
}
static int async_set_registers(rtl8150_t *dev, u16 indx, u16 size, u16 reg)
{
int res = -ENOMEM;
struct urb *async_urb;
struct async_req *req;
req = kmalloc(sizeof(struct async_req), GFP_ATOMIC);
if (req == NULL)
return res;
async_urb = usb_alloc_urb(0, GFP_ATOMIC);
if (async_urb == NULL) {
kfree(req);
return res;
}
req->rx_creg = cpu_to_le16(reg);
req->dr.bRequestType = RTL8150_REQT_WRITE;
req->dr.bRequest = RTL8150_REQ_SET_REGS;
req->dr.wIndex = 0;
req->dr.wValue = cpu_to_le16(indx);
req->dr.wLength = cpu_to_le16(size);
usb_fill_control_urb(async_urb, dev->udev,
usb_sndctrlpipe(dev->udev, 0), (void *)&req->dr,
&req->rx_creg, size, async_set_reg_cb, req);
res = usb_submit_urb(async_urb, GFP_ATOMIC);
if (res) {
if (res == -ENODEV)
netif_device_detach(dev->netdev);
dev_err(&dev->udev->dev, "%s failed with %d\n", __func__, res);
}
return res;
}
static int read_mii_word(rtl8150_t * dev, u8 phy, __u8 indx, u16 * reg)
{
int i;
u8 data[3], tmp;
data[0] = phy;
data[1] = data[2] = 0;
tmp = indx | PHY_READ | PHY_GO;
i = 0;
set_registers(dev, PHYADD, sizeof(data), data);
set_registers(dev, PHYCNT, 1, &tmp);
do {
get_registers(dev, PHYCNT, 1, data);
} while ((data[0] & PHY_GO) && (i++ < MII_TIMEOUT));
if (i <= MII_TIMEOUT) {
get_registers(dev, PHYDAT, 2, data);
*reg = data[0] | (data[1] << 8);
return 0;
} else
return 1;
}
static int write_mii_word(rtl8150_t * dev, u8 phy, __u8 indx, u16 reg)
{
int i;
u8 data[3], tmp;
data[0] = phy;
data[1] = reg & 0xff;
data[2] = (reg >> 8) & 0xff;
tmp = indx | PHY_WRITE | PHY_GO;
i = 0;
set_registers(dev, PHYADD, sizeof(data), data);
set_registers(dev, PHYCNT, 1, &tmp);
do {
get_registers(dev, PHYCNT, 1, data);
} while ((data[0] & PHY_GO) && (i++ < MII_TIMEOUT));
if (i <= MII_TIMEOUT)
return 0;
else
return 1;
}
static inline void set_ethernet_addr(rtl8150_t * dev)
{
u8 node_id[6];
get_registers(dev, IDR, sizeof(node_id), node_id);
memcpy(dev->netdev->dev_addr, node_id, sizeof(node_id));
}
static int rtl8150_set_mac_address(struct net_device *netdev, void *p)
{
struct sockaddr *addr = p;
rtl8150_t *dev = netdev_priv(netdev);
if (netif_running(netdev))
return -EBUSY;
memcpy(netdev->dev_addr, addr->sa_data, netdev->addr_len);
netdev_dbg(netdev, "Setting MAC address to %pM\n", netdev->dev_addr);
/* Set the IDR registers. */
set_registers(dev, IDR, netdev->addr_len, netdev->dev_addr);
#ifdef EEPROM_WRITE
{
int i;
u8 cr;
/* Get the CR contents. */
get_registers(dev, CR, 1, &cr);
/* Set the WEPROM bit (eeprom write enable). */
cr |= 0x20;
set_registers(dev, CR, 1, &cr);
/* Write the MAC address into eeprom. Eeprom writes must be word-sized,
so we need to split them up. */
for (i = 0; i * 2 < netdev->addr_len; i++) {
set_registers(dev, IDR_EEPROM + (i * 2), 2,
netdev->dev_addr + (i * 2));
}
/* Clear the WEPROM bit (preventing accidental eeprom writes). */
cr &= 0xdf;
set_registers(dev, CR, 1, &cr);
}
#endif
return 0;
}
static int rtl8150_reset(rtl8150_t * dev)
{
u8 data = 0x10;
int i = HZ;
set_registers(dev, CR, 1, &data);
do {
get_registers(dev, CR, 1, &data);
} while ((data & 0x10) && --i);
return (i > 0) ? 1 : 0;
}
static int alloc_all_urbs(rtl8150_t * dev)
{
dev->rx_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->rx_urb)
return 0;
dev->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->tx_urb) {
usb_free_urb(dev->rx_urb);
return 0;
}
dev->intr_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->intr_urb) {
usb_free_urb(dev->rx_urb);
usb_free_urb(dev->tx_urb);
return 0;
}
return 1;
}
static void free_all_urbs(rtl8150_t * dev)
{
usb_free_urb(dev->rx_urb);
usb_free_urb(dev->tx_urb);
usb_free_urb(dev->intr_urb);
}
static void unlink_all_urbs(rtl8150_t * dev)
{
usb_kill_urb(dev->rx_urb);
usb_kill_urb(dev->tx_urb);
usb_kill_urb(dev->intr_urb);
}
static inline struct sk_buff *pull_skb(rtl8150_t *dev)
{
struct sk_buff *skb;
int i;
for (i = 0; i < RX_SKB_POOL_SIZE; i++) {
if (dev->rx_skb_pool[i]) {
skb = dev->rx_skb_pool[i];
dev->rx_skb_pool[i] = NULL;
return skb;
}
}
return NULL;
}
static void read_bulk_callback(struct urb *urb)
{
rtl8150_t *dev;
unsigned pkt_len, res;
struct sk_buff *skb;
struct net_device *netdev;
u16 rx_stat;
int status = urb->status;
int result;
dev = urb->context;
if (!dev)
return;
if (test_bit(RTL8150_UNPLUG, &dev->flags))
return;
netdev = dev->netdev;
if (!netif_device_present(netdev))
return;
switch (status) {
case 0:
break;
case -ENOENT:
return; /* the urb is in unlink state */
case -ETIME:
if (printk_ratelimit())
dev_warn(&urb->dev->dev, "may be reset is needed?..\n");
goto goon;
default:
if (printk_ratelimit())
dev_warn(&urb->dev->dev, "Rx status %d\n", status);
goto goon;
}
if (!dev->rx_skb)
goto resched;
/* protect against short packets (tell me why we got some?!?) */
if (urb->actual_length < 4)
goto goon;
res = urb->actual_length;
rx_stat = le16_to_cpu(*(__le16 *)(urb->transfer_buffer + res - 4));
pkt_len = res - 4;
skb_put(dev->rx_skb, pkt_len);
dev->rx_skb->protocol = eth_type_trans(dev->rx_skb, netdev);
netif_rx(dev->rx_skb);
netdev->stats.rx_packets++;
netdev->stats.rx_bytes += pkt_len;
spin_lock(&dev->rx_pool_lock);
skb = pull_skb(dev);
spin_unlock(&dev->rx_pool_lock);
if (!skb)
goto resched;
dev->rx_skb = skb;
goon:
usb_fill_bulk_urb(dev->rx_urb, dev->udev, usb_rcvbulkpipe(dev->udev, 1),
dev->rx_skb->data, RTL8150_MTU, read_bulk_callback, dev);
result = usb_submit_urb(dev->rx_urb, GFP_ATOMIC);
if (result == -ENODEV)
netif_device_detach(dev->netdev);
else if (result) {
set_bit(RX_URB_FAIL, &dev->flags);
goto resched;
} else {
clear_bit(RX_URB_FAIL, &dev->flags);
}
return;
resched:
tasklet_schedule(&dev->tl);
}
static void write_bulk_callback(struct urb *urb)
{
rtl8150_t *dev;
int status = urb->status;
dev = urb->context;
if (!dev)
return;
dev_kfree_skb_irq(dev->tx_skb);
if (!netif_device_present(dev->netdev))
return;
if (status)
dev_info(&urb->dev->dev, "%s: Tx status %d\n",
dev->netdev->name, status);
netif_trans_update(dev->netdev);
netif_wake_queue(dev->netdev);
}
static void intr_callback(struct urb *urb)
{
rtl8150_t *dev;
__u8 *d;
int status = urb->status;
int res;
dev = urb->context;
if (!dev)
return;
switch (status) {
case 0: /* success */
break;
case -ECONNRESET: /* unlink */
case -ENOENT:
case -ESHUTDOWN:
return;
/* -EPIPE: should clear the halt */
default:
dev_info(&urb->dev->dev, "%s: intr status %d\n",
dev->netdev->name, status);
goto resubmit;
}
d = urb->transfer_buffer;
if (d[0] & TSR_ERRORS) {
dev->netdev->stats.tx_errors++;
if (d[INT_TSR] & (TSR_ECOL | TSR_JBR))
dev->netdev->stats.tx_aborted_errors++;
if (d[INT_TSR] & TSR_LCOL)
dev->netdev->stats.tx_window_errors++;
if (d[INT_TSR] & TSR_LOSS_CRS)
dev->netdev->stats.tx_carrier_errors++;
}
/* Report link status changes to the network stack */
if ((d[INT_MSR] & MSR_LINK) == 0) {
if (netif_carrier_ok(dev->netdev)) {
netif_carrier_off(dev->netdev);
netdev_dbg(dev->netdev, "%s: LINK LOST\n", __func__);
}
} else {
if (!netif_carrier_ok(dev->netdev)) {
netif_carrier_on(dev->netdev);
netdev_dbg(dev->netdev, "%s: LINK CAME BACK\n", __func__);
}
}
resubmit:
res = usb_submit_urb (urb, GFP_ATOMIC);
if (res == -ENODEV)
netif_device_detach(dev->netdev);
else if (res)
dev_err(&dev->udev->dev,
"can't resubmit intr, %s-%s/input0, status %d\n",
dev->udev->bus->bus_name, dev->udev->devpath, res);
}
static int rtl8150_suspend(struct usb_interface *intf, pm_message_t message)
{
rtl8150_t *dev = usb_get_intfdata(intf);
netif_device_detach(dev->netdev);
if (netif_running(dev->netdev)) {
usb_kill_urb(dev->rx_urb);
usb_kill_urb(dev->intr_urb);
}
return 0;
}
static int rtl8150_resume(struct usb_interface *intf)
{
rtl8150_t *dev = usb_get_intfdata(intf);
netif_device_attach(dev->netdev);
if (netif_running(dev->netdev)) {
dev->rx_urb->status = 0;
dev->rx_urb->actual_length = 0;
read_bulk_callback(dev->rx_urb);
dev->intr_urb->status = 0;
dev->intr_urb->actual_length = 0;
intr_callback(dev->intr_urb);
}
return 0;
}
/*
**
** network related part of the code
**
*/
static void fill_skb_pool(rtl8150_t *dev)
{
struct sk_buff *skb;
int i;
for (i = 0; i < RX_SKB_POOL_SIZE; i++) {
if (dev->rx_skb_pool[i])
continue;
skb = dev_alloc_skb(RTL8150_MTU + 2);
if (!skb) {
return;
}
skb_reserve(skb, 2);
dev->rx_skb_pool[i] = skb;
}
}
static void free_skb_pool(rtl8150_t *dev)
{
int i;
for (i = 0; i < RX_SKB_POOL_SIZE; i++)
if (dev->rx_skb_pool[i])
dev_kfree_skb(dev->rx_skb_pool[i]);
}
static void rx_fixup(unsigned long data)
{
struct rtl8150 *dev = (struct rtl8150 *)data;
struct sk_buff *skb;
int status;
spin_lock_irq(&dev->rx_pool_lock);
fill_skb_pool(dev);
spin_unlock_irq(&dev->rx_pool_lock);
if (test_bit(RX_URB_FAIL, &dev->flags))
if (dev->rx_skb)
goto try_again;
spin_lock_irq(&dev->rx_pool_lock);
skb = pull_skb(dev);
spin_unlock_irq(&dev->rx_pool_lock);
if (skb == NULL)
goto tlsched;
dev->rx_skb = skb;
usb_fill_bulk_urb(dev->rx_urb, dev->udev, usb_rcvbulkpipe(dev->udev, 1),
dev->rx_skb->data, RTL8150_MTU, read_bulk_callback, dev);
try_again:
status = usb_submit_urb(dev->rx_urb, GFP_ATOMIC);
if (status == -ENODEV) {
netif_device_detach(dev->netdev);
} else if (status) {
set_bit(RX_URB_FAIL, &dev->flags);
goto tlsched;
} else {
clear_bit(RX_URB_FAIL, &dev->flags);
}
return;
tlsched:
tasklet_schedule(&dev->tl);
}
static int enable_net_traffic(rtl8150_t * dev)
{
u8 cr, tcr, rcr, msr;
if (!rtl8150_reset(dev)) {
dev_warn(&dev->udev->dev, "device reset failed\n");
}
/* RCR bit7=1 attach Rx info at the end; =0 HW CRC (which is broken) */
rcr = 0x9e;
tcr = 0xd8;
cr = 0x0c;
if (!(rcr & 0x80))
set_bit(RTL8150_HW_CRC, &dev->flags);
set_registers(dev, RCR, 1, &rcr);
set_registers(dev, TCR, 1, &tcr);
set_registers(dev, CR, 1, &cr);
get_registers(dev, MSR, 1, &msr);
return 0;
}
static void disable_net_traffic(rtl8150_t * dev)
{
u8 cr;
get_registers(dev, CR, 1, &cr);
cr &= 0xf3;
set_registers(dev, CR, 1, &cr);
}
static void rtl8150_tx_timeout(struct net_device *netdev)
{
rtl8150_t *dev = netdev_priv(netdev);
dev_warn(&netdev->dev, "Tx timeout.\n");
usb_unlink_urb(dev->tx_urb);
netdev->stats.tx_errors++;
}
static void rtl8150_set_multicast(struct net_device *netdev)
{
rtl8150_t *dev = netdev_priv(netdev);
u16 rx_creg = 0x9e;
netif_stop_queue(netdev);
if (netdev->flags & IFF_PROMISC) {
rx_creg |= 0x0001;
dev_info(&netdev->dev, "%s: promiscuous mode\n", netdev->name);
} else if (!netdev_mc_empty(netdev) ||
(netdev->flags & IFF_ALLMULTI)) {
rx_creg &= 0xfffe;
rx_creg |= 0x0002;
dev_info(&netdev->dev, "%s: allmulti set\n", netdev->name);
} else {
/* ~RX_MULTICAST, ~RX_PROMISCUOUS */
rx_creg &= 0x00fc;
}
async_set_registers(dev, RCR, sizeof(rx_creg), rx_creg);
netif_wake_queue(netdev);
}
static netdev_tx_t rtl8150_start_xmit(struct sk_buff *skb,
struct net_device *netdev)
{
rtl8150_t *dev = netdev_priv(netdev);
int count, res;
netif_stop_queue(netdev);
count = (skb->len < 60) ? 60 : skb->len;
count = (count & 0x3f) ? count : count + 1;
dev->tx_skb = skb;
usb_fill_bulk_urb(dev->tx_urb, dev->udev, usb_sndbulkpipe(dev->udev, 2),
skb->data, count, write_bulk_callback, dev);
if ((res = usb_submit_urb(dev->tx_urb, GFP_ATOMIC))) {
/* Can we get/handle EPIPE here? */
if (res == -ENODEV)
netif_device_detach(dev->netdev);
else {
dev_warn(&netdev->dev, "failed tx_urb %d\n", res);
netdev->stats.tx_errors++;
netif_start_queue(netdev);
}
} else {
netdev->stats.tx_packets++;
netdev->stats.tx_bytes += skb->len;
netif_trans_update(netdev);
}
return NETDEV_TX_OK;
}
static void set_carrier(struct net_device *netdev)
{
rtl8150_t *dev = netdev_priv(netdev);
short tmp;
get_registers(dev, CSCR, 2, &tmp);
if (tmp & CSCR_LINK_STATUS)
netif_carrier_on(netdev);
else
netif_carrier_off(netdev);
}
static int rtl8150_open(struct net_device *netdev)
{
rtl8150_t *dev = netdev_priv(netdev);
int res;
if (dev->rx_skb == NULL)
dev->rx_skb = pull_skb(dev);
if (!dev->rx_skb)
return -ENOMEM;
set_registers(dev, IDR, 6, netdev->dev_addr);
usb_fill_bulk_urb(dev->rx_urb, dev->udev, usb_rcvbulkpipe(dev->udev, 1),
dev->rx_skb->data, RTL8150_MTU, read_bulk_callback, dev);
if ((res = usb_submit_urb(dev->rx_urb, GFP_KERNEL))) {
if (res == -ENODEV)
netif_device_detach(dev->netdev);
dev_warn(&netdev->dev, "rx_urb submit failed: %d\n", res);
return res;
}
usb_fill_int_urb(dev->intr_urb, dev->udev, usb_rcvintpipe(dev->udev, 3),
dev->intr_buff, INTBUFSIZE, intr_callback,
dev, dev->intr_interval);
if ((res = usb_submit_urb(dev->intr_urb, GFP_KERNEL))) {
if (res == -ENODEV)
netif_device_detach(dev->netdev);
dev_warn(&netdev->dev, "intr_urb submit failed: %d\n", res);
usb_kill_urb(dev->rx_urb);
return res;
}
enable_net_traffic(dev);
set_carrier(netdev);
netif_start_queue(netdev);
return res;
}
static int rtl8150_close(struct net_device *netdev)
{
rtl8150_t *dev = netdev_priv(netdev);
netif_stop_queue(netdev);
if (!test_bit(RTL8150_UNPLUG, &dev->flags))
disable_net_traffic(dev);
unlink_all_urbs(dev);
return 0;
}
static void rtl8150_get_drvinfo(struct net_device *netdev, struct ethtool_drvinfo *info)
{
rtl8150_t *dev = netdev_priv(netdev);
strlcpy(info->driver, driver_name, sizeof(info->driver));
strlcpy(info->version, DRIVER_VERSION, sizeof(info->version));
usb_make_path(dev->udev, info->bus_info, sizeof(info->bus_info));
}
static int rtl8150_get_settings(struct net_device *netdev, struct ethtool_cmd *ecmd)
{
rtl8150_t *dev = netdev_priv(netdev);
short lpa, bmcr;
ecmd->supported = (SUPPORTED_10baseT_Half |
SUPPORTED_10baseT_Full |
SUPPORTED_100baseT_Half |
SUPPORTED_100baseT_Full |
SUPPORTED_Autoneg |
SUPPORTED_TP | SUPPORTED_MII);
ecmd->port = PORT_TP;
ecmd->transceiver = XCVR_INTERNAL;
ecmd->phy_address = dev->phy;
get_registers(dev, BMCR, 2, &bmcr);
get_registers(dev, ANLP, 2, &lpa);
if (bmcr & BMCR_ANENABLE) {
u32 speed = ((lpa & (LPA_100HALF | LPA_100FULL)) ?
SPEED_100 : SPEED_10);
ethtool_cmd_speed_set(ecmd, speed);
ecmd->autoneg = AUTONEG_ENABLE;
if (speed == SPEED_100)
ecmd->duplex = (lpa & LPA_100FULL) ?
DUPLEX_FULL : DUPLEX_HALF;
else
ecmd->duplex = (lpa & LPA_10FULL) ?
DUPLEX_FULL : DUPLEX_HALF;
} else {
ecmd->autoneg = AUTONEG_DISABLE;
ethtool_cmd_speed_set(ecmd, ((bmcr & BMCR_SPEED100) ?
SPEED_100 : SPEED_10));
ecmd->duplex = (bmcr & BMCR_FULLDPLX) ?
DUPLEX_FULL : DUPLEX_HALF;
}
return 0;
}
static const struct ethtool_ops ops = {
.get_drvinfo = rtl8150_get_drvinfo,
.get_settings = rtl8150_get_settings,
.get_link = ethtool_op_get_link
};
static int rtl8150_ioctl(struct net_device *netdev, struct ifreq *rq, int cmd)
{
rtl8150_t *dev = netdev_priv(netdev);
u16 *data = (u16 *) & rq->ifr_ifru;
int res = 0;
switch (cmd) {
case SIOCDEVPRIVATE:
data[0] = dev->phy;
case SIOCDEVPRIVATE + 1:
read_mii_word(dev, dev->phy, (data[1] & 0x1f), &data[3]);
break;
case SIOCDEVPRIVATE + 2:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
write_mii_word(dev, dev->phy, (data[1] & 0x1f), data[2]);
break;
default:
res = -EOPNOTSUPP;
}
return res;
}
static const struct net_device_ops rtl8150_netdev_ops = {
.ndo_open = rtl8150_open,
.ndo_stop = rtl8150_close,
.ndo_do_ioctl = rtl8150_ioctl,
.ndo_start_xmit = rtl8150_start_xmit,
.ndo_tx_timeout = rtl8150_tx_timeout,
.ndo_set_rx_mode = rtl8150_set_multicast,
.ndo_set_mac_address = rtl8150_set_mac_address,
.ndo_validate_addr = eth_validate_addr,
};
static int rtl8150_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(intf);
rtl8150_t *dev;
struct net_device *netdev;
netdev = alloc_etherdev(sizeof(rtl8150_t));
if (!netdev)
return -ENOMEM;
dev = netdev_priv(netdev);
dev->intr_buff = kmalloc(INTBUFSIZE, GFP_KERNEL);
if (!dev->intr_buff) {
free_netdev(netdev);
return -ENOMEM;
}
tasklet_init(&dev->tl, rx_fixup, (unsigned long)dev);
spin_lock_init(&dev->rx_pool_lock);
dev->udev = udev;
dev->netdev = netdev;
netdev->netdev_ops = &rtl8150_netdev_ops;
netdev->watchdog_timeo = RTL8150_TX_TIMEOUT;
netdev->ethtool_ops = &ops;
dev->intr_interval = 100; /* 100ms */
if (!alloc_all_urbs(dev)) {
dev_err(&intf->dev, "out of memory\n");
goto out;
}
if (!rtl8150_reset(dev)) {
dev_err(&intf->dev, "couldn't reset the device\n");
goto out1;
}
fill_skb_pool(dev);
set_ethernet_addr(dev);
usb_set_intfdata(intf, dev);
SET_NETDEV_DEV(netdev, &intf->dev);
if (register_netdev(netdev) != 0) {
dev_err(&intf->dev, "couldn't register the device\n");
goto out2;
}
dev_info(&intf->dev, "%s: rtl8150 is detected\n", netdev->name);
return 0;
out2:
usb_set_intfdata(intf, NULL);
free_skb_pool(dev);
out1:
free_all_urbs(dev);
out:
kfree(dev->intr_buff);
free_netdev(netdev);
return -EIO;
}
static void rtl8150_disconnect(struct usb_interface *intf)
{
rtl8150_t *dev = usb_get_intfdata(intf);
usb_set_intfdata(intf, NULL);
if (dev) {
set_bit(RTL8150_UNPLUG, &dev->flags);
tasklet_kill(&dev->tl);
unregister_netdev(dev->netdev);
unlink_all_urbs(dev);
free_all_urbs(dev);
free_skb_pool(dev);
if (dev->rx_skb)
dev_kfree_skb(dev->rx_skb);
kfree(dev->intr_buff);
free_netdev(dev->netdev);
}
}
static struct usb_driver rtl8150_driver = {
.name = driver_name,
.probe = rtl8150_probe,
.disconnect = rtl8150_disconnect,
.id_table = rtl8150_table,
.suspend = rtl8150_suspend,
.resume = rtl8150_resume,
.disable_hub_initiated_lpm = 1,
};
module_usb_driver(rtl8150_driver);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3318_0 |
crossvul-cpp_data_bad_340_4 | /*
* PKCS15 emulation layer for EstEID card.
*
* Copyright (C) 2004, Martin Paljak <martin@martinpaljak.net>
* Copyright (C) 2004, Bud P. Bruegger <bud@comune.grosseto.it>
* Copyright (C) 2004, Antonino Iacono <ant_iacono@tin.it>
* Copyright (C) 2003, Olaf Kirch <okir@suse.de>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "common/compat_strlcpy.h"
#include "common/compat_strlcat.h"
#include "internal.h"
#include "opensc.h"
#include "pkcs15.h"
#include "esteid.h"
int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *, struct sc_aid *, sc_pkcs15emu_opt_t *);
static void
set_string (char **strp, const char *value)
{
if (*strp)
free (*strp);
*strp = value ? strdup (value) : NULL;
}
int
select_esteid_df (sc_card_t * card)
{
int r;
sc_path_t tmppath;
sc_format_path ("3F00EEEE", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "esteid select DF failed");
return r;
}
static int
sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
unsigned char buff[128];
int r, i;
size_t field_length = 0, modulus_length = 0;
sc_path_t tmppath;
set_string (&p15card->tokeninfo->label, "ID-kaart");
set_string (&p15card->tokeninfo->manufacturer_id, "AS Sertifitseerimiskeskus");
/* Select application directory */
sc_format_path ("3f00eeee5044", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "select esteid PD failed");
/* read the serial (document number) */
r = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "read document number failed");
buff[r] = '\0';
set_string (&p15card->tokeninfo->serial_number, (const char *) buff);
p15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION
| SC_PKCS15_TOKEN_EID_COMPLIANT
| SC_PKCS15_TOKEN_READONLY;
/* add certificates */
for (i = 0; i < 2; i++) {
static const char *esteid_cert_names[2] = {
"Isikutuvastus",
"Allkirjastamine"};
static char const *esteid_cert_paths[2] = {
"3f00eeeeaace",
"3f00eeeeddce"};
static int esteid_cert_ids[2] = {1, 2};
struct sc_pkcs15_cert_info cert_info;
struct sc_pkcs15_object cert_obj;
memset(&cert_info, 0, sizeof(cert_info));
memset(&cert_obj, 0, sizeof(cert_obj));
cert_info.id.value[0] = esteid_cert_ids[i];
cert_info.id.len = 1;
sc_format_path(esteid_cert_paths[i], &cert_info.path);
strlcpy(cert_obj.label, esteid_cert_names[i], sizeof(cert_obj.label));
r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info);
if (r < 0)
return SC_ERROR_INTERNAL;
if (i == 0) {
sc_pkcs15_cert_t *cert = NULL;
r = sc_pkcs15_read_certificate(p15card, &cert_info, &cert);
if (r < 0)
return SC_ERROR_INTERNAL;
if (cert->key->algorithm == SC_ALGORITHM_EC)
field_length = cert->key->u.ec.params.field_length;
else
modulus_length = cert->key->u.rsa.modulus.len * 8;
if (r == SC_SUCCESS) {
static const struct sc_object_id cn_oid = {{ 2, 5, 4, 3, -1 }};
u8 *cn_name = NULL;
size_t cn_len = 0;
sc_pkcs15_get_name_from_dn(card->ctx, cert->subject,
cert->subject_len, &cn_oid, &cn_name, &cn_len);
if (cn_len > 0) {
char *token_name = malloc(cn_len+1);
if (token_name) {
memcpy(token_name, cn_name, cn_len);
token_name[cn_len] = '\0';
set_string(&p15card->tokeninfo->label, (const char*)token_name);
free(token_name);
}
}
free(cn_name);
sc_pkcs15_free_certificate(cert);
}
}
}
/* the file with key pin info (tries left) */
sc_format_path ("3f000016", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
if (r < 0)
return SC_ERROR_INTERNAL;
/* add pins */
for (i = 0; i < 3; i++) {
unsigned char tries_left;
static const char *esteid_pin_names[3] = {
"PIN1",
"PIN2",
"PUK" };
static const int esteid_pin_min[3] = {4, 5, 8};
static const int esteid_pin_ref[3] = {1, 2, 0};
static const int esteid_pin_authid[3] = {1, 2, 3};
static const int esteid_pin_flags[3] = {0, 0, SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN};
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
/* read the number of tries left for the PIN */
r = sc_read_record (card, i + 1, buff, sizeof(buff), SC_RECORD_BY_REC_NR);
if (r < 0)
return SC_ERROR_INTERNAL;
tries_left = buff[5];
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = esteid_pin_authid[i];
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = esteid_pin_ref[i];
pin_info.attrs.pin.flags = esteid_pin_flags[i];
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = esteid_pin_min[i];
pin_info.attrs.pin.stored_length = 12;
pin_info.attrs.pin.max_length = 12;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = (int)tries_left;
pin_info.max_tries = 3;
strlcpy(pin_obj.label, esteid_pin_names[i], sizeof(pin_obj.label));
pin_obj.flags = esteid_pin_flags[i];
/* Link normal PINs with PUK */
if (i < 2) {
pin_obj.auth_id.len = 1;
pin_obj.auth_id.value[0] = 3;
}
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
return SC_ERROR_INTERNAL;
}
/* add private keys */
for (i = 0; i < 2; i++) {
static int prkey_pin[2] = {1, 2};
static const char *prkey_name[2] = {
"Isikutuvastus",
"Allkirjastamine"};
struct sc_pkcs15_prkey_info prkey_info;
struct sc_pkcs15_object prkey_obj;
memset(&prkey_info, 0, sizeof(prkey_info));
memset(&prkey_obj, 0, sizeof(prkey_obj));
prkey_info.id.len = 1;
prkey_info.id.value[0] = prkey_pin[i];
prkey_info.native = 1;
prkey_info.key_reference = i + 1;
prkey_info.field_length = field_length;
prkey_info.modulus_length = modulus_length;
if (i == 1)
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_NONREPUDIATION;
else if(field_length > 0) // ECC has sign and derive usage
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_DERIVE;
else
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_DECRYPT;
strlcpy(prkey_obj.label, prkey_name[i], sizeof(prkey_obj.label));
prkey_obj.auth_id.len = 1;
prkey_obj.auth_id.value[0] = prkey_pin[i];
prkey_obj.user_consent = 0;
prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
if(field_length > 0)
r = sc_pkcs15emu_add_ec_prkey(p15card, &prkey_obj, &prkey_info);
else
r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info);
if (r < 0)
return SC_ERROR_INTERNAL;
}
return SC_SUCCESS;
}
static int esteid_detect_card(sc_pkcs15_card_t *p15card)
{
if (is_esteid_card(p15card->card))
return SC_SUCCESS;
else
return SC_ERROR_WRONG_CARD;
}
int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *p15card,
struct sc_aid *aid,
sc_pkcs15emu_opt_t *opts)
{
if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)
return sc_pkcs15emu_esteid_init(p15card);
else {
int r = esteid_detect_card(p15card);
if (r)
return SC_ERROR_WRONG_CARD;
return sc_pkcs15emu_esteid_init(p15card);
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_340_4 |
crossvul-cpp_data_good_1359_1 | /**
* @file tree_data.c
* @author Radek Krejci <rkrejci@cesnet.cz>
* @brief Manipulation with libyang data structures
*
* Copyright (c) 2015 - 2018 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*/
#define _GNU_SOURCE
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <stdarg.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include "libyang.h"
#include "common.h"
#include "context.h"
#include "tree_data.h"
#include "parser.h"
#include "resolve.h"
#include "xml_internal.h"
#include "tree_internal.h"
#include "validation.h"
#include "xpath.h"
static struct lys_node *lyd_get_schema_inctx(const struct lyd_node *node, struct ly_ctx *ctx);
static int
lyd_anydata_equal(struct lyd_node *first, struct lyd_node *second)
{
char *str1 = NULL, *str2 = NULL;
struct lyd_node_anydata *anydata;
assert(first->schema->nodetype & LYS_ANYDATA);
assert(first->schema->nodetype == second->schema->nodetype);
anydata = (struct lyd_node_anydata *)first;
if (!anydata->value.str) {
lyxml_print_mem(&str1, anydata->value.xml, LYXML_PRINT_SIBLINGS);
anydata->value.str = lydict_insert_zc(anydata->schema->module->ctx, str1);
}
str1 = (char *)anydata->value.str;
anydata = (struct lyd_node_anydata *)second;
if (!anydata->value.str) {
lyxml_print_mem(&str2, anydata->value.xml, LYXML_PRINT_SIBLINGS);
anydata->value.str = lydict_insert_zc(anydata->schema->module->ctx, str2);
}
str2 = (char *)anydata->value.str;
if (first->schema->module->ctx != second->schema->module->ctx) {
return ly_strequal(str1, str2, 0);
} else {
return ly_strequal(str1, str2, 1);
}
}
/* used in tests */
int
lyd_list_has_keys(struct lyd_node *list)
{
struct lyd_node *iter;
struct lys_node_list *slist;
int i;
assert(list->schema->nodetype == LYS_LIST);
/* even though hash is 0, it may be a valid hash, that is what we are going to check */
slist = (struct lys_node_list *)list->schema;
if (!slist->keys_size) {
/* always has keys */
return 1;
}
i = 0;
iter = list->child;
while (iter && (i < slist->keys_size)) {
if (iter->schema != (struct lys_node *)slist->keys[i]) {
/* missing key */
return 0;
}
++i;
iter = iter->next;
}
if (i < slist->keys_size) {
/* missing key */
return 0;
}
/* all keys found */
return 1;
}
static int
lyd_leaf_val_equal(struct lyd_node *node1, struct lyd_node *node2, int diff_ctx)
{
assert(node1->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST));
assert(node1->schema->nodetype == node2->schema->nodetype);
if (diff_ctx) {
return ly_strequal(((struct lyd_node_leaf_list *)node1)->value_str, ((struct lyd_node_leaf_list *)node2)->value_str, 0);
} else {
return ly_strequal(((struct lyd_node_leaf_list *)node1)->value_str, ((struct lyd_node_leaf_list *)node2)->value_str, 1);
}
}
/*
* withdefaults (only for leaf-list):
* 0 - treat default nodes are normal nodes
* 1 - only change is that if 2 nodes have the same value, but one is default, the other not, they are considered non-equal
*/
int
lyd_list_equal(struct lyd_node *node1, struct lyd_node *node2, int with_defaults)
{
int i, diff_ctx;
struct lyd_node *elem1, *next1, *elem2, *next2;
struct lys_node *elem1_sch;
struct ly_ctx *ctx = node2->schema->module->ctx;
diff_ctx = (node1->schema->module->ctx != node2->schema->module->ctx);
switch (node2->schema->nodetype) {
case LYS_LEAFLIST:
if (lyd_leaf_val_equal(node1, node2, diff_ctx) && (!with_defaults || (node1->dflt == node2->dflt))) {
return 1;
}
break;
case LYS_LIST:
if (((struct lys_node_list *)node1->schema)->keys_size) {
/* lists with keys, their equivalence isb ased on their keys */
elem1 = node1->child;
elem2 = node2->child;
elem1_sch = NULL;
/* the exact data order is guaranteed */
for (i = 0; i < ((struct lys_node_list *)node1->schema)->keys_size; ++i) {
if (diff_ctx && elem1) {
/* we have different contexts */
if (!elem1_sch) {
elem1_sch = lyd_get_schema_inctx(elem1, ctx);
if (!elem1_sch) {
LOGERR(ctx, LY_EINVAL, "Target context does not contain a required schema node (%s:%s).",
lyd_node_module(elem1)->name, elem1->schema->name);
return -1;
}
} else {
/* just move to the next schema node */
elem1_sch = elem1_sch->next;
}
}
if (!elem1 || !elem2 || ((elem1_sch ? elem1_sch : elem1->schema) != elem2->schema)
|| !lyd_leaf_val_equal(elem1, elem2, diff_ctx)) {
break;
}
elem1 = elem1->next;
elem2 = elem2->next;
}
if (i == ((struct lys_node_list *)node1->schema)->keys_size) {
return 1;
}
} else {
/* lists wihtout keys, their equivalence is based on values of all the children (both dierct and indirect) */
if (!node1->child && !node2->child) {
/* no children, nothing to compare */
return 1;
}
/* status lists without keys, we need to compare all the children :( */
/* LY_TREE_DFS_BEGIN for 2 data trees */
elem1 = next1 = node1->child;
elem2 = next2 = node2->child;
while (elem1 && elem2) {
/* node comparison */
#ifdef LY_ENABLED_CACHE
if (elem1->hash != elem2->hash) {
break;
}
#endif
if (diff_ctx) {
elem1_sch = lyd_get_schema_inctx(elem1, ctx);
if (!elem1_sch) {
LOGERR(ctx, LY_EINVAL, "Target context does not contain a required schema node (%s:%s).",
lyd_node_module(elem1)->name, elem1->schema->name);
return -1;
}
} else {
elem1_sch = elem1->schema;
}
if (elem1_sch != elem2->schema) {
break;
}
if (elem2->schema->nodetype == LYS_LIST) {
if (!lyd_list_has_keys(elem1) && !lyd_list_has_keys(elem2)) {
/* we encountered lists without keys (but have some defined in schema), ignore them for comparison */
next1 = NULL;
next2 = NULL;
goto next_sibling;
}
/* we will compare all the children of this list instance, not just keys */
} else if (elem2->schema->nodetype & (LYS_LEAFLIST | LYS_LEAF)) {
if (!lyd_leaf_val_equal(elem1, elem2, diff_ctx) && (!with_defaults || (elem1->dflt == elem2->dflt))) {
break;
}
} else if (elem2->schema->nodetype & LYS_ANYDATA) {
if (!lyd_anydata_equal(elem1, elem2)) {
break;
}
}
/* LY_TREE_DFS_END for 2 data trees */
if (elem2->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
next1 = NULL;
next2 = NULL;
} else {
next1 = elem1->child;
next2 = elem2->child;
}
next_sibling:
if (!next1) {
next1 = elem1->next;
}
if (!next2) {
next2 = elem2->next;
}
while (!next1) {
elem1 = elem1->parent;
if (elem1 == node1) {
break;
}
next1 = elem1->next;
}
while (!next2) {
elem2 = elem2->parent;
if (elem2 == node2) {
break;
}
next2 = elem2->next;
}
elem1 = next1;
elem2 = next2;
}
if (!elem1 && !elem2) {
/* all children were successfully compared */
return 1;
}
}
break;
default:
LOGINT(ctx);
return -1;
}
return 0;
}
#ifdef LY_ENABLED_CACHE
static int
lyd_hash_table_val_equal(void *val1_p, void *val2_p, int mod, void *UNUSED(cb_data))
{
struct lyd_node *val1, *val2;
val1 = *((struct lyd_node **)val1_p);
val2 = *((struct lyd_node **)val2_p);
if (mod) {
if (val1 == val2) {
return 1;
} else {
return 0;
}
}
if (val1->schema != val2->schema) {
return 0;
}
switch (val1->schema->nodetype) {
case LYS_CONTAINER:
case LYS_LEAF:
case LYS_ANYXML:
case LYS_ANYDATA:
return 1;
case LYS_LEAFLIST:
case LYS_LIST:
return lyd_list_equal(val1, val2, 0);
default:
break;
}
LOGINT(val1->schema->module->ctx);
return 0;
}
static void
lyd_hash_keyless_list_dfs(struct lyd_node *child, uint32_t *hash)
{
LY_TREE_FOR(child, child) {
switch (child->schema->nodetype) {
case LYS_CONTAINER:
lyd_hash_keyless_list_dfs(child->child, hash);
break;
case LYS_LIST:
/* ignore lists with missing keys */
if (lyd_list_has_keys(child)) {
lyd_hash_keyless_list_dfs(child->child, hash);
}
break;
case LYS_LEAFLIST:
case LYS_ANYXML:
case LYS_ANYDATA:
case LYS_LEAF:
*hash = dict_hash_multi(*hash, (char *)&child->hash, sizeof child->hash);
break;
default:
assert(0);
}
}
}
int
lyd_hash(struct lyd_node *node)
{
struct lyd_node *iter;
int i;
assert(!node->hash || ((node->schema->nodetype == LYS_LIST) && !((struct lys_node_list *)node->schema)->keys_size));
if ((node->schema->nodetype != LYS_LIST) || lyd_list_has_keys(node)) {
node->hash = dict_hash_multi(0, lyd_node_module(node)->name, strlen(lyd_node_module(node)->name));
node->hash = dict_hash_multi(node->hash, node->schema->name, strlen(node->schema->name));
if (node->schema->nodetype == LYS_LEAFLIST) {
node->hash = dict_hash_multi(node->hash, ((struct lyd_node_leaf_list *)node)->value_str,
strlen(((struct lyd_node_leaf_list *)node)->value_str));
} else if (node->schema->nodetype == LYS_LIST) {
if (((struct lys_node_list *)node->schema)->keys_size) {
for (i = 0, iter = node->child; i < ((struct lys_node_list *)node->schema)->keys_size; ++i, iter = iter->next) {
assert(iter);
node->hash = dict_hash_multi(node->hash, ((struct lyd_node_leaf_list *)iter)->value_str,
strlen(((struct lyd_node_leaf_list *)iter)->value_str));
}
} else {
/* no-keys list */
lyd_hash_keyless_list_dfs(node->child, &node->hash);
}
}
node->hash = dict_hash_multi(node->hash, NULL, 0);
return 0;
}
return 1;
}
static void
lyd_keyless_list_hash_change(struct lyd_node *parent)
{
int r;
while (parent && (parent->schema->flags & LYS_CONFIG_R)) {
if (parent->schema->nodetype == LYS_LIST) {
if (!((struct lys_node_list *)parent->schema)->keys_size) {
if (parent->parent && parent->parent->ht) {
/* remove the list from the parent */
r = lyht_remove(parent->parent->ht, &parent, parent->hash);
assert(!r);
(void)r;
}
/* recalculate the hash */
lyd_hash(parent);
if (parent->parent && parent->parent->ht) {
/* re-add the list again */
r = lyht_insert(parent->parent->ht, &parent, parent->hash, NULL);
assert(!r);
(void)r;
}
} else if (!lyd_list_has_keys(parent)) {
/* a parent is a list without keys so it cannot be a part of any parent hash */
break;
}
}
parent = parent->parent;
}
}
static void
_lyd_insert_hash(struct lyd_node *node, int keyless_list_check)
{
struct lyd_node *iter;
int i;
if (node->parent) {
if ((node->schema->nodetype != LYS_LIST) || lyd_list_has_keys(node)) {
if ((node->schema->nodetype == LYS_LEAF) && lys_is_key((struct lys_node_leaf *)node->schema, NULL)) {
/* we are adding a key which means that it may be the last missing key for our parent's hash */
if (!lyd_hash(node->parent)) {
/* yep, we successfully hashed node->parent so it is technically now added to its parent (hash-wise) */
_lyd_insert_hash(node->parent, 0);
}
}
/* create parent hash table if required, otherwise just add the new child */
if (!node->parent->ht) {
for (i = 0, iter = node->parent->child; iter; ++i, iter = iter->next) {
if ((iter->schema->nodetype == LYS_LIST) && !lyd_list_has_keys(iter)) {
/* it will either never have keys and will never be hashed or has not all keys created yet */
--i;
}
}
assert(i <= LY_CACHE_HT_MIN_CHILDREN);
if (i == LY_CACHE_HT_MIN_CHILDREN) {
/* create hash table, insert all the children */
node->parent->ht = lyht_new(1, sizeof(struct lyd_node *), lyd_hash_table_val_equal, NULL, 1);
LY_TREE_FOR(node->parent->child, iter) {
if ((iter->schema->nodetype == LYS_LIST) && !lyd_list_has_keys(iter)) {
/* skip lists without keys */
continue;
}
if (lyht_insert(node->parent->ht, &iter, iter->hash, NULL)) {
assert(0);
}
}
}
} else {
if (lyht_insert(node->parent->ht, &node, node->hash, NULL)) {
assert(0);
}
}
/* if node was in a state data subtree, wasn't it a part of a key-less list hash? */
if (keyless_list_check) {
lyd_keyless_list_hash_change(node->parent);
}
}
}
}
/* we have inserted node into a parent */
void
lyd_insert_hash(struct lyd_node *node)
{
_lyd_insert_hash(node, 1);
}
static void
_lyd_unlink_hash(struct lyd_node *node, struct lyd_node *orig_parent, int keyless_list_check)
{
#ifndef NDEBUG
struct lyd_node *iter;
/* it must already be unlinked otherwise keyless lists would get wrong hash */
if (keyless_list_check && orig_parent) {
LY_TREE_FOR(orig_parent->child, iter) {
assert(iter != node);
}
}
#endif
if (orig_parent) {
if ((node->schema->nodetype != LYS_LIST) || lyd_list_has_keys(node)) {
if (orig_parent->ht) {
if (lyht_remove(orig_parent->ht, &node, node->hash)) {
assert(0);
}
/* if no longer enough children, free the whole hash table */
if (orig_parent->ht->used < LY_CACHE_HT_MIN_CHILDREN) {
lyht_free(orig_parent->ht);
orig_parent->ht = NULL;
}
}
/* if the parent is missing a key now, remove hash, also from parent */
if (lys_is_key((struct lys_node_leaf *)node->schema, NULL) && orig_parent->hash) {
assert((orig_parent->schema->nodetype == LYS_LIST) && !lyd_list_has_keys(orig_parent));
_lyd_unlink_hash(orig_parent, orig_parent->parent, 0);
orig_parent->hash = 0;
}
/* if node was in a state data subtree, shouldn't it be a part of a key-less list hash? */
if (keyless_list_check) {
lyd_keyless_list_hash_change(orig_parent);
}
}
}
}
/* we are unlinking a child from a parent */
void
lyd_unlink_hash(struct lyd_node *node, struct lyd_node *orig_parent)
{
_lyd_unlink_hash(node, orig_parent, 1);
}
#endif
/**
* @brief get the list of \p data's siblings of the given schema
*/
static int
lyd_get_node_siblings(const struct lyd_node *data, const struct lys_node *schema, struct ly_set *set)
{
const struct lyd_node *iter;
assert(set && !set->number);
assert(schema);
assert(schema->nodetype & (LYS_CONTAINER | LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_ANYDATA | LYS_NOTIF | LYS_RPC |
LYS_ACTION));
if (!data) {
return 0;
}
LY_TREE_FOR(data, iter) {
if (iter->schema == schema) {
ly_set_add(set, (void*)iter, LY_SET_OPT_USEASLIST);
}
}
return set->number;
}
/**
* Check whether there are any "when" statements on a \p schema node and evaluate them.
*
* @return -1 on error, 0 on no when or evaluated to true, 1 on when evaluated to false
*/
static int
lyd_is_when_false(struct lyd_node *root, struct lyd_node *last_parent, struct lys_node *schema, int options)
{
enum int_log_opts prev_ilo;
struct lyd_node *current, *dummy;
if ((!(options & LYD_OPT_TYPEMASK) || (options & (LYD_OPT_CONFIG | LYD_OPT_RPC | LYD_OPT_RPCREPLY | LYD_OPT_NOTIF | LYD_OPT_DATA_TEMPLATE)))
&& resolve_applies_when(schema, 1, last_parent ? last_parent->schema : NULL)) {
/* evaluate when statements on a dummy data node */
if (schema->nodetype == LYS_CHOICE) {
schema = (struct lys_node *)lys_getnext(NULL, schema, NULL, LYS_GETNEXT_NOSTATECHECK);
}
dummy = lyd_new_dummy(root, last_parent, schema, NULL, 0);
if (!dummy) {
return -1;
}
if (!dummy->parent && root) {
/* connect dummy nodes into the data tree, insert it before the root
* to optimize later unlinking (lyd_free()) */
lyd_insert_before(root, dummy);
}
for (current = dummy; current; current = current->child) {
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
resolve_when(current, 0, NULL);
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (current->when_status & LYD_WHEN_FALSE) {
/* when evaluates to false */
lyd_free(dummy);
return 1;
}
if (current->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
/* termination node without a child */
break;
}
}
lyd_free(dummy);
}
return 0;
}
/**
* @param[in] root Root node to be able search the data tree in case of no instance
* @return
* 0 - all restrictions met
* 1 - restrictions not met
* 2 - schema node not enabled
*/
static int
lyd_check_mandatory_data(struct lyd_node *root, struct lyd_node *last_parent,
struct ly_set *instances, struct lys_node *schema, int options)
{
struct ly_ctx *ctx = schema->module->ctx;
uint32_t limit;
uint16_t status;
if (!instances->number) {
/* no instance in the data tree - check if the instantiating is enabled
* (check: if-feature, when, status data in non-status data tree)
*/
status = (schema->flags & LYS_STATUS_MASK);
if (lys_is_disabled(schema, 2) || (status && status != LYS_STATUS_CURR)) {
/* disabled by if-feature */
return EXIT_SUCCESS;
} else if ((options & LYD_OPT_TRUSTED) || ((options & LYD_OPT_TYPEMASK) && (schema->flags & LYS_CONFIG_R))) {
/* status schema node in non-status data tree */
return EXIT_SUCCESS;
} else if (lyd_is_when_false(root, last_parent, schema, options)) {
return EXIT_SUCCESS;
}
/* the schema instance is not disabled by anything, continue with checking */
}
/* checking various mandatory conditions */
switch (schema->nodetype) {
case LYS_LEAF:
case LYS_ANYXML:
case LYS_ANYDATA:
/* mandatory */
if ((schema->flags & LYS_MAND_TRUE) && !instances->number) {
LOGVAL(ctx, LYE_MISSELEM, LY_VLOG_LYD, last_parent, schema->name,
last_parent ? last_parent->schema->name : lys_node_module(schema)->name);
return EXIT_FAILURE;
}
break;
case LYS_LIST:
/* min-elements */
limit = ((struct lys_node_list *)schema)->min;
if (limit && limit > instances->number) {
LOGVAL(ctx, LYE_NOMIN, LY_VLOG_LYD, last_parent, schema->name);
return EXIT_FAILURE;
}
/* max elements */
limit = ((struct lys_node_list *)schema)->max;
if (limit && limit < instances->number) {
LOGVAL(ctx, LYE_NOMAX, LY_VLOG_LYD, instances->set.d[limit], schema->name);
return EXIT_FAILURE;
}
break;
case LYS_LEAFLIST:
/* min-elements */
limit = ((struct lys_node_leaflist *)schema)->min;
if (limit && limit > instances->number) {
LOGVAL(ctx, LYE_NOMIN, LY_VLOG_LYD, last_parent, schema->name);
return EXIT_FAILURE;
}
/* max elements */
limit = ((struct lys_node_leaflist *)schema)->max;
if (limit && limit < instances->number) {
LOGVAL(ctx, LYE_NOMAX, LY_VLOG_LYD, instances->set.d[limit], schema->name);
return EXIT_FAILURE;
}
break;
default:
/* we cannot get here */
assert(0);
break;
}
return EXIT_SUCCESS;
}
/**
* @brief Check the specific subtree, specified by \p schema node, for presence of mandatory nodes. Function goes
* recursively into the subtree.
*
* What is being checked:
* - mandatory statement in leaf, choice, anyxml and anydata
* - min-elements and max-elements in list and leaf-list
*
* @param[in] tree Data tree, needed for case that subtree is NULL (in case of not existing data nodes to explore)
* @param[in] subtree Depend ons \p toplevel flag:
* toplevel = 1, then subtree is ignored, instead the tree is taken to search in top level data elements (if any)
* toplevel = 0, subtree is the parent data node of the possible instances of the schema node being checked
* @param[in] last_parent The last present parent data node (so it does not need to be a direct parent) of the possible
* instances of the schema node being checked
* @param[in] schema The schema node being checked for mandatory nodes
* @param[in] toplevel, see the \p root parameter description
* @param[in] options @ref parseroptions to specify the type of the data tree.
* @return EXIT_SUCCESS or EXIT_FAILURE if there are missing mandatory nodes
*/
static int
lyd_check_mandatory_subtree(struct lyd_node *tree, struct lyd_node *subtree, struct lyd_node *last_parent,
struct lys_node *schema, int toplevel, int options)
{
struct lys_node *siter, *siter_prev;
struct lyd_node *iter;
struct ly_set *present = NULL;
unsigned int u;
int ret = EXIT_FAILURE;
assert(schema);
if (schema->nodetype & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_ANYDATA | LYS_CONTAINER)) {
/* data node */
present = ly_set_new();
if (!present) {
goto error;
}
if ((toplevel && tree) || (!toplevel && subtree)) {
if (toplevel) {
lyd_get_node_siblings(tree, schema, present);
} else {
lyd_get_node_siblings(subtree->child, schema, present);
}
}
}
switch (schema->nodetype) {
case LYS_LEAF:
case LYS_LEAFLIST:
case LYS_ANYXML:
case LYS_ANYDATA:
/* check the schema item */
if (lyd_check_mandatory_data(tree, last_parent, present, schema, options)) {
goto error;
}
break;
case LYS_LIST:
/* check the schema item */
if (lyd_check_mandatory_data(tree, last_parent, present, schema, options)) {
goto error;
}
/* go recursively */
for (u = 0; u < present->number; u++) {
LY_TREE_FOR(schema->child, siter) {
if (lyd_check_mandatory_subtree(tree, present->set.d[u], present->set.d[u], siter, 0, options)) {
goto error;
}
}
}
break;
case LYS_CONTAINER:
if (present->number || !((struct lys_node_container *)schema)->presence) {
/* if we have existing or non-presence container, go recursively */
LY_TREE_FOR(schema->child, siter) {
if (lyd_check_mandatory_subtree(tree, present->number ? present->set.d[0] : NULL,
present->number ? present->set.d[0] : last_parent,
siter, 0, options)) {
goto error;
}
}
}
break;
case LYS_CHOICE:
/* get existing node in the data tree from the choice */
iter = NULL;
if ((toplevel && tree) || (!toplevel && subtree)) {
LY_TREE_FOR(toplevel ? tree : subtree->child, iter) {
for (siter = lys_parent(iter->schema), siter_prev = iter->schema;
siter && (siter->nodetype & (LYS_CASE | LYS_USES | LYS_CHOICE));
siter_prev = siter, siter = lys_parent(siter)) {
if (siter == schema) {
/* we have the choice instance */
break;
}
}
if (siter == schema) {
/* we have the choice instance;
* the condition must be the same as in the loop because of
* choice's sibling nodes that break the loop, so siter is not NULL,
* but it is not the same as schema */
break;
}
}
}
if (!iter) {
if (lyd_is_when_false(tree, last_parent, schema, options)) {
/* nothing to check */
break;
}
if (((struct lys_node_choice *)schema)->dflt) {
/* there is a default case */
if (lyd_check_mandatory_subtree(tree, subtree, last_parent, ((struct lys_node_choice *)schema)->dflt,
toplevel, options)) {
goto error;
}
} else if (schema->flags & LYS_MAND_TRUE) {
/* choice requires some data to be instantiated */
LOGVAL(schema->module->ctx, LYE_NOMANDCHOICE, LY_VLOG_LYD, last_parent, schema->name);
goto error;
}
} else {
/* one of the choice's cases is instantiated, continue into this case */
/* since iter != NULL, siter must be also != NULL and we also know siter_prev
* which points to the child of schema leading towards the instantiated data */
assert(siter && siter_prev);
if (lyd_check_mandatory_subtree(tree, subtree, last_parent, siter_prev, toplevel, options)) {
goto error;
}
}
break;
case LYS_NOTIF:
/* skip if validating a notification */
if (!(options & LYD_OPT_NOTIF)) {
break;
}
/* fallthrough */
case LYS_CASE:
case LYS_USES:
case LYS_INPUT:
case LYS_OUTPUT:
/* go recursively */
LY_TREE_FOR(schema->child, siter) {
if (lyd_check_mandatory_subtree(tree, subtree, last_parent, siter, toplevel, options)) {
goto error;
}
}
break;
default:
/* stop */
break;
}
ret = EXIT_SUCCESS;
error:
ly_set_free(present);
return ret;
}
int
lyd_check_mandatory_tree(struct lyd_node *root, struct ly_ctx *ctx, const struct lys_module **modules, int mod_count,
int options)
{
struct lys_node *siter;
int i;
assert(root || ctx);
assert(!(options & LYD_OPT_ACT_NOTIF));
if (options & (LYD_OPT_EDIT | LYD_OPT_GET | LYD_OPT_GETCONFIG)) {
/* no check is needed */
return EXIT_SUCCESS;
}
if (!ctx) {
/* get context */
ctx = root->schema->module->ctx;
}
if (!(options & LYD_OPT_TYPEMASK) || (options & LYD_OPT_CONFIG)) {
if (options & LYD_OPT_NOSIBLINGS) {
if (root && lyd_check_mandatory_subtree(root, NULL, NULL, root->schema, 1, options)) {
return EXIT_FAILURE;
}
} else if (modules && mod_count) {
for (i = 0; i < mod_count; ++i) {
LY_TREE_FOR(modules[i]->data, siter) {
if (!(siter->nodetype & (LYS_RPC | LYS_NOTIF)) &&
lyd_check_mandatory_subtree(root, NULL, NULL, siter, 1, options)) {
return EXIT_FAILURE;
}
}
}
} else {
for (i = (options & LYD_OPT_DATA_NO_YANGLIB) ? ctx->internal_module_count : ctx->internal_module_count - 1;
i < ctx->models.used;
i++) {
/* skip not implemented and disabled modules */
if (!ctx->models.list[i]->implemented || ctx->models.list[i]->disabled) {
continue;
}
LY_TREE_FOR(ctx->models.list[i]->data, siter) {
if (!(siter->nodetype & (LYS_RPC | LYS_NOTIF)) &&
lyd_check_mandatory_subtree(root, NULL, NULL, siter, 1, options)) {
return EXIT_FAILURE;
}
}
}
}
} else if (options & LYD_OPT_NOTIF) {
if (!root || (root->schema->nodetype != LYS_NOTIF)) {
LOGERR(ctx, LY_EINVAL, "Subtree is not a single notification.");
return EXIT_FAILURE;
}
if (root->schema->child && lyd_check_mandatory_subtree(root, root, root, root->schema, 0, options)) {
return EXIT_FAILURE;
}
} else if (options & (LYD_OPT_RPC | LYD_OPT_RPCREPLY)) {
if (!root || !(root->schema->nodetype & (LYS_RPC | LYS_ACTION))) {
LOGERR(ctx, LY_EINVAL, "Subtree is not a single RPC/action/reply.");
return EXIT_FAILURE;
}
if (options & LYD_OPT_RPC) {
for (siter = root->schema->child; siter && siter->nodetype != LYS_INPUT; siter = siter->next);
} else { /* LYD_OPT_RPCREPLY */
for (siter = root->schema->child; siter && siter->nodetype != LYS_OUTPUT; siter = siter->next);
}
if (siter && lyd_check_mandatory_subtree(root, root, root, siter, 0, options)) {
return EXIT_FAILURE;
}
} else if (options & LYD_OPT_DATA_TEMPLATE) {
if (root && lyd_check_mandatory_subtree(root, NULL, NULL, root->schema, 1, options)) {
return EXIT_FAILURE;
}
} else {
LOGINT(ctx);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
static struct lyd_node *
lyd_parse_(struct ly_ctx *ctx, const struct lyd_node *rpc_act, const char *data, LYD_FORMAT format, int options,
const struct lyd_node *data_tree, const char *yang_data_name)
{
struct lyxml_elem *xml;
struct lyd_node *result = NULL;
int xmlopt = LYXML_PARSE_MULTIROOT;
if (!ctx || !data) {
LOGARG;
return NULL;
}
if (options & LYD_OPT_NOSIBLINGS) {
xmlopt = 0;
}
/* we must free all the errors, otherwise we are unable to properly check returned ly_errno :-/ */
ly_errno = LY_SUCCESS;
switch (format) {
case LYD_XML:
xml = lyxml_parse_mem(ctx, data, xmlopt);
if (ly_errno) {
break;
}
if (options & LYD_OPT_RPCREPLY) {
result = lyd_parse_xml(ctx, &xml, options, rpc_act, data_tree);
} else if (options & (LYD_OPT_RPC | LYD_OPT_NOTIF)) {
result = lyd_parse_xml(ctx, &xml, options, data_tree);
} else if (options & LYD_OPT_DATA_TEMPLATE) {
result = lyd_parse_xml(ctx, &xml, options, yang_data_name);
} else {
result = lyd_parse_xml(ctx, &xml, options);
}
lyxml_free_withsiblings(ctx, xml);
break;
case LYD_JSON:
result = lyd_parse_json(ctx, data, options, rpc_act, data_tree, yang_data_name);
break;
case LYD_LYB:
result = lyd_parse_lyb(ctx, data, options, data_tree, yang_data_name, NULL);
break;
default:
/* error */
break;
}
if (ly_errno) {
lyd_free_withsiblings(result);
return NULL;
} else {
return result;
}
}
static struct lyd_node *
lyd_parse_data_(struct ly_ctx *ctx, const char *data, LYD_FORMAT format, int options, va_list ap)
{
const struct lyd_node *rpc_act = NULL, *data_tree = NULL, *iter;
const char *yang_data_name = NULL;
if (lyp_data_check_options(ctx, options, __func__)) {
return NULL;
}
if (options & LYD_OPT_RPCREPLY) {
rpc_act = va_arg(ap, const struct lyd_node *);
if (!rpc_act || rpc_act->parent || !(rpc_act->schema->nodetype & (LYS_RPC | LYS_LIST | LYS_CONTAINER))) {
LOGERR(ctx, LY_EINVAL, "%s: invalid variable parameter (const struct lyd_node *rpc_act).", __func__);
return NULL;
}
}
if (options & (LYD_OPT_RPC | LYD_OPT_NOTIF | LYD_OPT_RPCREPLY)) {
data_tree = va_arg(ap, const struct lyd_node *);
if (data_tree) {
if (options & LYD_OPT_NOEXTDEPS) {
LOGERR(ctx, LY_EINVAL, "%s: invalid parameter (variable arg const struct lyd_node *data_tree and LYD_OPT_NOEXTDEPS set).",
__func__);
return NULL;
}
LY_TREE_FOR(data_tree, iter) {
if (iter->parent) {
/* a sibling is not top-level */
LOGERR(ctx, LY_EINVAL, "%s: invalid variable parameter (const struct lyd_node *data_tree).", __func__);
return NULL;
}
}
/* move it to the beginning */
for (; data_tree->prev->next; data_tree = data_tree->prev);
/* LYD_OPT_NOSIBLINGS cannot be set in this case */
if (options & LYD_OPT_NOSIBLINGS) {
LOGERR(ctx, LY_EINVAL, "%s: invalid parameter (variable arg const struct lyd_node *data_tree with LYD_OPT_NOSIBLINGS).", __func__);
return NULL;
}
}
}
if (options & LYD_OPT_DATA_TEMPLATE) {
yang_data_name = va_arg(ap, const char *);
}
return lyd_parse_(ctx, rpc_act, data, format, options, data_tree, yang_data_name);
}
API struct lyd_node *
lyd_parse_mem(struct ly_ctx *ctx, const char *data, LYD_FORMAT format, int options, ...)
{
va_list ap;
struct lyd_node *result;
va_start(ap, options);
result = lyd_parse_data_(ctx, data, format, options, ap);
va_end(ap);
return result;
}
static struct lyd_node *
lyd_parse_fd_(struct ly_ctx *ctx, int fd, LYD_FORMAT format, int options, va_list ap)
{
struct lyd_node *ret;
size_t length;
char *data;
if (!ctx || (fd == -1)) {
LOGARG;
return NULL;
}
if (lyp_mmap(ctx, fd, 0, &length, (void **)&data)) {
LOGERR(ctx, LY_ESYS, "Mapping file descriptor into memory failed (%s()).", __func__);
return NULL;
} else if (!data) {
return NULL;
}
ret = lyd_parse_data_(ctx, data, format, options, ap);
lyp_munmap(data, length);
return ret;
}
API struct lyd_node *
lyd_parse_fd(struct ly_ctx *ctx, int fd, LYD_FORMAT format, int options, ...)
{
struct lyd_node *ret;
va_list ap;
va_start(ap, options);
ret = lyd_parse_fd_(ctx, fd, format, options, ap);
va_end(ap);
return ret;
}
API struct lyd_node *
lyd_parse_path(struct ly_ctx *ctx, const char *path, LYD_FORMAT format, int options, ...)
{
int fd;
struct lyd_node *ret;
va_list ap;
if (!ctx || !path) {
LOGARG;
return NULL;
}
fd = open(path, O_RDONLY);
if (fd == -1) {
LOGERR(ctx, LY_ESYS, "Failed to open data file \"%s\" (%s).", path, strerror(errno));
return NULL;
}
va_start(ap, options);
ret = lyd_parse_fd_(ctx, fd, format, options, ap);
va_end(ap);
close(fd);
return ret;
}
static struct lys_node *
lyd_new_find_schema(struct lyd_node *parent, const struct lys_module *module, int rpc_output)
{
struct lys_node *siblings;
if (!parent) {
siblings = module->data;
} else {
if (!parent->schema) {
return NULL;
}
siblings = parent->schema->child;
if (siblings && (siblings->nodetype == (rpc_output ? LYS_INPUT : LYS_OUTPUT))) {
siblings = siblings->next;
}
if (siblings && (siblings->nodetype == (rpc_output ? LYS_OUTPUT : LYS_INPUT))) {
siblings = siblings->child;
}
}
return siblings;
}
struct lyd_node *
_lyd_new(struct lyd_node *parent, const struct lys_node *schema, int dflt)
{
struct lyd_node *ret;
ret = calloc(1, sizeof *ret);
LY_CHECK_ERR_RETURN(!ret, LOGMEM(schema->module->ctx), NULL);
ret->schema = (struct lys_node *)schema;
ret->validity = ly_new_node_validity(schema);
if (resolve_applies_when(schema, 0, NULL)) {
ret->when_status = LYD_WHEN;
}
ret->prev = ret;
ret->dflt = dflt;
#ifdef LY_ENABLED_CACHE
lyd_hash(ret);
#endif
if (parent) {
if (lyd_insert(parent, ret)) {
lyd_free(ret);
return NULL;
}
}
return ret;
}
API struct lyd_node *
lyd_new(struct lyd_node *parent, const struct lys_module *module, const char *name)
{
const struct lys_node *snode = NULL, *siblings;
if ((!parent && !module) || !name) {
LOGARG;
return NULL;
}
siblings = lyd_new_find_schema(parent, module, 0);
if (!siblings) {
LOGARG;
return NULL;
}
if (lys_getnext_data(module, lys_parent(siblings), name, strlen(name), LYS_CONTAINER | LYS_LIST | LYS_NOTIF
| LYS_RPC | LYS_ACTION, 0, &snode) || !snode) {
LOGERR(siblings->module->ctx, LY_EINVAL, "Failed to find \"%s\" as a sibling to \"%s:%s\".",
name, lys_node_module(siblings)->name, siblings->name);
return NULL;
}
return _lyd_new(parent, snode, 0);
}
static struct lyd_node *
lyd_create_leaf(const struct lys_node *schema, const char *val_str, int dflt)
{
struct lyd_node_leaf_list *ret;
ret = calloc(1, sizeof *ret);
LY_CHECK_ERR_RETURN(!ret, LOGMEM(schema->module->ctx), NULL);
ret->schema = (struct lys_node *)schema;
ret->validity = ly_new_node_validity(schema);
if (resolve_applies_when(schema, 0, NULL)) {
ret->when_status = LYD_WHEN;
}
ret->prev = (struct lyd_node *)ret;
ret->value_type = ((struct lys_node_leaf *)schema)->type.base;
ret->value_str = lydict_insert(schema->module->ctx, val_str ? val_str : "", 0);
ret->dflt = dflt;
#ifdef LY_ENABLED_CACHE
lyd_hash((struct lyd_node *)ret);
#endif
return (struct lyd_node *)ret;
}
static struct lyd_node *
_lyd_new_leaf(struct lyd_node *parent, const struct lys_node *schema, const char *val_str, int dflt, int edit_leaf)
{
struct lyd_node *ret;
ret = lyd_create_leaf(schema, val_str, dflt);
if (!ret) {
return NULL;
}
/* connect to parent */
if (parent) {
if (lyd_insert(parent, ret)) {
lyd_free(ret);
return NULL;
}
}
if (edit_leaf && !((struct lyd_node_leaf_list *)ret)->value_str[0]) {
/* empty edit leaf, it is fine */
((struct lyd_node_leaf_list *)ret)->value_type = LY_TYPE_UNKNOWN;
return ret;
}
/* resolve the type correctly (after it was connected to parent cause of log) */
if (!lyp_parse_value(&((struct lys_node_leaf *)ret->schema)->type, &((struct lyd_node_leaf_list *)ret)->value_str,
NULL, (struct lyd_node_leaf_list *)ret, NULL, NULL, 1, dflt, 0)) {
lyd_free(ret);
return NULL;
}
if ((ret->schema->nodetype == LYS_LEAF) && (ret->schema->flags & LYS_UNIQUE)) {
for (; parent && (parent->schema->nodetype != LYS_LIST); parent = parent->parent);
if (parent) {
parent->validity |= LYD_VAL_UNIQUE;
} else {
LOGINT(schema->module->ctx);
}
}
return ret;
}
API struct lyd_node *
lyd_new_leaf(struct lyd_node *parent, const struct lys_module *module, const char *name, const char *val_str)
{
const struct lys_node *snode = NULL, *siblings;
if ((!parent && !module) || !name) {
LOGARG;
return NULL;
}
siblings = lyd_new_find_schema(parent, module, 0);
if (!siblings) {
LOGARG;
return NULL;
}
if (lys_getnext_data(module, lys_parent(siblings), name, strlen(name), LYS_LEAFLIST | LYS_LEAF, 0, &snode) || !snode) {
LOGERR(siblings->module->ctx, LY_EINVAL, "Failed to find \"%s\" as a sibling to \"%s:%s\".",
name, lys_node_module(siblings)->name, siblings->name);
return NULL;
}
return _lyd_new_leaf(parent, snode, val_str, 0, 0);
}
/**
* @brief Update (add) default flag of the parents of the added node.
*
* @param[in] node Added node
*/
static void
lyd_wd_update_parents(struct lyd_node *node)
{
struct lyd_node *parent = node->parent, *iter;
for (parent = node->parent; parent; parent = node->parent) {
if (parent->dflt || parent->schema->nodetype != LYS_CONTAINER ||
((struct lys_node_container *)parent->schema)->presence) {
/* parent is already default and there is nothing to update or
* it is not a non-presence container -> stop the loop */
break;
}
/* check that there is still some non default sibling */
for (iter = node->prev; iter != node; iter = iter->prev) {
if (!iter->dflt) {
break;
}
}
if (iter == node && node->prev != node) {
/* all siblings are implicit default nodes, propagate it to the parent */
node = node->parent;
node->dflt = 1;
continue;
} else {
/* stop the loop */
break;
}
}
}
/* op - 0 add, 1 del, 2 mod (add + del) */
static void
check_leaf_list_backlinks(struct lyd_node *node, int op)
{
struct lyd_node *next, *iter;
struct lyd_node_leaf_list *leaf_list;
struct ly_set *set, *data;
uint32_t i, j;
int validity_changed = 0;
assert((op == 0) || (op == 1) || (op == 2));
/* fix leafrefs */
LY_TREE_DFS_BEGIN(node, next, iter) {
/* the node is target of a leafref */
if ((iter->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST)) && iter->schema->child) {
set = (struct ly_set *)iter->schema->child;
for (i = 0; i < set->number; i++) {
data = lyd_find_instance(iter, set->set.s[i]);
if (data) {
for (j = 0; j < data->number; j++) {
leaf_list = (struct lyd_node_leaf_list *)data->set.d[j];
if (((op != 0) && (leaf_list->value_type == LY_TYPE_LEAFREF) && (leaf_list->value.leafref == iter))
|| ((op != 1) && (leaf_list->value_flags & LY_VALUE_UNRES))) {
/* invalidate the leafref, a change concerning it happened */
leaf_list->validity |= LYD_VAL_LEAFREF;
validity_changed = 1;
if (leaf_list->value_type == LY_TYPE_LEAFREF) {
/* remove invalid link and put unresolved value back */
lyp_parse_value(&((struct lys_node_leaf *)leaf_list->schema)->type, &leaf_list->value_str,
NULL, leaf_list, NULL, NULL, 1, leaf_list->dflt, 0);
}
}
}
ly_set_free(data);
} else {
LOGINT(node->schema->module->ctx);
return;
}
}
}
LY_TREE_DFS_END(node, next, iter)
}
/* invalidate parent to make sure it will be checked in future validation */
if (validity_changed && node->parent) {
node->parent->validity |= LYD_VAL_MAND;
}
}
API int
lyd_change_leaf(struct lyd_node_leaf_list *leaf, const char *val_str)
{
const char *backup;
int val_change, dflt_change;
struct lyd_node *parent;
if (!leaf || (leaf->schema->nodetype != LYS_LEAF)) {
LOGARG;
return -1;
}
backup = leaf->value_str;
leaf->value_str = lydict_insert(leaf->schema->module->ctx, val_str ? val_str : "", 0);
/* leaf->value is erased by lyp_parse_value() */
/* parse the type correctly, makes the value canonical if needed */
if (!lyp_parse_value(&((struct lys_node_leaf *)leaf->schema)->type, &leaf->value_str, NULL, leaf, NULL, NULL, 1, 0, 0)) {
lydict_remove(leaf->schema->module->ctx, backup);
return -1;
}
if (!strcmp(backup, leaf->value_str)) {
/* the value remains the same */
val_change = 0;
} else {
val_change = 1;
}
/* value is correct, remove backup */
lydict_remove(leaf->schema->module->ctx, backup);
/* clear the default flag, the value is different */
if (leaf->dflt) {
for (parent = (struct lyd_node *)leaf; parent; parent = parent->parent) {
parent->dflt = 0;
}
dflt_change = 1;
} else {
dflt_change = 0;
}
if (val_change) {
/* make the node non-validated */
leaf->validity = ly_new_node_validity(leaf->schema);
/* check possible leafref backlinks */
check_leaf_list_backlinks((struct lyd_node *)leaf, 2);
}
if (val_change && (leaf->schema->flags & LYS_UNIQUE)) {
for (parent = leaf->parent; parent && (parent->schema->nodetype != LYS_LIST); parent = parent->parent);
if (parent) {
parent->validity |= LYD_VAL_UNIQUE;
} else {
LOGINT(leaf->schema->module->ctx);
return -1;
}
}
return (val_change || dflt_change ? 0 : 1);
}
static struct lyd_node *
lyd_create_anydata(struct lyd_node *parent, const struct lys_node *schema, void *value,
LYD_ANYDATA_VALUETYPE value_type)
{
struct lyd_node *iter;
struct lyd_node_anydata *ret;
int len;
ret = calloc(1, sizeof *ret);
LY_CHECK_ERR_RETURN(!ret, LOGMEM(schema->module->ctx), NULL);
ret->schema = (struct lys_node *)schema;
ret->validity = ly_new_node_validity(schema);
if (resolve_applies_when(schema, 0, NULL)) {
ret->when_status = LYD_WHEN;
}
ret->prev = (struct lyd_node *)ret;
/* set the value */
switch (value_type) {
case LYD_ANYDATA_CONSTSTRING:
case LYD_ANYDATA_SXML:
case LYD_ANYDATA_JSON:
ret->value.str = lydict_insert(schema->module->ctx, (const char *)value, 0);
break;
case LYD_ANYDATA_STRING:
case LYD_ANYDATA_SXMLD:
case LYD_ANYDATA_JSOND:
ret->value.str = lydict_insert_zc(schema->module->ctx, (char *)value);
value_type &= ~LYD_ANYDATA_STRING; /* make const string from string */
break;
case LYD_ANYDATA_DATATREE:
ret->value.tree = (struct lyd_node *)value;
break;
case LYD_ANYDATA_XML:
ret->value.xml = (struct lyxml_elem *)value;
break;
case LYD_ANYDATA_LYB:
len = lyd_lyb_data_length(value);
if (len == -1) {
LOGERR(schema->module->ctx, LY_EINVAL, "Invalid LYB data.");
return NULL;
}
ret->value.mem = malloc(len);
LY_CHECK_ERR_RETURN(!ret->value.mem, LOGMEM(schema->module->ctx); free(ret), NULL);
memcpy(ret->value.mem, value, len);
break;
case LYD_ANYDATA_LYBD:
ret->value.mem = value;
value_type &= ~LYD_ANYDATA_STRING; /* make const string from string */
break;
}
ret->value_type = value_type;
#ifdef LY_ENABLED_CACHE
lyd_hash((struct lyd_node *)ret);
#endif
/* connect to parent */
if (parent) {
if (lyd_insert(parent, (struct lyd_node*)ret)) {
lyd_free((struct lyd_node*)ret);
return NULL;
}
/* remove the flag from parents */
for (iter = parent; iter && iter->dflt; iter = iter->parent) {
iter->dflt = 0;
}
}
return (struct lyd_node*)ret;
}
API struct lyd_node *
lyd_new_anydata(struct lyd_node *parent, const struct lys_module *module, const char *name,
void *value, LYD_ANYDATA_VALUETYPE value_type)
{
const struct lys_node *siblings, *snode;
if ((!parent && !module) || !name) {
LOGARG;
return NULL;
}
siblings = lyd_new_find_schema(parent, module, 0);
if (!siblings) {
LOGARG;
return NULL;
}
if (lys_getnext_data(module, lys_parent(siblings), name, strlen(name), LYS_ANYDATA, 0, &snode) || !snode) {
LOGERR(siblings->module->ctx, LY_EINVAL, "Failed to find \"%s\" as a sibling to \"%s:%s\".",
name, lys_node_module(siblings)->name, siblings->name);
return NULL;
}
return lyd_create_anydata(parent, snode, value, value_type);
}
API struct lyd_node *
lyd_new_yangdata(const struct lys_module *module, const char *name_template, const char *name)
{
const struct lys_node *schema = NULL, *snode;
if (!module || !name_template || !name) {
LOGARG;
return NULL;
}
schema = lyp_get_yang_data_template(module, name_template, strlen(name_template));
if (!schema) {
LOGERR(module->ctx, LY_EINVAL, "Failed to find yang-data template \"%s\".", name_template);
return NULL;
}
if (lys_getnext_data(module, schema, name, strlen(name), LYS_CONTAINER, 0, &snode) || !snode) {
LOGERR(module->ctx, LY_EINVAL, "Failed to find \"%s\" as a container child of \"%s:%s\".",
name, module->name, schema->name);
return NULL;
}
return _lyd_new(NULL, snode, 0);
}
API struct lyd_node *
lyd_new_output(struct lyd_node *parent, const struct lys_module *module, const char *name)
{
const struct lys_node *snode = NULL, *siblings;
if ((!parent && !module) || !name) {
LOGARG;
return NULL;
}
siblings = lyd_new_find_schema(parent, module, 1);
if (!siblings) {
LOGARG;
return NULL;
}
if (lys_getnext_data(module, lys_parent(siblings), name, strlen(name), LYS_CONTAINER | LYS_LIST | LYS_NOTIF
| LYS_RPC | LYS_ACTION, 0, &snode) || !snode) {
LOGERR(siblings->module->ctx, LY_EINVAL, "Failed to find \"%s\" as a sibling to \"%s:%s\".",
name, lys_node_module(siblings)->name, siblings->name);
return NULL;
}
return _lyd_new(parent, snode, 0);
}
API struct lyd_node *
lyd_new_output_leaf(struct lyd_node *parent, const struct lys_module *module, const char *name, const char *val_str)
{
const struct lys_node *snode = NULL, *siblings;
if ((!parent && !module) || !name) {
LOGARG;
return NULL;
}
siblings = lyd_new_find_schema(parent, module, 1);
if (!siblings) {
LOGARG;
return NULL;
}
if (lys_getnext_data(module, lys_parent(siblings), name, strlen(name), LYS_LEAFLIST | LYS_LEAF, 0, &snode) || !snode) {
LOGERR(siblings->module->ctx, LY_EINVAL, "Failed to find \"%s\" as a sibling to \"%s:%s\".",
name, lys_node_module(siblings)->name, siblings->name);
return NULL;
}
return _lyd_new_leaf(parent, snode, val_str, 0, 0);
}
API struct lyd_node *
lyd_new_output_anydata(struct lyd_node *parent, const struct lys_module *module, const char *name,
void *value, LYD_ANYDATA_VALUETYPE value_type)
{
const struct lys_node *siblings, *snode;
if ((!parent && !module) || !name) {
LOGARG;
return NULL;
}
siblings = lyd_new_find_schema(parent, module, 1);
if (!siblings) {
LOGARG;
return NULL;
}
if (lys_getnext_data(module, lys_parent(siblings), name, strlen(name), LYS_ANYDATA, 0, &snode) || !snode) {
LOGERR(siblings->module->ctx, LY_EINVAL, "Failed to find \"%s\" as a sibling to \"%s:%s\".",
name, lys_node_module(siblings)->name, siblings->name);
return NULL;
}
return lyd_create_anydata(parent, snode, value, value_type);
}
static int
lyd_new_path_list_predicate(struct lyd_node *list, const char *list_name, const char *predicate, int *parsed)
{
const char *mod_name, *name, *value;
char *key_val;
int r, i, mod_name_len, nam_len, val_len, has_predicate;
struct lys_node_list *slist;
struct lys_node *key;
slist = (struct lys_node_list *)list->schema;
/* is the predicate a number? */
if (((r = parse_schema_json_predicate(predicate, &mod_name, &mod_name_len, &name, &nam_len, &value, &val_len, &has_predicate)) < 1)
|| !strncmp(name, ".", nam_len)) {
LOGVAL(slist->module->ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, predicate[-r], &predicate[-r]);
return -1;
}
if (isdigit(name[0])) {
/* position index - creating without keys */
*parsed += r;
return 0;
}
/* it's not a number, so there must be some keys */
if (!slist->keys_size) {
/* there are none, so pretend we did not parse anything to get invalid char error later */
return 0;
}
/* go through all the keys */
i = 0;
goto check_parsed_values;
for (; i < slist->keys_size; ++i) {
if (!has_predicate) {
LOGVAL(slist->module->ctx, LYE_PATH_MISSKEY, LY_VLOG_NONE, NULL, list_name);
return -1;
}
if (((r = parse_schema_json_predicate(predicate, &mod_name, &mod_name_len, &name, &nam_len, &value, &val_len, &has_predicate)) < 1)
|| !strncmp(name, ".", nam_len)) {
LOGVAL(slist->module->ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, predicate[-r], &predicate[-r]);
return -1;
}
check_parsed_values:
key = (struct lys_node *)slist->keys[i];
*parsed += r;
predicate += r;
if (!value || (!mod_name && (lys_node_module(key) != lys_node_module((struct lys_node *)slist)))
|| (mod_name && (strncmp(lys_node_module(key)->name, mod_name, mod_name_len) || lys_node_module(key)->name[mod_name_len]))
|| strncmp(key->name, name, nam_len) || key->name[nam_len]) {
LOGVAL(slist->module->ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, name);
return -1;
}
key_val = malloc((val_len + 1) * sizeof(char));
LY_CHECK_ERR_RETURN(!key_val, LOGMEM(slist->module->ctx), -1);
strncpy(key_val, value, val_len);
key_val[val_len] = '\0';
if (!_lyd_new_leaf(list, key, key_val, 0, 0)) {
free(key_val);
return -1;
}
free(key_val);
}
return 0;
}
static struct lyd_node *
lyd_new_path_update(struct lyd_node *node, void *value, LYD_ANYDATA_VALUETYPE value_type, int dflt)
{
struct ly_ctx *ctx = node->schema->module->ctx;
struct lyd_node_anydata *any;
int len;
switch (node->schema->nodetype) {
case LYS_LEAF:
if (value_type > LYD_ANYDATA_STRING) {
LOGARG;
return NULL;
}
if (lyd_change_leaf((struct lyd_node_leaf_list *)node, value) == 0) {
/* there was an actual change */
if (dflt) {
node->dflt = 1;
}
return node;
}
if (dflt) {
/* maybe the value is the same, but the node is default now */
node->dflt = 1;
return node;
}
break;
case LYS_ANYXML:
case LYS_ANYDATA:
/* the nodes are the same if:
* 1) the value types are strings (LYD_ANYDATA_STRING and LYD_ANYDATA_CONSTSTRING equals)
* and the strings equals
* 2) the value types are the same, but not strings and the pointers (not the content) are the
* same
*/
any = (struct lyd_node_anydata *)node;
if (any->value_type <= LYD_ANYDATA_STRING && value_type <= LYD_ANYDATA_STRING) {
if (ly_strequal(any->value.str, (char *)value, 0)) {
/* values are the same */
return NULL;
}
} else if (any->value_type == value_type) {
/* compare pointers */
if ((void *)any->value.tree == value) {
/* values are the same */
return NULL;
}
}
/* values are not the same - 1) remove the old one ... */
switch (any->value_type) {
case LYD_ANYDATA_CONSTSTRING:
case LYD_ANYDATA_SXML:
case LYD_ANYDATA_JSON:
lydict_remove(ctx, any->value.str);
break;
case LYD_ANYDATA_DATATREE:
lyd_free_withsiblings(any->value.tree);
break;
case LYD_ANYDATA_XML:
lyxml_free_withsiblings(ctx, any->value.xml);
break;
case LYD_ANYDATA_LYB:
free(any->value.mem);
break;
case LYD_ANYDATA_STRING:
case LYD_ANYDATA_SXMLD:
case LYD_ANYDATA_JSOND:
case LYD_ANYDATA_LYBD:
/* dynamic strings are used only as input parameters */
assert(0);
break;
}
/* ... and 2) store the new one */
switch (value_type) {
case LYD_ANYDATA_CONSTSTRING:
case LYD_ANYDATA_SXML:
case LYD_ANYDATA_JSON:
any->value.str = lydict_insert(ctx, (const char *)value, 0);
break;
case LYD_ANYDATA_STRING:
case LYD_ANYDATA_SXMLD:
case LYD_ANYDATA_JSOND:
any->value.str = lydict_insert_zc(ctx, (char *)value);
value_type &= ~LYD_ANYDATA_STRING; /* make const string from string */
break;
case LYD_ANYDATA_DATATREE:
any->value.tree = value;
break;
case LYD_ANYDATA_XML:
any->value.xml = value;
break;
case LYD_ANYDATA_LYB:
len = lyd_lyb_data_length(value);
if (len == -1) {
LOGERR(ctx, LY_EINVAL, "Invalid LYB data.");
return NULL;
}
any->value.mem = malloc(len);
LY_CHECK_ERR_RETURN(!any->value.mem, LOGMEM(ctx), NULL);
memcpy(any->value.mem, value, len);
break;
case LYD_ANYDATA_LYBD:
any->value.mem = value;
value_type &= ~LYD_ANYDATA_STRING; /* make const string from string */
break;
}
return node;
default:
/* nothing needed - containers, lists and leaf-lists do not have value or it cannot be changed */
break;
}
/* not updated */
return NULL;
}
API struct lyd_node *
lyd_new_path(struct lyd_node *data_tree, const struct ly_ctx *ctx, const char *path, void *value,
LYD_ANYDATA_VALUETYPE value_type, int options)
{
char *str;
const char *mod_name, *name, *val_name, *val, *node_mod_name, *id, *backup_mod_name = NULL, *yang_data_name = NULL;
struct lyd_node *ret = NULL, *node, *parent = NULL;
const struct lys_node *schild, *sparent, *tmp;
const struct lys_node_list *slist;
const struct lys_module *module, *prev_mod;
int r, i, parsed = 0, mod_name_len, nam_len, val_name_len, val_len;
int is_relative = -1, has_predicate, first_iter = 1, edit_leaf;
int backup_is_relative, backup_mod_name_len, yang_data_name_len;
if (!path || (!data_tree && !ctx)
|| (!data_tree && (path[0] != '/'))) {
LOGARG;
return NULL;
}
if (!ctx) {
ctx = data_tree->schema->module->ctx;
}
id = path;
if (data_tree) {
if (path[0] == '/') {
/* absolute path, go through all the siblings and try to find the right parent, if exists,
* first go through all the next siblings keeping the original order, for positional predicates */
for (node = data_tree; !parsed && node; node = node->next) {
parent = resolve_partial_json_data_nodeid(id, value_type > LYD_ANYDATA_STRING ? NULL : value, node,
options, &parsed);
}
if (!parsed) {
for (node = data_tree->prev; !parsed && node->next; node = node->prev) {
parent = resolve_partial_json_data_nodeid(id, value_type > LYD_ANYDATA_STRING ? NULL : value, node,
options, &parsed);
}
}
} else {
/* relative path, use only the provided data tree root */
parent = resolve_partial_json_data_nodeid(id, value_type > LYD_ANYDATA_STRING ? NULL : value, data_tree,
options, &parsed);
}
if (parsed == -1) {
return NULL;
}
if (parsed) {
assert(parent);
/* if we parsed something we have a relative path now for sure, otherwise we don't know */
is_relative = 1;
id += parsed;
if (!id[0]) {
/* the node exists, are we supposed to update it or is it default? */
if (!(options & LYD_PATH_OPT_UPDATE) && (!parent->dflt || (options & LYD_PATH_OPT_DFLT))) {
LOGVAL(ctx, LYE_PATH_EXISTS, LY_VLOG_STR, path);
return NULL;
}
/* no change, the default node already exists */
if (parent->dflt && (options & LYD_PATH_OPT_DFLT)) {
return NULL;
}
return lyd_new_path_update(parent, value, value_type, options & LYD_PATH_OPT_DFLT);
}
}
}
backup_is_relative = is_relative;
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 1)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]);
return NULL;
}
if (name[0] == '#') {
if (is_relative) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, '#', name);
return NULL;
}
yang_data_name = name + 1;
yang_data_name_len = nam_len - 1;
backup_mod_name = mod_name;
backup_mod_name_len = mod_name_len;
/* move to the next node in the path */
id += r;
} else {
is_relative = backup_is_relative;
}
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, NULL, 0)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]);
return NULL;
}
/* move to the next node in the path */
id += r;
if (backup_mod_name) {
mod_name = backup_mod_name;
mod_name_len = backup_mod_name_len;
}
/* prepare everything for the schema search loop */
if (is_relative) {
/* we are relative to data_tree or parent if some part of the path already exists */
if (!data_tree) {
LOGERR(ctx, LY_EINVAL, "%s: provided relative path (%s) without context node.", path);
return NULL;
} else if (!parent) {
parent = data_tree;
}
sparent = parent->schema;
module = prev_mod = lys_node_module(sparent);
} else {
/* we are starting from scratch, absolute path */
assert(!parent);
if (!mod_name) {
str = strndup(path, (name + nam_len) - path);
LOGVAL(ctx, LYE_PATH_MISSMOD, LY_VLOG_STR, str);
free(str);
return NULL;
}
module = ly_ctx_nget_module(ctx, mod_name, mod_name_len, NULL, 1);
if (!module) {
str = strndup(path, (mod_name + mod_name_len) - path);
LOGVAL(ctx, LYE_PATH_INMOD, LY_VLOG_STR, str);
free(str);
return NULL;
}
mod_name = NULL;
mod_name_len = 0;
prev_mod = module;
sparent = NULL;
if (yang_data_name) {
sparent = lyp_get_yang_data_template(module, yang_data_name, yang_data_name_len);
if (!sparent) {
str = strndup(path, (yang_data_name + yang_data_name_len) - path);
LOGVAL(ctx, LYE_PATH_INNODE, LY_VLOG_STR, str);
free(str);
return NULL;
}
}
}
/* create nodes in a loop */
while (1) {
/* find the schema node */
schild = NULL;
while ((schild = lys_getnext(schild, sparent, module, 0))) {
if (schild->nodetype & (LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST
| LYS_ANYDATA | LYS_NOTIF | LYS_RPC | LYS_ACTION)) {
/* module comparison */
if (mod_name) {
node_mod_name = lys_node_module(schild)->name;
if (strncmp(node_mod_name, mod_name, mod_name_len) || node_mod_name[mod_name_len]) {
continue;
}
} else if (lys_node_module(schild) != prev_mod) {
continue;
}
/* name check */
if (strncmp(schild->name, name, nam_len) || schild->name[nam_len]) {
continue;
}
/* RPC/action in/out check */
for (tmp = lys_parent(schild); tmp && (tmp->nodetype == LYS_USES); tmp = lys_parent(tmp));
if (tmp) {
if (options & LYD_PATH_OPT_OUTPUT) {
if (tmp->nodetype == LYS_INPUT) {
continue;
}
} else {
if (tmp->nodetype == LYS_OUTPUT) {
continue;
}
}
}
break;
}
}
if (!schild) {
str = strndup(path, (name + nam_len) - path);
LOGVAL(ctx, LYE_PATH_INNODE, LY_VLOG_STR, str);
free(str);
lyd_free(ret);
return NULL;
}
/* we have the right schema node */
switch (schild->nodetype) {
case LYS_CONTAINER:
case LYS_LIST:
case LYS_NOTIF:
case LYS_RPC:
case LYS_ACTION:
if (options & LYD_PATH_OPT_NOPARENT) {
/* these were supposed to exist */
str = strndup(path, (name + nam_len) - path);
LOGVAL(ctx, LYE_PATH_MISSPAR, LY_VLOG_STR, str);
free(str);
lyd_free(ret);
return NULL;
}
node = _lyd_new(is_relative ? parent : NULL, schild, (options & LYD_PATH_OPT_DFLT) ? 1 : 0);
break;
case LYS_LEAF:
case LYS_LEAFLIST:
str = NULL;
if (has_predicate) {
if ((r = parse_schema_json_predicate(id, NULL, NULL, &val_name, &val_name_len, &val, &val_len, &has_predicate)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]);
lyd_free(ret);
return NULL;
}
id += r;
if ((val_name[0] != '.') || (val_name_len != 1)) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, val_name[0], val_name);
lyd_free(ret);
return NULL;
}
str = strndup(val, val_len);
if (!str) {
LOGMEM(ctx);
lyd_free(ret);
return NULL;
}
}
if (id[0]) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[0], id);
free(str);
lyd_free(ret);
return NULL;
}
if ((options & LYD_PATH_OPT_EDIT) && schild->nodetype == LYS_LEAF) {
edit_leaf = 1;
} else {
edit_leaf = 0;
}
node = _lyd_new_leaf(is_relative ? parent : NULL, schild, (str ? str : value),
(options & LYD_PATH_OPT_DFLT) ? 1 : 0, edit_leaf);
free(str);
break;
case LYS_ANYXML:
case LYS_ANYDATA:
if (id[0]) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[0], id);
lyd_free(ret);
return NULL;
}
if (value_type <= LYD_ANYDATA_STRING && !value) {
value_type = LYD_ANYDATA_CONSTSTRING;
value = "";
}
node = lyd_create_anydata(is_relative ? parent : NULL, schild, value, value_type);
break;
default:
LOGINT(ctx);
node = NULL;
break;
}
if (!node) {
str = strndup(path, id - path);
if (is_relative) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_STR, str, "Failed to create node \"%s\" as a child of \"%s\".",
schild->name, parent->schema->name);
} else {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_STR, str, "Failed to create node \"%s\".", schild->name);
}
free(str);
lyd_free(ret);
return NULL;
}
/* special case when we are creating a sibling of a top-level data node */
if (!is_relative) {
if (data_tree) {
for (; data_tree->next; data_tree = data_tree->next);
if (lyd_insert_after(data_tree, node)) {
lyd_free(ret);
return NULL;
}
}
is_relative = 1;
}
if (first_iter) {
/* sort if needed, but only when inserted somewhere */
sparent = node->schema;
do {
sparent = lys_parent(sparent);
} while (sparent && (sparent->nodetype != ((options & LYD_PATH_OPT_OUTPUT) ? LYS_OUTPUT : LYS_INPUT)));
if (sparent && lyd_schema_sort(node, 0)) {
lyd_free(ret);
return NULL;
}
/* set first created node */
ret = node;
first_iter = 0;
}
parsed = 0;
if ((schild->nodetype == LYS_LIST) && has_predicate && lyd_new_path_list_predicate(node, name, id, &parsed)) {
lyd_free(ret);
return NULL;
}
id += parsed;
if (!id[0]) {
/* we are done */
if (options & LYD_PATH_OPT_NOPARENTRET) {
/* last created node */
return node;
}
return ret;
}
/* prepare for another iteration */
parent = node;
sparent = schild;
prev_mod = lys_node_module(schild);
/* parse another node */
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, NULL, 0)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]);
lyd_free(ret);
return NULL;
}
id += r;
/* if a key of a list was supposed to be created, it is created as a part of the list instance creation */
if ((schild->nodetype == LYS_LIST) && !mod_name) {
slist = (const struct lys_node_list *)schild;
for (i = 0; i < slist->keys_size; ++i) {
if (!strncmp(slist->keys[i]->name, name, nam_len) && !slist->keys[i]->name[nam_len]) {
/* the path continues? there cannot be anything after a key (leaf) */
if (id[0]) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[0], id);
lyd_free(ret);
return NULL;
}
return ret;
}
}
}
}
LOGINT(ctx);
return NULL;
}
API unsigned int
lyd_list_pos(const struct lyd_node *node)
{
unsigned int pos;
struct lys_node *schema;
if (!node || ((node->schema->nodetype != LYS_LIST) && (node->schema->nodetype != LYS_LEAFLIST))) {
return 0;
}
schema = node->schema;
pos = 0;
do {
if (node->schema == schema) {
++pos;
}
node = node->prev;
} while (node->next);
return pos;
}
struct lyd_node *
lyd_new_dummy(struct lyd_node *root, struct lyd_node *parent, const struct lys_node *schema, const char *value, int dflt)
{
unsigned int index;
struct ly_set *spath;
const struct lys_node *siter;
struct lyd_node *iter, *dummy = NULL;
assert(schema);
assert(schema->nodetype & (LYS_CONTAINER | LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_ANYDATA | LYS_NOTIF |
LYS_RPC | LYS_ACTION));
spath = ly_set_new();
if (!spath) {
LOGMEM(schema->module->ctx);
return NULL;
}
if (!parent && root) {
/* find data root */
for (; root->parent; root = root->parent); /* vertical move (up) */
for (; root->prev->next; root = root->prev); /* horizontal move (left) */
}
/* build schema path */
for (siter = schema; siter; siter = lys_parent(siter)) {
/* stop if we know some of the parents */
if (parent && parent->schema == siter) {
break;
}
if (siter->nodetype & (LYS_CONTAINER | LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_ANYDATA | LYS_NOTIF |
LYS_RPC | LYS_ACTION)) {
/* we have a node that can appear in data tree */
ly_set_add(spath, (void*)siter, LY_SET_OPT_USEASLIST);
} /* else skip the rest node types */
}
assert(spath->number > 0);
index = spath->number;
if (!parent && !(spath->set.s[index - 1]->nodetype & LYS_LEAFLIST)) {
/* start by searching for the top-level parent */
LY_TREE_FOR(root, iter) {
if (iter->schema == spath->set.s[index - 1]) {
parent = iter;
index--;
break;
}
}
}
iter = parent;
while (iter && index && !(spath->set.s[index - 1]->nodetype & LYS_LEAFLIST)) {
/* search for closer parent on the path */
LY_TREE_FOR(parent->child, iter) {
if (iter->schema == spath->set.s[index - 1]) {
index--;
parent = iter;
break;
}
}
}
while(index) {
/* create the missing part of the path */
switch (spath->set.s[index - 1]->nodetype) {
case LYS_LEAF:
case LYS_LEAFLIST:
if (value) {
iter = _lyd_new_leaf(parent, spath->set.s[index - 1], value, dflt, 0);
} else {
iter = lyd_create_leaf(spath->set.s[index - 1], value, dflt);
if (iter && parent) {
if (lyd_insert(parent, iter)) {
lyd_free(iter);
goto error;
}
}
}
break;
case LYS_CONTAINER:
case LYS_LIST:
iter = _lyd_new(parent, spath->set.s[index - 1], dflt);
break;
case LYS_ANYXML:
case LYS_ANYDATA:
iter = lyd_create_anydata(parent, spath->set.s[index - 1], "", LYD_ANYDATA_CONSTSTRING);
break;
default:
goto error;
}
if (!iter) {
LOGINT(schema->module->ctx);
goto error;
}
/* we say it is valid and it is dummy */
iter->validity = LYD_VAL_INUSE;
if (!dummy) {
dummy = iter;
}
/* continue */
parent = iter;
index--;
}
ly_set_free(spath);
return dummy;
error:
ly_set_free(spath);
lyd_free(dummy);
return NULL;
}
static struct lys_node *
lys_get_schema_inctx(struct lys_node *schema, struct ly_ctx *ctx)
{
const struct lys_module *mod, *trg_mod = NULL;
struct lys_node *parent, *first_sibling = NULL, *iter = NULL;
struct ly_set *parents;
unsigned int index;
uint32_t idx;
void **ptr;
if (!ctx || schema->module->ctx == ctx) {
/* we have the same context */
return schema;
}
/* store the parents chain */
parents = ly_set_new();
for (parent = schema; parent; parent = lys_parent(parent)) {
/* note - augments are skipped so we will work only with the implemented modules
* (where the augments are applied) */
if (parent->nodetype != LYS_USES) {
ly_set_add(parents, parent, LY_SET_OPT_USEASLIST);
}
}
assert(parents->number);
index = parents->number - 1;
/* process the parents from the top level */
/* for the top-level node, we have to locate the module first */
parent = parents->set.s[index];
if (parent->nodetype == LYS_EXT) {
ptr = lys_ext_complex_get_substmt(LY_STMT_NODE, (struct lys_ext_instance_complex *)parent, NULL);
if (!ptr) {
ly_set_free(parents);
return NULL;
}
first_sibling = *(struct lys_node **)ptr;
parent = parents->set.s[--index];
}
idx = 0;
while ((mod = ly_ctx_get_module_iter(ctx, &idx))) {
trg_mod = lys_node_module(parent);
/* check module name */
if (strcmp(mod->name, trg_mod->name)) {
continue;
}
/* check revision */
if ((!mod->rev_size && !trg_mod->rev_size) ||
(mod->rev_size && trg_mod->rev_size && !strcmp(mod->rev[0].date, trg_mod->rev[0].date))) {
/* we have match */
break;
}
}
/* try data callback */
if (!mod && trg_mod && ctx->data_clb) {
LOGDBG(LY_LDGYANG, "Attempting to load '%s' into context using callback ...", trg_mod->name);
mod = ctx->data_clb(ctx, trg_mod->name, NULL, 0, ctx->data_clb_data);
}
if (!mod) {
ly_set_free(parents);
return NULL;
}
if (!first_sibling) {
first_sibling = mod->data;
}
/* now search in the schema tree for the matching node */
while (1) {
lys_get_sibling(first_sibling, trg_mod->name, 0, parent->name, 0, parent->nodetype,
(const struct lys_node **)&iter);
if (!iter) {
/* not found, iter will be used as NULL result */
break;
}
if (index == 0) {
/* we are done, iter is the result */
break;
} else {
/* we are going to continue, so update variables for the next loop */
first_sibling = iter->child;
parent = parents->set.s[--index];
iter = NULL;
}
}
ly_set_free(parents);
return iter;
}
static struct lys_node *
lyd_get_schema_inctx(const struct lyd_node *node, struct ly_ctx *ctx)
{
assert(node);
return lys_get_schema_inctx(node->schema, ctx);
}
/* both target and source were validated */
static void
lyd_merge_node_update(struct lyd_node *target, struct lyd_node *source)
{
struct ly_ctx *ctx;
struct lyd_node_leaf_list *trg_leaf, *src_leaf;
struct lyd_node_anydata *trg_any, *src_any;
int len;
assert(target->schema->nodetype & (LYS_LEAF | LYS_ANYDATA));
ctx = target->schema->module->ctx;
if (ctx == source->schema->module->ctx) {
/* source and targets are in the same context */
if (target->schema->nodetype == LYS_LEAF) {
trg_leaf = (struct lyd_node_leaf_list *)target;
src_leaf = (struct lyd_node_leaf_list *)source;
lydict_remove(ctx, trg_leaf->value_str);
trg_leaf->value_str = src_leaf->value_str;
src_leaf->value_str = NULL;
trg_leaf->value_type = src_leaf->value_type;
src_leaf->value_type = 0;
if (trg_leaf->value_type == LY_TYPE_LEAFREF) {
trg_leaf->validity |= LYD_VAL_LEAFREF;
lyp_parse_value(&((struct lys_node_leaf *)trg_leaf->schema)->type, &trg_leaf->value_str,
NULL, trg_leaf, NULL, NULL, 1, src_leaf->dflt, 0);
} else {
lyd_free_value(trg_leaf->value, trg_leaf->value_type, trg_leaf->value_flags,
&((struct lys_node_leaf *)trg_leaf->schema)->type, NULL, NULL, NULL);
trg_leaf->value = src_leaf->value;
}
src_leaf->value = (lyd_val)0;
trg_leaf->dflt = src_leaf->dflt;
check_leaf_list_backlinks(target, 2);
} else { /* ANYDATA */
trg_any = (struct lyd_node_anydata *)target;
src_any = (struct lyd_node_anydata *)source;
switch(trg_any->value_type) {
case LYD_ANYDATA_CONSTSTRING:
case LYD_ANYDATA_SXML:
case LYD_ANYDATA_JSON:
lydict_remove(ctx, trg_any->value.str);
break;
case LYD_ANYDATA_DATATREE:
lyd_free_withsiblings(trg_any->value.tree);
break;
case LYD_ANYDATA_XML:
lyxml_free_withsiblings(ctx, trg_any->value.xml);
break;
case LYD_ANYDATA_LYB:
free(trg_any->value.mem);
break;
case LYD_ANYDATA_STRING:
case LYD_ANYDATA_SXMLD:
case LYD_ANYDATA_JSOND:
case LYD_ANYDATA_LYBD:
/* dynamic strings are used only as input parameters */
assert(0);
break;
}
trg_any->value_type = src_any->value_type;
trg_any->value = src_any->value;
src_any->value_type = LYD_ANYDATA_DATATREE;
src_any->value.tree = NULL;
}
} else {
/* we have different contexts for the target and source */
if (target->schema->nodetype == LYS_LEAF) {
trg_leaf = (struct lyd_node_leaf_list *)target;
src_leaf = (struct lyd_node_leaf_list *)source;
lydict_remove(ctx, trg_leaf->value_str);
trg_leaf->value_str = lydict_insert(ctx, src_leaf->value_str, 0);
lyd_free_value(trg_leaf->value, trg_leaf->value_type, trg_leaf->value_flags,
&((struct lys_node_leaf *)trg_leaf->schema)->type, NULL, NULL, NULL);
trg_leaf->value_type = src_leaf->value_type;
trg_leaf->dflt = src_leaf->dflt;
switch (trg_leaf->value_type) {
case LY_TYPE_BINARY:
case LY_TYPE_STRING:
/* value_str pointer is shared in these cases */
trg_leaf->value.string = trg_leaf->value_str;
break;
case LY_TYPE_LEAFREF:
trg_leaf->validity |= LYD_VAL_LEAFREF;
lyp_parse_value(&((struct lys_node_leaf *)trg_leaf->schema)->type, &trg_leaf->value_str,
NULL, trg_leaf, NULL, NULL, 1, trg_leaf->dflt, 0);
break;
case LY_TYPE_INST:
trg_leaf->value.instance = NULL;
break;
case LY_TYPE_UNION:
/* unresolved union (this must be non-validated tree), duplicate the stored string (duplicated
* because of possible change of the value in case of instance-identifier) */
trg_leaf->value.string = lydict_insert(ctx, src_leaf->value.string, 0);
break;
case LY_TYPE_BITS:
case LY_TYPE_ENUM:
case LY_TYPE_IDENT:
/* in case of duplicating bits (no matter if in the same context or not) or enum and identityref into
* a different context, searching for the type and duplicating the data is almost as same as resolving
* the string value, so due to a simplicity, parse the value for the duplicated leaf */
lyp_parse_value(&((struct lys_node_leaf *)trg_leaf->schema)->type, &trg_leaf->value_str, NULL,
trg_leaf, NULL, NULL, 1, trg_leaf->dflt, 1);
break;
default:
trg_leaf->value = src_leaf->value;
break;
}
check_leaf_list_backlinks(target, 2);
} else { /* ANYDATA */
trg_any = (struct lyd_node_anydata *)target;
src_any = (struct lyd_node_anydata *)source;
switch(trg_any->value_type) {
case LYD_ANYDATA_CONSTSTRING:
case LYD_ANYDATA_SXML:
case LYD_ANYDATA_JSON:
lydict_remove(ctx, trg_any->value.str);
break;
case LYD_ANYDATA_DATATREE:
lyd_free_withsiblings(trg_any->value.tree);
break;
case LYD_ANYDATA_XML:
lyxml_free_withsiblings(ctx, trg_any->value.xml);
break;
case LYD_ANYDATA_LYB:
free(trg_any->value.mem);
break;
case LYD_ANYDATA_STRING:
case LYD_ANYDATA_SXMLD:
case LYD_ANYDATA_JSOND:
case LYD_ANYDATA_LYBD:
/* dynamic strings are used only as input parameters */
assert(0);
break;
}
trg_any->value_type = src_any->value_type;
if ((void*)src_any->value.tree) {
/* there is a value to duplicate */
switch (trg_any->value_type) {
case LYD_ANYDATA_CONSTSTRING:
case LYD_ANYDATA_SXML:
case LYD_ANYDATA_JSON:
trg_any->value.str = lydict_insert(ctx, src_any->value.str, 0);
break;
case LYD_ANYDATA_DATATREE:
trg_any->value.tree = lyd_dup_to_ctx(src_any->value.tree, 1, ctx);
break;
case LYD_ANYDATA_XML:
trg_any->value.xml = lyxml_dup_elem(ctx, src_any->value.xml, NULL, 1);
break;
case LYD_ANYDATA_LYB:
len = lyd_lyb_data_length(src_any->value.mem);
if (len == -1) {
LOGERR(ctx, LY_EINVAL, "Invalid LYB data.");
return;
}
trg_any->value.mem = malloc(len);
LY_CHECK_ERR_RETURN(!trg_any->value.mem, LOGMEM(ctx), );
memcpy(trg_any->value.mem, src_any->value.mem, len);
break;
case LYD_ANYDATA_STRING:
case LYD_ANYDATA_SXMLD:
case LYD_ANYDATA_JSOND:
case LYD_ANYDATA_LYBD:
/* dynamic strings are used only as input parameters */
assert(0);
break;
}
}
}
}
}
/* return: 0 (not equal), 1 (equal), -1 (error) */
static int
lyd_merge_node_schema_equal(struct lyd_node *node1, struct lyd_node *node2)
{
struct lys_node *sch1;
if (node1->schema->module->ctx == node2->schema->module->ctx) {
if (node1->schema != node2->schema) {
return 0;
}
} else {
/* the nodes are in different contexts, get the appropriate schema nodes from the
* same context */
sch1 = lyd_get_schema_inctx(node1, node2->schema->module->ctx);
if (!sch1) {
LOGERR(node2->schema->module->ctx, LY_EINVAL, "Target context does not contain a required schema node (%s:%s).",
lyd_node_module(node1)->name, node1->schema->name);
return -1;
} else if (sch1 != node2->schema) {
/* not matching nodes */
return 0;
}
}
return 1;
}
/* return: 0 (not equal), 1 (equal), 2 (equal and state leaf-/list marked), -1 (error) */
static int
lyd_merge_node_equal(struct lyd_node *node1, struct lyd_node *node2)
{
int ret;
switch (node1->schema->nodetype) {
case LYS_CONTAINER:
case LYS_LEAF:
case LYS_ANYXML:
case LYS_ANYDATA:
case LYS_RPC:
case LYS_ACTION:
case LYS_NOTIF:
return 1;
case LYS_LEAFLIST:
if (node1->validity & LYD_VAL_INUSE) {
/* this instance was already matched, we want to find another so that the number of the istances matches */
assert(node1->schema->flags & LYS_CONFIG_R);
return 0;
}
ret = lyd_list_equal(node1, node2, 1);
if ((ret == 1) && (node1->schema->flags & LYS_CONFIG_R)) {
/* mark it as matched */
node1->validity |= LYD_VAL_INUSE;
ret = 2;
}
return ret;
case LYS_LIST:
if (node1->validity & LYD_VAL_INUSE) {
/* this instance was already matched, we want to find another so that the number of the istances matches */
assert(!((struct lys_node_list *)node1->schema)->keys_size);
return 0;
}
ret = lyd_list_equal(node1, node2, 1);
if ((ret == 1) && !((struct lys_node_list *)node1->schema)->keys_size) {
/* mark it as matched */
node1->validity |= LYD_VAL_INUSE;
ret = 2;
}
return ret;
default:
break;
}
LOGINT(node2->schema->module->ctx);
return -1;
}
/* spends source */
static int
lyd_merge_parent_children(struct lyd_node *target, struct lyd_node *source, int options)
{
struct lyd_node *trg_parent, *src, *src_backup, *src_elem, *src_elem_backup, *src_next, *trg_child, *trg_parent_backup;
int ret, clear_flag = 0;
struct ly_ctx *ctx = target->schema->module->ctx; /* shortcut */
LY_TREE_FOR_SAFE(source, src_backup, src) {
for (src_elem = src_next = src, trg_parent = target;
src_elem;
src_elem = src_next) {
/* it won't get inserted in this case */
if (src_elem->dflt && (options & LYD_OPT_EXPLICIT)) {
if (src_elem == src) {
/* we are done with this subtree in this case */
break;
}
trg_child = (struct lyd_node *)1;
goto src_skip;
}
ret = 0;
#ifdef LY_ENABLED_CACHE
struct lyd_node **trg_child_p;
/* trees are supposed to be validated so all nodes must have their hash, but lets not be that strict */
if (!src_elem->hash) {
lyd_hash(src_elem);
}
if (trg_parent->ht) {
trg_child = NULL;
if (!lyht_find(trg_parent->ht, &src_elem, src_elem->hash, (void **)&trg_child_p)) {
trg_child = *trg_child_p;
ret = 1;
/* it is a bit more difficult with keyless state lists and leaf-lists */
if (((trg_child->schema->nodetype == LYS_LIST) && !((struct lys_node_list *)trg_child->schema)->keys_size)
|| ((trg_child->schema->nodetype == LYS_LEAFLIST) && (trg_child->schema->flags & LYS_CONFIG_R))) {
assert(trg_child->schema->flags & LYS_CONFIG_R);
while (trg_child && (trg_child->validity & LYD_VAL_INUSE)) {
/* state lists, find one not-already-found */
if (lyht_find_next(trg_parent->ht, &trg_child, trg_child->hash, (void **)&trg_child_p)) {
trg_child = NULL;
} else {
trg_child = *trg_child_p;
}
}
if (trg_child) {
/* mark it as matched */
trg_child->validity |= LYD_VAL_INUSE;
ret = 2;
} else {
/* actually, it was matched already and no other instance found, so now not a match */
ret = 0;
}
}
}
} else
#endif
{
LY_TREE_FOR(trg_parent->child, trg_child) {
/* schema match, data match? */
ret = lyd_merge_node_schema_equal(trg_child, src_elem);
if (ret == 1) {
ret = lyd_merge_node_equal(trg_child, src_elem);
}
if (ret != 0) {
/* even data match */
break;
}
}
}
if (ret > 0) {
if (trg_child->schema->nodetype & (LYS_LEAF | LYS_ANYDATA)) {
lyd_merge_node_update(trg_child, src_elem);
} else if (ret == 2) {
clear_flag = 1;
}
} else if (ret == -1) {
/* error */
lyd_free_withsiblings(source);
return 1;
}
/* first prepare for the next iteration */
src_elem_backup = src_elem;
trg_parent_backup = trg_parent;
if (((src_elem->schema->nodetype == LYS_CONTAINER) || ((src_elem->schema->nodetype == LYS_LIST)
&& ((struct lys_node_list *)src_elem->schema)->keys_size)) && src_elem->child && trg_child) {
/* go into children */
src_next = src_elem->child;
trg_parent = trg_child;
} else {
src_skip:
/* no children (or the whole subtree will be inserted), try siblings */
if (src_elem == src) {
/* we are done with this subtree */
if (trg_child) {
/* it's an empty container, list without keys, or an already-updated leaf/anydata, nothing else to do */
break;
} else {
/* ... but we still need to insert it */
src_next = NULL;
goto src_insert;
}
} else {
src_next = src_elem->next;
/* trg_parent does not change */
}
}
while (!src_next) {
src_elem = src_elem->parent;
if (src_elem->parent == src->parent) {
/* we are done, no next element to process */
break;
}
/* parent is already processed, go to its sibling */
src_next = src_elem->next;
trg_parent = trg_parent->parent;
}
if (!trg_child) {
src_insert:
/* we need to insert the whole subtree */
if (ctx == src_elem_backup->schema->module->ctx) {
/* same context - unlink the subtree and insert it into the target */
lyd_unlink(src_elem_backup);
} else {
/* different contexts - before inserting subtree, instead of unlinking, duplicate it into the
* target context */
src_elem_backup = lyd_dup_to_ctx(src_elem_backup, 1, ctx);
}
if (src_elem == source) {
/* it will be linked into another data tree and the pointers changed */
source = source->next;
}
/* insert subtree into the target */
if (lyd_insert(trg_parent_backup, src_elem_backup)) {
LOGINT(ctx);
lyd_free_withsiblings(source);
return 1;
}
if (src_elem == src) {
/* we are finished for this src */
break;
}
}
}
}
lyd_free_withsiblings(source);
if (clear_flag) {
return 2;
}
return 0;
}
/* spends source */
static int
lyd_merge_siblings(struct lyd_node *target, struct lyd_node *source, int options)
{
struct lyd_node *trg, *src, *src_backup, *ins;
int ret, clear_flag = 0;
struct ly_ctx *ctx = target->schema->module->ctx; /* shortcut */
while (target->prev->next) {
target = target->prev;
}
LY_TREE_FOR_SAFE(source, src_backup, src) {
LY_TREE_FOR(target, trg) {
/* sibling found, merge it */
ret = lyd_merge_node_schema_equal(trg, src);
if (ret == 1) {
ret = lyd_merge_node_equal(trg, src);
}
if (ret > 0) {
if (ret == 2) {
clear_flag = 1;
}
switch (trg->schema->nodetype) {
case LYS_LEAF:
case LYS_ANYXML:
case LYS_ANYDATA:
lyd_merge_node_update(trg, src);
break;
case LYS_LEAFLIST:
/* it's already there, nothing to do */
break;
case LYS_LIST:
case LYS_CONTAINER:
case LYS_NOTIF:
case LYS_RPC:
case LYS_INPUT:
case LYS_OUTPUT:
ret = lyd_merge_parent_children(trg, src->child, options);
if (ret == 2) {
clear_flag = 1;
} else if (ret) {
lyd_free_withsiblings(source);
return 1;
}
break;
default:
LOGINT(ctx);
lyd_free_withsiblings(source);
return 1;
}
break;
} else if (ret == -1) {
lyd_free_withsiblings(source);
return 1;
} /* else not equal, nothing to do */
}
/* sibling not found, insert it */
if (!trg) {
if (ctx != src->schema->module->ctx) {
ins = lyd_dup_to_ctx(src, 1, ctx);
} else {
lyd_unlink(src);
if (src == source) {
/* just so source is not freed, we inserted it and need it further */
source = src_backup;
}
ins = src;
}
lyd_insert_after(target->prev, ins);
}
}
lyd_free_withsiblings(source);
if (clear_flag) {
return 2;
}
return 0;
}
API int
lyd_merge_to_ctx(struct lyd_node **trg, const struct lyd_node *src, int options, struct ly_ctx *ctx)
{
struct lyd_node *node = NULL, *node2, *target, *trg_merge_start, *src_merge_start = NULL;
const struct lyd_node *iter;
struct lys_node *src_snode, *sch = NULL;
int i, src_depth, depth, first_iter, ret, dflt = 1;
const struct lys_node *parent = NULL;
if (!trg || !(*trg) || !src) {
LOGARG;
return -1;
}
target = *trg;
parent = lys_parent(target->schema);
/* go up all uses */
while (parent && (parent->nodetype == LYS_USES)) {
parent = lys_parent(parent);
}
if (parent && !lyp_get_yang_data_template_name(target)) {
LOGERR(parent->module->ctx, LY_EINVAL, "Target not a top-level data tree.");
return -1;
}
/* get know if we are converting data into a different context */
if (ctx && target->schema->module->ctx != ctx) {
/* target's data tree context differs from the target context, move the target
* data tree into the target context */
/* get the first target's top-level and store it as the result */
for (; target->prev->next; target = target->prev);
*trg = target;
for (node = NULL, trg_merge_start = target; target; target = target->next) {
node2 = lyd_dup_to_ctx(target, 1, ctx);
if (!node2) {
goto error;
}
if (node) {
if (lyd_insert_after(node->prev, node2)) {
goto error;
}
} else {
node = node2;
}
}
target = node;
node = NULL;
} else if (src->schema->module->ctx != target->schema->module->ctx) {
/* the source data will be converted into the target's context during the merge */
ctx = target->schema->module->ctx;
} else if (ctx == src->schema->module->ctx) {
/* no conversion is needed */
ctx = NULL;
}
/* find source top-level schema node */
for (src_snode = src->schema, src_depth = 0;
(src_snode = lys_parent(src_snode)) && src_snode->nodetype != LYS_EXT;
++src_depth);
/* find first shared missing schema parent of the subtrees */
trg_merge_start = target;
depth = 0;
first_iter = 1;
if (src_depth) {
/* we are going to create missing parents in the following loop,
* but we will need to know a dflt flag for them. In case the newly
* created parent is going to have at least one non-default child,
* it will be also non-default, otherwise it will be the default node */
if (options & LYD_OPT_NOSIBLINGS) {
dflt = src->dflt;
} else {
LY_TREE_FOR(src, iter) {
if (!iter->dflt) {
/* non default sibling -> parent is going to be
* created also as non-default */
dflt = 0;
break;
}
}
}
}
while (1) {
/* going from down (source root) to up (top-level or the common node with target */
do {
for (src_snode = src->schema, i = 0; i < src_depth - depth; src_snode = lys_parent(src_snode), ++i);
++depth;
} while (src_snode != src->schema && (src_snode->nodetype & (LYS_CHOICE | LYS_CASE | LYS_USES)));
if (src_snode == src->schema) {
break;
}
if (src_snode->nodetype != LYS_CONTAINER) {
/* we would have to create a list (the only data node with children except container), impossible */
LOGERR(ctx, LY_EINVAL, "Cannot create %s \"%s\" for the merge.", strnodetype(src_snode->nodetype), src_snode->name);
goto error;
}
/* have we created any missing containers already? if we did,
* it is totally useless to search for match, there won't ever be */
if (!src_merge_start) {
if (first_iter) {
node = trg_merge_start;
first_iter = 0;
} else {
node = trg_merge_start->child;
}
/* find it in target data nodes */
LY_TREE_FOR(node, node) {
if (ctx) {
/* we have the schema nodes in the different context */
sch = lys_get_schema_inctx(src_snode, ctx);
if (!sch) {
LOGERR(ctx, LY_EINVAL, "Target context does not contain schema node for the data node being "
"merged (%s:%s).", lys_node_module(src_snode)->name, src_snode->name);
goto error;
}
} else {
/* the context is same and comparison of the schema nodes will works fine */
sch = src_snode;
}
if (node->schema == sch) {
trg_merge_start = node;
break;
}
}
if (!(options & LYD_OPT_DESTRUCT)) {
/* the source tree will be duplicated, so to save some work in case
* of different target context, create also the parents nodes in the
* correct context */
src_snode = sch;
}
} else if (ctx && !(options & LYD_OPT_DESTRUCT)) {
/* get the schema node in the correct (target) context, same as above,
* this is done to save some work and have the source in the same context
* when the provided source tree is below duplicated in the target context
* and connected into the parents created here */
src_snode = lys_get_schema_inctx(src_snode, ctx);
if (!src_snode) {
LOGERR(ctx, LY_EINVAL, "Target context does not contain schema node for the data node being "
"merged (%s:%s).", lys_node_module(src_snode)->name, src_snode->name);
goto error;
}
}
if (!node) {
/* it is not there, create it */
node2 = _lyd_new(NULL, src_snode, dflt);
if (!src_merge_start) {
src_merge_start = node2;
} else {
if (lyd_insert(node2, src_merge_start)) {
goto error;
}
src_merge_start = node2;
}
}
}
/* process source according to options */
if (options & LYD_OPT_DESTRUCT) {
LY_TREE_FOR(src, iter) {
check_leaf_list_backlinks((struct lyd_node *)iter, 2);
if (options & LYD_OPT_NOSIBLINGS) {
break;
}
}
node = (struct lyd_node *)src;
if ((node->prev != node) && (options & LYD_OPT_NOSIBLINGS)) {
node2 = node->prev;
lyd_unlink(node);
lyd_free_withsiblings(node2);
}
} else {
node = NULL;
for (; src; src = src->next) {
/* because we already have to duplicate it, do it in the correct context */
node2 = lyd_dup_to_ctx(src, 1, ctx);
if (!node2) {
lyd_free_withsiblings(node);
goto error;
}
if (node) {
if (lyd_insert_after(node->prev, node2)) {
lyd_free_withsiblings(node);
goto error;
}
} else {
node = node2;
}
if (options & LYD_OPT_NOSIBLINGS) {
break;
}
}
}
if (src_merge_start) {
/* insert data into the created parents */
/* first, get the lowest created parent, we don't have to check the nodetype since we are
* creating only a simple chain of containers */
for (node2 = src_merge_start; node2->child; node2 = node2->child);
node2->child = node;
LY_TREE_FOR(node, node) {
node->parent = node2;
}
} else {
src_merge_start = node;
}
if (!first_iter) {
/* !! src_merge start is a child(ren) of trg_merge_start */
ret = lyd_merge_parent_children(trg_merge_start, src_merge_start, options);
} else {
/* !! src_merge start is a (top-level) sibling(s) of trg_merge_start */
ret = lyd_merge_siblings(trg_merge_start, src_merge_start, options);
}
/* it was freed whatever the return value */
src_merge_start = NULL;
if (ret == 2) {
/* clear remporary LYD_VAL_INUSE validation flags */
LY_TREE_DFS_BEGIN(target, node2, node) {
node->validity &= ~LYD_VAL_INUSE;
LY_TREE_DFS_END(target, node2, node);
}
ret = 0;
} else if (ret) {
goto error;
}
if (target->schema->nodetype == LYS_RPC) {
lyd_schema_sort(target, 1);
}
/* update the pointer to the target tree if needed */
if (*trg != target) {
lyd_free_withsiblings(*trg);
(*trg) = target;
}
return ret;
error:
if (*trg != target) {
/* target is duplication of the original target in different context,
* free it due to the error */
lyd_free_withsiblings(target);
}
lyd_free_withsiblings(src_merge_start);
return -1;
}
API int
lyd_merge(struct lyd_node *target, const struct lyd_node *source, int options)
{
if (!target || !source) {
LOGARG;
return -1;
}
return lyd_merge_to_ctx(&target, source, options, target->schema->module->ctx);
}
API void
lyd_free_diff(struct lyd_difflist *diff)
{
if (diff) {
free(diff->type);
free(diff->first);
free(diff->second);
free(diff);
}
}
static int
lyd_difflist_add(struct lyd_difflist *diff, unsigned int *size, unsigned int index,
LYD_DIFFTYPE type, struct lyd_node *first, struct lyd_node *second)
{
void *new;
struct ly_ctx *ctx = (first ? first->schema->module->ctx : second->schema->module->ctx);
assert(diff);
assert(size && *size);
if (index + 1 == *size) {
/* it's time to enlarge */
*size = *size + 16;
new = realloc(diff->type, *size * sizeof *diff->type);
LY_CHECK_ERR_RETURN(!new, LOGMEM(ctx), EXIT_FAILURE);
diff->type = new;
new = realloc(diff->first, *size * sizeof *diff->first);
LY_CHECK_ERR_RETURN(!new, LOGMEM(ctx), EXIT_FAILURE);
diff->first = new;
new = realloc(diff->second, *size * sizeof *diff->second);
LY_CHECK_ERR_RETURN(!new, LOGMEM(ctx), EXIT_FAILURE);
diff->second = new;
}
/* insert the item */
diff->type[index] = type;
diff->first[index] = first;
diff->second[index] = second;
/* terminate the arrays */
index++;
diff->type[index] = LYD_DIFF_END;
diff->first[index] = NULL;
diff->second[index] = NULL;
return EXIT_SUCCESS;
}
struct diff_ordered_dist {
struct diff_ordered_dist *next;
int dist;
};
struct diff_ordered_item {
struct lyd_node *first;
struct lyd_node *second;
struct diff_ordered_dist *dist;
};
struct diff_ordered {
struct lys_node *schema;
struct lyd_node *parent;
unsigned int count;
struct diff_ordered_item *items; /* array */
struct diff_ordered_dist *dist; /* linked list (1-way, ring) */
struct diff_ordered_dist *dist_last; /* aux pointer for faster insertion sort */
};
static int
diff_ordset_insert(struct lyd_node *node, struct ly_set *ordset)
{
unsigned int i;
struct diff_ordered *new_ordered, *iter;
for (i = 0; i < ordset->number; i++) {
iter = (struct diff_ordered *)ordset->set.g[i];
if (iter->schema == node->schema && iter->parent == node->parent) {
break;
}
}
if (i == ordset->number) {
/* not seen user-ordered list */
new_ordered = calloc(1, sizeof *new_ordered);
LY_CHECK_ERR_RETURN(!new_ordered, LOGMEM(node->schema->module->ctx), EXIT_FAILURE);
new_ordered->schema = node->schema;
new_ordered->parent = node->parent;
ly_set_add(ordset, new_ordered, LY_SET_OPT_USEASLIST);
}
((struct diff_ordered *)ordset->set.g[i])->count++;
return EXIT_SUCCESS;
}
static void
diff_ordset_free(struct ly_set *set)
{
unsigned int i, j;
struct diff_ordered *ord;
if (!set) {
return;
}
for (i = 0; i < set->number; i++) {
ord = (struct diff_ordered *)set->set.g[i];
for (j = 0; j < ord->count; j++) {
free(ord->items[j].dist);
}
free(ord->items);
free(ord);
}
ly_set_free(set);
}
/*
* -1 - error
* 0 - ok
* 1 - first and second not the same
*/
static int
lyd_diff_compare(struct lyd_node *first, struct lyd_node *second, int options)
{
int rc;
if (first->dflt && !(options & LYD_DIFFOPT_WITHDEFAULTS)) {
/* the second one cannot be default (see lyd_diff()),
* so the nodes differs (first one is default node) */
return 1;
}
if (first->schema->nodetype & (LYS_LEAFLIST | LYS_LIST)) {
if (first->validity & LYD_VAL_INUSE) {
/* this node was already matched, it cannot be matched twice (except for state leaf-/lists,
* which we want to keep the count on this way) */
return 1;
}
rc = lyd_list_equal(first, second, (options & LYD_DIFFOPT_WITHDEFAULTS ? 1 : 0));
if (rc == -1) {
return -1;
} else if (!rc) {
/* list instances differs */
return 1;
}
/* matches */
}
return 0;
}
/*
* -1 - error
* 0 - ok
*/
static int
lyd_diff_match(struct lyd_node *first, struct lyd_node *second, struct lyd_difflist *diff, unsigned int *size,
unsigned int *i, struct ly_set *matchset, struct ly_set *ordset, int options)
{
switch (first->schema->nodetype) {
case LYS_LEAFLIST:
case LYS_LIST:
/* additional work for future move matching in case of user ordered lists */
if (first->schema->flags & LYS_USERORDERED) {
diff_ordset_insert(first, ordset);
}
/* falls through */
case LYS_CONTAINER:
assert(!(second->validity & LYD_VAL_INUSE));
second->validity |= LYD_VAL_INUSE;
/* remember the matching node in first for keeping correct pointer in first
* for comparing when passing through the second tree in lyd_diff().
* Duplicities are not allowed actually, but they cannot happen since single
* node can match only one node in the other tree */
ly_set_add(matchset, first, LY_SET_OPT_USEASLIST);
break;
case LYS_LEAF:
/* check for leaf's modification */
if (!lyd_leaf_val_equal(first, second, 0) || ((options & LYD_DIFFOPT_WITHDEFAULTS) && (first->dflt != second->dflt))) {
if (lyd_difflist_add(diff, size, (*i)++, LYD_DIFF_CHANGED, first, second)) {
return -1;
}
}
break;
case LYS_ANYXML:
case LYS_ANYDATA:
/* check for anydata/anyxml's modification */
if (!lyd_anydata_equal(first, second) && lyd_difflist_add(diff, size, (*i)++, LYD_DIFF_CHANGED, first, second)) {
return -1;
}
break;
default:
LOGINT(first->schema->module->ctx);
return -1;
}
/* mark both that they have matching instance in the other tree */
assert(!(first->validity & LYD_VAL_INUSE));
first->validity |= LYD_VAL_INUSE;
return 0;
}
/* @brief compare if the nodes are equivalent including checking the list's keys
* Go through the nodes and their parents and in the case of list, compare its keys.
*
* @return 0 different, 1 equivalent
*/
static int
lyd_diff_equivnode(struct lyd_node *first, struct lyd_node *second)
{
struct lyd_node *iter1, *iter2;
for (iter1 = first, iter2 = second; iter1 && iter2; iter1 = iter1->parent, iter2 = iter2->parent) {
if (iter1->schema->module->ctx == iter2->schema->module->ctx) {
if (iter1->schema != iter2->schema) {
return 0;
}
} else {
if (!ly_strequal(iter1->schema->name, iter2->schema->name, 0)) {
/* comparing the names is fine, even if they are, in fact, 2 different nodes
* with equal names, some of their parents will differ */
return 0;
}
}
if (iter1->schema->nodetype == LYS_LIST) {
/* compare keys */
if (lyd_list_equal(iter1, iter2, 0) != 1) {
return 0;
}
}
}
if (iter1 != iter2) {
/* we are supposed to be in root (NULL) in both trees */
return 0;
}
return 1;
}
static int
lyd_diff_move_preprocess(struct diff_ordered *ordered, struct lyd_node *first, struct lyd_node *second)
{
struct ly_ctx *ctx = first->schema->module->ctx;
struct lyd_node *iter;
unsigned int pos = 0;
int abs_dist;
struct diff_ordered_dist *dist_aux;
struct diff_ordered_dist *dist_iter, *dist_last;
char *str = NULL;
/* ordered->count was zeroed and now it is incremented with each added
* item's information, so it is actually position of the second node
*/
/* get the position of the first node */
for (iter = first->prev; iter->next; iter = iter->prev) {
if (!(iter->validity & LYD_VAL_INUSE)) {
/* skip deleted nodes */
continue;
}
if (iter->schema == first->schema) {
pos++;
}
}
if (pos != ordered->count) {
LOGDBG(LY_LDGDIFF, "detected moved element \"%s\" from %d to %d (distance %d)",
str = lyd_path(first), pos, ordered->count, ordered->count - pos);
free(str);
}
/* store information, count distance */
ordered->items[pos].dist = dist_aux = calloc(1, sizeof *dist_aux);
LY_CHECK_ERR_RETURN(!dist_aux, LOGMEM(ctx), EXIT_FAILURE);
ordered->items[pos].dist->dist = ordered->count - pos;
abs_dist = abs(ordered->items[pos].dist->dist);
ordered->items[pos].first = first;
ordered->items[pos].second = second;
ordered->count++;
/* insert sort of distances, higher first */
for (dist_iter = ordered->dist, dist_last = NULL;
dist_iter;
dist_last = dist_iter, dist_iter = dist_iter->next) {
if (abs_dist >= abs(dist_iter->dist)) {
/* found correct place */
dist_aux->next = dist_iter;
if (dist_last) {
dist_last->next = dist_aux;
}
break;
} else if (dist_iter->next == ordered->dist) {
/* last item */
dist_aux->next = ordered->dist; /* ring list */
ordered->dist_last = dist_aux;
break;
}
}
if (dist_aux->next == ordered->dist) {
if (ordered->dist_last == dist_aux) {
/* last item */
if (!ordered->dist) {
/* the only item */
dist_aux->next = dist_aux;
ordered->dist = ordered->dist_last = dist_aux;
}
} else {
/* first item */
ordered->dist = dist_aux;
if (dist_aux->next) {
/* more than one item, update the last one's next */
ordered->dist_last->next = dist_aux;
} else {
/* the only item */
ordered->dist_last = dist_aux;
dist_aux->next = dist_aux; /* ring list */
}
}
}
return 0;
}
static struct lyd_difflist *
lyd_diff_init_difflist(struct ly_ctx *ctx, unsigned int *size)
{
struct lyd_difflist *result;
result = malloc(sizeof *result);
LY_CHECK_ERR_RETURN(!result, LOGMEM(ctx); *size = 0, NULL);
*size = 1;
result->type = calloc(*size, sizeof *result->type);
result->first = calloc(*size, sizeof *result->first);
result->second = calloc(*size, sizeof *result->second);
if (!result->type || !result->first || !result->second) {
LOGMEM(ctx);
free(result->second);
free(result->first);
free(result->type);
free(result);
*size = 0;
return NULL;
}
return result;
}
API struct lyd_difflist *
lyd_diff(struct lyd_node *first, struct lyd_node *second, int options)
{
struct ly_ctx *ctx;
int rc;
struct lyd_node *elem1, *elem2, *iter, *aux, *parent = NULL, *next1, *next2;
struct lyd_difflist *result, *result2 = NULL;
void *new;
unsigned int size, size2, index = 0, index2 = 0, i, j, k;
struct matchlist_s {
struct matchlist_s *prev;
struct ly_set *match;
unsigned int i;
} *matchlist = NULL, *mlaux;
struct ly_set *ordset = NULL;
struct diff_ordered *ordered;
struct diff_ordered_dist *dist_aux, *dist_iter;
struct diff_ordered_item item_aux;
if (!first) {
/* all nodes in second were created,
* but the second must be top level */
if (second && second->parent) {
LOGERR(second->schema->module->ctx, LY_EINVAL, "%s: \"first\" parameter is NULL and \"second\" is not top level.", __func__);
return NULL;
}
result = lyd_diff_init_difflist(NULL, &size);
LY_TREE_FOR(second, iter) {
if (!iter->dflt || (options & LYD_DIFFOPT_WITHDEFAULTS)) { /* skip the implicit nodes */
if (lyd_difflist_add(result, &size, index++, LYD_DIFF_CREATED, NULL, iter)) {
goto error;
}
}
if (options & LYD_DIFFOPT_NOSIBLINGS) {
break;
}
}
return result;
} else if (!second) {
/* all nodes from first were deleted */
result = lyd_diff_init_difflist(first->schema->module->ctx, &size);
LY_TREE_FOR(first, iter) {
if (!iter->dflt || (options & LYD_DIFFOPT_WITHDEFAULTS)) { /* skip the implicit nodes */
if (lyd_difflist_add(result, &size, index++, LYD_DIFF_DELETED, iter, NULL)) {
goto error;
}
}
if (options & LYD_DIFFOPT_NOSIBLINGS) {
break;
}
}
return result;
}
ctx = first->schema->module->ctx;
if (options & LYD_DIFFOPT_NOSIBLINGS) {
/* both trees must start at the same (schema) node */
if (first->schema != second->schema) {
LOGERR(ctx, LY_EINVAL, "%s: incompatible trees to compare with LYD_OPT_NOSIBLINGS option.", __func__);
return NULL;
}
/* use first's and second's child to make comparison the same as without LYD_OPT_NOSIBLINGS */
first = first->child;
second = second->child;
} else {
/* go to the first sibling in both trees */
if (first->parent) {
first = first->parent->child;
} else {
while (first->prev->next) {
first = first->prev;
}
}
if (second->parent) {
second = second->parent->child;
} else {
for (; second->prev->next; second = second->prev);
}
/* check that both has the same (schema) parent or that they are top-level nodes */
if ((first->parent && second->parent && first->parent->schema != second->parent->schema) ||
(!first->parent && first->parent != second->parent)) {
LOGERR(ctx, LY_EINVAL, "%s: incompatible trees with different parents.", __func__);
return NULL;
}
}
if (first == second) {
LOGERR(ctx, LY_EINVAL, "%s: comparing the same tree does not make sense.", __func__);
return NULL;
}
/* initiate resulting structure */
result = lyd_diff_init_difflist(ctx, &size);
LY_CHECK_ERR_GOTO(!result, , error);
/* the records about created and moved items are created in
* bad order, so the records about created nodes (and their
* possible moving) is stored separately and added to the
* main result at the end.
*/
result2 = lyd_diff_init_difflist(ctx, &size2);
LY_CHECK_ERR_GOTO(!result2, , error);
matchlist = malloc(sizeof *matchlist);
LY_CHECK_ERR_GOTO(!matchlist, LOGMEM(ctx), error);
matchlist->i = 0;
matchlist->match = ly_set_new();
matchlist->prev = NULL;
ordset = ly_set_new();
LY_CHECK_ERR_GOTO(!ordset, , error);
/*
* compare trees
*/
/* 1) newly created nodes + changed leafs/anyxmls */
next1 = first;
for (elem2 = next2 = second; elem2; elem2 = next2) {
/* keep right pointer for searching in the first tree */
elem1 = next1;
if (elem2->dflt && !(options & LYD_DIFFOPT_WITHDEFAULTS)) {
/* skip default elements, they could not be created or changed, just deleted */
goto cmp_continue;
}
#ifdef LY_ENABLED_CACHE
struct lyd_node **iter_p;
if (elem1 && elem1->parent && elem1->parent->ht) {
iter = NULL;
if (!lyht_find(elem1->parent->ht, &elem2, elem2->hash, (void **)&iter_p)) {
iter = *iter_p;
/* we found a match */
if (iter->dflt && !(options & LYD_DIFFOPT_WITHDEFAULTS)) {
/* the second one cannot be default (see lyd_diff()),
* so the nodes differs (first one is default node) */
iter = NULL;
}
while (iter && (iter->validity & LYD_VAL_INUSE)) {
/* state lists, find one not-already-found */
assert((iter->schema->nodetype & (LYS_LIST | LYS_LEAFLIST)) && (iter->schema->flags & LYS_CONFIG_R));
if (lyht_find_next(elem1->parent->ht, &iter, iter->hash, (void **)&iter_p)) {
iter = NULL;
} else {
iter = *iter_p;
}
}
}
} else
#endif
{
/* search for elem2 instance in the first */
LY_TREE_FOR(elem1, iter) {
if (iter->schema != elem2->schema) {
continue;
}
/* elem2 instance found */
rc = lyd_diff_compare(iter, elem2, options);
if (rc == -1) {
goto error;
} else if (rc == 0) {
/* match */
break;
} /* else, continue */
}
}
/* we have a match */
if (iter && lyd_diff_match(iter, elem2, result, &size, &index, matchlist->match, ordset, options)) {
goto error;
}
if (!iter) {
/* elem2 not found in the first tree */
if (lyd_difflist_add(result2, &size2, index2++, LYD_DIFF_CREATED, elem1 ? elem1->parent : parent, elem2)) {
goto error;
}
if (elem1 && (elem2->schema->flags & LYS_USERORDERED)) {
/* store the correct place where the node is supposed to be moved after creation */
/* if elem1 does not exist, all nodes were created and they will be created in
* correct order, so it is not needed to detect moves */
for (aux = elem2->prev; aux->next; aux = aux->prev) {
if (aux->schema == elem2->schema) {
/* predecessor found */
break;
}
}
if (!aux->next) {
/* predecessor not found */
aux = NULL;
}
if (lyd_difflist_add(result2, &size2, index2++, LYD_DIFF_MOVEDAFTER2, aux, elem2)) {
goto error;
}
}
}
cmp_continue:
/* select element for the next run 1 2
* - first, process all siblings of a single parent / \ / \
* - then, go to children (deep) 3 4 7 8
* - return to the parent's next sibling children / \
* 5 6
*/
/* siblings first */
next1 = elem1;
next2 = elem2->next;
if (!next2) {
/* children */
/* first pass of the siblings done, some additional work for future
* detection of move may be needed */
for (i = ordset->number; i > 0; i--) {
ordered = (struct diff_ordered *)ordset->set.g[i - 1];
if (ordered->items) {
/* already preprocessed ordered structure */
break;
}
ordered->items = calloc(ordered->count, sizeof *ordered->items);
LY_CHECK_ERR_GOTO(!ordered->items, LOGMEM(ctx), error);
ordered->dist = NULL;
/* zero the count to be used as a node position in lyd_diff_move_preprocess() */
ordered->count = 0;
}
/* first, get the first sibling */
if (elem2->parent == second->parent) {
elem2 = second;
} else {
elem2 = elem2->parent->child;
}
/* and then find the first child */
LY_TREE_FOR(elem2, iter) {
if (!(iter->validity & LYD_VAL_INUSE)) {
/* the iter is not present in both trees */
continue;
} else if (matchlist->i == matchlist->match->number) {
if (iter == elem2) {
/* we already went through all the matching nodes and now we are just supposed to stop
* the loop with no iter */
iter = NULL;
break;
} else {
/* we have started with some not processed data in matchlist, but now we have
* the INUSE iter and no nodes in matchlist to find its equivalent,
* so something went wrong somewhere */
LOGINT(ctx);
goto error;
}
}
iter->validity &= ~LYD_VAL_INUSE;
if ((iter->schema->nodetype & (LYS_LEAFLIST | LYS_LIST)) && (iter->schema->flags & LYS_USERORDERED)) {
for (j = ordset->number; j > 0; j--) {
ordered = (struct diff_ordered *)ordset->set.g[j - 1];
if (ordered->schema != iter->schema || !lyd_diff_equivnode(ordered->parent, iter->parent)) {
continue;
}
/* store necessary information for move detection */
lyd_diff_move_preprocess(ordered, matchlist->match->set.d[matchlist->i], iter);
break;
}
}
if (((iter->schema->nodetype == LYS_CONTAINER) || ((iter->schema->nodetype == LYS_LIST)
&& ((struct lys_node_list *)iter->schema)->keys_size)) && iter->child) {
while (matchlist->i < matchlist->match->number && matchlist->match->set.d[matchlist->i]->schema != iter->schema) {
matchlist->i++;
}
if (matchlist->i == matchlist->match->number) {
/* we have the INUSE iter, so we have to find its equivalent in match list */
LOGINT(ctx);
goto error;
}
next1 = matchlist->match->set.d[matchlist->i]->child;
if (!next1) {
parent = matchlist->match->set.d[matchlist->i];
}
matchlist->i++;
next2 = iter->child;
break;
}
matchlist->i++;
}
if (!iter) {
/* no child/data on next level */
if (elem2 == second) {
/* done */
break;
}
} else {
/* create new matchlist item */
mlaux = malloc(sizeof *mlaux);
LY_CHECK_ERR_GOTO(!mlaux, LOGMEM(ctx), error);
mlaux->i = 0;
mlaux->match = ly_set_new();
mlaux->prev = matchlist;
matchlist = mlaux;
}
}
while (!next2) {
/* parent */
/* clean the last match set */
ly_set_clean(matchlist->match);
matchlist->i = 0;
/* try to go to a cousin - child of the next parent's sibling */
mlaux = matchlist->prev;
LY_TREE_FOR(elem2->parent->next, iter) {
if (!(iter->validity & LYD_VAL_INUSE)) {
continue;
} else if (mlaux->i == mlaux->match->number) {
if (iter == elem2->parent->next) {
/* we already went through all the matching nodes and now we are just supposed to stop
* the loop with no iter */
iter = NULL;
break;
} else {
/* we have started with some not processed data in matchlist, but now we have
* the INUSE iter and no nodes in matchlist to find its equivalent,
* so something went wrong somewhere */
LOGINT(ctx);
goto error;
}
}
iter->validity &= ~LYD_VAL_INUSE;
if ((iter->schema->nodetype & (LYS_LEAFLIST | LYS_LIST)) && (iter->schema->flags & LYS_USERORDERED)) {
for (j = ordset->number ; j > 0; j--) {
ordered = (struct diff_ordered *)ordset->set.g[j - 1];
if (ordered->schema != iter->schema || !lyd_diff_equivnode(ordered->parent, iter->parent)) {
continue;
}
/* store necessary information for move detection */
lyd_diff_move_preprocess(ordered, mlaux->match->set.d[mlaux->i], iter);
break;
}
}
if (((iter->schema->nodetype == LYS_CONTAINER) || ((iter->schema->nodetype == LYS_LIST)
&& ((struct lys_node_list *)iter->schema)->keys_size)) && iter->child) {
while (mlaux->i < mlaux->match->number && mlaux->match->set.d[mlaux->i]->schema != iter->schema) {
mlaux->i++;
}
if (mlaux->i == mlaux->match->number) {
/* we have the INUSE iter, so we have to find its equivalent in match list */
LOGINT(ctx);
goto error;
}
next1 = mlaux->match->set.d[mlaux->i]->child;
if (!next1) {
parent = mlaux->match->set.d[mlaux->i];
}
mlaux->i++;
next2 = iter->child;
break;
}
mlaux->i++;
}
/* if no cousin exists, continue next loop on higher level */
if (!iter) {
elem2 = elem2->parent;
/* remove matchlist item */
ly_set_free(matchlist->match);
mlaux = matchlist;
matchlist = matchlist->prev;
free(mlaux);
if (!matchlist->prev) { /* elem2->parent == second->parent */
/* done */
break;
}
}
}
}
ly_set_free(matchlist->match);
free(matchlist);
matchlist = NULL;
/* 2) deleted nodes */
LY_TREE_DFS_BEGIN(first, next1, elem1) {
/* search for elem1s deleted in the second */
if (elem1->validity & LYD_VAL_INUSE) {
/* erase temporary LYD_VAL_INUSE flag and continue into children */
elem1->validity &= ~LYD_VAL_INUSE;
} else if (!elem1->dflt || (options & LYD_DIFFOPT_WITHDEFAULTS)) {
/* elem1 has no matching node in second, add it into result */
if (lyd_difflist_add(result, &size, index++, LYD_DIFF_DELETED, elem1, NULL)) {
goto error;
}
/* skip subtree processing of data missing in the second tree */
goto dfs_nextsibling;
}
/* modified LY_TREE_DFS_END() */
/* select element for the next run - children first */
if ((elem1->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) || ((elem1->schema->nodetype == LYS_LIST)
&& !((struct lys_node_list *)elem1->schema)->keys_size)) {
next1 = NULL;
} else {
next1 = elem1->child;
}
if (!next1) {
dfs_nextsibling:
/* try siblings */
next1 = elem1->next;
}
while (!next1) {
/* parent is already processed, go to its sibling */
elem1 = elem1->parent;
if (elem1 == first->parent) {
/* we are done, no next element to process */
break;
}
next1 = elem1->next;
}
}
/* 3) moved nodes (when user-ordered) */
for (i = 0; i < ordset->number; i++) {
ordered = (struct diff_ordered *)ordset->set.g[i];
if (!ordered->dist->dist) {
/* the dist list is sorted here, but the biggest dist is 0,
* so nothing changed in order of these items between first
* and second. We can continue with another user-ordered list.
*/
continue;
}
/* get needed movements
* - from the biggest distances try to apply node movements
* on first tree node until they will be ordered as in the
* second tree - i.e. until there will be no position difference
*/
for (dist_iter = ordered->dist; ; dist_iter = dist_iter->next) {
/* dist list is sorted at the beginning, since applying a move causes
* just a small change in other distances, we assume that the biggest
* dist is the next one (note that dist list is implemented as ring
* list). This way we avoid sorting distances after each move. The loop
* stops when all distances are zero.
*/
dist_aux = dist_iter;
while (!dist_iter->dist) {
/* no dist, so no move. Try another, but when
* there is no dist at all, stop the loop
*/
dist_iter = dist_iter->next;
if (dist_iter == dist_aux) {
/* all dist we zeroed */
goto movedone;
}
}
/* something to move */
/* get the item to move */
for (k = 0; k < ordered->count; k++) {
if (ordered->items[k].dist == dist_iter) {
break;
}
}
/* apply the move (distance) */
memcpy(&item_aux, &ordered->items[k], sizeof item_aux);
if (dist_iter->dist > 0) {
/* move to right (other move to left) */
while (dist_iter->dist) {
memcpy(&ordered->items[k], &ordered->items[k + 1], sizeof *ordered->items);
ordered->items[k].dist->dist++; /* update moved item distance */
dist_iter->dist--;
k++;
}
} else {
/* move to left (other move to right) */
while (dist_iter->dist) {
memcpy(&ordered->items[k], &ordered->items[k - 1], sizeof *ordered->items);
ordered->items[k].dist->dist--; /* update moved item distance */
dist_iter->dist++;
k--;
}
}
memcpy(&ordered->items[k], &item_aux, sizeof *ordered->items);
/* store the transaction into the difflist */
if (lyd_difflist_add(result, &size, index++, LYD_DIFF_MOVEDAFTER1, item_aux.first,
(k > 0) ? ordered->items[k - 1].first : NULL)) {
goto error;
}
continue;
movedone:
break;
}
}
diff_ordset_free(ordset);
ordset = NULL;
if (index2) {
/* append result2 with newly created
* (and possibly moved) nodes */
if (index + index2 + 1 >= size) {
/* result must be enlarged */
size = index + index2 + 1;
new = realloc(result->type, size * sizeof *result->type);
LY_CHECK_ERR_GOTO(!new, LOGMEM(ctx), error);
result->type = new;
new = realloc(result->first, size * sizeof *result->first);
LY_CHECK_ERR_GOTO(!new, LOGMEM(ctx), error);
result->first = new;
new = realloc(result->second, size * sizeof *result->second);
LY_CHECK_ERR_GOTO(!new, LOGMEM(ctx), error);
result->second = new;
}
/* append */
memcpy(&result->type[index], result2->type, (index2 + 1) * sizeof *result->type);
memcpy(&result->first[index], result2->first, (index2 + 1) * sizeof *result->first);
memcpy(&result->second[index], result2->second, (index2 + 1) * sizeof *result->second);
}
lyd_free_diff(result2);
return result;
error:
while (matchlist) {
mlaux = matchlist;
matchlist = mlaux->prev;
ly_set_free(mlaux->match);
free(mlaux);
}
diff_ordset_free(ordset);
lyd_free_diff(result);
lyd_free_diff(result2);
return NULL;
}
static void
lyd_insert_setinvalid(struct lyd_node *node)
{
struct lyd_node *next, *elem, *parent_list;
assert(node);
/* overall validity of the node itself */
node->validity = ly_new_node_validity(node->schema);
/* explore changed unique leaves */
/* first, get know if there is a list in parents chain */
for (parent_list = node->parent;
parent_list && parent_list->schema->nodetype != LYS_LIST;
parent_list = parent_list->parent);
if (parent_list && !(parent_list->validity & LYD_VAL_UNIQUE)) {
/* there is a list, so check if we inserted a leaf supposed to be unique */
for (elem = node; elem; elem = next) {
if (elem->schema->nodetype == LYS_LIST) {
/* stop searching to the depth, children would be unique to a list in subtree */
goto nextsibling;
}
if (elem->schema->nodetype == LYS_LEAF && (elem->schema->flags & LYS_UNIQUE)) {
/* set flag to list for future validation */
parent_list->validity |= LYD_VAL_UNIQUE;
break;
}
if (elem->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
if (elem == node) {
/* stop the loop */
break;
}
goto nextsibling;
}
/* select next elem to process */
/* go into children */
next = elem->child;
/* go through siblings */
if (!next) {
nextsibling:
next = elem->next;
if (!next) {
/* no sibling */
if (elem == node) {
/* we are done, back in start node */
break;
}
}
}
/* go back to parents */
while (!next) {
elem = elem->parent;
if (elem->parent == node->parent) {
/* we are done, back in start node */
break;
}
/* parent was actually already processed, so go to the parent's sibling */
next = elem->parent->next;
}
}
}
if (node->parent) {
/* if the inserted node is list/leaflist with constraint on max instances,
* invalidate the parent to make it validate this */
if (node->schema->nodetype & LYS_LEAFLIST) {
if (((struct lys_node_leaflist *)node->schema)->max) {
node->parent->validity |= LYD_VAL_MAND;
}
} else if (node->schema->nodetype & LYS_LIST) {
if (((struct lys_node_list *)node->schema)->max) {
node->parent->validity |= LYD_VAL_MAND;
}
}
}
}
static void
lyd_replace(struct lyd_node *orig, struct lyd_node *repl, int destroy)
{
struct lyd_node *iter, *last;
if (!repl) {
/* remove the old one */
goto finish;
}
if (repl->parent || repl->prev->next) {
/* isolate the new node */
repl->next = NULL;
repl->prev = repl;
last = repl;
} else {
/* get the last node of a possible list of nodes to be inserted */
for(last = repl; last->next; last = last->next) {
/* part of the parent changes */
last->parent = orig->parent;
}
}
/* parent */
if (orig->parent) {
if (orig->parent->child == orig) {
orig->parent->child = repl;
}
orig->parent = NULL;
}
/* predecessor */
if (orig->prev == orig) {
/* the old was alone */
goto finish;
}
if (orig->prev->next) {
orig->prev->next = repl;
}
repl->prev = orig->prev;
orig->prev = orig;
/* successor */
if (orig->next) {
orig->next->prev = last;
last->next = orig->next;
orig->next = NULL;
} else {
/* fix the last pointer */
if (repl->parent) {
repl->parent->child->prev = last;
} else {
/* get the first sibling */
for (iter = repl; iter->prev != orig; iter = iter->prev);
iter->prev = last;
}
}
finish:
/* remove the old one */
if (destroy) {
lyd_free(orig);
}
}
int
lyd_insert_common(struct lyd_node *parent, struct lyd_node **sibling, struct lyd_node *node, int invalidate)
{
struct lys_node *par1, *par2;
const struct lys_node *siter;
struct lyd_node *start, *iter, *ins, *next1, *next2;
int invalid = 0, isrpc = 0, clrdflt = 0;
struct ly_set *llists = NULL;
int i;
uint8_t pos;
int stype = LYS_INPUT | LYS_OUTPUT;
assert(parent || sibling);
/* get first sibling */
if (parent) {
start = parent->child;
} else {
for (start = *sibling; start->prev->next; start = start->prev);
}
/* check placing the node to the appropriate place according to the schema */
if (!start) {
if (!parent) {
/* empty tree to insert */
if (node->parent || node->prev->next) {
/* unlink the node first */
lyd_unlink_internal(node, 1);
} /* else insert also node's siblings */
*sibling = node;
return EXIT_SUCCESS;
}
par1 = parent->schema;
if (par1->nodetype & (LYS_RPC | LYS_ACTION)) {
/* it is not clear if the tree being created is going to
* be rpc (LYS_INPUT) or rpc-reply (LYS_OUTPUT) so we have to
* compare against LYS_RPC or LYS_ACTION in par2
*/
stype = LYS_RPC | LYS_ACTION;
}
} else if (parent && (parent->schema->nodetype & (LYS_RPC | LYS_ACTION))) {
par1 = parent->schema;
stype = LYS_RPC | LYS_ACTION;
} else {
for (par1 = lys_parent(start->schema);
par1 && !(par1->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_INPUT | LYS_OUTPUT | LYS_NOTIF));
par1 = lys_parent(par1));
}
for (par2 = lys_parent(node->schema);
par2 && !(par2->nodetype & (LYS_CONTAINER | LYS_LIST | stype | LYS_NOTIF));
par2 = lys_parent(par2));
if (par1 != par2) {
LOGERR(parent->schema->module->ctx, LY_EINVAL, "Cannot insert, different parents (\"%s\" and \"%s\").",
(par1 ? par1->name : "<top-lvl>"), (par2 ? par2->name : "<top-lvl>"));
return EXIT_FAILURE;
}
if (invalidate) {
invalid = isrpc = lyp_is_rpc_action(node->schema);
if (!parent || node->parent != parent || isrpc) {
/* it is not just moving under a parent node or it is in an RPC where
* nodes order matters, so the validation will be necessary */
invalid++;
}
}
/* unlink only if it is not a list of siblings without a parent and node is not the first sibling */
if (node->parent || node->prev->next) {
/* do it permanent if the parents are not exact same or if it is top-level */
lyd_unlink_internal(node, invalid);
}
llists = ly_set_new();
/* process the nodes to insert one by one */
LY_TREE_FOR_SAFE(node, next1, ins) {
if (invalid == 1) {
/* auto delete nodes from other cases, if any;
* this is done only if node->parent != parent */
if (lyv_multicases(ins, NULL, &start, 1, NULL)) {
goto error;
}
}
/* isolate the node to be handled separately */
ins->prev = ins;
ins->next = NULL;
iter = NULL;
if (!ins->dflt) {
clrdflt = 1;
}
/* are we inserting list key? */
if (!ins->dflt && ins->schema->nodetype == LYS_LEAF && lys_is_key((struct lys_node_leaf *)ins->schema, &pos)) {
/* yes, we have a key, get know its position */
for (i = 0, iter = parent->child;
iter && i < pos && iter->schema->nodetype == LYS_LEAF;
i++, iter = iter->next);
if (iter) {
/* insert list's key to the correct position - before the iter */
if (parent->child == iter) {
parent->child = ins;
}
if (iter->prev->next) {
iter->prev->next = ins;
}
ins->prev = iter->prev;
iter->prev = ins;
ins->next = iter;
/* update start element */
if (parent->child != start) {
start = parent->child;
}
}
/* try to find previously present default instance to replace */
} else if (ins->schema->nodetype == LYS_LEAFLIST) {
i = (int)llists->number;
if ((ly_set_add(llists, ins->schema, 0) != i) || ins->dflt) {
/* each leaf-list must be cleared only once (except when looking for exact same existing dflt nodes) */
LY_TREE_FOR_SAFE(start, next2, iter) {
if (iter->schema == ins->schema) {
if ((ins->dflt && (!iter->dflt || ((iter->schema->flags & LYS_CONFIG_W) &&
!strcmp(((struct lyd_node_leaf_list *)iter)->value_str,
((struct lyd_node_leaf_list *)ins)->value_str))))
|| (!ins->dflt && iter->dflt)) {
if (iter == start) {
start = next2;
}
lyd_free(iter);
}
}
}
}
} else if (ins->schema->nodetype == LYS_LEAF || (ins->schema->nodetype == LYS_CONTAINER
&& !((struct lys_node_container *)ins->schema)->presence)) {
LY_TREE_FOR(start, iter) {
if (iter->schema == ins->schema) {
if (ins->dflt || iter->dflt) {
/* replace existing (either explicit or default) node with the new (either explicit or default) node */
lyd_replace(iter, ins, 1);
} else {
/* keep both explicit nodes, let the caller solve it later */
iter = NULL;
}
break;
}
}
}
if (!iter) {
if (!start) {
/* add as the only child of the parent */
start = ins;
if (parent) {
parent->child = ins;
}
} else if (isrpc) {
/* add to the specific position in rpc/rpc-reply/action */
for (par1 = ins->schema->parent; !(par1->nodetype & (LYS_INPUT | LYS_OUTPUT)); par1 = lys_parent(par1));
siter = NULL;
LY_TREE_FOR(start, iter) {
while ((siter = lys_getnext(siter, par1, lys_node_module(par1), 0))) {
if (iter->schema == siter || ins->schema == siter) {
break;
}
}
if (ins->schema == siter) {
if ((siter->nodetype & (LYS_LEAFLIST | LYS_LIST)) && iter->schema == siter) {
/* we are inserting leaflist/list instance, but since there are already
* some instances of the same leaflist/list, we want to insert the new one
* as the last instance, so here we have to move on */
while (iter && iter->schema == siter) {
iter = iter->next;
}
if (!iter) {
break;
}
}
/* we have the correct place for new node (before the iter) */
if (iter == start) {
start = ins;
if (parent) {
parent->child = ins;
}
} else {
iter->prev->next = ins;
}
ins->prev = iter->prev;
iter->prev = ins;
ins->next = iter;
/* we are done */
break;
}
}
if (!iter) {
/* add as the last child of the parent */
start->prev->next = ins;
ins->prev = start->prev;
start->prev = ins;
}
} else {
/* add as the last child of the parent */
start->prev->next = ins;
ins->prev = start->prev;
start->prev = ins;
}
}
#ifdef LY_ENABLED_CACHE
lyd_unlink_hash(ins, ins->parent);
#endif
ins->parent = parent;
#ifdef LY_ENABLED_CACHE
lyd_insert_hash(ins);
#endif
if (invalidate) {
check_leaf_list_backlinks(ins, 0);
}
if (invalid) {
lyd_insert_setinvalid(ins);
}
}
ly_set_free(llists);
if (clrdflt) {
/* remove the dflt flag from parents */
for (iter = parent; iter && iter->dflt; iter = iter->parent) {
iter->dflt = 0;
}
}
if (sibling) {
*sibling = start;
}
return EXIT_SUCCESS;
error:
ly_set_free(llists);
return EXIT_FAILURE;
}
API int
lyd_insert(struct lyd_node *parent, struct lyd_node *node)
{
if (!node || !parent || (parent->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) {
LOGARG;
return EXIT_FAILURE;
}
return lyd_insert_common(parent, NULL, node, 1);
}
API int
lyd_insert_sibling(struct lyd_node **sibling, struct lyd_node *node)
{
if (!sibling || !node) {
LOGARG;
return EXIT_FAILURE;
}
return lyd_insert_common((*sibling) ? (*sibling)->parent : NULL, sibling, node, 1);
}
int
lyd_insert_nextto(struct lyd_node *sibling, struct lyd_node *node, int before, int invalidate)
{
struct ly_ctx *ctx;
struct lys_node *par1, *par2;
struct lyd_node *iter, *start = NULL, *ins, *next1, *next2, *last;
struct lyd_node *orig_parent = NULL, *orig_prev = NULL, *orig_next = NULL;
int invalid = 0;
char *str;
assert(sibling);
assert(node);
ctx = sibling->schema->module->ctx;
if (sibling == node) {
return EXIT_SUCCESS;
}
/* check placing the node to the appropriate place according to the schema */
for (par1 = lys_parent(sibling->schema);
par1 && !(par1->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_INPUT | LYS_OUTPUT | LYS_ACTION | LYS_NOTIF));
par1 = lys_parent(par1));
for (par2 = lys_parent(node->schema);
par2 && !(par2->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_INPUT | LYS_OUTPUT | LYS_ACTION | LYS_NOTIF));
par2 = lys_parent(par2));
if (par1 != par2) {
LOGERR(ctx, LY_EINVAL, "Cannot insert, different parents (\"%s\" and \"%s\").",
(par1 ? par1->name : "<top-lvl>"), (par2 ? par2->name : "<top-lvl>"));
return EXIT_FAILURE;
}
if (invalidate && ((node->parent != sibling->parent) || (invalid = lyp_is_rpc_action(node->schema)) || !node->parent)) {
/* a) it is not just moving under a parent node (invalid = 1) or
* b) it is in an RPC where nodes order matters (invalid = 2) or
* c) it is top-level where we don't know if it is the same tree (invalid = 1),
* so the validation will be necessary */
if (!node->parent && !invalid) {
/* c) search in siblings */
for (iter = node->prev; iter != node; iter = iter->prev) {
if (iter == sibling) {
break;
}
}
if (iter == node) {
/* node and siblings are not currently in the same data tree */
invalid++;
}
} else { /* a) and b) */
invalid++;
}
}
/* unlink only if it is not a list of siblings without a parent or node is not the first sibling,
* always unlink if just moving a node */
if ((!invalid) || node->parent || node->prev->next) {
/* remember the original position to be able to revert
* unlink in case of error */
orig_parent = node->parent;
if (node->prev != node) {
orig_prev = node->prev;
}
orig_next = node->next;
lyd_unlink_internal(node, invalid);
}
/* find first sibling node */
if (sibling->parent) {
start = sibling->parent->child;
} else {
for (start = sibling; start->prev->next; start = start->prev);
}
/* process the nodes one by one to clean the current tree */
if (!invalid) {
/* just moving one sibling */
last = node;
node->parent = sibling->parent;
} else {
LY_TREE_FOR_SAFE(node, next1, ins) {
lyd_insert_setinvalid(ins);
if (invalid == 1) {
/* auto delete nodes from other cases */
if (lyv_multicases(ins, NULL, &start, 1, sibling) == 2) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYD, sibling, "Insert request refers node (%s) that is going to be auto-deleted.",
ly_errpath(ctx));
goto error;
}
}
/* try to find previously present default instance to remove because of
* inserting the specified node */
if (ins->schema->nodetype == LYS_LEAFLIST) {
LY_TREE_FOR_SAFE(start, next2, iter) {
if (iter->schema == ins->schema) {
if ((ins->dflt && (!iter->dflt || ((iter->schema->flags & LYS_CONFIG_W) &&
!strcmp(((struct lyd_node_leaf_list *)iter)->value_str,
((struct lyd_node_leaf_list *)ins)->value_str))))
|| (!ins->dflt && iter->dflt)) {
/* iter will get deleted */
if (iter == sibling) {
LOGERR(ctx, LY_EINVAL, "Insert request refers node (%s) that is going to be auto-deleted.",
str = lyd_path(sibling));
free(str);
goto error;
}
if (iter == start) {
start = next2;
}
lyd_free(iter);
}
}
}
} else if (ins->schema->nodetype == LYS_LEAF ||
(ins->schema->nodetype == LYS_CONTAINER && !((struct lys_node_container *)ins->schema)->presence)) {
LY_TREE_FOR(start, iter) {
if (iter->schema == ins->schema) {
if (iter->dflt || ins->dflt) {
/* iter gets deleted */
if (iter == sibling) {
LOGERR(ctx, LY_EINVAL, "Insert request refers node (%s) that is going to be auto-deleted.",
str = lyd_path(sibling));
free(str);
goto error;
}
if (iter == start) {
start = iter->next;
}
lyd_free(iter);
}
break;
}
}
}
#ifdef LY_ENABLED_CACHE
lyd_unlink_hash(ins, ins->parent);
#endif
ins->parent = sibling->parent;
#ifdef LY_ENABLED_CACHE
lyd_insert_hash(ins);
#endif
last = ins;
}
}
/* insert the (list of) node(s) to the specified position */
if (before) {
if (sibling->prev->next) {
/* adding into a middle */
sibling->prev->next = node;
} else if (sibling->parent) {
/* at the beginning */
sibling->parent->child = node;
}
node->prev = sibling->prev;
sibling->prev = last;
last->next = sibling;
} else { /* after */
if (sibling->next) {
/* adding into a middle - fix the prev pointer of the node after inserted nodes */
last->next = sibling->next;
sibling->next->prev = last;
} else {
/* at the end - fix the prev pointer of the first node */
start->prev = last;
}
sibling->next = node;
node->prev = sibling;
}
if (invalidate) {
LY_TREE_FOR(node, next1) {
check_leaf_list_backlinks(next1, 0);
if (next1 == last) {
break;
}
}
}
return EXIT_SUCCESS;
error:
/* insert back to the original position */
if (orig_prev) {
lyd_insert_after(orig_prev, node);
} else if (orig_next) {
lyd_insert_before(orig_next, node);
} else if (orig_parent) {
/* there were no siblings */
orig_parent->child = node;
node->parent = orig_parent;
}
return EXIT_FAILURE;
}
API int
lyd_insert_before(struct lyd_node *sibling, struct lyd_node *node)
{
if (!node || !sibling) {
LOGARG;
return EXIT_FAILURE;
}
return lyd_insert_nextto(sibling, node, 1, 1);
}
API int
lyd_insert_after(struct lyd_node *sibling, struct lyd_node *node)
{
if (!node || !sibling) {
LOGARG;
return EXIT_FAILURE;
}
return lyd_insert_nextto(sibling, node, 0, 1);
}
static uint32_t
lys_module_pos(struct lys_module *module)
{
int i;
uint32_t pos = 1;
for (i = 0; i < module->ctx->models.used; ++i) {
if (module->ctx->models.list[i] == module) {
return pos;
}
++pos;
}
LOGINT(module->ctx);
return 0;
}
static int
lys_module_node_pos_r(struct lys_node *first_sibling, struct lys_node *target, uint32_t *pos)
{
const struct lys_node *next = NULL;
/* the schema nodes are actually from data, lys_getnext skips non-data schema nodes for us (we know the parent will not be uses) */
while ((next = lys_getnext(next, lys_parent(first_sibling), lys_node_module(first_sibling), LYS_GETNEXT_NOSTATECHECK))) {
++(*pos);
if (target == next) {
return 0;
}
}
LOGINT(first_sibling->module->ctx);
return 1;
}
static int
lyd_node_pos_cmp(const void *item1, const void *item2)
{
uint32_t mpos1, mpos2;
struct lyd_node_pos *np1, *np2;
np1 = (struct lyd_node_pos *)item1;
np2 = (struct lyd_node_pos *)item2;
/* different modules? */
if (lys_node_module(np1->node->schema) != lys_node_module(np2->node->schema)) {
mpos1 = lys_module_pos(lys_node_module(np1->node->schema));
mpos2 = lys_module_pos(lys_node_module(np2->node->schema));
/* if lys_module_pos failed, there is nothing we can do anyway,
* at least internal error will be printed */
if (mpos1 > mpos2) {
return 1;
} else {
return -1;
}
}
if (np1->pos > np2->pos) {
return 1;
} else if (np1->pos < np2->pos) {
return -1;
}
return 0;
}
API int
lyd_schema_sort(struct lyd_node *sibling, int recursive)
{
uint32_t len, i;
struct lyd_node *node;
struct lys_node *first_ssibling = NULL;
struct lyd_node_pos *array;
if (!sibling) {
LOGARG;
return -1;
}
/* something actually to sort */
if (sibling->prev != sibling) {
/* find the beginning */
sibling = lyd_first_sibling(sibling);
/* count siblings */
len = 0;
for (node = sibling; node; node = node->next) {
++len;
}
array = malloc(len * sizeof *array);
LY_CHECK_ERR_RETURN(!array, LOGMEM(sibling->schema->module->ctx), -1);
/* fill arrays with positions and corresponding nodes */
for (i = 0, node = sibling; i < len; ++i, node = node->next) {
array[i].pos = 0;
/* we need to repeat this for every module */
if (!first_ssibling || (lyd_node_module(node) != lys_node_module(first_ssibling))) {
/* find the data node schema parent */
first_ssibling = node->schema;
while (lys_parent(first_ssibling)
&& (lys_parent(first_ssibling)->nodetype & (LYS_CHOICE | LYS_CASE | LYS_USES))) {
first_ssibling = lys_parent(first_ssibling);
}
/* find the beginning */
if (lys_parent(first_ssibling)) {
first_ssibling = lys_parent(first_ssibling)->child;
} else {
while (first_ssibling->prev->next) {
first_ssibling = first_ssibling->prev;
}
}
}
if (lys_module_node_pos_r(first_ssibling, node->schema, &array[i].pos)) {
free(array);
return -1;
}
array[i].node = node;
}
/* sort the arrays */
qsort(array, len, sizeof *array, lyd_node_pos_cmp);
/* adjust siblings based on the sorted array */
for (i = 0; i < len; ++i) {
/* parent child */
if (i == 0) {
/* adjust sibling so that it still points to the beginning */
sibling = array[i].node;
if (array[i].node->parent) {
array[i].node->parent->child = array[i].node;
}
}
/* prev */
if (i > 0) {
array[i].node->prev = array[i - 1].node;
} else {
array[i].node->prev = array[len - 1].node;
}
/* next */
if (i < len - 1) {
array[i].node->next = array[i + 1].node;
} else {
array[i].node->next = NULL;
}
}
free(array);
}
/* sort all the children recursively */
if (recursive) {
LY_TREE_FOR(sibling, node) {
if ((node->schema->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_RPC | LYS_ACTION | LYS_NOTIF))
&& node->child && lyd_schema_sort(node->child, recursive)) {
return -1;
}
}
}
return EXIT_SUCCESS;
}
static int
_lyd_validate(struct lyd_node **node, struct lyd_node *data_tree, struct ly_ctx *ctx, const struct lys_module **modules,
int mod_count, struct lyd_difflist **diff, int options)
{
struct lyd_node *root, *next1, *next2, *iter, *act_notif = NULL;
int ret = EXIT_FAILURE;
unsigned int i;
struct unres_data *unres = NULL;
const struct lys_module *yanglib_mod;
unres = calloc(1, sizeof *unres);
LY_CHECK_ERR_RETURN(!unres, LOGMEM(NULL), EXIT_FAILURE);
if (diff) {
unres->store_diff = 1;
unres->diff = lyd_diff_init_difflist(ctx, &unres->diff_size);
}
if ((options & (LYD_OPT_RPC | LYD_OPT_RPCREPLY)) && *node && ((*node)->schema->nodetype != LYS_RPC)) {
options |= LYD_OPT_ACT_NOTIF;
}
if ((options & (LYD_OPT_NOTIF | LYD_OPT_NOTIF_FILTER)) && *node && ((*node)->schema->nodetype != LYS_NOTIF)) {
options |= LYD_OPT_ACT_NOTIF;
}
LY_TREE_FOR_SAFE(*node, next1, root) {
if (modules) {
for (i = 0; i < (unsigned)mod_count; ++i) {
if (lyd_node_module(root) == modules[i]) {
break;
}
}
if (i == (unsigned)mod_count) {
/* skip data that should not be validated */
continue;
}
}
LY_TREE_DFS_BEGIN(root, next2, iter) {
if (iter->parent && (iter->schema->nodetype & (LYS_ACTION | LYS_NOTIF))) {
if (!(options & LYD_OPT_ACT_NOTIF) || act_notif) {
LOGVAL(ctx, LYE_INELEM, LY_VLOG_LYD, iter, iter->schema->name);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Unexpected %s node \"%s\".",
(options & LYD_OPT_RPC ? "action" : "notification"), iter->schema->name);
goto cleanup;
}
act_notif = iter;
}
if (lyv_data_context(iter, options, unres) || lyv_data_content(iter, options, unres)) {
goto cleanup;
}
/* basic validation successful */
iter->validity &= ~LYD_VAL_MAND;
/* empty non-default, non-presence container without attributes, make it default */
if (!iter->dflt && (iter->schema->nodetype == LYS_CONTAINER) && !iter->child
&& !((struct lys_node_container *)iter->schema)->presence && !iter->attr) {
iter->dflt = 1;
}
LY_TREE_DFS_END(root, next2, iter);
}
if (options & LYD_OPT_NOSIBLINGS) {
break;
}
}
if (options & LYD_OPT_ACT_NOTIF) {
if (!act_notif) {
LOGVAL(ctx, LYE_MISSELEM, LY_VLOG_LYD, *node, (options & LYD_OPT_RPC ? "action" : "notification"), (*node)->schema->name);
goto cleanup;
}
options &= ~LYD_OPT_ACT_NOTIF;
}
if (*node) {
/* check for uniqueness of top-level lists/leaflists because
* only the inner instances were tested in lyv_data_content() */
yanglib_mod = ly_ctx_get_module(ctx ? ctx : (*node)->schema->module->ctx, "ietf-yang-library", NULL, 1);
LY_TREE_FOR(*node, root) {
if ((options & LYD_OPT_DATA_ADD_YANGLIB) && yanglib_mod && (root->schema->module == yanglib_mod)) {
/* ietf-yang-library data present, so ignore the option to add them */
options &= ~LYD_OPT_DATA_ADD_YANGLIB;
}
if (!(root->schema->nodetype & (LYS_LIST | LYS_LEAFLIST)) || !(root->validity & LYD_VAL_DUP)) {
continue;
}
if (options & LYD_OPT_TRUSTED) {
/* just clear the flag */
root->validity &= ~LYD_VAL_DUP;
continue;
}
if (lyv_data_dup(root, *node)) {
goto cleanup;
}
}
}
/* add missing ietf-yang-library if requested */
if (options & LYD_OPT_DATA_ADD_YANGLIB) {
if (!(*node)) {
(*node) = ly_ctx_info(ctx);
} else if (lyd_merge((*node), ly_ctx_info(ctx), LYD_OPT_DESTRUCT | LYD_OPT_EXPLICIT)) {
LOGERR(ctx, LY_EINT, "Adding ietf-yang-library data failed.");
goto cleanup;
}
}
/* add default values, resolve unres and check for mandatory nodes in final tree */
if (lyd_defaults_add_unres(node, options, ctx, modules, mod_count, data_tree, act_notif, unres, 1)) {
goto cleanup;
}
if (act_notif) {
if (lyd_check_mandatory_tree(act_notif, ctx, modules, mod_count, options)) {
goto cleanup;
}
} else {
if (lyd_check_mandatory_tree(*node, ctx, modules, mod_count, options)) {
goto cleanup;
}
}
/* consolidate diff if created */
if (diff) {
assert(unres->store_diff);
for (i = 0; i < unres->diff_idx; ++i) {
if (unres->diff->type[i] == LYD_DIFF_CREATED) {
if (unres->diff->second[i]->parent) {
unres->diff->first[i] = (struct lyd_node *)lyd_path(unres->diff->second[i]->parent);
}
unres->diff->second[i] = lyd_dup(unres->diff->second[i], LYD_DUP_OPT_RECURSIVE);
}
}
*diff = unres->diff;
unres->diff = 0;
unres->diff_idx = 0;
}
ret = EXIT_SUCCESS;
cleanup:
if (unres) {
free(unres->node);
free(unres->type);
for (i = 0; i < unres->diff_idx; ++i) {
if (unres->diff->type[i] == LYD_DIFF_DELETED) {
lyd_free_withsiblings(unres->diff->first[i]);
free(unres->diff->second[i]);
}
}
lyd_free_diff(unres->diff);
free(unres);
}
return ret;
}
API int
lyd_validate(struct lyd_node **node, int options, void *var_arg, ...)
{
struct lyd_node *iter, *data_tree = NULL;
struct lyd_difflist **diff = NULL;
struct ly_ctx *ctx = NULL;
va_list ap;
if (!node) {
LOGARG;
return EXIT_FAILURE;
}
if (lyp_data_check_options(NULL, options, __func__)) {
return EXIT_FAILURE;
}
data_tree = *node;
if ((!(options & LYD_OPT_TYPEMASK)
|| (options & (LYD_OPT_CONFIG | LYD_OPT_GET | LYD_OPT_GETCONFIG | LYD_OPT_EDIT))) && !(*node)) {
/* get context with schemas from the var_arg */
ctx = (struct ly_ctx *)var_arg;
if (!ctx) {
LOGERR(NULL, LY_EINVAL, "%s: invalid variable parameter (struct ly_ctx *ctx).", __func__);
return EXIT_FAILURE;
}
/* LYD_OPT_NOSIBLINGS has no meaning here */
options &= ~LYD_OPT_NOSIBLINGS;
} else if (options & (LYD_OPT_RPC | LYD_OPT_RPCREPLY | LYD_OPT_NOTIF)) {
/* LYD_OPT_NOSIBLINGS cannot be set in this case */
if (options & LYD_OPT_NOSIBLINGS) {
LOGERR(NULL, LY_EINVAL, "%s: invalid parameter (variable arg const struct lyd_node *data_tree with LYD_OPT_NOSIBLINGS).", __func__);
return EXIT_FAILURE;
} else if (!(*node)) {
LOGARG;
return EXIT_FAILURE;
}
/* get the additional data tree if given */
data_tree = (struct lyd_node *)var_arg;
if (data_tree) {
if (options & LYD_OPT_NOEXTDEPS) {
LOGERR(NULL, LY_EINVAL, "%s: invalid parameter (variable arg const struct lyd_node *data_tree and LYD_OPT_NOEXTDEPS set).",
__func__);
return EXIT_FAILURE;
}
LY_TREE_FOR(data_tree, iter) {
if (iter->parent) {
/* a sibling is not top-level */
LOGERR(NULL, LY_EINVAL, "%s: invalid variable parameter (const struct lyd_node *data_tree).", __func__);
return EXIT_FAILURE;
}
}
/* move it to the beginning */
for (; data_tree->prev->next; data_tree = data_tree->prev);
}
} else if (options & LYD_OPT_DATA_TEMPLATE) {
/* get context with schemas from the var_arg */
if (*node && ((*node)->prev->next || (*node)->next)) {
/* not allow sibling in top-level */
LOGERR(NULL, LY_EINVAL, "%s: invalid variable parameter (struct lyd_node *node).", __func__);
return EXIT_FAILURE;
}
}
if (options & LYD_OPT_VAL_DIFF) {
va_start(ap, var_arg);
diff = va_arg(ap, struct lyd_difflist **);
va_end(ap);
if (!diff) {
LOGERR(ctx, LY_EINVAL, "%s: invalid variable parameter (struct lyd_difflist **).", __func__);
return EXIT_FAILURE;
}
}
if (*node) {
if (!ctx) {
ctx = (*node)->schema->module->ctx;
}
if (!(options & LYD_OPT_NOSIBLINGS)) {
/* check that the node is the first sibling */
while ((*node)->prev->next) {
*node = (*node)->prev;
}
}
}
return _lyd_validate(node, data_tree, ctx, NULL, 0, diff, options);
}
API int
lyd_validate_modules(struct lyd_node **node, const struct lys_module **modules, int mod_count, int options, ...)
{
struct ly_ctx *ctx;
struct lyd_difflist **diff = NULL;
va_list ap;
if (!node || !modules || !mod_count) {
LOGARG;
return EXIT_FAILURE;
}
ctx = modules[0]->ctx;
if (*node && !(options & LYD_OPT_NOSIBLINGS)) {
/* check that the node is the first sibling */
while ((*node)->prev->next) {
*node = (*node)->prev;
}
}
if (lyp_data_check_options(ctx, options, __func__)) {
return EXIT_FAILURE;
}
if ((options & LYD_OPT_TYPEMASK) && !(options & (LYD_OPT_CONFIG | LYD_OPT_GET | LYD_OPT_GETCONFIG | LYD_OPT_EDIT))) {
LOGERR(NULL, LY_EINVAL, "%s: options include a forbidden data type.", __func__);
return EXIT_FAILURE;
}
if (options & LYD_OPT_VAL_DIFF) {
va_start(ap, options);
diff = va_arg(ap, struct lyd_difflist **);
va_end(ap);
if (!diff) {
LOGERR(ctx, LY_EINVAL, "%s: invalid variable parameter (struct lyd_difflist **).", __func__);
return EXIT_FAILURE;
}
}
return _lyd_validate(node, *node, ctx, modules, mod_count, diff, options);
}
API int
lyd_validate_value(struct lys_node *node, const char *value)
{
struct lyd_node_leaf_list leaf;
struct lys_node_leaf *sleaf = (struct lys_node_leaf*)node;
int ret = EXIT_SUCCESS;
if (!node || !(node->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
LOGARG;
return EXIT_FAILURE;
}
if (!value) {
value = "";
}
/* dummy leaf */
memset(&leaf, 0, sizeof leaf);
leaf.value_str = lydict_insert(node->module->ctx, value, 0);
repeat:
leaf.value_type = sleaf->type.base;
leaf.schema = node;
if (leaf.value_type == LY_TYPE_LEAFREF) {
if (!sleaf->type.info.lref.target) {
/* it should either be unresolved leafref (leaf.value_type are ORed flags) or it will be resolved */
LOGINT(node->module->ctx);
ret = EXIT_FAILURE;
goto cleanup;
}
sleaf = sleaf->type.info.lref.target;
goto repeat;
} else {
if (!lyp_parse_value(&sleaf->type, &leaf.value_str, NULL, &leaf, NULL, NULL, 0, 0, 0)) {
ret = EXIT_FAILURE;
goto cleanup;
}
}
cleanup:
lydict_remove(node->module->ctx, leaf.value_str);
return ret;
}
/* create an attribute copy */
static struct lyd_attr *
lyd_dup_attr(struct ly_ctx *ctx, struct lyd_node *parent, struct lyd_attr *attr)
{
struct lyd_attr *ret;
/* allocate new attr */
if (!parent->attr) {
parent->attr = malloc(sizeof *parent->attr);
ret = parent->attr;
} else {
for (ret = parent->attr; ret->next; ret = ret->next);
ret->next = calloc(1, sizeof *ret);
ret = ret->next;
}
LY_CHECK_ERR_RETURN(!ret, LOGMEM(ctx), NULL);
/* fill new attr except */
ret->parent = parent;
ret->next = NULL;
ret->annotation = attr->annotation;
ret->name = lydict_insert(ctx, attr->name, 0);
ret->value_str = lydict_insert(ctx, attr->value_str, 0);
ret->value_type = attr->value_type;
ret->value_flags = attr->value_flags;
switch (ret->value_type) {
case LY_TYPE_BINARY:
case LY_TYPE_STRING:
/* value_str pointer is shared in these cases */
ret->value.string = ret->value_str;
break;
case LY_TYPE_LEAFREF:
lyp_parse_value(*((struct lys_type **)lys_ext_complex_get_substmt(LY_STMT_TYPE, ret->annotation, NULL)),
&ret->value_str, NULL, NULL, ret, NULL, 1, 0, 0);
break;
case LY_TYPE_INST:
ret->value.instance = NULL;
break;
case LY_TYPE_UNION:
/* unresolved union (this must be non-validated tree), duplicate the stored string (duplicated
* because of possible change of the value in case of instance-identifier) */
ret->value.string = lydict_insert(ctx, attr->value.string, 0);
break;
case LY_TYPE_ENUM:
case LY_TYPE_IDENT:
case LY_TYPE_BITS:
/* in case of duplicating bits (no matter if in the same context or not) or enum and identityref into
* a different context, searching for the type and duplicating the data is almost as same as resolving
* the string value, so due to a simplicity, parse the value for the duplicated leaf */
lyp_parse_value(*((struct lys_type **)lys_ext_complex_get_substmt(LY_STMT_TYPE, ret->annotation, NULL)),
&ret->value_str, NULL, NULL, ret, NULL, 1, 0, 0);
break;
default:
ret->value = attr->value;
break;
}
return ret;
}
int
lyd_unlink_internal(struct lyd_node *node, int permanent)
{
struct lyd_node *iter;
if (!node) {
LOGARG;
return EXIT_FAILURE;
}
if (permanent) {
check_leaf_list_backlinks(node, 1);
}
/* unlink from siblings */
if (node->prev->next) {
node->prev->next = node->next;
}
if (node->next) {
node->next->prev = node->prev;
} else {
/* unlinking the last node */
if (node->parent) {
iter = node->parent->child;
} else {
iter = node->prev;
while (iter->prev != node) {
iter = iter->prev;
}
}
/* update the "last" pointer from the first node */
iter->prev = node->prev;
}
/* unlink from parent */
if (node->parent) {
if (node->parent->child == node) {
/* the node is the first child */
node->parent->child = node->next;
}
#ifdef LY_ENABLED_CACHE
/* do not remove from parent hash table if freeing the whole subtree */
if (permanent != 2) {
lyd_unlink_hash(node, node->parent);
}
#endif
node->parent = NULL;
}
node->next = NULL;
node->prev = node;
return EXIT_SUCCESS;
}
API int
lyd_unlink(struct lyd_node *node)
{
return lyd_unlink_internal(node, 1);
}
/*
* - in leaflist it must be added with value_str
*/
static int
_lyd_dup_node_common(struct lyd_node *new_node, const struct lyd_node *orig, struct ly_ctx *ctx, int options)
{
struct lyd_attr *attr;
new_node->attr = NULL;
if (!(options & LYD_DUP_OPT_NO_ATTR)) {
LY_TREE_FOR(orig->attr, attr) {
lyd_dup_attr(ctx, new_node, attr);
}
}
new_node->next = NULL;
new_node->prev = new_node;
new_node->parent = NULL;
new_node->validity = ly_new_node_validity(new_node->schema);
new_node->dflt = orig->dflt;
new_node->when_status = orig->when_status & LYD_WHEN;
#ifdef LY_ENABLED_CACHE
/* just copy the hash, it will not change */
if ((new_node->schema->nodetype != LYS_LIST) || lyd_list_has_keys(new_node)) {
new_node->hash = orig->hash;
}
#endif
#ifdef LY_ENABLED_LYD_PRIV
if (ctx->priv_dup_clb) {
new_node->priv = ctx->priv_dup_clb(orig->priv);
}
#endif
return EXIT_SUCCESS;
}
static struct lyd_node *
_lyd_dup_node(const struct lyd_node *node, const struct lys_node *schema, struct ly_ctx *ctx, int options)
{
struct lyd_node *new_node = NULL;
struct lys_node_leaf *sleaf;
struct lyd_node_leaf_list *new_leaf;
struct lyd_node_anydata *new_any, *old_any;
int r;
/* fill specific part */
switch (node->schema->nodetype) {
case LYS_LEAF:
case LYS_LEAFLIST:
new_leaf = calloc(1, sizeof *new_leaf);
new_node = (struct lyd_node *)new_leaf;
LY_CHECK_ERR_GOTO(!new_node, LOGMEM(ctx), error);
new_node->schema = (struct lys_node *)schema;
new_leaf->value_str = lydict_insert(ctx, ((struct lyd_node_leaf_list *)node)->value_str, 0);
new_leaf->value_type = ((struct lyd_node_leaf_list *)node)->value_type;
new_leaf->value_flags = ((struct lyd_node_leaf_list *)node)->value_flags;
if (_lyd_dup_node_common(new_node, node, ctx, options)) {
goto error;
}
/* get schema from the correct context */
sleaf = (struct lys_node_leaf *)new_leaf->schema;
switch (new_leaf->value_type) {
case LY_TYPE_BINARY:
case LY_TYPE_STRING:
/* value_str pointer is shared in these cases */
new_leaf->value.string = new_leaf->value_str;
break;
case LY_TYPE_LEAFREF:
new_leaf->validity |= LYD_VAL_LEAFREF;
lyp_parse_value(&sleaf->type, &new_leaf->value_str, NULL, new_leaf, NULL, NULL, 1, node->dflt, 0);
break;
case LY_TYPE_INST:
new_leaf->value.instance = NULL;
break;
case LY_TYPE_UNION:
/* unresolved union (this must be non-validated tree), duplicate the stored string (duplicated
* because of possible change of the value in case of instance-identifier) */
new_leaf->value.string = lydict_insert(ctx, ((struct lyd_node_leaf_list *)node)->value.string, 0);
break;
case LY_TYPE_ENUM:
case LY_TYPE_IDENT:
case LY_TYPE_BITS:
/* in case of duplicating bits (no matter if in the same context or not) or enum and identityref into
* a different context, searching for the type and duplicating the data is almost as same as resolving
* the string value, so due to a simplicity, parse the value for the duplicated leaf */
if (!lyp_parse_value(&sleaf->type, &new_leaf->value_str, NULL, new_leaf, NULL, NULL, 1, node->dflt, 0)) {
goto error;
}
break;
default:
new_leaf->value = ((struct lyd_node_leaf_list *)node)->value;
break;
}
if (sleaf->type.der && sleaf->type.der->module) {
r = lytype_store(sleaf->type.der->module, sleaf->type.der->name, new_leaf->value_str, &new_leaf->value);
if (r == -1) {
goto error;
} else if (!r) {
new_leaf->value_flags |= LY_VALUE_USER;
}
}
break;
case LYS_ANYXML:
case LYS_ANYDATA:
old_any = (struct lyd_node_anydata *)node;
new_any = calloc(1, sizeof *new_any);
new_node = (struct lyd_node *)new_any;
LY_CHECK_ERR_GOTO(!new_node, LOGMEM(ctx), error);
new_node->schema = (struct lys_node *)schema;
if (_lyd_dup_node_common(new_node, node, ctx, options)) {
goto error;
}
new_any->value_type = old_any->value_type;
if (!(void*)old_any->value.tree) {
/* no value to duplicate */
break;
}
/* duplicate the value */
switch (old_any->value_type) {
case LYD_ANYDATA_CONSTSTRING:
case LYD_ANYDATA_SXML:
case LYD_ANYDATA_JSON:
new_any->value.str = lydict_insert(ctx, old_any->value.str, 0);
break;
case LYD_ANYDATA_DATATREE:
new_any->value.tree = lyd_dup_to_ctx(old_any->value.tree, 1, ctx);
break;
case LYD_ANYDATA_XML:
new_any->value.xml = lyxml_dup_elem(ctx, old_any->value.xml, NULL, 1);
break;
case LYD_ANYDATA_LYB:
r = lyd_lyb_data_length(old_any->value.mem);
if (r == -1) {
LOGERR(ctx, LY_EINVAL, "Invalid LYB data.");
goto error;
}
new_any->value.mem = malloc(r);
LY_CHECK_ERR_GOTO(!new_any->value.mem, LOGMEM(ctx), error);
memcpy(new_any->value.mem, old_any->value.mem, r);
break;
case LYD_ANYDATA_STRING:
case LYD_ANYDATA_SXMLD:
case LYD_ANYDATA_JSOND:
case LYD_ANYDATA_LYBD:
/* dynamic strings are used only as input parameters */
assert(0);
break;
}
break;
case LYS_CONTAINER:
case LYS_LIST:
case LYS_NOTIF:
case LYS_RPC:
case LYS_ACTION:
new_node = calloc(1, sizeof *new_node);
LY_CHECK_ERR_GOTO(!new_node, LOGMEM(ctx), error);
new_node->schema = (struct lys_node *)schema;
if (_lyd_dup_node_common(new_node, node, ctx, options)) {
goto error;
}
break;
default:
LOGINT(ctx);
goto error;
}
return new_node;
error:
lyd_free(new_node);
return NULL;
}
API struct lyd_node *
lyd_dup_to_ctx(const struct lyd_node *node, int options, struct ly_ctx *ctx)
{
struct ly_ctx *log_ctx;
struct lys_node_list *slist;
struct lys_node *schema;
const char *yang_data_name;
const struct lys_module *trg_mod;
const struct lyd_node *next, *elem;
struct lyd_node *ret, *parent, *key, *key_dup, *new_node = NULL;
uint16_t i;
if (!node) {
LOGARG;
return NULL;
}
log_ctx = (ctx ? ctx : node->schema->module->ctx);
if (ctx == node->schema->module->ctx) {
/* target context is actually the same as the source context,
* ignore the target context */
ctx = NULL;
}
ret = NULL;
parent = NULL;
/* LY_TREE_DFS */
for (elem = next = node; elem; elem = next) {
/* find the correct schema */
if (ctx) {
schema = NULL;
if (parent) {
trg_mod = lyp_get_module(parent->schema->module, NULL, 0, lyd_node_module(elem)->name,
strlen(lyd_node_module(elem)->name), 1);
if (!trg_mod) {
LOGERR(log_ctx, LY_EINVAL, "Target context does not contain model for the data node being duplicated (%s).",
lyd_node_module(elem)->name);
goto error;
}
/* we know its parent, so we can start with it */
lys_getnext_data(trg_mod, parent->schema, elem->schema->name, strlen(elem->schema->name),
elem->schema->nodetype, 0, (const struct lys_node **)&schema);
} else {
/* we have to search in complete context */
schema = lyd_get_schema_inctx(elem, ctx);
}
if (!schema) {
yang_data_name = lyp_get_yang_data_template_name(elem);
if (yang_data_name) {
LOGERR(log_ctx, LY_EINVAL, "Target context does not contain schema node for the data node being duplicated "
"(%s:#%s/%s).", lyd_node_module(elem)->name, yang_data_name, elem->schema->name);
} else {
LOGERR(log_ctx, LY_EINVAL, "Target context does not contain schema node for the data node being duplicated "
"(%s:%s).", lyd_node_module(elem)->name, elem->schema->name);
}
goto error;
}
} else {
schema = elem->schema;
}
/* make node copy */
new_node = _lyd_dup_node(elem, schema, log_ctx, options);
if (!new_node) {
goto error;
}
if (parent && lyd_insert(parent, new_node)) {
goto error;
}
if (!ret) {
ret = new_node;
}
if (!(options & LYD_DUP_OPT_RECURSIVE)) {
break;
}
/* LY_TREE_DFS_END */
/* select element for the next run - children first,
* child exception for lyd_node_leaf and lyd_node_leaflist */
if (elem->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
next = NULL;
} else {
next = elem->child;
}
if (!next) {
if (elem->parent == node->parent) {
break;
}
/* no children, so try siblings */
next = elem->next;
} else {
parent = new_node;
}
new_node = NULL;
while (!next) {
/* no siblings, go back through parents */
elem = elem->parent;
if (elem->parent == node->parent) {
break;
}
if (!parent) {
LOGINT(log_ctx);
goto error;
}
parent = parent->parent;
/* parent is already processed, go to its sibling */
next = elem->next;
}
}
/* dup all the parents */
if (options & LYD_DUP_OPT_WITH_PARENTS) {
parent = ret;
for (elem = node->parent; elem; elem = elem->parent) {
new_node = lyd_dup(elem, options & LYD_DUP_OPT_NO_ATTR);
LY_CHECK_ERR_GOTO(!new_node, LOGMEM(log_ctx), error);
/* dup all list keys */
if (new_node->schema->nodetype == LYS_LIST) {
slist = (struct lys_node_list *)new_node->schema;
for (key = elem->child, i = 0; key && (i < slist->keys_size); ++i, key = key->next) {
if (key->schema != (struct lys_node *)slist->keys[i]) {
LOGVAL(log_ctx, LYE_PATH_INKEY, LY_VLOG_LYD, new_node, slist->keys[i]->name);
goto error;
}
key_dup = lyd_dup(key, options & LYD_DUP_OPT_NO_ATTR);
LY_CHECK_ERR_GOTO(!key_dup, LOGMEM(log_ctx), error);
if (lyd_insert(new_node, key_dup)) {
lyd_free(key_dup);
goto error;
}
}
if (!key && (i < slist->keys_size)) {
LOGVAL(log_ctx, LYE_PATH_INKEY, LY_VLOG_LYD, new_node, slist->keys[i]->name);
goto error;
}
}
/* link together */
if (lyd_insert(new_node, parent)) {
ret = parent;
goto error;
}
parent = new_node;
}
}
return ret;
error:
lyd_free(ret);
return NULL;
}
API struct lyd_node *
lyd_dup(const struct lyd_node *node, int options)
{
return lyd_dup_to_ctx(node, options, NULL);
}
static struct lyd_node *
lyd_dup_withsiblings_r(const struct lyd_node *first, struct lyd_node *parent_dup, int options)
{
struct lyd_node *first_dup = NULL, *prev_dup = NULL, *last_dup;
const struct lyd_node *next;
assert(first);
/* duplicate and connect all siblings */
LY_TREE_FOR(first, next) {
last_dup = _lyd_dup_node(next, next->schema, next->schema->module->ctx, options);
if (!last_dup) {
goto error;
}
/* the whole data tree is exactly the same so we can safely copy the validation flags */
last_dup->validity = next->validity;
last_dup->when_status = next->when_status;
last_dup->parent = parent_dup;
if (!first_dup) {
first_dup = last_dup;
} else {
assert(prev_dup);
prev_dup->next = last_dup;
last_dup->prev = prev_dup;
}
if ((next->schema->nodetype & (LYS_LIST | LYS_CONTAINER | LYS_RPC | LYS_ACTION | LYS_NOTIF)) && next->child) {
/* recursively duplicate all children */
if (!lyd_dup_withsiblings_r(next->child, last_dup, options)) {
goto error;
}
}
prev_dup = last_dup;
}
/* correctly set last sibling and parent child pointer */
assert(!prev_dup->next);
first_dup->prev = prev_dup;
if (parent_dup) {
parent_dup->child = first_dup;
}
return first_dup;
error:
/* disconnect and free */
first_dup->parent = NULL;
lyd_free_withsiblings(first_dup);
return NULL;
}
API struct lyd_node *
lyd_dup_withsiblings(const struct lyd_node *node, int options)
{
const struct lyd_node *iter;
struct lyd_node *ret, *ret_iter, *tmp;
if (!node) {
return NULL;
}
/* find first sibling */
while (node->prev->next) {
node = node->prev;
}
if (node->parent) {
ret = lyd_dup(node, options);
if (!ret) {
return NULL;
}
/* copy following siblings */
ret_iter = ret;
LY_TREE_FOR(node->next, iter) {
tmp = lyd_dup(iter, options);
if (!tmp) {
lyd_free_withsiblings(ret);
return NULL;
}
if (lyd_insert_after(ret_iter, tmp)) {
lyd_free_withsiblings(ret);
return NULL;
}
ret_iter = ret_iter->next;
assert(ret_iter == tmp);
}
} else {
/* duplicating top-level siblings, we can duplicate much more efficiently */
ret = lyd_dup_withsiblings_r(node, NULL, options);
}
return ret;
}
API void
lyd_free_attr(struct ly_ctx *ctx, struct lyd_node *parent, struct lyd_attr *attr, int recursive)
{
struct lyd_attr *iter;
struct lys_type **type;
if (!ctx || !attr) {
return;
}
if (parent) {
if (parent->attr == attr) {
if (recursive) {
parent->attr = NULL;
} else {
parent->attr = attr->next;
}
} else {
for (iter = parent->attr; iter->next != attr; iter = iter->next);
if (iter->next) {
if (recursive) {
iter->next = NULL;
} else {
iter->next = attr->next;
}
}
}
}
if (!recursive) {
attr->next = NULL;
}
for(iter = attr; iter; ) {
attr = iter;
iter = iter->next;
lydict_remove(ctx, attr->name);
type = lys_ext_complex_get_substmt(LY_STMT_TYPE, attr->annotation, NULL);
assert(type);
lyd_free_value(attr->value, attr->value_type, attr->value_flags, *type, NULL, NULL, NULL);
lydict_remove(ctx, attr->value_str);
free(attr);
}
}
const struct lyd_node *
lyd_attr_parent(const struct lyd_node *root, struct lyd_attr *attr)
{
const struct lyd_node *next, *elem;
struct lyd_attr *node_attr;
LY_TREE_DFS_BEGIN(root, next, elem) {
for (node_attr = elem->attr; node_attr; node_attr = node_attr->next) {
if (node_attr == attr) {
return elem;
}
}
LY_TREE_DFS_END(root, next, elem)
}
return NULL;
}
API struct lyd_attr *
lyd_insert_attr(struct lyd_node *parent, const struct lys_module *mod, const char *name, const char *value)
{
struct lyd_attr *a, *iter;
struct ly_ctx *ctx;
const struct lys_module *module;
const char *p;
char *aux;
int pos, i;
if (!parent || !name || !value) {
LOGARG;
return NULL;
}
ctx = parent->schema->module->ctx;
if ((p = strchr(name, ':'))) {
/* search for the namespace */
aux = strndup(name, p - name);
if (!aux) {
LOGMEM(ctx);
return NULL;
}
module = ly_ctx_get_module(ctx, aux, NULL, 1);
free(aux);
name = p + 1;
if (!module) {
/* module not found */
LOGERR(ctx, LY_EINVAL, "Attribute prefix does not match any implemented schema in the context.");
return NULL;
}
} else if (mod) {
module = mod;
} else if (!mod && (!strcmp(name, "type") || !strcmp(name, "select")) && !strcmp(parent->schema->name, "filter")) {
/* special case of inserting unqualified filter attributes "type" and "select" */
module = ly_ctx_get_module(ctx, "ietf-netconf", NULL, 1);
if (!module) {
LOGERR(ctx, LY_EINVAL, "Attribute prefix does not match any implemented schema in the context.");
return NULL;
}
} else {
/* no prefix -> module is the same as for the parent */
module = lyd_node_module(parent);
}
pos = -1;
do {
if ((unsigned int)(pos + 1) < module->ext_size) {
i = lys_ext_instance_presence(&ctx->models.list[0]->extensions[0],
&module->ext[pos + 1], module->ext_size - (pos + 1));
pos = (i == -1) ? -1 : pos + 1 + i;
} else {
pos = -1;
}
if (pos == -1) {
LOGERR(ctx, LY_EINVAL, "Attribute does not match any annotation instance definition.");
return NULL;
}
} while (!ly_strequal(module->ext[pos]->arg_value, name, 0));
a = calloc(1, sizeof *a);
LY_CHECK_ERR_RETURN(!a, LOGMEM(ctx), NULL);
a->parent = parent;
a->next = NULL;
a->annotation = (struct lys_ext_instance_complex *)module->ext[pos];
a->name = lydict_insert(ctx, name, 0);
a->value_str = lydict_insert(ctx, value, 0);
if (!lyp_parse_value(*((struct lys_type **)lys_ext_complex_get_substmt(LY_STMT_TYPE, a->annotation, NULL)),
&a->value_str, NULL, NULL, a, NULL, 1, 0, 0)) {
lyd_free_attr(ctx, NULL, a, 0);
return NULL;
}
if (!parent->attr) {
parent->attr = a;
} else {
for (iter = parent->attr; iter->next; iter = iter->next);
iter->next = a;
}
return a;
}
void
lyd_free_value(lyd_val value, LY_DATA_TYPE value_type, uint8_t value_flags, struct lys_type *type, lyd_val *old_val,
LY_DATA_TYPE *old_val_type, uint8_t *old_val_flags)
{
if (old_val) {
*old_val = value;
*old_val_type = value_type;
*old_val_flags = value_flags;
/* we only backup the values for now */
return;
}
/* otherwise the value is correctly freed */
if (value_flags & LY_VALUE_USER) {
assert(type->der && type->der->module);
lytype_free(type->der->module, type->der->name, value);
} else {
switch (value_type) {
case LY_TYPE_BITS:
if (value.bit) {
free(value.bit);
}
break;
case LY_TYPE_INST:
if (!(value_flags & LY_VALUE_UNRES)) {
break;
}
/* fallthrough */
case LY_TYPE_UNION:
/* unresolved union leaf */
lydict_remove(type->parent->module->ctx, value.string);
break;
default:
break;
}
}
}
static void
_lyd_free_node(struct lyd_node *node)
{
struct lyd_node_leaf_list *leaf;
if (!node) {
return;
}
switch (node->schema->nodetype) {
case LYS_CONTAINER:
case LYS_LIST:
case LYS_RPC:
case LYS_ACTION:
case LYS_NOTIF:
#ifdef LY_ENABLED_CACHE
/* it should be empty because all the children are freed already (only if in debug mode) */
lyht_free(node->ht);
#endif
break;
case LYS_ANYDATA:
case LYS_ANYXML:
switch (((struct lyd_node_anydata *)node)->value_type) {
case LYD_ANYDATA_CONSTSTRING:
case LYD_ANYDATA_SXML:
case LYD_ANYDATA_JSON:
lydict_remove(node->schema->module->ctx, ((struct lyd_node_anydata *)node)->value.str);
break;
case LYD_ANYDATA_DATATREE:
lyd_free_withsiblings(((struct lyd_node_anydata *)node)->value.tree);
break;
case LYD_ANYDATA_XML:
lyxml_free_withsiblings(node->schema->module->ctx, ((struct lyd_node_anydata *)node)->value.xml);
break;
case LYD_ANYDATA_LYB:
free(((struct lyd_node_anydata *)node)->value.mem);
break;
case LYD_ANYDATA_STRING:
case LYD_ANYDATA_SXMLD:
case LYD_ANYDATA_JSOND:
case LYD_ANYDATA_LYBD:
/* dynamic strings are used only as input parameters */
assert(0);
break;
}
break;
case LYS_LEAF:
case LYS_LEAFLIST:
leaf = (struct lyd_node_leaf_list *)node;
lyd_free_value(leaf->value, leaf->value_type, leaf->value_flags, &((struct lys_node_leaf *)leaf->schema)->type,
NULL, NULL, NULL);
lydict_remove(leaf->schema->module->ctx, leaf->value_str);
break;
default:
assert(0);
}
lyd_free_attr(node->schema->module->ctx, node, node->attr, 1);
free(node);
}
static void
lyd_free_internal_r(struct lyd_node *node, int top)
{
struct lyd_node *next, *iter;
if (!node) {
return;
}
/* if freeing top-level, always remove it from the parent hash table */
lyd_unlink_internal(node, (top ? 1 : 2));
if (!(node->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) {
/* free children */
LY_TREE_FOR_SAFE(node->child, next, iter) {
lyd_free_internal_r(iter, 0);
}
}
_lyd_free_node(node);
}
API void
lyd_free(struct lyd_node *node)
{
lyd_free_internal_r(node, 1);
}
static void
lyd_free_withsiblings_r(struct lyd_node *first)
{
struct lyd_node *next, *node;
LY_TREE_FOR_SAFE(first, next, node) {
if (node->schema->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_RPC | LYS_ACTION | LYS_NOTIF)) {
lyd_free_withsiblings_r(node->child);
}
_lyd_free_node(node);
}
}
API void
lyd_free_withsiblings(struct lyd_node *node)
{
struct lyd_node *iter, *aux;
if (!node) {
return;
}
if (node->parent) {
/* optimization - avoid freeing (unlinking) the last node of the siblings list */
/* so, first, free the node's predecessors to the beginning of the list ... */
for(iter = node->prev; iter->next; iter = aux) {
aux = iter->prev;
lyd_free(iter);
}
/* ... then, the node is the first in the siblings list, so free them all */
LY_TREE_FOR_SAFE(node, aux, iter) {
lyd_free(iter);
}
} else {
/* node is top-level so we are freeing the whole data tree, we can just free nodes without any unlinking */
while (node->prev->next) {
/* find the first sibling */
node = node->prev;
}
/* free it all */
lyd_free_withsiblings_r(node);
}
}
/**
* Expectations:
* - list exists in data tree
* - the leaf (defined by the unique_expr) is not instantiated under the list
*/
int
lyd_get_unique_default(const char* unique_expr, struct lyd_node *list, const char **dflt)
{
struct ly_ctx *ctx = list->schema->module->ctx;
const struct lys_node *parent;
const struct lys_node_leaf *sleaf = NULL;
struct lys_tpdf *tpdf;
struct lyd_node *last, *node;
struct ly_set *s, *r;
unsigned int i;
enum int_log_opts prev_ilo;
assert(unique_expr && list && dflt);
*dflt = NULL;
if (resolve_descendant_schema_nodeid(unique_expr, list->schema->child, LYS_LEAF, 1, &parent) || !parent) {
/* error, but unique expression was checked when the schema was parsed so this should not happened */
LOGINT(ctx);
return -1;
}
sleaf = (struct lys_node_leaf *)parent;
if (sleaf->dflt) {
/* leaf has a default value */
*dflt = sleaf->dflt;
} else if (!(sleaf->flags & LYS_MAND_TRUE)) {
/* get the default value from the type */
for (tpdf = sleaf->type.der; tpdf && !(*dflt); tpdf = tpdf->type.der) {
*dflt = tpdf->dflt;
}
}
if (!(*dflt)) {
return 0;
}
/* it has default value, but check if it can appear in the data tree under the list */
s = ly_set_new();
for (parent = lys_parent((struct lys_node *)sleaf); parent != list->schema; parent = lys_parent(parent)) {
if (!(parent->nodetype & (LYS_CONTAINER | LYS_CASE | LYS_CHOICE | LYS_USES))) {
/* This should be already detected when parsing schema */
LOGINT(ctx);
ly_set_free(s);
return -1;
}
ly_set_add(s, (void *)parent, LY_SET_OPT_USEASLIST);
}
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
for (i = 0, last = list; i < s->number; i++) {
parent = s->set.s[i]; /* shortcut */
switch (parent->nodetype) {
case LYS_CONTAINER:
if (last) {
/* find instance in the data */
r = lyd_find_path(last, parent->name);
if (!r || r->number > 1) {
ly_set_free(r);
*dflt = NULL;
goto end;
}
if (r->number) {
last = r->set.d[0];
} else {
last = NULL;
}
ly_set_free(r);
}
if (((struct lys_node_container *)parent)->presence) {
/* not-instantiated presence container on path */
*dflt = NULL;
goto end;
}
break;
case LYS_CHOICE :
/* check presence of another case */
if (!last) {
continue;
}
/* remember the case to be searched in choice by lyv_multicases() */
if (i + 1 == s->number) {
parent = (struct lys_node *)sleaf;
} else if (s->set.s[i + 1]->nodetype == LYS_CASE && (i + 2 < s->number) &&
s->set.s[i + 2]->nodetype == LYS_CHOICE) {
/* nested choices are covered by lyv_multicases, we just have to pass
* the lowest choice */
i++;
continue;
} else {
parent = s->set.s[i + 1];
}
node = last->child;
if (lyv_multicases(NULL, (struct lys_node *)parent, &node, 0, NULL)) {
/* another case is present */
*dflt = NULL;
goto end;
}
break;
default:
/* LYS_CASE, LYS_USES */
continue;
}
}
end:
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
ly_set_free(s);
return 0;
}
API char *
lyd_path(const struct lyd_node *node)
{
char *buf = NULL;
if (!node) {
LOGARG;
return NULL;
}
if (ly_vlog_build_path(LY_VLOG_LYD, node, &buf, 0, 0)) {
return NULL;
}
return buf;
}
int
lyd_build_relative_data_path(const struct lys_module *module, const struct lyd_node *node, const char *schema_id,
char *buf)
{
const struct lys_node *snode, *schema;
const char *mod_name, *name;
int mod_name_len, name_len, len = 0;
int r, is_relative = -1;
assert(schema_id && buf);
schema = node->schema;
while (*schema_id) {
if ((r = parse_schema_nodeid(schema_id, &mod_name, &mod_name_len, &name, &name_len, &is_relative, NULL, NULL, 0)) < 1) {
LOGINT(module->ctx);
return -1;
}
schema_id += r;
snode = NULL;
while ((snode = lys_getnext(snode, schema, NULL, LYS_GETNEXT_WITHCHOICE | LYS_GETNEXT_WITHCASE | LYS_GETNEXT_NOSTATECHECK))) {
r = schema_nodeid_siblingcheck(snode, module, mod_name, mod_name_len, name, name_len);
if (r == 0) {
schema = snode;
break;
} else if (r == 1) {
continue;
} else {
return -1;
}
}
/* no match */
if (!snode || (!schema_id[0] && snode->nodetype != LYS_LEAF)) {
LOGINT(module->ctx);
return -1;
}
if (!(snode->nodetype & (LYS_CHOICE | LYS_CASE))) {
len += sprintf(&buf[len], "%s%s", (len ? "/" : ""), snode->name);
}
}
return len;
}
API struct ly_set *
lyd_find_path(const struct lyd_node *ctx_node, const char *path)
{
struct lyxp_set xp_set;
struct ly_set *set;
char *yang_xpath;
const char * node_mod_name, *mod_name, *name;
int mod_name_len, name_len, is_relative = -1;
uint32_t i;
if (!ctx_node || !path) {
LOGARG;
return NULL;
}
if (parse_schema_nodeid(path, &mod_name, &mod_name_len, &name, &name_len, &is_relative, NULL, NULL, 1) > 0) {
if (name[0] == '#' && !is_relative) {
node_mod_name = lyd_node_module(ctx_node)->name;
if (strncmp(mod_name, node_mod_name, mod_name_len) || node_mod_name[mod_name_len]) {
return NULL;
}
path = name + name_len;
}
}
/* transform JSON into YANG XPATH */
yang_xpath = transform_json2xpath(lyd_node_module(ctx_node), path);
if (!yang_xpath) {
return NULL;
}
memset(&xp_set, 0, sizeof xp_set);
if (lyxp_eval(yang_xpath, ctx_node, LYXP_NODE_ELEM, lyd_node_module(ctx_node), &xp_set, 0) != EXIT_SUCCESS) {
free(yang_xpath);
return NULL;
}
free(yang_xpath);
set = ly_set_new();
LY_CHECK_ERR_RETURN(!set, LOGMEM(ctx_node->schema->module->ctx), NULL);
if (xp_set.type == LYXP_SET_NODE_SET) {
for (i = 0; i < xp_set.used; ++i) {
if (xp_set.val.nodes[i].type == LYXP_NODE_ELEM) {
if (ly_set_add(set, xp_set.val.nodes[i].node, LY_SET_OPT_USEASLIST) < 0) {
ly_set_free(set);
set = NULL;
break;
}
}
}
}
/* free xp_set content */
lyxp_set_cast(&xp_set, LYXP_SET_EMPTY, ctx_node, NULL, 0);
return set;
}
API struct ly_set *
lyd_find_instance(const struct lyd_node *data, const struct lys_node *schema)
{
struct ly_set *ret, *ret_aux, *spath;
const struct lys_node *siter;
struct lyd_node *iter;
unsigned int i, j;
if (!data || !schema ||
!(schema->nodetype & (LYS_CONTAINER | LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_ANYDATA | LYS_NOTIF | LYS_RPC | LYS_ACTION))) {
LOGARG;
return NULL;
}
ret = ly_set_new();
spath = ly_set_new();
if (!ret || !spath) {
LOGMEM(schema->module->ctx);
goto error;
}
/* find data root */
while (data->parent) {
/* vertical move (up) */
data = data->parent;
}
while (data->prev->next) {
/* horizontal move (left) */
data = data->prev;
}
/* build schema path */
for (siter = schema; siter; ) {
if (siter->nodetype == LYS_AUGMENT) {
siter = ((struct lys_node_augment *)siter)->target;
continue;
} else if (siter->nodetype & (LYS_CONTAINER | LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_ANYDATA | LYS_NOTIF | LYS_RPC | LYS_ACTION)) {
/* standard data node */
ly_set_add(spath, (void*)siter, LY_SET_OPT_USEASLIST);
} /* else skip the rest node types */
siter = siter->parent;
}
if (!spath->number) {
/* no valid path */
goto error;
}
/* start searching */
LY_TREE_FOR((struct lyd_node *)data, iter) {
if (iter->schema == spath->set.s[spath->number - 1]) {
ly_set_add(ret, iter, LY_SET_OPT_USEASLIST);
}
}
for (i = spath->number - 1; i; i--) {
if (!ret->number) {
/* nothing found */
break;
}
ret_aux = ly_set_new();
if (!ret_aux) {
LOGMEM(schema->module->ctx);
goto error;
}
for (j = 0; j < ret->number; j++) {
LY_TREE_FOR(ret->set.d[j]->child, iter) {
if (iter->schema == spath->set.s[i - 1]) {
ly_set_add(ret_aux, iter, LY_SET_OPT_USEASLIST);
}
}
}
ly_set_free(ret);
ret = ret_aux;
}
ly_set_free(spath);
return ret;
error:
ly_set_free(ret);
ly_set_free(spath);
return NULL;
}
API struct lyd_node *
lyd_first_sibling(struct lyd_node *node)
{
struct lyd_node *start;
if (!node) {
return NULL;
}
/* get the first sibling */
if (node->parent) {
start = node->parent->child;
} else {
for (start = node; start->prev->next; start = start->prev);
}
return start;
}
API struct ly_set *
ly_set_new(void)
{
struct ly_set *new;
new = calloc(1, sizeof(struct ly_set));
LY_CHECK_ERR_RETURN(!new, LOGMEM(NULL), NULL);
return new;
}
API void
ly_set_free(struct ly_set *set)
{
if (!set) {
return;
}
free(set->set.g);
free(set);
}
API int
ly_set_contains(const struct ly_set *set, void *node)
{
unsigned int i;
if (!set) {
return -1;
}
for (i = 0; i < set->number; i++) {
if (set->set.g[i] == node) {
/* object found */
return i;
}
}
/* object not found */
return -1;
}
API struct ly_set *
ly_set_dup(const struct ly_set *set)
{
struct ly_set *new;
if (!set) {
return NULL;
}
new = malloc(sizeof *new);
LY_CHECK_ERR_RETURN(!new, LOGMEM(NULL), NULL);
new->number = set->number;
new->size = set->size;
new->set.g = malloc(new->size * sizeof *(new->set.g));
LY_CHECK_ERR_RETURN(!new->set.g, LOGMEM(NULL); free(new), NULL);
memcpy(new->set.g, set->set.g, new->size * sizeof *(new->set.g));
return new;
}
API int
ly_set_add(struct ly_set *set, void *node, int options)
{
unsigned int i;
void **new;
if (!set || !node) {
LOGARG;
return -1;
}
if (!(options & LY_SET_OPT_USEASLIST)) {
/* search for duplication */
for (i = 0; i < set->number; i++) {
if (set->set.g[i] == node) {
/* already in set */
return i;
}
}
}
if (set->size == set->number) {
new = realloc(set->set.g, (set->size + 8) * sizeof *(set->set.g));
LY_CHECK_ERR_RETURN(!new, LOGMEM(NULL), -1);
set->size += 8;
set->set.g = new;
}
set->set.g[set->number++] = node;
return set->number - 1;
}
API int
ly_set_merge(struct ly_set *trg, struct ly_set *src, int options)
{
unsigned int i, ret;
void **new;
if (!trg) {
LOGARG;
return -1;
}
if (!src) {
return 0;
}
if (!(options & LY_SET_OPT_USEASLIST)) {
/* remove duplicates */
i = 0;
while (i < src->number) {
if (ly_set_contains(trg, src->set.g[i]) > -1) {
ly_set_rm_index(src, i);
} else {
++i;
}
}
}
/* allocate more memory if needed */
if (trg->size < trg->number + src->number) {
new = realloc(trg->set.g, (trg->number + src->number) * sizeof *(trg->set.g));
LY_CHECK_ERR_RETURN(!new, LOGMEM(NULL), -1);
trg->size = trg->number + src->number;
trg->set.g = new;
}
/* copy contents from src into trg */
memcpy(trg->set.g + trg->number, src->set.g, src->number * sizeof *(src->set.g));
ret = src->number;
trg->number += ret;
/* cleanup */
ly_set_free(src);
return ret;
}
API int
ly_set_rm_index(struct ly_set *set, unsigned int index)
{
if (!set || (index + 1) > set->number) {
LOGARG;
return EXIT_FAILURE;
}
if (index == set->number - 1) {
/* removing last item in set */
set->set.g[index] = NULL;
} else {
/* removing item somewhere in a middle, so put there the last item */
set->set.g[index] = set->set.g[set->number - 1];
set->set.g[set->number - 1] = NULL;
}
set->number--;
return EXIT_SUCCESS;
}
API int
ly_set_rm(struct ly_set *set, void *node)
{
unsigned int i;
if (!set || !node) {
LOGARG;
return EXIT_FAILURE;
}
/* get index */
for (i = 0; i < set->number; i++) {
if (set->set.g[i] == node) {
break;
}
}
if (i == set->number) {
/* node is not in set */
LOGARG;
return EXIT_FAILURE;
}
return ly_set_rm_index(set, i);
}
API int
ly_set_clean(struct ly_set *set)
{
if (!set) {
return EXIT_FAILURE;
}
set->number = 0;
return EXIT_SUCCESS;
}
API int
lyd_wd_default(struct lyd_node_leaf_list *node)
{
struct lys_node_leaf *leaf;
struct lys_node_leaflist *llist;
struct lyd_node *iter;
struct lys_tpdf *tpdf;
const char *dflt = NULL, **dflts = NULL;
uint8_t dflts_size = 0, c, i;
if (!node || !(node->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
return 0;
}
if (node->dflt) {
return 1;
}
if (node->schema->nodetype == LYS_LEAF) {
leaf = (struct lys_node_leaf *)node->schema;
/* get know if there is a default value */
if (leaf->dflt) {
/* leaf has a default value */
dflt = leaf->dflt;
} else if (!(leaf->flags & LYS_MAND_TRUE)) {
/* get the default value from the type */
for (tpdf = leaf->type.der; tpdf && !dflt; tpdf = tpdf->type.der) {
dflt = tpdf->dflt;
}
}
if (!dflt) {
/* no default value */
return 0;
}
/* compare the default value with the value of the leaf */
if (!ly_strequal(dflt, node->value_str, 1)) {
return 0;
}
} else if (node->schema->module->version >= LYS_VERSION_1_1) { /* LYS_LEAFLIST */
llist = (struct lys_node_leaflist *)node->schema;
/* get know if there is a default value */
if (llist->dflt_size) {
/* there are default values */
dflts_size = llist->dflt_size;
dflts = llist->dflt;
} else if (!llist->min) {
/* get the default value from the type */
for (tpdf = llist->type.der; tpdf && !dflts; tpdf = tpdf->type.der) {
if (tpdf->dflt) {
dflts = &tpdf->dflt;
dflts_size = 1;
break;
}
}
}
if (!dflts_size) {
/* no default values to use */
return 0;
}
/* compare the default value with the value of the leaf */
/* first, find the first leaf-list's sibling */
iter = (struct lyd_node *)node;
if (iter->parent) {
iter = iter->parent->child;
} else {
for (; iter->prev->next; iter = iter->prev);
}
for (c = 0; iter; iter = iter->next) {
if (iter->schema != node->schema) {
continue;
}
if (c == dflts_size) {
/* to many leaf-list instances */
return 0;
}
if (llist->flags & LYS_USERORDERED) {
/* we have strict order */
if (!ly_strequal(dflts[c], ((struct lyd_node_leaf_list *)iter)->value_str, 1)) {
return 0;
}
} else {
/* node's value is supposed to match with one of the default values */
for (i = 0; i < dflts_size; i++) {
if (ly_strequal(dflts[i], ((struct lyd_node_leaf_list *)iter)->value_str, 1)) {
break;
}
}
if (i == dflts_size) {
/* values do not match */
return 0;
}
}
c++;
}
if (c != dflts_size) {
/* different sets of leaf-list instances */
return 0;
}
} else {
return 0;
}
/* all checks ok */
return 1;
}
int
unres_data_diff_new(struct unres_data *unres, struct lyd_node *subtree, struct lyd_node *parent, int created)
{
char *parent_xpath = NULL;
if (created) {
return lyd_difflist_add(unres->diff, &unres->diff_size, unres->diff_idx++, LYD_DIFF_CREATED, NULL, subtree);
} else {
if (parent) {
parent_xpath = lyd_path(parent);
LY_CHECK_ERR_RETURN(!parent_xpath, LOGMEM(lyd_node_module(subtree)->ctx), -1);
}
return lyd_difflist_add(unres->diff, &unres->diff_size, unres->diff_idx++, LYD_DIFF_DELETED,
subtree, (struct lyd_node *)parent_xpath);
}
}
void
unres_data_diff_rem(struct unres_data *unres, unsigned int idx)
{
if (unres->diff->type[idx] == LYD_DIFF_DELETED) {
lyd_free_withsiblings(unres->diff->first[idx]);
free(unres->diff->second[idx]);
}
/* replace by last real value */
if (idx < unres->diff_idx - 1) {
unres->diff->type[idx] = unres->diff->type[unres->diff_idx - 1];
unres->diff->first[idx] = unres->diff->first[unres->diff_idx - 1];
unres->diff->second[idx] = unres->diff->second[unres->diff_idx - 1];
}
/* move the end */
assert(unres->diff->type[unres->diff_idx] == LYD_DIFF_END);
unres->diff->type[unres->diff_idx - 1] = unres->diff->type[unres->diff_idx];
--unres->diff_idx;
}
API void
lyd_free_val_diff(struct lyd_difflist *diff)
{
uint32_t i;
if (!diff) {
return;
}
for (i = 0; diff->type[i] != LYD_DIFF_END; ++i) {
switch (diff->type[i]) {
case LYD_DIFF_CREATED:
free(diff->first[i]);
lyd_free_withsiblings(diff->second[i]);
break;
case LYD_DIFF_DELETED:
lyd_free_withsiblings(diff->first[i]);
free(diff->second[i]);
break;
default:
/* what to do? */
break;
}
}
lyd_free_diff(diff);
}
static int
lyd_wd_add_leaf(struct lyd_node **tree, struct lyd_node *last_parent, struct lys_node_leaf *leaf, struct unres_data *unres,
int check_when_must)
{
struct lyd_node *dummy = NULL, *current;
struct lys_tpdf *tpdf;
const char *dflt = NULL;
int ret;
/* get know if there is a default value */
if (leaf->dflt) {
/* leaf has a default value */
dflt = leaf->dflt;
} else if (!(leaf->flags & LYS_MAND_TRUE)) {
/* get the default value from the type */
for (tpdf = leaf->type.der; tpdf && !dflt; tpdf = tpdf->type.der) {
dflt = tpdf->dflt;
}
}
if (!dflt) {
/* no default value */
return EXIT_SUCCESS;
}
/* create the node */
if (!(dummy = lyd_new_dummy(*tree, last_parent, (struct lys_node*)leaf, dflt, 1))) {
goto error;
}
if (unres->store_diff) {
/* remember this subtree in the diff */
if (unres_data_diff_new(unres, dummy, NULL, 1)) {
goto error;
}
}
if (!dummy->parent && (*tree)) {
/* connect dummy nodes into the data tree (at the end of top level nodes) */
if (lyd_insert_sibling(tree, dummy)) {
goto error;
}
}
for (current = dummy; ; current = current->child) {
/* remember the created data in unres */
if (check_when_must) {
if ((current->when_status & LYD_WHEN) && unres_data_add(unres, current, UNRES_WHEN) == -1) {
goto error;
}
if (check_when_must == 2) {
ret = resolve_applies_must(current);
if ((ret & 0x1) && (unres_data_add(unres, current, UNRES_MUST) == -1)) {
goto error;
}
if ((ret & 0x2) && (unres_data_add(unres, current, UNRES_MUST_INOUT) == -1)) {
goto error;
}
}
}
/* clear dummy-node flag */
current->validity &= ~LYD_VAL_INUSE;
if (current->schema == (struct lys_node *)leaf) {
break;
}
}
/* update parent's default flag if needed */
lyd_wd_update_parents(dummy);
/* if necessary, remember the created data value in unres */
if (((struct lyd_node_leaf_list *)current)->value_type == LY_TYPE_LEAFREF) {
if (unres_data_add(unres, current, UNRES_LEAFREF)) {
goto error;
}
} else if (((struct lyd_node_leaf_list *)current)->value_type == LY_TYPE_INST) {
if (unres_data_add(unres, current, UNRES_INSTID)) {
goto error;
}
}
if (!(*tree)) {
*tree = dummy;
}
return EXIT_SUCCESS;
error:
lyd_free(dummy);
return EXIT_FAILURE;
}
static int
lyd_wd_add_leaflist(struct lyd_node **tree, struct lyd_node *last_parent, struct lys_node_leaflist *llist,
struct unres_data *unres, int check_when_must)
{
struct lyd_node *dummy, *current, *first = NULL;
struct lys_tpdf *tpdf;
const char **dflt = NULL;
uint8_t dflt_size = 0;
int i, ret;
if (llist->module->version < LYS_VERSION_1_1) {
/* default values on leaf-lists are allowed from YANG 1.1 */
return EXIT_SUCCESS;
}
/* get know if there is a default value */
if (llist->dflt_size) {
/* there are default values */
dflt_size = llist->dflt_size;
dflt = llist->dflt;
} else if (!llist->min) {
/* get the default value from the type */
for (tpdf = llist->type.der; tpdf && !dflt; tpdf = tpdf->type.der) {
if (tpdf->dflt) {
dflt = &tpdf->dflt;
dflt_size = 1;
break;
}
}
}
if (!dflt_size) {
/* no default values to use */
return EXIT_SUCCESS;
}
for (i = 0; i < dflt_size; i++) {
/* create the node */
if (!(dummy = lyd_new_dummy(*tree, last_parent, (struct lys_node*)llist, dflt[i], 1))) {
goto error;
}
if (unres->store_diff) {
/* remember this subtree in the diff */
if (unres_data_diff_new(unres, dummy, NULL, 1)) {
goto error;
}
}
if (!first) {
first = dummy;
} else if (!dummy->parent) {
/* interconnect with the rest of leaf-lists */
first->prev->next = dummy;
dummy->prev = first->prev;
first->prev = dummy;
}
for (current = dummy; ; current = current->child) {
/* remember the created data in unres */
if (check_when_must) {
if ((current->when_status & LYD_WHEN) && unres_data_add(unres, current, UNRES_WHEN) == -1) {
goto error;
}
if (check_when_must == 2) {
ret = resolve_applies_must(current);
if ((ret & 0x1) && (unres_data_add(unres, current, UNRES_MUST) == -1)) {
goto error;
}
if ((ret & 0x2) && (unres_data_add(unres, current, UNRES_MUST_INOUT) == -1)) {
goto error;
}
}
}
/* clear dummy-node flag */
current->validity &= ~LYD_VAL_INUSE;
if (current->schema == (struct lys_node *)llist) {
break;
}
}
/* if necessary, remember the created data value in unres */
if (((struct lyd_node_leaf_list *)current)->value_type == LY_TYPE_LEAFREF) {
if (unres_data_add(unres, current, UNRES_LEAFREF)) {
goto error;
}
} else if (((struct lyd_node_leaf_list *)current)->value_type == LY_TYPE_INST) {
if (unres_data_add(unres, current, UNRES_INSTID)) {
goto error;
}
}
}
/* insert into the tree */
if (first && !first->parent && (*tree)) {
/* connect dummy nodes into the data tree (at the end of top level nodes) */
if (lyd_insert_sibling(tree, first)) {
goto error;
}
} else if (!(*tree)) {
*tree = first;
}
/* update parent's default flag if needed */
lyd_wd_update_parents(first);
return EXIT_SUCCESS;
error:
lyd_free_withsiblings(first);
return EXIT_FAILURE;
}
static void
lyd_wd_leaflist_cleanup(struct ly_set *set, struct unres_data *unres)
{
unsigned int i;
assert(set);
/* if there is an instance without the dflt flag, we have to
* remove all instances with the flag - an instance could be
* explicitely added, so the default leaflists were invalidated */
for (i = 0; i < set->number; i++) {
if (!set->set.d[i]->dflt) {
break;
}
}
if (i < set->number) {
for (i = 0; i < set->number; i++) {
if (set->set.d[i]->dflt) {
/* remove this default instance */
if (unres->store_diff) {
/* just move it to diff if is being generated */
unres_data_diff_new(unres, set->set.d[i], set->set.d[i]->parent, 0);
lyd_unlink(set->set.d[i]);
} else {
lyd_free(set->set.d[i]);
}
}
}
}
}
/**
* @brief Process (add/clean flags) default nodes in the schema subtree
*
* @param[in,out] root Pointer to the root node of the complete data tree, the root node can be NULL if the data tree
* is empty
* @param[in] last_parent The closest parent in the data tree to the currently processed \p schema node
* @param[in] subroot The root node of a data subtree, the node is instance of the \p schema node, NULL in case the
* schema node is not instantiated in the data tree
* @param[in] schema The schema node to be processed
* @param[in] toplevel Flag for processing top level schema nodes when \p last_parent and \p subroot are consider as
* unknown
* @param[in] options Parser options to know the data tree type, see @ref parseroptions.
* @param[in] unres Unresolved data list, the newly added default nodes may need to add some unresolved items
* @return EXIT_SUCCESS or EXIT_FAILURE
*/
static int
lyd_wd_add_subtree(struct lyd_node **root, struct lyd_node *last_parent, struct lyd_node *subroot,
struct lys_node *schema, int toplevel, int options, struct unres_data *unres)
{
struct ly_set *present = NULL;
struct lys_node *siter, *siter_prev;
struct lyd_node *iter;
int i, check_when_must, storing_diff = 0;
assert(root);
if ((options & LYD_OPT_TYPEMASK) && (schema->flags & LYS_CONFIG_R)) {
/* non LYD_OPT_DATA tree, status data are not expected here */
return EXIT_SUCCESS;
}
if (options & (LYD_OPT_NOTIF_FILTER | LYD_OPT_EDIT | LYD_OPT_GET | LYD_OPT_GETCONFIG)) {
check_when_must = 0; /* check neither */
} else if (options & LYD_OPT_TRUSTED) {
check_when_must = 1; /* check only when */
} else {
check_when_must = 2; /* check both when and must */
}
if (toplevel && (schema->nodetype & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER))) {
/* search for the schema node instance */
present = ly_set_new();
if (!present) {
goto error;
}
if ((*root) && lyd_get_node_siblings(*root, schema, present)) {
/* there are some instances */
for (i = 0; i < (signed)present->number; i++) {
if (schema->nodetype & LYS_LEAFLIST) {
lyd_wd_leaflist_cleanup(present, unres);
} else if (schema->nodetype != LYS_LEAF) {
if (lyd_wd_add_subtree(root, present->set.d[i], present->set.d[i], schema, 0, options, unres)) {
goto error;
}
} /* else LYS_LEAF - nothing to do */
}
} else {
/* no instance */
if (lyd_wd_add_subtree(root, last_parent, NULL, schema, 0, options, unres)) {
goto error;
}
}
ly_set_free(present);
return EXIT_SUCCESS;
}
/* skip disabled parts of schema */
if (!subroot) {
/* go through all the uses and check whether they are enabled */
for (siter = schema->parent; siter && (siter->nodetype & (LYS_USES | LYS_CHOICE)); siter = siter->parent) {
if (lys_is_disabled(siter, 0)) {
/* ignore disabled uses nodes */
return EXIT_SUCCESS;
}
}
/* check augment state */
if (siter && siter->nodetype == LYS_AUGMENT) {
if (lys_is_disabled(siter, 0)) {
/* ignore disabled augment */
return EXIT_SUCCESS;
}
}
/* check the node itself */
if (lys_is_disabled(schema, 0)) {
/* ignore disabled data */
return EXIT_SUCCESS;
}
}
/* go recursively */
switch (schema->nodetype) {
case LYS_LIST:
if (!subroot) {
/* stop recursion */
break;
}
/* falls through */
case LYS_CONTAINER:
if (!subroot) {
/* container does not exists, continue only in case of non presence container */
if (((struct lys_node_container *)schema)->presence) {
/* stop recursion */
break;
}
/* always create empty NP container even if there is no default node,
* because accroding to RFC, the empty NP container is always part of
* accessible tree (e.g. for evaluating when and must conditions) */
subroot = _lyd_new(last_parent, schema, 1);
/* useless to set mand flag */
subroot->validity &= ~LYD_VAL_MAND;
if (unres->store_diff) {
/* remember this container in the diff */
if (unres_data_diff_new(unres, subroot, NULL, 1)) {
goto error;
}
/* do not store diff for recursive calls, created values will be connected to this one */
storing_diff = 1;
unres->store_diff = 0;
}
if (!last_parent) {
if (*root) {
lyd_insert_common((*root)->parent, root, subroot, 0);
} else {
*root = subroot;
}
}
last_parent = subroot;
/* remember the created container in unres */
if (check_when_must) {
if ((subroot->when_status & LYD_WHEN) && unres_data_add(unres, subroot, UNRES_WHEN) == -1) {
goto error;
}
if (check_when_must == 2) {
i = resolve_applies_must(subroot);
if ((i & 0x1) && (unres_data_add(unres, subroot, UNRES_MUST) == -1)) {
goto error;
}
if ((i & 0x2) && (unres_data_add(unres, subroot, UNRES_MUST_INOUT) == -1)) {
goto error;
}
}
}
} else if (!((struct lys_node_container *)schema)->presence) {
/* fix default flag on existing containers - set it on all non-presence containers and in case we will
* have in recursion function some non-default node, it will unset it */
subroot->dflt = 1;
}
/* falls through */
case LYS_CASE:
case LYS_USES:
case LYS_INPUT:
case LYS_OUTPUT:
case LYS_NOTIF:
/* recursion */
present = ly_set_new();
if (!present) {
goto error;
}
LY_TREE_FOR(schema->child, siter) {
if (siter->nodetype & (LYS_CHOICE | LYS_USES)) {
/* go into without searching for data instance */
if (lyd_wd_add_subtree(root, last_parent, subroot, siter, toplevel, options, unres)) {
goto error;
}
} else if (siter->nodetype & (LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_ANYDATA)) {
/* search for the schema node instance */
if (subroot && lyd_get_node_siblings(subroot->child, siter, present)) {
/* there are some instances in the data root */
if (siter->nodetype & LYS_LEAFLIST) {
/* already have some leaflists, check that they are all
* default, if not, remove the default leaflists */
lyd_wd_leaflist_cleanup(present, unres);
} else if (siter->nodetype != LYS_LEAF) {
/* recursion */
for (i = 0; i < (signed)present->number; i++) {
if (lyd_wd_add_subtree(root, present->set.d[i], present->set.d[i], siter, toplevel, options,
unres)) {
goto error;
}
}
} /* else LYS_LEAF - nothing to do */
/* fix default flag (2nd part) - for non-default node with default parent, unset the default flag
* from the parents (starting from subroot node) */
if (subroot->dflt) {
for (i = 0; i < (signed)present->number; i++) {
if (!present->set.d[i]->dflt) {
for (iter = subroot; iter && iter->dflt; iter = iter->parent) {
iter->dflt = 0;
}
break;
}
}
}
ly_set_clean(present);
} else {
/* no instance */
if (lyd_wd_add_subtree(root, last_parent, NULL, siter, toplevel, options, unres)) {
goto error;
}
}
}
}
if (storing_diff) {
/* continue generating the diff in functions above this one */
unres->store_diff = 1;
}
break;
case LYS_LEAF:
case LYS_LEAFLIST:
if (subroot) {
/* default shortcase of a choice */
present = ly_set_new();
if (!present) {
goto error;
}
lyd_get_node_siblings(subroot->child, schema, present);
if (present->number) {
/* the shortcase leaf(-list) exists, stop the processing */
break;
}
}
if (schema->nodetype == LYS_LEAF) {
if (lyd_wd_add_leaf(root, last_parent, (struct lys_node_leaf*)schema, unres, check_when_must)) {
return EXIT_FAILURE;
}
} else { /* LYS_LEAFLIST */
if (lyd_wd_add_leaflist(root, last_parent, (struct lys_node_leaflist*)schema, unres, check_when_must)) {
goto error;
}
}
break;
case LYS_CHOICE:
/* get existing node in the data root from the choice */
iter = NULL;
if ((toplevel && (*root)) || (!toplevel && subroot)) {
LY_TREE_FOR(toplevel ? (*root) : subroot->child, iter) {
for (siter = lys_parent(iter->schema), siter_prev = iter->schema;
siter && (siter->nodetype & (LYS_CASE | LYS_USES | LYS_CHOICE));
siter_prev = siter, siter = lys_parent(siter)) {
if (siter == schema) {
/* we have the choice instance */
break;
}
}
if (siter == schema) {
/* we have the choice instance;
* the condition must be the same as in the loop because of
* choice's sibling nodes that break the loop, so siter is not NULL,
* but it is not the same as schema */
break;
}
}
}
if (!iter) {
if (((struct lys_node_choice *)schema)->dflt) {
/* there is a default case */
if (lyd_wd_add_subtree(root, last_parent, subroot, ((struct lys_node_choice *)schema)->dflt,
toplevel, options, unres)) {
goto error;
}
}
} else {
/* one of the choice's cases is instantiated, continue into this case */
/* since iter != NULL, siter must be also != NULL and we also know siter_prev
* which points to the child of schema leading towards the instantiated data */
assert(siter && siter_prev);
if (lyd_wd_add_subtree(root, last_parent, subroot, siter_prev, toplevel, options, unres)) {
goto error;
}
}
break;
default:
/* LYS_ANYXML, LYS_ANYDATA, LYS_USES, LYS_GROUPING - do nothing */
break;
}
ly_set_free(present);
return EXIT_SUCCESS;
error:
ly_set_free(present);
return EXIT_FAILURE;
}
/**
* @brief Covering function to process (add/clean) default nodes in the data tree
* @param[in,out] root Pointer to the root node of the complete data tree, the root node can be NULL if the data tree
* is empty
* @param[in] ctx Context for the case the data tree is empty (in that case \p ctx must not be NULL)
* @param[in] options Parser options to know the data tree type, see @ref parseroptions.
* @param[in] unres Unresolved data list, the newly added default nodes may need to add some unresolved items
* @return EXIT_SUCCESS or EXIT_FAILURE
*/
static int
lyd_wd_add(struct lyd_node **root, struct ly_ctx *ctx, const struct lys_module **modules, int mod_count,
struct unres_data *unres, int options)
{
struct lys_node *siter;
int i;
assert(root && !(options & LYD_OPT_ACT_NOTIF));
assert(*root || ctx);
assert(!(options & LYD_OPT_NOSIBLINGS) || *root);
if (options & (LYD_OPT_EDIT | LYD_OPT_GET | LYD_OPT_GETCONFIG)) {
/* no change supposed */
return EXIT_SUCCESS;
}
if (!ctx) {
ctx = (*root)->schema->module->ctx;
}
if (!(options & LYD_OPT_TYPEMASK) || (options & LYD_OPT_CONFIG)) {
if (options & LYD_OPT_NOSIBLINGS) {
if (lyd_wd_add_subtree(root, NULL, NULL, (*root)->schema, 1, options, unres)) {
return EXIT_FAILURE;
}
} else if (modules && mod_count) {
for (i = 0; i < mod_count; ++i) {
LY_TREE_FOR(modules[i]->data, siter) {
if (!(siter->nodetype & (LYS_CONTAINER | LYS_CHOICE | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_ANYDATA |
LYS_USES))) {
continue;
}
if (lyd_wd_add_subtree(root, NULL, NULL, siter, 1, options, unres)) {
return EXIT_FAILURE;
}
}
}
} else {
for (i = 0; i < ctx->models.used; i++) {
/* skip not implemented and disabled modules */
if (!ctx->models.list[i]->implemented || ctx->models.list[i]->disabled) {
continue;
}
LY_TREE_FOR(ctx->models.list[i]->data, siter) {
if (!(siter->nodetype & (LYS_CONTAINER | LYS_CHOICE | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_ANYDATA |
LYS_USES))) {
continue;
}
if (lyd_wd_add_subtree(root, NULL, NULL, siter, 1, options, unres)) {
return EXIT_FAILURE;
}
}
}
}
} else if (options & LYD_OPT_NOTIF) {
if (!(*root) || ((*root)->schema->nodetype != LYS_NOTIF)) {
LOGERR(ctx, LY_EINVAL, "Subtree is not a single notification.");
return EXIT_FAILURE;
}
if (lyd_wd_add_subtree(root, *root, *root, (*root)->schema, 0, options, unres)) {
return EXIT_FAILURE;
}
} else if (options & (LYD_OPT_RPC | LYD_OPT_RPCREPLY)) {
if (!(*root) || !((*root)->schema->nodetype & (LYS_RPC | LYS_ACTION))) {
LOGERR(ctx, LY_EINVAL, "Subtree is not a single RPC/action/reply.");
return EXIT_FAILURE;
}
if (options & LYD_OPT_RPC) {
for (siter = (*root)->schema->child; siter && siter->nodetype != LYS_INPUT; siter = siter->next);
} else { /* LYD_OPT_RPCREPLY */
for (siter = (*root)->schema->child; siter && siter->nodetype != LYS_OUTPUT; siter = siter->next);
}
if (siter) {
if (lyd_wd_add_subtree(root, *root, *root, siter, 0, options, unres)) {
return EXIT_FAILURE;
}
}
} else if (options & LYD_OPT_DATA_TEMPLATE) {
if (lyd_wd_add_subtree(root, NULL, NULL, (*root)->schema, 1, options, unres)) {
return EXIT_FAILURE;
}
} else {
LOGINT(ctx);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
int
lyd_defaults_add_unres(struct lyd_node **root, int options, struct ly_ctx *ctx, const struct lys_module **modules,
int mod_count, const struct lyd_node *data_tree, struct lyd_node *act_notif,
struct unres_data *unres, int wd)
{
struct lyd_node *msg_sibling = NULL, *msg_parent = NULL, *data_tree_sibling, *data_tree_parent;
struct lys_node *msg_op = NULL;
struct ly_set *set;
int ret = EXIT_FAILURE;
assert(root && (*root || ctx) && unres && !(options & LYD_OPT_ACT_NOTIF));
if (!ctx) {
ctx = (*root)->schema->module->ctx;
}
if ((options & LYD_OPT_NOSIBLINGS) && !(*root)) {
LOGERR(ctx, LY_EINVAL, "Cannot add default values for one module (LYD_OPT_NOSIBLINGS) without any data.");
return EXIT_FAILURE;
}
if (options & (LYD_OPT_RPC | LYD_OPT_RPCREPLY | LYD_OPT_NOTIF)) {
if (!(*root)) {
LOGERR(ctx, LY_EINVAL, "Cannot add default values to RPC, RPC reply, and notification without at least the empty container.");
return EXIT_FAILURE;
}
if ((options & LYD_OPT_RPC) && !act_notif && ((*root)->schema->nodetype != LYS_RPC)) {
LOGERR(ctx, LY_EINVAL, "Not valid RPC/action data.");
return EXIT_FAILURE;
}
if ((options & LYD_OPT_RPCREPLY) && !act_notif && ((*root)->schema->nodetype != LYS_RPC)) {
LOGERR(ctx, LY_EINVAL, "Not valid reply data.");
return EXIT_FAILURE;
}
if ((options & LYD_OPT_NOTIF) && !act_notif && ((*root)->schema->nodetype != LYS_NOTIF)) {
LOGERR(ctx, LY_EINVAL, "Not valid notification data.");
return EXIT_FAILURE;
}
/* remember the operation/notification schema */
msg_op = act_notif ? act_notif->schema : (*root)->schema;
} else if (*root && (*root)->parent) {
/* we have inner node, so it will be considered as
* a root of subtree where to add default nodes and
* no of its siblings will be affected */
options |= LYD_OPT_NOSIBLINGS;
}
/* add missing default nodes */
if (wd && lyd_wd_add((act_notif ? &act_notif : root), ctx, modules, mod_count, unres, options)) {
return EXIT_FAILURE;
}
/* check leafrefs and/or instids if any */
if (unres && unres->count) {
if (!(*root)) {
LOGINT(ctx);
return EXIT_FAILURE;
}
/* temporarily link the additional data tree to the RPC/action/notification */
if (data_tree && (options & (LYD_OPT_RPC | LYD_OPT_RPCREPLY | LYD_OPT_NOTIF))) {
/* duplicate the message tree - if it gets deleted we would not be able to positively identify it */
msg_parent = NULL;
msg_sibling = *root;
if (act_notif) {
/* fun case */
data_tree_parent = NULL;
data_tree_sibling = (struct lyd_node *)data_tree;
while (data_tree_sibling) {
while (data_tree_sibling) {
if ((data_tree_sibling->schema == msg_sibling->schema)
&& ((msg_sibling->schema->nodetype != LYS_LIST)
|| lyd_list_equal(data_tree_sibling, msg_sibling, 0))) {
/* match */
break;
}
data_tree_sibling = data_tree_sibling->next;
}
if (data_tree_sibling) {
/* prepare for the new data_tree iteration */
data_tree_parent = data_tree_sibling;
data_tree_sibling = data_tree_sibling->child;
/* find new action sibling to search for later (skip list keys) */
msg_parent = msg_sibling;
assert(msg_sibling->child);
for (msg_sibling = msg_sibling->child;
msg_sibling->schema->nodetype == LYS_LEAF;
msg_sibling = msg_sibling->next) {
assert(msg_sibling->next);
}
if (msg_sibling->schema->nodetype & (LYS_ACTION | LYS_NOTIF)) {
/* we are done */
assert(act_notif->parent);
assert(act_notif->parent->schema == data_tree_parent->schema);
assert(msg_sibling == act_notif);
break;
}
}
}
/* loop ended after the first iteration, set the values correctly */
if (!data_tree_parent) {
data_tree_sibling = (struct lyd_node *)data_tree;
}
} else {
/* easy case */
data_tree_parent = NULL;
data_tree_sibling = (struct lyd_node *)data_tree;
}
/* unlink msg_sibling if needed (won't do anything otherwise) */
lyd_unlink_internal(msg_sibling, 0);
/* now we can insert msg_sibling into data_tree_parent or next to data_tree_sibling */
assert(data_tree_parent || data_tree_sibling);
if (data_tree_parent) {
if (lyd_insert_common(data_tree_parent, NULL, msg_sibling, 0)) {
goto unlink_datatree;
}
} else {
assert(!data_tree_sibling->parent);
if (lyd_insert_nextto(data_tree_sibling->prev, msg_sibling, 0, 0)) {
goto unlink_datatree;
}
}
}
if (resolve_unres_data(ctx, unres, root, options)) {
goto unlink_datatree;
}
/* we are done */
ret = EXIT_SUCCESS;
/* check that the operation/notification tree was not removed */
if (options & (LYD_OPT_RPC | LYD_OPT_RPCREPLY | LYD_OPT_NOTIF)) {
set = NULL;
if (data_tree) {
set = lyd_find_instance(data_tree_parent ? data_tree_parent : data_tree_sibling, msg_op);
assert(set && ((set->number == 0) || (set->number == 1)));
} else if (*root) {
set = lyd_find_instance(*root, msg_op);
assert(set && ((set->number == 0) || (set->number == 1)));
}
if (!set || !set->number) {
/* it was removed, handle specially */
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, msg_op, "Operation/notification not supported because of the current configuration.");
ret = EXIT_FAILURE;
}
ly_set_free(set);
}
unlink_datatree:
/* put the trees back in order */
if (data_tree && (options & (LYD_OPT_RPC | LYD_OPT_RPCREPLY | LYD_OPT_NOTIF))) {
/* unlink and insert it back, if there is a parent */
lyd_unlink_internal(msg_sibling, 0);
if (msg_parent) {
lyd_insert_common(msg_parent, NULL, msg_sibling, 0);
}
}
} else {
/* we are done */
ret = EXIT_SUCCESS;
}
return ret;
}
API struct lys_module *
lyd_node_module(const struct lyd_node *node)
{
if (!node) {
return NULL;
}
return node->schema->module->type ? ((struct lys_submodule *)node->schema->module)->belongsto : node->schema->module;
}
API double
lyd_dec64_to_double(const struct lyd_node *node)
{
if (!node || !(node->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST))
|| (((struct lys_node_leaf *)node->schema)->type.base != LY_TYPE_DEC64)) {
LOGARG;
return 0;
}
return atof(((struct lyd_node_leaf_list *)node)->value_str);
}
API const struct lys_type *
lyd_leaf_type(const struct lyd_node_leaf_list *leaf)
{
struct lys_type *type;
if (!leaf || !(leaf->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
return NULL;
}
type = &((struct lys_node_leaf *)leaf->schema)->type;
do {
if (type->base == LY_TYPE_LEAFREF) {
type = &type->info.lref.target->type;
} else if (type->base == LY_TYPE_UNION) {
if (type->info.uni.has_ptr_type && leaf->validity) {
/* we don't know what it will be after resolution (validation) */
LOGVAL(leaf->schema->module->ctx, LYE_SPEC, LY_VLOG_LYD, leaf,
"Unable to determine the type of value \"%s\" from union type \"%s\" prior to validation.",
leaf->value_str, type->der->name);
return NULL;
}
if (resolve_union((struct lyd_node_leaf_list *)leaf, type, 0, 0, &type)) {
/* resolve union failed */
return NULL;
}
}
} while (type->base == LY_TYPE_LEAFREF);
return type;
}
API int
lyd_lyb_data_length(const char *data)
{
const char *ptr;
uint16_t i, mod_count, str_len;
uint8_t tmp_buf[2];
LYB_META meta;
if (!data) {
return -1;
}
ptr = data;
/* magic number */
if ((ptr[0] != 'l') || (ptr[1] != 'y') || (ptr[2] != 'b')) {
return -1;
}
ptr += 3;
/* header */
++ptr;
/* models */
memcpy(tmp_buf, ptr, 2);
ptr += 2;
mod_count = tmp_buf[0] | (tmp_buf[1] << 8);
for (i = 0; i < mod_count; ++i) {
/* model name */
memcpy(tmp_buf, ptr, 2);
ptr += 2;
str_len = tmp_buf[0] | (tmp_buf[1] << 8);
ptr += str_len;
/* revision */
ptr += 2;
}
if (ptr[0]) {
/* subtrees */
do {
memcpy(&meta, ptr, LYB_META_BYTES);
ptr += LYB_META_BYTES;
/* read whole subtree (chunk size) */
ptr += *((uint8_t *)&meta);
/* skip inner chunks (inner chunk count) */
ptr += *(((uint8_t *)&meta) + LYB_SIZE_BYTES) * LYB_META_BYTES;
} while ((*((uint8_t *)&meta) == LYB_SIZE_MAX) || ptr[0]);
}
/* ending zero */
++ptr;
return ptr - data;
}
#ifdef LY_ENABLED_LYD_PRIV
API void *
lyd_set_private(const struct lyd_node *node, void *priv)
{
void *prev;
if (!node) {
LOGARG;
return NULL;
}
prev = node->priv;
((struct lyd_node *)node)->priv = priv;
return prev;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_1359_1 |
crossvul-cpp_data_bad_5830_0 | /*
* Radiotap parser
*
* Copyright 2007 Andy Green <andy@warmcat.com>
* Copyright 2009 Johannes Berg <johannes@sipsolutions.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Alternatively, this software may be distributed under the terms of BSD
* license.
*
* See COPYING for more details.
*/
#include <linux/kernel.h>
#include <linux/export.h>
#include <net/cfg80211.h>
#include <net/ieee80211_radiotap.h>
#include <asm/unaligned.h>
/* function prototypes and related defs are in include/net/cfg80211.h */
static const struct radiotap_align_size rtap_namespace_sizes[] = {
[IEEE80211_RADIOTAP_TSFT] = { .align = 8, .size = 8, },
[IEEE80211_RADIOTAP_FLAGS] = { .align = 1, .size = 1, },
[IEEE80211_RADIOTAP_RATE] = { .align = 1, .size = 1, },
[IEEE80211_RADIOTAP_CHANNEL] = { .align = 2, .size = 4, },
[IEEE80211_RADIOTAP_FHSS] = { .align = 2, .size = 2, },
[IEEE80211_RADIOTAP_DBM_ANTSIGNAL] = { .align = 1, .size = 1, },
[IEEE80211_RADIOTAP_DBM_ANTNOISE] = { .align = 1, .size = 1, },
[IEEE80211_RADIOTAP_LOCK_QUALITY] = { .align = 2, .size = 2, },
[IEEE80211_RADIOTAP_TX_ATTENUATION] = { .align = 2, .size = 2, },
[IEEE80211_RADIOTAP_DB_TX_ATTENUATION] = { .align = 2, .size = 2, },
[IEEE80211_RADIOTAP_DBM_TX_POWER] = { .align = 1, .size = 1, },
[IEEE80211_RADIOTAP_ANTENNA] = { .align = 1, .size = 1, },
[IEEE80211_RADIOTAP_DB_ANTSIGNAL] = { .align = 1, .size = 1, },
[IEEE80211_RADIOTAP_DB_ANTNOISE] = { .align = 1, .size = 1, },
[IEEE80211_RADIOTAP_RX_FLAGS] = { .align = 2, .size = 2, },
[IEEE80211_RADIOTAP_TX_FLAGS] = { .align = 2, .size = 2, },
[IEEE80211_RADIOTAP_RTS_RETRIES] = { .align = 1, .size = 1, },
[IEEE80211_RADIOTAP_DATA_RETRIES] = { .align = 1, .size = 1, },
[IEEE80211_RADIOTAP_MCS] = { .align = 1, .size = 3, },
[IEEE80211_RADIOTAP_AMPDU_STATUS] = { .align = 4, .size = 8, },
/*
* add more here as they are defined in radiotap.h
*/
};
static const struct ieee80211_radiotap_namespace radiotap_ns = {
.n_bits = ARRAY_SIZE(rtap_namespace_sizes),
.align_size = rtap_namespace_sizes,
};
/**
* ieee80211_radiotap_iterator_init - radiotap parser iterator initialization
* @iterator: radiotap_iterator to initialize
* @radiotap_header: radiotap header to parse
* @max_length: total length we can parse into (eg, whole packet length)
*
* Returns: 0 or a negative error code if there is a problem.
*
* This function initializes an opaque iterator struct which can then
* be passed to ieee80211_radiotap_iterator_next() to visit every radiotap
* argument which is present in the header. It knows about extended
* present headers and handles them.
*
* How to use:
* call __ieee80211_radiotap_iterator_init() to init a semi-opaque iterator
* struct ieee80211_radiotap_iterator (no need to init the struct beforehand)
* checking for a good 0 return code. Then loop calling
* __ieee80211_radiotap_iterator_next()... it returns either 0,
* -ENOENT if there are no more args to parse, or -EINVAL if there is a problem.
* The iterator's @this_arg member points to the start of the argument
* associated with the current argument index that is present, which can be
* found in the iterator's @this_arg_index member. This arg index corresponds
* to the IEEE80211_RADIOTAP_... defines.
*
* Radiotap header length:
* You can find the CPU-endian total radiotap header length in
* iterator->max_length after executing ieee80211_radiotap_iterator_init()
* successfully.
*
* Alignment Gotcha:
* You must take care when dereferencing iterator.this_arg
* for multibyte types... the pointer is not aligned. Use
* get_unaligned((type *)iterator.this_arg) to dereference
* iterator.this_arg for type "type" safely on all arches.
*
* Example code:
* See Documentation/networking/radiotap-headers.txt
*/
int ieee80211_radiotap_iterator_init(
struct ieee80211_radiotap_iterator *iterator,
struct ieee80211_radiotap_header *radiotap_header,
int max_length, const struct ieee80211_radiotap_vendor_namespaces *vns)
{
/* Linux only supports version 0 radiotap format */
if (radiotap_header->it_version)
return -EINVAL;
/* sanity check for allowed length and radiotap length field */
if (max_length < get_unaligned_le16(&radiotap_header->it_len))
return -EINVAL;
iterator->_rtheader = radiotap_header;
iterator->_max_length = get_unaligned_le16(&radiotap_header->it_len);
iterator->_arg_index = 0;
iterator->_bitmap_shifter = get_unaligned_le32(&radiotap_header->it_present);
iterator->_arg = (uint8_t *)radiotap_header + sizeof(*radiotap_header);
iterator->_reset_on_ext = 0;
iterator->_next_bitmap = &radiotap_header->it_present;
iterator->_next_bitmap++;
iterator->_vns = vns;
iterator->current_namespace = &radiotap_ns;
iterator->is_radiotap_ns = 1;
/* find payload start allowing for extended bitmap(s) */
if (iterator->_bitmap_shifter & (1<<IEEE80211_RADIOTAP_EXT)) {
while (get_unaligned_le32(iterator->_arg) &
(1 << IEEE80211_RADIOTAP_EXT)) {
iterator->_arg += sizeof(uint32_t);
/*
* check for insanity where the present bitmaps
* keep claiming to extend up to or even beyond the
* stated radiotap header length
*/
if ((unsigned long)iterator->_arg -
(unsigned long)iterator->_rtheader >
(unsigned long)iterator->_max_length)
return -EINVAL;
}
iterator->_arg += sizeof(uint32_t);
/*
* no need to check again for blowing past stated radiotap
* header length, because ieee80211_radiotap_iterator_next
* checks it before it is dereferenced
*/
}
iterator->this_arg = iterator->_arg;
/* we are all initialized happily */
return 0;
}
EXPORT_SYMBOL(ieee80211_radiotap_iterator_init);
static void find_ns(struct ieee80211_radiotap_iterator *iterator,
uint32_t oui, uint8_t subns)
{
int i;
iterator->current_namespace = NULL;
if (!iterator->_vns)
return;
for (i = 0; i < iterator->_vns->n_ns; i++) {
if (iterator->_vns->ns[i].oui != oui)
continue;
if (iterator->_vns->ns[i].subns != subns)
continue;
iterator->current_namespace = &iterator->_vns->ns[i];
break;
}
}
/**
* ieee80211_radiotap_iterator_next - return next radiotap parser iterator arg
* @iterator: radiotap_iterator to move to next arg (if any)
*
* Returns: 0 if there is an argument to handle,
* -ENOENT if there are no more args or -EINVAL
* if there is something else wrong.
*
* This function provides the next radiotap arg index (IEEE80211_RADIOTAP_*)
* in @this_arg_index and sets @this_arg to point to the
* payload for the field. It takes care of alignment handling and extended
* present fields. @this_arg can be changed by the caller (eg,
* incremented to move inside a compound argument like
* IEEE80211_RADIOTAP_CHANNEL). The args pointed to are in
* little-endian format whatever the endianess of your CPU.
*
* Alignment Gotcha:
* You must take care when dereferencing iterator.this_arg
* for multibyte types... the pointer is not aligned. Use
* get_unaligned((type *)iterator.this_arg) to dereference
* iterator.this_arg for type "type" safely on all arches.
*/
int ieee80211_radiotap_iterator_next(
struct ieee80211_radiotap_iterator *iterator)
{
while (1) {
int hit = 0;
int pad, align, size, subns;
uint32_t oui;
/* if no more EXT bits, that's it */
if ((iterator->_arg_index % 32) == IEEE80211_RADIOTAP_EXT &&
!(iterator->_bitmap_shifter & 1))
return -ENOENT;
if (!(iterator->_bitmap_shifter & 1))
goto next_entry; /* arg not present */
/* get alignment/size of data */
switch (iterator->_arg_index % 32) {
case IEEE80211_RADIOTAP_RADIOTAP_NAMESPACE:
case IEEE80211_RADIOTAP_EXT:
align = 1;
size = 0;
break;
case IEEE80211_RADIOTAP_VENDOR_NAMESPACE:
align = 2;
size = 6;
break;
default:
if (!iterator->current_namespace ||
iterator->_arg_index >= iterator->current_namespace->n_bits) {
if (iterator->current_namespace == &radiotap_ns)
return -ENOENT;
align = 0;
} else {
align = iterator->current_namespace->align_size[iterator->_arg_index].align;
size = iterator->current_namespace->align_size[iterator->_arg_index].size;
}
if (!align) {
/* skip all subsequent data */
iterator->_arg = iterator->_next_ns_data;
/* give up on this namespace */
iterator->current_namespace = NULL;
goto next_entry;
}
break;
}
/*
* arg is present, account for alignment padding
*
* Note that these alignments are relative to the start
* of the radiotap header. There is no guarantee
* that the radiotap header itself is aligned on any
* kind of boundary.
*
* The above is why get_unaligned() is used to dereference
* multibyte elements from the radiotap area.
*/
pad = ((unsigned long)iterator->_arg -
(unsigned long)iterator->_rtheader) & (align - 1);
if (pad)
iterator->_arg += align - pad;
if (iterator->_arg_index % 32 == IEEE80211_RADIOTAP_VENDOR_NAMESPACE) {
int vnslen;
if ((unsigned long)iterator->_arg + size -
(unsigned long)iterator->_rtheader >
(unsigned long)iterator->_max_length)
return -EINVAL;
oui = (*iterator->_arg << 16) |
(*(iterator->_arg + 1) << 8) |
*(iterator->_arg + 2);
subns = *(iterator->_arg + 3);
find_ns(iterator, oui, subns);
vnslen = get_unaligned_le16(iterator->_arg + 4);
iterator->_next_ns_data = iterator->_arg + size + vnslen;
if (!iterator->current_namespace)
size += vnslen;
}
/*
* this is what we will return to user, but we need to
* move on first so next call has something fresh to test
*/
iterator->this_arg_index = iterator->_arg_index;
iterator->this_arg = iterator->_arg;
iterator->this_arg_size = size;
/* internally move on the size of this arg */
iterator->_arg += size;
/*
* check for insanity where we are given a bitmap that
* claims to have more arg content than the length of the
* radiotap section. We will normally end up equalling this
* max_length on the last arg, never exceeding it.
*/
if ((unsigned long)iterator->_arg -
(unsigned long)iterator->_rtheader >
(unsigned long)iterator->_max_length)
return -EINVAL;
/* these special ones are valid in each bitmap word */
switch (iterator->_arg_index % 32) {
case IEEE80211_RADIOTAP_VENDOR_NAMESPACE:
iterator->_reset_on_ext = 1;
iterator->is_radiotap_ns = 0;
/*
* If parser didn't register this vendor
* namespace with us, allow it to show it
* as 'raw. Do do that, set argument index
* to vendor namespace.
*/
iterator->this_arg_index =
IEEE80211_RADIOTAP_VENDOR_NAMESPACE;
if (!iterator->current_namespace)
hit = 1;
goto next_entry;
case IEEE80211_RADIOTAP_RADIOTAP_NAMESPACE:
iterator->_reset_on_ext = 1;
iterator->current_namespace = &radiotap_ns;
iterator->is_radiotap_ns = 1;
goto next_entry;
case IEEE80211_RADIOTAP_EXT:
/*
* bit 31 was set, there is more
* -- move to next u32 bitmap
*/
iterator->_bitmap_shifter =
get_unaligned_le32(iterator->_next_bitmap);
iterator->_next_bitmap++;
if (iterator->_reset_on_ext)
iterator->_arg_index = 0;
else
iterator->_arg_index++;
iterator->_reset_on_ext = 0;
break;
default:
/* we've got a hit! */
hit = 1;
next_entry:
iterator->_bitmap_shifter >>= 1;
iterator->_arg_index++;
}
/* if we found a valid arg earlier, return it now */
if (hit)
return 0;
}
}
EXPORT_SYMBOL(ieee80211_radiotap_iterator_next);
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5830_0 |
crossvul-cpp_data_bad_5056_0 | /*
* videobuf2-v4l2.c - V4L2 driver helper framework
*
* Copyright (C) 2010 Samsung Electronics
*
* Author: Pawel Osciak <pawel@osciak.com>
* Marek Szyprowski <m.szyprowski@samsung.com>
*
* The vb2_thread implementation was based on code from videobuf-dvb.c:
* (c) 2004 Gerd Knorr <kraxel@bytesex.org> [SUSE Labs]
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation.
*/
#include <linux/err.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/poll.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/freezer.h>
#include <linux/kthread.h>
#include <media/v4l2-dev.h>
#include <media/v4l2-fh.h>
#include <media/v4l2-event.h>
#include <media/v4l2-common.h>
#include <media/videobuf2-v4l2.h>
static int debug;
module_param(debug, int, 0644);
#define dprintk(level, fmt, arg...) \
do { \
if (debug >= level) \
pr_info("vb2-v4l2: %s: " fmt, __func__, ## arg); \
} while (0)
/* Flags that are set by the vb2 core */
#define V4L2_BUFFER_MASK_FLAGS (V4L2_BUF_FLAG_MAPPED | V4L2_BUF_FLAG_QUEUED | \
V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_ERROR | \
V4L2_BUF_FLAG_PREPARED | \
V4L2_BUF_FLAG_TIMESTAMP_MASK)
/* Output buffer flags that should be passed on to the driver */
#define V4L2_BUFFER_OUT_FLAGS (V4L2_BUF_FLAG_PFRAME | V4L2_BUF_FLAG_BFRAME | \
V4L2_BUF_FLAG_KEYFRAME | V4L2_BUF_FLAG_TIMECODE)
/**
* __verify_planes_array() - verify that the planes array passed in struct
* v4l2_buffer from userspace can be safely used
*/
static int __verify_planes_array(struct vb2_buffer *vb, const struct v4l2_buffer *b)
{
if (!V4L2_TYPE_IS_MULTIPLANAR(b->type))
return 0;
/* Is memory for copying plane information present? */
if (b->m.planes == NULL) {
dprintk(1, "multi-planar buffer passed but "
"planes array not provided\n");
return -EINVAL;
}
if (b->length < vb->num_planes || b->length > VB2_MAX_PLANES) {
dprintk(1, "incorrect planes array length, "
"expected %d, got %d\n", vb->num_planes, b->length);
return -EINVAL;
}
return 0;
}
/**
* __verify_length() - Verify that the bytesused value for each plane fits in
* the plane length and that the data offset doesn't exceed the bytesused value.
*/
static int __verify_length(struct vb2_buffer *vb, const struct v4l2_buffer *b)
{
unsigned int length;
unsigned int bytesused;
unsigned int plane;
if (!V4L2_TYPE_IS_OUTPUT(b->type))
return 0;
if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) {
for (plane = 0; plane < vb->num_planes; ++plane) {
length = (b->memory == VB2_MEMORY_USERPTR ||
b->memory == VB2_MEMORY_DMABUF)
? b->m.planes[plane].length
: vb->planes[plane].length;
bytesused = b->m.planes[plane].bytesused
? b->m.planes[plane].bytesused : length;
if (b->m.planes[plane].bytesused > length)
return -EINVAL;
if (b->m.planes[plane].data_offset > 0 &&
b->m.planes[plane].data_offset >= bytesused)
return -EINVAL;
}
} else {
length = (b->memory == VB2_MEMORY_USERPTR)
? b->length : vb->planes[0].length;
if (b->bytesused > length)
return -EINVAL;
}
return 0;
}
static void __copy_timestamp(struct vb2_buffer *vb, const void *pb)
{
const struct v4l2_buffer *b = pb;
struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
struct vb2_queue *q = vb->vb2_queue;
if (q->is_output) {
/*
* For output buffers copy the timestamp if needed,
* and the timecode field and flag if needed.
*/
if (q->copy_timestamp)
vb->timestamp = timeval_to_ns(&b->timestamp);
vbuf->flags |= b->flags & V4L2_BUF_FLAG_TIMECODE;
if (b->flags & V4L2_BUF_FLAG_TIMECODE)
vbuf->timecode = b->timecode;
}
};
static void vb2_warn_zero_bytesused(struct vb2_buffer *vb)
{
static bool check_once;
if (check_once)
return;
check_once = true;
WARN_ON(1);
pr_warn("use of bytesused == 0 is deprecated and will be removed in the future,\n");
if (vb->vb2_queue->allow_zero_bytesused)
pr_warn("use VIDIOC_DECODER_CMD(V4L2_DEC_CMD_STOP) instead.\n");
else
pr_warn("use the actual size instead.\n");
}
static int vb2_queue_or_prepare_buf(struct vb2_queue *q, struct v4l2_buffer *b,
const char *opname)
{
if (b->type != q->type) {
dprintk(1, "%s: invalid buffer type\n", opname);
return -EINVAL;
}
if (b->index >= q->num_buffers) {
dprintk(1, "%s: buffer index out of range\n", opname);
return -EINVAL;
}
if (q->bufs[b->index] == NULL) {
/* Should never happen */
dprintk(1, "%s: buffer is NULL\n", opname);
return -EINVAL;
}
if (b->memory != q->memory) {
dprintk(1, "%s: invalid memory type\n", opname);
return -EINVAL;
}
return __verify_planes_array(q->bufs[b->index], b);
}
/**
* __fill_v4l2_buffer() - fill in a struct v4l2_buffer with information to be
* returned to userspace
*/
static void __fill_v4l2_buffer(struct vb2_buffer *vb, void *pb)
{
struct v4l2_buffer *b = pb;
struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
struct vb2_queue *q = vb->vb2_queue;
unsigned int plane;
/* Copy back data such as timestamp, flags, etc. */
b->index = vb->index;
b->type = vb->type;
b->memory = vb->memory;
b->bytesused = 0;
b->flags = vbuf->flags;
b->field = vbuf->field;
b->timestamp = ns_to_timeval(vb->timestamp);
b->timecode = vbuf->timecode;
b->sequence = vbuf->sequence;
b->reserved2 = 0;
b->reserved = 0;
if (q->is_multiplanar) {
/*
* Fill in plane-related data if userspace provided an array
* for it. The caller has already verified memory and size.
*/
b->length = vb->num_planes;
for (plane = 0; plane < vb->num_planes; ++plane) {
struct v4l2_plane *pdst = &b->m.planes[plane];
struct vb2_plane *psrc = &vb->planes[plane];
pdst->bytesused = psrc->bytesused;
pdst->length = psrc->length;
if (q->memory == VB2_MEMORY_MMAP)
pdst->m.mem_offset = psrc->m.offset;
else if (q->memory == VB2_MEMORY_USERPTR)
pdst->m.userptr = psrc->m.userptr;
else if (q->memory == VB2_MEMORY_DMABUF)
pdst->m.fd = psrc->m.fd;
pdst->data_offset = psrc->data_offset;
memset(pdst->reserved, 0, sizeof(pdst->reserved));
}
} else {
/*
* We use length and offset in v4l2_planes array even for
* single-planar buffers, but userspace does not.
*/
b->length = vb->planes[0].length;
b->bytesused = vb->planes[0].bytesused;
if (q->memory == VB2_MEMORY_MMAP)
b->m.offset = vb->planes[0].m.offset;
else if (q->memory == VB2_MEMORY_USERPTR)
b->m.userptr = vb->planes[0].m.userptr;
else if (q->memory == VB2_MEMORY_DMABUF)
b->m.fd = vb->planes[0].m.fd;
}
/*
* Clear any buffer state related flags.
*/
b->flags &= ~V4L2_BUFFER_MASK_FLAGS;
b->flags |= q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK;
if (!q->copy_timestamp) {
/*
* For non-COPY timestamps, drop timestamp source bits
* and obtain the timestamp source from the queue.
*/
b->flags &= ~V4L2_BUF_FLAG_TSTAMP_SRC_MASK;
b->flags |= q->timestamp_flags & V4L2_BUF_FLAG_TSTAMP_SRC_MASK;
}
switch (vb->state) {
case VB2_BUF_STATE_QUEUED:
case VB2_BUF_STATE_ACTIVE:
b->flags |= V4L2_BUF_FLAG_QUEUED;
break;
case VB2_BUF_STATE_ERROR:
b->flags |= V4L2_BUF_FLAG_ERROR;
/* fall through */
case VB2_BUF_STATE_DONE:
b->flags |= V4L2_BUF_FLAG_DONE;
break;
case VB2_BUF_STATE_PREPARED:
b->flags |= V4L2_BUF_FLAG_PREPARED;
break;
case VB2_BUF_STATE_PREPARING:
case VB2_BUF_STATE_DEQUEUED:
case VB2_BUF_STATE_REQUEUEING:
/* nothing */
break;
}
if (vb2_buffer_in_use(q, vb))
b->flags |= V4L2_BUF_FLAG_MAPPED;
if (!q->is_output &&
b->flags & V4L2_BUF_FLAG_DONE &&
b->flags & V4L2_BUF_FLAG_LAST)
q->last_buffer_dequeued = true;
}
/**
* __fill_vb2_buffer() - fill a vb2_buffer with information provided in a
* v4l2_buffer by the userspace. It also verifies that struct
* v4l2_buffer has a valid number of planes.
*/
static int __fill_vb2_buffer(struct vb2_buffer *vb,
const void *pb, struct vb2_plane *planes)
{
struct vb2_queue *q = vb->vb2_queue;
const struct v4l2_buffer *b = pb;
struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
unsigned int plane;
int ret;
ret = __verify_length(vb, b);
if (ret < 0) {
dprintk(1, "plane parameters verification failed: %d\n", ret);
return ret;
}
if (b->field == V4L2_FIELD_ALTERNATE && q->is_output) {
/*
* If the format's field is ALTERNATE, then the buffer's field
* should be either TOP or BOTTOM, not ALTERNATE since that
* makes no sense. The driver has to know whether the
* buffer represents a top or a bottom field in order to
* program any DMA correctly. Using ALTERNATE is wrong, since
* that just says that it is either a top or a bottom field,
* but not which of the two it is.
*/
dprintk(1, "the field is incorrectly set to ALTERNATE "
"for an output buffer\n");
return -EINVAL;
}
vb->timestamp = 0;
vbuf->sequence = 0;
if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) {
if (b->memory == VB2_MEMORY_USERPTR) {
for (plane = 0; plane < vb->num_planes; ++plane) {
planes[plane].m.userptr =
b->m.planes[plane].m.userptr;
planes[plane].length =
b->m.planes[plane].length;
}
}
if (b->memory == VB2_MEMORY_DMABUF) {
for (plane = 0; plane < vb->num_planes; ++plane) {
planes[plane].m.fd =
b->m.planes[plane].m.fd;
planes[plane].length =
b->m.planes[plane].length;
}
}
/* Fill in driver-provided information for OUTPUT types */
if (V4L2_TYPE_IS_OUTPUT(b->type)) {
/*
* Will have to go up to b->length when API starts
* accepting variable number of planes.
*
* If bytesused == 0 for the output buffer, then fall
* back to the full buffer size. In that case
* userspace clearly never bothered to set it and
* it's a safe assumption that they really meant to
* use the full plane sizes.
*
* Some drivers, e.g. old codec drivers, use bytesused == 0
* as a way to indicate that streaming is finished.
* In that case, the driver should use the
* allow_zero_bytesused flag to keep old userspace
* applications working.
*/
for (plane = 0; plane < vb->num_planes; ++plane) {
struct vb2_plane *pdst = &planes[plane];
struct v4l2_plane *psrc = &b->m.planes[plane];
if (psrc->bytesused == 0)
vb2_warn_zero_bytesused(vb);
if (vb->vb2_queue->allow_zero_bytesused)
pdst->bytesused = psrc->bytesused;
else
pdst->bytesused = psrc->bytesused ?
psrc->bytesused : pdst->length;
pdst->data_offset = psrc->data_offset;
}
}
} else {
/*
* Single-planar buffers do not use planes array,
* so fill in relevant v4l2_buffer struct fields instead.
* In videobuf we use our internal V4l2_planes struct for
* single-planar buffers as well, for simplicity.
*
* If bytesused == 0 for the output buffer, then fall back
* to the full buffer size as that's a sensible default.
*
* Some drivers, e.g. old codec drivers, use bytesused == 0 as
* a way to indicate that streaming is finished. In that case,
* the driver should use the allow_zero_bytesused flag to keep
* old userspace applications working.
*/
if (b->memory == VB2_MEMORY_USERPTR) {
planes[0].m.userptr = b->m.userptr;
planes[0].length = b->length;
}
if (b->memory == VB2_MEMORY_DMABUF) {
planes[0].m.fd = b->m.fd;
planes[0].length = b->length;
}
if (V4L2_TYPE_IS_OUTPUT(b->type)) {
if (b->bytesused == 0)
vb2_warn_zero_bytesused(vb);
if (vb->vb2_queue->allow_zero_bytesused)
planes[0].bytesused = b->bytesused;
else
planes[0].bytesused = b->bytesused ?
b->bytesused : planes[0].length;
} else
planes[0].bytesused = 0;
}
/* Zero flags that the vb2 core handles */
vbuf->flags = b->flags & ~V4L2_BUFFER_MASK_FLAGS;
if (!vb->vb2_queue->copy_timestamp || !V4L2_TYPE_IS_OUTPUT(b->type)) {
/*
* Non-COPY timestamps and non-OUTPUT queues will get
* their timestamp and timestamp source flags from the
* queue.
*/
vbuf->flags &= ~V4L2_BUF_FLAG_TSTAMP_SRC_MASK;
}
if (V4L2_TYPE_IS_OUTPUT(b->type)) {
/*
* For output buffers mask out the timecode flag:
* this will be handled later in vb2_internal_qbuf().
* The 'field' is valid metadata for this output buffer
* and so that needs to be copied here.
*/
vbuf->flags &= ~V4L2_BUF_FLAG_TIMECODE;
vbuf->field = b->field;
} else {
/* Zero any output buffer flags as this is a capture buffer */
vbuf->flags &= ~V4L2_BUFFER_OUT_FLAGS;
}
return 0;
}
static const struct vb2_buf_ops v4l2_buf_ops = {
.fill_user_buffer = __fill_v4l2_buffer,
.fill_vb2_buffer = __fill_vb2_buffer,
.copy_timestamp = __copy_timestamp,
};
/**
* vb2_querybuf() - query video buffer information
* @q: videobuf queue
* @b: buffer struct passed from userspace to vidioc_querybuf handler
* in driver
*
* Should be called from vidioc_querybuf ioctl handler in driver.
* This function will verify the passed v4l2_buffer structure and fill the
* relevant information for the userspace.
*
* The return values from this function are intended to be directly returned
* from vidioc_querybuf handler in driver.
*/
int vb2_querybuf(struct vb2_queue *q, struct v4l2_buffer *b)
{
struct vb2_buffer *vb;
int ret;
if (b->type != q->type) {
dprintk(1, "wrong buffer type\n");
return -EINVAL;
}
if (b->index >= q->num_buffers) {
dprintk(1, "buffer index out of range\n");
return -EINVAL;
}
vb = q->bufs[b->index];
ret = __verify_planes_array(vb, b);
if (!ret)
vb2_core_querybuf(q, b->index, b);
return ret;
}
EXPORT_SYMBOL(vb2_querybuf);
/**
* vb2_reqbufs() - Wrapper for vb2_core_reqbufs() that also verifies
* the memory and type values.
* @q: videobuf2 queue
* @req: struct passed from userspace to vidioc_reqbufs handler
* in driver
*/
int vb2_reqbufs(struct vb2_queue *q, struct v4l2_requestbuffers *req)
{
int ret = vb2_verify_memory_type(q, req->memory, req->type);
return ret ? ret : vb2_core_reqbufs(q, req->memory, &req->count);
}
EXPORT_SYMBOL_GPL(vb2_reqbufs);
/**
* vb2_prepare_buf() - Pass ownership of a buffer from userspace to the kernel
* @q: videobuf2 queue
* @b: buffer structure passed from userspace to vidioc_prepare_buf
* handler in driver
*
* Should be called from vidioc_prepare_buf ioctl handler of a driver.
* This function:
* 1) verifies the passed buffer,
* 2) calls buf_prepare callback in the driver (if provided), in which
* driver-specific buffer initialization can be performed,
*
* The return values from this function are intended to be directly returned
* from vidioc_prepare_buf handler in driver.
*/
int vb2_prepare_buf(struct vb2_queue *q, struct v4l2_buffer *b)
{
int ret;
if (vb2_fileio_is_active(q)) {
dprintk(1, "file io in progress\n");
return -EBUSY;
}
ret = vb2_queue_or_prepare_buf(q, b, "prepare_buf");
return ret ? ret : vb2_core_prepare_buf(q, b->index, b);
}
EXPORT_SYMBOL_GPL(vb2_prepare_buf);
/**
* vb2_create_bufs() - Wrapper for vb2_core_create_bufs() that also verifies
* the memory and type values.
* @q: videobuf2 queue
* @create: creation parameters, passed from userspace to vidioc_create_bufs
* handler in driver
*/
int vb2_create_bufs(struct vb2_queue *q, struct v4l2_create_buffers *create)
{
unsigned requested_planes = 1;
unsigned requested_sizes[VIDEO_MAX_PLANES];
struct v4l2_format *f = &create->format;
int ret = vb2_verify_memory_type(q, create->memory, f->type);
unsigned i;
create->index = q->num_buffers;
if (create->count == 0)
return ret != -EBUSY ? ret : 0;
switch (f->type) {
case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
requested_planes = f->fmt.pix_mp.num_planes;
if (requested_planes == 0 ||
requested_planes > VIDEO_MAX_PLANES)
return -EINVAL;
for (i = 0; i < requested_planes; i++)
requested_sizes[i] =
f->fmt.pix_mp.plane_fmt[i].sizeimage;
break;
case V4L2_BUF_TYPE_VIDEO_CAPTURE:
case V4L2_BUF_TYPE_VIDEO_OUTPUT:
requested_sizes[0] = f->fmt.pix.sizeimage;
break;
case V4L2_BUF_TYPE_VBI_CAPTURE:
case V4L2_BUF_TYPE_VBI_OUTPUT:
requested_sizes[0] = f->fmt.vbi.samples_per_line *
(f->fmt.vbi.count[0] + f->fmt.vbi.count[1]);
break;
case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE:
case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT:
requested_sizes[0] = f->fmt.sliced.io_size;
break;
case V4L2_BUF_TYPE_SDR_CAPTURE:
case V4L2_BUF_TYPE_SDR_OUTPUT:
requested_sizes[0] = f->fmt.sdr.buffersize;
break;
default:
return -EINVAL;
}
for (i = 0; i < requested_planes; i++)
if (requested_sizes[i] == 0)
return -EINVAL;
return ret ? ret : vb2_core_create_bufs(q, create->memory,
&create->count, requested_planes, requested_sizes);
}
EXPORT_SYMBOL_GPL(vb2_create_bufs);
static int vb2_internal_qbuf(struct vb2_queue *q, struct v4l2_buffer *b)
{
int ret = vb2_queue_or_prepare_buf(q, b, "qbuf");
return ret ? ret : vb2_core_qbuf(q, b->index, b);
}
/**
* vb2_qbuf() - Queue a buffer from userspace
* @q: videobuf2 queue
* @b: buffer structure passed from userspace to vidioc_qbuf handler
* in driver
*
* Should be called from vidioc_qbuf ioctl handler of a driver.
* This function:
* 1) verifies the passed buffer,
* 2) if necessary, calls buf_prepare callback in the driver (if provided), in
* which driver-specific buffer initialization can be performed,
* 3) if streaming is on, queues the buffer in driver by the means of buf_queue
* callback for processing.
*
* The return values from this function are intended to be directly returned
* from vidioc_qbuf handler in driver.
*/
int vb2_qbuf(struct vb2_queue *q, struct v4l2_buffer *b)
{
if (vb2_fileio_is_active(q)) {
dprintk(1, "file io in progress\n");
return -EBUSY;
}
return vb2_internal_qbuf(q, b);
}
EXPORT_SYMBOL_GPL(vb2_qbuf);
static int vb2_internal_dqbuf(struct vb2_queue *q, struct v4l2_buffer *b,
bool nonblocking)
{
int ret;
if (b->type != q->type) {
dprintk(1, "invalid buffer type\n");
return -EINVAL;
}
ret = vb2_core_dqbuf(q, NULL, b, nonblocking);
return ret;
}
/**
* vb2_dqbuf() - Dequeue a buffer to the userspace
* @q: videobuf2 queue
* @b: buffer structure passed from userspace to vidioc_dqbuf handler
* in driver
* @nonblocking: if true, this call will not sleep waiting for a buffer if no
* buffers ready for dequeuing are present. Normally the driver
* would be passing (file->f_flags & O_NONBLOCK) here
*
* Should be called from vidioc_dqbuf ioctl handler of a driver.
* This function:
* 1) verifies the passed buffer,
* 2) calls buf_finish callback in the driver (if provided), in which
* driver can perform any additional operations that may be required before
* returning the buffer to userspace, such as cache sync,
* 3) the buffer struct members are filled with relevant information for
* the userspace.
*
* The return values from this function are intended to be directly returned
* from vidioc_dqbuf handler in driver.
*/
int vb2_dqbuf(struct vb2_queue *q, struct v4l2_buffer *b, bool nonblocking)
{
if (vb2_fileio_is_active(q)) {
dprintk(1, "file io in progress\n");
return -EBUSY;
}
return vb2_internal_dqbuf(q, b, nonblocking);
}
EXPORT_SYMBOL_GPL(vb2_dqbuf);
/**
* vb2_streamon - start streaming
* @q: videobuf2 queue
* @type: type argument passed from userspace to vidioc_streamon handler
*
* Should be called from vidioc_streamon handler of a driver.
* This function:
* 1) verifies current state
* 2) passes any previously queued buffers to the driver and starts streaming
*
* The return values from this function are intended to be directly returned
* from vidioc_streamon handler in the driver.
*/
int vb2_streamon(struct vb2_queue *q, enum v4l2_buf_type type)
{
if (vb2_fileio_is_active(q)) {
dprintk(1, "file io in progress\n");
return -EBUSY;
}
return vb2_core_streamon(q, type);
}
EXPORT_SYMBOL_GPL(vb2_streamon);
/**
* vb2_streamoff - stop streaming
* @q: videobuf2 queue
* @type: type argument passed from userspace to vidioc_streamoff handler
*
* Should be called from vidioc_streamoff handler of a driver.
* This function:
* 1) verifies current state,
* 2) stop streaming and dequeues any queued buffers, including those previously
* passed to the driver (after waiting for the driver to finish).
*
* This call can be used for pausing playback.
* The return values from this function are intended to be directly returned
* from vidioc_streamoff handler in the driver
*/
int vb2_streamoff(struct vb2_queue *q, enum v4l2_buf_type type)
{
if (vb2_fileio_is_active(q)) {
dprintk(1, "file io in progress\n");
return -EBUSY;
}
return vb2_core_streamoff(q, type);
}
EXPORT_SYMBOL_GPL(vb2_streamoff);
/**
* vb2_expbuf() - Export a buffer as a file descriptor
* @q: videobuf2 queue
* @eb: export buffer structure passed from userspace to vidioc_expbuf
* handler in driver
*
* The return values from this function are intended to be directly returned
* from vidioc_expbuf handler in driver.
*/
int vb2_expbuf(struct vb2_queue *q, struct v4l2_exportbuffer *eb)
{
return vb2_core_expbuf(q, &eb->fd, eb->type, eb->index,
eb->plane, eb->flags);
}
EXPORT_SYMBOL_GPL(vb2_expbuf);
/**
* vb2_queue_init() - initialize a videobuf2 queue
* @q: videobuf2 queue; this structure should be allocated in driver
*
* The vb2_queue structure should be allocated by the driver. The driver is
* responsible of clearing it's content and setting initial values for some
* required entries before calling this function.
* q->ops, q->mem_ops, q->type and q->io_modes are mandatory. Please refer
* to the struct vb2_queue description in include/media/videobuf2-core.h
* for more information.
*/
int vb2_queue_init(struct vb2_queue *q)
{
/*
* Sanity check
*/
if (WARN_ON(!q) ||
WARN_ON(q->timestamp_flags &
~(V4L2_BUF_FLAG_TIMESTAMP_MASK |
V4L2_BUF_FLAG_TSTAMP_SRC_MASK)))
return -EINVAL;
/* Warn that the driver should choose an appropriate timestamp type */
WARN_ON((q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) ==
V4L2_BUF_FLAG_TIMESTAMP_UNKNOWN);
/* Warn that vb2_memory should match with v4l2_memory */
if (WARN_ON(VB2_MEMORY_MMAP != (int)V4L2_MEMORY_MMAP)
|| WARN_ON(VB2_MEMORY_USERPTR != (int)V4L2_MEMORY_USERPTR)
|| WARN_ON(VB2_MEMORY_DMABUF != (int)V4L2_MEMORY_DMABUF))
return -EINVAL;
if (q->buf_struct_size == 0)
q->buf_struct_size = sizeof(struct vb2_v4l2_buffer);
q->buf_ops = &v4l2_buf_ops;
q->is_multiplanar = V4L2_TYPE_IS_MULTIPLANAR(q->type);
q->is_output = V4L2_TYPE_IS_OUTPUT(q->type);
q->copy_timestamp = (q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK)
== V4L2_BUF_FLAG_TIMESTAMP_COPY;
return vb2_core_queue_init(q);
}
EXPORT_SYMBOL_GPL(vb2_queue_init);
/**
* vb2_queue_release() - stop streaming, release the queue and free memory
* @q: videobuf2 queue
*
* This function stops streaming and performs necessary clean ups, including
* freeing video buffer memory. The driver is responsible for freeing
* the vb2_queue structure itself.
*/
void vb2_queue_release(struct vb2_queue *q)
{
vb2_core_queue_release(q);
}
EXPORT_SYMBOL_GPL(vb2_queue_release);
/**
* vb2_poll() - implements poll userspace operation
* @q: videobuf2 queue
* @file: file argument passed to the poll file operation handler
* @wait: wait argument passed to the poll file operation handler
*
* This function implements poll file operation handler for a driver.
* For CAPTURE queues, if a buffer is ready to be dequeued, the userspace will
* be informed that the file descriptor of a video device is available for
* reading.
* For OUTPUT queues, if a buffer is ready to be dequeued, the file descriptor
* will be reported as available for writing.
*
* If the driver uses struct v4l2_fh, then vb2_poll() will also check for any
* pending events.
*
* The return values from this function are intended to be directly returned
* from poll handler in driver.
*/
unsigned int vb2_poll(struct vb2_queue *q, struct file *file, poll_table *wait)
{
struct video_device *vfd = video_devdata(file);
unsigned long req_events = poll_requested_events(wait);
unsigned int res = 0;
if (test_bit(V4L2_FL_USES_V4L2_FH, &vfd->flags)) {
struct v4l2_fh *fh = file->private_data;
if (v4l2_event_pending(fh))
res = POLLPRI;
else if (req_events & POLLPRI)
poll_wait(file, &fh->wait, wait);
}
/*
* For compatibility with vb1: if QBUF hasn't been called yet, then
* return POLLERR as well. This only affects capture queues, output
* queues will always initialize waiting_for_buffers to false.
*/
if (q->waiting_for_buffers && (req_events & (POLLIN | POLLRDNORM)))
return POLLERR;
return res | vb2_core_poll(q, file, wait);
}
EXPORT_SYMBOL_GPL(vb2_poll);
/*
* The following functions are not part of the vb2 core API, but are helper
* functions that plug into struct v4l2_ioctl_ops, struct v4l2_file_operations
* and struct vb2_ops.
* They contain boilerplate code that most if not all drivers have to do
* and so they simplify the driver code.
*/
/* The queue is busy if there is a owner and you are not that owner. */
static inline bool vb2_queue_is_busy(struct video_device *vdev, struct file *file)
{
return vdev->queue->owner && vdev->queue->owner != file->private_data;
}
/* vb2 ioctl helpers */
int vb2_ioctl_reqbufs(struct file *file, void *priv,
struct v4l2_requestbuffers *p)
{
struct video_device *vdev = video_devdata(file);
int res = vb2_verify_memory_type(vdev->queue, p->memory, p->type);
if (res)
return res;
if (vb2_queue_is_busy(vdev, file))
return -EBUSY;
res = vb2_core_reqbufs(vdev->queue, p->memory, &p->count);
/* If count == 0, then the owner has released all buffers and he
is no longer owner of the queue. Otherwise we have a new owner. */
if (res == 0)
vdev->queue->owner = p->count ? file->private_data : NULL;
return res;
}
EXPORT_SYMBOL_GPL(vb2_ioctl_reqbufs);
int vb2_ioctl_create_bufs(struct file *file, void *priv,
struct v4l2_create_buffers *p)
{
struct video_device *vdev = video_devdata(file);
int res = vb2_verify_memory_type(vdev->queue, p->memory,
p->format.type);
p->index = vdev->queue->num_buffers;
/*
* If count == 0, then just check if memory and type are valid.
* Any -EBUSY result from vb2_verify_memory_type can be mapped to 0.
*/
if (p->count == 0)
return res != -EBUSY ? res : 0;
if (res)
return res;
if (vb2_queue_is_busy(vdev, file))
return -EBUSY;
res = vb2_create_bufs(vdev->queue, p);
if (res == 0)
vdev->queue->owner = file->private_data;
return res;
}
EXPORT_SYMBOL_GPL(vb2_ioctl_create_bufs);
int vb2_ioctl_prepare_buf(struct file *file, void *priv,
struct v4l2_buffer *p)
{
struct video_device *vdev = video_devdata(file);
if (vb2_queue_is_busy(vdev, file))
return -EBUSY;
return vb2_prepare_buf(vdev->queue, p);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_prepare_buf);
int vb2_ioctl_querybuf(struct file *file, void *priv, struct v4l2_buffer *p)
{
struct video_device *vdev = video_devdata(file);
/* No need to call vb2_queue_is_busy(), anyone can query buffers. */
return vb2_querybuf(vdev->queue, p);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_querybuf);
int vb2_ioctl_qbuf(struct file *file, void *priv, struct v4l2_buffer *p)
{
struct video_device *vdev = video_devdata(file);
if (vb2_queue_is_busy(vdev, file))
return -EBUSY;
return vb2_qbuf(vdev->queue, p);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_qbuf);
int vb2_ioctl_dqbuf(struct file *file, void *priv, struct v4l2_buffer *p)
{
struct video_device *vdev = video_devdata(file);
if (vb2_queue_is_busy(vdev, file))
return -EBUSY;
return vb2_dqbuf(vdev->queue, p, file->f_flags & O_NONBLOCK);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_dqbuf);
int vb2_ioctl_streamon(struct file *file, void *priv, enum v4l2_buf_type i)
{
struct video_device *vdev = video_devdata(file);
if (vb2_queue_is_busy(vdev, file))
return -EBUSY;
return vb2_streamon(vdev->queue, i);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_streamon);
int vb2_ioctl_streamoff(struct file *file, void *priv, enum v4l2_buf_type i)
{
struct video_device *vdev = video_devdata(file);
if (vb2_queue_is_busy(vdev, file))
return -EBUSY;
return vb2_streamoff(vdev->queue, i);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_streamoff);
int vb2_ioctl_expbuf(struct file *file, void *priv, struct v4l2_exportbuffer *p)
{
struct video_device *vdev = video_devdata(file);
if (vb2_queue_is_busy(vdev, file))
return -EBUSY;
return vb2_expbuf(vdev->queue, p);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_expbuf);
/* v4l2_file_operations helpers */
int vb2_fop_mmap(struct file *file, struct vm_area_struct *vma)
{
struct video_device *vdev = video_devdata(file);
return vb2_mmap(vdev->queue, vma);
}
EXPORT_SYMBOL_GPL(vb2_fop_mmap);
int _vb2_fop_release(struct file *file, struct mutex *lock)
{
struct video_device *vdev = video_devdata(file);
if (lock)
mutex_lock(lock);
if (file->private_data == vdev->queue->owner) {
vb2_queue_release(vdev->queue);
vdev->queue->owner = NULL;
}
if (lock)
mutex_unlock(lock);
return v4l2_fh_release(file);
}
EXPORT_SYMBOL_GPL(_vb2_fop_release);
int vb2_fop_release(struct file *file)
{
struct video_device *vdev = video_devdata(file);
struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
return _vb2_fop_release(file, lock);
}
EXPORT_SYMBOL_GPL(vb2_fop_release);
ssize_t vb2_fop_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct video_device *vdev = video_devdata(file);
struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
int err = -EBUSY;
if (!(vdev->queue->io_modes & VB2_WRITE))
return -EINVAL;
if (lock && mutex_lock_interruptible(lock))
return -ERESTARTSYS;
if (vb2_queue_is_busy(vdev, file))
goto exit;
err = vb2_write(vdev->queue, buf, count, ppos,
file->f_flags & O_NONBLOCK);
if (vdev->queue->fileio)
vdev->queue->owner = file->private_data;
exit:
if (lock)
mutex_unlock(lock);
return err;
}
EXPORT_SYMBOL_GPL(vb2_fop_write);
ssize_t vb2_fop_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct video_device *vdev = video_devdata(file);
struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
int err = -EBUSY;
if (!(vdev->queue->io_modes & VB2_READ))
return -EINVAL;
if (lock && mutex_lock_interruptible(lock))
return -ERESTARTSYS;
if (vb2_queue_is_busy(vdev, file))
goto exit;
err = vb2_read(vdev->queue, buf, count, ppos,
file->f_flags & O_NONBLOCK);
if (vdev->queue->fileio)
vdev->queue->owner = file->private_data;
exit:
if (lock)
mutex_unlock(lock);
return err;
}
EXPORT_SYMBOL_GPL(vb2_fop_read);
unsigned int vb2_fop_poll(struct file *file, poll_table *wait)
{
struct video_device *vdev = video_devdata(file);
struct vb2_queue *q = vdev->queue;
struct mutex *lock = q->lock ? q->lock : vdev->lock;
unsigned res;
void *fileio;
/*
* If this helper doesn't know how to lock, then you shouldn't be using
* it but you should write your own.
*/
WARN_ON(!lock);
if (lock && mutex_lock_interruptible(lock))
return POLLERR;
fileio = q->fileio;
res = vb2_poll(vdev->queue, file, wait);
/* If fileio was started, then we have a new queue owner. */
if (!fileio && q->fileio)
q->owner = file->private_data;
if (lock)
mutex_unlock(lock);
return res;
}
EXPORT_SYMBOL_GPL(vb2_fop_poll);
#ifndef CONFIG_MMU
unsigned long vb2_fop_get_unmapped_area(struct file *file, unsigned long addr,
unsigned long len, unsigned long pgoff, unsigned long flags)
{
struct video_device *vdev = video_devdata(file);
return vb2_get_unmapped_area(vdev->queue, addr, len, pgoff, flags);
}
EXPORT_SYMBOL_GPL(vb2_fop_get_unmapped_area);
#endif
/* vb2_ops helpers. Only use if vq->lock is non-NULL. */
void vb2_ops_wait_prepare(struct vb2_queue *vq)
{
mutex_unlock(vq->lock);
}
EXPORT_SYMBOL_GPL(vb2_ops_wait_prepare);
void vb2_ops_wait_finish(struct vb2_queue *vq)
{
mutex_lock(vq->lock);
}
EXPORT_SYMBOL_GPL(vb2_ops_wait_finish);
MODULE_DESCRIPTION("Driver helper framework for Video for Linux 2");
MODULE_AUTHOR("Pawel Osciak <pawel@osciak.com>, Marek Szyprowski");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5056_0 |
crossvul-cpp_data_good_255_1 | /**
* @file
* POP network mailbox
*
* @authors
* Copyright (C) 2000-2002 Vsevolod Volkov <vvv@mutt.org.ua>
* Copyright (C) 2006-2007,2009 Rocco Rutte <pdmef@gmx.net>
*
* @copyright
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @page pop POP network mailbox
*
* POP network mailbox
*/
#include "config.h"
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "mutt/mutt.h"
#include "conn/conn.h"
#include "mutt.h"
#include "pop.h"
#include "bcache.h"
#include "body.h"
#include "context.h"
#include "envelope.h"
#include "globals.h"
#include "header.h"
#include "mailbox.h"
#include "mutt_account.h"
#include "mutt_curses.h"
#include "mutt_socket.h"
#include "mx.h"
#include "ncrypt/ncrypt.h"
#include "options.h"
#include "progress.h"
#include "protos.h"
#include "url.h"
#ifdef USE_HCACHE
#include "hcache/hcache.h"
#endif
#ifdef USE_HCACHE
#define HC_FNAME "neomutt" /* filename for hcache as POP lacks paths */
#define HC_FEXT "hcache" /* extension for hcache as POP lacks paths */
#endif
/**
* cache_id - Make a message-cache-compatible id
* @param id POP message id
* @retval ptr Sanitised string
*
* The POP message id may contain '/' and other awkward characters.
*
* @note This function returns a pointer to a static buffer.
*/
static const char *cache_id(const char *id)
{
static char clean[SHORT_STRING];
mutt_str_strfcpy(clean, id, sizeof(clean));
mutt_file_sanitize_filename(clean, true);
return clean;
}
/**
* fetch_message - write line to file
* @param line String to write
* @param file FILE pointer to write to
* @retval 0 Success
* @retval -1 Failure
*/
static int fetch_message(char *line, void *file)
{
FILE *f = (FILE *) file;
fputs(line, f);
if (fputc('\n', f) == EOF)
return -1;
return 0;
}
/**
* pop_read_header - Read header
* @param pop_data POP data
* @param h Email header
* @retval 0 Success
* @retval -1 Connection lost
* @retval -2 Invalid command or execution error
* @retval -3 Error writing to tempfile
*/
static int pop_read_header(struct PopData *pop_data, struct Header *h)
{
int rc, index;
size_t length;
char buf[LONG_STRING];
FILE *f = mutt_file_mkstemp();
if (!f)
{
mutt_perror("mutt_file_mkstemp failed!");
return -3;
}
snprintf(buf, sizeof(buf), "LIST %d\r\n", h->refno);
rc = pop_query(pop_data, buf, sizeof(buf));
if (rc == 0)
{
sscanf(buf, "+OK %d %zu", &index, &length);
snprintf(buf, sizeof(buf), "TOP %d 0\r\n", h->refno);
rc = pop_fetch_data(pop_data, buf, NULL, fetch_message, f);
if (pop_data->cmd_top == 2)
{
if (rc == 0)
{
pop_data->cmd_top = 1;
mutt_debug(1, "set TOP capability\n");
}
if (rc == -2)
{
pop_data->cmd_top = 0;
mutt_debug(1, "unset TOP capability\n");
snprintf(pop_data->err_msg, sizeof(pop_data->err_msg), "%s",
_("Command TOP is not supported by server."));
}
}
}
switch (rc)
{
case 0:
{
rewind(f);
h->env = mutt_rfc822_read_header(f, h, 0, 0);
h->content->length = length - h->content->offset + 1;
rewind(f);
while (!feof(f))
{
h->content->length--;
fgets(buf, sizeof(buf), f);
}
break;
}
case -2:
{
mutt_error("%s", pop_data->err_msg);
break;
}
case -3:
{
mutt_error(_("Can't write header to temporary file!"));
break;
}
}
mutt_file_fclose(&f);
return rc;
}
/**
* fetch_uidl - parse UIDL
* @param line String to parse
* @param data Mailbox Context
* @retval 0 Success
* @retval -1 Failure
*/
static int fetch_uidl(char *line, void *data)
{
int i, index;
struct Context *ctx = (struct Context *) data;
struct PopData *pop_data = (struct PopData *) ctx->data;
char *endp = NULL;
errno = 0;
index = strtol(line, &endp, 10);
if (errno)
return -1;
while (*endp == ' ')
endp++;
memmove(line, endp, strlen(endp) + 1);
for (i = 0; i < ctx->msgcount; i++)
if (mutt_str_strcmp(line, ctx->hdrs[i]->data) == 0)
break;
if (i == ctx->msgcount)
{
mutt_debug(1, "new header %d %s\n", index, line);
if (i >= ctx->hdrmax)
mx_alloc_memory(ctx);
ctx->msgcount++;
ctx->hdrs[i] = mutt_header_new();
ctx->hdrs[i]->data = mutt_str_strdup(line);
}
else if (ctx->hdrs[i]->index != index - 1)
pop_data->clear_cache = true;
ctx->hdrs[i]->refno = index;
ctx->hdrs[i]->index = index - 1;
return 0;
}
/**
* msg_cache_check - Check the Body Cache for an ID
* @param id Cache ID
* @param bcache Body cache
* @param data Mailbox Context
* @retval 0 Success
* @retval -1 Failure
*/
static int msg_cache_check(const char *id, struct BodyCache *bcache, void *data)
{
struct Context *ctx = (struct Context *) data;
if (!ctx)
return -1;
struct PopData *pop_data = (struct PopData *) ctx->data;
if (!pop_data)
return -1;
#ifdef USE_HCACHE
/* keep hcache file if hcache == bcache */
if (strcmp(HC_FNAME "." HC_FEXT, id) == 0)
return 0;
#endif
for (int i = 0; i < ctx->msgcount; i++)
{
/* if the id we get is known for a header: done (i.e. keep in cache) */
if (ctx->hdrs[i]->data && (mutt_str_strcmp(ctx->hdrs[i]->data, id) == 0))
return 0;
}
/* message not found in context -> remove it from cache
* return the result of bcache, so we stop upon its first error
*/
return mutt_bcache_del(bcache, cache_id(id));
}
#ifdef USE_HCACHE
/**
* pop_hcache_namer - Create a header cache filename for a POP mailbox
* @param path Path of mailbox
* @param dest Buffer for filename
* @param destlen Length of buffer
* @retval num Characters written to buffer
*/
static int pop_hcache_namer(const char *path, char *dest, size_t destlen)
{
return snprintf(dest, destlen, "%s." HC_FEXT, path);
}
/**
* pop_hcache_open - Open the header cache
* @param pop_data POP server data
* @param path Path to the mailbox
* @retval ptr Header cache
*/
static header_cache_t *pop_hcache_open(struct PopData *pop_data, const char *path)
{
struct Url url;
char p[LONG_STRING];
if (!pop_data || !pop_data->conn)
return mutt_hcache_open(HeaderCache, path, NULL);
mutt_account_tourl(&pop_data->conn->account, &url);
url.path = HC_FNAME;
url_tostring(&url, p, sizeof(p), U_PATH);
return mutt_hcache_open(HeaderCache, p, pop_hcache_namer);
}
#endif
/**
* pop_fetch_headers - Read headers
* @param ctx Context
* @retval 0 Success
* @retval -1 Connection lost
* @retval -2 Invalid command or execution error
* @retval -3 Error writing to tempfile
*/
static int pop_fetch_headers(struct Context *ctx)
{
struct PopData *pop_data = (struct PopData *) ctx->data;
struct Progress progress;
#ifdef USE_HCACHE
header_cache_t *hc = pop_hcache_open(pop_data, ctx->path);
#endif
time(&pop_data->check_time);
pop_data->clear_cache = false;
for (int i = 0; i < ctx->msgcount; i++)
ctx->hdrs[i]->refno = -1;
const int old_count = ctx->msgcount;
int ret = pop_fetch_data(pop_data, "UIDL\r\n", NULL, fetch_uidl, ctx);
const int new_count = ctx->msgcount;
ctx->msgcount = old_count;
if (pop_data->cmd_uidl == 2)
{
if (ret == 0)
{
pop_data->cmd_uidl = 1;
mutt_debug(1, "set UIDL capability\n");
}
if (ret == -2 && pop_data->cmd_uidl == 2)
{
pop_data->cmd_uidl = 0;
mutt_debug(1, "unset UIDL capability\n");
snprintf(pop_data->err_msg, sizeof(pop_data->err_msg), "%s",
_("Command UIDL is not supported by server."));
}
}
if (!ctx->quiet)
{
mutt_progress_init(&progress, _("Fetching message headers..."),
MUTT_PROGRESS_MSG, ReadInc, new_count - old_count);
}
if (ret == 0)
{
int i, deleted;
for (i = 0, deleted = 0; i < old_count; i++)
{
if (ctx->hdrs[i]->refno == -1)
{
ctx->hdrs[i]->deleted = true;
deleted++;
}
}
if (deleted > 0)
{
mutt_error(
ngettext("%d message has been lost. Try reopening the mailbox.",
"%d messages have been lost. Try reopening the mailbox.", deleted),
deleted);
}
bool hcached = false;
for (i = old_count; i < new_count; i++)
{
if (!ctx->quiet)
mutt_progress_update(&progress, i + 1 - old_count, -1);
#ifdef USE_HCACHE
void *data = mutt_hcache_fetch(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data));
if (data)
{
char *uidl = mutt_str_strdup(ctx->hdrs[i]->data);
int refno = ctx->hdrs[i]->refno;
int index = ctx->hdrs[i]->index;
/*
* - POP dynamically numbers headers and relies on h->refno
* to map messages; so restore header and overwrite restored
* refno with current refno, same for index
* - h->data needs to a separate pointer as it's driver-specific
* data freed separately elsewhere
* (the old h->data should point inside a malloc'd block from
* hcache so there shouldn't be a memleak here)
*/
struct Header *h = mutt_hcache_restore((unsigned char *) data);
mutt_hcache_free(hc, &data);
mutt_header_free(&ctx->hdrs[i]);
ctx->hdrs[i] = h;
ctx->hdrs[i]->refno = refno;
ctx->hdrs[i]->index = index;
ctx->hdrs[i]->data = uidl;
ret = 0;
hcached = true;
}
else
#endif
if ((ret = pop_read_header(pop_data, ctx->hdrs[i])) < 0)
break;
#ifdef USE_HCACHE
else
{
mutt_hcache_store(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data),
ctx->hdrs[i], 0);
}
#endif
/*
* faked support for flags works like this:
* - if 'hcached' is true, we have the message in our hcache:
* - if we also have a body: read
* - if we don't have a body: old
* (if $mark_old is set which is maybe wrong as
* $mark_old should be considered for syncing the
* folder and not when opening it XXX)
* - if 'hcached' is false, we don't have the message in our hcache:
* - if we also have a body: read
* - if we don't have a body: new
*/
const bool bcached =
(mutt_bcache_exists(pop_data->bcache, cache_id(ctx->hdrs[i]->data)) == 0);
ctx->hdrs[i]->old = false;
ctx->hdrs[i]->read = false;
if (hcached)
{
if (bcached)
ctx->hdrs[i]->read = true;
else if (MarkOld)
ctx->hdrs[i]->old = true;
}
else
{
if (bcached)
ctx->hdrs[i]->read = true;
}
ctx->msgcount++;
}
if (i > old_count)
mx_update_context(ctx, i - old_count);
}
#ifdef USE_HCACHE
mutt_hcache_close(hc);
#endif
if (ret < 0)
{
for (int i = ctx->msgcount; i < new_count; i++)
mutt_header_free(&ctx->hdrs[i]);
return ret;
}
/* after putting the result into our structures,
* clean up cache, i.e. wipe messages deleted outside
* the availability of our cache
*/
if (MessageCacheClean)
mutt_bcache_list(pop_data->bcache, msg_cache_check, (void *) ctx);
mutt_clear_error();
return (new_count - old_count);
}
/**
* pop_open_mailbox - open POP mailbox, fetch only headers
* @param ctx Mailbox Context
* @retval 0 Success
* @retval -1 Failure
*/
static int pop_open_mailbox(struct Context *ctx)
{
char buf[PATH_MAX];
struct Connection *conn = NULL;
struct Account acct;
struct PopData *pop_data = NULL;
struct Url url;
if (pop_parse_path(ctx->path, &acct))
{
mutt_error(_("%s is an invalid POP path"), ctx->path);
return -1;
}
mutt_account_tourl(&acct, &url);
url.path = NULL;
url_tostring(&url, buf, sizeof(buf), 0);
conn = mutt_conn_find(NULL, &acct);
if (!conn)
return -1;
FREE(&ctx->path);
FREE(&ctx->realpath);
ctx->path = mutt_str_strdup(buf);
ctx->realpath = mutt_str_strdup(ctx->path);
pop_data = mutt_mem_calloc(1, sizeof(struct PopData));
pop_data->conn = conn;
ctx->data = pop_data;
if (pop_open_connection(pop_data) < 0)
return -1;
conn->data = pop_data;
pop_data->bcache = mutt_bcache_open(&acct, NULL);
/* init (hard-coded) ACL rights */
memset(ctx->rights, 0, sizeof(ctx->rights));
mutt_bit_set(ctx->rights, MUTT_ACL_SEEN);
mutt_bit_set(ctx->rights, MUTT_ACL_DELETE);
#ifdef USE_HCACHE
/* flags are managed using header cache, so it only makes sense to
* enable them in that case */
mutt_bit_set(ctx->rights, MUTT_ACL_WRITE);
#endif
while (true)
{
if (pop_reconnect(ctx) < 0)
return -1;
ctx->size = pop_data->size;
mutt_message(_("Fetching list of messages..."));
const int ret = pop_fetch_headers(ctx);
if (ret >= 0)
return 0;
if (ret < -1)
{
mutt_sleep(2);
return -1;
}
}
}
/**
* pop_clear_cache - delete all cached messages
* @param pop_data POP server data
*/
static void pop_clear_cache(struct PopData *pop_data)
{
if (!pop_data->clear_cache)
return;
mutt_debug(1, "delete cached messages\n");
for (int i = 0; i < POP_CACHE_LEN; i++)
{
if (pop_data->cache[i].path)
{
unlink(pop_data->cache[i].path);
FREE(&pop_data->cache[i].path);
}
}
}
/**
* pop_close_mailbox - close POP mailbox
* @param ctx Mailbox Context
* @retval 0 Always
*/
static int pop_close_mailbox(struct Context *ctx)
{
struct PopData *pop_data = (struct PopData *) ctx->data;
if (!pop_data)
return 0;
pop_logout(ctx);
if (pop_data->status != POP_NONE)
mutt_socket_close(pop_data->conn);
pop_data->status = POP_NONE;
pop_data->clear_cache = true;
pop_clear_cache(pop_data);
if (!pop_data->conn->data)
mutt_socket_free(pop_data->conn);
mutt_bcache_close(&pop_data->bcache);
return 0;
}
/**
* pop_fetch_message - fetch message from POP server
* @param ctx Mailbox Context
* @param msg Message
* @param msgno Message number
* @retval 0 Success
* @retval -1 Failure
*/
static int pop_fetch_message(struct Context *ctx, struct Message *msg, int msgno)
{
void *uidl = NULL;
char buf[LONG_STRING];
char path[PATH_MAX];
struct Progress progressbar;
struct PopData *pop_data = (struct PopData *) ctx->data;
struct PopCache *cache = NULL;
struct Header *h = ctx->hdrs[msgno];
unsigned short bcache = 1;
/* see if we already have the message in body cache */
msg->fp = mutt_bcache_get(pop_data->bcache, cache_id(h->data));
if (msg->fp)
return 0;
/*
* see if we already have the message in our cache in
* case $message_cachedir is unset
*/
cache = &pop_data->cache[h->index % POP_CACHE_LEN];
if (cache->path)
{
if (cache->index == h->index)
{
/* yes, so just return a pointer to the message */
msg->fp = fopen(cache->path, "r");
if (msg->fp)
return 0;
mutt_perror(cache->path);
return -1;
}
else
{
/* clear the previous entry */
unlink(cache->path);
FREE(&cache->path);
}
}
while (true)
{
if (pop_reconnect(ctx) < 0)
return -1;
/* verify that massage index is correct */
if (h->refno < 0)
{
mutt_error(
_("The message index is incorrect. Try reopening the mailbox."));
return -1;
}
mutt_progress_init(&progressbar, _("Fetching message..."), MUTT_PROGRESS_SIZE,
NetInc, h->content->length + h->content->offset - 1);
/* see if we can put in body cache; use our cache as fallback */
msg->fp = mutt_bcache_put(pop_data->bcache, cache_id(h->data));
if (!msg->fp)
{
/* no */
bcache = 0;
mutt_mktemp(path, sizeof(path));
msg->fp = mutt_file_fopen(path, "w+");
if (!msg->fp)
{
mutt_perror(path);
return -1;
}
}
snprintf(buf, sizeof(buf), "RETR %d\r\n", h->refno);
const int ret = pop_fetch_data(pop_data, buf, &progressbar, fetch_message, msg->fp);
if (ret == 0)
break;
mutt_file_fclose(&msg->fp);
/* if RETR failed (e.g. connection closed), be sure to remove either
* the file in bcache or from POP's own cache since the next iteration
* of the loop will re-attempt to put() the message */
if (!bcache)
unlink(path);
if (ret == -2)
{
mutt_error("%s", pop_data->err_msg);
return -1;
}
if (ret == -3)
{
mutt_error(_("Can't write message to temporary file!"));
return -1;
}
}
/* Update the header information. Previously, we only downloaded a
* portion of the headers, those required for the main display.
*/
if (bcache)
mutt_bcache_commit(pop_data->bcache, cache_id(h->data));
else
{
cache->index = h->index;
cache->path = mutt_str_strdup(path);
}
rewind(msg->fp);
uidl = h->data;
/* we replace envelop, key in subj_hash has to be updated as well */
if (ctx->subj_hash && h->env->real_subj)
mutt_hash_delete(ctx->subj_hash, h->env->real_subj, h);
mutt_label_hash_remove(ctx, h);
mutt_env_free(&h->env);
h->env = mutt_rfc822_read_header(msg->fp, h, 0, 0);
if (ctx->subj_hash && h->env->real_subj)
mutt_hash_insert(ctx->subj_hash, h->env->real_subj, h);
mutt_label_hash_add(ctx, h);
h->data = uidl;
h->lines = 0;
fgets(buf, sizeof(buf), msg->fp);
while (!feof(msg->fp))
{
ctx->hdrs[msgno]->lines++;
fgets(buf, sizeof(buf), msg->fp);
}
h->content->length = ftello(msg->fp) - h->content->offset;
/* This needs to be done in case this is a multipart message */
if (!WithCrypto)
h->security = crypt_query(h->content);
mutt_clear_error();
rewind(msg->fp);
return 0;
}
/**
* pop_close_message - Close POP Message
* @param ctx Mailbox Context
* @param msg Message
* @retval 0 Success
* @retval EOF Error, see errno
*/
static int pop_close_message(struct Context *ctx, struct Message *msg)
{
return mutt_file_fclose(&msg->fp);
}
/**
* pop_sync_mailbox - update POP mailbox, delete messages from server
* @param ctx Mailbox Context
* @param index_hint Current Message
* @retval 0 Success
* @retval -1 Failure
*/
static int pop_sync_mailbox(struct Context *ctx, int *index_hint)
{
int i, j, ret = 0;
char buf[LONG_STRING];
struct PopData *pop_data = (struct PopData *) ctx->data;
struct Progress progress;
#ifdef USE_HCACHE
header_cache_t *hc = NULL;
#endif
pop_data->check_time = 0;
while (true)
{
if (pop_reconnect(ctx) < 0)
return -1;
mutt_progress_init(&progress, _("Marking messages deleted..."),
MUTT_PROGRESS_MSG, WriteInc, ctx->deleted);
#ifdef USE_HCACHE
hc = pop_hcache_open(pop_data, ctx->path);
#endif
for (i = 0, j = 0, ret = 0; ret == 0 && i < ctx->msgcount; i++)
{
if (ctx->hdrs[i]->deleted && ctx->hdrs[i]->refno != -1)
{
j++;
if (!ctx->quiet)
mutt_progress_update(&progress, j, -1);
snprintf(buf, sizeof(buf), "DELE %d\r\n", ctx->hdrs[i]->refno);
ret = pop_query(pop_data, buf, sizeof(buf));
if (ret == 0)
{
mutt_bcache_del(pop_data->bcache, cache_id(ctx->hdrs[i]->data));
#ifdef USE_HCACHE
mutt_hcache_delete(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data));
#endif
}
}
#ifdef USE_HCACHE
if (ctx->hdrs[i]->changed)
{
mutt_hcache_store(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data),
ctx->hdrs[i], 0);
}
#endif
}
#ifdef USE_HCACHE
mutt_hcache_close(hc);
#endif
if (ret == 0)
{
mutt_str_strfcpy(buf, "QUIT\r\n", sizeof(buf));
ret = pop_query(pop_data, buf, sizeof(buf));
}
if (ret == 0)
{
pop_data->clear_cache = true;
pop_clear_cache(pop_data);
pop_data->status = POP_DISCONNECTED;
return 0;
}
if (ret == -2)
{
mutt_error("%s", pop_data->err_msg);
return -1;
}
}
}
/**
* pop_check_mailbox - Check for new messages and fetch headers
* @param ctx Mailbox Context
* @param index_hint Current Message
* @retval 0 Success
* @retval -1 Failure
*/
static int pop_check_mailbox(struct Context *ctx, int *index_hint)
{
int ret;
struct PopData *pop_data = (struct PopData *) ctx->data;
if ((pop_data->check_time + PopCheckinterval) > time(NULL))
return 0;
pop_logout(ctx);
mutt_socket_close(pop_data->conn);
if (pop_open_connection(pop_data) < 0)
return -1;
ctx->size = pop_data->size;
mutt_message(_("Checking for new messages..."));
ret = pop_fetch_headers(ctx);
pop_clear_cache(pop_data);
if (ret < 0)
return -1;
if (ret > 0)
return MUTT_NEW_MAIL;
return 0;
}
/**
* pop_fetch_mail - Fetch messages and save them in $spoolfile
*/
void pop_fetch_mail(void)
{
char buffer[LONG_STRING];
char msgbuf[SHORT_STRING];
char *url = NULL, *p = NULL;
int delanswer, last = 0, msgs, bytes, rset = 0, ret;
struct Connection *conn = NULL;
struct Context ctx;
struct Message *msg = NULL;
struct Account acct;
struct PopData *pop_data = NULL;
if (!PopHost)
{
mutt_error(_("POP host is not defined."));
return;
}
url = p = mutt_mem_calloc(strlen(PopHost) + 7, sizeof(char));
if (url_check_scheme(PopHost) == U_UNKNOWN)
{
strcpy(url, "pop://");
p = strchr(url, '\0');
}
strcpy(p, PopHost);
ret = pop_parse_path(url, &acct);
FREE(&url);
if (ret)
{
mutt_error(_("%s is an invalid POP path"), PopHost);
return;
}
conn = mutt_conn_find(NULL, &acct);
if (!conn)
return;
pop_data = mutt_mem_calloc(1, sizeof(struct PopData));
pop_data->conn = conn;
if (pop_open_connection(pop_data) < 0)
{
mutt_socket_free(pop_data->conn);
FREE(&pop_data);
return;
}
conn->data = pop_data;
mutt_message(_("Checking for new messages..."));
/* find out how many messages are in the mailbox. */
mutt_str_strfcpy(buffer, "STAT\r\n", sizeof(buffer));
ret = pop_query(pop_data, buffer, sizeof(buffer));
if (ret == -1)
goto fail;
if (ret == -2)
{
mutt_error("%s", pop_data->err_msg);
goto finish;
}
sscanf(buffer, "+OK %d %d", &msgs, &bytes);
/* only get unread messages */
if (msgs > 0 && PopLast)
{
mutt_str_strfcpy(buffer, "LAST\r\n", sizeof(buffer));
ret = pop_query(pop_data, buffer, sizeof(buffer));
if (ret == -1)
goto fail;
if (ret == 0)
sscanf(buffer, "+OK %d", &last);
}
if (msgs <= last)
{
mutt_message(_("No new mail in POP mailbox."));
goto finish;
}
if (mx_mbox_open(NONULL(Spoolfile), MUTT_APPEND, &ctx) == NULL)
goto finish;
delanswer = query_quadoption(PopDelete, _("Delete messages from server?"));
snprintf(msgbuf, sizeof(msgbuf),
ngettext("Reading new messages (%d byte)...",
"Reading new messages (%d bytes)...", bytes),
bytes);
mutt_message("%s", msgbuf);
for (int i = last + 1; i <= msgs; i++)
{
msg = mx_msg_open_new(&ctx, NULL, MUTT_ADD_FROM);
if (!msg)
ret = -3;
else
{
snprintf(buffer, sizeof(buffer), "RETR %d\r\n", i);
ret = pop_fetch_data(pop_data, buffer, NULL, fetch_message, msg->fp);
if (ret == -3)
rset = 1;
if (ret == 0 && mx_msg_commit(&ctx, msg) != 0)
{
rset = 1;
ret = -3;
}
mx_msg_close(&ctx, &msg);
}
if (ret == 0 && delanswer == MUTT_YES)
{
/* delete the message on the server */
snprintf(buffer, sizeof(buffer), "DELE %d\r\n", i);
ret = pop_query(pop_data, buffer, sizeof(buffer));
}
if (ret == -1)
{
mx_mbox_close(&ctx, NULL);
goto fail;
}
if (ret == -2)
{
mutt_error("%s", pop_data->err_msg);
break;
}
if (ret == -3)
{
mutt_error(_("Error while writing mailbox!"));
break;
}
/* L10N: The plural is picked by the second numerical argument, i.e.
* the %d right before 'messages', i.e. the total number of messages. */
mutt_message(ngettext("%s [%d of %d message read]",
"%s [%d of %d messages read]", msgs - last),
msgbuf, i - last, msgs - last);
}
mx_mbox_close(&ctx, NULL);
if (rset)
{
/* make sure no messages get deleted */
mutt_str_strfcpy(buffer, "RSET\r\n", sizeof(buffer));
if (pop_query(pop_data, buffer, sizeof(buffer)) == -1)
goto fail;
}
finish:
/* exit gracefully */
mutt_str_strfcpy(buffer, "QUIT\r\n", sizeof(buffer));
if (pop_query(pop_data, buffer, sizeof(buffer)) == -1)
goto fail;
mutt_socket_close(conn);
FREE(&pop_data);
return;
fail:
mutt_error(_("Server closed connection!"));
mutt_socket_close(conn);
FREE(&pop_data);
}
// clang-format off
/**
* mx_pop_ops - Mailbox callback functions for POP mailboxes
*/
struct MxOps mx_pop_ops = {
.mbox_open = pop_open_mailbox,
.mbox_open_append = NULL,
.mbox_check = pop_check_mailbox,
.mbox_sync = pop_sync_mailbox,
.mbox_close = pop_close_mailbox,
.msg_open = pop_fetch_message,
.msg_open_new = NULL,
.msg_commit = NULL,
.msg_close = pop_close_message,
.tags_edit = NULL,
.tags_commit = NULL,
};
// clang-format on
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_255_1 |
crossvul-cpp_data_good_4807_0 | /*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common.h"
#include "git2/types.h"
#include "git2/errors.h"
#include "git2/refs.h"
#include "git2/revwalk.h"
#include "smart.h"
#include "util.h"
#include "netops.h"
#include "posix.h"
#include "buffer.h"
#include <ctype.h>
#define PKT_LEN_SIZE 4
static const char pkt_done_str[] = "0009done\n";
static const char pkt_flush_str[] = "0000";
static const char pkt_have_prefix[] = "0032have ";
static const char pkt_want_prefix[] = "0032want ";
static int flush_pkt(git_pkt **out)
{
git_pkt *pkt;
pkt = git__malloc(sizeof(git_pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_FLUSH;
*out = pkt;
return 0;
}
/* the rest of the line will be useful for multi_ack and multi_ack_detailed */
static int ack_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_ack *pkt;
GIT_UNUSED(line);
GIT_UNUSED(len);
pkt = git__calloc(1, sizeof(git_pkt_ack));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_ACK;
line += 3;
len -= 3;
if (len >= GIT_OID_HEXSZ) {
git_oid_fromstr(&pkt->oid, line + 1);
line += GIT_OID_HEXSZ + 1;
len -= GIT_OID_HEXSZ + 1;
}
if (len >= 7) {
if (!git__prefixcmp(line + 1, "continue"))
pkt->status = GIT_ACK_CONTINUE;
if (!git__prefixcmp(line + 1, "common"))
pkt->status = GIT_ACK_COMMON;
if (!git__prefixcmp(line + 1, "ready"))
pkt->status = GIT_ACK_READY;
}
*out = (git_pkt *) pkt;
return 0;
}
static int nak_pkt(git_pkt **out)
{
git_pkt *pkt;
pkt = git__malloc(sizeof(git_pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_NAK;
*out = pkt;
return 0;
}
static int pack_pkt(git_pkt **out)
{
git_pkt *pkt;
pkt = git__malloc(sizeof(git_pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_PACK;
*out = pkt;
return 0;
}
static int comment_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_comment *pkt;
size_t alloclen;
GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_comment), len);
GITERR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1);
pkt = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_COMMENT;
memcpy(pkt->comment, line, len);
pkt->comment[len] = '\0';
*out = (git_pkt *) pkt;
return 0;
}
static int err_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_err *pkt;
size_t alloclen;
/* Remove "ERR " from the line */
line += 4;
len -= 4;
GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_progress), len);
GITERR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1);
pkt = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_ERR;
pkt->len = (int)len;
memcpy(pkt->error, line, len);
pkt->error[len] = '\0';
*out = (git_pkt *) pkt;
return 0;
}
static int data_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_data *pkt;
size_t alloclen;
line++;
len--;
GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_progress), len);
pkt = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_DATA;
pkt->len = (int) len;
memcpy(pkt->data, line, len);
*out = (git_pkt *) pkt;
return 0;
}
static int sideband_progress_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_progress *pkt;
size_t alloclen;
line++;
len--;
GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_progress), len);
pkt = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_PROGRESS;
pkt->len = (int) len;
memcpy(pkt->data, line, len);
*out = (git_pkt *) pkt;
return 0;
}
static int sideband_error_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_err *pkt;
size_t alloc_len;
line++;
len--;
GITERR_CHECK_ALLOC_ADD(&alloc_len, sizeof(git_pkt_err), len);
GITERR_CHECK_ALLOC_ADD(&alloc_len, alloc_len, 1);
pkt = git__malloc(alloc_len);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_ERR;
pkt->len = (int)len;
memcpy(pkt->error, line, len);
pkt->error[len] = '\0';
*out = (git_pkt *)pkt;
return 0;
}
/*
* Parse an other-ref line.
*/
static int ref_pkt(git_pkt **out, const char *line, size_t len)
{
int error;
git_pkt_ref *pkt;
size_t alloclen;
pkt = git__malloc(sizeof(git_pkt_ref));
GITERR_CHECK_ALLOC(pkt);
memset(pkt, 0x0, sizeof(git_pkt_ref));
pkt->type = GIT_PKT_REF;
if ((error = git_oid_fromstr(&pkt->head.oid, line)) < 0)
goto error_out;
/* Check for a bit of consistency */
if (line[GIT_OID_HEXSZ] != ' ') {
giterr_set(GITERR_NET, "Error parsing pkt-line");
error = -1;
goto error_out;
}
/* Jump from the name */
line += GIT_OID_HEXSZ + 1;
len -= (GIT_OID_HEXSZ + 1);
if (line[len - 1] == '\n')
--len;
GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);
pkt->head.name = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt->head.name);
memcpy(pkt->head.name, line, len);
pkt->head.name[len] = '\0';
if (strlen(pkt->head.name) < len) {
pkt->capabilities = strchr(pkt->head.name, '\0') + 1;
}
*out = (git_pkt *)pkt;
return 0;
error_out:
git__free(pkt);
return error;
}
static int ok_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_ok *pkt;
const char *ptr;
size_t alloc_len;
pkt = git__malloc(sizeof(*pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_OK;
line += 3; /* skip "ok " */
if (!(ptr = strchr(line, '\n'))) {
giterr_set(GITERR_NET, "Invalid packet line");
git__free(pkt);
return -1;
}
len = ptr - line;
GITERR_CHECK_ALLOC_ADD(&alloc_len, len, 1);
pkt->ref = git__malloc(alloc_len);
GITERR_CHECK_ALLOC(pkt->ref);
memcpy(pkt->ref, line, len);
pkt->ref[len] = '\0';
*out = (git_pkt *)pkt;
return 0;
}
static int ng_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_ng *pkt;
const char *ptr;
size_t alloclen;
pkt = git__malloc(sizeof(*pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->ref = NULL;
pkt->type = GIT_PKT_NG;
line += 3; /* skip "ng " */
if (!(ptr = strchr(line, ' ')))
goto out_err;
len = ptr - line;
GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);
pkt->ref = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt->ref);
memcpy(pkt->ref, line, len);
pkt->ref[len] = '\0';
line = ptr + 1;
if (!(ptr = strchr(line, '\n')))
goto out_err;
len = ptr - line;
GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);
pkt->msg = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt->msg);
memcpy(pkt->msg, line, len);
pkt->msg[len] = '\0';
*out = (git_pkt *)pkt;
return 0;
out_err:
giterr_set(GITERR_NET, "Invalid packet line");
git__free(pkt->ref);
git__free(pkt);
return -1;
}
static int unpack_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_unpack *pkt;
GIT_UNUSED(len);
pkt = git__malloc(sizeof(*pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_UNPACK;
if (!git__prefixcmp(line, "unpack ok"))
pkt->unpack_ok = 1;
else
pkt->unpack_ok = 0;
*out = (git_pkt *)pkt;
return 0;
}
static int32_t parse_len(const char *line)
{
char num[PKT_LEN_SIZE + 1];
int i, k, error;
int32_t len;
const char *num_end;
memcpy(num, line, PKT_LEN_SIZE);
num[PKT_LEN_SIZE] = '\0';
for (i = 0; i < PKT_LEN_SIZE; ++i) {
if (!isxdigit(num[i])) {
/* Make sure there are no special characters before passing to error message */
for (k = 0; k < PKT_LEN_SIZE; ++k) {
if(!isprint(num[k])) {
num[k] = '.';
}
}
giterr_set(GITERR_NET, "invalid hex digit in length: '%s'", num);
return -1;
}
}
if ((error = git__strtol32(&len, num, &num_end, 16)) < 0)
return error;
return len;
}
/*
* As per the documentation, the syntax is:
*
* pkt-line = data-pkt / flush-pkt
* data-pkt = pkt-len pkt-payload
* pkt-len = 4*(HEXDIG)
* pkt-payload = (pkt-len -4)*(OCTET)
* flush-pkt = "0000"
*
* Which means that the first four bytes are the length of the line,
* in ASCII hexadecimal (including itself)
*/
int git_pkt_parse_line(
git_pkt **head, const char *line, const char **out, size_t bufflen)
{
int ret;
int32_t len;
/* Not even enough for the length */
if (bufflen > 0 && bufflen < PKT_LEN_SIZE)
return GIT_EBUFS;
len = parse_len(line);
if (len < 0) {
/*
* If we fail to parse the length, it might be because the
* server is trying to send us the packfile already.
*/
if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) {
giterr_clear();
*out = line;
return pack_pkt(head);
}
return (int)len;
}
/*
* If we were given a buffer length, then make sure there is
* enough in the buffer to satisfy this line
*/
if (bufflen > 0 && bufflen < (size_t)len)
return GIT_EBUFS;
/*
* The length has to be exactly 0 in case of a flush
* packet or greater than PKT_LEN_SIZE, as the decoded
* length includes its own encoded length of four bytes.
*/
if (len != 0 && len < PKT_LEN_SIZE)
return GIT_ERROR;
line += PKT_LEN_SIZE;
/*
* TODO: How do we deal with empty lines? Try again? with the next
* line?
*/
if (len == PKT_LEN_SIZE) {
*head = NULL;
*out = line;
return 0;
}
if (len == 0) { /* Flush pkt */
*out = line;
return flush_pkt(head);
}
len -= PKT_LEN_SIZE; /* the encoded length includes its own size */
if (*line == GIT_SIDE_BAND_DATA)
ret = data_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_PROGRESS)
ret = sideband_progress_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_ERROR)
ret = sideband_error_pkt(head, line, len);
else if (!git__prefixcmp(line, "ACK"))
ret = ack_pkt(head, line, len);
else if (!git__prefixcmp(line, "NAK"))
ret = nak_pkt(head);
else if (!git__prefixcmp(line, "ERR "))
ret = err_pkt(head, line, len);
else if (*line == '#')
ret = comment_pkt(head, line, len);
else if (!git__prefixcmp(line, "ok"))
ret = ok_pkt(head, line, len);
else if (!git__prefixcmp(line, "ng"))
ret = ng_pkt(head, line, len);
else if (!git__prefixcmp(line, "unpack"))
ret = unpack_pkt(head, line, len);
else
ret = ref_pkt(head, line, len);
*out = line + len;
return ret;
}
void git_pkt_free(git_pkt *pkt)
{
if (pkt->type == GIT_PKT_REF) {
git_pkt_ref *p = (git_pkt_ref *) pkt;
git__free(p->head.name);
git__free(p->head.symref_target);
}
if (pkt->type == GIT_PKT_OK) {
git_pkt_ok *p = (git_pkt_ok *) pkt;
git__free(p->ref);
}
if (pkt->type == GIT_PKT_NG) {
git_pkt_ng *p = (git_pkt_ng *) pkt;
git__free(p->ref);
git__free(p->msg);
}
git__free(pkt);
}
int git_pkt_buffer_flush(git_buf *buf)
{
return git_buf_put(buf, pkt_flush_str, strlen(pkt_flush_str));
}
static int buffer_want_with_caps(const git_remote_head *head, transport_smart_caps *caps, git_buf *buf)
{
git_buf str = GIT_BUF_INIT;
char oid[GIT_OID_HEXSZ +1] = {0};
size_t len;
/* Prefer multi_ack_detailed */
if (caps->multi_ack_detailed)
git_buf_puts(&str, GIT_CAP_MULTI_ACK_DETAILED " ");
else if (caps->multi_ack)
git_buf_puts(&str, GIT_CAP_MULTI_ACK " ");
/* Prefer side-band-64k if the server supports both */
if (caps->side_band_64k)
git_buf_printf(&str, "%s ", GIT_CAP_SIDE_BAND_64K);
else if (caps->side_band)
git_buf_printf(&str, "%s ", GIT_CAP_SIDE_BAND);
if (caps->include_tag)
git_buf_puts(&str, GIT_CAP_INCLUDE_TAG " ");
if (caps->thin_pack)
git_buf_puts(&str, GIT_CAP_THIN_PACK " ");
if (caps->ofs_delta)
git_buf_puts(&str, GIT_CAP_OFS_DELTA " ");
if (git_buf_oom(&str))
return -1;
len = strlen("XXXXwant ") + GIT_OID_HEXSZ + 1 /* NUL */ +
git_buf_len(&str) + 1 /* LF */;
if (len > 0xffff) {
giterr_set(GITERR_NET,
"Tried to produce packet with invalid length %" PRIuZ, len);
return -1;
}
git_buf_grow_by(buf, len);
git_oid_fmt(oid, &head->oid);
git_buf_printf(buf,
"%04xwant %s %s\n", (unsigned int)len, oid, git_buf_cstr(&str));
git_buf_free(&str);
GITERR_CHECK_ALLOC_BUF(buf);
return 0;
}
/*
* All "want" packets have the same length and format, so what we do
* is overwrite the OID each time.
*/
int git_pkt_buffer_wants(
const git_remote_head * const *refs,
size_t count,
transport_smart_caps *caps,
git_buf *buf)
{
size_t i = 0;
const git_remote_head *head;
if (caps->common) {
for (; i < count; ++i) {
head = refs[i];
if (!head->local)
break;
}
if (buffer_want_with_caps(refs[i], caps, buf) < 0)
return -1;
i++;
}
for (; i < count; ++i) {
char oid[GIT_OID_HEXSZ];
head = refs[i];
if (head->local)
continue;
git_oid_fmt(oid, &head->oid);
git_buf_put(buf, pkt_want_prefix, strlen(pkt_want_prefix));
git_buf_put(buf, oid, GIT_OID_HEXSZ);
git_buf_putc(buf, '\n');
if (git_buf_oom(buf))
return -1;
}
return git_pkt_buffer_flush(buf);
}
int git_pkt_buffer_have(git_oid *oid, git_buf *buf)
{
char oidhex[GIT_OID_HEXSZ + 1];
memset(oidhex, 0x0, sizeof(oidhex));
git_oid_fmt(oidhex, oid);
return git_buf_printf(buf, "%s%s\n", pkt_have_prefix, oidhex);
}
int git_pkt_buffer_done(git_buf *buf)
{
return git_buf_puts(buf, pkt_done_str);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4807_0 |
crossvul-cpp_data_bad_341_2 | /*
* card-muscle.c: Support for MuscleCard Applet from musclecard.com
*
* Copyright (C) 2006, Identity Alliance, Thomas Harning <support@identityalliance.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include "internal.h"
#include "cardctl.h"
#include "muscle.h"
#include "muscle-filesystem.h"
#include "types.h"
#include "opensc.h"
static struct sc_card_operations muscle_ops;
static const struct sc_card_operations *iso_ops = NULL;
static struct sc_card_driver muscle_drv = {
"MuscleApplet",
"muscle",
&muscle_ops,
NULL, 0, NULL
};
static struct sc_atr_table muscle_atrs[] = {
/* Tyfone JCOP 242R2 cards */
{ "3b:6d:00:00:ff:54:79:66:6f:6e:65:20:32:34:32:52:32", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU, 0, NULL },
/* Aladdin eToken PRO USB 72K Java */
{ "3b:d5:18:00:81:31:3a:7d:80:73:c8:21:10:30", NULL, NULL, SC_CARD_TYPE_MUSCLE_ETOKEN_72K, 0, NULL },
/* JCOP31 v2.4.1 contact interface */
{ "3b:f8:13:00:00:81:31:fe:45:4a:43:4f:50:76:32:34:31:b7", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL },
/* JCOP31 v2.4.1 RF interface */
{ "3b:88:80:01:4a:43:4f:50:76:32:34:31:5e", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
#define MUSCLE_DATA(card) ( (muscle_private_t*)card->drv_data )
#define MUSCLE_FS(card) ( ((muscle_private_t*)card->drv_data)->fs )
typedef struct muscle_private {
sc_security_env_t env;
unsigned short verifiedPins;
mscfs_t *fs;
int rsa_key_ref;
} muscle_private_t;
static int muscle_finish(sc_card_t *card)
{
muscle_private_t *priv = MUSCLE_DATA(card);
mscfs_free(priv->fs);
free(priv);
return 0;
}
static u8 muscleAppletId[] = { 0xA0, 0x00,0x00,0x00, 0x01, 0x01 };
static int muscle_match_card(sc_card_t *card)
{
sc_apdu_t apdu;
u8 response[64];
int r;
/* Since we send an APDU, the card's logout function may be called...
* however it's not always properly nulled out... */
card->ops->logout = NULL;
if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) == 1) {
/* Muscle applet is present, check the protocol version to be sure */
sc_format_apdu(card, &apdu, SC_APDU_CASE_2, 0x3C, 0x00, 0x00);
apdu.cla = 0xB0;
apdu.le = 64;
apdu.resplen = 64;
apdu.resp = response;
r = sc_transmit_apdu(card, &apdu);
if (r == SC_SUCCESS && response[0] == 0x01) {
card->type = SC_CARD_TYPE_MUSCLE_V1;
} else {
card->type = SC_CARD_TYPE_MUSCLE_GENERIC;
}
return 1;
}
return 0;
}
/* Since Musclecard has a different ACL system then PKCS15
* objects need to have their READ/UPDATE/DELETE permissions mapped for files
* and directory ACLS need to be set
* For keys.. they have different ACLS, but are accessed in different locations, so it shouldn't be an issue here
*/
static unsigned short muscle_parse_singleAcl(const sc_acl_entry_t* acl)
{
unsigned short acl_entry = 0;
while(acl) {
int key = acl->key_ref;
int method = acl->method;
switch(method) {
case SC_AC_NEVER:
return 0xFFFF;
/* Ignore... other items overwrite these */
case SC_AC_NONE:
case SC_AC_UNKNOWN:
break;
case SC_AC_CHV:
acl_entry |= (1 << key); /* Assuming key 0 == SO */
break;
case SC_AC_AUT:
case SC_AC_TERM:
case SC_AC_PRO:
default:
/* Ignored */
break;
}
acl = acl->next;
}
return acl_entry;
}
static void muscle_parse_acls(const sc_file_t* file, unsigned short* read_perm, unsigned short* write_perm, unsigned short* delete_perm)
{
assert(read_perm && write_perm && delete_perm);
*read_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_READ));
*write_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_UPDATE));
*delete_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_DELETE));
}
static int muscle_create_directory(sc_card_t *card, sc_file_t *file)
{
mscfs_t *fs = MUSCLE_FS(card);
msc_id objectId;
u8* oid = objectId.id;
unsigned id = file->id;
unsigned short read_perm = 0, write_perm = 0, delete_perm = 0;
int objectSize;
int r;
if(id == 0) /* No null name files */
return SC_ERROR_INVALID_ARGUMENTS;
/* No nesting directories */
if(fs->currentPath[0] != 0x3F || fs->currentPath[1] != 0x00)
return SC_ERROR_NOT_SUPPORTED;
oid[0] = ((id & 0xFF00) >> 8) & 0xFF;
oid[1] = id & 0xFF;
oid[2] = oid[3] = 0;
objectSize = file->size;
muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm);
r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm);
mscfs_clear_cache(fs);
if(r >= 0) return 0;
return r;
}
static int muscle_create_file(sc_card_t *card, sc_file_t *file)
{
mscfs_t *fs = MUSCLE_FS(card);
int objectSize = file->size;
unsigned short read_perm = 0, write_perm = 0, delete_perm = 0;
msc_id objectId;
int r;
if(file->type == SC_FILE_TYPE_DF)
return muscle_create_directory(card, file);
if(file->type != SC_FILE_TYPE_WORKING_EF)
return SC_ERROR_NOT_SUPPORTED;
if(file->id == 0) /* No null name files */
return SC_ERROR_INVALID_ARGUMENTS;
muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm);
mscfs_lookup_local(fs, file->id, &objectId);
r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm);
mscfs_clear_cache(fs);
if(r >= 0) return 0;
return r;
}
static int muscle_read_binary(sc_card_t *card, unsigned int idx, u8* buf, size_t count, unsigned long flags)
{
mscfs_t *fs = MUSCLE_FS(card);
int r;
msc_id objectId;
u8* oid = objectId.id;
mscfs_file_t *file;
r = mscfs_check_selection(fs, -1);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
file = &fs->cache.array[fs->currentFileIndex];
objectId = file->objectId;
/* memcpy(objectId.id, file->objectId.id, 4); */
if(!file->ef) {
oid[0] = oid[2];
oid[1] = oid[3];
oid[2] = oid[3] = 0;
}
r = msc_read_object(card, objectId, idx, buf, count);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
static int muscle_update_binary(sc_card_t *card, unsigned int idx, const u8* buf, size_t count, unsigned long flags)
{
mscfs_t *fs = MUSCLE_FS(card);
int r;
mscfs_file_t *file;
msc_id objectId;
u8* oid = objectId.id;
r = mscfs_check_selection(fs, -1);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
file = &fs->cache.array[fs->currentFileIndex];
objectId = file->objectId;
/* memcpy(objectId.id, file->objectId.id, 4); */
if(!file->ef) {
oid[0] = oid[2];
oid[1] = oid[3];
oid[2] = oid[3] = 0;
}
if(file->size < idx + count) {
int newFileSize = idx + count;
u8* buffer = malloc(newFileSize);
if(buffer == NULL) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
r = msc_read_object(card, objectId, 0, buffer, file->size);
/* TODO: RETRIEVE ACLS */
if(r < 0) goto update_bin_free_buffer;
r = msc_delete_object(card, objectId, 0);
if(r < 0) goto update_bin_free_buffer;
r = msc_create_object(card, objectId, newFileSize, 0,0,0);
if(r < 0) goto update_bin_free_buffer;
memcpy(buffer + idx, buf, count);
r = msc_update_object(card, objectId, 0, buffer, newFileSize);
if(r < 0) goto update_bin_free_buffer;
file->size = newFileSize;
update_bin_free_buffer:
free(buffer);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
} else {
r = msc_update_object(card, objectId, idx, buf, count);
}
/* mscfs_clear_cache(fs); */
return r;
}
/* TODO: Evaluate correctness */
static int muscle_delete_mscfs_file(sc_card_t *card, mscfs_file_t *file_data)
{
mscfs_t *fs = MUSCLE_FS(card);
msc_id id = file_data->objectId;
u8* oid = id.id;
int r;
if(!file_data->ef) {
int x;
mscfs_file_t *childFile;
/* Delete children */
mscfs_check_cache(fs);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"DELETING Children of: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
for(x = 0; x < fs->cache.size; x++) {
msc_id objectId;
childFile = &fs->cache.array[x];
objectId = childFile->objectId;
if(0 == memcmp(oid + 2, objectId.id, 2)) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"DELETING: %02X%02X%02X%02X\n",
objectId.id[0],objectId.id[1],
objectId.id[2],objectId.id[3]);
r = muscle_delete_mscfs_file(card, childFile);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
}
}
oid[0] = oid[2];
oid[1] = oid[3];
oid[2] = oid[3] = 0;
/* ??? objectId = objectId >> 16; */
}
if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4))
|| (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) {
}
r = msc_delete_object(card, id, 1);
/* Check if its the root... this file generally is virtual
* So don't return an error if it fails */
if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4))
|| (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4)))
return 0;
if(r < 0) {
printf("ID: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
}
return 0;
}
static int muscle_delete_file(sc_card_t *card, const sc_path_t *path_in)
{
mscfs_t *fs = MUSCLE_FS(card);
mscfs_file_t *file_data = NULL;
int r = 0;
r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, NULL);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
r = muscle_delete_mscfs_file(card, file_data);
mscfs_clear_cache(fs);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
return 0;
}
static void muscle_load_single_acl(sc_file_t* file, int operation, unsigned short acl)
{
int key;
/* Everybody by default.... */
sc_file_add_acl_entry(file, operation, SC_AC_NONE, 0);
if(acl == 0xFFFF) {
sc_file_add_acl_entry(file, operation, SC_AC_NEVER, 0);
return;
}
for(key = 0; key < 16; key++) {
if(acl >> key & 1) {
sc_file_add_acl_entry(file, operation, SC_AC_CHV, key);
}
}
}
static void muscle_load_file_acls(sc_file_t* file, mscfs_file_t *file_data)
{
muscle_load_single_acl(file, SC_AC_OP_READ, file_data->read);
muscle_load_single_acl(file, SC_AC_OP_WRITE, file_data->write);
muscle_load_single_acl(file, SC_AC_OP_UPDATE, file_data->write);
muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete);
}
static void muscle_load_dir_acls(sc_file_t* file, mscfs_file_t *file_data)
{
muscle_load_single_acl(file, SC_AC_OP_SELECT, 0);
muscle_load_single_acl(file, SC_AC_OP_LIST_FILES, 0);
muscle_load_single_acl(file, SC_AC_OP_LOCK, 0xFFFF);
muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete);
muscle_load_single_acl(file, SC_AC_OP_CREATE, file_data->write);
}
/* Required type = -1 for don't care, 1 for EF, 0 for DF */
static int select_item(sc_card_t *card, const sc_path_t *path_in, sc_file_t ** file_out, int requiredType)
{
mscfs_t *fs = MUSCLE_FS(card);
mscfs_file_t *file_data = NULL;
int pathlen = path_in->len;
int r = 0;
int objectIndex;
u8* oid;
mscfs_check_cache(fs);
r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, &objectIndex);
if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
/* Check if its the right type */
if(requiredType >= 0 && requiredType != file_data->ef) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
}
oid = file_data->objectId.id;
/* Is it a file or directory */
if(file_data->ef) {
fs->currentPath[0] = oid[0];
fs->currentPath[1] = oid[1];
fs->currentFile[0] = oid[2];
fs->currentFile[1] = oid[3];
} else {
fs->currentPath[0] = oid[pathlen - 2];
fs->currentPath[1] = oid[pathlen - 1];
fs->currentFile[0] = 0;
fs->currentFile[1] = 0;
}
fs->currentFileIndex = objectIndex;
if(file_out) {
sc_file_t *file;
file = sc_file_new();
file->path = *path_in;
file->size = file_data->size;
file->id = (oid[2] << 8) | oid[3];
if(!file_data->ef) {
file->type = SC_FILE_TYPE_DF;
} else {
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_TRANSPARENT;
}
/* Setup ACLS */
if(file_data->ef) {
muscle_load_file_acls(file, file_data);
} else {
muscle_load_dir_acls(file, file_data);
/* Setup directory acls... */
}
file->magic = SC_FILE_MAGIC;
*file_out = file;
}
return 0;
}
static int muscle_select_file(sc_card_t *card, const sc_path_t *path_in,
sc_file_t **file_out)
{
int r;
assert(card != NULL && path_in != NULL);
switch (path_in->type) {
case SC_PATH_TYPE_FILE_ID:
r = select_item(card, path_in, file_out, 1);
break;
case SC_PATH_TYPE_DF_NAME:
r = select_item(card, path_in, file_out, 0);
break;
case SC_PATH_TYPE_PATH:
r = select_item(card, path_in, file_out, -1);
break;
default:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
if(r > 0) r = 0;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
}
static int _listFile(mscfs_file_t *file, int reset, void *udata)
{
int next = reset ? 0x00 : 0x01;
return msc_list_objects( (sc_card_t*)udata, next, file);
}
static int muscle_init(sc_card_t *card)
{
muscle_private_t *priv;
card->name = "MuscleApplet";
card->drv_data = malloc(sizeof(muscle_private_t));
if(!card->drv_data) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
}
memset(card->drv_data, 0, sizeof(muscle_private_t));
priv = MUSCLE_DATA(card);
priv->verifiedPins = 0;
priv->fs = mscfs_new();
if(!priv->fs) {
free(card->drv_data);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
}
priv->fs->udata = card;
priv->fs->listFile = _listFile;
card->cla = 0xB0;
card->flags |= SC_CARD_FLAG_RNG;
card->caps |= SC_CARD_CAP_RNG;
/* Card type detection */
_sc_match_atr(card, muscle_atrs, &card->type);
if(card->type == SC_CARD_TYPE_MUSCLE_ETOKEN_72K) {
card->caps |= SC_CARD_CAP_APDU_EXT;
}
if(card->type == SC_CARD_TYPE_MUSCLE_JCOP241) {
card->caps |= SC_CARD_CAP_APDU_EXT;
}
if (!(card->caps & SC_CARD_CAP_APDU_EXT)) {
card->max_recv_size = 255;
card->max_send_size = 255;
}
if(card->type == SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU) {
/* Tyfone JCOP v242R2 card that doesn't support extended APDUs */
}
/* FIXME: Card type detection */
if (1) {
unsigned long flags;
flags = SC_ALGORITHM_RSA_RAW;
flags |= SC_ALGORITHM_RSA_HASH_NONE;
flags |= SC_ALGORITHM_ONBOARD_KEY_GEN;
_sc_card_add_rsa_alg(card, 1024, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
}
return SC_SUCCESS;
}
static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)
{
muscle_private_t* priv = MUSCLE_DATA(card);
mscfs_t *fs = priv->fs;
int x;
int count = 0;
mscfs_check_cache(priv->fs);
for(x = 0; x < fs->cache.size; x++) {
u8* oid= fs->cache.array[x].objectId.id;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"FILE: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
if(0 == memcmp(fs->currentPath, oid, 2)) {
buf[0] = oid[2];
buf[1] = oid[3];
if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */
buf += 2;
count+=2;
}
}
return count;
}
static int muscle_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *cmd,
int *tries_left)
{
muscle_private_t* priv = MUSCLE_DATA(card);
const int bufferLength = MSC_MAX_PIN_COMMAND_LENGTH;
u8 buffer[MSC_MAX_PIN_COMMAND_LENGTH];
switch(cmd->cmd) {
case SC_PIN_CMD_VERIFY:
switch(cmd->pin_type) {
case SC_AC_CHV: {
sc_apdu_t apdu;
int r;
msc_verify_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len);
cmd->apdu = &apdu;
cmd->pin1.offset = 5;
r = iso_ops->pin_cmd(card, cmd, tries_left);
if(r >= 0)
priv->verifiedPins |= (1 << cmd->pin_reference);
return r;
}
case SC_AC_TERM:
case SC_AC_PRO:
case SC_AC_AUT:
case SC_AC_NONE:
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n");
return SC_ERROR_NOT_SUPPORTED;
}
case SC_PIN_CMD_CHANGE:
switch(cmd->pin_type) {
case SC_AC_CHV: {
sc_apdu_t apdu;
msc_change_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len, cmd->pin2.data, cmd->pin2.len);
cmd->apdu = &apdu;
return iso_ops->pin_cmd(card, cmd, tries_left);
}
case SC_AC_TERM:
case SC_AC_PRO:
case SC_AC_AUT:
case SC_AC_NONE:
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n");
return SC_ERROR_NOT_SUPPORTED;
}
case SC_PIN_CMD_UNBLOCK:
switch(cmd->pin_type) {
case SC_AC_CHV: {
sc_apdu_t apdu;
msc_unblock_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len);
cmd->apdu = &apdu;
return iso_ops->pin_cmd(card, cmd, tries_left);
}
case SC_AC_TERM:
case SC_AC_PRO:
case SC_AC_AUT:
case SC_AC_NONE:
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n");
return SC_ERROR_NOT_SUPPORTED;
}
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported command\n");
return SC_ERROR_NOT_SUPPORTED;
}
}
static int muscle_card_extract_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info)
{
/* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */
switch(info->keyType) {
case 1: /* RSA */
return msc_extract_rsa_public_key(card,
info->keyLocation,
&info->modLength,
&info->modValue,
&info->expLength,
&info->expValue);
default:
return SC_ERROR_NOT_SUPPORTED;
}
}
static int muscle_card_import_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info)
{
/* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */
switch(info->keyType) {
case 0x02: /* RSA_PRIVATE */
case 0x03: /* RSA_PRIVATE_CRT */
return msc_import_key(card,
info->keyLocation,
info);
default:
return SC_ERROR_NOT_SUPPORTED;
}
}
static int muscle_card_generate_key(sc_card_t *card, sc_cardctl_muscle_gen_key_info_t *info)
{
return msc_generate_keypair(card,
info->privateKeyLocation,
info->publicKeyLocation,
info->keyType,
info->keySize,
0);
}
static int muscle_card_verified_pins(sc_card_t *card, sc_cardctl_muscle_verified_pins_info_t *info)
{
muscle_private_t* priv = MUSCLE_DATA(card);
info->verifiedPins = priv->verifiedPins;
return 0;
}
static int muscle_card_ctl(sc_card_t *card, unsigned long request, void *data)
{
switch(request) {
case SC_CARDCTL_MUSCLE_GENERATE_KEY:
return muscle_card_generate_key(card, (sc_cardctl_muscle_gen_key_info_t*) data);
case SC_CARDCTL_MUSCLE_EXTRACT_KEY:
return muscle_card_extract_key(card, (sc_cardctl_muscle_key_info_t*) data);
case SC_CARDCTL_MUSCLE_IMPORT_KEY:
return muscle_card_import_key(card, (sc_cardctl_muscle_key_info_t*) data);
case SC_CARDCTL_MUSCLE_VERIFIED_PINS:
return muscle_card_verified_pins(card, (sc_cardctl_muscle_verified_pins_info_t*) data);
default:
return SC_ERROR_NOT_SUPPORTED; /* Unsupported.. whatever it is */
}
}
static int muscle_set_security_env(sc_card_t *card,
const sc_security_env_t *env,
int se_num)
{
muscle_private_t* priv = MUSCLE_DATA(card);
if (env->operation != SC_SEC_OPERATION_SIGN &&
env->operation != SC_SEC_OPERATION_DECIPHER) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto operation supplied.\n");
return SC_ERROR_NOT_SUPPORTED;
}
if (env->algorithm != SC_ALGORITHM_RSA) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto algorithm supplied.\n");
return SC_ERROR_NOT_SUPPORTED;
}
/* ADJUST FOR PKCS1 padding support for decryption only */
if ((env->algorithm_flags & SC_ALGORITHM_RSA_PADS) ||
(env->algorithm_flags & SC_ALGORITHM_RSA_HASHES)) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card supports only raw RSA.\n");
return SC_ERROR_NOT_SUPPORTED;
}
if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) {
if (env->key_ref_len != 1 ||
(env->key_ref[0] > 0x0F)) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid key reference supplied.\n");
return SC_ERROR_NOT_SUPPORTED;
}
priv->rsa_key_ref = env->key_ref[0];
}
if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Algorithm reference not supported.\n");
return SC_ERROR_NOT_SUPPORTED;
}
/* if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT)
if (memcmp(env->file_ref.value, "\x00\x12", 2) != 0) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File reference is not 0012.\n");
return SC_ERROR_NOT_SUPPORTED;
} */
priv->env = *env;
return 0;
}
static int muscle_restore_security_env(sc_card_t *card, int se_num)
{
muscle_private_t* priv = MUSCLE_DATA(card);
memset(&priv->env, 0, sizeof(priv->env));
return 0;
}
static int muscle_decipher(sc_card_t * card,
const u8 * crgram, size_t crgram_len, u8 * out,
size_t out_len)
{
muscle_private_t* priv = MUSCLE_DATA(card);
u8 key_id;
int r;
/* sanity check */
if (priv->env.operation != SC_SEC_OPERATION_DECIPHER)
return SC_ERROR_INVALID_ARGUMENTS;
key_id = priv->rsa_key_ref * 2; /* Private key */
if (out_len < crgram_len) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small");
return SC_ERROR_BUFFER_TOO_SMALL;
}
r = msc_compute_crypt(card,
key_id,
0x00, /* RSA NO PADDING */
0x04, /* decrypt */
crgram,
out,
crgram_len,
out_len);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed");
return r;
}
static int muscle_compute_signature(sc_card_t *card, const u8 *data,
size_t data_len, u8 * out, size_t outlen)
{
muscle_private_t* priv = MUSCLE_DATA(card);
u8 key_id;
int r;
key_id = priv->rsa_key_ref * 2; /* Private key */
if (outlen < data_len) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small");
return SC_ERROR_BUFFER_TOO_SMALL;
}
r = msc_compute_crypt(card,
key_id,
0x00, /* RSA NO PADDING */
0x04, /* -- decrypt raw... will do what we need since signing isn't yet supported */
data,
out,
data_len,
outlen);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed");
return r;
}
static int muscle_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
{
if (len == 0)
return SC_SUCCESS;
else {
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL,
msc_get_challenge(card, len, 0, NULL, rnd),
"GET CHALLENGE cmd failed");
return (int) len;
}
}
static int muscle_check_sw(sc_card_t * card, unsigned int sw1, unsigned int sw2) {
if(sw1 == 0x9C) {
switch(sw2) {
case 0x01: /* SW_NO_MEMORY_LEFT */
return SC_ERROR_NOT_ENOUGH_MEMORY;
case 0x02: /* SW_AUTH_FAILED */
return SC_ERROR_PIN_CODE_INCORRECT;
case 0x03: /* SW_OPERATION_NOT_ALLOWED */
return SC_ERROR_NOT_ALLOWED;
case 0x05: /* SW_UNSUPPORTED_FEATURE */
return SC_ERROR_NO_CARD_SUPPORT;
case 0x06: /* SW_UNAUTHORIZED */
return SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;
case 0x07: /* SW_OBJECT_NOT_FOUND */
return SC_ERROR_FILE_NOT_FOUND;
case 0x08: /* SW_OBJECT_EXISTS */
return SC_ERROR_FILE_ALREADY_EXISTS;
case 0x09: /* SW_INCORRECT_ALG */
return SC_ERROR_INCORRECT_PARAMETERS;
case 0x0B: /* SW_SIGNATURE_INVALID */
return SC_ERROR_CARD_CMD_FAILED;
case 0x0C: /* SW_IDENTITY_BLOCKED */
return SC_ERROR_AUTH_METHOD_BLOCKED;
case 0x0F: /* SW_INVALID_PARAMETER */
case 0x10: /* SW_INCORRECT_P1 */
case 0x11: /* SW_INCORRECT_P2 */
return SC_ERROR_INCORRECT_PARAMETERS;
}
}
return iso_ops->check_sw(card, sw1, sw2);
}
static int muscle_card_reader_lock_obtained(sc_card_t *card, int was_reset)
{
int r = SC_SUCCESS;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (was_reset > 0) {
if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) != 1) {
r = SC_ERROR_INVALID_CARD;
}
}
LOG_FUNC_RETURN(card->ctx, r);
}
static struct sc_card_driver * sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (iso_ops == NULL)
iso_ops = iso_drv->ops;
muscle_ops = *iso_drv->ops;
muscle_ops.check_sw = muscle_check_sw;
muscle_ops.pin_cmd = muscle_pin_cmd;
muscle_ops.match_card = muscle_match_card;
muscle_ops.init = muscle_init;
muscle_ops.finish = muscle_finish;
muscle_ops.get_challenge = muscle_get_challenge;
muscle_ops.set_security_env = muscle_set_security_env;
muscle_ops.restore_security_env = muscle_restore_security_env;
muscle_ops.compute_signature = muscle_compute_signature;
muscle_ops.decipher = muscle_decipher;
muscle_ops.card_ctl = muscle_card_ctl;
muscle_ops.read_binary = muscle_read_binary;
muscle_ops.update_binary = muscle_update_binary;
muscle_ops.create_file = muscle_create_file;
muscle_ops.select_file = muscle_select_file;
muscle_ops.delete_file = muscle_delete_file;
muscle_ops.list_files = muscle_list_files;
muscle_ops.card_reader_lock_obtained = muscle_card_reader_lock_obtained;
return &muscle_drv;
}
struct sc_card_driver * sc_get_muscle_driver(void)
{
return sc_get_driver();
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_341_2 |
crossvul-cpp_data_bad_1359_3 | /**
* @file tree_schema.c
* @author Radek Krejci <rkrejci@cesnet.cz>
* @brief Manipulation with libyang schema data structures
*
* Copyright (c) 2015 - 2018 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*/
#define _GNU_SOURCE
#ifdef __APPLE__
# include <sys/param.h>
#endif
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <dirent.h>
#include "common.h"
#include "context.h"
#include "parser.h"
#include "resolve.h"
#include "xml.h"
#include "xpath.h"
#include "xml_internal.h"
#include "tree_internal.h"
#include "validation.h"
#include "parser_yang.h"
static int lys_type_dup(struct lys_module *mod, struct lys_node *parent, struct lys_type *new, struct lys_type *old,
int in_grp, int shallow, struct unres_schema *unres);
API const struct lys_node_list *
lys_is_key(const struct lys_node_leaf *node, uint8_t *index)
{
struct lys_node *parent = (struct lys_node *)node;
struct lys_node_list *list;
uint8_t i;
if (!node || node->nodetype != LYS_LEAF) {
return NULL;
}
do {
parent = lys_parent(parent);
} while (parent && parent->nodetype == LYS_USES);
if (!parent || parent->nodetype != LYS_LIST) {
return NULL;
}
list = (struct lys_node_list*)parent;
for (i = 0; i < list->keys_size; i++) {
if (list->keys[i] == node) {
if (index) {
(*index) = i;
}
return list;
}
}
return NULL;
}
API const struct lys_node *
lys_is_disabled(const struct lys_node *node, int recursive)
{
int i;
if (!node) {
return NULL;
}
check:
if (node->nodetype != LYS_INPUT && node->nodetype != LYS_OUTPUT) {
/* input/output does not have if-feature, so skip them */
/* check local if-features */
for (i = 0; i < node->iffeature_size; i++) {
if (!resolve_iffeature(&node->iffeature[i])) {
return node;
}
}
}
if (!recursive) {
return NULL;
}
/* go through parents */
if (node->nodetype == LYS_AUGMENT) {
/* go to parent actually means go to the target node */
node = ((struct lys_node_augment *)node)->target;
if (!node) {
/* unresolved augment, let's say it's enabled */
return NULL;
}
} else if (node->nodetype == LYS_EXT) {
return NULL;
} else if (node->parent) {
node = node->parent;
} else {
return NULL;
}
if (recursive == 2) {
/* continue only if the node cannot have a data instance */
if (node->nodetype & (LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST)) {
return NULL;
}
}
goto check;
}
API const struct lys_type *
lys_getnext_union_type(const struct lys_type *last, const struct lys_type *type)
{
int found = 0;
if (!type || (type->base != LY_TYPE_UNION)) {
return NULL;
}
return lyp_get_next_union_type((struct lys_type *)type, (struct lys_type *)last, &found);
}
int
lys_get_sibling(const struct lys_node *siblings, const char *mod_name, int mod_name_len, const char *name,
int nam_len, LYS_NODE type, const struct lys_node **ret)
{
const struct lys_node *node, *parent = NULL;
const struct lys_module *mod = NULL;
const char *node_mod_name;
assert(siblings && mod_name && name);
assert(!(type & (LYS_USES | LYS_GROUPING)));
/* fill the lengths in case the caller is so indifferent */
if (!mod_name_len) {
mod_name_len = strlen(mod_name);
}
if (!nam_len) {
nam_len = strlen(name);
}
while (siblings && (siblings->nodetype == LYS_USES)) {
siblings = siblings->child;
}
if (!siblings) {
/* unresolved uses */
return EXIT_FAILURE;
}
if (siblings->nodetype == LYS_GROUPING) {
for (node = siblings; (node->nodetype == LYS_GROUPING) && (node->prev != siblings); node = node->prev);
if (node->nodetype == LYS_GROUPING) {
/* we went through all the siblings, only groupings there - no valid sibling */
return EXIT_FAILURE;
}
/* update siblings to be valid */
siblings = node;
}
/* set parent correctly */
parent = lys_parent(siblings);
/* go up all uses */
while (parent && (parent->nodetype == LYS_USES)) {
parent = lys_parent(parent);
}
if (!parent) {
/* handle situation when there is a top-level uses referencing a foreign grouping */
for (node = siblings; lys_parent(node) && (node->nodetype == LYS_USES); node = lys_parent(node));
mod = lys_node_module(node);
}
/* try to find the node */
node = NULL;
while ((node = lys_getnext(node, parent, mod, LYS_GETNEXT_WITHCHOICE | LYS_GETNEXT_WITHCASE | LYS_GETNEXT_WITHINOUT))) {
if (!type || (node->nodetype & type)) {
/* module name comparison */
node_mod_name = lys_node_module(node)->name;
if (!ly_strequal(node_mod_name, mod_name, 1) && (strncmp(node_mod_name, mod_name, mod_name_len) || node_mod_name[mod_name_len])) {
continue;
}
/* direct name check */
if (ly_strequal(node->name, name, 1) || (!strncmp(node->name, name, nam_len) && !node->name[nam_len])) {
if (ret) {
*ret = node;
}
return EXIT_SUCCESS;
}
}
}
return EXIT_FAILURE;
}
int
lys_getnext_data(const struct lys_module *mod, const struct lys_node *parent, const char *name, int nam_len,
LYS_NODE type, const struct lys_node **ret)
{
const struct lys_node *node;
assert((mod || parent) && name);
assert(!(type & (LYS_AUGMENT | LYS_USES | LYS_GROUPING | LYS_CHOICE | LYS_CASE | LYS_INPUT | LYS_OUTPUT)));
if (!mod) {
mod = lys_node_module(parent);
}
/* try to find the node */
node = NULL;
while ((node = lys_getnext(node, parent, mod, 0))) {
if (!type || (node->nodetype & type)) {
/* module check */
if (lys_node_module(node) != lys_main_module(mod)) {
continue;
}
/* direct name check */
if (!strncmp(node->name, name, nam_len) && !node->name[nam_len]) {
if (ret) {
*ret = node;
}
return EXIT_SUCCESS;
}
}
}
return EXIT_FAILURE;
}
API const struct lys_node *
lys_getnext(const struct lys_node *last, const struct lys_node *parent, const struct lys_module *module, int options)
{
const struct lys_node *next, *aug_parent;
struct lys_node **snode;
if ((!parent && !module) || (module && module->type) || (parent && (parent->nodetype == LYS_USES) && !(options & LYS_GETNEXT_PARENTUSES))) {
LOGARG;
return NULL;
}
if (!last) {
/* first call */
/* get know where to start */
if (parent) {
/* schema subtree */
snode = lys_child(parent, LYS_UNKNOWN);
/* do not return anything if the augment does not have any children */
if (!snode || !(*snode) || ((parent->nodetype == LYS_AUGMENT) && ((*snode)->parent != parent))) {
return NULL;
}
next = last = *snode;
} else {
/* top level data */
if (!(options & LYS_GETNEXT_NOSTATECHECK) && (module->disabled || !module->implemented)) {
/* nothing to return from a disabled/imported module */
return NULL;
}
next = last = module->data;
}
} else if ((last->nodetype == LYS_USES) && (options & LYS_GETNEXT_INTOUSES) && last->child) {
/* continue with uses content */
next = last->child;
} else {
/* continue after the last returned value */
next = last->next;
}
repeat:
if (parent && (parent->nodetype == LYS_AUGMENT) && next) {
/* do not return anything outside the parent augment */
aug_parent = next->parent;
do {
while (aug_parent && (aug_parent->nodetype != LYS_AUGMENT)) {
aug_parent = aug_parent->parent;
}
if (aug_parent) {
if (aug_parent == parent) {
break;
}
aug_parent = ((struct lys_node_augment *)aug_parent)->target;
}
} while (aug_parent);
if (!aug_parent) {
return NULL;
}
}
while (next && (next->nodetype == LYS_GROUPING)) {
if (options & LYS_GETNEXT_WITHGROUPING) {
return next;
}
next = next->next;
}
if (!next) { /* cover case when parent is augment */
if (!last || last->parent == parent || lys_parent(last) == parent) {
/* no next element */
return NULL;
}
last = lys_parent(last);
next = last->next;
goto repeat;
} else {
last = next;
}
if (!(options & LYS_GETNEXT_NOSTATECHECK) && lys_is_disabled(next, 0)) {
next = next->next;
goto repeat;
}
switch (next->nodetype) {
case LYS_INPUT:
case LYS_OUTPUT:
if (options & LYS_GETNEXT_WITHINOUT) {
return next;
} else if (next->child) {
next = next->child;
} else {
next = next->next;
}
goto repeat;
case LYS_CASE:
if (options & LYS_GETNEXT_WITHCASE) {
return next;
} else if (next->child) {
next = next->child;
} else {
next = next->next;
}
goto repeat;
case LYS_USES:
/* go into */
if (options & LYS_GETNEXT_WITHUSES) {
return next;
} else if (next->child) {
next = next->child;
} else {
next = next->next;
}
goto repeat;
case LYS_RPC:
case LYS_ACTION:
case LYS_NOTIF:
case LYS_LEAF:
case LYS_ANYXML:
case LYS_ANYDATA:
case LYS_LIST:
case LYS_LEAFLIST:
return next;
case LYS_CONTAINER:
if (!((struct lys_node_container *)next)->presence && (options & LYS_GETNEXT_INTONPCONT)) {
if (next->child) {
/* go into */
next = next->child;
} else {
next = next->next;
}
goto repeat;
} else {
return next;
}
case LYS_CHOICE:
if (options & LYS_GETNEXT_WITHCHOICE) {
return next;
} else if (next->child) {
/* go into */
next = next->child;
} else {
next = next->next;
}
goto repeat;
default:
/* we should not be here */
return NULL;
}
}
void
lys_node_unlink(struct lys_node *node)
{
struct lys_node *parent, *first, **pp = NULL;
struct lys_module *main_module;
if (!node) {
return;
}
/* unlink from data model if necessary */
if (node->module) {
/* get main module with data tree */
main_module = lys_node_module(node);
if (main_module->data == node) {
main_module->data = node->next;
}
}
/* store pointers to important nodes */
parent = node->parent;
if (parent && (parent->nodetype == LYS_AUGMENT)) {
/* handle augments - first, unlink it from the augment parent ... */
if (parent->child == node) {
parent->child = (node->next && node->next->parent == parent) ? node->next : NULL;
}
if (parent->flags & LYS_NOTAPPLIED) {
/* data are not connected in the target, so we cannot continue with the target as a parent */
parent = NULL;
} else {
/* data are connected in target, so we will continue with the target as a parent */
parent = ((struct lys_node_augment *)parent)->target;
}
}
/* unlink from parent */
if (parent) {
if (parent->nodetype == LYS_EXT) {
pp = (struct lys_node **)lys_ext_complex_get_substmt(lys_snode2stmt(node->nodetype),
(struct lys_ext_instance_complex*)parent, NULL);
if (*pp == node) {
*pp = node->next;
}
} else if (parent->child == node) {
parent->child = node->next;
}
node->parent = NULL;
}
/* unlink from siblings */
if (node->prev == node) {
/* there are no more siblings */
return;
}
if (node->next) {
node->next->prev = node->prev;
} else {
/* unlinking the last element */
if (parent) {
if (parent->nodetype == LYS_EXT) {
first = *(struct lys_node **)pp;
} else {
first = parent->child;
}
} else {
first = node;
while (first->prev->next) {
first = first->prev;
}
}
first->prev = node->prev;
}
if (node->prev->next) {
node->prev->next = node->next;
}
/* clean up the unlinked element */
node->next = NULL;
node->prev = node;
}
struct lys_node_grp *
lys_find_grouping_up(const char *name, struct lys_node *start)
{
struct lys_node *par_iter, *iter, *stop;
for (par_iter = start; par_iter; par_iter = par_iter->parent) {
/* top-level augment, look into module (uses augment is handled correctly below) */
if (par_iter->parent && !par_iter->parent->parent && (par_iter->parent->nodetype == LYS_AUGMENT)) {
par_iter = lys_main_module(par_iter->parent->module)->data;
if (!par_iter) {
break;
}
}
if (par_iter->nodetype == LYS_EXT) {
/* we are in a top-level extension, search grouping in top-level groupings */
par_iter = lys_main_module(par_iter->module)->data;
if (!par_iter) {
/* not connected yet, wait */
return NULL;
}
} else if (par_iter->parent && (par_iter->parent->nodetype & (LYS_CHOICE | LYS_CASE | LYS_AUGMENT | LYS_USES))) {
continue;
}
for (iter = par_iter, stop = NULL; iter; iter = iter->prev) {
if (!stop) {
stop = par_iter;
} else if (iter == stop) {
break;
}
if (iter->nodetype != LYS_GROUPING) {
continue;
}
if (!strcmp(name, iter->name)) {
return (struct lys_node_grp *)iter;
}
}
}
return NULL;
}
/*
* get next grouping in the root's subtree, in the
* first call, tha last is NULL
*/
static struct lys_node_grp *
lys_get_next_grouping(struct lys_node_grp *lastgrp, struct lys_node *root)
{
struct lys_node *last = (struct lys_node *)lastgrp;
struct lys_node *next;
assert(root);
if (!last) {
last = root;
}
while (1) {
if ((last->nodetype & (LYS_CONTAINER | LYS_CHOICE | LYS_LIST | LYS_GROUPING | LYS_INPUT | LYS_OUTPUT))) {
next = last->child;
} else {
next = NULL;
}
if (!next) {
if (last == root) {
/* we are done */
return NULL;
}
/* no children, go to siblings */
next = last->next;
}
while (!next) {
/* go back through parents */
if (lys_parent(last) == root) {
/* we are done */
return NULL;
}
next = last->next;
last = lys_parent(last);
}
if (next->nodetype == LYS_GROUPING) {
return (struct lys_node_grp *)next;
}
last = next;
}
}
/* logs directly */
int
lys_check_id(struct lys_node *node, struct lys_node *parent, struct lys_module *module)
{
struct lys_node *start, *stop, *iter;
struct lys_node_grp *grp;
int down, up;
assert(node);
if (!parent) {
assert(module);
} else {
module = parent->module;
}
module = lys_main_module(module);
switch (node->nodetype) {
case LYS_GROUPING:
/* 6.2.1, rule 6 */
if (parent) {
start = *lys_child(parent, LYS_GROUPING);
if (!start) {
down = 0;
start = parent;
} else {
down = 1;
}
if (parent->nodetype == LYS_EXT) {
up = 0;
} else {
up = 1;
}
} else {
down = up = 1;
start = module->data;
}
/* go up */
if (up && lys_find_grouping_up(node->name, start)) {
LOGVAL(module->ctx, LYE_DUPID, LY_VLOG_LYS, node, "grouping", node->name);
return EXIT_FAILURE;
}
/* go down, because grouping can be defined after e.g. container in which is collision */
if (down) {
for (iter = start, stop = NULL; iter; iter = iter->prev) {
if (!stop) {
stop = start;
} else if (iter == stop) {
break;
}
if (!(iter->nodetype & (LYS_CONTAINER | LYS_CHOICE | LYS_LIST | LYS_GROUPING | LYS_INPUT | LYS_OUTPUT))) {
continue;
}
grp = NULL;
while ((grp = lys_get_next_grouping(grp, iter))) {
if (ly_strequal(node->name, grp->name, 1)) {
LOGVAL(module->ctx, LYE_DUPID,LY_VLOG_LYS, node, "grouping", node->name);
return EXIT_FAILURE;
}
}
}
}
break;
case LYS_LEAF:
case LYS_LEAFLIST:
case LYS_LIST:
case LYS_CONTAINER:
case LYS_CHOICE:
case LYS_ANYDATA:
/* 6.2.1, rule 7 */
if (parent) {
iter = parent;
while (iter && (iter->nodetype & (LYS_USES | LYS_CASE | LYS_CHOICE | LYS_AUGMENT))) {
if (iter->nodetype == LYS_AUGMENT) {
if (((struct lys_node_augment *)iter)->target) {
/* augment is resolved, go up */
iter = ((struct lys_node_augment *)iter)->target;
continue;
}
/* augment is not resolved, this is the final parent */
break;
}
iter = iter->parent;
}
if (!iter) {
stop = NULL;
iter = module->data;
} else if (iter->nodetype == LYS_EXT) {
stop = iter;
iter = (struct lys_node *)lys_child(iter, node->nodetype);
if (iter) {
iter = *(struct lys_node **)iter;
}
} else {
stop = iter;
iter = iter->child;
}
} else {
stop = NULL;
iter = module->data;
}
while (iter) {
if (iter->nodetype & (LYS_USES | LYS_CASE)) {
iter = iter->child;
continue;
}
if (iter->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_CONTAINER | LYS_CHOICE | LYS_ANYDATA)) {
if (iter->module == node->module && ly_strequal(iter->name, node->name, 1)) {
LOGVAL(module->ctx, LYE_DUPID, LY_VLOG_LYS, node, strnodetype(node->nodetype), node->name);
return EXIT_FAILURE;
}
}
/* special case for choice - we must check the choice's name as
* well as the names of nodes under the choice
*/
if (iter->nodetype == LYS_CHOICE) {
iter = iter->child;
continue;
}
/* go to siblings */
if (!iter->next) {
/* no sibling, go to parent's sibling */
do {
/* for parent LYS_AUGMENT */
if (iter->parent == stop) {
iter = stop;
break;
}
iter = lys_parent(iter);
if (iter && iter->next) {
break;
}
} while (iter != stop);
if (iter == stop) {
break;
}
}
iter = iter->next;
}
break;
case LYS_CASE:
/* 6.2.1, rule 8 */
if (parent) {
start = *lys_child(parent, LYS_CASE);
} else {
start = module->data;
}
LY_TREE_FOR(start, iter) {
if (!(iter->nodetype & (LYS_ANYDATA | LYS_CASE | LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST))) {
continue;
}
if (iter->module == node->module && ly_strequal(iter->name, node->name, 1)) {
LOGVAL(module->ctx, LYE_DUPID, LY_VLOG_LYS, node, "case", node->name);
return EXIT_FAILURE;
}
}
break;
default:
/* no check needed */
break;
}
return EXIT_SUCCESS;
}
/* logs directly */
int
lys_node_addchild(struct lys_node *parent, struct lys_module *module, struct lys_node *child, int options)
{
struct ly_ctx *ctx = child->module->ctx;
struct lys_node *iter, **pchild, *log_parent;
struct lys_node_inout *in, *out;
struct lys_node_case *c;
int type, shortcase = 0;
void *p;
struct lyext_substmt *info = NULL;
assert(child);
if (parent) {
type = parent->nodetype;
module = parent->module;
log_parent = parent;
if (type == LYS_USES) {
/* we are adding children to uses -> we must be copying grouping contents into it, so properly check the parent */
log_parent = lys_parent(log_parent);
while (log_parent && (log_parent->nodetype == LYS_USES)) {
log_parent = lys_parent(log_parent);
}
if (log_parent) {
type = log_parent->nodetype;
} else {
type = 0;
}
}
} else {
assert(module);
assert(!(child->nodetype & (LYS_INPUT | LYS_OUTPUT)));
type = 0;
log_parent = NULL;
}
/* checks */
switch (type) {
case LYS_CONTAINER:
case LYS_LIST:
case LYS_GROUPING:
case LYS_USES:
if (!(child->nodetype &
(LYS_ANYDATA | LYS_CHOICE | LYS_CONTAINER | LYS_GROUPING | LYS_LEAF |
LYS_LEAFLIST | LYS_LIST | LYS_USES | LYS_ACTION | LYS_NOTIF))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), strnodetype(log_parent->nodetype));
return EXIT_FAILURE;
}
break;
case LYS_INPUT:
case LYS_OUTPUT:
case LYS_NOTIF:
if (!(child->nodetype &
(LYS_ANYDATA | LYS_CHOICE | LYS_CONTAINER | LYS_GROUPING | LYS_LEAF |
LYS_LEAFLIST | LYS_LIST | LYS_USES))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), strnodetype(log_parent->nodetype));
return EXIT_FAILURE;
}
break;
case LYS_CHOICE:
if (!(child->nodetype &
(LYS_ANYDATA | LYS_CASE | LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_CHOICE))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), "choice");
return EXIT_FAILURE;
}
if (child->nodetype != LYS_CASE) {
shortcase = 1;
}
break;
case LYS_CASE:
if (!(child->nodetype &
(LYS_ANYDATA | LYS_CHOICE | LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_USES))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), "case");
return EXIT_FAILURE;
}
break;
case LYS_RPC:
case LYS_ACTION:
if (!(child->nodetype & (LYS_INPUT | LYS_OUTPUT | LYS_GROUPING))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), "rpc");
return EXIT_FAILURE;
}
break;
case LYS_LEAF:
case LYS_LEAFLIST:
case LYS_ANYXML:
case LYS_ANYDATA:
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), strnodetype(log_parent->nodetype));
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "The \"%s\" statement cannot have any data substatement.",
strnodetype(log_parent->nodetype));
return EXIT_FAILURE;
case LYS_AUGMENT:
if (!(child->nodetype &
(LYS_ANYDATA | LYS_CASE | LYS_CHOICE | LYS_CONTAINER | LYS_LEAF
| LYS_LEAFLIST | LYS_LIST | LYS_USES | LYS_ACTION | LYS_NOTIF))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), strnodetype(log_parent->nodetype));
return EXIT_FAILURE;
}
break;
case LYS_UNKNOWN:
/* top level */
if (!(child->nodetype &
(LYS_ANYDATA | LYS_CHOICE | LYS_CONTAINER | LYS_LEAF | LYS_GROUPING
| LYS_LEAFLIST | LYS_LIST | LYS_USES | LYS_RPC | LYS_NOTIF | LYS_AUGMENT))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), "(sub)module");
return EXIT_FAILURE;
}
break;
case LYS_EXT:
/* plugin-defined */
p = lys_ext_complex_get_substmt(lys_snode2stmt(child->nodetype), (struct lys_ext_instance_complex*)log_parent, &info);
if (!p) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype),
((struct lys_ext_instance_complex*)log_parent)->def->name);
return EXIT_FAILURE;
}
/* TODO check cardinality */
break;
}
/* check identifier uniqueness */
if (!(module->ctx->models.flags & LY_CTX_TRUSTED) && lys_check_id(child, parent, module)) {
return EXIT_FAILURE;
}
if (child->parent) {
lys_node_unlink(child);
}
if ((child->nodetype & (LYS_INPUT | LYS_OUTPUT)) && parent->nodetype != LYS_EXT) {
/* find the implicit input/output node */
LY_TREE_FOR(parent->child, iter) {
if (iter->nodetype == child->nodetype) {
break;
}
}
assert(iter);
/* switch the old implicit node (iter) with the new one (child) */
if (parent->child == iter) {
/* first child */
parent->child = child;
} else {
iter->prev->next = child;
}
child->prev = iter->prev;
child->next = iter->next;
if (iter->next) {
iter->next->prev = child;
} else {
/* last child */
parent->child->prev = child;
}
child->parent = parent;
/* isolate the node and free it */
iter->next = NULL;
iter->prev = iter;
iter->parent = NULL;
lys_node_free(iter, NULL, 0);
} else {
if (shortcase) {
/* create the implicit case to allow it to serve as a target of the augments,
* it won't be printed, but it will be present in the tree */
c = calloc(1, sizeof *c);
LY_CHECK_ERR_RETURN(!c, LOGMEM(ctx), EXIT_FAILURE);
c->name = lydict_insert(module->ctx, child->name, 0);
c->flags = LYS_IMPLICIT;
if (!(options & (LYS_PARSE_OPT_CFG_IGNORE | LYS_PARSE_OPT_CFG_NOINHERIT))) {
/* get config flag from parent */
c->flags |= parent->flags & LYS_CONFIG_MASK;
}
c->module = module;
c->nodetype = LYS_CASE;
c->prev = (struct lys_node*)c;
lys_node_addchild(parent, module, (struct lys_node*)c, options);
parent = (struct lys_node*)c;
}
/* connect the child correctly */
if (!parent) {
if (module->data) {
module->data->prev->next = child;
child->prev = module->data->prev;
module->data->prev = child;
} else {
module->data = child;
}
} else {
pchild = lys_child(parent, child->nodetype);
assert(pchild);
child->parent = parent;
if (!(*pchild)) {
/* the only/first child of the parent */
*pchild = child;
iter = child;
} else {
/* add a new child at the end of parent's child list */
iter = (*pchild)->prev;
iter->next = child;
child->prev = iter;
}
while (iter->next) {
iter = iter->next;
iter->parent = parent;
}
(*pchild)->prev = iter;
}
}
/* check config value (but ignore them in groupings and augments) */
for (iter = parent; iter && !(iter->nodetype & (LYS_GROUPING | LYS_AUGMENT | LYS_EXT)); iter = iter->parent);
if (parent && !iter) {
for (iter = child; iter && !(iter->nodetype & (LYS_NOTIF | LYS_INPUT | LYS_OUTPUT | LYS_RPC)); iter = iter->parent);
if (!iter && (parent->flags & LYS_CONFIG_R) && (child->flags & LYS_CONFIG_W)) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, child, "true", "config");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "State nodes cannot have configuration nodes as children.");
return EXIT_FAILURE;
}
}
/* propagate information about status data presence */
if ((child->nodetype & (LYS_CONTAINER | LYS_CHOICE | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_ANYDATA)) &&
(child->flags & LYS_INCL_STATUS)) {
for(iter = parent; iter; iter = lys_parent(iter)) {
/* store it only into container or list - the only data inner nodes */
if (iter->nodetype & (LYS_CONTAINER | LYS_LIST)) {
if (iter->flags & LYS_INCL_STATUS) {
/* done, someone else set it already from here */
break;
}
/* set flag about including status data */
iter->flags |= LYS_INCL_STATUS;
}
}
}
/* create implicit input/output nodes to have available them as possible target for augment */
if ((child->nodetype & (LYS_RPC | LYS_ACTION)) && !child->child) {
in = calloc(1, sizeof *in);
out = calloc(1, sizeof *out);
if (!in || !out) {
LOGMEM(ctx);
free(in);
free(out);
return EXIT_FAILURE;
}
in->nodetype = LYS_INPUT;
in->name = lydict_insert(child->module->ctx, "input", 5);
out->nodetype = LYS_OUTPUT;
out->name = lydict_insert(child->module->ctx, "output", 6);
in->module = out->module = child->module;
in->parent = out->parent = child;
in->flags = out->flags = LYS_IMPLICIT;
in->next = (struct lys_node *)out;
in->prev = (struct lys_node *)out;
out->prev = (struct lys_node *)in;
child->child = (struct lys_node *)in;
}
return EXIT_SUCCESS;
}
const struct lys_module *
lys_parse_mem_(struct ly_ctx *ctx, const char *data, LYS_INFORMAT format, const char *revision, int internal, int implement)
{
char *enlarged_data = NULL;
struct lys_module *mod = NULL;
unsigned int len;
if (!ctx || !data) {
LOGARG;
return NULL;
}
if (!internal && format == LYS_IN_YANG) {
/* enlarge data by 2 bytes for flex */
len = strlen(data);
enlarged_data = malloc((len + 2) * sizeof *enlarged_data);
LY_CHECK_ERR_RETURN(!enlarged_data, LOGMEM(ctx), NULL);
memcpy(enlarged_data, data, len);
enlarged_data[len] = enlarged_data[len + 1] = '\0';
data = enlarged_data;
}
switch (format) {
case LYS_IN_YIN:
mod = yin_read_module(ctx, data, revision, implement);
break;
case LYS_IN_YANG:
mod = yang_read_module(ctx, data, 0, revision, implement);
break;
default:
LOGERR(ctx, LY_EINVAL, "Invalid schema input format.");
break;
}
free(enlarged_data);
/* hack for NETCONF's edit-config's operation attribute. It is not defined in the schema, but since libyang
* implements YANG metadata (annotations), we need its definition. Because the ietf-netconf schema is not the
* internal part of libyang, we cannot add the annotation into the schema source, but we do it here to have
* the anotation definitions available in the internal schema structure. There is another hack in schema
* printers to do not print this internally added annotation. */
if (mod && ly_strequal(mod->name, "ietf-netconf", 0)) {
if (lyp_add_ietf_netconf_annotations_config(mod)) {
lys_free(mod, NULL, 1, 1);
return NULL;
}
}
return mod;
}
API const struct lys_module *
lys_parse_mem(struct ly_ctx *ctx, const char *data, LYS_INFORMAT format)
{
return lys_parse_mem_(ctx, data, format, NULL, 0, 1);
}
struct lys_submodule *
lys_sub_parse_mem(struct lys_module *module, const char *data, LYS_INFORMAT format, struct unres_schema *unres)
{
char *enlarged_data = NULL;
struct lys_submodule *submod = NULL;
unsigned int len;
assert(module);
assert(data);
if (format == LYS_IN_YANG) {
/* enlarge data by 2 bytes for flex */
len = strlen(data);
enlarged_data = malloc((len + 2) * sizeof *enlarged_data);
LY_CHECK_ERR_RETURN(!enlarged_data, LOGMEM(module->ctx), NULL);
memcpy(enlarged_data, data, len);
enlarged_data[len] = enlarged_data[len + 1] = '\0';
data = enlarged_data;
}
/* get the main module */
module = lys_main_module(module);
switch (format) {
case LYS_IN_YIN:
submod = yin_read_submodule(module, data, unres);
break;
case LYS_IN_YANG:
submod = yang_read_submodule(module, data, 0, unres);
break;
default:
assert(0);
break;
}
free(enlarged_data);
return submod;
}
API const struct lys_module *
lys_parse_path(struct ly_ctx *ctx, const char *path, LYS_INFORMAT format)
{
int fd;
const struct lys_module *ret;
const char *rev, *dot, *filename;
size_t len;
if (!ctx || !path) {
LOGARG;
return NULL;
}
fd = open(path, O_RDONLY);
if (fd == -1) {
LOGERR(ctx, LY_ESYS, "Opening file \"%s\" failed (%s).", path, strerror(errno));
return NULL;
}
ret = lys_parse_fd(ctx, fd, format);
close(fd);
if (!ret) {
/* error */
return NULL;
}
/* check that name and revision match filename */
filename = strrchr(path, '/');
if (!filename) {
filename = path;
} else {
filename++;
}
rev = strchr(filename, '@');
dot = strrchr(filename, '.');
/* name */
len = strlen(ret->name);
if (strncmp(filename, ret->name, len) ||
((rev && rev != &filename[len]) || (!rev && dot != &filename[len]))) {
LOGWRN(ctx, "File name \"%s\" does not match module name \"%s\".", filename, ret->name);
}
if (rev) {
len = dot - ++rev;
if (!ret->rev_size || len != 10 || strncmp(ret->rev[0].date, rev, len)) {
LOGWRN(ctx, "File name \"%s\" does not match module revision \"%s\".", filename,
ret->rev_size ? ret->rev[0].date : "none");
}
}
if (!ret->filepath) {
/* store URI */
char rpath[PATH_MAX];
if (realpath(path, rpath) != NULL) {
((struct lys_module *)ret)->filepath = lydict_insert(ctx, rpath, 0);
} else {
((struct lys_module *)ret)->filepath = lydict_insert(ctx, path, 0);
}
}
return ret;
}
API const struct lys_module *
lys_parse_fd(struct ly_ctx *ctx, int fd, LYS_INFORMAT format)
{
return lys_parse_fd_(ctx, fd, format, NULL, 1);
}
static void
lys_parse_set_filename(struct ly_ctx *ctx, const char **filename, int fd)
{
#ifdef __APPLE__
char path[MAXPATHLEN];
#else
int len;
char path[PATH_MAX], proc_path[32];
#endif
#ifdef __APPLE__
if (fcntl(fd, F_GETPATH, path) != -1) {
*filename = lydict_insert(ctx, path, 0);
}
#else
/* get URI if there is /proc */
sprintf(proc_path, "/proc/self/fd/%d", fd);
if ((len = readlink(proc_path, path, PATH_MAX - 1)) > 0) {
*filename = lydict_insert(ctx, path, len);
}
#endif
}
const struct lys_module *
lys_parse_fd_(struct ly_ctx *ctx, int fd, LYS_INFORMAT format, const char *revision, int implement)
{
const struct lys_module *module;
size_t length;
char *addr;
if (!ctx || fd < 0) {
LOGARG;
return NULL;
}
if (lyp_mmap(ctx, fd, format == LYS_IN_YANG ? 1 : 0, &length, (void **)&addr)) {
LOGERR(ctx, LY_ESYS, "Mapping file descriptor into memory failed (%s()).", __func__);
return NULL;
} else if (!addr) {
LOGERR(ctx, LY_EINVAL, "Empty schema file.");
return NULL;
}
module = lys_parse_mem_(ctx, addr, format, revision, 1, implement);
lyp_munmap(addr, length);
if (module && !module->filepath) {
lys_parse_set_filename(ctx, (const char **)&module->filepath, fd);
}
return module;
}
struct lys_submodule *
lys_sub_parse_fd(struct lys_module *module, int fd, LYS_INFORMAT format, struct unres_schema *unres)
{
struct lys_submodule *submodule;
size_t length;
char *addr;
assert(module);
assert(fd >= 0);
if (lyp_mmap(module->ctx, fd, format == LYS_IN_YANG ? 1 : 0, &length, (void **)&addr)) {
LOGERR(module->ctx, LY_ESYS, "Mapping file descriptor into memory failed (%s()).", __func__);
return NULL;
} else if (!addr) {
LOGERR(module->ctx, LY_EINVAL, "Empty submodule schema file.");
return NULL;
}
/* get the main module */
module = lys_main_module(module);
switch (format) {
case LYS_IN_YIN:
submodule = yin_read_submodule(module, addr, unres);
break;
case LYS_IN_YANG:
submodule = yang_read_submodule(module, addr, 0, unres);
break;
default:
LOGINT(module->ctx);
return NULL;
}
lyp_munmap(addr, length);
if (submodule && !submodule->filepath) {
lys_parse_set_filename(module->ctx, (const char **)&submodule->filepath, fd);
}
return submodule;
}
API int
lys_search_localfile(const char * const *searchpaths, int cwd, const char *name, const char *revision, char **localfile, LYS_INFORMAT *format)
{
size_t len, flen, match_len = 0, dir_len;
int i, implicit_cwd = 0, ret = EXIT_FAILURE;
char *wd, *wn = NULL;
DIR *dir = NULL;
struct dirent *file;
char *match_name = NULL;
LYS_INFORMAT format_aux, match_format = 0;
unsigned int u;
struct ly_set *dirs;
struct stat st;
if (!localfile) {
LOGARG;
return EXIT_FAILURE;
}
/* start to fill the dir fifo with the context's search path (if set)
* and the current working directory */
dirs = ly_set_new();
if (!dirs) {
LOGMEM(NULL);
return EXIT_FAILURE;
}
len = strlen(name);
if (cwd) {
wd = get_current_dir_name();
if (!wd) {
LOGMEM(NULL);
goto cleanup;
} else {
/* add implicit current working directory (./) to be searched,
* this directory is not searched recursively */
if (ly_set_add(dirs, wd, 0) == -1) {
goto cleanup;
}
implicit_cwd = 1;
}
}
if (searchpaths) {
for (i = 0; searchpaths[i]; i++) {
/* check for duplicities with the implicit current working directory */
if (implicit_cwd && !strcmp(dirs->set.g[0], searchpaths[i])) {
implicit_cwd = 0;
continue;
}
wd = strdup(searchpaths[i]);
if (!wd) {
LOGMEM(NULL);
goto cleanup;
} else if (ly_set_add(dirs, wd, 0) == -1) {
goto cleanup;
}
}
}
wd = NULL;
/* start searching */
while (dirs->number) {
free(wd);
free(wn); wn = NULL;
dirs->number--;
wd = (char *)dirs->set.g[dirs->number];
dirs->set.g[dirs->number] = NULL;
LOGVRB("Searching for \"%s\" in %s.", name, wd);
if (dir) {
closedir(dir);
}
dir = opendir(wd);
dir_len = strlen(wd);
if (!dir) {
LOGWRN(NULL, "Unable to open directory \"%s\" for searching (sub)modules (%s).", wd, strerror(errno));
} else {
while ((file = readdir(dir))) {
if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
/* skip . and .. */
continue;
}
free(wn);
if (asprintf(&wn, "%s/%s", wd, file->d_name) == -1) {
LOGMEM(NULL);
goto cleanup;
}
if (stat(wn, &st) == -1) {
LOGWRN(NULL, "Unable to get information about \"%s\" file in \"%s\" when searching for (sub)modules (%s)",
file->d_name, wd, strerror(errno));
continue;
}
if (S_ISDIR(st.st_mode) && (dirs->number || !implicit_cwd)) {
/* we have another subdirectory in searchpath to explore,
* subdirectories are not taken into account in current working dir (dirs->set.g[0]) */
if (ly_set_add(dirs, wn, 0) == -1) {
goto cleanup;
}
/* continue with the next item in current directory */
wn = NULL;
continue;
} else if (!S_ISREG(st.st_mode)) {
/* not a regular file (note that we see the target of symlinks instead of symlinks */
continue;
}
/* here we know that the item is a file which can contain a module */
if (strncmp(name, file->d_name, len) ||
(file->d_name[len] != '.' && file->d_name[len] != '@')) {
/* different filename than the module we search for */
continue;
}
/* get type according to filename suffix */
flen = strlen(file->d_name);
if (!strcmp(&file->d_name[flen - 4], ".yin")) {
format_aux = LYS_IN_YIN;
} else if (!strcmp(&file->d_name[flen - 5], ".yang")) {
format_aux = LYS_IN_YANG;
} else {
/* not supportde suffix/file format */
continue;
}
if (revision) {
/* we look for the specific revision, try to get it from the filename */
if (file->d_name[len] == '@') {
/* check revision from the filename */
if (strncmp(revision, &file->d_name[len + 1], strlen(revision))) {
/* another revision */
continue;
} else {
/* exact revision */
free(match_name);
match_name = wn;
wn = NULL;
match_len = dir_len + 1 + len;
match_format = format_aux;
goto success;
}
} else {
/* continue trying to find exact revision match, use this only if not found */
free(match_name);
match_name = wn;
wn = NULL;
match_len = dir_len + 1 +len;
match_format = format_aux;
continue;
}
} else {
/* remember the revision and try to find the newest one */
if (match_name) {
if (file->d_name[len] != '@' || lyp_check_date(NULL, &file->d_name[len + 1])) {
continue;
} else if (match_name[match_len] == '@' &&
(strncmp(&match_name[match_len + 1], &file->d_name[len + 1], LY_REV_SIZE - 1) >= 0)) {
continue;
}
free(match_name);
}
match_name = wn;
wn = NULL;
match_len = dir_len + 1 + len;
match_format = format_aux;
continue;
}
}
}
}
success:
(*localfile) = match_name;
match_name = NULL;
if (format) {
(*format) = match_format;
}
ret = EXIT_SUCCESS;
cleanup:
free(wn);
free(wd);
if (dir) {
closedir(dir);
}
free(match_name);
for (u = 0; u < dirs->number; u++) {
free(dirs->set.g[u]);
}
ly_set_free(dirs);
return ret;
}
int
lys_ext_iter(struct lys_ext_instance **ext, uint8_t ext_size, uint8_t start, LYEXT_SUBSTMT substmt)
{
unsigned int u;
for (u = start; u < ext_size; u++) {
if (ext[u]->insubstmt == substmt) {
return u;
}
}
return -1;
}
/*
* duplicate extension instance
*/
int
lys_ext_dup(struct ly_ctx *ctx, struct lys_module *mod, struct lys_ext_instance **orig, uint8_t size, void *parent,
LYEXT_PAR parent_type, struct lys_ext_instance ***new, int shallow, struct unres_schema *unres)
{
int i;
uint8_t u = 0;
struct lys_ext_instance **result;
struct unres_ext *info, *info_orig;
size_t len;
assert(new);
if (!size) {
if (orig) {
LOGINT(ctx);
return EXIT_FAILURE;
}
(*new) = NULL;
return EXIT_SUCCESS;
}
(*new) = result = calloc(size, sizeof *result);
LY_CHECK_ERR_RETURN(!result, LOGMEM(ctx), EXIT_FAILURE);
for (u = 0; u < size; u++) {
if (orig[u]) {
/* resolved extension instance, just duplicate it */
switch(orig[u]->ext_type) {
case LYEXT_FLAG:
result[u] = malloc(sizeof(struct lys_ext_instance));
LY_CHECK_ERR_GOTO(!result[u], LOGMEM(ctx), error);
break;
case LYEXT_COMPLEX:
len = ((struct lyext_plugin_complex*)orig[u]->def->plugin)->instance_size;
result[u] = calloc(1, len);
LY_CHECK_ERR_GOTO(!result[u], LOGMEM(ctx), error);
((struct lys_ext_instance_complex*)result[u])->substmt = ((struct lyext_plugin_complex*)orig[u]->def->plugin)->substmt;
/* TODO duplicate data in extension instance content */
memcpy((void*)result[u] + sizeof(**orig), (void*)orig[u] + sizeof(**orig), len - sizeof(**orig));
break;
}
/* generic part */
result[u]->def = orig[u]->def;
result[u]->flags = LYEXT_OPT_CONTENT;
result[u]->arg_value = lydict_insert(ctx, orig[u]->arg_value, 0);
result[u]->parent = parent;
result[u]->parent_type = parent_type;
result[u]->insubstmt = orig[u]->insubstmt;
result[u]->insubstmt_index = orig[u]->insubstmt_index;
result[u]->ext_type = orig[u]->ext_type;
result[u]->priv = NULL;
result[u]->nodetype = LYS_EXT;
result[u]->module = mod;
/* extensions */
result[u]->ext_size = orig[u]->ext_size;
if (lys_ext_dup(ctx, mod, orig[u]->ext, orig[u]->ext_size, result[u],
LYEXT_PAR_EXTINST, &result[u]->ext, shallow, unres)) {
goto error;
}
/* in case of shallow copy (duplication for deviation), duplicate only the link to private data
* in a new copy, otherwise (grouping instantiation) do not duplicate the private data */
if (shallow) {
result[u]->priv = orig[u]->priv;
}
} else {
/* original extension is not yet resolved, so duplicate it in unres */
i = unres_schema_find(unres, -1, &orig, UNRES_EXT);
if (i == -1) {
/* extension not found in unres */
LOGINT(ctx);
goto error;
}
info_orig = unres->str_snode[i];
info = malloc(sizeof *info);
LY_CHECK_ERR_GOTO(!info, LOGMEM(ctx), error);
info->datatype = info_orig->datatype;
if (info->datatype == LYS_IN_YIN) {
info->data.yin = lyxml_dup_elem(ctx, info_orig->data.yin, NULL, 1);
} /* else TODO YANG */
info->parent = parent;
info->mod = mod;
info->parent_type = parent_type;
info->ext_index = u;
if (unres_schema_add_node(info->mod, unres, new, UNRES_EXT, (struct lys_node *)info) == -1) {
goto error;
}
}
}
return EXIT_SUCCESS;
error:
(*new) = NULL;
lys_extension_instances_free(ctx, result, u, NULL);
return EXIT_FAILURE;
}
static struct lys_restr *
lys_restr_dup(struct lys_module *mod, struct lys_restr *old, int size, int shallow, struct unres_schema *unres)
{
struct lys_restr *result;
int i;
if (!size) {
return NULL;
}
result = calloc(size, sizeof *result);
LY_CHECK_ERR_RETURN(!result, LOGMEM(mod->ctx), NULL);
for (i = 0; i < size; i++) {
result[i].ext_size = old[i].ext_size;
lys_ext_dup(mod->ctx, mod, old[i].ext, old[i].ext_size, &result[i], LYEXT_PAR_RESTR, &result[i].ext, shallow, unres);
result[i].expr = lydict_insert(mod->ctx, old[i].expr, 0);
result[i].dsc = lydict_insert(mod->ctx, old[i].dsc, 0);
result[i].ref = lydict_insert(mod->ctx, old[i].ref, 0);
result[i].eapptag = lydict_insert(mod->ctx, old[i].eapptag, 0);
result[i].emsg = lydict_insert(mod->ctx, old[i].emsg, 0);
}
return result;
}
void
lys_restr_free(struct ly_ctx *ctx, struct lys_restr *restr,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
assert(ctx);
if (!restr) {
return;
}
lys_extension_instances_free(ctx, restr->ext, restr->ext_size, private_destructor);
lydict_remove(ctx, restr->expr);
lydict_remove(ctx, restr->dsc);
lydict_remove(ctx, restr->ref);
lydict_remove(ctx, restr->eapptag);
lydict_remove(ctx, restr->emsg);
}
API void
lys_iffeature_free(struct ly_ctx *ctx, struct lys_iffeature *iffeature, uint8_t iffeature_size,
int shallow, void (*private_destructor)(const struct lys_node *node, void *priv))
{
uint8_t i;
for (i = 0; i < iffeature_size; ++i) {
lys_extension_instances_free(ctx, iffeature[i].ext, iffeature[i].ext_size, private_destructor);
if (!shallow) {
free(iffeature[i].expr);
free(iffeature[i].features);
}
}
free(iffeature);
}
static int
type_dup(struct lys_module *mod, struct lys_node *parent, struct lys_type *new, struct lys_type *old,
LY_DATA_TYPE base, int in_grp, int shallow, struct unres_schema *unres)
{
int i;
unsigned int u;
switch (base) {
case LY_TYPE_BINARY:
if (old->info.binary.length) {
new->info.binary.length = lys_restr_dup(mod, old->info.binary.length, 1, shallow, unres);
}
break;
case LY_TYPE_BITS:
new->info.bits.count = old->info.bits.count;
if (new->info.bits.count) {
new->info.bits.bit = calloc(new->info.bits.count, sizeof *new->info.bits.bit);
LY_CHECK_ERR_RETURN(!new->info.bits.bit, LOGMEM(mod->ctx), -1);
for (u = 0; u < new->info.bits.count; u++) {
new->info.bits.bit[u].name = lydict_insert(mod->ctx, old->info.bits.bit[u].name, 0);
new->info.bits.bit[u].dsc = lydict_insert(mod->ctx, old->info.bits.bit[u].dsc, 0);
new->info.bits.bit[u].ref = lydict_insert(mod->ctx, old->info.bits.bit[u].ref, 0);
new->info.bits.bit[u].flags = old->info.bits.bit[u].flags;
new->info.bits.bit[u].pos = old->info.bits.bit[u].pos;
new->info.bits.bit[u].ext_size = old->info.bits.bit[u].ext_size;
if (lys_ext_dup(mod->ctx, mod, old->info.bits.bit[u].ext, old->info.bits.bit[u].ext_size,
&new->info.bits.bit[u], LYEXT_PAR_TYPE_BIT,
&new->info.bits.bit[u].ext, shallow, unres)) {
return -1;
}
}
}
break;
case LY_TYPE_DEC64:
new->info.dec64.dig = old->info.dec64.dig;
new->info.dec64.div = old->info.dec64.div;
if (old->info.dec64.range) {
new->info.dec64.range = lys_restr_dup(mod, old->info.dec64.range, 1, shallow, unres);
}
break;
case LY_TYPE_ENUM:
new->info.enums.count = old->info.enums.count;
if (new->info.enums.count) {
new->info.enums.enm = calloc(new->info.enums.count, sizeof *new->info.enums.enm);
LY_CHECK_ERR_RETURN(!new->info.enums.enm, LOGMEM(mod->ctx), -1);
for (u = 0; u < new->info.enums.count; u++) {
new->info.enums.enm[u].name = lydict_insert(mod->ctx, old->info.enums.enm[u].name, 0);
new->info.enums.enm[u].dsc = lydict_insert(mod->ctx, old->info.enums.enm[u].dsc, 0);
new->info.enums.enm[u].ref = lydict_insert(mod->ctx, old->info.enums.enm[u].ref, 0);
new->info.enums.enm[u].flags = old->info.enums.enm[u].flags;
new->info.enums.enm[u].value = old->info.enums.enm[u].value;
new->info.enums.enm[u].ext_size = old->info.enums.enm[u].ext_size;
if (lys_ext_dup(mod->ctx, mod, old->info.enums.enm[u].ext, old->info.enums.enm[u].ext_size,
&new->info.enums.enm[u], LYEXT_PAR_TYPE_ENUM,
&new->info.enums.enm[u].ext, shallow, unres)) {
return -1;
}
}
}
break;
case LY_TYPE_IDENT:
new->info.ident.count = old->info.ident.count;
if (old->info.ident.count) {
new->info.ident.ref = malloc(old->info.ident.count * sizeof *new->info.ident.ref);
LY_CHECK_ERR_RETURN(!new->info.ident.ref, LOGMEM(mod->ctx), -1);
memcpy(new->info.ident.ref, old->info.ident.ref, old->info.ident.count * sizeof *new->info.ident.ref);
} else {
/* there can be several unresolved base identities, duplicate them all */
i = -1;
do {
i = unres_schema_find(unres, i, old, UNRES_TYPE_IDENTREF);
if (i != -1) {
if (unres_schema_add_str(mod, unres, new, UNRES_TYPE_IDENTREF, unres->str_snode[i]) == -1) {
return -1;
}
}
--i;
} while (i > -1);
}
break;
case LY_TYPE_INST:
new->info.inst.req = old->info.inst.req;
break;
case LY_TYPE_INT8:
case LY_TYPE_INT16:
case LY_TYPE_INT32:
case LY_TYPE_INT64:
case LY_TYPE_UINT8:
case LY_TYPE_UINT16:
case LY_TYPE_UINT32:
case LY_TYPE_UINT64:
if (old->info.num.range) {
new->info.num.range = lys_restr_dup(mod, old->info.num.range, 1, shallow, unres);
}
break;
case LY_TYPE_LEAFREF:
if (old->info.lref.path) {
new->info.lref.path = lydict_insert(mod->ctx, old->info.lref.path, 0);
new->info.lref.req = old->info.lref.req;
if (!in_grp && unres_schema_add_node(mod, unres, new, UNRES_TYPE_LEAFREF, parent) == -1) {
return -1;
}
}
break;
case LY_TYPE_STRING:
if (old->info.str.length) {
new->info.str.length = lys_restr_dup(mod, old->info.str.length, 1, shallow, unres);
}
if (old->info.str.pat_count) {
new->info.str.patterns = lys_restr_dup(mod, old->info.str.patterns, old->info.str.pat_count, shallow, unres);
new->info.str.pat_count = old->info.str.pat_count;
#ifdef LY_ENABLED_CACHE
if (!in_grp) {
new->info.str.patterns_pcre = malloc(new->info.str.pat_count * 2 * sizeof *new->info.str.patterns_pcre);
LY_CHECK_ERR_RETURN(!new->info.str.patterns_pcre, LOGMEM(mod->ctx), -1);
for (u = 0; u < new->info.str.pat_count; u++) {
if (lyp_precompile_pattern(mod->ctx, &new->info.str.patterns[u].expr[1],
(pcre**)&new->info.str.patterns_pcre[2 * u],
(pcre_extra**)&new->info.str.patterns_pcre[2 * u + 1])) {
free(new->info.str.patterns_pcre);
new->info.str.patterns_pcre = NULL;
return -1;
}
}
}
#endif
}
break;
case LY_TYPE_UNION:
new->info.uni.has_ptr_type = old->info.uni.has_ptr_type;
new->info.uni.count = old->info.uni.count;
if (new->info.uni.count) {
new->info.uni.types = calloc(new->info.uni.count, sizeof *new->info.uni.types);
LY_CHECK_ERR_RETURN(!new->info.uni.types, LOGMEM(mod->ctx), -1);
for (u = 0; u < new->info.uni.count; u++) {
if (lys_type_dup(mod, parent, &(new->info.uni.types[u]), &(old->info.uni.types[u]), in_grp,
shallow, unres)) {
return -1;
}
}
}
break;
default:
/* nothing to do for LY_TYPE_BOOL, LY_TYPE_EMPTY */
break;
}
return EXIT_SUCCESS;
}
struct yang_type *
lys_yang_type_dup(struct lys_module *module, struct lys_node *parent, struct yang_type *old, struct lys_type *type,
int in_grp, int shallow, struct unres_schema *unres)
{
struct yang_type *new;
new = calloc(1, sizeof *new);
LY_CHECK_ERR_RETURN(!new, LOGMEM(module->ctx), NULL);
new->flags = old->flags;
new->base = old->base;
new->name = lydict_insert(module->ctx, old->name, 0);
new->type = type;
if (!new->name) {
LOGMEM(module->ctx);
goto error;
}
if (type_dup(module, parent, type, old->type, new->base, in_grp, shallow, unres)) {
new->type->base = new->base;
lys_type_free(module->ctx, new->type, NULL);
memset(&new->type->info, 0, sizeof new->type->info);
goto error;
}
return new;
error:
free(new);
return NULL;
}
int
lys_copy_union_leafrefs(struct lys_module *mod, struct lys_node *parent, struct lys_type *type, struct lys_type *prev_new,
struct unres_schema *unres)
{
struct lys_type new;
unsigned int i, top_type;
struct lys_ext_instance **ext;
uint8_t ext_size;
void *reloc;
if (!prev_new) {
/* this is the "top-level" type, meaning it is a real type and no typedef directly above */
top_type = 1;
memset(&new, 0, sizeof new);
new.base = type->base;
new.parent = (struct lys_tpdf *)parent;
prev_new = &new;
} else {
/* this is not top-level type, just a type of a typedef */
top_type = 0;
}
assert(type->der);
if (type->der->module) {
/* typedef, skip it, but keep the extensions */
ext_size = type->ext_size;
if (lys_ext_dup(mod->ctx, mod, type->ext, type->ext_size, prev_new, LYEXT_PAR_TYPE, &ext, 0, unres)) {
return -1;
}
if (prev_new->ext) {
reloc = realloc(prev_new->ext, (prev_new->ext_size + ext_size) * sizeof *prev_new->ext);
LY_CHECK_ERR_RETURN(!reloc, LOGMEM(mod->ctx), -1);
prev_new->ext = reloc;
memcpy(prev_new->ext + prev_new->ext_size, ext, ext_size * sizeof *ext);
free(ext);
prev_new->ext_size += ext_size;
} else {
prev_new->ext = ext;
prev_new->ext_size = ext_size;
}
if (lys_copy_union_leafrefs(mod, parent, &type->der->type, prev_new, unres)) {
return -1;
}
} else {
/* type, just make a deep copy */
switch (type->base) {
case LY_TYPE_UNION:
prev_new->info.uni.has_ptr_type = type->info.uni.has_ptr_type;
prev_new->info.uni.count = type->info.uni.count;
/* this cannot be a typedef anymore */
assert(prev_new->info.uni.count);
prev_new->info.uni.types = calloc(prev_new->info.uni.count, sizeof *prev_new->info.uni.types);
LY_CHECK_ERR_RETURN(!prev_new->info.uni.types, LOGMEM(mod->ctx), -1);
for (i = 0; i < prev_new->info.uni.count; i++) {
if (lys_copy_union_leafrefs(mod, parent, &(type->info.uni.types[i]), &(prev_new->info.uni.types[i]), unres)) {
return -1;
}
}
prev_new->der = type->der;
break;
default:
if (lys_type_dup(mod, parent, prev_new, type, 0, 0, unres)) {
return -1;
}
break;
}
}
if (top_type) {
memcpy(type, prev_new, sizeof *type);
}
return EXIT_SUCCESS;
}
API const void *
lys_ext_instance_substmt(const struct lys_ext_instance *ext)
{
if (!ext) {
return NULL;
}
switch (ext->insubstmt) {
case LYEXT_SUBSTMT_SELF:
case LYEXT_SUBSTMT_MODIFIER:
case LYEXT_SUBSTMT_VERSION:
return NULL;
case LYEXT_SUBSTMT_ARGUMENT:
if (ext->parent_type == LYEXT_PAR_EXT) {
return ((struct lys_ext_instance*)ext->parent)->arg_value;
}
break;
case LYEXT_SUBSTMT_BASE:
if (ext->parent_type == LYEXT_PAR_TYPE) {
return ((struct lys_type*)ext->parent)->info.ident.ref[ext->insubstmt_index];
} else if (ext->parent_type == LYEXT_PAR_IDENT) {
return ((struct lys_ident*)ext->parent)->base[ext->insubstmt_index];
}
break;
case LYEXT_SUBSTMT_BELONGSTO:
if (ext->parent_type == LYEXT_PAR_MODULE && ((struct lys_module*)ext->parent)->type) {
return ((struct lys_submodule*)ext->parent)->belongsto;
}
break;
case LYEXT_SUBSTMT_CONFIG:
case LYEXT_SUBSTMT_MANDATORY:
if (ext->parent_type == LYEXT_PAR_NODE) {
return &((struct lys_node*)ext->parent)->flags;
} else if (ext->parent_type == LYEXT_PAR_DEVIATE) {
return &((struct lys_deviate*)ext->parent)->flags;
} else if (ext->parent_type == LYEXT_PAR_REFINE) {
return &((struct lys_refine*)ext->parent)->flags;
}
break;
case LYEXT_SUBSTMT_CONTACT:
if (ext->parent_type == LYEXT_PAR_MODULE) {
return ((struct lys_module*)ext->parent)->contact;
}
break;
case LYEXT_SUBSTMT_DEFAULT:
if (ext->parent_type == LYEXT_PAR_NODE) {
switch (((struct lys_node*)ext->parent)->nodetype) {
case LYS_LEAF:
case LYS_LEAFLIST:
/* in case of leaf, the index is supposed to be 0, so it will return the
* correct pointer despite the leaf structure does not have dflt as array */
return ((struct lys_node_leaflist*)ext->parent)->dflt[ext->insubstmt_index];
case LYS_CHOICE:
return ((struct lys_node_choice*)ext->parent)->dflt;
default:
/* internal error */
break;
}
} else if (ext->parent_type == LYEXT_PAR_TPDF) {
return ((struct lys_tpdf*)ext->parent)->dflt;
} else if (ext->parent_type == LYEXT_PAR_DEVIATE) {
return ((struct lys_deviate*)ext->parent)->dflt[ext->insubstmt_index];
} else if (ext->parent_type == LYEXT_PAR_REFINE) {
return &((struct lys_refine*)ext->parent)->dflt[ext->insubstmt_index];
}
break;
case LYEXT_SUBSTMT_DESCRIPTION:
switch (ext->parent_type) {
case LYEXT_PAR_NODE:
return ((struct lys_node*)ext->parent)->dsc;
case LYEXT_PAR_MODULE:
return ((struct lys_module*)ext->parent)->dsc;
case LYEXT_PAR_IMPORT:
return ((struct lys_import*)ext->parent)->dsc;
case LYEXT_PAR_INCLUDE:
return ((struct lys_include*)ext->parent)->dsc;
case LYEXT_PAR_EXT:
return ((struct lys_ext*)ext->parent)->dsc;
case LYEXT_PAR_FEATURE:
return ((struct lys_feature*)ext->parent)->dsc;
case LYEXT_PAR_TPDF:
return ((struct lys_tpdf*)ext->parent)->dsc;
case LYEXT_PAR_TYPE_BIT:
return ((struct lys_type_bit*)ext->parent)->dsc;
case LYEXT_PAR_TYPE_ENUM:
return ((struct lys_type_enum*)ext->parent)->dsc;
case LYEXT_PAR_RESTR:
return ((struct lys_restr*)ext->parent)->dsc;
case LYEXT_PAR_WHEN:
return ((struct lys_when*)ext->parent)->dsc;
case LYEXT_PAR_IDENT:
return ((struct lys_ident*)ext->parent)->dsc;
case LYEXT_PAR_DEVIATION:
return ((struct lys_deviation*)ext->parent)->dsc;
case LYEXT_PAR_REVISION:
return ((struct lys_revision*)ext->parent)->dsc;
case LYEXT_PAR_REFINE:
return ((struct lys_refine*)ext->parent)->dsc;
default:
break;
}
break;
case LYEXT_SUBSTMT_ERRTAG:
if (ext->parent_type == LYEXT_PAR_RESTR) {
return ((struct lys_restr*)ext->parent)->eapptag;
}
break;
case LYEXT_SUBSTMT_ERRMSG:
if (ext->parent_type == LYEXT_PAR_RESTR) {
return ((struct lys_restr*)ext->parent)->emsg;
}
break;
case LYEXT_SUBSTMT_DIGITS:
if (ext->parent_type == LYEXT_PAR_TYPE && ((struct lys_type*)ext->parent)->base == LY_TYPE_DEC64) {
return &((struct lys_type*)ext->parent)->info.dec64.dig;
}
break;
case LYEXT_SUBSTMT_KEY:
if (ext->parent_type == LYEXT_PAR_NODE && ((struct lys_node*)ext->parent)->nodetype == LYS_LIST) {
return ((struct lys_node_list*)ext->parent)->keys;
}
break;
case LYEXT_SUBSTMT_MAX:
if (ext->parent_type == LYEXT_PAR_NODE) {
if (((struct lys_node*)ext->parent)->nodetype == LYS_LIST) {
return &((struct lys_node_list*)ext->parent)->max;
} else if (((struct lys_node*)ext->parent)->nodetype == LYS_LEAFLIST) {
return &((struct lys_node_leaflist*)ext->parent)->max;
}
} else if (ext->parent_type == LYEXT_PAR_REFINE) {
return &((struct lys_refine*)ext->parent)->mod.list.max;
}
break;
case LYEXT_SUBSTMT_MIN:
if (ext->parent_type == LYEXT_PAR_NODE) {
if (((struct lys_node*)ext->parent)->nodetype == LYS_LIST) {
return &((struct lys_node_list*)ext->parent)->min;
} else if (((struct lys_node*)ext->parent)->nodetype == LYS_LEAFLIST) {
return &((struct lys_node_leaflist*)ext->parent)->min;
}
} else if (ext->parent_type == LYEXT_PAR_REFINE) {
return &((struct lys_refine*)ext->parent)->mod.list.min;
}
break;
case LYEXT_SUBSTMT_NAMESPACE:
if (ext->parent_type == LYEXT_PAR_MODULE && !((struct lys_module*)ext->parent)->type) {
return ((struct lys_module*)ext->parent)->ns;
}
break;
case LYEXT_SUBSTMT_ORDEREDBY:
if (ext->parent_type == LYEXT_PAR_NODE &&
(((struct lys_node*)ext->parent)->nodetype & (LYS_LIST | LYS_LEAFLIST))) {
return &((struct lys_node_list*)ext->parent)->flags;
}
break;
case LYEXT_SUBSTMT_ORGANIZATION:
if (ext->parent_type == LYEXT_PAR_MODULE) {
return ((struct lys_module*)ext->parent)->org;
}
break;
case LYEXT_SUBSTMT_PATH:
if (ext->parent_type == LYEXT_PAR_TYPE && ((struct lys_type*)ext->parent)->base == LY_TYPE_LEAFREF) {
return ((struct lys_type*)ext->parent)->info.lref.path;
}
break;
case LYEXT_SUBSTMT_POSITION:
if (ext->parent_type == LYEXT_PAR_TYPE_BIT) {
return &((struct lys_type_bit*)ext->parent)->pos;
}
break;
case LYEXT_SUBSTMT_PREFIX:
if (ext->parent_type == LYEXT_PAR_MODULE) {
/* covers also lys_submodule */
return ((struct lys_module*)ext->parent)->prefix;
} else if (ext->parent_type == LYEXT_PAR_IMPORT) {
return ((struct lys_import*)ext->parent)->prefix;
}
break;
case LYEXT_SUBSTMT_PRESENCE:
if (ext->parent_type == LYEXT_PAR_NODE && ((struct lys_node*)ext->parent)->nodetype == LYS_CONTAINER) {
return ((struct lys_node_container*)ext->parent)->presence;
} else if (ext->parent_type == LYEXT_PAR_REFINE) {
return ((struct lys_refine*)ext->parent)->mod.presence;
}
break;
case LYEXT_SUBSTMT_REFERENCE:
switch (ext->parent_type) {
case LYEXT_PAR_NODE:
return ((struct lys_node*)ext->parent)->ref;
case LYEXT_PAR_MODULE:
return ((struct lys_module*)ext->parent)->ref;
case LYEXT_PAR_IMPORT:
return ((struct lys_import*)ext->parent)->ref;
case LYEXT_PAR_INCLUDE:
return ((struct lys_include*)ext->parent)->ref;
case LYEXT_PAR_EXT:
return ((struct lys_ext*)ext->parent)->ref;
case LYEXT_PAR_FEATURE:
return ((struct lys_feature*)ext->parent)->ref;
case LYEXT_PAR_TPDF:
return ((struct lys_tpdf*)ext->parent)->ref;
case LYEXT_PAR_TYPE_BIT:
return ((struct lys_type_bit*)ext->parent)->ref;
case LYEXT_PAR_TYPE_ENUM:
return ((struct lys_type_enum*)ext->parent)->ref;
case LYEXT_PAR_RESTR:
return ((struct lys_restr*)ext->parent)->ref;
case LYEXT_PAR_WHEN:
return ((struct lys_when*)ext->parent)->ref;
case LYEXT_PAR_IDENT:
return ((struct lys_ident*)ext->parent)->ref;
case LYEXT_PAR_DEVIATION:
return ((struct lys_deviation*)ext->parent)->ref;
case LYEXT_PAR_REVISION:
return ((struct lys_revision*)ext->parent)->ref;
case LYEXT_PAR_REFINE:
return ((struct lys_refine*)ext->parent)->ref;
default:
break;
}
break;
case LYEXT_SUBSTMT_REQINSTANCE:
if (ext->parent_type == LYEXT_PAR_TYPE) {
if (((struct lys_type*)ext->parent)->base == LY_TYPE_LEAFREF) {
return &((struct lys_type*)ext->parent)->info.lref.req;
} else if (((struct lys_type*)ext->parent)->base == LY_TYPE_INST) {
return &((struct lys_type*)ext->parent)->info.inst.req;
}
}
break;
case LYEXT_SUBSTMT_REVISIONDATE:
if (ext->parent_type == LYEXT_PAR_IMPORT) {
return ((struct lys_import*)ext->parent)->rev;
} else if (ext->parent_type == LYEXT_PAR_INCLUDE) {
return ((struct lys_include*)ext->parent)->rev;
}
break;
case LYEXT_SUBSTMT_STATUS:
switch (ext->parent_type) {
case LYEXT_PAR_NODE:
case LYEXT_PAR_IDENT:
case LYEXT_PAR_TPDF:
case LYEXT_PAR_EXT:
case LYEXT_PAR_FEATURE:
case LYEXT_PAR_TYPE_ENUM:
case LYEXT_PAR_TYPE_BIT:
/* in all structures the flags member is at the same offset */
return &((struct lys_node*)ext->parent)->flags;
default:
break;
}
break;
case LYEXT_SUBSTMT_UNIQUE:
if (ext->parent_type == LYEXT_PAR_DEVIATE) {
return &((struct lys_deviate*)ext->parent)->unique[ext->insubstmt_index];
} else if (ext->parent_type == LYEXT_PAR_NODE && ((struct lys_node*)ext->parent)->nodetype == LYS_LIST) {
return &((struct lys_node_list*)ext->parent)->unique[ext->insubstmt_index];
}
break;
case LYEXT_SUBSTMT_UNITS:
if (ext->parent_type == LYEXT_PAR_NODE &&
(((struct lys_node*)ext->parent)->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
/* units is at the same offset in both lys_node_leaf and lys_node_leaflist */
return ((struct lys_node_leaf*)ext->parent)->units;
} else if (ext->parent_type == LYEXT_PAR_TPDF) {
return ((struct lys_tpdf*)ext->parent)->units;
} else if (ext->parent_type == LYEXT_PAR_DEVIATE) {
return ((struct lys_deviate*)ext->parent)->units;
}
break;
case LYEXT_SUBSTMT_VALUE:
if (ext->parent_type == LYEXT_PAR_TYPE_ENUM) {
return &((struct lys_type_enum*)ext->parent)->value;
}
break;
case LYEXT_SUBSTMT_YINELEM:
if (ext->parent_type == LYEXT_PAR_EXT) {
return &((struct lys_ext*)ext->parent)->flags;
}
break;
}
LOGINT(ext->module->ctx);
return NULL;
}
static int
lys_type_dup(struct lys_module *mod, struct lys_node *parent, struct lys_type *new, struct lys_type *old,
int in_grp, int shallow, struct unres_schema *unres)
{
int i;
new->base = old->base;
new->der = old->der;
new->parent = (struct lys_tpdf *)parent;
new->ext_size = old->ext_size;
if (lys_ext_dup(mod->ctx, mod, old->ext, old->ext_size, new, LYEXT_PAR_TYPE, &new->ext, shallow, unres)) {
return -1;
}
i = unres_schema_find(unres, -1, old, UNRES_TYPE_DER);
if (i != -1) {
/* HACK (serious one) for unres */
/* nothing else we can do but duplicate it immediately */
if (((struct lyxml_elem *)old->der)->flags & LY_YANG_STRUCTURE_FLAG) {
new->der = (struct lys_tpdf *)lys_yang_type_dup(mod, parent, (struct yang_type *)old->der, new, in_grp,
shallow, unres);
} else {
new->der = (struct lys_tpdf *)lyxml_dup_elem(mod->ctx, (struct lyxml_elem *)old->der, NULL, 1);
}
/* all these unres additions can fail even though they did not before */
if (!new->der || (unres_schema_add_node(mod, unres, new, UNRES_TYPE_DER, parent) == -1)) {
return -1;
}
return EXIT_SUCCESS;
}
return type_dup(mod, parent, new, old, new->base, in_grp, shallow, unres);
}
void
lys_type_free(struct ly_ctx *ctx, struct lys_type *type,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
unsigned int i;
assert(ctx);
if (!type) {
return;
}
lys_extension_instances_free(ctx, type->ext, type->ext_size, private_destructor);
switch (type->base) {
case LY_TYPE_BINARY:
lys_restr_free(ctx, type->info.binary.length, private_destructor);
free(type->info.binary.length);
break;
case LY_TYPE_BITS:
for (i = 0; i < type->info.bits.count; i++) {
lydict_remove(ctx, type->info.bits.bit[i].name);
lydict_remove(ctx, type->info.bits.bit[i].dsc);
lydict_remove(ctx, type->info.bits.bit[i].ref);
lys_iffeature_free(ctx, type->info.bits.bit[i].iffeature, type->info.bits.bit[i].iffeature_size, 0,
private_destructor);
lys_extension_instances_free(ctx, type->info.bits.bit[i].ext, type->info.bits.bit[i].ext_size,
private_destructor);
}
free(type->info.bits.bit);
break;
case LY_TYPE_DEC64:
lys_restr_free(ctx, type->info.dec64.range, private_destructor);
free(type->info.dec64.range);
break;
case LY_TYPE_ENUM:
for (i = 0; i < type->info.enums.count; i++) {
lydict_remove(ctx, type->info.enums.enm[i].name);
lydict_remove(ctx, type->info.enums.enm[i].dsc);
lydict_remove(ctx, type->info.enums.enm[i].ref);
lys_iffeature_free(ctx, type->info.enums.enm[i].iffeature, type->info.enums.enm[i].iffeature_size, 0,
private_destructor);
lys_extension_instances_free(ctx, type->info.enums.enm[i].ext, type->info.enums.enm[i].ext_size,
private_destructor);
}
free(type->info.enums.enm);
break;
case LY_TYPE_INT8:
case LY_TYPE_INT16:
case LY_TYPE_INT32:
case LY_TYPE_INT64:
case LY_TYPE_UINT8:
case LY_TYPE_UINT16:
case LY_TYPE_UINT32:
case LY_TYPE_UINT64:
lys_restr_free(ctx, type->info.num.range, private_destructor);
free(type->info.num.range);
break;
case LY_TYPE_LEAFREF:
lydict_remove(ctx, type->info.lref.path);
break;
case LY_TYPE_STRING:
lys_restr_free(ctx, type->info.str.length, private_destructor);
free(type->info.str.length);
for (i = 0; i < type->info.str.pat_count; i++) {
lys_restr_free(ctx, &type->info.str.patterns[i], private_destructor);
#ifdef LY_ENABLED_CACHE
if (type->info.str.patterns_pcre) {
pcre_free((pcre*)type->info.str.patterns_pcre[2 * i]);
pcre_free_study((pcre_extra*)type->info.str.patterns_pcre[2 * i + 1]);
}
#endif
}
free(type->info.str.patterns);
#ifdef LY_ENABLED_CACHE
free(type->info.str.patterns_pcre);
#endif
break;
case LY_TYPE_UNION:
for (i = 0; i < type->info.uni.count; i++) {
lys_type_free(ctx, &type->info.uni.types[i], private_destructor);
}
free(type->info.uni.types);
break;
case LY_TYPE_IDENT:
free(type->info.ident.ref);
break;
default:
/* nothing to do for LY_TYPE_INST, LY_TYPE_BOOL, LY_TYPE_EMPTY */
break;
}
}
static void
lys_tpdf_free(struct ly_ctx *ctx, struct lys_tpdf *tpdf,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
assert(ctx);
if (!tpdf) {
return;
}
lydict_remove(ctx, tpdf->name);
lydict_remove(ctx, tpdf->dsc);
lydict_remove(ctx, tpdf->ref);
lys_type_free(ctx, &tpdf->type, private_destructor);
lydict_remove(ctx, tpdf->units);
lydict_remove(ctx, tpdf->dflt);
lys_extension_instances_free(ctx, tpdf->ext, tpdf->ext_size, private_destructor);
}
static struct lys_when *
lys_when_dup(struct lys_module *mod, struct lys_when *old, int shallow, struct unres_schema *unres)
{
struct lys_when *new;
if (!old) {
return NULL;
}
new = calloc(1, sizeof *new);
LY_CHECK_ERR_RETURN(!new, LOGMEM(mod->ctx), NULL);
new->cond = lydict_insert(mod->ctx, old->cond, 0);
new->dsc = lydict_insert(mod->ctx, old->dsc, 0);
new->ref = lydict_insert(mod->ctx, old->ref, 0);
new->ext_size = old->ext_size;
lys_ext_dup(mod->ctx, mod, old->ext, old->ext_size, new, LYEXT_PAR_WHEN, &new->ext, shallow, unres);
return new;
}
void
lys_when_free(struct ly_ctx *ctx, struct lys_when *w,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
if (!w) {
return;
}
lys_extension_instances_free(ctx, w->ext, w->ext_size, private_destructor);
lydict_remove(ctx, w->cond);
lydict_remove(ctx, w->dsc);
lydict_remove(ctx, w->ref);
free(w);
}
static void
lys_augment_free(struct ly_ctx *ctx, struct lys_node_augment *aug,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
struct lys_node *next, *sub;
/* children from a resolved augment are freed under the target node */
if (!aug->target || (aug->flags & LYS_NOTAPPLIED)) {
LY_TREE_FOR_SAFE(aug->child, next, sub) {
lys_node_free(sub, private_destructor, 0);
}
}
lydict_remove(ctx, aug->target_name);
lydict_remove(ctx, aug->dsc);
lydict_remove(ctx, aug->ref);
lys_iffeature_free(ctx, aug->iffeature, aug->iffeature_size, 0, private_destructor);
lys_extension_instances_free(ctx, aug->ext, aug->ext_size, private_destructor);
lys_when_free(ctx, aug->when, private_destructor);
}
static void
lys_ident_free(struct ly_ctx *ctx, struct lys_ident *ident,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
assert(ctx);
if (!ident) {
return;
}
free(ident->base);
ly_set_free(ident->der);
lydict_remove(ctx, ident->name);
lydict_remove(ctx, ident->dsc);
lydict_remove(ctx, ident->ref);
lys_iffeature_free(ctx, ident->iffeature, ident->iffeature_size, 0, private_destructor);
lys_extension_instances_free(ctx, ident->ext, ident->ext_size, private_destructor);
}
static void
lys_grp_free(struct ly_ctx *ctx, struct lys_node_grp *grp,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i;
/* handle only specific parts for LYS_GROUPING */
for (i = 0; i < grp->tpdf_size; i++) {
lys_tpdf_free(ctx, &grp->tpdf[i], private_destructor);
}
free(grp->tpdf);
}
static void
lys_rpc_action_free(struct ly_ctx *ctx, struct lys_node_rpc_action *rpc_act,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i;
/* handle only specific parts for LYS_GROUPING */
for (i = 0; i < rpc_act->tpdf_size; i++) {
lys_tpdf_free(ctx, &rpc_act->tpdf[i], private_destructor);
}
free(rpc_act->tpdf);
}
static void
lys_inout_free(struct ly_ctx *ctx, struct lys_node_inout *io,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i;
/* handle only specific parts for LYS_INPUT and LYS_OUTPUT */
for (i = 0; i < io->tpdf_size; i++) {
lys_tpdf_free(ctx, &io->tpdf[i], private_destructor);
}
free(io->tpdf);
for (i = 0; i < io->must_size; i++) {
lys_restr_free(ctx, &io->must[i], private_destructor);
}
free(io->must);
}
static void
lys_notif_free(struct ly_ctx *ctx, struct lys_node_notif *notif,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i;
for (i = 0; i < notif->must_size; i++) {
lys_restr_free(ctx, ¬if->must[i], private_destructor);
}
free(notif->must);
for (i = 0; i < notif->tpdf_size; i++) {
lys_tpdf_free(ctx, ¬if->tpdf[i], private_destructor);
}
free(notif->tpdf);
}
static void
lys_anydata_free(struct ly_ctx *ctx, struct lys_node_anydata *anyxml,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i;
for (i = 0; i < anyxml->must_size; i++) {
lys_restr_free(ctx, &anyxml->must[i], private_destructor);
}
free(anyxml->must);
lys_when_free(ctx, anyxml->when, private_destructor);
}
static void
lys_leaf_free(struct ly_ctx *ctx, struct lys_node_leaf *leaf,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i;
/* leafref backlinks */
ly_set_free((struct ly_set *)leaf->backlinks);
for (i = 0; i < leaf->must_size; i++) {
lys_restr_free(ctx, &leaf->must[i], private_destructor);
}
free(leaf->must);
lys_when_free(ctx, leaf->when, private_destructor);
lys_type_free(ctx, &leaf->type, private_destructor);
lydict_remove(ctx, leaf->units);
lydict_remove(ctx, leaf->dflt);
}
static void
lys_leaflist_free(struct ly_ctx *ctx, struct lys_node_leaflist *llist,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i;
if (llist->backlinks) {
/* leafref backlinks */
ly_set_free(llist->backlinks);
}
for (i = 0; i < llist->must_size; i++) {
lys_restr_free(ctx, &llist->must[i], private_destructor);
}
free(llist->must);
for (i = 0; i < llist->dflt_size; i++) {
lydict_remove(ctx, llist->dflt[i]);
}
free(llist->dflt);
lys_when_free(ctx, llist->when, private_destructor);
lys_type_free(ctx, &llist->type, private_destructor);
lydict_remove(ctx, llist->units);
}
static void
lys_list_free(struct ly_ctx *ctx, struct lys_node_list *list,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i, j;
/* handle only specific parts for LY_NODE_LIST */
lys_when_free(ctx, list->when, private_destructor);
for (i = 0; i < list->must_size; i++) {
lys_restr_free(ctx, &list->must[i], private_destructor);
}
free(list->must);
for (i = 0; i < list->tpdf_size; i++) {
lys_tpdf_free(ctx, &list->tpdf[i], private_destructor);
}
free(list->tpdf);
free(list->keys);
for (i = 0; i < list->unique_size; i++) {
for (j = 0; j < list->unique[i].expr_size; j++) {
lydict_remove(ctx, list->unique[i].expr[j]);
}
free(list->unique[i].expr);
}
free(list->unique);
lydict_remove(ctx, list->keys_str);
}
static void
lys_container_free(struct ly_ctx *ctx, struct lys_node_container *cont,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i;
/* handle only specific parts for LY_NODE_CONTAINER */
lydict_remove(ctx, cont->presence);
for (i = 0; i < cont->tpdf_size; i++) {
lys_tpdf_free(ctx, &cont->tpdf[i], private_destructor);
}
free(cont->tpdf);
for (i = 0; i < cont->must_size; i++) {
lys_restr_free(ctx, &cont->must[i], private_destructor);
}
free(cont->must);
lys_when_free(ctx, cont->when, private_destructor);
}
static void
lys_feature_free(struct ly_ctx *ctx, struct lys_feature *f,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
lydict_remove(ctx, f->name);
lydict_remove(ctx, f->dsc);
lydict_remove(ctx, f->ref);
lys_iffeature_free(ctx, f->iffeature, f->iffeature_size, 0, private_destructor);
ly_set_free(f->depfeatures);
lys_extension_instances_free(ctx, f->ext, f->ext_size, private_destructor);
}
static void
lys_extension_free(struct ly_ctx *ctx, struct lys_ext *e,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
lydict_remove(ctx, e->name);
lydict_remove(ctx, e->dsc);
lydict_remove(ctx, e->ref);
lydict_remove(ctx, e->argument);
lys_extension_instances_free(ctx, e->ext, e->ext_size, private_destructor);
}
static void
lys_deviation_free(struct lys_module *module, struct lys_deviation *dev,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i, j, k;
struct ly_ctx *ctx;
struct lys_node *next, *elem;
ctx = module->ctx;
lydict_remove(ctx, dev->target_name);
lydict_remove(ctx, dev->dsc);
lydict_remove(ctx, dev->ref);
lys_extension_instances_free(ctx, dev->ext, dev->ext_size, private_destructor);
if (!dev->deviate) {
return;
}
/* it could not be applied because it failed to be applied */
if (dev->orig_node) {
/* the module was freed, but we only need the context from orig_node, use ours */
if (dev->deviate[0].mod == LY_DEVIATE_NO) {
/* it's actually a node subtree, we need to update modules on all the nodes :-/ */
LY_TREE_DFS_BEGIN(dev->orig_node, next, elem) {
elem->module = module;
LY_TREE_DFS_END(dev->orig_node, next, elem);
}
lys_node_free(dev->orig_node, NULL, 0);
} else {
/* it's just a shallow copy, freeing one node */
dev->orig_node->module = module;
lys_node_free(dev->orig_node, NULL, 1);
}
}
for (i = 0; i < dev->deviate_size; i++) {
lys_extension_instances_free(ctx, dev->deviate[i].ext, dev->deviate[i].ext_size, private_destructor);
for (j = 0; j < dev->deviate[i].dflt_size; j++) {
lydict_remove(ctx, dev->deviate[i].dflt[j]);
}
free(dev->deviate[i].dflt);
lydict_remove(ctx, dev->deviate[i].units);
if (dev->deviate[i].mod == LY_DEVIATE_DEL) {
for (j = 0; j < dev->deviate[i].must_size; j++) {
lys_restr_free(ctx, &dev->deviate[i].must[j], private_destructor);
}
free(dev->deviate[i].must);
for (j = 0; j < dev->deviate[i].unique_size; j++) {
for (k = 0; k < dev->deviate[i].unique[j].expr_size; k++) {
lydict_remove(ctx, dev->deviate[i].unique[j].expr[k]);
}
free(dev->deviate[i].unique[j].expr);
}
free(dev->deviate[i].unique);
}
}
free(dev->deviate);
}
static void
lys_uses_free(struct ly_ctx *ctx, struct lys_node_uses *uses,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i, j;
for (i = 0; i < uses->refine_size; i++) {
lydict_remove(ctx, uses->refine[i].target_name);
lydict_remove(ctx, uses->refine[i].dsc);
lydict_remove(ctx, uses->refine[i].ref);
lys_iffeature_free(ctx, uses->refine[i].iffeature, uses->refine[i].iffeature_size, 0, private_destructor);
for (j = 0; j < uses->refine[i].must_size; j++) {
lys_restr_free(ctx, &uses->refine[i].must[j], private_destructor);
}
free(uses->refine[i].must);
for (j = 0; j < uses->refine[i].dflt_size; j++) {
lydict_remove(ctx, uses->refine[i].dflt[j]);
}
free(uses->refine[i].dflt);
lys_extension_instances_free(ctx, uses->refine[i].ext, uses->refine[i].ext_size, private_destructor);
if (uses->refine[i].target_type & LYS_CONTAINER) {
lydict_remove(ctx, uses->refine[i].mod.presence);
}
}
free(uses->refine);
for (i = 0; i < uses->augment_size; i++) {
lys_augment_free(ctx, &uses->augment[i], private_destructor);
}
free(uses->augment);
lys_when_free(ctx, uses->when, private_destructor);
}
void
lys_node_free(struct lys_node *node, void (*private_destructor)(const struct lys_node *node, void *priv), int shallow)
{
struct ly_ctx *ctx;
struct lys_node *sub, *next;
if (!node) {
return;
}
assert(node->module);
assert(node->module->ctx);
ctx = node->module->ctx;
/* remove private object */
if (node->priv && private_destructor) {
private_destructor(node, node->priv);
}
/* common part */
lydict_remove(ctx, node->name);
if (!(node->nodetype & (LYS_INPUT | LYS_OUTPUT))) {
lys_iffeature_free(ctx, node->iffeature, node->iffeature_size, shallow, private_destructor);
lydict_remove(ctx, node->dsc);
lydict_remove(ctx, node->ref);
}
if (!shallow && !(node->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
LY_TREE_FOR_SAFE(node->child, next, sub) {
lys_node_free(sub, private_destructor, 0);
}
}
lys_extension_instances_free(ctx, node->ext, node->ext_size, private_destructor);
/* specific part */
switch (node->nodetype) {
case LYS_CONTAINER:
lys_container_free(ctx, (struct lys_node_container *)node, private_destructor);
break;
case LYS_CHOICE:
lys_when_free(ctx, ((struct lys_node_choice *)node)->when, private_destructor);
break;
case LYS_LEAF:
lys_leaf_free(ctx, (struct lys_node_leaf *)node, private_destructor);
break;
case LYS_LEAFLIST:
lys_leaflist_free(ctx, (struct lys_node_leaflist *)node, private_destructor);
break;
case LYS_LIST:
lys_list_free(ctx, (struct lys_node_list *)node, private_destructor);
break;
case LYS_ANYXML:
case LYS_ANYDATA:
lys_anydata_free(ctx, (struct lys_node_anydata *)node, private_destructor);
break;
case LYS_USES:
lys_uses_free(ctx, (struct lys_node_uses *)node, private_destructor);
break;
case LYS_CASE:
lys_when_free(ctx, ((struct lys_node_case *)node)->when, private_destructor);
break;
case LYS_AUGMENT:
/* do nothing */
break;
case LYS_GROUPING:
lys_grp_free(ctx, (struct lys_node_grp *)node, private_destructor);
break;
case LYS_RPC:
case LYS_ACTION:
lys_rpc_action_free(ctx, (struct lys_node_rpc_action *)node, private_destructor);
break;
case LYS_NOTIF:
lys_notif_free(ctx, (struct lys_node_notif *)node, private_destructor);
break;
case LYS_INPUT:
case LYS_OUTPUT:
lys_inout_free(ctx, (struct lys_node_inout *)node, private_destructor);
break;
case LYS_EXT:
case LYS_UNKNOWN:
LOGINT(ctx);
break;
}
/* again common part */
lys_node_unlink(node);
free(node);
}
API struct lys_module *
lys_implemented_module(const struct lys_module *mod)
{
struct ly_ctx *ctx;
int i;
if (!mod || mod->implemented) {
/* invalid argument or the module itself is implemented */
return (struct lys_module *)mod;
}
ctx = mod->ctx;
for (i = 0; i < ctx->models.used; i++) {
if (!ctx->models.list[i]->implemented) {
continue;
}
if (ly_strequal(mod->name, ctx->models.list[i]->name, 1)) {
/* we have some revision of the module implemented */
return ctx->models.list[i];
}
}
/* we have no revision of the module implemented, return the module itself,
* it is up to the caller to set the module implemented when needed */
return (struct lys_module *)mod;
}
/* free_int_mods - flag whether to free the internal modules as well */
static void
module_free_common(struct lys_module *module, void (*private_destructor)(const struct lys_node *node, void *priv))
{
struct ly_ctx *ctx;
struct lys_node *next, *iter;
unsigned int i;
assert(module->ctx);
ctx = module->ctx;
/* just free the import array, imported modules will stay in the context */
for (i = 0; i < module->imp_size; i++) {
lydict_remove(ctx, module->imp[i].prefix);
lydict_remove(ctx, module->imp[i].dsc);
lydict_remove(ctx, module->imp[i].ref);
lys_extension_instances_free(ctx, module->imp[i].ext, module->imp[i].ext_size, private_destructor);
}
free(module->imp);
/* submodules don't have data tree, the data nodes
* are placed in the main module altogether */
if (!module->type) {
LY_TREE_FOR_SAFE(module->data, next, iter) {
lys_node_free(iter, private_destructor, 0);
}
}
lydict_remove(ctx, module->dsc);
lydict_remove(ctx, module->ref);
lydict_remove(ctx, module->org);
lydict_remove(ctx, module->contact);
lydict_remove(ctx, module->filepath);
/* revisions */
for (i = 0; i < module->rev_size; i++) {
lys_extension_instances_free(ctx, module->rev[i].ext, module->rev[i].ext_size, private_destructor);
lydict_remove(ctx, module->rev[i].dsc);
lydict_remove(ctx, module->rev[i].ref);
}
free(module->rev);
/* identities */
for (i = 0; i < module->ident_size; i++) {
lys_ident_free(ctx, &module->ident[i], private_destructor);
}
module->ident_size = 0;
free(module->ident);
/* typedefs */
for (i = 0; i < module->tpdf_size; i++) {
lys_tpdf_free(ctx, &module->tpdf[i], private_destructor);
}
free(module->tpdf);
/* extension instances */
lys_extension_instances_free(ctx, module->ext, module->ext_size, private_destructor);
/* augment */
for (i = 0; i < module->augment_size; i++) {
lys_augment_free(ctx, &module->augment[i], private_destructor);
}
free(module->augment);
/* features */
for (i = 0; i < module->features_size; i++) {
lys_feature_free(ctx, &module->features[i], private_destructor);
}
free(module->features);
/* deviations */
for (i = 0; i < module->deviation_size; i++) {
lys_deviation_free(module, &module->deviation[i], private_destructor);
}
free(module->deviation);
/* extensions */
for (i = 0; i < module->extensions_size; i++) {
lys_extension_free(ctx, &module->extensions[i], private_destructor);
}
free(module->extensions);
lydict_remove(ctx, module->name);
lydict_remove(ctx, module->prefix);
}
void
lys_submodule_free(struct lys_submodule *submodule, void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i;
if (!submodule) {
return;
}
/* common part with struct ly_module */
module_free_common((struct lys_module *)submodule, private_destructor);
/* include */
for (i = 0; i < submodule->inc_size; i++) {
lydict_remove(submodule->ctx, submodule->inc[i].dsc);
lydict_remove(submodule->ctx, submodule->inc[i].ref);
lys_extension_instances_free(submodule->ctx, submodule->inc[i].ext, submodule->inc[i].ext_size, private_destructor);
/* complete submodule free is done only from main module since
* submodules propagate their includes to the main module */
}
free(submodule->inc);
free(submodule);
}
int
lys_ingrouping(const struct lys_node *node)
{
const struct lys_node *iter = node;
assert(node);
for(iter = node; iter && iter->nodetype != LYS_GROUPING; iter = lys_parent(iter));
if (!iter) {
return 0;
} else {
return 1;
}
}
/*
* final: 0 - do not change config flags; 1 - inherit config flags from the parent; 2 - remove config flags
*/
static struct lys_node *
lys_node_dup_recursion(struct lys_module *module, struct lys_node *parent, const struct lys_node *node,
struct unres_schema *unres, int shallow, int finalize)
{
struct lys_node *retval = NULL, *iter, *p;
struct ly_ctx *ctx = module->ctx;
int i, j, rc;
unsigned int size, size1, size2;
struct unres_list_uniq *unique_info;
uint16_t flags;
struct lys_node_container *cont = NULL;
struct lys_node_container *cont_orig = (struct lys_node_container *)node;
struct lys_node_choice *choice = NULL;
struct lys_node_choice *choice_orig = (struct lys_node_choice *)node;
struct lys_node_leaf *leaf = NULL;
struct lys_node_leaf *leaf_orig = (struct lys_node_leaf *)node;
struct lys_node_leaflist *llist = NULL;
struct lys_node_leaflist *llist_orig = (struct lys_node_leaflist *)node;
struct lys_node_list *list = NULL;
struct lys_node_list *list_orig = (struct lys_node_list *)node;
struct lys_node_anydata *any = NULL;
struct lys_node_anydata *any_orig = (struct lys_node_anydata *)node;
struct lys_node_uses *uses = NULL;
struct lys_node_uses *uses_orig = (struct lys_node_uses *)node;
struct lys_node_rpc_action *rpc = NULL;
struct lys_node_inout *io = NULL;
struct lys_node_notif *ntf = NULL;
struct lys_node_case *cs = NULL;
struct lys_node_case *cs_orig = (struct lys_node_case *)node;
/* we cannot just duplicate memory since the strings are stored in
* dictionary and we need to update dictionary counters.
*/
switch (node->nodetype) {
case LYS_CONTAINER:
cont = calloc(1, sizeof *cont);
retval = (struct lys_node *)cont;
break;
case LYS_CHOICE:
choice = calloc(1, sizeof *choice);
retval = (struct lys_node *)choice;
break;
case LYS_LEAF:
leaf = calloc(1, sizeof *leaf);
retval = (struct lys_node *)leaf;
break;
case LYS_LEAFLIST:
llist = calloc(1, sizeof *llist);
retval = (struct lys_node *)llist;
break;
case LYS_LIST:
list = calloc(1, sizeof *list);
retval = (struct lys_node *)list;
break;
case LYS_ANYXML:
case LYS_ANYDATA:
any = calloc(1, sizeof *any);
retval = (struct lys_node *)any;
break;
case LYS_USES:
uses = calloc(1, sizeof *uses);
retval = (struct lys_node *)uses;
break;
case LYS_CASE:
cs = calloc(1, sizeof *cs);
retval = (struct lys_node *)cs;
break;
case LYS_RPC:
case LYS_ACTION:
rpc = calloc(1, sizeof *rpc);
retval = (struct lys_node *)rpc;
break;
case LYS_INPUT:
case LYS_OUTPUT:
io = calloc(1, sizeof *io);
retval = (struct lys_node *)io;
break;
case LYS_NOTIF:
ntf = calloc(1, sizeof *ntf);
retval = (struct lys_node *)ntf;
break;
default:
LOGINT(ctx);
goto error;
}
LY_CHECK_ERR_RETURN(!retval, LOGMEM(ctx), NULL);
/*
* duplicate generic part of the structure
*/
retval->name = lydict_insert(ctx, node->name, 0);
retval->dsc = lydict_insert(ctx, node->dsc, 0);
retval->ref = lydict_insert(ctx, node->ref, 0);
retval->flags = node->flags;
retval->module = module;
retval->nodetype = node->nodetype;
retval->prev = retval;
retval->ext_size = node->ext_size;
if (lys_ext_dup(ctx, module, node->ext, node->ext_size, retval, LYEXT_PAR_NODE, &retval->ext, shallow, unres)) {
goto error;
}
if (node->iffeature_size) {
retval->iffeature_size = node->iffeature_size;
retval->iffeature = calloc(retval->iffeature_size, sizeof *retval->iffeature);
LY_CHECK_ERR_GOTO(!retval->iffeature, LOGMEM(ctx), error);
}
if (!shallow) {
for (i = 0; i < node->iffeature_size; ++i) {
resolve_iffeature_getsizes(&node->iffeature[i], &size1, &size2);
if (size1) {
/* there is something to duplicate */
/* duplicate compiled expression */
size = (size1 / 4) + (size1 % 4) ? 1 : 0;
retval->iffeature[i].expr = malloc(size * sizeof *retval->iffeature[i].expr);
LY_CHECK_ERR_GOTO(!retval->iffeature[i].expr, LOGMEM(ctx), error);
memcpy(retval->iffeature[i].expr, node->iffeature[i].expr, size * sizeof *retval->iffeature[i].expr);
/* list of feature pointer must be updated to point to the resulting tree */
retval->iffeature[i].features = calloc(size2, sizeof *retval->iffeature[i].features);
LY_CHECK_ERR_GOTO(!retval->iffeature[i].features, LOGMEM(ctx); free(retval->iffeature[i].expr), error);
for (j = 0; (unsigned int)j < size2; j++) {
rc = unres_schema_dup(module, unres, &node->iffeature[i].features[j], UNRES_IFFEAT,
&retval->iffeature[i].features[j]);
if (rc == EXIT_FAILURE) {
/* feature is resolved in origin, so copy it
* - duplication is used for instantiating groupings
* and if-feature inside grouping is supposed to be
* resolved inside the original grouping, so we want
* to keep pointers to features from the grouping
* context */
retval->iffeature[i].features[j] = node->iffeature[i].features[j];
} else if (rc == -1) {
goto error;
} /* else unres was duplicated */
}
}
/* duplicate if-feature's extensions */
retval->iffeature[i].ext_size = node->iffeature[i].ext_size;
if (lys_ext_dup(ctx, module, node->iffeature[i].ext, node->iffeature[i].ext_size,
&retval->iffeature[i], LYEXT_PAR_IFFEATURE, &retval->iffeature[i].ext, shallow, unres)) {
goto error;
}
}
/* inherit config flags */
p = parent;
do {
for (iter = p; iter && (iter->nodetype == LYS_USES); iter = iter->parent);
} while (iter && iter->nodetype == LYS_AUGMENT && (p = lys_parent(iter)));
if (iter) {
flags = iter->flags & LYS_CONFIG_MASK;
} else {
/* default */
flags = LYS_CONFIG_W;
}
switch (finalize) {
case 1:
/* inherit config flags */
if (retval->flags & LYS_CONFIG_SET) {
/* skip nodes with an explicit config value */
if ((flags & LYS_CONFIG_R) && (retval->flags & LYS_CONFIG_W)) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, "true", "config");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "State nodes cannot have configuration nodes as children.");
goto error;
}
break;
}
if (retval->nodetype != LYS_USES) {
retval->flags = (retval->flags & ~LYS_CONFIG_MASK) | flags;
}
/* inherit status */
if ((parent->flags & LYS_STATUS_MASK) > (retval->flags & LYS_STATUS_MASK)) {
/* but do it only in case the parent has a stonger status */
retval->flags &= ~LYS_STATUS_MASK;
retval->flags |= (parent->flags & LYS_STATUS_MASK);
}
break;
case 2:
/* erase config flags */
retval->flags &= ~LYS_CONFIG_MASK;
retval->flags &= ~LYS_CONFIG_SET;
break;
}
/* connect it to the parent */
if (lys_node_addchild(parent, retval->module, retval, 0)) {
goto error;
}
/* go recursively */
if (!(node->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
LY_TREE_FOR(node->child, iter) {
if (iter->nodetype & LYS_GROUPING) {
/* do not instantiate groupings */
continue;
}
if (!lys_node_dup_recursion(module, retval, iter, unres, 0, finalize)) {
goto error;
}
}
}
if (finalize == 1) {
/* check that configuration lists have keys
* - we really want to check keys_size in original node, because the keys are
* not yet resolved here, it is done below in nodetype specific part */
if ((retval->nodetype == LYS_LIST) && (retval->flags & LYS_CONFIG_W)
&& !((struct lys_node_list *)node)->keys_size) {
LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, retval, "key", "list");
goto error;
}
}
} else {
memcpy(retval->iffeature, node->iffeature, retval->iffeature_size * sizeof *retval->iffeature);
}
/*
* duplicate specific part of the structure
*/
switch (node->nodetype) {
case LYS_CONTAINER:
if (cont_orig->when) {
cont->when = lys_when_dup(module, cont_orig->when, shallow, unres);
LY_CHECK_GOTO(!cont->when, error);
}
cont->presence = lydict_insert(ctx, cont_orig->presence, 0);
if (cont_orig->must) {
cont->must = lys_restr_dup(module, cont_orig->must, cont_orig->must_size, shallow, unres);
LY_CHECK_GOTO(!cont->must, error);
cont->must_size = cont_orig->must_size;
}
/* typedefs are not needed in instantiated grouping, nor the deviation's shallow copy */
break;
case LYS_CHOICE:
if (choice_orig->when) {
choice->when = lys_when_dup(module, choice_orig->when, shallow, unres);
LY_CHECK_GOTO(!choice->when, error);
}
if (!shallow) {
if (choice_orig->dflt) {
rc = lys_get_sibling(choice->child, lys_node_module(retval)->name, 0, choice_orig->dflt->name, 0,
LYS_ANYDATA | LYS_CASE | LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST,
(const struct lys_node **)&choice->dflt);
if (rc) {
if (rc == EXIT_FAILURE) {
LOGINT(ctx);
}
goto error;
}
} else {
/* useless to check return value, we don't know whether
* there really wasn't any default defined or it just hasn't
* been resolved, we just hope for the best :)
*/
unres_schema_dup(module, unres, choice_orig, UNRES_CHOICE_DFLT, choice);
}
} else {
choice->dflt = choice_orig->dflt;
}
break;
case LYS_LEAF:
if (lys_type_dup(module, retval, &(leaf->type), &(leaf_orig->type), lys_ingrouping(retval), shallow, unres)) {
goto error;
}
leaf->units = lydict_insert(module->ctx, leaf_orig->units, 0);
if (leaf_orig->dflt) {
leaf->dflt = lydict_insert(ctx, leaf_orig->dflt, 0);
}
if (leaf_orig->must) {
leaf->must = lys_restr_dup(module, leaf_orig->must, leaf_orig->must_size, shallow, unres);
LY_CHECK_GOTO(!leaf->must, error);
leaf->must_size = leaf_orig->must_size;
}
if (leaf_orig->when) {
leaf->when = lys_when_dup(module, leaf_orig->when, shallow, unres);
LY_CHECK_GOTO(!leaf->when, error);
}
break;
case LYS_LEAFLIST:
if (lys_type_dup(module, retval, &(llist->type), &(llist_orig->type), lys_ingrouping(retval), shallow, unres)) {
goto error;
}
llist->units = lydict_insert(module->ctx, llist_orig->units, 0);
llist->min = llist_orig->min;
llist->max = llist_orig->max;
if (llist_orig->must) {
llist->must = lys_restr_dup(module, llist_orig->must, llist_orig->must_size, shallow, unres);
LY_CHECK_GOTO(!llist->must, error);
llist->must_size = llist_orig->must_size;
}
if (llist_orig->dflt) {
llist->dflt = malloc(llist_orig->dflt_size * sizeof *llist->dflt);
LY_CHECK_ERR_GOTO(!llist->dflt, LOGMEM(ctx), error);
llist->dflt_size = llist_orig->dflt_size;
for (i = 0; i < llist->dflt_size; i++) {
llist->dflt[i] = lydict_insert(ctx, llist_orig->dflt[i], 0);
}
}
if (llist_orig->when) {
llist->when = lys_when_dup(module, llist_orig->when, shallow, unres);
}
break;
case LYS_LIST:
list->min = list_orig->min;
list->max = list_orig->max;
if (list_orig->must) {
list->must = lys_restr_dup(module, list_orig->must, list_orig->must_size, shallow, unres);
LY_CHECK_GOTO(!list->must, error);
list->must_size = list_orig->must_size;
}
/* typedefs are not needed in instantiated grouping, nor the deviation's shallow copy */
if (list_orig->keys_size) {
list->keys = calloc(list_orig->keys_size, sizeof *list->keys);
LY_CHECK_ERR_GOTO(!list->keys, LOGMEM(ctx), error);
list->keys_str = lydict_insert(ctx, list_orig->keys_str, 0);
list->keys_size = list_orig->keys_size;
if (!shallow) {
if (unres_schema_add_node(module, unres, list, UNRES_LIST_KEYS, NULL) == -1) {
goto error;
}
} else {
memcpy(list->keys, list_orig->keys, list_orig->keys_size * sizeof *list->keys);
}
}
if (list_orig->unique) {
list->unique = malloc(list_orig->unique_size * sizeof *list->unique);
LY_CHECK_ERR_GOTO(!list->unique, LOGMEM(ctx), error);
list->unique_size = list_orig->unique_size;
for (i = 0; i < list->unique_size; ++i) {
list->unique[i].expr = malloc(list_orig->unique[i].expr_size * sizeof *list->unique[i].expr);
LY_CHECK_ERR_GOTO(!list->unique[i].expr, LOGMEM(ctx), error);
list->unique[i].expr_size = list_orig->unique[i].expr_size;
for (j = 0; j < list->unique[i].expr_size; j++) {
list->unique[i].expr[j] = lydict_insert(ctx, list_orig->unique[i].expr[j], 0);
/* if it stays in unres list, duplicate it also there */
unique_info = malloc(sizeof *unique_info);
LY_CHECK_ERR_GOTO(!unique_info, LOGMEM(ctx), error);
unique_info->list = (struct lys_node *)list;
unique_info->expr = list->unique[i].expr[j];
unique_info->trg_type = &list->unique[i].trg_type;
unres_schema_dup(module, unres, &list_orig, UNRES_LIST_UNIQ, unique_info);
}
}
}
if (list_orig->when) {
list->when = lys_when_dup(module, list_orig->when, shallow, unres);
LY_CHECK_GOTO(!list->when, error);
}
break;
case LYS_ANYXML:
case LYS_ANYDATA:
if (any_orig->must) {
any->must = lys_restr_dup(module, any_orig->must, any_orig->must_size, shallow, unres);
LY_CHECK_GOTO(!any->must, error);
any->must_size = any_orig->must_size;
}
if (any_orig->when) {
any->when = lys_when_dup(module, any_orig->when, shallow, unres);
LY_CHECK_GOTO(!any->when, error);
}
break;
case LYS_USES:
uses->grp = uses_orig->grp;
if (uses_orig->when) {
uses->when = lys_when_dup(module, uses_orig->when, shallow, unres);
LY_CHECK_GOTO(!uses->when, error);
}
/* it is not needed to duplicate refine, nor augment. They are already applied to the uses children */
break;
case LYS_CASE:
if (cs_orig->when) {
cs->when = lys_when_dup(module, cs_orig->when, shallow, unres);
LY_CHECK_GOTO(!cs->when, error);
}
break;
case LYS_ACTION:
case LYS_RPC:
case LYS_INPUT:
case LYS_OUTPUT:
case LYS_NOTIF:
/* typedefs are not needed in instantiated grouping, nor the deviation's shallow copy */
break;
default:
/* LY_NODE_AUGMENT */
LOGINT(ctx);
goto error;
}
return retval;
error:
lys_node_free(retval, NULL, 0);
return NULL;
}
int
lys_has_xpath(const struct lys_node *node)
{
assert(node);
switch (node->nodetype) {
case LYS_AUGMENT:
if (((struct lys_node_augment *)node)->when) {
return 1;
}
break;
case LYS_CASE:
if (((struct lys_node_case *)node)->when) {
return 1;
}
break;
case LYS_CHOICE:
if (((struct lys_node_choice *)node)->when) {
return 1;
}
break;
case LYS_ANYDATA:
if (((struct lys_node_anydata *)node)->when || ((struct lys_node_anydata *)node)->must_size) {
return 1;
}
break;
case LYS_LEAF:
if (((struct lys_node_leaf *)node)->when || ((struct lys_node_leaf *)node)->must_size) {
return 1;
}
break;
case LYS_LEAFLIST:
if (((struct lys_node_leaflist *)node)->when || ((struct lys_node_leaflist *)node)->must_size) {
return 1;
}
break;
case LYS_LIST:
if (((struct lys_node_list *)node)->when || ((struct lys_node_list *)node)->must_size) {
return 1;
}
break;
case LYS_CONTAINER:
if (((struct lys_node_container *)node)->when || ((struct lys_node_container *)node)->must_size) {
return 1;
}
break;
case LYS_INPUT:
case LYS_OUTPUT:
if (((struct lys_node_inout *)node)->must_size) {
return 1;
}
break;
case LYS_NOTIF:
if (((struct lys_node_notif *)node)->must_size) {
return 1;
}
break;
case LYS_USES:
if (((struct lys_node_uses *)node)->when) {
return 1;
}
break;
default:
/* does not have XPath */
break;
}
return 0;
}
int
lys_type_is_local(const struct lys_type *type)
{
if (!type->der->module) {
/* build-in type */
return 1;
}
/* type->parent can be either a typedef or leaf/leaf-list, but module pointers are compatible */
return (lys_main_module(type->der->module) == lys_main_module(((struct lys_tpdf *)type->parent)->module));
}
/*
* shallow -
* - do not inherit status from the parent
*/
struct lys_node *
lys_node_dup(struct lys_module *module, struct lys_node *parent, const struct lys_node *node,
struct unres_schema *unres, int shallow)
{
struct lys_node *p = NULL;
int finalize = 0;
struct lys_node *result, *iter, *next;
if (!shallow) {
/* get know where in schema tree we are to know what should be done during instantiation of the grouping */
for (p = parent;
p && !(p->nodetype & (LYS_NOTIF | LYS_INPUT | LYS_OUTPUT | LYS_RPC | LYS_ACTION | LYS_GROUPING));
p = lys_parent(p));
finalize = p ? ((p->nodetype == LYS_GROUPING) ? 0 : 2) : 1;
}
result = lys_node_dup_recursion(module, parent, node, unres, shallow, finalize);
if (finalize) {
/* check xpath expressions in the instantiated tree */
for (iter = next = result; iter; iter = next) {
if (lys_has_xpath(iter) && unres_schema_add_node(module, unres, iter, UNRES_XPATH, NULL) == -1) {
/* invalid xpath */
return NULL;
}
/* select next item */
if (iter->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA | LYS_GROUPING)) {
/* child exception for leafs, leaflists and anyxml without children, ignore groupings */
next = NULL;
} else {
next = iter->child;
}
if (!next) {
/* no children, try siblings */
if (iter == result) {
/* we are done, no next element to process */
break;
}
next = iter->next;
}
while (!next) {
/* parent is already processed, go to its sibling */
iter = lys_parent(iter);
if (lys_parent(iter) == lys_parent(result)) {
/* we are done, no next element to process */
break;
}
next = iter->next;
}
}
}
return result;
}
/**
* @brief Switch contents of two same schema nodes. One of the nodes
* is expected to be ashallow copy of the other.
*
* @param[in] node1 Node whose contents will be switched with \p node2.
* @param[in] node2 Node whose contents will be switched with \p node1.
*/
static void
lys_node_switch(struct lys_node *node1, struct lys_node *node2)
{
const size_t mem_size = 104;
uint8_t mem[mem_size];
size_t offset, size;
assert((node1->module == node2->module) && ly_strequal(node1->name, node2->name, 1) && (node1->nodetype == node2->nodetype));
/*
* Initially, the nodes were really switched in the tree which
* caused problems for some other nodes with pointers (augments, leafrefs, ...)
* because their pointers were not being updated. Code kept in case there is
* a use of it in future (it took some debugging to cover all the cases).
* sibling next *
if (node1->prev->next) {
node1->prev->next = node2;
}
* sibling prev *
if (node1->next) {
node1->next->prev = node2;
} else {
for (child = node1->prev; child->prev->next; child = child->prev);
child->prev = node2;
}
* next *
node2->next = node1->next;
node1->next = NULL;
* prev *
if (node1->prev != node1) {
node2->prev = node1->prev;
}
node1->prev = node1;
* parent child *
if (node1->parent) {
if (node1->parent->child == node1) {
node1->parent->child = node2;
}
} else if (lys_main_module(node1->module)->data == node1) {
lys_main_module(node1->module)->data = node2;
}
* parent *
node2->parent = node1->parent;
node1->parent = NULL;
* child parent *
LY_TREE_FOR(node1->child, child) {
if (child->parent == node1) {
child->parent = node2;
}
}
* child *
node2->child = node1->child;
node1->child = NULL;
*/
/* switch common node part */
offset = 3 * sizeof(char *);
size = sizeof(uint16_t) + 6 * sizeof(uint8_t) + sizeof(struct lys_ext_instance **) + sizeof(struct lys_iffeature *);
memcpy(mem, ((uint8_t *)node1) + offset, size);
memcpy(((uint8_t *)node1) + offset, ((uint8_t *)node2) + offset, size);
memcpy(((uint8_t *)node2) + offset, mem, size);
/* switch node-specific data */
offset = sizeof(struct lys_node);
switch (node1->nodetype) {
case LYS_CONTAINER:
size = sizeof(struct lys_node_container) - offset;
break;
case LYS_CHOICE:
size = sizeof(struct lys_node_choice) - offset;
break;
case LYS_LEAF:
size = sizeof(struct lys_node_leaf) - offset;
break;
case LYS_LEAFLIST:
size = sizeof(struct lys_node_leaflist) - offset;
break;
case LYS_LIST:
size = sizeof(struct lys_node_list) - offset;
break;
case LYS_ANYDATA:
case LYS_ANYXML:
size = sizeof(struct lys_node_anydata) - offset;
break;
case LYS_CASE:
size = sizeof(struct lys_node_case) - offset;
break;
case LYS_INPUT:
case LYS_OUTPUT:
size = sizeof(struct lys_node_inout) - offset;
break;
case LYS_NOTIF:
size = sizeof(struct lys_node_notif) - offset;
break;
case LYS_RPC:
case LYS_ACTION:
size = sizeof(struct lys_node_rpc_action) - offset;
break;
default:
assert(0);
LOGINT(node1->module->ctx);
return;
}
assert(size <= mem_size);
memcpy(mem, ((uint8_t *)node1) + offset, size);
memcpy(((uint8_t *)node1) + offset, ((uint8_t *)node2) + offset, size);
memcpy(((uint8_t *)node2) + offset, mem, size);
/* typedefs were not copied to the backup node, so always reuse them,
* in leaves/leaf-lists we must correct the type parent pointer */
switch (node1->nodetype) {
case LYS_CONTAINER:
((struct lys_node_container *)node1)->tpdf_size = ((struct lys_node_container *)node2)->tpdf_size;
((struct lys_node_container *)node1)->tpdf = ((struct lys_node_container *)node2)->tpdf;
((struct lys_node_container *)node2)->tpdf_size = 0;
((struct lys_node_container *)node2)->tpdf = NULL;
break;
case LYS_LIST:
((struct lys_node_list *)node1)->tpdf_size = ((struct lys_node_list *)node2)->tpdf_size;
((struct lys_node_list *)node1)->tpdf = ((struct lys_node_list *)node2)->tpdf;
((struct lys_node_list *)node2)->tpdf_size = 0;
((struct lys_node_list *)node2)->tpdf = NULL;
break;
case LYS_RPC:
case LYS_ACTION:
((struct lys_node_rpc_action *)node1)->tpdf_size = ((struct lys_node_rpc_action *)node2)->tpdf_size;
((struct lys_node_rpc_action *)node1)->tpdf = ((struct lys_node_rpc_action *)node2)->tpdf;
((struct lys_node_rpc_action *)node2)->tpdf_size = 0;
((struct lys_node_rpc_action *)node2)->tpdf = NULL;
break;
case LYS_NOTIF:
((struct lys_node_notif *)node1)->tpdf_size = ((struct lys_node_notif *)node2)->tpdf_size;
((struct lys_node_notif *)node1)->tpdf = ((struct lys_node_notif *)node2)->tpdf;
((struct lys_node_notif *)node2)->tpdf_size = 0;
((struct lys_node_notif *)node2)->tpdf = NULL;
break;
case LYS_INPUT:
case LYS_OUTPUT:
((struct lys_node_inout *)node1)->tpdf_size = ((struct lys_node_inout *)node2)->tpdf_size;
((struct lys_node_inout *)node1)->tpdf = ((struct lys_node_inout *)node2)->tpdf;
((struct lys_node_inout *)node2)->tpdf_size = 0;
((struct lys_node_inout *)node2)->tpdf = NULL;
break;
case LYS_LEAF:
case LYS_LEAFLIST:
((struct lys_node_leaf *)node1)->type.parent = (struct lys_tpdf *)node1;
((struct lys_node_leaf *)node2)->type.parent = (struct lys_tpdf *)node2;
default:
break;
}
}
void
lys_free(struct lys_module *module, void (*private_destructor)(const struct lys_node *node, void *priv), int free_subs, int remove_from_ctx)
{
struct ly_ctx *ctx;
int i;
if (!module) {
return;
}
/* remove schema from the context */
ctx = module->ctx;
if (remove_from_ctx && ctx->models.used) {
for (i = 0; i < ctx->models.used; i++) {
if (ctx->models.list[i] == module) {
/* move all the models to not change the order in the list */
ctx->models.used--;
memmove(&ctx->models.list[i], ctx->models.list[i + 1], (ctx->models.used - i) * sizeof *ctx->models.list);
ctx->models.list[ctx->models.used] = NULL;
/* we are done */
break;
}
}
}
/* common part with struct ly_submodule */
module_free_common(module, private_destructor);
/* include */
for (i = 0; i < module->inc_size; i++) {
lydict_remove(ctx, module->inc[i].dsc);
lydict_remove(ctx, module->inc[i].ref);
lys_extension_instances_free(ctx, module->inc[i].ext, module->inc[i].ext_size, private_destructor);
/* complete submodule free is done only from main module since
* submodules propagate their includes to the main module */
if (free_subs) {
lys_submodule_free(module->inc[i].submodule, private_destructor);
}
}
free(module->inc);
/* specific items to free */
lydict_remove(ctx, module->ns);
free(module);
}
static void
lys_features_disable_recursive(struct lys_feature *f)
{
unsigned int i;
struct lys_feature *depf;
/* disable the feature */
f->flags &= ~LYS_FENABLED;
/* by disabling feature we have to disable also all features that depends on this feature */
if (f->depfeatures) {
for (i = 0; i < f->depfeatures->number; i++) {
depf = (struct lys_feature *)f->depfeatures->set.g[i];
if (depf->flags & LYS_FENABLED) {
lys_features_disable_recursive(depf);
}
}
}
}
/*
* op: 1 - enable, 0 - disable
*/
static int
lys_features_change(const struct lys_module *module, const char *name, int op)
{
int all = 0;
int i, j, k;
int progress, faili, failj, failk;
uint8_t fsize;
struct lys_feature *f;
if (!module || !name || !strlen(name)) {
LOGARG;
return EXIT_FAILURE;
}
if (!strcmp(name, "*")) {
/* enable all */
all = 1;
}
progress = failk = 1;
while (progress && failk) {
for (i = -1, failk = progress = 0; i < module->inc_size; i++) {
if (i == -1) {
fsize = module->features_size;
f = module->features;
} else {
fsize = module->inc[i].submodule->features_size;
f = module->inc[i].submodule->features;
}
for (j = 0; j < fsize; j++) {
if (all || !strcmp(f[j].name, name)) {
if ((op && (f[j].flags & LYS_FENABLED)) || (!op && !(f[j].flags & LYS_FENABLED))) {
if (all) {
/* skip already set features */
continue;
} else {
/* feature already set correctly */
return EXIT_SUCCESS;
}
}
if (op) {
/* check referenced features if they are enabled */
for (k = 0; k < f[j].iffeature_size; k++) {
if (!resolve_iffeature(&f[j].iffeature[k])) {
if (all) {
faili = i;
failj = j;
failk = k + 1;
break;
} else {
LOGERR(module->ctx, LY_EINVAL, "Feature \"%s\" is disabled by its %d. if-feature condition.",
f[j].name, k + 1);
return EXIT_FAILURE;
}
}
}
if (k == f[j].iffeature_size) {
/* the last check passed, do the change */
f[j].flags |= LYS_FENABLED;
progress++;
}
} else {
lys_features_disable_recursive(&f[j]);
progress++;
}
if (!all) {
/* stop in case changing a single feature */
return EXIT_SUCCESS;
}
}
}
}
}
if (failk) {
/* print info about the last failing feature */
LOGERR(module->ctx, LY_EINVAL, "Feature \"%s\" is disabled by its %d. if-feature condition.",
faili == -1 ? module->features[failj].name : module->inc[faili].submodule->features[failj].name, failk);
return EXIT_FAILURE;
}
if (all) {
return EXIT_SUCCESS;
} else {
/* the specified feature not found */
return EXIT_FAILURE;
}
}
API int
lys_features_enable(const struct lys_module *module, const char *feature)
{
return lys_features_change(module, feature, 1);
}
API int
lys_features_disable(const struct lys_module *module, const char *feature)
{
return lys_features_change(module, feature, 0);
}
API int
lys_features_state(const struct lys_module *module, const char *feature)
{
int i, j;
if (!module || !feature) {
return -1;
}
/* search for the specified feature */
/* module itself */
for (i = 0; i < module->features_size; i++) {
if (!strcmp(feature, module->features[i].name)) {
if (module->features[i].flags & LYS_FENABLED) {
return 1;
} else {
return 0;
}
}
}
/* submodules */
for (j = 0; j < module->inc_size; j++) {
for (i = 0; i < module->inc[j].submodule->features_size; i++) {
if (!strcmp(feature, module->inc[j].submodule->features[i].name)) {
if (module->inc[j].submodule->features[i].flags & LYS_FENABLED) {
return 1;
} else {
return 0;
}
}
}
}
/* feature definition not found */
return -1;
}
API const char **
lys_features_list(const struct lys_module *module, uint8_t **states)
{
const char **result = NULL;
int i, j;
unsigned int count;
if (!module) {
return NULL;
}
count = module->features_size;
for (i = 0; i < module->inc_size; i++) {
count += module->inc[i].submodule->features_size;
}
result = malloc((count + 1) * sizeof *result);
LY_CHECK_ERR_RETURN(!result, LOGMEM(module->ctx), NULL);
if (states) {
*states = malloc((count + 1) * sizeof **states);
LY_CHECK_ERR_RETURN(!(*states), LOGMEM(module->ctx); free(result), NULL);
}
count = 0;
/* module itself */
for (i = 0; i < module->features_size; i++) {
result[count] = module->features[i].name;
if (states) {
if (module->features[i].flags & LYS_FENABLED) {
(*states)[count] = 1;
} else {
(*states)[count] = 0;
}
}
count++;
}
/* submodules */
for (j = 0; j < module->inc_size; j++) {
for (i = 0; i < module->inc[j].submodule->features_size; i++) {
result[count] = module->inc[j].submodule->features[i].name;
if (states) {
if (module->inc[j].submodule->features[i].flags & LYS_FENABLED) {
(*states)[count] = 1;
} else {
(*states)[count] = 0;
}
}
count++;
}
}
/* terminating NULL byte */
result[count] = NULL;
return result;
}
API struct lys_module *
lys_node_module(const struct lys_node *node)
{
if (!node) {
return NULL;
}
return node->module->type ? ((struct lys_submodule *)node->module)->belongsto : node->module;
}
API struct lys_module *
lys_main_module(const struct lys_module *module)
{
if (!module) {
return NULL;
}
return (module->type ? ((struct lys_submodule *)module)->belongsto : (struct lys_module *)module);
}
API struct lys_node *
lys_parent(const struct lys_node *node)
{
struct lys_node *parent;
if (!node) {
return NULL;
}
if (node->nodetype == LYS_EXT) {
if (((struct lys_ext_instance_complex*)node)->parent_type != LYEXT_PAR_NODE) {
return NULL;
}
parent = (struct lys_node*)((struct lys_ext_instance_complex*)node)->parent;
} else if (!node->parent) {
return NULL;
} else {
parent = node->parent;
}
if (parent->nodetype == LYS_AUGMENT) {
return ((struct lys_node_augment *)parent)->target;
} else {
return parent;
}
}
struct lys_node **
lys_child(const struct lys_node *node, LYS_NODE nodetype)
{
void *pp;
assert(node);
if (node->nodetype == LYS_EXT) {
pp = lys_ext_complex_get_substmt(lys_snode2stmt(nodetype), (struct lys_ext_instance_complex*)node, NULL);
if (!pp) {
return NULL;
}
return (struct lys_node **)pp;
} else if (node->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
return NULL;
} else {
return (struct lys_node **)&node->child;
}
}
API void *
lys_set_private(const struct lys_node *node, void *priv)
{
void *prev;
if (!node) {
LOGARG;
return NULL;
}
prev = node->priv;
((struct lys_node *)node)->priv = priv;
return prev;
}
int
lys_leaf_add_leafref_target(struct lys_node_leaf *leafref_target, struct lys_node *leafref)
{
struct lys_node_leaf *iter;
struct ly_ctx *ctx = leafref_target->module->ctx;
if (!(leafref_target->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
LOGINT(ctx);
return -1;
}
/* check for config flag */
if (((struct lys_node_leaf*)leafref)->type.info.lref.req != -1 &&
(leafref->flags & LYS_CONFIG_W) && (leafref_target->flags & LYS_CONFIG_R)) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, leafref,
"The leafref %s is config but refers to a non-config %s.",
strnodetype(leafref->nodetype), strnodetype(leafref_target->nodetype));
return -1;
}
/* check for cycles */
for (iter = leafref_target; iter && iter->type.base == LY_TYPE_LEAFREF; iter = iter->type.info.lref.target) {
if ((void *)iter == (void *)leafref) {
/* cycle detected */
LOGVAL(ctx, LYE_CIRC_LEAFREFS, LY_VLOG_LYS, leafref);
return -1;
}
}
/* create fake child - the ly_set structure to hold the list of
* leafrefs referencing the leaf(-list) */
if (!leafref_target->backlinks) {
leafref_target->backlinks = (void *)ly_set_new();
if (!leafref_target->backlinks) {
LOGMEM(ctx);
return -1;
}
}
ly_set_add(leafref_target->backlinks, leafref, 0);
return 0;
}
/* not needed currently */
#if 0
static const char *
lys_data_path_reverse(const struct lys_node *node, char * const buf, uint32_t buf_len)
{
struct lys_module *prev_mod;
uint32_t str_len, mod_len, buf_idx;
if (!(node->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) {
LOGINT;
return NULL;
}
buf_idx = buf_len - 1;
buf[buf_idx] = '\0';
while (node) {
if (lys_parent(node)) {
prev_mod = lys_node_module(lys_parent(node));
} else {
prev_mod = NULL;
}
if (node->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
str_len = strlen(node->name);
if (prev_mod != node->module) {
mod_len = strlen(node->module->name);
} else {
mod_len = 0;
}
if (buf_idx < 1 + (mod_len ? mod_len + 1 : 0) + str_len) {
LOGINT;
return NULL;
}
buf_idx -= 1 + (mod_len ? mod_len + 1 : 0) + str_len;
buf[buf_idx] = '/';
if (mod_len) {
memcpy(buf + buf_idx + 1, node->module->name, mod_len);
buf[buf_idx + 1 + mod_len] = ':';
}
memcpy(buf + buf_idx + 1 + (mod_len ? mod_len + 1 : 0), node->name, str_len);
}
node = lys_parent(node);
}
return buf + buf_idx;
}
#endif
API struct ly_set *
lys_xpath_atomize(const struct lys_node *ctx_node, enum lyxp_node_type ctx_node_type, const char *expr, int options)
{
struct lyxp_set set;
struct ly_set *ret_set;
uint32_t i;
if (!ctx_node || !expr) {
LOGARG;
return NULL;
}
/* adjust the root */
if ((ctx_node_type == LYXP_NODE_ROOT) || (ctx_node_type == LYXP_NODE_ROOT_CONFIG)) {
do {
ctx_node = lys_getnext(NULL, NULL, lys_node_module(ctx_node), LYS_GETNEXT_NOSTATECHECK);
} while ((ctx_node_type == LYXP_NODE_ROOT_CONFIG) && (ctx_node->flags & LYS_CONFIG_R));
}
memset(&set, 0, sizeof set);
if (options & LYXP_MUST) {
options &= ~LYXP_MUST;
options |= LYXP_SNODE_MUST;
} else if (options & LYXP_WHEN) {
options &= ~LYXP_WHEN;
options |= LYXP_SNODE_WHEN;
} else {
options |= LYXP_SNODE;
}
if (lyxp_atomize(expr, ctx_node, ctx_node_type, &set, options, NULL)) {
free(set.val.snodes);
LOGVAL(ctx_node->module->ctx, LYE_SPEC, LY_VLOG_LYS, ctx_node, "Resolving XPath expression \"%s\" failed.", expr);
return NULL;
}
ret_set = ly_set_new();
for (i = 0; i < set.used; ++i) {
switch (set.val.snodes[i].type) {
case LYXP_NODE_ELEM:
if (ly_set_add(ret_set, set.val.snodes[i].snode, LY_SET_OPT_USEASLIST) == -1) {
ly_set_free(ret_set);
free(set.val.snodes);
return NULL;
}
break;
default:
/* ignore roots, text and attr should not ever appear */
break;
}
}
free(set.val.snodes);
return ret_set;
}
API struct ly_set *
lys_node_xpath_atomize(const struct lys_node *node, int options)
{
const struct lys_node *next, *elem, *parent, *tmp;
struct lyxp_set set;
struct ly_set *ret_set;
uint16_t i;
if (!node) {
LOGARG;
return NULL;
}
for (parent = node; parent && !(parent->nodetype & (LYS_NOTIF | LYS_INPUT | LYS_OUTPUT)); parent = lys_parent(parent));
if (!parent) {
/* not in input, output, or notification */
return NULL;
}
ret_set = ly_set_new();
if (!ret_set) {
return NULL;
}
LY_TREE_DFS_BEGIN(node, next, elem) {
if ((options & LYXP_NO_LOCAL) && !(elem->flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP))) {
/* elem has no dependencies from other subtrees and local nodes get discarded */
goto next_iter;
}
if (lyxp_node_atomize(elem, &set, 0)) {
ly_set_free(ret_set);
free(set.val.snodes);
return NULL;
}
for (i = 0; i < set.used; ++i) {
switch (set.val.snodes[i].type) {
case LYXP_NODE_ELEM:
if (options & LYXP_NO_LOCAL) {
for (tmp = set.val.snodes[i].snode; tmp && (tmp != parent); tmp = lys_parent(tmp));
if (tmp) {
/* in local subtree, discard */
break;
}
}
if (ly_set_add(ret_set, set.val.snodes[i].snode, 0) == -1) {
ly_set_free(ret_set);
free(set.val.snodes);
return NULL;
}
break;
default:
/* ignore roots, text and attr should not ever appear */
break;
}
}
free(set.val.snodes);
if (!(options & LYXP_RECURSIVE)) {
break;
}
next_iter:
LY_TREE_DFS_END(node, next, elem);
}
return ret_set;
}
/* logs */
int
apply_aug(struct lys_node_augment *augment, struct unres_schema *unres)
{
struct lys_node *child, *parent;
int clear_config;
unsigned int u;
uint8_t *v;
struct lys_ext_instance *ext;
assert(augment->target && (augment->flags & LYS_NOTAPPLIED));
if (!augment->child) {
/* nothing to apply */
goto success;
}
/* inherit config information from actual parent */
for (parent = augment->target; parent && !(parent->nodetype & (LYS_NOTIF | LYS_INPUT | LYS_OUTPUT | LYS_RPC)); parent = lys_parent(parent));
clear_config = (parent) ? 1 : 0;
LY_TREE_FOR(augment->child, child) {
if (inherit_config_flag(child, augment->target->flags & LYS_CONFIG_MASK, clear_config)) {
return -1;
}
}
/* inherit extensions if any */
for (u = 0; u < augment->target->ext_size; u++) {
ext = augment->target->ext[u]; /* shortcut */
if (ext && ext->def->plugin && (ext->def->plugin->flags & LYEXT_OPT_INHERIT)) {
v = malloc(sizeof *v);
LY_CHECK_ERR_RETURN(!v, LOGMEM(augment->module->ctx), -1);
*v = u;
if (unres_schema_add_node(lys_main_module(augment->module), unres, &augment->target->ext,
UNRES_EXT_FINALIZE, (struct lys_node *)v) == -1) {
/* something really bad happend since the extension finalization is not actually
* being resolved while adding into unres, so something more serious with the unres
* list itself must happened */
return -1;
}
}
}
/* reconnect augmenting data into the target - add them to the target child list */
if (augment->target->child) {
child = augment->target->child->prev;
child->next = augment->child;
augment->target->child->prev = augment->child->prev;
augment->child->prev = child;
} else {
augment->target->child = augment->child;
}
success:
/* remove the flag about not applicability */
augment->flags &= ~LYS_NOTAPPLIED;
return EXIT_SUCCESS;
}
static void
remove_aug(struct lys_node_augment *augment)
{
struct lys_node *last, *elem;
if ((augment->flags & LYS_NOTAPPLIED) || !augment->target) {
/* skip already not applied augment */
return;
}
elem = augment->child;
if (elem) {
LY_TREE_FOR(elem, last) {
if (!last->next || (last->next->parent != (struct lys_node *)augment)) {
break;
}
}
/* elem is first augment child, last is the last child */
/* parent child ptr */
if (augment->target->child == elem) {
augment->target->child = last->next;
}
/* parent child next ptr */
if (elem->prev->next) {
elem->prev->next = last->next;
}
/* parent child prev ptr */
if (last->next) {
last->next->prev = elem->prev;
} else if (augment->target->child) {
augment->target->child->prev = elem->prev;
}
/* update augment children themselves */
elem->prev = last;
last->next = NULL;
}
/* augment->target still keeps the resolved target, but for lys_augment_free()
* we have to keep information that this augment is not applied to free its data */
augment->flags |= LYS_NOTAPPLIED;
}
/*
* @param[in] module - the module where the deviation is defined
*/
static void
lys_switch_deviation(struct lys_deviation *dev, const struct lys_module *module, struct unres_schema *unres)
{
int ret, reapply = 0;
char *parent_path;
struct lys_node *target = NULL, *parent;
struct lys_node_inout *inout;
struct ly_set *set;
if (!dev->deviate) {
return;
}
if (dev->deviate[0].mod == LY_DEVIATE_NO) {
if (dev->orig_node) {
/* removing not-supported deviation ... */
if (strrchr(dev->target_name, '/') != dev->target_name) {
/* ... from a parent */
/* reconnect to its previous position */
parent = dev->orig_node->parent;
if (parent && (parent->nodetype == LYS_AUGMENT)) {
dev->orig_node->parent = NULL;
/* the original node was actually from augment, we have to get know if the augment is
* applied (its module is enabled and implemented). If yes, the node will be connected
* to the augment and the linkage with the target will be fixed if needed, otherwise
* it will be connected only to the augment */
if (!(parent->flags & LYS_NOTAPPLIED)) {
/* start with removing augment if applied before adding nodes, we have to make sure
* that everything will be connect correctly */
remove_aug((struct lys_node_augment *)parent);
reapply = 1;
}
/* connect the deviated node back into the augment */
lys_node_addchild(parent, NULL, dev->orig_node, 0);
if (reapply) {
/* augment is supposed to be applied, so fix pointers in target and the status of the original node */
assert(lys_node_module(parent)->implemented);
parent->flags |= LYS_NOTAPPLIED; /* allow apply_aug() */
apply_aug((struct lys_node_augment *)parent, unres);
}
} else if (parent && (parent->nodetype == LYS_USES)) {
/* uses child */
lys_node_addchild(parent, NULL, dev->orig_node, 0);
} else {
/* non-augment, non-toplevel */
parent_path = strndup(dev->target_name, strrchr(dev->target_name, '/') - dev->target_name);
ret = resolve_schema_nodeid(parent_path, NULL, module, &set, 0, 1);
free(parent_path);
if (ret == -1) {
LOGINT(module->ctx);
ly_set_free(set);
return;
}
target = set->set.s[0];
ly_set_free(set);
lys_node_addchild(target, NULL, dev->orig_node, 0);
}
} else {
/* ... from top-level data */
lys_node_addchild(NULL, (struct lys_module *)dev->orig_node->module, dev->orig_node, 0);
}
dev->orig_node = NULL;
} else {
/* adding not-supported deviation */
ret = resolve_schema_nodeid(dev->target_name, NULL, module, &set, 0, 1);
if (ret == -1) {
LOGINT(module->ctx);
ly_set_free(set);
return;
}
target = set->set.s[0];
ly_set_free(set);
/* unlink and store the original node */
parent = target->parent;
lys_node_unlink(target);
if (parent) {
if (parent->nodetype & (LYS_AUGMENT | LYS_USES)) {
/* hack for augment, because when the original will be sometime reconnected back, we actually need
* to reconnect it to both - the augment and its target (which is deduced from the deviations target
* path), so we need to remember the augment as an addition */
/* we also need to remember the parent uses so that we connect it back to it when switching deviation state */
target->parent = parent;
} else if (parent->nodetype & (LYS_RPC | LYS_ACTION)) {
/* re-create implicit node */
inout = calloc(1, sizeof *inout);
LY_CHECK_ERR_RETURN(!inout, LOGMEM(module->ctx), );
inout->nodetype = target->nodetype;
inout->name = lydict_insert(module->ctx, (inout->nodetype == LYS_INPUT) ? "input" : "output", 0);
inout->module = target->module;
inout->flags = LYS_IMPLICIT;
/* insert it manually */
assert(parent->child && !parent->child->next
&& (parent->child->nodetype == (inout->nodetype == LYS_INPUT ? LYS_OUTPUT : LYS_INPUT)));
parent->child->next = (struct lys_node *)inout;
inout->prev = parent->child;
parent->child->prev = (struct lys_node *)inout;
inout->parent = parent;
}
}
dev->orig_node = target;
}
} else {
ret = resolve_schema_nodeid(dev->target_name, NULL, module, &set, 0, 1);
if (ret == -1) {
LOGINT(module->ctx);
ly_set_free(set);
return;
}
target = set->set.s[0];
ly_set_free(set);
/* contents are switched */
lys_node_switch(target, dev->orig_node);
}
}
/* temporarily removes or applies deviations, updates module deviation flag accordingly */
void
lys_enable_deviations(struct lys_module *module)
{
uint32_t i = 0, j;
const struct lys_module *mod;
const char *ptr;
struct unres_schema *unres;
if (module->deviated) {
unres = calloc(1, sizeof *unres);
LY_CHECK_ERR_RETURN(!unres, LOGMEM(module->ctx), );
while ((mod = ly_ctx_get_module_iter(module->ctx, &i))) {
if (mod == module) {
continue;
}
for (j = 0; j < mod->deviation_size; ++j) {
ptr = strstr(mod->deviation[j].target_name, module->name);
if (ptr && ptr[strlen(module->name)] == ':') {
lys_switch_deviation(&mod->deviation[j], mod, unres);
}
}
}
assert(module->deviated == 2);
module->deviated = 1;
for (j = 0; j < module->inc_size; j++) {
if (module->inc[j].submodule->deviated) {
module->inc[j].submodule->deviated = module->deviated;
}
}
if (unres->count) {
resolve_unres_schema(module, unres);
}
unres_schema_free(module, &unres, 1);
}
}
void
lys_disable_deviations(struct lys_module *module)
{
uint32_t i, j;
const struct lys_module *mod;
const char *ptr;
struct unres_schema *unres;
if (module->deviated) {
unres = calloc(1, sizeof *unres);
LY_CHECK_ERR_RETURN(!unres, LOGMEM(module->ctx), );
i = module->ctx->models.used;
while (i--) {
mod = module->ctx->models.list[i];
if (mod == module) {
continue;
}
j = mod->deviation_size;
while (j--) {
ptr = strstr(mod->deviation[j].target_name, module->name);
if (ptr && ptr[strlen(module->name)] == ':') {
lys_switch_deviation(&mod->deviation[j], mod, unres);
}
}
}
assert(module->deviated == 1);
module->deviated = 2;
for (j = 0; j < module->inc_size; j++) {
if (module->inc[j].submodule->deviated) {
module->inc[j].submodule->deviated = module->deviated;
}
}
if (unres->count) {
resolve_unres_schema(module, unres);
}
unres_schema_free(module, &unres, 1);
}
}
static void
apply_dev(struct lys_deviation *dev, const struct lys_module *module, struct unres_schema *unres)
{
lys_switch_deviation(dev, module, unres);
assert(dev->orig_node);
lys_node_module(dev->orig_node)->deviated = 1; /* main module */
dev->orig_node->module->deviated = 1; /* possible submodule */
}
static void
remove_dev(struct lys_deviation *dev, const struct lys_module *module, struct unres_schema *unres)
{
uint32_t idx = 0, j;
const struct lys_module *mod;
struct lys_module *target_mod, *target_submod;
const char *ptr;
if (dev->orig_node) {
target_mod = lys_node_module(dev->orig_node);
target_submod = dev->orig_node->module;
} else {
LOGINT(module->ctx);
return;
}
lys_switch_deviation(dev, module, unres);
/* clear the deviation flag if possible */
while ((mod = ly_ctx_get_module_iter(module->ctx, &idx))) {
if ((mod == module) || (mod == target_mod)) {
continue;
}
for (j = 0; j < mod->deviation_size; ++j) {
ptr = strstr(mod->deviation[j].target_name, target_mod->name);
if (ptr && (ptr[strlen(target_mod->name)] == ':')) {
/* some other module deviation targets the inspected module, flag remains */
break;
}
}
if (j < mod->deviation_size) {
break;
}
}
if (!mod) {
target_mod->deviated = 0; /* main module */
target_submod->deviated = 0; /* possible submodule */
}
}
void
lys_sub_module_apply_devs_augs(struct lys_module *module)
{
uint8_t u, v;
struct unres_schema *unres;
assert(module->implemented);
unres = calloc(1, sizeof *unres);
LY_CHECK_ERR_RETURN(!unres, LOGMEM(module->ctx), );
/* apply deviations */
for (u = 0; u < module->deviation_size; ++u) {
apply_dev(&module->deviation[u], module, unres);
}
/* apply augments */
for (u = 0; u < module->augment_size; ++u) {
apply_aug(&module->augment[u], unres);
}
/* apply deviations and augments defined in submodules */
for (v = 0; v < module->inc_size; ++v) {
for (u = 0; u < module->inc[v].submodule->deviation_size; ++u) {
apply_dev(&module->inc[v].submodule->deviation[u], module, unres);
}
for (u = 0; u < module->inc[v].submodule->augment_size; ++u) {
apply_aug(&module->inc[v].submodule->augment[u], unres);
}
}
if (unres->count) {
resolve_unres_schema(module, unres);
}
/* nothing else left to do even if something is not resolved */
unres_schema_free(module, &unres, 1);
}
void
lys_sub_module_remove_devs_augs(struct lys_module *module)
{
uint8_t u, v, w;
struct unres_schema *unres;
unres = calloc(1, sizeof *unres);
LY_CHECK_ERR_RETURN(!unres, LOGMEM(module->ctx), );
/* remove applied deviations */
for (u = 0; u < module->deviation_size; ++u) {
/* the deviation could not be applied because it failed to be applied in the first place*/
if (module->deviation[u].orig_node) {
remove_dev(&module->deviation[u], module, unres);
}
/* Free the deviation's must array(s). These are shallow copies of the arrays
on the target node(s), so a deep free is not needed. */
for (v = 0; v < module->deviation[u].deviate_size; ++v) {
if (module->deviation[u].deviate[v].mod == LY_DEVIATE_ADD) {
free(module->deviation[u].deviate[v].must);
}
}
}
/* remove applied augments */
for (u = 0; u < module->augment_size; ++u) {
remove_aug(&module->augment[u]);
}
/* remove deviation and augments defined in submodules */
for (v = 0; v < module->inc_size && module->inc[v].submodule; ++v) {
for (u = 0; u < module->inc[v].submodule->deviation_size; ++u) {
if (module->inc[v].submodule->deviation[u].orig_node) {
remove_dev(&module->inc[v].submodule->deviation[u], module, unres);
}
/* Free the deviation's must array(s). These are shallow copies of the arrays
on the target node(s), so a deep free is not needed. */
for (w = 0; w < module->inc[v].submodule->deviation[u].deviate_size; ++w) {
if (module->inc[v].submodule->deviation[u].deviate[w].mod == LY_DEVIATE_ADD) {
free(module->inc[v].submodule->deviation[u].deviate[w].must);
}
}
}
for (u = 0; u < module->inc[v].submodule->augment_size; ++u) {
remove_aug(&module->inc[v].submodule->augment[u]);
}
}
if (unres->count) {
resolve_unres_schema(module, unres);
}
/* nothing else left to do even if something is not resolved */
unres_schema_free(module, &unres, 1);
}
int
lys_make_implemented_r(struct lys_module *module, struct unres_schema *unres)
{
struct ly_ctx *ctx;
struct lys_node *root, *next, *node;
struct lys_module *target_module;
uint16_t i, j, k;
assert(module->implemented);
ctx = module->ctx;
for (i = 0; i < ctx->models.used; ++i) {
if (module == ctx->models.list[i]) {
continue;
}
if (!strcmp(module->name, ctx->models.list[i]->name) && ctx->models.list[i]->implemented) {
LOGERR(ctx, LY_EINVAL, "Module \"%s\" in another revision already implemented.", module->name);
return EXIT_FAILURE;
}
}
for (i = 0; i < module->augment_size; i++) {
/* make target module implemented if was not */
assert(module->augment[i].target);
target_module = lys_node_module(module->augment[i].target);
if (!target_module->implemented) {
target_module->implemented = 1;
if (unres_schema_add_node(target_module, unres, NULL, UNRES_MOD_IMPLEMENT, NULL) == -1) {
return -1;
}
}
/* apply augment */
if ((module->augment[i].flags & LYS_NOTAPPLIED) && apply_aug(&module->augment[i], unres)) {
return -1;
}
}
/* identities */
for (i = 0; i < module->ident_size; i++) {
for (j = 0; j < module->ident[i].base_size; j++) {
resolve_identity_backlink_update(&module->ident[i], module->ident[i].base[j]);
}
}
/* process augments in submodules */
for (i = 0; i < module->inc_size && module->inc[i].submodule; ++i) {
module->inc[i].submodule->implemented = 1;
for (j = 0; j < module->inc[i].submodule->augment_size; j++) {
/* make target module implemented if it was not */
assert(module->inc[i].submodule->augment[j].target);
target_module = lys_node_module(module->inc[i].submodule->augment[j].target);
if (!target_module->implemented) {
target_module->implemented = 1;
if (unres_schema_add_node(target_module, unres, NULL, UNRES_MOD_IMPLEMENT, NULL) == -1) {
return -1;
}
}
/* apply augment */
if ((module->inc[i].submodule->augment[j].flags & LYS_NOTAPPLIED) && apply_aug(&module->inc[i].submodule->augment[j], unres)) {
return -1;
}
}
/* identities */
for (j = 0; j < module->inc[i].submodule->ident_size; j++) {
for (k = 0; k < module->inc[i].submodule->ident[j].base_size; k++) {
resolve_identity_backlink_update(&module->inc[i].submodule->ident[j],
module->inc[i].submodule->ident[j].base[k]);
}
}
}
LY_TREE_FOR(module->data, root) {
/* handle leafrefs and recursively change the implemented flags in the leafref targets */
LY_TREE_DFS_BEGIN(root, next, node) {
if (node->nodetype == LYS_GROUPING) {
goto nextsibling;
}
if (node->nodetype & (LYS_LEAF | LYS_LEAFLIST)) {
if (((struct lys_node_leaf *)node)->type.base == LY_TYPE_LEAFREF) {
if (unres_schema_add_node(module, unres, &((struct lys_node_leaf *)node)->type,
UNRES_TYPE_LEAFREF, node) == -1) {
return -1;
}
}
}
/* modified LY_TREE_DFS_END */
next = node->child;
/* child exception for leafs, leaflists and anyxml without children */
if (node->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
next = NULL;
}
if (!next) {
nextsibling:
/* no children */
if (node == root) {
/* we are done, root has no children */
break;
}
/* try siblings */
next = node->next;
}
while (!next) {
/* parent is already processed, go to its sibling */
node = lys_parent(node);
/* no siblings, go back through parents */
if (lys_parent(node) == lys_parent(root)) {
/* we are done, no next element to process */
break;
}
next = node->next;
}
}
}
return EXIT_SUCCESS;
}
API int
lys_set_implemented(const struct lys_module *module)
{
struct unres_schema *unres;
int disabled = 0;
if (!module) {
LOGARG;
return EXIT_FAILURE;
}
module = lys_main_module(module);
if (module->disabled) {
disabled = 1;
lys_set_enabled(module);
}
if (module->implemented) {
return EXIT_SUCCESS;
}
unres = calloc(1, sizeof *unres);
if (!unres) {
LOGMEM(module->ctx);
if (disabled) {
/* set it back disabled */
lys_set_disabled(module);
}
return EXIT_FAILURE;
}
/* recursively make the module implemented */
((struct lys_module *)module)->implemented = 1;
if (lys_make_implemented_r((struct lys_module *)module, unres)) {
goto error;
}
/* try again resolve augments in other modules possibly augmenting this one,
* since we have just enabled it
*/
/* resolve rest of unres items */
if (unres->count && resolve_unres_schema((struct lys_module *)module, unres)) {
goto error;
}
unres_schema_free(NULL, &unres, 0);
LOGVRB("Module \"%s%s%s\" now implemented.", module->name, (module->rev_size ? "@" : ""),
(module->rev_size ? module->rev[0].date : ""));
return EXIT_SUCCESS;
error:
if (disabled) {
/* set it back disabled */
lys_set_disabled(module);
}
((struct lys_module *)module)->implemented = 0;
unres_schema_free((struct lys_module *)module, &unres, 1);
return EXIT_FAILURE;
}
void
lys_submodule_module_data_free(struct lys_submodule *submodule)
{
struct lys_node *next, *elem;
/* remove parsed data */
LY_TREE_FOR_SAFE(submodule->belongsto->data, next, elem) {
if (elem->module == (struct lys_module *)submodule) {
lys_node_free(elem, NULL, 0);
}
}
}
API char *
lys_path(const struct lys_node *node, int options)
{
char *buf = NULL;
if (!node) {
LOGARG;
return NULL;
}
if (ly_vlog_build_path(LY_VLOG_LYS, node, &buf, (options & LYS_PATH_FIRST_PREFIX) ? 0 : 1, 0)) {
return NULL;
}
return buf;
}
API char *
lys_data_path(const struct lys_node *node)
{
char *result = NULL, buf[1024];
const char *separator, *name;
int i, used;
struct ly_set *set;
const struct lys_module *prev_mod;
if (!node) {
LOGARG;
return NULL;
}
buf[0] = '\0';
set = ly_set_new();
LY_CHECK_ERR_GOTO(!set, LOGMEM(node->module->ctx), cleanup);
while (node) {
ly_set_add(set, (void *)node, 0);
do {
node = lys_parent(node);
} while (node && (node->nodetype & (LYS_USES | LYS_CHOICE | LYS_CASE | LYS_INPUT | LYS_OUTPUT)));
}
prev_mod = NULL;
used = 0;
for (i = set->number - 1; i > -1; --i) {
node = set->set.s[i];
if (node->nodetype == LYS_EXT) {
if (strcmp(((struct lys_ext_instance *)node)->def->name, "yang-data")) {
continue;
}
name = ((struct lys_ext_instance *)node)->arg_value;
separator = ":#";
} else {
name = node->name;
separator = ":";
}
used += sprintf(buf + used, "/%s%s%s", (lys_node_module(node) == prev_mod ? "" : lys_node_module(node)->name),
(lys_node_module(node) == prev_mod ? "" : separator), name);
prev_mod = lys_node_module(node);
}
result = strdup(buf);
LY_CHECK_ERR_GOTO(!result, LOGMEM(node->module->ctx), cleanup);
cleanup:
ly_set_free(set);
return result;
}
struct lys_node_augment *
lys_getnext_target_aug(struct lys_node_augment *last, const struct lys_module *mod, const struct lys_node *aug_target)
{
struct lys_node *child;
struct lys_node_augment *aug;
int i, j, last_found;
assert(mod && aug_target);
if (!last) {
last_found = 1;
} else {
last_found = 0;
}
/* search module augments */
for (i = 0; i < mod->augment_size; ++i) {
if (!mod->augment[i].target) {
/* still unresolved, skip */
continue;
}
if (mod->augment[i].target == aug_target) {
if (last_found) {
/* next match after last */
return &mod->augment[i];
}
if (&mod->augment[i] == last) {
last_found = 1;
}
}
}
/* search submodule augments */
for (i = 0; i < mod->inc_size; ++i) {
for (j = 0; j < mod->inc[i].submodule->augment_size; ++j) {
if (!mod->inc[i].submodule->augment[j].target) {
continue;
}
if (mod->inc[i].submodule->augment[j].target == aug_target) {
if (last_found) {
/* next match after last */
return &mod->inc[i].submodule->augment[j];
}
if (&mod->inc[i].submodule->augment[j] == last) {
last_found = 1;
}
}
}
}
/* we also need to check possible augments to choices */
LY_TREE_FOR(aug_target->child, child) {
if (child->nodetype == LYS_CHOICE) {
aug = lys_getnext_target_aug(last, mod, child);
if (aug) {
return aug;
}
}
}
return NULL;
}
API struct ly_set *
lys_find_path(const struct lys_module *cur_module, const struct lys_node *cur_node, const char *path)
{
struct ly_set *ret;
int rc;
if ((!cur_module && !cur_node) || !path) {
return NULL;
}
rc = resolve_schema_nodeid(path, cur_node, cur_module, &ret, 1, 1);
if (rc == -1) {
return NULL;
}
return ret;
}
static void
lys_extcomplex_free_str(struct ly_ctx *ctx, struct lys_ext_instance_complex *ext, LY_STMT stmt)
{
struct lyext_substmt *info;
const char **str, ***a;
int c;
str = lys_ext_complex_get_substmt(stmt, ext, &info);
if (!str || !(*str)) {
return;
}
if (info->cardinality >= LY_STMT_CARD_SOME) {
/* we have array */
a = (const char ***)str;
for (str = (*(const char ***)str), c = 0; str[c]; c++) {
lydict_remove(ctx, str[c]);
}
free(a[0]);
if (stmt == LY_STMT_BELONGSTO) {
for (str = a[1], c = 0; str[c]; c++) {
lydict_remove(ctx, str[c]);
}
free(a[1]);
} else if (stmt == LY_STMT_ARGUMENT) {
free(a[1]);
}
} else {
lydict_remove(ctx, str[0]);
if (stmt == LY_STMT_BELONGSTO) {
lydict_remove(ctx, str[1]);
}
}
}
void
lys_extension_instances_free(struct ly_ctx *ctx, struct lys_ext_instance **e, unsigned int size,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
unsigned int i, j, k;
struct lyext_substmt *substmt;
void **pp, **start;
struct lys_node *siter, *snext;
#define EXTCOMPLEX_FREE_STRUCT(STMT, TYPE, FUNC, FREE, ARGS...) \
pp = lys_ext_complex_get_substmt(STMT, (struct lys_ext_instance_complex *)e[i], NULL); \
if (!pp || !(*pp)) { break; } \
if (substmt[j].cardinality >= LY_STMT_CARD_SOME) { /* process array */ \
for (start = pp = *pp; *pp; pp++) { \
FUNC(ctx, (TYPE *)(*pp), ##ARGS, private_destructor); \
if (FREE) { free(*pp); } \
} \
free(start); \
} else { /* single item */ \
FUNC(ctx, (TYPE *)(*pp), ##ARGS, private_destructor); \
if (FREE) { free(*pp); } \
}
if (!size || !e) {
return;
}
for (i = 0; i < size; i++) {
if (!e[i]) {
continue;
}
if (e[i]->flags & (LYEXT_OPT_INHERIT)) {
/* no free, this is just a shadow copy of the original extension instance */
} else {
if (e[i]->flags & (LYEXT_OPT_YANG)) {
free(e[i]->def); /* remove name of instance extension */
e[i]->def = NULL;
yang_free_ext_data((struct yang_ext_substmt *)e[i]->parent); /* remove backup part of yang file */
}
/* remove private object */
if (e[i]->priv && private_destructor) {
private_destructor((struct lys_node*)e[i], e[i]->priv);
}
lys_extension_instances_free(ctx, e[i]->ext, e[i]->ext_size, private_destructor);
lydict_remove(ctx, e[i]->arg_value);
}
if (e[i]->def && e[i]->def->plugin && e[i]->def->plugin->type == LYEXT_COMPLEX
&& ((e[i]->flags & LYEXT_OPT_CONTENT) == 0)) {
substmt = ((struct lys_ext_instance_complex *)e[i])->substmt;
for (j = 0; substmt[j].stmt; j++) {
switch(substmt[j].stmt) {
case LY_STMT_DESCRIPTION:
case LY_STMT_REFERENCE:
case LY_STMT_UNITS:
case LY_STMT_ARGUMENT:
case LY_STMT_DEFAULT:
case LY_STMT_ERRTAG:
case LY_STMT_ERRMSG:
case LY_STMT_PREFIX:
case LY_STMT_NAMESPACE:
case LY_STMT_PRESENCE:
case LY_STMT_REVISIONDATE:
case LY_STMT_KEY:
case LY_STMT_BASE:
case LY_STMT_BELONGSTO:
case LY_STMT_CONTACT:
case LY_STMT_ORGANIZATION:
case LY_STMT_PATH:
lys_extcomplex_free_str(ctx, (struct lys_ext_instance_complex *)e[i], substmt[j].stmt);
break;
case LY_STMT_TYPE:
EXTCOMPLEX_FREE_STRUCT(LY_STMT_TYPE, struct lys_type, lys_type_free, 1);
break;
case LY_STMT_TYPEDEF:
EXTCOMPLEX_FREE_STRUCT(LY_STMT_TYPEDEF, struct lys_tpdf, lys_tpdf_free, 1);
break;
case LY_STMT_IFFEATURE:
EXTCOMPLEX_FREE_STRUCT(LY_STMT_IFFEATURE, struct lys_iffeature, lys_iffeature_free, 0, 1, 0);
break;
case LY_STMT_MAX:
case LY_STMT_MIN:
case LY_STMT_POSITION:
case LY_STMT_VALUE:
pp = (void**)&((struct lys_ext_instance_complex *)e[i])->content[substmt[j].offset];
if (substmt[j].cardinality >= LY_STMT_CARD_SOME && *pp) {
for(k = 0; ((uint32_t**)(*pp))[k]; k++) {
free(((uint32_t**)(*pp))[k]);
}
}
free(*pp);
break;
case LY_STMT_DIGITS:
if (substmt[j].cardinality >= LY_STMT_CARD_SOME) {
/* free the array */
pp = (void**)&((struct lys_ext_instance_complex *)e[i])->content[substmt[j].offset];
free(*pp);
}
break;
case LY_STMT_MODULE:
/* modules are part of the context, so they will be freed there */
if (substmt[j].cardinality >= LY_STMT_CARD_SOME) {
/* free the array */
pp = (void**)&((struct lys_ext_instance_complex *)e[i])->content[substmt[j].offset];
free(*pp);
}
break;
case LY_STMT_ACTION:
case LY_STMT_ANYDATA:
case LY_STMT_ANYXML:
case LY_STMT_CASE:
case LY_STMT_CHOICE:
case LY_STMT_CONTAINER:
case LY_STMT_GROUPING:
case LY_STMT_INPUT:
case LY_STMT_LEAF:
case LY_STMT_LEAFLIST:
case LY_STMT_LIST:
case LY_STMT_NOTIFICATION:
case LY_STMT_OUTPUT:
case LY_STMT_RPC:
case LY_STMT_USES:
pp = (void**)&((struct lys_ext_instance_complex *)e[i])->content[substmt[j].offset];
LY_TREE_FOR_SAFE((struct lys_node *)(*pp), snext, siter) {
lys_node_free(siter, NULL, 0);
}
*pp = NULL;
break;
case LY_STMT_UNIQUE:
pp = lys_ext_complex_get_substmt(LY_STMT_UNIQUE, (struct lys_ext_instance_complex *)e[i], NULL);
if (!pp || !(*pp)) {
break;
}
if (substmt[j].cardinality >= LY_STMT_CARD_SOME) { /* process array */
for (start = pp = *pp; *pp; pp++) {
for (k = 0; k < (*(struct lys_unique**)pp)->expr_size; k++) {
lydict_remove(ctx, (*(struct lys_unique**)pp)->expr[k]);
}
free((*(struct lys_unique**)pp)->expr);
free(*pp);
}
free(start);
} else { /* single item */
for (k = 0; k < (*(struct lys_unique**)pp)->expr_size; k++) {
lydict_remove(ctx, (*(struct lys_unique**)pp)->expr[k]);
}
free((*(struct lys_unique**)pp)->expr);
free(*pp);
}
break;
case LY_STMT_LENGTH:
case LY_STMT_MUST:
case LY_STMT_PATTERN:
case LY_STMT_RANGE:
EXTCOMPLEX_FREE_STRUCT(substmt[j].stmt, struct lys_restr, lys_restr_free, 1);
break;
case LY_STMT_WHEN:
EXTCOMPLEX_FREE_STRUCT(LY_STMT_WHEN, struct lys_when, lys_when_free, 0);
break;
case LY_STMT_REVISION:
pp = lys_ext_complex_get_substmt(LY_STMT_REVISION, (struct lys_ext_instance_complex *)e[i], NULL);
if (!pp || !(*pp)) {
break;
}
if (substmt[j].cardinality >= LY_STMT_CARD_SOME) { /* process array */
for (start = pp = *pp; *pp; pp++) {
lydict_remove(ctx, (*(struct lys_revision**)pp)->dsc);
lydict_remove(ctx, (*(struct lys_revision**)pp)->ref);
lys_extension_instances_free(ctx, (*(struct lys_revision**)pp)->ext,
(*(struct lys_revision**)pp)->ext_size, private_destructor);
free(*pp);
}
free(start);
} else { /* single item */
lydict_remove(ctx, (*(struct lys_revision**)pp)->dsc);
lydict_remove(ctx, (*(struct lys_revision**)pp)->ref);
lys_extension_instances_free(ctx, (*(struct lys_revision**)pp)->ext,
(*(struct lys_revision**)pp)->ext_size, private_destructor);
free(*pp);
}
break;
default:
/* nothing to free */
break;
}
}
}
free(e[i]);
}
free(e);
#undef EXTCOMPLEX_FREE_STRUCT
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1359_3 |
crossvul-cpp_data_good_941_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% SSSSS TTTTT AAA TTTTT IIIII SSSSS TTTTT IIIII CCCC %
% SS T A A T I SS T I C %
% SSS T AAAAA T I SSS T I C %
% SS T A A T I SS T I C %
% SSSSS T A A T IIIII SSSSS T IIIII CCCC %
% %
% %
% MagickCore Image Statistical Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/accelerate-private.h"
#include "magick/animate.h"
#include "magick/animate.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/cache-private.h"
#include "magick/cache-view.h"
#include "magick/client.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/composite.h"
#include "magick/composite-private.h"
#include "magick/compress.h"
#include "magick/constitute.h"
#include "magick/deprecate.h"
#include "magick/display.h"
#include "magick/draw.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/gem.h"
#include "magick/geometry.h"
#include "magick/list.h"
#include "magick/image-private.h"
#include "magick/magic.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/paint.h"
#include "magick/pixel-private.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantize.h"
#include "magick/random_.h"
#include "magick/random-private.h"
#include "magick/resource_.h"
#include "magick/segment.h"
#include "magick/semaphore.h"
#include "magick/signature-private.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/thread-private.h"
#include "magick/timer.h"
#include "magick/utility.h"
#include "magick/version.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E v a l u a t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% EvaluateImage() applies a value to the image with an arithmetic, relational,
% or logical operator to an image. Use these operations to lighten or darken
% an image, to increase or decrease contrast in an image, or to produce the
% "negative" of an image.
%
% The format of the EvaluateImageChannel method is:
%
% MagickBooleanType EvaluateImage(Image *image,
% const MagickEvaluateOperator op,const double value,
% ExceptionInfo *exception)
% MagickBooleanType EvaluateImages(Image *images,
% const MagickEvaluateOperator op,const double value,
% ExceptionInfo *exception)
% MagickBooleanType EvaluateImageChannel(Image *image,
% const ChannelType channel,const MagickEvaluateOperator op,
% const double value,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o op: A channel op.
%
% o value: A value value.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickPixelPacket **DestroyPixelThreadSet(MagickPixelPacket **pixels)
{
register ssize_t
i;
assert(pixels != (MagickPixelPacket **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (pixels[i] != (MagickPixelPacket *) NULL)
pixels[i]=(MagickPixelPacket *) RelinquishMagickMemory(pixels[i]);
pixels=(MagickPixelPacket **) RelinquishMagickMemory(pixels);
return(pixels);
}
static MagickPixelPacket **AcquirePixelThreadSet(const Image *images)
{
const Image
*next;
MagickPixelPacket
**pixels;
register ssize_t
i,
j;
size_t
columns,
rows;
rows=MagickMax(GetImageListLength(images),
(size_t) GetMagickResourceLimit(ThreadResource));
pixels=(MagickPixelPacket **) AcquireQuantumMemory(rows,sizeof(*pixels));
if (pixels == (MagickPixelPacket **) NULL)
return((MagickPixelPacket **) NULL);
columns=images->columns;
for (next=images; next != (Image *) NULL; next=next->next)
columns=MagickMax(next->columns,columns);
for (i=0; i < (ssize_t) rows; i++)
{
pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(columns,
sizeof(**pixels));
if (pixels[i] == (MagickPixelPacket *) NULL)
return(DestroyPixelThreadSet(pixels));
for (j=0; j < (ssize_t) columns; j++)
GetMagickPixelPacket(images,&pixels[i][j]);
}
return(pixels);
}
static inline double EvaluateMax(const double x,const double y)
{
if (x > y)
return(x);
return(y);
}
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int IntensityCompare(const void *x,const void *y)
{
const MagickPixelPacket
*color_1,
*color_2;
int
intensity;
color_1=(const MagickPixelPacket *) x;
color_2=(const MagickPixelPacket *) y;
intensity=(int) MagickPixelIntensity(color_2)-(int)
MagickPixelIntensity(color_1);
return(intensity);
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info,
const Quantum pixel,const MagickEvaluateOperator op,
const MagickRealType value)
{
MagickRealType
result;
result=0.0;
switch (op)
{
case UndefinedEvaluateOperator:
break;
case AbsEvaluateOperator:
{
result=(MagickRealType) fabs((double) (pixel+value));
break;
}
case AddEvaluateOperator:
{
result=(MagickRealType) (pixel+value);
break;
}
case AddModulusEvaluateOperator:
{
/*
This returns a 'floored modulus' of the addition which is a
positive result. It differs from % or fmod() which returns a
'truncated modulus' result, where floor() is replaced by trunc()
and could return a negative result (which is clipped).
*/
result=pixel+value;
result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0));
break;
}
case AndEvaluateOperator:
{
result=(MagickRealType) ((size_t) pixel & (size_t) (value+0.5));
break;
}
case CosineEvaluateOperator:
{
result=(MagickRealType) (QuantumRange*(0.5*cos((double) (2.0*MagickPI*
QuantumScale*pixel*value))+0.5));
break;
}
case DivideEvaluateOperator:
{
result=pixel/(value == 0.0 ? 1.0 : value);
break;
}
case ExponentialEvaluateOperator:
{
result=(MagickRealType) (QuantumRange*exp((double) (value*QuantumScale*
pixel)));
break;
}
case GaussianNoiseEvaluateOperator:
{
result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
GaussianNoise,value);
break;
}
case ImpulseNoiseEvaluateOperator:
{
result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
ImpulseNoise,value);
break;
}
case LaplacianNoiseEvaluateOperator:
{
result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
LaplacianNoise,value);
break;
}
case LeftShiftEvaluateOperator:
{
result=(MagickRealType) ((size_t) pixel << (size_t) (value+0.5));
break;
}
case LogEvaluateOperator:
{
if ((QuantumScale*pixel) >= MagickEpsilon)
result=(MagickRealType) (QuantumRange*log((double) (QuantumScale*value*
pixel+1.0))/log((double) (value+1.0)));
break;
}
case MaxEvaluateOperator:
{
result=(MagickRealType) EvaluateMax((double) pixel,value);
break;
}
case MeanEvaluateOperator:
{
result=(MagickRealType) (pixel+value);
break;
}
case MedianEvaluateOperator:
{
result=(MagickRealType) (pixel+value);
break;
}
case MinEvaluateOperator:
{
result=(MagickRealType) MagickMin((double) pixel,value);
break;
}
case MultiplicativeNoiseEvaluateOperator:
{
result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
MultiplicativeGaussianNoise,value);
break;
}
case MultiplyEvaluateOperator:
{
result=(MagickRealType) (value*pixel);
break;
}
case OrEvaluateOperator:
{
result=(MagickRealType) ((size_t) pixel | (size_t) (value+0.5));
break;
}
case PoissonNoiseEvaluateOperator:
{
result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
PoissonNoise,value);
break;
}
case PowEvaluateOperator:
{
result=(MagickRealType) (QuantumRange*pow((double) (QuantumScale*pixel),
(double) value));
break;
}
case RightShiftEvaluateOperator:
{
result=(MagickRealType) ((size_t) pixel >> (size_t) (value+0.5));
break;
}
case RootMeanSquareEvaluateOperator:
{
result=(MagickRealType) (pixel*pixel+value);
break;
}
case SetEvaluateOperator:
{
result=value;
break;
}
case SineEvaluateOperator:
{
result=(MagickRealType) (QuantumRange*(0.5*sin((double) (2.0*MagickPI*
QuantumScale*pixel*value))+0.5));
break;
}
case SubtractEvaluateOperator:
{
result=(MagickRealType) (pixel-value);
break;
}
case SumEvaluateOperator:
{
result=(MagickRealType) (pixel+value);
break;
}
case ThresholdEvaluateOperator:
{
result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 :
QuantumRange);
break;
}
case ThresholdBlackEvaluateOperator:
{
result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : pixel);
break;
}
case ThresholdWhiteEvaluateOperator:
{
result=(MagickRealType) (((MagickRealType) pixel > value) ? QuantumRange :
pixel);
break;
}
case UniformNoiseEvaluateOperator:
{
result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
UniformNoise,value);
break;
}
case XorEvaluateOperator:
{
result=(MagickRealType) ((size_t) pixel ^ (size_t) (value+0.5));
break;
}
}
return(result);
}
static Image *AcquireImageCanvas(const Image *images,ExceptionInfo *exception)
{
const Image
*p,
*q;
size_t
columns,
number_channels,
rows;
q=images;
columns=images->columns;
rows=images->rows;
number_channels=0;
for (p=images; p != (Image *) NULL; p=p->next)
{
size_t
channels;
channels=3;
if (p->matte != MagickFalse)
channels+=1;
if (p->colorspace == CMYKColorspace)
channels+=1;
if (channels > number_channels)
{
number_channels=channels;
q=p;
}
if (p->columns > columns)
columns=p->columns;
if (p->rows > rows)
rows=p->rows;
}
return(CloneImage(q,columns,rows,MagickTrue,exception));
}
MagickExport MagickBooleanType EvaluateImage(Image *image,
const MagickEvaluateOperator op,const double value,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=EvaluateImageChannel(image,CompositeChannels,op,value,exception);
return(status);
}
MagickExport Image *EvaluateImages(const Image *images,
const MagickEvaluateOperator op,ExceptionInfo *exception)
{
#define EvaluateImageTag "Evaluate/Image"
CacheView
*evaluate_view;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
**magick_restrict evaluate_pixels,
zero;
RandomInfo
**magick_restrict random_info;
size_t
number_images;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
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);
image=AcquireImageCanvas(images,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
InheritException(exception,&image->exception);
image=DestroyImage(image);
return((Image *) NULL);
}
evaluate_pixels=AcquirePixelThreadSet(images);
if (evaluate_pixels == (MagickPixelPacket **) NULL)
{
image=DestroyImage(image);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
return((Image *) NULL);
}
/*
Evaluate image pixels.
*/
status=MagickTrue;
progress=0;
number_images=GetImageListLength(images);
GetMagickPixelPacket(images,&zero);
random_info=AcquireRandomInfoThreadSet();
evaluate_view=AcquireAuthenticCacheView(image,exception);
if (op == MedianEvaluateOperator)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,images,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
CacheView
*image_view;
const Image
*next;
const int
id = GetOpenMPThreadId();
register IndexPacket
*magick_restrict evaluate_indexes;
register MagickPixelPacket
*evaluate_pixel;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view);
evaluate_pixel=evaluate_pixels[id];
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) number_images; i++)
evaluate_pixel[i]=zero;
next=images;
for (i=0; i < (ssize_t) number_images; i++)
{
register const IndexPacket
*indexes;
register const PixelPacket
*p;
image_view=AcquireVirtualCacheView(next,exception);
p=GetCacheViewVirtualPixels(image_view,x,y,1,1,exception);
if (p == (const PixelPacket *) NULL)
{
image_view=DestroyCacheView(image_view);
break;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
evaluate_pixel[i].red=ApplyEvaluateOperator(random_info[id],
GetPixelRed(p),op,evaluate_pixel[i].red);
evaluate_pixel[i].green=ApplyEvaluateOperator(random_info[id],
GetPixelGreen(p),op,evaluate_pixel[i].green);
evaluate_pixel[i].blue=ApplyEvaluateOperator(random_info[id],
GetPixelBlue(p),op,evaluate_pixel[i].blue);
evaluate_pixel[i].opacity=ApplyEvaluateOperator(random_info[id],
GetPixelAlpha(p),op,evaluate_pixel[i].opacity);
if (image->colorspace == CMYKColorspace)
evaluate_pixel[i].index=ApplyEvaluateOperator(random_info[id],
*indexes,op,evaluate_pixel[i].index);
image_view=DestroyCacheView(image_view);
next=GetNextImageInList(next);
}
qsort((void *) evaluate_pixel,number_images,sizeof(*evaluate_pixel),
IntensityCompare);
SetPixelRed(q,ClampToQuantum(evaluate_pixel[i/2].red));
SetPixelGreen(q,ClampToQuantum(evaluate_pixel[i/2].green));
SetPixelBlue(q,ClampToQuantum(evaluate_pixel[i/2].blue));
SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[i/2].opacity));
if (image->colorspace == CMYKColorspace)
SetPixelIndex(evaluate_indexes+i,ClampToQuantum(
evaluate_pixel[i/2].index));
q++;
}
if (SyncCacheViewAuthenticPixels(evaluate_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,EvaluateImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
}
else
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,images,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
CacheView
*image_view;
const Image
*next;
const int
id = GetOpenMPThreadId();
register IndexPacket
*magick_restrict evaluate_indexes;
register ssize_t
i,
x;
register MagickPixelPacket
*evaluate_pixel;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view);
evaluate_pixel=evaluate_pixels[id];
for (x=0; x < (ssize_t) image->columns; x++)
evaluate_pixel[x]=zero;
next=images;
for (i=0; i < (ssize_t) number_images; i++)
{
register const IndexPacket
*indexes;
register const PixelPacket
*p;
image_view=AcquireVirtualCacheView(next,exception);
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,
exception);
if (p == (const PixelPacket *) NULL)
{
image_view=DestroyCacheView(image_view);
break;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
evaluate_pixel[x].red=ApplyEvaluateOperator(random_info[id],
GetPixelRed(p),i == 0 ? AddEvaluateOperator : op,
evaluate_pixel[x].red);
evaluate_pixel[x].green=ApplyEvaluateOperator(random_info[id],
GetPixelGreen(p),i == 0 ? AddEvaluateOperator : op,
evaluate_pixel[x].green);
evaluate_pixel[x].blue=ApplyEvaluateOperator(random_info[id],
GetPixelBlue(p),i == 0 ? AddEvaluateOperator : op,
evaluate_pixel[x].blue);
evaluate_pixel[x].opacity=ApplyEvaluateOperator(random_info[id],
GetPixelAlpha(p),i == 0 ? AddEvaluateOperator : op,
evaluate_pixel[x].opacity);
if (image->colorspace == CMYKColorspace)
evaluate_pixel[x].index=ApplyEvaluateOperator(random_info[id],
GetPixelIndex(indexes+x),i == 0 ? AddEvaluateOperator : op,
evaluate_pixel[x].index);
p++;
}
image_view=DestroyCacheView(image_view);
next=GetNextImageInList(next);
}
if (op == MeanEvaluateOperator)
for (x=0; x < (ssize_t) image->columns; x++)
{
evaluate_pixel[x].red/=number_images;
evaluate_pixel[x].green/=number_images;
evaluate_pixel[x].blue/=number_images;
evaluate_pixel[x].opacity/=number_images;
evaluate_pixel[x].index/=number_images;
}
if (op == RootMeanSquareEvaluateOperator)
for (x=0; x < (ssize_t) image->columns; x++)
{
evaluate_pixel[x].red=sqrt((double) evaluate_pixel[x].red/
number_images);
evaluate_pixel[x].green=sqrt((double) evaluate_pixel[x].green/
number_images);
evaluate_pixel[x].blue=sqrt((double) evaluate_pixel[x].blue/
number_images);
evaluate_pixel[x].opacity=sqrt((double) evaluate_pixel[x].opacity/
number_images);
evaluate_pixel[x].index=sqrt((double) evaluate_pixel[x].index/
number_images);
}
if (op == MultiplyEvaluateOperator)
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
for (j=0; j < (ssize_t) (number_images-1); j++)
{
evaluate_pixel[x].red*=(MagickRealType) QuantumScale;
evaluate_pixel[x].green*=(MagickRealType) QuantumScale;
evaluate_pixel[x].blue*=(MagickRealType) QuantumScale;
evaluate_pixel[x].opacity*=(MagickRealType) QuantumScale;
evaluate_pixel[x].index*=(MagickRealType) QuantumScale;
}
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ClampToQuantum(evaluate_pixel[x].red));
SetPixelGreen(q,ClampToQuantum(evaluate_pixel[x].green));
SetPixelBlue(q,ClampToQuantum(evaluate_pixel[x].blue));
SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[x].opacity));
if (image->colorspace == CMYKColorspace)
SetPixelIndex(evaluate_indexes+x,ClampToQuantum(
evaluate_pixel[x].index));
q++;
}
if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(images,EvaluateImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
}
evaluate_view=DestroyCacheView(evaluate_view);
evaluate_pixels=DestroyPixelThreadSet(evaluate_pixels);
random_info=DestroyRandomInfoThreadSet(random_info);
if (status == MagickFalse)
image=DestroyImage(image);
return(image);
}
MagickExport MagickBooleanType EvaluateImageChannel(Image *image,
const ChannelType channel,const MagickEvaluateOperator op,const double value,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
RandomInfo
**magick_restrict random_info;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
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);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
InheritException(exception,&image->exception);
return(MagickFalse);
}
status=MagickTrue;
progress=0;
random_info=AcquireRandomInfoThreadSet();
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register IndexPacket
*magick_restrict indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickRealType
result;
if ((channel & RedChannel) != 0)
{
result=ApplyEvaluateOperator(random_info[id],GetPixelRed(q),op,value);
if (op == MeanEvaluateOperator)
result/=2.0;
SetPixelRed(q,ClampToQuantum(result));
}
if ((channel & GreenChannel) != 0)
{
result=ApplyEvaluateOperator(random_info[id],GetPixelGreen(q),op,
value);
if (op == MeanEvaluateOperator)
result/=2.0;
SetPixelGreen(q,ClampToQuantum(result));
}
if ((channel & BlueChannel) != 0)
{
result=ApplyEvaluateOperator(random_info[id],GetPixelBlue(q),op,
value);
if (op == MeanEvaluateOperator)
result/=2.0;
SetPixelBlue(q,ClampToQuantum(result));
}
if ((channel & OpacityChannel) != 0)
{
if (image->matte == MagickFalse)
{
result=ApplyEvaluateOperator(random_info[id],GetPixelOpacity(q),
op,value);
if (op == MeanEvaluateOperator)
result/=2.0;
SetPixelOpacity(q,ClampToQuantum(result));
}
else
{
result=ApplyEvaluateOperator(random_info[id],GetPixelAlpha(q),
op,value);
if (op == MeanEvaluateOperator)
result/=2.0;
SetPixelAlpha(q,ClampToQuantum(result));
}
}
if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL))
{
result=ApplyEvaluateOperator(random_info[id],GetPixelIndex(indexes+x),
op,value);
if (op == MeanEvaluateOperator)
result/=2.0;
SetPixelIndex(indexes+x,ClampToQuantum(result));
}
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,EvaluateImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
random_info=DestroyRandomInfoThreadSet(random_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F u n c t i o n I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FunctionImage() applies a value to the image with an arithmetic, relational,
% or logical operator to an image. Use these operations to lighten or darken
% an image, to increase or decrease contrast in an image, or to produce the
% "negative" of an image.
%
% The format of the FunctionImageChannel method is:
%
% MagickBooleanType FunctionImage(Image *image,
% const MagickFunction function,const ssize_t number_parameters,
% const double *parameters,ExceptionInfo *exception)
% MagickBooleanType FunctionImageChannel(Image *image,
% const ChannelType channel,const MagickFunction function,
% const ssize_t number_parameters,const double *argument,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o function: A channel function.
%
% o parameters: one or more parameters.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Quantum ApplyFunction(Quantum pixel,const MagickFunction function,
const size_t number_parameters,const double *parameters,
ExceptionInfo *exception)
{
MagickRealType
result;
register ssize_t
i;
(void) exception;
result=0.0;
switch (function)
{
case PolynomialFunction:
{
/*
* Polynomial
* Parameters: polynomial constants, highest to lowest order
* For example: c0*x^3 + c1*x^2 + c2*x + c3
*/
result=0.0;
for (i=0; i < (ssize_t) number_parameters; i++)
result=result*QuantumScale*pixel + parameters[i];
result*=QuantumRange;
break;
}
case SinusoidFunction:
{
/* Sinusoid Function
* Parameters: Freq, Phase, Ampl, bias
*/
double freq,phase,ampl,bias;
freq = ( number_parameters >= 1 ) ? parameters[0] : 1.0;
phase = ( number_parameters >= 2 ) ? parameters[1] : 0.0;
ampl = ( number_parameters >= 3 ) ? parameters[2] : 0.5;
bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5;
result=(MagickRealType) (QuantumRange*(ampl*sin((double) (2.0*MagickPI*
(freq*QuantumScale*pixel + phase/360.0) )) + bias ) );
break;
}
case ArcsinFunction:
{
/* Arcsin Function (peged at range limits for invalid results)
* Parameters: Width, Center, Range, Bias
*/
double width,range,center,bias;
width = ( number_parameters >= 1 ) ? parameters[0] : 1.0;
center = ( number_parameters >= 2 ) ? parameters[1] : 0.5;
range = ( number_parameters >= 3 ) ? parameters[2] : 1.0;
bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5;
result = 2.0/width*(QuantumScale*pixel - center);
if ( result <= -1.0 )
result = bias - range/2.0;
else if ( result >= 1.0 )
result = bias + range/2.0;
else
result=(MagickRealType) (range/MagickPI*asin((double) result)+bias);
result *= QuantumRange;
break;
}
case ArctanFunction:
{
/* Arctan Function
* Parameters: Slope, Center, Range, Bias
*/
double slope,range,center,bias;
slope = ( number_parameters >= 1 ) ? parameters[0] : 1.0;
center = ( number_parameters >= 2 ) ? parameters[1] : 0.5;
range = ( number_parameters >= 3 ) ? parameters[2] : 1.0;
bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5;
result=(MagickRealType) (MagickPI*slope*(QuantumScale*pixel-center));
result=(MagickRealType) (QuantumRange*(range/MagickPI*atan((double)
result) + bias ) );
break;
}
case UndefinedFunction:
break;
}
return(ClampToQuantum(result));
}
MagickExport MagickBooleanType FunctionImage(Image *image,
const MagickFunction function,const size_t number_parameters,
const double *parameters,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=FunctionImageChannel(image,CompositeChannels,function,
number_parameters,parameters,exception);
return(status);
}
MagickExport MagickBooleanType FunctionImageChannel(Image *image,
const ChannelType channel,const MagickFunction function,
const size_t number_parameters,const double *parameters,
ExceptionInfo *exception)
{
#define FunctionImageTag "Function/Image "
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
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);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
InheritException(exception,&image->exception);
return(MagickFalse);
}
#if defined(MAGICKCORE_OPENCL_SUPPORT)
status=AccelerateFunctionImage(image,channel,function,number_parameters,
parameters,exception);
if (status != MagickFalse)
return(status);
#endif
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
SetPixelRed(q,ApplyFunction(GetPixelRed(q),function,
number_parameters,parameters,exception));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ApplyFunction(GetPixelGreen(q),function,
number_parameters,parameters,exception));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ApplyFunction(GetPixelBlue(q),function,
number_parameters,parameters,exception));
if ((channel & OpacityChannel) != 0)
{
if (image->matte == MagickFalse)
SetPixelOpacity(q,ApplyFunction(GetPixelOpacity(q),function,
number_parameters,parameters,exception));
else
SetPixelAlpha(q,ApplyFunction((Quantum) GetPixelAlpha(q),function,
number_parameters,parameters,exception));
}
if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL))
SetPixelIndex(indexes+x,ApplyFunction(GetPixelIndex(indexes+x),function,
number_parameters,parameters,exception));
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,FunctionImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l E n t r o p y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelEntropy() returns the entropy of one or more image channels.
%
% The format of the GetImageChannelEntropy method is:
%
% MagickBooleanType GetImageChannelEntropy(const Image *image,
% const ChannelType channel,double *entropy,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o entropy: the average entropy of the selected channels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageEntropy(const Image *image,
double *entropy,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=GetImageChannelEntropy(image,CompositeChannels,entropy,exception);
return(status);
}
MagickExport MagickBooleanType GetImageChannelEntropy(const Image *image,
const ChannelType channel,double *entropy,ExceptionInfo *exception)
{
ChannelStatistics
*channel_statistics;
size_t
channels;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
channel_statistics=GetImageChannelStatistics(image,exception);
if (channel_statistics == (ChannelStatistics *) NULL)
return(MagickFalse);
channels=0;
channel_statistics[CompositeChannels].entropy=0.0;
if ((channel & RedChannel) != 0)
{
channel_statistics[CompositeChannels].entropy+=
channel_statistics[RedChannel].entropy;
channels++;
}
if ((channel & GreenChannel) != 0)
{
channel_statistics[CompositeChannels].entropy+=
channel_statistics[GreenChannel].entropy;
channels++;
}
if ((channel & BlueChannel) != 0)
{
channel_statistics[CompositeChannels].entropy+=
channel_statistics[BlueChannel].entropy;
channels++;
}
if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse))
{
channel_statistics[CompositeChannels].entropy+=
channel_statistics[OpacityChannel].entropy;
channels++;
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
{
channel_statistics[CompositeChannels].entropy+=
channel_statistics[BlackChannel].entropy;
channels++;
}
channel_statistics[CompositeChannels].entropy/=channels;
*entropy=channel_statistics[CompositeChannels].entropy;
channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
channel_statistics);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t I m a g e C h a n n e l E x t r e m a %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelExtrema() returns the extrema of one or more image channels.
%
% The format of the GetImageChannelExtrema method is:
%
% MagickBooleanType GetImageChannelExtrema(const Image *image,
% const ChannelType channel,size_t *minima,size_t *maxima,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o minima: the minimum value in the channel.
%
% o maxima: the maximum value in the channel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageExtrema(const Image *image,
size_t *minima,size_t *maxima,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=GetImageChannelExtrema(image,CompositeChannels,minima,maxima,
exception);
return(status);
}
MagickExport MagickBooleanType GetImageChannelExtrema(const Image *image,
const ChannelType channel,size_t *minima,size_t *maxima,
ExceptionInfo *exception)
{
double
max,
min;
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=GetImageChannelRange(image,channel,&min,&max,exception);
*minima=(size_t) ceil(min-0.5);
*maxima=(size_t) floor(max+0.5);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l K u r t o s i s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelKurtosis() returns the kurtosis and skewness of one or more
% image channels.
%
% The format of the GetImageChannelKurtosis method is:
%
% MagickBooleanType GetImageChannelKurtosis(const Image *image,
% const ChannelType channel,double *kurtosis,double *skewness,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o kurtosis: the kurtosis of the channel.
%
% o skewness: the skewness of the channel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageKurtosis(const Image *image,
double *kurtosis,double *skewness,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=GetImageChannelKurtosis(image,CompositeChannels,kurtosis,skewness,
exception);
return(status);
}
MagickExport MagickBooleanType GetImageChannelKurtosis(const Image *image,
const ChannelType channel,double *kurtosis,double *skewness,
ExceptionInfo *exception)
{
double
area,
mean,
standard_deviation,
sum_squares,
sum_cubes,
sum_fourth_power;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
*kurtosis=0.0;
*skewness=0.0;
area=0.0;
mean=0.0;
standard_deviation=0.0;
sum_squares=0.0;
sum_cubes=0.0;
sum_fourth_power=0.0;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
{
mean+=GetPixelRed(p);
sum_squares+=(double) GetPixelRed(p)*GetPixelRed(p);
sum_cubes+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p);
sum_fourth_power+=(double) GetPixelRed(p)*GetPixelRed(p)*
GetPixelRed(p)*GetPixelRed(p);
area++;
}
if ((channel & GreenChannel) != 0)
{
mean+=GetPixelGreen(p);
sum_squares+=(double) GetPixelGreen(p)*GetPixelGreen(p);
sum_cubes+=(double) GetPixelGreen(p)*GetPixelGreen(p)*
GetPixelGreen(p);
sum_fourth_power+=(double) GetPixelGreen(p)*GetPixelGreen(p)*
GetPixelGreen(p)*GetPixelGreen(p);
area++;
}
if ((channel & BlueChannel) != 0)
{
mean+=GetPixelBlue(p);
sum_squares+=(double) GetPixelBlue(p)*GetPixelBlue(p);
sum_cubes+=(double) GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p);
sum_fourth_power+=(double) GetPixelBlue(p)*GetPixelBlue(p)*
GetPixelBlue(p)*GetPixelBlue(p);
area++;
}
if ((channel & OpacityChannel) != 0)
{
mean+=GetPixelAlpha(p);
sum_squares+=(double) GetPixelOpacity(p)*GetPixelAlpha(p);
sum_cubes+=(double) GetPixelOpacity(p)*GetPixelAlpha(p)*
GetPixelAlpha(p);
sum_fourth_power+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)*
GetPixelAlpha(p)*GetPixelAlpha(p);
area++;
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
{
double
index;
index=(double) GetPixelIndex(indexes+x);
mean+=index;
sum_squares+=index*index;
sum_cubes+=index*index*index;
sum_fourth_power+=index*index*index*index;
area++;
}
p++;
}
}
if (y < (ssize_t) image->rows)
return(MagickFalse);
if (area != 0.0)
{
mean/=area;
sum_squares/=area;
sum_cubes/=area;
sum_fourth_power/=area;
}
standard_deviation=sqrt(sum_squares-(mean*mean));
if (standard_deviation != 0.0)
{
*kurtosis=sum_fourth_power-4.0*mean*sum_cubes+6.0*mean*mean*sum_squares-
3.0*mean*mean*mean*mean;
*kurtosis/=standard_deviation*standard_deviation*standard_deviation*
standard_deviation;
*kurtosis-=3.0;
*skewness=sum_cubes-3.0*mean*sum_squares+2.0*mean*mean*mean;
*skewness/=standard_deviation*standard_deviation*standard_deviation;
}
return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l M e a n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelMean() returns the mean and standard deviation of one or more
% image channels.
%
% The format of the GetImageChannelMean method is:
%
% MagickBooleanType GetImageChannelMean(const Image *image,
% const ChannelType channel,double *mean,double *standard_deviation,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o mean: the average value in the channel.
%
% o standard_deviation: the standard deviation of the channel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean,
double *standard_deviation,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=GetImageChannelMean(image,CompositeChannels,mean,standard_deviation,
exception);
return(status);
}
MagickExport MagickBooleanType GetImageChannelMean(const Image *image,
const ChannelType channel,double *mean,double *standard_deviation,
ExceptionInfo *exception)
{
ChannelStatistics
*channel_statistics;
size_t
channels;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
channel_statistics=GetImageChannelStatistics(image,exception);
if (channel_statistics == (ChannelStatistics *) NULL)
return(MagickFalse);
channels=0;
channel_statistics[CompositeChannels].mean=0.0;
channel_statistics[CompositeChannels].standard_deviation=0.0;
if ((channel & RedChannel) != 0)
{
channel_statistics[CompositeChannels].mean+=
channel_statistics[RedChannel].mean;
channel_statistics[CompositeChannels].standard_deviation+=
channel_statistics[RedChannel].standard_deviation;
channels++;
}
if ((channel & GreenChannel) != 0)
{
channel_statistics[CompositeChannels].mean+=
channel_statistics[GreenChannel].mean;
channel_statistics[CompositeChannels].standard_deviation+=
channel_statistics[GreenChannel].standard_deviation;
channels++;
}
if ((channel & BlueChannel) != 0)
{
channel_statistics[CompositeChannels].mean+=
channel_statistics[BlueChannel].mean;
channel_statistics[CompositeChannels].standard_deviation+=
channel_statistics[BlueChannel].standard_deviation;
channels++;
}
if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse))
{
channel_statistics[CompositeChannels].mean+=
(QuantumRange-channel_statistics[OpacityChannel].mean);
channel_statistics[CompositeChannels].standard_deviation+=
channel_statistics[OpacityChannel].standard_deviation;
channels++;
}
if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace))
{
channel_statistics[CompositeChannels].mean+=
channel_statistics[BlackChannel].mean;
channel_statistics[CompositeChannels].standard_deviation+=
channel_statistics[CompositeChannels].standard_deviation;
channels++;
}
channel_statistics[CompositeChannels].mean/=channels;
channel_statistics[CompositeChannels].standard_deviation/=channels;
*mean=channel_statistics[CompositeChannels].mean;
*standard_deviation=channel_statistics[CompositeChannels].standard_deviation;
channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
channel_statistics);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l M o m e n t s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelMoments() returns the normalized moments of one or more image
% channels.
%
% The format of the GetImageChannelMoments method is:
%
% ChannelMoments *GetImageChannelMoments(const Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ChannelMoments *GetImageChannelMoments(const Image *image,
ExceptionInfo *exception)
{
#define MaxNumberImageMoments 8
ChannelMoments
*channel_moments;
double
M00[CompositeChannels+1],
M01[CompositeChannels+1],
M02[CompositeChannels+1],
M03[CompositeChannels+1],
M10[CompositeChannels+1],
M11[CompositeChannels+1],
M12[CompositeChannels+1],
M20[CompositeChannels+1],
M21[CompositeChannels+1],
M22[CompositeChannels+1],
M30[CompositeChannels+1];
MagickPixelPacket
pixel;
PointInfo
centroid[CompositeChannels+1];
ssize_t
channel,
channels,
y;
size_t
length;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
length=CompositeChannels+1UL;
channel_moments=(ChannelMoments *) AcquireQuantumMemory(length,
sizeof(*channel_moments));
if (channel_moments == (ChannelMoments *) NULL)
return(channel_moments);
(void) memset(channel_moments,0,length*sizeof(*channel_moments));
(void) memset(centroid,0,sizeof(centroid));
(void) memset(M00,0,sizeof(M00));
(void) memset(M01,0,sizeof(M01));
(void) memset(M02,0,sizeof(M02));
(void) memset(M03,0,sizeof(M03));
(void) memset(M10,0,sizeof(M10));
(void) memset(M11,0,sizeof(M11));
(void) memset(M12,0,sizeof(M12));
(void) memset(M20,0,sizeof(M20));
(void) memset(M21,0,sizeof(M21));
(void) memset(M22,0,sizeof(M22));
(void) memset(M30,0,sizeof(M30));
GetMagickPixelPacket(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
/*
Compute center of mass (centroid).
*/
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetMagickPixelPacket(image,p,indexes+x,&pixel);
M00[RedChannel]+=QuantumScale*pixel.red;
M10[RedChannel]+=x*QuantumScale*pixel.red;
M01[RedChannel]+=y*QuantumScale*pixel.red;
M00[GreenChannel]+=QuantumScale*pixel.green;
M10[GreenChannel]+=x*QuantumScale*pixel.green;
M01[GreenChannel]+=y*QuantumScale*pixel.green;
M00[BlueChannel]+=QuantumScale*pixel.blue;
M10[BlueChannel]+=x*QuantumScale*pixel.blue;
M01[BlueChannel]+=y*QuantumScale*pixel.blue;
if (image->matte != MagickFalse)
{
M00[OpacityChannel]+=QuantumScale*pixel.opacity;
M10[OpacityChannel]+=x*QuantumScale*pixel.opacity;
M01[OpacityChannel]+=y*QuantumScale*pixel.opacity;
}
if (image->colorspace == CMYKColorspace)
{
M00[IndexChannel]+=QuantumScale*pixel.index;
M10[IndexChannel]+=x*QuantumScale*pixel.index;
M01[IndexChannel]+=y*QuantumScale*pixel.index;
}
p++;
}
}
for (channel=0; channel <= CompositeChannels; channel++)
{
/*
Compute center of mass (centroid).
*/
if (M00[channel] < MagickEpsilon)
{
M00[channel]+=MagickEpsilon;
centroid[channel].x=(double) image->columns/2.0;
centroid[channel].y=(double) image->rows/2.0;
continue;
}
M00[channel]+=MagickEpsilon;
centroid[channel].x=M10[channel]/M00[channel];
centroid[channel].y=M01[channel]/M00[channel];
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
/*
Compute the image moments.
*/
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetMagickPixelPacket(image,p,indexes+x,&pixel);
M11[RedChannel]+=(x-centroid[RedChannel].x)*(y-
centroid[RedChannel].y)*QuantumScale*pixel.red;
M20[RedChannel]+=(x-centroid[RedChannel].x)*(x-
centroid[RedChannel].x)*QuantumScale*pixel.red;
M02[RedChannel]+=(y-centroid[RedChannel].y)*(y-
centroid[RedChannel].y)*QuantumScale*pixel.red;
M21[RedChannel]+=(x-centroid[RedChannel].x)*(x-
centroid[RedChannel].x)*(y-centroid[RedChannel].y)*QuantumScale*
pixel.red;
M12[RedChannel]+=(x-centroid[RedChannel].x)*(y-
centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale*
pixel.red;
M22[RedChannel]+=(x-centroid[RedChannel].x)*(x-
centroid[RedChannel].x)*(y-centroid[RedChannel].y)*(y-
centroid[RedChannel].y)*QuantumScale*pixel.red;
M30[RedChannel]+=(x-centroid[RedChannel].x)*(x-
centroid[RedChannel].x)*(x-centroid[RedChannel].x)*QuantumScale*
pixel.red;
M03[RedChannel]+=(y-centroid[RedChannel].y)*(y-
centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale*
pixel.red;
M11[GreenChannel]+=(x-centroid[GreenChannel].x)*(y-
centroid[GreenChannel].y)*QuantumScale*pixel.green;
M20[GreenChannel]+=(x-centroid[GreenChannel].x)*(x-
centroid[GreenChannel].x)*QuantumScale*pixel.green;
M02[GreenChannel]+=(y-centroid[GreenChannel].y)*(y-
centroid[GreenChannel].y)*QuantumScale*pixel.green;
M21[GreenChannel]+=(x-centroid[GreenChannel].x)*(x-
centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*QuantumScale*
pixel.green;
M12[GreenChannel]+=(x-centroid[GreenChannel].x)*(y-
centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale*
pixel.green;
M22[GreenChannel]+=(x-centroid[GreenChannel].x)*(x-
centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*(y-
centroid[GreenChannel].y)*QuantumScale*pixel.green;
M30[GreenChannel]+=(x-centroid[GreenChannel].x)*(x-
centroid[GreenChannel].x)*(x-centroid[GreenChannel].x)*QuantumScale*
pixel.green;
M03[GreenChannel]+=(y-centroid[GreenChannel].y)*(y-
centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale*
pixel.green;
M11[BlueChannel]+=(x-centroid[BlueChannel].x)*(y-
centroid[BlueChannel].y)*QuantumScale*pixel.blue;
M20[BlueChannel]+=(x-centroid[BlueChannel].x)*(x-
centroid[BlueChannel].x)*QuantumScale*pixel.blue;
M02[BlueChannel]+=(y-centroid[BlueChannel].y)*(y-
centroid[BlueChannel].y)*QuantumScale*pixel.blue;
M21[BlueChannel]+=(x-centroid[BlueChannel].x)*(x-
centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*QuantumScale*
pixel.blue;
M12[BlueChannel]+=(x-centroid[BlueChannel].x)*(y-
centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale*
pixel.blue;
M22[BlueChannel]+=(x-centroid[BlueChannel].x)*(x-
centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*(y-
centroid[BlueChannel].y)*QuantumScale*pixel.blue;
M30[BlueChannel]+=(x-centroid[BlueChannel].x)*(x-
centroid[BlueChannel].x)*(x-centroid[BlueChannel].x)*QuantumScale*
pixel.blue;
M03[BlueChannel]+=(y-centroid[BlueChannel].y)*(y-
centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale*
pixel.blue;
if (image->matte != MagickFalse)
{
M11[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y-
centroid[OpacityChannel].y)*QuantumScale*pixel.opacity;
M20[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x-
centroid[OpacityChannel].x)*QuantumScale*pixel.opacity;
M02[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y-
centroid[OpacityChannel].y)*QuantumScale*pixel.opacity;
M21[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x-
centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)*
QuantumScale*pixel.opacity;
M12[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y-
centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)*
QuantumScale*pixel.opacity;
M22[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x-
centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)*(y-
centroid[OpacityChannel].y)*QuantumScale*pixel.opacity;
M30[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x-
centroid[OpacityChannel].x)*(x-centroid[OpacityChannel].x)*
QuantumScale*pixel.opacity;
M03[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y-
centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)*
QuantumScale*pixel.opacity;
}
if (image->colorspace == CMYKColorspace)
{
M11[IndexChannel]+=(x-centroid[IndexChannel].x)*(y-
centroid[IndexChannel].y)*QuantumScale*pixel.index;
M20[IndexChannel]+=(x-centroid[IndexChannel].x)*(x-
centroid[IndexChannel].x)*QuantumScale*pixel.index;
M02[IndexChannel]+=(y-centroid[IndexChannel].y)*(y-
centroid[IndexChannel].y)*QuantumScale*pixel.index;
M21[IndexChannel]+=(x-centroid[IndexChannel].x)*(x-
centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)*
QuantumScale*pixel.index;
M12[IndexChannel]+=(x-centroid[IndexChannel].x)*(y-
centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)*
QuantumScale*pixel.index;
M22[IndexChannel]+=(x-centroid[IndexChannel].x)*(x-
centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)*(y-
centroid[IndexChannel].y)*QuantumScale*pixel.index;
M30[IndexChannel]+=(x-centroid[IndexChannel].x)*(x-
centroid[IndexChannel].x)*(x-centroid[IndexChannel].x)*
QuantumScale*pixel.index;
M03[IndexChannel]+=(y-centroid[IndexChannel].y)*(y-
centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)*
QuantumScale*pixel.index;
}
p++;
}
}
channels=3;
M00[CompositeChannels]+=(M00[RedChannel]+M00[GreenChannel]+M00[BlueChannel]);
M01[CompositeChannels]+=(M01[RedChannel]+M01[GreenChannel]+M01[BlueChannel]);
M02[CompositeChannels]+=(M02[RedChannel]+M02[GreenChannel]+M02[BlueChannel]);
M03[CompositeChannels]+=(M03[RedChannel]+M03[GreenChannel]+M03[BlueChannel]);
M10[CompositeChannels]+=(M10[RedChannel]+M10[GreenChannel]+M10[BlueChannel]);
M11[CompositeChannels]+=(M11[RedChannel]+M11[GreenChannel]+M11[BlueChannel]);
M12[CompositeChannels]+=(M12[RedChannel]+M12[GreenChannel]+M12[BlueChannel]);
M20[CompositeChannels]+=(M20[RedChannel]+M20[GreenChannel]+M20[BlueChannel]);
M21[CompositeChannels]+=(M21[RedChannel]+M21[GreenChannel]+M21[BlueChannel]);
M22[CompositeChannels]+=(M22[RedChannel]+M22[GreenChannel]+M22[BlueChannel]);
M30[CompositeChannels]+=(M30[RedChannel]+M30[GreenChannel]+M30[BlueChannel]);
if (image->matte != MagickFalse)
{
channels+=1;
M00[CompositeChannels]+=M00[OpacityChannel];
M01[CompositeChannels]+=M01[OpacityChannel];
M02[CompositeChannels]+=M02[OpacityChannel];
M03[CompositeChannels]+=M03[OpacityChannel];
M10[CompositeChannels]+=M10[OpacityChannel];
M11[CompositeChannels]+=M11[OpacityChannel];
M12[CompositeChannels]+=M12[OpacityChannel];
M20[CompositeChannels]+=M20[OpacityChannel];
M21[CompositeChannels]+=M21[OpacityChannel];
M22[CompositeChannels]+=M22[OpacityChannel];
M30[CompositeChannels]+=M30[OpacityChannel];
}
if (image->colorspace == CMYKColorspace)
{
channels+=1;
M00[CompositeChannels]+=M00[IndexChannel];
M01[CompositeChannels]+=M01[IndexChannel];
M02[CompositeChannels]+=M02[IndexChannel];
M03[CompositeChannels]+=M03[IndexChannel];
M10[CompositeChannels]+=M10[IndexChannel];
M11[CompositeChannels]+=M11[IndexChannel];
M12[CompositeChannels]+=M12[IndexChannel];
M20[CompositeChannels]+=M20[IndexChannel];
M21[CompositeChannels]+=M21[IndexChannel];
M22[CompositeChannels]+=M22[IndexChannel];
M30[CompositeChannels]+=M30[IndexChannel];
}
M00[CompositeChannels]/=(double) channels;
M01[CompositeChannels]/=(double) channels;
M02[CompositeChannels]/=(double) channels;
M03[CompositeChannels]/=(double) channels;
M10[CompositeChannels]/=(double) channels;
M11[CompositeChannels]/=(double) channels;
M12[CompositeChannels]/=(double) channels;
M20[CompositeChannels]/=(double) channels;
M21[CompositeChannels]/=(double) channels;
M22[CompositeChannels]/=(double) channels;
M30[CompositeChannels]/=(double) channels;
for (channel=0; channel <= CompositeChannels; channel++)
{
/*
Compute elliptical angle, major and minor axes, eccentricity, & intensity.
*/
channel_moments[channel].centroid=centroid[channel];
channel_moments[channel].ellipse_axis.x=sqrt((2.0/M00[channel])*
((M20[channel]+M02[channel])+sqrt(4.0*M11[channel]*M11[channel]+
(M20[channel]-M02[channel])*(M20[channel]-M02[channel]))));
channel_moments[channel].ellipse_axis.y=sqrt((2.0/M00[channel])*
((M20[channel]+M02[channel])-sqrt(4.0*M11[channel]*M11[channel]+
(M20[channel]-M02[channel])*(M20[channel]-M02[channel]))));
channel_moments[channel].ellipse_angle=RadiansToDegrees(0.5*atan(2.0*
M11[channel]/(M20[channel]-M02[channel]+MagickEpsilon)));
if (fabs(M11[channel]) < MagickEpsilon)
{
if (fabs(M20[channel]-M02[channel]) < MagickEpsilon)
channel_moments[channel].ellipse_angle+=0.0;
else
if ((M20[channel]-M02[channel]) < 0.0)
channel_moments[channel].ellipse_angle+=90.0;
else
channel_moments[channel].ellipse_angle+=0.0;
}
else
if (M11[channel] < 0.0)
{
if (fabs(M20[channel]-M02[channel]) < MagickEpsilon)
channel_moments[channel].ellipse_angle+=0.0;
else
if ((M20[channel]-M02[channel]) < 0.0)
channel_moments[channel].ellipse_angle+=90.0;
else
channel_moments[channel].ellipse_angle+=180.0;
}
else
{
if (fabs(M20[channel]-M02[channel]) < MagickEpsilon)
channel_moments[channel].ellipse_angle+=0.0;
else
if ((M20[channel]-M02[channel]) < 0.0)
channel_moments[channel].ellipse_angle+=90.0;
else
channel_moments[channel].ellipse_angle+=0.0;
}
channel_moments[channel].ellipse_eccentricity=sqrt(1.0-(
channel_moments[channel].ellipse_axis.y/
(channel_moments[channel].ellipse_axis.x+MagickEpsilon)));
channel_moments[channel].ellipse_intensity=M00[channel]/
(MagickPI*channel_moments[channel].ellipse_axis.x*
channel_moments[channel].ellipse_axis.y+MagickEpsilon);
}
for (channel=0; channel <= CompositeChannels; channel++)
{
/*
Normalize image moments.
*/
M10[channel]=0.0;
M01[channel]=0.0;
M11[channel]/=pow(M00[channel],1.0+(1.0+1.0)/2.0);
M20[channel]/=pow(M00[channel],1.0+(2.0+0.0)/2.0);
M02[channel]/=pow(M00[channel],1.0+(0.0+2.0)/2.0);
M21[channel]/=pow(M00[channel],1.0+(2.0+1.0)/2.0);
M12[channel]/=pow(M00[channel],1.0+(1.0+2.0)/2.0);
M22[channel]/=pow(M00[channel],1.0+(2.0+2.0)/2.0);
M30[channel]/=pow(M00[channel],1.0+(3.0+0.0)/2.0);
M03[channel]/=pow(M00[channel],1.0+(0.0+3.0)/2.0);
M00[channel]=1.0;
}
for (channel=0; channel <= CompositeChannels; channel++)
{
/*
Compute Hu invariant moments.
*/
channel_moments[channel].I[0]=M20[channel]+M02[channel];
channel_moments[channel].I[1]=(M20[channel]-M02[channel])*
(M20[channel]-M02[channel])+4.0*M11[channel]*M11[channel];
channel_moments[channel].I[2]=(M30[channel]-3.0*M12[channel])*
(M30[channel]-3.0*M12[channel])+(3.0*M21[channel]-M03[channel])*
(3.0*M21[channel]-M03[channel]);
channel_moments[channel].I[3]=(M30[channel]+M12[channel])*
(M30[channel]+M12[channel])+(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]);
channel_moments[channel].I[4]=(M30[channel]-3.0*M12[channel])*
(M30[channel]+M12[channel])*((M30[channel]+M12[channel])*
(M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]))+(3.0*M21[channel]-M03[channel])*
(M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])*
(M30[channel]+M12[channel])-(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]));
channel_moments[channel].I[5]=(M20[channel]-M02[channel])*
((M30[channel]+M12[channel])*(M30[channel]+M12[channel])-
(M21[channel]+M03[channel])*(M21[channel]+M03[channel]))+
4.0*M11[channel]*(M30[channel]+M12[channel])*(M21[channel]+M03[channel]);
channel_moments[channel].I[6]=(3.0*M21[channel]-M03[channel])*
(M30[channel]+M12[channel])*((M30[channel]+M12[channel])*
(M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]))-(M30[channel]-3*M12[channel])*
(M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])*
(M30[channel]+M12[channel])-(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]));
channel_moments[channel].I[7]=M11[channel]*((M30[channel]+M12[channel])*
(M30[channel]+M12[channel])-(M03[channel]+M21[channel])*
(M03[channel]+M21[channel]))-(M20[channel]-M02[channel])*
(M30[channel]+M12[channel])*(M03[channel]+M21[channel]);
}
if (y < (ssize_t) image->rows)
channel_moments=(ChannelMoments *) RelinquishMagickMemory(channel_moments);
return(channel_moments);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l P e r c e p t u a l H a s h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelPerceptualHash() returns the perceptual hash of one or more
% image channels.
%
% The format of the GetImageChannelPerceptualHash method is:
%
% ChannelPerceptualHash *GetImageChannelPerceptualHash(const Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double MagickLog10(const double x)
{
#define Log10Epsilon (1.0e-11)
if (fabs(x) < Log10Epsilon)
return(log10(Log10Epsilon));
return(log10(fabs(x)));
}
MagickExport ChannelPerceptualHash *GetImageChannelPerceptualHash(
const Image *image,ExceptionInfo *exception)
{
ChannelMoments
*moments;
ChannelPerceptualHash
*perceptual_hash;
Image
*hash_image;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
channel;
/*
Blur then transform to sRGB colorspace.
*/
hash_image=BlurImage(image,0.0,1.0,exception);
if (hash_image == (Image *) NULL)
return((ChannelPerceptualHash *) NULL);
hash_image->depth=8;
status=TransformImageColorspace(hash_image,sRGBColorspace);
if (status == MagickFalse)
return((ChannelPerceptualHash *) NULL);
moments=GetImageChannelMoments(hash_image,exception);
hash_image=DestroyImage(hash_image);
if (moments == (ChannelMoments *) NULL)
return((ChannelPerceptualHash *) NULL);
perceptual_hash=(ChannelPerceptualHash *) AcquireQuantumMemory(
CompositeChannels+1UL,sizeof(*perceptual_hash));
if (perceptual_hash == (ChannelPerceptualHash *) NULL)
return((ChannelPerceptualHash *) NULL);
for (channel=0; channel <= CompositeChannels; channel++)
for (i=0; i < MaximumNumberOfImageMoments; i++)
perceptual_hash[channel].P[i]=(-MagickLog10(moments[channel].I[i]));
moments=(ChannelMoments *) RelinquishMagickMemory(moments);
/*
Blur then transform to HCLp colorspace.
*/
hash_image=BlurImage(image,0.0,1.0,exception);
if (hash_image == (Image *) NULL)
{
perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory(
perceptual_hash);
return((ChannelPerceptualHash *) NULL);
}
hash_image->depth=8;
status=TransformImageColorspace(hash_image,HCLpColorspace);
if (status == MagickFalse)
{
perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory(
perceptual_hash);
return((ChannelPerceptualHash *) NULL);
}
moments=GetImageChannelMoments(hash_image,exception);
hash_image=DestroyImage(hash_image);
if (moments == (ChannelMoments *) NULL)
{
perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory(
perceptual_hash);
return((ChannelPerceptualHash *) NULL);
}
for (channel=0; channel <= CompositeChannels; channel++)
for (i=0; i < MaximumNumberOfImageMoments; i++)
perceptual_hash[channel].Q[i]=(-MagickLog10(moments[channel].I[i]));
moments=(ChannelMoments *) RelinquishMagickMemory(moments);
return(perceptual_hash);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l R a n g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelRange() returns the range of one or more image channels.
%
% The format of the GetImageChannelRange method is:
%
% MagickBooleanType GetImageChannelRange(const Image *image,
% const ChannelType channel,double *minima,double *maxima,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o minima: the minimum value in the channel.
%
% o maxima: the maximum value in the channel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageRange(const Image *image,
double *minima,double *maxima,ExceptionInfo *exception)
{
return(GetImageChannelRange(image,CompositeChannels,minima,maxima,exception));
}
MagickExport MagickBooleanType GetImageChannelRange(const Image *image,
const ChannelType channel,double *minima,double *maxima,
ExceptionInfo *exception)
{
MagickPixelPacket
pixel;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
*maxima=(-MagickMaximumValue);
*minima=MagickMaximumValue;
GetMagickPixelPacket(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetMagickPixelPacket(image,p,indexes+x,&pixel);
if ((channel & RedChannel) != 0)
{
if (pixel.red < *minima)
*minima=(double) pixel.red;
if (pixel.red > *maxima)
*maxima=(double) pixel.red;
}
if ((channel & GreenChannel) != 0)
{
if (pixel.green < *minima)
*minima=(double) pixel.green;
if (pixel.green > *maxima)
*maxima=(double) pixel.green;
}
if ((channel & BlueChannel) != 0)
{
if (pixel.blue < *minima)
*minima=(double) pixel.blue;
if (pixel.blue > *maxima)
*maxima=(double) pixel.blue;
}
if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse))
{
if ((QuantumRange-pixel.opacity) < *minima)
*minima=(double) (QuantumRange-pixel.opacity);
if ((QuantumRange-pixel.opacity) > *maxima)
*maxima=(double) (QuantumRange-pixel.opacity);
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
{
if ((double) pixel.index < *minima)
*minima=(double) pixel.index;
if ((double) pixel.index > *maxima)
*maxima=(double) pixel.index;
}
p++;
}
}
return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l S t a t i s t i c s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelStatistics() returns statistics for each channel in the
% image. The statistics include the channel depth, its minima, maxima, mean,
% standard deviation, kurtosis and skewness. You can access the red channel
% mean, for example, like this:
%
% channel_statistics=GetImageChannelStatistics(image,exception);
% red_mean=channel_statistics[RedChannel].mean;
%
% Use MagickRelinquishMemory() to free the statistics buffer.
%
% The format of the GetImageChannelStatistics method is:
%
% ChannelStatistics *GetImageChannelStatistics(const Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ChannelStatistics *GetImageChannelStatistics(const Image *image,
ExceptionInfo *exception)
{
ChannelStatistics
*channel_statistics;
double
area,
standard_deviation;
MagickPixelPacket
number_bins,
*histogram;
QuantumAny
range;
register ssize_t
i;
size_t
channels,
depth,
length;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
length=CompositeChannels+1UL;
channel_statistics=(ChannelStatistics *) AcquireQuantumMemory(length,
sizeof(*channel_statistics));
histogram=(MagickPixelPacket *) AcquireQuantumMemory(MaxMap+1U,
sizeof(*histogram));
if ((channel_statistics == (ChannelStatistics *) NULL) ||
(histogram == (MagickPixelPacket *) NULL))
{
if (histogram != (MagickPixelPacket *) NULL)
histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram);
if (channel_statistics != (ChannelStatistics *) NULL)
channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
channel_statistics);
return(channel_statistics);
}
(void) memset(channel_statistics,0,length*
sizeof(*channel_statistics));
for (i=0; i <= (ssize_t) CompositeChannels; i++)
{
channel_statistics[i].depth=1;
channel_statistics[i].maxima=(-MagickMaximumValue);
channel_statistics[i].minima=MagickMaximumValue;
}
(void) memset(histogram,0,(MaxMap+1U)*sizeof(*histogram));
(void) memset(&number_bins,0,sizeof(number_bins));
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
/*
Compute pixel statistics.
*/
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; )
{
if (channel_statistics[RedChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[RedChannel].depth;
range=GetQuantumRange(depth);
if (IsPixelAtDepth(GetPixelRed(p),range) == MagickFalse)
{
channel_statistics[RedChannel].depth++;
continue;
}
}
if (channel_statistics[GreenChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[GreenChannel].depth;
range=GetQuantumRange(depth);
if (IsPixelAtDepth(GetPixelGreen(p),range) == MagickFalse)
{
channel_statistics[GreenChannel].depth++;
continue;
}
}
if (channel_statistics[BlueChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[BlueChannel].depth;
range=GetQuantumRange(depth);
if (IsPixelAtDepth(GetPixelBlue(p),range) == MagickFalse)
{
channel_statistics[BlueChannel].depth++;
continue;
}
}
if (image->matte != MagickFalse)
{
if (channel_statistics[OpacityChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[OpacityChannel].depth;
range=GetQuantumRange(depth);
if (IsPixelAtDepth(GetPixelAlpha(p),range) == MagickFalse)
{
channel_statistics[OpacityChannel].depth++;
continue;
}
}
}
if (image->colorspace == CMYKColorspace)
{
if (channel_statistics[BlackChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[BlackChannel].depth;
range=GetQuantumRange(depth);
if (IsPixelAtDepth(GetPixelIndex(indexes+x),range) == MagickFalse)
{
channel_statistics[BlackChannel].depth++;
continue;
}
}
}
if ((double) GetPixelRed(p) < channel_statistics[RedChannel].minima)
channel_statistics[RedChannel].minima=(double) GetPixelRed(p);
if ((double) GetPixelRed(p) > channel_statistics[RedChannel].maxima)
channel_statistics[RedChannel].maxima=(double) GetPixelRed(p);
channel_statistics[RedChannel].sum+=GetPixelRed(p);
channel_statistics[RedChannel].sum_squared+=(double) GetPixelRed(p)*
GetPixelRed(p);
channel_statistics[RedChannel].sum_cubed+=(double)
GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p);
channel_statistics[RedChannel].sum_fourth_power+=(double)
GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p);
if ((double) GetPixelGreen(p) < channel_statistics[GreenChannel].minima)
channel_statistics[GreenChannel].minima=(double) GetPixelGreen(p);
if ((double) GetPixelGreen(p) > channel_statistics[GreenChannel].maxima)
channel_statistics[GreenChannel].maxima=(double) GetPixelGreen(p);
channel_statistics[GreenChannel].sum+=GetPixelGreen(p);
channel_statistics[GreenChannel].sum_squared+=(double) GetPixelGreen(p)*
GetPixelGreen(p);
channel_statistics[GreenChannel].sum_cubed+=(double) GetPixelGreen(p)*
GetPixelGreen(p)*GetPixelGreen(p);
channel_statistics[GreenChannel].sum_fourth_power+=(double)
GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p);
if ((double) GetPixelBlue(p) < channel_statistics[BlueChannel].minima)
channel_statistics[BlueChannel].minima=(double) GetPixelBlue(p);
if ((double) GetPixelBlue(p) > channel_statistics[BlueChannel].maxima)
channel_statistics[BlueChannel].maxima=(double) GetPixelBlue(p);
channel_statistics[BlueChannel].sum+=GetPixelBlue(p);
channel_statistics[BlueChannel].sum_squared+=(double) GetPixelBlue(p)*
GetPixelBlue(p);
channel_statistics[BlueChannel].sum_cubed+=(double) GetPixelBlue(p)*
GetPixelBlue(p)*GetPixelBlue(p);
channel_statistics[BlueChannel].sum_fourth_power+=(double)
GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p);
histogram[ScaleQuantumToMap(GetPixelRed(p))].red++;
histogram[ScaleQuantumToMap(GetPixelGreen(p))].green++;
histogram[ScaleQuantumToMap(GetPixelBlue(p))].blue++;
if (image->matte != MagickFalse)
{
if ((double) GetPixelAlpha(p) < channel_statistics[OpacityChannel].minima)
channel_statistics[OpacityChannel].minima=(double) GetPixelAlpha(p);
if ((double) GetPixelAlpha(p) > channel_statistics[OpacityChannel].maxima)
channel_statistics[OpacityChannel].maxima=(double) GetPixelAlpha(p);
channel_statistics[OpacityChannel].sum+=GetPixelAlpha(p);
channel_statistics[OpacityChannel].sum_squared+=(double)
GetPixelAlpha(p)*GetPixelAlpha(p);
channel_statistics[OpacityChannel].sum_cubed+=(double)
GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p);
channel_statistics[OpacityChannel].sum_fourth_power+=(double)
GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p);
histogram[ScaleQuantumToMap(GetPixelAlpha(p))].opacity++;
}
if (image->colorspace == CMYKColorspace)
{
if ((double) GetPixelIndex(indexes+x) < channel_statistics[BlackChannel].minima)
channel_statistics[BlackChannel].minima=(double)
GetPixelIndex(indexes+x);
if ((double) GetPixelIndex(indexes+x) > channel_statistics[BlackChannel].maxima)
channel_statistics[BlackChannel].maxima=(double)
GetPixelIndex(indexes+x);
channel_statistics[BlackChannel].sum+=GetPixelIndex(indexes+x);
channel_statistics[BlackChannel].sum_squared+=(double)
GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x);
channel_statistics[BlackChannel].sum_cubed+=(double)
GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)*
GetPixelIndex(indexes+x);
channel_statistics[BlackChannel].sum_fourth_power+=(double)
GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)*
GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x);
histogram[ScaleQuantumToMap(GetPixelIndex(indexes+x))].index++;
}
x++;
p++;
}
}
for (i=0; i < (ssize_t) CompositeChannels; i++)
{
double
area,
mean,
standard_deviation;
/*
Normalize pixel statistics.
*/
area=PerceptibleReciprocal((double) image->columns*image->rows);
mean=channel_statistics[i].sum*area;
channel_statistics[i].sum=mean;
channel_statistics[i].sum_squared*=area;
channel_statistics[i].sum_cubed*=area;
channel_statistics[i].sum_fourth_power*=area;
channel_statistics[i].mean=mean;
channel_statistics[i].variance=channel_statistics[i].sum_squared;
standard_deviation=sqrt(channel_statistics[i].variance-(mean*mean));
area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)*
((double) image->columns*image->rows);
standard_deviation=sqrt(area*standard_deviation*standard_deviation);
channel_statistics[i].standard_deviation=standard_deviation;
}
for (i=0; i < (ssize_t) (MaxMap+1U); i++)
{
if (histogram[i].red > 0.0)
number_bins.red++;
if (histogram[i].green > 0.0)
number_bins.green++;
if (histogram[i].blue > 0.0)
number_bins.blue++;
if ((image->matte != MagickFalse) && (histogram[i].opacity > 0.0))
number_bins.opacity++;
if ((image->colorspace == CMYKColorspace) && (histogram[i].index > 0.0))
number_bins.index++;
}
area=PerceptibleReciprocal((double) image->columns*image->rows);
for (i=0; i < (ssize_t) (MaxMap+1U); i++)
{
/*
Compute pixel entropy.
*/
histogram[i].red*=area;
channel_statistics[RedChannel].entropy+=-histogram[i].red*
MagickLog10(histogram[i].red)*
PerceptibleReciprocal(MagickLog10((double) number_bins.red));
histogram[i].green*=area;
channel_statistics[GreenChannel].entropy+=-histogram[i].green*
MagickLog10(histogram[i].green)*
PerceptibleReciprocal(MagickLog10((double) number_bins.green));
histogram[i].blue*=area;
channel_statistics[BlueChannel].entropy+=-histogram[i].blue*
MagickLog10(histogram[i].blue)*
PerceptibleReciprocal(MagickLog10((double) number_bins.blue));
if (image->matte != MagickFalse)
{
histogram[i].opacity*=area;
channel_statistics[OpacityChannel].entropy+=-histogram[i].opacity*
MagickLog10(histogram[i].opacity)*
PerceptibleReciprocal(MagickLog10((double) number_bins.opacity));
}
if (image->colorspace == CMYKColorspace)
{
histogram[i].index*=area;
channel_statistics[IndexChannel].entropy+=-histogram[i].index*
MagickLog10(histogram[i].index)*
PerceptibleReciprocal(MagickLog10((double) number_bins.index));
}
}
/*
Compute overall statistics.
*/
for (i=0; i < (ssize_t) CompositeChannels; i++)
{
channel_statistics[CompositeChannels].depth=(size_t) EvaluateMax((double)
channel_statistics[CompositeChannels].depth,(double)
channel_statistics[i].depth);
channel_statistics[CompositeChannels].minima=MagickMin(
channel_statistics[CompositeChannels].minima,
channel_statistics[i].minima);
channel_statistics[CompositeChannels].maxima=EvaluateMax(
channel_statistics[CompositeChannels].maxima,
channel_statistics[i].maxima);
channel_statistics[CompositeChannels].sum+=channel_statistics[i].sum;
channel_statistics[CompositeChannels].sum_squared+=
channel_statistics[i].sum_squared;
channel_statistics[CompositeChannels].sum_cubed+=
channel_statistics[i].sum_cubed;
channel_statistics[CompositeChannels].sum_fourth_power+=
channel_statistics[i].sum_fourth_power;
channel_statistics[CompositeChannels].mean+=channel_statistics[i].mean;
channel_statistics[CompositeChannels].variance+=
channel_statistics[i].variance-channel_statistics[i].mean*
channel_statistics[i].mean;
standard_deviation=sqrt(channel_statistics[i].variance-
(channel_statistics[i].mean*channel_statistics[i].mean));
area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)*
((double) image->columns*image->rows);
standard_deviation=sqrt(area*standard_deviation*standard_deviation);
channel_statistics[CompositeChannels].standard_deviation=standard_deviation;
channel_statistics[CompositeChannels].entropy+=
channel_statistics[i].entropy;
}
channels=3;
if (image->matte != MagickFalse)
channels++;
if (image->colorspace == CMYKColorspace)
channels++;
channel_statistics[CompositeChannels].sum/=channels;
channel_statistics[CompositeChannels].sum_squared/=channels;
channel_statistics[CompositeChannels].sum_cubed/=channels;
channel_statistics[CompositeChannels].sum_fourth_power/=channels;
channel_statistics[CompositeChannels].mean/=channels;
channel_statistics[CompositeChannels].kurtosis/=channels;
channel_statistics[CompositeChannels].skewness/=channels;
channel_statistics[CompositeChannels].entropy/=channels;
i=CompositeChannels;
area=PerceptibleReciprocal((double) channels*image->columns*image->rows);
channel_statistics[i].variance=channel_statistics[i].sum_squared;
channel_statistics[i].mean=channel_statistics[i].sum;
standard_deviation=sqrt(channel_statistics[i].variance-
(channel_statistics[i].mean*channel_statistics[i].mean));
standard_deviation=sqrt(PerceptibleReciprocal((double) channels*
image->columns*image->rows-1.0)*channels*image->columns*image->rows*
standard_deviation*standard_deviation);
channel_statistics[i].standard_deviation=standard_deviation;
for (i=0; i <= (ssize_t) CompositeChannels; i++)
{
/*
Compute kurtosis & skewness statistics.
*/
standard_deviation=PerceptibleReciprocal(
channel_statistics[i].standard_deviation);
channel_statistics[i].skewness=(channel_statistics[i].sum_cubed-3.0*
channel_statistics[i].mean*channel_statistics[i].sum_squared+2.0*
channel_statistics[i].mean*channel_statistics[i].mean*
channel_statistics[i].mean)*(standard_deviation*standard_deviation*
standard_deviation);
channel_statistics[i].kurtosis=(channel_statistics[i].sum_fourth_power-4.0*
channel_statistics[i].mean*channel_statistics[i].sum_cubed+6.0*
channel_statistics[i].mean*channel_statistics[i].mean*
channel_statistics[i].sum_squared-3.0*channel_statistics[i].mean*
channel_statistics[i].mean*1.0*channel_statistics[i].mean*
channel_statistics[i].mean)*(standard_deviation*standard_deviation*
standard_deviation*standard_deviation)-3.0;
}
channel_statistics[CompositeChannels].mean=0.0;
channel_statistics[CompositeChannels].standard_deviation=0.0;
for (i=0; i < (ssize_t) CompositeChannels; i++)
{
channel_statistics[CompositeChannels].mean+=
channel_statistics[i].mean;
channel_statistics[CompositeChannels].standard_deviation+=
channel_statistics[i].standard_deviation;
}
channel_statistics[CompositeChannels].mean/=(double) channels;
channel_statistics[CompositeChannels].standard_deviation/=(double) channels;
histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram);
if (y < (ssize_t) image->rows)
channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
channel_statistics);
return(channel_statistics);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P o l y n o m i a l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PolynomialImage() returns a new image where each pixel is the sum of the
% pixels in the image sequence after applying its corresponding terms
% (coefficient and degree pairs).
%
% The format of the PolynomialImage method is:
%
% Image *PolynomialImage(const Image *images,const size_t number_terms,
% const double *terms,ExceptionInfo *exception)
% Image *PolynomialImageChannel(const Image *images,
% const size_t number_terms,const ChannelType channel,
% const double *terms,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o images: the image sequence.
%
% o channel: the channel.
%
% o number_terms: the number of terms in the list. The actual list length
% is 2 x number_terms + 1 (the constant).
%
% o terms: the list of polynomial coefficients and degree pairs and a
% constant.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *PolynomialImage(const Image *images,
const size_t number_terms,const double *terms,ExceptionInfo *exception)
{
Image
*polynomial_image;
polynomial_image=PolynomialImageChannel(images,DefaultChannels,number_terms,
terms,exception);
return(polynomial_image);
}
MagickExport Image *PolynomialImageChannel(const Image *images,
const ChannelType channel,const size_t number_terms,const double *terms,
ExceptionInfo *exception)
{
#define PolynomialImageTag "Polynomial/Image"
CacheView
*polynomial_view;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
**magick_restrict polynomial_pixels,
zero;
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);
image=AcquireImageCanvas(images,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
InheritException(exception,&image->exception);
image=DestroyImage(image);
return((Image *) NULL);
}
polynomial_pixels=AcquirePixelThreadSet(images);
if (polynomial_pixels == (MagickPixelPacket **) NULL)
{
image=DestroyImage(image);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
return((Image *) NULL);
}
/*
Polynomial image pixels.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(images,&zero);
polynomial_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
CacheView
*image_view;
const Image
*next;
const int
id = GetOpenMPThreadId();
register IndexPacket
*magick_restrict polynomial_indexes;
register MagickPixelPacket
*polynomial_pixel;
register PixelPacket
*magick_restrict q;
register ssize_t
i,
x;
size_t
number_images;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(polynomial_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
polynomial_indexes=GetCacheViewAuthenticIndexQueue(polynomial_view);
polynomial_pixel=polynomial_pixels[id];
for (x=0; x < (ssize_t) image->columns; x++)
polynomial_pixel[x]=zero;
next=images;
number_images=GetImageListLength(images);
for (i=0; i < (ssize_t) number_images; i++)
{
register const IndexPacket
*indexes;
register const PixelPacket
*p;
if (i >= (ssize_t) number_terms)
break;
image_view=AcquireVirtualCacheView(next,exception);
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
{
image_view=DestroyCacheView(image_view);
break;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
double
coefficient,
degree;
coefficient=terms[i << 1];
degree=terms[(i << 1)+1];
if ((channel & RedChannel) != 0)
polynomial_pixel[x].red+=coefficient*pow(QuantumScale*p->red,degree);
if ((channel & GreenChannel) != 0)
polynomial_pixel[x].green+=coefficient*pow(QuantumScale*p->green,
degree);
if ((channel & BlueChannel) != 0)
polynomial_pixel[x].blue+=coefficient*pow(QuantumScale*p->blue,
degree);
if ((channel & OpacityChannel) != 0)
polynomial_pixel[x].opacity+=coefficient*pow(QuantumScale*
(QuantumRange-p->opacity),degree);
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
polynomial_pixel[x].index+=coefficient*pow(QuantumScale*indexes[x],
degree);
p++;
}
image_view=DestroyCacheView(image_view);
next=GetNextImageInList(next);
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].red));
SetPixelGreen(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].green));
SetPixelBlue(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].blue));
if (image->matte == MagickFalse)
SetPixelOpacity(q,ClampToQuantum(QuantumRange-QuantumRange*
polynomial_pixel[x].opacity));
else
SetPixelAlpha(q,ClampToQuantum(QuantumRange-QuantumRange*
polynomial_pixel[x].opacity));
if (image->colorspace == CMYKColorspace)
SetPixelIndex(polynomial_indexes+x,ClampToQuantum(QuantumRange*
polynomial_pixel[x].index));
q++;
}
if (SyncCacheViewAuthenticPixels(polynomial_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(images,PolynomialImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
polynomial_view=DestroyCacheView(polynomial_view);
polynomial_pixels=DestroyPixelThreadSet(polynomial_pixels);
if (status == MagickFalse)
image=DestroyImage(image);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S t a t i s t i c I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% StatisticImage() makes each pixel the min / max / median / mode / etc. of
% the neighborhood of the specified width and height.
%
% The format of the StatisticImage method is:
%
% Image *StatisticImage(const Image *image,const StatisticType type,
% const size_t width,const size_t height,ExceptionInfo *exception)
% Image *StatisticImageChannel(const Image *image,
% const ChannelType channel,const StatisticType type,
% const size_t width,const size_t height,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the image channel.
%
% o type: the statistic type (median, mode, etc.).
%
% o width: the width of the pixel neighborhood.
%
% o height: the height of the pixel neighborhood.
%
% o exception: return any errors or warnings in this structure.
%
*/
#define ListChannels 5
typedef struct _ListNode
{
size_t
next[9],
count,
signature;
} ListNode;
typedef struct _SkipList
{
ssize_t
level;
ListNode
*nodes;
} SkipList;
typedef struct _PixelList
{
size_t
length,
seed,
signature;
SkipList
lists[ListChannels];
} PixelList;
static PixelList *DestroyPixelList(PixelList *pixel_list)
{
register ssize_t
i;
if (pixel_list == (PixelList *) NULL)
return((PixelList *) NULL);
for (i=0; i < ListChannels; i++)
if (pixel_list->lists[i].nodes != (ListNode *) NULL)
pixel_list->lists[i].nodes=(ListNode *) RelinquishAlignedMemory(
pixel_list->lists[i].nodes);
pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list);
return(pixel_list);
}
static PixelList **DestroyPixelListThreadSet(PixelList **pixel_list)
{
register ssize_t
i;
assert(pixel_list != (PixelList **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (pixel_list[i] != (PixelList *) NULL)
pixel_list[i]=DestroyPixelList(pixel_list[i]);
pixel_list=(PixelList **) RelinquishMagickMemory(pixel_list);
return(pixel_list);
}
static PixelList *AcquirePixelList(const size_t width,const size_t height)
{
PixelList
*pixel_list;
register ssize_t
i;
pixel_list=(PixelList *) AcquireMagickMemory(sizeof(*pixel_list));
if (pixel_list == (PixelList *) NULL)
return(pixel_list);
(void) memset((void *) pixel_list,0,sizeof(*pixel_list));
pixel_list->length=width*height;
for (i=0; i < ListChannels; i++)
{
pixel_list->lists[i].nodes=(ListNode *) AcquireAlignedMemory(65537UL,
sizeof(*pixel_list->lists[i].nodes));
if (pixel_list->lists[i].nodes == (ListNode *) NULL)
return(DestroyPixelList(pixel_list));
(void) memset(pixel_list->lists[i].nodes,0,65537UL*
sizeof(*pixel_list->lists[i].nodes));
}
pixel_list->signature=MagickCoreSignature;
return(pixel_list);
}
static PixelList **AcquirePixelListThreadSet(const size_t width,
const size_t height)
{
PixelList
**pixel_list;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixel_list=(PixelList **) AcquireQuantumMemory(number_threads,
sizeof(*pixel_list));
if (pixel_list == (PixelList **) NULL)
return((PixelList **) NULL);
(void) memset(pixel_list,0,number_threads*sizeof(*pixel_list));
for (i=0; i < (ssize_t) number_threads; i++)
{
pixel_list[i]=AcquirePixelList(width,height);
if (pixel_list[i] == (PixelList *) NULL)
return(DestroyPixelListThreadSet(pixel_list));
}
return(pixel_list);
}
static void AddNodePixelList(PixelList *pixel_list,const ssize_t channel,
const size_t color)
{
register SkipList
*list;
register ssize_t
level;
size_t
search,
update[9];
/*
Initialize the node.
*/
list=pixel_list->lists+channel;
list->nodes[color].signature=pixel_list->signature;
list->nodes[color].count=1;
/*
Determine where it belongs in the list.
*/
search=65536UL;
for (level=list->level; level >= 0; level--)
{
while (list->nodes[search].next[level] < color)
search=list->nodes[search].next[level];
update[level]=search;
}
/*
Generate a pseudo-random level for this node.
*/
for (level=0; ; level++)
{
pixel_list->seed=(pixel_list->seed*42893621L)+1L;
if ((pixel_list->seed & 0x300) != 0x300)
break;
}
if (level > 8)
level=8;
if (level > (list->level+2))
level=list->level+2;
/*
If we're raising the list's level, link back to the root node.
*/
while (level > list->level)
{
list->level++;
update[list->level]=65536UL;
}
/*
Link the node into the skip-list.
*/
do
{
list->nodes[color].next[level]=list->nodes[update[level]].next[level];
list->nodes[update[level]].next[level]=color;
} while (level-- > 0);
}
static void GetMaximumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel)
{
register SkipList
*list;
register ssize_t
channel;
size_t
color,
maximum;
ssize_t
count;
unsigned short
channels[ListChannels];
/*
Find the maximum value for each of the color.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
count=0;
maximum=list->nodes[color].next[0];
do
{
color=list->nodes[color].next[0];
if (color > maximum)
maximum=color;
count+=list->nodes[color].count;
} while (count < (ssize_t) pixel_list->length);
channels[channel]=(unsigned short) maximum;
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetMeanPixelList(PixelList *pixel_list,MagickPixelPacket *pixel)
{
MagickRealType
sum;
register SkipList
*list;
register ssize_t
channel;
size_t
color;
ssize_t
count;
unsigned short
channels[ListChannels];
/*
Find the mean value for each of the color.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
count=0;
sum=0.0;
do
{
color=list->nodes[color].next[0];
sum+=(MagickRealType) list->nodes[color].count*color;
count+=list->nodes[color].count;
} while (count < (ssize_t) pixel_list->length);
sum/=pixel_list->length;
channels[channel]=(unsigned short) sum;
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetMedianPixelList(PixelList *pixel_list,MagickPixelPacket *pixel)
{
register SkipList
*list;
register ssize_t
channel;
size_t
color;
ssize_t
count;
unsigned short
channels[ListChannels];
/*
Find the median value for each of the color.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
count=0;
do
{
color=list->nodes[color].next[0];
count+=list->nodes[color].count;
} while (count <= (ssize_t) (pixel_list->length >> 1));
channels[channel]=(unsigned short) color;
}
GetMagickPixelPacket((const Image *) NULL,pixel);
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetMinimumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel)
{
register SkipList
*list;
register ssize_t
channel;
size_t
color,
minimum;
ssize_t
count;
unsigned short
channels[ListChannels];
/*
Find the minimum value for each of the color.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
count=0;
color=65536UL;
minimum=list->nodes[color].next[0];
do
{
color=list->nodes[color].next[0];
if (color < minimum)
minimum=color;
count+=list->nodes[color].count;
} while (count < (ssize_t) pixel_list->length);
channels[channel]=(unsigned short) minimum;
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetModePixelList(PixelList *pixel_list,MagickPixelPacket *pixel)
{
register SkipList
*list;
register ssize_t
channel;
size_t
color,
max_count,
mode;
ssize_t
count;
unsigned short
channels[5];
/*
Make each pixel the 'predominant color' of the specified neighborhood.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
mode=color;
max_count=list->nodes[mode].count;
count=0;
do
{
color=list->nodes[color].next[0];
if (list->nodes[color].count > max_count)
{
mode=color;
max_count=list->nodes[mode].count;
}
count+=list->nodes[color].count;
} while (count < (ssize_t) pixel_list->length);
channels[channel]=(unsigned short) mode;
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetNonpeakPixelList(PixelList *pixel_list,MagickPixelPacket *pixel)
{
register SkipList
*list;
register ssize_t
channel;
size_t
color,
next,
previous;
ssize_t
count;
unsigned short
channels[5];
/*
Finds the non peak value for each of the colors.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
next=list->nodes[color].next[0];
count=0;
do
{
previous=color;
color=next;
next=list->nodes[color].next[0];
count+=list->nodes[color].count;
} while (count <= (ssize_t) (pixel_list->length >> 1));
if ((previous == 65536UL) && (next != 65536UL))
color=next;
else
if ((previous != 65536UL) && (next == 65536UL))
color=previous;
channels[channel]=(unsigned short) color;
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetRootMeanSquarePixelList(PixelList *pixel_list,
MagickPixelPacket *pixel)
{
MagickRealType
sum;
register SkipList
*list;
register ssize_t
channel;
size_t
color;
ssize_t
count;
unsigned short
channels[ListChannels];
/*
Find the root mean square value for each of the color.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
count=0;
sum=0.0;
do
{
color=list->nodes[color].next[0];
sum+=(MagickRealType) (list->nodes[color].count*color*color);
count+=list->nodes[color].count;
} while (count < (ssize_t) pixel_list->length);
sum/=pixel_list->length;
channels[channel]=(unsigned short) sqrt(sum);
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetStandardDeviationPixelList(PixelList *pixel_list,
MagickPixelPacket *pixel)
{
MagickRealType
sum,
sum_squared;
register SkipList
*list;
register ssize_t
channel;
size_t
color;
ssize_t
count;
unsigned short
channels[ListChannels];
/*
Find the standard-deviation value for each of the color.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
count=0;
sum=0.0;
sum_squared=0.0;
do
{
register ssize_t
i;
color=list->nodes[color].next[0];
sum+=(MagickRealType) list->nodes[color].count*color;
for (i=0; i < (ssize_t) list->nodes[color].count; i++)
sum_squared+=((MagickRealType) color)*((MagickRealType) color);
count+=list->nodes[color].count;
} while (count < (ssize_t) pixel_list->length);
sum/=pixel_list->length;
sum_squared/=pixel_list->length;
channels[channel]=(unsigned short) sqrt(sum_squared-(sum*sum));
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static inline void InsertPixelList(const Image *image,const PixelPacket *pixel,
const IndexPacket *indexes,PixelList *pixel_list)
{
size_t
signature;
unsigned short
index;
index=ScaleQuantumToShort(GetPixelRed(pixel));
signature=pixel_list->lists[0].nodes[index].signature;
if (signature == pixel_list->signature)
pixel_list->lists[0].nodes[index].count++;
else
AddNodePixelList(pixel_list,0,index);
index=ScaleQuantumToShort(GetPixelGreen(pixel));
signature=pixel_list->lists[1].nodes[index].signature;
if (signature == pixel_list->signature)
pixel_list->lists[1].nodes[index].count++;
else
AddNodePixelList(pixel_list,1,index);
index=ScaleQuantumToShort(GetPixelBlue(pixel));
signature=pixel_list->lists[2].nodes[index].signature;
if (signature == pixel_list->signature)
pixel_list->lists[2].nodes[index].count++;
else
AddNodePixelList(pixel_list,2,index);
index=ScaleQuantumToShort(GetPixelOpacity(pixel));
signature=pixel_list->lists[3].nodes[index].signature;
if (signature == pixel_list->signature)
pixel_list->lists[3].nodes[index].count++;
else
AddNodePixelList(pixel_list,3,index);
if (image->colorspace == CMYKColorspace)
index=ScaleQuantumToShort(GetPixelIndex(indexes));
signature=pixel_list->lists[4].nodes[index].signature;
if (signature == pixel_list->signature)
pixel_list->lists[4].nodes[index].count++;
else
AddNodePixelList(pixel_list,4,index);
}
static void ResetPixelList(PixelList *pixel_list)
{
int
level;
register ListNode
*root;
register SkipList
*list;
register ssize_t
channel;
/*
Reset the skip-list.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
root=list->nodes+65536UL;
list->level=0;
for (level=0; level < 9; level++)
root->next[level]=65536UL;
}
pixel_list->seed=pixel_list->signature++;
}
MagickExport Image *StatisticImage(const Image *image,const StatisticType type,
const size_t width,const size_t height,ExceptionInfo *exception)
{
Image
*statistic_image;
statistic_image=StatisticImageChannel(image,DefaultChannels,type,width,
height,exception);
return(statistic_image);
}
MagickExport Image *StatisticImageChannel(const Image *image,
const ChannelType channel,const StatisticType type,const size_t width,
const size_t height,ExceptionInfo *exception)
{
#define StatisticImageTag "Statistic/Image"
CacheView
*image_view,
*statistic_view;
Image
*statistic_image;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelList
**magick_restrict pixel_list;
size_t
neighbor_height,
neighbor_width;
ssize_t
y;
/*
Initialize statistics image attributes.
*/
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);
statistic_image=CloneImage(image,0,0,MagickTrue,exception);
if (statistic_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(statistic_image,DirectClass) == MagickFalse)
{
InheritException(exception,&statistic_image->exception);
statistic_image=DestroyImage(statistic_image);
return((Image *) NULL);
}
neighbor_width=width == 0 ? GetOptimalKernelWidth2D((double) width,0.5) :
width;
neighbor_height=height == 0 ? GetOptimalKernelWidth2D((double) height,0.5) :
height;
pixel_list=AcquirePixelListThreadSet(neighbor_width,neighbor_height);
if (pixel_list == (PixelList **) NULL)
{
statistic_image=DestroyImage(statistic_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Make each pixel the min / max / median / mode / etc. of the neighborhood.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
statistic_view=AcquireAuthenticCacheView(statistic_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,statistic_image,statistic_image->rows,1)
#endif
for (y=0; y < (ssize_t) statistic_image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict statistic_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) neighbor_width/2L),y-
(ssize_t) (neighbor_height/2L),image->columns+neighbor_width,
neighbor_height,exception);
q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns, 1,exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
statistic_indexes=GetCacheViewAuthenticIndexQueue(statistic_view);
for (x=0; x < (ssize_t) statistic_image->columns; x++)
{
MagickPixelPacket
pixel;
register const IndexPacket
*magick_restrict s;
register const PixelPacket
*magick_restrict r;
register ssize_t
u,
v;
r=p;
s=indexes+x;
ResetPixelList(pixel_list[id]);
for (v=0; v < (ssize_t) neighbor_height; v++)
{
for (u=0; u < (ssize_t) neighbor_width; u++)
InsertPixelList(image,r+u,s+u,pixel_list[id]);
r+=image->columns+neighbor_width;
s+=image->columns+neighbor_width;
}
GetMagickPixelPacket(image,&pixel);
SetMagickPixelPacket(image,p+neighbor_width*neighbor_height/2,indexes+x+
neighbor_width*neighbor_height/2,&pixel);
switch (type)
{
case GradientStatistic:
{
MagickPixelPacket
maximum,
minimum;
GetMinimumPixelList(pixel_list[id],&pixel);
minimum=pixel;
GetMaximumPixelList(pixel_list[id],&pixel);
maximum=pixel;
pixel.red=MagickAbsoluteValue(maximum.red-minimum.red);
pixel.green=MagickAbsoluteValue(maximum.green-minimum.green);
pixel.blue=MagickAbsoluteValue(maximum.blue-minimum.blue);
pixel.opacity=MagickAbsoluteValue(maximum.opacity-minimum.opacity);
if (image->colorspace == CMYKColorspace)
pixel.index=MagickAbsoluteValue(maximum.index-minimum.index);
break;
}
case MaximumStatistic:
{
GetMaximumPixelList(pixel_list[id],&pixel);
break;
}
case MeanStatistic:
{
GetMeanPixelList(pixel_list[id],&pixel);
break;
}
case MedianStatistic:
default:
{
GetMedianPixelList(pixel_list[id],&pixel);
break;
}
case MinimumStatistic:
{
GetMinimumPixelList(pixel_list[id],&pixel);
break;
}
case ModeStatistic:
{
GetModePixelList(pixel_list[id],&pixel);
break;
}
case NonpeakStatistic:
{
GetNonpeakPixelList(pixel_list[id],&pixel);
break;
}
case RootMeanSquareStatistic:
{
GetRootMeanSquarePixelList(pixel_list[id],&pixel);
break;
}
case StandardDeviationStatistic:
{
GetStandardDeviationPixelList(pixel_list[id],&pixel);
break;
}
}
if ((channel & RedChannel) != 0)
SetPixelRed(q,ClampToQuantum(pixel.red));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ClampToQuantum(pixel.green));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ClampToQuantum(pixel.blue));
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,ClampToQuantum(pixel.opacity));
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(statistic_indexes+x,ClampToQuantum(pixel.index));
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(statistic_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,StatisticImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
statistic_view=DestroyCacheView(statistic_view);
image_view=DestroyCacheView(image_view);
pixel_list=DestroyPixelListThreadSet(pixel_list);
if (status == MagickFalse)
statistic_image=DestroyImage(statistic_image);
return(statistic_image);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_941_0 |
crossvul-cpp_data_good_5053_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD RRRR AAA W W %
% D D R R A A W W %
% D D RRRR AAAAA W W W %
% D D R RN A A WW WW %
% DDDD R R A A W W %
% %
% %
% MagickCore Image Drawing Methods %
% %
% %
% Software Design %
% Cristy %
% July 1998 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Bill Radcliffe of Corbis (www.corbis.com) contributed the polygon
% rendering code based on Paul Heckbert's "Concave Polygon Scan Conversion",
% Graphics Gems, 1990. Leonard Rosenthal and David Harr of Appligent
% (www.appligent.com) contributed the dash pattern, linecap stroking
% algorithm, and minor rendering improvements.
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/annotate.h"
#include "MagickCore/artifact.h"
#include "MagickCore/blob.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/color.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/draw.h"
#include "MagickCore/draw-private.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/paint.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/property.h"
#include "MagickCore/resample.h"
#include "MagickCore/resample-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/token.h"
#include "MagickCore/transform-private.h"
#include "MagickCore/utility.h"
/*
Define declarations.
*/
#define BezierQuantum 200
/*
Typedef declarations.
*/
typedef struct _EdgeInfo
{
SegmentInfo
bounds;
double
scanline;
PointInfo
*points;
size_t
number_points;
ssize_t
direction;
MagickBooleanType
ghostline;
size_t
highwater;
} EdgeInfo;
typedef struct _ElementInfo
{
double
cx,
cy,
major,
minor,
angle;
} ElementInfo;
typedef struct _PolygonInfo
{
EdgeInfo
*edges;
size_t
number_edges;
} PolygonInfo;
typedef enum
{
MoveToCode,
OpenCode,
GhostlineCode,
LineToCode,
EndCode
} PathInfoCode;
typedef struct _PathInfo
{
PointInfo
point;
PathInfoCode
code;
} PathInfo;
/*
Forward declarations.
*/
static MagickBooleanType
DrawStrokePolygon(Image *,const DrawInfo *,const PrimitiveInfo *,
ExceptionInfo *);
static PrimitiveInfo
*TraceStrokePolygon(const DrawInfo *,const PrimitiveInfo *);
static size_t
TracePath(PrimitiveInfo *,const char *);
static void
TraceArc(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo),
TraceArcPath(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo,
const double,const MagickBooleanType,const MagickBooleanType),
TraceBezier(PrimitiveInfo *,const size_t),
TraceCircle(PrimitiveInfo *,const PointInfo,const PointInfo),
TraceEllipse(PrimitiveInfo *,const PointInfo,const PointInfo,
const PointInfo),
TraceLine(PrimitiveInfo *,const PointInfo,const PointInfo),
TraceRectangle(PrimitiveInfo *,const PointInfo,const PointInfo),
TraceRoundRectangle(PrimitiveInfo *,const PointInfo,const PointInfo,
PointInfo),
TraceSquareLinecap(PrimitiveInfo *,const size_t,const double);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireDrawInfo() returns a DrawInfo structure properly initialized.
%
% The format of the AcquireDrawInfo method is:
%
% DrawInfo *AcquireDrawInfo(void)
%
*/
MagickExport DrawInfo *AcquireDrawInfo(void)
{
DrawInfo
*draw_info;
draw_info=(DrawInfo *) AcquireMagickMemory(sizeof(*draw_info));
if (draw_info == (DrawInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
GetDrawInfo((ImageInfo *) NULL,draw_info);
return(draw_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneDrawInfo() makes a copy of the given draw_info structure. If NULL
% is specified, a new DrawInfo structure is created initialized to default
% values.
%
% The format of the CloneDrawInfo method is:
%
% DrawInfo *CloneDrawInfo(const ImageInfo *image_info,
% const DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o draw_info: the draw info.
%
*/
MagickExport DrawInfo *CloneDrawInfo(const ImageInfo *image_info,
const DrawInfo *draw_info)
{
DrawInfo
*clone_info;
ExceptionInfo
*exception;
clone_info=(DrawInfo *) AcquireMagickMemory(sizeof(*clone_info));
if (clone_info == (DrawInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
GetDrawInfo(image_info,clone_info);
if (draw_info == (DrawInfo *) NULL)
return(clone_info);
exception=AcquireExceptionInfo();
if (clone_info->primitive != (char *) NULL)
(void) CloneString(&clone_info->primitive,draw_info->primitive);
if (draw_info->geometry != (char *) NULL)
(void) CloneString(&clone_info->geometry,draw_info->geometry);
clone_info->viewbox=draw_info->viewbox;
clone_info->affine=draw_info->affine;
clone_info->gravity=draw_info->gravity;
clone_info->fill=draw_info->fill;
clone_info->stroke=draw_info->stroke;
clone_info->stroke_width=draw_info->stroke_width;
if (draw_info->fill_pattern != (Image *) NULL)
clone_info->fill_pattern=CloneImage(draw_info->fill_pattern,0,0,MagickTrue,
exception);
if (draw_info->stroke_pattern != (Image *) NULL)
clone_info->stroke_pattern=CloneImage(draw_info->stroke_pattern,0,0,
MagickTrue,exception);
clone_info->stroke_antialias=draw_info->stroke_antialias;
clone_info->text_antialias=draw_info->text_antialias;
clone_info->fill_rule=draw_info->fill_rule;
clone_info->linecap=draw_info->linecap;
clone_info->linejoin=draw_info->linejoin;
clone_info->miterlimit=draw_info->miterlimit;
clone_info->dash_offset=draw_info->dash_offset;
clone_info->decorate=draw_info->decorate;
clone_info->compose=draw_info->compose;
if (draw_info->text != (char *) NULL)
(void) CloneString(&clone_info->text,draw_info->text);
if (draw_info->font != (char *) NULL)
(void) CloneString(&clone_info->font,draw_info->font);
if (draw_info->metrics != (char *) NULL)
(void) CloneString(&clone_info->metrics,draw_info->metrics);
if (draw_info->family != (char *) NULL)
(void) CloneString(&clone_info->family,draw_info->family);
clone_info->style=draw_info->style;
clone_info->stretch=draw_info->stretch;
clone_info->weight=draw_info->weight;
if (draw_info->encoding != (char *) NULL)
(void) CloneString(&clone_info->encoding,draw_info->encoding);
clone_info->pointsize=draw_info->pointsize;
clone_info->kerning=draw_info->kerning;
clone_info->interline_spacing=draw_info->interline_spacing;
clone_info->interword_spacing=draw_info->interword_spacing;
clone_info->direction=draw_info->direction;
if (draw_info->density != (char *) NULL)
(void) CloneString(&clone_info->density,draw_info->density);
clone_info->align=draw_info->align;
clone_info->undercolor=draw_info->undercolor;
clone_info->border_color=draw_info->border_color;
if (draw_info->server_name != (char *) NULL)
(void) CloneString(&clone_info->server_name,draw_info->server_name);
if (draw_info->dash_pattern != (double *) NULL)
{
register ssize_t
x;
for (x=0; draw_info->dash_pattern[x] != 0.0; x++) ;
clone_info->dash_pattern=(double *) AcquireQuantumMemory((size_t) x+1UL,
sizeof(*clone_info->dash_pattern));
if (clone_info->dash_pattern == (double *) NULL)
ThrowFatalException(ResourceLimitFatalError,
"UnableToAllocateDashPattern");
(void) CopyMagickMemory(clone_info->dash_pattern,draw_info->dash_pattern,
(size_t) (x+1)*sizeof(*clone_info->dash_pattern));
}
clone_info->gradient=draw_info->gradient;
if (draw_info->gradient.stops != (StopInfo *) NULL)
{
size_t
number_stops;
number_stops=clone_info->gradient.number_stops;
clone_info->gradient.stops=(StopInfo *) AcquireQuantumMemory((size_t)
number_stops,sizeof(*clone_info->gradient.stops));
if (clone_info->gradient.stops == (StopInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,
"UnableToAllocateDashPattern");
(void) CopyMagickMemory(clone_info->gradient.stops,
draw_info->gradient.stops,(size_t) number_stops*
sizeof(*clone_info->gradient.stops));
}
if (draw_info->clip_mask != (char *) NULL)
(void) CloneString(&clone_info->clip_mask,draw_info->clip_mask);
clone_info->bounds=draw_info->bounds;
clone_info->clip_units=draw_info->clip_units;
clone_info->render=draw_info->render;
clone_info->alpha=draw_info->alpha;
clone_info->element_reference=draw_info->element_reference;
clone_info->debug=IsEventLogging();
exception=DestroyExceptionInfo(exception);
return(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n v e r t P a t h T o P o l y g o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConvertPathToPolygon() converts a path to the more efficient sorted
% rendering form.
%
% The format of the ConvertPathToPolygon method is:
%
% PolygonInfo *ConvertPathToPolygon(const DrawInfo *draw_info,
% const PathInfo *path_info)
%
% A description of each parameter follows:
%
% o Method ConvertPathToPolygon returns the path in a more efficient sorted
% rendering form of type PolygonInfo.
%
% o draw_info: Specifies a pointer to an DrawInfo structure.
%
% o path_info: Specifies a pointer to an PathInfo structure.
%
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int CompareEdges(const void *x,const void *y)
{
register const EdgeInfo
*p,
*q;
/*
Compare two edges.
*/
p=(const EdgeInfo *) x;
q=(const EdgeInfo *) y;
if ((p->points[0].y-MagickEpsilon) > q->points[0].y)
return(1);
if ((p->points[0].y+MagickEpsilon) < q->points[0].y)
return(-1);
if ((p->points[0].x-MagickEpsilon) > q->points[0].x)
return(1);
if ((p->points[0].x+MagickEpsilon) < q->points[0].x)
return(-1);
if (((p->points[1].x-p->points[0].x)*(q->points[1].y-q->points[0].y)-
(p->points[1].y-p->points[0].y)*(q->points[1].x-q->points[0].x)) > 0.0)
return(1);
return(-1);
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static void LogPolygonInfo(const PolygonInfo *polygon_info)
{
register EdgeInfo
*p;
register ssize_t
i,
j;
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin active-edge");
p=polygon_info->edges;
for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
{
(void) LogMagickEvent(DrawEvent,GetMagickModule()," edge %.20g:",
(double) i);
(void) LogMagickEvent(DrawEvent,GetMagickModule()," direction: %s",
p->direction != MagickFalse ? "down" : "up");
(void) LogMagickEvent(DrawEvent,GetMagickModule()," ghostline: %s",
p->ghostline != MagickFalse ? "transparent" : "opaque");
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" bounds: %g %g - %g %g",p->bounds.x1,p->bounds.y1,
p->bounds.x2,p->bounds.y2);
for (j=0; j < (ssize_t) p->number_points; j++)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," %g %g",
p->points[j].x,p->points[j].y);
p++;
}
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end active-edge");
}
static void ReversePoints(PointInfo *points,const size_t number_points)
{
PointInfo
point;
register ssize_t
i;
for (i=0; i < (ssize_t) (number_points >> 1); i++)
{
point=points[i];
points[i]=points[number_points-(i+1)];
points[number_points-(i+1)]=point;
}
}
static PolygonInfo *ConvertPathToPolygon(const PathInfo *path_info)
{
long
direction,
next_direction;
PointInfo
point,
*points;
PolygonInfo
*polygon_info;
SegmentInfo
bounds;
register ssize_t
i,
n;
MagickBooleanType
ghostline;
size_t
edge,
number_edges,
number_points;
/*
Convert a path to the more efficient sorted rendering form.
*/
polygon_info=(PolygonInfo *) AcquireMagickMemory(sizeof(*polygon_info));
if (polygon_info == (PolygonInfo *) NULL)
return((PolygonInfo *) NULL);
number_edges=16;
polygon_info->edges=(EdgeInfo *) AcquireQuantumMemory((size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
direction=0;
edge=0;
ghostline=MagickFalse;
n=0;
number_points=0;
points=(PointInfo *) NULL;
(void) ResetMagickMemory(&point,0,sizeof(point));
(void) ResetMagickMemory(&bounds,0,sizeof(bounds));
for (i=0; path_info[i].code != EndCode; i++)
{
if ((path_info[i].code == MoveToCode) || (path_info[i].code == OpenCode) ||
(path_info[i].code == GhostlineCode))
{
/*
Move to.
*/
if ((points != (PointInfo *) NULL) && (n >= 2))
{
if (edge == number_edges)
{
number_edges<<=1;
polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
polygon_info->edges,(size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
}
polygon_info->edges[edge].number_points=(size_t) n;
polygon_info->edges[edge].scanline=(-1.0);
polygon_info->edges[edge].highwater=0;
polygon_info->edges[edge].ghostline=ghostline;
polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
if (direction < 0)
ReversePoints(points,(size_t) n);
polygon_info->edges[edge].points=points;
polygon_info->edges[edge].bounds=bounds;
polygon_info->edges[edge].bounds.y1=points[0].y;
polygon_info->edges[edge].bounds.y2=points[n-1].y;
points=(PointInfo *) NULL;
ghostline=MagickFalse;
edge++;
}
if (points == (PointInfo *) NULL)
{
number_points=16;
points=(PointInfo *) AcquireQuantumMemory((size_t) number_points,
sizeof(*points));
if (points == (PointInfo *) NULL)
return((PolygonInfo *) NULL);
}
ghostline=path_info[i].code == GhostlineCode ? MagickTrue : MagickFalse;
point=path_info[i].point;
points[0]=point;
bounds.x1=point.x;
bounds.x2=point.x;
direction=0;
n=1;
continue;
}
/*
Line to.
*/
next_direction=((path_info[i].point.y > point.y) ||
((path_info[i].point.y == point.y) &&
(path_info[i].point.x > point.x))) ? 1 : -1;
if ((points != (PointInfo *) NULL) && (direction != 0) &&
(direction != next_direction))
{
/*
New edge.
*/
point=points[n-1];
if (edge == number_edges)
{
number_edges<<=1;
polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
polygon_info->edges,(size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
}
polygon_info->edges[edge].number_points=(size_t) n;
polygon_info->edges[edge].scanline=(-1.0);
polygon_info->edges[edge].highwater=0;
polygon_info->edges[edge].ghostline=ghostline;
polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
if (direction < 0)
ReversePoints(points,(size_t) n);
polygon_info->edges[edge].points=points;
polygon_info->edges[edge].bounds=bounds;
polygon_info->edges[edge].bounds.y1=points[0].y;
polygon_info->edges[edge].bounds.y2=points[n-1].y;
number_points=16;
points=(PointInfo *) AcquireQuantumMemory((size_t) number_points,
sizeof(*points));
if (points == (PointInfo *) NULL)
return((PolygonInfo *) NULL);
n=1;
ghostline=MagickFalse;
points[0]=point;
bounds.x1=point.x;
bounds.x2=point.x;
edge++;
}
direction=next_direction;
if (points == (PointInfo *) NULL)
continue;
if (n == (ssize_t) number_points)
{
number_points<<=1;
points=(PointInfo *) ResizeQuantumMemory(points,(size_t) number_points,
sizeof(*points));
if (points == (PointInfo *) NULL)
return((PolygonInfo *) NULL);
}
point=path_info[i].point;
points[n]=point;
if (point.x < bounds.x1)
bounds.x1=point.x;
if (point.x > bounds.x2)
bounds.x2=point.x;
n++;
}
if (points != (PointInfo *) NULL)
{
if (n < 2)
points=(PointInfo *) RelinquishMagickMemory(points);
else
{
if (edge == number_edges)
{
number_edges<<=1;
polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
polygon_info->edges,(size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
}
polygon_info->edges[edge].number_points=(size_t) n;
polygon_info->edges[edge].scanline=(-1.0);
polygon_info->edges[edge].highwater=0;
polygon_info->edges[edge].ghostline=ghostline;
polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
if (direction < 0)
ReversePoints(points,(size_t) n);
polygon_info->edges[edge].points=points;
polygon_info->edges[edge].bounds=bounds;
polygon_info->edges[edge].bounds.y1=points[0].y;
polygon_info->edges[edge].bounds.y2=points[n-1].y;
ghostline=MagickFalse;
edge++;
}
}
polygon_info->number_edges=edge;
qsort(polygon_info->edges,(size_t) polygon_info->number_edges,
sizeof(*polygon_info->edges),CompareEdges);
if (IsEventLogging() != MagickFalse)
LogPolygonInfo(polygon_info);
return(polygon_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n v e r t P r i m i t i v e T o P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConvertPrimitiveToPath() converts a PrimitiveInfo structure into a vector
% path structure.
%
% The format of the ConvertPrimitiveToPath method is:
%
% PathInfo *ConvertPrimitiveToPath(const DrawInfo *draw_info,
% const PrimitiveInfo *primitive_info)
%
% A description of each parameter follows:
%
% o Method ConvertPrimitiveToPath returns a vector path structure of type
% PathInfo.
%
% o draw_info: a structure of type DrawInfo.
%
% o primitive_info: Specifies a pointer to an PrimitiveInfo structure.
%
%
*/
static void LogPathInfo(const PathInfo *path_info)
{
register const PathInfo
*p;
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin vector-path");
for (p=path_info; p->code != EndCode; p++)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" %g %g %s",p->point.x,p->point.y,p->code == GhostlineCode ?
"moveto ghostline" : p->code == OpenCode ? "moveto open" :
p->code == MoveToCode ? "moveto" : p->code == LineToCode ? "lineto" :
"?");
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end vector-path");
}
static PathInfo *ConvertPrimitiveToPath(const PrimitiveInfo *primitive_info)
{
PathInfo
*path_info;
PathInfoCode
code;
PointInfo
p,
q;
register ssize_t
i,
n;
ssize_t
coordinates,
start;
/*
Converts a PrimitiveInfo structure into a vector path structure.
*/
switch (primitive_info->primitive)
{
case AlphaPrimitive:
case ColorPrimitive:
case ImagePrimitive:
case PointPrimitive:
case TextPrimitive:
return((PathInfo *) NULL);
default:
break;
}
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
path_info=(PathInfo *) AcquireQuantumMemory((size_t) (2UL*i+3UL),
sizeof(*path_info));
if (path_info == (PathInfo *) NULL)
return((PathInfo *) NULL);
coordinates=0;
n=0;
p.x=(-1.0);
p.y=(-1.0);
q.x=(-1.0);
q.y=(-1.0);
start=0;
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
{
code=LineToCode;
if (coordinates <= 0)
{
coordinates=(ssize_t) primitive_info[i].coordinates;
p=primitive_info[i].point;
start=n;
code=MoveToCode;
}
coordinates--;
/*
Eliminate duplicate points.
*/
if ((i == 0) || (fabs(q.x-primitive_info[i].point.x) >= MagickEpsilon) ||
(fabs(q.y-primitive_info[i].point.y) >= MagickEpsilon))
{
path_info[n].code=code;
path_info[n].point=primitive_info[i].point;
q=primitive_info[i].point;
n++;
}
if (coordinates > 0)
continue;
if ((fabs(p.x-primitive_info[i].point.x) < MagickEpsilon) &&
(fabs(p.y-primitive_info[i].point.y) < MagickEpsilon))
continue;
/*
Mark the p point as open if it does not match the q.
*/
path_info[start].code=OpenCode;
path_info[n].code=GhostlineCode;
path_info[n].point=primitive_info[i].point;
n++;
path_info[n].code=LineToCode;
path_info[n].point=p;
n++;
}
path_info[n].code=EndCode;
path_info[n].point.x=0.0;
path_info[n].point.y=0.0;
if (IsEventLogging() != MagickFalse)
LogPathInfo(path_info);
return(path_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyDrawInfo() deallocates memory associated with an DrawInfo
% structure.
%
% The format of the DestroyDrawInfo method is:
%
% DrawInfo *DestroyDrawInfo(DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o draw_info: the draw info.
%
*/
MagickExport DrawInfo *DestroyDrawInfo(DrawInfo *draw_info)
{
if (draw_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if (draw_info->primitive != (char *) NULL)
draw_info->primitive=DestroyString(draw_info->primitive);
if (draw_info->text != (char *) NULL)
draw_info->text=DestroyString(draw_info->text);
if (draw_info->geometry != (char *) NULL)
draw_info->geometry=DestroyString(draw_info->geometry);
if (draw_info->fill_pattern != (Image *) NULL)
draw_info->fill_pattern=DestroyImage(draw_info->fill_pattern);
if (draw_info->stroke_pattern != (Image *) NULL)
draw_info->stroke_pattern=DestroyImage(draw_info->stroke_pattern);
if (draw_info->font != (char *) NULL)
draw_info->font=DestroyString(draw_info->font);
if (draw_info->metrics != (char *) NULL)
draw_info->metrics=DestroyString(draw_info->metrics);
if (draw_info->family != (char *) NULL)
draw_info->family=DestroyString(draw_info->family);
if (draw_info->encoding != (char *) NULL)
draw_info->encoding=DestroyString(draw_info->encoding);
if (draw_info->density != (char *) NULL)
draw_info->density=DestroyString(draw_info->density);
if (draw_info->server_name != (char *) NULL)
draw_info->server_name=(char *)
RelinquishMagickMemory(draw_info->server_name);
if (draw_info->dash_pattern != (double *) NULL)
draw_info->dash_pattern=(double *) RelinquishMagickMemory(
draw_info->dash_pattern);
if (draw_info->gradient.stops != (StopInfo *) NULL)
draw_info->gradient.stops=(StopInfo *) RelinquishMagickMemory(
draw_info->gradient.stops);
if (draw_info->clip_mask != (char *) NULL)
draw_info->clip_mask=DestroyString(draw_info->clip_mask);
draw_info->signature=(~MagickCoreSignature);
draw_info=(DrawInfo *) RelinquishMagickMemory(draw_info);
return(draw_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y E d g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyEdge() destroys the specified polygon edge.
%
% The format of the DestroyEdge method is:
%
% ssize_t DestroyEdge(PolygonInfo *polygon_info,const int edge)
%
% A description of each parameter follows:
%
% o polygon_info: Specifies a pointer to an PolygonInfo structure.
%
% o edge: the polygon edge number to destroy.
%
*/
static size_t DestroyEdge(PolygonInfo *polygon_info,
const size_t edge)
{
assert(edge < polygon_info->number_edges);
polygon_info->edges[edge].points=(PointInfo *) RelinquishMagickMemory(
polygon_info->edges[edge].points);
polygon_info->number_edges--;
if (edge < polygon_info->number_edges)
(void) CopyMagickMemory(polygon_info->edges+edge,polygon_info->edges+edge+1,
(size_t) (polygon_info->number_edges-edge)*sizeof(*polygon_info->edges));
return(polygon_info->number_edges);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y P o l y g o n I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyPolygonInfo() destroys the PolygonInfo data structure.
%
% The format of the DestroyPolygonInfo method is:
%
% PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info)
%
% A description of each parameter follows:
%
% o polygon_info: Specifies a pointer to an PolygonInfo structure.
%
*/
static PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info)
{
register ssize_t
i;
for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
polygon_info->edges[i].points=(PointInfo *)
RelinquishMagickMemory(polygon_info->edges[i].points);
polygon_info->edges=(EdgeInfo *) RelinquishMagickMemory(polygon_info->edges);
return((PolygonInfo *) RelinquishMagickMemory(polygon_info));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w A f f i n e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawAffineImage() composites the source over the destination image as
% dictated by the affine transform.
%
% The format of the DrawAffineImage method is:
%
% MagickBooleanType DrawAffineImage(Image *image,const Image *source,
% const AffineMatrix *affine,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o source: the source image.
%
% o affine: the affine transform.
%
% o exception: return any errors or warnings in this structure.
%
*/
static SegmentInfo AffineEdge(const Image *image,const AffineMatrix *affine,
const double y,const SegmentInfo *edge)
{
double
intercept,
z;
register double
x;
SegmentInfo
inverse_edge;
/*
Determine left and right edges.
*/
inverse_edge.x1=edge->x1;
inverse_edge.y1=edge->y1;
inverse_edge.x2=edge->x2;
inverse_edge.y2=edge->y2;
z=affine->ry*y+affine->tx;
if (affine->sx >= MagickEpsilon)
{
intercept=(-z/affine->sx);
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z+(double) image->columns)/affine->sx;
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if (affine->sx < -MagickEpsilon)
{
intercept=(-z+(double) image->columns)/affine->sx;
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z/affine->sx);
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->columns))
{
inverse_edge.x2=edge->x1;
return(inverse_edge);
}
/*
Determine top and bottom edges.
*/
z=affine->sy*y+affine->ty;
if (affine->rx >= MagickEpsilon)
{
intercept=(-z/affine->rx);
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z+(double) image->rows)/affine->rx;
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if (affine->rx < -MagickEpsilon)
{
intercept=(-z+(double) image->rows)/affine->rx;
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z/affine->rx);
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->rows))
{
inverse_edge.x2=edge->x2;
return(inverse_edge);
}
return(inverse_edge);
}
static AffineMatrix InverseAffineMatrix(const AffineMatrix *affine)
{
AffineMatrix
inverse_affine;
double
determinant;
determinant=PerceptibleReciprocal(affine->sx*affine->sy-affine->rx*
affine->ry);
inverse_affine.sx=determinant*affine->sy;
inverse_affine.rx=determinant*(-affine->rx);
inverse_affine.ry=determinant*(-affine->ry);
inverse_affine.sy=determinant*affine->sx;
inverse_affine.tx=(-affine->tx)*inverse_affine.sx-affine->ty*
inverse_affine.ry;
inverse_affine.ty=(-affine->tx)*inverse_affine.rx-affine->ty*
inverse_affine.sy;
return(inverse_affine);
}
MagickExport MagickBooleanType DrawAffineImage(Image *image,
const Image *source,const AffineMatrix *affine,ExceptionInfo *exception)
{
AffineMatrix
inverse_affine;
CacheView
*image_view,
*source_view;
MagickBooleanType
status;
PixelInfo
zero;
PointInfo
extent[4],
min,
max;
register ssize_t
i;
SegmentInfo
edge;
ssize_t
start,
stop,
y;
/*
Determine bounding box.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(source != (const Image *) NULL);
assert(source->signature == MagickCoreSignature);
assert(affine != (AffineMatrix *) NULL);
extent[0].x=0.0;
extent[0].y=0.0;
extent[1].x=(double) source->columns-1.0;
extent[1].y=0.0;
extent[2].x=(double) source->columns-1.0;
extent[2].y=(double) source->rows-1.0;
extent[3].x=0.0;
extent[3].y=(double) source->rows-1.0;
for (i=0; i < 4; i++)
{
PointInfo
point;
point=extent[i];
extent[i].x=point.x*affine->sx+point.y*affine->ry+affine->tx;
extent[i].y=point.x*affine->rx+point.y*affine->sy+affine->ty;
}
min=extent[0];
max=extent[0];
for (i=1; i < 4; i++)
{
if (min.x > extent[i].x)
min.x=extent[i].x;
if (min.y > extent[i].y)
min.y=extent[i].y;
if (max.x < extent[i].x)
max.x=extent[i].x;
if (max.y < extent[i].y)
max.y=extent[i].y;
}
/*
Affine transform image.
*/
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
edge.x1=MagickMax(min.x,0.0);
edge.y1=MagickMax(min.y,0.0);
edge.x2=MagickMin(max.x,(double) image->columns-1.0);
edge.y2=MagickMin(max.y,(double) image->rows-1.0);
inverse_affine=InverseAffineMatrix(affine);
GetPixelInfo(image,&zero);
start=(ssize_t) ceil(edge.y1-0.5);
stop=(ssize_t) floor(edge.y2+0.5);
source_view=AcquireVirtualCacheView(source,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(source,image,1,1)
#endif
for (y=start; y <= stop; y++)
{
PixelInfo
composite,
pixel;
PointInfo
point;
register ssize_t
x;
register Quantum
*magick_restrict q;
SegmentInfo
inverse_edge;
ssize_t
x_offset;
inverse_edge=AffineEdge(source,&inverse_affine,(double) y,&edge);
if (inverse_edge.x2 < inverse_edge.x1)
continue;
q=GetCacheViewAuthenticPixels(image_view,(ssize_t) ceil(inverse_edge.x1-
0.5),y,(size_t) (floor(inverse_edge.x2+0.5)-ceil(inverse_edge.x1-0.5)+1),
1,exception);
if (q == (Quantum *) NULL)
continue;
pixel=zero;
composite=zero;
x_offset=0;
for (x=(ssize_t) ceil(inverse_edge.x1-0.5); x <= (ssize_t) floor(inverse_edge.x2+0.5); x++)
{
point.x=(double) x*inverse_affine.sx+y*inverse_affine.ry+
inverse_affine.tx;
point.y=(double) x*inverse_affine.rx+y*inverse_affine.sy+
inverse_affine.ty;
(void) InterpolatePixelInfo(source,source_view,UndefinedInterpolatePixel,
point.x,point.y,&pixel,exception);
GetPixelInfoPixel(image,q,&composite);
CompositePixelInfoOver(&pixel,pixel.alpha,&composite,composite.alpha,
&composite);
SetPixelViaPixelInfo(image,&composite,q);
x_offset++;
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
source_view=DestroyCacheView(source_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w B o u n d i n g R e c t a n g l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawBoundingRectangles() draws the bounding rectangles on the image. This
% is only useful for developers debugging the rendering algorithm.
%
% The format of the DrawBoundingRectangles method is:
%
% void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info,
% PolygonInfo *polygon_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o polygon_info: Specifies a pointer to a PolygonInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info,
const PolygonInfo *polygon_info,ExceptionInfo *exception)
{
DrawInfo
*clone_info;
double
mid;
PointInfo
end,
resolution,
start;
PrimitiveInfo
primitive_info[6];
register ssize_t
i;
SegmentInfo
bounds;
ssize_t
coordinates;
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) QueryColorCompliance("#0000",AllCompliance,&clone_info->fill,
exception);
resolution.x=DefaultResolution;
resolution.y=DefaultResolution;
if (clone_info->density != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(clone_info->density,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == MagickFalse)
resolution.y=resolution.x;
}
mid=(resolution.x/72.0)*ExpandAffine(&clone_info->affine)*
clone_info->stroke_width/2.0;
bounds.x1=0.0;
bounds.y1=0.0;
bounds.x2=0.0;
bounds.y2=0.0;
if (polygon_info != (PolygonInfo *) NULL)
{
bounds=polygon_info->edges[0].bounds;
for (i=1; i < (ssize_t) polygon_info->number_edges; i++)
{
if (polygon_info->edges[i].bounds.x1 < (double) bounds.x1)
bounds.x1=polygon_info->edges[i].bounds.x1;
if (polygon_info->edges[i].bounds.y1 < (double) bounds.y1)
bounds.y1=polygon_info->edges[i].bounds.y1;
if (polygon_info->edges[i].bounds.x2 > (double) bounds.x2)
bounds.x2=polygon_info->edges[i].bounds.x2;
if (polygon_info->edges[i].bounds.y2 > (double) bounds.y2)
bounds.y2=polygon_info->edges[i].bounds.y2;
}
bounds.x1-=mid;
bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double)
image->columns ? (double) image->columns-1 : bounds.x1;
bounds.y1-=mid;
bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double)
image->rows ? (double) image->rows-1 : bounds.y1;
bounds.x2+=mid;
bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double)
image->columns ? (double) image->columns-1 : bounds.x2;
bounds.y2+=mid;
bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double)
image->rows ? (double) image->rows-1 : bounds.y2;
for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
{
if (polygon_info->edges[i].direction != 0)
(void) QueryColorCompliance("red",AllCompliance,&clone_info->stroke,
exception);
else
(void) QueryColorCompliance("green",AllCompliance,&clone_info->stroke,
exception);
start.x=(double) (polygon_info->edges[i].bounds.x1-mid);
start.y=(double) (polygon_info->edges[i].bounds.y1-mid);
end.x=(double) (polygon_info->edges[i].bounds.x2+mid);
end.y=(double) (polygon_info->edges[i].bounds.y2+mid);
primitive_info[0].primitive=RectanglePrimitive;
TraceRectangle(primitive_info,start,end);
primitive_info[0].method=ReplaceMethod;
coordinates=(ssize_t) primitive_info[0].coordinates;
primitive_info[coordinates].primitive=UndefinedPrimitive;
(void) DrawPrimitive(image,clone_info,primitive_info,exception);
}
}
(void) QueryColorCompliance("blue",AllCompliance,&clone_info->stroke,
exception);
start.x=(double) (bounds.x1-mid);
start.y=(double) (bounds.y1-mid);
end.x=(double) (bounds.x2+mid);
end.y=(double) (bounds.y2+mid);
primitive_info[0].primitive=RectanglePrimitive;
TraceRectangle(primitive_info,start,end);
primitive_info[0].method=ReplaceMethod;
coordinates=(ssize_t) primitive_info[0].coordinates;
primitive_info[coordinates].primitive=UndefinedPrimitive;
(void) DrawPrimitive(image,clone_info,primitive_info,exception);
clone_info=DestroyDrawInfo(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w C l i p P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawClipPath() draws the clip path on the image mask.
%
% The format of the DrawClipPath method is:
%
% MagickBooleanType DrawClipPath(Image *image,const DrawInfo *draw_info,
% const char *name,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o name: the name of the clip path.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType DrawClipPath(Image *image,
const DrawInfo *draw_info,const char *name,ExceptionInfo *exception)
{
char
filename[MagickPathExtent];
Image
*clip_mask;
const char
*value;
DrawInfo
*clone_info;
MagickStatusType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (const DrawInfo *) NULL);
(void) FormatLocaleString(filename,MagickPathExtent,"%s",name);
value=GetImageArtifact(image,filename);
if (value == (const char *) NULL)
return(MagickFalse);
clip_mask=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if (clip_mask == (Image *) NULL)
return(MagickFalse);
(void) QueryColorCompliance("#0000",AllCompliance,
&clip_mask->background_color,exception);
clip_mask->background_color.alpha=(MagickRealType) TransparentAlpha;
(void) SetImageBackgroundColor(clip_mask,exception);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin clip-path %s",
draw_info->clip_mask);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) CloneString(&clone_info->primitive,value);
(void) QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill,
exception);
clone_info->clip_mask=(char *) NULL;
status=NegateImage(clip_mask,MagickFalse,exception);
(void) SetImageMask(image,ReadPixelMask,clip_mask,exception);
clip_mask=DestroyImage(clip_mask);
status&=DrawImage(image,clone_info,exception);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"end clip-path");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w D a s h P o l y g o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawDashPolygon() draws a dashed polygon (line, rectangle, ellipse) on the
% image while respecting the dash offset and dash pattern attributes.
%
% The format of the DrawDashPolygon method is:
%
% MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,
% const PrimitiveInfo *primitive_info,Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info,Image *image,ExceptionInfo *exception)
{
DrawInfo
*clone_info;
double
length,
maximum_length,
offset,
scale,
total_length;
MagickStatusType
status;
PrimitiveInfo
*dash_polygon;
register ssize_t
i;
register double
dx,
dy;
size_t
number_vertices;
ssize_t
j,
n;
assert(draw_info != (const DrawInfo *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-dash");
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
number_vertices=(size_t) i;
dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
(2UL*number_vertices+1UL),sizeof(*dash_polygon));
if (dash_polygon == (PrimitiveInfo *) NULL)
return(MagickFalse);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->miterlimit=0;
dash_polygon[0]=primitive_info[0];
scale=ExpandAffine(&draw_info->affine);
length=scale*(draw_info->dash_pattern[0]-0.5);
offset=draw_info->dash_offset != 0.0 ? scale*draw_info->dash_offset : 0.0;
j=1;
for (n=0; offset > 0.0; j=0)
{
if (draw_info->dash_pattern[n] <= 0.0)
break;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
if (offset > length)
{
offset-=length;
n++;
length=scale*(draw_info->dash_pattern[n]+0.5);
continue;
}
if (offset < length)
{
length-=offset;
offset=0.0;
break;
}
offset=0.0;
n++;
}
status=MagickTrue;
maximum_length=0.0;
total_length=0.0;
for (i=1; (i < (ssize_t) number_vertices) && (length >= 0.0); i++)
{
dx=primitive_info[i].point.x-primitive_info[i-1].point.x;
dy=primitive_info[i].point.y-primitive_info[i-1].point.y;
maximum_length=hypot((double) dx,dy);
if (length == 0.0)
{
n++;
if (draw_info->dash_pattern[n] == 0.0)
n=0;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
}
for (total_length=0.0; (length >= 0.0) && (maximum_length >= (total_length+length)); )
{
total_length+=length;
if ((n & 0x01) != 0)
{
dash_polygon[0]=primitive_info[0];
dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx*
total_length/maximum_length);
dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy*
total_length/maximum_length);
j=1;
}
else
{
if ((j+1) > (ssize_t) (2*number_vertices))
break;
dash_polygon[j]=primitive_info[i-1];
dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx*
total_length/maximum_length);
dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy*
total_length/maximum_length);
dash_polygon[j].coordinates=1;
j++;
dash_polygon[0].coordinates=(size_t) j;
dash_polygon[j].primitive=UndefinedPrimitive;
status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception);
}
n++;
if (draw_info->dash_pattern[n] == 0.0)
n=0;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
}
length-=(maximum_length-total_length);
if ((n & 0x01) != 0)
continue;
dash_polygon[j]=primitive_info[i];
dash_polygon[j].coordinates=1;
j++;
}
if ((total_length <= maximum_length) && ((n & 0x01) == 0) && (j > 1))
{
dash_polygon[j]=primitive_info[i-1];
dash_polygon[j].point.x+=MagickEpsilon;
dash_polygon[j].point.y+=MagickEpsilon;
dash_polygon[j].coordinates=1;
j++;
dash_polygon[0].coordinates=(size_t) j;
dash_polygon[j].primitive=UndefinedPrimitive;
status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception);
}
dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-dash");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawImage() draws a graphic primitive on your image. The primitive
% may be represented as a string or filename. Precede the filename with an
% "at" sign (@) and the contents of the file are drawn on the image. You
% can affect how text is drawn by setting one or more members of the draw
% info structure.
%
% The format of the DrawImage method is:
%
% MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline MagickBooleanType IsPoint(const char *point)
{
char
*p;
double
value;
value=StringToDouble(point,&p);
return((value == 0.0) && (p == point) ? MagickFalse : MagickTrue);
}
static inline void TracePoint(PrimitiveInfo *primitive_info,
const PointInfo point)
{
primitive_info->coordinates=1;
primitive_info->point=point;
}
MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info,
ExceptionInfo *exception)
{
#define RenderImageTag "Render/Image"
AffineMatrix
affine,
current;
char
keyword[MagickPathExtent],
geometry[MagickPathExtent],
pattern[MagickPathExtent],
*primitive,
*token;
const char
*q;
DrawInfo
**graphic_context;
MagickBooleanType
proceed;
MagickStatusType
status;
double
angle,
factor,
primitive_extent;
PointInfo
point;
PrimitiveInfo
*primitive_info;
PrimitiveType
primitive_type;
register const char
*p;
register ssize_t
i,
x;
SegmentInfo
bounds;
size_t
extent,
length,
number_points,
number_stops;
ssize_t
j,
k,
n;
StopInfo
*stops;
/*
Ensure the annotation info is valid.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
if ((draw_info->primitive == (char *) NULL) ||
(*draw_info->primitive == '\0'))
return(MagickFalse);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"begin draw-image");
if (*draw_info->primitive != '@')
primitive=AcquireString(draw_info->primitive);
else
primitive=FileToString(draw_info->primitive+1,~0UL,exception);
if (primitive == (char *) NULL)
return(MagickFalse);
primitive_extent=(double) strlen(primitive);
(void) SetImageArtifact(image,"MVG",primitive);
n=0;
number_stops=0;
stops=(StopInfo *) NULL;
/*
Allocate primitive info memory.
*/
graphic_context=(DrawInfo **) AcquireMagickMemory(
sizeof(*graphic_context));
if (graphic_context == (DrawInfo **) NULL)
{
primitive=DestroyString(primitive);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
number_points=6553;
primitive_info=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_points,
sizeof(*primitive_info));
if (primitive_info == (PrimitiveInfo *) NULL)
{
primitive=DestroyString(primitive);
for ( ; n >= 0; n--)
graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,draw_info);
graphic_context[n]->viewbox=image->page;
if ((image->page.width == 0) || (image->page.height == 0))
{
graphic_context[n]->viewbox.width=image->columns;
graphic_context[n]->viewbox.height=image->rows;
}
token=AcquireString(primitive);
extent=strlen(token)+MagickPathExtent;
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
for (q=primitive; *q != '\0'; )
{
/*
Interpret graphic primitive.
*/
GetNextToken(q,&q,MagickPathExtent,keyword);
if (*keyword == '\0')
break;
if (*keyword == '#')
{
/*
Comment.
*/
while ((*q != '\n') && (*q != '\0'))
q++;
continue;
}
p=q-strlen(keyword)-1;
primitive_type=UndefinedPrimitive;
current=graphic_context[n]->affine;
GetAffineMatrix(&affine);
switch (*keyword)
{
case ';':
break;
case 'a':
case 'A':
{
if (LocaleCompare("affine",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
affine.sx=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.rx=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.ry=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.sy=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.tx=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.ty=StringToDouble(token,(char **) NULL);
break;
}
if (LocaleCompare("alpha",keyword) == 0)
{
primitive_type=AlphaPrimitive;
break;
}
if (LocaleCompare("arc",keyword) == 0)
{
primitive_type=ArcPrimitive;
break;
}
status=MagickFalse;
break;
}
case 'b':
case 'B':
{
if (LocaleCompare("bezier",keyword) == 0)
{
primitive_type=BezierPrimitive;
break;
}
if (LocaleCompare("border-color",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) QueryColorCompliance(token,AllCompliance,
&graphic_context[n]->border_color,exception);
break;
}
status=MagickFalse;
break;
}
case 'c':
case 'C':
{
if (LocaleCompare("clip-path",keyword) == 0)
{
/*
Create clip mask.
*/
GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->clip_mask,token);
(void) DrawClipPath(image,graphic_context[n],
graphic_context[n]->clip_mask,exception);
break;
}
if (LocaleCompare("clip-rule",keyword) == 0)
{
ssize_t
fill_rule;
GetNextToken(q,&q,extent,token);
fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse,
token);
if (fill_rule == -1)
status=MagickFalse;
else
graphic_context[n]->fill_rule=(FillRule) fill_rule;
break;
}
if (LocaleCompare("clip-units",keyword) == 0)
{
ssize_t
clip_units;
GetNextToken(q,&q,extent,token);
clip_units=ParseCommandOption(MagickClipPathOptions,MagickFalse,
token);
if (clip_units == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->clip_units=(ClipPathUnits) clip_units;
if (clip_units == ObjectBoundingBox)
{
GetAffineMatrix(¤t);
affine.sx=draw_info->bounds.x2;
affine.sy=draw_info->bounds.y2;
affine.tx=draw_info->bounds.x1;
affine.ty=draw_info->bounds.y1;
break;
}
break;
}
if (LocaleCompare("circle",keyword) == 0)
{
primitive_type=CirclePrimitive;
break;
}
if (LocaleCompare("color",keyword) == 0)
{
primitive_type=ColorPrimitive;
break;
}
status=MagickFalse;
break;
}
case 'd':
case 'D':
{
if (LocaleCompare("decorate",keyword) == 0)
{
ssize_t
decorate;
GetNextToken(q,&q,extent,token);
decorate=ParseCommandOption(MagickDecorateOptions,MagickFalse,
token);
if (decorate == -1)
status=MagickFalse;
else
graphic_context[n]->decorate=(DecorationType) decorate;
break;
}
if (LocaleCompare("density",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->density,token);
break;
}
if (LocaleCompare("direction",keyword) == 0)
{
ssize_t
direction;
GetNextToken(q,&q,extent,token);
direction=ParseCommandOption(MagickDirectionOptions,MagickFalse,
token);
if (direction == -1)
status=MagickFalse;
else
graphic_context[n]->direction=(DirectionType) direction;
break;
}
status=MagickFalse;
break;
}
case 'e':
case 'E':
{
if (LocaleCompare("ellipse",keyword) == 0)
{
primitive_type=EllipsePrimitive;
break;
}
if (LocaleCompare("encoding",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->encoding,token);
break;
}
status=MagickFalse;
break;
}
case 'f':
case 'F':
{
if (LocaleCompare("fill",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(pattern,MagickPathExtent,"%s",token);
if (GetImageArtifact(image,pattern) != (const char *) NULL)
(void) DrawPatternPath(image,draw_info,token,
&graphic_context[n]->fill_pattern,exception);
else
{
status&=QueryColorCompliance(token,AllCompliance,
&graphic_context[n]->fill,exception);
if (status == MagickFalse)
{
ImageInfo
*pattern_info;
pattern_info=AcquireImageInfo();
(void) CopyMagickString(pattern_info->filename,token,
MagickPathExtent);
graphic_context[n]->fill_pattern=ReadImage(pattern_info,
exception);
CatchException(exception);
pattern_info=DestroyImageInfo(pattern_info);
}
}
break;
}
if (LocaleCompare("fill-opacity",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
graphic_context[n]->fill.alpha=(double) QuantumRange*
factor*StringToDouble(token,(char **) NULL);
break;
}
if (LocaleCompare("fill-rule",keyword) == 0)
{
ssize_t
fill_rule;
GetNextToken(q,&q,extent,token);
fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse,
token);
if (fill_rule == -1)
status=MagickFalse;
else
graphic_context[n]->fill_rule=(FillRule) fill_rule;
break;
}
if (LocaleCompare("font",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->font,token);
if (LocaleCompare("none",token) == 0)
graphic_context[n]->font=(char *)
RelinquishMagickMemory(graphic_context[n]->font);
break;
}
if (LocaleCompare("font-family",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->family,token);
break;
}
if (LocaleCompare("font-size",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->pointsize=StringToDouble(token,(char **) NULL);
break;
}
if (LocaleCompare("font-stretch",keyword) == 0)
{
ssize_t
stretch;
GetNextToken(q,&q,extent,token);
stretch=ParseCommandOption(MagickStretchOptions,MagickFalse,token);
if (stretch == -1)
status=MagickFalse;
else
graphic_context[n]->stretch=(StretchType) stretch;
break;
}
if (LocaleCompare("font-style",keyword) == 0)
{
ssize_t
style;
GetNextToken(q,&q,extent,token);
style=ParseCommandOption(MagickStyleOptions,MagickFalse,token);
if (style == -1)
status=MagickFalse;
else
graphic_context[n]->style=(StyleType) style;
break;
}
if (LocaleCompare("font-weight",keyword) == 0)
{
ssize_t
weight;
GetNextToken(q,&q,extent,token);
weight=ParseCommandOption(MagickWeightOptions,MagickFalse,token);
if (weight == -1)
weight=(ssize_t) StringToUnsignedLong(token);
graphic_context[n]->weight=(size_t) weight;
break;
}
status=MagickFalse;
break;
}
case 'g':
case 'G':
{
if (LocaleCompare("gradient-units",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("gravity",keyword) == 0)
{
ssize_t
gravity;
GetNextToken(q,&q,extent,token);
gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,token);
if (gravity == -1)
status=MagickFalse;
else
graphic_context[n]->gravity=(GravityType) gravity;
break;
}
status=MagickFalse;
break;
}
case 'i':
case 'I':
{
if (LocaleCompare("image",keyword) == 0)
{
ssize_t
compose;
primitive_type=ImagePrimitive;
GetNextToken(q,&q,extent,token);
compose=ParseCommandOption(MagickComposeOptions,MagickFalse,token);
if (compose == -1)
status=MagickFalse;
else
graphic_context[n]->compose=(CompositeOperator) compose;
break;
}
if (LocaleCompare("interline-spacing",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->interline_spacing=StringToDouble(token,
(char **) NULL);
break;
}
if (LocaleCompare("interword-spacing",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->interword_spacing=StringToDouble(token,
(char **) NULL);
break;
}
status=MagickFalse;
break;
}
case 'k':
case 'K':
{
if (LocaleCompare("kerning",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->kerning=StringToDouble(token,(char **) NULL);
break;
}
status=MagickFalse;
break;
}
case 'l':
case 'L':
{
if (LocaleCompare("line",keyword) == 0)
primitive_type=LinePrimitive;
else
status=MagickFalse;
break;
}
case 'o':
case 'O':
{
if (LocaleCompare("offset",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("opacity",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
graphic_context[n]->alpha=ClampToQuantum(QuantumRange*(1.0-((1.0-
QuantumScale*graphic_context[n]->alpha)*factor*
StringToDouble(token,(char **) NULL))));
graphic_context[n]->fill.alpha=(double) graphic_context[n]->alpha;
graphic_context[n]->stroke.alpha=(double) graphic_context[n]->alpha;
break;
}
status=MagickFalse;
break;
}
case 'p':
case 'P':
{
if (LocaleCompare("path",keyword) == 0)
{
primitive_type=PathPrimitive;
break;
}
if (LocaleCompare("point",keyword) == 0)
{
primitive_type=PointPrimitive;
break;
}
if (LocaleCompare("polyline",keyword) == 0)
{
primitive_type=PolylinePrimitive;
break;
}
if (LocaleCompare("polygon",keyword) == 0)
{
primitive_type=PolygonPrimitive;
break;
}
if (LocaleCompare("pop",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare("clip-path",token) == 0)
break;
if (LocaleCompare("defs",token) == 0)
break;
if (LocaleCompare("gradient",token) == 0)
break;
if (LocaleCompare("graphic-context",token) == 0)
{
if (n <= 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),
DrawError,"UnbalancedGraphicContextPushPop","`%s'",token);
n=0;
break;
}
if (graphic_context[n]->clip_mask != (char *) NULL)
if (LocaleCompare(graphic_context[n]->clip_mask,
graphic_context[n-1]->clip_mask) != 0)
(void) SetImageMask(image,ReadPixelMask,(Image *) NULL,
exception);
graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
n--;
break;
}
if (LocaleCompare("pattern",token) == 0)
break;
status=MagickFalse;
break;
}
if (LocaleCompare("push",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare("clip-path",token) == 0)
{
char
name[MagickPathExtent];
GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(name,MagickPathExtent,"%s",token);
for (p=q; *q != '\0'; )
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare(token,"pop") != 0)
continue;
GetNextToken(q,(const char **) NULL,extent,token);
if (LocaleCompare(token,"clip-path") != 0)
continue;
break;
}
(void) CopyMagickString(token,p,(size_t) (q-p-4+1));
(void) SetImageArtifact(image,name,token);
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("gradient",token) == 0)
{
char
key[2*MagickPathExtent],
name[MagickPathExtent],
type[MagickPathExtent];
SegmentInfo
segment;
GetNextToken(q,&q,extent,token);
(void) CopyMagickString(name,token,MagickPathExtent);
GetNextToken(q,&q,extent,token);
(void) CopyMagickString(type,token,MagickPathExtent);
GetNextToken(q,&q,extent,token);
segment.x1=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
segment.y1=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
segment.x2=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
segment.y2=StringToDouble(token,(char **) NULL);
if (LocaleCompare(type,"radial") == 0)
{
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
}
for (p=q; *q != '\0'; )
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare(token,"pop") != 0)
continue;
GetNextToken(q,(const char **) NULL,extent,token);
if (LocaleCompare(token,"gradient") != 0)
continue;
break;
}
(void) CopyMagickString(token,p,(size_t) (q-p-4+1));
bounds.x1=graphic_context[n]->affine.sx*segment.x1+
graphic_context[n]->affine.ry*segment.y1+
graphic_context[n]->affine.tx;
bounds.y1=graphic_context[n]->affine.rx*segment.x1+
graphic_context[n]->affine.sy*segment.y1+
graphic_context[n]->affine.ty;
bounds.x2=graphic_context[n]->affine.sx*segment.x2+
graphic_context[n]->affine.ry*segment.y2+
graphic_context[n]->affine.tx;
bounds.y2=graphic_context[n]->affine.rx*segment.x2+
graphic_context[n]->affine.sy*segment.y2+
graphic_context[n]->affine.ty;
(void) FormatLocaleString(key,MagickPathExtent,"%s",name);
(void) SetImageArtifact(image,key,token);
(void) FormatLocaleString(key,MagickPathExtent,"%s-type",name);
(void) SetImageArtifact(image,key,type);
(void) FormatLocaleString(key,MagickPathExtent,"%s-geometry",
name);
(void) FormatLocaleString(geometry,MagickPathExtent,
"%gx%g%+.15g%+.15g",
MagickMax(fabs(bounds.x2-bounds.x1+1.0),1.0),
MagickMax(fabs(bounds.y2-bounds.y1+1.0),1.0),
bounds.x1,bounds.y1);
(void) SetImageArtifact(image,key,geometry);
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("pattern",token) == 0)
{
char
key[2*MagickPathExtent],
name[MagickPathExtent];
RectangleInfo
pattern_bounds;
GetNextToken(q,&q,extent,token);
(void) CopyMagickString(name,token,MagickPathExtent);
GetNextToken(q,&q,extent,token);
pattern_bounds.x=(ssize_t) ceil(StringToDouble(token,
(char **) NULL)-0.5);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
pattern_bounds.y=(ssize_t) ceil(StringToDouble(token,
(char **) NULL)-0.5);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
pattern_bounds.width=(size_t) floor(StringToDouble(token,
(char **) NULL)+0.5);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
pattern_bounds.height=(size_t) floor(StringToDouble(token,
(char **) NULL)+0.5);
for (p=q; *q != '\0'; )
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare(token,"pop") != 0)
continue;
GetNextToken(q,(const char **) NULL,extent,token);
if (LocaleCompare(token,"pattern") != 0)
continue;
break;
}
(void) CopyMagickString(token,p,(size_t) (q-p-4+1));
(void) FormatLocaleString(key,MagickPathExtent,"%s",name);
(void) SetImageArtifact(image,key,token);
(void) FormatLocaleString(key,MagickPathExtent,"%s-geometry",
name);
(void) FormatLocaleString(geometry,MagickPathExtent,
"%.20gx%.20g%+.20g%+.20g",(double)pattern_bounds.width,
(double)pattern_bounds.height,(double)pattern_bounds.x,
(double)pattern_bounds.y);
(void) SetImageArtifact(image,key,geometry);
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("graphic-context",token) == 0)
{
n++;
graphic_context=(DrawInfo **) ResizeQuantumMemory(
graphic_context,(size_t) (n+1),sizeof(*graphic_context));
if (graphic_context == (DrawInfo **) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
break;
}
graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,
graphic_context[n-1]);
break;
}
if (LocaleCompare("defs",token) == 0)
break;
status=MagickFalse;
break;
}
status=MagickFalse;
break;
}
case 'r':
case 'R':
{
if (LocaleCompare("rectangle",keyword) == 0)
{
primitive_type=RectanglePrimitive;
break;
}
if (LocaleCompare("rotate",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
angle=StringToDouble(token,(char **) NULL);
affine.sx=cos(DegreesToRadians(fmod((double) angle,360.0)));
affine.rx=sin(DegreesToRadians(fmod((double) angle,360.0)));
affine.ry=(-sin(DegreesToRadians(fmod((double) angle,360.0))));
affine.sy=cos(DegreesToRadians(fmod((double) angle,360.0)));
break;
}
if (LocaleCompare("roundRectangle",keyword) == 0)
{
primitive_type=RoundRectanglePrimitive;
break;
}
status=MagickFalse;
break;
}
case 's':
case 'S':
{
if (LocaleCompare("scale",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
affine.sx=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.sy=StringToDouble(token,(char **) NULL);
break;
}
if (LocaleCompare("skewX",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
angle=StringToDouble(token,(char **) NULL);
affine.ry=sin(DegreesToRadians(angle));
break;
}
if (LocaleCompare("skewY",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
angle=StringToDouble(token,(char **) NULL);
affine.rx=(-tan(DegreesToRadians(angle)/2.0));
break;
}
if (LocaleCompare("stop-color",keyword) == 0)
{
PixelInfo
stop_color;
number_stops++;
if (number_stops == 1)
stops=(StopInfo *) AcquireQuantumMemory(2,sizeof(*stops));
else if (number_stops > 2)
stops=(StopInfo *) ResizeQuantumMemory(stops,number_stops,
sizeof(*stops));
if (stops == (StopInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
break;
}
GetNextToken(q,&q,extent,token);
(void) QueryColorCompliance(token,AllCompliance,&stop_color,
exception);
stops[number_stops-1].color=stop_color;
GetNextToken(q,&q,extent,token);
stops[number_stops-1].offset=StringToDouble(token,(char **) NULL);
break;
}
if (LocaleCompare("stroke",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(pattern,MagickPathExtent,"%s",token);
if (GetImageArtifact(image,pattern) != (const char *) NULL)
(void) DrawPatternPath(image,draw_info,token,
&graphic_context[n]->stroke_pattern,exception);
else
{
status&=QueryColorCompliance(token,AllCompliance,
&graphic_context[n]->stroke,exception);
if (status == MagickFalse)
{
ImageInfo
*pattern_info;
pattern_info=AcquireImageInfo();
(void) CopyMagickString(pattern_info->filename,token,
MagickPathExtent);
graphic_context[n]->stroke_pattern=ReadImage(pattern_info,
exception);
CatchException(exception);
pattern_info=DestroyImageInfo(pattern_info);
}
}
break;
}
if (LocaleCompare("stroke-antialias",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->stroke_antialias=
StringToLong(token) != 0 ? MagickTrue : MagickFalse;
break;
}
if (LocaleCompare("stroke-dasharray",keyword) == 0)
{
if (graphic_context[n]->dash_pattern != (double *) NULL)
graphic_context[n]->dash_pattern=(double *)
RelinquishMagickMemory(graphic_context[n]->dash_pattern);
if (IsPoint(q) != MagickFalse)
{
const char
*r;
r=q;
GetNextToken(r,&r,extent,token);
if (*token == ',')
GetNextToken(r,&r,extent,token);
for (x=0; IsPoint(token) != MagickFalse; x++)
{
GetNextToken(r,&r,extent,token);
if (*token == ',')
GetNextToken(r,&r,extent,token);
}
graphic_context[n]->dash_pattern=(double *)
AcquireQuantumMemory((size_t) (2UL*x+1UL),
sizeof(*graphic_context[n]->dash_pattern));
if (graphic_context[n]->dash_pattern == (double *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
break;
}
for (j=0; j < x; j++)
{
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
graphic_context[n]->dash_pattern[j]=StringToDouble(token,
(char **) NULL);
if (graphic_context[n]->dash_pattern[j] < 0.0)
status=MagickFalse;
}
if ((x & 0x01) != 0)
for ( ; j < (2*x); j++)
graphic_context[n]->dash_pattern[j]=
graphic_context[n]->dash_pattern[j-x];
graphic_context[n]->dash_pattern[j]=0.0;
break;
}
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("stroke-dashoffset",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->dash_offset=StringToDouble(token,
(char **) NULL);
break;
}
if (LocaleCompare("stroke-linecap",keyword) == 0)
{
ssize_t
linecap;
GetNextToken(q,&q,extent,token);
linecap=ParseCommandOption(MagickLineCapOptions,MagickFalse,token);
if (linecap == -1)
status=MagickFalse;
else
graphic_context[n]->linecap=(LineCap) linecap;
break;
}
if (LocaleCompare("stroke-linejoin",keyword) == 0)
{
ssize_t
linejoin;
GetNextToken(q,&q,extent,token);
linejoin=ParseCommandOption(MagickLineJoinOptions,MagickFalse,
token);
if (linejoin == -1)
status=MagickFalse;
else
graphic_context[n]->linejoin=(LineJoin) linejoin;
break;
}
if (LocaleCompare("stroke-miterlimit",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->miterlimit=StringToUnsignedLong(token);
break;
}
if (LocaleCompare("stroke-opacity",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
graphic_context[n]->stroke.alpha=(double) QuantumRange*
factor*StringToDouble(token,(char **) NULL);
break;
}
if (LocaleCompare("stroke-width",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->stroke_width=StringToDouble(token,
(char **) NULL);
break;
}
status=MagickFalse;
break;
}
case 't':
case 'T':
{
if (LocaleCompare("text",keyword) == 0)
{
primitive_type=TextPrimitive;
break;
}
if (LocaleCompare("text-align",keyword) == 0)
{
ssize_t
align;
GetNextToken(q,&q,extent,token);
align=ParseCommandOption(MagickAlignOptions,MagickFalse,token);
if (align == -1)
status=MagickFalse;
else
graphic_context[n]->align=(AlignType) align;
break;
}
if (LocaleCompare("text-anchor",keyword) == 0)
{
ssize_t
align;
GetNextToken(q,&q,extent,token);
align=ParseCommandOption(MagickAlignOptions,MagickFalse,token);
if (align == -1)
status=MagickFalse;
else
graphic_context[n]->align=(AlignType) align;
break;
}
if (LocaleCompare("text-antialias",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->text_antialias=
StringToLong(token) != 0 ? MagickTrue : MagickFalse;
break;
}
if (LocaleCompare("text-undercolor",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) QueryColorCompliance(token,AllCompliance,
&graphic_context[n]->undercolor,exception);
break;
}
if (LocaleCompare("translate",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
affine.tx=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.ty=StringToDouble(token,(char **) NULL);
break;
}
status=MagickFalse;
break;
}
case 'v':
case 'V':
{
if (LocaleCompare("viewbox",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.x=(ssize_t) ceil(StringToDouble(token,
(char **) NULL)-0.5);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.y=(ssize_t) ceil(StringToDouble(token,
(char **) NULL)-0.5);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.width=(size_t) floor(StringToDouble(
token,(char **) NULL)+0.5);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.height=(size_t) floor(StringToDouble(
token,(char **) NULL)+0.5);
break;
}
status=MagickFalse;
break;
}
default:
{
status=MagickFalse;
break;
}
}
if (status == MagickFalse)
break;
if ((affine.sx != 1.0) || (affine.rx != 0.0) || (affine.ry != 0.0) ||
(affine.sy != 1.0) || (affine.tx != 0.0) || (affine.ty != 0.0))
{
graphic_context[n]->affine.sx=current.sx*affine.sx+current.ry*affine.rx;
graphic_context[n]->affine.rx=current.rx*affine.sx+current.sy*affine.rx;
graphic_context[n]->affine.ry=current.sx*affine.ry+current.ry*affine.sy;
graphic_context[n]->affine.sy=current.rx*affine.ry+current.sy*affine.sy;
graphic_context[n]->affine.tx=current.sx*affine.tx+current.ry*affine.ty+
current.tx;
graphic_context[n]->affine.ty=current.rx*affine.tx+current.sy*affine.ty+
current.ty;
}
if (primitive_type == UndefinedPrimitive)
{
if (*q == '\0')
{
if (number_stops > 1)
{
GradientType
type;
type=LinearGradient;
if (draw_info->gradient.type == RadialGradient)
type=RadialGradient;
(void) GradientImage(image,type,PadSpread,stops,number_stops,
exception);
}
if (number_stops > 0)
stops=(StopInfo *) RelinquishMagickMemory(stops);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",
(int) (q-p),p);
continue;
}
/*
Parse the primitive attributes.
*/
i=0;
j=0;
primitive_info[0].point.x=0.0;
primitive_info[0].point.y=0.0;
for (x=0; *q != '\0'; x++)
{
/*
Define points.
*/
if (IsPoint(q) == MagickFalse)
break;
GetNextToken(q,&q,extent,token);
point.x=StringToDouble(token,(char **) NULL);
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
point.y=StringToDouble(token,(char **) NULL);
GetNextToken(q,(const char **) NULL,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
primitive_info[i].primitive=primitive_type;
primitive_info[i].point=point;
primitive_info[i].coordinates=0;
primitive_info[i].method=FloodfillMethod;
i++;
if (i < (ssize_t) number_points)
continue;
number_points<<=1;
primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info,
(size_t) number_points,sizeof(*primitive_info));
if (primitive_info == (PrimitiveInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
break;
}
}
primitive_info[j].primitive=primitive_type;
primitive_info[j].coordinates=(size_t) x;
primitive_info[j].method=FloodfillMethod;
primitive_info[j].text=(char *) NULL;
/*
Circumscribe primitive within a circle.
*/
bounds.x1=primitive_info[j].point.x;
bounds.y1=primitive_info[j].point.y;
bounds.x2=primitive_info[j].point.x;
bounds.y2=primitive_info[j].point.y;
for (k=1; k < (ssize_t) primitive_info[j].coordinates; k++)
{
point=primitive_info[j+k].point;
if (point.x < bounds.x1)
bounds.x1=point.x;
if (point.y < bounds.y1)
bounds.y1=point.y;
if (point.x > bounds.x2)
bounds.x2=point.x;
if (point.y > bounds.y2)
bounds.y2=point.y;
}
/*
Speculate how many points our primitive might consume.
*/
length=primitive_info[j].coordinates;
switch (primitive_type)
{
case RectanglePrimitive:
{
length*=5;
break;
}
case RoundRectanglePrimitive:
{
double
alpha,
beta,
radius;
alpha=bounds.x2-bounds.x1;
beta=bounds.y2-bounds.y1;
radius=hypot((double) alpha,(double) beta);
length*=5;
length+=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360;
break;
}
case BezierPrimitive:
{
if (primitive_info[j].coordinates > 107)
(void) ThrowMagickException(exception,GetMagickModule(),DrawError,
"TooManyBezierCoordinates","`%s'",token);
length=BezierQuantum*primitive_info[j].coordinates;
break;
}
case PathPrimitive:
{
char
*s,
*t;
GetNextToken(q,&q,extent,token);
length=1;
t=token;
for (s=token; *s != '\0'; s=t)
{
double
value;
value=StringToDouble(s,&t);
(void) value;
if (s == t)
{
t++;
continue;
}
length++;
}
length=length*BezierQuantum/2;
break;
}
case CirclePrimitive:
case ArcPrimitive:
case EllipsePrimitive:
{
double
alpha,
beta,
radius;
alpha=bounds.x2-bounds.x1;
beta=bounds.y2-bounds.y1;
radius=hypot((double) alpha,(double) beta);
length=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360;
break;
}
default:
break;
}
if ((size_t) (i+length) >= number_points)
{
/*
Resize based on speculative points required by primitive.
*/
number_points+=length+1;
primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info,
(size_t) number_points,sizeof(*primitive_info));
if (primitive_info == (PrimitiveInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
break;
}
}
switch (primitive_type)
{
case PointPrimitive:
default:
{
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
TracePoint(primitive_info+j,primitive_info[j].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case LinePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
TraceLine(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case RectanglePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
TraceRectangle(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case RoundRectanglePrimitive:
{
if (primitive_info[j].coordinates != 3)
{
status=MagickFalse;
break;
}
TraceRoundRectangle(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point,primitive_info[j+2].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case ArcPrimitive:
{
if (primitive_info[j].coordinates != 3)
{
primitive_type=UndefinedPrimitive;
break;
}
TraceArc(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point,primitive_info[j+2].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case EllipsePrimitive:
{
if (primitive_info[j].coordinates != 3)
{
status=MagickFalse;
break;
}
TraceEllipse(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point,primitive_info[j+2].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case CirclePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
TraceCircle(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case PolylinePrimitive:
break;
case PolygonPrimitive:
{
primitive_info[i]=primitive_info[j];
primitive_info[i].coordinates=0;
primitive_info[j].coordinates++;
i++;
break;
}
case BezierPrimitive:
{
if (primitive_info[j].coordinates < 3)
{
status=MagickFalse;
break;
}
TraceBezier(primitive_info+j,primitive_info[j].coordinates);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case PathPrimitive:
{
i=(ssize_t) (j+TracePath(primitive_info+j,token));
break;
}
case AlphaPrimitive:
case ColorPrimitive:
{
ssize_t
method;
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
GetNextToken(q,&q,extent,token);
method=ParseCommandOption(MagickMethodOptions,MagickFalse,token);
if (method == -1)
status=MagickFalse;
else
primitive_info[j].method=(PaintMethod) method;
break;
}
case TextPrimitive:
{
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
if (*token != ',')
GetNextToken(q,&q,extent,token);
primitive_info[j].text=AcquireString(token);
break;
}
case ImagePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
GetNextToken(q,&q,extent,token);
primitive_info[j].text=AcquireString(token);
break;
}
}
if (primitive_info == (PrimitiveInfo *) NULL)
break;
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p),p);
if (status == MagickFalse)
break;
primitive_info[i].primitive=UndefinedPrimitive;
if (i == 0)
continue;
/*
Transform points.
*/
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
{
point=primitive_info[i].point;
primitive_info[i].point.x=graphic_context[n]->affine.sx*point.x+
graphic_context[n]->affine.ry*point.y+graphic_context[n]->affine.tx;
primitive_info[i].point.y=graphic_context[n]->affine.rx*point.x+
graphic_context[n]->affine.sy*point.y+graphic_context[n]->affine.ty;
point=primitive_info[i].point;
if (point.x < graphic_context[n]->bounds.x1)
graphic_context[n]->bounds.x1=point.x;
if (point.y < graphic_context[n]->bounds.y1)
graphic_context[n]->bounds.y1=point.y;
if (point.x > graphic_context[n]->bounds.x2)
graphic_context[n]->bounds.x2=point.x;
if (point.y > graphic_context[n]->bounds.y2)
graphic_context[n]->bounds.y2=point.y;
if (primitive_info[i].primitive == ImagePrimitive)
break;
if (i >= (ssize_t) number_points)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
}
if (graphic_context[n]->render != MagickFalse)
{
if ((n != 0) && (graphic_context[n]->clip_mask != (char *) NULL) &&
(LocaleCompare(graphic_context[n]->clip_mask,
graphic_context[n-1]->clip_mask) != 0))
status&=DrawClipPath(image,graphic_context[n],
graphic_context[n]->clip_mask,exception);
status&=DrawPrimitive(image,graphic_context[n],primitive_info,
exception);
}
if (primitive_info->text != (char *) NULL)
primitive_info->text=(char *) RelinquishMagickMemory(
primitive_info->text);
proceed=SetImageProgress(image,RenderImageTag,q-primitive,(MagickSizeType)
primitive_extent);
if (proceed == MagickFalse)
break;
if (status == 0)
break;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"end draw-image");
/*
Relinquish resources.
*/
token=DestroyString(token);
if (primitive_info != (PrimitiveInfo *) NULL)
primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info);
primitive=DestroyString(primitive);
for ( ; n >= 0; n--)
graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context);
if (status == MagickFalse)
ThrowBinaryException(DrawError,"NonconformingDrawingPrimitiveDefinition",
keyword);
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w G r a d i e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawGradientImage() draws a linear gradient on the image.
%
% The format of the DrawGradientImage method is:
%
% MagickBooleanType DrawGradientImage(Image *image,
% const DrawInfo *draw_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double GetStopColorOffset(const GradientInfo *gradient,
const ssize_t x,const ssize_t y)
{
switch (gradient->type)
{
case UndefinedGradient:
case LinearGradient:
{
double
gamma,
length,
offset,
scale;
PointInfo
p,
q;
const SegmentInfo
*gradient_vector;
gradient_vector=(&gradient->gradient_vector);
p.x=gradient_vector->x2-gradient_vector->x1;
p.y=gradient_vector->y2-gradient_vector->y1;
q.x=(double) x-gradient_vector->x1;
q.y=(double) y-gradient_vector->y1;
length=sqrt(q.x*q.x+q.y*q.y);
gamma=sqrt(p.x*p.x+p.y*p.y)*length;
gamma=PerceptibleReciprocal(gamma);
scale=p.x*q.x+p.y*q.y;
offset=gamma*scale*length;
return(offset);
}
case RadialGradient:
{
PointInfo
v;
if (gradient->spread == RepeatSpread)
{
v.x=(double) x-gradient->center.x;
v.y=(double) y-gradient->center.y;
return(sqrt(v.x*v.x+v.y*v.y));
}
v.x=(double) (((x-gradient->center.x)*cos(DegreesToRadians(
gradient->angle)))+((y-gradient->center.y)*sin(DegreesToRadians(
gradient->angle))))/gradient->radii.x;
v.y=(double) (((x-gradient->center.x)*sin(DegreesToRadians(
gradient->angle)))-((y-gradient->center.y)*cos(DegreesToRadians(
gradient->angle))))/gradient->radii.y;
return(sqrt(v.x*v.x+v.y*v.y));
}
}
return(0.0);
}
static int StopInfoCompare(const void *x,const void *y)
{
StopInfo
*stop_1,
*stop_2;
stop_1=(StopInfo *) x;
stop_2=(StopInfo *) y;
if (stop_1->offset > stop_2->offset)
return(1);
if (fabs(stop_1->offset-stop_2->offset) <= MagickEpsilon)
return(0);
return(-1);
}
MagickExport MagickBooleanType DrawGradientImage(Image *image,
const DrawInfo *draw_info,ExceptionInfo *exception)
{
CacheView
*image_view;
const GradientInfo
*gradient;
const SegmentInfo
*gradient_vector;
double
length;
MagickBooleanType
status;
PixelInfo
zero;
PointInfo
point;
RectangleInfo
bounding_box;
ssize_t
y;
/*
Draw linear or radial gradient on image.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (const DrawInfo *) NULL);
gradient=(&draw_info->gradient);
qsort(gradient->stops,gradient->number_stops,sizeof(StopInfo),
StopInfoCompare);
gradient_vector=(&gradient->gradient_vector);
point.x=gradient_vector->x2-gradient_vector->x1;
point.y=gradient_vector->y2-gradient_vector->y1;
length=sqrt(point.x*point.x+point.y*point.y);
bounding_box=gradient->bounding_box;
status=MagickTrue;
GetPixelInfo(image,&zero);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,1,1)
#endif
for (y=bounding_box.y; y < (ssize_t) bounding_box.height; y++)
{
PixelInfo
composite,
pixel;
double
alpha,
offset;
register Quantum
*magick_restrict q;
register ssize_t
i,
x;
ssize_t
j;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
pixel=zero;
composite=zero;
offset=GetStopColorOffset(gradient,0,y);
if (gradient->type != RadialGradient)
offset/=length;
for (x=bounding_box.x; x < (ssize_t) bounding_box.width; x++)
{
GetPixelInfoPixel(image,q,&pixel);
switch (gradient->spread)
{
case UndefinedSpread:
case PadSpread:
{
if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
(y != (ssize_t) ceil(gradient_vector->y1-0.5)))
{
offset=GetStopColorOffset(gradient,x,y);
if (gradient->type != RadialGradient)
offset/=length;
}
for (i=0; i < (ssize_t) gradient->number_stops; i++)
if (offset < gradient->stops[i].offset)
break;
if ((offset < 0.0) || (i == 0))
composite=gradient->stops[0].color;
else
if ((offset > 1.0) || (i == (ssize_t) gradient->number_stops))
composite=gradient->stops[gradient->number_stops-1].color;
else
{
j=i;
i--;
alpha=(offset-gradient->stops[i].offset)/
(gradient->stops[j].offset-gradient->stops[i].offset);
CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,
&gradient->stops[j].color,alpha,&composite);
}
break;
}
case ReflectSpread:
{
if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
(y != (ssize_t) ceil(gradient_vector->y1-0.5)))
{
offset=GetStopColorOffset(gradient,x,y);
if (gradient->type != RadialGradient)
offset/=length;
}
if (offset < 0.0)
offset=(-offset);
if ((ssize_t) fmod(offset,2.0) == 0)
offset=fmod(offset,1.0);
else
offset=1.0-fmod(offset,1.0);
for (i=0; i < (ssize_t) gradient->number_stops; i++)
if (offset < gradient->stops[i].offset)
break;
if (i == 0)
composite=gradient->stops[0].color;
else
if (i == (ssize_t) gradient->number_stops)
composite=gradient->stops[gradient->number_stops-1].color;
else
{
j=i;
i--;
alpha=(offset-gradient->stops[i].offset)/
(gradient->stops[j].offset-gradient->stops[i].offset);
CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,
&gradient->stops[j].color,alpha,&composite);
}
break;
}
case RepeatSpread:
{
MagickBooleanType
antialias;
double
repeat;
antialias=MagickFalse;
repeat=0.0;
if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
(y != (ssize_t) ceil(gradient_vector->y1-0.5)))
{
offset=GetStopColorOffset(gradient,x,y);
if (gradient->type == LinearGradient)
{
repeat=fmod(offset,length);
if (repeat < 0.0)
repeat=length-fmod(-repeat,length);
else
repeat=fmod(offset,length);
antialias=(repeat < length) && ((repeat+1.0) > length) ?
MagickTrue : MagickFalse;
offset=repeat/length;
}
else
{
repeat=fmod(offset,gradient->radius);
if (repeat < 0.0)
repeat=gradient->radius-fmod(-repeat,gradient->radius);
else
repeat=fmod(offset,gradient->radius);
antialias=repeat+1.0 > gradient->radius ? MagickTrue :
MagickFalse;
offset=repeat/gradient->radius;
}
}
for (i=0; i < (ssize_t) gradient->number_stops; i++)
if (offset < gradient->stops[i].offset)
break;
if (i == 0)
composite=gradient->stops[0].color;
else
if (i == (ssize_t) gradient->number_stops)
composite=gradient->stops[gradient->number_stops-1].color;
else
{
j=i;
i--;
alpha=(offset-gradient->stops[i].offset)/
(gradient->stops[j].offset-gradient->stops[i].offset);
if (antialias != MagickFalse)
{
if (gradient->type == LinearGradient)
alpha=length-repeat;
else
alpha=gradient->radius-repeat;
i=0;
j=(ssize_t) gradient->number_stops-1L;
}
CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,
&gradient->stops[j].color,alpha,&composite);
}
break;
}
}
CompositePixelInfoOver(&composite,composite.alpha,&pixel,pixel.alpha,
&pixel);
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w P a t t e r n P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawPatternPath() draws a pattern.
%
% The format of the DrawPatternPath method is:
%
% MagickBooleanType DrawPatternPath(Image *image,const DrawInfo *draw_info,
% const char *name,Image **pattern,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o name: the pattern name.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType DrawPatternPath(Image *image,
const DrawInfo *draw_info,const char *name,Image **pattern,
ExceptionInfo *exception)
{
char
property[MagickPathExtent];
const char
*geometry,
*path,
*type;
DrawInfo
*clone_info;
ImageInfo
*image_info;
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (const DrawInfo *) NULL);
assert(name != (const char *) NULL);
(void) FormatLocaleString(property,MagickPathExtent,"%s",name);
path=GetImageArtifact(image,property);
if (path == (const char *) NULL)
return(MagickFalse);
(void) FormatLocaleString(property,MagickPathExtent,"%s-geometry",name);
geometry=GetImageArtifact(image,property);
if (geometry == (const char *) NULL)
return(MagickFalse);
if ((*pattern) != (Image *) NULL)
*pattern=DestroyImage(*pattern);
image_info=AcquireImageInfo();
image_info->size=AcquireString(geometry);
*pattern=AcquireImage(image_info,exception);
image_info=DestroyImageInfo(image_info);
(void) QueryColorCompliance("#000000ff",AllCompliance,
&(*pattern)->background_color,exception);
(void) SetImageBackgroundColor(*pattern,exception);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"begin pattern-path %s %s",name,geometry);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->fill_pattern=NewImageList();
clone_info->stroke_pattern=NewImageList();
(void) FormatLocaleString(property,MagickPathExtent,"%s-type",name);
type=GetImageArtifact(image,property);
if (type != (const char *) NULL)
clone_info->gradient.type=(GradientType) ParseCommandOption(
MagickGradientOptions,MagickFalse,type);
(void) CloneString(&clone_info->primitive,path);
status=DrawImage(*pattern,clone_info,exception);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"end pattern-path");
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w P o l y g o n P r i m i t i v e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawPolygonPrimitive() draws a polygon on the image.
%
% The format of the DrawPolygonPrimitive method is:
%
% MagickBooleanType DrawPolygonPrimitive(Image *image,
% const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static PolygonInfo **DestroyPolygonThreadSet(PolygonInfo **polygon_info)
{
register ssize_t
i;
assert(polygon_info != (PolygonInfo **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (polygon_info[i] != (PolygonInfo *) NULL)
polygon_info[i]=DestroyPolygonInfo(polygon_info[i]);
polygon_info=(PolygonInfo **) RelinquishMagickMemory(polygon_info);
return(polygon_info);
}
static PolygonInfo **AcquirePolygonThreadSet(
const PrimitiveInfo *primitive_info)
{
PathInfo
*magick_restrict path_info;
PolygonInfo
**polygon_info;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
polygon_info=(PolygonInfo **) AcquireQuantumMemory(number_threads,
sizeof(*polygon_info));
if (polygon_info == (PolygonInfo **) NULL)
return((PolygonInfo **) NULL);
(void) ResetMagickMemory(polygon_info,0,number_threads*sizeof(*polygon_info));
path_info=ConvertPrimitiveToPath(primitive_info);
if (path_info == (PathInfo *) NULL)
return(DestroyPolygonThreadSet(polygon_info));
for (i=0; i < (ssize_t) number_threads; i++)
{
polygon_info[i]=ConvertPathToPolygon(path_info);
if (polygon_info[i] == (PolygonInfo *) NULL)
return(DestroyPolygonThreadSet(polygon_info));
}
path_info=(PathInfo *) RelinquishMagickMemory(path_info);
return(polygon_info);
}
static double GetFillAlpha(PolygonInfo *polygon_info,const double mid,
const MagickBooleanType fill,const FillRule fill_rule,const ssize_t x,
const ssize_t y,double *stroke_alpha)
{
double
alpha,
beta,
distance,
subpath_alpha;
PointInfo
delta;
register const PointInfo
*q;
register EdgeInfo
*p;
register ssize_t
i;
ssize_t
j,
winding_number;
/*
Compute fill & stroke opacity for this (x,y) point.
*/
*stroke_alpha=0.0;
subpath_alpha=0.0;
p=polygon_info->edges;
for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++)
{
if ((double) y <= (p->bounds.y1-mid-0.5))
break;
if ((double) y > (p->bounds.y2+mid+0.5))
{
(void) DestroyEdge(polygon_info,(size_t) j);
continue;
}
if (((double) x <= (p->bounds.x1-mid-0.5)) ||
((double) x > (p->bounds.x2+mid+0.5)))
continue;
i=(ssize_t) MagickMax((double) p->highwater,1.0);
for ( ; i < (ssize_t) p->number_points; i++)
{
if ((double) y <= (p->points[i-1].y-mid-0.5))
break;
if ((double) y > (p->points[i].y+mid+0.5))
continue;
if (p->scanline != (double) y)
{
p->scanline=(double) y;
p->highwater=(size_t) i;
}
/*
Compute distance between a point and an edge.
*/
q=p->points+i-1;
delta.x=(q+1)->x-q->x;
delta.y=(q+1)->y-q->y;
beta=delta.x*(x-q->x)+delta.y*(y-q->y);
if (beta < 0.0)
{
delta.x=(double) x-q->x;
delta.y=(double) y-q->y;
distance=delta.x*delta.x+delta.y*delta.y;
}
else
{
alpha=delta.x*delta.x+delta.y*delta.y;
if (beta > alpha)
{
delta.x=(double) x-(q+1)->x;
delta.y=(double) y-(q+1)->y;
distance=delta.x*delta.x+delta.y*delta.y;
}
else
{
alpha=1.0/alpha;
beta=delta.x*(y-q->y)-delta.y*(x-q->x);
distance=alpha*beta*beta;
}
}
/*
Compute stroke & subpath opacity.
*/
beta=0.0;
if (p->ghostline == MagickFalse)
{
alpha=mid+0.5;
if ((*stroke_alpha < 1.0) &&
(distance <= ((alpha+0.25)*(alpha+0.25))))
{
alpha=mid-0.5;
if (distance <= ((alpha+0.25)*(alpha+0.25)))
*stroke_alpha=1.0;
else
{
beta=1.0;
if (distance != 1.0)
beta=sqrt((double) distance);
alpha=beta-mid-0.5;
if (*stroke_alpha < ((alpha-0.25)*(alpha-0.25)))
*stroke_alpha=(alpha-0.25)*(alpha-0.25);
}
}
}
if ((fill == MagickFalse) || (distance > 1.0) || (subpath_alpha >= 1.0))
continue;
if (distance <= 0.0)
{
subpath_alpha=1.0;
continue;
}
if (distance > 1.0)
continue;
if (beta == 0.0)
{
beta=1.0;
if (distance != 1.0)
beta=sqrt(distance);
}
alpha=beta-1.0;
if (subpath_alpha < (alpha*alpha))
subpath_alpha=alpha*alpha;
}
}
/*
Compute fill opacity.
*/
if (fill == MagickFalse)
return(0.0);
if (subpath_alpha >= 1.0)
return(1.0);
/*
Determine winding number.
*/
winding_number=0;
p=polygon_info->edges;
for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++)
{
if ((double) y <= p->bounds.y1)
break;
if (((double) y > p->bounds.y2) || ((double) x <= p->bounds.x1))
continue;
if ((double) x > p->bounds.x2)
{
winding_number+=p->direction ? 1 : -1;
continue;
}
i=(ssize_t) MagickMax((double) p->highwater,1.0);
for ( ; i < (ssize_t) p->number_points; i++)
if ((double) y <= p->points[i].y)
break;
q=p->points+i-1;
if ((((q+1)->x-q->x)*(y-q->y)) <= (((q+1)->y-q->y)*(x-q->x)))
winding_number+=p->direction ? 1 : -1;
}
if (fill_rule != NonZeroRule)
{
if ((MagickAbsoluteValue(winding_number) & 0x01) != 0)
return(1.0);
}
else
if (MagickAbsoluteValue(winding_number) != 0)
return(1.0);
return(subpath_alpha);
}
static MagickBooleanType DrawPolygonPrimitive(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
fill,
status;
double
mid;
PolygonInfo
**magick_restrict polygon_info;
register EdgeInfo
*p;
register ssize_t
i;
SegmentInfo
bounds;
ssize_t
start_y,
stop_y,
y;
/*
Compute bounding box.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
assert(primitive_info != (PrimitiveInfo *) NULL);
if (primitive_info->coordinates == 0)
return(MagickTrue);
polygon_info=AcquirePolygonThreadSet(primitive_info);
if (polygon_info == (PolygonInfo **) NULL)
return(MagickFalse);
DisableMSCWarning(4127)
if (0)
DrawBoundingRectangles(image,draw_info,polygon_info[0],exception);
RestoreMSCWarning
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-polygon");
fill=(primitive_info->method == FillToBorderMethod) ||
(primitive_info->method == FloodfillMethod) ? MagickTrue : MagickFalse;
mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
bounds=polygon_info[0]->edges[0].bounds;
for (i=1; i < (ssize_t) polygon_info[0]->number_edges; i++)
{
p=polygon_info[0]->edges+i;
if (p->bounds.x1 < bounds.x1)
bounds.x1=p->bounds.x1;
if (p->bounds.y1 < bounds.y1)
bounds.y1=p->bounds.y1;
if (p->bounds.x2 > bounds.x2)
bounds.x2=p->bounds.x2;
if (p->bounds.y2 > bounds.y2)
bounds.y2=p->bounds.y2;
}
bounds.x1-=(mid+1.0);
bounds.x1=bounds.x1 < 0.0 ? 0.0 : (size_t) ceil(bounds.x1-0.5) >=
image->columns ? (double) image->columns-1 : bounds.x1;
bounds.y1-=(mid+1.0);
bounds.y1=bounds.y1 < 0.0 ? 0.0 : (size_t) ceil(bounds.y1-0.5) >=
image->rows ? (double) image->rows-1 : bounds.y1;
bounds.x2+=(mid+1.0);
bounds.x2=bounds.x2 < 0.0 ? 0.0 : (size_t) floor(bounds.x2+0.5) >=
image->columns ? (double) image->columns-1 : bounds.x2;
bounds.y2+=(mid+1.0);
bounds.y2=bounds.y2 < 0.0 ? 0.0 : (size_t) floor(bounds.y2+0.5) >=
image->rows ? (double) image->rows-1 : bounds.y2;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
if ((primitive_info->coordinates == 1) ||
(polygon_info[0]->number_edges == 0))
{
/*
Draw point.
*/
start_y=(ssize_t) ceil(bounds.y1-0.5);
stop_y=(ssize_t) floor(bounds.y2+0.5);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,1,1)
#endif
for (y=start_y; y <= stop_y; y++)
{
MagickBooleanType
sync;
PixelInfo
pixel;
register ssize_t
x;
register Quantum
*magick_restrict q;
ssize_t
start_x,
stop_x;
if (status == MagickFalse)
continue;
start_x=(ssize_t) ceil(bounds.x1-0.5);
stop_x=(ssize_t) floor(bounds.x2+0.5);
x=start_x;
q=GetCacheViewAuthenticPixels(image_view,x,y,(size_t) (stop_x-x+1),1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
GetPixelInfo(image,&pixel);
for ( ; x <= stop_x; x++)
{
if ((x == (ssize_t) ceil(primitive_info->point.x-0.5)) &&
(y == (ssize_t) ceil(primitive_info->point.y-0.5)))
{
GetFillColor(draw_info,x-start_x,y-start_y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
}
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
polygon_info=DestroyPolygonThreadSet(polygon_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" end draw-polygon");
return(status);
}
/*
Draw polygon or line.
*/
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
start_y=(ssize_t) ceil(bounds.y1-0.5);
stop_y=(ssize_t) floor(bounds.y2+0.5);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,1,1)
#endif
for (y=start_y; y <= stop_y; y++)
{
const int
id = GetOpenMPThreadId();
double
fill_alpha,
stroke_alpha;
PixelInfo
fill_color,
stroke_color;
register Quantum
*magick_restrict q;
register ssize_t
x;
ssize_t
start_x,
stop_x;
if (status == MagickFalse)
continue;
start_x=(ssize_t) ceil(bounds.x1-0.5);
stop_x=(ssize_t) floor(bounds.x2+0.5);
q=GetCacheViewAuthenticPixels(image_view,start_x,y,(size_t) (stop_x-start_x+1),1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=start_x; x <= stop_x; x++)
{
/*
Fill and/or stroke.
*/
fill_alpha=GetFillAlpha(polygon_info[id],mid,fill,draw_info->fill_rule,
x,y,&stroke_alpha);
if (draw_info->stroke_antialias == MagickFalse)
{
fill_alpha=fill_alpha > 0.25 ? 1.0 : 0.0;
stroke_alpha=stroke_alpha > 0.25 ? 1.0 : 0.0;
}
GetFillColor(draw_info,x-start_x,y-start_y,&fill_color,exception);
fill_alpha=fill_alpha*fill_color.alpha;
CompositePixelOver(image,&fill_color,fill_alpha,q,(double)
GetPixelAlpha(image,q),q);
GetStrokeColor(draw_info,x-start_x,y-start_y,&stroke_color,exception);
stroke_alpha=stroke_alpha*stroke_color.alpha;
CompositePixelOver(image,&stroke_color,stroke_alpha,q,(double)
GetPixelAlpha(image,q),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
polygon_info=DestroyPolygonThreadSet(polygon_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-polygon");
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w P r i m i t i v e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawPrimitive() draws a primitive (line, rectangle, ellipse) on the image.
%
% The format of the DrawPrimitive method is:
%
% MagickBooleanType DrawPrimitive(Image *image,const DrawInfo *draw_info,
% PrimitiveInfo *primitive_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static void LogPrimitiveInfo(const PrimitiveInfo *primitive_info)
{
const char
*methods[] =
{
"point",
"replace",
"floodfill",
"filltoborder",
"reset",
"?"
};
PointInfo
p,
q,
point;
register ssize_t
i,
x;
ssize_t
coordinates,
y;
x=(ssize_t) ceil(primitive_info->point.x-0.5);
y=(ssize_t) ceil(primitive_info->point.y-0.5);
switch (primitive_info->primitive)
{
case AlphaPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"AlphaPrimitive %.20g,%.20g %s",(double) x,(double) y,
methods[primitive_info->method]);
return;
}
case ColorPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"ColorPrimitive %.20g,%.20g %s",(double) x,(double) y,
methods[primitive_info->method]);
return;
}
case ImagePrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"ImagePrimitive %.20g,%.20g",(double) x,(double) y);
return;
}
case PointPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"PointPrimitive %.20g,%.20g %s",(double) x,(double) y,
methods[primitive_info->method]);
return;
}
case TextPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"TextPrimitive %.20g,%.20g",(double) x,(double) y);
return;
}
default:
break;
}
coordinates=0;
p=primitive_info[0].point;
q.x=(-1.0);
q.y=(-1.0);
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
{
point=primitive_info[i].point;
if (coordinates <= 0)
{
coordinates=(ssize_t) primitive_info[i].coordinates;
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin open (%.20g)",(double) coordinates);
p=point;
}
point=primitive_info[i].point;
if ((fabs(q.x-point.x) >= MagickEpsilon) ||
(fabs(q.y-point.y) >= MagickEpsilon))
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" %.20g: %.18g,%.18g",(double) coordinates,point.x,point.y);
else
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" %.20g: %g %g (duplicate)",(double) coordinates,point.x,point.y);
q=point;
coordinates--;
if (coordinates > 0)
continue;
if ((fabs(p.x-point.x) >= MagickEpsilon) ||
(fabs(p.y-point.y) >= MagickEpsilon))
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end last (%.20g)",
(double) coordinates);
else
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end open (%.20g)",
(double) coordinates);
}
}
MagickExport MagickBooleanType DrawPrimitive(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickStatusType
status;
register ssize_t
i,
x;
ssize_t
y;
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin draw-primitive");
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" affine: %g %g %g %g %g %g",draw_info->affine.sx,
draw_info->affine.rx,draw_info->affine.ry,draw_info->affine.sy,
draw_info->affine.tx,draw_info->affine.ty);
}
if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
((IsPixelInfoGray(&draw_info->fill) == MagickFalse) ||
(IsPixelInfoGray(&draw_info->stroke) == MagickFalse)))
(void) SetImageColorspace(image,sRGBColorspace,exception);
status=MagickTrue;
x=(ssize_t) ceil(primitive_info->point.x-0.5);
y=(ssize_t) ceil(primitive_info->point.y-0.5);
image_view=AcquireAuthenticCacheView(image,exception);
switch (primitive_info->primitive)
{
case AlphaPrimitive:
{
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
switch (primitive_info->method)
{
case PointMethod:
default:
{
PixelInfo
pixel;
register Quantum
*q;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (Quantum *) NULL)
break;
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case ReplaceMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel,
target;
(void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,
exception);
GetPixelInfo(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,q,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)
{
q+=GetPixelChannels(image);
continue;
}
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
case FloodfillMethod:
case FillToBorderMethod:
{
ChannelType
channel_mask;
PixelInfo
target;
(void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,
&target,exception);
if (primitive_info->method == FillToBorderMethod)
{
target.red=(double) draw_info->border_color.red;
target.green=(double) draw_info->border_color.green;
target.blue=(double) draw_info->border_color.blue;
}
channel_mask=SetImageChannelMask(image,AlphaChannel);
status&=FloodfillPaintImage(image,draw_info,&target,x,y,
primitive_info->method == FloodfillMethod ? MagickFalse :
MagickTrue,exception);
(void) SetImageChannelMask(image,channel_mask);
break;
}
case ResetMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel;
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
}
break;
}
case ColorPrimitive:
{
switch (primitive_info->method)
{
case PointMethod:
default:
{
PixelInfo
pixel;
register Quantum
*q;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (Quantum *) NULL)
break;
GetPixelInfo(image,&pixel);
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case ReplaceMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel,
target;
(void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,
exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,q,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)
{
q+=GetPixelChannels(image);
continue;
}
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
case FloodfillMethod:
case FillToBorderMethod:
{
PixelInfo
target;
(void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,
&target,exception);
if (primitive_info->method == FillToBorderMethod)
{
target.red=(double) draw_info->border_color.red;
target.green=(double) draw_info->border_color.green;
target.blue=(double) draw_info->border_color.blue;
}
status&=FloodfillPaintImage(image,draw_info,&target,x,y,
primitive_info->method == FloodfillMethod ? MagickFalse :
MagickTrue,exception);
break;
}
case ResetMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel;
GetPixelInfo(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
}
break;
}
case ImagePrimitive:
{
AffineMatrix
affine;
char
composite_geometry[MagickPathExtent];
Image
*composite_image;
ImageInfo
*clone_info;
RectangleInfo
geometry;
ssize_t
x1,
y1;
if (primitive_info->text == (char *) NULL)
break;
clone_info=AcquireImageInfo();
if (LocaleNCompare(primitive_info->text,"data:",5) == 0)
composite_image=ReadInlineImage(clone_info,primitive_info->text,
exception);
else
{
(void) CopyMagickString(clone_info->filename,primitive_info->text,
MagickPathExtent);
composite_image=ReadImage(clone_info,exception);
}
clone_info=DestroyImageInfo(clone_info);
if (composite_image == (Image *) NULL)
break;
(void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor)
NULL,(void *) NULL);
x1=(ssize_t) ceil(primitive_info[1].point.x-0.5);
y1=(ssize_t) ceil(primitive_info[1].point.y-0.5);
if (((x1 != 0L) && (x1 != (ssize_t) composite_image->columns)) ||
((y1 != 0L) && (y1 != (ssize_t) composite_image->rows)))
{
/*
Resize image.
*/
(void) FormatLocaleString(composite_geometry,MagickPathExtent,
"%gx%g!",primitive_info[1].point.x,primitive_info[1].point.y);
composite_image->filter=image->filter;
(void) TransformImage(&composite_image,(char *) NULL,
composite_geometry,exception);
}
if (composite_image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel,
exception);
if (draw_info->alpha != OpaqueAlpha)
(void) SetImageAlpha(composite_image,draw_info->alpha,exception);
SetGeometry(image,&geometry);
image->gravity=draw_info->gravity;
geometry.x=x;
geometry.y=y;
(void) FormatLocaleString(composite_geometry,MagickPathExtent,
"%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns,(double)
composite_image->rows,(double) geometry.x,(double) geometry.y);
(void) ParseGravityGeometry(image,composite_geometry,&geometry,exception);
affine=draw_info->affine;
affine.tx=(double) geometry.x;
affine.ty=(double) geometry.y;
composite_image->interpolate=image->interpolate;
if (draw_info->compose == OverCompositeOp)
(void) DrawAffineImage(image,composite_image,&affine,exception);
else
(void) CompositeImage(image,composite_image,draw_info->compose,
MagickTrue,geometry.x,geometry.y,exception);
composite_image=DestroyImage(composite_image);
break;
}
case PointPrimitive:
{
PixelInfo
fill_color;
register Quantum
*q;
if ((y < 0) || (y >= (ssize_t) image->rows))
break;
if ((x < 0) || (x >= (ssize_t) image->columns))
break;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (Quantum *) NULL)
break;
GetFillColor(draw_info,x,y,&fill_color,exception);
CompositePixelOver(image,&fill_color,(double) fill_color.alpha,q,
(double) GetPixelAlpha(image,q),q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case TextPrimitive:
{
char
geometry[MagickPathExtent];
DrawInfo
*clone_info;
if (primitive_info->text == (char *) NULL)
break;
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) CloneString(&clone_info->text,primitive_info->text);
(void) FormatLocaleString(geometry,MagickPathExtent,"%+f%+f",
primitive_info->point.x,primitive_info->point.y);
(void) CloneString(&clone_info->geometry,geometry);
status&=AnnotateImage(image,clone_info,exception);
clone_info=DestroyDrawInfo(clone_info);
break;
}
default:
{
double
mid,
scale;
DrawInfo
*clone_info;
if (IsEventLogging() != MagickFalse)
LogPrimitiveInfo(primitive_info);
scale=ExpandAffine(&draw_info->affine);
if ((draw_info->dash_pattern != (double *) NULL) &&
(draw_info->dash_pattern[0] != 0.0) &&
((scale*draw_info->stroke_width) >= MagickEpsilon) &&
(draw_info->stroke.alpha != (Quantum) TransparentAlpha))
{
/*
Draw dash polygon.
*/
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->stroke_width=0.0;
clone_info->stroke.alpha=(MagickRealType) TransparentAlpha;
status&=DrawPolygonPrimitive(image,clone_info,primitive_info,
exception);
clone_info=DestroyDrawInfo(clone_info);
(void) DrawDashPolygon(draw_info,primitive_info,image,exception);
break;
}
mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
if ((mid > 1.0) &&
((draw_info->stroke.alpha != (Quantum) TransparentAlpha) ||
(draw_info->stroke_pattern != (Image *) NULL)))
{
MagickBooleanType
closed_path;
/*
Draw strokes while respecting line cap/join attributes.
*/
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
closed_path=
(primitive_info[i-1].point.x == primitive_info[0].point.x) &&
(primitive_info[i-1].point.y == primitive_info[0].point.y) ?
MagickTrue : MagickFalse;
i=(ssize_t) primitive_info[0].coordinates;
if ((((draw_info->linecap == RoundCap) ||
(closed_path != MagickFalse)) &&
(draw_info->linejoin == RoundJoin)) ||
(primitive_info[i].primitive != UndefinedPrimitive))
{
(void) DrawPolygonPrimitive(image,draw_info,primitive_info,
exception);
break;
}
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->stroke_width=0.0;
clone_info->stroke.alpha=(MagickRealType) TransparentAlpha;
status&=DrawPolygonPrimitive(image,clone_info,primitive_info,
exception);
clone_info=DestroyDrawInfo(clone_info);
status&=DrawStrokePolygon(image,draw_info,primitive_info,exception);
break;
}
status&=DrawPolygonPrimitive(image,draw_info,primitive_info,exception);
break;
}
}
image_view=DestroyCacheView(image_view);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-primitive");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w S t r o k e P o l y g o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawStrokePolygon() draws a stroked polygon (line, rectangle, ellipse) on
% the image while respecting the line cap and join attributes.
%
% The format of the DrawStrokePolygon method is:
%
% MagickBooleanType DrawStrokePolygon(Image *image,
% const DrawInfo *draw_info,const PrimitiveInfo *primitive_info)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
%
*/
static void DrawRoundLinecap(Image *image,const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info,ExceptionInfo *exception)
{
PrimitiveInfo
linecap[5];
register ssize_t
i;
for (i=0; i < 4; i++)
linecap[i]=(*primitive_info);
linecap[0].coordinates=4;
linecap[1].point.x+=(double) (10.0*MagickEpsilon);
linecap[2].point.x+=(double) (10.0*MagickEpsilon);
linecap[2].point.y+=(double) (10.0*MagickEpsilon);
linecap[3].point.y+=(double) (10.0*MagickEpsilon);
linecap[4].primitive=UndefinedPrimitive;
(void) DrawPolygonPrimitive(image,draw_info,linecap,exception);
}
static MagickBooleanType DrawStrokePolygon(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
ExceptionInfo *exception)
{
DrawInfo
*clone_info;
MagickBooleanType
closed_path;
MagickStatusType
status;
PrimitiveInfo
*stroke_polygon;
register const PrimitiveInfo
*p,
*q;
/*
Draw stroked polygon.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin draw-stroke-polygon");
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->fill=draw_info->stroke;
if (clone_info->fill_pattern != (Image *) NULL)
clone_info->fill_pattern=DestroyImage(clone_info->fill_pattern);
if (clone_info->stroke_pattern != (Image *) NULL)
clone_info->fill_pattern=CloneImage(clone_info->stroke_pattern,0,0,
MagickTrue,exception);
clone_info->stroke.alpha=(MagickRealType) TransparentAlpha;
clone_info->stroke_width=0.0;
clone_info->fill_rule=NonZeroRule;
status=MagickTrue;
for (p=primitive_info; p->primitive != UndefinedPrimitive; p+=p->coordinates)
{
stroke_polygon=TraceStrokePolygon(draw_info,p);
status&=DrawPolygonPrimitive(image,clone_info,stroke_polygon,exception);
if (status == 0)
break;
stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon);
q=p+p->coordinates-1;
closed_path=(q->point.x == p->point.x) && (q->point.y == p->point.y) ?
MagickTrue : MagickFalse;
if ((draw_info->linecap == RoundCap) && (closed_path == MagickFalse))
{
DrawRoundLinecap(image,draw_info,p,exception);
DrawRoundLinecap(image,draw_info,q,exception);
}
}
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" end draw-stroke-polygon");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t A f f i n e M a t r i x %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAffineMatrix() returns an AffineMatrix initialized to the identity
% matrix.
%
% The format of the GetAffineMatrix method is:
%
% void GetAffineMatrix(AffineMatrix *affine_matrix)
%
% A description of each parameter follows:
%
% o affine_matrix: the affine matrix.
%
*/
MagickExport void GetAffineMatrix(AffineMatrix *affine_matrix)
{
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(affine_matrix != (AffineMatrix *) NULL);
(void) ResetMagickMemory(affine_matrix,0,sizeof(*affine_matrix));
affine_matrix->sx=1.0;
affine_matrix->sy=1.0;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetDrawInfo() initializes draw_info to default values from image_info.
%
% The format of the GetDrawInfo method is:
%
% void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o image_info: the image info..
%
% o draw_info: the draw info.
%
*/
MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)
{
const char
*option;
ExceptionInfo
*exception;
ImageInfo
*clone_info;
/*
Initialize draw attributes.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(draw_info != (DrawInfo *) NULL);
(void) ResetMagickMemory(draw_info,0,sizeof(*draw_info));
clone_info=CloneImageInfo(image_info);
GetAffineMatrix(&draw_info->affine);
exception=AcquireExceptionInfo();
(void) QueryColorCompliance("#000F",AllCompliance,&draw_info->fill,
exception);
(void) QueryColorCompliance("#0000",AllCompliance,&draw_info->stroke,
exception);
draw_info->stroke_width=1.0;
draw_info->alpha=OpaqueAlpha;
draw_info->fill_rule=EvenOddRule;
draw_info->linecap=ButtCap;
draw_info->linejoin=MiterJoin;
draw_info->miterlimit=10;
draw_info->decorate=NoDecoration;
draw_info->pointsize=12.0;
draw_info->undercolor.alpha=(MagickRealType) TransparentAlpha;
draw_info->compose=OverCompositeOp;
draw_info->render=MagickTrue;
draw_info->debug=IsEventLogging();
draw_info->stroke_antialias=clone_info->antialias;
if (clone_info->font != (char *) NULL)
draw_info->font=AcquireString(clone_info->font);
if (clone_info->density != (char *) NULL)
draw_info->density=AcquireString(clone_info->density);
draw_info->text_antialias=clone_info->antialias;
if (clone_info->pointsize != 0.0)
draw_info->pointsize=clone_info->pointsize;
draw_info->border_color=clone_info->border_color;
if (clone_info->server_name != (char *) NULL)
draw_info->server_name=AcquireString(clone_info->server_name);
option=GetImageOption(clone_info,"direction");
if (option != (const char *) NULL)
draw_info->direction=(DirectionType) ParseCommandOption(
MagickDirectionOptions,MagickFalse,option);
else
draw_info->direction=UndefinedDirection;
option=GetImageOption(clone_info,"encoding");
if (option != (const char *) NULL)
(void) CloneString(&draw_info->encoding,option);
option=GetImageOption(clone_info,"family");
if (option != (const char *) NULL)
(void) CloneString(&draw_info->family,option);
option=GetImageOption(clone_info,"fill");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&draw_info->fill,
exception);
option=GetImageOption(clone_info,"gravity");
if (option != (const char *) NULL)
draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions,
MagickFalse,option);
option=GetImageOption(clone_info,"interline-spacing");
if (option != (const char *) NULL)
draw_info->interline_spacing=StringToDouble(option,(char **) NULL);
option=GetImageOption(clone_info,"interword-spacing");
if (option != (const char *) NULL)
draw_info->interword_spacing=StringToDouble(option,(char **) NULL);
option=GetImageOption(clone_info,"kerning");
if (option != (const char *) NULL)
draw_info->kerning=StringToDouble(option,(char **) NULL);
option=GetImageOption(clone_info,"stroke");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&draw_info->stroke,
exception);
option=GetImageOption(clone_info,"strokewidth");
if (option != (const char *) NULL)
draw_info->stroke_width=StringToDouble(option,(char **) NULL);
option=GetImageOption(clone_info,"style");
if (option != (const char *) NULL)
draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions,
MagickFalse,option);
option=GetImageOption(clone_info,"undercolor");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&draw_info->undercolor,
exception);
option=GetImageOption(clone_info,"weight");
if (option != (const char *) NULL)
{
ssize_t
weight;
weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option);
if (weight == -1)
weight=(ssize_t) StringToUnsignedLong(option);
draw_info->weight=(size_t) weight;
}
exception=DestroyExceptionInfo(exception);
draw_info->signature=MagickCoreSignature;
clone_info=DestroyImageInfo(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ P e r m u t a t e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Permutate() returns the permuation of the (n,k).
%
% The format of the Permutate method is:
%
% void Permutate(ssize_t n,ssize_t k)
%
% A description of each parameter follows:
%
% o n:
%
% o k:
%
%
*/
static inline double Permutate(const ssize_t n,const ssize_t k)
{
double
r;
register ssize_t
i;
r=1.0;
for (i=k+1; i <= n; i++)
r*=i;
for (i=1; i <= (n-k); i++)
r/=i;
return(r);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ T r a c e P r i m i t i v e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TracePrimitive is a collection of methods for generating graphic
% primitives such as arcs, ellipses, paths, etc.
%
*/
static void TraceArc(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end,const PointInfo degrees)
{
PointInfo
center,
radii;
center.x=0.5*(end.x+start.x);
center.y=0.5*(end.y+start.y);
radii.x=fabs(center.x-start.x);
radii.y=fabs(center.y-start.y);
TraceEllipse(primitive_info,center,radii,degrees);
}
static void TraceArcPath(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end,const PointInfo arc,const double angle,
const MagickBooleanType large_arc,const MagickBooleanType sweep)
{
double
alpha,
beta,
delta,
factor,
gamma,
theta;
PointInfo
center,
points[3],
radii;
register double
cosine,
sine;
register PrimitiveInfo
*p;
register ssize_t
i;
size_t
arc_segments;
if ((start.x == end.x) && (start.y == end.y))
{
TracePoint(primitive_info,end);
return;
}
radii.x=fabs(arc.x);
radii.y=fabs(arc.y);
if ((radii.x == 0.0) || (radii.y == 0.0))
{
TraceLine(primitive_info,start,end);
return;
}
cosine=cos(DegreesToRadians(fmod((double) angle,360.0)));
sine=sin(DegreesToRadians(fmod((double) angle,360.0)));
center.x=(double) (cosine*(end.x-start.x)/2+sine*(end.y-start.y)/2);
center.y=(double) (cosine*(end.y-start.y)/2-sine*(end.x-start.x)/2);
delta=(center.x*center.x)/(radii.x*radii.x)+(center.y*center.y)/
(radii.y*radii.y);
if (delta < MagickEpsilon)
{
TraceLine(primitive_info,start,end);
return;
}
if (delta > 1.0)
{
radii.x*=sqrt((double) delta);
radii.y*=sqrt((double) delta);
}
points[0].x=(double) (cosine*start.x/radii.x+sine*start.y/radii.x);
points[0].y=(double) (cosine*start.y/radii.y-sine*start.x/radii.y);
points[1].x=(double) (cosine*end.x/radii.x+sine*end.y/radii.x);
points[1].y=(double) (cosine*end.y/radii.y-sine*end.x/radii.y);
alpha=points[1].x-points[0].x;
beta=points[1].y-points[0].y;
factor=PerceptibleReciprocal(alpha*alpha+beta*beta)-0.25;
if (factor <= 0.0)
factor=0.0;
else
{
factor=sqrt((double) factor);
if (sweep == large_arc)
factor=(-factor);
}
center.x=(double) ((points[0].x+points[1].x)/2-factor*beta);
center.y=(double) ((points[0].y+points[1].y)/2+factor*alpha);
alpha=atan2(points[0].y-center.y,points[0].x-center.x);
theta=atan2(points[1].y-center.y,points[1].x-center.x)-alpha;
if ((theta < 0.0) && (sweep != MagickFalse))
theta+=(double) (2.0*MagickPI);
else
if ((theta > 0.0) && (sweep == MagickFalse))
theta-=(double) (2.0*MagickPI);
arc_segments=(size_t) ceil(fabs((double) (theta/(0.5*MagickPI+
MagickEpsilon))));
p=primitive_info;
for (i=0; i < (ssize_t) arc_segments; i++)
{
beta=0.5*((alpha+(i+1)*theta/arc_segments)-(alpha+i*theta/arc_segments));
gamma=(8.0/3.0)*sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))*
sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))/
sin(fmod((double) beta,DegreesToRadians(360.0)));
points[0].x=(double) (center.x+cos(fmod((double) (alpha+(double) i*theta/
arc_segments),DegreesToRadians(360.0)))-gamma*sin(fmod((double) (alpha+
(double) i*theta/arc_segments),DegreesToRadians(360.0))));
points[0].y=(double) (center.y+sin(fmod((double) (alpha+(double) i*theta/
arc_segments),DegreesToRadians(360.0)))+gamma*cos(fmod((double) (alpha+
(double) i*theta/arc_segments),DegreesToRadians(360.0))));
points[2].x=(double) (center.x+cos(fmod((double) (alpha+(double) (i+1)*
theta/arc_segments),DegreesToRadians(360.0))));
points[2].y=(double) (center.y+sin(fmod((double) (alpha+(double) (i+1)*
theta/arc_segments),DegreesToRadians(360.0))));
points[1].x=(double) (points[2].x+gamma*sin(fmod((double) (alpha+(double)
(i+1)*theta/arc_segments),DegreesToRadians(360.0))));
points[1].y=(double) (points[2].y-gamma*cos(fmod((double) (alpha+(double)
(i+1)*theta/arc_segments),DegreesToRadians(360.0))));
p->point.x=(p == primitive_info) ? start.x : (p-1)->point.x;
p->point.y=(p == primitive_info) ? start.y : (p-1)->point.y;
(p+1)->point.x=(double) (cosine*radii.x*points[0].x-sine*radii.y*
points[0].y);
(p+1)->point.y=(double) (sine*radii.x*points[0].x+cosine*radii.y*
points[0].y);
(p+2)->point.x=(double) (cosine*radii.x*points[1].x-sine*radii.y*
points[1].y);
(p+2)->point.y=(double) (sine*radii.x*points[1].x+cosine*radii.y*
points[1].y);
(p+3)->point.x=(double) (cosine*radii.x*points[2].x-sine*radii.y*
points[2].y);
(p+3)->point.y=(double) (sine*radii.x*points[2].x+cosine*radii.y*
points[2].y);
if (i == (ssize_t) (arc_segments-1))
(p+3)->point=end;
TraceBezier(p,4);
p+=p->coordinates;
}
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceBezier(PrimitiveInfo *primitive_info,
const size_t number_coordinates)
{
double
alpha,
*coefficients,
weight;
PointInfo
end,
point,
*points;
register PrimitiveInfo
*p;
register ssize_t
i,
j;
size_t
control_points,
quantum;
/*
Allocate coeficients.
*/
quantum=number_coordinates;
for (i=0; i < (ssize_t) number_coordinates; i++)
{
for (j=i+1; j < (ssize_t) number_coordinates; j++)
{
alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x);
if (alpha > (double) quantum)
quantum=(size_t) alpha;
alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y);
if (alpha > (double) quantum)
quantum=(size_t) alpha;
}
}
quantum=(size_t) MagickMin((double) quantum/number_coordinates,
(double) BezierQuantum);
control_points=quantum*number_coordinates;
coefficients=(double *) AcquireQuantumMemory((size_t)
number_coordinates,sizeof(*coefficients));
points=(PointInfo *) AcquireQuantumMemory((size_t) control_points,
sizeof(*points));
if ((coefficients == (double *) NULL) ||
(points == (PointInfo *) NULL))
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
/*
Compute bezier points.
*/
end=primitive_info[number_coordinates-1].point;
for (i=0; i < (ssize_t) number_coordinates; i++)
coefficients[i]=Permutate((ssize_t) number_coordinates-1,i);
weight=0.0;
for (i=0; i < (ssize_t) control_points; i++)
{
p=primitive_info;
point.x=0.0;
point.y=0.0;
alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0);
for (j=0; j < (ssize_t) number_coordinates; j++)
{
point.x+=alpha*coefficients[j]*p->point.x;
point.y+=alpha*coefficients[j]*p->point.y;
alpha*=weight/(1.0-weight);
p++;
}
points[i]=point;
weight+=1.0/control_points;
}
/*
Bezier curves are just short segmented polys.
*/
p=primitive_info;
for (i=0; i < (ssize_t) control_points; i++)
{
TracePoint(p,points[i]);
p+=p->coordinates;
}
TracePoint(p,end);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
points=(PointInfo *) RelinquishMagickMemory(points);
coefficients=(double *) RelinquishMagickMemory(coefficients);
}
static void TraceCircle(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end)
{
double
alpha,
beta,
radius;
PointInfo
offset,
degrees;
alpha=end.x-start.x;
beta=end.y-start.y;
radius=hypot((double) alpha,(double) beta);
offset.x=(double) radius;
offset.y=(double) radius;
degrees.x=0.0;
degrees.y=360.0;
TraceEllipse(primitive_info,start,offset,degrees);
}
static void TraceEllipse(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo stop,const PointInfo degrees)
{
double
delta,
step,
y;
PointInfo
angle,
point;
register PrimitiveInfo
*p;
register ssize_t
i;
/*
Ellipses are just short segmented polys.
*/
if ((stop.x == 0.0) && (stop.y == 0.0))
{
TracePoint(primitive_info,start);
return;
}
delta=2.0/MagickMax(stop.x,stop.y);
step=(double) (MagickPI/8.0);
if ((delta >= 0.0) && (delta < (double) (MagickPI/8.0)))
step=(double) (MagickPI/(4*(MagickPI/delta/2+0.5)));
angle.x=DegreesToRadians(degrees.x);
y=degrees.y;
while (y < degrees.x)
y+=360.0;
angle.y=(double) DegreesToRadians(y);
for (p=primitive_info; angle.x < angle.y; angle.x+=step)
{
point.x=cos(fmod(angle.x,DegreesToRadians(360.0)))*stop.x+start.x;
point.y=sin(fmod(angle.x,DegreesToRadians(360.0)))*stop.y+start.y;
TracePoint(p,point);
p+=p->coordinates;
}
point.x=cos(fmod(angle.y,DegreesToRadians(360.0)))*stop.x+start.x;
point.y=sin(fmod(angle.y,DegreesToRadians(360.0)))*stop.y+start.y;
TracePoint(p,point);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceLine(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end)
{
TracePoint(primitive_info,start);
if ((fabs(start.x-end.x) < MagickEpsilon) &&
(fabs(start.y-end.y) < MagickEpsilon))
{
primitive_info->primitive=PointPrimitive;
primitive_info->coordinates=1;
return;
}
TracePoint(primitive_info+1,end);
(primitive_info+1)->primitive=primitive_info->primitive;
primitive_info->coordinates=2;
}
static size_t TracePath(PrimitiveInfo *primitive_info,const char *path)
{
char
token[MagickPathExtent];
const char
*p;
int
attribute,
last_attribute;
double
x,
y;
PointInfo
end = {0.0, 0.0},
points[4] = { {0.0,0.0}, {0.0,0.0}, {0.0,0.0}, {0.0,0.0} },
point = {0.0, 0.0},
start = {0.0, 0.0};
PrimitiveType
primitive_type;
register PrimitiveInfo
*q;
register ssize_t
i;
size_t
number_coordinates,
z_count;
attribute=0;
number_coordinates=0;
z_count=0;
primitive_type=primitive_info->primitive;
q=primitive_info;
for (p=path; *p != '\0'; )
{
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == '\0')
break;
last_attribute=attribute;
attribute=(int) (*p++);
switch (attribute)
{
case 'a':
case 'A':
{
MagickBooleanType
large_arc,
sweep;
double
angle;
PointInfo
arc;
/*
Compute arc points.
*/
do
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
arc.x=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
arc.y=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
angle=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse;
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse;
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,(char **) NULL);
end.x=(double) (attribute == (int) 'A' ? x : point.x+x);
end.y=(double) (attribute == (int) 'A' ? y : point.y+y);
TraceArcPath(q,point,end,arc,angle,large_arc,sweep);
q+=q->coordinates;
point=end;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'c':
case 'C':
{
/*
Compute bezier points.
*/
do
{
points[0]=point;
for (i=1; i < 4; i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,(char **) NULL);
end.x=(double) (attribute == (int) 'C' ? x : point.x+x);
end.y=(double) (attribute == (int) 'C' ? y : point.y+y);
points[i]=end;
}
for (i=0; i < 4; i++)
(q+i)->point=points[i];
TraceBezier(q,4);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'H':
case 'h':
{
do
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,(char **) NULL);
point.x=(double) (attribute == (int) 'H' ? x: point.x+x);
TracePoint(q,point);
q+=q->coordinates;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'l':
case 'L':
{
do
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,(char **) NULL);
point.x=(double) (attribute == (int) 'L' ? x : point.x+x);
point.y=(double) (attribute == (int) 'L' ? y : point.y+y);
TracePoint(q,point);
q+=q->coordinates;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'M':
case 'm':
{
if (q != primitive_info)
{
primitive_info->coordinates=(size_t) (q-primitive_info);
number_coordinates+=primitive_info->coordinates;
primitive_info=q;
}
i=0;
do
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,(char **) NULL);
point.x=(double) (attribute == (int) 'M' ? x : point.x+x);
point.y=(double) (attribute == (int) 'M' ? y : point.y+y);
if (i == 0)
start=point;
i++;
TracePoint(q,point);
q+=q->coordinates;
if ((i != 0) && (attribute == (int) 'M'))
{
TracePoint(q,point);
q+=q->coordinates;
}
} while (IsPoint(p) != MagickFalse);
break;
}
case 'q':
case 'Q':
{
/*
Compute bezier points.
*/
do
{
points[0]=point;
for (i=1; i < 3; i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,(char **) NULL);
if (*p == ',')
p++;
end.x=(double) (attribute == (int) 'Q' ? x : point.x+x);
end.y=(double) (attribute == (int) 'Q' ? y : point.y+y);
points[i]=end;
}
for (i=0; i < 3; i++)
(q+i)->point=points[i];
TraceBezier(q,3);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 's':
case 'S':
{
/*
Compute bezier points.
*/
do
{
points[0]=points[3];
points[1].x=2.0*points[3].x-points[2].x;
points[1].y=2.0*points[3].y-points[2].y;
for (i=2; i < 4; i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,(char **) NULL);
if (*p == ',')
p++;
end.x=(double) (attribute == (int) 'S' ? x : point.x+x);
end.y=(double) (attribute == (int) 'S' ? y : point.y+y);
points[i]=end;
}
if (strchr("CcSs",last_attribute) == (char *) NULL)
{
points[0]=point;
points[1]=point;
}
for (i=0; i < 4; i++)
(q+i)->point=points[i];
TraceBezier(q,4);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 't':
case 'T':
{
/*
Compute bezier points.
*/
do
{
points[0]=points[2];
points[1].x=2.0*points[2].x-points[1].x;
points[1].y=2.0*points[2].y-points[1].y;
for (i=2; i < 3; i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,(char **) NULL);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,(char **) NULL);
end.x=(double) (attribute == (int) 'T' ? x : point.x+x);
end.y=(double) (attribute == (int) 'T' ? y : point.y+y);
points[i]=end;
}
if (strchr("QqTt",last_attribute) == (char *) NULL)
{
points[0]=point;
points[1]=point;
}
for (i=0; i < 3; i++)
(q+i)->point=points[i];
TraceBezier(q,3);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'v':
case 'V':
{
do
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,(char **) NULL);
point.y=(double) (attribute == (int) 'V' ? y : point.y+y);
TracePoint(q,point);
q+=q->coordinates;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'z':
case 'Z':
{
point=start;
TracePoint(q,point);
q+=q->coordinates;
primitive_info->coordinates=(size_t) (q-primitive_info);
number_coordinates+=primitive_info->coordinates;
primitive_info=q;
z_count++;
break;
}
default:
{
if (isalpha((int) ((unsigned char) attribute)) != 0)
(void) FormatLocaleFile(stderr,"attribute not recognized: %c\n",
attribute);
break;
}
}
}
primitive_info->coordinates=(size_t) (q-primitive_info);
number_coordinates+=primitive_info->coordinates;
for (i=0; i < (ssize_t) number_coordinates; i++)
{
q--;
q->primitive=primitive_type;
if (z_count > 1)
q->method=FillToBorderMethod;
}
q=primitive_info;
return(number_coordinates);
}
static void TraceRectangle(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end)
{
PointInfo
point;
register PrimitiveInfo
*p;
register ssize_t
i;
p=primitive_info;
TracePoint(p,start);
p+=p->coordinates;
point.x=start.x;
point.y=end.y;
TracePoint(p,point);
p+=p->coordinates;
TracePoint(p,end);
p+=p->coordinates;
point.x=end.x;
point.y=start.y;
TracePoint(p,point);
p+=p->coordinates;
TracePoint(p,start);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceRoundRectangle(PrimitiveInfo *primitive_info,
const PointInfo start,const PointInfo end,PointInfo arc)
{
PointInfo
degrees,
offset,
point;
register PrimitiveInfo
*p;
register ssize_t
i;
p=primitive_info;
offset.x=fabs(end.x-start.x);
offset.y=fabs(end.y-start.y);
if (arc.x > (0.5*offset.x))
arc.x=0.5*offset.x;
if (arc.y > (0.5*offset.y))
arc.y=0.5*offset.y;
point.x=start.x+offset.x-arc.x;
point.y=start.y+arc.y;
degrees.x=270.0;
degrees.y=360.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
point.x=start.x+offset.x-arc.x;
point.y=start.y+offset.y-arc.y;
degrees.x=0.0;
degrees.y=90.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
point.x=start.x+arc.x;
point.y=start.y+offset.y-arc.y;
degrees.x=90.0;
degrees.y=180.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
point.x=start.x+arc.x;
point.y=start.y+arc.y;
degrees.x=180.0;
degrees.y=270.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
TracePoint(p,primitive_info->point);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceSquareLinecap(PrimitiveInfo *primitive_info,
const size_t number_vertices,const double offset)
{
double
distance;
register double
dx,
dy;
register ssize_t
i;
ssize_t
j;
dx=0.0;
dy=0.0;
for (i=1; i < (ssize_t) number_vertices; i++)
{
dx=primitive_info[0].point.x-primitive_info[i].point.x;
dy=primitive_info[0].point.y-primitive_info[i].point.y;
if ((fabs((double) dx) >= MagickEpsilon) ||
(fabs((double) dy) >= MagickEpsilon))
break;
}
if (i == (ssize_t) number_vertices)
i=(ssize_t) number_vertices-1L;
distance=hypot((double) dx,(double) dy);
primitive_info[0].point.x=(double) (primitive_info[i].point.x+
dx*(distance+offset)/distance);
primitive_info[0].point.y=(double) (primitive_info[i].point.y+
dy*(distance+offset)/distance);
for (j=(ssize_t) number_vertices-2; j >= 0; j--)
{
dx=primitive_info[number_vertices-1].point.x-primitive_info[j].point.x;
dy=primitive_info[number_vertices-1].point.y-primitive_info[j].point.y;
if ((fabs((double) dx) >= MagickEpsilon) ||
(fabs((double) dy) >= MagickEpsilon))
break;
}
distance=hypot((double) dx,(double) dy);
primitive_info[number_vertices-1].point.x=(double) (primitive_info[j].point.x+
dx*(distance+offset)/distance);
primitive_info[number_vertices-1].point.y=(double) (primitive_info[j].point.y+
dy*(distance+offset)/distance);
}
static inline double DrawEpsilonReciprocal(const double x)
{
#define DrawEpsilon (1.0e-6)
double sign = x < 0.0 ? -1.0 : 1.0;
return((sign*x) >= DrawEpsilon ? 1.0/x : sign*(1.0/DrawEpsilon));
}
static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info)
{
typedef struct _LineSegment
{
double
p,
q;
} LineSegment;
LineSegment
dx,
dy,
inverse_slope,
slope,
theta;
MagickBooleanType
closed_path;
double
delta_theta,
dot_product,
mid,
miterlimit;
PointInfo
box_p[5],
box_q[5],
center,
offset,
*path_p,
*path_q;
PrimitiveInfo
*polygon_primitive,
*stroke_polygon;
register ssize_t
i;
size_t
arc_segments,
max_strokes,
number_vertices;
ssize_t
j,
n,
p,
q;
/*
Allocate paths.
*/
number_vertices=primitive_info->coordinates;
max_strokes=2*number_vertices+6*BezierQuantum+360;
path_p=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,
sizeof(*path_p));
path_q=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,
sizeof(*path_q));
polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
number_vertices+2UL,sizeof(*polygon_primitive));
if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL) ||
(polygon_primitive == (PrimitiveInfo *) NULL))
return((PrimitiveInfo *) NULL);
(void) CopyMagickMemory(polygon_primitive,primitive_info,(size_t)
number_vertices*sizeof(*polygon_primitive));
closed_path=
(primitive_info[number_vertices-1].point.x == primitive_info[0].point.x) &&
(primitive_info[number_vertices-1].point.y == primitive_info[0].point.y) ?
MagickTrue : MagickFalse;
if ((draw_info->linejoin == RoundJoin) ||
((draw_info->linejoin == MiterJoin) && (closed_path != MagickFalse)))
{
polygon_primitive[number_vertices]=primitive_info[1];
number_vertices++;
}
polygon_primitive[number_vertices].primitive=UndefinedPrimitive;
/*
Compute the slope for the first line segment, p.
*/
dx.p=0.0;
dy.p=0.0;
for (n=1; n < (ssize_t) number_vertices; n++)
{
dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x;
dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y;
if ((fabs(dx.p) >= MagickEpsilon) || (fabs(dy.p) >= MagickEpsilon))
break;
}
if (n == (ssize_t) number_vertices)
n=(ssize_t) number_vertices-1L;
slope.p=DrawEpsilonReciprocal(dx.p)*dy.p;
inverse_slope.p=(-1.0*DrawEpsilonReciprocal(slope.p));
mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit*
mid*mid);
if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse))
TraceSquareLinecap(polygon_primitive,number_vertices,mid);
offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0)));
offset.y=(double) (offset.x*inverse_slope.p);
if ((dy.p*offset.x-dx.p*offset.y) > 0.0)
{
box_p[0].x=polygon_primitive[0].point.x-offset.x;
box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p;
box_p[1].x=polygon_primitive[n].point.x-offset.x;
box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p;
box_q[0].x=polygon_primitive[0].point.x+offset.x;
box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p;
box_q[1].x=polygon_primitive[n].point.x+offset.x;
box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p;
}
else
{
box_p[0].x=polygon_primitive[0].point.x+offset.x;
box_p[0].y=polygon_primitive[0].point.y+offset.y;
box_p[1].x=polygon_primitive[n].point.x+offset.x;
box_p[1].y=polygon_primitive[n].point.y+offset.y;
box_q[0].x=polygon_primitive[0].point.x-offset.x;
box_q[0].y=polygon_primitive[0].point.y-offset.y;
box_q[1].x=polygon_primitive[n].point.x-offset.x;
box_q[1].y=polygon_primitive[n].point.y-offset.y;
}
/*
Create strokes for the line join attribute: bevel, miter, round.
*/
p=0;
q=0;
path_q[p++]=box_q[0];
path_p[q++]=box_p[0];
for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++)
{
/*
Compute the slope for this line segment, q.
*/
dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x;
dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y;
dot_product=dx.q*dx.q+dy.q*dy.q;
if (dot_product < 0.25)
continue;
slope.q=DrawEpsilonReciprocal(dx.q)*dy.q;
inverse_slope.q=(-1.0*DrawEpsilonReciprocal(slope.q));
offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0)));
offset.y=(double) (offset.x*inverse_slope.q);
dot_product=dy.q*offset.x-dx.q*offset.y;
if (dot_product > 0.0)
{
box_p[2].x=polygon_primitive[n].point.x-offset.x;
box_p[2].y=polygon_primitive[n].point.y-offset.y;
box_p[3].x=polygon_primitive[i].point.x-offset.x;
box_p[3].y=polygon_primitive[i].point.y-offset.y;
box_q[2].x=polygon_primitive[n].point.x+offset.x;
box_q[2].y=polygon_primitive[n].point.y+offset.y;
box_q[3].x=polygon_primitive[i].point.x+offset.x;
box_q[3].y=polygon_primitive[i].point.y+offset.y;
}
else
{
box_p[2].x=polygon_primitive[n].point.x+offset.x;
box_p[2].y=polygon_primitive[n].point.y+offset.y;
box_p[3].x=polygon_primitive[i].point.x+offset.x;
box_p[3].y=polygon_primitive[i].point.y+offset.y;
box_q[2].x=polygon_primitive[n].point.x-offset.x;
box_q[2].y=polygon_primitive[n].point.y-offset.y;
box_q[3].x=polygon_primitive[i].point.x-offset.x;
box_q[3].y=polygon_primitive[i].point.y-offset.y;
}
if (fabs((double) (slope.p-slope.q)) < MagickEpsilon)
{
box_p[4]=box_p[1];
box_q[4]=box_q[1];
}
else
{
box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+
box_p[3].y)/(slope.p-slope.q));
box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y);
box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+
box_q[3].y)/(slope.p-slope.q));
box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y);
}
if (q >= (ssize_t) (max_strokes-6*BezierQuantum-360))
{
if (~max_strokes < (6*BezierQuantum+360))
{
path_p=(PointInfo *) RelinquishMagickMemory(path_p);
path_q=(PointInfo *) RelinquishMagickMemory(path_q);
}
else
{
max_strokes+=6*BezierQuantum+360;
path_p=(PointInfo *) ResizeQuantumMemory(path_p,max_strokes,
sizeof(*path_p));
path_q=(PointInfo *) ResizeQuantumMemory(path_q,max_strokes,
sizeof(*path_q));
}
if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL))
{
if (path_p != (PointInfo *) NULL)
path_p=(PointInfo *) RelinquishMagickMemory(path_p);
if (path_q != (PointInfo *) NULL)
path_q=(PointInfo *) RelinquishMagickMemory(path_q);
polygon_primitive=(PrimitiveInfo *)
RelinquishMagickMemory(polygon_primitive);
return((PrimitiveInfo *) NULL);
}
}
dot_product=dx.q*dy.p-dx.p*dy.q;
if (dot_product <= 0.0)
switch (draw_info->linejoin)
{
case BevelJoin:
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_p[p++]=box_p[4];
else
{
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
break;
}
case MiterJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
{
path_q[q++]=box_q[4];
path_p[p++]=box_p[4];
}
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
break;
}
case RoundJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_p[p++]=box_p[4];
else
{
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
center=polygon_primitive[n].point;
theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x);
theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x);
if (theta.q < theta.p)
theta.q+=(double) (2.0*MagickPI);
arc_segments=(size_t) ceil((double) ((theta.q-theta.p)/
(2.0*sqrt((double) (1.0/mid)))));
path_q[q].x=box_q[1].x;
path_q[q].y=box_q[1].y;
q++;
for (j=1; j < (ssize_t) arc_segments; j++)
{
delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);
path_q[q].x=(double) (center.x+mid*cos(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
path_q[q].y=(double) (center.y+mid*sin(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
q++;
}
path_q[q++]=box_q[2];
break;
}
default:
break;
}
else
switch (draw_info->linejoin)
{
case BevelJoin:
{
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_q[q++]=box_q[4];
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
}
break;
}
case MiterJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
{
path_q[q++]=box_q[4];
path_p[p++]=box_p[4];
}
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
break;
}
case RoundJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_q[q++]=box_q[4];
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
}
center=polygon_primitive[n].point;
theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x);
theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x);
if (theta.p < theta.q)
theta.p+=(double) (2.0*MagickPI);
arc_segments=(size_t) ceil((double) ((theta.p-theta.q)/
(2.0*sqrt((double) (1.0/mid)))));
path_p[p++]=box_p[1];
for (j=1; j < (ssize_t) arc_segments; j++)
{
delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);
path_p[p].x=(double) (center.x+mid*cos(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
path_p[p].y=(double) (center.y+mid*sin(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
p++;
}
path_p[p++]=box_p[2];
break;
}
default:
break;
}
slope.p=slope.q;
inverse_slope.p=inverse_slope.q;
box_p[0]=box_p[2];
box_p[1]=box_p[3];
box_q[0]=box_q[2];
box_q[1]=box_q[3];
dx.p=dx.q;
dy.p=dy.q;
n=i;
}
path_p[p++]=box_p[1];
path_q[q++]=box_q[1];
/*
Trace stroked polygon.
*/
stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
(p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon));
if (stroke_polygon != (PrimitiveInfo *) NULL)
{
for (i=0; i < (ssize_t) p; i++)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=path_p[i];
}
if (closed_path != MagickFalse)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=stroke_polygon[0].point;
i++;
}
for ( ; i < (ssize_t) (p+q+closed_path); i++)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=path_q[p+q+closed_path-(i+1)];
}
if (closed_path != MagickFalse)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=stroke_polygon[p+closed_path].point;
i++;
}
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=stroke_polygon[0].point;
i++;
stroke_polygon[i].primitive=UndefinedPrimitive;
stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1);
}
path_p=(PointInfo *) RelinquishMagickMemory(path_p);
path_q=(PointInfo *) RelinquishMagickMemory(path_q);
polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive);
return(stroke_polygon);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5053_1 |
crossvul-cpp_data_bad_4063_0 | /*
* corre.c
*
* Routines to implement Compact Rise-and-Run-length Encoding (CoRRE). This
* code is based on krw's original javatel rfbserver.
*/
/*
* Copyright (C) 2002 RealVNC Ltd.
* OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk@incompleteness.net>.
* Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge.
* All Rights Reserved.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
#include <rfb/rfb.h>
/*
* cl->beforeEncBuf contains pixel data in the client's format.
* cl->afterEncBuf contains the RRE encoded version. If the RRE encoded version is
* larger than the raw data or if it exceeds cl->afterEncBufSize then
* raw encoding is used instead.
*/
static int subrectEncode8(rfbClientPtr cl, uint8_t *data, int w, int h);
static int subrectEncode16(rfbClientPtr cl, uint16_t *data, int w, int h);
static int subrectEncode32(rfbClientPtr cl, uint32_t *data, int w, int h);
static uint32_t getBgColour(char *data, int size, int bpp);
static rfbBool rfbSendSmallRectEncodingCoRRE(rfbClientPtr cl, int x, int y,
int w, int h);
/*
* rfbSendRectEncodingCoRRE - send an arbitrary size rectangle using CoRRE
* encoding.
*/
rfbBool
rfbSendRectEncodingCoRRE(rfbClientPtr cl,
int x,
int y,
int w,
int h)
{
if (h > cl->correMaxHeight) {
return (rfbSendRectEncodingCoRRE(cl, x, y, w, cl->correMaxHeight) &&
rfbSendRectEncodingCoRRE(cl, x, y + cl->correMaxHeight, w,
h - cl->correMaxHeight));
}
if (w > cl->correMaxWidth) {
return (rfbSendRectEncodingCoRRE(cl, x, y, cl->correMaxWidth, h) &&
rfbSendRectEncodingCoRRE(cl, x + cl->correMaxWidth, y,
w - cl->correMaxWidth, h));
}
rfbSendSmallRectEncodingCoRRE(cl, x, y, w, h);
return TRUE;
}
/*
* rfbSendSmallRectEncodingCoRRE - send a small (guaranteed < 256x256)
* rectangle using CoRRE encoding.
*/
static rfbBool
rfbSendSmallRectEncodingCoRRE(rfbClientPtr cl,
int x,
int y,
int w,
int h)
{
rfbFramebufferUpdateRectHeader rect;
rfbRREHeader hdr;
int nSubrects;
int i;
char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y)
+ (x * (cl->scaledScreen->bitsPerPixel / 8)));
int maxRawSize = (cl->scaledScreen->width * cl->scaledScreen->height
* (cl->format.bitsPerPixel / 8));
if (cl->beforeEncBufSize < maxRawSize) {
cl->beforeEncBufSize = maxRawSize;
if (cl->beforeEncBuf == NULL)
cl->beforeEncBuf = (char *)malloc(cl->beforeEncBufSize);
else
cl->beforeEncBuf = (char *)realloc(cl->beforeEncBuf, cl->beforeEncBufSize);
}
if (cl->afterEncBufSize < maxRawSize) {
cl->afterEncBufSize = maxRawSize;
if (cl->afterEncBuf == NULL)
cl->afterEncBuf = (char *)malloc(cl->afterEncBufSize);
else
cl->afterEncBuf = (char *)realloc(cl->afterEncBuf, cl->afterEncBufSize);
}
(*cl->translateFn)(cl->translateLookupTable,&(cl->screen->serverFormat),
&cl->format, fbptr, cl->beforeEncBuf,
cl->scaledScreen->paddedWidthInBytes, w, h);
switch (cl->format.bitsPerPixel) {
case 8:
nSubrects = subrectEncode8(cl, (uint8_t *)cl->beforeEncBuf, w, h);
break;
case 16:
nSubrects = subrectEncode16(cl, (uint16_t *)cl->beforeEncBuf, w, h);
break;
case 32:
nSubrects = subrectEncode32(cl, (uint32_t *)cl->beforeEncBuf, w, h);
break;
default:
rfbLog("getBgColour: bpp %d?\n",cl->format.bitsPerPixel);
return FALSE;
}
if (nSubrects < 0) {
/* RRE encoding was too large, use raw */
return rfbSendRectEncodingRaw(cl, x, y, w, h);
}
rfbStatRecordEncodingSent(cl,rfbEncodingCoRRE,
sz_rfbFramebufferUpdateRectHeader + sz_rfbRREHeader + cl->afterEncBufLen,
sz_rfbFramebufferUpdateRectHeader + w * h * (cl->format.bitsPerPixel / 8));
if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbRREHeader
> UPDATE_BUF_SIZE)
{
if (!rfbSendUpdateBuf(cl))
return FALSE;
}
rect.r.x = Swap16IfLE(x);
rect.r.y = Swap16IfLE(y);
rect.r.w = Swap16IfLE(w);
rect.r.h = Swap16IfLE(h);
rect.encoding = Swap32IfLE(rfbEncodingCoRRE);
memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,
sz_rfbFramebufferUpdateRectHeader);
cl->ublen += sz_rfbFramebufferUpdateRectHeader;
hdr.nSubrects = Swap32IfLE(nSubrects);
memcpy(&cl->updateBuf[cl->ublen], (char *)&hdr, sz_rfbRREHeader);
cl->ublen += sz_rfbRREHeader;
for (i = 0; i < cl->afterEncBufLen;) {
int bytesToCopy = UPDATE_BUF_SIZE - cl->ublen;
if (i + bytesToCopy > cl->afterEncBufLen) {
bytesToCopy = cl->afterEncBufLen - i;
}
memcpy(&cl->updateBuf[cl->ublen], &cl->afterEncBuf[i], bytesToCopy);
cl->ublen += bytesToCopy;
i += bytesToCopy;
if (cl->ublen == UPDATE_BUF_SIZE) {
if (!rfbSendUpdateBuf(cl))
return FALSE;
}
}
return TRUE;
}
/*
* subrectEncode() encodes the given multicoloured rectangle as a background
* colour overwritten by single-coloured rectangles. It returns the number
* of subrectangles in the encoded buffer, or -1 if subrect encoding won't
* fit in the buffer. It puts the encoded rectangles in cl->afterEncBuf. The
* single-colour rectangle partition is not optimal, but does find the biggest
* horizontal or vertical rectangle top-left anchored to each consecutive
* coordinate position.
*
* The coding scheme is simply [<bgcolour><subrect><subrect>...] where each
* <subrect> is [<colour><x><y><w><h>].
*/
#define DEFINE_SUBRECT_ENCODE(bpp) \
static int \
subrectEncode##bpp(rfbClientPtr client, uint##bpp##_t *data, int w, int h) { \
uint##bpp##_t cl; \
rfbCoRRERectangle subrect; \
int x,y; \
int i,j; \
int hx=0,hy,vx=0,vy; \
int hyflag; \
uint##bpp##_t *seg; \
uint##bpp##_t *line; \
int hw,hh,vw,vh; \
int thex,they,thew,theh; \
int numsubs = 0; \
int newLen; \
uint##bpp##_t bg = (uint##bpp##_t)getBgColour((char*)data,w*h,bpp); \
\
*((uint##bpp##_t*)client->afterEncBuf) = bg; \
\
client->afterEncBufLen = (bpp/8); \
\
for (y=0; y<h; y++) { \
line = data+(y*w); \
for (x=0; x<w; x++) { \
if (line[x] != bg) { \
cl = line[x]; \
hy = y-1; \
hyflag = 1; \
for (j=y; j<h; j++) { \
seg = data+(j*w); \
if (seg[x] != cl) {break;} \
i = x; \
while ((seg[i] == cl) && (i < w)) i += 1; \
i -= 1; \
if (j == y) vx = hx = i; \
if (i < vx) vx = i; \
if ((hyflag > 0) && (i >= hx)) {hy += 1;} else {hyflag = 0;} \
} \
vy = j-1; \
\
/* We now have two possible subrects: (x,y,hx,hy) and (x,y,vx,vy) \
* We'll choose the bigger of the two. \
*/ \
hw = hx-x+1; \
hh = hy-y+1; \
vw = vx-x+1; \
vh = vy-y+1; \
\
thex = x; \
they = y; \
\
if ((hw*hh) > (vw*vh)) { \
thew = hw; \
theh = hh; \
} else { \
thew = vw; \
theh = vh; \
} \
\
subrect.x = thex; \
subrect.y = they; \
subrect.w = thew; \
subrect.h = theh; \
\
newLen = client->afterEncBufLen + (bpp/8) + sz_rfbCoRRERectangle; \
if ((newLen > (w * h * (bpp/8))) || (newLen > client->afterEncBufSize)) \
return -1; \
\
numsubs += 1; \
*((uint##bpp##_t*)(client->afterEncBuf + client->afterEncBufLen)) = cl; \
client->afterEncBufLen += (bpp/8); \
memcpy(&client->afterEncBuf[client->afterEncBufLen],&subrect,sz_rfbCoRRERectangle); \
client->afterEncBufLen += sz_rfbCoRRERectangle; \
\
/* \
* Now mark the subrect as done. \
*/ \
for (j=they; j < (they+theh); j++) { \
for (i=thex; i < (thex+thew); i++) { \
data[j*w+i] = bg; \
} \
} \
} \
} \
} \
\
return numsubs; \
}
DEFINE_SUBRECT_ENCODE(8)
DEFINE_SUBRECT_ENCODE(16)
DEFINE_SUBRECT_ENCODE(32)
/*
* getBgColour() gets the most prevalent colour in a byte array.
*/
static uint32_t
getBgColour(char *data, int size, int bpp)
{
#define NUMCLRS 256
static int counts[NUMCLRS];
int i,j,k;
int maxcount = 0;
uint8_t maxclr = 0;
if (bpp != 8) {
if (bpp == 16) {
return ((uint16_t *)data)[0];
} else if (bpp == 32) {
return ((uint32_t *)data)[0];
} else {
rfbLog("getBgColour: bpp %d?\n",bpp);
return 0;
}
}
for (i=0; i<NUMCLRS; i++) {
counts[i] = 0;
}
for (j=0; j<size; j++) {
k = (int)(((uint8_t *)data)[j]);
if (k >= NUMCLRS) {
rfbLog("getBgColour: unusual colour = %d\n", k);
return 0;
}
counts[k] += 1;
if (counts[k] > maxcount) {
maxcount = counts[k];
maxclr = ((uint8_t *)data)[j];
}
}
return maxclr;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4063_0 |
crossvul-cpp_data_bad_3227_0 | /*
** Copyright (C) 1999-2017 Erik de Castro Lopo <erikd@mega-nerd.com>
** Copyright (C) 2005 David Viens <davidv@plogue.com>
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation; either version 2.1 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "sfconfig.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#include <inttypes.h>
#include "sndfile.h"
#include "sfendian.h"
#include "common.h"
#include "chanmap.h"
/*------------------------------------------------------------------------------
* Macros to handle big/little endian issues.
*/
#define FORM_MARKER (MAKE_MARKER ('F', 'O', 'R', 'M'))
#define AIFF_MARKER (MAKE_MARKER ('A', 'I', 'F', 'F'))
#define AIFC_MARKER (MAKE_MARKER ('A', 'I', 'F', 'C'))
#define COMM_MARKER (MAKE_MARKER ('C', 'O', 'M', 'M'))
#define SSND_MARKER (MAKE_MARKER ('S', 'S', 'N', 'D'))
#define MARK_MARKER (MAKE_MARKER ('M', 'A', 'R', 'K'))
#define INST_MARKER (MAKE_MARKER ('I', 'N', 'S', 'T'))
#define APPL_MARKER (MAKE_MARKER ('A', 'P', 'P', 'L'))
#define CHAN_MARKER (MAKE_MARKER ('C', 'H', 'A', 'N'))
#define c_MARKER (MAKE_MARKER ('(', 'c', ')', ' '))
#define NAME_MARKER (MAKE_MARKER ('N', 'A', 'M', 'E'))
#define AUTH_MARKER (MAKE_MARKER ('A', 'U', 'T', 'H'))
#define ANNO_MARKER (MAKE_MARKER ('A', 'N', 'N', 'O'))
#define COMT_MARKER (MAKE_MARKER ('C', 'O', 'M', 'T'))
#define FVER_MARKER (MAKE_MARKER ('F', 'V', 'E', 'R'))
#define SFX_MARKER (MAKE_MARKER ('S', 'F', 'X', '!'))
#define PEAK_MARKER (MAKE_MARKER ('P', 'E', 'A', 'K'))
#define basc_MARKER (MAKE_MARKER ('b', 'a', 's', 'c'))
/* Supported AIFC encodings.*/
#define NONE_MARKER (MAKE_MARKER ('N', 'O', 'N', 'E'))
#define sowt_MARKER (MAKE_MARKER ('s', 'o', 'w', 't'))
#define twos_MARKER (MAKE_MARKER ('t', 'w', 'o', 's'))
#define raw_MARKER (MAKE_MARKER ('r', 'a', 'w', ' '))
#define in24_MARKER (MAKE_MARKER ('i', 'n', '2', '4'))
#define ni24_MARKER (MAKE_MARKER ('4', '2', 'n', '1'))
#define in32_MARKER (MAKE_MARKER ('i', 'n', '3', '2'))
#define ni32_MARKER (MAKE_MARKER ('2', '3', 'n', 'i'))
#define fl32_MARKER (MAKE_MARKER ('f', 'l', '3', '2'))
#define FL32_MARKER (MAKE_MARKER ('F', 'L', '3', '2'))
#define fl64_MARKER (MAKE_MARKER ('f', 'l', '6', '4'))
#define FL64_MARKER (MAKE_MARKER ('F', 'L', '6', '4'))
#define ulaw_MARKER (MAKE_MARKER ('u', 'l', 'a', 'w'))
#define ULAW_MARKER (MAKE_MARKER ('U', 'L', 'A', 'W'))
#define alaw_MARKER (MAKE_MARKER ('a', 'l', 'a', 'w'))
#define ALAW_MARKER (MAKE_MARKER ('A', 'L', 'A', 'W'))
#define DWVW_MARKER (MAKE_MARKER ('D', 'W', 'V', 'W'))
#define GSM_MARKER (MAKE_MARKER ('G', 'S', 'M', ' '))
#define ima4_MARKER (MAKE_MARKER ('i', 'm', 'a', '4'))
/*
** This value is officially assigned to Mega Nerd Pty Ltd by Apple
** Corportation as the Application marker for libsndfile.
**
** See : http://developer.apple.com/faq/datatype.html
*/
#define m3ga_MARKER (MAKE_MARKER ('m', '3', 'g', 'a'))
/* Unsupported AIFC encodings.*/
#define MAC3_MARKER (MAKE_MARKER ('M', 'A', 'C', '3'))
#define MAC6_MARKER (MAKE_MARKER ('M', 'A', 'C', '6'))
#define ADP4_MARKER (MAKE_MARKER ('A', 'D', 'P', '4'))
/* Predfined chunk sizes. */
#define SIZEOF_AIFF_COMM 18
#define SIZEOF_AIFC_COMM_MIN 22
#define SIZEOF_AIFC_COMM 24
#define SIZEOF_SSND_CHUNK 8
#define SIZEOF_INST_CHUNK 20
/* Is it constant? */
/* AIFC/IMA4 defines. */
#define AIFC_IMA4_BLOCK_LEN 34
#define AIFC_IMA4_SAMPLES_PER_BLOCK 64
#define AIFF_PEAK_CHUNK_SIZE(ch) (2 * sizeof (int) + ch * (sizeof (float) + sizeof (int)))
/*------------------------------------------------------------------------------
* Typedefs for file chunks.
*/
enum
{ HAVE_FORM = 0x01,
HAVE_AIFF = 0x02,
HAVE_AIFC = 0x04,
HAVE_FVER = 0x08,
HAVE_COMM = 0x10,
HAVE_SSND = 0x20
} ;
typedef struct
{ uint32_t size ;
int16_t numChannels ;
uint32_t numSampleFrames ;
int16_t sampleSize ;
uint8_t sampleRate [10] ;
uint32_t encoding ;
char zero_bytes [2] ;
} COMM_CHUNK ;
typedef struct
{ uint32_t offset ;
uint32_t blocksize ;
} SSND_CHUNK ;
typedef struct
{ int16_t playMode ;
uint16_t beginLoop ;
uint16_t endLoop ;
} INST_LOOP ;
typedef struct
{ int8_t baseNote ; /* all notes are MIDI note numbers */
int8_t detune ; /* cents off, only -50 to +50 are significant */
int8_t lowNote ;
int8_t highNote ;
int8_t lowVelocity ; /* 1 to 127 */
int8_t highVelocity ; /* 1 to 127 */
int16_t gain ; /* in dB, 0 is normal */
INST_LOOP sustain_loop ;
INST_LOOP release_loop ;
} INST_CHUNK ;
enum
{ basc_SCALE_MINOR = 1,
basc_SCALE_MAJOR,
basc_SCALE_NEITHER,
basc_SCALE_BOTH
} ;
enum
{ basc_TYPE_LOOP = 0,
basc_TYPE_ONE_SHOT
} ;
typedef struct
{ uint32_t version ;
uint32_t numBeats ;
uint16_t rootNote ;
uint16_t scaleType ;
uint16_t sigNumerator ;
uint16_t sigDenominator ;
uint16_t loopType ;
} basc_CHUNK ;
typedef struct
{ uint16_t markerID ;
uint32_t position ;
} MARK_ID_POS ;
typedef struct
{ sf_count_t comm_offset ;
sf_count_t ssnd_offset ;
int32_t chanmap_tag ;
MARK_ID_POS *markstr ;
} AIFF_PRIVATE ;
/*------------------------------------------------------------------------------
* Private static functions.
*/
static int aiff_close (SF_PRIVATE *psf) ;
static int tenbytefloat2int (uint8_t *bytes) ;
static void uint2tenbytefloat (uint32_t num, uint8_t *bytes) ;
static int aiff_read_comm_chunk (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt) ;
static int aiff_read_header (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt) ;
static int aiff_write_header (SF_PRIVATE *psf, int calc_length) ;
static int aiff_write_tailer (SF_PRIVATE *psf) ;
static void aiff_write_strings (SF_PRIVATE *psf, int location) ;
static int aiff_command (SF_PRIVATE *psf, int command, void *data, int datasize) ;
static const char *get_loop_mode_str (int16_t mode) ;
static int16_t get_loop_mode (int16_t mode) ;
static int aiff_read_basc_chunk (SF_PRIVATE * psf, int) ;
static int aiff_read_chanmap (SF_PRIVATE * psf, unsigned dword) ;
static uint32_t marker_to_position (const MARK_ID_POS *m, uint16_t n, int marksize) ;
static int aiff_set_chunk (SF_PRIVATE *psf, const SF_CHUNK_INFO * chunk_info) ;
static SF_CHUNK_ITERATOR * aiff_next_chunk_iterator (SF_PRIVATE *psf, SF_CHUNK_ITERATOR * iterator) ;
static int aiff_get_chunk_size (SF_PRIVATE *psf, const SF_CHUNK_ITERATOR * iterator, SF_CHUNK_INFO * chunk_info) ;
static int aiff_get_chunk_data (SF_PRIVATE *psf, const SF_CHUNK_ITERATOR * iterator, SF_CHUNK_INFO * chunk_info) ;
/*------------------------------------------------------------------------------
** Public function.
*/
int
aiff_open (SF_PRIVATE *psf)
{ COMM_CHUNK comm_fmt ;
int error, subformat ;
memset (&comm_fmt, 0, sizeof (comm_fmt)) ;
subformat = SF_CODEC (psf->sf.format) ;
if ((psf->container_data = calloc (1, sizeof (AIFF_PRIVATE))) == NULL)
return SFE_MALLOC_FAILED ;
if (psf->file.mode == SFM_READ || (psf->file.mode == SFM_RDWR && psf->filelength > 0))
{ if ((error = aiff_read_header (psf, &comm_fmt)))
return error ;
psf->next_chunk_iterator = aiff_next_chunk_iterator ;
psf->get_chunk_size = aiff_get_chunk_size ;
psf->get_chunk_data = aiff_get_chunk_data ;
psf_fseek (psf, psf->dataoffset, SEEK_SET) ;
} ;
if (psf->file.mode == SFM_WRITE || psf->file.mode == SFM_RDWR)
{ if (psf->is_pipe)
return SFE_NO_PIPE_WRITE ;
if ((SF_CONTAINER (psf->sf.format)) != SF_FORMAT_AIFF)
return SFE_BAD_OPEN_FORMAT ;
if (psf->file.mode == SFM_WRITE && (subformat == SF_FORMAT_FLOAT || subformat == SF_FORMAT_DOUBLE))
{ if ((psf->peak_info = peak_info_calloc (psf->sf.channels)) == NULL)
return SFE_MALLOC_FAILED ;
psf->peak_info->peak_loc = SF_PEAK_START ;
} ;
if (psf->file.mode != SFM_RDWR || psf->filelength < 40)
{ psf->filelength = 0 ;
psf->datalength = 0 ;
psf->dataoffset = 0 ;
psf->sf.frames = 0 ;
} ;
psf->strings.flags = SF_STR_ALLOW_START | SF_STR_ALLOW_END ;
if ((error = aiff_write_header (psf, SF_FALSE)))
return error ;
psf->write_header = aiff_write_header ;
psf->set_chunk = aiff_set_chunk ;
} ;
psf->container_close = aiff_close ;
psf->command = aiff_command ;
switch (SF_CODEC (psf->sf.format))
{ case SF_FORMAT_PCM_U8 :
error = pcm_init (psf) ;
break ;
case SF_FORMAT_PCM_S8 :
error = pcm_init (psf) ;
break ;
case SF_FORMAT_PCM_16 :
case SF_FORMAT_PCM_24 :
case SF_FORMAT_PCM_32 :
error = pcm_init (psf) ;
break ;
case SF_FORMAT_ULAW :
error = ulaw_init (psf) ;
break ;
case SF_FORMAT_ALAW :
error = alaw_init (psf) ;
break ;
/* Lite remove start */
case SF_FORMAT_FLOAT :
error = float32_init (psf) ;
break ;
case SF_FORMAT_DOUBLE :
error = double64_init (psf) ;
break ;
case SF_FORMAT_DWVW_12 :
if (psf->sf.frames > comm_fmt.numSampleFrames)
psf->sf.frames = comm_fmt.numSampleFrames ;
break ;
case SF_FORMAT_DWVW_16 :
error = dwvw_init (psf, 16) ;
if (psf->sf.frames > comm_fmt.numSampleFrames)
psf->sf.frames = comm_fmt.numSampleFrames ;
break ;
case SF_FORMAT_DWVW_24 :
error = dwvw_init (psf, 24) ;
if (psf->sf.frames > comm_fmt.numSampleFrames)
psf->sf.frames = comm_fmt.numSampleFrames ;
break ;
case SF_FORMAT_DWVW_N :
if (psf->file.mode != SFM_READ)
{ error = SFE_DWVW_BAD_BITWIDTH ;
break ;
} ;
if (comm_fmt.sampleSize >= 8 && comm_fmt.sampleSize < 24)
{ error = dwvw_init (psf, comm_fmt.sampleSize) ;
if (psf->sf.frames > comm_fmt.numSampleFrames)
psf->sf.frames = comm_fmt.numSampleFrames ;
break ;
} ;
psf_log_printf (psf, "AIFC/DWVW : Bad bitwidth %d\n", comm_fmt.sampleSize) ;
error = SFE_DWVW_BAD_BITWIDTH ;
break ;
case SF_FORMAT_IMA_ADPCM :
/*
** IMA ADPCM encoded AIFF files always have a block length
** of 34 which decodes to 64 samples.
*/
error = aiff_ima_init (psf, AIFC_IMA4_BLOCK_LEN, AIFC_IMA4_SAMPLES_PER_BLOCK) ;
break ;
/* Lite remove end */
case SF_FORMAT_GSM610 :
error = gsm610_init (psf) ;
if (psf->sf.frames > comm_fmt.numSampleFrames)
psf->sf.frames = comm_fmt.numSampleFrames ;
break ;
default : return SFE_UNIMPLEMENTED ;
} ;
if (psf->file.mode != SFM_WRITE && psf->sf.frames - comm_fmt.numSampleFrames != 0)
{ psf_log_printf (psf,
"*** Frame count read from 'COMM' chunk (%u) not equal to frame count\n"
"*** calculated from length of 'SSND' chunk (%u).\n",
comm_fmt.numSampleFrames, (uint32_t) psf->sf.frames) ;
} ;
return error ;
} /* aiff_open */
/*==========================================================================================
** Private functions.
*/
/* This function ought to check size */
static uint32_t
marker_to_position (const MARK_ID_POS *m, uint16_t n, int marksize)
{ int i ;
for (i = 0 ; i < marksize ; i++)
if (m [i].markerID == n)
return m [i].position ;
return 0 ;
} /* marker_to_position */
static int
aiff_read_header (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
{ SSND_CHUNK ssnd_fmt ;
AIFF_PRIVATE *paiff ;
BUF_UNION ubuf ;
uint32_t chunk_size = 0, FORMsize, SSNDsize, bytesread, mark_count = 0 ;
int k, found_chunk = 0, done = 0, error = 0 ;
char *cptr ;
int instr_found = 0, mark_found = 0 ;
if (psf->filelength > SF_PLATFORM_S64 (0xffffffff))
psf_log_printf (psf, "Warning : filelength > 0xffffffff. This is bad!!!!\n") ;
if ((paiff = psf->container_data) == NULL)
return SFE_INTERNAL ;
paiff->comm_offset = 0 ;
paiff->ssnd_offset = 0 ;
/* Set position to start of file to begin reading header. */
psf_binheader_readf (psf, "p", 0) ;
memset (comm_fmt, 0, sizeof (COMM_CHUNK)) ;
/* Until recently AIF* file were all BIG endian. */
psf->endian = SF_ENDIAN_BIG ;
/* AIFF files can apparently have their chunks in any order. However, they
** must have a FORM chunk. Approach here is to read all the chunks one by
** one and then check for the mandatory chunks at the end.
*/
while (! done)
{ unsigned marker ;
size_t jump = chunk_size & 1 ;
marker = chunk_size = 0 ;
psf_binheader_readf (psf, "Ejm4", jump, &marker, &chunk_size) ;
if (marker == 0)
{ sf_count_t pos = psf_ftell (psf) ;
psf_log_printf (psf, "Have 0 marker at position %D (0x%x).\n", pos, pos) ;
break ;
} ;
if (psf->file.mode == SFM_RDWR && (found_chunk & HAVE_SSND))
return SFE_AIFF_RW_SSND_NOT_LAST ;
psf_store_read_chunk_u32 (&psf->rchunks, marker, psf_ftell (psf), chunk_size) ;
switch (marker)
{ case FORM_MARKER :
if (found_chunk)
return SFE_AIFF_NO_FORM ;
FORMsize = chunk_size ;
found_chunk |= HAVE_FORM ;
psf_binheader_readf (psf, "m", &marker) ;
switch (marker)
{ case AIFC_MARKER :
case AIFF_MARKER :
found_chunk |= (marker == AIFC_MARKER) ? (HAVE_AIFC | HAVE_AIFF) : HAVE_AIFF ;
break ;
default :
break ;
} ;
if (psf->fileoffset > 0 && psf->filelength > FORMsize + 8)
{ /* Set file length. */
psf->filelength = FORMsize + 8 ;
psf_log_printf (psf, "FORM : %u\n %M\n", FORMsize, marker) ;
}
else if (FORMsize != psf->filelength - 2 * SIGNED_SIZEOF (chunk_size))
{ chunk_size = psf->filelength - 2 * sizeof (chunk_size) ;
psf_log_printf (psf, "FORM : %u (should be %u)\n %M\n", FORMsize, chunk_size, marker) ;
FORMsize = chunk_size ;
}
else
psf_log_printf (psf, "FORM : %u\n %M\n", FORMsize, marker) ;
/* Set this to 0, so we don't jump a byte when parsing the next marker. */
chunk_size = 0 ;
break ;
case COMM_MARKER :
paiff->comm_offset = psf_ftell (psf) - 8 ;
chunk_size += chunk_size & 1 ;
comm_fmt->size = chunk_size ;
if ((error = aiff_read_comm_chunk (psf, comm_fmt)) != 0)
return error ;
found_chunk |= HAVE_COMM ;
break ;
case PEAK_MARKER :
/* Must have COMM chunk before PEAK chunk. */
if ((found_chunk & (HAVE_FORM | HAVE_AIFF | HAVE_COMM)) != (HAVE_FORM | HAVE_AIFF | HAVE_COMM))
return SFE_AIFF_PEAK_B4_COMM ;
psf_log_printf (psf, "%M : %d\n", marker, chunk_size) ;
if (chunk_size != AIFF_PEAK_CHUNK_SIZE (psf->sf.channels))
{ psf_binheader_readf (psf, "j", chunk_size) ;
psf_log_printf (psf, "*** File PEAK chunk too big.\n") ;
return SFE_WAV_BAD_PEAK ;
} ;
if ((psf->peak_info = peak_info_calloc (psf->sf.channels)) == NULL)
return SFE_MALLOC_FAILED ;
/* read in rest of PEAK chunk. */
psf_binheader_readf (psf, "E44", &(psf->peak_info->version), &(psf->peak_info->timestamp)) ;
if (psf->peak_info->version != 1)
psf_log_printf (psf, " version : %d *** (should be version 1)\n", psf->peak_info->version) ;
else
psf_log_printf (psf, " version : %d\n", psf->peak_info->version) ;
psf_log_printf (psf, " time stamp : %d\n", psf->peak_info->timestamp) ;
psf_log_printf (psf, " Ch Position Value\n") ;
cptr = ubuf.cbuf ;
for (k = 0 ; k < psf->sf.channels ; k++)
{ float value ;
uint32_t position ;
psf_binheader_readf (psf, "Ef4", &value, &position) ;
psf->peak_info->peaks [k].value = value ;
psf->peak_info->peaks [k].position = position ;
snprintf (cptr, sizeof (ubuf.scbuf), " %2d %-12" PRId64 " %g\n",
k, psf->peak_info->peaks [k].position, psf->peak_info->peaks [k].value) ;
cptr [sizeof (ubuf.scbuf) - 1] = 0 ;
psf_log_printf (psf, "%s", cptr) ;
} ;
psf->peak_info->peak_loc = ((found_chunk & HAVE_SSND) == 0) ? SF_PEAK_START : SF_PEAK_END ;
break ;
case SSND_MARKER :
if ((found_chunk & HAVE_AIFC) && (found_chunk & HAVE_FVER) == 0)
psf_log_printf (psf, "*** Valid AIFC files should have an FVER chunk.\n") ;
paiff->ssnd_offset = psf_ftell (psf) - 8 ;
SSNDsize = chunk_size ;
psf_binheader_readf (psf, "E44", &(ssnd_fmt.offset), &(ssnd_fmt.blocksize)) ;
psf->datalength = SSNDsize - sizeof (ssnd_fmt) ;
psf->dataoffset = psf_ftell (psf) ;
if (psf->datalength > psf->filelength - psf->dataoffset || psf->datalength < 0)
{ psf_log_printf (psf, " SSND : %u (should be %D)\n", SSNDsize, psf->filelength - psf->dataoffset + sizeof (SSND_CHUNK)) ;
psf->datalength = psf->filelength - psf->dataoffset ;
}
else
psf_log_printf (psf, " SSND : %u\n", SSNDsize) ;
if (ssnd_fmt.offset == 0 || psf->dataoffset + ssnd_fmt.offset == ssnd_fmt.blocksize)
{ psf_log_printf (psf, " Offset : %u\n", ssnd_fmt.offset) ;
psf_log_printf (psf, " Block Size : %u\n", ssnd_fmt.blocksize) ;
psf->dataoffset += ssnd_fmt.offset ;
psf->datalength -= ssnd_fmt.offset ;
}
else
{ psf_log_printf (psf, " Offset : %u\n", ssnd_fmt.offset) ;
psf_log_printf (psf, " Block Size : %u ???\n", ssnd_fmt.blocksize) ;
psf->dataoffset += ssnd_fmt.offset ;
psf->datalength -= ssnd_fmt.offset ;
} ;
/* Only set dataend if there really is data at the end. */
if (psf->datalength + psf->dataoffset < psf->filelength)
psf->dataend = psf->datalength + psf->dataoffset ;
found_chunk |= HAVE_SSND ;
if (! psf->sf.seekable)
break ;
/* Seek to end of SSND chunk. */
psf_fseek (psf, psf->dataoffset + psf->datalength, SEEK_SET) ;
break ;
case c_MARKER :
if (chunk_size == 0)
break ;
if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf))
{ psf_log_printf (psf, " %M : %d (too big)\n", marker, chunk_size) ;
return SFE_INTERNAL ;
} ;
cptr = ubuf.cbuf ;
psf_binheader_readf (psf, "b", cptr, chunk_size + (chunk_size & 1)) ;
cptr [chunk_size] = 0 ;
psf_sanitize_string (cptr, chunk_size) ;
psf_log_printf (psf, " %M : %s\n", marker, cptr) ;
psf_store_string (psf, SF_STR_COPYRIGHT, cptr) ;
chunk_size += chunk_size & 1 ;
break ;
case AUTH_MARKER :
if (chunk_size == 0)
break ;
if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf) - 1)
{ psf_log_printf (psf, " %M : %d (too big)\n", marker, chunk_size) ;
return SFE_INTERNAL ;
} ;
cptr = ubuf.cbuf ;
psf_binheader_readf (psf, "b", cptr, chunk_size + (chunk_size & 1)) ;
cptr [chunk_size] = 0 ;
psf_log_printf (psf, " %M : %s\n", marker, cptr) ;
psf_store_string (psf, SF_STR_ARTIST, cptr) ;
chunk_size += chunk_size & 1 ;
break ;
case COMT_MARKER :
{ uint16_t count, id, len ;
uint32_t timestamp, bytes ;
if (chunk_size == 0)
break ;
bytes = chunk_size ;
bytes -= psf_binheader_readf (psf, "E2", &count) ;
psf_log_printf (psf, " %M : %d\n count : %d\n", marker, chunk_size, count) ;
for (k = 0 ; k < count ; k++)
{ bytes -= psf_binheader_readf (psf, "E422", ×tamp, &id, &len) ;
psf_log_printf (psf, " time : 0x%x\n marker : %x\n length : %d\n", timestamp, id, len) ;
if (len + 1 > SIGNED_SIZEOF (ubuf.scbuf))
{ psf_log_printf (psf, "\nError : string length (%d) too big.\n", len) ;
return SFE_INTERNAL ;
} ;
cptr = ubuf.cbuf ;
bytes -= psf_binheader_readf (psf, "b", cptr, len) ;
cptr [len] = 0 ;
psf_log_printf (psf, " string : %s\n", cptr) ;
} ;
if (bytes > 0)
psf_binheader_readf (psf, "j", bytes) ;
} ;
break ;
case APPL_MARKER :
{ unsigned appl_marker ;
if (chunk_size == 0)
break ;
if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf) - 1)
{ psf_log_printf (psf, " %M : %u (too big, skipping)\n", marker, chunk_size) ;
psf_binheader_readf (psf, "j", chunk_size + (chunk_size & 1)) ;
break ;
} ;
if (chunk_size < 4)
{ psf_log_printf (psf, " %M : %d (too small, skipping)\n", marker, chunk_size) ;
psf_binheader_readf (psf, "j", chunk_size + (chunk_size & 1)) ;
break ;
} ;
cptr = ubuf.cbuf ;
psf_binheader_readf (psf, "mb", &appl_marker, cptr, chunk_size + (chunk_size & 1) - 4) ;
cptr [chunk_size] = 0 ;
for (k = 0 ; k < (int) chunk_size ; k++)
if (! psf_isprint (cptr [k]))
{ cptr [k] = 0 ;
break ;
} ;
psf_log_printf (psf, " %M : %d\n AppSig : %M\n Name : %s\n", marker, chunk_size, appl_marker, cptr) ;
psf_store_string (psf, SF_STR_SOFTWARE, cptr) ;
chunk_size += chunk_size & 1 ;
} ;
break ;
case NAME_MARKER :
if (chunk_size == 0)
break ;
if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf) - 2)
{ psf_log_printf (psf, " %M : %d (too big)\n", marker, chunk_size) ;
return SFE_INTERNAL ;
} ;
cptr = ubuf.cbuf ;
psf_binheader_readf (psf, "b", cptr, chunk_size + (chunk_size & 1)) ;
cptr [chunk_size] = 0 ;
psf_log_printf (psf, " %M : %s\n", marker, cptr) ;
psf_store_string (psf, SF_STR_TITLE, cptr) ;
chunk_size += chunk_size & 1 ;
break ;
case ANNO_MARKER :
if (chunk_size == 0)
break ;
if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf) - 2)
{ psf_log_printf (psf, " %M : %d (too big)\n", marker, chunk_size) ;
return SFE_INTERNAL ;
} ;
cptr = ubuf.cbuf ;
psf_binheader_readf (psf, "b", cptr, chunk_size + (chunk_size & 1)) ;
cptr [chunk_size] = 0 ;
psf_log_printf (psf, " %M : %s\n", marker, cptr) ;
psf_store_string (psf, SF_STR_COMMENT, cptr) ;
chunk_size += chunk_size & 1 ;
break ;
case INST_MARKER :
if (chunk_size != SIZEOF_INST_CHUNK)
{ psf_log_printf (psf, " %M : %d (should be %d)\n", marker, chunk_size, SIZEOF_INST_CHUNK) ;
psf_binheader_readf (psf, "j", chunk_size) ;
break ;
} ;
psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
{ uint8_t bytes [6] ;
int16_t gain ;
if (psf->instrument == NULL && (psf->instrument = psf_instrument_alloc ()) == NULL)
return SFE_MALLOC_FAILED ;
psf_binheader_readf (psf, "b", bytes, 6) ;
psf_log_printf (psf, " Base Note : %u\n Detune : %u\n"
" Low Note : %u\n High Note : %u\n"
" Low Vel. : %u\n High Vel. : %u\n",
bytes [0], bytes [1], bytes [2], bytes [3], bytes [4], bytes [5]) ;
psf->instrument->basenote = bytes [0] ;
psf->instrument->detune = bytes [1] ;
psf->instrument->key_lo = bytes [2] ;
psf->instrument->key_hi = bytes [3] ;
psf->instrument->velocity_lo = bytes [4] ;
psf->instrument->velocity_hi = bytes [5] ;
psf_binheader_readf (psf, "E2", &gain) ;
psf->instrument->gain = gain ;
psf_log_printf (psf, " Gain (dB) : %d\n", gain) ;
} ;
{ int16_t mode ; /* 0 - no loop, 1 - forward looping, 2 - backward looping */
const char *loop_mode ;
uint16_t begin, end ;
psf_binheader_readf (psf, "E222", &mode, &begin, &end) ;
loop_mode = get_loop_mode_str (mode) ;
mode = get_loop_mode (mode) ;
if (mode == SF_LOOP_NONE)
{ psf->instrument->loop_count = 0 ;
psf->instrument->loops [0].mode = SF_LOOP_NONE ;
}
else
{ psf->instrument->loop_count = 1 ;
psf->instrument->loops [0].mode = SF_LOOP_FORWARD ;
psf->instrument->loops [0].start = begin ;
psf->instrument->loops [0].end = end ;
psf->instrument->loops [0].count = 0 ;
} ;
psf_log_printf (psf, " Sustain\n mode : %d => %s\n begin : %u\n end : %u\n",
mode, loop_mode, begin, end) ;
psf_binheader_readf (psf, "E222", &mode, &begin, &end) ;
loop_mode = get_loop_mode_str (mode) ;
mode = get_loop_mode (mode) ;
if (mode == SF_LOOP_NONE)
psf->instrument->loops [1].mode = SF_LOOP_NONE ;
else
{ psf->instrument->loop_count += 1 ;
psf->instrument->loops [1].mode = SF_LOOP_FORWARD ;
psf->instrument->loops [1].start = begin ;
psf->instrument->loops [1].end = end ;
psf->instrument->loops [1].count = 0 ;
} ;
psf_log_printf (psf, " Release\n mode : %d => %s\n begin : %u\n end : %u\n",
mode, loop_mode, begin, end) ;
} ;
instr_found++ ;
break ;
case basc_MARKER :
psf_log_printf (psf, " basc : %u\n", chunk_size) ;
if ((error = aiff_read_basc_chunk (psf, chunk_size)))
return error ;
break ;
case MARK_MARKER :
psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
{ uint16_t mark_id, n = 0 ;
uint32_t position ;
bytesread = psf_binheader_readf (psf, "E2", &n) ;
mark_count = n ;
psf_log_printf (psf, " Count : %u\n", mark_count) ;
if (paiff->markstr != NULL)
{ psf_log_printf (psf, "*** Second MARK chunk found. Throwing away the first.\n") ;
free (paiff->markstr) ;
} ;
paiff->markstr = calloc (mark_count, sizeof (MARK_ID_POS)) ;
if (paiff->markstr == NULL)
return SFE_MALLOC_FAILED ;
if (mark_count > 1000)
{ psf_log_printf (psf, " More than 1000 markers, skipping!\n") ;
psf_binheader_readf (psf, "j", chunk_size - bytesread) ;
break ;
} ;
if ((psf->cues = psf_cues_alloc (mark_count)) == NULL)
return SFE_MALLOC_FAILED ;
for (n = 0 ; n < mark_count && bytesread < chunk_size ; n++)
{ uint32_t pstr_len ;
uint8_t ch ;
bytesread += psf_binheader_readf (psf, "E241", &mark_id, &position, &ch) ;
psf_log_printf (psf, " Mark ID : %u\n Position : %u\n", mark_id, position) ;
psf->cues->cue_points [n].indx = mark_id ;
psf->cues->cue_points [n].position = 0 ;
psf->cues->cue_points [n].fcc_chunk = MAKE_MARKER ('d', 'a', 't', 'a') ; /* always data */
psf->cues->cue_points [n].chunk_start = 0 ;
psf->cues->cue_points [n].block_start = 0 ;
psf->cues->cue_points [n].sample_offset = position ;
pstr_len = (ch & 1) ? ch : ch + 1 ;
if (pstr_len < sizeof (ubuf.scbuf) - 1)
{ bytesread += psf_binheader_readf (psf, "b", ubuf.scbuf, pstr_len) ;
ubuf.scbuf [pstr_len] = 0 ;
}
else
{ uint32_t read_len = pstr_len - (sizeof (ubuf.scbuf) - 1) ;
bytesread += psf_binheader_readf (psf, "bj", ubuf.scbuf, read_len, pstr_len - read_len) ;
ubuf.scbuf [sizeof (ubuf.scbuf) - 1] = 0 ;
}
psf_log_printf (psf, " Name : %s\n", ubuf.scbuf) ;
psf_strlcpy (psf->cues->cue_points [n].name, sizeof (psf->cues->cue_points [n].name), ubuf.cbuf) ;
paiff->markstr [n].markerID = mark_id ;
paiff->markstr [n].position = position ;
/*
** TODO if ubuf.scbuf is equal to
** either Beg_loop, Beg loop or beg loop and spam
** if (psf->instrument == NULL && (psf->instrument = psf_instrument_alloc ()) == NULL)
** return SFE_MALLOC_FAILED ;
*/
} ;
} ;
mark_found++ ;
psf_binheader_readf (psf, "j", chunk_size - bytesread) ;
break ;
case FVER_MARKER :
found_chunk |= HAVE_FVER ;
/* Fall through to next case. */
case SFX_MARKER :
psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
psf_binheader_readf (psf, "j", chunk_size) ;
break ;
case NONE_MARKER :
/* Fix for broken AIFC files with incorrect COMM chunk length. */
chunk_size = (chunk_size >> 24) - 3 ;
psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
psf_binheader_readf (psf, "j", make_size_t (chunk_size)) ;
break ;
case CHAN_MARKER :
if (chunk_size < 12)
{ psf_log_printf (psf, " %M : %d (should be >= 12)\n", marker, chunk_size) ;
psf_binheader_readf (psf, "j", chunk_size) ;
break ;
}
psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
if ((error = aiff_read_chanmap (psf, chunk_size)))
return error ;
break ;
default :
if (chunk_size >= 0xffff0000)
{ done = SF_TRUE ;
psf_log_printf (psf, "*** Unknown chunk marker (%X) at position %D with length %u. Exiting parser.\n", marker, psf_ftell (psf) - 8, chunk_size) ;
break ;
} ;
if (psf_isprint ((marker >> 24) & 0xFF) && psf_isprint ((marker >> 16) & 0xFF)
&& psf_isprint ((marker >> 8) & 0xFF) && psf_isprint (marker & 0xFF))
{ psf_log_printf (psf, " %M : %u (unknown marker)\n", marker, chunk_size) ;
psf_binheader_readf (psf, "j", chunk_size) ;
break ;
} ;
if (psf_ftell (psf) & 0x03)
{ psf_log_printf (psf, " Unknown chunk marker at position %D. Resynching.\n", psf_ftell (psf) - 8) ;
psf_binheader_readf (psf, "j", -3) ;
break ;
} ;
psf_log_printf (psf, "*** Unknown chunk marker %X at position %D. Exiting parser.\n", marker, psf_ftell (psf)) ;
done = SF_TRUE ;
break ;
} ; /* switch (marker) */
if (chunk_size >= psf->filelength)
{ psf_log_printf (psf, "*** Chunk size %u > file length %D. Exiting parser.\n", chunk_size, psf->filelength) ;
break ;
} ;
if ((! psf->sf.seekable) && (found_chunk & HAVE_SSND))
break ;
if (psf_ftell (psf) >= psf->filelength - (2 * SIGNED_SIZEOF (int32_t)))
break ;
} ; /* while (1) */
if (instr_found && mark_found)
{ int ji, str_index ;
/* Next loop will convert markers to loop positions for internal handling */
for (ji = 0 ; ji < psf->instrument->loop_count ; ji ++)
{ if (ji < ARRAY_LEN (psf->instrument->loops))
{ psf->instrument->loops [ji].start = marker_to_position (paiff->markstr, psf->instrument->loops [ji].start, mark_count) ;
psf->instrument->loops [ji].end = marker_to_position (paiff->markstr, psf->instrument->loops [ji].end, mark_count) ;
psf->instrument->loops [ji].mode = SF_LOOP_FORWARD ;
} ;
} ;
/* The markers that correspond to loop positions can now be removed from cues struct */
if (psf->cues->cue_count > (uint32_t) (psf->instrument->loop_count * 2))
{ uint32_t j ;
for (j = 0 ; j < psf->cues->cue_count - (uint32_t) (psf->instrument->loop_count * 2) ; j ++)
{ /* This simply copies the information in cues above loop positions and writes it at current count instead */
psf->cues->cue_points [j].indx = psf->cues->cue_points [j + psf->instrument->loop_count * 2].indx ;
psf->cues->cue_points [j].position = psf->cues->cue_points [j + psf->instrument->loop_count * 2].position ;
psf->cues->cue_points [j].fcc_chunk = psf->cues->cue_points [j + psf->instrument->loop_count * 2].fcc_chunk ;
psf->cues->cue_points [j].chunk_start = psf->cues->cue_points [j + psf->instrument->loop_count * 2].chunk_start ;
psf->cues->cue_points [j].block_start = psf->cues->cue_points [j + psf->instrument->loop_count * 2].block_start ;
psf->cues->cue_points [j].sample_offset = psf->cues->cue_points [j + psf->instrument->loop_count * 2].sample_offset ;
for (str_index = 0 ; str_index < 256 ; str_index++)
psf->cues->cue_points [j].name [str_index] = psf->cues->cue_points [j + psf->instrument->loop_count * 2].name [str_index] ;
} ;
psf->cues->cue_count -= psf->instrument->loop_count * 2 ;
} else
{ /* All the cues were in fact loop positions so we can actually remove the cues altogether */
free (psf->cues) ;
psf->cues = NULL ;
}
} ;
if (psf->sf.channels < 1)
return SFE_CHANNEL_COUNT_ZERO ;
if (psf->sf.channels >= SF_MAX_CHANNELS)
return SFE_CHANNEL_COUNT ;
if (! (found_chunk & HAVE_FORM))
return SFE_AIFF_NO_FORM ;
if (! (found_chunk & HAVE_AIFF))
return SFE_AIFF_COMM_NO_FORM ;
if (! (found_chunk & HAVE_COMM))
return SFE_AIFF_SSND_NO_COMM ;
if (! psf->dataoffset)
return SFE_AIFF_NO_DATA ;
return 0 ;
} /* aiff_read_header */
static int
aiff_close (SF_PRIVATE *psf)
{ AIFF_PRIVATE *paiff = psf->container_data ;
if (paiff != NULL && paiff->markstr != NULL)
{ free (paiff->markstr) ;
paiff->markstr = NULL ;
} ;
if (psf->file.mode == SFM_WRITE || psf->file.mode == SFM_RDWR)
{ aiff_write_tailer (psf) ;
aiff_write_header (psf, SF_TRUE) ;
} ;
return 0 ;
} /* aiff_close */
static int
aiff_read_comm_chunk (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
{ BUF_UNION ubuf ;
int subformat, samplerate ;
ubuf.scbuf [0] = 0 ;
/* The COMM chunk has an int aligned to an odd word boundary. Some
** procesors are not able to deal with this (ie bus fault) so we have
** to take special care.
*/
psf_binheader_readf (psf, "E242b", &(comm_fmt->numChannels), &(comm_fmt->numSampleFrames),
&(comm_fmt->sampleSize), &(comm_fmt->sampleRate), SIGNED_SIZEOF (comm_fmt->sampleRate)) ;
if (comm_fmt->size > 0x10000 && (comm_fmt->size & 0xffff) == 0)
{ psf_log_printf (psf, " COMM : %d (0x%x) *** should be ", comm_fmt->size, comm_fmt->size) ;
comm_fmt->size = ENDSWAP_32 (comm_fmt->size) ;
psf_log_printf (psf, "%d (0x%x)\n", comm_fmt->size, comm_fmt->size) ;
}
else
psf_log_printf (psf, " COMM : %d\n", comm_fmt->size) ;
if (comm_fmt->size == SIZEOF_AIFF_COMM)
comm_fmt->encoding = NONE_MARKER ;
else if (comm_fmt->size == SIZEOF_AIFC_COMM_MIN)
psf_binheader_readf (psf, "Em", &(comm_fmt->encoding)) ;
else if (comm_fmt->size >= SIZEOF_AIFC_COMM)
{ uint8_t encoding_len ;
unsigned read_len ;
psf_binheader_readf (psf, "Em1", &(comm_fmt->encoding), &encoding_len) ;
comm_fmt->size = SF_MIN (sizeof (ubuf.scbuf), make_size_t (comm_fmt->size)) ;
memset (ubuf.scbuf, 0, comm_fmt->size) ;
read_len = comm_fmt->size - SIZEOF_AIFC_COMM + 1 ;
psf_binheader_readf (psf, "b", ubuf.scbuf, read_len) ;
ubuf.scbuf [read_len + 1] = 0 ;
} ;
samplerate = tenbytefloat2int (comm_fmt->sampleRate) ;
psf_log_printf (psf, " Sample Rate : %d\n", samplerate) ;
psf_log_printf (psf, " Frames : %u%s\n", comm_fmt->numSampleFrames, (comm_fmt->numSampleFrames == 0 && psf->filelength > 104) ? " (Should not be 0)" : "") ;
if (comm_fmt->numChannels < 1 || comm_fmt->numChannels >= SF_MAX_CHANNELS)
{ psf_log_printf (psf, " Channels : %d (should be >= 1 and < %d)\n", comm_fmt->numChannels, SF_MAX_CHANNELS) ;
return SFE_CHANNEL_COUNT_BAD ;
} ;
psf_log_printf (psf, " Channels : %d\n", comm_fmt->numChannels) ;
/* Found some broken 'fl32' files with comm.samplesize == 16. Fix it here. */
if ((comm_fmt->encoding == fl32_MARKER || comm_fmt->encoding == FL32_MARKER) && comm_fmt->sampleSize != 32)
{ psf_log_printf (psf, " Sample Size : %d (should be 32)\n", comm_fmt->sampleSize) ;
comm_fmt->sampleSize = 32 ;
}
else if ((comm_fmt->encoding == fl64_MARKER || comm_fmt->encoding == FL64_MARKER) && comm_fmt->sampleSize != 64)
{ psf_log_printf (psf, " Sample Size : %d (should be 64)\n", comm_fmt->sampleSize) ;
comm_fmt->sampleSize = 64 ;
}
else
psf_log_printf (psf, " Sample Size : %d\n", comm_fmt->sampleSize) ;
subformat = s_bitwidth_to_subformat (comm_fmt->sampleSize) ;
psf->sf.samplerate = samplerate ;
psf->sf.frames = comm_fmt->numSampleFrames ;
psf->sf.channels = comm_fmt->numChannels ;
psf->bytewidth = BITWIDTH2BYTES (comm_fmt->sampleSize) ;
psf->endian = SF_ENDIAN_BIG ;
switch (comm_fmt->encoding)
{ case NONE_MARKER :
psf->sf.format = (SF_FORMAT_AIFF | subformat) ;
break ;
case twos_MARKER :
case in24_MARKER :
case in32_MARKER :
psf->sf.format = (SF_ENDIAN_BIG | SF_FORMAT_AIFF | subformat) ;
break ;
case sowt_MARKER :
case ni24_MARKER :
case ni32_MARKER :
psf->endian = SF_ENDIAN_LITTLE ;
psf->sf.format = (SF_ENDIAN_LITTLE | SF_FORMAT_AIFF | subformat) ;
break ;
case fl32_MARKER :
case FL32_MARKER :
psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_FLOAT) ;
break ;
case ulaw_MARKER :
case ULAW_MARKER :
psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_ULAW) ;
break ;
case alaw_MARKER :
case ALAW_MARKER :
psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_ALAW) ;
break ;
case fl64_MARKER :
case FL64_MARKER :
psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_DOUBLE) ;
break ;
case raw_MARKER :
psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_PCM_U8) ;
break ;
case DWVW_MARKER :
psf->sf.format = SF_FORMAT_AIFF ;
switch (comm_fmt->sampleSize)
{ case 12 :
psf->sf.format |= SF_FORMAT_DWVW_12 ;
break ;
case 16 :
psf->sf.format |= SF_FORMAT_DWVW_16 ;
break ;
case 24 :
psf->sf.format |= SF_FORMAT_DWVW_24 ;
break ;
default :
psf->sf.format |= SF_FORMAT_DWVW_N ;
break ;
} ;
break ;
case GSM_MARKER :
psf->sf.format = SF_FORMAT_AIFF ;
psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_GSM610) ;
break ;
case ima4_MARKER :
psf->endian = SF_ENDIAN_BIG ;
psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_IMA_ADPCM) ;
break ;
default :
psf_log_printf (psf, "AIFC : Unimplemented format : %M\n", comm_fmt->encoding) ;
return SFE_UNIMPLEMENTED ;
} ;
if (! ubuf.scbuf [0])
psf_log_printf (psf, " Encoding : %M\n", comm_fmt->encoding) ;
else
psf_log_printf (psf, " Encoding : %M => %s\n", comm_fmt->encoding, ubuf.scbuf) ;
return 0 ;
} /* aiff_read_comm_chunk */
/*==========================================================================================
*/
static void
aiff_rewrite_header (SF_PRIVATE *psf)
{
/* Assuming here that the header has already been written and just
** needs to be corrected for new data length. That means that we
** only change the length fields of the FORM and SSND chunks ;
** everything else can be skipped over.
*/
int k, ch, comm_size, comm_frames ;
psf_fseek (psf, 0, SEEK_SET) ;
psf_fread (psf->header.ptr, psf->dataoffset, 1, psf) ;
psf->header.indx = 0 ;
/* FORM chunk. */
psf_binheader_writef (psf, "Etm8", FORM_MARKER, psf->filelength - 8) ;
/* COMM chunk. */
if ((k = psf_find_read_chunk_m32 (&psf->rchunks, COMM_MARKER)) >= 0)
{ psf->header.indx = psf->rchunks.chunks [k].offset - 8 ;
comm_frames = psf->sf.frames ;
comm_size = psf->rchunks.chunks [k].len ;
psf_binheader_writef (psf, "Em42t4", COMM_MARKER, comm_size, psf->sf.channels, comm_frames) ;
} ;
/* PEAK chunk. */
if ((k = psf_find_read_chunk_m32 (&psf->rchunks, PEAK_MARKER)) >= 0)
{ psf->header.indx = psf->rchunks.chunks [k].offset - 8 ;
psf_binheader_writef (psf, "Em4", PEAK_MARKER, AIFF_PEAK_CHUNK_SIZE (psf->sf.channels)) ;
psf_binheader_writef (psf, "E44", 1, time (NULL)) ;
for (ch = 0 ; ch < psf->sf.channels ; ch++)
psf_binheader_writef (psf, "Eft8", (float) psf->peak_info->peaks [ch].value, psf->peak_info->peaks [ch].position) ;
} ;
/* SSND chunk. */
if ((k = psf_find_read_chunk_m32 (&psf->rchunks, SSND_MARKER)) >= 0)
{ psf->header.indx = psf->rchunks.chunks [k].offset - 8 ;
psf_binheader_writef (psf, "Etm8", SSND_MARKER, psf->datalength + SIZEOF_SSND_CHUNK) ;
} ;
/* Header mangling complete so write it out. */
psf_fseek (psf, 0, SEEK_SET) ;
psf_fwrite (psf->header.ptr, psf->header.indx, 1, psf) ;
return ;
} /* aiff_rewrite_header */
static int
aiff_write_header (SF_PRIVATE *psf, int calc_length)
{ sf_count_t current ;
AIFF_PRIVATE *paiff ;
uint8_t comm_sample_rate [10], comm_zero_bytes [2] = { 0, 0 } ;
uint32_t comm_type, comm_size, comm_encoding, comm_frames = 0, uk ;
int k, endian, has_data = SF_FALSE ;
int16_t bit_width ;
if ((paiff = psf->container_data) == NULL)
return SFE_INTERNAL ;
current = psf_ftell (psf) ;
if (current > psf->dataoffset)
has_data = SF_TRUE ;
if (calc_length)
{ psf->filelength = psf_get_filelen (psf) ;
psf->datalength = psf->filelength - psf->dataoffset ;
if (psf->dataend)
psf->datalength -= psf->filelength - psf->dataend ;
if (psf->bytewidth > 0)
psf->sf.frames = psf->datalength / (psf->bytewidth * psf->sf.channels) ;
} ;
if (psf->file.mode == SFM_RDWR && psf->dataoffset > 0 && psf->rchunks.count > 0)
{ aiff_rewrite_header (psf) ;
if (current > 0)
psf_fseek (psf, current, SEEK_SET) ;
return 0 ;
} ;
endian = SF_ENDIAN (psf->sf.format) ;
if (CPU_IS_LITTLE_ENDIAN && endian == SF_ENDIAN_CPU)
endian = SF_ENDIAN_LITTLE ;
/* Standard value here. */
bit_width = psf->bytewidth * 8 ;
comm_frames = (psf->sf.frames > 0xFFFFFFFF) ? 0xFFFFFFFF : psf->sf.frames ;
switch (SF_CODEC (psf->sf.format) | endian)
{ case SF_FORMAT_PCM_S8 | SF_ENDIAN_BIG :
psf->endian = SF_ENDIAN_BIG ;
comm_type = AIFC_MARKER ;
comm_size = SIZEOF_AIFC_COMM ;
comm_encoding = twos_MARKER ;
break ;
case SF_FORMAT_PCM_S8 | SF_ENDIAN_LITTLE :
psf->endian = SF_ENDIAN_LITTLE ;
comm_type = AIFC_MARKER ;
comm_size = SIZEOF_AIFC_COMM ;
comm_encoding = sowt_MARKER ;
break ;
case SF_FORMAT_PCM_16 | SF_ENDIAN_BIG :
psf->endian = SF_ENDIAN_BIG ;
comm_type = AIFC_MARKER ;
comm_size = SIZEOF_AIFC_COMM ;
comm_encoding = twos_MARKER ;
break ;
case SF_FORMAT_PCM_16 | SF_ENDIAN_LITTLE :
psf->endian = SF_ENDIAN_LITTLE ;
comm_type = AIFC_MARKER ;
comm_size = SIZEOF_AIFC_COMM ;
comm_encoding = sowt_MARKER ;
break ;
case SF_FORMAT_PCM_24 | SF_ENDIAN_BIG :
psf->endian = SF_ENDIAN_BIG ;
comm_type = AIFC_MARKER ;
comm_size = SIZEOF_AIFC_COMM ;
comm_encoding = in24_MARKER ;
break ;
case SF_FORMAT_PCM_24 | SF_ENDIAN_LITTLE :
psf->endian = SF_ENDIAN_LITTLE ;
comm_type = AIFC_MARKER ;
comm_size = SIZEOF_AIFC_COMM ;
comm_encoding = ni24_MARKER ;
break ;
case SF_FORMAT_PCM_32 | SF_ENDIAN_BIG :
psf->endian = SF_ENDIAN_BIG ;
comm_type = AIFC_MARKER ;
comm_size = SIZEOF_AIFC_COMM ;
comm_encoding = in32_MARKER ;
break ;
case SF_FORMAT_PCM_32 | SF_ENDIAN_LITTLE :
psf->endian = SF_ENDIAN_LITTLE ;
comm_type = AIFC_MARKER ;
comm_size = SIZEOF_AIFC_COMM ;
comm_encoding = ni32_MARKER ;
break ;
case SF_FORMAT_PCM_S8 : /* SF_ENDIAN_FILE */
case SF_FORMAT_PCM_16 :
case SF_FORMAT_PCM_24 :
case SF_FORMAT_PCM_32 :
psf->endian = SF_ENDIAN_BIG ;
comm_type = AIFF_MARKER ;
comm_size = SIZEOF_AIFF_COMM ;
comm_encoding = 0 ;
break ;
case SF_FORMAT_FLOAT : /* Big endian floating point. */
psf->endian = SF_ENDIAN_BIG ;
comm_type = AIFC_MARKER ;
comm_size = SIZEOF_AIFC_COMM ;
comm_encoding = FL32_MARKER ; /* Use 'FL32' because its easier to read. */
break ;
case SF_FORMAT_DOUBLE : /* Big endian double precision floating point. */
psf->endian = SF_ENDIAN_BIG ;
comm_type = AIFC_MARKER ;
comm_size = SIZEOF_AIFC_COMM ;
comm_encoding = FL64_MARKER ; /* Use 'FL64' because its easier to read. */
break ;
case SF_FORMAT_ULAW :
psf->endian = SF_ENDIAN_BIG ;
comm_type = AIFC_MARKER ;
comm_size = SIZEOF_AIFC_COMM ;
comm_encoding = ulaw_MARKER ;
break ;
case SF_FORMAT_ALAW :
psf->endian = SF_ENDIAN_BIG ;
comm_type = AIFC_MARKER ;
comm_size = SIZEOF_AIFC_COMM ;
comm_encoding = alaw_MARKER ;
break ;
case SF_FORMAT_PCM_U8 :
psf->endian = SF_ENDIAN_BIG ;
comm_type = AIFC_MARKER ;
comm_size = SIZEOF_AIFC_COMM ;
comm_encoding = raw_MARKER ;
break ;
case SF_FORMAT_DWVW_12 :
psf->endian = SF_ENDIAN_BIG ;
comm_type = AIFC_MARKER ;
comm_size = SIZEOF_AIFC_COMM ;
comm_encoding = DWVW_MARKER ;
/* Override standard value here.*/
bit_width = 12 ;
break ;
case SF_FORMAT_DWVW_16 :
psf->endian = SF_ENDIAN_BIG ;
comm_type = AIFC_MARKER ;
comm_size = SIZEOF_AIFC_COMM ;
comm_encoding = DWVW_MARKER ;
/* Override standard value here.*/
bit_width = 16 ;
break ;
case SF_FORMAT_DWVW_24 :
psf->endian = SF_ENDIAN_BIG ;
comm_type = AIFC_MARKER ;
comm_size = SIZEOF_AIFC_COMM ;
comm_encoding = DWVW_MARKER ;
/* Override standard value here.*/
bit_width = 24 ;
break ;
case SF_FORMAT_GSM610 :
psf->endian = SF_ENDIAN_BIG ;
comm_type = AIFC_MARKER ;
comm_size = SIZEOF_AIFC_COMM ;
comm_encoding = GSM_MARKER ;
/* Override standard value here.*/
bit_width = 16 ;
break ;
case SF_FORMAT_IMA_ADPCM :
psf->endian = SF_ENDIAN_BIG ;
comm_type = AIFC_MARKER ;
comm_size = SIZEOF_AIFC_COMM ;
comm_encoding = ima4_MARKER ;
/* Override standard value here.*/
bit_width = 16 ;
comm_frames = psf->sf.frames / AIFC_IMA4_SAMPLES_PER_BLOCK ;
break ;
default : return SFE_BAD_OPEN_FORMAT ;
} ;
/* Reset the current header length to zero. */
psf->header.ptr [0] = 0 ;
psf->header.indx = 0 ;
psf_fseek (psf, 0, SEEK_SET) ;
psf_binheader_writef (psf, "Etm8", FORM_MARKER, psf->filelength - 8) ;
/* Write AIFF/AIFC marker and COM chunk. */
if (comm_type == AIFC_MARKER)
/* AIFC must have an FVER chunk. */
psf_binheader_writef (psf, "Emm44", comm_type, FVER_MARKER, 4, 0xA2805140) ;
else
psf_binheader_writef (psf, "Em", comm_type) ;
paiff->comm_offset = psf->header.indx - 8 ;
memset (comm_sample_rate, 0, sizeof (comm_sample_rate)) ;
uint2tenbytefloat (psf->sf.samplerate, comm_sample_rate) ;
psf_binheader_writef (psf, "Em42t42", COMM_MARKER, comm_size, psf->sf.channels, comm_frames, bit_width) ;
psf_binheader_writef (psf, "b", comm_sample_rate, sizeof (comm_sample_rate)) ;
/* AIFC chunks have some extra data. */
if (comm_type == AIFC_MARKER)
psf_binheader_writef (psf, "mb", comm_encoding, comm_zero_bytes, sizeof (comm_zero_bytes)) ;
if (psf->channel_map && paiff->chanmap_tag)
psf_binheader_writef (psf, "Em4444", CHAN_MARKER, 12, paiff->chanmap_tag, 0, 0) ;
/* Check if there's a INST chunk to write */
if (psf->instrument != NULL && psf->cues != NULL)
{ /* Huge chunk of code removed here because it had egregious errors that were
** not detected by either the compiler or the tests. It was found when updating
** the way psf_binheader_writef works.
*/
}
else if (psf->instrument == NULL && psf->cues != NULL)
{ /* There are cues but no loops */
uint32_t idx ;
int totalStringLength = 0, stringLength ;
/* Here we count how many bytes will the pascal strings need */
for (idx = 0 ; idx < psf->cues->cue_count ; idx++)
{ stringLength = strlen (psf->cues->cue_points [idx].name) + 1 ; /* We'll count the first byte also of every pascal string */
totalStringLength += stringLength + (stringLength % 2 == 0 ? 0 : 1) ;
} ;
psf_binheader_writef (psf, "Em42",
MARK_MARKER, 2 + psf->cues->cue_count * (2 + 4) + totalStringLength, psf->cues->cue_count) ;
for (idx = 0 ; idx < psf->cues->cue_count ; idx++)
psf_binheader_writef (psf, "E24p", psf->cues->cue_points [idx].indx, psf->cues->cue_points [idx].sample_offset, psf->cues->cue_points [idx].name) ;
} ;
if (psf->strings.flags & SF_STR_LOCATE_START)
aiff_write_strings (psf, SF_STR_LOCATE_START) ;
if (psf->peak_info != NULL && psf->peak_info->peak_loc == SF_PEAK_START)
{ psf_binheader_writef (psf, "Em4", PEAK_MARKER, AIFF_PEAK_CHUNK_SIZE (psf->sf.channels)) ;
psf_binheader_writef (psf, "E44", 1, time (NULL)) ;
for (k = 0 ; k < psf->sf.channels ; k++)
psf_binheader_writef (psf, "Eft8", (float) psf->peak_info->peaks [k].value, psf->peak_info->peaks [k].position) ;
} ;
/* Write custom headers. */
for (uk = 0 ; uk < psf->wchunks.used ; uk++)
psf_binheader_writef (psf, "Em4b", psf->wchunks.chunks [uk].mark32, psf->wchunks.chunks [uk].len, psf->wchunks.chunks [uk].data, make_size_t (psf->wchunks.chunks [uk].len)) ;
/* Write SSND chunk. */
paiff->ssnd_offset = psf->header.indx ;
psf_binheader_writef (psf, "Etm844", SSND_MARKER, psf->datalength + SIZEOF_SSND_CHUNK, 0, 0) ;
/* Header construction complete so write it out. */
psf_fwrite (psf->header.ptr, psf->header.indx, 1, psf) ;
if (psf->error)
return psf->error ;
if (has_data && psf->dataoffset != psf->header.indx)
return psf->error = SFE_INTERNAL ;
psf->dataoffset = psf->header.indx ;
if (! has_data)
psf_fseek (psf, psf->dataoffset, SEEK_SET) ;
else if (current > 0)
psf_fseek (psf, current, SEEK_SET) ;
return psf->error ;
} /* aiff_write_header */
static int
aiff_write_tailer (SF_PRIVATE *psf)
{ int k ;
/* Reset the current header length to zero. */
psf->header.ptr [0] = 0 ;
psf->header.indx = 0 ;
psf->dataend = psf_fseek (psf, 0, SEEK_END) ;
/* Make sure tailer data starts at even byte offset. Pad if necessary. */
if (psf->dataend % 2 == 1)
{ psf_fwrite (psf->header.ptr, 1, 1, psf) ;
psf->dataend ++ ;
} ;
if (psf->peak_info != NULL && psf->peak_info->peak_loc == SF_PEAK_END)
{ psf_binheader_writef (psf, "Em4", PEAK_MARKER, AIFF_PEAK_CHUNK_SIZE (psf->sf.channels)) ;
psf_binheader_writef (psf, "E44", 1, time (NULL)) ;
for (k = 0 ; k < psf->sf.channels ; k++)
psf_binheader_writef (psf, "Eft8", (float) psf->peak_info->peaks [k].value, psf->peak_info->peaks [k].position) ;
} ;
if (psf->strings.flags & SF_STR_LOCATE_END)
aiff_write_strings (psf, SF_STR_LOCATE_END) ;
/* Write the tailer. */
if (psf->header.indx > 0)
psf_fwrite (psf->header.ptr, psf->header.indx, 1, psf) ;
return 0 ;
} /* aiff_write_tailer */
static void
aiff_write_strings (SF_PRIVATE *psf, int location)
{ int k, slen ;
for (k = 0 ; k < SF_MAX_STRINGS ; k++)
{ if (psf->strings.data [k].type == 0)
break ;
if (psf->strings.data [k].flags != location)
continue ;
switch (psf->strings.data [k].type)
{ case SF_STR_SOFTWARE :
slen = strlen (psf->strings.storage + psf->strings.data [k].offset) ;
psf_binheader_writef (psf, "Em4mb", APPL_MARKER, slen + 4, m3ga_MARKER, psf->strings.storage + psf->strings.data [k].offset, make_size_t (slen + (slen & 1))) ;
break ;
case SF_STR_TITLE :
psf_binheader_writef (psf, "EmS", NAME_MARKER, psf->strings.storage + psf->strings.data [k].offset) ;
break ;
case SF_STR_COPYRIGHT :
psf_binheader_writef (psf, "EmS", c_MARKER, psf->strings.storage + psf->strings.data [k].offset) ;
break ;
case SF_STR_ARTIST :
psf_binheader_writef (psf, "EmS", AUTH_MARKER, psf->strings.storage + psf->strings.data [k].offset) ;
break ;
case SF_STR_COMMENT :
psf_binheader_writef (psf, "EmS", ANNO_MARKER, psf->strings.storage + psf->strings.data [k].offset) ;
break ;
/*
case SF_STR_DATE :
psf_binheader_writef (psf, "Ems", ICRD_MARKER, psf->strings.data [k].str) ;
break ;
*/
} ;
} ;
return ;
} /* aiff_write_strings */
static int
aiff_command (SF_PRIVATE * psf, int command, void * UNUSED (data), int UNUSED (datasize))
{ AIFF_PRIVATE *paiff ;
if ((paiff = psf->container_data) == NULL)
return SFE_INTERNAL ;
switch (command)
{ case SFC_SET_CHANNEL_MAP_INFO :
paiff->chanmap_tag = aiff_caf_find_channel_layout_tag (psf->channel_map, psf->sf.channels) ;
return (paiff->chanmap_tag != 0) ;
default :
break ;
} ;
return 0 ;
} /* aiff_command */
static const char*
get_loop_mode_str (int16_t mode)
{ switch (mode)
{ case 0 : return "none" ;
case 1 : return "forward" ;
case 2 : return "backward" ;
} ;
return "*** unknown" ;
} /* get_loop_mode_str */
static int16_t
get_loop_mode (int16_t mode)
{ switch (mode)
{ case 0 : return SF_LOOP_NONE ;
case 1 : return SF_LOOP_FORWARD ;
case 2 : return SF_LOOP_BACKWARD ;
} ;
return SF_LOOP_NONE ;
} /* get_loop_mode */
/*==========================================================================================
** Rough hack at converting from 80 bit IEEE float in AIFF header to an int and
** back again. It assumes that all sample rates are between 1 and 800MHz, which
** should be OK as other sound file formats use a 32 bit integer to store sample
** rate.
** There is another (probably better) version in the source code to the SoX but it
** has a copyright which probably prevents it from being allowable as GPL/LGPL.
*/
static int
tenbytefloat2int (uint8_t *bytes)
{ int val = 3 ;
if (bytes [0] & 0x80) /* Negative number. */
return 0 ;
if (bytes [0] <= 0x3F) /* Less than 1. */
return 1 ;
if (bytes [0] > 0x40) /* Way too big. */
return 0x4000000 ;
if (bytes [0] == 0x40 && bytes [1] > 0x1C) /* Too big. */
return 800000000 ;
/* Ok, can handle it. */
val = (bytes [2] << 23) | (bytes [3] << 15) | (bytes [4] << 7) | (bytes [5] >> 1) ;
val >>= (29 - bytes [1]) ;
return val ;
} /* tenbytefloat2int */
static void
uint2tenbytefloat (uint32_t num, uint8_t *bytes)
{ uint32_t mask = 0x40000000 ;
int count ;
if (num <= 1)
{ bytes [0] = 0x3F ;
bytes [1] = 0xFF ;
bytes [2] = 0x80 ;
return ;
} ;
bytes [0] = 0x40 ;
if (num >= mask)
{ bytes [1] = 0x1D ;
return ;
} ;
for (count = 0 ; count < 32 ; count ++)
{ if (num & mask)
break ;
mask >>= 1 ;
} ;
num = count < 31 ? num << (count + 1) : 0 ;
bytes [1] = 29 - count ;
bytes [2] = (num >> 24) & 0xFF ;
bytes [3] = (num >> 16) & 0xFF ;
bytes [4] = (num >> 8) & 0xFF ;
bytes [5] = num & 0xFF ;
} /* uint2tenbytefloat */
static int
aiff_read_basc_chunk (SF_PRIVATE * psf, int datasize)
{ const char * type_str ;
basc_CHUNK bc ;
int count ;
count = psf_binheader_readf (psf, "E442", &bc.version, &bc.numBeats, &bc.rootNote) ;
count += psf_binheader_readf (psf, "E222", &bc.scaleType, &bc.sigNumerator, &bc.sigDenominator) ;
count += psf_binheader_readf (psf, "E2j", &bc.loopType, datasize - sizeof (bc)) ;
psf_log_printf (psf, " Version ? : %u\n Num Beats : %u\n Root Note : 0x%x\n",
bc.version, bc.numBeats, bc.rootNote) ;
switch (bc.scaleType)
{ case basc_SCALE_MINOR :
type_str = "MINOR" ;
break ;
case basc_SCALE_MAJOR :
type_str = "MAJOR" ;
break ;
case basc_SCALE_NEITHER :
type_str = "NEITHER" ;
break ;
case basc_SCALE_BOTH :
type_str = "BOTH" ;
break ;
default :
type_str = "!!WRONG!!" ;
break ;
} ;
psf_log_printf (psf, " ScaleType : 0x%x (%s)\n", bc.scaleType, type_str) ;
psf_log_printf (psf, " Time Sig : %d/%d\n", bc.sigNumerator, bc.sigDenominator) ;
switch (bc.loopType)
{ case basc_TYPE_ONE_SHOT :
type_str = "One Shot" ;
break ;
case basc_TYPE_LOOP :
type_str = "Loop" ;
break ;
default:
type_str = "!!WRONG!!" ;
break ;
} ;
psf_log_printf (psf, " Loop Type : 0x%x (%s)\n", bc.loopType, type_str) ;
if ((psf->loop_info = calloc (1, sizeof (SF_LOOP_INFO))) == NULL)
return SFE_MALLOC_FAILED ;
psf->loop_info->time_sig_num = bc.sigNumerator ;
psf->loop_info->time_sig_den = bc.sigDenominator ;
psf->loop_info->loop_mode = (bc.loopType == basc_TYPE_ONE_SHOT) ? SF_LOOP_NONE : SF_LOOP_FORWARD ;
psf->loop_info->num_beats = bc.numBeats ;
/* Can always be recalculated from other known fields. */
psf->loop_info->bpm = (1.0 / psf->sf.frames) * psf->sf.samplerate
* ((bc.numBeats * 4.0) / bc.sigDenominator) * 60.0 ;
psf->loop_info->root_key = bc.rootNote ;
if (count < datasize)
psf_binheader_readf (psf, "j", datasize - count) ;
return 0 ;
} /* aiff_read_basc_chunk */
static int
aiff_read_chanmap (SF_PRIVATE * psf, unsigned dword)
{ const AIFF_CAF_CHANNEL_MAP * map_info ;
unsigned channel_bitmap, channel_decriptions, bytesread ;
int layout_tag ;
bytesread = psf_binheader_readf (psf, "444", &layout_tag, &channel_bitmap, &channel_decriptions) ;
if ((map_info = aiff_caf_of_channel_layout_tag (layout_tag)) == NULL)
return 0 ;
psf_log_printf (psf, " Tag : %x\n", layout_tag) ;
if (map_info)
psf_log_printf (psf, " Layout : %s\n", map_info->name) ;
if (bytesread < dword)
psf_binheader_readf (psf, "j", dword - bytesread) ;
if (map_info->channel_map != NULL)
{ size_t chanmap_size = psf->sf.channels * sizeof (psf->channel_map [0]) ;
free (psf->channel_map) ;
if ((psf->channel_map = malloc (chanmap_size)) == NULL)
return SFE_MALLOC_FAILED ;
memcpy (psf->channel_map, map_info->channel_map, chanmap_size) ;
} ;
return 0 ;
} /* aiff_read_chanmap */
/*==============================================================================
*/
static int
aiff_set_chunk (SF_PRIVATE *psf, const SF_CHUNK_INFO * chunk_info)
{ return psf_save_write_chunk (&psf->wchunks, chunk_info) ;
} /* aiff_set_chunk */
static SF_CHUNK_ITERATOR *
aiff_next_chunk_iterator (SF_PRIVATE *psf, SF_CHUNK_ITERATOR * iterator)
{ return psf_next_chunk_iterator (&psf->rchunks, iterator) ;
} /* aiff_next_chunk_iterator */
static int
aiff_get_chunk_size (SF_PRIVATE *psf, const SF_CHUNK_ITERATOR * iterator, SF_CHUNK_INFO * chunk_info)
{ int indx ;
if ((indx = psf_find_read_chunk_iterator (&psf->rchunks, iterator)) < 0)
return SFE_UNKNOWN_CHUNK ;
chunk_info->datalen = psf->rchunks.chunks [indx].len ;
return SFE_NO_ERROR ;
} /* aiff_get_chunk_size */
static int
aiff_get_chunk_data (SF_PRIVATE *psf, const SF_CHUNK_ITERATOR * iterator, SF_CHUNK_INFO * chunk_info)
{ sf_count_t pos ;
int indx ;
if ((indx = psf_find_read_chunk_iterator (&psf->rchunks, iterator)) < 0)
return SFE_UNKNOWN_CHUNK ;
if (chunk_info->data == NULL)
return SFE_BAD_CHUNK_DATA_PTR ;
chunk_info->id_size = psf->rchunks.chunks [indx].id_size ;
memcpy (chunk_info->id, psf->rchunks.chunks [indx].id, sizeof (chunk_info->id) / sizeof (*chunk_info->id)) ;
pos = psf_ftell (psf) ;
psf_fseek (psf, psf->rchunks.chunks [indx].offset, SEEK_SET) ;
psf_fread (chunk_info->data, SF_MIN (chunk_info->datalen, psf->rchunks.chunks [indx].len), 1, psf) ;
psf_fseek (psf, pos, SEEK_SET) ;
return SFE_NO_ERROR ;
} /* aiff_get_chunk_data */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3227_0 |
crossvul-cpp_data_bad_2211_0 | /*
* Copyright 2011-2013 Con Kolivas
* Copyright 2010 Jeff Garzik
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version. See COPYING for more details.
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include <string.h>
#include <jansson.h>
#ifdef HAVE_LIBCURL
#include <curl/curl.h>
#endif
#include <time.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#ifndef WIN32
#include <fcntl.h>
# ifdef __linux__
# include <sys/prctl.h>
# endif
# include <sys/socket.h>
# include <netinet/in.h>
# include <netinet/tcp.h>
# include <netdb.h>
#else
# include <windows.h>
# include <winsock2.h>
# include <ws2tcpip.h>
# include <mmsystem.h>
#endif
#include "miner.h"
#include "elist.h"
#include "compat.h"
#include "util.h"
#include "pool.h"
#define DEFAULT_SOCKWAIT 60
extern double opt_diff_mult;
bool successful_connect = false;
static void keep_sockalive(SOCKETTYPE fd)
{
const int tcp_one = 1;
#ifndef WIN32
const int tcp_keepidle = 45;
const int tcp_keepintvl = 30;
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, O_NONBLOCK | flags);
#else
u_long flags = 1;
ioctlsocket(fd, FIONBIO, &flags);
#endif
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&tcp_one, sizeof(tcp_one));
if (!opt_delaynet)
#ifndef __linux
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char *)&tcp_one, sizeof(tcp_one));
#else /* __linux */
setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one));
setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_one, sizeof(tcp_one));
setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle));
setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl));
#endif /* __linux__ */
#ifdef __APPLE_CC__
setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl));
#endif /* __APPLE_CC__ */
}
struct tq_ent {
void *data;
struct list_head q_node;
};
#ifdef HAVE_LIBCURL
struct timeval nettime;
struct data_buffer {
void *buf;
size_t len;
};
struct upload_buffer {
const void *buf;
size_t len;
};
struct header_info {
char *lp_path;
int rolltime;
char *reason;
char *stratum_url;
bool hadrolltime;
bool canroll;
bool hadexpire;
};
static void databuf_free(struct data_buffer *db)
{
if (!db)
return;
free(db->buf);
memset(db, 0, sizeof(*db));
}
static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
void *user_data)
{
struct data_buffer *db = (struct data_buffer *)user_data;
size_t len = size * nmemb;
size_t oldlen, newlen;
void *newmem;
static const unsigned char zero = 0;
oldlen = db->len;
newlen = oldlen + len;
newmem = realloc(db->buf, newlen + 1);
if (!newmem)
return 0;
db->buf = newmem;
db->len = newlen;
memcpy((uint8_t*)db->buf + oldlen, ptr, len);
memcpy((uint8_t*)db->buf + newlen, &zero, 1); /* null terminate */
return len;
}
static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
void *user_data)
{
struct upload_buffer *ub = (struct upload_buffer *)user_data;
unsigned int len = size * nmemb;
if (len > ub->len)
len = ub->len;
if (len) {
memcpy(ptr, ub->buf, len);
ub->buf = (uint8_t*)ub->buf + len;
ub->len -= len;
}
return len;
}
static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
{
struct header_info *hi = (struct header_info *)user_data;
size_t remlen, slen, ptrlen = size * nmemb;
char *rem, *val = NULL, *key = NULL;
void *tmp;
val = (char *)calloc(1, ptrlen);
key = (char *)calloc(1, ptrlen);
if (!key || !val)
goto out;
tmp = memchr(ptr, ':', ptrlen);
if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
goto out;
slen = (uint8_t*)tmp - (uint8_t*)ptr;
if ((slen + 1) == ptrlen) /* skip key w/ no value */
goto out;
memcpy(key, ptr, slen); /* store & nul term key */
key[slen] = 0;
rem = (char*)ptr + slen + 1; /* trim value's leading whitespace */
remlen = ptrlen - slen - 1;
while ((remlen > 0) && (isspace(*rem))) {
remlen--;
rem++;
}
memcpy(val, rem, remlen); /* store value, trim trailing ws */
val[remlen] = 0;
while ((*val) && (isspace(val[strlen(val) - 1])))
val[strlen(val) - 1] = 0;
if (!*val) /* skip blank value */
goto out;
if (opt_protocol)
applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
if (!strcasecmp("X-Roll-Ntime", key)) {
hi->hadrolltime = true;
if (!strncasecmp("N", val, 1))
applog(LOG_DEBUG, "X-Roll-Ntime: N found");
else {
hi->canroll = true;
/* Check to see if expire= is supported and if not, set
* the rolltime to the default scantime */
if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
sscanf(val + 7, "%d", &hi->rolltime);
hi->hadexpire = true;
} else
hi->rolltime = opt_scantime;
applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
}
}
if (!strcasecmp("X-Long-Polling", key)) {
hi->lp_path = val; /* steal memory reference */
val = NULL;
}
if (!strcasecmp("X-Reject-Reason", key)) {
hi->reason = val; /* steal memory reference */
val = NULL;
}
if (!strcasecmp("X-Stratum", key)) {
hi->stratum_url = val;
val = NULL;
}
out:
free(key);
free(val);
return ptrlen;
}
static void last_nettime(struct timeval *last)
{
rd_lock(&netacc_lock);
last->tv_sec = nettime.tv_sec;
last->tv_usec = nettime.tv_usec;
rd_unlock(&netacc_lock);
}
static void set_nettime(void)
{
wr_lock(&netacc_lock);
cgtime(&nettime);
wr_unlock(&netacc_lock);
}
#if CURL_HAS_KEEPALIVE
static void keep_curlalive(CURL *curl)
{
const long int keepalive = 1;
curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, keepalive);
curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, opt_tcp_keepalive);
curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, opt_tcp_keepalive);
}
#else
static void keep_curlalive(CURL *curl)
{
SOCKETTYPE sock;
curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&sock);
keep_sockalive(sock);
}
#endif
static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
__maybe_unused char *data, size_t size, void *userdata)
{
struct pool *pool = (struct pool *)userdata;
switch(type) {
case CURLINFO_HEADER_IN:
case CURLINFO_DATA_IN:
case CURLINFO_SSL_DATA_IN:
pool->sgminer_pool_stats.net_bytes_received += size;
break;
case CURLINFO_HEADER_OUT:
case CURLINFO_DATA_OUT:
case CURLINFO_SSL_DATA_OUT:
pool->sgminer_pool_stats.net_bytes_sent += size;
break;
case CURLINFO_TEXT:
default:
break;
}
return 0;
}
json_t *json_rpc_call(CURL *curl, const char *url,
const char *userpass, const char *rpc_req,
bool probe, bool longpoll, int *rolltime,
struct pool *pool, bool share)
{
long timeout = longpoll ? (60 * 60) : 60;
struct data_buffer all_data = {NULL, 0};
struct header_info hi = {NULL, 0, NULL, NULL, false, false, false};
char len_hdr[64], user_agent_hdr[128];
char curl_err_str[CURL_ERROR_SIZE];
struct curl_slist *headers = NULL;
struct upload_buffer upload_data;
json_t *val, *err_val, *res_val;
bool probing = false;
double byte_count;
json_error_t err;
int rc;
memset(&err, 0, sizeof(err));
/* it is assumed that 'curl' is freshly [re]initialized at this pt */
if (probe)
probing = !pool->probed;
curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
// CURLOPT_VERBOSE won't write to stderr if we use CURLOPT_DEBUGFUNCTION
curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_ENCODING, "");
curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
/* Shares are staggered already and delays in submission can be costly
* so do not delay them */
if (!opt_delaynet || share)
curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
if (pool->rpc_proxy) {
curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype);
} else if (opt_socks_proxy) {
curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
}
if (userpass) {
curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
}
if (longpoll)
keep_curlalive(curl);
curl_easy_setopt(curl, CURLOPT_POST, 1);
if (opt_protocol)
applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
upload_data.buf = rpc_req;
upload_data.len = strlen(rpc_req);
sprintf(len_hdr, "Content-Length: %lu",
(unsigned long) upload_data.len);
sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
headers = curl_slist_append(headers,
"Content-type: application/json");
headers = curl_slist_append(headers,
"X-Mining-Extensions: longpoll midstate rollntime submitold");
if (likely(global_hashrate)) {
char ghashrate[255];
sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate);
headers = curl_slist_append(headers, ghashrate);
}
headers = curl_slist_append(headers, len_hdr);
headers = curl_slist_append(headers, user_agent_hdr);
headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
if (opt_delaynet) {
/* Don't delay share submission, but still track the nettime */
if (!share) {
long long now_msecs, last_msecs;
struct timeval now, last;
cgtime(&now);
last_nettime(&last);
now_msecs = (long long)now.tv_sec * 1000;
now_msecs += now.tv_usec / 1000;
last_msecs = (long long)last.tv_sec * 1000;
last_msecs += last.tv_usec / 1000;
if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
struct timespec rgtp;
rgtp.tv_sec = 0;
rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
nanosleep(&rgtp, NULL);
}
}
set_nettime();
}
rc = curl_easy_perform(curl);
if (rc) {
applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
goto err_out;
}
if (!all_data.buf) {
applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
goto err_out;
}
pool->sgminer_pool_stats.times_sent++;
if (curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &byte_count) == CURLE_OK)
pool->sgminer_pool_stats.bytes_sent += byte_count;
pool->sgminer_pool_stats.times_received++;
if (curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &byte_count) == CURLE_OK)
pool->sgminer_pool_stats.bytes_received += byte_count;
if (probing) {
pool->probed = true;
/* If X-Long-Polling was found, activate long polling */
if (hi.lp_path) {
if (pool->hdr_path != NULL)
free(pool->hdr_path);
pool->hdr_path = hi.lp_path;
} else
pool->hdr_path = NULL;
if (hi.stratum_url) {
pool->stratum_url = hi.stratum_url;
hi.stratum_url = NULL;
}
} else {
if (hi.lp_path) {
free(hi.lp_path);
hi.lp_path = NULL;
}
if (hi.stratum_url) {
free(hi.stratum_url);
hi.stratum_url = NULL;
}
}
*rolltime = hi.rolltime;
pool->sgminer_pool_stats.rolltime = hi.rolltime;
pool->sgminer_pool_stats.hadrolltime = hi.hadrolltime;
pool->sgminer_pool_stats.canroll = hi.canroll;
pool->sgminer_pool_stats.hadexpire = hi.hadexpire;
val = JSON_LOADS((const char *)all_data.buf, &err);
if (!val) {
applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
if (opt_protocol)
applog(LOG_DEBUG, "JSON protocol response:\n%s", (char *)(all_data.buf));
goto err_out;
}
if (opt_protocol) {
char *s = json_dumps(val, JSON_INDENT(3));
applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
free(s);
}
/* JSON-RPC valid response returns a non-null 'result',
* and a null 'error'.
*/
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val ||(err_val && !json_is_null(err_val))) {
char *s;
if (err_val)
s = json_dumps(err_val, JSON_INDENT(3));
else
s = strdup("(unknown reason)");
applog(LOG_INFO, "JSON-RPC call failed: %s", s);
free(s);
goto err_out;
}
if (hi.reason) {
json_object_set_new(val, "reject-reason", json_string(hi.reason));
free(hi.reason);
hi.reason = NULL;
}
successful_connect = true;
databuf_free(&all_data);
curl_slist_free_all(headers);
curl_easy_reset(curl);
return val;
err_out:
databuf_free(&all_data);
curl_slist_free_all(headers);
curl_easy_reset(curl);
if (!successful_connect)
applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
return NULL;
}
#define PROXY_HTTP CURLPROXY_HTTP
#define PROXY_HTTP_1_0 CURLPROXY_HTTP_1_0
#define PROXY_SOCKS4 CURLPROXY_SOCKS4
#define PROXY_SOCKS5 CURLPROXY_SOCKS5
#define PROXY_SOCKS4A CURLPROXY_SOCKS4A
#define PROXY_SOCKS5H CURLPROXY_SOCKS5_HOSTNAME
#else /* HAVE_LIBCURL */
#define PROXY_HTTP 0
#define PROXY_HTTP_1_0 1
#define PROXY_SOCKS4 2
#define PROXY_SOCKS5 3
#define PROXY_SOCKS4A 4
#define PROXY_SOCKS5H 5
#endif /* HAVE_LIBCURL */
static struct {
const char *name;
proxytypes_t proxytype;
} proxynames[] = {
{ "http:", PROXY_HTTP },
{ "http0:", PROXY_HTTP_1_0 },
{ "socks4:", PROXY_SOCKS4 },
{ "socks5:", PROXY_SOCKS5 },
{ "socks4a:", PROXY_SOCKS4A },
{ "socks5h:", PROXY_SOCKS5H },
{ NULL, (proxytypes_t)NULL }
};
const char *proxytype(proxytypes_t proxytype)
{
int i;
for (i = 0; proxynames[i].name; i++)
if (proxynames[i].proxytype == proxytype)
return proxynames[i].name;
return "invalid";
}
char *get_proxy(char *url, struct pool *pool)
{
pool->rpc_proxy = NULL;
char *split;
int plen, len, i;
for (i = 0; proxynames[i].name; i++) {
plen = strlen(proxynames[i].name);
if (strncmp(url, proxynames[i].name, plen) == 0) {
if (!(split = strchr(url, '|')))
return url;
*split = '\0';
len = split - url;
pool->rpc_proxy = (char *)malloc(1 + len - plen);
if (!(pool->rpc_proxy))
quithere(1, "Failed to malloc rpc_proxy");
strcpy(pool->rpc_proxy, url + plen);
extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port);
pool->rpc_proxytype = proxynames[i].proxytype;
url = split + 1;
break;
}
}
return url;
}
/* Adequate size s==len*2 + 1 must be alloced to use this variant */
void __bin2hex(char *s, const unsigned char *p, size_t len)
{
int i;
static const char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
for (i = 0; i < (int)len; i++) {
*s++ = hex[p[i] >> 4];
*s++ = hex[p[i] & 0xF];
}
*s++ = '\0';
}
/* Returns a malloced array string of a binary value of arbitrary length. The
* array is rounded up to a 4 byte size to appease architectures that need
* aligned array sizes */
char *bin2hex(const unsigned char *p, size_t len)
{
ssize_t slen;
char *s;
slen = len * 2 + 1;
if (slen % 4)
slen += 4 - (slen % 4);
s = (char *)calloc(slen, 1);
if (unlikely(!s))
quithere(1, "Failed to calloc");
__bin2hex(s, p, len);
return s;
}
/* Does the reverse of bin2hex but does not allocate any ram */
static const int hex2bin_tbl[256] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
{
int nibble1, nibble2;
unsigned char idx;
bool ret = false;
while (*hexstr && len) {
if (unlikely(!hexstr[1])) {
applog(LOG_ERR, "hex2bin str truncated");
return ret;
}
idx = *hexstr++;
nibble1 = hex2bin_tbl[idx];
idx = *hexstr++;
nibble2 = hex2bin_tbl[idx];
if (unlikely((nibble1 < 0) || (nibble2 < 0))) {
applog(LOG_ERR, "hex2bin scan failed");
return ret;
}
*p++ = (((unsigned char)nibble1) << 4) | ((unsigned char)nibble2);
--len;
}
if (likely(len == 0 && *hexstr == 0))
ret = true;
return ret;
}
bool fulltest(const unsigned char *hash, const unsigned char *target)
{
uint32_t *hash32 = (uint32_t *)hash;
uint32_t *target32 = (uint32_t *)target;
bool rc = true;
int i;
for (i = 28 / 4; i >= 0; i--) {
uint32_t h32tmp = le32toh(hash32[i]);
uint32_t t32tmp = le32toh(target32[i]);
if (h32tmp > t32tmp) {
rc = false;
break;
}
if (h32tmp < t32tmp) {
rc = true;
break;
}
}
if (opt_debug) {
unsigned char hash_swap[32], target_swap[32];
char *hash_str, *target_str;
swab256(hash_swap, hash);
swab256(target_swap, target);
hash_str = bin2hex(hash_swap, 32);
target_str = bin2hex(target_swap, 32);
applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
hash_str,
target_str,
rc ? "YES (hash <= target)" :
"no (false positive; hash > target)");
free(hash_str);
free(target_str);
}
return rc;
}
struct thread_q *tq_new(void)
{
struct thread_q *tq;
tq = (struct thread_q *)calloc(1, sizeof(*tq));
if (!tq)
return NULL;
INIT_LIST_HEAD(&tq->q);
pthread_mutex_init(&tq->mutex, NULL);
pthread_cond_init(&tq->cond, NULL);
return tq;
}
void tq_free(struct thread_q *tq)
{
struct tq_ent *ent, *iter;
if (!tq)
return;
list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
list_del(&ent->q_node);
free(ent);
}
pthread_cond_destroy(&tq->cond);
pthread_mutex_destroy(&tq->mutex);
memset(tq, 0, sizeof(*tq)); /* poison */
free(tq);
}
static void tq_freezethaw(struct thread_q *tq, bool frozen)
{
mutex_lock(&tq->mutex);
tq->frozen = frozen;
pthread_cond_signal(&tq->cond);
mutex_unlock(&tq->mutex);
}
void tq_freeze(struct thread_q *tq)
{
tq_freezethaw(tq, true);
}
void tq_thaw(struct thread_q *tq)
{
tq_freezethaw(tq, false);
}
bool tq_push(struct thread_q *tq, void *data)
{
struct tq_ent *ent;
bool rc = true;
ent = (struct tq_ent *)calloc(1, sizeof(*ent));
if (!ent)
return false;
ent->data = data;
INIT_LIST_HEAD(&ent->q_node);
mutex_lock(&tq->mutex);
if (!tq->frozen) {
list_add_tail(&ent->q_node, &tq->q);
} else {
free(ent);
rc = false;
}
pthread_cond_signal(&tq->cond);
mutex_unlock(&tq->mutex);
return rc;
}
void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
{
struct tq_ent *ent;
void *rval = NULL;
int rc;
mutex_lock(&tq->mutex);
if (!list_empty(&tq->q))
goto pop;
if (abstime)
rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
else
rc = pthread_cond_wait(&tq->cond, &tq->mutex);
if (rc)
goto out;
if (list_empty(&tq->q))
goto out;
pop:
ent = list_entry(tq->q.next, struct tq_ent*, q_node);
rval = ent->data;
list_del(&ent->q_node);
free(ent);
out:
mutex_unlock(&tq->mutex);
return rval;
}
int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
{
cgsem_init(&thr->sem);
return pthread_create(&thr->pth, attr, start, arg);
}
void thr_info_cancel(struct thr_info *thr)
{
if (!thr)
return;
if (PTH(thr) != 0L) {
pthread_cancel(thr->pth);
PTH(thr) = 0L;
}
cgsem_destroy(&thr->sem);
}
void subtime(struct timeval *a, struct timeval *b)
{
timersub(a, b, b);
}
void addtime(struct timeval *a, struct timeval *b)
{
timeradd(a, b, b);
}
bool time_more(struct timeval *a, struct timeval *b)
{
return timercmp(a, b, >);
}
bool time_less(struct timeval *a, struct timeval *b)
{
return timercmp(a, b, <);
}
void copy_time(struct timeval *dest, const struct timeval *src)
{
memcpy(dest, src, sizeof(struct timeval));
}
void timespec_to_val(struct timeval *val, const struct timespec *spec)
{
val->tv_sec = spec->tv_sec;
val->tv_usec = spec->tv_nsec / 1000;
}
void timeval_to_spec(struct timespec *spec, const struct timeval *val)
{
spec->tv_sec = val->tv_sec;
spec->tv_nsec = val->tv_usec * 1000;
}
void us_to_timeval(struct timeval *val, int64_t us)
{
lldiv_t tvdiv = lldiv(us, 1000000);
val->tv_sec = tvdiv.quot;
val->tv_usec = tvdiv.rem;
}
void us_to_timespec(struct timespec *spec, int64_t us)
{
lldiv_t tvdiv = lldiv(us, 1000000);
spec->tv_sec = tvdiv.quot;
spec->tv_nsec = tvdiv.rem * 1000;
}
void ms_to_timespec(struct timespec *spec, int64_t ms)
{
lldiv_t tvdiv = lldiv(ms, 1000);
spec->tv_sec = tvdiv.quot;
spec->tv_nsec = tvdiv.rem * 1000000;
}
void ms_to_timeval(struct timeval *val, int64_t ms)
{
lldiv_t tvdiv = lldiv(ms, 1000);
val->tv_sec = tvdiv.quot;
val->tv_usec = tvdiv.rem * 1000;
}
void timeraddspec(struct timespec *a, const struct timespec *b)
{
a->tv_sec += b->tv_sec;
a->tv_nsec += b->tv_nsec;
if (a->tv_nsec >= 1000000000) {
a->tv_nsec -= 1000000000;
a->tv_sec++;
}
}
static int __maybe_unused timespec_to_ms(struct timespec *ts)
{
return ts->tv_sec * 1000 + ts->tv_nsec / 1000000;
}
/* Subtract b from a */
static void __maybe_unused timersubspec(struct timespec *a, const struct timespec *b)
{
a->tv_sec -= b->tv_sec;
a->tv_nsec -= b->tv_nsec;
if (a->tv_nsec < 0) {
a->tv_nsec += 1000000000;
a->tv_sec--;
}
}
/* These are sgminer specific sleep functions that use an absolute nanosecond
* resolution timer to avoid poor usleep accuracy and overruns. */
#ifdef WIN32
/* Windows start time is since 1601 LOL so convert it to unix epoch 1970. */
#define EPOCHFILETIME (116444736000000000LL)
/* Return the system time as an lldiv_t in decimicroseconds. */
static void decius_time(lldiv_t *lidiv)
{
FILETIME ft;
LARGE_INTEGER li;
GetSystemTimeAsFileTime(&ft);
li.LowPart = ft.dwLowDateTime;
li.HighPart = ft.dwHighDateTime;
li.QuadPart -= EPOCHFILETIME;
/* SystemTime is in decimicroseconds so divide by an unusual number */
*lidiv = lldiv(li.QuadPart, 10000000);
}
/* This is a sgminer gettimeofday wrapper. Since we always call gettimeofday
* with tz set to NULL, and windows' default resolution is only 15ms, this
* gives us higher resolution times on windows. */
void cgtime(struct timeval *tv)
{
lldiv_t lidiv;
decius_time(&lidiv);
tv->tv_sec = lidiv.quot;
tv->tv_usec = lidiv.rem / 10;
}
#else /* WIN32 */
void cgtime(struct timeval *tv)
{
gettimeofday(tv, NULL);
}
int cgtimer_to_ms(cgtimer_t *cgt)
{
return timespec_to_ms(cgt);
}
/* Subtracts b from a and stores it in res. */
void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
{
res->tv_sec = a->tv_sec - b->tv_sec;
res->tv_nsec = a->tv_nsec - b->tv_nsec;
if (res->tv_nsec < 0) {
res->tv_nsec += 1000000000;
res->tv_sec--;
}
}
#endif /* WIN32 */
#ifdef CLOCK_MONOTONIC /* Essentially just linux */
void cgtimer_time(cgtimer_t *ts_start)
{
clock_gettime(CLOCK_MONOTONIC, ts_start);
}
static void nanosleep_abstime(struct timespec *ts_end)
{
int ret;
do {
ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL);
} while (ret == EINTR);
}
/* Reentrant version of cgsleep functions allow start time to be set separately
* from the beginning of the actual sleep, allowing scheduling delays to be
* counted in the sleep. */
void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
{
struct timespec ts_end;
ms_to_timespec(&ts_end, ms);
timeraddspec(&ts_end, ts_start);
nanosleep_abstime(&ts_end);
}
void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
{
struct timespec ts_end;
us_to_timespec(&ts_end, us);
timeraddspec(&ts_end, ts_start);
nanosleep_abstime(&ts_end);
}
#else /* CLOCK_MONOTONIC */
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
void cgtimer_time(cgtimer_t *ts_start)
{
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
ts_start->tv_sec = mts.tv_sec;
ts_start->tv_nsec = mts.tv_nsec;
}
#elif !defined(WIN32) /* __MACH__ - Everything not linux/macosx/win32 */
void cgtimer_time(cgtimer_t *ts_start)
{
struct timeval tv;
cgtime(&tv);
ts_start->tv_sec = tv->tv_sec;
ts_start->tv_nsec = tv->tv_usec * 1000;
}
#endif /* __MACH__ */
#ifdef WIN32
/* For windows we use the SystemTime stored as a LARGE_INTEGER as the cgtimer_t
* typedef, allowing us to have sub-microsecond resolution for times, do simple
* arithmetic for timer calculations, and use windows' own hTimers to get
* accurate absolute timeouts. */
int cgtimer_to_ms(cgtimer_t *cgt)
{
return (int)(cgt->QuadPart / 10000LL);
}
/* Subtracts b from a and stores it in res. */
void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
{
res->QuadPart = a->QuadPart - b->QuadPart;
}
/* Note that cgtimer time is NOT offset by the unix epoch since we use absolute
* timeouts with hTimers. */
void cgtimer_time(cgtimer_t *ts_start)
{
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
ts_start->LowPart = ft.dwLowDateTime;
ts_start->HighPart = ft.dwHighDateTime;
}
static void liSleep(LARGE_INTEGER *li, int timeout)
{
HANDLE hTimer;
DWORD ret;
if (unlikely(timeout <= 0))
return;
hTimer = CreateWaitableTimer(NULL, TRUE, NULL);
if (unlikely(!hTimer))
quit(1, "Failed to create hTimer in liSleep");
ret = SetWaitableTimer(hTimer, li, 0, NULL, NULL, 0);
if (unlikely(!ret))
quit(1, "Failed to SetWaitableTimer in liSleep");
/* We still use a timeout as a sanity check in case the system time
* is changed while we're running */
ret = WaitForSingleObject(hTimer, timeout);
if (unlikely(ret != WAIT_OBJECT_0 && ret != WAIT_TIMEOUT))
quit(1, "Failed to WaitForSingleObject in liSleep");
CloseHandle(hTimer);
}
void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
{
LARGE_INTEGER li;
li.QuadPart = ts_start->QuadPart + (int64_t)ms * 10000LL;
liSleep(&li, ms);
}
void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
{
LARGE_INTEGER li;
int ms;
li.QuadPart = ts_start->QuadPart + us * 10LL;
ms = us / 1000;
if (!ms)
ms = 1;
liSleep(&li, ms);
}
#else /* WIN32 */
static void cgsleep_spec(struct timespec *ts_diff, const struct timespec *ts_start)
{
struct timespec now;
timeraddspec(ts_diff, ts_start);
cgtimer_time(&now);
timersubspec(ts_diff, &now);
if (unlikely(ts_diff->tv_sec < 0))
return;
nanosleep(ts_diff, NULL);
}
void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
{
struct timespec ts_diff;
ms_to_timespec(&ts_diff, ms);
cgsleep_spec(&ts_diff, ts_start);
}
void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
{
struct timespec ts_diff;
us_to_timespec(&ts_diff, us);
cgsleep_spec(&ts_diff, ts_start);
}
#endif /* WIN32 */
#endif /* CLOCK_MONOTONIC */
void cgsleep_ms(int ms)
{
cgtimer_t ts_start;
cgsleep_prepare_r(&ts_start);
cgsleep_ms_r(&ts_start, ms);
}
void cgsleep_us(int64_t us)
{
cgtimer_t ts_start;
cgsleep_prepare_r(&ts_start);
cgsleep_us_r(&ts_start, us);
}
/* Returns the microseconds difference between end and start times as a double */
double us_tdiff(struct timeval *end, struct timeval *start)
{
/* Sanity check. We should only be using this for small differences so
* limit the max to 60 seconds. */
if (unlikely(end->tv_sec - start->tv_sec > 60))
return 60000000;
return (end->tv_sec - start->tv_sec) * 1000000 + (end->tv_usec - start->tv_usec);
}
/* Returns the milliseconds difference between end and start times */
int ms_tdiff(struct timeval *end, struct timeval *start)
{
/* Like us_tdiff, limit to 1 hour. */
if (unlikely(end->tv_sec - start->tv_sec > 3600))
return 3600000;
return (end->tv_sec - start->tv_sec) * 1000 + (end->tv_usec - start->tv_usec) / 1000;
}
/* Returns the seconds difference between end and start times as a double */
double tdiff(struct timeval *end, struct timeval *start)
{
return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
}
bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
{
char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
char url_address[256], port[6];
int url_len, port_len = 0;
*sockaddr_url = url;
url_begin = strstr(url, "//");
if (!url_begin)
url_begin = url;
else
url_begin += 2;
/* Look for numeric ipv6 entries */
ipv6_begin = strstr(url_begin, "[");
ipv6_end = strstr(url_begin, "]");
if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
url_end = strstr(ipv6_end, ":");
else
url_end = strstr(url_begin, ":");
if (url_end) {
url_len = url_end - url_begin;
port_len = strlen(url_begin) - url_len - 1;
if (port_len < 1)
return false;
port_start = url_end + 1;
} else
url_len = strlen(url_begin);
if (url_len < 1)
return false;
sprintf(url_address, "%.*s", url_len, url_begin);
if (port_len) {
char *slash;
snprintf(port, 6, "%.*s", port_len, port_start);
slash = strchr(port, '/');
if (slash)
*slash = '\0';
} else
strcpy(port, "80");
*sockaddr_port = strdup(port);
*sockaddr_url = strdup(url_address);
return true;
}
enum send_ret {
SEND_OK,
SEND_SELECTFAIL,
SEND_SENDFAIL,
SEND_INACTIVE
};
/* Send a single command across a socket, appending \n to it. This should all
* be done under stratum lock except when first establishing the socket */
static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
{
SOCKETTYPE sock = pool->sock;
ssize_t ssent = 0;
strcat(s, "\n");
len++;
while (len > 0 ) {
struct timeval timeout = {1, 0};
ssize_t sent;
fd_set wd;
retry:
FD_ZERO(&wd);
FD_SET(sock, &wd);
if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
if (interrupted())
goto retry;
return SEND_SELECTFAIL;
}
#ifdef __APPLE__
sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
#elif WIN32
sent = send(pool->sock, s + ssent, len, 0);
#else
sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
#endif
if (sent < 0) {
if (!sock_blocks())
return SEND_SENDFAIL;
sent = 0;
}
ssent += sent;
len -= sent;
}
pool->sgminer_pool_stats.times_sent++;
pool->sgminer_pool_stats.bytes_sent += ssent;
pool->sgminer_pool_stats.net_bytes_sent += ssent;
return SEND_OK;
}
bool stratum_send(struct pool *pool, char *s, ssize_t len)
{
enum send_ret ret = SEND_INACTIVE;
if (opt_protocol)
applog(LOG_DEBUG, "SEND: %s", s);
mutex_lock(&pool->stratum_lock);
if (pool->stratum_active)
ret = __stratum_send(pool, s, len);
mutex_unlock(&pool->stratum_lock);
/* This is to avoid doing applog under stratum_lock */
switch (ret) {
default:
case SEND_OK:
break;
case SEND_SELECTFAIL:
applog(LOG_DEBUG, "Write select failed on %s sock", get_pool_name(pool));
suspend_stratum(pool);
break;
case SEND_SENDFAIL:
applog(LOG_DEBUG, "Failed to send in stratum_send");
suspend_stratum(pool);
break;
case SEND_INACTIVE:
applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
break;
}
return (ret == SEND_OK);
}
static bool socket_full(struct pool *pool, int wait)
{
SOCKETTYPE sock = pool->sock;
struct timeval timeout;
fd_set rd;
if (unlikely(wait < 0))
wait = 0;
FD_ZERO(&rd);
FD_SET(sock, &rd);
timeout.tv_usec = 0;
timeout.tv_sec = wait;
if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
return true;
return false;
}
/* Check to see if Santa's been good to you */
bool sock_full(struct pool *pool)
{
if (strlen(pool->sockbuf))
return true;
return (socket_full(pool, 0));
}
static void clear_sockbuf(struct pool *pool)
{
strcpy(pool->sockbuf, "");
}
static void clear_sock(struct pool *pool)
{
ssize_t n;
mutex_lock(&pool->stratum_lock);
do {
if (pool->sock)
n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
else
n = 0;
} while (n > 0);
mutex_unlock(&pool->stratum_lock);
clear_sockbuf(pool);
}
/* Make sure the pool sockbuf is large enough to cope with any coinbase size
* by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
* and zeroing the new memory */
static void recalloc_sock(struct pool *pool, size_t len)
{
size_t old, newlen;
old = strlen(pool->sockbuf);
newlen = old + len + 1;
if (newlen < pool->sockbuf_size)
return;
newlen = newlen + (RBUFSIZE - (newlen % RBUFSIZE));
// Avoid potentially recursive locking
// applog(LOG_DEBUG, "Recallocing pool sockbuf to %d", new);
pool->sockbuf = (char *)realloc(pool->sockbuf, newlen);
if (!pool->sockbuf)
quithere(1, "Failed to realloc pool sockbuf");
memset(pool->sockbuf + old, 0, newlen - old);
pool->sockbuf_size = newlen;
}
/* Peeks at a socket to find the first end of line and then reads just that
* from the socket and returns that as a malloced char */
char *recv_line(struct pool *pool)
{
char *tok, *sret = NULL;
ssize_t len, buflen;
int waited = 0;
if (!strstr(pool->sockbuf, "\n")) {
struct timeval rstart, now;
cgtime(&rstart);
if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
goto out;
}
do {
char s[RBUFSIZE];
size_t slen;
ssize_t n;
memset(s, 0, RBUFSIZE);
n = recv(pool->sock, s, RECVSIZE, 0);
if (!n) {
applog(LOG_DEBUG, "Socket closed waiting in recv_line");
suspend_stratum(pool);
break;
}
cgtime(&now);
waited = tdiff(&now, &rstart);
if (n < 0) {
if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) {
applog(LOG_DEBUG, "Failed to recv sock in recv_line");
suspend_stratum(pool);
break;
}
} else {
slen = strlen(s);
recalloc_sock(pool, slen);
strcat(pool->sockbuf, s);
}
} while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
}
buflen = strlen(pool->sockbuf);
tok = strtok(pool->sockbuf, "\n");
if (!tok) {
applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
goto out;
}
sret = strdup(tok);
len = strlen(sret);
/* Copy what's left in the buffer after the \n, including the
* terminating \0 */
if (buflen > len + 1)
memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
else
strcpy(pool->sockbuf, "");
pool->sgminer_pool_stats.times_received++;
pool->sgminer_pool_stats.bytes_received += len;
pool->sgminer_pool_stats.net_bytes_received += len;
out:
if (!sret)
clear_sock(pool);
else if (opt_protocol)
applog(LOG_DEBUG, "RECVD: %s", sret);
return sret;
}
/* Extracts a string value from a json array with error checking. To be used
* when the value of the string returned is only examined and not to be stored.
* See json_array_string below */
static char *__json_array_string(json_t *val, unsigned int entry)
{
json_t *arr_entry;
if (json_is_null(val))
return NULL;
if (!json_is_array(val))
return NULL;
if (entry > json_array_size(val))
return NULL;
arr_entry = json_array_get(val, entry);
if (!json_is_string(arr_entry))
return NULL;
return (char *)json_string_value(arr_entry);
}
/* Creates a freshly malloced dup of __json_array_string */
static char *json_array_string(json_t *val, unsigned int entry)
{
char *buf = __json_array_string(val, entry);
if (buf)
return strdup(buf);
return NULL;
}
static char *blank_merkel = "0000000000000000000000000000000000000000000000000000000000000000";
static bool parse_notify(struct pool *pool, json_t *val)
{
char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
*ntime, *header;
size_t cb1_len, cb2_len, alloc_len;
unsigned char *cb1, *cb2;
bool clean, ret = false;
int merkles, i;
json_t *arr;
arr = json_array_get(val, 4);
if (!arr || !json_is_array(arr))
goto out;
merkles = json_array_size(arr);
job_id = json_array_string(val, 0);
prev_hash = json_array_string(val, 1);
coinbase1 = json_array_string(val, 2);
coinbase2 = json_array_string(val, 3);
bbversion = json_array_string(val, 5);
nbit = json_array_string(val, 6);
ntime = json_array_string(val, 7);
clean = json_is_true(json_array_get(val, 8));
if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
/* Annoying but we must not leak memory */
if (job_id)
free(job_id);
if (prev_hash)
free(prev_hash);
if (coinbase1)
free(coinbase1);
if (coinbase2)
free(coinbase2);
if (bbversion)
free(bbversion);
if (nbit)
free(nbit);
if (ntime)
free(ntime);
goto out;
}
cg_wlock(&pool->data_lock);
free(pool->swork.job_id);
free(pool->swork.prev_hash);
free(pool->swork.bbversion);
free(pool->swork.nbit);
free(pool->swork.ntime);
pool->swork.job_id = job_id;
pool->swork.prev_hash = prev_hash;
cb1_len = strlen(coinbase1) / 2;
cb2_len = strlen(coinbase2) / 2;
pool->swork.bbversion = bbversion;
pool->swork.nbit = nbit;
pool->swork.ntime = ntime;
pool->swork.clean = clean;
alloc_len = pool->swork.cb_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
pool->nonce2_offset = cb1_len + pool->n1_len;
for (i = 0; i < pool->swork.merkles; i++)
free(pool->swork.merkle_bin[i]);
if (merkles) {
pool->swork.merkle_bin = (unsigned char **)realloc(pool->swork.merkle_bin,
sizeof(char *) * merkles + 1);
for (i = 0; i < merkles; i++) {
char *merkle = json_array_string(arr, i);
pool->swork.merkle_bin[i] = (unsigned char *)malloc(32);
if (unlikely(!pool->swork.merkle_bin[i]))
quit(1, "Failed to malloc pool swork merkle_bin");
hex2bin(pool->swork.merkle_bin[i], merkle, 32);
free(merkle);
}
}
pool->swork.merkles = merkles;
if (clean)
pool->nonce2 = 0;
pool->merkle_offset = strlen(pool->swork.bbversion) +
strlen(pool->swork.prev_hash);
pool->swork.header_len = pool->merkle_offset +
/* merkle_hash */ 32 +
strlen(pool->swork.ntime) +
strlen(pool->swork.nbit) +
/* nonce */ 8 +
/* workpadding */ 96;
pool->merkle_offset /= 2;
pool->swork.header_len = pool->swork.header_len * 2 + 1;
align_len(&pool->swork.header_len);
header = (char *)alloca(pool->swork.header_len);
snprintf(header, pool->swork.header_len,
"%s%s%s%s%s%s%s",
pool->swork.bbversion,
pool->swork.prev_hash,
blank_merkel,
pool->swork.ntime,
pool->swork.nbit,
"00000000", /* nonce */
workpadding);
if (unlikely(!hex2bin(pool->header_bin, header, 128)))
quit(1, "Failed to convert header to header_bin in parse_notify");
cb1 = (unsigned char *)calloc(cb1_len, 1);
if (unlikely(!cb1))
quithere(1, "Failed to calloc cb1 in parse_notify");
hex2bin(cb1, coinbase1, cb1_len);
cb2 = (unsigned char *)calloc(cb2_len, 1);
if (unlikely(!cb2))
quithere(1, "Failed to calloc cb2 in parse_notify");
hex2bin(cb2, coinbase2, cb2_len);
free(pool->coinbase);
align_len(&alloc_len);
pool->coinbase = (unsigned char *)calloc(alloc_len, 1);
if (unlikely(!pool->coinbase))
quit(1, "Failed to calloc pool coinbase in parse_notify");
memcpy(pool->coinbase, cb1, cb1_len);
memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len);
memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len);
cg_wunlock(&pool->data_lock);
if (opt_protocol) {
applog(LOG_DEBUG, "job_id: %s", job_id);
applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
applog(LOG_DEBUG, "bbversion: %s", bbversion);
applog(LOG_DEBUG, "nbit: %s", nbit);
applog(LOG_DEBUG, "ntime: %s", ntime);
applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
}
free(coinbase1);
free(coinbase2);
free(cb1);
free(cb2);
/* A notify message is the closest stratum gets to a getwork */
pool->getwork_requested++;
total_getworks++;
ret = true;
if (pool == current_pool())
opt_work_update = true;
out:
return ret;
}
static bool parse_diff(struct pool *pool, json_t *val)
{
double old_diff, diff;
if (opt_diff_mult == 0.0)
diff = json_number_value(json_array_get(val, 0)) * pool->algorithm.diff_multiplier1;
else
diff = json_number_value(json_array_get(val, 0)) * opt_diff_mult;
if (diff == 0)
return false;
cg_wlock(&pool->data_lock);
old_diff = pool->swork.diff;
pool->swork.diff = diff;
cg_wunlock(&pool->data_lock);
if (old_diff != diff) {
int idiff = diff;
if ((double)idiff == diff)
applog(pool == current_pool() ? LOG_NOTICE : LOG_DEBUG, "%s difficulty changed to %d", get_pool_name(pool), idiff);
else
applog(pool == current_pool() ? LOG_NOTICE : LOG_DEBUG, "%s difficulty changed to %.3f", get_pool_name(pool), diff);
} else
applog(LOG_DEBUG, "%s difficulty set to %f", get_pool_name(pool), diff);
return true;
}
static bool parse_extranonce(struct pool *pool, json_t *val)
{
char *nonce1;
int n2size;
nonce1 = json_array_string(val, 0);
if (!nonce1) {
return false;
}
n2size = json_integer_value(json_array_get(val, 1));
if (!n2size) {
free(nonce1);
return false;
}
cg_wlock(&pool->data_lock);
pool->nonce1 = nonce1;
pool->n1_len = strlen(nonce1) / 2;
free(pool->nonce1bin);
pool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1);
if (unlikely(!pool->nonce1bin))
quithere(1, "Failed to calloc pool->nonce1bin");
hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
pool->n2size = n2size;
cg_wunlock(&pool->data_lock);
applog(LOG_NOTICE, "%s extranonce change requested", get_pool_name(pool));
return true;
}
static void __suspend_stratum(struct pool *pool)
{
clear_sockbuf(pool);
pool->stratum_active = pool->stratum_notify = false;
if (pool->sock)
CLOSESOCKET(pool->sock);
pool->sock = 0;
}
static bool parse_reconnect(struct pool *pool, json_t *val)
{
char *sockaddr_url, *stratum_port, *tmp;
char *url, *port, address[256];
if (opt_disable_client_reconnect) {
applog(LOG_WARNING, "Stratum client.reconnect forbidden, aborting.");
return false;
}
memset(address, 0, 255);
url = (char *)json_string_value(json_array_get(val, 0));
if (!url)
url = pool->sockaddr_url;
port = (char *)json_string_value(json_array_get(val, 1));
if (!port)
port = pool->stratum_port;
sprintf(address, "%s:%s", url, port);
if (!extract_sockaddr(address, &sockaddr_url, &stratum_port))
return false;
applog(LOG_NOTICE, "Reconnect requested from %s to %s", get_pool_name(pool), address);
clear_pool_work(pool);
mutex_lock(&pool->stratum_lock);
__suspend_stratum(pool);
tmp = pool->sockaddr_url;
pool->sockaddr_url = sockaddr_url;
pool->stratum_url = pool->sockaddr_url;
free(tmp);
tmp = pool->stratum_port;
pool->stratum_port = stratum_port;
free(tmp);
mutex_unlock(&pool->stratum_lock);
if (!restart_stratum(pool)) {
pool_failed(pool);
return false;
}
return true;
}
static bool send_version(struct pool *pool, json_t *val)
{
char s[RBUFSIZE];
int id = json_integer_value(json_object_get(val, "id"));
if (!id)
return false;
sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
if (!stratum_send(pool, s, strlen(s)))
return false;
return true;
}
static bool show_message(struct pool *pool, json_t *val)
{
char *msg;
if (!json_is_array(val))
return false;
msg = (char *)json_string_value(json_array_get(val, 0));
if (!msg)
return false;
applog(LOG_NOTICE, "%s message: %s", get_pool_name(pool), msg);
return true;
}
bool parse_method(struct pool *pool, char *s)
{
json_t *val = NULL, *method, *err_val, *params;
json_error_t err;
bool ret = false;
char *buf;
if (!s)
return ret;
val = JSON_LOADS(s, &err);
if (!val) {
applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
return ret;
}
method = json_object_get(val, "method");
if (!method) {
json_decref(val);
return ret;
}
err_val = json_object_get(val, "error");
params = json_object_get(val, "params");
if (err_val && !json_is_null(err_val)) {
char *ss;
if (err_val)
ss = json_dumps(err_val, JSON_INDENT(3));
else
ss = strdup("(unknown reason)");
applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
json_decref(val);
free(ss);
return ret;
}
buf = (char *)json_string_value(method);
if (!buf) {
json_decref(val);
return ret;
}
if (!strncasecmp(buf, "mining.notify", 13)) {
if (parse_notify(pool, params))
pool->stratum_notify = ret = true;
else
pool->stratum_notify = ret = false;
json_decref(val);
return ret;
}
if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
ret = true;
json_decref(val);
return ret;
}
if (!strncasecmp(buf, "mining.set_extranonce", 21) && parse_extranonce(pool, params)) {
ret = true;
json_decref(val);
return ret;
}
if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
ret = true;
json_decref(val);
return ret;
}
if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
ret = true;
json_decref(val);
return ret;
}
if (!strncasecmp(buf, "client.show_message", 19) && show_message(pool, params)) {
ret = true;
json_decref(val);
return ret;
}
json_decref(val);
return ret;
}
bool subscribe_extranonce(struct pool *pool)
{
json_t *val = NULL, *res_val, *err_val;
char s[RBUFSIZE], *sret = NULL;
json_error_t err;
bool ret = false;
sprintf(s, "{\"id\": %d, \"method\": \"mining.extranonce.subscribe\", \"params\": []}",
swork_id++);
if (!stratum_send(pool, s, strlen(s)))
return ret;
/* Parse all data in the queue and anything left should be the response */
while (42) {
if (!socket_full(pool, DEFAULT_SOCKWAIT / 30)) {
applog(LOG_DEBUG, "Timed out waiting for response extranonce.subscribe");
/* some pool doesnt send anything, so this is normal */
ret = true;
goto out;
}
sret = recv_line(pool);
if (!sret)
return ret;
if (parse_method(pool, sret))
free(sret);
else
break;
}
val = JSON_LOADS(sret, &err);
free(sret);
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
char *ss;
if (err_val) {
ss = __json_array_string(err_val, 1);
if (!ss)
ss = (char *)json_string_value(err_val);
if (ss && (strcmp(ss, "Method 'subscribe' not found for service 'mining.extranonce'") == 0)) {
applog(LOG_INFO, "Cannot subscribe to mining.extranonce on %s", get_pool_name(pool));
ret = true;
goto out;
}
if (ss && (strcmp(ss, "Unrecognized request provided") == 0)) {
applog(LOG_INFO, "Cannot subscribe to mining.extranonce on %s", get_pool_name(pool));
ret = true;
goto out;
}
ss = json_dumps(err_val, JSON_INDENT(3));
}
else
ss = strdup("(unknown reason)");
applog(LOG_INFO, "%s JSON stratum auth failed: %s", get_pool_name(pool), ss);
free(ss);
goto out;
}
ret = true;
applog(LOG_INFO, "Stratum extranonce subscribe for %s", get_pool_name(pool));
out:
json_decref(val);
return ret;
}
bool auth_stratum(struct pool *pool)
{
json_t *val = NULL, *res_val, *err_val;
char s[RBUFSIZE], *sret = NULL;
json_error_t err;
bool ret = false;
sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
swork_id++, pool->rpc_user, pool->rpc_pass);
if (!stratum_send(pool, s, strlen(s)))
return ret;
/* Parse all data in the queue and anything left should be auth */
while (42) {
sret = recv_line(pool);
if (!sret)
return ret;
if (parse_method(pool, sret))
free(sret);
else
break;
}
val = JSON_LOADS(sret, &err);
free(sret);
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
char *ss;
if (err_val)
ss = json_dumps(err_val, JSON_INDENT(3));
else
ss = strdup("(unknown reason)");
applog(LOG_INFO, "%s JSON stratum auth failed: %s", get_pool_name(pool), ss);
free(ss);
suspend_stratum(pool);
goto out;
}
ret = true;
applog(LOG_INFO, "Stratum authorisation success for %s", get_pool_name(pool));
pool->probed = true;
successful_connect = true;
out:
json_decref(val);
return ret;
}
static int recv_byte(int sockd)
{
char c;
if (recv(sockd, &c, 1, 0) != -1)
return c;
return -1;
}
static bool http_negotiate(struct pool *pool, int sockd, bool http0)
{
char buf[1024];
int i, len;
if (http0) {
snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.0\r\n\r\n",
pool->sockaddr_url, pool->stratum_port);
} else {
snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.1\r\nHost: %s:%s\r\n\r\n",
pool->sockaddr_url, pool->stratum_port, pool->sockaddr_url,
pool->stratum_port);
}
applog(LOG_DEBUG, "Sending proxy %s:%s - %s",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
send(sockd, buf, strlen(buf), 0);
len = recv(sockd, buf, 12, 0);
if (len <= 0) {
applog(LOG_WARNING, "Couldn't read from proxy %s:%s after sending CONNECT",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return false;
}
buf[len] = '\0';
applog(LOG_DEBUG, "Received from proxy %s:%s - %s",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
if (strcmp(buf, "HTTP/1.1 200") && strcmp(buf, "HTTP/1.0 200")) {
applog(LOG_WARNING, "HTTP Error from proxy %s:%s - %s",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
return false;
}
/* Ignore unwanted headers till we get desired response */
for (i = 0; i < 4; i++) {
buf[i] = recv_byte(sockd);
if (buf[i] == (char)-1) {
applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return false;
}
}
while (strncmp(buf, "\r\n\r\n", 4)) {
for (i = 0; i < 3; i++)
buf[i] = buf[i + 1];
buf[3] = recv_byte(sockd);
if (buf[3] == (char)-1) {
applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return false;
}
}
applog(LOG_DEBUG, "Success negotiating with %s:%s HTTP proxy",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return true;
}
static bool socks5_negotiate(struct pool *pool, int sockd)
{
unsigned char atyp, uclen;
unsigned short port;
char buf[515];
int i, len;
buf[0] = 0x05;
buf[1] = 0x01;
buf[2] = 0x00;
applog(LOG_DEBUG, "Attempting to negotiate with %s:%s SOCKS5 proxy",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
send(sockd, buf, 3, 0);
if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != buf[2]) {
applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
return false;
}
buf[0] = 0x05;
buf[1] = 0x01;
buf[2] = 0x00;
buf[3] = 0x03;
len = (strlen(pool->sockaddr_url));
if (len > 255)
len = 255;
uclen = len;
buf[4] = (uclen & 0xff);
memcpy(buf + 5, pool->sockaddr_url, len);
port = atoi(pool->stratum_port);
buf[5 + len] = (port >> 8);
buf[6 + len] = (port & 0xff);
send(sockd, buf, (7 + len), 0);
if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != 0x00) {
applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
return false;
}
recv_byte(sockd);
atyp = recv_byte(sockd);
if (atyp == 0x01) {
for (i = 0; i < 4; i++)
recv_byte(sockd);
} else if (atyp == 0x03) {
len = recv_byte(sockd);
for (i = 0; i < len; i++)
recv_byte(sockd);
} else {
applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
return false;
}
for (i = 0; i < 2; i++)
recv_byte(sockd);
applog(LOG_DEBUG, "Success negotiating with %s:%s SOCKS5 proxy",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return true;
}
static bool socks4_negotiate(struct pool *pool, int sockd, bool socks4a)
{
unsigned short port;
in_addr_t inp;
char buf[515];
int i, len;
int ret;
buf[0] = 0x04;
buf[1] = 0x01;
port = atoi(pool->stratum_port);
buf[2] = port >> 8;
buf[3] = port & 0xff;
sprintf(&buf[8], "SGMINER");
/* See if we've been given an IP address directly to avoid needing to
* resolve it. */
inp = inet_addr(pool->sockaddr_url);
inp = ntohl(inp);
if ((int)inp != -1)
socks4a = false;
else {
/* Try to extract the IP address ourselves first */
struct addrinfo servinfobase, *servinfo, hints;
servinfo = &servinfobase;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET; /* IPV4 only */
ret = getaddrinfo(pool->sockaddr_url, NULL, &hints, &servinfo);
if (!ret) {
applog(LOG_ERR, "getaddrinfo() in socks4_negotiate() returned %i: %s", ret, gai_strerror(ret));
struct sockaddr_in *saddr_in = (struct sockaddr_in *)servinfo->ai_addr;
inp = ntohl(saddr_in->sin_addr.s_addr);
socks4a = false;
freeaddrinfo(servinfo);
}
}
if (!socks4a) {
if ((int)inp == -1) {
applog(LOG_WARNING, "Invalid IP address specified for socks4 proxy: %s",
pool->sockaddr_url);
return false;
}
buf[4] = (inp >> 24) & 0xFF;
buf[5] = (inp >> 16) & 0xFF;
buf[6] = (inp >> 8) & 0xFF;
buf[7] = (inp >> 0) & 0xFF;
send(sockd, buf, 16, 0);
} else {
/* This appears to not be working but hopefully most will be
* able to resolve IP addresses themselves. */
buf[4] = 0;
buf[5] = 0;
buf[6] = 0;
buf[7] = 1;
len = strlen(pool->sockaddr_url);
if (len > 255)
len = 255;
memcpy(&buf[16], pool->sockaddr_url, len);
len += 16;
buf[len++] = '\0';
send(sockd, buf, len, 0);
}
if (recv_byte(sockd) != 0x00 || recv_byte(sockd) != 0x5a) {
applog(LOG_WARNING, "Bad response from %s:%s SOCKS4 server",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return false;
}
for (i = 0; i < 6; i++)
recv_byte(sockd);
return true;
}
static void noblock_socket(SOCKETTYPE fd)
{
#ifndef WIN32
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, O_NONBLOCK | flags);
#else
u_long flags = 1;
ioctlsocket(fd, FIONBIO, &flags);
#endif
}
static void block_socket(SOCKETTYPE fd)
{
#ifndef WIN32
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
#else
u_long flags = 0;
ioctlsocket(fd, FIONBIO, &flags);
#endif
}
static bool sock_connecting(void)
{
#ifndef WIN32
return errno == EINPROGRESS;
#else
return WSAGetLastError() == WSAEWOULDBLOCK;
#endif
}
static bool setup_stratum_socket(struct pool *pool)
{
struct addrinfo servinfobase, *servinfo, *hints, *p;
char *sockaddr_url, *sockaddr_port;
int sockd;
int ret;
mutex_lock(&pool->stratum_lock);
pool->stratum_active = false;
if (pool->sock) {
/* FIXME: change to LOG_DEBUG if issue #88 resolved */
applog(LOG_INFO, "Closing %s socket", get_pool_name(pool));
CLOSESOCKET(pool->sock);
}
pool->sock = 0;
mutex_unlock(&pool->stratum_lock);
hints = &pool->stratum_hints;
memset(hints, 0, sizeof(struct addrinfo));
hints->ai_family = AF_UNSPEC;
hints->ai_socktype = SOCK_STREAM;
servinfo = &servinfobase;
if (!pool->rpc_proxy && opt_socks_proxy) {
pool->rpc_proxy = opt_socks_proxy;
extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port);
pool->rpc_proxytype = PROXY_SOCKS5;
}
if (pool->rpc_proxy) {
sockaddr_url = pool->sockaddr_proxy_url;
sockaddr_port = pool->sockaddr_proxy_port;
} else {
sockaddr_url = pool->sockaddr_url;
sockaddr_port = pool->stratum_port;
}
ret = getaddrinfo(sockaddr_url, sockaddr_port, hints, &servinfo);
if (ret) {
applog(LOG_INFO, "getaddrinfo() in setup_stratum_socket() returned %i: %s", ret, gai_strerror(ret));
if (!pool->probed) {
applog(LOG_WARNING, "Failed to resolve (wrong URL?) %s:%s",
sockaddr_url, sockaddr_port);
pool->probed = true;
} else {
applog(LOG_INFO, "Failed to getaddrinfo for %s:%s",
sockaddr_url, sockaddr_port);
}
return false;
}
for (p = servinfo; p != NULL; p = p->ai_next) {
sockd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (sockd == -1) {
applog(LOG_DEBUG, "Failed socket");
continue;
}
/* Iterate non blocking over entries returned by getaddrinfo
* to cope with round robin DNS entries, finding the first one
* we can connect to quickly. */
noblock_socket(sockd);
if (connect(sockd, p->ai_addr, p->ai_addrlen) == -1) {
struct timeval tv_timeout = {1, 0};
int selret;
fd_set rw;
if (!sock_connecting()) {
CLOSESOCKET(sockd);
applog(LOG_DEBUG, "Failed sock connect");
continue;
}
retry:
FD_ZERO(&rw);
FD_SET(sockd, &rw);
selret = select(sockd + 1, NULL, &rw, NULL, &tv_timeout);
if (selret > 0 && FD_ISSET(sockd, &rw)) {
socklen_t len;
int err, n;
len = sizeof(err);
n = getsockopt(sockd, SOL_SOCKET, SO_ERROR, (char *)&err, &len);
if (!n && !err) {
applog(LOG_DEBUG, "Succeeded delayed connect");
block_socket(sockd);
break;
}
}
if (selret < 0 && interrupted())
goto retry;
CLOSESOCKET(sockd);
applog(LOG_DEBUG, "Select timeout/failed connect");
continue;
}
applog(LOG_WARNING, "Succeeded immediate connect");
block_socket(sockd);
break;
}
if (p == NULL) {
applog(LOG_INFO, "Failed to connect to stratum on %s:%s",
sockaddr_url, sockaddr_port);
freeaddrinfo(servinfo);
return false;
}
freeaddrinfo(servinfo);
if (pool->rpc_proxy) {
switch (pool->rpc_proxytype) {
case PROXY_HTTP_1_0:
if (!http_negotiate(pool, sockd, true))
return false;
break;
case PROXY_HTTP:
if (!http_negotiate(pool, sockd, false))
return false;
break;
case PROXY_SOCKS5:
case PROXY_SOCKS5H:
if (!socks5_negotiate(pool, sockd))
return false;
break;
case PROXY_SOCKS4:
if (!socks4_negotiate(pool, sockd, false))
return false;
break;
case PROXY_SOCKS4A:
if (!socks4_negotiate(pool, sockd, true))
return false;
break;
default:
applog(LOG_WARNING, "Unsupported proxy type for %s:%s",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return false;
break;
}
}
if (!pool->sockbuf) {
pool->sockbuf = (char *)calloc(RBUFSIZE, 1);
if (!pool->sockbuf)
quithere(1, "Failed to calloc pool sockbuf");
pool->sockbuf_size = RBUFSIZE;
}
pool->sock = sockd;
keep_sockalive(sockd);
return true;
}
static char *get_sessionid(json_t *val)
{
char *ret = NULL;
json_t *arr_val;
int arrsize, i;
arr_val = json_array_get(val, 0);
if (!arr_val || !json_is_array(arr_val))
goto out;
arrsize = json_array_size(arr_val);
for (i = 0; i < arrsize; i++) {
json_t *arr = json_array_get(arr_val, i);
char *notify;
if (!arr | !json_is_array(arr))
break;
notify = __json_array_string(arr, 0);
if (!notify)
continue;
if (!strncasecmp(notify, "mining.notify", 13)) {
ret = json_array_string(arr, 1);
break;
}
}
out:
return ret;
}
void suspend_stratum(struct pool *pool)
{
applog(LOG_INFO, "Closing socket for stratum %s", get_pool_name(pool));
mutex_lock(&pool->stratum_lock);
__suspend_stratum(pool);
mutex_unlock(&pool->stratum_lock);
}
bool initiate_stratum(struct pool *pool)
{
bool ret = false, recvd = false, noresume = false, sockd = false;
char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
json_t *val = NULL, *res_val, *err_val;
json_error_t err;
int n2size;
resend:
if (!setup_stratum_socket(pool)) {
/* FIXME: change to LOG_DEBUG when issue #88 resolved */
applog(LOG_INFO, "setup_stratum_socket() on %s failed", get_pool_name(pool));
sockd = false;
goto out;
}
sockd = true;
if (recvd) {
/* Get rid of any crap lying around if we're resending */
clear_sock(pool);
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
} else {
if (pool->sessionid)
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
else
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
}
if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
goto out;
}
if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
goto out;
}
sret = recv_line(pool);
if (!sret)
goto out;
recvd = true;
val = JSON_LOADS(sret, &err);
free(sret);
if (!val) {
applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
goto out;
}
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val || json_is_null(res_val) ||
(err_val && !json_is_null(err_val))) {
char *ss;
if (err_val)
ss = json_dumps(err_val, JSON_INDENT(3));
else
ss = strdup("(unknown reason)");
applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
free(ss);
goto out;
}
sessionid = get_sessionid(res_val);
if (!sessionid)
applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
nonce1 = json_array_string(res_val, 1);
if (!nonce1) {
applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
free(sessionid);
goto out;
}
n2size = json_integer_value(json_array_get(res_val, 2));
if (!n2size) {
applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
free(sessionid);
free(nonce1);
goto out;
}
cg_wlock(&pool->data_lock);
pool->sessionid = sessionid;
pool->nonce1 = nonce1;
pool->n1_len = strlen(nonce1) / 2;
free(pool->nonce1bin);
pool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1);
if (unlikely(!pool->nonce1bin))
quithere(1, "Failed to calloc pool->nonce1bin");
hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
pool->n2size = n2size;
cg_wunlock(&pool->data_lock);
if (sessionid)
applog(LOG_DEBUG, "%s stratum session id: %s", get_pool_name(pool), pool->sessionid);
ret = true;
out:
if (ret) {
if (!pool->stratum_url)
pool->stratum_url = pool->sockaddr_url;
pool->stratum_active = true;
pool->swork.diff = 1;
if (opt_protocol) {
applog(LOG_DEBUG, "%s confirmed mining.subscribe with extranonce1 %s extran2size %d",
get_pool_name(pool), pool->nonce1, pool->n2size);
}
} else {
if (recvd && !noresume) {
/* Reset the sessionid used for stratum resuming in case the pool
* does not support it, or does not know how to respond to the
* presence of the sessionid parameter. */
cg_wlock(&pool->data_lock);
free(pool->sessionid);
free(pool->nonce1);
pool->sessionid = pool->nonce1 = NULL;
cg_wunlock(&pool->data_lock);
applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
noresume = true;
json_decref(val);
goto resend;
}
applog(LOG_DEBUG, "Initiating stratum failed on %s", get_pool_name(pool));
if (sockd) {
applog(LOG_DEBUG, "Suspending stratum on %s", get_pool_name(pool));
suspend_stratum(pool);
}
}
json_decref(val);
return ret;
}
bool restart_stratum(struct pool *pool)
{
applog(LOG_DEBUG, "Restarting stratum on pool %s", get_pool_name(pool));
if (pool->stratum_active)
suspend_stratum(pool);
if (!initiate_stratum(pool))
return false;
if (pool->extranonce_subscribe && !subscribe_extranonce(pool))
return false;
if (!auth_stratum(pool))
return false;
return true;
}
void dev_error(struct cgpu_info *dev, enum dev_reason reason)
{
dev->device_last_not_well = time(NULL);
dev->device_not_well_reason = reason;
switch (reason) {
case REASON_THREAD_FAIL_INIT:
dev->thread_fail_init_count++;
break;
case REASON_THREAD_ZERO_HASH:
dev->thread_zero_hash_count++;
break;
case REASON_THREAD_FAIL_QUEUE:
dev->thread_fail_queue_count++;
break;
case REASON_DEV_SICK_IDLE_60:
dev->dev_sick_idle_60_count++;
break;
case REASON_DEV_DEAD_IDLE_600:
dev->dev_dead_idle_600_count++;
break;
case REASON_DEV_NOSTART:
dev->dev_nostart_count++;
break;
case REASON_DEV_OVER_HEAT:
dev->dev_over_heat_count++;
break;
case REASON_DEV_THERMAL_CUTOFF:
dev->dev_thermal_cutoff_count++;
break;
case REASON_DEV_COMMS_ERROR:
dev->dev_comms_error_count++;
break;
case REASON_DEV_THROTTLE:
dev->dev_throttle_count++;
break;
}
}
/* Realloc an existing string to fit an extra string s, appending s to it. */
void *realloc_strcat(char *ptr, char *s)
{
size_t old = strlen(ptr), len = strlen(s);
char *ret;
if (!len)
return ptr;
len += old + 1;
align_len(&len);
ret = (char *)malloc(len);
if (unlikely(!ret))
quithere(1, "Failed to malloc");
sprintf(ret, "%s%s", ptr, s);
free(ptr);
return ret;
}
void RenameThread(const char* name)
{
char buf[16];
snprintf(buf, sizeof(buf), "cg@%s", name);
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
prctl(PR_SET_NAME, buf, 0, 0, 0);
#elif (defined(__FreeBSD__) || defined(__OpenBSD__))
pthread_set_name_np(pthread_self(), buf);
#elif defined(MAC_OSX)
pthread_setname_np(buf);
#else
// Prevent warnings
(void)buf;
#endif
}
/* sgminer specific wrappers for true unnamed semaphore usage on platforms
* that support them and for apple which does not. We use a single byte across
* a pipe to emulate semaphore behaviour there. */
#ifdef __APPLE__
void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
{
int flags, fd, i;
if (pipe(cgsem->pipefd) == -1)
quitfrom(1, file, func, line, "Failed pipe errno=%d", errno);
/* Make the pipes FD_CLOEXEC to allow them to close should we call
* execv on restart. */
for (i = 0; i < 2; i++) {
fd = cgsem->pipefd[i];
flags = fcntl(fd, F_GETFD, 0);
flags |= FD_CLOEXEC;
if (fcntl(fd, F_SETFD, flags) == -1)
quitfrom(1, file, func, line, "Failed to fcntl errno=%d", errno);
}
}
void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
{
const char buf = 1;
int ret;
retry:
ret = write(cgsem->pipefd[1], &buf, 1);
if (unlikely(ret == 0))
applog(LOG_WARNING, "Failed to write errno=%d" IN_FMT_FFL, errno, file, func, line);
else if (unlikely(ret < 0 && interrupted))
goto retry;
}
void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
{
char buf;
int ret;
retry:
ret = read(cgsem->pipefd[0], &buf, 1);
if (unlikely(ret == 0))
applog(LOG_WARNING, "Failed to read errno=%d" IN_FMT_FFL, errno, file, func, line);
else if (unlikely(ret < 0 && interrupted))
goto retry;
}
void cgsem_destroy(cgsem_t *cgsem)
{
close(cgsem->pipefd[1]);
close(cgsem->pipefd[0]);
}
/* This is similar to sem_timedwait but takes a millisecond value */
int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
{
struct timeval timeout;
int ret, fd;
fd_set rd;
char buf;
retry:
fd = cgsem->pipefd[0];
FD_ZERO(&rd);
FD_SET(fd, &rd);
ms_to_timeval(&timeout, ms);
ret = select(fd + 1, &rd, NULL, NULL, &timeout);
if (ret > 0) {
ret = read(fd, &buf, 1);
return 0;
}
if (likely(!ret))
return ETIMEDOUT;
if (interrupted())
goto retry;
quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
/* We don't reach here */
return 0;
}
/* Reset semaphore count back to zero */
void cgsem_reset(cgsem_t *cgsem)
{
int ret, fd;
fd_set rd;
char buf;
fd = cgsem->pipefd[0];
FD_ZERO(&rd);
FD_SET(fd, &rd);
do {
struct timeval timeout = {0, 0};
ret = select(fd + 1, &rd, NULL, NULL, &timeout);
if (ret > 0)
ret = read(fd, &buf, 1);
else if (unlikely(ret < 0 && interrupted()))
ret = 1;
} while (ret > 0);
}
#else
void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
{
int ret;
if ((ret = sem_init(cgsem, 0, 0)))
quitfrom(1, file, func, line, "Failed to sem_init ret=%d errno=%d", ret, errno);
}
void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
{
if (unlikely(sem_post(cgsem)))
quitfrom(1, file, func, line, "Failed to sem_post errno=%d cgsem=0x%p", errno, cgsem);
}
void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
{
retry:
if (unlikely(sem_wait(cgsem))) {
if (interrupted())
goto retry;
quitfrom(1, file, func, line, "Failed to sem_wait errno=%d cgsem=0x%p", errno, cgsem);
}
}
int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
{
struct timespec abs_timeout, ts_now;
struct timeval tv_now;
int ret;
cgtime(&tv_now);
timeval_to_spec(&ts_now, &tv_now);
ms_to_timespec(&abs_timeout, ms);
retry:
timeraddspec(&abs_timeout, &ts_now);
ret = sem_timedwait(cgsem, &abs_timeout);
if (ret) {
if (likely(sock_timeout()))
return ETIMEDOUT;
if (interrupted())
goto retry;
quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
}
return 0;
}
void cgsem_reset(cgsem_t *cgsem)
{
int ret;
do {
ret = sem_trywait(cgsem);
if (unlikely(ret < 0 && interrupted()))
ret = 0;
} while (!ret);
}
void cgsem_destroy(cgsem_t *cgsem)
{
sem_destroy(cgsem);
}
#endif
/* Provide a completion_timeout helper function for unreliable functions that
* may die due to driver issues etc that time out if the function fails and
* can then reliably return. */
struct cg_completion {
cgsem_t cgsem;
void (*fn)(void *fnarg);
void *fnarg;
};
void *completion_thread(void *arg)
{
struct cg_completion *cgc = (struct cg_completion *)arg;
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
cgc->fn(cgc->fnarg);
cgsem_post(&cgc->cgsem);
return NULL;
}
bool cg_completion_timeout(void *fn, void *fnarg, int timeout)
{
struct cg_completion *cgc;
pthread_t pthread;
bool ret = false;
cgc = (struct cg_completion *)malloc(sizeof(struct cg_completion));
if (unlikely(!cgc))
return ret;
cgsem_init(&cgc->cgsem);
#ifdef _MSC_VER
cgc->fn = (void(__cdecl *)(void *))fn;
#else
cgc->fn = fn;
#endif
cgc->fnarg = fnarg;
pthread_create(&pthread, NULL, completion_thread, (void *)cgc);
ret = cgsem_mswait(&cgc->cgsem, timeout);
if (ret)
pthread_cancel(pthread);
pthread_join(pthread, NULL);
free(cgc);
return !ret;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2211_0 |
crossvul-cpp_data_good_2364_0 | /* hivex - Windows Registry "hive" extraction library.
* Copyright (C) 2009-2011 Red Hat Inc.
* Derived from code by Petter Nordahl-Hagen under a compatible license:
* Copyright (c) 1997-2007 Petter Nordahl-Hagen.
* Derived from code by Markus Stephany under a compatible license:
* Copyright (c) 2000-2004, Markus Stephany.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* See file LICENSE for the full license.
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include <assert.h>
#ifdef HAVE_MMAP
#include <sys/mman.h>
#else
/* On systems without mmap (and munmap), use a replacement function. */
#include "mmap.h"
#endif
#include "full-read.h"
#include "full-write.h"
#include "c-ctype.h"
#include "hivex.h"
#include "hivex-internal.h"
static uint32_t
header_checksum (const hive_h *h)
{
uint32_t *daddr = (uint32_t *) h->addr;
size_t i;
uint32_t sum = 0;
for (i = 0; i < 0x1fc / 4; ++i) {
sum ^= le32toh (*daddr);
daddr++;
}
return sum;
}
#define HIVEX_OPEN_MSGLVL_MASK (HIVEX_OPEN_VERBOSE|HIVEX_OPEN_DEBUG)
hive_h *
hivex_open (const char *filename, int flags)
{
hive_h *h = NULL;
assert (sizeof (struct ntreg_header) == 0x1000);
assert (offsetof (struct ntreg_header, csum) == 0x1fc);
h = calloc (1, sizeof *h);
if (h == NULL)
goto error;
h->msglvl = flags & HIVEX_OPEN_MSGLVL_MASK;
const char *debug = getenv ("HIVEX_DEBUG");
if (debug && STREQ (debug, "1"))
h->msglvl = 2;
DEBUG (2, "created handle %p", h);
h->writable = !!(flags & HIVEX_OPEN_WRITE);
h->filename = strdup (filename);
if (h->filename == NULL)
goto error;
#ifdef O_CLOEXEC
h->fd = open (filename, O_RDONLY | O_CLOEXEC | O_BINARY);
#else
h->fd = open (filename, O_RDONLY | O_BINARY);
#endif
if (h->fd == -1)
goto error;
#ifndef O_CLOEXEC
fcntl (h->fd, F_SETFD, FD_CLOEXEC);
#endif
struct stat statbuf;
if (fstat (h->fd, &statbuf) == -1)
goto error;
h->size = statbuf.st_size;
if (h->size < 0x2000) {
SET_ERRNO (EINVAL,
"%s: file is too small to be a Windows NT Registry hive file",
filename);
goto error;
}
if (!h->writable) {
h->addr = mmap (NULL, h->size, PROT_READ, MAP_SHARED, h->fd, 0);
if (h->addr == MAP_FAILED)
goto error;
DEBUG (2, "mapped file at %p", h->addr);
} else {
h->addr = malloc (h->size);
if (h->addr == NULL)
goto error;
if (full_read (h->fd, h->addr, h->size) < h->size)
goto error;
/* We don't need the file descriptor along this path, since we
* have read all the data.
*/
if (close (h->fd) == -1)
goto error;
h->fd = -1;
}
/* Check header. */
if (h->hdr->magic[0] != 'r' ||
h->hdr->magic[1] != 'e' ||
h->hdr->magic[2] != 'g' ||
h->hdr->magic[3] != 'f') {
SET_ERRNO (ENOTSUP,
"%s: not a Windows NT Registry hive file", filename);
goto error;
}
/* Check major version. */
uint32_t major_ver = le32toh (h->hdr->major_ver);
if (major_ver != 1) {
SET_ERRNO (ENOTSUP,
"%s: hive file major version %" PRIu32 " (expected 1)",
filename, major_ver);
goto error;
}
h->bitmap = calloc (1 + h->size / 32, 1);
if (h->bitmap == NULL)
goto error;
/* Header checksum. */
uint32_t sum = header_checksum (h);
if (sum != le32toh (h->hdr->csum)) {
SET_ERRNO (EINVAL, "%s: bad checksum in hive header", filename);
goto error;
}
/* Last modified time. */
h->last_modified = le64toh ((int64_t) h->hdr->last_modified);
if (h->msglvl >= 2) {
char *name = _hivex_windows_utf16_to_utf8 (h->hdr->name, 64);
fprintf (stderr,
"hivex_open: header fields:\n"
" file version %" PRIu32 ".%" PRIu32 "\n"
" sequence nos %" PRIu32 " %" PRIu32 "\n"
" (sequences nos should match if hive was synched at shutdown)\n"
" last modified %" PRIu64 "\n"
" (Windows filetime, x 100 ns since 1601-01-01)\n"
" original file name %s\n"
" (only 32 chars are stored, name is probably truncated)\n"
" root offset 0x%x + 0x1000\n"
" end of last page 0x%x + 0x1000 (total file size 0x%zx)\n"
" checksum 0x%x (calculated 0x%x)\n",
major_ver, le32toh (h->hdr->minor_ver),
le32toh (h->hdr->sequence1), le32toh (h->hdr->sequence2),
h->last_modified,
name ? name : "(conversion failed)",
le32toh (h->hdr->offset),
le32toh (h->hdr->blocks), h->size,
le32toh (h->hdr->csum), sum);
free (name);
}
h->rootoffs = le32toh (h->hdr->offset) + 0x1000;
h->endpages = le32toh (h->hdr->blocks) + 0x1000;
DEBUG (2, "root offset = 0x%zx", h->rootoffs);
/* We'll set this flag when we see a block with the root offset (ie.
* the root block).
*/
int seen_root_block = 0, bad_root_block = 0;
/* Collect some stats. */
size_t pages = 0; /* Number of hbin pages read. */
size_t smallest_page = SIZE_MAX, largest_page = 0;
size_t blocks = 0; /* Total number of blocks found. */
size_t smallest_block = SIZE_MAX, largest_block = 0, blocks_bytes = 0;
size_t used_blocks = 0; /* Total number of used blocks found. */
size_t used_size = 0; /* Total size (bytes) of used blocks. */
/* Read the pages and blocks. The aim here is to be robust against
* corrupt or malicious registries. So we make sure the loops
* always make forward progress. We add the address of each block
* we read to a hash table so pointers will only reference the start
* of valid blocks.
*/
size_t off;
struct ntreg_hbin_page *page;
for (off = 0x1000; off < h->size; off += le32toh (page->page_size)) {
if (off >= h->endpages)
break;
page = (struct ntreg_hbin_page *) ((char *) h->addr + off);
if (page->magic[0] != 'h' ||
page->magic[1] != 'b' ||
page->magic[2] != 'i' ||
page->magic[3] != 'n') {
SET_ERRNO (ENOTSUP,
"%s: trailing garbage at end of file "
"(at 0x%zx, after %zu pages)",
filename, off, pages);
goto error;
}
size_t page_size = le32toh (page->page_size);
DEBUG (2, "page at 0x%zx, size %zu", off, page_size);
pages++;
if (page_size < smallest_page) smallest_page = page_size;
if (page_size > largest_page) largest_page = page_size;
if (page_size <= sizeof (struct ntreg_hbin_page) ||
(page_size & 0x0fff) != 0) {
SET_ERRNO (ENOTSUP,
"%s: page size %zu at 0x%zx, bad registry",
filename, page_size, off);
goto error;
}
/* Read the blocks in this page. */
size_t blkoff;
struct ntreg_hbin_block *block;
size_t seg_len;
for (blkoff = off + 0x20;
blkoff < off + page_size;
blkoff += seg_len) {
blocks++;
int is_root = blkoff == h->rootoffs;
if (is_root)
seen_root_block = 1;
block = (struct ntreg_hbin_block *) ((char *) h->addr + blkoff);
int used;
seg_len = block_len (h, blkoff, &used);
if (seg_len <= 4 || (seg_len & 3) != 0) {
SET_ERRNO (ENOTSUP,
"%s: block size %" PRIu32 " at 0x%zx, bad registry",
filename, le32toh (block->seg_len), blkoff);
goto error;
}
if (h->msglvl >= 2) {
unsigned char *id = (unsigned char *) block->id;
int id0 = id[0], id1 = id[1];
fprintf (stderr, "%s: %s: "
"%s block id %d,%d (%c%c) at 0x%zx size %zu%s\n",
"hivex", __func__,
used ? "used" : "free",
id0, id1,
c_isprint (id0) ? id0 : '.',
c_isprint (id1) ? id1 : '.',
blkoff,
seg_len, is_root ? " (root)" : "");
}
blocks_bytes += seg_len;
if (seg_len < smallest_block) smallest_block = seg_len;
if (seg_len > largest_block) largest_block = seg_len;
if (is_root && !used)
bad_root_block = 1;
if (used) {
used_blocks++;
used_size += seg_len;
/* Root block must be an nk-block. */
if (is_root && (block->id[0] != 'n' || block->id[1] != 'k'))
bad_root_block = 1;
/* Note this blkoff is a valid address. */
BITMAP_SET (h->bitmap, blkoff);
}
}
}
if (!seen_root_block) {
SET_ERRNO (ENOTSUP, "%s: no root block found", filename);
goto error;
}
if (bad_root_block) {
SET_ERRNO (ENOTSUP, "%s: bad root block (free or not nk)", filename);
goto error;
}
DEBUG (1, "successfully read Windows Registry hive file:\n"
" pages: %zu [sml: %zu, lge: %zu]\n"
" blocks: %zu [sml: %zu, avg: %zu, lge: %zu]\n"
" blocks used: %zu\n"
" bytes used: %zu",
pages, smallest_page, largest_page,
blocks, smallest_block, blocks_bytes / blocks, largest_block,
used_blocks, used_size);
return h;
error:;
int err = errno;
if (h) {
free (h->bitmap);
if (h->addr && h->size && h->addr != MAP_FAILED) {
if (!h->writable)
munmap (h->addr, h->size);
else
free (h->addr);
}
if (h->fd >= 0)
close (h->fd);
free (h->filename);
free (h);
}
errno = err;
return NULL;
}
int
hivex_close (hive_h *h)
{
int r;
DEBUG (1, "hivex_close");
free (h->bitmap);
if (!h->writable)
munmap (h->addr, h->size);
else
free (h->addr);
if (h->fd >= 0)
r = close (h->fd);
else
r = 0;
free (h->filename);
free (h);
return r;
}
int
hivex_commit (hive_h *h, const char *filename, int flags)
{
int fd;
if (flags != 0) {
SET_ERRNO (EINVAL, "flags != 0");
return -1;
}
CHECK_WRITABLE (-1);
filename = filename ? : h->filename;
#ifdef O_CLOEXEC
fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY|O_CLOEXEC|O_BINARY,
0666);
#else
fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY|O_BINARY, 0666);
#endif
if (fd == -1)
return -1;
#ifndef O_CLOEXEC
fcntl (fd, F_SETFD, FD_CLOEXEC);
#endif
/* Update the header fields. */
uint32_t sequence = le32toh (h->hdr->sequence1);
sequence++;
h->hdr->sequence1 = htole32 (sequence);
h->hdr->sequence2 = htole32 (sequence);
/* XXX Ought to update h->hdr->last_modified. */
h->hdr->blocks = htole32 (h->endpages - 0x1000);
/* Recompute header checksum. */
uint32_t sum = header_checksum (h);
h->hdr->csum = htole32 (sum);
DEBUG (2, "hivex_commit: new header checksum: 0x%x", sum);
if (full_write (fd, h->addr, h->size) != h->size) {
int err = errno;
close (fd);
errno = err;
return -1;
}
if (close (fd) == -1)
return -1;
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2364_0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.