1 /*
   2  * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 // -*- C++ -*-
  27 // Program for unpacking specially compressed Java packages.
  28 // John R. Rose
  29 
  30 /*
  31  * When compiling for a 64bit LP64 system (longs and pointers being 64bits),
  32  *    the printf format %ld is correct and use of %lld will cause warning
  33  *    errors from some compilers (gcc/g++).
  34  * _LP64 can be explicitly set (used on Linux).
  35  * Solaris compilers will define __sparcv9 or __x86_64 on 64bit compilations.
  36  */
  37 #if defined(_LP64) || defined(__sparcv9) || defined(__x86_64)
  38   #define LONG_LONG_FORMAT "%ld"
  39   #define LONG_LONG_HEX_FORMAT "%lx"
  40 #else
  41   #define LONG_LONG_FORMAT "%lld"
  42   #define LONG_LONG_HEX_FORMAT "%016llx"
  43 #endif
  44 
  45 #include <sys/types.h>
  46 
  47 #include <stdio.h>
  48 #include <string.h>
  49 #include <stdlib.h>
  50 #include <stdarg.h>
  51 
  52 #include <limits.h>
  53 #include <time.h>
  54 
  55 
  56 
  57 
  58 #include "defines.h"
  59 #include "bytes.h"
  60 #include "utils.h"
  61 #include "coding.h"
  62 #include "bands.h"
  63 
  64 #include "constants.h"
  65 
  66 #include "zip.h"
  67 
  68 #include "unpack.h"
  69 
  70 
  71 // tags, in canonical order:
  72 static const byte TAGS_IN_ORDER[] = {
  73   CONSTANT_Utf8,
  74   CONSTANT_Integer,
  75   CONSTANT_Float,
  76   CONSTANT_Long,
  77   CONSTANT_Double,
  78   CONSTANT_String,
  79   CONSTANT_Class,
  80   CONSTANT_Signature,
  81   CONSTANT_NameandType,
  82   CONSTANT_Fieldref,
  83   CONSTANT_Methodref,
  84   CONSTANT_InterfaceMethodref,
  85   // constants defined as of JDK 7
  86   CONSTANT_MethodHandle,
  87   CONSTANT_MethodType,
  88   CONSTANT_BootstrapMethod,
  89   CONSTANT_InvokeDynamic
  90 };
  91 #define N_TAGS_IN_ORDER (sizeof TAGS_IN_ORDER)
  92 
  93 #ifndef PRODUCT
  94 static const char* TAG_NAME[] = {
  95   "*None",
  96   "Utf8",
  97   "*Unicode",
  98   "Integer",
  99   "Float",
 100   "Long",
 101   "Double",
 102   "Class",
 103   "String",
 104   "Fieldref",
 105   "Methodref",
 106   "InterfaceMethodref",
 107   "NameandType",
 108   "*Signature",
 109   "unused14",
 110   "MethodHandle",
 111   "MethodType",
 112   "*BootstrapMethod",
 113   "InvokeDynamic",
 114   0
 115 };
 116 
 117 static const char* ATTR_CONTEXT_NAME[] = {  // match ATTR_CONTEXT_NAME, etc.
 118   "class", "field", "method", "code"
 119 };
 120 
 121 #else
 122 
 123 #define ATTR_CONTEXT_NAME ((const char**)null)
 124 
 125 #endif
 126 
 127 // Note that REQUESTED_LDC comes first, then the normal REQUESTED,
 128 // in the regular constant pool.
 129 enum { REQUESTED_NONE = -1,
 130        // The codes below REQUESTED_NONE are in constant pool output order,
 131        // for the sake of outputEntry_cmp:
 132        REQUESTED_LDC = -99, REQUESTED
 133 };
 134 
 135 #define NO_INORD ((uint)-1)
 136 
 137 struct entry {
 138   byte tag;
 139 
 140   #if 0
 141   byte bits;
 142   enum {
 143     //EB_EXTRA = 1,
 144     EB_SUPER = 2
 145   };
 146   #endif
 147   unsigned short nrefs;  // pack w/ tag
 148 
 149   int  outputIndex;
 150   uint inord;   // &cp.entries[cp.tag_base[this->tag]+this->inord] == this
 151 
 152   entry* *refs;
 153 
 154   // put last to pack best
 155   union {
 156     bytes b;
 157     int i;
 158     jlong l;
 159   } value;
 160 
 161   void requestOutputIndex(cpool& cp, int req = REQUESTED);
 162   int getOutputIndex() {
 163     assert(outputIndex > REQUESTED_NONE);
 164     return outputIndex;
 165   }
 166 
 167   entry* ref(int refnum) {
 168     assert((uint)refnum < nrefs);
 169     return refs[refnum];
 170   }
 171 
 172   const char* utf8String() {
 173     assert(tagMatches(CONSTANT_Utf8));
 174     assert(value.b.len == strlen((const char*)value.b.ptr));
 175     return (const char*)value.b.ptr;
 176   }
 177 
 178   entry* className() {
 179     assert(tagMatches(CONSTANT_Class));
 180     return ref(0);
 181   }
 182 
 183   entry* memberClass() {
 184     assert(tagMatches(CONSTANT_AnyMember));
 185     return ref(0);
 186   }
 187 
 188   entry* memberDescr() {
 189     assert(tagMatches(CONSTANT_AnyMember));
 190     return ref(1);
 191   }
 192 
 193   entry* descrName() {
 194     assert(tagMatches(CONSTANT_NameandType));
 195     return ref(0);
 196   }
 197 
 198   entry* descrType() {
 199     assert(tagMatches(CONSTANT_NameandType));
 200     return ref(1);
 201   }
 202 
 203   int typeSize();
 204 
 205   bytes& asUtf8();
 206   int    asInteger() { assert(tag == CONSTANT_Integer); return value.i; }
 207 
 208   bool isUtf8(bytes& b) { return tagMatches(CONSTANT_Utf8) && value.b.equals(b); }
 209 
 210   bool isDoubleWord() { return tag == CONSTANT_Double || tag == CONSTANT_Long; }
 211 
 212   bool tagMatches(byte tag2) {
 213     return (tag2 == tag)
 214       || (tag2 == CONSTANT_Utf8 && tag == CONSTANT_Signature)
 215       #ifndef PRODUCT
 216       || (tag2 == CONSTANT_FieldSpecific
 217           && tag >= CONSTANT_Integer && tag <= CONSTANT_String && tag != CONSTANT_Class)
 218       || (tag2 == CONSTANT_AnyMember
 219           && tag >= CONSTANT_Fieldref && tag <= CONSTANT_InterfaceMethodref)
 220       #endif
 221       ;
 222   }
 223 
 224 #ifdef PRODUCT
 225   char* string() { return 0; }
 226 #else
 227   char* string();  // see far below
 228 #endif
 229 };
 230 
 231 entry* cpindex::get(uint i) {
 232   if (i >= len)
 233     return null;
 234   else if (base1 != null)
 235     // primary index
 236     return &base1[i];
 237   else
 238     // secondary index
 239     return base2[i];
 240 }
 241 
 242 inline bytes& entry::asUtf8() {
 243   assert(tagMatches(CONSTANT_Utf8));
 244   return value.b;
 245 }
 246 
 247 int entry::typeSize() {
 248   assert(tagMatches(CONSTANT_Utf8));
 249   const char* sigp = (char*) value.b.ptr;
 250   switch (*sigp) {
 251   case '(': sigp++; break;  // skip opening '('
 252   case 'D':
 253   case 'J': return 2; // double field
 254   default:  return 1; // field
 255   }
 256   int siglen = 0;
 257   for (;;) {
 258     int ch = *sigp++;
 259     switch (ch) {
 260     case 'D': case 'J':
 261       siglen += 1;
 262       break;
 263     case '[':
 264       // Skip rest of array info.
 265       while (ch == '[') { ch = *sigp++; }
 266       if (ch != 'L')  break;
 267       // else fall through
 268     case 'L':
 269       sigp = strchr(sigp, ';');
 270       if (sigp == null) {
 271           unpack_abort("bad data");
 272           return 0;
 273       }
 274       sigp += 1;
 275       break;
 276     case ')':  // closing ')'
 277       return siglen;
 278     }
 279     siglen += 1;
 280   }
 281 }
 282 
 283 inline cpindex* cpool::getFieldIndex(entry* classRef) {
 284   assert(classRef->tagMatches(CONSTANT_Class));
 285   assert((uint)classRef->inord < (uint)tag_count[CONSTANT_Class]);
 286   return &member_indexes[classRef->inord*2+0];
 287 }
 288 inline cpindex* cpool::getMethodIndex(entry* classRef) {
 289   assert(classRef->tagMatches(CONSTANT_Class));
 290   assert((uint)classRef->inord < (uint)tag_count[CONSTANT_Class]);
 291   return &member_indexes[classRef->inord*2+1];
 292 }
 293 
 294 struct inner_class {
 295   entry* inner;
 296   entry* outer;
 297   entry* name;
 298   int    flags;
 299   inner_class* next_sibling;
 300   bool   requested;
 301 };
 302 
 303 // Here is where everything gets deallocated:
 304 void unpacker::free() {
 305   int i;
 306   assert(jniobj == null); // caller resp.
 307   assert(infileptr == null);  // caller resp.
 308   if (jarout != null)  jarout->reset();
 309   if (gzin != null)    { gzin->free(); gzin = null; }
 310   if (free_input)  input.free();
 311   // free everybody ever allocated with U_NEW or (recently) with T_NEW
 312   assert(smallbuf.base()  == null || mallocs.contains(smallbuf.base()));
 313   assert(tsmallbuf.base() == null || tmallocs.contains(tsmallbuf.base()));
 314   mallocs.freeAll();
 315   tmallocs.freeAll();
 316   smallbuf.init();
 317   tsmallbuf.init();
 318   bcimap.free();
 319   class_fixup_type.free();
 320   class_fixup_offset.free();
 321   class_fixup_ref.free();
 322   code_fixup_type.free();
 323   code_fixup_offset.free();
 324   code_fixup_source.free();
 325   requested_ics.free();
 326   cp.requested_bsms.free();
 327   cur_classfile_head.free();
 328   cur_classfile_tail.free();
 329   for (i = 0; i < ATTR_CONTEXT_LIMIT; i++)
 330     attr_defs[i].free();
 331 
 332   // free CP state
 333   cp.outputEntries.free();
 334   for (i = 0; i < CONSTANT_Limit; i++)
 335     cp.tag_extras[i].free();
 336 }
 337 
 338 // input handling
 339 // Attempts to advance rplimit so that (rplimit-rp) is at least 'more'.
 340 // Will eagerly read ahead by larger chunks, if possible.
 341 // Returns false if (rplimit-rp) is not at least 'more',
 342 // unless rplimit hits input.limit().
 343 bool unpacker::ensure_input(jlong more) {
 344   julong want = more - input_remaining();
 345   if ((jlong)want <= 0)          return true;  // it's already in the buffer
 346   if (rplimit == input.limit())  return true;  // not expecting any more
 347 
 348   if (read_input_fn == null) {
 349     // assume it is already all there
 350     bytes_read += input.limit() - rplimit;
 351     rplimit = input.limit();
 352     return true;
 353   }
 354   CHECK_0;
 355 
 356   julong remaining = (input.limit() - rplimit);  // how much left to read?
 357   byte* rpgoal = (want >= remaining)? input.limit(): rplimit + (size_t)want;
 358   enum { CHUNK_SIZE = (1<<14) };
 359   julong fetch = want;
 360   if (fetch < CHUNK_SIZE)
 361     fetch = CHUNK_SIZE;
 362   if (fetch > remaining*3/4)
 363     fetch = remaining;
 364   // Try to fetch at least "more" bytes.
 365   while ((jlong)fetch > 0) {
 366     jlong nr = (*read_input_fn)(this, rplimit, fetch, remaining);
 367     if (nr <= 0) {
 368       return (rplimit >= rpgoal);
 369     }
 370     remaining -= nr;
 371     rplimit += nr;
 372     fetch -= nr;
 373     bytes_read += nr;
 374     assert(remaining == (julong)(input.limit() - rplimit));
 375   }
 376   return true;
 377 }
 378 
 379 // output handling
 380 
 381 fillbytes* unpacker::close_output(fillbytes* which) {
 382   assert(wp != null);
 383   if (which == null) {
 384     if (wpbase == cur_classfile_head.base()) {
 385       which = &cur_classfile_head;
 386     } else {
 387       which = &cur_classfile_tail;
 388     }
 389   }
 390   assert(wpbase  == which->base());
 391   assert(wplimit == which->end());
 392   which->setLimit(wp);
 393   wp      = null;
 394   wplimit = null;
 395   //wpbase = null;
 396   return which;
 397 }
 398 
 399 //maybe_inline
 400 void unpacker::ensure_put_space(size_t size) {
 401   if (wp + size <= wplimit)  return;
 402   // Determine which segment needs expanding.
 403   fillbytes* which = close_output();
 404   byte* wp0 = which->grow(size);
 405   wpbase  = which->base();
 406   wplimit = which->end();
 407   wp = wp0;
 408 }
 409 
 410 maybe_inline
 411 byte* unpacker::put_space(size_t size) {
 412   byte* wp0 = wp;
 413   byte* wp1 = wp0 + size;
 414   if (wp1 > wplimit) {
 415     ensure_put_space(size);
 416     wp0 = wp;
 417     wp1 = wp0 + size;
 418   }
 419   wp = wp1;
 420   return wp0;
 421 }
 422 
 423 maybe_inline
 424 void unpacker::putu2_at(byte* wp, int n) {
 425   if (n != (unsigned short)n) {
 426     unpack_abort(ERROR_OVERFLOW);
 427     return;
 428   }
 429   wp[0] = (n) >> 8;
 430   wp[1] = (n) >> 0;
 431 }
 432 
 433 maybe_inline
 434 void unpacker::putu4_at(byte* wp, int n) {
 435   wp[0] = (n) >> 24;
 436   wp[1] = (n) >> 16;
 437   wp[2] = (n) >> 8;
 438   wp[3] = (n) >> 0;
 439 }
 440 
 441 maybe_inline
 442 void unpacker::putu8_at(byte* wp, jlong n) {
 443   putu4_at(wp+0, (int)((julong)n >> 32));
 444   putu4_at(wp+4, (int)((julong)n >> 0));
 445 }
 446 
 447 maybe_inline
 448 void unpacker::putu2(int n) {
 449   putu2_at(put_space(2), n);
 450 }
 451 
 452 maybe_inline
 453 void unpacker::putu4(int n) {
 454   putu4_at(put_space(4), n);
 455 }
 456 
 457 maybe_inline
 458 void unpacker::putu8(jlong n) {
 459   putu8_at(put_space(8), n);
 460 }
 461 
 462 maybe_inline
 463 int unpacker::putref_index(entry* e, int size) {
 464   if (e == null)
 465     return 0;
 466   else if (e->outputIndex > REQUESTED_NONE)
 467     return e->outputIndex;
 468   else if (e->tag == CONSTANT_Signature)
 469     return putref_index(e->ref(0), size);
 470   else {
 471     e->requestOutputIndex(cp, (size == 1 ? REQUESTED_LDC : REQUESTED));
 472     // Later on we'll fix the bits.
 473     class_fixup_type.addByte(size);
 474     class_fixup_offset.add((int)wpoffset());
 475     class_fixup_ref.add(e);
 476 #ifdef PRODUCT
 477     return 0;
 478 #else
 479     return 0x20+size;  // 0x22 is easy to eyeball
 480 #endif
 481   }
 482 }
 483 
 484 maybe_inline
 485 void unpacker::putref(entry* e) {
 486   int oidx = putref_index(e, 2);
 487   putu2_at(put_space(2), oidx);
 488 }
 489 
 490 maybe_inline
 491 void unpacker::putu1ref(entry* e) {
 492   int oidx = putref_index(e, 1);
 493   putu1_at(put_space(1), oidx);
 494 }
 495 
 496 
 497 static int total_cp_size[] = {0, 0};
 498 static int largest_cp_ref[] = {0, 0};
 499 static int hash_probes[] = {0, 0};
 500 
 501 // Allocation of small and large blocks.
 502 
 503 enum { CHUNK = (1 << 14), SMALL = (1 << 9) };
 504 
 505 // Call malloc.  Try to combine small blocks and free much later.
 506 void* unpacker::alloc_heap(size_t size, bool smallOK, bool temp) {
 507   if (!smallOK || size > SMALL) {
 508     void* res = must_malloc((int)size);
 509     (temp ? &tmallocs : &mallocs)->add(res);
 510     return res;
 511   }
 512   fillbytes& xsmallbuf = *(temp ? &tsmallbuf : &smallbuf);
 513   if (!xsmallbuf.canAppend(size+1)) {
 514     xsmallbuf.init(CHUNK);
 515     (temp ? &tmallocs : &mallocs)->add(xsmallbuf.base());
 516   }
 517   int growBy = (int)size;
 518   growBy += -growBy & 7;  // round up mod 8
 519   return xsmallbuf.grow(growBy);
 520 }
 521 
 522 maybe_inline
 523 void unpacker::saveTo(bytes& b, byte* ptr, size_t len) {
 524   b.ptr = U_NEW(byte, add_size(len,1));
 525   if (aborting()) {
 526     b.len = 0;
 527     return;
 528   }
 529   b.len = len;
 530   b.copyFrom(ptr, len);
 531 }
 532 
 533 bool testBit(int archive_options, int bitMask) {
 534     return (archive_options & bitMask) != 0;
 535 }
 536 
 537 // Read up through band_headers.
 538 // Do the archive_size dance to set the size of the input mega-buffer.
 539 void unpacker::read_file_header() {
 540   // Read file header to determine file type and total size.
 541   enum {
 542     MAGIC_BYTES = 4,
 543     AH_LENGTH_0 = 3,  // archive_header_0 = {minver, majver, options}
 544     AH_LENGTH_MIN = 15, // observed in spec {header_0[3], cp_counts[8], class_counts[4]}
 545     AH_LENGTH_0_MAX = AH_LENGTH_0 + 1,  // options might have 2 bytes
 546     AH_LENGTH   = 30, //maximum archive header length (w/ all fields)
 547     // Length contributions from optional header fields:
 548     AH_LENGTH_S = 2, // archive_header_S = optional {size_hi, size_lo}
 549     AH_ARCHIVE_SIZE_HI = 0, // offset in archive_header_S
 550     AH_ARCHIVE_SIZE_LO = 1, // offset in archive_header_S
 551     AH_FILE_HEADER_LEN = 5, // file_counts = {{size_hi, size_lo), next, modtile, files}
 552     AH_SPECIAL_FORMAT_LEN = 2, // special_count = {layouts, band_headers}
 553     AH_CP_NUMBER_LEN = 4,      // cp_number_counts = {int, float, long, double}
 554     AH_CP_EXTRA_LEN = 4,        // cp_attr_counts = {MH, MT, InDy, BSM}
 555     ARCHIVE_SIZE_MIN = AH_LENGTH_MIN - AH_LENGTH_0 - AH_LENGTH_S,
 556     FIRST_READ  = MAGIC_BYTES + AH_LENGTH_MIN
 557   };
 558 
 559   assert(AH_LENGTH_MIN    == 15); // # of UNSIGNED5 fields required after archive_magic
 560   // An absolute minimum null archive is magic[4], {minver,majver,options}[3],
 561   // archive_size[0], cp_counts[8], class_counts[4], for a total of 19 bytes.
 562   // (Note that archive_size is optional; it may be 0..10 bytes in length.)
 563   // The first read must capture everything up through the options field.
 564   // This happens to work even if {minver,majver,options} is a pathological
 565   // 15 bytes long.  Legal pack files limit those three fields to 1+1+2 bytes.
 566   assert(FIRST_READ >= MAGIC_BYTES + AH_LENGTH_0 * B_MAX);
 567 
 568   // Up through archive_size, the largest possible archive header is
 569   // magic[4], {minver,majver,options}[4], archive_size[10].
 570   // (Note only the low 12 bits of options are allowed to be non-zero.)
 571   // In order to parse archive_size, we need at least this many bytes
 572   // in the first read.  Of course, if archive_size_hi is more than
 573   // a byte, we probably will fail to allocate the buffer, since it
 574   // will be many gigabytes long.  This is a practical, not an
 575   // architectural limit to Pack200 archive sizes.
 576   assert(FIRST_READ >= MAGIC_BYTES + AH_LENGTH_0_MAX + 2*B_MAX);
 577 
 578   bool foreign_buf = (read_input_fn == null);
 579   byte initbuf[(int)FIRST_READ + (int)C_SLOP + 200];  // 200 is for JAR I/O
 580   if (foreign_buf) {
 581     // inbytes is all there is
 582     input.set(inbytes);
 583     rp      = input.base();
 584     rplimit = input.limit();
 585   } else {
 586     // inbytes, if not empty, contains some read-ahead we must use first
 587     // ensure_input will take care of copying it into initbuf,
 588     // then querying read_input_fn for any additional data needed.
 589     // However, the caller must assume that we use up all of inbytes.
 590     // There is no way to tell the caller that we used only part of them.
 591     // Therefore, the caller must use only a bare minimum of read-ahead.
 592     if (inbytes.len > FIRST_READ) {
 593       abort("too much read-ahead");
 594       return;
 595     }
 596     input.set(initbuf, sizeof(initbuf));
 597     input.b.clear();
 598     input.b.copyFrom(inbytes);
 599     rplimit = rp = input.base();
 600     rplimit += inbytes.len;
 601     bytes_read += inbytes.len;
 602   }
 603   // Read only 19 bytes, which is certain to contain #archive_options fields,
 604   // but is certain not to overflow past the archive_header.
 605   input.b.len = FIRST_READ;
 606   if (!ensure_input(FIRST_READ))
 607     abort("EOF reading archive magic number");
 608 
 609   if (rp[0] == 'P' && rp[1] == 'K') {
 610 #ifdef UNPACK_JNI
 611     // Java driver must handle this case before we get this far.
 612     abort("encountered a JAR header in unpacker");
 613 #else
 614     // In the Unix-style program, we simply simulate a copy command.
 615     // Copy until EOF; assume the JAR file is the last segment.
 616     fprintf(errstrm, "Copy-mode.\n");
 617     for (;;) {
 618       jarout->write_data(rp, (int)input_remaining());
 619       if (foreign_buf)
 620         break;  // one-time use of a passed in buffer
 621       if (input.size() < CHUNK) {
 622         // Get some breathing room.
 623         input.set(U_NEW(byte, (size_t) CHUNK + C_SLOP), (size_t) CHUNK);
 624         CHECK;
 625       }
 626       rp = rplimit = input.base();
 627       if (!ensure_input(1))
 628         break;
 629     }
 630     jarout->closeJarFile(false);
 631 #endif
 632     return;
 633   }
 634 
 635   // Read the magic number.
 636   magic = 0;
 637   for (int i1 = 0; i1 < (int)sizeof(magic); i1++) {
 638     magic <<= 8;
 639     magic += (*rp++ & 0xFF);
 640   }
 641 
 642   // Read the first 3 values from the header.
 643   value_stream hdr;
 644   int          hdrVals = 0;
 645   int          hdrValsSkipped = 0;  // for assert
 646   hdr.init(rp, rplimit, UNSIGNED5_spec);
 647   minver = hdr.getInt();
 648   majver = hdr.getInt();
 649   hdrVals += 2;
 650 
 651   int majmin[4][2] = {
 652       {JAVA5_PACKAGE_MAJOR_VERSION, JAVA5_PACKAGE_MINOR_VERSION},
 653       {JAVA6_PACKAGE_MAJOR_VERSION, JAVA6_PACKAGE_MINOR_VERSION},
 654       {JAVA7_PACKAGE_MAJOR_VERSION, JAVA7_PACKAGE_MINOR_VERSION},
 655       {JAVA8_PACKAGE_MAJOR_VERSION, JAVA8_PACKAGE_MINOR_VERSION}
 656   };
 657   int majminfound = false;
 658   for (int i = 0 ; i < 4 ; i++) {
 659       if (majver == majmin[i][0] && minver == majmin[i][1]) {
 660           majminfound = true;
 661           break;
 662       }
 663   }
 664   if (majminfound == null) {
 665     char message[200];
 666     sprintf(message, "@" ERROR_FORMAT ": magic/ver = "
 667             "%08X/%d.%d should be %08X/%d.%d OR %08X/%d.%d OR %08X/%d.%d OR %08X/%d.%d\n",
 668             magic, majver, minver,
 669             JAVA_PACKAGE_MAGIC, JAVA5_PACKAGE_MAJOR_VERSION, JAVA5_PACKAGE_MINOR_VERSION,
 670             JAVA_PACKAGE_MAGIC, JAVA6_PACKAGE_MAJOR_VERSION, JAVA6_PACKAGE_MINOR_VERSION,
 671             JAVA_PACKAGE_MAGIC, JAVA7_PACKAGE_MAJOR_VERSION, JAVA7_PACKAGE_MINOR_VERSION,
 672             JAVA_PACKAGE_MAGIC, JAVA8_PACKAGE_MAJOR_VERSION, JAVA8_PACKAGE_MINOR_VERSION);
 673     abort(message);
 674   }
 675   CHECK;
 676 
 677   archive_options = hdr.getInt();
 678   hdrVals += 1;
 679   assert(hdrVals == AH_LENGTH_0);  // first three fields only
 680   bool haveSizeHi = testBit(archive_options, AO_HAVE_FILE_SIZE_HI);
 681   bool haveModTime = testBit(archive_options, AO_HAVE_FILE_MODTIME);
 682   bool haveFileOpt = testBit(archive_options, AO_HAVE_FILE_OPTIONS);
 683 
 684   bool haveSpecial = testBit(archive_options, AO_HAVE_SPECIAL_FORMATS);
 685   bool haveFiles = testBit(archive_options, AO_HAVE_FILE_HEADERS);
 686   bool haveNumbers = testBit(archive_options, AO_HAVE_CP_NUMBERS);
 687   bool haveCPExtra = testBit(archive_options, AO_HAVE_CP_EXTRAS);
 688 
 689   if (majver < JAVA7_PACKAGE_MAJOR_VERSION) {
 690     if (haveCPExtra) {
 691         abort("Format bits for Java 7 must be zero in previous releases");
 692         return;
 693     }
 694   }
 695   if (testBit(archive_options, AO_UNUSED_MBZ)) {
 696     abort("High archive option bits are reserved and must be zero");
 697     return;
 698   }
 699   if (haveFiles) {
 700     uint hi = hdr.getInt();
 701     uint lo = hdr.getInt();
 702     julong x = band::makeLong(hi, lo);
 703     archive_size = (size_t) x;
 704     if (archive_size != x) {
 705       // Silly size specified; force overflow.
 706       archive_size = PSIZE_MAX+1;
 707     }
 708     hdrVals += 2;
 709   } else {
 710     hdrValsSkipped += 2;
 711   }
 712 
 713   // Now we can size the whole archive.
 714   // Read everything else into a mega-buffer.
 715   rp = hdr.rp;
 716   int header_size_0 = (int)(rp - input.base()); // used-up header (4byte + 3int)
 717   int header_size_1 = (int)(rplimit - rp);      // buffered unused initial fragment
 718   int header_size   = header_size_0+header_size_1;
 719   unsized_bytes_read = header_size_0;
 720   CHECK;
 721   if (foreign_buf) {
 722     if (archive_size > (size_t)header_size_1) {
 723       abort("EOF reading fixed input buffer");
 724       return;
 725     }
 726   } else if (archive_size != 0) {
 727     if (archive_size < ARCHIVE_SIZE_MIN) {
 728       abort("impossible archive size");  // bad input data
 729       return;
 730     }
 731     if (archive_size < header_size_1) {
 732       abort("too much read-ahead");  // somehow we pre-fetched too much?
 733       return;
 734     }
 735     input.set(U_NEW(byte, add_size(header_size_0, archive_size, C_SLOP)),
 736               (size_t) header_size_0 + archive_size);
 737     CHECK;
 738     assert(input.limit()[0] == 0);
 739     // Move all the bytes we read initially into the real buffer.
 740     input.b.copyFrom(initbuf, header_size);
 741     rp      = input.b.ptr + header_size_0;
 742     rplimit = input.b.ptr + header_size;
 743   } else {
 744     // It's more complicated and painful.
 745     // A zero archive_size means that we must read until EOF.
 746     input.init(CHUNK*2);
 747     CHECK;
 748     input.b.len = input.allocated;
 749     rp = rplimit = input.base();
 750     // Set up input buffer as if we already read the header:
 751     input.b.copyFrom(initbuf, header_size);
 752     CHECK;
 753     rplimit += header_size;
 754     while (ensure_input(input.limit() - rp)) {
 755       size_t dataSoFar = input_remaining();
 756       size_t nextSize = add_size(dataSoFar, CHUNK);
 757       input.ensureSize(nextSize);
 758       CHECK;
 759       input.b.len = input.allocated;
 760       rp = rplimit = input.base();
 761       rplimit += dataSoFar;
 762     }
 763     size_t dataSize = (rplimit - input.base());
 764     input.b.len = dataSize;
 765     input.grow(C_SLOP);
 766     CHECK;
 767     free_input = true;  // free it later
 768     input.b.len = dataSize;
 769     assert(input.limit()[0] == 0);
 770     rp = rplimit = input.base();
 771     rplimit += dataSize;
 772     rp += header_size_0;  // already scanned these bytes...
 773   }
 774   live_input = true;    // mark as "do not reuse"
 775   if (aborting()) {
 776     abort("cannot allocate large input buffer for package file");
 777     return;
 778   }
 779 
 780   // read the rest of the header fields  int assertSkipped = AH_LENGTH_MIN - AH_LENGTH_0 - AH_LENGTH_S;
 781   int remainingHeaders = AH_LENGTH_MIN - AH_LENGTH_0 - AH_LENGTH_S;
 782   if (haveSpecial)
 783     remainingHeaders += AH_SPECIAL_FORMAT_LEN;
 784   if (haveFiles)
 785      remainingHeaders += AH_FILE_HEADER_LEN;
 786   if (haveNumbers)
 787     remainingHeaders += AH_CP_NUMBER_LEN;
 788   if (haveCPExtra)
 789     remainingHeaders += AH_CP_EXTRA_LEN;
 790 
 791   ensure_input(remainingHeaders * B_MAX);
 792   CHECK;
 793   hdr.rp      = rp;
 794   hdr.rplimit = rplimit;
 795 
 796   if (haveFiles) {
 797     archive_next_count = hdr.getInt();
 798     CHECK_COUNT(archive_next_count);
 799     archive_modtime = hdr.getInt();
 800     file_count = hdr.getInt();
 801     CHECK_COUNT(file_count);
 802     hdrVals += 3;
 803   } else {
 804     hdrValsSkipped += 3;
 805   }
 806 
 807   if (haveSpecial) {
 808     band_headers_size = hdr.getInt();
 809     CHECK_COUNT(band_headers_size);
 810     attr_definition_count = hdr.getInt();
 811     CHECK_COUNT(attr_definition_count);
 812     hdrVals += 2;
 813   } else {
 814     hdrValsSkipped += 2;
 815   }
 816 
 817   int cp_counts[N_TAGS_IN_ORDER];
 818   for (int k = 0; k < (int)N_TAGS_IN_ORDER; k++) {
 819     if (!haveNumbers) {
 820       switch (TAGS_IN_ORDER[k]) {
 821       case CONSTANT_Integer:
 822       case CONSTANT_Float:
 823       case CONSTANT_Long:
 824       case CONSTANT_Double:
 825         cp_counts[k] = 0;
 826         hdrValsSkipped += 1;
 827         continue;
 828       }
 829     }
 830     if (!haveCPExtra) {
 831         switch(TAGS_IN_ORDER[k]) {
 832         case CONSTANT_MethodHandle:
 833         case CONSTANT_MethodType:
 834         case CONSTANT_InvokeDynamic:
 835         case CONSTANT_BootstrapMethod:
 836           cp_counts[k] = 0;
 837           hdrValsSkipped += 1;
 838           continue;
 839         }
 840     }
 841     cp_counts[k] = hdr.getInt();
 842     CHECK_COUNT(cp_counts[k]);
 843     hdrVals += 1;
 844   }
 845 
 846   ic_count = hdr.getInt();
 847   CHECK_COUNT(ic_count);
 848   default_class_minver = hdr.getInt();
 849   default_class_majver = hdr.getInt();
 850   class_count = hdr.getInt();
 851   CHECK_COUNT(class_count);
 852   hdrVals += 4;
 853 
 854   // done with archive_header, time to reconcile to ensure
 855   // we have read everything correctly
 856   hdrVals += hdrValsSkipped;
 857   assert(hdrVals == AH_LENGTH);
 858   rp = hdr.rp;
 859   if (rp > rplimit)
 860     abort("EOF reading archive header");
 861 
 862   // Now size the CP.
 863 #ifndef PRODUCT
 864   // bool x = (N_TAGS_IN_ORDER == CONSTANT_Limit);
 865   // assert(x);
 866 #endif //PRODUCT
 867   cp.init(this, cp_counts);
 868   CHECK;
 869 
 870   default_file_modtime = archive_modtime;
 871   if (default_file_modtime == 0 && haveModTime)
 872     default_file_modtime = DEFAULT_ARCHIVE_MODTIME;  // taken from driver
 873   if (testBit(archive_options, AO_DEFLATE_HINT))
 874     default_file_options |= FO_DEFLATE_HINT;
 875 
 876   // meta-bytes, if any, immediately follow archive header
 877   //band_headers.readData(band_headers_size);
 878   ensure_input(band_headers_size);
 879   if (input_remaining() < (size_t)band_headers_size) {
 880     abort("EOF reading band headers");
 881     return;
 882   }
 883   bytes band_headers;
 884   // The "1+" allows an initial byte to be pushed on the front.
 885   band_headers.set(1+U_NEW(byte, 1+band_headers_size+C_SLOP),
 886                    band_headers_size);
 887   CHECK;
 888   // Start scanning band headers here:
 889   band_headers.copyFrom(rp, band_headers.len);
 890   rp += band_headers.len;
 891   assert(rp <= rplimit);
 892   meta_rp = band_headers.ptr;
 893   // Put evil meta-codes at the end of the band headers,
 894   // so we are sure to throw an error if we run off the end.
 895   bytes::of(band_headers.limit(), C_SLOP).clear(_meta_error);
 896 }
 897 
 898 void unpacker::finish() {
 899   if (verbose >= 1) {
 900     fprintf(errstrm,
 901             "A total of "
 902             LONG_LONG_FORMAT " bytes were read in %d segment(s).\n",
 903             (bytes_read_before_reset+bytes_read),
 904             segments_read_before_reset+1);
 905     fprintf(errstrm,
 906             "A total of "
 907             LONG_LONG_FORMAT " file content bytes were written.\n",
 908             (bytes_written_before_reset+bytes_written));
 909     fprintf(errstrm,
 910             "A total of %d files (of which %d are classes) were written to output.\n",
 911             files_written_before_reset+files_written,
 912             classes_written_before_reset+classes_written);
 913   }
 914   if (jarout != null)
 915     jarout->closeJarFile(true);
 916   if (errstrm != null) {
 917     if (errstrm == stdout || errstrm == stderr) {
 918       fflush(errstrm);
 919     } else {
 920       fclose(errstrm);
 921     }
 922     errstrm = null;
 923     errstrm_name = null;
 924   }
 925 }
 926 
 927 
 928 // Cf. PackageReader.readConstantPoolCounts
 929 void cpool::init(unpacker* u_, int counts[CONSTANT_Limit]) {
 930   this->u = u_;
 931 
 932   // Fill-pointer for CP.
 933   int next_entry = 0;
 934 
 935   // Size the constant pool:
 936   for (int k = 0; k < (int)N_TAGS_IN_ORDER; k++) {
 937     byte tag = TAGS_IN_ORDER[k];
 938     int  len = counts[k];
 939     tag_count[tag] = len;
 940     tag_base[tag] = next_entry;
 941     next_entry += len;
 942     // Detect and defend against constant pool size overflow.
 943     // (Pack200 forbids the sum of CP counts to exceed 2^29-1.)
 944     enum {
 945       CP_SIZE_LIMIT = (1<<29),
 946       IMPLICIT_ENTRY_COUNT = 1  // empty Utf8 string
 947     };
 948     if (len >= (1<<29) || len < 0
 949         || next_entry >= CP_SIZE_LIMIT+IMPLICIT_ENTRY_COUNT) {
 950       abort("archive too large:  constant pool limit exceeded");
 951       return;
 952     }
 953   }
 954 
 955   // Close off the end of the CP:
 956   nentries = next_entry;
 957 
 958   // place a limit on future CP growth:
 959   int generous = 0;
 960   generous = add_size(generous, u->ic_count); // implicit name
 961   generous = add_size(generous, u->ic_count); // outer
 962   generous = add_size(generous, u->ic_count); // outer.utf8
 963   generous = add_size(generous, 40); // WKUs, misc
 964   generous = add_size(generous, u->class_count); // implicit SourceFile strings
 965   maxentries = add_size(nentries, generous);
 966 
 967   // Note that this CP does not include "empty" entries
 968   // for longs and doubles.  Those are introduced when
 969   // the entries are renumbered for classfile output.
 970 
 971   entries = U_NEW(entry, maxentries);
 972   CHECK;
 973 
 974   first_extra_entry = &entries[nentries];
 975 
 976   // Initialize the standard indexes.
 977   for (int tag = 0; tag < CONSTANT_Limit; tag++) {
 978     entry* cpMap = &entries[tag_base[tag]];
 979     tag_index[tag].init(tag_count[tag], cpMap, tag);
 980   }
 981 
 982   // Initialize *all* our entries once
 983   for (int i = 0 ; i < maxentries ; i++)
 984     entries[i].outputIndex = REQUESTED_NONE;
 985 
 986   initGroupIndexes();
 987   // Initialize hashTab to a generous power-of-two size.
 988   uint pow2 = 1;
 989   uint target = maxentries + maxentries/2;  // 60% full
 990   while (pow2 < target)  pow2 <<= 1;
 991   hashTab = U_NEW(entry*, hashTabLength = pow2);
 992 }
 993 
 994 static byte* store_Utf8_char(byte* cp, unsigned short ch) {
 995   if (ch >= 0x001 && ch <= 0x007F) {
 996     *cp++ = (byte) ch;
 997   } else if (ch <= 0x07FF) {
 998     *cp++ = (byte) (0xC0 | ((ch >>  6) & 0x1F));
 999     *cp++ = (byte) (0x80 | ((ch >>  0) & 0x3F));
1000   } else {
1001     *cp++ = (byte) (0xE0 | ((ch >> 12) & 0x0F));
1002     *cp++ = (byte) (0x80 | ((ch >>  6) & 0x3F));
1003     *cp++ = (byte) (0x80 | ((ch >>  0) & 0x3F));
1004   }
1005   return cp;
1006 }
1007 
1008 static byte* skip_Utf8_chars(byte* cp, int len) {
1009   for (;; cp++) {
1010     int ch = *cp & 0xFF;
1011     if ((ch & 0xC0) != 0x80) {
1012       if (len-- == 0)
1013         return cp;
1014       if (ch < 0x80 && len == 0)
1015         return cp+1;
1016     }
1017   }
1018 }
1019 
1020 static int compare_Utf8_chars(bytes& b1, bytes& b2) {
1021   int l1 = (int)b1.len;
1022   int l2 = (int)b2.len;
1023   int l0 = (l1 < l2) ? l1 : l2;
1024   byte* p1 = b1.ptr;
1025   byte* p2 = b2.ptr;
1026   int c0 = 0;
1027   for (int i = 0; i < l0; i++) {
1028     int c1 = p1[i] & 0xFF;
1029     int c2 = p2[i] & 0xFF;
1030     if (c1 != c2) {
1031       // Before returning the obvious answer,
1032       // check to see if c1 or c2 is part of a 0x0000,
1033       // which encodes as {0xC0,0x80}.  The 0x0000 is the
1034       // lowest-sorting Java char value, and yet it encodes
1035       // as if it were the first char after 0x7F, which causes
1036       // strings containing nulls to sort too high.  All other
1037       // comparisons are consistent between Utf8 and Java chars.
1038       if (c1 == 0xC0 && (p1[i+1] & 0xFF) == 0x80)  c1 = 0;
1039       if (c2 == 0xC0 && (p2[i+1] & 0xFF) == 0x80)  c2 = 0;
1040       if (c0 == 0xC0) {
1041         assert(((c1|c2) & 0xC0) == 0x80);  // c1 & c2 are extension chars
1042         if (c1 == 0x80)  c1 = 0;  // will sort below c2
1043         if (c2 == 0x80)  c2 = 0;  // will sort below c1
1044       }
1045       return c1 - c2;
1046     }
1047     c0 = c1;  // save away previous char
1048   }
1049   // common prefix is identical; return length difference if any
1050   return l1 - l2;
1051 }
1052 
1053 // Cf. PackageReader.readUtf8Bands
1054 local_inline
1055 void unpacker::read_Utf8_values(entry* cpMap, int len) {
1056   // Implicit first Utf8 string is the empty string.
1057   enum {
1058     // certain bands begin with implicit zeroes
1059     PREFIX_SKIP_2 = 2,
1060     SUFFIX_SKIP_1 = 1
1061   };
1062 
1063   int i;
1064 
1065   // First band:  Read lengths of shared prefixes.
1066   if (len > PREFIX_SKIP_2)
1067     cp_Utf8_prefix.readData(len - PREFIX_SKIP_2);
1068     NOT_PRODUCT(else cp_Utf8_prefix.readData(0));  // for asserts
1069 
1070   // Second band:  Read lengths of unshared suffixes:
1071   if (len > SUFFIX_SKIP_1)
1072     cp_Utf8_suffix.readData(len - SUFFIX_SKIP_1);
1073     NOT_PRODUCT(else cp_Utf8_suffix.readData(0));  // for asserts
1074 
1075   bytes* allsuffixes = T_NEW(bytes, len);
1076   CHECK;
1077 
1078   int nbigsuf = 0;
1079   fillbytes charbuf;    // buffer to allocate small strings
1080   charbuf.init();
1081 
1082   // Third band:  Read the char values in the unshared suffixes:
1083   cp_Utf8_chars.readData(cp_Utf8_suffix.getIntTotal());
1084   for (i = 0; i < len; i++) {
1085     int suffix = (i < SUFFIX_SKIP_1)? 0: cp_Utf8_suffix.getInt();
1086     if (suffix < 0) {
1087       abort("bad utf8 suffix");
1088       return;
1089     }
1090     if (suffix == 0 && i >= SUFFIX_SKIP_1) {
1091       // chars are packed in cp_Utf8_big_chars
1092       nbigsuf += 1;
1093       continue;
1094     }
1095     bytes& chars  = allsuffixes[i];
1096     uint size3    = suffix * 3;     // max Utf8 length
1097     bool isMalloc = (suffix > SMALL);
1098     if (isMalloc) {
1099       chars.malloc(size3);
1100     } else {
1101       if (!charbuf.canAppend(size3+1)) {
1102         assert(charbuf.allocated == 0 || tmallocs.contains(charbuf.base()));
1103         charbuf.init(CHUNK);  // Reset to new buffer.
1104         tmallocs.add(charbuf.base());
1105       }
1106       chars.set(charbuf.grow(size3+1), size3);
1107     }
1108     CHECK;
1109     byte* chp = chars.ptr;
1110     for (int j = 0; j < suffix; j++) {
1111       unsigned short ch = cp_Utf8_chars.getInt();
1112       chp = store_Utf8_char(chp, ch);
1113     }
1114     // shrink to fit:
1115     if (isMalloc) {
1116       chars.realloc(chp - chars.ptr);
1117       CHECK;
1118       tmallocs.add(chars.ptr); // free it later
1119     } else {
1120       int shrink = (int)(chars.limit() - chp);
1121       chars.len -= shrink;
1122       charbuf.b.len -= shrink;  // ungrow to reclaim buffer space
1123       // Note that we did not reclaim the final '\0'.
1124       assert(chars.limit() == charbuf.limit()-1);
1125       assert(strlen((char*)chars.ptr) == chars.len);
1126     }
1127   }
1128   //cp_Utf8_chars.done();
1129 #ifndef PRODUCT
1130   charbuf.b.set(null, 0); // tidy
1131 #endif
1132 
1133   // Fourth band:  Go back and size the specially packed strings.
1134   int maxlen = 0;
1135   cp_Utf8_big_suffix.readData(nbigsuf);
1136   cp_Utf8_suffix.rewind();
1137   for (i = 0; i < len; i++) {
1138     int suffix = (i < SUFFIX_SKIP_1)? 0: cp_Utf8_suffix.getInt();
1139     int prefix = (i < PREFIX_SKIP_2)? 0: cp_Utf8_prefix.getInt();
1140     if (prefix < 0 || prefix+suffix < 0) {
1141        abort("bad utf8 prefix");
1142        return;
1143     }
1144     bytes& chars = allsuffixes[i];
1145     if (suffix == 0 && i >= SUFFIX_SKIP_1) {
1146       suffix = cp_Utf8_big_suffix.getInt();
1147       assert(chars.ptr == null);
1148       chars.len = suffix;  // just a momentary hack
1149     } else {
1150       assert(chars.ptr != null);
1151     }
1152     if (maxlen < prefix + suffix) {
1153       maxlen = prefix + suffix;
1154     }
1155   }
1156   //cp_Utf8_suffix.done();      // will use allsuffixes[i].len (ptr!=null)
1157   //cp_Utf8_big_suffix.done();  // will use allsuffixes[i].len
1158 
1159   // Fifth band(s):  Get the specially packed characters.
1160   cp_Utf8_big_suffix.rewind();
1161   for (i = 0; i < len; i++) {
1162     bytes& chars = allsuffixes[i];
1163     if (chars.ptr != null)  continue;  // already input
1164     int suffix = (int)chars.len;  // pick up the hack
1165     uint size3 = suffix * 3;
1166     if (suffix == 0)  continue;  // done with empty string
1167     chars.malloc(size3);
1168     CHECK;
1169     byte* chp = chars.ptr;
1170     band saved_band = cp_Utf8_big_chars;
1171     cp_Utf8_big_chars.readData(suffix);
1172     CHECK;
1173     for (int j = 0; j < suffix; j++) {
1174       unsigned short ch = cp_Utf8_big_chars.getInt();
1175       CHECK;
1176       chp = store_Utf8_char(chp, ch);
1177     }
1178     chars.realloc(chp - chars.ptr);
1179     CHECK;
1180     tmallocs.add(chars.ptr);  // free it later
1181     //cp_Utf8_big_chars.done();
1182     cp_Utf8_big_chars = saved_band;  // reset the band for the next string
1183   }
1184   cp_Utf8_big_chars.readData(0);  // zero chars
1185   //cp_Utf8_big_chars.done();
1186 
1187   // Finally, sew together all the prefixes and suffixes.
1188   bytes bigbuf;
1189   bigbuf.malloc(maxlen * 3 + 1);  // max Utf8 length, plus slop for null
1190   CHECK;
1191   int prevlen = 0;  // previous string length (in chars)
1192   tmallocs.add(bigbuf.ptr);  // free after this block
1193   CHECK;
1194   cp_Utf8_prefix.rewind();
1195   for (i = 0; i < len; i++) {
1196     bytes& chars = allsuffixes[i];
1197     int prefix = (i < PREFIX_SKIP_2)? 0: cp_Utf8_prefix.getInt();
1198     CHECK;
1199     int suffix = (int)chars.len;
1200     byte* fillp;
1201     // by induction, the buffer is already filled with the prefix
1202     // make sure the prefix value is not corrupted, though:
1203     if (prefix > prevlen) {
1204        abort("utf8 prefix overflow");
1205        return;
1206     }
1207     fillp = skip_Utf8_chars(bigbuf.ptr, prefix);
1208     // copy the suffix into the same buffer:
1209     fillp = chars.writeTo(fillp);
1210     assert(bigbuf.inBounds(fillp));
1211     *fillp = 0;  // bigbuf must contain a well-formed Utf8 string
1212     int length = (int)(fillp - bigbuf.ptr);
1213     bytes& value = cpMap[i].value.b;
1214     value.set(U_NEW(byte, add_size(length,1)), length);
1215     value.copyFrom(bigbuf.ptr, length);
1216     CHECK;
1217     // Index all Utf8 strings
1218     entry* &htref = cp.hashTabRef(CONSTANT_Utf8, value);
1219     if (htref == null) {
1220       // Note that if two identical strings are transmitted,
1221       // the first is taken to be the canonical one.
1222       htref = &cpMap[i];
1223     }
1224     prevlen = prefix + suffix;
1225   }
1226   //cp_Utf8_prefix.done();
1227 
1228   // Free intermediate buffers.
1229   free_temps();
1230 }
1231 
1232 local_inline
1233 void unpacker::read_single_words(band& cp_band, entry* cpMap, int len) {
1234   cp_band.readData(len);
1235   for (int i = 0; i < len; i++) {
1236     cpMap[i].value.i = cp_band.getInt();  // coding handles signs OK
1237   }
1238 }
1239 
1240 maybe_inline
1241 void unpacker::read_double_words(band& cp_bands, entry* cpMap, int len) {
1242   band& cp_band_hi = cp_bands;
1243   band& cp_band_lo = cp_bands.nextBand();
1244   cp_band_hi.readData(len);
1245   cp_band_lo.readData(len);
1246   for (int i = 0; i < len; i++) {
1247     cpMap[i].value.l = cp_band_hi.getLong(cp_band_lo, true);
1248   }
1249   //cp_band_hi.done();
1250   //cp_band_lo.done();
1251 }
1252 
1253 maybe_inline
1254 void unpacker::read_single_refs(band& cp_band, byte refTag, entry* cpMap, int len) {
1255   assert(refTag == CONSTANT_Utf8);
1256   cp_band.setIndexByTag(refTag);
1257   cp_band.readData(len);
1258   CHECK;
1259   int indexTag = (cp_band.bn == e_cp_Class) ? CONSTANT_Class : 0;
1260   for (int i = 0; i < len; i++) {
1261     entry& e = cpMap[i];
1262     e.refs = U_NEW(entry*, e.nrefs = 1);
1263     entry* utf = cp_band.getRef();
1264     CHECK;
1265     e.refs[0] = utf;
1266     e.value.b = utf->value.b;  // copy value of Utf8 string to self
1267     if (indexTag != 0) {
1268       // Maintain cross-reference:
1269       entry* &htref = cp.hashTabRef(indexTag, e.value.b);
1270       if (htref == null) {
1271         // Note that if two identical classes are transmitted,
1272         // the first is taken to be the canonical one.
1273         htref = &e;
1274       }
1275     }
1276   }
1277   //cp_band.done();
1278 }
1279 
1280 maybe_inline
1281 void unpacker::read_double_refs(band& cp_band, byte ref1Tag, byte ref2Tag,
1282                                 entry* cpMap, int len) {
1283   band& cp_band1 = cp_band;
1284   band& cp_band2 = cp_band.nextBand();
1285   cp_band1.setIndexByTag(ref1Tag);
1286   cp_band2.setIndexByTag(ref2Tag);
1287   cp_band1.readData(len);
1288   cp_band2.readData(len);
1289   CHECK;
1290   for (int i = 0; i < len; i++) {
1291     entry& e = cpMap[i];
1292     e.refs = U_NEW(entry*, e.nrefs = 2);
1293     e.refs[0] = cp_band1.getRef();
1294     e.refs[1] = cp_band2.getRef();
1295     CHECK;
1296   }
1297   //cp_band1.done();
1298   //cp_band2.done();
1299 }
1300 
1301 // Cf. PackageReader.readSignatureBands
1302 maybe_inline
1303 void unpacker::read_signature_values(entry* cpMap, int len) {
1304   cp_Signature_form.setIndexByTag(CONSTANT_Utf8);
1305   cp_Signature_form.readData(len);
1306   CHECK;
1307   int ncTotal = 0;
1308   int i;
1309   for (i = 0; i < len; i++) {
1310     entry& e = cpMap[i];
1311     entry& form = *cp_Signature_form.getRef();
1312     CHECK;
1313     int nc = 0;
1314 
1315     for ( const char* ncp = form.utf8String() ; *ncp; ncp++) {
1316       if (*ncp == 'L')  nc++;
1317     }
1318 
1319     ncTotal += nc;
1320     e.refs = U_NEW(entry*, cpMap[i].nrefs = 1 + nc);
1321     CHECK;
1322     e.refs[0] = &form;
1323   }
1324   //cp_Signature_form.done();
1325   cp_Signature_classes.setIndexByTag(CONSTANT_Class);
1326   cp_Signature_classes.readData(ncTotal);
1327   for (i = 0; i < len; i++) {
1328     entry& e = cpMap[i];
1329     for (int j = 1; j < e.nrefs; j++) {
1330       e.refs[j] = cp_Signature_classes.getRef();
1331       CHECK;
1332     }
1333   }
1334   //cp_Signature_classes.done();
1335 }
1336 
1337 maybe_inline
1338 void unpacker::checkLegacy(const char* name) {
1339   if (u->majver < JAVA7_PACKAGE_MAJOR_VERSION) {
1340       char message[100];
1341       snprintf(message, 99, "unexpected band %s\n", name);
1342       abort(message);
1343   }
1344 }
1345 
1346 maybe_inline
1347 void unpacker::read_method_handle(entry* cpMap, int len) {
1348   if (len > 0) {
1349     checkLegacy(cp_MethodHandle_refkind.name);
1350   }
1351   cp_MethodHandle_refkind.readData(len);
1352   cp_MethodHandle_member.setIndexByTag(CONSTANT_AnyMember);
1353   cp_MethodHandle_member.readData(len);
1354   for (int i = 0 ; i < len ; i++) {
1355     entry& e = cpMap[i];
1356     e.value.i = cp_MethodHandle_refkind.getInt();
1357     e.refs = U_NEW(entry*, e.nrefs = 1);
1358     e.refs[0] = cp_MethodHandle_member.getRef();
1359     CHECK;
1360   }
1361 }
1362 
1363 maybe_inline
1364 void unpacker::read_method_type(entry* cpMap, int len) {
1365   if (len > 0) {
1366     checkLegacy(cp_MethodType.name);
1367   }
1368   cp_MethodType.setIndexByTag(CONSTANT_Signature);
1369   cp_MethodType.readData(len);
1370   for (int i = 0 ; i < len ; i++) {
1371       entry& e = cpMap[i];
1372       e.refs = U_NEW(entry*, e.nrefs = 1);
1373       e.refs[0] = cp_MethodType.getRef();
1374   }
1375 }
1376 
1377 maybe_inline
1378 void unpacker::read_bootstrap_methods(entry* cpMap, int len) {
1379   if (len > 0) {
1380     checkLegacy(cp_BootstrapMethod_ref.name);
1381   }
1382   cp_BootstrapMethod_ref.setIndexByTag(CONSTANT_MethodHandle);
1383   cp_BootstrapMethod_ref.readData(len);
1384 
1385   cp_BootstrapMethod_arg_count.readData(len);
1386   int totalArgCount = cp_BootstrapMethod_arg_count.getIntTotal();
1387   cp_BootstrapMethod_arg.setIndexByTag(CONSTANT_LoadableValue);
1388   cp_BootstrapMethod_arg.readData(totalArgCount);
1389   for (int i = 0; i < len; i++) {
1390     entry& e = cpMap[i];
1391     int argc = cp_BootstrapMethod_arg_count.getInt();
1392     e.value.i = argc;
1393     e.refs = U_NEW(entry*, e.nrefs = argc + 1);
1394     e.refs[0] = cp_BootstrapMethod_ref.getRef();
1395     for (int j = 1 ; j < e.nrefs ; j++) {
1396       e.refs[j] = cp_BootstrapMethod_arg.getRef();
1397       CHECK;
1398     }
1399   }
1400 }
1401 // Cf. PackageReader.readConstantPool
1402 void unpacker::read_cp() {
1403   byte* rp0 = rp;
1404 
1405   int i;
1406 
1407   for (int k = 0; k < (int)N_TAGS_IN_ORDER; k++) {
1408     byte tag = TAGS_IN_ORDER[k];
1409     int  len = cp.tag_count[tag];
1410     int base = cp.tag_base[tag];
1411 
1412     PRINTCR((1,"Reading %d %s entries...", len, NOT_PRODUCT(TAG_NAME[tag])+0));
1413     entry* cpMap = &cp.entries[base];
1414     for (i = 0; i < len; i++) {
1415       cpMap[i].tag = tag;
1416       cpMap[i].inord = i;
1417     }
1418     // Initialize the tag's CP index right away, since it might be needed
1419     // in the next pass to initialize the CP for another tag.
1420 #ifndef PRODUCT
1421     cpindex* ix = &cp.tag_index[tag];
1422     assert(ix->ixTag == tag);
1423     assert((int)ix->len   == len);
1424     assert(ix->base1 == cpMap);
1425 #endif
1426 
1427     switch (tag) {
1428     case CONSTANT_Utf8:
1429       read_Utf8_values(cpMap, len);
1430       break;
1431     case CONSTANT_Integer:
1432       read_single_words(cp_Int, cpMap, len);
1433       break;
1434     case CONSTANT_Float:
1435       read_single_words(cp_Float, cpMap, len);
1436       break;
1437     case CONSTANT_Long:
1438       read_double_words(cp_Long_hi /*& cp_Long_lo*/, cpMap, len);
1439       break;
1440     case CONSTANT_Double:
1441       read_double_words(cp_Double_hi /*& cp_Double_lo*/, cpMap, len);
1442       break;
1443     case CONSTANT_String:
1444       read_single_refs(cp_String, CONSTANT_Utf8, cpMap, len);
1445       break;
1446     case CONSTANT_Class:
1447       read_single_refs(cp_Class, CONSTANT_Utf8, cpMap, len);
1448       break;
1449     case CONSTANT_Signature:
1450       read_signature_values(cpMap, len);
1451       break;
1452     case CONSTANT_NameandType:
1453       read_double_refs(cp_Descr_name /*& cp_Descr_type*/,
1454                        CONSTANT_Utf8, CONSTANT_Signature,
1455                        cpMap, len);
1456       break;
1457     case CONSTANT_Fieldref:
1458       read_double_refs(cp_Field_class /*& cp_Field_desc*/,
1459                        CONSTANT_Class, CONSTANT_NameandType,
1460                        cpMap, len);
1461       break;
1462     case CONSTANT_Methodref:
1463       read_double_refs(cp_Method_class /*& cp_Method_desc*/,
1464                        CONSTANT_Class, CONSTANT_NameandType,
1465                        cpMap, len);
1466       break;
1467     case CONSTANT_InterfaceMethodref:
1468       read_double_refs(cp_Imethod_class /*& cp_Imethod_desc*/,
1469                        CONSTANT_Class, CONSTANT_NameandType,
1470                        cpMap, len);
1471       break;
1472     case CONSTANT_MethodHandle:
1473       // consumes cp_MethodHandle_refkind and cp_MethodHandle_member
1474       read_method_handle(cpMap, len);
1475       break;
1476     case CONSTANT_MethodType:
1477       // consumes cp_MethodType
1478       read_method_type(cpMap, len);
1479       break;
1480     case CONSTANT_InvokeDynamic:
1481       read_double_refs(cp_InvokeDynamic_spec, CONSTANT_BootstrapMethod,
1482                        CONSTANT_NameandType,
1483                        cpMap, len);
1484       break;
1485     case CONSTANT_BootstrapMethod:
1486       // consumes cp_BootstrapMethod_ref, cp_BootstrapMethod_arg_count and cp_BootstrapMethod_arg
1487       read_bootstrap_methods(cpMap, len);
1488       break;
1489     default:
1490       assert(false);
1491       break;
1492     }
1493     CHECK;
1494   }
1495 
1496   cp.expandSignatures();
1497   CHECK;
1498   cp.initMemberIndexes();
1499   CHECK;
1500 
1501   PRINTCR((1,"parsed %d constant pool entries in %d bytes", cp.nentries, (rp - rp0)));
1502 
1503   #define SNAME(n,s) #s "\0"
1504   const char* symNames = (
1505     ALL_ATTR_DO(SNAME)
1506     "<init>"
1507   );
1508   #undef SNAME
1509 
1510   for (int sn = 0; sn < cpool::s_LIMIT; sn++) {
1511     assert(symNames[0] >= '0' && symNames[0] <= 'Z');  // sanity
1512     bytes name; name.set(symNames);
1513     if (name.len > 0 && name.ptr[0] != '0') {
1514       cp.sym[sn] = cp.ensureUtf8(name);
1515       PRINTCR((4, "well-known sym %d=%s", sn, cp.sym[sn]->string()));
1516     }
1517     symNames += name.len + 1;  // skip trailing null to next name
1518   }
1519 
1520   band::initIndexes(this);
1521 }
1522 
1523 static band* no_bands[] = { null };  // shared empty body
1524 
1525 inline
1526 band& unpacker::attr_definitions::fixed_band(int e_class_xxx) {
1527   return u->all_bands[xxx_flags_hi_bn + (e_class_xxx-e_class_flags_hi)];
1528 }
1529 inline band& unpacker::attr_definitions::xxx_flags_hi()
1530   { return fixed_band(e_class_flags_hi); }
1531 inline band& unpacker::attr_definitions::xxx_flags_lo()
1532   { return fixed_band(e_class_flags_lo); }
1533 inline band& unpacker::attr_definitions::xxx_attr_count()
1534   { return fixed_band(e_class_attr_count); }
1535 inline band& unpacker::attr_definitions::xxx_attr_indexes()
1536   { return fixed_band(e_class_attr_indexes); }
1537 inline band& unpacker::attr_definitions::xxx_attr_calls()
1538   { return fixed_band(e_class_attr_calls); }
1539 
1540 
1541 inline
1542 unpacker::layout_definition*
1543 unpacker::attr_definitions::defineLayout(int idx,
1544                                          entry* nameEntry,
1545                                          const char* layout) {
1546   const char* name = nameEntry->value.b.strval();
1547   layout_definition* lo = defineLayout(idx, name, layout);
1548   CHECK_0;
1549   lo->nameEntry = nameEntry;
1550   return lo;
1551 }
1552 
1553 unpacker::layout_definition*
1554 unpacker::attr_definitions::defineLayout(int idx,
1555                                          const char* name,
1556                                          const char* layout) {
1557   assert(flag_limit != 0);  // must be set up already
1558   if (idx >= 0) {
1559     // Fixed attr.
1560     if (idx >= (int)flag_limit)
1561       abort("attribute index too large");
1562     if (isRedefined(idx))
1563       abort("redefined attribute index");
1564     redef |= ((julong)1<<idx);
1565   } else {
1566     idx = flag_limit + overflow_count.length();
1567     overflow_count.add(0);  // make a new counter
1568   }
1569   layout_definition* lo = U_NEW(layout_definition, 1);
1570   CHECK_0;
1571   lo->idx = idx;
1572   lo->name = name;
1573   lo->layout = layout;
1574   for (int adds = (idx+1) - layouts.length(); adds > 0; adds--) {
1575     layouts.add(null);
1576   }
1577   CHECK_0;
1578   layouts.get(idx) = lo;
1579   return lo;
1580 }
1581 
1582 band**
1583 unpacker::attr_definitions::buildBands(unpacker::layout_definition* lo) {
1584   int i;
1585   if (lo->elems != null)
1586     return lo->bands();
1587   if (lo->layout[0] == '\0') {
1588     lo->elems = no_bands;
1589   } else {
1590     // Create bands for this attribute by parsing the layout.
1591     bool hasCallables = lo->hasCallables();
1592     bands_made = 0x10000;  // base number for bands made
1593     const char* lp = lo->layout;
1594     lp = parseLayout(lp, lo->elems, -1);
1595     CHECK_0;
1596     if (lp[0] != '\0' || band_stack.length() > 0) {
1597       abort("garbage at end of layout");
1598     }
1599     band_stack.popTo(0);
1600     CHECK_0;
1601 
1602     // Fix up callables to point at their callees.
1603     band** bands = lo->elems;
1604     assert(bands == lo->bands());
1605     int num_callables = 0;
1606     if (hasCallables) {
1607       while (bands[num_callables] != null) {
1608         if (bands[num_callables]->le_kind != EK_CBLE) {
1609           abort("garbage mixed with callables");
1610           break;
1611         }
1612         num_callables += 1;
1613       }
1614     }
1615     for (i = 0; i < calls_to_link.length(); i++) {
1616       band& call = *(band*) calls_to_link.get(i);
1617       assert(call.le_kind == EK_CALL);
1618       // Determine the callee.
1619       int call_num = call.le_len;
1620       if (call_num < 0 || call_num >= num_callables) {
1621         abort("bad call in layout");
1622         break;
1623       }
1624       band& cble = *bands[call_num];
1625       // Link the call to it.
1626       call.le_body[0] = &cble;
1627       // Distinguish backward calls and callables:
1628       assert(cble.le_kind == EK_CBLE);
1629       assert(cble.le_len == call_num);
1630       cble.le_back |= call.le_back;
1631     }
1632     calls_to_link.popTo(0);
1633   }
1634   return lo->elems;
1635 }
1636 
1637 /* attribute layout language parser
1638 
1639   attribute_layout:
1640         ( layout_element )* | ( callable )+
1641   layout_element:
1642         ( integral | replication | union | call | reference )
1643 
1644   callable:
1645         '[' body ']'
1646   body:
1647         ( layout_element )+
1648 
1649   integral:
1650         ( unsigned_int | signed_int | bc_index | bc_offset | flag )
1651   unsigned_int:
1652         uint_type
1653   signed_int:
1654         'S' uint_type
1655   any_int:
1656         ( unsigned_int | signed_int )
1657   bc_index:
1658         ( 'P' uint_type | 'PO' uint_type )
1659   bc_offset:
1660         'O' any_int
1661   flag:
1662         'F' uint_type
1663   uint_type:
1664         ( 'B' | 'H' | 'I' | 'V' )
1665 
1666   replication:
1667         'N' uint_type '[' body ']'
1668 
1669   union:
1670         'T' any_int (union_case)* '(' ')' '[' (body)? ']'
1671   union_case:
1672         '(' union_case_tag (',' union_case_tag)* ')' '[' (body)? ']'
1673   union_case_tag:
1674         ( numeral | numeral '-' numeral )
1675   call:
1676         '(' numeral ')'
1677 
1678   reference:
1679         reference_type ( 'N' )? uint_type
1680   reference_type:
1681         ( constant_ref | schema_ref | utf8_ref | untyped_ref )
1682   constant_ref:
1683         ( 'KI' | 'KJ' | 'KF' | 'KD' | 'KS' | 'KQ' )
1684   schema_ref:
1685         ( 'RC' | 'RS' | 'RD' | 'RF' | 'RM' | 'RI' )
1686   utf8_ref:
1687         'RU'
1688   untyped_ref:
1689         'RQ'
1690 
1691   numeral:
1692         '(' ('-')? (digit)+ ')'
1693   digit:
1694         ( '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' )
1695 
1696 */
1697 
1698 const char*
1699 unpacker::attr_definitions::parseIntLayout(const char* lp, band* &res,
1700                                            byte le_kind, bool can_be_signed) {
1701   const char* lp0 = lp;
1702   band* b = U_NEW(band, 1);
1703   CHECK_(lp);
1704   char le = *lp++;
1705   int spec = UNSIGNED5_spec;
1706   if (le == 'S' && can_be_signed) {
1707     // Note:  This is the last use of sign.  There is no 'EF_SIGN'.
1708     spec = SIGNED5_spec;
1709     le = *lp++;
1710   } else if (le == 'B') {
1711     spec = BYTE1_spec;  // unsigned byte
1712   }
1713   b->init(u, bands_made++, spec);
1714   b->le_kind = le_kind;
1715   int le_len = 0;
1716   switch (le) {
1717   case 'B': le_len = 1; break;
1718   case 'H': le_len = 2; break;
1719   case 'I': le_len = 4; break;
1720   case 'V': le_len = 0; break;
1721   default:  abort("bad layout element");
1722   }
1723   b->le_len = le_len;
1724   band_stack.add(b);
1725   res = b;
1726   return lp;
1727 }
1728 
1729 const char*
1730 unpacker::attr_definitions::parseNumeral(const char* lp, int &res) {
1731   const char* lp0 = lp;
1732   bool sgn = false;
1733   if (*lp == '0') { res = 0; return lp+1; }  // special case '0'
1734   if (*lp == '-') { sgn = true; lp++; }
1735   const char* dp = lp;
1736   int con = 0;
1737   while (*dp >= '0' && *dp <= '9') {
1738     int con0 = con;
1739     con *= 10;
1740     con += (*dp++) - '0';
1741     if (con <= con0) { con = -1; break; }  //  numeral overflow
1742   }
1743   if (lp == dp) {
1744     abort("missing numeral in layout");
1745     return "";
1746   }
1747   lp = dp;
1748   if (con < 0 && !(sgn && con == -con)) {
1749     // (Portability note:  Misses the error if int is not 32 bits.)
1750     abort("numeral overflow");
1751     return "" ;
1752   }
1753   if (sgn)  con = -con;
1754   res = con;
1755   return lp;
1756 }
1757 
1758 band**
1759 unpacker::attr_definitions::popBody(int bs_base) {
1760   // Return everything that was pushed, as a null-terminated pointer array.
1761   int bs_limit = band_stack.length();
1762   if (bs_base == bs_limit) {
1763     return no_bands;
1764   } else {
1765     int nb = bs_limit - bs_base;
1766     band** res = U_NEW(band*, add_size(nb, 1));
1767     CHECK_(no_bands);
1768     for (int i = 0; i < nb; i++) {
1769       band* b = (band*) band_stack.get(bs_base + i);
1770       res[i] = b;
1771     }
1772     band_stack.popTo(bs_base);
1773     return res;
1774   }
1775 }
1776 
1777 const char*
1778 unpacker::attr_definitions::parseLayout(const char* lp, band** &res,
1779                                         int curCble) {
1780   const char* lp0 = lp;
1781   int bs_base = band_stack.length();
1782   bool top_level = (bs_base == 0);
1783   band* b;
1784   enum { can_be_signed = true };  // optional arg to parseIntLayout
1785 
1786   for (bool done = false; !done; ) {
1787     switch (*lp++) {
1788     case 'B': case 'H': case 'I': case 'V': // unsigned_int
1789     case 'S': // signed_int
1790       --lp;  // reparse
1791     case 'F':
1792       lp = parseIntLayout(lp, b, EK_INT);
1793       break;
1794     case 'P':
1795       {
1796         int le_bci = EK_BCI;
1797         if (*lp == 'O') {
1798           ++lp;
1799           le_bci = EK_BCID;
1800         }
1801         assert(*lp != 'S');  // no PSH, etc.
1802         lp = parseIntLayout(lp, b, EK_INT);
1803         b->le_bci = le_bci;
1804         if (le_bci == EK_BCI)
1805           b->defc = coding::findBySpec(BCI5_spec);
1806         else
1807           b->defc = coding::findBySpec(BRANCH5_spec);
1808       }
1809       break;
1810     case 'O':
1811       lp = parseIntLayout(lp, b, EK_INT, can_be_signed);
1812       b->le_bci = EK_BCO;
1813       b->defc = coding::findBySpec(BRANCH5_spec);
1814       break;
1815     case 'N': // replication: 'N' uint '[' elem ... ']'
1816       lp = parseIntLayout(lp, b, EK_REPL);
1817       assert(*lp == '[');
1818       ++lp;
1819       lp = parseLayout(lp, b->le_body, curCble);
1820       CHECK_(lp);
1821       break;
1822     case 'T': // union: 'T' any_int union_case* '(' ')' '[' body ']'
1823       lp = parseIntLayout(lp, b, EK_UN, can_be_signed);
1824       {
1825         int union_base = band_stack.length();
1826         for (;;) {   // for each case
1827           band& k_case = *U_NEW(band, 1);
1828           CHECK_(lp);
1829           band_stack.add(&k_case);
1830           k_case.le_kind = EK_CASE;
1831           k_case.bn = bands_made++;
1832           if (*lp++ != '(') {
1833             abort("bad union case");
1834             return "";
1835           }
1836           if (*lp++ != ')') {
1837             --lp;  // reparse
1838             // Read some case values.  (Use band_stack for temp. storage.)
1839             int case_base = band_stack.length();
1840             for (;;) {
1841               int caseval = 0;
1842               lp = parseNumeral(lp, caseval);
1843               band_stack.add((void*)(size_t)caseval);
1844               if (*lp == '-') {
1845                 // new in version 160, allow (1-5) for (1,2,3,4,5)
1846                 if (u->majver < JAVA6_PACKAGE_MAJOR_VERSION) {
1847                   abort("bad range in union case label (old archive format)");
1848                   return "";
1849                 }
1850                 int caselimit = caseval;
1851                 lp++;
1852                 lp = parseNumeral(lp, caselimit);
1853                 if (caseval >= caselimit
1854                     || (uint)(caselimit - caseval) > 0x10000) {
1855                   // Note:  0x10000 is arbitrary implementation restriction.
1856                   // We can remove it later if it's important to.
1857                   abort("bad range in union case label");
1858                   return "";
1859                 }
1860                 for (;;) {
1861                   ++caseval;
1862                   band_stack.add((void*)(size_t)caseval);
1863                   if (caseval == caselimit)  break;
1864                 }
1865               }
1866               if (*lp != ',')  break;
1867               lp++;
1868             }
1869             if (*lp++ != ')') {
1870               abort("bad case label");
1871               return "";
1872             }
1873             // save away the case labels
1874             int ntags = band_stack.length() - case_base;
1875             int* tags = U_NEW(int, add_size(ntags, 1));
1876             CHECK_(lp);
1877             k_case.le_casetags = tags;
1878             *tags++ = ntags;
1879             for (int i = 0; i < ntags; i++) {
1880               *tags++ = ptrlowbits(band_stack.get(case_base+i));
1881             }
1882             band_stack.popTo(case_base);
1883             CHECK_(lp);
1884           }
1885           // Got le_casetags.  Now grab the body.
1886           assert(*lp == '[');
1887           ++lp;
1888           lp = parseLayout(lp, k_case.le_body, curCble);
1889           CHECK_(lp);
1890           if (k_case.le_casetags == null)  break;  // done
1891         }
1892         b->le_body = popBody(union_base);
1893       }
1894       break;
1895     case '(': // call: '(' -?NN* ')'
1896       {
1897         band& call = *U_NEW(band, 1);
1898         CHECK_(lp);
1899         band_stack.add(&call);
1900         call.le_kind = EK_CALL;
1901         call.bn = bands_made++;
1902         call.le_body = U_NEW(band*, 2); // fill in later
1903         int call_num = 0;
1904         lp = parseNumeral(lp, call_num);
1905         call.le_back = (call_num <= 0);
1906         call_num += curCble;  // numeral is self-relative offset
1907         call.le_len = call_num;  //use le_len as scratch
1908         calls_to_link.add(&call);
1909         CHECK_(lp);
1910         if (*lp++ != ')') {
1911           abort("bad call label");
1912           return "";
1913         }
1914       }
1915       break;
1916     case 'K': // reference_type: constant_ref
1917     case 'R': // reference_type: schema_ref
1918       {
1919         int ixTag = CONSTANT_None;
1920         if (lp[-1] == 'K') {
1921           switch (*lp++) {
1922           case 'I': ixTag = CONSTANT_Integer; break;
1923           case 'J': ixTag = CONSTANT_Long; break;
1924           case 'F': ixTag = CONSTANT_Float; break;
1925           case 'D': ixTag = CONSTANT_Double; break;
1926           case 'S': ixTag = CONSTANT_String; break;
1927           case 'Q': ixTag = CONSTANT_FieldSpecific; break;
1928 
1929           // new in 1.7
1930           case 'M': ixTag = CONSTANT_MethodHandle; break;
1931           case 'T': ixTag = CONSTANT_MethodType; break;
1932           case 'L': ixTag = CONSTANT_LoadableValue; break;
1933           }
1934         } else {
1935           switch (*lp++) {
1936           case 'C': ixTag = CONSTANT_Class; break;
1937           case 'S': ixTag = CONSTANT_Signature; break;
1938           case 'D': ixTag = CONSTANT_NameandType; break;
1939           case 'F': ixTag = CONSTANT_Fieldref; break;
1940           case 'M': ixTag = CONSTANT_Methodref; break;
1941           case 'I': ixTag = CONSTANT_InterfaceMethodref; break;
1942           case 'U': ixTag = CONSTANT_Utf8; break; //utf8_ref
1943           case 'Q': ixTag = CONSTANT_All; break; //untyped_ref
1944 
1945           // new in 1.7
1946           case 'Y': ixTag = CONSTANT_InvokeDynamic; break;
1947           case 'B': ixTag = CONSTANT_BootstrapMethod; break;
1948           case 'N': ixTag = CONSTANT_AnyMember; break;
1949           }
1950         }
1951         if (ixTag == CONSTANT_None) {
1952           abort("bad reference layout");
1953           break;
1954         }
1955         bool nullOK = false;
1956         if (*lp == 'N') {
1957           nullOK = true;
1958           lp++;
1959         }
1960         lp = parseIntLayout(lp, b, EK_REF);
1961         b->defc = coding::findBySpec(UNSIGNED5_spec);
1962         b->initRef(ixTag, nullOK);
1963       }
1964       break;
1965     case '[':
1966       {
1967         // [callable1][callable2]...
1968         if (!top_level) {
1969           abort("bad nested callable");
1970           break;
1971         }
1972         curCble += 1;
1973         NOT_PRODUCT(int call_num = band_stack.length() - bs_base);
1974         band& cble = *U_NEW(band, 1);
1975         CHECK_(lp);
1976         band_stack.add(&cble);
1977         cble.le_kind = EK_CBLE;
1978         NOT_PRODUCT(cble.le_len = call_num);
1979         cble.bn = bands_made++;
1980         lp = parseLayout(lp, cble.le_body, curCble);
1981       }
1982       break;
1983     case ']':
1984       // Hit a closing brace.  This ends whatever body we were in.
1985       done = true;
1986       break;
1987     case '\0':
1988       // Hit a null.  Also ends the (top-level) body.
1989       --lp;  // back up, so caller can see the null also
1990       done = true;
1991       break;
1992     default:
1993       abort("bad layout");
1994       break;
1995     }
1996     CHECK_(lp);
1997   }
1998 
1999   // Return the accumulated bands:
2000   res = popBody(bs_base);
2001   return lp;
2002 }
2003 
2004 void unpacker::read_attr_defs() {
2005   int i;
2006 
2007   // Tell each AD which attrc it is and where its fixed flags are:
2008   attr_defs[ATTR_CONTEXT_CLASS].attrc            = ATTR_CONTEXT_CLASS;
2009   attr_defs[ATTR_CONTEXT_CLASS].xxx_flags_hi_bn  = e_class_flags_hi;
2010   attr_defs[ATTR_CONTEXT_FIELD].attrc            = ATTR_CONTEXT_FIELD;
2011   attr_defs[ATTR_CONTEXT_FIELD].xxx_flags_hi_bn  = e_field_flags_hi;
2012   attr_defs[ATTR_CONTEXT_METHOD].attrc           = ATTR_CONTEXT_METHOD;
2013   attr_defs[ATTR_CONTEXT_METHOD].xxx_flags_hi_bn = e_method_flags_hi;
2014   attr_defs[ATTR_CONTEXT_CODE].attrc             = ATTR_CONTEXT_CODE;
2015   attr_defs[ATTR_CONTEXT_CODE].xxx_flags_hi_bn   = e_code_flags_hi;
2016 
2017   // Decide whether bands for the optional high flag words are present.
2018   attr_defs[ATTR_CONTEXT_CLASS]
2019     .setHaveLongFlags(testBit(archive_options, AO_HAVE_CLASS_FLAGS_HI));
2020   attr_defs[ATTR_CONTEXT_FIELD]
2021     .setHaveLongFlags(testBit(archive_options, AO_HAVE_FIELD_FLAGS_HI));
2022   attr_defs[ATTR_CONTEXT_METHOD]
2023     .setHaveLongFlags(testBit(archive_options, AO_HAVE_METHOD_FLAGS_HI));
2024   attr_defs[ATTR_CONTEXT_CODE]
2025     .setHaveLongFlags(testBit(archive_options, AO_HAVE_CODE_FLAGS_HI));
2026 
2027   // Set up built-in attrs.
2028   // (The simple ones are hard-coded.  The metadata layouts are not.)
2029   const char* md_layout = (
2030     // parameter annotations:
2031 #define MDL0 \
2032     "[NB[(1)]]"
2033     MDL0
2034     // annotations:
2035 #define MDL1 \
2036     "[NH[(1)]]" \
2037     "[RSHNH[RUH(1)]]"
2038     MDL1
2039     // member_value:
2040     "[TB"
2041       "(66,67,73,83,90)[KIH]"
2042       "(68)[KDH]"
2043       "(70)[KFH]"
2044       "(74)[KJH]"
2045       "(99)[RSH]"
2046       "(101)[RSHRUH]"
2047       "(115)[RUH]"
2048       "(91)[NH[(0)]]"
2049       "(64)["
2050         // nested annotation:
2051         "RSH"
2052         "NH[RUH(0)]"
2053         "]"
2054       "()[]"
2055     "]"
2056     );
2057 
2058   const char* md_layout_P = md_layout;
2059   const char* md_layout_A = md_layout+strlen(MDL0);
2060   const char* md_layout_V = md_layout+strlen(MDL0 MDL1);
2061   assert(0 == strncmp(&md_layout_A[-3], ")]][", 4));
2062   assert(0 == strncmp(&md_layout_V[-3], ")]][", 4));
2063 
2064   for (i = 0; i < ATTR_CONTEXT_LIMIT; i++) {
2065     attr_definitions& ad = attr_defs[i];
2066     ad.defineLayout(X_ATTR_RuntimeVisibleAnnotations,
2067                     "RuntimeVisibleAnnotations", md_layout_A);
2068     ad.defineLayout(X_ATTR_RuntimeInvisibleAnnotations,
2069                     "RuntimeInvisibleAnnotations", md_layout_A);
2070     if (i != ATTR_CONTEXT_METHOD)  continue;
2071     ad.defineLayout(METHOD_ATTR_RuntimeVisibleParameterAnnotations,
2072                     "RuntimeVisibleParameterAnnotations", md_layout_P);
2073     ad.defineLayout(METHOD_ATTR_RuntimeInvisibleParameterAnnotations,
2074                     "RuntimeInvisibleParameterAnnotations", md_layout_P);
2075     ad.defineLayout(METHOD_ATTR_AnnotationDefault,
2076                     "AnnotationDefault", md_layout_V);
2077   }
2078 
2079   attr_definition_headers.readData(attr_definition_count);
2080   attr_definition_name.readData(attr_definition_count);
2081   attr_definition_layout.readData(attr_definition_count);
2082 
2083   CHECK;
2084 
2085   // Initialize correct predef bits, to distinguish predefs from new defs.
2086 #define ORBIT(n,s) |((julong)1<<n)
2087   attr_defs[ATTR_CONTEXT_CLASS].predef
2088     = (0 X_ATTR_DO(ORBIT) CLASS_ATTR_DO(ORBIT));
2089   attr_defs[ATTR_CONTEXT_FIELD].predef
2090     = (0 X_ATTR_DO(ORBIT) FIELD_ATTR_DO(ORBIT));
2091   attr_defs[ATTR_CONTEXT_METHOD].predef
2092     = (0 X_ATTR_DO(ORBIT) METHOD_ATTR_DO(ORBIT));
2093   attr_defs[ATTR_CONTEXT_CODE].predef
2094     = (0 O_ATTR_DO(ORBIT) CODE_ATTR_DO(ORBIT));
2095 #undef ORBIT
2096   // Clear out the redef bits, folding them back into predef.
2097   for (i = 0; i < ATTR_CONTEXT_LIMIT; i++) {
2098     attr_defs[i].predef |= attr_defs[i].redef;
2099     attr_defs[i].redef = 0;
2100   }
2101 
2102   // Now read the transmitted locally defined attrs.
2103   // This will set redef bits again.
2104   for (i = 0; i < attr_definition_count; i++) {
2105     int    header  = attr_definition_headers.getByte();
2106     int    attrc   = ADH_BYTE_CONTEXT(header);
2107     int    idx     = ADH_BYTE_INDEX(header);
2108     entry* name    = attr_definition_name.getRef();
2109     entry* layout  = attr_definition_layout.getRef();
2110     CHECK;
2111     attr_defs[attrc].defineLayout(idx, name, layout->value.b.strval());
2112   }
2113 }
2114 
2115 #define NO_ENTRY_YET ((entry*)-1)
2116 
2117 static bool isDigitString(bytes& x, int beg, int end) {
2118   if (beg == end)  return false;  // null string
2119   byte* xptr = x.ptr;
2120   for (int i = beg; i < end; i++) {
2121     char ch = xptr[i];
2122     if (!(ch >= '0' && ch <= '9'))  return false;
2123   }
2124   return true;
2125 }
2126 
2127 enum {  // constants for parsing class names
2128   SLASH_MIN = '.',
2129   SLASH_MAX = '/',
2130   DOLLAR_MIN = 0,
2131   DOLLAR_MAX = '-'
2132 };
2133 
2134 static int lastIndexOf(int chmin, int chmax, bytes& x, int pos) {
2135   byte* ptr = x.ptr;
2136   for (byte* cp = ptr + pos; --cp >= ptr; ) {
2137     assert(x.inBounds(cp));
2138     if (*cp >= chmin && *cp <= chmax)
2139       return (int)(cp - ptr);
2140   }
2141   return -1;
2142 }
2143 
2144 maybe_inline
2145 inner_class* cpool::getIC(entry* inner) {
2146   if (inner == null)  return null;
2147   assert(inner->tag == CONSTANT_Class);
2148   if (inner->inord == NO_INORD)  return null;
2149   inner_class* ic = ic_index[inner->inord];
2150   assert(ic == null || ic->inner == inner);
2151   return ic;
2152 }
2153 
2154 maybe_inline
2155 inner_class* cpool::getFirstChildIC(entry* outer) {
2156   if (outer == null)  return null;
2157   assert(outer->tag == CONSTANT_Class);
2158   if (outer->inord == NO_INORD)  return null;
2159   inner_class* ic = ic_child_index[outer->inord];
2160   assert(ic == null || ic->outer == outer);
2161   return ic;
2162 }
2163 
2164 maybe_inline
2165 inner_class* cpool::getNextChildIC(inner_class* child) {
2166   inner_class* ic = child->next_sibling;
2167   assert(ic == null || ic->outer == child->outer);
2168   return ic;
2169 }
2170 
2171 void unpacker::read_ics() {
2172   int i;
2173   int index_size = cp.tag_count[CONSTANT_Class];
2174   inner_class** ic_index       = U_NEW(inner_class*, index_size);
2175   inner_class** ic_child_index = U_NEW(inner_class*, index_size);
2176   cp.ic_index = ic_index;
2177   cp.ic_child_index = ic_child_index;
2178   ics = U_NEW(inner_class, ic_count);
2179   ic_this_class.readData(ic_count);
2180   ic_flags.readData(ic_count);
2181   CHECK;
2182   // Scan flags to get count of long-form bands.
2183   int long_forms = 0;
2184   for (i = 0; i < ic_count; i++) {
2185     int flags = ic_flags.getInt();  // may be long form!
2186     if ((flags & ACC_IC_LONG_FORM) != 0) {
2187       long_forms += 1;
2188       ics[i].name = NO_ENTRY_YET;
2189     }
2190     flags &= ~ACC_IC_LONG_FORM;
2191     entry* inner = ic_this_class.getRef();
2192     CHECK;
2193     uint inord = inner->inord;
2194     assert(inord < (uint)cp.tag_count[CONSTANT_Class]);
2195     if (ic_index[inord] != null) {
2196       abort("identical inner class");
2197       break;
2198     }
2199     ic_index[inord] = &ics[i];
2200     ics[i].inner = inner;
2201     ics[i].flags = flags;
2202     assert(cp.getIC(inner) == &ics[i]);
2203   }
2204   CHECK;
2205   //ic_this_class.done();
2206   //ic_flags.done();
2207   ic_outer_class.readData(long_forms);
2208   ic_name.readData(long_forms);
2209   for (i = 0; i < ic_count; i++) {
2210     if (ics[i].name == NO_ENTRY_YET) {
2211       // Long form.
2212       ics[i].outer = ic_outer_class.getRefN();
2213       ics[i].name  = ic_name.getRefN();
2214     } else {
2215       // Fill in outer and name based on inner.
2216       bytes& n = ics[i].inner->value.b;
2217       bytes pkgOuter;
2218       bytes number;
2219       bytes name;
2220       // Parse n into pkgOuter and name (and number).
2221       PRINTCR((5, "parse short IC name %s", n.ptr));
2222       int dollar1, dollar2;  // pointers to $ in the pattern
2223       // parse n = (<pkg>/)*<outer>($<number>)?($<name>)?
2224       int nlen = (int)n.len;
2225       int pkglen = lastIndexOf(SLASH_MIN,  SLASH_MAX,  n, nlen) + 1;
2226       dollar2    = lastIndexOf(DOLLAR_MIN, DOLLAR_MAX, n, nlen);
2227       if (dollar2 < 0) {
2228          abort();
2229          return;
2230       }
2231       assert(dollar2 >= pkglen);
2232       if (isDigitString(n, dollar2+1, nlen)) {
2233         // n = (<pkg>/)*<outer>$<number>
2234         number = n.slice(dollar2+1, nlen);
2235         name.set(null,0);
2236         dollar1 = dollar2;
2237       } else if (pkglen < (dollar1
2238                            = lastIndexOf(DOLLAR_MIN, DOLLAR_MAX, n, dollar2-1))
2239                  && isDigitString(n, dollar1+1, dollar2)) {
2240         // n = (<pkg>/)*<outer>$<number>$<name>
2241         number = n.slice(dollar1+1, dollar2);
2242         name = n.slice(dollar2+1, nlen);
2243       } else {
2244         // n = (<pkg>/)*<outer>$<name>
2245         dollar1 = dollar2;
2246         number.set(null,0);
2247         name = n.slice(dollar2+1, nlen);
2248       }
2249       if (number.ptr == null)
2250         pkgOuter = n.slice(0, dollar1);
2251       else
2252         pkgOuter.set(null,0);
2253       PRINTCR((5,"=> %s$ 0%s $%s",
2254               pkgOuter.string(), number.string(), name.string()));
2255 
2256       if (pkgOuter.ptr != null)
2257         ics[i].outer = cp.ensureClass(pkgOuter);
2258 
2259       if (name.ptr != null)
2260         ics[i].name = cp.ensureUtf8(name);
2261     }
2262 
2263     // update child/sibling list
2264     if (ics[i].outer != null) {
2265       uint outord = ics[i].outer->inord;
2266       if (outord != NO_INORD) {
2267         assert(outord < (uint)cp.tag_count[CONSTANT_Class]);
2268         ics[i].next_sibling = ic_child_index[outord];
2269         ic_child_index[outord] = &ics[i];
2270       }
2271     }
2272   }
2273   //ic_outer_class.done();
2274   //ic_name.done();
2275 }
2276 
2277 void unpacker::read_classes() {
2278   PRINTCR((1,"  ...scanning %d classes...", class_count));
2279   class_this.readData(class_count);
2280   class_super.readData(class_count);
2281   class_interface_count.readData(class_count);
2282   class_interface.readData(class_interface_count.getIntTotal());
2283 
2284   CHECK;
2285 
2286   #if 0
2287   int i;
2288   // Make a little mark on super-classes.
2289   for (i = 0; i < class_count; i++) {
2290     entry* e = class_super.getRefN();
2291     if (e != null)  e->bits |= entry::EB_SUPER;
2292   }
2293   class_super.rewind();
2294   #endif
2295 
2296   // Members.
2297   class_field_count.readData(class_count);
2298   class_method_count.readData(class_count);
2299 
2300   CHECK;
2301 
2302   int field_count = class_field_count.getIntTotal();
2303   int method_count = class_method_count.getIntTotal();
2304 
2305   field_descr.readData(field_count);
2306   read_attrs(ATTR_CONTEXT_FIELD, field_count);
2307   CHECK;
2308 
2309   method_descr.readData(method_count);
2310   read_attrs(ATTR_CONTEXT_METHOD, method_count);
2311 
2312   CHECK;
2313 
2314   read_attrs(ATTR_CONTEXT_CLASS, class_count);
2315   CHECK;
2316 
2317   read_code_headers();
2318 
2319   PRINTCR((1,"scanned %d classes, %d fields, %d methods, %d code headers",
2320           class_count, field_count, method_count, code_count));
2321 }
2322 
2323 maybe_inline
2324 int unpacker::attr_definitions::predefCount(uint idx) {
2325   return isPredefined(idx) ? flag_count[idx] : 0;
2326 }
2327 
2328 void unpacker::read_attrs(int attrc, int obj_count) {
2329   attr_definitions& ad = attr_defs[attrc];
2330   assert(ad.attrc == attrc);
2331 
2332   int i, idx, count;
2333 
2334   CHECK;
2335 
2336   bool haveLongFlags = ad.haveLongFlags();
2337 
2338   band& xxx_flags_hi = ad.xxx_flags_hi();
2339   assert(endsWith(xxx_flags_hi.name, "_flags_hi"));
2340   if (haveLongFlags)
2341     xxx_flags_hi.readData(obj_count);
2342   CHECK;
2343 
2344   band& xxx_flags_lo = ad.xxx_flags_lo();
2345   assert(endsWith(xxx_flags_lo.name, "_flags_lo"));
2346   xxx_flags_lo.readData(obj_count);
2347   CHECK;
2348 
2349   // pre-scan flags, counting occurrences of each index bit
2350   julong indexMask = ad.flagIndexMask();  // which flag bits are index bits?
2351   for (i = 0; i < obj_count; i++) {
2352     julong indexBits = xxx_flags_hi.getLong(xxx_flags_lo, haveLongFlags);
2353     if ((indexBits & ~indexMask) > (ushort)-1) {
2354       abort("undefined attribute flag bit");
2355       return;
2356     }
2357     indexBits &= indexMask;  // ignore classfile flag bits
2358     for (idx = 0; indexBits != 0; idx++, indexBits >>= 1) {
2359       ad.flag_count[idx] += (int)(indexBits & 1);
2360     }
2361   }
2362   // we'll scan these again later for output:
2363   xxx_flags_lo.rewind();
2364   xxx_flags_hi.rewind();
2365 
2366   band& xxx_attr_count = ad.xxx_attr_count();
2367   assert(endsWith(xxx_attr_count.name, "_attr_count"));
2368   // There is one count element for each 1<<16 bit set in flags:
2369   xxx_attr_count.readData(ad.predefCount(X_ATTR_OVERFLOW));
2370   CHECK;
2371 
2372   band& xxx_attr_indexes = ad.xxx_attr_indexes();
2373   assert(endsWith(xxx_attr_indexes.name, "_attr_indexes"));
2374   int overflowIndexCount = xxx_attr_count.getIntTotal();
2375   xxx_attr_indexes.readData(overflowIndexCount);
2376   CHECK;
2377   // pre-scan attr indexes, counting occurrences of each value
2378   for (i = 0; i < overflowIndexCount; i++) {
2379     idx = xxx_attr_indexes.getInt();
2380     if (!ad.isIndex(idx)) {
2381       abort("attribute index out of bounds");
2382       return;
2383     }
2384     ad.getCount(idx) += 1;
2385   }
2386   xxx_attr_indexes.rewind();  // we'll scan it again later for output
2387 
2388   // We will need a backward call count for each used backward callable.
2389   int backwardCounts = 0;
2390   for (idx = 0; idx < ad.layouts.length(); idx++) {
2391     layout_definition* lo = ad.getLayout(idx);
2392     if (lo != null && ad.getCount(idx) != 0) {
2393       // Build the bands lazily, only when they are used.
2394       band** bands = ad.buildBands(lo);
2395       CHECK;
2396       if (lo->hasCallables()) {
2397         for (i = 0; bands[i] != null; i++) {
2398           if (bands[i]->le_back) {
2399             assert(bands[i]->le_kind == EK_CBLE);
2400             backwardCounts += 1;
2401           }
2402         }
2403       }
2404     }
2405   }
2406   ad.xxx_attr_calls().readData(backwardCounts);
2407   CHECK;
2408 
2409   // Read built-in bands.
2410   // Mostly, these are hand-coded equivalents to readBandData().
2411   switch (attrc) {
2412   case ATTR_CONTEXT_CLASS:
2413 
2414     count = ad.predefCount(CLASS_ATTR_SourceFile);
2415     class_SourceFile_RUN.readData(count);
2416     CHECK;
2417 
2418     count = ad.predefCount(CLASS_ATTR_EnclosingMethod);
2419     class_EnclosingMethod_RC.readData(count);
2420     class_EnclosingMethod_RDN.readData(count);
2421     CHECK;
2422 
2423     count = ad.predefCount(X_ATTR_Signature);
2424     class_Signature_RS.readData(count);
2425     CHECK;
2426 
2427     ad.readBandData(X_ATTR_RuntimeVisibleAnnotations);
2428     ad.readBandData(X_ATTR_RuntimeInvisibleAnnotations);
2429 
2430     count = ad.predefCount(CLASS_ATTR_InnerClasses);
2431     class_InnerClasses_N.readData(count);
2432     CHECK;
2433 
2434     count = class_InnerClasses_N.getIntTotal();
2435     class_InnerClasses_RC.readData(count);
2436     class_InnerClasses_F.readData(count);
2437     CHECK;
2438     // Drop remaining columns wherever flags are zero:
2439     count -= class_InnerClasses_F.getIntCount(0);
2440     class_InnerClasses_outer_RCN.readData(count);
2441     class_InnerClasses_name_RUN.readData(count);
2442     CHECK;
2443 
2444     count = ad.predefCount(CLASS_ATTR_ClassFile_version);
2445     class_ClassFile_version_minor_H.readData(count);
2446     class_ClassFile_version_major_H.readData(count);
2447     CHECK;
2448     break;
2449 
2450   case ATTR_CONTEXT_FIELD:
2451 
2452     count = ad.predefCount(FIELD_ATTR_ConstantValue);
2453     field_ConstantValue_KQ.readData(count);
2454     CHECK;
2455 
2456     count = ad.predefCount(X_ATTR_Signature);
2457     field_Signature_RS.readData(count);
2458     CHECK;
2459 
2460     ad.readBandData(X_ATTR_RuntimeVisibleAnnotations);
2461     ad.readBandData(X_ATTR_RuntimeInvisibleAnnotations);
2462     CHECK;
2463     break;
2464 
2465   case ATTR_CONTEXT_METHOD:
2466 
2467     code_count = ad.predefCount(METHOD_ATTR_Code);
2468     // Code attrs are handled very specially below...
2469 
2470     count = ad.predefCount(METHOD_ATTR_Exceptions);
2471     method_Exceptions_N.readData(count);
2472     count = method_Exceptions_N.getIntTotal();
2473     method_Exceptions_RC.readData(count);
2474     CHECK;
2475 
2476     count = ad.predefCount(X_ATTR_Signature);
2477     method_Signature_RS.readData(count);
2478     CHECK;
2479 
2480     ad.readBandData(X_ATTR_RuntimeVisibleAnnotations);
2481     ad.readBandData(X_ATTR_RuntimeInvisibleAnnotations);
2482     ad.readBandData(METHOD_ATTR_RuntimeVisibleParameterAnnotations);
2483     ad.readBandData(METHOD_ATTR_RuntimeInvisibleParameterAnnotations);
2484     ad.readBandData(METHOD_ATTR_AnnotationDefault);
2485     CHECK;
2486 
2487     count = ad.predefCount(METHOD_ATTR_MethodParameters);
2488     method_MethodParameters_NB.readData(count);
2489     count = method_MethodParameters_NB.getIntTotal();
2490     method_MethodParameters_name_RUN.readData(count);
2491     method_MethodParameters_flag_FH.readData(count);
2492     CHECK;
2493     break;
2494 
2495   case ATTR_CONTEXT_CODE:
2496     // (keep this code aligned with its brother in unpacker::write_attrs)
2497     count = ad.predefCount(CODE_ATTR_StackMapTable);
2498     // disable this feature in old archives!
2499     if (count != 0 && majver < JAVA6_PACKAGE_MAJOR_VERSION) {
2500       abort("undefined StackMapTable attribute (old archive format)");
2501       return;
2502     }
2503     code_StackMapTable_N.readData(count);
2504     CHECK;
2505     count = code_StackMapTable_N.getIntTotal();
2506     code_StackMapTable_frame_T.readData(count);
2507     CHECK;
2508     // the rest of it depends in a complicated way on frame tags
2509     {
2510       int fat_frame_count = 0;
2511       int offset_count = 0;
2512       int type_count = 0;
2513       for (int k = 0; k < count; k++) {
2514         int tag = code_StackMapTable_frame_T.getByte();
2515         if (tag <= 127) {
2516           // (64-127)  [(2)]
2517           if (tag >= 64)  type_count++;
2518         } else if (tag <= 251) {
2519           // (247)     [(1)(2)]
2520           // (248-251) [(1)]
2521           if (tag >= 247)  offset_count++;
2522           if (tag == 247)  type_count++;
2523         } else if (tag <= 254) {
2524           // (252)     [(1)(2)]
2525           // (253)     [(1)(2)(2)]
2526           // (254)     [(1)(2)(2)(2)]
2527           offset_count++;
2528           type_count += (tag - 251);
2529         } else {
2530           // (255)     [(1)NH[(2)]NH[(2)]]
2531           fat_frame_count++;
2532         }
2533       }
2534 
2535       // done pre-scanning frame tags:
2536       code_StackMapTable_frame_T.rewind();
2537 
2538       // deal completely with fat frames:
2539       offset_count += fat_frame_count;
2540       code_StackMapTable_local_N.readData(fat_frame_count);
2541       CHECK;
2542       type_count += code_StackMapTable_local_N.getIntTotal();
2543       code_StackMapTable_stack_N.readData(fat_frame_count);
2544       type_count += code_StackMapTable_stack_N.getIntTotal();
2545       CHECK;
2546       // read the rest:
2547       code_StackMapTable_offset.readData(offset_count);
2548       code_StackMapTable_T.readData(type_count);
2549       CHECK;
2550       // (7) [RCH]
2551       count = code_StackMapTable_T.getIntCount(7);
2552       code_StackMapTable_RC.readData(count);
2553       CHECK;
2554       // (8) [PH]
2555       count = code_StackMapTable_T.getIntCount(8);
2556       code_StackMapTable_P.readData(count);
2557       CHECK;
2558     }
2559 
2560     count = ad.predefCount(CODE_ATTR_LineNumberTable);
2561     code_LineNumberTable_N.readData(count);
2562     count = code_LineNumberTable_N.getIntTotal();
2563     code_LineNumberTable_bci_P.readData(count);
2564     code_LineNumberTable_line.readData(count);
2565 
2566     count = ad.predefCount(CODE_ATTR_LocalVariableTable);
2567     code_LocalVariableTable_N.readData(count);
2568     count = code_LocalVariableTable_N.getIntTotal();
2569     code_LocalVariableTable_bci_P.readData(count);
2570     code_LocalVariableTable_span_O.readData(count);
2571     code_LocalVariableTable_name_RU.readData(count);
2572     code_LocalVariableTable_type_RS.readData(count);
2573     code_LocalVariableTable_slot.readData(count);
2574 
2575     count = ad.predefCount(CODE_ATTR_LocalVariableTypeTable);
2576     code_LocalVariableTypeTable_N.readData(count);
2577     count = code_LocalVariableTypeTable_N.getIntTotal();
2578     code_LocalVariableTypeTable_bci_P.readData(count);
2579     code_LocalVariableTypeTable_span_O.readData(count);
2580     code_LocalVariableTypeTable_name_RU.readData(count);
2581     code_LocalVariableTypeTable_type_RS.readData(count);
2582     code_LocalVariableTypeTable_slot.readData(count);
2583     break;
2584   }
2585 
2586   // Read compressor-defined bands.
2587   for (idx = 0; idx < ad.layouts.length(); idx++) {
2588     if (ad.getLayout(idx) == null)
2589       continue;  // none at this fixed index <32
2590     if (idx < (int)ad.flag_limit && ad.isPredefined(idx))
2591       continue;  // already handled
2592     if (ad.getCount(idx) == 0)
2593       continue;  // no attributes of this type (then why transmit layouts?)
2594     ad.readBandData(idx);
2595   }
2596 }
2597 
2598 void unpacker::attr_definitions::readBandData(int idx) {
2599   int j;
2600   uint count = getCount(idx);
2601   if (count == 0)  return;
2602   layout_definition* lo = getLayout(idx);
2603   if (lo != null) {
2604     PRINTCR((1, "counted %d [redefined = %d predefined = %d] attributes of type %s.%s",
2605             count, isRedefined(idx), isPredefined(idx),
2606             ATTR_CONTEXT_NAME[attrc], lo->name));
2607   }
2608   bool hasCallables = lo->hasCallables();
2609   band** bands = lo->bands();
2610   if (!hasCallables) {
2611     // Read through the rest of the bands in a regular way.
2612     readBandData(bands, count);
2613   } else {
2614     // Deal with the callables.
2615     // First set up the forward entry count for each callable.
2616     // This is stored on band::length of the callable.
2617     bands[0]->expectMoreLength(count);
2618     for (j = 0; bands[j] != null; j++) {
2619       band& j_cble = *bands[j];
2620       assert(j_cble.le_kind == EK_CBLE);
2621       if (j_cble.le_back) {
2622         // Add in the predicted effects of backward calls, too.
2623         int back_calls = xxx_attr_calls().getInt();
2624         j_cble.expectMoreLength(back_calls);
2625         // In a moment, more forward calls may increment j_cble.length.
2626       }
2627     }
2628     // Now consult whichever callables have non-zero entry counts.
2629     readBandData(bands, (uint)-1);
2630   }
2631 }
2632 
2633 // Recursive helper to the previous function:
2634 void unpacker::attr_definitions::readBandData(band** body, uint count) {
2635   int j, k;
2636   for (j = 0; body[j] != null; j++) {
2637     band& b = *body[j];
2638     if (b.defc != null) {
2639       // It has data, so read it.
2640       b.readData(count);
2641     }
2642     switch (b.le_kind) {
2643     case EK_REPL:
2644       {
2645         int reps = b.getIntTotal();
2646         readBandData(b.le_body, reps);
2647       }
2648       break;
2649     case EK_UN:
2650       {
2651         int remaining = count;
2652         for (k = 0; b.le_body[k] != null; k++) {
2653           band& k_case = *b.le_body[k];
2654           int   k_count = 0;
2655           if (k_case.le_casetags == null) {
2656             k_count = remaining;  // last (empty) case
2657           } else {
2658             int* tags = k_case.le_casetags;
2659             int ntags = *tags++;  // 1st element is length (why not?)
2660             while (ntags-- > 0) {
2661               int tag = *tags++;
2662               k_count += b.getIntCount(tag);
2663             }
2664           }
2665           readBandData(k_case.le_body, k_count);
2666           remaining -= k_count;
2667         }
2668         assert(remaining == 0);
2669       }
2670       break;
2671     case EK_CALL:
2672       // Push the count forward, if it is not a backward call.
2673       if (!b.le_back) {
2674         band& cble = *b.le_body[0];
2675         assert(cble.le_kind == EK_CBLE);
2676         cble.expectMoreLength(count);
2677       }
2678       break;
2679     case EK_CBLE:
2680       assert((int)count == -1);  // incoming count is meaningless
2681       k = b.length;
2682       assert(k >= 0);
2683       // This is intended and required for non production mode.
2684       assert((b.length = -1)); // make it unable to accept more calls now.
2685       readBandData(b.le_body, k);
2686       break;
2687     }
2688   }
2689 }
2690 
2691 static inline
2692 band** findMatchingCase(int matchTag, band** cases) {
2693   for (int k = 0; cases[k] != null; k++) {
2694     band& k_case = *cases[k];
2695     if (k_case.le_casetags != null) {
2696       // If it has tags, it must match a tag.
2697       int* tags = k_case.le_casetags;
2698       int ntags = *tags++;  // 1st element is length
2699       for (; ntags > 0; ntags--) {
2700         int tag = *tags++;
2701         if (tag == matchTag)
2702           break;
2703       }
2704       if (ntags == 0)
2705         continue;   // does not match
2706     }
2707     return k_case.le_body;
2708   }
2709   return null;
2710 }
2711 
2712 // write attribute band data:
2713 void unpacker::putlayout(band** body) {
2714   int i;
2715   int prevBII = -1;
2716   int prevBCI = -1;
2717   if (body == NULL) {
2718     abort("putlayout: unexpected NULL for body");
2719     return;
2720   }
2721   for (i = 0; body[i] != null; i++) {
2722     band& b = *body[i];
2723     byte le_kind = b.le_kind;
2724 
2725     // Handle scalar part, if any.
2726     int    x = 0;
2727     entry* e = null;
2728     if (b.defc != null) {
2729       // It has data, so unparse an element.
2730       if (b.ixTag != CONSTANT_None) {
2731         assert(le_kind == EK_REF);
2732         if (b.ixTag == CONSTANT_FieldSpecific)
2733           e = b.getRefUsing(cp.getKQIndex());
2734         else
2735           e = b.getRefN();
2736         switch (b.le_len) {
2737         case 0: break;
2738         case 1: putu1ref(e); break;
2739         case 2: putref(e); break;
2740         case 4: putu2(0); putref(e); break;
2741         default: assert(false);
2742         }
2743       } else {
2744         assert(le_kind == EK_INT || le_kind == EK_REPL || le_kind == EK_UN);
2745         x = b.getInt();
2746 
2747         assert(!b.le_bci || prevBCI == (int)to_bci(prevBII));
2748         switch (b.le_bci) {
2749         case EK_BCI:   // PH:  transmit R(bci), store bci
2750           x = to_bci(prevBII = x);
2751           prevBCI = x;
2752           break;
2753         case EK_BCID:  // POH: transmit D(R(bci)), store bci
2754           x = to_bci(prevBII += x);
2755           prevBCI = x;
2756           break;
2757         case EK_BCO:   // OH:  transmit D(R(bci)), store D(bci)
2758           x = to_bci(prevBII += x) - prevBCI;
2759           prevBCI += x;
2760           break;
2761         }
2762         assert(!b.le_bci || prevBCI == (int)to_bci(prevBII));
2763 
2764         switch (b.le_len) {
2765         case 0: break;
2766         case 1: putu1(x); break;
2767         case 2: putu2(x); break;
2768         case 4: putu4(x); break;
2769         default: assert(false);
2770         }
2771       }
2772     }
2773 
2774     // Handle subparts, if any.
2775     switch (le_kind) {
2776     case EK_REPL:
2777       // x is the repeat count
2778       while (x-- > 0) {
2779         putlayout(b.le_body);
2780       }
2781       break;
2782     case EK_UN:
2783       // x is the tag
2784       putlayout(findMatchingCase(x, b.le_body));
2785       break;
2786     case EK_CALL:
2787       {
2788         band& cble = *b.le_body[0];
2789         assert(cble.le_kind == EK_CBLE);
2790         assert(cble.le_len == b.le_len);
2791         putlayout(cble.le_body);
2792       }
2793       break;
2794 
2795     #ifndef PRODUCT
2796     case EK_CBLE:
2797     case EK_CASE:
2798       assert(false);  // should not reach here
2799     #endif
2800     }
2801   }
2802 }
2803 
2804 void unpacker::read_files() {
2805   file_name.readData(file_count);
2806   if (testBit(archive_options, AO_HAVE_FILE_SIZE_HI))
2807     file_size_hi.readData(file_count);
2808   file_size_lo.readData(file_count);
2809   if (testBit(archive_options, AO_HAVE_FILE_MODTIME))
2810     file_modtime.readData(file_count);
2811   int allFiles = file_count + class_count;
2812   if (testBit(archive_options, AO_HAVE_FILE_OPTIONS)) {
2813     file_options.readData(file_count);
2814     // FO_IS_CLASS_STUB might be set, causing overlap between classes and files
2815     for (int i = 0; i < file_count; i++) {
2816       if ((file_options.getInt() & FO_IS_CLASS_STUB) != 0) {
2817         allFiles -= 1;  // this one counts as both class and file
2818       }
2819     }
2820     file_options.rewind();
2821   }
2822   assert((default_file_options & FO_IS_CLASS_STUB) == 0);
2823   files_remaining = allFiles;
2824 }
2825 
2826 maybe_inline
2827 void unpacker::get_code_header(int& max_stack,
2828                                int& max_na_locals,
2829                                int& handler_count,
2830                                int& cflags) {
2831   int sc = code_headers.getByte();
2832   if (sc == 0) {
2833     max_stack = max_na_locals = handler_count = cflags = -1;
2834     return;
2835   }
2836   // Short code header is the usual case:
2837   int nh;
2838   int mod;
2839   if (sc < 1 + 12*12) {
2840     sc -= 1;
2841     nh = 0;
2842     mod = 12;
2843   } else if (sc < 1 + 12*12 + 8*8) {
2844     sc -= 1 + 12*12;
2845     nh = 1;
2846     mod = 8;
2847   } else {
2848     assert(sc < 1 + 12*12 + 8*8 + 7*7);
2849     sc -= 1 + 12*12 + 8*8;
2850     nh = 2;
2851     mod = 7;
2852   }
2853   max_stack     = sc % mod;
2854   max_na_locals = sc / mod;  // caller must add static, siglen
2855   handler_count = nh;
2856   if (testBit(archive_options, AO_HAVE_ALL_CODE_FLAGS))
2857     cflags      = -1;
2858   else
2859     cflags      = 0;  // this one has no attributes
2860 }
2861 
2862 // Cf. PackageReader.readCodeHeaders
2863 void unpacker::read_code_headers() {
2864   code_headers.readData(code_count);
2865   CHECK;
2866   int totalHandlerCount = 0;
2867   int totalFlagsCount   = 0;
2868   for (int i = 0; i < code_count; i++) {
2869     int max_stack, max_locals, handler_count, cflags;
2870     get_code_header(max_stack, max_locals, handler_count, cflags);
2871     if (max_stack < 0)      code_max_stack.expectMoreLength(1);
2872     if (max_locals < 0)     code_max_na_locals.expectMoreLength(1);
2873     if (handler_count < 0)  code_handler_count.expectMoreLength(1);
2874     else                    totalHandlerCount += handler_count;
2875     if (cflags < 0)         totalFlagsCount += 1;
2876   }
2877   code_headers.rewind();  // replay later during writing
2878 
2879   code_max_stack.readData();
2880   code_max_na_locals.readData();
2881   code_handler_count.readData();
2882   totalHandlerCount += code_handler_count.getIntTotal();
2883   CHECK;
2884 
2885   // Read handler specifications.
2886   // Cf. PackageReader.readCodeHandlers.
2887   code_handler_start_P.readData(totalHandlerCount);
2888   code_handler_end_PO.readData(totalHandlerCount);
2889   code_handler_catch_PO.readData(totalHandlerCount);
2890   code_handler_class_RCN.readData(totalHandlerCount);
2891   CHECK;
2892 
2893   read_attrs(ATTR_CONTEXT_CODE, totalFlagsCount);
2894   CHECK;
2895 }
2896 
2897 static inline bool is_in_range(uint n, uint min, uint max) {
2898   return n - min <= max - min;  // unsigned arithmetic!
2899 }
2900 static inline bool is_field_op(int bc) {
2901   return is_in_range(bc, bc_getstatic, bc_putfield);
2902 }
2903 static inline bool is_invoke_init_op(int bc) {
2904   return is_in_range(bc, _invokeinit_op, _invokeinit_limit-1);
2905 }
2906 static inline bool is_self_linker_op(int bc) {
2907   return is_in_range(bc, _self_linker_op, _self_linker_limit-1);
2908 }
2909 static bool is_branch_op(int bc) {
2910   return is_in_range(bc, bc_ifeq,   bc_jsr)
2911       || is_in_range(bc, bc_ifnull, bc_jsr_w);
2912 }
2913 static bool is_local_slot_op(int bc) {
2914   return is_in_range(bc, bc_iload,  bc_aload)
2915       || is_in_range(bc, bc_istore, bc_astore)
2916       || bc == bc_iinc || bc == bc_ret;
2917 }
2918 band* unpacker::ref_band_for_op(int bc) {
2919   switch (bc) {
2920   case bc_ildc:
2921   case bc_ildc_w:
2922     return &bc_intref;
2923   case bc_fldc:
2924   case bc_fldc_w:
2925     return &bc_floatref;
2926   case bc_lldc2_w:
2927     return &bc_longref;
2928   case bc_dldc2_w:
2929     return &bc_doubleref;
2930   case bc_sldc:
2931   case bc_sldc_w:
2932     return &bc_stringref;
2933   case bc_cldc:
2934   case bc_cldc_w:
2935     return &bc_classref;
2936   case bc_qldc: case bc_qldc_w:
2937     return &bc_loadablevalueref;
2938 
2939   case bc_getstatic:
2940   case bc_putstatic:
2941   case bc_getfield:
2942   case bc_putfield:
2943     return &bc_fieldref;
2944 
2945   case bc_invokevirtual:
2946   case bc_invokespecial:
2947   case bc_invokestatic:
2948     return &bc_methodref;
2949   case bc_invokeinterface:
2950     return &bc_imethodref;
2951   case bc_invokedynamic:
2952     return &bc_indyref;
2953 
2954   case bc_new:
2955   case bc_anewarray:
2956   case bc_checkcast:
2957   case bc_instanceof:
2958   case bc_multianewarray:
2959     return &bc_classref;
2960   }
2961   return null;
2962 }
2963 
2964 maybe_inline
2965 band* unpacker::ref_band_for_self_op(int bc, bool& isAloadVar, int& origBCVar) {
2966   if (!is_self_linker_op(bc))  return null;
2967   int idx = (bc - _self_linker_op);
2968   bool isSuper = (idx >= _self_linker_super_flag);
2969   if (isSuper)  idx -= _self_linker_super_flag;
2970   bool isAload = (idx >= _self_linker_aload_flag);
2971   if (isAload)  idx -= _self_linker_aload_flag;
2972   int origBC = _first_linker_op + idx;
2973   bool isField = is_field_op(origBC);
2974   isAloadVar = isAload;
2975   origBCVar  = _first_linker_op + idx;
2976   if (!isSuper)
2977     return isField? &bc_thisfield: &bc_thismethod;
2978   else
2979     return isField? &bc_superfield: &bc_supermethod;
2980 }
2981 
2982 // Cf. PackageReader.readByteCodes
2983 inline  // called exactly once => inline
2984 void unpacker::read_bcs() {
2985   PRINTCR((3, "reading compressed bytecodes and operands for %d codes...",
2986           code_count));
2987 
2988   // read from bc_codes and bc_case_count
2989   fillbytes all_switch_ops;
2990   all_switch_ops.init();
2991   CHECK;
2992 
2993   // Read directly from rp/rplimit.
2994   //Do this later:  bc_codes.readData(...)
2995   byte* rp0 = rp;
2996 
2997   band* bc_which;
2998   byte* opptr = rp;
2999   byte* oplimit = rplimit;
3000 
3001   bool  isAload;  // passed by ref and then ignored
3002   int   junkBC;   // passed by ref and then ignored
3003   for (int k = 0; k < code_count; k++) {
3004     // Scan one method:
3005     for (;;) {
3006       if (opptr+2 > oplimit) {
3007         rp = opptr;
3008         ensure_input(2);
3009         oplimit = rplimit;
3010         rp = rp0;  // back up
3011       }
3012       if (opptr == oplimit) { abort(); break; }
3013       int bc = *opptr++ & 0xFF;
3014       bool isWide = false;
3015       if (bc == bc_wide) {
3016         if (opptr == oplimit) { abort(); break; }
3017         bc = *opptr++ & 0xFF;
3018         isWide = true;
3019       }
3020       // Adjust expectations of various band sizes.
3021       switch (bc) {
3022       case bc_tableswitch:
3023       case bc_lookupswitch:
3024         all_switch_ops.addByte(bc);
3025         break;
3026       case bc_iinc:
3027         bc_local.expectMoreLength(1);
3028         bc_which = isWide ? &bc_short : &bc_byte;
3029         bc_which->expectMoreLength(1);
3030         break;
3031       case bc_sipush:
3032         bc_short.expectMoreLength(1);
3033         break;
3034       case bc_bipush:
3035         bc_byte.expectMoreLength(1);
3036         break;
3037       case bc_newarray:
3038         bc_byte.expectMoreLength(1);
3039         break;
3040       case bc_multianewarray:
3041         assert(ref_band_for_op(bc) == &bc_classref);
3042         bc_classref.expectMoreLength(1);
3043         bc_byte.expectMoreLength(1);
3044         break;
3045       case bc_ref_escape:
3046         bc_escrefsize.expectMoreLength(1);
3047         bc_escref.expectMoreLength(1);
3048         break;
3049       case bc_byte_escape:
3050         bc_escsize.expectMoreLength(1);
3051         // bc_escbyte will have to be counted too
3052         break;
3053       default:
3054         if (is_invoke_init_op(bc)) {
3055           bc_initref.expectMoreLength(1);
3056           break;
3057         }
3058         bc_which = ref_band_for_self_op(bc, isAload, junkBC);
3059         if (bc_which != null) {
3060           bc_which->expectMoreLength(1);
3061           break;
3062         }
3063         if (is_branch_op(bc)) {
3064           bc_label.expectMoreLength(1);
3065           break;
3066         }
3067         bc_which = ref_band_for_op(bc);
3068         if (bc_which != null) {
3069           bc_which->expectMoreLength(1);
3070           assert(bc != bc_multianewarray);  // handled elsewhere
3071           break;
3072         }
3073         if (is_local_slot_op(bc)) {
3074           bc_local.expectMoreLength(1);
3075           break;
3076         }
3077         break;
3078       case bc_end_marker:
3079         // Increment k and test against code_count.
3080         goto doneScanningMethod;
3081       }
3082     }
3083   doneScanningMethod:{}
3084     if (aborting())  break;
3085   }
3086 
3087   // Go through the formality, so we can use it in a regular fashion later:
3088   assert(rp == rp0);
3089   bc_codes.readData((int)(opptr - rp));
3090 
3091   int i = 0;
3092 
3093   // To size instruction bands correctly, we need info on switches:
3094   bc_case_count.readData((int)all_switch_ops.size());
3095   for (i = 0; i < (int)all_switch_ops.size(); i++) {
3096     int caseCount = bc_case_count.getInt();
3097     int bc        = all_switch_ops.getByte(i);
3098     bc_label.expectMoreLength(1+caseCount); // default label + cases
3099     bc_case_value.expectMoreLength(bc == bc_tableswitch ? 1 : caseCount);
3100     PRINTCR((2, "switch bc=%d caseCount=%d", bc, caseCount));
3101   }
3102   bc_case_count.rewind();  // uses again for output
3103 
3104   all_switch_ops.free();
3105 
3106   for (i = e_bc_case_value; i <= e_bc_escsize; i++) {
3107     all_bands[i].readData();
3108   }
3109 
3110   // The bc_escbyte band is counted by the immediately previous band.
3111   bc_escbyte.readData(bc_escsize.getIntTotal());
3112 
3113   PRINTCR((3, "scanned %d opcode and %d operand bytes for %d codes...",
3114           (int)(bc_codes.size()),
3115           (int)(bc_escsize.maxRP() - bc_case_value.minRP()),
3116           code_count));
3117 }
3118 
3119 void unpacker::read_bands() {
3120   byte* rp0 = rp;
3121 
3122   read_file_header();
3123   CHECK;
3124 
3125   if (cp.nentries == 0) {
3126     // read_file_header failed to read a CP, because it copied a JAR.
3127     return;
3128   }
3129 
3130   // Do this after the file header has been read:
3131   check_options();
3132 
3133   read_cp();
3134   CHECK;
3135   read_attr_defs();
3136   CHECK;
3137   read_ics();
3138   CHECK;
3139   read_classes();
3140   CHECK;
3141   read_bcs();
3142   CHECK;
3143   read_files();
3144 }
3145 
3146 /// CP routines
3147 
3148 entry*& cpool::hashTabRef(byte tag, bytes& b) {
3149   PRINTCR((5, "hashTabRef tag=%d %s[%d]", tag, b.string(), b.len));
3150   uint hash = tag + (int)b.len;
3151   for (int i = 0; i < (int)b.len; i++) {
3152     hash = hash * 31 + (0xFF & b.ptr[i]);
3153   }
3154   entry**  ht = hashTab;
3155   int    hlen = hashTabLength;
3156   assert((hlen & (hlen-1)) == 0);  // must be power of 2
3157   uint hash1 = hash & (hlen-1);    // == hash % hlen
3158   uint hash2 = 0;                  // lazily computed (requires mod op.)
3159   int probes = 0;
3160   while (ht[hash1] != null) {
3161     entry& e = *ht[hash1];
3162     if (e.value.b.equals(b) && e.tag == tag)
3163       break;
3164     if (hash2 == 0)
3165       // Note:  hash2 must be relatively prime to hlen, hence the "|1".
3166       hash2 = (((hash % 499) & (hlen-1)) | 1);
3167     hash1 += hash2;
3168     if (hash1 >= (uint)hlen)  hash1 -= hlen;
3169     assert(hash1 < (uint)hlen);
3170     assert(++probes < hlen);
3171   }
3172   #ifndef PRODUCT
3173   hash_probes[0] += 1;
3174   hash_probes[1] += probes;
3175   #endif
3176   PRINTCR((5, " => @%d %p", hash1, ht[hash1]));
3177   return ht[hash1];
3178 }
3179 
3180 maybe_inline
3181 static void insert_extra(entry* e, ptrlist& extras) {
3182   // This ordering helps implement the Pack200 requirement
3183   // of a predictable CP order in the class files produced.
3184   e->inord = NO_INORD;  // mark as an "extra"
3185   extras.add(e);
3186   // Note:  We will sort the list (by string-name) later.
3187 }
3188 
3189 entry* cpool::ensureUtf8(bytes& b) {
3190   entry*& ix = hashTabRef(CONSTANT_Utf8, b);
3191   if (ix != null)  return ix;
3192   // Make one.
3193   if (nentries == maxentries) {
3194     abort("cp utf8 overflow");
3195     return &entries[tag_base[CONSTANT_Utf8]];  // return something
3196   }
3197   entry& e = entries[nentries++];
3198   e.tag = CONSTANT_Utf8;
3199   u->saveTo(e.value.b, b);
3200   assert(&e >= first_extra_entry);
3201   insert_extra(&e, tag_extras[CONSTANT_Utf8]);
3202   PRINTCR((4,"ensureUtf8 miss %s", e.string()));
3203   return ix = &e;
3204 }
3205 
3206 entry* cpool::ensureClass(bytes& b) {
3207   entry*& ix = hashTabRef(CONSTANT_Class, b);
3208   if (ix != null)  return ix;
3209   // Make one.
3210   if (nentries == maxentries) {
3211     abort("cp class overflow");
3212     return &entries[tag_base[CONSTANT_Class]];  // return something
3213   }
3214   entry& e = entries[nentries++];
3215   e.tag = CONSTANT_Class;
3216   e.nrefs = 1;
3217   e.refs = U_NEW(entry*, 1);
3218   ix = &e;  // hold my spot in the index
3219   entry* utf = ensureUtf8(b);
3220   e.refs[0] = utf;
3221   e.value.b = utf->value.b;
3222   assert(&e >= first_extra_entry);
3223   insert_extra(&e, tag_extras[CONSTANT_Class]);
3224   PRINTCR((4,"ensureClass miss %s", e.string()));
3225   return &e;
3226 }
3227 
3228 void cpool::expandSignatures() {
3229   int i;
3230   int nsigs = 0;
3231   int nreused = 0;
3232   int first_sig = tag_base[CONSTANT_Signature];
3233   int sig_limit = tag_count[CONSTANT_Signature] + first_sig;
3234   fillbytes buf;
3235   buf.init(1<<10);
3236   CHECK;
3237   for (i = first_sig; i < sig_limit; i++) {
3238     entry& e = entries[i];
3239     assert(e.tag == CONSTANT_Signature);
3240     int refnum = 0;
3241     bytes form = e.refs[refnum++]->asUtf8();
3242     buf.empty();
3243     for (int j = 0; j < (int)form.len; j++) {
3244       int c = form.ptr[j];
3245       buf.addByte(c);
3246       if (c == 'L') {
3247         entry* cls = e.refs[refnum++];
3248         buf.append(cls->className()->asUtf8());
3249       }
3250     }
3251     assert(refnum == e.nrefs);
3252     bytes& sig = buf.b;
3253     PRINTCR((5,"signature %d %s -> %s", i, form.ptr, sig.ptr));
3254 
3255     // try to find a pre-existing Utf8:
3256     entry* &e2 = hashTabRef(CONSTANT_Utf8, sig);
3257     if (e2 != null) {
3258       assert(e2->isUtf8(sig));
3259       e.value.b = e2->value.b;
3260       e.refs[0] = e2;
3261       e.nrefs = 1;
3262       PRINTCR((5,"signature replaced %d => %s", i, e.string()));
3263       nreused++;
3264     } else {
3265       // there is no other replacement; reuse this CP entry as a Utf8
3266       u->saveTo(e.value.b, sig);
3267       e.tag = CONSTANT_Utf8;
3268       e.nrefs = 0;
3269       e2 = &e;
3270       PRINTCR((5,"signature changed %d => %s", e.inord, e.string()));
3271     }
3272     nsigs++;
3273   }
3274   PRINTCR((1,"expanded %d signatures (reused %d utfs)", nsigs, nreused));
3275   buf.free();
3276 
3277   // go expunge all references to remaining signatures:
3278   for (i = 0; i < (int)nentries; i++) {
3279     entry& e = entries[i];
3280     for (int j = 0; j < e.nrefs; j++) {
3281       entry*& e2 = e.refs[j];
3282       if (e2 != null && e2->tag == CONSTANT_Signature)
3283         e2 = e2->refs[0];
3284     }
3285   }
3286 }
3287 
3288 bool isLoadableValue(int tag) {
3289   switch(tag) {
3290     case CONSTANT_Integer:
3291     case CONSTANT_Float:
3292     case CONSTANT_Long:
3293     case CONSTANT_Double:
3294     case CONSTANT_String:
3295     case CONSTANT_Class:
3296     case CONSTANT_MethodHandle:
3297     case CONSTANT_MethodType:
3298       return true;
3299     default:
3300       return false;
3301   }
3302 }
3303 /*
3304  * this method can be used to size an array using null as the parameter,
3305  * thereafter can be reused to initialize the array using a valid pointer
3306  * as a parameter.
3307  */
3308 int cpool::initLoadableValues(entry** loadable_entries) {
3309   int loadable_count = 0;
3310   for (int i = 0; i < (int)N_TAGS_IN_ORDER; i++) {
3311     int tag = TAGS_IN_ORDER[i];
3312     if (!isLoadableValue(tag))
3313       continue;
3314     if (loadable_entries != NULL) {
3315       for (int n = 0 ; n < tag_count[tag] ; n++) {
3316         loadable_entries[loadable_count + n] = &entries[tag_base[tag] + n];
3317       }
3318     }
3319     loadable_count += tag_count[tag];
3320   }
3321   return loadable_count;
3322 }
3323 
3324 // Initialize various views into the constant pool.
3325 void cpool::initGroupIndexes() {
3326   // Initialize All
3327   int all_count = 0;
3328   for (int tag = CONSTANT_None ; tag < CONSTANT_Limit ; tag++) {
3329     all_count += tag_count[tag];
3330   }
3331   entry* all_entries = &entries[tag_base[CONSTANT_None]];
3332   tag_group_count[CONSTANT_All - CONSTANT_All] = all_count;
3333   tag_group_index[CONSTANT_All - CONSTANT_All].init(all_count, all_entries, CONSTANT_All);
3334 
3335   // Initialize LoadableValues
3336   int loadable_count = initLoadableValues(NULL);
3337   entry** loadable_entries = U_NEW(entry*, loadable_count);
3338   initLoadableValues(loadable_entries);
3339   tag_group_count[CONSTANT_LoadableValue - CONSTANT_All] = loadable_count;
3340   tag_group_index[CONSTANT_LoadableValue - CONSTANT_All].init(loadable_count,
3341                   loadable_entries, CONSTANT_LoadableValue);
3342 
3343 // Initialize AnyMembers
3344   int any_count = tag_count[CONSTANT_Fieldref] +
3345                   tag_count[CONSTANT_Methodref] +
3346                   tag_count[CONSTANT_InterfaceMethodref];
3347   entry *any_entries = &entries[tag_base[CONSTANT_Fieldref]];
3348   tag_group_count[CONSTANT_AnyMember - CONSTANT_All] = any_count;
3349   tag_group_index[CONSTANT_AnyMember - CONSTANT_All].init(any_count,
3350                                                any_entries, CONSTANT_AnyMember);
3351 }
3352 
3353 void cpool::initMemberIndexes() {
3354   // This function does NOT refer to any class schema.
3355   // It is totally internal to the cpool.
3356   int i, j;
3357 
3358   // Get the pre-existing indexes:
3359   int   nclasses = tag_count[CONSTANT_Class];
3360   entry* classes = tag_base[CONSTANT_Class] + entries;
3361   int   nfields  = tag_count[CONSTANT_Fieldref];
3362   entry* fields  = tag_base[CONSTANT_Fieldref] + entries;
3363   int   nmethods = tag_count[CONSTANT_Methodref];
3364   entry* methods = tag_base[CONSTANT_Methodref] + entries;
3365 
3366   int*     field_counts  = T_NEW(int, nclasses);
3367   int*     method_counts = T_NEW(int, nclasses);
3368   cpindex* all_indexes   = U_NEW(cpindex, nclasses*2);
3369   entry**  field_ix      = U_NEW(entry*, add_size(nfields, nclasses));
3370   entry**  method_ix     = U_NEW(entry*, add_size(nmethods, nclasses));
3371 
3372   for (j = 0; j < nfields; j++) {
3373     entry& f = fields[j];
3374     i = f.memberClass()->inord;
3375     assert(i < nclasses);
3376     field_counts[i]++;
3377   }
3378   for (j = 0; j < nmethods; j++) {
3379     entry& m = methods[j];
3380     i = m.memberClass()->inord;
3381     assert(i < nclasses);
3382     method_counts[i]++;
3383   }
3384 
3385   int fbase = 0, mbase = 0;
3386   for (i = 0; i < nclasses; i++) {
3387     int fc = field_counts[i];
3388     int mc = method_counts[i];
3389     all_indexes[i*2+0].init(fc, field_ix+fbase,
3390                             CONSTANT_Fieldref  + SUBINDEX_BIT);
3391     all_indexes[i*2+1].init(mc, method_ix+mbase,
3392                             CONSTANT_Methodref + SUBINDEX_BIT);
3393     // reuse field_counts and member_counts as fill pointers:
3394     field_counts[i] = fbase;
3395     method_counts[i] = mbase;
3396     PRINTCR((3, "class %d fields @%d[%d] methods @%d[%d]",
3397             i, fbase, fc, mbase, mc));
3398     fbase += fc+1;
3399     mbase += mc+1;
3400     // (the +1 leaves a space between every subarray)
3401   }
3402   assert(fbase == nfields+nclasses);
3403   assert(mbase == nmethods+nclasses);
3404 
3405   for (j = 0; j < nfields; j++) {
3406     entry& f = fields[j];
3407     i = f.memberClass()->inord;
3408     field_ix[field_counts[i]++] = &f;
3409   }
3410   for (j = 0; j < nmethods; j++) {
3411     entry& m = methods[j];
3412     i = m.memberClass()->inord;
3413     method_ix[method_counts[i]++] = &m;
3414   }
3415 
3416   member_indexes = all_indexes;
3417 
3418 #ifndef PRODUCT
3419   // Test the result immediately on every class and field.
3420   int fvisited = 0, mvisited = 0;
3421   int prevord, len;
3422   for (i = 0; i < nclasses; i++) {
3423     entry*   cls = &classes[i];
3424     cpindex* fix = getFieldIndex(cls);
3425     cpindex* mix = getMethodIndex(cls);
3426     PRINTCR((2, "field and method index for %s [%d] [%d]",
3427             cls->string(), mix->len, fix->len));
3428     prevord = -1;
3429     for (j = 0, len = fix->len; j < len; j++) {
3430       entry* f = fix->get(j);
3431       assert(f != null);
3432       PRINTCR((3, "- field %s", f->string()));
3433       assert(f->memberClass() == cls);
3434       assert(prevord < (int)f->inord);
3435       prevord = f->inord;
3436       fvisited++;
3437     }
3438     assert(fix->base2[j] == null);
3439     prevord = -1;
3440     for (j = 0, len = mix->len; j < len; j++) {
3441       entry* m = mix->get(j);
3442       assert(m != null);
3443       PRINTCR((3, "- method %s", m->string()));
3444       assert(m->memberClass() == cls);
3445       assert(prevord < (int)m->inord);
3446       prevord = m->inord;
3447       mvisited++;
3448     }
3449     assert(mix->base2[j] == null);
3450   }
3451   assert(fvisited == nfields);
3452   assert(mvisited == nmethods);
3453 #endif
3454 
3455   // Free intermediate buffers.
3456   u->free_temps();
3457 }
3458 
3459 void entry::requestOutputIndex(cpool& cp, int req) {
3460   assert(outputIndex <= REQUESTED_NONE);  // must not have assigned indexes yet
3461   if (tag == CONSTANT_Signature) {
3462     ref(0)->requestOutputIndex(cp, req);
3463     return;
3464   }
3465   assert(req == REQUESTED || req == REQUESTED_LDC);
3466   if (outputIndex != REQUESTED_NONE) {
3467     if (req == REQUESTED_LDC)
3468       outputIndex = req;  // this kind has precedence
3469     return;
3470   }
3471   outputIndex = req;
3472   //assert(!cp.outputEntries.contains(this));
3473   assert(tag != CONSTANT_Signature);
3474   // The BSMs are jetisoned to a side table, however all references
3475   // that the BSMs refer to,  need to be considered.
3476   if (tag == CONSTANT_BootstrapMethod) {
3477     // this is a a pseudo-op entry; an attribute will be generated later on
3478     cp.requested_bsms.add(this);
3479   } else {
3480     // all other tag types go into real output file CP:
3481     cp.outputEntries.add(this);
3482   }
3483   for (int j = 0; j < nrefs; j++) {
3484     ref(j)->requestOutputIndex(cp);
3485   }
3486 }
3487 
3488 void cpool::resetOutputIndexes() {
3489     /*
3490      * reset those few entries that are being used in the current class
3491      * (Caution since this method is called after every class written, a loop
3492      * over every global constant pool entry would be a quadratic cost.)
3493      */
3494 
3495   int noes    = outputEntries.length();
3496   entry** oes = (entry**) outputEntries.base();
3497   for (int i = 0 ; i < noes ; i++) {
3498     entry& e = *oes[i];
3499     e.outputIndex = REQUESTED_NONE;
3500   }
3501 
3502   // do the same for bsms and reset them if required
3503   int nbsms = requested_bsms.length();
3504   entry** boes = (entry**) requested_bsms.base();
3505   for (int i = 0 ; i < nbsms ; i++) {
3506     entry& e = *boes[i];
3507     e.outputIndex = REQUESTED_NONE;
3508   }
3509   outputIndexLimit = 0;
3510   outputEntries.empty();
3511 #ifndef PRODUCT
3512   // ensure things are cleared out
3513   for (int i = 0; i < (int)maxentries; i++)
3514     assert(entries[i].outputIndex == REQUESTED_NONE);
3515 #endif
3516 }
3517 
3518 static const byte TAG_ORDER[CONSTANT_Limit] = {
3519   0, 1, 0, 2, 3, 4, 5, 7, 6, 10, 11, 12, 9, 8, 0, 13, 14, 15, 16
3520 };
3521 
3522 extern "C"
3523 int outputEntry_cmp(const void* e1p, const void* e2p) {
3524   // Sort entries according to the Pack200 rules for deterministic
3525   // constant pool ordering.
3526   //
3527   // The four sort keys as follows, in order of decreasing importance:
3528   //   1. ldc first, then non-ldc guys
3529   //   2. normal cp_All entries by input order (i.e., address order)
3530   //   3. after that, extra entries by lexical order (as in tag_extras[*])
3531   entry& e1 = *(entry*) *(void**) e1p;
3532   entry& e2 = *(entry*) *(void**) e2p;
3533   int   oi1 = e1.outputIndex;
3534   int   oi2 = e2.outputIndex;
3535   assert(oi1 == REQUESTED || oi1 == REQUESTED_LDC);
3536   assert(oi2 == REQUESTED || oi2 == REQUESTED_LDC);
3537   if (oi1 != oi2) {
3538     if (oi1 == REQUESTED_LDC)  return 0-1;
3539     if (oi2 == REQUESTED_LDC)  return 1-0;
3540     // Else fall through; neither is an ldc request.
3541   }
3542   if (e1.inord != NO_INORD || e2.inord != NO_INORD) {
3543     // One or both is normal.  Use input order.
3544     if (&e1 > &e2)  return 1-0;
3545     if (&e1 < &e2)  return 0-1;
3546     return 0;  // equal pointers
3547   }
3548   // Both are extras.  Sort by tag and then by value.
3549   if (e1.tag != e2.tag) {
3550     return TAG_ORDER[e1.tag] - TAG_ORDER[e2.tag];
3551   }
3552   // If the tags are the same, use string comparison.
3553   return compare_Utf8_chars(e1.value.b, e2.value.b);
3554 }
3555 
3556 void cpool::computeOutputIndexes() {
3557   int i;
3558 
3559 #ifndef PRODUCT
3560   // outputEntries must be a complete list of those requested:
3561   static uint checkStart = 0;
3562   int checkStep = 1;
3563   if (nentries > 100)  checkStep = nentries / 100;
3564   for (i = (int)(checkStart++ % checkStep); i < (int)nentries; i += checkStep) {
3565     entry& e = entries[i];
3566     if (e.tag == CONSTANT_BootstrapMethod) {
3567       if (e.outputIndex != REQUESTED_NONE) {
3568         assert(requested_bsms.contains(&e));
3569       } else {
3570         assert(!requested_bsms.contains(&e));
3571       }
3572     } else {
3573       if (e.outputIndex != REQUESTED_NONE) {
3574         assert(outputEntries.contains(&e));
3575       } else {
3576         assert(!outputEntries.contains(&e));
3577       }
3578     }
3579   }
3580 
3581   // check hand-initialization of TAG_ORDER
3582   for (i = 0; i < (int)N_TAGS_IN_ORDER; i++) {
3583     byte tag = TAGS_IN_ORDER[i];
3584     assert(TAG_ORDER[tag] == i+1);
3585   }
3586 #endif
3587 
3588   int    noes =           outputEntries.length();
3589   entry** oes = (entry**) outputEntries.base();
3590 
3591   // Sort the output constant pool into the order required by Pack200.
3592   PTRLIST_QSORT(outputEntries, outputEntry_cmp);
3593 
3594   // Allocate a new index for each entry that needs one.
3595   // We do this in two passes, one for LDC entries and one for the rest.
3596   int nextIndex = 1;  // always skip index #0 in output cpool
3597   for (i = 0; i < noes; i++) {
3598     entry& e = *oes[i];
3599     assert(e.outputIndex >= REQUESTED_LDC);
3600     e.outputIndex = nextIndex++;
3601     if (e.isDoubleWord())  nextIndex++;  // do not use the next index
3602   }
3603   outputIndexLimit = nextIndex;
3604   PRINTCR((3,"renumbering CP to %d entries", outputIndexLimit));
3605 }
3606 
3607 #ifndef PRODUCT
3608 // debugging goo
3609 
3610 unpacker* debug_u;
3611 
3612 static bytes& getbuf(int len) {  // for debugging only!
3613   static int bn = 0;
3614   static bytes bufs[8];
3615   bytes& buf = bufs[bn++ & 7];
3616   while ((int)buf.len < len+10)
3617     buf.realloc(buf.len ? buf.len * 2 : 1000);
3618   buf.ptr[0] = 0;  // for the sake of strcat
3619   return buf;
3620 }
3621 
3622 char* entry::string() {
3623   bytes buf;
3624   switch (tag) {
3625   case CONSTANT_None:
3626     return (char*)"<empty>";
3627   case CONSTANT_Signature:
3628     if (value.b.ptr == null)
3629       return ref(0)->string();
3630     // else fall through:
3631   case CONSTANT_Utf8:
3632     buf = value.b;
3633     break;
3634   case CONSTANT_Integer:
3635   case CONSTANT_Float:
3636     buf = getbuf(12);
3637     sprintf((char*)buf.ptr, "0x%08x", value.i);
3638     break;
3639   case CONSTANT_Long:
3640   case CONSTANT_Double:
3641     buf = getbuf(24);
3642     sprintf((char*)buf.ptr, "0x" LONG_LONG_HEX_FORMAT, value.l);
3643     break;
3644   default:
3645     if (nrefs == 0) {
3646       buf = getbuf(20);
3647       sprintf((char*)buf.ptr, TAG_NAME[tag]);
3648     } else if (nrefs == 1) {
3649       return refs[0]->string();
3650     } else {
3651       char* s1 = refs[0]->string();
3652       char* s2 = refs[1]->string();
3653       buf = getbuf((int)strlen(s1) + 1 + (int)strlen(s2) + 4 + 1);
3654       buf.strcat(s1).strcat(" ").strcat(s2);
3655       if (nrefs > 2)  buf.strcat(" ...");
3656     }
3657   }
3658   return (char*)buf.ptr;
3659 }
3660 
3661 void print_cp_entry(int i) {
3662   entry& e = debug_u->cp.entries[i];
3663   char buf[30];
3664   sprintf(buf, ((uint)e.tag < CONSTANT_Limit)? TAG_NAME[e.tag]: "%d", e.tag);
3665   printf(" %d\t%s %s\n", i, buf, e.string());
3666 }
3667 
3668 void print_cp_entries(int beg, int end) {
3669   for (int i = beg; i < end; i++)
3670     print_cp_entry(i);
3671 }
3672 
3673 void print_cp() {
3674   print_cp_entries(0, debug_u->cp.nentries);
3675 }
3676 
3677 #endif
3678 
3679 // Unpacker Start
3680 
3681 const char str_tf[] = "true\0false";
3682 #undef STR_TRUE
3683 #undef STR_FALSE
3684 #define STR_TRUE   (&str_tf[0])
3685 #define STR_FALSE  (&str_tf[5])
3686 
3687 const char* unpacker::get_option(const char* prop) {
3688   if (prop == null )  return null;
3689   if (strcmp(prop, UNPACK_DEFLATE_HINT) == 0) {
3690     return deflate_hint_or_zero == 0? null : STR_TF(deflate_hint_or_zero > 0);
3691 #ifdef HAVE_STRIP
3692   } else if (strcmp(prop, UNPACK_STRIP_COMPILE) == 0) {
3693     return STR_TF(strip_compile);
3694   } else if (strcmp(prop, UNPACK_STRIP_DEBUG) == 0) {
3695     return STR_TF(strip_debug);
3696   } else if (strcmp(prop, UNPACK_STRIP_JCOV) == 0) {
3697     return STR_TF(strip_jcov);
3698 #endif /*HAVE_STRIP*/
3699   } else if (strcmp(prop, UNPACK_REMOVE_PACKFILE) == 0) {
3700     return STR_TF(remove_packfile);
3701   } else if (strcmp(prop, DEBUG_VERBOSE) == 0) {
3702     return saveIntStr(verbose);
3703   } else if (strcmp(prop, UNPACK_MODIFICATION_TIME) == 0) {
3704     return (modification_time_or_zero == 0)? null:
3705       saveIntStr(modification_time_or_zero);
3706   } else if (strcmp(prop, UNPACK_LOG_FILE) == 0) {
3707     return log_file;
3708   } else {
3709     return NULL; // unknown option ignore
3710   }
3711 }
3712 
3713 bool unpacker::set_option(const char* prop, const char* value) {
3714   if (prop == NULL)  return false;
3715   if (strcmp(prop, UNPACK_DEFLATE_HINT) == 0) {
3716     deflate_hint_or_zero = ( (value == null || strcmp(value, "keep") == 0)
3717                                 ? 0: BOOL_TF(value) ? +1: -1);
3718 #ifdef HAVE_STRIP
3719   } else if (strcmp(prop, UNPACK_STRIP_COMPILE) == 0) {
3720     strip_compile = STR_TF(value);
3721   } else if (strcmp(prop, UNPACK_STRIP_DEBUG) == 0) {
3722     strip_debug = STR_TF(value);
3723   } else if (strcmp(prop, UNPACK_STRIP_JCOV) == 0) {
3724     strip_jcov = STR_TF(value);
3725 #endif /*HAVE_STRIP*/
3726   } else if (strcmp(prop, UNPACK_REMOVE_PACKFILE) == 0) {
3727     remove_packfile = STR_TF(value);
3728   } else if (strcmp(prop, DEBUG_VERBOSE) == 0) {
3729     verbose = (value == null)? 0: atoi(value);
3730   } else if (strcmp(prop, DEBUG_VERBOSE ".bands") == 0) {
3731 #ifndef PRODUCT
3732     verbose_bands = (value == null)? 0: atoi(value);
3733 #endif
3734   } else if (strcmp(prop, UNPACK_MODIFICATION_TIME) == 0) {
3735     if (value == null || (strcmp(value, "keep") == 0)) {
3736       modification_time_or_zero = 0;
3737     } else if (strcmp(value, "now") == 0) {
3738       time_t now;
3739       time(&now);
3740       modification_time_or_zero = (int) now;
3741     } else {
3742       modification_time_or_zero = atoi(value);
3743       if (modification_time_or_zero == 0)
3744         modification_time_or_zero = 1;  // make non-zero
3745     }
3746   } else if (strcmp(prop, UNPACK_LOG_FILE) == 0) {
3747     log_file = (value == null)? value: saveStr(value);
3748   } else {
3749     return false; // unknown option ignore
3750   }
3751   return true;
3752 }
3753 
3754 // Deallocate all internal storage and reset to a clean state.
3755 // Do not disturb any input or output connections, including
3756 // infileptr, infileno, inbytes, read_input_fn, jarout, or errstrm.
3757 // Do not reset any unpack options.
3758 void unpacker::reset() {
3759   bytes_read_before_reset      += bytes_read;
3760   bytes_written_before_reset   += bytes_written;
3761   files_written_before_reset   += files_written;
3762   classes_written_before_reset += classes_written;
3763   segments_read_before_reset   += 1;
3764   if (verbose >= 2) {
3765     fprintf(errstrm,
3766             "After segment %d, "
3767             LONG_LONG_FORMAT " bytes read and "
3768             LONG_LONG_FORMAT " bytes written.\n",
3769             segments_read_before_reset-1,
3770             bytes_read_before_reset, bytes_written_before_reset);
3771     fprintf(errstrm,
3772             "After segment %d, %d files (of which %d are classes) written to output.\n",
3773             segments_read_before_reset-1,
3774             files_written_before_reset, classes_written_before_reset);
3775     if (archive_next_count != 0) {
3776       fprintf(errstrm,
3777               "After segment %d, %d segment%s remaining (estimated).\n",
3778               segments_read_before_reset-1,
3779               archive_next_count, archive_next_count==1?"":"s");
3780     }
3781   }
3782 
3783   unpacker save_u = (*this);  // save bytewise image
3784   infileptr = null;  // make asserts happy
3785   jniobj = null;  // make asserts happy
3786   jarout = null;  // do not close the output jar
3787   gzin = null;  // do not close the input gzip stream
3788   bytes esn;
3789   if (errstrm_name != null) {
3790     esn.saveFrom(errstrm_name);
3791   } else {
3792     esn.set(null, 0);
3793   }
3794   this->free();
3795   mtrace('s', 0, 0);  // note the boundary between segments
3796   this->init(read_input_fn);
3797 
3798   // restore selected interface state:
3799 #define SAVE(x) this->x = save_u.x
3800   SAVE(jniobj);
3801   SAVE(jnienv);
3802   SAVE(infileptr);  // buffered
3803   SAVE(infileno);   // unbuffered
3804   SAVE(inbytes);    // direct
3805   SAVE(jarout);
3806   SAVE(gzin);
3807   //SAVE(read_input_fn);
3808   SAVE(errstrm);
3809   SAVE(verbose);  // verbose level, 0 means no output
3810   SAVE(strip_compile);
3811   SAVE(strip_debug);
3812   SAVE(strip_jcov);
3813   SAVE(remove_packfile);
3814   SAVE(deflate_hint_or_zero);  // ==0 means not set, otherwise -1 or 1
3815   SAVE(modification_time_or_zero);
3816   SAVE(bytes_read_before_reset);
3817   SAVE(bytes_written_before_reset);
3818   SAVE(files_written_before_reset);
3819   SAVE(classes_written_before_reset);
3820   SAVE(segments_read_before_reset);
3821 #undef SAVE
3822   if (esn.len > 0) {
3823     errstrm_name = saveStr(esn.strval());
3824     esn.free();
3825   }
3826   log_file = errstrm_name;
3827   // Note:  If we use strip_names, watch out:  They get nuked here.
3828 }
3829 
3830 void unpacker::init(read_input_fn_t input_fn) {
3831   int i;
3832   NOT_PRODUCT(debug_u = this);
3833   BYTES_OF(*this).clear();
3834 #ifndef PRODUCT
3835   free();  // just to make sure freeing is idempotent
3836 #endif
3837   this->u = this;    // self-reference for U_NEW macro
3838   errstrm = stdout;  // default error-output
3839   log_file = LOGFILE_STDOUT;
3840   read_input_fn = input_fn;
3841   all_bands = band::makeBands(this);
3842   // Make a default jar buffer; caller may safely overwrite it.
3843   jarout = U_NEW(jar, 1);
3844   jarout->init(this);
3845   for (i = 0; i < ATTR_CONTEXT_LIMIT; i++)
3846     attr_defs[i].u = u;  // set up outer ptr
3847 }
3848 
3849 const char* unpacker::get_abort_message() {
3850    return abort_message;
3851 }
3852 
3853 void unpacker::dump_options() {
3854   static const char* opts[] = {
3855     UNPACK_LOG_FILE,
3856     UNPACK_DEFLATE_HINT,
3857 #ifdef HAVE_STRIP
3858     UNPACK_STRIP_COMPILE,
3859     UNPACK_STRIP_DEBUG,
3860     UNPACK_STRIP_JCOV,
3861 #endif /*HAVE_STRIP*/
3862     UNPACK_REMOVE_PACKFILE,
3863     DEBUG_VERBOSE,
3864     UNPACK_MODIFICATION_TIME,
3865     null
3866   };
3867   for (int i = 0; opts[i] != null; i++) {
3868     const char* str = get_option(opts[i]);
3869     if (str == null) {
3870       if (verbose == 0)  continue;
3871       str = "(not set)";
3872     }
3873     fprintf(errstrm, "%s=%s\n", opts[i], str);
3874   }
3875 }
3876 
3877 
3878 // Usage: unpack a byte buffer
3879 // packptr is a reference to byte buffer containing a
3880 // packed file and len is the length of the buffer.
3881 // If null, the callback is used to fill an internal buffer.
3882 void unpacker::start(void* packptr, size_t len) {
3883   NOT_PRODUCT(debug_u = this);
3884   if (packptr != null && len != 0) {
3885     inbytes.set((byte*) packptr, len);
3886   }
3887   read_bands();
3888 }
3889 
3890 void unpacker::check_options() {
3891   const char* strue  = "true";
3892   const char* sfalse = "false";
3893   if (deflate_hint_or_zero != 0) {
3894     bool force_deflate_hint = (deflate_hint_or_zero > 0);
3895     if (force_deflate_hint)
3896       default_file_options |= FO_DEFLATE_HINT;
3897     else
3898       default_file_options &= ~FO_DEFLATE_HINT;
3899     // Turn off per-file deflate hint by force.
3900     suppress_file_options |= FO_DEFLATE_HINT;
3901   }
3902   if (modification_time_or_zero != 0) {
3903     default_file_modtime = modification_time_or_zero;
3904     // Turn off per-file modtime by force.
3905     archive_options &= ~AO_HAVE_FILE_MODTIME;
3906   }
3907   // %%% strip_compile, etc...
3908 }
3909 
3910 // classfile writing
3911 
3912 void unpacker::reset_cur_classfile() {
3913   // set defaults
3914   cur_class_minver = default_class_minver;
3915   cur_class_majver = default_class_majver;
3916 
3917   // reset constant pool state
3918   cp.resetOutputIndexes();
3919 
3920   // reset fixups
3921   class_fixup_type.empty();
3922   class_fixup_offset.empty();
3923   class_fixup_ref.empty();
3924   requested_ics.empty();
3925   cp.requested_bsms.empty();
3926 }
3927 
3928 cpindex* cpool::getKQIndex() {
3929   char ch = '?';
3930   if (u->cur_descr != null) {
3931     entry* type = u->cur_descr->descrType();
3932     ch = type->value.b.ptr[0];
3933   }
3934   byte tag = CONSTANT_Integer;
3935   switch (ch) {
3936   case 'L': tag = CONSTANT_String;   break;
3937   case 'I': tag = CONSTANT_Integer;  break;
3938   case 'J': tag = CONSTANT_Long;     break;
3939   case 'F': tag = CONSTANT_Float;    break;
3940   case 'D': tag = CONSTANT_Double;   break;
3941   case 'B': case 'S': case 'C':
3942   case 'Z': tag = CONSTANT_Integer;  break;
3943   default:  abort("bad KQ reference"); break;
3944   }
3945   return getIndex(tag);
3946 }
3947 
3948 uint unpacker::to_bci(uint bii) {
3949   uint  len =         bcimap.length();
3950   uint* map = (uint*) bcimap.base();
3951   assert(len > 0);  // must be initialized before using to_bci
3952   if (bii < len)
3953     return map[bii];
3954   // Else it's a fractional or out-of-range BCI.
3955   uint key = bii-len;
3956   for (int i = len; ; i--) {
3957     if (map[i-1]-(i-1) <= key)
3958       break;
3959     else
3960       --bii;
3961   }
3962   return bii;
3963 }
3964 
3965 void unpacker::put_stackmap_type() {
3966   int tag = code_StackMapTable_T.getByte();
3967   putu1(tag);
3968   switch (tag) {
3969   case 7: // (7) [RCH]
3970     putref(code_StackMapTable_RC.getRef());
3971     break;
3972   case 8: // (8) [PH]
3973     putu2(to_bci(code_StackMapTable_P.getInt()));
3974     break;
3975   }
3976 }
3977 
3978 // Functions for writing code.
3979 
3980 maybe_inline
3981 void unpacker::put_label(int curIP, int size) {
3982   code_fixup_type.addByte(size);
3983   code_fixup_offset.add((int)put_empty(size));
3984   code_fixup_source.add(curIP);
3985 }
3986 
3987 inline  // called exactly once => inline
3988 void unpacker::write_bc_ops() {
3989   bcimap.empty();
3990   code_fixup_type.empty();
3991   code_fixup_offset.empty();
3992   code_fixup_source.empty();
3993 
3994   band* bc_which;
3995 
3996   byte*  opptr = bc_codes.curRP();
3997   // No need for oplimit, since the codes are pre-counted.
3998 
3999   size_t codeBase = wpoffset();
4000 
4001   bool   isAload;  // copy-out result
4002   int    origBC;
4003 
4004   entry* thisClass  = cur_class;
4005   entry* superClass = cur_super;
4006   entry* newClass   = null;  // class of last _new opcode
4007 
4008   // overwrite any prior index on these bands; it changes w/ current class:
4009   bc_thisfield.setIndex(    cp.getFieldIndex( thisClass));
4010   bc_thismethod.setIndex(   cp.getMethodIndex(thisClass));
4011   if (superClass != null) {
4012     bc_superfield.setIndex( cp.getFieldIndex( superClass));
4013     bc_supermethod.setIndex(cp.getMethodIndex(superClass));
4014   } else {
4015     NOT_PRODUCT(bc_superfield.setIndex(null));
4016     NOT_PRODUCT(bc_supermethod.setIndex(null));
4017   }
4018 
4019   for (int curIP = 0; ; curIP++) {
4020     int curPC = (int)(wpoffset() - codeBase);
4021     bcimap.add(curPC);
4022     ensure_put_space(10);  // covers most instrs w/o further bounds check
4023     int bc = *opptr++ & 0xFF;
4024 
4025     putu1_fast(bc);
4026     // Note:  See '--wp' below for pseudo-bytecodes like bc_end_marker.
4027 
4028     bool isWide = false;
4029     if (bc == bc_wide) {
4030       bc = *opptr++ & 0xFF;
4031       putu1_fast(bc);
4032       isWide = true;
4033     }
4034     switch (bc) {
4035     case bc_end_marker:
4036       --wp;  // not really part of the code
4037       assert(opptr <= bc_codes.maxRP());
4038       bc_codes.curRP() = opptr;  // advance over this in bc_codes
4039       goto doneScanningMethod;
4040     case bc_tableswitch: // apc:  (df, lo, hi, (hi-lo+1)*(label))
4041     case bc_lookupswitch: // apc:  (df, nc, nc*(case, label))
4042       {
4043         int caseCount = bc_case_count.getInt();
4044         while (((wpoffset() - codeBase) % 4) != 0)  putu1_fast(0);
4045         ensure_put_space(30 + caseCount*8);
4046         put_label(curIP, 4);  //int df = bc_label.getInt();
4047         if (bc == bc_tableswitch) {
4048           int lo = bc_case_value.getInt();
4049           int hi = lo + caseCount-1;
4050           putu4(lo);
4051           putu4(hi);
4052           for (int j = 0; j < caseCount; j++) {
4053             put_label(curIP, 4); //int lVal = bc_label.getInt();
4054             //int cVal = lo + j;
4055           }
4056         } else {
4057           putu4(caseCount);
4058           for (int j = 0; j < caseCount; j++) {
4059             int cVal = bc_case_value.getInt();
4060             putu4(cVal);
4061             put_label(curIP, 4); //int lVal = bc_label.getInt();
4062           }
4063         }
4064         assert((int)to_bci(curIP) == curPC);
4065         continue;
4066       }
4067     case bc_iinc:
4068       {
4069         int local = bc_local.getInt();
4070         int delta = (isWide ? bc_short : bc_byte).getInt();
4071         if (isWide) {
4072           putu2(local);
4073           putu2(delta);
4074         } else {
4075           putu1_fast(local);
4076           putu1_fast(delta);
4077         }
4078         continue;
4079       }
4080     case bc_sipush:
4081       {
4082         int val = bc_short.getInt();
4083         putu2(val);
4084         continue;
4085       }
4086     case bc_bipush:
4087     case bc_newarray:
4088       {
4089         int val = bc_byte.getByte();
4090         putu1_fast(val);
4091         continue;
4092       }
4093     case bc_ref_escape:
4094       {
4095         // Note that insnMap has one entry for this.
4096         --wp;  // not really part of the code
4097         int size = bc_escrefsize.getInt();
4098         entry* ref = bc_escref.getRefN();
4099         CHECK;
4100         switch (size) {
4101         case 1: putu1ref(ref); break;
4102         case 2: putref(ref);   break;
4103         default: assert(false);
4104         }
4105         continue;
4106       }
4107     case bc_byte_escape:
4108       {
4109         // Note that insnMap has one entry for all these bytes.
4110         --wp;  // not really part of the code
4111         int size = bc_escsize.getInt();
4112         ensure_put_space(size);
4113         for (int j = 0; j < size; j++)
4114           putu1_fast(bc_escbyte.getByte());
4115         continue;
4116       }
4117     default:
4118       if (is_invoke_init_op(bc)) {
4119         origBC = bc_invokespecial;
4120         entry* classRef;
4121         switch (bc - _invokeinit_op) {
4122         case _invokeinit_self_option:   classRef = thisClass;  break;
4123         case _invokeinit_super_option:  classRef = superClass; break;
4124         default: assert(bc == _invokeinit_op+_invokeinit_new_option);
4125         case _invokeinit_new_option:    classRef = newClass;   break;
4126         }
4127         wp[-1] = origBC;  // overwrite with origBC
4128         int coding = bc_initref.getInt();
4129         // Find the nth overloading of <init> in classRef.
4130         entry*   ref = null;
4131         cpindex* ix = (classRef == null)? null: cp.getMethodIndex(classRef);
4132         for (int j = 0, which_init = 0; ; j++) {
4133           ref = (ix == null)? null: ix->get(j);
4134           if (ref == null)  break;  // oops, bad input
4135           assert(ref->tag == CONSTANT_Methodref);
4136           if (ref->memberDescr()->descrName() == cp.sym[cpool::s_lt_init_gt]) {
4137             if (which_init++ == coding)  break;
4138           }
4139         }
4140         putref(ref);
4141         continue;
4142       }
4143       bc_which = ref_band_for_self_op(bc, isAload, origBC);
4144       if (bc_which != null) {
4145         if (!isAload) {
4146           wp[-1] = origBC;  // overwrite with origBC
4147         } else {
4148           wp[-1] = bc_aload_0;  // overwrite with _aload_0
4149           // Note: insnMap keeps the _aload_0 separate.
4150           bcimap.add(++curPC);
4151           ++curIP;
4152           putu1_fast(origBC);
4153         }
4154         entry* ref = bc_which->getRef();
4155         CHECK;
4156         putref(ref);
4157         continue;
4158       }
4159       if (is_branch_op(bc)) {
4160         //int lVal = bc_label.getInt();
4161         if (bc < bc_goto_w) {
4162           put_label(curIP, 2);  //putu2(lVal & 0xFFFF);
4163         } else {
4164           assert(bc <= bc_jsr_w);
4165           put_label(curIP, 4);  //putu4(lVal);
4166         }
4167         assert((int)to_bci(curIP) == curPC);
4168         continue;
4169       }
4170       bc_which = ref_band_for_op(bc);
4171       if (bc_which != null) {
4172         entry* ref = bc_which->getRefCommon(bc_which->ix, bc_which->nullOK);
4173         CHECK;
4174         if (ref == null && bc_which == &bc_classref) {
4175           // Shorthand for class self-references.
4176           ref = thisClass;
4177         }
4178         origBC = bc;
4179         switch (bc) {
4180         case bc_ildc:
4181         case bc_cldc:
4182         case bc_fldc:
4183         case bc_sldc:
4184         case bc_qldc:
4185           origBC = bc_ldc;
4186           break;
4187         case bc_ildc_w:
4188         case bc_cldc_w:
4189         case bc_fldc_w:
4190         case bc_sldc_w:
4191         case bc_qldc_w:
4192           origBC = bc_ldc_w;
4193           break;
4194         case bc_lldc2_w:
4195         case bc_dldc2_w:
4196           origBC = bc_ldc2_w;
4197           break;
4198         case bc_new:
4199           newClass = ref;
4200           break;
4201         }
4202         wp[-1] = origBC;  // overwrite with origBC
4203         if (origBC == bc_ldc) {
4204           putu1ref(ref);
4205         } else {
4206           putref(ref);
4207         }
4208         if (origBC == bc_multianewarray) {
4209           // Copy the trailing byte also.
4210           int val = bc_byte.getByte();
4211           putu1_fast(val);
4212         } else if (origBC == bc_invokeinterface) {
4213           int argSize = ref->memberDescr()->descrType()->typeSize();
4214           putu1_fast(1 + argSize);
4215           putu1_fast(0);
4216         } else if (origBC == bc_invokedynamic) {
4217           // pad the next two byte
4218           putu1_fast(0);
4219           putu1_fast(0);
4220         }
4221         continue;
4222       }
4223       if (is_local_slot_op(bc)) {
4224         int local = bc_local.getInt();
4225         if (isWide) {
4226           putu2(local);
4227           if (bc == bc_iinc) {
4228             int iVal = bc_short.getInt();
4229             putu2(iVal);
4230           }
4231         } else {
4232           putu1_fast(local);
4233           if (bc == bc_iinc) {
4234             int iVal = bc_byte.getByte();
4235             putu1_fast(iVal);
4236           }
4237         }
4238         continue;
4239       }
4240       // Random bytecode.  Just copy it.
4241       assert(bc < bc_bytecode_limit);
4242     }
4243   }
4244  doneScanningMethod:{}
4245   //bcimap.add(curPC);  // PC limit is already also in map, from bc_end_marker
4246 
4247   // Armed with a bcimap, we can now fix up all the labels.
4248   for (int i = 0; i < (int)code_fixup_type.size(); i++) {
4249     int   type   = code_fixup_type.getByte(i);
4250     byte* bp     = wp_at(code_fixup_offset.get(i));
4251     int   curIP  = code_fixup_source.get(i);
4252     int   destIP = curIP + bc_label.getInt();
4253     int   span   = to_bci(destIP) - to_bci(curIP);
4254     switch (type) {
4255     case 2: putu2_at(bp, (ushort)span); break;
4256     case 4: putu4_at(bp,         span); break;
4257     default: assert(false);
4258     }
4259   }
4260 }
4261 
4262 inline  // called exactly once => inline
4263 void unpacker::write_code() {
4264   int j;
4265 
4266   int max_stack, max_locals, handler_count, cflags;
4267   get_code_header(max_stack, max_locals, handler_count, cflags);
4268 
4269   if (max_stack < 0)      max_stack = code_max_stack.getInt();
4270   if (max_locals < 0)     max_locals = code_max_na_locals.getInt();
4271   if (handler_count < 0)  handler_count = code_handler_count.getInt();
4272 
4273   int siglen = cur_descr->descrType()->typeSize();
4274   CHECK;
4275   if ((cur_descr_flags & ACC_STATIC) == 0)  siglen++;
4276   max_locals += siglen;
4277 
4278   putu2(max_stack);
4279   putu2(max_locals);
4280   size_t bcbase = put_empty(4);
4281 
4282   // Write the bytecodes themselves.
4283   write_bc_ops();
4284   CHECK;
4285 
4286   byte* bcbasewp = wp_at(bcbase);
4287   putu4_at(bcbasewp, (int)(wp - (bcbasewp+4)));  // size of code attr
4288 
4289   putu2(handler_count);
4290   for (j = 0; j < handler_count; j++) {
4291     int bii = code_handler_start_P.getInt();
4292     putu2(to_bci(bii));
4293     bii    += code_handler_end_PO.getInt();
4294     putu2(to_bci(bii));
4295     bii    += code_handler_catch_PO.getInt();
4296     putu2(to_bci(bii));
4297     putref(code_handler_class_RCN.getRefN());
4298     CHECK;
4299   }
4300 
4301   julong indexBits = cflags;
4302   if (cflags < 0) {
4303     bool haveLongFlags = attr_defs[ATTR_CONTEXT_CODE].haveLongFlags();
4304     indexBits = code_flags_hi.getLong(code_flags_lo, haveLongFlags);
4305   }
4306   write_attrs(ATTR_CONTEXT_CODE, indexBits);
4307 }
4308 
4309 int unpacker::write_attrs(int attrc, julong indexBits) {
4310   CHECK_0;
4311   if (indexBits == 0) {
4312     // Quick short-circuit.
4313     putu2(0);
4314     return 0;
4315   }
4316 
4317   attr_definitions& ad = attr_defs[attrc];
4318 
4319   int i, j, j2, idx, count;
4320 
4321   int oiCount = 0;
4322   if (ad.isPredefined(X_ATTR_OVERFLOW)
4323       && (indexBits & ((julong)1<<X_ATTR_OVERFLOW)) != 0) {
4324     indexBits -= ((julong)1<<X_ATTR_OVERFLOW);
4325     oiCount = ad.xxx_attr_count().getInt();
4326   }
4327 
4328   int bitIndexes[X_ATTR_LIMIT_FLAGS_HI];
4329   int biCount = 0;
4330 
4331   // Fill bitIndexes with index bits, in order.
4332   for (idx = 0; indexBits != 0; idx++, indexBits >>= 1) {
4333     if ((indexBits & 1) != 0)
4334       bitIndexes[biCount++] = idx;
4335   }
4336   assert(biCount <= (int)lengthof(bitIndexes));
4337 
4338   // Write a provisional attribute count, perhaps to be corrected later.
4339   int naOffset = (int)wpoffset();
4340   int na0 = biCount + oiCount;
4341   putu2(na0);
4342 
4343   int na = 0;
4344   for (i = 0; i < na0; i++) {
4345     if (i < biCount)
4346       idx = bitIndexes[i];
4347     else
4348       idx = ad.xxx_attr_indexes().getInt();
4349     assert(ad.isIndex(idx));
4350     entry* aname = null;
4351     entry* ref;  // scratch
4352     size_t abase = put_empty(2+4);
4353     CHECK_0;
4354     if (idx < (int)ad.flag_limit && ad.isPredefined(idx)) {
4355       // Switch on the attrc and idx simultaneously.
4356       switch (ADH_BYTE(attrc, idx)) {
4357 
4358       case ADH_BYTE(ATTR_CONTEXT_CLASS,  X_ATTR_OVERFLOW):
4359       case ADH_BYTE(ATTR_CONTEXT_FIELD,  X_ATTR_OVERFLOW):
4360       case ADH_BYTE(ATTR_CONTEXT_METHOD, X_ATTR_OVERFLOW):
4361       case ADH_BYTE(ATTR_CONTEXT_CODE,   X_ATTR_OVERFLOW):
4362         // no attribute at all, so back up on this one
4363         wp = wp_at(abase);
4364         continue;
4365 
4366       case ADH_BYTE(ATTR_CONTEXT_CLASS, CLASS_ATTR_ClassFile_version):
4367         cur_class_minver = class_ClassFile_version_minor_H.getInt();
4368         cur_class_majver = class_ClassFile_version_major_H.getInt();
4369         // back up; not a real attribute
4370         wp = wp_at(abase);
4371         continue;
4372 
4373       case ADH_BYTE(ATTR_CONTEXT_CLASS, CLASS_ATTR_InnerClasses):
4374         // note the existence of this attr, but save for later
4375         if (cur_class_has_local_ics)
4376           abort("too many InnerClasses attrs");
4377         cur_class_has_local_ics = true;
4378         wp = wp_at(abase);
4379         continue;
4380 
4381       case ADH_BYTE(ATTR_CONTEXT_CLASS, CLASS_ATTR_SourceFile):
4382         aname = cp.sym[cpool::s_SourceFile];
4383         ref = class_SourceFile_RUN.getRefN();
4384         CHECK_0;
4385         if (ref == null) {
4386           bytes& n = cur_class->ref(0)->value.b;
4387           // parse n = (<pkg>/)*<outer>?($<id>)*
4388           int pkglen = lastIndexOf(SLASH_MIN,  SLASH_MAX,  n, (int)n.len)+1;
4389           bytes prefix = n.slice(pkglen, n.len);
4390           for (;;) {
4391             // Work backwards, finding all '$', '#', etc.
4392             int dollar = lastIndexOf(DOLLAR_MIN, DOLLAR_MAX, prefix, (int)prefix.len);
4393             if (dollar < 0)  break;
4394             prefix = prefix.slice(0, dollar);
4395           }
4396           const char* suffix = ".java";
4397           int len = (int)(prefix.len + strlen(suffix));
4398           bytes name; name.set(T_NEW(byte, add_size(len, 1)), len);
4399           name.strcat(prefix).strcat(suffix);
4400           ref = cp.ensureUtf8(name);
4401         }
4402         putref(ref);
4403         break;
4404 
4405       case ADH_BYTE(ATTR_CONTEXT_CLASS, CLASS_ATTR_EnclosingMethod):
4406         aname = cp.sym[cpool::s_EnclosingMethod];
4407         putref(class_EnclosingMethod_RC.getRefN());
4408         putref(class_EnclosingMethod_RDN.getRefN());
4409         break;
4410 
4411       case ADH_BYTE(ATTR_CONTEXT_FIELD, FIELD_ATTR_ConstantValue):
4412         aname = cp.sym[cpool::s_ConstantValue];
4413         putref(field_ConstantValue_KQ.getRefUsing(cp.getKQIndex()));
4414         break;
4415 
4416       case ADH_BYTE(ATTR_CONTEXT_METHOD, METHOD_ATTR_Code):
4417         aname = cp.sym[cpool::s_Code];
4418         write_code();
4419         break;
4420 
4421       case ADH_BYTE(ATTR_CONTEXT_METHOD, METHOD_ATTR_Exceptions):
4422         aname = cp.sym[cpool::s_Exceptions];
4423         putu2(count = method_Exceptions_N.getInt());
4424         for (j = 0; j < count; j++) {
4425           putref(method_Exceptions_RC.getRefN());
4426         }
4427         break;
4428 
4429       case ADH_BYTE(ATTR_CONTEXT_METHOD, METHOD_ATTR_MethodParameters):
4430         aname = cp.sym[cpool::s_MethodParameters];
4431         putu1(count = method_MethodParameters_NB.getByte());
4432         for (j = 0; j < count; j++) {
4433           putref(method_MethodParameters_name_RUN.getRefN());
4434           putu2(method_MethodParameters_flag_FH.getInt());
4435         }
4436         break;
4437 
4438       case ADH_BYTE(ATTR_CONTEXT_CODE, CODE_ATTR_StackMapTable):
4439         aname = cp.sym[cpool::s_StackMapTable];
4440         // (keep this code aligned with its brother in unpacker::read_attrs)
4441         putu2(count = code_StackMapTable_N.getInt());
4442         for (j = 0; j < count; j++) {
4443           int tag = code_StackMapTable_frame_T.getByte();
4444           putu1(tag);
4445           if (tag <= 127) {
4446             // (64-127)  [(2)]
4447             if (tag >= 64)  put_stackmap_type();
4448           } else if (tag <= 251) {
4449             // (247)     [(1)(2)]
4450             // (248-251) [(1)]
4451             if (tag >= 247)  putu2(code_StackMapTable_offset.getInt());
4452             if (tag == 247)  put_stackmap_type();
4453           } else if (tag <= 254) {
4454             // (252)     [(1)(2)]
4455             // (253)     [(1)(2)(2)]
4456             // (254)     [(1)(2)(2)(2)]
4457             putu2(code_StackMapTable_offset.getInt());
4458             for (int k = (tag - 251); k > 0; k--) {
4459               put_stackmap_type();
4460             }
4461           } else {
4462             // (255)     [(1)NH[(2)]NH[(2)]]
4463             putu2(code_StackMapTable_offset.getInt());
4464             putu2(j2 = code_StackMapTable_local_N.getInt());
4465             while (j2-- > 0)  put_stackmap_type();
4466             putu2(j2 = code_StackMapTable_stack_N.getInt());
4467             while (j2-- > 0)  put_stackmap_type();
4468           }
4469         }
4470         break;
4471 
4472       case ADH_BYTE(ATTR_CONTEXT_CODE, CODE_ATTR_LineNumberTable):
4473         aname = cp.sym[cpool::s_LineNumberTable];
4474         putu2(count = code_LineNumberTable_N.getInt());
4475         for (j = 0; j < count; j++) {
4476           putu2(to_bci(code_LineNumberTable_bci_P.getInt()));
4477           putu2(code_LineNumberTable_line.getInt());
4478         }
4479         break;
4480 
4481       case ADH_BYTE(ATTR_CONTEXT_CODE, CODE_ATTR_LocalVariableTable):
4482         aname = cp.sym[cpool::s_LocalVariableTable];
4483         putu2(count = code_LocalVariableTable_N.getInt());
4484         for (j = 0; j < count; j++) {
4485           int bii = code_LocalVariableTable_bci_P.getInt();
4486           int bci = to_bci(bii);
4487           putu2(bci);
4488           bii    += code_LocalVariableTable_span_O.getInt();
4489           putu2(to_bci(bii) - bci);
4490           putref(code_LocalVariableTable_name_RU.getRefN());
4491           putref(code_LocalVariableTable_type_RS.getRefN());
4492           putu2(code_LocalVariableTable_slot.getInt());
4493         }
4494         break;
4495 
4496       case ADH_BYTE(ATTR_CONTEXT_CODE, CODE_ATTR_LocalVariableTypeTable):
4497         aname = cp.sym[cpool::s_LocalVariableTypeTable];
4498         putu2(count = code_LocalVariableTypeTable_N.getInt());
4499         for (j = 0; j < count; j++) {
4500           int bii = code_LocalVariableTypeTable_bci_P.getInt();
4501           int bci = to_bci(bii);
4502           putu2(bci);
4503           bii    += code_LocalVariableTypeTable_span_O.getInt();
4504           putu2(to_bci(bii) - bci);
4505           putref(code_LocalVariableTypeTable_name_RU.getRefN());
4506           putref(code_LocalVariableTypeTable_type_RS.getRefN());
4507           putu2(code_LocalVariableTypeTable_slot.getInt());
4508         }
4509         break;
4510 
4511       case ADH_BYTE(ATTR_CONTEXT_CLASS, X_ATTR_Signature):
4512         aname = cp.sym[cpool::s_Signature];
4513         putref(class_Signature_RS.getRefN());
4514         break;
4515 
4516       case ADH_BYTE(ATTR_CONTEXT_FIELD, X_ATTR_Signature):
4517         aname = cp.sym[cpool::s_Signature];
4518         putref(field_Signature_RS.getRefN());
4519         break;
4520 
4521       case ADH_BYTE(ATTR_CONTEXT_METHOD, X_ATTR_Signature):
4522         aname = cp.sym[cpool::s_Signature];
4523         putref(method_Signature_RS.getRefN());
4524         break;
4525 
4526       case ADH_BYTE(ATTR_CONTEXT_CLASS,  X_ATTR_Deprecated):
4527       case ADH_BYTE(ATTR_CONTEXT_FIELD,  X_ATTR_Deprecated):
4528       case ADH_BYTE(ATTR_CONTEXT_METHOD, X_ATTR_Deprecated):
4529         aname = cp.sym[cpool::s_Deprecated];
4530         // no data
4531         break;
4532       }
4533     }
4534 
4535     if (aname == null) {
4536       // Unparse a compressor-defined attribute.
4537       layout_definition* lo = ad.getLayout(idx);
4538       if (lo == null) {
4539         abort("bad layout index");
4540         break;
4541       }
4542       assert((int)lo->idx == idx);
4543       aname = lo->nameEntry;
4544       if (aname == null) {
4545         bytes nameb; nameb.set(lo->name);
4546         aname = cp.ensureUtf8(nameb);
4547         // Cache the name entry for next time.
4548         lo->nameEntry = aname;
4549       }
4550       // Execute all the layout elements.
4551       band** bands = lo->bands();
4552       if (lo->hasCallables()) {
4553         band& cble = *bands[0];
4554         assert(cble.le_kind == EK_CBLE);
4555         bands = cble.le_body;
4556       }
4557       putlayout(bands);
4558     }
4559 
4560     if (aname == null)
4561       abort("bad attribute index");
4562     CHECK_0;
4563 
4564     byte* wp1 = wp;
4565     wp = wp_at(abase);
4566 
4567     // DTRT if this attr is on the strip-list.
4568     // (Note that we emptied the data out of the band first.)
4569     if (ad.strip_names.contains(aname)) {
4570       continue;
4571     }
4572 
4573     // patch the name and length
4574     putref(aname);
4575     putu4((int)(wp1 - (wp+4)));  // put the attr size
4576     wp = wp1;
4577     na++;  // count the attrs actually written
4578   }
4579 
4580   if (na != na0)
4581     // Refresh changed count.
4582     putu2_at(wp_at(naOffset), na);
4583   return na;
4584 }
4585 
4586 void unpacker::write_members(int num, int attrc) {
4587   CHECK;
4588   attr_definitions& ad = attr_defs[attrc];
4589   band& member_flags_hi = ad.xxx_flags_hi();
4590   band& member_flags_lo = ad.xxx_flags_lo();
4591   band& member_descr = (&member_flags_hi)[e_field_descr-e_field_flags_hi];
4592   assert(endsWith(member_descr.name, "_descr"));
4593   assert(endsWith(member_flags_lo.name, "_flags_lo"));
4594   assert(endsWith(member_flags_lo.name, "_flags_lo"));
4595   bool haveLongFlags = ad.haveLongFlags();
4596 
4597   putu2(num);
4598   julong indexMask = attr_defs[attrc].flagIndexMask();
4599   for (int i = 0; i < num; i++) {
4600     julong mflags = member_flags_hi.getLong(member_flags_lo, haveLongFlags);
4601     entry* mdescr = member_descr.getRef();
4602     cur_descr = mdescr;
4603     putu2(cur_descr_flags = (ushort)(mflags & ~indexMask));
4604     CHECK;
4605     putref(mdescr->descrName());
4606     putref(mdescr->descrType());
4607     write_attrs(attrc, (mflags & indexMask));
4608     CHECK;
4609   }
4610   cur_descr = null;
4611 }
4612 
4613 extern "C"
4614 int raw_address_cmp(const void* p1p, const void* p2p) {
4615   void* p1 = *(void**) p1p;
4616   void* p2 = *(void**) p2p;
4617   return (p1 > p2)? 1: (p1 < p2)? -1: 0;
4618 }
4619 
4620 /*
4621  * writes the InnerClass attributes and returns the updated attribute
4622  */
4623 int  unpacker::write_ics(int naOffset, int na) {
4624 #ifdef ASSERT
4625   for (int i = 0; i < ic_count; i++) {
4626     assert(!ics[i].requested);
4627   }
4628 #endif
4629   // First, consult the global table and the local constant pool,
4630   // and decide on the globally implied inner classes.
4631   // (Note that we read the cpool's outputIndex fields, but we
4632   // do not yet write them, since the local IC attribute might
4633   // reverse a global decision to declare an IC.)
4634   assert(requested_ics.length() == 0);  // must start out empty
4635   // Always include all members of the current class.
4636   for (inner_class* child = cp.getFirstChildIC(cur_class);
4637        child != null;
4638        child = cp.getNextChildIC(child)) {
4639     child->requested = true;
4640     requested_ics.add(child);
4641   }
4642   // And, for each inner class mentioned in the constant pool,
4643   // include it and all its outers.
4644   int    noes =           cp.outputEntries.length();
4645   entry** oes = (entry**) cp.outputEntries.base();
4646   for (int i = 0; i < noes; i++) {
4647     entry& e = *oes[i];
4648     if (e.tag != CONSTANT_Class)  continue;  // wrong sort
4649     for (inner_class* ic = cp.getIC(&e);
4650          ic != null;
4651          ic = cp.getIC(ic->outer)) {
4652       if (ic->requested)  break;  // already processed
4653       ic->requested = true;
4654       requested_ics.add(ic);
4655     }
4656   }
4657   int local_ics = requested_ics.length();
4658   // Second, consult a local attribute (if any) and adjust the global set.
4659   inner_class* extra_ics = null;
4660   int      num_extra_ics = 0;
4661   if (cur_class_has_local_ics) {
4662     // adjust the set of ICs by symmetric set difference w/ the locals
4663     num_extra_ics = class_InnerClasses_N.getInt();
4664     if (num_extra_ics == 0) {
4665       // Explicit zero count has an irregular meaning:  It deletes the attr.
4666       local_ics = 0;  // (short-circuit all tests of requested bits)
4667     } else {
4668       extra_ics = T_NEW(inner_class, num_extra_ics);
4669       // Note:  extra_ics will be freed up by next call to get_next_file().
4670     }
4671   }
4672   for (int i = 0; i < num_extra_ics; i++) {
4673     inner_class& extra_ic = extra_ics[i];
4674     extra_ic.inner = class_InnerClasses_RC.getRef();
4675     CHECK_0;
4676     // Find the corresponding equivalent global IC:
4677     inner_class* global_ic = cp.getIC(extra_ic.inner);
4678     int flags = class_InnerClasses_F.getInt();
4679     if (flags == 0) {
4680       // The extra IC is simply a copy of a global IC.
4681       if (global_ic == null) {
4682         abort("bad reference to inner class");
4683         break;
4684       }
4685       extra_ic = (*global_ic);  // fill in rest of fields
4686     } else {
4687       flags &= ~ACC_IC_LONG_FORM;  // clear high bit if set to get clean zero
4688       extra_ic.flags = flags;
4689       extra_ic.outer = class_InnerClasses_outer_RCN.getRefN();
4690       extra_ic.name  = class_InnerClasses_name_RUN.getRefN();
4691       // Detect if this is an exact copy of the global tuple.
4692       if (global_ic != null) {
4693         if (global_ic->flags != extra_ic.flags ||
4694             global_ic->outer != extra_ic.outer ||
4695             global_ic->name  != extra_ic.name) {
4696           global_ic = null;  // not really the same, so break the link
4697         }
4698       }
4699     }
4700     if (global_ic != null && global_ic->requested) {
4701       // This local repetition reverses the globally implied request.
4702       global_ic->requested = false;
4703       extra_ic.requested = false;
4704       local_ics -= 1;
4705     } else {
4706       // The global either does not exist, or is not yet requested.
4707       extra_ic.requested = true;
4708       local_ics += 1;
4709     }
4710   }
4711   // Finally, if there are any that survived, put them into an attribute.
4712   // (Note that a zero-count attribute is always deleted.)
4713   // The putref calls below will tell the constant pool to add any
4714   // necessary local CP references to support the InnerClasses attribute.
4715   // This step must be the last round of additions to the local CP.
4716   if (local_ics > 0) {
4717     // append the new attribute:
4718     putref(cp.sym[cpool::s_InnerClasses]);
4719     putu4(2 + 2*4*local_ics);
4720     putu2(local_ics);
4721     PTRLIST_QSORT(requested_ics, raw_address_cmp);
4722     int num_global_ics = requested_ics.length();
4723     for (int i = -num_global_ics; i < num_extra_ics; i++) {
4724       inner_class* ic;
4725       if (i < 0)
4726         ic = (inner_class*) requested_ics.get(num_global_ics+i);
4727       else
4728         ic = &extra_ics[i];
4729       if (ic->requested) {
4730         putref(ic->inner);
4731         putref(ic->outer);
4732         putref(ic->name);
4733         putu2(ic->flags);
4734         NOT_PRODUCT(local_ics--);
4735       }
4736     }
4737     assert(local_ics == 0);           // must balance
4738     putu2_at(wp_at(naOffset), ++na);  // increment class attr count
4739   }
4740 
4741   // Tidy up global 'requested' bits:
4742   for (int i = requested_ics.length(); --i >= 0; ) {
4743     inner_class* ic = (inner_class*) requested_ics.get(i);
4744     ic->requested = false;
4745   }
4746   requested_ics.empty();
4747   return na;
4748 }
4749 
4750 /*
4751  * Writes the BootstrapMethods attribute and returns the updated attribute count
4752  */
4753 int unpacker::write_bsms(int naOffset, int na) {
4754   cur_class_local_bsm_count = cp.requested_bsms.length();
4755   if (cur_class_local_bsm_count > 0) {
4756     int    noes =           cp.outputEntries.length();
4757     entry** oes = (entry**) cp.outputEntries.base();
4758     PTRLIST_QSORT(cp.requested_bsms, outputEntry_cmp);
4759     // append the BootstrapMethods attribute (after the InnerClasses attr):
4760     putref(cp.sym[cpool::s_BootstrapMethods]);
4761     // make a note of the offset, for lazy patching
4762     int sizeOffset = (int)wpoffset();
4763     putu4(-99);  // attr size will be patched
4764     putu2(cur_class_local_bsm_count);
4765     int written_bsms = 0;
4766     for (int i = 0 ; i < cur_class_local_bsm_count ; i++) {
4767       entry* e = (entry*)cp.requested_bsms.get(i);
4768       assert(e->outputIndex != REQUESTED_NONE);
4769       // output index is the index within the array
4770       e->outputIndex = i;
4771       putref(e->refs[0]);  // bsm
4772       putu2(e->nrefs-1);  // number of args after bsm
4773       for (int j = 1; j < e->nrefs; j++) {
4774         putref(e->refs[j]);
4775       }
4776       written_bsms += 1;
4777     }
4778     assert(written_bsms == cur_class_local_bsm_count);  // else insane
4779     byte* sizewp = wp_at(sizeOffset);
4780     putu4_at(sizewp, (int)(wp - (sizewp+4)));  // size of code attr
4781     putu2_at(wp_at(naOffset), ++na);  // increment class attr count
4782   }
4783   return na;
4784 }
4785 
4786 void unpacker::write_classfile_tail() {
4787 
4788   cur_classfile_tail.empty();
4789   set_output(&cur_classfile_tail);
4790 
4791   int i, num;
4792 
4793   attr_definitions& ad = attr_defs[ATTR_CONTEXT_CLASS];
4794 
4795   bool haveLongFlags = ad.haveLongFlags();
4796   julong kflags = class_flags_hi.getLong(class_flags_lo, haveLongFlags);
4797   julong indexMask = ad.flagIndexMask();
4798 
4799   cur_class = class_this.getRef();
4800   cur_super = class_super.getRef();
4801   CHECK;
4802 
4803   if (cur_super == cur_class)  cur_super = null;
4804   // special representation for java/lang/Object
4805 
4806   putu2((ushort)(kflags & ~indexMask));
4807   putref(cur_class);
4808   putref(cur_super);
4809 
4810   putu2(num = class_interface_count.getInt());
4811   for (i = 0; i < num; i++) {
4812     putref(class_interface.getRef());
4813   }
4814 
4815   write_members(class_field_count.getInt(),  ATTR_CONTEXT_FIELD);
4816   write_members(class_method_count.getInt(), ATTR_CONTEXT_METHOD);
4817   CHECK;
4818 
4819   cur_class_has_local_ics = false;  // may be set true by write_attrs
4820 
4821   int naOffset = (int)wpoffset();   // note the attr count location
4822   int na = write_attrs(ATTR_CONTEXT_CLASS, (kflags & indexMask));
4823   CHECK;
4824 
4825   na = write_bsms(naOffset, na);
4826   CHECK;
4827 
4828   // choose which inner classes (if any) pertain to k:
4829   na = write_ics(naOffset, na);
4830   CHECK;
4831 
4832   close_output();
4833   cp.computeOutputIndexes();
4834 
4835   // rewrite CP references in the tail
4836   int nextref = 0;
4837   for (i = 0; i < (int)class_fixup_type.size(); i++) {
4838     int    type = class_fixup_type.getByte(i);
4839     byte*  fixp = wp_at(class_fixup_offset.get(i));
4840     entry* e    = (entry*)class_fixup_ref.get(nextref++);
4841     int    idx  = e->getOutputIndex();
4842     switch (type) {
4843     case 1:  putu1_at(fixp, idx);  break;
4844     case 2:  putu2_at(fixp, idx);  break;
4845     default: assert(false);  // should not reach here
4846     }
4847   }
4848   CHECK;
4849 }
4850 
4851 void unpacker::write_classfile_head() {
4852   cur_classfile_head.empty();
4853   set_output(&cur_classfile_head);
4854 
4855   putu4(JAVA_MAGIC);
4856   putu2(cur_class_minver);
4857   putu2(cur_class_majver);
4858   putu2(cp.outputIndexLimit);
4859 
4860   int checkIndex = 1;
4861   int    noes =           cp.outputEntries.length();
4862   entry** oes = (entry**) cp.outputEntries.base();
4863   for (int i = 0; i < noes; i++) {
4864     entry& e = *oes[i];
4865     assert(e.getOutputIndex() == checkIndex++);
4866     byte tag = e.tag;
4867     assert(tag != CONSTANT_Signature);
4868     putu1(tag);
4869     switch (tag) {
4870     case CONSTANT_Utf8:
4871       putu2((int)e.value.b.len);
4872       put_bytes(e.value.b);
4873       break;
4874     case CONSTANT_Integer:
4875     case CONSTANT_Float:
4876       putu4(e.value.i);
4877       break;
4878     case CONSTANT_Long:
4879     case CONSTANT_Double:
4880       putu8(e.value.l);
4881       assert(checkIndex++);
4882       break;
4883     case CONSTANT_Class:
4884     case CONSTANT_String:
4885       // just write the ref
4886       putu2(e.refs[0]->getOutputIndex());
4887       break;
4888     case CONSTANT_Fieldref:
4889     case CONSTANT_Methodref:
4890     case CONSTANT_InterfaceMethodref:
4891     case CONSTANT_NameandType:
4892     case CONSTANT_InvokeDynamic:
4893       putu2(e.refs[0]->getOutputIndex());
4894       putu2(e.refs[1]->getOutputIndex());
4895       break;
4896     case CONSTANT_MethodHandle:
4897         putu1(e.value.i);
4898         putu2(e.refs[0]->getOutputIndex());
4899         break;
4900     case CONSTANT_MethodType:
4901       putu2(e.refs[0]->getOutputIndex());
4902       break;
4903     case CONSTANT_BootstrapMethod: // should not happen
4904     default:
4905       abort(ERROR_INTERNAL);
4906     }
4907   }
4908 
4909 #ifndef PRODUCT
4910   total_cp_size[0] += cp.outputIndexLimit;
4911   total_cp_size[1] += (int)cur_classfile_head.size();
4912 #endif
4913   close_output();
4914 }
4915 
4916 unpacker::file* unpacker::get_next_file() {
4917   CHECK_0;
4918   free_temps();
4919   if (files_remaining == 0) {
4920     // Leave a clue that we're exhausted.
4921     cur_file.name = null;
4922     cur_file.size = null;
4923     if (archive_size != 0) {
4924       julong predicted_size = unsized_bytes_read + archive_size;
4925       if (predicted_size != bytes_read)
4926         abort("archive header had incorrect size");
4927     }
4928     return null;
4929   }
4930   files_remaining -= 1;
4931   assert(files_written < file_count || classes_written < class_count);
4932   cur_file.name = "";
4933   cur_file.size = 0;
4934   cur_file.modtime = default_file_modtime;
4935   cur_file.options = default_file_options;
4936   cur_file.data[0].set(null, 0);
4937   cur_file.data[1].set(null, 0);
4938   if (files_written < file_count) {
4939     entry* e = file_name.getRef();
4940     CHECK_0;
4941     cur_file.name = e->utf8String();
4942     bool haveLongSize = (testBit(archive_options, AO_HAVE_FILE_SIZE_HI));
4943     cur_file.size = file_size_hi.getLong(file_size_lo, haveLongSize);
4944     if (testBit(archive_options, AO_HAVE_FILE_MODTIME))
4945       cur_file.modtime += file_modtime.getInt();  //relative to archive modtime
4946     if (testBit(archive_options, AO_HAVE_FILE_OPTIONS))
4947       cur_file.options |= file_options.getInt() & ~suppress_file_options;
4948   } else if (classes_written < class_count) {
4949     // there is a class for a missing file record
4950     cur_file.options |= FO_IS_CLASS_STUB;
4951   }
4952   if ((cur_file.options & FO_IS_CLASS_STUB) != 0) {
4953     assert(classes_written < class_count);
4954     classes_written += 1;
4955     if (cur_file.size != 0) {
4956       abort("class file size transmitted");
4957       return null;
4958     }
4959     reset_cur_classfile();
4960 
4961     // write the meat of the classfile:
4962     write_classfile_tail();
4963     cur_file.data[1] = cur_classfile_tail.b;
4964     CHECK_0;
4965 
4966     // write the CP of the classfile, second:
4967     write_classfile_head();
4968     cur_file.data[0] = cur_classfile_head.b;
4969     CHECK_0;
4970 
4971     cur_file.size += cur_file.data[0].len;
4972     cur_file.size += cur_file.data[1].len;
4973     if (cur_file.name[0] == '\0') {
4974       bytes& prefix = cur_class->ref(0)->value.b;
4975       const char* suffix = ".class";
4976       int len = (int)(prefix.len + strlen(suffix));
4977       bytes name; name.set(T_NEW(byte, add_size(len, 1)), len);
4978       cur_file.name = name.strcat(prefix).strcat(suffix).strval();
4979     }
4980   } else {
4981     // If there is buffered file data, produce a pointer to it.
4982     if (cur_file.size != (size_t) cur_file.size) {
4983       // Silly size specified.
4984       abort("resource file too large");
4985       return null;
4986     }
4987     size_t rpleft = input_remaining();
4988     if (rpleft > 0) {
4989       if (rpleft > cur_file.size)
4990         rpleft = (size_t) cur_file.size;
4991       cur_file.data[0].set(rp, rpleft);
4992       rp += rpleft;
4993     }
4994     if (rpleft < cur_file.size) {
4995       // Caller must read the rest.
4996       size_t fleft = (size_t)cur_file.size - rpleft;
4997       bytes_read += fleft;  // Credit it to the overall archive size.
4998     }
4999   }
5000   CHECK_0;
5001   bytes_written += cur_file.size;
5002   files_written += 1;
5003   return &cur_file;
5004 }
5005 
5006 // Write a file to jarout.
5007 void unpacker::write_file_to_jar(unpacker::file* f) {
5008   size_t htsize = f->data[0].len + f->data[1].len;
5009   julong fsize = f->size;
5010 #ifndef PRODUCT
5011   if (nowrite NOT_PRODUCT(|| skipfiles-- > 0)) {
5012     PRINTCR((2,"would write %d bytes to %s", (int) fsize, f->name));
5013     return;
5014   }
5015 #endif
5016   if (htsize == fsize) {
5017     jarout->addJarEntry(f->name, f->deflate_hint(), f->modtime,
5018                         f->data[0], f->data[1]);
5019   } else {
5020     assert(input_remaining() == 0);
5021     bytes part1, part2;
5022     part1.len = f->data[0].len;
5023     part1.set(T_NEW(byte, part1.len), part1.len);
5024     part1.copyFrom(f->data[0]);
5025     assert(f->data[1].len == 0);
5026     part2.set(null, 0);
5027     size_t fleft = (size_t) fsize - part1.len;
5028     assert(bytes_read > fleft);  // part2 already credited by get_next_file
5029     bytes_read -= fleft;
5030     if (fleft > 0) {
5031       // Must read some more.
5032       if (live_input) {
5033         // Stop using the input buffer.  Make a new one:
5034         if (free_input)  input.free();
5035         input.init(fleft > (1<<12) ? fleft : (1<<12));
5036         free_input = true;
5037         live_input = false;
5038       } else {
5039         // Make it large enough.
5040         assert(free_input);  // must be reallocable
5041         input.ensureSize(fleft);
5042       }
5043       rplimit = rp = input.base();
5044       CHECK;
5045       input.setLimit(rp + fleft);
5046       if (!ensure_input(fleft))
5047         abort("EOF reading resource file");
5048       part2.ptr = input_scan();
5049       part2.len = input_remaining();
5050       rplimit = rp = input.base();
5051     }
5052     jarout->addJarEntry(f->name, f->deflate_hint(), f->modtime,
5053                         part1, part2);
5054   }
5055   if (verbose >= 3) {
5056     fprintf(errstrm, "Wrote "
5057                      LONG_LONG_FORMAT " bytes to: %s\n", fsize, f->name);
5058   }
5059 }
5060 
5061 // Redirect the stdio to the specified file in the unpack.log.file option
5062 void unpacker::redirect_stdio() {
5063   if (log_file == null) {
5064     log_file = LOGFILE_STDOUT;
5065   }
5066   if (log_file == errstrm_name)
5067     // Nothing more to be done.
5068     return;
5069   errstrm_name = log_file;
5070   if (strcmp(log_file, LOGFILE_STDERR) == 0) {
5071     errstrm = stderr;
5072     return;
5073   } else if (strcmp(log_file, LOGFILE_STDOUT) == 0) {
5074     errstrm = stdout;
5075     return;
5076   } else if (log_file[0] != '\0' && (errstrm = fopen(log_file,"a+")) != NULL) {
5077     return;
5078   } else {
5079     char log_file_name[PATH_MAX+100];
5080     char tmpdir[PATH_MAX];
5081 #ifdef WIN32
5082     int n = GetTempPath(PATH_MAX,tmpdir); //API returns with trailing '\'
5083     if (n < 1 || n > PATH_MAX) {
5084       sprintf(tmpdir,"C:\\");
5085     }
5086     sprintf(log_file_name, "%sunpack.log", tmpdir);
5087 #else
5088     sprintf(tmpdir,"/tmp");
5089     sprintf(log_file_name, "/tmp/unpack.log");
5090 #endif
5091     if ((errstrm = fopen(log_file_name, "a+")) != NULL) {
5092       log_file = errstrm_name = saveStr(log_file_name);
5093       return ;
5094     }
5095 
5096     char *tname = tempnam(tmpdir,"#upkg");
5097     if (tname == NULL) return;
5098     sprintf(log_file_name, "%s", tname);
5099     ::free(tname);
5100     if ((errstrm = fopen(log_file_name, "a+")) != NULL) {
5101       log_file = errstrm_name = saveStr(log_file_name);
5102       return ;
5103     }
5104 #ifndef WIN32
5105     sprintf(log_file_name, "/dev/null");
5106     // On windows most likely it will fail.
5107     if ( (errstrm = fopen(log_file_name, "a+")) != NULL) {
5108       log_file = errstrm_name = saveStr(log_file_name);
5109       return ;
5110     }
5111 #endif
5112     // Last resort
5113     // (Do not use stdout, since it might be jarout->jarfp.)
5114     errstrm = stderr;
5115     log_file = errstrm_name = LOGFILE_STDERR;
5116   }
5117 }
5118 
5119 #ifndef PRODUCT
5120 int unpacker::printcr_if_verbose(int level, const char* fmt ...) {
5121   if (verbose < level+10)  return 0;
5122   va_list vl;
5123   va_start(vl, fmt);
5124   char fmtbuf[300];
5125   strcpy(fmtbuf+100, fmt);
5126   strcat(fmtbuf+100, "\n");
5127   char* fmt2 = fmtbuf+100;
5128   while (level-- > 0)  *--fmt2 = ' ';
5129   vfprintf(errstrm, fmt2, vl);
5130   return 1;  // for ?: usage
5131 }
5132 #endif
5133 
5134 void unpacker::abort(const char* message) {
5135   if (message == null)  message = "error unpacking archive";
5136 #ifdef UNPACK_JNI
5137   if (message[0] == '@') {  // secret convention for sprintf
5138      bytes saved;
5139      saved.saveFrom(message+1);
5140      mallocs.add(message = saved.strval());
5141    }
5142   abort_message = message;
5143   return;
5144 #else
5145   if (message[0] == '@')  ++message;
5146   fprintf(errstrm, "%s\n", message);
5147 #ifndef PRODUCT
5148   fflush(errstrm);
5149   ::abort();
5150 #else
5151   exit(-1);
5152 #endif
5153 #endif // JNI
5154 }