--- CBOR-XS/XS.xs 2013/11/28 11:43:26 1.31 +++ CBOR-XS/XS.xs 2016/11/26 00:47:02 1.60 @@ -9,6 +9,7 @@ #include #include +#define ECB_NO_THREADS 1 #include "ecb.h" // compatibility with perl <5.18 @@ -25,44 +26,86 @@ # define SvREFCNT_dec_NN(sv) SvREFCNT_dec (sv) #endif +// known major and minor types +enum cbor_type +{ + MAJOR_SHIFT = 5, + MINOR_MASK = 0x1f, + + MAJOR_POS_INT = 0 << MAJOR_SHIFT, + MAJOR_NEG_INT = 1 << MAJOR_SHIFT, + MAJOR_BYTES = 2 << MAJOR_SHIFT, + MAJOR_TEXT = 3 << MAJOR_SHIFT, + MAJOR_ARRAY = 4 << MAJOR_SHIFT, + MAJOR_MAP = 5 << MAJOR_SHIFT, + MAJOR_TAG = 6 << MAJOR_SHIFT, + MAJOR_MISC = 7 << MAJOR_SHIFT, + + // INT/STRING/ARRAY/MAP subtypes + LENGTH_EXT1 = 24, + LENGTH_EXT2 = 25, + LENGTH_EXT4 = 26, + LENGTH_EXT8 = 27, + + // SIMPLE types (effectively MISC subtypes) + SIMPLE_FALSE = 20, + SIMPLE_TRUE = 21, + SIMPLE_NULL = 22, + SIMPLE_UNDEF = 23, + + // MISC subtype (unused) + MISC_EXT1 = 24, + MISC_FLOAT16 = 25, + MISC_FLOAT32 = 26, + MISC_FLOAT64 = 27, + + // BYTES/TEXT/ARRAY/MAP + MINOR_INDEF = 31, +}; + // known tags enum cbor_tag { - // extensions - CBOR_TAG_STRINGREF = 25, // http://cbor.schmorp.de/stringref - CBOR_TAG_PERL_OBJECT = 26, // http://cbor.schmorp.de/perl-object - CBOR_TAG_GENERIC_OBJECT = 27, // http://cbor.schmorp.de/generic-object - CBOR_TAG_VALUE_SHAREABLE = 28, // http://cbor.schmorp.de/value-sharing - CBOR_TAG_VALUE_SHAREDREF = 29, // http://cbor.schmorp.de/value-sharing - CBOR_TAG_STRINGREF_NAMESPACE = 256, // http://cbor.schmorp.de/stringref - CBOR_TAG_INDIRECTION = 22098, // http://cbor.schmorp.de/indirection - - // rfc7049 - CBOR_TAG_DATETIME = 0, // rfc4287, utf-8 - CBOR_TAG_TIMESTAMP = 1, // unix timestamp, any - CBOR_TAG_POS_BIGNUM = 2, // byte string - CBOR_TAG_NEG_BIGNUM = 3, // byte string - CBOR_TAG_DECIMAL = 4, // decimal fraction, array - CBOR_TAG_BIGFLOAT = 5, // array - - CBOR_TAG_CONV_B64U = 21, // base64url, any - CBOR_TAG_CONV_B64 = 22, // base64, any - CBOR_TAG_CONV_HEX = 23, // base16, any - CBOR_TAG_CBOR = 24, // embedded cbor, byte string - - CBOR_TAG_URI = 32, // URI rfc3986, utf-8 - CBOR_TAG_B64U = 33, // base64url rfc4648, utf-8 - CBOR_TAG_B64 = 34, // base6 rfc46484, utf-8 - CBOR_TAG_REGEX = 35, // regex pcre/ecma262, utf-8 - CBOR_TAG_MIME = 36, // mime message rfc2045, utf-8 + // extensions + CBOR_TAG_STRINGREF = 25, // http://cbor.schmorp.de/stringref + CBOR_TAG_PERL_OBJECT = 26, // http://cbor.schmorp.de/perl-object + CBOR_TAG_GENERIC_OBJECT = 27, // http://cbor.schmorp.de/generic-object + CBOR_TAG_VALUE_SHAREABLE = 28, // http://cbor.schmorp.de/value-sharing + CBOR_TAG_VALUE_SHAREDREF = 29, // http://cbor.schmorp.de/value-sharing + CBOR_TAG_STRINGREF_NAMESPACE = 256, // http://cbor.schmorp.de/stringref + CBOR_TAG_INDIRECTION = 22098, // http://cbor.schmorp.de/indirection + + // rfc7049 + CBOR_TAG_DATETIME = 0, // rfc4287, utf-8 + CBOR_TAG_TIMESTAMP = 1, // unix timestamp, any + CBOR_TAG_POS_BIGNUM = 2, // byte string + CBOR_TAG_NEG_BIGNUM = 3, // byte string + CBOR_TAG_DECIMAL = 4, // decimal fraction, array + CBOR_TAG_BIGFLOAT = 5, // array + + CBOR_TAG_CONV_B64U = 21, // base64url, any + CBOR_TAG_CONV_B64 = 22, // base64, any + CBOR_TAG_CONV_HEX = 23, // base16, any + CBOR_TAG_CBOR = 24, // embedded cbor, byte string + + CBOR_TAG_URI = 32, // URI rfc3986, utf-8 + CBOR_TAG_B64U = 33, // base64url rfc4648, utf-8 + CBOR_TAG_B64 = 34, // base6 rfc46484, utf-8 + CBOR_TAG_REGEX = 35, // regex pcre/ecma262, utf-8 + CBOR_TAG_MIME = 36, // mime message rfc2045, utf-8 - CBOR_TAG_MAGIC = 55799 // self-describe cbor + CBOR_TAG_MAGIC = 55799, // self-describe cbor }; #define F_SHRINK 0x00000001UL #define F_ALLOW_UNKNOWN 0x00000002UL -#define F_ALLOW_SHARING 0x00000004UL //TODO -#define F_ALLOW_STRINGREF 0x00000008UL //TODO +#define F_ALLOW_SHARING 0x00000004UL +#define F_ALLOW_CYCLES 0x00000008UL +#define F_FORBID_OBJECTS 0x00000010UL +#define F_PACK_STRINGS 0x00000020UL +#define F_TEXT_KEYS 0x00000040UL +#define F_TEXT_STRINGS 0x00000080UL +#define F_VALIDATE_UTF8 0x00000100UL #define INIT_SIZE 32 // initial scalar size to be allocated @@ -91,6 +134,11 @@ U32 max_depth; STRLEN max_size; SV *filter; + + // for the incremental parser + STRLEN incr_pos; // the current offset into the text + STRLEN incr_need; // minimum bytes needed to decode + AV *incr_count; // for every nesting level, the number of outstanding values, or -1 for indef. } CBOR; ecb_inline void @@ -104,6 +152,7 @@ cbor_free (CBOR *cbor) { SvREFCNT_dec (cbor->filter); + SvREFCNT_dec (cbor->incr_count); } ///////////////////////////////////////////////////////////////////////////// @@ -191,22 +240,22 @@ { need (enc, 9); - if (ecb_expect_true (len < 24)) + if (ecb_expect_true (len < LENGTH_EXT1)) *enc->cur++ = major | len; - else if (ecb_expect_true (len <= 0xff)) + else if (ecb_expect_true (len <= 0xffU)) { - *enc->cur++ = major | 24; + *enc->cur++ = major | LENGTH_EXT1; *enc->cur++ = len; } - else if (len <= 0xffff) + else if (len <= 0xffffU) { - *enc->cur++ = major | 25; + *enc->cur++ = major | LENGTH_EXT2; *enc->cur++ = len >> 8; *enc->cur++ = len; } - else if (len <= 0xffffffff) + else if (len <= 0xffffffffU) { - *enc->cur++ = major | 26; + *enc->cur++ = major | LENGTH_EXT4; *enc->cur++ = len >> 24; *enc->cur++ = len >> 16; *enc->cur++ = len >> 8; @@ -214,7 +263,7 @@ } else { - *enc->cur++ = major | 27; + *enc->cur++ = major | LENGTH_EXT8; *enc->cur++ = len >> 56; *enc->cur++ = len >> 48; *enc->cur++ = len >> 40; @@ -229,22 +278,52 @@ ecb_inline void encode_tag (enc_t *enc, UV tag) { - encode_uint (enc, 0xc0, tag); + encode_uint (enc, MAJOR_TAG, tag); +} + +// exceptional (hopefully) slow path for byte strings that need to be utf8-encoded +ecb_noinline static void +encode_str_utf8 (enc_t *enc, int utf8, char *str, STRLEN len) +{ + STRLEN ulen = len; + U8 *p, *pend = (U8 *)str + len; + + for (p = (U8 *)str; p < pend; ++p) + ulen += *p >> 7; // count set high bits + + encode_uint (enc, MAJOR_TEXT, ulen); + + need (enc, ulen); + for (p = (U8 *)str; p < pend; ++p) + if (*p < 0x80) + *enc->cur++ = *p; + else + { + *enc->cur++ = 0xc0 + (*p >> 6); + *enc->cur++ = 0x80 + (*p & 63); + } } ecb_inline void -encode_str (enc_t *enc, int utf8, char *str, STRLEN len) +encode_str (enc_t *enc, int upgrade_utf8, int utf8, char *str, STRLEN len) { - encode_uint (enc, utf8 ? 0x60 : 0x40, len); + if (ecb_expect_false (upgrade_utf8)) + if (!utf8) + { + encode_str_utf8 (enc, utf8, str, len); + return; + } + + encode_uint (enc, utf8 ? MAJOR_TEXT : MAJOR_BYTES, len); need (enc, len); memcpy (enc->cur, str, len); enc->cur += len; } -static void -encode_strref (enc_t *enc, int utf8, char *str, STRLEN len) +ecb_inline void +encode_strref (enc_t *enc, int upgrade_utf8, int utf8, char *str, STRLEN len) { - if (ecb_expect_false (enc->cbor.flags & F_ALLOW_STRINGREF)) + if (ecb_expect_false (enc->cbor.flags & F_PACK_STRINGS)) { SV **svp = hv_fetch (enc->stringref[!!utf8], str, len, 1); @@ -252,7 +331,7 @@ { // already registered, use stringref encode_tag (enc, CBOR_TAG_STRINGREF); - encode_uint (enc, 0x00, SvUV (*svp)); + encode_uint (enc, MAJOR_POS_INT, SvUV (*svp)); return; } else if (len >= minimum_string_length (enc->stringref_idx)) @@ -263,7 +342,7 @@ } } - encode_str (enc, utf8, str, len); + encode_str (enc, upgrade_utf8, utf8, str, len); } static void encode_sv (enc_t *enc, SV *sv); @@ -278,13 +357,20 @@ ++enc->depth; - encode_uint (enc, 0x80, len + 1); + encode_uint (enc, MAJOR_ARRAY, len + 1); - for (i = 0; i <= len; ++i) - { - SV **svp = av_fetch (av, i, 0); - encode_sv (enc, svp ? *svp : &PL_sv_undef); - } + if (SvMAGICAL (av)) + for (i = 0; i <= len; ++i) + { + SV **svp = av_fetch (av, i, 0); + encode_sv (enc, svp ? *svp : &PL_sv_undef); + } + else + for (i = 0; i <= len; ++i) + { + SV *sv = AvARRAY (av)[i]; + encode_sv (enc, sv ? sv : &PL_sv_undef); + } --enc->depth; } @@ -303,22 +389,22 @@ int mg = SvMAGICAL (hv); if (mg) - encode_ch (enc, 0xa0 | 31); + encode_ch (enc, MAJOR_MAP | MINOR_INDEF); else - encode_uint (enc, 0xa0, pairs); + encode_uint (enc, MAJOR_MAP, pairs); while ((he = hv_iternext (hv))) { if (HeKLEN (he) == HEf_SVKEY) encode_sv (enc, HeSVKEY (he)); else - encode_strref (enc, HeKUTF8 (he), HeKEY (he), HeKLEN (he)); + encode_strref (enc, enc->cbor.flags & (F_TEXT_KEYS | F_TEXT_STRINGS), HeKUTF8 (he), HeKEY (he), HeKLEN (he)); encode_sv (enc, ecb_expect_false (mg) ? hv_iterval (hv, he) : HeVAL (he)); } if (mg) - encode_ch (enc, 0xe0 | 31); + encode_ch (enc, MAJOR_MISC | MINOR_INDEF); --enc->depth; } @@ -329,28 +415,6 @@ { SvGETMAGIC (sv); - if (ecb_expect_false (enc->cbor.flags & F_ALLOW_SHARING) - && ecb_expect_false (SvREFCNT (sv) > 1)) - { - if (!enc->shareable) - enc->shareable = (HV *)sv_2mortal ((SV *)newHV ()); - - SV **svp = hv_fetch (enc->shareable, (char *)&sv, sizeof (sv), 1); - - if (SvOK (*svp)) - { - encode_tag (enc, CBOR_TAG_VALUE_SHAREDREF); - encode_uint (enc, 0x00, SvUV (*svp)); - return; - } - else - { - sv_setuv (*svp, enc->shareable_idx); - ++enc->shareable_idx; - encode_tag (enc, CBOR_TAG_VALUE_SHAREABLE); - } - } - svtype svt = SvTYPE (sv); if (ecb_expect_false (SvOBJECT (sv))) @@ -366,25 +430,65 @@ : gv_stashpv ("CBOR::XS::Tagged" , 1); HV *stash = SvSTASH (sv); - GV *method; if (stash == boolean_stash) - encode_ch (enc, SvIV (sv) ? 0xe0 | 21 : 0xe0 | 20); + { + encode_ch (enc, SvIV (sv) ? MAJOR_MISC | SIMPLE_TRUE : MAJOR_MISC | SIMPLE_FALSE); + return; + } else if (stash == error_stash) - encode_ch (enc, 0xe0 | 23); + { + encode_ch (enc, MAJOR_MISC | SIMPLE_UNDEF); + return; + } else if (stash == tagged_stash) { if (svt != SVt_PVAV) croak ("encountered CBOR::XS::Tagged object that isn't an array"); - encode_uint (enc, 0xc0, SvUV (*av_fetch ((AV *)sv, 0, 1))); + encode_uint (enc, MAJOR_TAG, SvUV (*av_fetch ((AV *)sv, 0, 1))); encode_sv (enc, *av_fetch ((AV *)sv, 1, 1)); + + return; + } + } + + if (ecb_expect_false (SvREFCNT (sv) > 1) + && ecb_expect_false (enc->cbor.flags & F_ALLOW_SHARING)) + { + if (!enc->shareable) + enc->shareable = (HV *)sv_2mortal ((SV *)newHV ()); + + SV **svp = hv_fetch (enc->shareable, (char *)&sv, sizeof (sv), 1); + + if (SvOK (*svp)) + { + encode_tag (enc, CBOR_TAG_VALUE_SHAREDREF); + encode_uint (enc, MAJOR_POS_INT, SvUV (*svp)); + return; } + else + { + sv_setuv (*svp, enc->shareable_idx); + ++enc->shareable_idx; + encode_tag (enc, CBOR_TAG_VALUE_SHAREABLE); + } + } + + if (ecb_expect_false (SvOBJECT (sv))) + { + HV *stash = SvSTASH (sv); + GV *method; + + if (enc->cbor.flags & F_FORBID_OBJECTS) + croak ("encountered object '%s', but forbid_objects is enabled", + SvPV_nolen (sv_2mortal (newRV_inc (sv)))); else if ((method = gv_fetchmethod_autoload (stash, "TO_CBOR", 0))) { dSP; - ENTER; SAVETMPS; PUSHMARK (SP); + ENTER; SAVETMPS; + PUSHMARK (SP); // we re-bless the reference to get overload and other niceties right XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), stash)); @@ -407,7 +511,9 @@ { dSP; - ENTER; SAVETMPS; PUSHMARK (SP); + ENTER; SAVETMPS; + SAVESTACK_POS (); + PUSHMARK (SP); EXTEND (SP, 2); // we re-bless the reference to get overload and other niceties right PUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), stash)); @@ -422,8 +528,8 @@ croak ("%s::FREEZE(CBOR) method returned same object as was passed instead of a new one", HvNAME (stash)); encode_tag (enc, CBOR_TAG_PERL_OBJECT); - encode_uint (enc, 0x80, count + 1); - encode_strref (enc, HvNAMEUTF8 (stash), HvNAME (stash), HvNAMELEN (stash)); + encode_uint (enc, MAJOR_ARRAY, count + 1); + encode_strref (enc, 0, HvNAMEUTF8 (stash), HvNAME (stash), HvNAMELEN (stash)); while (count) encode_sv (enc, SP[1 - count--]); @@ -454,14 +560,14 @@ need (enc, 9); - if (ecb_expect_false (nv == (U32)nv)) - encode_uint (enc, 0x00, (U32)nv); + if (ecb_expect_false (nv == (NV)(U32)nv)) + encode_uint (enc, MAJOR_POS_INT, (U32)nv); //TODO: maybe I32? else if (ecb_expect_false (nv == (float)nv)) { uint32_t fp = ecb_float_to_binary32 (nv); - *enc->cur++ = 0xe0 | 26; + *enc->cur++ = MAJOR_MISC | MISC_FLOAT32; if (!ecb_big_endian ()) fp = ecb_bswap32 (fp); @@ -473,7 +579,7 @@ { uint64_t fp = ecb_double_to_binary64 (nv); - *enc->cur++ = 0xe0 | 27; + *enc->cur++ = MAJOR_MISC | MISC_FLOAT64; if (!ecb_big_endian ()) fp = ecb_bswap64 (fp); @@ -492,25 +598,25 @@ { STRLEN len; char *str = SvPV (sv, len); - encode_strref (enc, SvUTF8 (sv), str, len); + encode_strref (enc, enc->cbor.flags & F_TEXT_STRINGS, SvUTF8 (sv), str, len); } else if (SvNOKp (sv)) encode_nv (enc, sv); else if (SvIOKp (sv)) { if (SvIsUV (sv)) - encode_uint (enc, 0x00, SvUVX (sv)); + encode_uint (enc, MAJOR_POS_INT, SvUVX (sv)); else if (SvIVX (sv) >= 0) - encode_uint (enc, 0x00, SvIVX (sv)); + encode_uint (enc, MAJOR_POS_INT, SvIVX (sv)); else - encode_uint (enc, 0x20, -(SvIVX (sv) + 1)); + encode_uint (enc, MAJOR_NEG_INT, -(SvIVX (sv) + 1)); } else if (SvROK (sv)) encode_rv (enc, SvRV (sv)); else if (!SvOK (sv)) - encode_ch (enc, 0xe0 | 22); + encode_ch (enc, MAJOR_MISC | SIMPLE_NULL); else if (enc->cbor.flags & F_ALLOW_UNKNOWN) - encode_ch (enc, 0xe0 | 23); + encode_ch (enc, MAJOR_MISC | SIMPLE_UNDEF); else croak ("encountered perl type (%s,0x%x) that CBOR cannot handle, check your input data", SvPV_nolen (sv), (unsigned int)SvFLAGS (sv)); @@ -519,7 +625,7 @@ static SV * encode_cbor (SV *scalar, CBOR *cbor) { - enc_t enc = { }; + enc_t enc = { 0 }; enc.cbor = *cbor; enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); @@ -528,7 +634,7 @@ SvPOK_only (enc.sv); - if (cbor->flags & F_ALLOW_STRINGREF) + if (cbor->flags & F_PACK_STRINGS) { encode_tag (&enc, CBOR_TAG_STRINGREF_NAMESPACE); enc.stringref[0]= (HV *)sv_2mortal ((SV *)newHV ()); @@ -561,59 +667,105 @@ AV *shareable; AV *stringref; SV *decode_tagged; + SV *err_sv; // optional sv for error, needs to be freed } dec_t; -#define ERR(reason) SB if (!dec->err) dec->err = reason; goto fail; SE +// set dec->err to ERRSV +ecb_cold static void +err_errsv (dec_t *dec) +{ + if (!dec->err) + { + dec->err_sv = newSVsv (ERRSV); + + // chop off the trailing \n + SvCUR_set (dec->err_sv, SvCUR (dec->err_sv) - 1); + *SvEND (dec->err_sv) = 0; + + dec->err = SvPVutf8_nolen (dec->err_sv); + } +} -#define WANT(len) if (ecb_expect_false (dec->cur + len > dec->end)) ERR ("unexpected end of CBOR data") +// the following functions are used to reduce code size and help the compiler to optimise +ecb_cold static void +err_set (dec_t *dec, const char *reason) +{ + if (!dec->err) + dec->err = reason; +} + +ecb_cold static void +err_unexpected_end (dec_t *dec) +{ + err_set (dec, "unexpected end of CBOR data"); +} -#define DEC_INC_DEPTH if (++dec->depth > dec->cbor.max_depth) ERR (ERR_NESTING_EXCEEDED) +ecb_cold static void +err_nesting_exceeded (dec_t *dec) +{ + err_set (dec, ERR_NESTING_EXCEEDED); +} + +#define ERR_DO(do) SB do; goto fail; SE +#define ERR(reason) ERR_DO (err_set (dec, reason)) +#define ERR_ERRSV ERR_DO (err_errsv (dec)) + +#define WANT(len) if (ecb_expect_false ((UV)(dec->end - dec->cur) < (UV)len)) ERR_DO (err_unexpected_end (dec)) + +#define DEC_INC_DEPTH if (ecb_expect_false (++dec->depth > dec->cbor.max_depth)) ERR (ERR_NESTING_EXCEEDED) #define DEC_DEC_DEPTH --dec->depth static UV decode_uint (dec_t *dec) { - switch (*dec->cur & 31) + U8 m = *dec->cur & MINOR_MASK; + ++dec->cur; + + if (ecb_expect_true (m < LENGTH_EXT1)) + return m; + else if (ecb_expect_true (m == LENGTH_EXT1)) { - case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: - case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: - case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23: - return *dec->cur++ & 31; - - case 24: - WANT (2); - dec->cur += 2; - return dec->cur[-1]; - - case 25: - WANT (3); - dec->cur += 3; - return (((UV)dec->cur[-2]) << 8) - | ((UV)dec->cur[-1]); - - case 26: - WANT (5); - dec->cur += 5; - return (((UV)dec->cur[-4]) << 24) - | (((UV)dec->cur[-3]) << 16) - | (((UV)dec->cur[-2]) << 8) - | ((UV)dec->cur[-1]); - - case 27: - WANT (9); - dec->cur += 9; - return (((UV)dec->cur[-8]) << 56) - | (((UV)dec->cur[-7]) << 48) - | (((UV)dec->cur[-6]) << 40) - | (((UV)dec->cur[-5]) << 32) - | (((UV)dec->cur[-4]) << 24) - | (((UV)dec->cur[-3]) << 16) - | (((UV)dec->cur[-2]) << 8) - | ((UV)dec->cur[-1]); + WANT (1); + dec->cur += 1; + return dec->cur[-1]; + } + else if (ecb_expect_true (m == LENGTH_EXT2)) + { + WANT (2); + dec->cur += 2; + return (((UV)dec->cur[-2]) << 8) + | ((UV)dec->cur[-1]); + } + else if (ecb_expect_true (m == LENGTH_EXT4)) + { + WANT (4); + dec->cur += 4; + return (((UV)dec->cur[-4]) << 24) + | (((UV)dec->cur[-3]) << 16) + | (((UV)dec->cur[-2]) << 8) + | ((UV)dec->cur[-1]); + } + else if (ecb_expect_true (m == LENGTH_EXT8)) + { + WANT (8); + dec->cur += 8; - default: - ERR ("corrupted CBOR data (unsupported integer minor encoding)"); + return +#if UVSIZE < 8 + 0 +#else + (((UV)dec->cur[-8]) << 56) + | (((UV)dec->cur[-7]) << 48) + | (((UV)dec->cur[-6]) << 40) + | (((UV)dec->cur[-5]) << 32) +#endif + | (((UV)dec->cur[-4]) << 24) + | (((UV)dec->cur[-3]) << 16) + | (((UV)dec->cur[-2]) << 8) + | ((UV)dec->cur[-1]); } + else + ERR ("corrupted CBOR data (unsupported integer minor encoding)"); fail: return 0; @@ -628,7 +780,7 @@ DEC_INC_DEPTH; - if ((*dec->cur & 31) == 31) + if (*dec->cur == (MAJOR_ARRAY | MINOR_INDEF)) { ++dec->cur; @@ -636,7 +788,7 @@ { WANT (1); - if (*dec->cur == (0xe0 | 31)) + if (*dec->cur == (MAJOR_MISC | MINOR_INDEF)) { ++dec->cur; break; @@ -647,8 +799,9 @@ } else { - int i, len = decode_uint (dec); + UV i, len = decode_uint (dec); + WANT (len); // complexity check for av_fill - need at least one byte per value, do not allow supersize arrays av_fill (av, len - 1); for (i = 0; i < len; ++i) @@ -671,29 +824,29 @@ // byte or utf-8 strings as keys, but only when !stringref if (ecb_expect_true (!dec->stringref)) - if (*dec->cur >= 0x40 && *dec->cur <= 0x40 + 27) + if (ecb_expect_true ((U8)(*dec->cur - MAJOR_BYTES) <= LENGTH_EXT8)) { - I32 len = decode_uint (dec); + STRLEN len = decode_uint (dec); char *key = (char *)dec->cur; + WANT (len); dec->cur += len; - if (ecb_expect_false (dec->stringref)) - av_push (dec->stringref, newSVpvn (key, len)); - - hv_store (hv, key, len, decode_sv (dec), 0); + hv_store (hv, key, len, decode_sv (dec), 0); return; } - else if (*dec->cur >= 0x60 && *dec->cur <= 0x60 + 27) + else if (ecb_expect_true ((U8)(*dec->cur - MAJOR_TEXT) <= LENGTH_EXT8)) { - I32 len = decode_uint (dec); + STRLEN len = decode_uint (dec); char *key = (char *)dec->cur; + WANT (len); dec->cur += len; - if (ecb_expect_false (dec->stringref)) - av_push (dec->stringref, newSVpvn_utf8 (key, len, 1)); + if (ecb_expect_false (dec->cbor.flags & F_VALIDATE_UTF8)) + if (!is_utf8_string (key, len)) + ERR ("corrupted CBOR data (invalid UTF-8 in map key)"); hv_store (hv, key, -len, decode_sv (dec), 0); @@ -703,8 +856,39 @@ SV *k = decode_sv (dec); SV *v = decode_sv (dec); + // we leak memory if uncaught exceptions are thrown by random magical + // methods, and this is hopefully the only place where it can happen, + // so if there is a chance of an exception, take the very slow path. + // since catching exceptions is "undocumented/internal/forbidden" by + // the new p5p powers, we need to call out to a perl function :/ + if (ecb_expect_false (SvAMAGIC (k))) + { + dSP; + + ENTER; SAVETMPS; + PUSHMARK (SP); + EXTEND (SP, 3); + PUSHs (sv_2mortal (newRV_inc ((SV *)hv))); + PUSHs (sv_2mortal (k)); + PUSHs (sv_2mortal (v)); + + PUTBACK; + call_pv ("CBOR::XS::_hv_store", G_VOID | G_DISCARD | G_EVAL); + SPAGAIN; + + FREETMPS; LEAVE; + + if (SvTRUE (ERRSV)) + ERR_ERRSV; + + return; + } + hv_store_ent (hv, k, v, 0); SvREFCNT_dec (k); + +fail: + ; } static SV * @@ -714,7 +898,7 @@ DEC_INC_DEPTH; - if ((*dec->cur & 31) == 31) + if (*dec->cur == (MAJOR_MAP | MINOR_INDEF)) { ++dec->cur; @@ -722,7 +906,7 @@ { WANT (1); - if (*dec->cur == (0xe0 | 31)) + if (*dec->cur == (MAJOR_MISC | MINOR_INDEF)) { ++dec->cur; break; @@ -733,7 +917,9 @@ } else { - int pairs = decode_uint (dec); + UV pairs = decode_uint (dec); + + WANT (pairs); // complexity check - need at least one byte per value, do not allow supersize hashes while (pairs--) decode_he (dec, hv); @@ -753,24 +939,33 @@ { SV *sv = 0; - if ((*dec->cur & 31) == 31) + if ((*dec->cur & MINOR_MASK) == MINOR_INDEF) { + // indefinite length strings ++dec->cur; + U8 major = *dec->cur & MAJOR_MISC; + sv = newSVpvn ("", 0); - // not very fast, and certainly not robust against illegal input for (;;) { WANT (1); - if (*dec->cur == (0xe0 | 31)) - { - ++dec->cur; - break; - } + if ((*dec->cur - major) > LENGTH_EXT8) + if (*dec->cur == (MAJOR_MISC | MINOR_INDEF)) + { + ++dec->cur; + break; + } + else + ERR ("corrupted CBOR data (invalid chunks in indefinite length string)"); + + STRLEN len = decode_uint (dec); - sv_catsv (sv, decode_sv (dec)); + WANT (len); + sv_catpvn (sv, dec->cur, len); + dec->cur += len; } } else @@ -787,7 +982,13 @@ } if (utf8) - SvUTF8_on (sv); + { + if (ecb_expect_false (dec->cbor.flags & F_VALIDATE_UTF8)) + if (!is_utf8_string (SvPVX (sv), SvCUR (sv))) + ERR ("corrupted CBOR data (invalid UTF-8 in text string)"); + + SvUTF8_on (sv); + } return sv; @@ -816,20 +1017,22 @@ case CBOR_TAG_STRINGREF_NAMESPACE: { - ENTER; SAVETMPS; + // do nmot use SAVETMPS/FREETMPS, as these will + // erase mortalised caches, e.g. "shareable" + ENTER; SAVESPTR (dec->stringref); dec->stringref = (AV *)sv_2mortal ((SV *)newAV ()); sv = decode_sv (dec); - FREETMPS; LEAVE; + LEAVE; } break; case CBOR_TAG_STRINGREF: { - if ((*dec->cur >> 5) != 0) + if ((*dec->cur >> MAJOR_SHIFT) != (MAJOR_POS_INT >> MAJOR_SHIFT)) ERR ("corrupted CBOR data (stringref index not an unsigned integer)"); UV idx = decode_uint (dec); @@ -846,18 +1049,28 @@ if (ecb_expect_false (!dec->shareable)) dec->shareable = (AV *)sv_2mortal ((SV *)newAV ()); - sv = newSV (0); - av_push (dec->shareable, SvREFCNT_inc_NN (sv)); + if (dec->cbor.flags & F_ALLOW_CYCLES) + { + sv = newSV (0); + av_push (dec->shareable, SvREFCNT_inc_NN (sv)); - SV *osv = decode_sv (dec); - sv_setsv (sv, osv); - SvREFCNT_dec_NN (osv); + SV *osv = decode_sv (dec); + sv_setsv (sv, osv); + SvREFCNT_dec_NN (osv); + } + else + { + av_push (dec->shareable, &PL_sv_undef); + int idx = AvFILLp (dec->shareable); + sv = decode_sv (dec); + av_store (dec->shareable, idx, SvREFCNT_inc_NN (sv)); + } } break; case CBOR_TAG_VALUE_SHAREDREF: { - if ((*dec->cur >> 5) != 0) + if ((*dec->cur >> MAJOR_SHIFT) != (MAJOR_POS_INT >> MAJOR_SHIFT)) ERR ("corrupted CBOR data (sharedref index not an unsigned integer)"); UV idx = decode_uint (dec); @@ -866,11 +1079,17 @@ ERR ("corrupted CBOR data (sharedref index out of bounds)"); sv = SvREFCNT_inc_NN (AvARRAY (dec->shareable)[idx]); + + if (sv == &PL_sv_undef) + ERR ("cyclic CBOR data structure found, but allow_cycles is not enabled"); } break; case CBOR_TAG_PERL_OBJECT: { + if (dec->cbor.flags & F_FORBID_OBJECTS) + goto filter; + sv = decode_sv (dec); if (!SvROK (sv) || SvTYPE (SvRV (sv)) != SVt_PVAV) @@ -890,7 +1109,8 @@ dSP; - ENTER; SAVETMPS; PUSHMARK (SP); + ENTER; SAVETMPS; + PUSHMARK (SP); EXTEND (SP, len + 1); // we re-bless the reference to get overload and other niceties right PUSHs (*av_fetch (av, 0, 1)); @@ -908,7 +1128,7 @@ if (SvTRUE (ERRSV)) { FREETMPS; LEAVE; - ERR (SvPVutf8_nolen (sv_2mortal (SvREFCNT_inc (ERRSV)))); + ERR_ERRSV; } SvREFCNT_dec (sv); @@ -921,13 +1141,18 @@ break; default: + filter: { + SV *tag_sv = newSVuv (tag); + sv = decode_sv (dec); dSP; - ENTER; SAVETMPS; PUSHMARK (SP); + ENTER; SAVETMPS; + SAVESTACK_POS (); + PUSHMARK (SP); EXTEND (SP, 2); - PUSHs (newSVuv (tag)); + PUSHs (tag_sv); PUSHs (sv); PUTBACK; @@ -936,19 +1161,21 @@ if (SvTRUE (ERRSV)) { + SvREFCNT_dec (tag_sv); FREETMPS; LEAVE; - ERR (SvPVutf8_nolen (sv_2mortal (SvREFCNT_inc (ERRSV)))); + ERR_ERRSV; } if (count) { + SvREFCNT_dec (tag_sv); SvREFCNT_dec (sv); sv = SvREFCNT_inc (POPs); } else { AV *av = newAV (); - av_push (av, newSVuv (tag)); + av_push (av, tag_sv); av_push (av, sv); HV *tagged_stash = !CBOR_SLOW || cbor_tagged_stash @@ -976,44 +1203,38 @@ { WANT (1); - switch (*dec->cur >> 5) + switch (*dec->cur >> MAJOR_SHIFT) { - case 0: // unsigned int - return newSVuv (decode_uint (dec)); - case 1: // negative int - return newSViv (-1 - (IV)decode_uint (dec)); - case 2: // octet string - return decode_str (dec, 0); - case 3: // utf-8 string - return decode_str (dec, 1); - case 4: // array - return decode_av (dec); - case 5: // map - return decode_hv (dec); - case 6: // tag - return decode_tagged (dec); - case 7: // misc - switch (*dec->cur++ & 31) + case MAJOR_POS_INT >> MAJOR_SHIFT: return newSVuv (decode_uint (dec)); + case MAJOR_NEG_INT >> MAJOR_SHIFT: return newSViv (-1 - (IV)decode_uint (dec)); + case MAJOR_BYTES >> MAJOR_SHIFT: return decode_str (dec, 0); + case MAJOR_TEXT >> MAJOR_SHIFT: return decode_str (dec, 1); + case MAJOR_ARRAY >> MAJOR_SHIFT: return decode_av (dec); + case MAJOR_MAP >> MAJOR_SHIFT: return decode_hv (dec); + case MAJOR_TAG >> MAJOR_SHIFT: return decode_tagged (dec); + + case MAJOR_MISC >> MAJOR_SHIFT: + switch (*dec->cur++ & MINOR_MASK) { - case 20: + case SIMPLE_FALSE: #if CBOR_SLOW types_false = get_bool ("Types::Serialiser::false"); #endif return newSVsv (types_false); - case 21: + case SIMPLE_TRUE: #if CBOR_SLOW types_true = get_bool ("Types::Serialiser::true"); #endif return newSVsv (types_true); - case 22: + case SIMPLE_NULL: return newSVsv (&PL_sv_undef); - case 23: + case SIMPLE_UNDEF: #if CBOR_SLOW types_error = get_bool ("Types::Serialiser::error"); #endif return newSVsv (types_error); - case 25: + case MISC_FLOAT16: { WANT (2); @@ -1023,7 +1244,7 @@ return newSVnv (ecb_binary16_to_float (fp)); } - case 26: + case MISC_FLOAT32: { uint32_t fp; WANT (4); @@ -1036,7 +1257,7 @@ return newSVnv (ecb_binary32_to_float (fp)); } - case 27: + case MISC_FLOAT64: { uint64_t fp; WANT (8); @@ -1049,10 +1270,12 @@ return newSVnv (ecb_binary64_to_double (fp)); } - // 0..19 unassigned - // 24 reserved + unassigned (reserved values are not encodable) + // 0..19 unassigned simple + // 24 reserved + unassigned simple (reserved values are not encodable) + // 28-30 unassigned misc + // 31 break code default: - ERR ("corrupted CBOR data (reserved/unassigned major 7 value)"); + ERR ("corrupted CBOR data (reserved/unassigned/unexpected major 7 value)"); } break; @@ -1065,7 +1288,7 @@ static SV * decode_cbor (SV *string, CBOR *cbor, char **offset_return) { - dec_t dec = { }; + dec_t dec = { 0 }; SV *sv; STRLEN len; char *data = SvPVbyte (string, len); @@ -1089,7 +1312,22 @@ if (dec.err) { + if (dec.shareable) + { + // need to break cyclic links, which would all be in shareable + int i; + SV **svp; + + for (i = av_len (dec.shareable) + 1; i--; ) + if ((svp = av_fetch (dec.shareable, i, 0))) + sv_setsv (*svp, &PL_sv_undef); + } + SvREFCNT_dec (sv); + + if (dec.err_sv) + sv_2mortal (dec.err_sv); + croak ("%s, at offset %d (octet 0x%02x)", dec.err, dec.cur - (U8 *)data, (int)(uint8_t)*dec.cur); } @@ -1099,6 +1337,130 @@ } ///////////////////////////////////////////////////////////////////////////// +// incremental parser + +#define INCR_DONE(cbor) (AvFILLp (cbor->incr_count) < 0) + +// returns 0 for notyet, 1 for success or error +static int +incr_parse (CBOR *self, SV *cborstr) +{ + STRLEN cur; + SvPV (cborstr, cur); + + while (ecb_expect_true (self->incr_need <= cur)) + { + // table of integer count bytes + static I8 incr_len[MINOR_MASK + 1] = { + 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, 2, 4, 8,-1,-1,-1,-2 + }; + + const U8 *p = SvPVX (cborstr) + self->incr_pos; + U8 m = *p & MINOR_MASK; + IV count = SvIVX (AvARRAY (self->incr_count)[AvFILLp (self->incr_count)]); + I8 ilen = incr_len[m]; + + self->incr_need = self->incr_pos + 1; + + if (ecb_expect_false (ilen < 0)) + { + if (m != MINOR_INDEF) + return 1; // error + + if (*p == (MAJOR_MISC | MINOR_INDEF)) + { + if (count >= 0) + return 1; // error + + count = 1; + } + else + { + av_push (self->incr_count, newSViv (-1)); //TODO: nest + count = -1; + } + } + else + { + self->incr_need += ilen; + if (ecb_expect_false (self->incr_need > cur)) + return 0; + + int major = *p >> MAJOR_SHIFT; + + switch (major) + { + case MAJOR_TAG >> MAJOR_SHIFT: + ++count; // tags merely prefix another value + break; + + case MAJOR_BYTES >> MAJOR_SHIFT: + case MAJOR_TEXT >> MAJOR_SHIFT: + case MAJOR_ARRAY >> MAJOR_SHIFT: + case MAJOR_MAP >> MAJOR_SHIFT: + { + UV len; + + if (ecb_expect_false (ilen)) + { + len = 0; + + do { + len = (len << 8) | *++p; + } while (--ilen); + } + else + len = m; + + switch (major) + { + case MAJOR_BYTES >> MAJOR_SHIFT: + case MAJOR_TEXT >> MAJOR_SHIFT: + self->incr_need += len; + if (ecb_expect_false (self->incr_need > cur)) + return 0; + + break; + + case MAJOR_MAP >> MAJOR_SHIFT: + len <<= 1; + case MAJOR_ARRAY >> MAJOR_SHIFT: + if (len) + { + av_push (self->incr_count, newSViv (len + 1)); //TODO: nest + count = len + 1; + } + break; + } + } + } + } + + self->incr_pos = self->incr_need; + + if (count > 0) + { + while (!--count) + { + if (!AvFILLp (self->incr_count)) + return 1; // done + + SvREFCNT_dec_NN (av_pop (self->incr_count)); + count = SvIVX (AvARRAY (self->incr_count)[AvFILLp (self->incr_count)]); + } + + SvIVX (AvARRAY (self->incr_count)[AvFILLp (self->incr_count)]) = count; + } + } + + return 0; +} + + +///////////////////////////////////////////////////////////////////////////// // XS interface functions MODULE = CBOR::XS PACKAGE = CBOR::XS @@ -1119,6 +1481,8 @@ sv_cbor = newSVpv ("CBOR", 0); SvREADONLY_on (sv_cbor); + + assert (("STRLEN must be an unsigned type", 0 <= (STRLEN)-1)); } PROTOTYPES: DISABLE @@ -1147,7 +1511,12 @@ shrink = F_SHRINK allow_unknown = F_ALLOW_UNKNOWN allow_sharing = F_ALLOW_SHARING - allow_stringref = F_ALLOW_STRINGREF + allow_cycles = F_ALLOW_CYCLES + forbid_objects = F_FORBID_OBJECTS + pack_strings = F_PACK_STRINGS + text_keys = F_TEXT_KEYS + text_strings = F_TEXT_STRINGS + validate_utf8 = F_VALIDATE_UTF8 PPCODE: { if (enable) @@ -1163,7 +1532,12 @@ get_shrink = F_SHRINK get_allow_unknown = F_ALLOW_UNKNOWN get_allow_sharing = F_ALLOW_SHARING - get_allow_stringref = F_ALLOW_STRINGREF + get_allow_cycles = F_ALLOW_CYCLES + get_forbid_objects = F_FORBID_OBJECTS + get_pack_strings = F_PACK_STRINGS + get_text_keys = F_TEXT_KEYS + get_text_strings = F_TEXT_STRINGS + get_validate_utf8 = F_VALIDATE_UTF8 PPCODE: XPUSHs (boolSV (self->flags & ix)); @@ -1222,6 +1596,58 @@ PUSHs (sv_2mortal (newSVuv (offset - SvPVX (cborstr)))); } +void incr_parse (CBOR *self, SV *cborstr) + ALIAS: + incr_parse_multiple = 1 + PPCODE: +{ + if (SvUTF8 (cborstr)) + sv_utf8_downgrade (cborstr, 0); + + if (!self->incr_count) + { + self->incr_count = newAV (); + self->incr_pos = 0; + self->incr_need = 1; + + av_push (self->incr_count, newSViv (1)); + } + + do + { + if (!incr_parse (self, cborstr)) + { + if (self->incr_need > self->max_size && self->max_size) + croak ("attempted decode of CBOR text of %lu bytes size, but max_size is set to %lu", + (unsigned long)self->incr_need, (unsigned long)self->max_size); + + break; + } + + SV *sv; + char *offset; + + PUTBACK; sv = decode_cbor (cborstr, self, &offset); SPAGAIN; + XPUSHs (sv); + + sv_chop (cborstr, offset); + + av_clear (self->incr_count); + av_push (self->incr_count, newSViv (1)); + + self->incr_pos = 0; + self->incr_need = self->incr_pos + 1; + } + while (ix); +} + +void incr_reset (CBOR *self) + CODE: +{ + SvREFCNT_dec (self->incr_count); + self->incr_count = 0; +} + void DESTROY (CBOR *self) PPCODE: cbor_free (self); @@ -1229,10 +1655,14 @@ PROTOTYPES: ENABLE void encode_cbor (SV *scalar) + ALIAS: + encode_cbor = 0 + encode_cbor_sharing = F_ALLOW_SHARING PPCODE: { CBOR cbor; cbor_init (&cbor); + cbor.flags |= ix; PUTBACK; scalar = encode_cbor (scalar, &cbor); SPAGAIN; XPUSHs (scalar); }