tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

cff_charstring.cc (29942B)


      1 // Copyright (c) 2010-2017 The OTS Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 // A parser for the Type 2 Charstring Format.
      6 // http://www.adobe.com/devnet/font/pdfs/5177.Type2.pdf
      7 
      8 #include "cff_charstring.h"
      9 
     10 #include <climits>
     11 #include <cstdio>
     12 #include <cstring>
     13 #include <stack>
     14 #include <string>
     15 #include <utility>
     16 
     17 #define TABLE_NAME "CFF"
     18 
     19 namespace {
     20 
     21 // Type 2 Charstring Implementation Limits. See Appendix. B in Adobe Technical
     22 // Note #5177.
     23 const int32_t kMaxSubrsCount = 65536;
     24 const size_t kMaxCharStringLength = 65535;
     25 const size_t kMaxNumberOfStemHints = 96;
     26 const size_t kMaxSubrNesting = 10;
     27 
     28 // |dummy_result| should be a huge positive integer so callsubr and callgsubr
     29 // will fail with the dummy value.
     30 const int32_t dummy_result = INT_MAX;
     31 
     32 bool ExecuteCharString(ots::OpenTypeCFF& cff,
     33                       size_t call_depth,
     34                       const ots::CFFIndex& global_subrs_index,
     35                       const ots::CFFIndex& local_subrs_index,
     36                       ots::Buffer *cff_table,
     37                       ots::Buffer *char_string,
     38                       std::stack<int32_t> *argument_stack,
     39                       ots::CharStringContext& cs_ctx);
     40 
     41 bool ArgumentStackOverflows(std::stack<int32_t> *argument_stack, bool cff2) {
     42  if ((cff2 && argument_stack->size() > ots::kMaxCFF2ArgumentStack) ||
     43      (!cff2 && argument_stack->size() > ots::kMaxCFF1ArgumentStack)) {
     44    return true;
     45  }
     46  return false;
     47 }
     48 
     49 #ifdef DUMP_T2CHARSTRING
     50 // Converts |op| to a string and returns it.
     51 const char *CharStringOperatorToString(ots::CharStringOperator op) {
     52  switch (op) {
     53  case ots::kHStem:
     54    return "hstem";
     55  case ots::kVStem:
     56    return "vstem";
     57  case ots::kVMoveTo:
     58    return "vmoveto";
     59  case ots::kRLineTo:
     60    return "rlineto";
     61  case ots::kHLineTo:
     62    return "hlineto";
     63  case ots::kVLineTo:
     64    return "vlineto";
     65  case ots::kRRCurveTo:
     66    return "rrcurveto";
     67  case ots::kCallSubr:
     68    return "callsubr";
     69  case ots::kReturn:
     70    return "return";
     71  case ots::kEndChar:
     72    return "endchar";
     73  case ots::kVSIndex:
     74    return "vsindex";
     75  case ots::kBlend:
     76    return "blend";
     77  case ots::kHStemHm:
     78    return "hstemhm";
     79  case ots::kHintMask:
     80    return "hintmask";
     81  case ots::kCntrMask:
     82    return "cntrmask";
     83  case ots::kRMoveTo:
     84    return "rmoveto";
     85  case ots::kHMoveTo:
     86    return "hmoveto";
     87  case ots::kVStemHm:
     88    return "vstemhm";
     89  case ots::kRCurveLine:
     90    return "rcurveline";
     91  case ots::kRLineCurve:
     92    return "rlinecurve";
     93  case ots::kVVCurveTo:
     94    return "VVCurveTo";
     95  case ots::kHHCurveTo:
     96    return "hhcurveto";
     97  case ots::kCallGSubr:
     98    return "callgsubr";
     99  case ots::kVHCurveTo:
    100    return "vhcurveto";
    101  case ots::kHVCurveTo:
    102    return "HVCurveTo";
    103  case ots::kDotSection:
    104    return "dotsection";
    105  case ots::kAnd:
    106    return "and";
    107  case ots::kOr:
    108    return "or";
    109  case ots::kNot:
    110    return "not";
    111  case ots::kAbs:
    112    return "abs";
    113  case ots::kAdd:
    114    return "add";
    115  case ots::kSub:
    116    return "sub";
    117  case ots::kDiv:
    118    return "div";
    119  case ots::kNeg:
    120    return "neg";
    121  case ots::kEq:
    122    return "eq";
    123  case ots::kDrop:
    124    return "drop";
    125  case ots::kPut:
    126    return "put";
    127  case ots::kGet:
    128    return "get";
    129  case ots::kIfElse:
    130    return "ifelse";
    131  case ots::kRandom:
    132    return "random";
    133  case ots::kMul:
    134    return "mul";
    135  case ots::kSqrt:
    136    return "sqrt";
    137  case ots::kDup:
    138    return "dup";
    139  case ots::kExch:
    140    return "exch";
    141  case ots::kIndex:
    142    return "index";
    143  case ots::kRoll:
    144    return "roll";
    145  case ots::kHFlex:
    146    return "hflex";
    147  case ots::kFlex:
    148    return "flex";
    149  case ots::kHFlex1:
    150    return "hflex1";
    151  case ots::kFlex1:
    152    return "flex1";
    153  }
    154 
    155  return "UNKNOWN";
    156 }
    157 #endif
    158 
    159 // Read one or more bytes from the |char_string| buffer and stores the number
    160 // read on |out_number|. If the number read is an operator (ex 'vstem'), sets
    161 // true on |out_is_operator|. Returns true if the function read a number.
    162 bool ReadNextNumberFromCharString(ots::Buffer *char_string,
    163                                  int32_t *out_number,
    164                                  bool *out_is_operator) {
    165  uint8_t v = 0;
    166  if (!char_string->ReadU8(&v)) {
    167    return OTS_FAILURE();
    168  }
    169  *out_is_operator = false;
    170 
    171  // The conversion algorithm is described in Adobe Technical Note #5177, page
    172  // 13, Table 1.
    173  if (v <= 11) {
    174    *out_number = v;
    175    *out_is_operator = true;
    176  } else if (v == 12) {
    177    uint16_t result = (v << 8);
    178    if (!char_string->ReadU8(&v)) {
    179      return OTS_FAILURE();
    180    }
    181    result += v;
    182    *out_number = result;
    183    *out_is_operator = true;
    184  } else if (v <= 27) {
    185    // Special handling for v==19 and v==20 are implemented in
    186    // ExecuteCharStringOperator().
    187    *out_number = v;
    188    *out_is_operator = true;
    189  } else if (v == 28) {
    190    if (!char_string->ReadU8(&v)) {
    191      return OTS_FAILURE();
    192    }
    193    uint16_t result = (v << 8);
    194    if (!char_string->ReadU8(&v)) {
    195      return OTS_FAILURE();
    196    }
    197    result += v;
    198    *out_number = result;
    199  } else if (v <= 31) {
    200    *out_number = v;
    201    *out_is_operator = true;
    202  } else if (v <= 246) {
    203    *out_number = static_cast<int32_t>(v) - 139;
    204  } else if (v <= 250) {
    205    uint8_t w = 0;
    206    if (!char_string->ReadU8(&w)) {
    207      return OTS_FAILURE();
    208    }
    209    *out_number = ((static_cast<int32_t>(v) - 247) * 256) +
    210        static_cast<int32_t>(w) + 108;
    211  } else if (v <= 254) {
    212    uint8_t w = 0;
    213    if (!char_string->ReadU8(&w)) {
    214      return OTS_FAILURE();
    215    }
    216    *out_number = -((static_cast<int32_t>(v) - 251) * 256) -
    217        static_cast<int32_t>(w) - 108;
    218  } else if (v == 255) {
    219    // TODO(yusukes): We should not skip the 4 bytes. Note that when v is 255,
    220    // we should treat the following 4-bytes as a 16.16 fixed-point number
    221    // rather than 32bit signed int.
    222    if (!char_string->Skip(4)) {
    223      return OTS_FAILURE();
    224    }
    225    *out_number = dummy_result;
    226  } else {
    227    return OTS_FAILURE();
    228  }
    229 
    230  return true;
    231 }
    232 
    233 bool ValidCFF2Operator(int32_t op) {
    234  switch (op) {
    235  case ots::kReturn:
    236  case ots::kEndChar:
    237  case ots::kAbs:
    238  case ots::kAdd:
    239  case ots::kSub:
    240  case ots::kDiv:
    241  case ots::kNeg:
    242  case ots::kRandom:
    243  case ots::kMul:
    244  case ots::kSqrt:
    245  case ots::kDrop:
    246  case ots::kExch:
    247  case ots::kIndex:
    248  case ots::kRoll:
    249  case ots::kDup:
    250  case ots::kPut:
    251  case ots::kGet:
    252  case ots::kDotSection:
    253  case ots::kAnd:
    254  case ots::kOr:
    255  case ots::kNot:
    256  case ots::kEq:
    257  case ots::kIfElse:
    258    return false;
    259  }
    260 
    261  return true;
    262 }
    263 
    264 // Executes |op| and updates |argument_stack|. Returns true if the execution
    265 // succeeds. If the |op| is kCallSubr or kCallGSubr, the function recursively
    266 // calls ExecuteCharString() function. The |cs_ctx| argument holds values that
    267 // need to persist through these calls (see CharStringContext for details)
    268 bool ExecuteCharStringOperator(ots::OpenTypeCFF& cff,
    269                               int32_t op,
    270                               size_t call_depth,
    271                               const ots::CFFIndex& global_subrs_index,
    272                               const ots::CFFIndex& local_subrs_index,
    273                               ots::Buffer *cff_table,
    274                               ots::Buffer *char_string,
    275                               std::stack<int32_t> *argument_stack,
    276                               ots::CharStringContext& cs_ctx) {
    277  ots::Font* font = cff.GetFont();
    278  const size_t stack_size = argument_stack->size();
    279 
    280  if (cs_ctx.cff2 && !ValidCFF2Operator(op)) {
    281    return OTS_FAILURE();
    282  }
    283 
    284  switch (op) {
    285  case ots::kCallSubr:
    286  case ots::kCallGSubr: {
    287    const ots::CFFIndex& subrs_index =
    288        (op == ots::kCallSubr ? local_subrs_index : global_subrs_index);
    289 
    290    if (stack_size < 1) {
    291      return OTS_FAILURE();
    292    }
    293    int32_t subr_number = argument_stack->top();
    294    argument_stack->pop();
    295    if (subr_number == dummy_result) {
    296      // For safety, we allow subr calls only with immediate subr numbers for
    297      // now. For example, we allow "123 callgsubr", but does not allow "100 12
    298      // add callgsubr". Please note that arithmetic and conditional operators
    299      // always push the |dummy_result| in this implementation.
    300      return OTS_FAILURE();
    301    }
    302 
    303    // See Adobe Technical Note #5176 (CFF), "16. Local/GlobalSubrs INDEXes."
    304    int32_t bias = 32768;
    305    if (subrs_index.count < 1240) {
    306      bias = 107;
    307    } else if (subrs_index.count < 33900) {
    308      bias = 1131;
    309    }
    310    subr_number += bias;
    311 
    312    // Sanity checks of |subr_number|.
    313    if (subr_number < 0) {
    314      return OTS_FAILURE();
    315    }
    316    if (subr_number >= kMaxSubrsCount) {
    317      return OTS_FAILURE();
    318    }
    319    if (subrs_index.offsets.size() <= static_cast<size_t>(subr_number + 1)) {
    320      return OTS_FAILURE();  // The number is out-of-bounds.
    321    }
    322 
    323    // Prepare ots::Buffer where we're going to jump.
    324    const size_t length =
    325      subrs_index.offsets[subr_number + 1] - subrs_index.offsets[subr_number];
    326    if (length > kMaxCharStringLength) {
    327      return OTS_FAILURE();
    328    }
    329    const size_t offset = subrs_index.offsets[subr_number];
    330    cff_table->set_offset(offset);
    331    if (!cff_table->Skip(length)) {
    332      return OTS_FAILURE();
    333    }
    334    ots::Buffer char_string_to_jump(cff_table->buffer() + offset, length);
    335 
    336    return ExecuteCharString(cff,
    337                             call_depth + 1,
    338                             global_subrs_index,
    339                             local_subrs_index,
    340                             cff_table,
    341                             &char_string_to_jump,
    342                             argument_stack,
    343                             cs_ctx);
    344  }
    345 
    346  case ots::kReturn:
    347    return true;
    348 
    349  case ots::kEndChar:
    350    cs_ctx.endchar_seen = true;
    351    cs_ctx.width_seen = true;  // just in case.
    352    return true;
    353 
    354  case ots::kVSIndex: {
    355    if (!cs_ctx.cff2) {
    356      return OTS_FAILURE();
    357    }
    358    if (stack_size != 1) {
    359      return OTS_FAILURE();
    360    }
    361    if (cs_ctx.blend_seen || cs_ctx.vsindex_seen) {
    362      return OTS_FAILURE();
    363    }
    364    if (argument_stack->top() < 0 ||
    365        argument_stack->top() >= (int32_t)cff.region_index_count.size()) {
    366      return OTS_FAILURE();
    367    }
    368    cs_ctx.vsindex_seen = true;
    369    cs_ctx.vsindex = argument_stack->top();
    370    while (!argument_stack->empty())
    371      argument_stack->pop();
    372    return true;
    373  }
    374 
    375  case ots::kBlend: {
    376    if (!cs_ctx.cff2) {
    377      return OTS_FAILURE();
    378    }
    379    if (stack_size < 1) {
    380      return OTS_FAILURE();
    381    }
    382    if (cs_ctx.vsindex >= (int32_t)cff.region_index_count.size()) {
    383      return OTS_FAILURE();
    384    }
    385    uint16_t k = cff.region_index_count.at(cs_ctx.vsindex);
    386    uint16_t n = argument_stack->top();
    387    if (stack_size < n * (k + 1u) + 1u) {
    388      return OTS_FAILURE();
    389    }
    390 
    391    // Keep the 1st n operands on the stack for the next operator to use and
    392    // pop the rest. There can be multiple consecutive blend operators, so this
    393    // makes sure the operands of all of them are kept on the stack.
    394    while (argument_stack->size() > stack_size - ((n * k) + 1))
    395      argument_stack->pop();
    396    cs_ctx.blend_seen = true;
    397    return true;
    398  }
    399 
    400  case ots::kHStem:
    401  case ots::kVStem:
    402  case ots::kHStemHm:
    403  case ots::kVStemHm: {
    404    bool successful = false;
    405    if (stack_size < 2) {
    406      return OTS_FAILURE();
    407    }
    408    if ((stack_size % 2) == 0) {
    409      successful = true;
    410    } else if ((!(cs_ctx.width_seen)) && (((stack_size - 1) % 2) == 0)) {
    411      // The -1 is for "width" argument. For details, see Adobe Technical Note
    412      // #5177, page 16, note 4.
    413      successful = true;
    414    }
    415    cs_ctx.num_stems += (stack_size / 2);
    416    if ((cs_ctx.num_stems) > kMaxNumberOfStemHints) {
    417      return OTS_FAILURE();
    418    }
    419    while (!argument_stack->empty())
    420      argument_stack->pop();
    421    cs_ctx.width_seen = true;  // always set true since "w" might be 0 byte.
    422    return successful ? true : OTS_FAILURE();
    423  }
    424 
    425  case ots::kRMoveTo: {
    426    bool successful = false;
    427    if (stack_size == 2) {
    428      successful = true;
    429    } else if ((!(cs_ctx.width_seen)) && (stack_size - 1 == 2)) {
    430      successful = true;
    431    }
    432    while (!argument_stack->empty())
    433      argument_stack->pop();
    434    cs_ctx.width_seen = true;
    435    return successful ? true : OTS_FAILURE();
    436  }
    437 
    438  case ots::kVMoveTo:
    439  case ots::kHMoveTo: {
    440    bool successful = false;
    441    if (stack_size == 1) {
    442      successful = true;
    443    } else if ((!(cs_ctx.width_seen)) && (stack_size - 1 == 1)) {
    444      successful = true;
    445    }
    446    while (!argument_stack->empty())
    447      argument_stack->pop();
    448    cs_ctx.width_seen = true;
    449    return successful ? true : OTS_FAILURE();
    450  }
    451 
    452  case ots::kHintMask:
    453  case ots::kCntrMask: {
    454    bool successful = false;
    455    if (stack_size == 0) {
    456      successful = true;
    457    } else if ((!(cs_ctx.width_seen)) && (stack_size == 1)) {
    458      // A number for "width" is found.
    459      successful = true;
    460    } else if ((!(cs_ctx.width_seen)) ||  // in this case, any sizes are ok.
    461               ((stack_size % 2) == 0)) {
    462      // The numbers are vstem definition.
    463      // See Adobe Technical Note #5177, page 24, hintmask.
    464      cs_ctx.num_stems += (stack_size / 2);
    465      if ((cs_ctx.num_stems) > kMaxNumberOfStemHints) {
    466        return OTS_FAILURE();
    467      }
    468      successful = true;
    469    }
    470    if (!successful) {
    471       return OTS_FAILURE();
    472    }
    473 
    474    if ((cs_ctx.num_stems) == 0) {
    475      return OTS_FAILURE();
    476    }
    477    const size_t mask_bytes = (cs_ctx.num_stems + 7) / 8;
    478    if (!char_string->Skip(mask_bytes)) {
    479      return OTS_FAILURE();
    480    }
    481    while (!argument_stack->empty())
    482      argument_stack->pop();
    483    cs_ctx.width_seen = true;
    484    return true;
    485  }
    486 
    487  case ots::kRLineTo:
    488    if (!(cs_ctx.width_seen)) {
    489      // The first stack-clearing operator should be one of hstem, hstemhm,
    490      // vstem, vstemhm, cntrmask, hintmask, hmoveto, vmoveto, rmoveto, or
    491      // endchar. For details, see Adobe Technical Note #5177, page 16, note 4.
    492      return OTS_FAILURE();
    493    }
    494    if (stack_size < 2) {
    495      return OTS_FAILURE();
    496    }
    497    if ((stack_size % 2) != 0) {
    498      return OTS_FAILURE();
    499    }
    500    while (!argument_stack->empty())
    501      argument_stack->pop();
    502    return true;
    503 
    504  case ots::kHLineTo:
    505  case ots::kVLineTo:
    506    if (!(cs_ctx.width_seen)) {
    507      return OTS_FAILURE();
    508    }
    509    if (stack_size < 1) {
    510      return OTS_FAILURE();
    511    }
    512    while (!argument_stack->empty())
    513      argument_stack->pop();
    514    return true;
    515 
    516  case ots::kRRCurveTo:
    517    if (!(cs_ctx.width_seen)) {
    518      return OTS_FAILURE();
    519    }
    520    if (stack_size < 6) {
    521      return OTS_FAILURE();
    522    }
    523    if ((stack_size % 6) != 0) {
    524      return OTS_FAILURE();
    525    }
    526    while (!argument_stack->empty())
    527      argument_stack->pop();
    528    return true;
    529 
    530  case ots::kRCurveLine:
    531    if (!(cs_ctx.width_seen)) {
    532      return OTS_FAILURE();
    533    }
    534    if (stack_size < 8) {
    535      return OTS_FAILURE();
    536    }
    537    if (((stack_size - 2) % 6) != 0) {
    538      return OTS_FAILURE();
    539    }
    540    while (!argument_stack->empty())
    541      argument_stack->pop();
    542    return true;
    543 
    544  case ots::kRLineCurve:
    545    if (!(cs_ctx.width_seen)) {
    546      return OTS_FAILURE();
    547    }
    548    if (stack_size < 8) {
    549      return OTS_FAILURE();
    550    }
    551    if (((stack_size - 6) % 2) != 0) {
    552      return OTS_FAILURE();
    553    }
    554    while (!argument_stack->empty())
    555      argument_stack->pop();
    556    return true;
    557 
    558  case ots::kVVCurveTo:
    559    if (!(cs_ctx.width_seen)) {
    560      return OTS_FAILURE();
    561    }
    562    if (stack_size < 4) {
    563      return OTS_FAILURE();
    564    }
    565    if (((stack_size % 4) != 0) &&
    566        (((stack_size - 1) % 4) != 0)) {
    567      return OTS_FAILURE();
    568    }
    569    while (!argument_stack->empty())
    570      argument_stack->pop();
    571    return true;
    572 
    573  case ots::kHHCurveTo: {
    574    bool successful = false;
    575    if (!(cs_ctx.width_seen)) {
    576      return OTS_FAILURE();
    577    }
    578    if (stack_size < 4) {
    579      return OTS_FAILURE();
    580    }
    581    if ((stack_size % 4) == 0) {
    582      // {dxa dxb dyb dxc}+
    583      successful = true;
    584    } else if (((stack_size - 1) % 4) == 0) {
    585      // dy1? {dxa dxb dyb dxc}+
    586      successful = true;
    587    }
    588    while (!argument_stack->empty())
    589      argument_stack->pop();
    590    return successful ? true : OTS_FAILURE();
    591  }
    592 
    593  case ots::kVHCurveTo:
    594  case ots::kHVCurveTo: {
    595    bool successful = false;
    596    if (!(cs_ctx.width_seen)) {
    597      return OTS_FAILURE();
    598    }
    599    if (stack_size < 4) {
    600      return OTS_FAILURE();
    601    }
    602    if (((stack_size - 4) % 8) == 0) {
    603      // dx1 dx2 dy2 dy3 {dya dxb dyb dxc dxd dxe dye dyf}*
    604      successful = true;
    605    } else if ((stack_size >= 5) &&
    606               ((stack_size - 5) % 8) == 0) {
    607      // dx1 dx2 dy2 dy3 {dya dxb dyb dxc dxd dxe dye dyf}* dxf
    608      successful = true;
    609    } else if ((stack_size >= 8) &&
    610               ((stack_size - 8) % 8) == 0) {
    611      // {dxa dxb dyb dyc dyd dxe dye dxf}+
    612      successful = true;
    613    } else if ((stack_size >= 9) &&
    614               ((stack_size - 9) % 8) == 0) {
    615      // {dxa dxb dyb dyc dyd dxe dye dxf}+ dyf?
    616      successful = true;
    617    }
    618    while (!argument_stack->empty())
    619      argument_stack->pop();
    620    return successful ? true : OTS_FAILURE();
    621  }
    622 
    623  case ots::kDotSection:
    624    // Deprecated operator but harmless, we probably should drop it some how.
    625    if (stack_size != 0) {
    626      return OTS_FAILURE();
    627    }
    628    return true;
    629 
    630  case ots::kAnd:
    631  case ots::kOr:
    632  case ots::kEq:
    633  case ots::kAdd:
    634  case ots::kSub:
    635    if (stack_size < 2) {
    636      return OTS_FAILURE();
    637    }
    638    argument_stack->pop();
    639    argument_stack->pop();
    640    argument_stack->push(dummy_result);
    641    // TODO(yusukes): Implement this. We should push a real value for all
    642    // arithmetic and conditional operations.
    643    return true;
    644 
    645  case ots::kNot:
    646  case ots::kAbs:
    647  case ots::kNeg:
    648    if (stack_size < 1) {
    649      return OTS_FAILURE();
    650    }
    651    argument_stack->pop();
    652    argument_stack->push(dummy_result);
    653    // TODO(yusukes): Implement this. We should push a real value for all
    654    // arithmetic and conditional operations.
    655    return true;
    656 
    657  case ots::kDiv:
    658    // TODO(yusukes): Should detect div-by-zero errors.
    659    if (stack_size < 2) {
    660      return OTS_FAILURE();
    661    }
    662    argument_stack->pop();
    663    argument_stack->pop();
    664    argument_stack->push(dummy_result);
    665    // TODO(yusukes): Implement this. We should push a real value for all
    666    // arithmetic and conditional operations.
    667    return true;
    668 
    669  case ots::kDrop:
    670    if (stack_size < 1) {
    671      return OTS_FAILURE();
    672    }
    673    argument_stack->pop();
    674    return true;
    675 
    676  case ots::kPut:
    677  case ots::kGet:
    678  case ots::kIndex:
    679    // For now, just call OTS_FAILURE since there is no way to check whether the
    680    // index argument, |i|, is out-of-bounds or not. Fortunately, no OpenType
    681    // fonts I have (except malicious ones!) use the operators.
    682    // TODO(yusukes): Implement them in a secure way.
    683    return OTS_FAILURE();
    684 
    685  case ots::kRoll:
    686    // Likewise, just call OTS_FAILURE for kRoll since there is no way to check
    687    // whether |N| is smaller than the current stack depth or not.
    688    // TODO(yusukes): Implement them in a secure way.
    689    return OTS_FAILURE();
    690 
    691  case ots::kRandom:
    692    // For now, we don't handle the 'random' operator since the operator makes
    693    // it hard to analyze hinting code statically.
    694    return OTS_FAILURE();
    695 
    696  case ots::kIfElse:
    697    if (stack_size < 4) {
    698      return OTS_FAILURE();
    699    }
    700    argument_stack->pop();
    701    argument_stack->pop();
    702    argument_stack->pop();
    703    argument_stack->pop();
    704    argument_stack->push(dummy_result);
    705    // TODO(yusukes): Implement this. We should push a real value for all
    706    // arithmetic and conditional operations.
    707    return true;
    708 
    709  case ots::kMul:
    710    // TODO(yusukes): Should detect overflows.
    711    if (stack_size < 2) {
    712      return OTS_FAILURE();
    713    }
    714    argument_stack->pop();
    715    argument_stack->pop();
    716    argument_stack->push(dummy_result);
    717    // TODO(yusukes): Implement this. We should push a real value for all
    718    // arithmetic and conditional operations.
    719    return true;
    720 
    721  case ots::kSqrt:
    722    // TODO(yusukes): Should check if the argument is negative.
    723    if (stack_size < 1) {
    724      return OTS_FAILURE();
    725    }
    726    argument_stack->pop();
    727    argument_stack->push(dummy_result);
    728    // TODO(yusukes): Implement this. We should push a real value for all
    729    // arithmetic and conditional operations.
    730    return true;
    731 
    732  case ots::kDup:
    733    if (stack_size < 1) {
    734      return OTS_FAILURE();
    735    }
    736    argument_stack->pop();
    737    argument_stack->push(dummy_result);
    738    argument_stack->push(dummy_result);
    739    if (ArgumentStackOverflows(argument_stack, cs_ctx.cff2)) {
    740      return OTS_FAILURE();
    741    }
    742    // TODO(yusukes): Implement this. We should push a real value for all
    743    // arithmetic and conditional operations.
    744    return true;
    745 
    746  case ots::kExch:
    747    if (stack_size < 2) {
    748      return OTS_FAILURE();
    749    }
    750    argument_stack->pop();
    751    argument_stack->pop();
    752    argument_stack->push(dummy_result);
    753    argument_stack->push(dummy_result);
    754    // TODO(yusukes): Implement this. We should push a real value for all
    755    // arithmetic and conditional operations.
    756    return true;
    757 
    758  case ots::kHFlex:
    759    if (!(cs_ctx.width_seen)) {
    760      return OTS_FAILURE();
    761    }
    762    if (stack_size != 7) {
    763      return OTS_FAILURE();
    764    }
    765    while (!argument_stack->empty())
    766      argument_stack->pop();
    767    return true;
    768 
    769  case ots::kFlex:
    770    if (!(cs_ctx.width_seen)) {
    771      return OTS_FAILURE();
    772    }
    773    if (stack_size != 13) {
    774      return OTS_FAILURE();
    775    }
    776    while (!argument_stack->empty())
    777      argument_stack->pop();
    778    return true;
    779 
    780  case ots::kHFlex1:
    781    if (!(cs_ctx.width_seen)) {
    782      return OTS_FAILURE();
    783    }
    784    if (stack_size != 9) {
    785      return OTS_FAILURE();
    786    }
    787    while (!argument_stack->empty())
    788      argument_stack->pop();
    789    return true;
    790 
    791  case ots::kFlex1:
    792    if (!(cs_ctx.width_seen)) {
    793      return OTS_FAILURE();
    794    }
    795    if (stack_size != 11) {
    796      return OTS_FAILURE();
    797    }
    798    while (!argument_stack->empty())
    799      argument_stack->pop();
    800    return true;
    801  }
    802 
    803  return OTS_FAILURE_MSG("Undefined operator: %d (0x%x)", op, op);
    804 }
    805 
    806 // Executes |char_string| and updates |argument_stack|.
    807 //
    808 // cff: parent OpenTypeCFF reference
    809 // call_depth: The current call depth. Initial value is zero.
    810 // global_subrs_index: Global subroutines.
    811 // local_subrs_index: Local subroutines for the current glyph.
    812 // cff_table: A whole CFF table which contains all global and local subroutines.
    813 // char_string: A charstring we'll execute. |char_string| can be a main routine
    814 //              in CharString INDEX, or a subroutine in GlobalSubr/LocalSubr.
    815 // argument_stack: The stack which an operator in |char_string| operates.
    816 // cs_ctx: a CharStringContext holding values to persist across subrs, etc.
    817 //   endchar_seen: true is set if |char_string| contains 'endchar'.
    818 //   width_seen: true is set if |char_string| contains 'width' byte (which
    819 //               is 0 or 1 byte) or if cff2
    820 //   num_stems: total number of hstems and vstems processed so far.
    821 //   cff2: true if this is a CFF2 table
    822 //   blend_seen: initially false; set to true if 'blend' operator encountered.
    823 //   vsindex_seen: initially false; set to true if 'vsindex' encountered.
    824 //   vsindex: initially = PrivateDICT's vsindex; may be changed by 'vsindex'
    825 //            operator in CharString
    826 bool ExecuteCharString(ots::OpenTypeCFF& cff,
    827                       size_t call_depth,
    828                       const ots::CFFIndex& global_subrs_index,
    829                       const ots::CFFIndex& local_subrs_index,
    830                       ots::Buffer *cff_table,
    831                       ots::Buffer *char_string,
    832                       std::stack<int32_t> *argument_stack,
    833                       ots::CharStringContext& cs_ctx) {
    834  if (call_depth > kMaxSubrNesting) {
    835    return OTS_FAILURE();
    836  }
    837  cs_ctx.endchar_seen = false;
    838 
    839  const size_t length = char_string->length();
    840  while (char_string->offset() < length) {
    841    int32_t operator_or_operand = 0;
    842    bool is_operator = false;
    843    if (!ReadNextNumberFromCharString(char_string,
    844                                           &operator_or_operand,
    845                                           &is_operator)) {
    846      return OTS_FAILURE();
    847    }
    848 
    849 #ifdef DUMP_T2CHARSTRING
    850    /*
    851      You can dump all operators and operands (except mask bytes for hintmask
    852      and cntrmask) by the following code:
    853    */
    854 
    855      if (!is_operator) {
    856        std::fprintf(stderr, "%d ", operator_or_operand);
    857      } else {
    858        std::fprintf(stderr, "%s\n",
    859           CharStringOperatorToString(
    860               ots::CharStringOperator(operator_or_operand))
    861           );
    862      }
    863 #endif
    864 
    865    if (!is_operator) {
    866      argument_stack->push(operator_or_operand);
    867      if (ArgumentStackOverflows(argument_stack, cs_ctx.cff2)) {
    868        return OTS_FAILURE();
    869      }
    870      continue;
    871    }
    872 
    873    // An operator is found. Execute it.
    874    if (!ExecuteCharStringOperator(cff,
    875                                   operator_or_operand,
    876                                   call_depth,
    877                                   global_subrs_index,
    878                                   local_subrs_index,
    879                                   cff_table,
    880                                   char_string,
    881                                   argument_stack,
    882                                   cs_ctx)) {
    883      return OTS_FAILURE();
    884    }
    885    if (cs_ctx.endchar_seen) {
    886      return true;
    887    }
    888    if (operator_or_operand == ots::kReturn) {
    889      return true;
    890    }
    891  }
    892 
    893  // No endchar operator is found (CFF1 only)
    894  if (cs_ctx.cff2)
    895    return true;
    896  return OTS_FAILURE();
    897 }
    898 
    899 // Selects a set of subroutines for |glyph_index| from |cff| and sets it on
    900 // |out_local_subrs_to_use|. Returns true on success.
    901 bool SelectLocalSubr(const ots::OpenTypeCFF& cff,
    902                     uint16_t glyph_index,  // 0-origin
    903                     const ots::CFFIndex **out_local_subrs_to_use) {
    904  bool cff2 = (cff.major == 2);
    905  *out_local_subrs_to_use = NULL;
    906 
    907  // First, find local subrs from |local_subrs_per_font|.
    908  if ((cff.fd_select.size() > 0) &&
    909      (!cff.local_subrs_per_font.empty())) {
    910    // Look up FDArray index for the glyph.
    911    const auto& iter = cff.fd_select.find(glyph_index);
    912    if (iter == cff.fd_select.end()) {
    913      return OTS_FAILURE();
    914    }
    915    const auto fd_index = iter->second;
    916    if (fd_index >= cff.local_subrs_per_font.size()) {
    917      return OTS_FAILURE();
    918    }
    919    *out_local_subrs_to_use = cff.local_subrs_per_font.at(fd_index);
    920  } else if (cff.local_subrs) {
    921    // Second, try to use |local_subrs|. Most Latin fonts don't have FDSelect
    922    // entries. If The font has a local subrs index associated with the Top
    923    // DICT (not FDArrays), use it.
    924    *out_local_subrs_to_use = cff.local_subrs;
    925  } else if (cff2 && cff.local_subrs_per_font.size() == 1) {
    926    *out_local_subrs_to_use = cff.local_subrs_per_font.at(0);
    927  } else {
    928    // Just return NULL.
    929    *out_local_subrs_to_use = NULL;
    930  }
    931 
    932  return true;
    933 }
    934 
    935 }  // namespace
    936 
    937 namespace ots {
    938 
    939 bool ValidateCFFCharStrings(
    940    ots::OpenTypeCFF& cff,
    941    const CFFIndex& global_subrs_index,
    942    Buffer* cff_table) {
    943  const CFFIndex& char_strings_index = *(cff.charstrings_index);
    944  if (char_strings_index.offsets.size() == 0) {
    945    return OTS_FAILURE();  // no charstring.
    946  }
    947 
    948  // For each glyph, validate the corresponding charstring.
    949  for (unsigned i = 1; i < char_strings_index.offsets.size(); ++i) {
    950    // Prepare a Buffer object, |char_string|, which contains the charstring
    951    // for the |i|-th glyph.
    952    const size_t length =
    953      char_strings_index.offsets[i] - char_strings_index.offsets[i - 1];
    954    if (length > kMaxCharStringLength) {
    955      return OTS_FAILURE();
    956    }
    957    const size_t offset = char_strings_index.offsets[i - 1];
    958    cff_table->set_offset(offset);
    959    if (!cff_table->Skip(length)) {
    960      return OTS_FAILURE();
    961    }
    962    Buffer char_string(cff_table->buffer() + offset, length);
    963 
    964    // Get a local subrs for the glyph.
    965    const unsigned glyph_index = i - 1;  // index in the map is 0-origin.
    966    const CFFIndex *local_subrs_to_use = NULL;
    967    if (!SelectLocalSubr(cff,
    968                         glyph_index,
    969                         &local_subrs_to_use)) {
    970      return OTS_FAILURE();
    971    }
    972    // If |local_subrs_to_use| is still NULL, use an empty one.
    973    CFFIndex default_empty_subrs;
    974    if (!local_subrs_to_use){
    975      local_subrs_to_use = &default_empty_subrs;
    976    }
    977 
    978    // Check a charstring for the |i|-th glyph.
    979    std::stack<int32_t> argument_stack;
    980    // Context to store values that must persist across subrs, etc.
    981    CharStringContext cs_ctx;
    982    cs_ctx.cff2 = (cff.major == 2);
    983    // CFF2 CharString has no value for width, so we start with true here to
    984    // error out if width is found.
    985    cs_ctx.width_seen = cs_ctx.cff2;
    986    // CFF2 CharStrings' default vsindex comes from the associated PrivateDICT
    987    if (cs_ctx.cff2) {
    988      const auto& iter = cff.fd_select.find(glyph_index);
    989      auto fd_index = 0;
    990      if (iter != cff.fd_select.end()) {
    991        fd_index = iter->second;
    992      }
    993      if (fd_index >= (int32_t)cff.vsindex_per_font.size()) {
    994        // shouldn't get this far with a font in this condition, but just in case
    995        return OTS_FAILURE();  // fd_index out-of-range
    996      }
    997      cs_ctx.vsindex = cff.vsindex_per_font.at(fd_index);
    998    }
    999 
   1000 #ifdef DUMP_T2CHARSTRING
   1001    fprintf(stderr, "\n---- CharString %*d ----\n", 5, glyph_index);
   1002 #endif
   1003 
   1004    if (!ExecuteCharString(cff,
   1005                           0 /* initial call_depth is zero */,
   1006                           global_subrs_index, *local_subrs_to_use,
   1007                           cff_table, &char_string, &argument_stack,
   1008                           cs_ctx)) {
   1009      return OTS_FAILURE();
   1010    }
   1011    if (!cs_ctx.cff2 && !cs_ctx.endchar_seen) {
   1012      return OTS_FAILURE();
   1013    }
   1014  }
   1015  return true;
   1016 }
   1017 
   1018 }  // namespace ots
   1019 
   1020 #undef TABLE_NAME