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