src/jdk.pack/share/native/common-unpack/unpack.cpp
changeset 47216 71c04702a3d5
parent 42693 6645de32a866
child 50514 2a524e603529
equal deleted inserted replaced
47215:4ebc2e2fb97c 47216:71c04702a3d5
       
     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     case 'F':
       
  1803       lp = parseIntLayout(lp, b, EK_INT);
       
  1804       break;
       
  1805     case 'P':
       
  1806       {
       
  1807         int le_bci = EK_BCI;
       
  1808         if (*lp == 'O') {
       
  1809           ++lp;
       
  1810           le_bci = EK_BCID;
       
  1811         }
       
  1812         assert(*lp != 'S');  // no PSH, etc.
       
  1813         lp = parseIntLayout(lp, b, EK_INT);
       
  1814         b->le_bci = le_bci;
       
  1815         if (le_bci == EK_BCI)
       
  1816           b->defc = coding::findBySpec(BCI5_spec);
       
  1817         else
       
  1818           b->defc = coding::findBySpec(BRANCH5_spec);
       
  1819       }
       
  1820       break;
       
  1821     case 'O':
       
  1822       lp = parseIntLayout(lp, b, EK_INT, can_be_signed);
       
  1823       b->le_bci = EK_BCO;
       
  1824       b->defc = coding::findBySpec(BRANCH5_spec);
       
  1825       break;
       
  1826     case 'N': // replication: 'N' uint '[' elem ... ']'
       
  1827       lp = parseIntLayout(lp, b, EK_REPL);
       
  1828       assert(*lp == '[');
       
  1829       ++lp;
       
  1830       lp = parseLayout(lp, b->le_body, curCble);
       
  1831       CHECK_(lp);
       
  1832       break;
       
  1833     case 'T': // union: 'T' any_int union_case* '(' ')' '[' body ']'
       
  1834       lp = parseIntLayout(lp, b, EK_UN, can_be_signed);
       
  1835       {
       
  1836         int union_base = band_stack.length();
       
  1837         for (;;) {   // for each case
       
  1838           band& k_case = *U_NEW(band, 1);
       
  1839           CHECK_(lp);
       
  1840           band_stack.add(&k_case);
       
  1841           k_case.le_kind = EK_CASE;
       
  1842           k_case.bn = bands_made++;
       
  1843           if (*lp++ != '(') {
       
  1844             abort("bad union case");
       
  1845             return "";
       
  1846           }
       
  1847           if (*lp++ != ')') {
       
  1848             --lp;  // reparse
       
  1849             // Read some case values.  (Use band_stack for temp. storage.)
       
  1850             int case_base = band_stack.length();
       
  1851             for (;;) {
       
  1852               int caseval = 0;
       
  1853               lp = parseNumeral(lp, caseval);
       
  1854               band_stack.add((void*)(size_t)caseval);
       
  1855               if (*lp == '-') {
       
  1856                 // new in version 160, allow (1-5) for (1,2,3,4,5)
       
  1857                 if (u->majver < JAVA6_PACKAGE_MAJOR_VERSION) {
       
  1858                   abort("bad range in union case label (old archive format)");
       
  1859                   return "";
       
  1860                 }
       
  1861                 int caselimit = caseval;
       
  1862                 lp++;
       
  1863                 lp = parseNumeral(lp, caselimit);
       
  1864                 if (caseval >= caselimit
       
  1865                     || (uint)(caselimit - caseval) > 0x10000) {
       
  1866                   // Note:  0x10000 is arbitrary implementation restriction.
       
  1867                   // We can remove it later if it's important to.
       
  1868                   abort("bad range in union case label");
       
  1869                   return "";
       
  1870                 }
       
  1871                 for (;;) {
       
  1872                   ++caseval;
       
  1873                   band_stack.add((void*)(size_t)caseval);
       
  1874                   if (caseval == caselimit)  break;
       
  1875                 }
       
  1876               }
       
  1877               if (*lp != ',')  break;
       
  1878               lp++;
       
  1879             }
       
  1880             if (*lp++ != ')') {
       
  1881               abort("bad case label");
       
  1882               return "";
       
  1883             }
       
  1884             // save away the case labels
       
  1885             int ntags = band_stack.length() - case_base;
       
  1886             int* tags = U_NEW(int, add_size(ntags, 1));
       
  1887             CHECK_(lp);
       
  1888             k_case.le_casetags = tags;
       
  1889             *tags++ = ntags;
       
  1890             for (int i = 0; i < ntags; i++) {
       
  1891               *tags++ = ptrlowbits(band_stack.get(case_base+i));
       
  1892             }
       
  1893             band_stack.popTo(case_base);
       
  1894             CHECK_(lp);
       
  1895           }
       
  1896           // Got le_casetags.  Now grab the body.
       
  1897           assert(*lp == '[');
       
  1898           ++lp;
       
  1899           lp = parseLayout(lp, k_case.le_body, curCble);
       
  1900           CHECK_(lp);
       
  1901           if (k_case.le_casetags == null)  break;  // done
       
  1902         }
       
  1903         b->le_body = popBody(union_base);
       
  1904       }
       
  1905       break;
       
  1906     case '(': // call: '(' -?NN* ')'
       
  1907       {
       
  1908         band& call = *U_NEW(band, 1);
       
  1909         CHECK_(lp);
       
  1910         band_stack.add(&call);
       
  1911         call.le_kind = EK_CALL;
       
  1912         call.bn = bands_made++;
       
  1913         call.le_body = U_NEW(band*, 2); // fill in later
       
  1914         int call_num = 0;
       
  1915         lp = parseNumeral(lp, call_num);
       
  1916         call.le_back = (call_num <= 0);
       
  1917         call_num += curCble;  // numeral is self-relative offset
       
  1918         call.le_len = call_num;  //use le_len as scratch
       
  1919         calls_to_link.add(&call);
       
  1920         CHECK_(lp);
       
  1921         if (*lp++ != ')') {
       
  1922           abort("bad call label");
       
  1923           return "";
       
  1924         }
       
  1925       }
       
  1926       break;
       
  1927     case 'K': // reference_type: constant_ref
       
  1928     case 'R': // reference_type: schema_ref
       
  1929       {
       
  1930         int ixTag = CONSTANT_None;
       
  1931         if (lp[-1] == 'K') {
       
  1932           switch (*lp++) {
       
  1933           case 'I': ixTag = CONSTANT_Integer; break;
       
  1934           case 'J': ixTag = CONSTANT_Long; break;
       
  1935           case 'F': ixTag = CONSTANT_Float; break;
       
  1936           case 'D': ixTag = CONSTANT_Double; break;
       
  1937           case 'S': ixTag = CONSTANT_String; break;
       
  1938           case 'Q': ixTag = CONSTANT_FieldSpecific; break;
       
  1939 
       
  1940           // new in 1.7
       
  1941           case 'M': ixTag = CONSTANT_MethodHandle; break;
       
  1942           case 'T': ixTag = CONSTANT_MethodType; break;
       
  1943           case 'L': ixTag = CONSTANT_LoadableValue; break;
       
  1944           }
       
  1945         } else {
       
  1946           switch (*lp++) {
       
  1947           case 'C': ixTag = CONSTANT_Class; break;
       
  1948           case 'S': ixTag = CONSTANT_Signature; break;
       
  1949           case 'D': ixTag = CONSTANT_NameandType; break;
       
  1950           case 'F': ixTag = CONSTANT_Fieldref; break;
       
  1951           case 'M': ixTag = CONSTANT_Methodref; break;
       
  1952           case 'I': ixTag = CONSTANT_InterfaceMethodref; break;
       
  1953           case 'U': ixTag = CONSTANT_Utf8; break; //utf8_ref
       
  1954           case 'Q': ixTag = CONSTANT_All; break; //untyped_ref
       
  1955 
       
  1956           // new in 1.7
       
  1957           case 'Y': ixTag = CONSTANT_InvokeDynamic; break;
       
  1958           case 'B': ixTag = CONSTANT_BootstrapMethod; break;
       
  1959           case 'N': ixTag = CONSTANT_AnyMember; break;
       
  1960           }
       
  1961         }
       
  1962         if (ixTag == CONSTANT_None) {
       
  1963           abort("bad reference layout");
       
  1964           break;
       
  1965         }
       
  1966         bool nullOK = false;
       
  1967         if (*lp == 'N') {
       
  1968           nullOK = true;
       
  1969           lp++;
       
  1970         }
       
  1971         lp = parseIntLayout(lp, b, EK_REF);
       
  1972         b->defc = coding::findBySpec(UNSIGNED5_spec);
       
  1973         b->initRef(ixTag, nullOK);
       
  1974       }
       
  1975       break;
       
  1976     case '[':
       
  1977       {
       
  1978         // [callable1][callable2]...
       
  1979         if (!top_level) {
       
  1980           abort("bad nested callable");
       
  1981           break;
       
  1982         }
       
  1983         curCble += 1;
       
  1984         NOT_PRODUCT(int call_num = band_stack.length() - bs_base);
       
  1985         band& cble = *U_NEW(band, 1);
       
  1986         CHECK_(lp);
       
  1987         band_stack.add(&cble);
       
  1988         cble.le_kind = EK_CBLE;
       
  1989         NOT_PRODUCT(cble.le_len = call_num);
       
  1990         cble.bn = bands_made++;
       
  1991         lp = parseLayout(lp, cble.le_body, curCble);
       
  1992       }
       
  1993       break;
       
  1994     case ']':
       
  1995       // Hit a closing brace.  This ends whatever body we were in.
       
  1996       done = true;
       
  1997       break;
       
  1998     case '\0':
       
  1999       // Hit a null.  Also ends the (top-level) body.
       
  2000       --lp;  // back up, so caller can see the null also
       
  2001       done = true;
       
  2002       break;
       
  2003     default:
       
  2004       abort("bad layout");
       
  2005       break;
       
  2006     }
       
  2007     CHECK_(lp);
       
  2008   }
       
  2009 
       
  2010   // Return the accumulated bands:
       
  2011   res = popBody(bs_base);
       
  2012   return lp;
       
  2013 }
       
  2014 
       
  2015 void unpacker::read_attr_defs() {
       
  2016   int i;
       
  2017 
       
  2018   // Tell each AD which attrc it is and where its fixed flags are:
       
  2019   attr_defs[ATTR_CONTEXT_CLASS].attrc            = ATTR_CONTEXT_CLASS;
       
  2020   attr_defs[ATTR_CONTEXT_CLASS].xxx_flags_hi_bn  = e_class_flags_hi;
       
  2021   attr_defs[ATTR_CONTEXT_FIELD].attrc            = ATTR_CONTEXT_FIELD;
       
  2022   attr_defs[ATTR_CONTEXT_FIELD].xxx_flags_hi_bn  = e_field_flags_hi;
       
  2023   attr_defs[ATTR_CONTEXT_METHOD].attrc           = ATTR_CONTEXT_METHOD;
       
  2024   attr_defs[ATTR_CONTEXT_METHOD].xxx_flags_hi_bn = e_method_flags_hi;
       
  2025   attr_defs[ATTR_CONTEXT_CODE].attrc             = ATTR_CONTEXT_CODE;
       
  2026   attr_defs[ATTR_CONTEXT_CODE].xxx_flags_hi_bn   = e_code_flags_hi;
       
  2027 
       
  2028   // Decide whether bands for the optional high flag words are present.
       
  2029   attr_defs[ATTR_CONTEXT_CLASS]
       
  2030     .setHaveLongFlags(testBit(archive_options, AO_HAVE_CLASS_FLAGS_HI));
       
  2031   attr_defs[ATTR_CONTEXT_FIELD]
       
  2032     .setHaveLongFlags(testBit(archive_options, AO_HAVE_FIELD_FLAGS_HI));
       
  2033   attr_defs[ATTR_CONTEXT_METHOD]
       
  2034     .setHaveLongFlags(testBit(archive_options, AO_HAVE_METHOD_FLAGS_HI));
       
  2035   attr_defs[ATTR_CONTEXT_CODE]
       
  2036     .setHaveLongFlags(testBit(archive_options, AO_HAVE_CODE_FLAGS_HI));
       
  2037 
       
  2038   // Set up built-in attrs.
       
  2039   // (The simple ones are hard-coded.  The metadata layouts are not.)
       
  2040   const char* md_layout = (
       
  2041     // parameter annotations:
       
  2042 #define MDL0 \
       
  2043     "[NB[(1)]]"
       
  2044     MDL0
       
  2045     // annotations:
       
  2046 #define MDL1 \
       
  2047     "[NH[(1)]]"
       
  2048     MDL1
       
  2049 #define MDL2 \
       
  2050     "[RSHNH[RUH(1)]]"
       
  2051     MDL2
       
  2052     // element_value:
       
  2053 #define MDL3 \
       
  2054     "[TB"                        \
       
  2055       "(66,67,73,83,90)[KIH]"    \
       
  2056       "(68)[KDH]"                \
       
  2057       "(70)[KFH]"                \
       
  2058       "(74)[KJH]"                \
       
  2059       "(99)[RSH]"                \
       
  2060       "(101)[RSHRUH]"            \
       
  2061       "(115)[RUH]"               \
       
  2062       "(91)[NH[(0)]]"            \
       
  2063       "(64)["                    \
       
  2064         /* nested annotation: */ \
       
  2065         "RSH"                    \
       
  2066         "NH[RUH(0)]"             \
       
  2067         "]"                      \
       
  2068       "()[]"                     \
       
  2069     "]"
       
  2070     MDL3
       
  2071     );
       
  2072 
       
  2073   const char* md_layout_P = md_layout;
       
  2074   const char* md_layout_A = md_layout+strlen(MDL0);
       
  2075   const char* md_layout_V = md_layout+strlen(MDL0 MDL1 MDL2);
       
  2076   assert(0 == strncmp(&md_layout_A[-3], ")]][", 4));
       
  2077   assert(0 == strncmp(&md_layout_V[-3], ")]][", 4));
       
  2078 
       
  2079 const char* type_md_layout(
       
  2080     "[NH[(1)(2)(3)]]"
       
  2081     // target-type + target_info
       
  2082     "[TB"
       
  2083        "(0,1)[B]"
       
  2084        "(16)[FH]"
       
  2085        "(17,18)[BB]"
       
  2086        "(19,20,21)[]"
       
  2087        "(22)[B]"
       
  2088        "(23)[H]"
       
  2089        "(64,65)[NH[PHOHH]]"
       
  2090        "(66)[H]"
       
  2091        "(67,68,69,70)[PH]"
       
  2092        "(71,72,73,74,75)[PHB]"
       
  2093        "()[]]"
       
  2094     // target-path
       
  2095     "[NB[BB]]"
       
  2096     // annotation + element_value
       
  2097     MDL2
       
  2098     MDL3
       
  2099 );
       
  2100 
       
  2101   for (i = 0; i < ATTR_CONTEXT_LIMIT; i++) {
       
  2102     attr_definitions& ad = attr_defs[i];
       
  2103     if (i != ATTR_CONTEXT_CODE) {
       
  2104       ad.defineLayout(X_ATTR_RuntimeVisibleAnnotations,
       
  2105                       "RuntimeVisibleAnnotations", md_layout_A);
       
  2106       ad.defineLayout(X_ATTR_RuntimeInvisibleAnnotations,
       
  2107                       "RuntimeInvisibleAnnotations", md_layout_A);
       
  2108       if (i == ATTR_CONTEXT_METHOD) {
       
  2109         ad.defineLayout(METHOD_ATTR_RuntimeVisibleParameterAnnotations,
       
  2110                         "RuntimeVisibleParameterAnnotations", md_layout_P);
       
  2111         ad.defineLayout(METHOD_ATTR_RuntimeInvisibleParameterAnnotations,
       
  2112                         "RuntimeInvisibleParameterAnnotations", md_layout_P);
       
  2113         ad.defineLayout(METHOD_ATTR_AnnotationDefault,
       
  2114                         "AnnotationDefault", md_layout_V);
       
  2115       }
       
  2116     }
       
  2117     ad.defineLayout(X_ATTR_RuntimeVisibleTypeAnnotations,
       
  2118                     "RuntimeVisibleTypeAnnotations", type_md_layout);
       
  2119     ad.defineLayout(X_ATTR_RuntimeInvisibleTypeAnnotations,
       
  2120                     "RuntimeInvisibleTypeAnnotations", type_md_layout);
       
  2121   }
       
  2122 
       
  2123   attr_definition_headers.readData(attr_definition_count);
       
  2124   attr_definition_name.readData(attr_definition_count);
       
  2125   attr_definition_layout.readData(attr_definition_count);
       
  2126 
       
  2127   CHECK;
       
  2128 
       
  2129   // Initialize correct predef bits, to distinguish predefs from new defs.
       
  2130 #define ORBIT(n,s) |((julong)1<<n)
       
  2131   attr_defs[ATTR_CONTEXT_CLASS].predef
       
  2132     = (0 X_ATTR_DO(ORBIT) CLASS_ATTR_DO(ORBIT));
       
  2133   attr_defs[ATTR_CONTEXT_FIELD].predef
       
  2134     = (0 X_ATTR_DO(ORBIT) FIELD_ATTR_DO(ORBIT));
       
  2135   attr_defs[ATTR_CONTEXT_METHOD].predef
       
  2136     = (0 X_ATTR_DO(ORBIT) METHOD_ATTR_DO(ORBIT));
       
  2137   attr_defs[ATTR_CONTEXT_CODE].predef
       
  2138     = (0 O_ATTR_DO(ORBIT) CODE_ATTR_DO(ORBIT));
       
  2139 #undef ORBIT
       
  2140   // Clear out the redef bits, folding them back into predef.
       
  2141   for (i = 0; i < ATTR_CONTEXT_LIMIT; i++) {
       
  2142     attr_defs[i].predef |= attr_defs[i].redef;
       
  2143     attr_defs[i].redef = 0;
       
  2144   }
       
  2145 
       
  2146   // Now read the transmitted locally defined attrs.
       
  2147   // This will set redef bits again.
       
  2148   for (i = 0; i < attr_definition_count; i++) {
       
  2149     int    header  = attr_definition_headers.getByte();
       
  2150     int    attrc   = ADH_BYTE_CONTEXT(header);
       
  2151     int    idx     = ADH_BYTE_INDEX(header);
       
  2152     entry* name    = attr_definition_name.getRef();
       
  2153     CHECK;
       
  2154     entry* layout  = attr_definition_layout.getRef();
       
  2155     CHECK;
       
  2156     attr_defs[attrc].defineLayout(idx, name, layout->value.b.strval());
       
  2157   }
       
  2158 }
       
  2159 
       
  2160 #define NO_ENTRY_YET ((entry*)-1)
       
  2161 
       
  2162 static bool isDigitString(bytes& x, int beg, int end) {
       
  2163   if (beg == end)  return false;  // null string
       
  2164   byte* xptr = x.ptr;
       
  2165   for (int i = beg; i < end; i++) {
       
  2166     char ch = xptr[i];
       
  2167     if (!(ch >= '0' && ch <= '9'))  return false;
       
  2168   }
       
  2169   return true;
       
  2170 }
       
  2171 
       
  2172 enum {  // constants for parsing class names
       
  2173   SLASH_MIN = '.',
       
  2174   SLASH_MAX = '/',
       
  2175   DOLLAR_MIN = 0,
       
  2176   DOLLAR_MAX = '-'
       
  2177 };
       
  2178 
       
  2179 static int lastIndexOf(int chmin, int chmax, bytes& x, int pos) {
       
  2180   byte* ptr = x.ptr;
       
  2181   for (byte* cp = ptr + pos; --cp >= ptr; ) {
       
  2182     assert(x.inBounds(cp));
       
  2183     if (*cp >= chmin && *cp <= chmax)
       
  2184       return (int)(cp - ptr);
       
  2185   }
       
  2186   return -1;
       
  2187 }
       
  2188 
       
  2189 maybe_inline
       
  2190 inner_class* cpool::getIC(entry* inner) {
       
  2191   if (inner == null)  return null;
       
  2192   assert(inner->tag == CONSTANT_Class);
       
  2193   if (inner->inord == NO_INORD)  return null;
       
  2194   inner_class* ic = ic_index[inner->inord];
       
  2195   assert(ic == null || ic->inner == inner);
       
  2196   return ic;
       
  2197 }
       
  2198 
       
  2199 maybe_inline
       
  2200 inner_class* cpool::getFirstChildIC(entry* outer) {
       
  2201   if (outer == null)  return null;
       
  2202   assert(outer->tag == CONSTANT_Class);
       
  2203   if (outer->inord == NO_INORD)  return null;
       
  2204   inner_class* ic = ic_child_index[outer->inord];
       
  2205   assert(ic == null || ic->outer == outer);
       
  2206   return ic;
       
  2207 }
       
  2208 
       
  2209 maybe_inline
       
  2210 inner_class* cpool::getNextChildIC(inner_class* child) {
       
  2211   inner_class* ic = child->next_sibling;
       
  2212   assert(ic == null || ic->outer == child->outer);
       
  2213   return ic;
       
  2214 }
       
  2215 
       
  2216 void unpacker::read_ics() {
       
  2217   int i;
       
  2218   int index_size = cp.tag_count[CONSTANT_Class];
       
  2219   inner_class** ic_index       = U_NEW(inner_class*, index_size);
       
  2220   inner_class** ic_child_index = U_NEW(inner_class*, index_size);
       
  2221   cp.ic_index = ic_index;
       
  2222   cp.ic_child_index = ic_child_index;
       
  2223   ics = U_NEW(inner_class, ic_count);
       
  2224   ic_this_class.readData(ic_count);
       
  2225   ic_flags.readData(ic_count);
       
  2226   CHECK;
       
  2227   // Scan flags to get count of long-form bands.
       
  2228   int long_forms = 0;
       
  2229   for (i = 0; i < ic_count; i++) {
       
  2230     int flags = ic_flags.getInt();  // may be long form!
       
  2231     if ((flags & ACC_IC_LONG_FORM) != 0) {
       
  2232       long_forms += 1;
       
  2233       ics[i].name = NO_ENTRY_YET;
       
  2234     }
       
  2235     flags &= ~ACC_IC_LONG_FORM;
       
  2236     entry* inner = ic_this_class.getRef();
       
  2237     CHECK;
       
  2238     uint inord = inner->inord;
       
  2239     assert(inord < (uint)cp.tag_count[CONSTANT_Class]);
       
  2240     if (ic_index[inord] != null) {
       
  2241       abort("identical inner class");
       
  2242       break;
       
  2243     }
       
  2244     ic_index[inord] = &ics[i];
       
  2245     ics[i].inner = inner;
       
  2246     ics[i].flags = flags;
       
  2247     assert(cp.getIC(inner) == &ics[i]);
       
  2248   }
       
  2249   CHECK;
       
  2250   //ic_this_class.done();
       
  2251   //ic_flags.done();
       
  2252   ic_outer_class.readData(long_forms);
       
  2253   ic_name.readData(long_forms);
       
  2254   for (i = 0; i < ic_count; i++) {
       
  2255     if (ics[i].name == NO_ENTRY_YET) {
       
  2256       // Long form.
       
  2257       ics[i].outer = ic_outer_class.getRefN();
       
  2258       CHECK;
       
  2259       ics[i].name  = ic_name.getRefN();
       
  2260       CHECK;
       
  2261     } else {
       
  2262       // Fill in outer and name based on inner.
       
  2263       bytes& n = ics[i].inner->value.b;
       
  2264       bytes pkgOuter;
       
  2265       bytes number;
       
  2266       bytes name;
       
  2267       // Parse n into pkgOuter and name (and number).
       
  2268       PRINTCR((5, "parse short IC name %s", n.ptr));
       
  2269       int dollar1, dollar2;  // pointers to $ in the pattern
       
  2270       // parse n = (<pkg>/)*<outer>($<number>)?($<name>)?
       
  2271       int nlen = (int)n.len;
       
  2272       int pkglen = lastIndexOf(SLASH_MIN,  SLASH_MAX,  n, nlen) + 1;
       
  2273       dollar2    = lastIndexOf(DOLLAR_MIN, DOLLAR_MAX, n, nlen);
       
  2274       if (dollar2 < 0) {
       
  2275          abort();
       
  2276          return;
       
  2277       }
       
  2278       assert(dollar2 >= pkglen);
       
  2279       if (isDigitString(n, dollar2+1, nlen)) {
       
  2280         // n = (<pkg>/)*<outer>$<number>
       
  2281         number = n.slice(dollar2+1, nlen);
       
  2282         name.set(null,0);
       
  2283         dollar1 = dollar2;
       
  2284       } else if (pkglen < (dollar1
       
  2285                            = lastIndexOf(DOLLAR_MIN, DOLLAR_MAX, n, dollar2-1))
       
  2286                  && isDigitString(n, dollar1+1, dollar2)) {
       
  2287         // n = (<pkg>/)*<outer>$<number>$<name>
       
  2288         number = n.slice(dollar1+1, dollar2);
       
  2289         name = n.slice(dollar2+1, nlen);
       
  2290       } else {
       
  2291         // n = (<pkg>/)*<outer>$<name>
       
  2292         dollar1 = dollar2;
       
  2293         number.set(null,0);
       
  2294         name = n.slice(dollar2+1, nlen);
       
  2295       }
       
  2296       if (number.ptr == null) {
       
  2297         if (dollar1 < 0) {
       
  2298           abort();
       
  2299           return;
       
  2300         }
       
  2301         pkgOuter = n.slice(0, dollar1);
       
  2302       } else {
       
  2303         pkgOuter.set(null,0);
       
  2304       }
       
  2305       PRINTCR((5,"=> %s$ 0%s $%s",
       
  2306               pkgOuter.string(), number.string(), name.string()));
       
  2307 
       
  2308       if (pkgOuter.ptr != null)
       
  2309         ics[i].outer = cp.ensureClass(pkgOuter);
       
  2310 
       
  2311       if (name.ptr != null)
       
  2312         ics[i].name = cp.ensureUtf8(name);
       
  2313     }
       
  2314 
       
  2315     // update child/sibling list
       
  2316     if (ics[i].outer != null) {
       
  2317       uint outord = ics[i].outer->inord;
       
  2318       if (outord != NO_INORD) {
       
  2319         assert(outord < (uint)cp.tag_count[CONSTANT_Class]);
       
  2320         ics[i].next_sibling = ic_child_index[outord];
       
  2321         ic_child_index[outord] = &ics[i];
       
  2322       }
       
  2323     }
       
  2324   }
       
  2325   //ic_outer_class.done();
       
  2326   //ic_name.done();
       
  2327 }
       
  2328 
       
  2329 void unpacker::read_classes() {
       
  2330   PRINTCR((1,"  ...scanning %d classes...", class_count));
       
  2331   class_this.readData(class_count);
       
  2332   class_super.readData(class_count);
       
  2333   class_interface_count.readData(class_count);
       
  2334   class_interface.readData(class_interface_count.getIntTotal());
       
  2335 
       
  2336   CHECK;
       
  2337 
       
  2338   #if 0
       
  2339   int i;
       
  2340   // Make a little mark on super-classes.
       
  2341   for (i = 0; i < class_count; i++) {
       
  2342     entry* e = class_super.getRefN();
       
  2343     if (e != null)  e->bits |= entry::EB_SUPER;
       
  2344   }
       
  2345   class_super.rewind();
       
  2346   #endif
       
  2347 
       
  2348   // Members.
       
  2349   class_field_count.readData(class_count);
       
  2350   class_method_count.readData(class_count);
       
  2351 
       
  2352   CHECK;
       
  2353 
       
  2354   int field_count = class_field_count.getIntTotal();
       
  2355   int method_count = class_method_count.getIntTotal();
       
  2356 
       
  2357   field_descr.readData(field_count);
       
  2358   read_attrs(ATTR_CONTEXT_FIELD, field_count);
       
  2359   CHECK;
       
  2360 
       
  2361   method_descr.readData(method_count);
       
  2362   read_attrs(ATTR_CONTEXT_METHOD, method_count);
       
  2363 
       
  2364   CHECK;
       
  2365 
       
  2366   read_attrs(ATTR_CONTEXT_CLASS, class_count);
       
  2367   CHECK;
       
  2368 
       
  2369   read_code_headers();
       
  2370 
       
  2371   PRINTCR((1,"scanned %d classes, %d fields, %d methods, %d code headers",
       
  2372           class_count, field_count, method_count, code_count));
       
  2373 }
       
  2374 
       
  2375 maybe_inline
       
  2376 int unpacker::attr_definitions::predefCount(uint idx) {
       
  2377   return isPredefined(idx) ? flag_count[idx] : 0;
       
  2378 }
       
  2379 
       
  2380 void unpacker::read_attrs(int attrc, int obj_count) {
       
  2381   attr_definitions& ad = attr_defs[attrc];
       
  2382   assert(ad.attrc == attrc);
       
  2383 
       
  2384   int i, idx, count;
       
  2385 
       
  2386   CHECK;
       
  2387 
       
  2388   bool haveLongFlags = ad.haveLongFlags();
       
  2389 
       
  2390   band& xxx_flags_hi = ad.xxx_flags_hi();
       
  2391   assert(endsWith(xxx_flags_hi.name, "_flags_hi"));
       
  2392   if (haveLongFlags)
       
  2393     xxx_flags_hi.readData(obj_count);
       
  2394   CHECK;
       
  2395 
       
  2396   band& xxx_flags_lo = ad.xxx_flags_lo();
       
  2397   assert(endsWith(xxx_flags_lo.name, "_flags_lo"));
       
  2398   xxx_flags_lo.readData(obj_count);
       
  2399   CHECK;
       
  2400 
       
  2401   // pre-scan flags, counting occurrences of each index bit
       
  2402   julong indexMask = ad.flagIndexMask();  // which flag bits are index bits?
       
  2403   for (i = 0; i < obj_count; i++) {
       
  2404     julong indexBits = xxx_flags_hi.getLong(xxx_flags_lo, haveLongFlags);
       
  2405     if ((indexBits & ~indexMask) > (ushort)-1) {
       
  2406       abort("undefined attribute flag bit");
       
  2407       return;
       
  2408     }
       
  2409     indexBits &= indexMask;  // ignore classfile flag bits
       
  2410     for (idx = 0; indexBits != 0; idx++, indexBits >>= 1) {
       
  2411       ad.flag_count[idx] += (int)(indexBits & 1);
       
  2412     }
       
  2413   }
       
  2414   // we'll scan these again later for output:
       
  2415   xxx_flags_lo.rewind();
       
  2416   xxx_flags_hi.rewind();
       
  2417 
       
  2418   band& xxx_attr_count = ad.xxx_attr_count();
       
  2419   assert(endsWith(xxx_attr_count.name, "_attr_count"));
       
  2420   // There is one count element for each 1<<16 bit set in flags:
       
  2421   xxx_attr_count.readData(ad.predefCount(X_ATTR_OVERFLOW));
       
  2422   CHECK;
       
  2423 
       
  2424   band& xxx_attr_indexes = ad.xxx_attr_indexes();
       
  2425   assert(endsWith(xxx_attr_indexes.name, "_attr_indexes"));
       
  2426   int overflowIndexCount = xxx_attr_count.getIntTotal();
       
  2427   xxx_attr_indexes.readData(overflowIndexCount);
       
  2428   CHECK;
       
  2429   // pre-scan attr indexes, counting occurrences of each value
       
  2430   for (i = 0; i < overflowIndexCount; i++) {
       
  2431     idx = xxx_attr_indexes.getInt();
       
  2432     if (!ad.isIndex(idx)) {
       
  2433       abort("attribute index out of bounds");
       
  2434       return;
       
  2435     }
       
  2436     ad.getCount(idx) += 1;
       
  2437   }
       
  2438   xxx_attr_indexes.rewind();  // we'll scan it again later for output
       
  2439 
       
  2440   // We will need a backward call count for each used backward callable.
       
  2441   int backwardCounts = 0;
       
  2442   for (idx = 0; idx < ad.layouts.length(); idx++) {
       
  2443     layout_definition* lo = ad.getLayout(idx);
       
  2444     if (lo != null && ad.getCount(idx) != 0) {
       
  2445       // Build the bands lazily, only when they are used.
       
  2446       band** bands = ad.buildBands(lo);
       
  2447       CHECK;
       
  2448       if (lo->hasCallables()) {
       
  2449         for (i = 0; bands[i] != null; i++) {
       
  2450           if (bands[i]->le_back) {
       
  2451             assert(bands[i]->le_kind == EK_CBLE);
       
  2452             backwardCounts += 1;
       
  2453           }
       
  2454         }
       
  2455       }
       
  2456     }
       
  2457   }
       
  2458   ad.xxx_attr_calls().readData(backwardCounts);
       
  2459   CHECK;
       
  2460 
       
  2461   // Read built-in bands.
       
  2462   // Mostly, these are hand-coded equivalents to readBandData().
       
  2463   switch (attrc) {
       
  2464   case ATTR_CONTEXT_CLASS:
       
  2465 
       
  2466     count = ad.predefCount(CLASS_ATTR_SourceFile);
       
  2467     class_SourceFile_RUN.readData(count);
       
  2468     CHECK;
       
  2469 
       
  2470     count = ad.predefCount(CLASS_ATTR_EnclosingMethod);
       
  2471     class_EnclosingMethod_RC.readData(count);
       
  2472     class_EnclosingMethod_RDN.readData(count);
       
  2473     CHECK;
       
  2474 
       
  2475     count = ad.predefCount(X_ATTR_Signature);
       
  2476     class_Signature_RS.readData(count);
       
  2477     CHECK;
       
  2478 
       
  2479     ad.readBandData(X_ATTR_RuntimeVisibleAnnotations);
       
  2480     ad.readBandData(X_ATTR_RuntimeInvisibleAnnotations);
       
  2481     CHECK;
       
  2482 
       
  2483     count = ad.predefCount(CLASS_ATTR_InnerClasses);
       
  2484     class_InnerClasses_N.readData(count);
       
  2485     CHECK;
       
  2486 
       
  2487     count = class_InnerClasses_N.getIntTotal();
       
  2488     class_InnerClasses_RC.readData(count);
       
  2489     class_InnerClasses_F.readData(count);
       
  2490     CHECK;
       
  2491     // Drop remaining columns wherever flags are zero:
       
  2492     count -= class_InnerClasses_F.getIntCount(0);
       
  2493     class_InnerClasses_outer_RCN.readData(count);
       
  2494     class_InnerClasses_name_RUN.readData(count);
       
  2495     CHECK;
       
  2496 
       
  2497     count = ad.predefCount(CLASS_ATTR_ClassFile_version);
       
  2498     class_ClassFile_version_minor_H.readData(count);
       
  2499     class_ClassFile_version_major_H.readData(count);
       
  2500     CHECK;
       
  2501 
       
  2502     ad.readBandData(X_ATTR_RuntimeVisibleTypeAnnotations);
       
  2503     ad.readBandData(X_ATTR_RuntimeInvisibleTypeAnnotations);
       
  2504     CHECK;
       
  2505     break;
       
  2506 
       
  2507   case ATTR_CONTEXT_FIELD:
       
  2508 
       
  2509     count = ad.predefCount(FIELD_ATTR_ConstantValue);
       
  2510     field_ConstantValue_KQ.readData(count);
       
  2511     CHECK;
       
  2512 
       
  2513     count = ad.predefCount(X_ATTR_Signature);
       
  2514     field_Signature_RS.readData(count);
       
  2515     CHECK;
       
  2516 
       
  2517     ad.readBandData(X_ATTR_RuntimeVisibleAnnotations);
       
  2518     ad.readBandData(X_ATTR_RuntimeInvisibleAnnotations);
       
  2519     CHECK;
       
  2520 
       
  2521     ad.readBandData(X_ATTR_RuntimeVisibleTypeAnnotations);
       
  2522     ad.readBandData(X_ATTR_RuntimeInvisibleTypeAnnotations);
       
  2523     CHECK;
       
  2524     break;
       
  2525 
       
  2526   case ATTR_CONTEXT_METHOD:
       
  2527 
       
  2528     code_count = ad.predefCount(METHOD_ATTR_Code);
       
  2529     // Code attrs are handled very specially below...
       
  2530 
       
  2531     count = ad.predefCount(METHOD_ATTR_Exceptions);
       
  2532     method_Exceptions_N.readData(count);
       
  2533     count = method_Exceptions_N.getIntTotal();
       
  2534     method_Exceptions_RC.readData(count);
       
  2535     CHECK;
       
  2536 
       
  2537     count = ad.predefCount(X_ATTR_Signature);
       
  2538     method_Signature_RS.readData(count);
       
  2539     CHECK;
       
  2540 
       
  2541     ad.readBandData(X_ATTR_RuntimeVisibleAnnotations);
       
  2542     ad.readBandData(X_ATTR_RuntimeInvisibleAnnotations);
       
  2543     ad.readBandData(METHOD_ATTR_RuntimeVisibleParameterAnnotations);
       
  2544     ad.readBandData(METHOD_ATTR_RuntimeInvisibleParameterAnnotations);
       
  2545     ad.readBandData(METHOD_ATTR_AnnotationDefault);
       
  2546     CHECK;
       
  2547 
       
  2548     count = ad.predefCount(METHOD_ATTR_MethodParameters);
       
  2549     method_MethodParameters_NB.readData(count);
       
  2550     count = method_MethodParameters_NB.getIntTotal();
       
  2551     method_MethodParameters_name_RUN.readData(count);
       
  2552     method_MethodParameters_flag_FH.readData(count);
       
  2553     CHECK;
       
  2554 
       
  2555     ad.readBandData(X_ATTR_RuntimeVisibleTypeAnnotations);
       
  2556     ad.readBandData(X_ATTR_RuntimeInvisibleTypeAnnotations);
       
  2557     CHECK;
       
  2558 
       
  2559     break;
       
  2560 
       
  2561   case ATTR_CONTEXT_CODE:
       
  2562     // (keep this code aligned with its brother in unpacker::write_attrs)
       
  2563     count = ad.predefCount(CODE_ATTR_StackMapTable);
       
  2564     // disable this feature in old archives!
       
  2565     if (count != 0 && majver < JAVA6_PACKAGE_MAJOR_VERSION) {
       
  2566       abort("undefined StackMapTable attribute (old archive format)");
       
  2567       return;
       
  2568     }
       
  2569     code_StackMapTable_N.readData(count);
       
  2570     CHECK;
       
  2571     count = code_StackMapTable_N.getIntTotal();
       
  2572     code_StackMapTable_frame_T.readData(count);
       
  2573     CHECK;
       
  2574     // the rest of it depends in a complicated way on frame tags
       
  2575     {
       
  2576       int fat_frame_count = 0;
       
  2577       int offset_count = 0;
       
  2578       int type_count = 0;
       
  2579       for (int k = 0; k < count; k++) {
       
  2580         int tag = code_StackMapTable_frame_T.getByte();
       
  2581         if (tag <= 127) {
       
  2582           // (64-127)  [(2)]
       
  2583           if (tag >= 64)  type_count++;
       
  2584         } else if (tag <= 251) {
       
  2585           // (247)     [(1)(2)]
       
  2586           // (248-251) [(1)]
       
  2587           if (tag >= 247)  offset_count++;
       
  2588           if (tag == 247)  type_count++;
       
  2589         } else if (tag <= 254) {
       
  2590           // (252)     [(1)(2)]
       
  2591           // (253)     [(1)(2)(2)]
       
  2592           // (254)     [(1)(2)(2)(2)]
       
  2593           offset_count++;
       
  2594           type_count += (tag - 251);
       
  2595         } else {
       
  2596           // (255)     [(1)NH[(2)]NH[(2)]]
       
  2597           fat_frame_count++;
       
  2598         }
       
  2599       }
       
  2600 
       
  2601       // done pre-scanning frame tags:
       
  2602       code_StackMapTable_frame_T.rewind();
       
  2603 
       
  2604       // deal completely with fat frames:
       
  2605       offset_count += fat_frame_count;
       
  2606       code_StackMapTable_local_N.readData(fat_frame_count);
       
  2607       CHECK;
       
  2608       type_count += code_StackMapTable_local_N.getIntTotal();
       
  2609       code_StackMapTable_stack_N.readData(fat_frame_count);
       
  2610       type_count += code_StackMapTable_stack_N.getIntTotal();
       
  2611       CHECK;
       
  2612       // read the rest:
       
  2613       code_StackMapTable_offset.readData(offset_count);
       
  2614       code_StackMapTable_T.readData(type_count);
       
  2615       CHECK;
       
  2616       // (7) [RCH]
       
  2617       count = code_StackMapTable_T.getIntCount(7);
       
  2618       code_StackMapTable_RC.readData(count);
       
  2619       CHECK;
       
  2620       // (8) [PH]
       
  2621       count = code_StackMapTable_T.getIntCount(8);
       
  2622       code_StackMapTable_P.readData(count);
       
  2623       CHECK;
       
  2624     }
       
  2625 
       
  2626     count = ad.predefCount(CODE_ATTR_LineNumberTable);
       
  2627     code_LineNumberTable_N.readData(count);
       
  2628     CHECK;
       
  2629     count = code_LineNumberTable_N.getIntTotal();
       
  2630     code_LineNumberTable_bci_P.readData(count);
       
  2631     code_LineNumberTable_line.readData(count);
       
  2632     CHECK;
       
  2633 
       
  2634     count = ad.predefCount(CODE_ATTR_LocalVariableTable);
       
  2635     code_LocalVariableTable_N.readData(count);
       
  2636     CHECK;
       
  2637     count = code_LocalVariableTable_N.getIntTotal();
       
  2638     code_LocalVariableTable_bci_P.readData(count);
       
  2639     code_LocalVariableTable_span_O.readData(count);
       
  2640     code_LocalVariableTable_name_RU.readData(count);
       
  2641     code_LocalVariableTable_type_RS.readData(count);
       
  2642     code_LocalVariableTable_slot.readData(count);
       
  2643     CHECK;
       
  2644 
       
  2645     count = ad.predefCount(CODE_ATTR_LocalVariableTypeTable);
       
  2646     code_LocalVariableTypeTable_N.readData(count);
       
  2647     count = code_LocalVariableTypeTable_N.getIntTotal();
       
  2648     code_LocalVariableTypeTable_bci_P.readData(count);
       
  2649     code_LocalVariableTypeTable_span_O.readData(count);
       
  2650     code_LocalVariableTypeTable_name_RU.readData(count);
       
  2651     code_LocalVariableTypeTable_type_RS.readData(count);
       
  2652     code_LocalVariableTypeTable_slot.readData(count);
       
  2653     CHECK;
       
  2654 
       
  2655     ad.readBandData(X_ATTR_RuntimeVisibleTypeAnnotations);
       
  2656     ad.readBandData(X_ATTR_RuntimeInvisibleTypeAnnotations);
       
  2657     CHECK;
       
  2658 
       
  2659     break;
       
  2660   }
       
  2661 
       
  2662   // Read compressor-defined bands.
       
  2663   for (idx = 0; idx < ad.layouts.length(); idx++) {
       
  2664     if (ad.getLayout(idx) == null)
       
  2665       continue;  // none at this fixed index <32
       
  2666     if (idx < (int)ad.flag_limit && ad.isPredefined(idx))
       
  2667       continue;  // already handled
       
  2668     if (ad.getCount(idx) == 0)
       
  2669       continue;  // no attributes of this type (then why transmit layouts?)
       
  2670     ad.readBandData(idx);
       
  2671   }
       
  2672 }
       
  2673 
       
  2674 void unpacker::attr_definitions::readBandData(int idx) {
       
  2675   int j;
       
  2676   uint count = getCount(idx);
       
  2677   if (count == 0)  return;
       
  2678   layout_definition* lo = getLayout(idx);
       
  2679   if (lo != null) {
       
  2680     PRINTCR((1, "counted %d [redefined = %d predefined = %d] attributes of type %s.%s",
       
  2681             count, isRedefined(idx), isPredefined(idx),
       
  2682             ATTR_CONTEXT_NAME[attrc], lo->name));
       
  2683   }
       
  2684   bool hasCallables = lo->hasCallables();
       
  2685   band** bands = lo->bands();
       
  2686   if (!hasCallables) {
       
  2687     // Read through the rest of the bands in a regular way.
       
  2688     readBandData(bands, count);
       
  2689   } else {
       
  2690     // Deal with the callables.
       
  2691     // First set up the forward entry count for each callable.
       
  2692     // This is stored on band::length of the callable.
       
  2693     bands[0]->expectMoreLength(count);
       
  2694     for (j = 0; bands[j] != null; j++) {
       
  2695       band& j_cble = *bands[j];
       
  2696       assert(j_cble.le_kind == EK_CBLE);
       
  2697       if (j_cble.le_back) {
       
  2698         // Add in the predicted effects of backward calls, too.
       
  2699         int back_calls = xxx_attr_calls().getInt();
       
  2700         j_cble.expectMoreLength(back_calls);
       
  2701         // In a moment, more forward calls may increment j_cble.length.
       
  2702       }
       
  2703     }
       
  2704     // Now consult whichever callables have non-zero entry counts.
       
  2705     readBandData(bands, (uint)-1);
       
  2706   }
       
  2707 }
       
  2708 
       
  2709 // Recursive helper to the previous function:
       
  2710 void unpacker::attr_definitions::readBandData(band** body, uint count) {
       
  2711   int j, k;
       
  2712   for (j = 0; body[j] != null; j++) {
       
  2713     band& b = *body[j];
       
  2714     if (b.defc != null) {
       
  2715       // It has data, so read it.
       
  2716       b.readData(count);
       
  2717     }
       
  2718     switch (b.le_kind) {
       
  2719     case EK_REPL:
       
  2720       {
       
  2721         int reps = b.getIntTotal();
       
  2722         readBandData(b.le_body, reps);
       
  2723       }
       
  2724       break;
       
  2725     case EK_UN:
       
  2726       {
       
  2727         int remaining = count;
       
  2728         for (k = 0; b.le_body[k] != null; k++) {
       
  2729           band& k_case = *b.le_body[k];
       
  2730           int   k_count = 0;
       
  2731           if (k_case.le_casetags == null) {
       
  2732             k_count = remaining;  // last (empty) case
       
  2733           } else {
       
  2734             int* tags = k_case.le_casetags;
       
  2735             int ntags = *tags++;  // 1st element is length (why not?)
       
  2736             while (ntags-- > 0) {
       
  2737               int tag = *tags++;
       
  2738               k_count += b.getIntCount(tag);
       
  2739             }
       
  2740           }
       
  2741           readBandData(k_case.le_body, k_count);
       
  2742           remaining -= k_count;
       
  2743         }
       
  2744         assert(remaining == 0);
       
  2745       }
       
  2746       break;
       
  2747     case EK_CALL:
       
  2748       // Push the count forward, if it is not a backward call.
       
  2749       if (!b.le_back) {
       
  2750         band& cble = *b.le_body[0];
       
  2751         assert(cble.le_kind == EK_CBLE);
       
  2752         cble.expectMoreLength(count);
       
  2753       }
       
  2754       break;
       
  2755     case EK_CBLE:
       
  2756       assert((int)count == -1);  // incoming count is meaningless
       
  2757       k = b.length;
       
  2758       assert(k >= 0);
       
  2759       // This is intended and required for non production mode.
       
  2760       assert((b.length = -1)); // make it unable to accept more calls now.
       
  2761       readBandData(b.le_body, k);
       
  2762       break;
       
  2763     }
       
  2764   }
       
  2765 }
       
  2766 
       
  2767 static inline
       
  2768 band** findMatchingCase(int matchTag, band** cases) {
       
  2769   for (int k = 0; cases[k] != null; k++) {
       
  2770     band& k_case = *cases[k];
       
  2771     if (k_case.le_casetags != null) {
       
  2772       // If it has tags, it must match a tag.
       
  2773       int* tags = k_case.le_casetags;
       
  2774       int ntags = *tags++;  // 1st element is length
       
  2775       for (; ntags > 0; ntags--) {
       
  2776         int tag = *tags++;
       
  2777         if (tag == matchTag)
       
  2778           break;
       
  2779       }
       
  2780       if (ntags == 0)
       
  2781         continue;   // does not match
       
  2782     }
       
  2783     return k_case.le_body;
       
  2784   }
       
  2785   return null;
       
  2786 }
       
  2787 
       
  2788 // write attribute band data:
       
  2789 void unpacker::putlayout(band** body) {
       
  2790   int i;
       
  2791   int prevBII = -1;
       
  2792   int prevBCI = -1;
       
  2793   if (body == NULL) {
       
  2794     abort("putlayout: unexpected NULL for body");
       
  2795     return;
       
  2796   }
       
  2797   for (i = 0; body[i] != null; i++) {
       
  2798     band& b = *body[i];
       
  2799     byte le_kind = b.le_kind;
       
  2800 
       
  2801     // Handle scalar part, if any.
       
  2802     int    x = 0;
       
  2803     entry* e = null;
       
  2804     if (b.defc != null) {
       
  2805       // It has data, so unparse an element.
       
  2806       if (b.ixTag != CONSTANT_None) {
       
  2807         assert(le_kind == EK_REF);
       
  2808         if (b.ixTag == CONSTANT_FieldSpecific)
       
  2809           e = b.getRefUsing(cp.getKQIndex());
       
  2810         else
       
  2811           e = b.getRefN();
       
  2812         CHECK;
       
  2813         switch (b.le_len) {
       
  2814         case 0: break;
       
  2815         case 1: putu1ref(e); break;
       
  2816         case 2: putref(e); break;
       
  2817         case 4: putu2(0); putref(e); break;
       
  2818         default: assert(false);
       
  2819         }
       
  2820       } else {
       
  2821         assert(le_kind == EK_INT || le_kind == EK_REPL || le_kind == EK_UN);
       
  2822         x = b.getInt();
       
  2823 
       
  2824         assert(!b.le_bci || prevBCI == (int)to_bci(prevBII));
       
  2825         switch (b.le_bci) {
       
  2826         case EK_BCI:   // PH:  transmit R(bci), store bci
       
  2827           x = to_bci(prevBII = x);
       
  2828           prevBCI = x;
       
  2829           break;
       
  2830         case EK_BCID:  // POH: transmit D(R(bci)), store bci
       
  2831           x = to_bci(prevBII += x);
       
  2832           prevBCI = x;
       
  2833           break;
       
  2834         case EK_BCO:   // OH:  transmit D(R(bci)), store D(bci)
       
  2835           x = to_bci(prevBII += x) - prevBCI;
       
  2836           prevBCI += x;
       
  2837           break;
       
  2838         }
       
  2839         assert(!b.le_bci || prevBCI == (int)to_bci(prevBII));
       
  2840 
       
  2841         CHECK;
       
  2842         switch (b.le_len) {
       
  2843         case 0: break;
       
  2844         case 1: putu1(x); break;
       
  2845         case 2: putu2(x); break;
       
  2846         case 4: putu4(x); break;
       
  2847         default: assert(false);
       
  2848         }
       
  2849       }
       
  2850     }
       
  2851 
       
  2852     // Handle subparts, if any.
       
  2853     switch (le_kind) {
       
  2854     case EK_REPL:
       
  2855       // x is the repeat count
       
  2856       while (x-- > 0) {
       
  2857         putlayout(b.le_body);
       
  2858       }
       
  2859       break;
       
  2860     case EK_UN:
       
  2861       // x is the tag
       
  2862       putlayout(findMatchingCase(x, b.le_body));
       
  2863       break;
       
  2864     case EK_CALL:
       
  2865       {
       
  2866         band& cble = *b.le_body[0];
       
  2867         assert(cble.le_kind == EK_CBLE);
       
  2868         assert(cble.le_len == b.le_len);
       
  2869         putlayout(cble.le_body);
       
  2870       }
       
  2871       break;
       
  2872 
       
  2873     #ifndef PRODUCT
       
  2874     case EK_CBLE:
       
  2875     case EK_CASE:
       
  2876       assert(false);  // should not reach here
       
  2877     #endif
       
  2878     }
       
  2879   }
       
  2880 }
       
  2881 
       
  2882 void unpacker::read_files() {
       
  2883   file_name.readData(file_count);
       
  2884   if (testBit(archive_options, AO_HAVE_FILE_SIZE_HI))
       
  2885     file_size_hi.readData(file_count);
       
  2886   file_size_lo.readData(file_count);
       
  2887   if (testBit(archive_options, AO_HAVE_FILE_MODTIME))
       
  2888     file_modtime.readData(file_count);
       
  2889   int allFiles = file_count + class_count;
       
  2890   if (testBit(archive_options, AO_HAVE_FILE_OPTIONS)) {
       
  2891     file_options.readData(file_count);
       
  2892     // FO_IS_CLASS_STUB might be set, causing overlap between classes and files
       
  2893     for (int i = 0; i < file_count; i++) {
       
  2894       if ((file_options.getInt() & FO_IS_CLASS_STUB) != 0) {
       
  2895         allFiles -= 1;  // this one counts as both class and file
       
  2896       }
       
  2897     }
       
  2898     file_options.rewind();
       
  2899   }
       
  2900   assert((default_file_options & FO_IS_CLASS_STUB) == 0);
       
  2901   files_remaining = allFiles;
       
  2902 }
       
  2903 
       
  2904 maybe_inline
       
  2905 void unpacker::get_code_header(int& max_stack,
       
  2906                                int& max_na_locals,
       
  2907                                int& handler_count,
       
  2908                                int& cflags) {
       
  2909   int sc = code_headers.getByte();
       
  2910   if (sc == 0) {
       
  2911     max_stack = max_na_locals = handler_count = cflags = -1;
       
  2912     return;
       
  2913   }
       
  2914   // Short code header is the usual case:
       
  2915   int nh;
       
  2916   int mod;
       
  2917   if (sc < 1 + 12*12) {
       
  2918     sc -= 1;
       
  2919     nh = 0;
       
  2920     mod = 12;
       
  2921   } else if (sc < 1 + 12*12 + 8*8) {
       
  2922     sc -= 1 + 12*12;
       
  2923     nh = 1;
       
  2924     mod = 8;
       
  2925   } else {
       
  2926     assert(sc < 1 + 12*12 + 8*8 + 7*7);
       
  2927     sc -= 1 + 12*12 + 8*8;
       
  2928     nh = 2;
       
  2929     mod = 7;
       
  2930   }
       
  2931   max_stack     = sc % mod;
       
  2932   max_na_locals = sc / mod;  // caller must add static, siglen
       
  2933   handler_count = nh;
       
  2934   if (testBit(archive_options, AO_HAVE_ALL_CODE_FLAGS))
       
  2935     cflags      = -1;
       
  2936   else
       
  2937     cflags      = 0;  // this one has no attributes
       
  2938 }
       
  2939 
       
  2940 // Cf. PackageReader.readCodeHeaders
       
  2941 void unpacker::read_code_headers() {
       
  2942   code_headers.readData(code_count);
       
  2943   CHECK;
       
  2944   int totalHandlerCount = 0;
       
  2945   int totalFlagsCount   = 0;
       
  2946   for (int i = 0; i < code_count; i++) {
       
  2947     int max_stack, max_locals, handler_count, cflags;
       
  2948     get_code_header(max_stack, max_locals, handler_count, cflags);
       
  2949     if (max_stack < 0)      code_max_stack.expectMoreLength(1);
       
  2950     if (max_locals < 0)     code_max_na_locals.expectMoreLength(1);
       
  2951     if (handler_count < 0)  code_handler_count.expectMoreLength(1);
       
  2952     else                    totalHandlerCount += handler_count;
       
  2953     if (cflags < 0)         totalFlagsCount += 1;
       
  2954   }
       
  2955   code_headers.rewind();  // replay later during writing
       
  2956 
       
  2957   code_max_stack.readData();
       
  2958   code_max_na_locals.readData();
       
  2959   code_handler_count.readData();
       
  2960   totalHandlerCount += code_handler_count.getIntTotal();
       
  2961   CHECK;
       
  2962 
       
  2963   // Read handler specifications.
       
  2964   // Cf. PackageReader.readCodeHandlers.
       
  2965   code_handler_start_P.readData(totalHandlerCount);
       
  2966   code_handler_end_PO.readData(totalHandlerCount);
       
  2967   code_handler_catch_PO.readData(totalHandlerCount);
       
  2968   code_handler_class_RCN.readData(totalHandlerCount);
       
  2969   CHECK;
       
  2970 
       
  2971   read_attrs(ATTR_CONTEXT_CODE, totalFlagsCount);
       
  2972   CHECK;
       
  2973 }
       
  2974 
       
  2975 static inline bool is_in_range(uint n, uint min, uint max) {
       
  2976   return n - min <= max - min;  // unsigned arithmetic!
       
  2977 }
       
  2978 static inline bool is_field_op(int bc) {
       
  2979   return is_in_range(bc, bc_getstatic, bc_putfield);
       
  2980 }
       
  2981 static inline bool is_invoke_init_op(int bc) {
       
  2982   return is_in_range(bc, _invokeinit_op, _invokeinit_limit-1);
       
  2983 }
       
  2984 static inline bool is_self_linker_op(int bc) {
       
  2985   return is_in_range(bc, _self_linker_op, _self_linker_limit-1);
       
  2986 }
       
  2987 static bool is_branch_op(int bc) {
       
  2988   return is_in_range(bc, bc_ifeq,   bc_jsr)
       
  2989       || is_in_range(bc, bc_ifnull, bc_jsr_w);
       
  2990 }
       
  2991 static bool is_local_slot_op(int bc) {
       
  2992   return is_in_range(bc, bc_iload,  bc_aload)
       
  2993       || is_in_range(bc, bc_istore, bc_astore)
       
  2994       || bc == bc_iinc || bc == bc_ret;
       
  2995 }
       
  2996 band* unpacker::ref_band_for_op(int bc) {
       
  2997   switch (bc) {
       
  2998   case bc_ildc:
       
  2999   case bc_ildc_w:
       
  3000     return &bc_intref;
       
  3001   case bc_fldc:
       
  3002   case bc_fldc_w:
       
  3003     return &bc_floatref;
       
  3004   case bc_lldc2_w:
       
  3005     return &bc_longref;
       
  3006   case bc_dldc2_w:
       
  3007     return &bc_doubleref;
       
  3008   case bc_sldc:
       
  3009   case bc_sldc_w:
       
  3010     return &bc_stringref;
       
  3011   case bc_cldc:
       
  3012   case bc_cldc_w:
       
  3013     return &bc_classref;
       
  3014   case bc_qldc: case bc_qldc_w:
       
  3015     return &bc_loadablevalueref;
       
  3016 
       
  3017   case bc_getstatic:
       
  3018   case bc_putstatic:
       
  3019   case bc_getfield:
       
  3020   case bc_putfield:
       
  3021     return &bc_fieldref;
       
  3022 
       
  3023   case _invokespecial_int:
       
  3024   case _invokestatic_int:
       
  3025     return &bc_imethodref;
       
  3026   case bc_invokevirtual:
       
  3027   case bc_invokespecial:
       
  3028   case bc_invokestatic:
       
  3029     return &bc_methodref;
       
  3030   case bc_invokeinterface:
       
  3031     return &bc_imethodref;
       
  3032   case bc_invokedynamic:
       
  3033     return &bc_indyref;
       
  3034 
       
  3035   case bc_new:
       
  3036   case bc_anewarray:
       
  3037   case bc_checkcast:
       
  3038   case bc_instanceof:
       
  3039   case bc_multianewarray:
       
  3040     return &bc_classref;
       
  3041   }
       
  3042   return null;
       
  3043 }
       
  3044 
       
  3045 maybe_inline
       
  3046 band* unpacker::ref_band_for_self_op(int bc, bool& isAloadVar, int& origBCVar) {
       
  3047   if (!is_self_linker_op(bc))  return null;
       
  3048   int idx = (bc - _self_linker_op);
       
  3049   bool isSuper = (idx >= _self_linker_super_flag);
       
  3050   if (isSuper)  idx -= _self_linker_super_flag;
       
  3051   bool isAload = (idx >= _self_linker_aload_flag);
       
  3052   if (isAload)  idx -= _self_linker_aload_flag;
       
  3053   int origBC = _first_linker_op + idx;
       
  3054   bool isField = is_field_op(origBC);
       
  3055   isAloadVar = isAload;
       
  3056   origBCVar  = _first_linker_op + idx;
       
  3057   if (!isSuper)
       
  3058     return isField? &bc_thisfield: &bc_thismethod;
       
  3059   else
       
  3060     return isField? &bc_superfield: &bc_supermethod;
       
  3061 }
       
  3062 
       
  3063 // Cf. PackageReader.readByteCodes
       
  3064 inline  // called exactly once => inline
       
  3065 void unpacker::read_bcs() {
       
  3066   PRINTCR((3, "reading compressed bytecodes and operands for %d codes...",
       
  3067           code_count));
       
  3068 
       
  3069   // read from bc_codes and bc_case_count
       
  3070   fillbytes all_switch_ops;
       
  3071   all_switch_ops.init();
       
  3072   CHECK;
       
  3073 
       
  3074   // Read directly from rp/rplimit.
       
  3075   //Do this later:  bc_codes.readData(...)
       
  3076   byte* rp0 = rp;
       
  3077 
       
  3078   band* bc_which;
       
  3079   byte* opptr = rp;
       
  3080   byte* oplimit = rplimit;
       
  3081 
       
  3082   bool  isAload;  // passed by ref and then ignored
       
  3083   int   junkBC;   // passed by ref and then ignored
       
  3084   for (int k = 0; k < code_count; k++) {
       
  3085     // Scan one method:
       
  3086     for (;;) {
       
  3087       if (opptr+2 > oplimit) {
       
  3088         rp = opptr;
       
  3089         ensure_input(2);
       
  3090         oplimit = rplimit;
       
  3091         rp = rp0;  // back up
       
  3092       }
       
  3093       if (opptr == oplimit) { abort(); break; }
       
  3094       int bc = *opptr++ & 0xFF;
       
  3095       bool isWide = false;
       
  3096       if (bc == bc_wide) {
       
  3097         if (opptr == oplimit) { abort(); break; }
       
  3098         bc = *opptr++ & 0xFF;
       
  3099         isWide = true;
       
  3100       }
       
  3101       // Adjust expectations of various band sizes.
       
  3102       switch (bc) {
       
  3103       case bc_tableswitch:
       
  3104       case bc_lookupswitch:
       
  3105         all_switch_ops.addByte(bc);
       
  3106         break;
       
  3107       case bc_iinc:
       
  3108         bc_local.expectMoreLength(1);
       
  3109         bc_which = isWide ? &bc_short : &bc_byte;
       
  3110         bc_which->expectMoreLength(1);
       
  3111         break;
       
  3112       case bc_sipush:
       
  3113         bc_short.expectMoreLength(1);
       
  3114         break;
       
  3115       case bc_bipush:
       
  3116         bc_byte.expectMoreLength(1);
       
  3117         break;
       
  3118       case bc_newarray:
       
  3119         bc_byte.expectMoreLength(1);
       
  3120         break;
       
  3121       case bc_multianewarray:
       
  3122         assert(ref_band_for_op(bc) == &bc_classref);
       
  3123         bc_classref.expectMoreLength(1);
       
  3124         bc_byte.expectMoreLength(1);
       
  3125         break;
       
  3126       case bc_ref_escape:
       
  3127         bc_escrefsize.expectMoreLength(1);
       
  3128         bc_escref.expectMoreLength(1);
       
  3129         break;
       
  3130       case bc_byte_escape:
       
  3131         bc_escsize.expectMoreLength(1);
       
  3132         // bc_escbyte will have to be counted too
       
  3133         break;
       
  3134       default:
       
  3135         if (is_invoke_init_op(bc)) {
       
  3136           bc_initref.expectMoreLength(1);
       
  3137           break;
       
  3138         }
       
  3139         bc_which = ref_band_for_self_op(bc, isAload, junkBC);
       
  3140         if (bc_which != null) {
       
  3141           bc_which->expectMoreLength(1);
       
  3142           break;
       
  3143         }
       
  3144         if (is_branch_op(bc)) {
       
  3145           bc_label.expectMoreLength(1);
       
  3146           break;
       
  3147         }
       
  3148         bc_which = ref_band_for_op(bc);
       
  3149         if (bc_which != null) {
       
  3150           bc_which->expectMoreLength(1);
       
  3151           assert(bc != bc_multianewarray);  // handled elsewhere
       
  3152           break;
       
  3153         }
       
  3154         if (is_local_slot_op(bc)) {
       
  3155           bc_local.expectMoreLength(1);
       
  3156           break;
       
  3157         }
       
  3158         break;
       
  3159       case bc_end_marker:
       
  3160         // Increment k and test against code_count.
       
  3161         goto doneScanningMethod;
       
  3162       }
       
  3163     }
       
  3164   doneScanningMethod:{}
       
  3165     if (aborting())  break;
       
  3166   }
       
  3167 
       
  3168   // Go through the formality, so we can use it in a regular fashion later:
       
  3169   assert(rp == rp0);
       
  3170   bc_codes.readData((int)(opptr - rp));
       
  3171 
       
  3172   int i = 0;
       
  3173 
       
  3174   // To size instruction bands correctly, we need info on switches:
       
  3175   bc_case_count.readData((int)all_switch_ops.size());
       
  3176   for (i = 0; i < (int)all_switch_ops.size(); i++) {
       
  3177     int caseCount = bc_case_count.getInt();
       
  3178     int bc        = all_switch_ops.getByte(i);
       
  3179     bc_label.expectMoreLength(1+caseCount); // default label + cases
       
  3180     bc_case_value.expectMoreLength(bc == bc_tableswitch ? 1 : caseCount);
       
  3181     PRINTCR((2, "switch bc=%d caseCount=%d", bc, caseCount));
       
  3182   }
       
  3183   bc_case_count.rewind();  // uses again for output
       
  3184 
       
  3185   all_switch_ops.free();
       
  3186 
       
  3187   for (i = e_bc_case_value; i <= e_bc_escsize; i++) {
       
  3188     all_bands[i].readData();
       
  3189   }
       
  3190 
       
  3191   // The bc_escbyte band is counted by the immediately previous band.
       
  3192   bc_escbyte.readData(bc_escsize.getIntTotal());
       
  3193 
       
  3194   PRINTCR((3, "scanned %d opcode and %d operand bytes for %d codes...",
       
  3195           (int)(bc_codes.size()),
       
  3196           (int)(bc_escsize.maxRP() - bc_case_value.minRP()),
       
  3197           code_count));
       
  3198 }
       
  3199 
       
  3200 void unpacker::read_bands() {
       
  3201   byte* rp0 = rp;
       
  3202   CHECK;
       
  3203   read_file_header();
       
  3204   CHECK;
       
  3205 
       
  3206   if (cp.nentries == 0) {
       
  3207     // read_file_header failed to read a CP, because it copied a JAR.
       
  3208     return;
       
  3209   }
       
  3210 
       
  3211   // Do this after the file header has been read:
       
  3212   check_options();
       
  3213 
       
  3214   read_cp();
       
  3215   CHECK;
       
  3216   read_attr_defs();
       
  3217   CHECK;
       
  3218   read_ics();
       
  3219   CHECK;
       
  3220   read_classes();
       
  3221   CHECK;
       
  3222   read_bcs();
       
  3223   CHECK;
       
  3224   read_files();
       
  3225 }
       
  3226 
       
  3227 /// CP routines
       
  3228 
       
  3229 entry*& cpool::hashTabRef(byte tag, bytes& b) {
       
  3230   PRINTCR((5, "hashTabRef tag=%d %s[%d]", tag, b.string(), b.len));
       
  3231   uint hash = tag + (int)b.len;
       
  3232   for (int i = 0; i < (int)b.len; i++) {
       
  3233     hash = hash * 31 + (0xFF & b.ptr[i]);
       
  3234   }
       
  3235   entry**  ht = hashTab;
       
  3236   int    hlen = hashTabLength;
       
  3237   assert((hlen & (hlen-1)) == 0);  // must be power of 2
       
  3238   uint hash1 = hash & (hlen-1);    // == hash % hlen
       
  3239   uint hash2 = 0;                  // lazily computed (requires mod op.)
       
  3240   int probes = 0;
       
  3241   while (ht[hash1] != null) {
       
  3242     entry& e = *ht[hash1];
       
  3243     if (e.value.b.equals(b) && e.tag == tag)
       
  3244       break;
       
  3245     if (hash2 == 0)
       
  3246       // Note:  hash2 must be relatively prime to hlen, hence the "|1".
       
  3247       hash2 = (((hash % 499) & (hlen-1)) | 1);
       
  3248     hash1 += hash2;
       
  3249     if (hash1 >= (uint)hlen)  hash1 -= hlen;
       
  3250     assert(hash1 < (uint)hlen);
       
  3251     assert(++probes < hlen);
       
  3252   }
       
  3253   #ifndef PRODUCT
       
  3254   hash_probes[0] += 1;
       
  3255   hash_probes[1] += probes;
       
  3256   #endif
       
  3257   PRINTCR((5, " => @%d %p", hash1, ht[hash1]));
       
  3258   return ht[hash1];
       
  3259 }
       
  3260 
       
  3261 maybe_inline
       
  3262 static void insert_extra(entry* e, ptrlist& extras) {
       
  3263   // This ordering helps implement the Pack200 requirement
       
  3264   // of a predictable CP order in the class files produced.
       
  3265   e->inord = NO_INORD;  // mark as an "extra"
       
  3266   extras.add(e);
       
  3267   // Note:  We will sort the list (by string-name) later.
       
  3268 }
       
  3269 
       
  3270 entry* cpool::ensureUtf8(bytes& b) {
       
  3271   entry*& ix = hashTabRef(CONSTANT_Utf8, b);
       
  3272   if (ix != null)  return ix;
       
  3273   // Make one.
       
  3274   if (nentries == maxentries) {
       
  3275     abort("cp utf8 overflow");
       
  3276     return &entries[tag_base[CONSTANT_Utf8]];  // return something
       
  3277   }
       
  3278   entry& e = entries[nentries++];
       
  3279   e.tag = CONSTANT_Utf8;
       
  3280   u->saveTo(e.value.b, b);
       
  3281   assert(&e >= first_extra_entry);
       
  3282   insert_extra(&e, tag_extras[CONSTANT_Utf8]);
       
  3283   PRINTCR((4,"ensureUtf8 miss %s", e.string()));
       
  3284   return ix = &e;
       
  3285 }
       
  3286 
       
  3287 entry* cpool::ensureClass(bytes& b) {
       
  3288   entry*& ix = hashTabRef(CONSTANT_Class, b);
       
  3289   if (ix != null)  return ix;
       
  3290   // Make one.
       
  3291   if (nentries == maxentries) {
       
  3292     abort("cp class overflow");
       
  3293     return &entries[tag_base[CONSTANT_Class]];  // return something
       
  3294   }
       
  3295   entry& e = entries[nentries++];
       
  3296   e.tag = CONSTANT_Class;
       
  3297   e.nrefs = 1;
       
  3298   e.refs = U_NEW(entry*, 1);
       
  3299   ix = &e;  // hold my spot in the index
       
  3300   entry* utf = ensureUtf8(b);
       
  3301   e.refs[0] = utf;
       
  3302   e.value.b = utf->value.b;
       
  3303   assert(&e >= first_extra_entry);
       
  3304   insert_extra(&e, tag_extras[CONSTANT_Class]);
       
  3305   PRINTCR((4,"ensureClass miss %s", e.string()));
       
  3306   return &e;
       
  3307 }
       
  3308 
       
  3309 void cpool::expandSignatures() {
       
  3310   int i;
       
  3311   int nsigs = 0;
       
  3312   int nreused = 0;
       
  3313   int first_sig = tag_base[CONSTANT_Signature];
       
  3314   int sig_limit = tag_count[CONSTANT_Signature] + first_sig;
       
  3315   fillbytes buf;
       
  3316   buf.init(1<<10);
       
  3317   CHECK;
       
  3318   for (i = first_sig; i < sig_limit; i++) {
       
  3319     entry& e = entries[i];
       
  3320     assert(e.tag == CONSTANT_Signature);
       
  3321     int refnum = 0;
       
  3322     bytes form = e.refs[refnum++]->asUtf8();
       
  3323     buf.empty();
       
  3324     for (int j = 0; j < (int)form.len; j++) {
       
  3325       int c = form.ptr[j];
       
  3326       buf.addByte(c);
       
  3327       if (c == 'L') {
       
  3328         entry* cls = e.refs[refnum++];
       
  3329         buf.append(cls->className()->asUtf8());
       
  3330       }
       
  3331     }
       
  3332     assert(refnum == e.nrefs);
       
  3333     bytes& sig = buf.b;
       
  3334     PRINTCR((5,"signature %d %s -> %s", i, form.ptr, sig.ptr));
       
  3335 
       
  3336     // try to find a pre-existing Utf8:
       
  3337     entry* &e2 = hashTabRef(CONSTANT_Utf8, sig);
       
  3338     if (e2 != null) {
       
  3339       assert(e2->isUtf8(sig));
       
  3340       e.value.b = e2->value.b;
       
  3341       e.refs[0] = e2;
       
  3342       e.nrefs = 1;
       
  3343       PRINTCR((5,"signature replaced %d => %s", i, e.string()));
       
  3344       nreused++;
       
  3345     } else {
       
  3346       // there is no other replacement; reuse this CP entry as a Utf8
       
  3347       u->saveTo(e.value.b, sig);
       
  3348       e.tag = CONSTANT_Utf8;
       
  3349       e.nrefs = 0;
       
  3350       e2 = &e;
       
  3351       PRINTCR((5,"signature changed %d => %s", e.inord, e.string()));
       
  3352     }
       
  3353     nsigs++;
       
  3354   }
       
  3355   PRINTCR((1,"expanded %d signatures (reused %d utfs)", nsigs, nreused));
       
  3356   buf.free();
       
  3357 
       
  3358   // go expunge all references to remaining signatures:
       
  3359   for (i = 0; i < (int)nentries; i++) {
       
  3360     entry& e = entries[i];
       
  3361     for (int j = 0; j < e.nrefs; j++) {
       
  3362       entry*& e2 = e.refs[j];
       
  3363       if (e2 != null && e2->tag == CONSTANT_Signature)
       
  3364         e2 = e2->refs[0];
       
  3365     }
       
  3366   }
       
  3367 }
       
  3368 
       
  3369 bool isLoadableValue(int tag) {
       
  3370   switch(tag) {
       
  3371     case CONSTANT_Integer:
       
  3372     case CONSTANT_Float:
       
  3373     case CONSTANT_Long:
       
  3374     case CONSTANT_Double:
       
  3375     case CONSTANT_String:
       
  3376     case CONSTANT_Class:
       
  3377     case CONSTANT_MethodHandle:
       
  3378     case CONSTANT_MethodType:
       
  3379       return true;
       
  3380     default:
       
  3381       return false;
       
  3382   }
       
  3383 }
       
  3384 /*
       
  3385  * this method can be used to size an array using null as the parameter,
       
  3386  * thereafter can be reused to initialize the array using a valid pointer
       
  3387  * as a parameter.
       
  3388  */
       
  3389 int cpool::initLoadableValues(entry** loadable_entries) {
       
  3390   int loadable_count = 0;
       
  3391   for (int i = 0; i < (int)N_TAGS_IN_ORDER; i++) {
       
  3392     int tag = TAGS_IN_ORDER[i];
       
  3393     if (!isLoadableValue(tag))
       
  3394       continue;
       
  3395     if (loadable_entries != NULL) {
       
  3396       for (int n = 0 ; n < tag_count[tag] ; n++) {
       
  3397         loadable_entries[loadable_count + n] = &entries[tag_base[tag] + n];
       
  3398       }
       
  3399     }
       
  3400     loadable_count += tag_count[tag];
       
  3401   }
       
  3402   return loadable_count;
       
  3403 }
       
  3404 
       
  3405 // Initialize various views into the constant pool.
       
  3406 void cpool::initGroupIndexes() {
       
  3407   // Initialize All
       
  3408   int all_count = 0;
       
  3409   for (int tag = CONSTANT_None ; tag < CONSTANT_Limit ; tag++) {
       
  3410     all_count += tag_count[tag];
       
  3411   }
       
  3412   entry* all_entries = &entries[tag_base[CONSTANT_None]];
       
  3413   tag_group_count[CONSTANT_All - CONSTANT_All] = all_count;
       
  3414   tag_group_index[CONSTANT_All - CONSTANT_All].init(all_count, all_entries, CONSTANT_All);
       
  3415 
       
  3416   // Initialize LoadableValues
       
  3417   int loadable_count = initLoadableValues(NULL);
       
  3418   entry** loadable_entries = U_NEW(entry*, loadable_count);
       
  3419   initLoadableValues(loadable_entries);
       
  3420   tag_group_count[CONSTANT_LoadableValue - CONSTANT_All] = loadable_count;
       
  3421   tag_group_index[CONSTANT_LoadableValue - CONSTANT_All].init(loadable_count,
       
  3422                   loadable_entries, CONSTANT_LoadableValue);
       
  3423 
       
  3424 // Initialize AnyMembers
       
  3425   int any_count = tag_count[CONSTANT_Fieldref] +
       
  3426                   tag_count[CONSTANT_Methodref] +
       
  3427                   tag_count[CONSTANT_InterfaceMethodref];
       
  3428   entry *any_entries = &entries[tag_base[CONSTANT_Fieldref]];
       
  3429   tag_group_count[CONSTANT_AnyMember - CONSTANT_All] = any_count;
       
  3430   tag_group_index[CONSTANT_AnyMember - CONSTANT_All].init(any_count,
       
  3431                                                any_entries, CONSTANT_AnyMember);
       
  3432 }
       
  3433 
       
  3434 void cpool::initMemberIndexes() {
       
  3435   // This function does NOT refer to any class schema.
       
  3436   // It is totally internal to the cpool.
       
  3437   int i, j;
       
  3438 
       
  3439   // Get the pre-existing indexes:
       
  3440   int   nclasses = tag_count[CONSTANT_Class];
       
  3441   entry* classes = tag_base[CONSTANT_Class] + entries;
       
  3442   int   nfields  = tag_count[CONSTANT_Fieldref];
       
  3443   entry* fields  = tag_base[CONSTANT_Fieldref] + entries;
       
  3444   int   nmethods = tag_count[CONSTANT_Methodref];
       
  3445   entry* methods = tag_base[CONSTANT_Methodref] + entries;
       
  3446 
       
  3447   int*     field_counts  = T_NEW(int, nclasses);
       
  3448   int*     method_counts = T_NEW(int, nclasses);
       
  3449   cpindex* all_indexes   = U_NEW(cpindex, nclasses*2);
       
  3450   entry**  field_ix      = U_NEW(entry*, add_size(nfields, nclasses));
       
  3451   entry**  method_ix     = U_NEW(entry*, add_size(nmethods, nclasses));
       
  3452 
       
  3453   for (j = 0; j < nfields; j++) {
       
  3454     entry& f = fields[j];
       
  3455     i = f.memberClass()->inord;
       
  3456     assert(i < nclasses);
       
  3457     field_counts[i]++;
       
  3458   }
       
  3459   for (j = 0; j < nmethods; j++) {
       
  3460     entry& m = methods[j];
       
  3461     i = m.memberClass()->inord;
       
  3462     assert(i < nclasses);
       
  3463     method_counts[i]++;
       
  3464   }
       
  3465 
       
  3466   int fbase = 0, mbase = 0;
       
  3467   for (i = 0; i < nclasses; i++) {
       
  3468     int fc = field_counts[i];
       
  3469     int mc = method_counts[i];
       
  3470     all_indexes[i*2+0].init(fc, field_ix+fbase,
       
  3471                             CONSTANT_Fieldref  + SUBINDEX_BIT);
       
  3472     all_indexes[i*2+1].init(mc, method_ix+mbase,
       
  3473                             CONSTANT_Methodref + SUBINDEX_BIT);
       
  3474     // reuse field_counts and member_counts as fill pointers:
       
  3475     field_counts[i] = fbase;
       
  3476     method_counts[i] = mbase;
       
  3477     PRINTCR((3, "class %d fields @%d[%d] methods @%d[%d]",
       
  3478             i, fbase, fc, mbase, mc));
       
  3479     fbase += fc+1;
       
  3480     mbase += mc+1;
       
  3481     // (the +1 leaves a space between every subarray)
       
  3482   }
       
  3483   assert(fbase == nfields+nclasses);
       
  3484   assert(mbase == nmethods+nclasses);
       
  3485 
       
  3486   for (j = 0; j < nfields; j++) {
       
  3487     entry& f = fields[j];
       
  3488     i = f.memberClass()->inord;
       
  3489     field_ix[field_counts[i]++] = &f;
       
  3490   }
       
  3491   for (j = 0; j < nmethods; j++) {
       
  3492     entry& m = methods[j];
       
  3493     i = m.memberClass()->inord;
       
  3494     method_ix[method_counts[i]++] = &m;
       
  3495   }
       
  3496 
       
  3497   member_indexes = all_indexes;
       
  3498 
       
  3499 #ifndef PRODUCT
       
  3500   // Test the result immediately on every class and field.
       
  3501   int fvisited = 0, mvisited = 0;
       
  3502   int prevord, len;
       
  3503   for (i = 0; i < nclasses; i++) {
       
  3504     entry*   cls = &classes[i];
       
  3505     cpindex* fix = getFieldIndex(cls);
       
  3506     cpindex* mix = getMethodIndex(cls);
       
  3507     PRINTCR((2, "field and method index for %s [%d] [%d]",
       
  3508             cls->string(), mix->len, fix->len));
       
  3509     prevord = -1;
       
  3510     for (j = 0, len = fix->len; j < len; j++) {
       
  3511       entry* f = fix->get(j);
       
  3512       assert(f != null);
       
  3513       PRINTCR((3, "- field %s", f->string()));
       
  3514       assert(f->memberClass() == cls);
       
  3515       assert(prevord < (int)f->inord);
       
  3516       prevord = f->inord;
       
  3517       fvisited++;
       
  3518     }
       
  3519     assert(fix->base2[j] == null);
       
  3520     prevord = -1;
       
  3521     for (j = 0, len = mix->len; j < len; j++) {
       
  3522       entry* m = mix->get(j);
       
  3523       assert(m != null);
       
  3524       PRINTCR((3, "- method %s", m->string()));
       
  3525       assert(m->memberClass() == cls);
       
  3526       assert(prevord < (int)m->inord);
       
  3527       prevord = m->inord;
       
  3528       mvisited++;
       
  3529     }
       
  3530     assert(mix->base2[j] == null);
       
  3531   }
       
  3532   assert(fvisited == nfields);
       
  3533   assert(mvisited == nmethods);
       
  3534 #endif
       
  3535 
       
  3536   // Free intermediate buffers.
       
  3537   u->free_temps();
       
  3538 }
       
  3539 
       
  3540 void entry::requestOutputIndex(cpool& cp, int req) {
       
  3541   assert(outputIndex <= REQUESTED_NONE);  // must not have assigned indexes yet
       
  3542   if (tag == CONSTANT_Signature) {
       
  3543     ref(0)->requestOutputIndex(cp, req);
       
  3544     return;
       
  3545   }
       
  3546   assert(req == REQUESTED || req == REQUESTED_LDC);
       
  3547   if (outputIndex != REQUESTED_NONE) {
       
  3548     if (req == REQUESTED_LDC)
       
  3549       outputIndex = req;  // this kind has precedence
       
  3550     return;
       
  3551   }
       
  3552   outputIndex = req;
       
  3553   //assert(!cp.outputEntries.contains(this));
       
  3554   assert(tag != CONSTANT_Signature);
       
  3555   // The BSMs are jetisoned to a side table, however all references
       
  3556   // that the BSMs refer to,  need to be considered.
       
  3557   if (tag == CONSTANT_BootstrapMethod) {
       
  3558     // this is a a pseudo-op entry; an attribute will be generated later on
       
  3559     cp.requested_bsms.add(this);
       
  3560   } else {
       
  3561     // all other tag types go into real output file CP:
       
  3562     cp.outputEntries.add(this);
       
  3563   }
       
  3564   for (int j = 0; j < nrefs; j++) {
       
  3565     ref(j)->requestOutputIndex(cp);
       
  3566   }
       
  3567 }
       
  3568 
       
  3569 void cpool::resetOutputIndexes() {
       
  3570     /*
       
  3571      * reset those few entries that are being used in the current class
       
  3572      * (Caution since this method is called after every class written, a loop
       
  3573      * over every global constant pool entry would be a quadratic cost.)
       
  3574      */
       
  3575 
       
  3576   int noes    = outputEntries.length();
       
  3577   entry** oes = (entry**) outputEntries.base();
       
  3578   for (int i = 0 ; i < noes ; i++) {
       
  3579     entry& e = *oes[i];
       
  3580     e.outputIndex = REQUESTED_NONE;
       
  3581   }
       
  3582 
       
  3583   // do the same for bsms and reset them if required
       
  3584   int nbsms = requested_bsms.length();
       
  3585   entry** boes = (entry**) requested_bsms.base();
       
  3586   for (int i = 0 ; i < nbsms ; i++) {
       
  3587     entry& e = *boes[i];
       
  3588     e.outputIndex = REQUESTED_NONE;
       
  3589   }
       
  3590   outputIndexLimit = 0;
       
  3591   outputEntries.empty();
       
  3592 #ifndef PRODUCT
       
  3593   // ensure things are cleared out
       
  3594   for (int i = 0; i < (int)maxentries; i++)
       
  3595     assert(entries[i].outputIndex == REQUESTED_NONE);
       
  3596 #endif
       
  3597 }
       
  3598 
       
  3599 static const byte TAG_ORDER[CONSTANT_Limit] = {
       
  3600   0, 1, 0, 2, 3, 4, 5, 7, 6, 10, 11, 12, 9, 8, 0, 13, 14, 15, 16
       
  3601 };
       
  3602 
       
  3603 extern "C"
       
  3604 int outputEntry_cmp(const void* e1p, const void* e2p) {
       
  3605   // Sort entries according to the Pack200 rules for deterministic
       
  3606   // constant pool ordering.
       
  3607   //
       
  3608   // The four sort keys as follows, in order of decreasing importance:
       
  3609   //   1. ldc first, then non-ldc guys
       
  3610   //   2. normal cp_All entries by input order (i.e., address order)
       
  3611   //   3. after that, extra entries by lexical order (as in tag_extras[*])
       
  3612   entry& e1 = *(entry*) *(void**) e1p;
       
  3613   entry& e2 = *(entry*) *(void**) e2p;
       
  3614   int   oi1 = e1.outputIndex;
       
  3615   int   oi2 = e2.outputIndex;
       
  3616   assert(oi1 == REQUESTED || oi1 == REQUESTED_LDC);
       
  3617   assert(oi2 == REQUESTED || oi2 == REQUESTED_LDC);
       
  3618   if (oi1 != oi2) {
       
  3619     if (oi1 == REQUESTED_LDC)  return 0-1;
       
  3620     if (oi2 == REQUESTED_LDC)  return 1-0;
       
  3621     // Else fall through; neither is an ldc request.
       
  3622   }
       
  3623   if (e1.inord != NO_INORD || e2.inord != NO_INORD) {
       
  3624     // One or both is normal.  Use input order.
       
  3625     if (&e1 > &e2)  return 1-0;
       
  3626     if (&e1 < &e2)  return 0-1;
       
  3627     return 0;  // equal pointers
       
  3628   }
       
  3629   // Both are extras.  Sort by tag and then by value.
       
  3630   if (e1.tag != e2.tag) {
       
  3631     return TAG_ORDER[e1.tag] - TAG_ORDER[e2.tag];
       
  3632   }
       
  3633   // If the tags are the same, use string comparison.
       
  3634   return compare_Utf8_chars(e1.value.b, e2.value.b);
       
  3635 }
       
  3636 
       
  3637 void cpool::computeOutputIndexes() {
       
  3638   int i;
       
  3639 
       
  3640 #ifndef PRODUCT
       
  3641   // outputEntries must be a complete list of those requested:
       
  3642   static uint checkStart = 0;
       
  3643   int checkStep = 1;
       
  3644   if (nentries > 100)  checkStep = nentries / 100;
       
  3645   for (i = (int)(checkStart++ % checkStep); i < (int)nentries; i += checkStep) {
       
  3646     entry& e = entries[i];
       
  3647     if (e.tag == CONSTANT_BootstrapMethod) {
       
  3648       if (e.outputIndex != REQUESTED_NONE) {
       
  3649         assert(requested_bsms.contains(&e));
       
  3650       } else {
       
  3651         assert(!requested_bsms.contains(&e));
       
  3652       }
       
  3653     } else {
       
  3654       if (e.outputIndex != REQUESTED_NONE) {
       
  3655         assert(outputEntries.contains(&e));
       
  3656       } else {
       
  3657         assert(!outputEntries.contains(&e));
       
  3658       }
       
  3659     }
       
  3660   }
       
  3661 
       
  3662   // check hand-initialization of TAG_ORDER
       
  3663   for (i = 0; i < (int)N_TAGS_IN_ORDER; i++) {
       
  3664     byte tag = TAGS_IN_ORDER[i];
       
  3665     assert(TAG_ORDER[tag] == i+1);
       
  3666   }
       
  3667 #endif
       
  3668 
       
  3669   int    noes =           outputEntries.length();
       
  3670   entry** oes = (entry**) outputEntries.base();
       
  3671 
       
  3672   // Sort the output constant pool into the order required by Pack200.
       
  3673   PTRLIST_QSORT(outputEntries, outputEntry_cmp);
       
  3674 
       
  3675   // Allocate a new index for each entry that needs one.
       
  3676   // We do this in two passes, one for LDC entries and one for the rest.
       
  3677   int nextIndex = 1;  // always skip index #0 in output cpool
       
  3678   for (i = 0; i < noes; i++) {
       
  3679     entry& e = *oes[i];
       
  3680     assert(e.outputIndex >= REQUESTED_LDC);
       
  3681     e.outputIndex = nextIndex++;
       
  3682     if (e.isDoubleWord())  nextIndex++;  // do not use the next index
       
  3683   }
       
  3684   outputIndexLimit = nextIndex;
       
  3685   PRINTCR((3,"renumbering CP to %d entries", outputIndexLimit));
       
  3686 }
       
  3687 
       
  3688 #ifndef PRODUCT
       
  3689 // debugging goo
       
  3690 
       
  3691 unpacker* debug_u;
       
  3692 
       
  3693 static bytes& getbuf(size_t len) {  // for debugging only!
       
  3694   static int bn = 0;
       
  3695   static bytes bufs[8];
       
  3696   bytes& buf = bufs[bn++ & 7];
       
  3697   while (buf.len < len + 10) {
       
  3698     buf.realloc(buf.len ? buf.len * 2 : 1000);
       
  3699   }
       
  3700   buf.ptr[0] = 0;  // for the sake of strcat
       
  3701   return buf;
       
  3702 }
       
  3703 
       
  3704 const char* entry::string() {
       
  3705   bytes buf;
       
  3706   switch (tag) {
       
  3707   case CONSTANT_None:
       
  3708     return "<empty>";
       
  3709   case CONSTANT_Signature:
       
  3710     if (value.b.ptr == null)
       
  3711       return ref(0)->string();
       
  3712     // else fall through:
       
  3713   case CONSTANT_Utf8:
       
  3714     buf = value.b;
       
  3715     break;
       
  3716   case CONSTANT_Integer:
       
  3717   case CONSTANT_Float:
       
  3718     buf = getbuf(12);
       
  3719     sprintf((char*)buf.ptr, "0x%08x", value.i);
       
  3720     break;
       
  3721   case CONSTANT_Long:
       
  3722   case CONSTANT_Double:
       
  3723     buf = getbuf(24);
       
  3724     sprintf((char*)buf.ptr, "0x" LONG_LONG_HEX_FORMAT, value.l);
       
  3725     break;
       
  3726   default:
       
  3727     if (nrefs == 0) {
       
  3728       return TAG_NAME[tag];
       
  3729     } else if (nrefs == 1) {
       
  3730       return refs[0]->string();
       
  3731     } else {
       
  3732       const char* s1 = refs[0]->string();
       
  3733       const char* s2 = refs[1]->string();
       
  3734       buf = getbuf(strlen(s1) + 1 + strlen(s2) + 4 + 1);
       
  3735       buf.strcat(s1).strcat(" ").strcat(s2);
       
  3736       if (nrefs > 2)  buf.strcat(" ...");
       
  3737     }
       
  3738   }
       
  3739   return (const char*)buf.ptr;
       
  3740 }
       
  3741 
       
  3742 void print_cp_entry(int i) {
       
  3743   entry& e = debug_u->cp.entries[i];
       
  3744 
       
  3745   if ((uint)e.tag < CONSTANT_Limit) {
       
  3746     printf(" %d\t%s %s\n", i, TAG_NAME[e.tag], e.string());
       
  3747   } else {
       
  3748     printf(" %d\t%d %s\n", i, e.tag, e.string());
       
  3749   }
       
  3750 }
       
  3751 
       
  3752 void print_cp_entries(int beg, int end) {
       
  3753   for (int i = beg; i < end; i++)
       
  3754     print_cp_entry(i);
       
  3755 }
       
  3756 
       
  3757 void print_cp() {
       
  3758   print_cp_entries(0, debug_u->cp.nentries);
       
  3759 }
       
  3760 
       
  3761 #endif
       
  3762 
       
  3763 // Unpacker Start
       
  3764 
       
  3765 const char str_tf[] = "true\0false";
       
  3766 #undef STR_TRUE
       
  3767 #undef STR_FALSE
       
  3768 #define STR_TRUE   (&str_tf[0])
       
  3769 #define STR_FALSE  (&str_tf[5])
       
  3770 
       
  3771 const char* unpacker::get_option(const char* prop) {
       
  3772   if (prop == null )  return null;
       
  3773   if (strcmp(prop, UNPACK_DEFLATE_HINT) == 0) {
       
  3774     return deflate_hint_or_zero == 0? null : STR_TF(deflate_hint_or_zero > 0);
       
  3775 #ifdef HAVE_STRIP
       
  3776   } else if (strcmp(prop, UNPACK_STRIP_COMPILE) == 0) {
       
  3777     return STR_TF(strip_compile);
       
  3778   } else if (strcmp(prop, UNPACK_STRIP_DEBUG) == 0) {
       
  3779     return STR_TF(strip_debug);
       
  3780   } else if (strcmp(prop, UNPACK_STRIP_JCOV) == 0) {
       
  3781     return STR_TF(strip_jcov);
       
  3782 #endif /*HAVE_STRIP*/
       
  3783   } else if (strcmp(prop, UNPACK_REMOVE_PACKFILE) == 0) {
       
  3784     return STR_TF(remove_packfile);
       
  3785   } else if (strcmp(prop, DEBUG_VERBOSE) == 0) {
       
  3786     return saveIntStr(verbose);
       
  3787   } else if (strcmp(prop, UNPACK_MODIFICATION_TIME) == 0) {
       
  3788     return (modification_time_or_zero == 0)? null:
       
  3789       saveIntStr(modification_time_or_zero);
       
  3790   } else if (strcmp(prop, UNPACK_LOG_FILE) == 0) {
       
  3791     return log_file;
       
  3792   } else {
       
  3793     return NULL; // unknown option ignore
       
  3794   }
       
  3795 }
       
  3796 
       
  3797 bool unpacker::set_option(const char* prop, const char* value) {
       
  3798   if (prop == NULL)  return false;
       
  3799   if (strcmp(prop, UNPACK_DEFLATE_HINT) == 0) {
       
  3800     deflate_hint_or_zero = ( (value == null || strcmp(value, "keep") == 0)
       
  3801                                 ? 0: BOOL_TF(value) ? +1: -1);
       
  3802 #ifdef HAVE_STRIP
       
  3803   } else if (strcmp(prop, UNPACK_STRIP_COMPILE) == 0) {
       
  3804     strip_compile = STR_TF(value);
       
  3805   } else if (strcmp(prop, UNPACK_STRIP_DEBUG) == 0) {
       
  3806     strip_debug = STR_TF(value);
       
  3807   } else if (strcmp(prop, UNPACK_STRIP_JCOV) == 0) {
       
  3808     strip_jcov = STR_TF(value);
       
  3809 #endif /*HAVE_STRIP*/
       
  3810   } else if (strcmp(prop, UNPACK_REMOVE_PACKFILE) == 0) {
       
  3811     remove_packfile = STR_TF(value);
       
  3812   } else if (strcmp(prop, DEBUG_VERBOSE) == 0) {
       
  3813     verbose = (value == null)? 0: atoi(value);
       
  3814   } else if (strcmp(prop, DEBUG_VERBOSE ".bands") == 0) {
       
  3815 #ifndef PRODUCT
       
  3816     verbose_bands = (value == null)? 0: atoi(value);
       
  3817 #endif
       
  3818   } else if (strcmp(prop, UNPACK_MODIFICATION_TIME) == 0) {
       
  3819     if (value == null || (strcmp(value, "keep") == 0)) {
       
  3820       modification_time_or_zero = 0;
       
  3821     } else if (strcmp(value, "now") == 0) {
       
  3822       time_t now;
       
  3823       time(&now);
       
  3824       modification_time_or_zero = (int) now;
       
  3825     } else {
       
  3826       modification_time_or_zero = atoi(value);
       
  3827       if (modification_time_or_zero == 0)
       
  3828         modification_time_or_zero = 1;  // make non-zero
       
  3829     }
       
  3830   } else if (strcmp(prop, UNPACK_LOG_FILE) == 0) {
       
  3831     log_file = (value == null)? value: saveStr(value);
       
  3832   } else {
       
  3833     return false; // unknown option ignore
       
  3834   }
       
  3835   return true;
       
  3836 }
       
  3837 
       
  3838 // Deallocate all internal storage and reset to a clean state.
       
  3839 // Do not disturb any input or output connections, including
       
  3840 // infileptr, infileno, inbytes, read_input_fn, jarout, or errstrm.
       
  3841 // Do not reset any unpack options.
       
  3842 void unpacker::reset() {
       
  3843   bytes_read_before_reset      += bytes_read;
       
  3844   bytes_written_before_reset   += bytes_written;
       
  3845   files_written_before_reset   += files_written;
       
  3846   classes_written_before_reset += classes_written;
       
  3847   segments_read_before_reset   += 1;
       
  3848   if (verbose >= 2) {
       
  3849     fprintf(errstrm,
       
  3850             "After segment %d, "
       
  3851             LONG_LONG_FORMAT " bytes read and "
       
  3852             LONG_LONG_FORMAT " bytes written.\n",
       
  3853             segments_read_before_reset-1,
       
  3854             bytes_read_before_reset, bytes_written_before_reset);
       
  3855     fprintf(errstrm,
       
  3856             "After segment %d, %d files (of which %d are classes) written to output.\n",
       
  3857             segments_read_before_reset-1,
       
  3858             files_written_before_reset, classes_written_before_reset);
       
  3859     if (archive_next_count != 0) {
       
  3860       fprintf(errstrm,
       
  3861               "After segment %d, %d segment%s remaining (estimated).\n",
       
  3862               segments_read_before_reset-1,
       
  3863               archive_next_count, archive_next_count==1?"":"s");
       
  3864     }
       
  3865   }
       
  3866 
       
  3867   unpacker save_u = (*this);  // save bytewise image
       
  3868   infileptr = null;  // make asserts happy
       
  3869   jniobj = null;  // make asserts happy
       
  3870   jarout = null;  // do not close the output jar
       
  3871   gzin = null;  // do not close the input gzip stream
       
  3872   bytes esn;
       
  3873   if (errstrm_name != null) {
       
  3874     esn.saveFrom(errstrm_name);
       
  3875   } else {
       
  3876     esn.set(null, 0);
       
  3877   }
       
  3878   this->free();
       
  3879   mtrace('s', 0, 0);  // note the boundary between segments
       
  3880   this->init(read_input_fn);
       
  3881 
       
  3882   // restore selected interface state:
       
  3883 #define SAVE(x) this->x = save_u.x
       
  3884   SAVE(jniobj);
       
  3885   SAVE(jnienv);
       
  3886   SAVE(infileptr);  // buffered
       
  3887   SAVE(infileno);   // unbuffered
       
  3888   SAVE(inbytes);    // direct
       
  3889   SAVE(jarout);
       
  3890   SAVE(gzin);
       
  3891   //SAVE(read_input_fn);
       
  3892   SAVE(errstrm);
       
  3893   SAVE(verbose);  // verbose level, 0 means no output
       
  3894   SAVE(strip_compile);
       
  3895   SAVE(strip_debug);
       
  3896   SAVE(strip_jcov);
       
  3897   SAVE(remove_packfile);
       
  3898   SAVE(deflate_hint_or_zero);  // ==0 means not set, otherwise -1 or 1
       
  3899   SAVE(modification_time_or_zero);
       
  3900   SAVE(bytes_read_before_reset);
       
  3901   SAVE(bytes_written_before_reset);
       
  3902   SAVE(files_written_before_reset);
       
  3903   SAVE(classes_written_before_reset);
       
  3904   SAVE(segments_read_before_reset);
       
  3905 #undef SAVE
       
  3906   if (esn.len > 0) {
       
  3907     errstrm_name = saveStr(esn.strval());
       
  3908     esn.free();
       
  3909   }
       
  3910   log_file = errstrm_name;
       
  3911   // Note:  If we use strip_names, watch out:  They get nuked here.
       
  3912 }
       
  3913 
       
  3914 void unpacker::init(read_input_fn_t input_fn) {
       
  3915   int i;
       
  3916   NOT_PRODUCT(debug_u = this);
       
  3917   BYTES_OF(*this).clear();
       
  3918 #ifndef PRODUCT
       
  3919   free();  // just to make sure freeing is idempotent
       
  3920 #endif
       
  3921   this->u = this;    // self-reference for U_NEW macro
       
  3922   errstrm = stdout;  // default error-output
       
  3923   log_file = LOGFILE_STDOUT;
       
  3924   read_input_fn = input_fn;
       
  3925   all_bands = band::makeBands(this);
       
  3926   // Make a default jar buffer; caller may safely overwrite it.
       
  3927   jarout = U_NEW(jar, 1);
       
  3928   jarout->init(this);
       
  3929   for (i = 0; i < ATTR_CONTEXT_LIMIT; i++)
       
  3930     attr_defs[i].u = u;  // set up outer ptr
       
  3931 }
       
  3932 
       
  3933 const char* unpacker::get_abort_message() {
       
  3934    return abort_message;
       
  3935 }
       
  3936 
       
  3937 void unpacker::dump_options() {
       
  3938   static const char* opts[] = {
       
  3939     UNPACK_LOG_FILE,
       
  3940     UNPACK_DEFLATE_HINT,
       
  3941 #ifdef HAVE_STRIP
       
  3942     UNPACK_STRIP_COMPILE,
       
  3943     UNPACK_STRIP_DEBUG,
       
  3944     UNPACK_STRIP_JCOV,
       
  3945 #endif /*HAVE_STRIP*/
       
  3946     UNPACK_REMOVE_PACKFILE,
       
  3947     DEBUG_VERBOSE,
       
  3948     UNPACK_MODIFICATION_TIME,
       
  3949     null
       
  3950   };
       
  3951   for (int i = 0; opts[i] != null; i++) {
       
  3952     const char* str = get_option(opts[i]);
       
  3953     if (str == null) {
       
  3954       if (verbose == 0)  continue;
       
  3955       str = "(not set)";
       
  3956     }
       
  3957     fprintf(errstrm, "%s=%s\n", opts[i], str);
       
  3958   }
       
  3959 }
       
  3960 
       
  3961 
       
  3962 // Usage: unpack a byte buffer
       
  3963 // packptr is a reference to byte buffer containing a
       
  3964 // packed file and len is the length of the buffer.
       
  3965 // If null, the callback is used to fill an internal buffer.
       
  3966 void unpacker::start(void* packptr, size_t len) {
       
  3967   CHECK;
       
  3968   NOT_PRODUCT(debug_u = this);
       
  3969   if (packptr != null && len != 0) {
       
  3970     inbytes.set((byte*) packptr, len);
       
  3971   }
       
  3972   CHECK;
       
  3973   read_bands();
       
  3974 }
       
  3975 
       
  3976 void unpacker::check_options() {
       
  3977   const char* strue  = "true";
       
  3978   const char* sfalse = "false";
       
  3979   if (deflate_hint_or_zero != 0) {
       
  3980     bool force_deflate_hint = (deflate_hint_or_zero > 0);
       
  3981     if (force_deflate_hint)
       
  3982       default_file_options |= FO_DEFLATE_HINT;
       
  3983     else
       
  3984       default_file_options &= ~FO_DEFLATE_HINT;
       
  3985     // Turn off per-file deflate hint by force.
       
  3986     suppress_file_options |= FO_DEFLATE_HINT;
       
  3987   }
       
  3988   if (modification_time_or_zero != 0) {
       
  3989     default_file_modtime = modification_time_or_zero;
       
  3990     // Turn off per-file modtime by force.
       
  3991     archive_options &= ~AO_HAVE_FILE_MODTIME;
       
  3992   }
       
  3993   // %%% strip_compile, etc...
       
  3994 }
       
  3995 
       
  3996 // classfile writing
       
  3997 
       
  3998 void unpacker::reset_cur_classfile() {
       
  3999   // set defaults
       
  4000   cur_class_minver = default_class_minver;
       
  4001   cur_class_majver = default_class_majver;
       
  4002 
       
  4003   // reset constant pool state
       
  4004   cp.resetOutputIndexes();
       
  4005 
       
  4006   // reset fixups
       
  4007   class_fixup_type.empty();
       
  4008   class_fixup_offset.empty();
       
  4009   class_fixup_ref.empty();
       
  4010   requested_ics.empty();
       
  4011   cp.requested_bsms.empty();
       
  4012 }
       
  4013 
       
  4014 cpindex* cpool::getKQIndex() {
       
  4015   char ch = '?';
       
  4016   if (u->cur_descr != null) {
       
  4017     entry* type = u->cur_descr->descrType();
       
  4018     ch = type->value.b.ptr[0];
       
  4019   }
       
  4020   byte tag = CONSTANT_Integer;
       
  4021   switch (ch) {
       
  4022   case 'L': tag = CONSTANT_String;   break;
       
  4023   case 'I': tag = CONSTANT_Integer;  break;
       
  4024   case 'J': tag = CONSTANT_Long;     break;
       
  4025   case 'F': tag = CONSTANT_Float;    break;
       
  4026   case 'D': tag = CONSTANT_Double;   break;
       
  4027   case 'B': case 'S': case 'C':
       
  4028   case 'Z': tag = CONSTANT_Integer;  break;
       
  4029   default:  abort("bad KQ reference"); break;
       
  4030   }
       
  4031   return getIndex(tag);
       
  4032 }
       
  4033 
       
  4034 uint unpacker::to_bci(uint bii) {
       
  4035   uint  len =         bcimap.length();
       
  4036   uint* map = (uint*) bcimap.base();
       
  4037   assert(len > 0);  // must be initialized before using to_bci
       
  4038   if (len == 0) {
       
  4039     abort("bad bcimap");
       
  4040     return 0;
       
  4041   }
       
  4042   if (bii < len)
       
  4043     return map[bii];
       
  4044   // Else it's a fractional or out-of-range BCI.
       
  4045   uint key = bii-len;
       
  4046   for (int i = len; ; i--) {
       
  4047     if (map[i-1]-(i-1) <= key)
       
  4048       break;
       
  4049     else
       
  4050       --bii;
       
  4051   }
       
  4052   return bii;
       
  4053 }
       
  4054 
       
  4055 void unpacker::put_stackmap_type() {
       
  4056   int tag = code_StackMapTable_T.getByte();
       
  4057   putu1(tag);
       
  4058   switch (tag) {
       
  4059   case 7: // (7) [RCH]
       
  4060     putref(code_StackMapTable_RC.getRef());
       
  4061     break;
       
  4062   case 8: // (8) [PH]
       
  4063     putu2(to_bci(code_StackMapTable_P.getInt()));
       
  4064     CHECK;
       
  4065     break;
       
  4066   }
       
  4067 }
       
  4068 
       
  4069 // Functions for writing code.
       
  4070 
       
  4071 maybe_inline
       
  4072 void unpacker::put_label(int curIP, int size) {
       
  4073   code_fixup_type.addByte(size);
       
  4074   code_fixup_offset.add((int)put_empty(size));
       
  4075   code_fixup_source.add(curIP);
       
  4076 }
       
  4077 
       
  4078 inline  // called exactly once => inline
       
  4079 void unpacker::write_bc_ops() {
       
  4080   bcimap.empty();
       
  4081   code_fixup_type.empty();
       
  4082   code_fixup_offset.empty();
       
  4083   code_fixup_source.empty();
       
  4084 
       
  4085   band* bc_which;
       
  4086 
       
  4087   byte*  opptr = bc_codes.curRP();
       
  4088   // No need for oplimit, since the codes are pre-counted.
       
  4089 
       
  4090   size_t codeBase = wpoffset();
       
  4091 
       
  4092   bool   isAload;  // copy-out result
       
  4093   int    origBC;
       
  4094 
       
  4095   entry* thisClass  = cur_class;
       
  4096   entry* superClass = cur_super;
       
  4097   entry* newClass   = null;  // class of last _new opcode
       
  4098 
       
  4099   // overwrite any prior index on these bands; it changes w/ current class:
       
  4100   bc_thisfield.setIndex(    cp.getFieldIndex( thisClass));
       
  4101   bc_thismethod.setIndex(   cp.getMethodIndex(thisClass));
       
  4102   if (superClass != null) {
       
  4103     bc_superfield.setIndex( cp.getFieldIndex( superClass));
       
  4104     bc_supermethod.setIndex(cp.getMethodIndex(superClass));
       
  4105   } else {
       
  4106     NOT_PRODUCT(bc_superfield.setIndex(null));
       
  4107     NOT_PRODUCT(bc_supermethod.setIndex(null));
       
  4108   }
       
  4109   CHECK;
       
  4110 
       
  4111   for (int curIP = 0; ; curIP++) {
       
  4112     CHECK;
       
  4113     int curPC = (int)(wpoffset() - codeBase);
       
  4114     bcimap.add(curPC);
       
  4115     ensure_put_space(10);  // covers most instrs w/o further bounds check
       
  4116     int bc = *opptr++ & 0xFF;
       
  4117 
       
  4118     putu1_fast(bc);
       
  4119     // Note:  See '--wp' below for pseudo-bytecodes like bc_end_marker.
       
  4120 
       
  4121     bool isWide = false;
       
  4122     if (bc == bc_wide) {
       
  4123       bc = *opptr++ & 0xFF;
       
  4124       putu1_fast(bc);
       
  4125       isWide = true;
       
  4126     }
       
  4127     switch (bc) {
       
  4128     case bc_end_marker:
       
  4129       --wp;  // not really part of the code
       
  4130       assert(opptr <= bc_codes.maxRP());
       
  4131       bc_codes.curRP() = opptr;  // advance over this in bc_codes
       
  4132       goto doneScanningMethod;
       
  4133     case bc_tableswitch: // apc:  (df, lo, hi, (hi-lo+1)*(label))
       
  4134     case bc_lookupswitch: // apc:  (df, nc, nc*(case, label))
       
  4135       {
       
  4136         int caseCount = bc_case_count.getInt();
       
  4137         while (((wpoffset() - codeBase) % 4) != 0)  putu1_fast(0);
       
  4138         ensure_put_space(30 + caseCount*8);
       
  4139         put_label(curIP, 4);  //int df = bc_label.getInt();
       
  4140         if (bc == bc_tableswitch) {
       
  4141           int lo = bc_case_value.getInt();
       
  4142           int hi = lo + caseCount-1;
       
  4143           putu4(lo);
       
  4144           putu4(hi);
       
  4145           for (int j = 0; j < caseCount; j++) {
       
  4146             put_label(curIP, 4); //int lVal = bc_label.getInt();
       
  4147             //int cVal = lo + j;
       
  4148           }
       
  4149         } else {
       
  4150           putu4(caseCount);
       
  4151           for (int j = 0; j < caseCount; j++) {
       
  4152             int cVal = bc_case_value.getInt();
       
  4153             putu4(cVal);
       
  4154             put_label(curIP, 4); //int lVal = bc_label.getInt();
       
  4155           }
       
  4156         }
       
  4157         assert((int)to_bci(curIP) == curPC);
       
  4158         continue;
       
  4159       }
       
  4160     case bc_iinc:
       
  4161       {
       
  4162         int local = bc_local.getInt();
       
  4163         int delta = (isWide ? bc_short : bc_byte).getInt();
       
  4164         if (isWide) {
       
  4165           putu2(local);
       
  4166           putu2(delta);
       
  4167         } else {
       
  4168           putu1_fast(local);
       
  4169           putu1_fast(delta);
       
  4170         }
       
  4171         continue;
       
  4172       }
       
  4173     case bc_sipush:
       
  4174       {
       
  4175         int val = bc_short.getInt();
       
  4176         putu2(val);
       
  4177         continue;
       
  4178       }
       
  4179     case bc_bipush:
       
  4180     case bc_newarray:
       
  4181       {
       
  4182         int val = bc_byte.getByte();
       
  4183         putu1_fast(val);
       
  4184         continue;
       
  4185       }
       
  4186     case bc_ref_escape:
       
  4187       {
       
  4188         // Note that insnMap has one entry for this.
       
  4189         --wp;  // not really part of the code
       
  4190         int size = bc_escrefsize.getInt();
       
  4191         entry* ref = bc_escref.getRefN();
       
  4192         CHECK;
       
  4193         switch (size) {
       
  4194         case 1: putu1ref(ref); break;
       
  4195         case 2: putref(ref);   break;
       
  4196         default: assert(false);
       
  4197         }
       
  4198         continue;
       
  4199       }
       
  4200     case bc_byte_escape:
       
  4201       {
       
  4202         // Note that insnMap has one entry for all these bytes.
       
  4203         --wp;  // not really part of the code
       
  4204         int size = bc_escsize.getInt();
       
  4205         if (size < 0) { assert(false); continue; }
       
  4206         ensure_put_space(size);
       
  4207         for (int j = 0; j < size; j++)
       
  4208           putu1_fast(bc_escbyte.getByte());
       
  4209         continue;
       
  4210       }
       
  4211     default:
       
  4212       if (is_invoke_init_op(bc)) {
       
  4213         origBC = bc_invokespecial;
       
  4214         entry* classRef;
       
  4215         switch (bc - _invokeinit_op) {
       
  4216         case _invokeinit_self_option:   classRef = thisClass;  break;
       
  4217         case _invokeinit_super_option:  classRef = superClass; break;
       
  4218         default: assert(bc == _invokeinit_op+_invokeinit_new_option);
       
  4219         case _invokeinit_new_option:    classRef = newClass;   break;
       
  4220         }
       
  4221         wp[-1] = origBC;  // overwrite with origBC
       
  4222         int coding = bc_initref.getInt();
       
  4223         // Find the nth overloading of <init> in classRef.
       
  4224         entry*   ref = null;
       
  4225         cpindex* ix = cp.getMethodIndex(classRef);
       
  4226         CHECK;
       
  4227         for (int j = 0, which_init = 0; ; j++) {
       
  4228           ref = (ix == null)? null: ix->get(j);
       
  4229           if (ref == null)  break;  // oops, bad input
       
  4230           assert(ref->tag == CONSTANT_Methodref);
       
  4231           if (ref->memberDescr()->descrName() == cp.sym[cpool::s_lt_init_gt]) {
       
  4232             if (which_init++ == coding)  break;
       
  4233           }
       
  4234         }
       
  4235         putref(ref);
       
  4236         continue;
       
  4237       }
       
  4238       bc_which = ref_band_for_self_op(bc, isAload, origBC);
       
  4239       if (bc_which != null) {
       
  4240         if (!isAload) {
       
  4241           wp[-1] = origBC;  // overwrite with origBC
       
  4242         } else {
       
  4243           wp[-1] = bc_aload_0;  // overwrite with _aload_0
       
  4244           // Note: insnMap keeps the _aload_0 separate.
       
  4245           bcimap.add(++curPC);
       
  4246           ++curIP;
       
  4247           putu1_fast(origBC);
       
  4248         }
       
  4249         entry* ref = bc_which->getRef();
       
  4250         CHECK;
       
  4251         putref(ref);
       
  4252         continue;
       
  4253       }
       
  4254       if (is_branch_op(bc)) {
       
  4255         //int lVal = bc_label.getInt();
       
  4256         if (bc < bc_goto_w) {
       
  4257           put_label(curIP, 2);  //putu2(lVal & 0xFFFF);
       
  4258         } else {
       
  4259           assert(bc <= bc_jsr_w);
       
  4260           put_label(curIP, 4);  //putu4(lVal);
       
  4261         }
       
  4262         assert((int)to_bci(curIP) == curPC);
       
  4263         continue;
       
  4264       }
       
  4265       bc_which = ref_band_for_op(bc);
       
  4266       if (bc_which != null) {
       
  4267         entry* ref = bc_which->getRefCommon(bc_which->ix, bc_which->nullOK);
       
  4268         CHECK;
       
  4269         if (ref == null && bc_which == &bc_classref) {
       
  4270           // Shorthand for class self-references.
       
  4271           ref = thisClass;
       
  4272         }
       
  4273         origBC = bc;
       
  4274         switch (bc) {
       
  4275         case _invokestatic_int:
       
  4276           origBC = bc_invokestatic;
       
  4277           break;
       
  4278         case _invokespecial_int:
       
  4279           origBC = bc_invokespecial;
       
  4280           break;
       
  4281         case bc_ildc:
       
  4282         case bc_cldc:
       
  4283         case bc_fldc:
       
  4284         case bc_sldc:
       
  4285         case bc_qldc:
       
  4286           origBC = bc_ldc;
       
  4287           break;
       
  4288         case bc_ildc_w:
       
  4289         case bc_cldc_w:
       
  4290         case bc_fldc_w:
       
  4291         case bc_sldc_w:
       
  4292         case bc_qldc_w:
       
  4293           origBC = bc_ldc_w;
       
  4294           break;
       
  4295         case bc_lldc2_w:
       
  4296         case bc_dldc2_w:
       
  4297           origBC = bc_ldc2_w;
       
  4298           break;
       
  4299         case bc_new:
       
  4300           newClass = ref;
       
  4301           break;
       
  4302         }
       
  4303         wp[-1] = origBC;  // overwrite with origBC
       
  4304         if (origBC == bc_ldc) {
       
  4305           putu1ref(ref);
       
  4306         } else {
       
  4307           putref(ref);
       
  4308         }
       
  4309         if (origBC == bc_multianewarray) {
       
  4310           // Copy the trailing byte also.
       
  4311           int val = bc_byte.getByte();
       
  4312           putu1_fast(val);
       
  4313         } else if (origBC == bc_invokeinterface) {
       
  4314           int argSize = ref->memberDescr()->descrType()->typeSize();
       
  4315           putu1_fast(1 + argSize);
       
  4316           putu1_fast(0);
       
  4317         } else if (origBC == bc_invokedynamic) {
       
  4318           // pad the next two byte
       
  4319           putu1_fast(0);
       
  4320           putu1_fast(0);
       
  4321         }
       
  4322         continue;
       
  4323       }
       
  4324       if (is_local_slot_op(bc)) {
       
  4325         int local = bc_local.getInt();
       
  4326         if (isWide) {
       
  4327           putu2(local);
       
  4328           if (bc == bc_iinc) {
       
  4329             int iVal = bc_short.getInt();
       
  4330             putu2(iVal);
       
  4331           }
       
  4332         } else {
       
  4333           putu1_fast(local);
       
  4334           if (bc == bc_iinc) {
       
  4335             int iVal = bc_byte.getByte();
       
  4336             putu1_fast(iVal);
       
  4337           }
       
  4338         }
       
  4339         continue;
       
  4340       }
       
  4341       // Random bytecode.  Just copy it.
       
  4342       assert(bc < bc_bytecode_limit);
       
  4343     }
       
  4344   }
       
  4345  doneScanningMethod:{}
       
  4346   //bcimap.add(curPC);  // PC limit is already also in map, from bc_end_marker
       
  4347 
       
  4348   // Armed with a bcimap, we can now fix up all the labels.
       
  4349   for (int i = 0; i < (int)code_fixup_type.size(); i++) {
       
  4350     int   type   = code_fixup_type.getByte(i);
       
  4351     byte* bp     = wp_at(code_fixup_offset.get(i));
       
  4352     int   curIP  = code_fixup_source.get(i);
       
  4353     int   destIP = curIP + bc_label.getInt();
       
  4354     int   span   = to_bci(destIP) - to_bci(curIP);
       
  4355     CHECK;
       
  4356     switch (type) {
       
  4357     case 2: putu2_at(bp, (ushort)span); break;
       
  4358     case 4: putu4_at(bp,         span); break;
       
  4359     default: assert(false);
       
  4360     }
       
  4361   }
       
  4362 }
       
  4363 
       
  4364 inline  // called exactly once => inline
       
  4365 void unpacker::write_code() {
       
  4366   int j;
       
  4367 
       
  4368   int max_stack, max_locals, handler_count, cflags;
       
  4369   get_code_header(max_stack, max_locals, handler_count, cflags);
       
  4370 
       
  4371   if (max_stack < 0)      max_stack = code_max_stack.getInt();
       
  4372   if (max_locals < 0)     max_locals = code_max_na_locals.getInt();
       
  4373   if (handler_count < 0)  handler_count = code_handler_count.getInt();
       
  4374 
       
  4375   int siglen = cur_descr->descrType()->typeSize();
       
  4376   CHECK;
       
  4377   if ((cur_descr_flags & ACC_STATIC) == 0)  siglen++;
       
  4378   max_locals += siglen;
       
  4379 
       
  4380   putu2(max_stack);
       
  4381   putu2(max_locals);
       
  4382   size_t bcbase = put_empty(4);
       
  4383 
       
  4384   // Write the bytecodes themselves.
       
  4385   write_bc_ops();
       
  4386   CHECK;
       
  4387 
       
  4388   byte* bcbasewp = wp_at(bcbase);
       
  4389   putu4_at(bcbasewp, (int)(wp - (bcbasewp+4)));  // size of code attr
       
  4390 
       
  4391   putu2(handler_count);
       
  4392   for (j = 0; j < handler_count; j++) {
       
  4393     int bii = code_handler_start_P.getInt();
       
  4394     putu2(to_bci(bii));
       
  4395     bii    += code_handler_end_PO.getInt();
       
  4396     putu2(to_bci(bii));
       
  4397     bii    += code_handler_catch_PO.getInt();
       
  4398     putu2(to_bci(bii));
       
  4399     putref(code_handler_class_RCN.getRefN());
       
  4400     CHECK;
       
  4401   }
       
  4402 
       
  4403   julong indexBits = cflags;
       
  4404   if (cflags < 0) {
       
  4405     bool haveLongFlags = attr_defs[ATTR_CONTEXT_CODE].haveLongFlags();
       
  4406     indexBits = code_flags_hi.getLong(code_flags_lo, haveLongFlags);
       
  4407   }
       
  4408   write_attrs(ATTR_CONTEXT_CODE, indexBits);
       
  4409 }
       
  4410 
       
  4411 int unpacker::write_attrs(int attrc, julong indexBits) {
       
  4412   CHECK_0;
       
  4413   if (indexBits == 0) {
       
  4414     // Quick short-circuit.
       
  4415     putu2(0);
       
  4416     return 0;
       
  4417   }
       
  4418 
       
  4419   attr_definitions& ad = attr_defs[attrc];
       
  4420 
       
  4421   int i, j, j2, idx, count;
       
  4422 
       
  4423   int oiCount = 0;
       
  4424   if (ad.isPredefined(X_ATTR_OVERFLOW)
       
  4425       && (indexBits & ((julong)1<<X_ATTR_OVERFLOW)) != 0) {
       
  4426     indexBits -= ((julong)1<<X_ATTR_OVERFLOW);
       
  4427     oiCount = ad.xxx_attr_count().getInt();
       
  4428   }
       
  4429 
       
  4430   int bitIndexes[X_ATTR_LIMIT_FLAGS_HI];
       
  4431   int biCount = 0;
       
  4432 
       
  4433   // Fill bitIndexes with index bits, in order.
       
  4434   for (idx = 0; indexBits != 0; idx++, indexBits >>= 1) {
       
  4435     if ((indexBits & 1) != 0)
       
  4436       bitIndexes[biCount++] = idx;
       
  4437   }
       
  4438   assert(biCount <= (int)lengthof(bitIndexes));
       
  4439 
       
  4440   // Write a provisional attribute count, perhaps to be corrected later.
       
  4441   int naOffset = (int)wpoffset();
       
  4442   int na0 = biCount + oiCount;
       
  4443   putu2(na0);
       
  4444 
       
  4445   int na = 0;
       
  4446   for (i = 0; i < na0; i++) {
       
  4447     if (i < biCount)
       
  4448       idx = bitIndexes[i];
       
  4449     else
       
  4450       idx = ad.xxx_attr_indexes().getInt();
       
  4451     assert(ad.isIndex(idx));
       
  4452     entry* aname = null;
       
  4453     entry* ref;  // scratch
       
  4454     size_t abase = put_empty(2+4);
       
  4455     CHECK_0;
       
  4456     if (idx < (int)ad.flag_limit && ad.isPredefined(idx)) {
       
  4457       // Switch on the attrc and idx simultaneously.
       
  4458       switch (ADH_BYTE(attrc, idx)) {
       
  4459 
       
  4460       case ADH_BYTE(ATTR_CONTEXT_CLASS,  X_ATTR_OVERFLOW):
       
  4461       case ADH_BYTE(ATTR_CONTEXT_FIELD,  X_ATTR_OVERFLOW):
       
  4462       case ADH_BYTE(ATTR_CONTEXT_METHOD, X_ATTR_OVERFLOW):
       
  4463       case ADH_BYTE(ATTR_CONTEXT_CODE,   X_ATTR_OVERFLOW):
       
  4464         // no attribute at all, so back up on this one
       
  4465         wp = wp_at(abase);
       
  4466         continue;
       
  4467 
       
  4468       case ADH_BYTE(ATTR_CONTEXT_CLASS, CLASS_ATTR_ClassFile_version):
       
  4469         cur_class_minver = class_ClassFile_version_minor_H.getInt();
       
  4470         cur_class_majver = class_ClassFile_version_major_H.getInt();
       
  4471         // back up; not a real attribute
       
  4472         wp = wp_at(abase);
       
  4473         continue;
       
  4474 
       
  4475       case ADH_BYTE(ATTR_CONTEXT_CLASS, CLASS_ATTR_InnerClasses):
       
  4476         // note the existence of this attr, but save for later
       
  4477         if (cur_class_has_local_ics)
       
  4478           abort("too many InnerClasses attrs");
       
  4479         cur_class_has_local_ics = true;
       
  4480         wp = wp_at(abase);
       
  4481         continue;
       
  4482 
       
  4483       case ADH_BYTE(ATTR_CONTEXT_CLASS, CLASS_ATTR_SourceFile):
       
  4484         aname = cp.sym[cpool::s_SourceFile];
       
  4485         ref = class_SourceFile_RUN.getRefN();
       
  4486         CHECK_0;
       
  4487         if (ref == null) {
       
  4488           bytes& n = cur_class->ref(0)->value.b;
       
  4489           // parse n = (<pkg>/)*<outer>?($<id>)*
       
  4490           int pkglen = lastIndexOf(SLASH_MIN,  SLASH_MAX,  n, (int)n.len)+1;
       
  4491           bytes prefix = n.slice(pkglen, n.len);
       
  4492           for (;;) {
       
  4493             // Work backwards, finding all '$', '#', etc.
       
  4494             int dollar = lastIndexOf(DOLLAR_MIN, DOLLAR_MAX, prefix, (int)prefix.len);
       
  4495             if (dollar < 0)  break;
       
  4496             prefix = prefix.slice(0, dollar);
       
  4497           }
       
  4498           const char* suffix = ".java";
       
  4499           int len = (int)(prefix.len + strlen(suffix));
       
  4500           bytes name; name.set(T_NEW(byte, add_size(len, 1)), len);
       
  4501           name.strcat(prefix).strcat(suffix);
       
  4502           ref = cp.ensureUtf8(name);
       
  4503         }
       
  4504         putref(ref);
       
  4505         break;
       
  4506 
       
  4507       case ADH_BYTE(ATTR_CONTEXT_CLASS, CLASS_ATTR_EnclosingMethod):
       
  4508         aname = cp.sym[cpool::s_EnclosingMethod];
       
  4509         putref(class_EnclosingMethod_RC.getRefN());
       
  4510         CHECK_0;
       
  4511         putref(class_EnclosingMethod_RDN.getRefN());
       
  4512         break;
       
  4513 
       
  4514       case ADH_BYTE(ATTR_CONTEXT_FIELD, FIELD_ATTR_ConstantValue):
       
  4515         aname = cp.sym[cpool::s_ConstantValue];
       
  4516         putref(field_ConstantValue_KQ.getRefUsing(cp.getKQIndex()));
       
  4517         break;
       
  4518 
       
  4519       case ADH_BYTE(ATTR_CONTEXT_METHOD, METHOD_ATTR_Code):
       
  4520         aname = cp.sym[cpool::s_Code];
       
  4521         write_code();
       
  4522         break;
       
  4523 
       
  4524       case ADH_BYTE(ATTR_CONTEXT_METHOD, METHOD_ATTR_Exceptions):
       
  4525         aname = cp.sym[cpool::s_Exceptions];
       
  4526         putu2(count = method_Exceptions_N.getInt());
       
  4527         for (j = 0; j < count; j++) {
       
  4528           putref(method_Exceptions_RC.getRefN());
       
  4529           CHECK_0;
       
  4530         }
       
  4531         break;
       
  4532 
       
  4533       case ADH_BYTE(ATTR_CONTEXT_METHOD, METHOD_ATTR_MethodParameters):
       
  4534         aname = cp.sym[cpool::s_MethodParameters];
       
  4535         putu1(count = method_MethodParameters_NB.getByte());
       
  4536         for (j = 0; j < count; j++) {
       
  4537           putref(method_MethodParameters_name_RUN.getRefN());
       
  4538           putu2(method_MethodParameters_flag_FH.getInt());
       
  4539         }
       
  4540         break;
       
  4541 
       
  4542       case ADH_BYTE(ATTR_CONTEXT_CODE, CODE_ATTR_StackMapTable):
       
  4543         aname = cp.sym[cpool::s_StackMapTable];
       
  4544         // (keep this code aligned with its brother in unpacker::read_attrs)
       
  4545         putu2(count = code_StackMapTable_N.getInt());
       
  4546         for (j = 0; j < count; j++) {
       
  4547           int tag = code_StackMapTable_frame_T.getByte();
       
  4548           putu1(tag);
       
  4549           if (tag <= 127) {
       
  4550             // (64-127)  [(2)]
       
  4551             if (tag >= 64)  put_stackmap_type();
       
  4552             CHECK_0;
       
  4553           } else if (tag <= 251) {
       
  4554             // (247)     [(1)(2)]
       
  4555             // (248-251) [(1)]
       
  4556             if (tag >= 247)  putu2(code_StackMapTable_offset.getInt());
       
  4557             if (tag == 247)  put_stackmap_type();
       
  4558             CHECK_0;
       
  4559           } else if (tag <= 254) {
       
  4560             // (252)     [(1)(2)]
       
  4561             // (253)     [(1)(2)(2)]
       
  4562             // (254)     [(1)(2)(2)(2)]
       
  4563             putu2(code_StackMapTable_offset.getInt());
       
  4564             CHECK_0;
       
  4565             for (int k = (tag - 251); k > 0; k--) {
       
  4566               put_stackmap_type();
       
  4567               CHECK_0;
       
  4568             }
       
  4569           } else {
       
  4570             // (255)     [(1)NH[(2)]NH[(2)]]
       
  4571             putu2(code_StackMapTable_offset.getInt());
       
  4572             putu2(j2 = code_StackMapTable_local_N.getInt());
       
  4573             while (j2-- > 0) {put_stackmap_type(); CHECK_0;}
       
  4574             putu2(j2 = code_StackMapTable_stack_N.getInt());
       
  4575             while (j2-- > 0)  {put_stackmap_type(); CHECK_0;}
       
  4576           }
       
  4577         }
       
  4578         break;
       
  4579 
       
  4580       case ADH_BYTE(ATTR_CONTEXT_CODE, CODE_ATTR_LineNumberTable):
       
  4581         aname = cp.sym[cpool::s_LineNumberTable];
       
  4582         putu2(count = code_LineNumberTable_N.getInt());
       
  4583         for (j = 0; j < count; j++) {
       
  4584           putu2(to_bci(code_LineNumberTable_bci_P.getInt()));
       
  4585           CHECK_0;
       
  4586           putu2(code_LineNumberTable_line.getInt());
       
  4587         }
       
  4588         break;
       
  4589 
       
  4590       case ADH_BYTE(ATTR_CONTEXT_CODE, CODE_ATTR_LocalVariableTable):
       
  4591         aname = cp.sym[cpool::s_LocalVariableTable];
       
  4592         putu2(count = code_LocalVariableTable_N.getInt());
       
  4593         for (j = 0; j < count; j++) {
       
  4594           int bii = code_LocalVariableTable_bci_P.getInt();
       
  4595           int bci = to_bci(bii);
       
  4596           CHECK_0;
       
  4597           putu2(bci);
       
  4598           bii    += code_LocalVariableTable_span_O.getInt();
       
  4599           putu2(to_bci(bii) - bci);
       
  4600           CHECK_0;
       
  4601           putref(code_LocalVariableTable_name_RU.getRefN());
       
  4602           CHECK_0;
       
  4603           putref(code_LocalVariableTable_type_RS.getRefN());
       
  4604           CHECK_0;
       
  4605           putu2(code_LocalVariableTable_slot.getInt());
       
  4606         }
       
  4607         break;
       
  4608 
       
  4609       case ADH_BYTE(ATTR_CONTEXT_CODE, CODE_ATTR_LocalVariableTypeTable):
       
  4610         aname = cp.sym[cpool::s_LocalVariableTypeTable];
       
  4611         putu2(count = code_LocalVariableTypeTable_N.getInt());
       
  4612         for (j = 0; j < count; j++) {
       
  4613           int bii = code_LocalVariableTypeTable_bci_P.getInt();
       
  4614           int bci = to_bci(bii);
       
  4615           CHECK_0;
       
  4616           putu2(bci);
       
  4617           bii    += code_LocalVariableTypeTable_span_O.getInt();
       
  4618           putu2(to_bci(bii) - bci);
       
  4619           CHECK_0;
       
  4620           putref(code_LocalVariableTypeTable_name_RU.getRefN());
       
  4621           CHECK_0;
       
  4622           putref(code_LocalVariableTypeTable_type_RS.getRefN());
       
  4623           CHECK_0;
       
  4624           putu2(code_LocalVariableTypeTable_slot.getInt());
       
  4625         }
       
  4626         break;
       
  4627 
       
  4628       case ADH_BYTE(ATTR_CONTEXT_CLASS, X_ATTR_Signature):
       
  4629         aname = cp.sym[cpool::s_Signature];
       
  4630         putref(class_Signature_RS.getRefN());
       
  4631         break;
       
  4632 
       
  4633       case ADH_BYTE(ATTR_CONTEXT_FIELD, X_ATTR_Signature):
       
  4634         aname = cp.sym[cpool::s_Signature];
       
  4635         putref(field_Signature_RS.getRefN());
       
  4636         break;
       
  4637 
       
  4638       case ADH_BYTE(ATTR_CONTEXT_METHOD, X_ATTR_Signature):
       
  4639         aname = cp.sym[cpool::s_Signature];
       
  4640         putref(method_Signature_RS.getRefN());
       
  4641         break;
       
  4642 
       
  4643       case ADH_BYTE(ATTR_CONTEXT_CLASS,  X_ATTR_Deprecated):
       
  4644       case ADH_BYTE(ATTR_CONTEXT_FIELD,  X_ATTR_Deprecated):
       
  4645       case ADH_BYTE(ATTR_CONTEXT_METHOD, X_ATTR_Deprecated):
       
  4646         aname = cp.sym[cpool::s_Deprecated];
       
  4647         // no data
       
  4648         break;
       
  4649       }
       
  4650     }
       
  4651     CHECK_0;
       
  4652     if (aname == null) {
       
  4653       // Unparse a compressor-defined attribute.
       
  4654       layout_definition* lo = ad.getLayout(idx);
       
  4655       if (lo == null) {
       
  4656         abort("bad layout index");
       
  4657         break;
       
  4658       }
       
  4659       assert((int)lo->idx == idx);
       
  4660       aname = lo->nameEntry;
       
  4661       if (aname == null) {
       
  4662         bytes nameb; nameb.set(lo->name);
       
  4663         aname = cp.ensureUtf8(nameb);
       
  4664         // Cache the name entry for next time.
       
  4665         lo->nameEntry = aname;
       
  4666       }
       
  4667       // Execute all the layout elements.
       
  4668       band** bands = lo->bands();
       
  4669       if (lo->hasCallables()) {
       
  4670         band& cble = *bands[0];
       
  4671         assert(cble.le_kind == EK_CBLE);
       
  4672         bands = cble.le_body;
       
  4673       }
       
  4674       putlayout(bands);
       
  4675     }
       
  4676 
       
  4677     if (aname == null)
       
  4678       abort("bad attribute index");
       
  4679     CHECK_0;
       
  4680 
       
  4681     byte* wp1 = wp;
       
  4682     wp = wp_at(abase);
       
  4683 
       
  4684     // DTRT if this attr is on the strip-list.
       
  4685     // (Note that we emptied the data out of the band first.)
       
  4686     if (ad.strip_names.contains(aname)) {
       
  4687       continue;
       
  4688     }
       
  4689 
       
  4690     // patch the name and length
       
  4691     putref(aname);
       
  4692     putu4((int)(wp1 - (wp+4)));  // put the attr size
       
  4693     wp = wp1;
       
  4694     na++;  // count the attrs actually written
       
  4695   }
       
  4696 
       
  4697   if (na != na0)
       
  4698     // Refresh changed count.
       
  4699     putu2_at(wp_at(naOffset), na);
       
  4700   return na;
       
  4701 }
       
  4702 
       
  4703 void unpacker::write_members(int num, int attrc) {
       
  4704   CHECK;
       
  4705   attr_definitions& ad = attr_defs[attrc];
       
  4706   band& member_flags_hi = ad.xxx_flags_hi();
       
  4707   band& member_flags_lo = ad.xxx_flags_lo();
       
  4708   band& member_descr = (&member_flags_hi)[e_field_descr-e_field_flags_hi];
       
  4709   assert(endsWith(member_descr.name, "_descr"));
       
  4710   assert(endsWith(member_flags_lo.name, "_flags_lo"));
       
  4711   assert(endsWith(member_flags_lo.name, "_flags_lo"));
       
  4712   bool haveLongFlags = ad.haveLongFlags();
       
  4713 
       
  4714   putu2(num);
       
  4715   julong indexMask = attr_defs[attrc].flagIndexMask();
       
  4716   for (int i = 0; i < num; i++) {
       
  4717     julong mflags = member_flags_hi.getLong(member_flags_lo, haveLongFlags);
       
  4718     entry* mdescr = member_descr.getRef();
       
  4719     cur_descr = mdescr;
       
  4720     putu2(cur_descr_flags = (ushort)(mflags & ~indexMask));
       
  4721     CHECK;
       
  4722     putref(mdescr->descrName());
       
  4723     putref(mdescr->descrType());
       
  4724     write_attrs(attrc, (mflags & indexMask));
       
  4725     CHECK;
       
  4726   }
       
  4727   cur_descr = null;
       
  4728 }
       
  4729 
       
  4730 extern "C"
       
  4731 int raw_address_cmp(const void* p1p, const void* p2p) {
       
  4732   void* p1 = *(void**) p1p;
       
  4733   void* p2 = *(void**) p2p;
       
  4734   return (p1 > p2)? 1: (p1 < p2)? -1: 0;
       
  4735 }
       
  4736 
       
  4737 /*
       
  4738  * writes the InnerClass attributes and returns the updated attribute
       
  4739  */
       
  4740 int  unpacker::write_ics(int naOffset, int na) {
       
  4741 #ifdef ASSERT
       
  4742   for (int i = 0; i < ic_count; i++) {
       
  4743     assert(!ics[i].requested);
       
  4744   }
       
  4745 #endif
       
  4746   // First, consult the global table and the local constant pool,
       
  4747   // and decide on the globally implied inner classes.
       
  4748   // (Note that we read the cpool's outputIndex fields, but we
       
  4749   // do not yet write them, since the local IC attribute might
       
  4750   // reverse a global decision to declare an IC.)
       
  4751   assert(requested_ics.length() == 0);  // must start out empty
       
  4752   // Always include all members of the current class.
       
  4753   for (inner_class* child = cp.getFirstChildIC(cur_class);
       
  4754        child != null;
       
  4755        child = cp.getNextChildIC(child)) {
       
  4756     child->requested = true;
       
  4757     requested_ics.add(child);
       
  4758   }
       
  4759   // And, for each inner class mentioned in the constant pool,
       
  4760   // include it and all its outers.
       
  4761   int    noes =           cp.outputEntries.length();
       
  4762   entry** oes = (entry**) cp.outputEntries.base();
       
  4763   for (int i = 0; i < noes; i++) {
       
  4764     entry& e = *oes[i];
       
  4765     if (e.tag != CONSTANT_Class)  continue;  // wrong sort
       
  4766     for (inner_class* ic = cp.getIC(&e);
       
  4767          ic != null;
       
  4768          ic = cp.getIC(ic->outer)) {
       
  4769       if (ic->requested)  break;  // already processed
       
  4770       ic->requested = true;
       
  4771       requested_ics.add(ic);
       
  4772     }
       
  4773   }
       
  4774   int local_ics = requested_ics.length();
       
  4775   // Second, consult a local attribute (if any) and adjust the global set.
       
  4776   inner_class* extra_ics = null;
       
  4777   int      num_extra_ics = 0;
       
  4778   if (cur_class_has_local_ics) {
       
  4779     // adjust the set of ICs by symmetric set difference w/ the locals
       
  4780     num_extra_ics = class_InnerClasses_N.getInt();
       
  4781     if (num_extra_ics == 0) {
       
  4782       // Explicit zero count has an irregular meaning:  It deletes the attr.
       
  4783       local_ics = 0;  // (short-circuit all tests of requested bits)
       
  4784     } else {
       
  4785       extra_ics = T_NEW(inner_class, num_extra_ics);
       
  4786       // Note:  extra_ics will be freed up by next call to get_next_file().
       
  4787     }
       
  4788   }
       
  4789   for (int i = 0; i < num_extra_ics; i++) {
       
  4790     inner_class& extra_ic = extra_ics[i];
       
  4791     extra_ic.inner = class_InnerClasses_RC.getRef();
       
  4792     CHECK_0;
       
  4793     // Find the corresponding equivalent global IC:
       
  4794     inner_class* global_ic = cp.getIC(extra_ic.inner);
       
  4795     int flags = class_InnerClasses_F.getInt();
       
  4796     if (flags == 0) {
       
  4797       // The extra IC is simply a copy of a global IC.
       
  4798       if (global_ic == null) {
       
  4799         abort("bad reference to inner class");
       
  4800         break;
       
  4801       }
       
  4802       extra_ic = (*global_ic);  // fill in rest of fields
       
  4803     } else {
       
  4804       flags &= ~ACC_IC_LONG_FORM;  // clear high bit if set to get clean zero
       
  4805       extra_ic.flags = flags;
       
  4806       extra_ic.outer = class_InnerClasses_outer_RCN.getRefN();
       
  4807       CHECK_0;
       
  4808       extra_ic.name  = class_InnerClasses_name_RUN.getRefN();
       
  4809       CHECK_0;
       
  4810       // Detect if this is an exact copy of the global tuple.
       
  4811       if (global_ic != null) {
       
  4812         if (global_ic->flags != extra_ic.flags ||
       
  4813             global_ic->outer != extra_ic.outer ||
       
  4814             global_ic->name  != extra_ic.name) {
       
  4815           global_ic = null;  // not really the same, so break the link
       
  4816         }
       
  4817       }
       
  4818     }
       
  4819     if (global_ic != null && global_ic->requested) {
       
  4820       // This local repetition reverses the globally implied request.
       
  4821       global_ic->requested = false;
       
  4822       extra_ic.requested = false;
       
  4823       local_ics -= 1;
       
  4824     } else {
       
  4825       // The global either does not exist, or is not yet requested.
       
  4826       extra_ic.requested = true;
       
  4827       local_ics += 1;
       
  4828     }
       
  4829   }
       
  4830   // Finally, if there are any that survived, put them into an attribute.
       
  4831   // (Note that a zero-count attribute is always deleted.)
       
  4832   // The putref calls below will tell the constant pool to add any
       
  4833   // necessary local CP references to support the InnerClasses attribute.
       
  4834   // This step must be the last round of additions to the local CP.
       
  4835   if (local_ics > 0) {
       
  4836     // append the new attribute:
       
  4837     putref(cp.sym[cpool::s_InnerClasses]);
       
  4838     putu4(2 + 2*4*local_ics);
       
  4839     putu2(local_ics);
       
  4840     PTRLIST_QSORT(requested_ics, raw_address_cmp);
       
  4841     int num_global_ics = requested_ics.length();
       
  4842     for (int i = -num_global_ics; i < num_extra_ics; i++) {
       
  4843       inner_class* ic;
       
  4844       if (i < 0)
       
  4845         ic = (inner_class*) requested_ics.get(num_global_ics+i);
       
  4846       else
       
  4847         ic = &extra_ics[i];
       
  4848       if (ic->requested) {
       
  4849         putref(ic->inner);
       
  4850         putref(ic->outer);
       
  4851         putref(ic->name);
       
  4852         putu2(ic->flags);
       
  4853         NOT_PRODUCT(local_ics--);
       
  4854       }
       
  4855     }
       
  4856     assert(local_ics == 0);           // must balance
       
  4857     putu2_at(wp_at(naOffset), ++na);  // increment class attr count
       
  4858   }
       
  4859 
       
  4860   // Tidy up global 'requested' bits:
       
  4861   for (int i = requested_ics.length(); --i >= 0; ) {
       
  4862     inner_class* ic = (inner_class*) requested_ics.get(i);
       
  4863     ic->requested = false;
       
  4864   }
       
  4865   requested_ics.empty();
       
  4866   return na;
       
  4867 }
       
  4868 
       
  4869 /*
       
  4870  * Writes the BootstrapMethods attribute and returns the updated attribute count
       
  4871  */
       
  4872 int unpacker::write_bsms(int naOffset, int na) {
       
  4873   cur_class_local_bsm_count = cp.requested_bsms.length();
       
  4874   if (cur_class_local_bsm_count > 0) {
       
  4875     int    noes =           cp.outputEntries.length();
       
  4876     entry** oes = (entry**) cp.outputEntries.base();
       
  4877     PTRLIST_QSORT(cp.requested_bsms, outputEntry_cmp);
       
  4878     // append the BootstrapMethods attribute (after the InnerClasses attr):
       
  4879     putref(cp.sym[cpool::s_BootstrapMethods]);
       
  4880     // make a note of the offset, for lazy patching
       
  4881     int sizeOffset = (int)wpoffset();
       
  4882     putu4(-99);  // attr size will be patched
       
  4883     putu2(cur_class_local_bsm_count);
       
  4884     int written_bsms = 0;
       
  4885     for (int i = 0 ; i < cur_class_local_bsm_count ; i++) {
       
  4886       entry* e = (entry*)cp.requested_bsms.get(i);
       
  4887       assert(e->outputIndex != REQUESTED_NONE);
       
  4888       // output index is the index within the array
       
  4889       e->outputIndex = i;
       
  4890       putref(e->refs[0]);  // bsm
       
  4891       putu2(e->nrefs-1);  // number of args after bsm
       
  4892       for (int j = 1; j < e->nrefs; j++) {
       
  4893         putref(e->refs[j]);
       
  4894       }
       
  4895       written_bsms += 1;
       
  4896     }
       
  4897     assert(written_bsms == cur_class_local_bsm_count);  // else insane
       
  4898     byte* sizewp = wp_at(sizeOffset);
       
  4899     putu4_at(sizewp, (int)(wp - (sizewp+4)));  // size of code attr
       
  4900     putu2_at(wp_at(naOffset), ++na);  // increment class attr count
       
  4901   }
       
  4902   return na;
       
  4903 }
       
  4904 
       
  4905 void unpacker::write_classfile_tail() {
       
  4906 
       
  4907   cur_classfile_tail.empty();
       
  4908   set_output(&cur_classfile_tail);
       
  4909 
       
  4910   int i, num;
       
  4911 
       
  4912   attr_definitions& ad = attr_defs[ATTR_CONTEXT_CLASS];
       
  4913 
       
  4914   bool haveLongFlags = ad.haveLongFlags();
       
  4915   julong kflags = class_flags_hi.getLong(class_flags_lo, haveLongFlags);
       
  4916   julong indexMask = ad.flagIndexMask();
       
  4917 
       
  4918   cur_class = class_this.getRef();
       
  4919   CHECK;
       
  4920   cur_super = class_super.getRef();
       
  4921   CHECK;
       
  4922 
       
  4923   if (cur_super == cur_class)  cur_super = null;
       
  4924   // special representation for java/lang/Object
       
  4925 
       
  4926   putu2((ushort)(kflags & ~indexMask));
       
  4927   putref(cur_class);
       
  4928   putref(cur_super);
       
  4929 
       
  4930   putu2(num = class_interface_count.getInt());
       
  4931   for (i = 0; i < num; i++) {
       
  4932     putref(class_interface.getRef());
       
  4933     CHECK;
       
  4934   }
       
  4935 
       
  4936   write_members(class_field_count.getInt(),  ATTR_CONTEXT_FIELD);
       
  4937   write_members(class_method_count.getInt(), ATTR_CONTEXT_METHOD);
       
  4938   CHECK;
       
  4939 
       
  4940   cur_class_has_local_ics = false;  // may be set true by write_attrs
       
  4941 
       
  4942   int naOffset = (int)wpoffset();   // note the attr count location
       
  4943   int na = write_attrs(ATTR_CONTEXT_CLASS, (kflags & indexMask));
       
  4944   CHECK;
       
  4945 
       
  4946   na = write_bsms(naOffset, na);
       
  4947   CHECK;
       
  4948 
       
  4949   // choose which inner classes (if any) pertain to k:
       
  4950   na = write_ics(naOffset, na);
       
  4951   CHECK;
       
  4952 
       
  4953   close_output();
       
  4954   cp.computeOutputIndexes();
       
  4955 
       
  4956   // rewrite CP references in the tail
       
  4957   int nextref = 0;
       
  4958   for (i = 0; i < (int)class_fixup_type.size(); i++) {
       
  4959     int    type = class_fixup_type.getByte(i);
       
  4960     byte*  fixp = wp_at(class_fixup_offset.get(i));
       
  4961     entry* e    = (entry*)class_fixup_ref.get(nextref++);
       
  4962     int    idx  = e->getOutputIndex();
       
  4963     switch (type) {
       
  4964     case 1:  putu1_at(fixp, idx);  break;
       
  4965     case 2:  putu2_at(fixp, idx);  break;
       
  4966     default: assert(false);  // should not reach here
       
  4967     }
       
  4968   }
       
  4969   CHECK;
       
  4970 }
       
  4971 
       
  4972 void unpacker::write_classfile_head() {
       
  4973   cur_classfile_head.empty();
       
  4974   set_output(&cur_classfile_head);
       
  4975 
       
  4976   putu4(JAVA_MAGIC);
       
  4977   putu2(cur_class_minver);
       
  4978   putu2(cur_class_majver);
       
  4979   putu2(cp.outputIndexLimit);
       
  4980 
       
  4981   int checkIndex = 1;
       
  4982   int    noes =           cp.outputEntries.length();
       
  4983   entry** oes = (entry**) cp.outputEntries.base();
       
  4984   for (int i = 0; i < noes; i++) {
       
  4985     entry& e = *oes[i];
       
  4986     assert(e.getOutputIndex() == checkIndex++);
       
  4987     byte tag = e.tag;
       
  4988     assert(tag != CONSTANT_Signature);
       
  4989     putu1(tag);
       
  4990     switch (tag) {
       
  4991     case CONSTANT_Utf8:
       
  4992       putu2((int)e.value.b.len);
       
  4993       put_bytes(e.value.b);
       
  4994       break;
       
  4995     case CONSTANT_Integer:
       
  4996     case CONSTANT_Float:
       
  4997       putu4(e.value.i);
       
  4998       break;
       
  4999     case CONSTANT_Long:
       
  5000     case CONSTANT_Double:
       
  5001       putu8(e.value.l);
       
  5002       assert(checkIndex++);
       
  5003       break;
       
  5004     case CONSTANT_Class:
       
  5005     case CONSTANT_String:
       
  5006       // just write the ref
       
  5007       putu2(e.refs[0]->getOutputIndex());
       
  5008       break;
       
  5009     case CONSTANT_Fieldref:
       
  5010     case CONSTANT_Methodref:
       
  5011     case CONSTANT_InterfaceMethodref:
       
  5012     case CONSTANT_NameandType:
       
  5013     case CONSTANT_InvokeDynamic:
       
  5014       putu2(e.refs[0]->getOutputIndex());
       
  5015       putu2(e.refs[1]->getOutputIndex());
       
  5016       break;
       
  5017     case CONSTANT_MethodHandle:
       
  5018         putu1(e.value.i);
       
  5019         putu2(e.refs[0]->getOutputIndex());
       
  5020         break;
       
  5021     case CONSTANT_MethodType:
       
  5022       putu2(e.refs[0]->getOutputIndex());
       
  5023       break;
       
  5024     case CONSTANT_BootstrapMethod: // should not happen
       
  5025     default:
       
  5026       abort(ERROR_INTERNAL);
       
  5027     }
       
  5028   }
       
  5029 
       
  5030 #ifndef PRODUCT
       
  5031   total_cp_size[0] += cp.outputIndexLimit;
       
  5032   total_cp_size[1] += (int)cur_classfile_head.size();
       
  5033 #endif
       
  5034   close_output();
       
  5035 }
       
  5036 
       
  5037 unpacker::file* unpacker::get_next_file() {
       
  5038   CHECK_0;
       
  5039   free_temps();
       
  5040   if (files_remaining == 0) {
       
  5041     // Leave a clue that we're exhausted.
       
  5042     cur_file.name = null;
       
  5043     cur_file.size = null;
       
  5044     if (archive_size != 0) {
       
  5045       julong predicted_size = unsized_bytes_read + archive_size;
       
  5046       if (predicted_size != bytes_read)
       
  5047         abort("archive header had incorrect size");
       
  5048     }
       
  5049     return null;
       
  5050   }
       
  5051   files_remaining -= 1;
       
  5052   assert(files_written < file_count || classes_written < class_count);
       
  5053   cur_file.name = "";
       
  5054   cur_file.size = 0;
       
  5055   cur_file.modtime = default_file_modtime;
       
  5056   cur_file.options = default_file_options;
       
  5057   cur_file.data[0].set(null, 0);
       
  5058   cur_file.data[1].set(null, 0);
       
  5059   if (files_written < file_count) {
       
  5060     entry* e = file_name.getRef();
       
  5061     CHECK_0;
       
  5062     cur_file.name = e->utf8String();
       
  5063     CHECK_0;
       
  5064     bool haveLongSize = (testBit(archive_options, AO_HAVE_FILE_SIZE_HI));
       
  5065     cur_file.size = file_size_hi.getLong(file_size_lo, haveLongSize);
       
  5066     if (testBit(archive_options, AO_HAVE_FILE_MODTIME))
       
  5067       cur_file.modtime += file_modtime.getInt();  //relative to archive modtime
       
  5068     if (testBit(archive_options, AO_HAVE_FILE_OPTIONS))
       
  5069       cur_file.options |= file_options.getInt() & ~suppress_file_options;
       
  5070   } else if (classes_written < class_count) {
       
  5071     // there is a class for a missing file record
       
  5072     cur_file.options |= FO_IS_CLASS_STUB;
       
  5073   }
       
  5074   if ((cur_file.options & FO_IS_CLASS_STUB) != 0) {
       
  5075     assert(classes_written < class_count);
       
  5076     classes_written += 1;
       
  5077     if (cur_file.size != 0) {
       
  5078       abort("class file size transmitted");
       
  5079       return null;
       
  5080     }
       
  5081     reset_cur_classfile();
       
  5082 
       
  5083     // write the meat of the classfile:
       
  5084     write_classfile_tail();
       
  5085     cur_file.data[1] = cur_classfile_tail.b;
       
  5086     CHECK_0;
       
  5087 
       
  5088     // write the CP of the classfile, second:
       
  5089     write_classfile_head();
       
  5090     cur_file.data[0] = cur_classfile_head.b;
       
  5091     CHECK_0;
       
  5092 
       
  5093     cur_file.size += cur_file.data[0].len;
       
  5094     cur_file.size += cur_file.data[1].len;
       
  5095     if (cur_file.name[0] == '\0') {
       
  5096       bytes& prefix = cur_class->ref(0)->value.b;
       
  5097       const char* suffix = ".class";
       
  5098       int len = (int)(prefix.len + strlen(suffix));
       
  5099       bytes name; name.set(T_NEW(byte, add_size(len, 1)), len);
       
  5100       cur_file.name = name.strcat(prefix).strcat(suffix).strval();
       
  5101     }
       
  5102   } else {
       
  5103     // If there is buffered file data, produce a pointer to it.
       
  5104     if (cur_file.size != (size_t) cur_file.size) {
       
  5105       // Silly size specified.
       
  5106       abort("resource file too large");
       
  5107       return null;
       
  5108     }
       
  5109     size_t rpleft = input_remaining();
       
  5110     if (rpleft > 0) {
       
  5111       if (rpleft > cur_file.size)
       
  5112         rpleft = (size_t) cur_file.size;
       
  5113       cur_file.data[0].set(rp, rpleft);
       
  5114       rp += rpleft;
       
  5115     }
       
  5116     if (rpleft < cur_file.size) {
       
  5117       // Caller must read the rest.
       
  5118       size_t fleft = (size_t)cur_file.size - rpleft;
       
  5119       bytes_read += fleft;  // Credit it to the overall archive size.
       
  5120     }
       
  5121   }
       
  5122   CHECK_0;
       
  5123   bytes_written += cur_file.size;
       
  5124   files_written += 1;
       
  5125   return &cur_file;
       
  5126 }
       
  5127 
       
  5128 // Write a file to jarout.
       
  5129 void unpacker::write_file_to_jar(unpacker::file* f) {
       
  5130   size_t htsize = f->data[0].len + f->data[1].len;
       
  5131   julong fsize = f->size;
       
  5132 #ifndef PRODUCT
       
  5133   if (nowrite NOT_PRODUCT(|| skipfiles-- > 0)) {
       
  5134     PRINTCR((2,"would write %d bytes to %s", (int) fsize, f->name));
       
  5135     return;
       
  5136   }
       
  5137 #endif
       
  5138   if (htsize == fsize) {
       
  5139     jarout->addJarEntry(f->name, f->deflate_hint(), f->modtime,
       
  5140                         f->data[0], f->data[1]);
       
  5141   } else {
       
  5142     assert(input_remaining() == 0);
       
  5143     bytes part1, part2;
       
  5144     part1.len = f->data[0].len;
       
  5145     part1.set(T_NEW(byte, part1.len), part1.len);
       
  5146     part1.copyFrom(f->data[0]);
       
  5147     assert(f->data[1].len == 0);
       
  5148     part2.set(null, 0);
       
  5149     size_t fleft = (size_t) fsize - part1.len;
       
  5150     assert(bytes_read > fleft);  // part2 already credited by get_next_file
       
  5151     bytes_read -= fleft;
       
  5152     if (fleft > 0) {
       
  5153       // Must read some more.
       
  5154       if (live_input) {
       
  5155         // Stop using the input buffer.  Make a new one:
       
  5156         if (free_input)  input.free();
       
  5157         input.init(fleft > (1<<12) ? fleft : (1<<12));
       
  5158         free_input = true;
       
  5159         live_input = false;
       
  5160       } else {
       
  5161         // Make it large enough.
       
  5162         assert(free_input);  // must be reallocable
       
  5163         input.ensureSize(fleft);
       
  5164       }
       
  5165       rplimit = rp = input.base();
       
  5166       CHECK;
       
  5167       input.setLimit(rp + fleft);
       
  5168       if (!ensure_input(fleft))
       
  5169         abort("EOF reading resource file");
       
  5170       part2.ptr = input_scan();
       
  5171       part2.len = input_remaining();
       
  5172       rplimit = rp = input.base();
       
  5173     }
       
  5174     jarout->addJarEntry(f->name, f->deflate_hint(), f->modtime,
       
  5175                         part1, part2);
       
  5176   }
       
  5177   if (verbose >= 3) {
       
  5178     fprintf(errstrm, "Wrote "
       
  5179                      LONG_LONG_FORMAT " bytes to: %s\n", fsize, f->name);
       
  5180   }
       
  5181 }
       
  5182 
       
  5183 // Redirect the stdio to the specified file in the unpack.log.file option
       
  5184 void unpacker::redirect_stdio() {
       
  5185   if (log_file == null) {
       
  5186     log_file = LOGFILE_STDOUT;
       
  5187   }
       
  5188   if (log_file == errstrm_name)
       
  5189     // Nothing more to be done.
       
  5190     return;
       
  5191   errstrm_name = log_file;
       
  5192   if (strcmp(log_file, LOGFILE_STDERR) == 0) {
       
  5193     errstrm = stderr;
       
  5194     return;
       
  5195   } else if (strcmp(log_file, LOGFILE_STDOUT) == 0) {
       
  5196     errstrm = stdout;
       
  5197     return;
       
  5198   } else if (log_file[0] != '\0' && (errstrm = fopen(log_file,"a+")) != NULL) {
       
  5199     return;
       
  5200   } else {
       
  5201     fprintf(stderr, "Can not open log file %s\n", log_file);
       
  5202     // Last resort
       
  5203     // (Do not use stdout, since it might be jarout->jarfp.)
       
  5204     errstrm = stderr;
       
  5205     log_file = errstrm_name = LOGFILE_STDERR;
       
  5206   }
       
  5207 }
       
  5208 
       
  5209 #ifndef PRODUCT
       
  5210 int unpacker::printcr_if_verbose(int level, const char* fmt ...) {
       
  5211   if (verbose < level)  return 0;
       
  5212   va_list vl;
       
  5213   va_start(vl, fmt);
       
  5214   char fmtbuf[300];
       
  5215   strcpy(fmtbuf+100, fmt);
       
  5216   strcat(fmtbuf+100, "\n");
       
  5217   char* fmt2 = fmtbuf+100;
       
  5218   while (level-- > 0)  *--fmt2 = ' ';
       
  5219   vfprintf(errstrm, fmt2, vl);
       
  5220   return 1;  // for ?: usage
       
  5221 }
       
  5222 #endif
       
  5223 
       
  5224 void unpacker::abort(const char* message) {
       
  5225   if (message == null)  message = "error unpacking archive";
       
  5226 #ifdef UNPACK_JNI
       
  5227   if (message[0] == '@') {  // secret convention for sprintf
       
  5228      bytes saved;
       
  5229      saved.saveFrom(message+1);
       
  5230      mallocs.add(message = saved.strval());
       
  5231    }
       
  5232   abort_message = message;
       
  5233   return;
       
  5234 #else
       
  5235   if (message[0] == '@')  ++message;
       
  5236   fprintf(errstrm, "%s\n", message);
       
  5237 #ifndef PRODUCT
       
  5238   fflush(errstrm);
       
  5239   ::abort();
       
  5240 #else
       
  5241   exit(-1);
       
  5242 #endif
       
  5243 #endif // JNI
       
  5244 }