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