author | ohair |
Tue, 28 Dec 2010 15:53:50 -0800 | |
changeset 7668 | d4a77089c587 |
parent 7192 | 445c518364c4 |
child 7816 | 55a18147b4bf |
permissions | -rw-r--r-- |
2 | 1 |
/* |
7668 | 2 |
* Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved. |
2 | 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 |
|
5506 | 7 |
* published by the Free Software Foundation. Oracle designates this |
2 | 8 |
* particular file as subject to the "Classpath" exception as provided |
5506 | 9 |
* by Oracle in the LICENSE file that accompanied this code. |
2 | 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 |
* |
|
5506 | 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. |
|
2 | 24 |
*/ |
25 |
||
26 |
package com.sun.java.util.jar.pack; |
|
27 |
||
7192
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
28 |
import com.sun.java.util.jar.pack.ConstantPool.ClassEntry; |
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
29 |
import com.sun.java.util.jar.pack.ConstantPool.DescriptorEntry; |
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
30 |
import com.sun.java.util.jar.pack.ConstantPool.Entry; |
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
31 |
import com.sun.java.util.jar.pack.ConstantPool.Index; |
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
32 |
import com.sun.java.util.jar.pack.ConstantPool.IndexGroup; |
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
33 |
import com.sun.java.util.jar.pack.ConstantPool.MemberEntry; |
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
34 |
import com.sun.java.util.jar.pack.ConstantPool.NumberEntry; |
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
35 |
import com.sun.java.util.jar.pack.ConstantPool.SignatureEntry; |
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
36 |
import com.sun.java.util.jar.pack.ConstantPool.StringEntry; |
2 | 37 |
import com.sun.java.util.jar.pack.Package.Class; |
38 |
import com.sun.java.util.jar.pack.Package.File; |
|
39 |
import com.sun.java.util.jar.pack.Package.InnerClass; |
|
7192
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
40 |
import java.io.IOException; |
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
41 |
import java.io.OutputStream; |
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
42 |
import java.io.PrintStream; |
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
43 |
import java.util.ArrayList; |
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
44 |
import java.util.Arrays; |
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
45 |
import java.util.Comparator; |
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
46 |
import java.util.HashMap; |
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
47 |
import java.util.HashSet; |
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
48 |
import java.util.Iterator; |
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
49 |
import java.util.List; |
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
50 |
import java.util.ListIterator; |
445c518364c4
7003227: (pack200) intermittent failures compiling pack200
ksrini
parents:
5506
diff
changeset
|
51 |
import java.util.Map; |
2 | 52 |
|
53 |
/** |
|
54 |
* Writer for a package file. |
|
55 |
* @author John Rose |
|
56 |
*/ |
|
57 |
class PackageWriter extends BandStructure { |
|
58 |
Package pkg; |
|
59 |
OutputStream finalOut; |
|
60 |
||
61 |
PackageWriter(Package pkg, OutputStream out) throws IOException { |
|
62 |
this.pkg = pkg; |
|
63 |
this.finalOut = out; |
|
64 |
// Caller has specified archive version in the package: |
|
65 |
initPackageMajver(pkg.package_majver); |
|
66 |
} |
|
67 |
||
68 |
void write() throws IOException { |
|
69 |
boolean ok = false; |
|
70 |
try { |
|
71 |
if (verbose > 0) { |
|
72 |
Utils.log.info("Setting up constant pool..."); |
|
73 |
} |
|
74 |
setup(); |
|
75 |
||
76 |
if (verbose > 0) { |
|
77 |
Utils.log.info("Packing..."); |
|
78 |
} |
|
79 |
||
80 |
// writeFileHeader() is done last, since it has ultimate counts |
|
81 |
// writeBandHeaders() is called after all other bands are done |
|
82 |
writeConstantPool(); |
|
83 |
writeFiles(); |
|
84 |
writeAttrDefs(); |
|
85 |
writeInnerClasses(); |
|
86 |
writeClassesAndByteCodes(); |
|
87 |
writeAttrCounts(); |
|
88 |
||
89 |
if (verbose > 1) printCodeHist(); |
|
90 |
||
91 |
// choose codings (fill band_headers if needed) |
|
92 |
if (verbose > 0) { |
|
93 |
Utils.log.info("Coding..."); |
|
94 |
} |
|
95 |
all_bands.chooseBandCodings(); |
|
96 |
||
97 |
// now we can write the headers: |
|
98 |
writeFileHeader(); |
|
99 |
||
100 |
writeAllBandsTo(finalOut); |
|
101 |
||
102 |
ok = true; |
|
103 |
} catch (Exception ee) { |
|
4919 | 104 |
Utils.log.warning("Error on output: "+ee, ee); |
2 | 105 |
//if (verbose > 0) ee.printStackTrace(); |
106 |
// Write partial output only if we are verbose. |
|
107 |
if (verbose > 0) finalOut.close(); |
|
108 |
if (ee instanceof IOException) throw (IOException)ee; |
|
109 |
if (ee instanceof RuntimeException) throw (RuntimeException)ee; |
|
110 |
throw new Error("error packing", ee); |
|
111 |
} |
|
112 |
} |
|
113 |
||
114 |
HashSet requiredEntries; // for the CP |
|
115 |
HashMap backCountTable; // for layout callables |
|
116 |
int[][] attrCounts; // count attr. occurences |
|
117 |
||
118 |
void setup() { |
|
119 |
requiredEntries = new HashSet(); |
|
120 |
setArchiveOptions(); |
|
121 |
trimClassAttributes(); |
|
122 |
collectAttributeLayouts(); |
|
123 |
pkg.buildGlobalConstantPool(requiredEntries); |
|
124 |
setBandIndexes(); |
|
125 |
makeNewAttributeBands(); |
|
126 |
collectInnerClasses(); |
|
127 |
} |
|
128 |
||
129 |
void setArchiveOptions() { |
|
130 |
// Decide on some archive options early. |
|
131 |
// Does not decide on: AO_HAVE_SPECIAL_FORMATS, |
|
132 |
// AO_HAVE_CP_NUMBERS, AO_HAVE_FILE_HEADERS. |
|
133 |
// Also, AO_HAVE_FILE_OPTIONS may be forced on later. |
|
134 |
int minModtime = pkg.default_modtime; |
|
135 |
int maxModtime = pkg.default_modtime; |
|
136 |
int minOptions = -1; |
|
137 |
int maxOptions = 0; |
|
138 |
||
139 |
// Import defaults from package (deflate hint, etc.). |
|
140 |
archiveOptions |= pkg.default_options; |
|
141 |
||
142 |
for (Iterator i = pkg.files.iterator(); i.hasNext(); ) { |
|
143 |
File file = (File) i.next(); |
|
144 |
||
145 |
int modtime = file.modtime; |
|
146 |
int options = file.options; |
|
147 |
||
148 |
if (minModtime == NO_MODTIME) { |
|
149 |
minModtime = maxModtime = modtime; |
|
150 |
} else { |
|
151 |
if (minModtime > modtime) minModtime = modtime; |
|
152 |
if (maxModtime < modtime) maxModtime = modtime; |
|
153 |
} |
|
154 |
minOptions &= options; |
|
155 |
maxOptions |= options; |
|
156 |
} |
|
157 |
if (pkg.default_modtime == NO_MODTIME) { |
|
158 |
// Make everything else be a positive offset from here. |
|
159 |
pkg.default_modtime = minModtime; |
|
160 |
} |
|
161 |
if (minModtime != NO_MODTIME && minModtime != maxModtime) { |
|
162 |
// Put them into a band. |
|
163 |
archiveOptions |= AO_HAVE_FILE_MODTIME; |
|
164 |
} |
|
165 |
// If the archive deflation is set do not bother with each file. |
|
166 |
if (!testBit(archiveOptions,AO_DEFLATE_HINT) && minOptions != -1) { |
|
167 |
if (testBit(minOptions, FO_DEFLATE_HINT)) { |
|
168 |
// Every file has the deflate_hint set. |
|
169 |
// Set it for the whole archive, and omit options. |
|
170 |
archiveOptions |= AO_DEFLATE_HINT; |
|
171 |
minOptions -= FO_DEFLATE_HINT; |
|
172 |
maxOptions -= FO_DEFLATE_HINT; |
|
173 |
} |
|
174 |
pkg.default_options |= minOptions; |
|
175 |
if (minOptions != maxOptions |
|
176 |
|| minOptions != pkg.default_options) { |
|
177 |
archiveOptions |= AO_HAVE_FILE_OPTIONS; |
|
178 |
} |
|
179 |
} |
|
180 |
// Decide on default version number (majority rule). |
|
181 |
HashMap verCounts = new HashMap(); |
|
182 |
int bestCount = 0; |
|
183 |
int bestVersion = -1; |
|
184 |
for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) { |
|
185 |
Class cls = (Class) i.next(); |
|
186 |
int version = cls.getVersion(); |
|
187 |
int[] var = (int[]) verCounts.get(new Integer(version)); |
|
188 |
if (var == null) { |
|
189 |
var = new int[1]; |
|
190 |
verCounts.put(new Integer(version), var); |
|
191 |
} |
|
192 |
int count = (var[0] += 1); |
|
193 |
//System.out.println("version="+version+" count="+count); |
|
194 |
if (bestCount < count) { |
|
195 |
bestCount = count; |
|
196 |
bestVersion = version; |
|
197 |
} |
|
198 |
} |
|
199 |
verCounts.clear(); |
|
200 |
if (bestVersion == -1) bestVersion = 0; // degenerate case |
|
201 |
int bestMajver = (char)(bestVersion >>> 16); |
|
202 |
int bestMinver = (char)(bestVersion); |
|
203 |
pkg.default_class_majver = (short) bestMajver; |
|
204 |
pkg.default_class_minver = (short) bestMinver; |
|
205 |
String bestVerStr = Package.versionStringOf(bestMajver, bestMinver); |
|
206 |
if (verbose > 0) |
|
207 |
Utils.log.info("Consensus version number in segment is "+bestVerStr); |
|
208 |
if (verbose > 0) |
|
209 |
Utils.log.info("Highest version number in segment is "+ |
|
210 |
Package.versionStringOf(pkg.getHighestClassVersion())); |
|
211 |
||
212 |
// Now add explicit pseudo-attrs. to classes with odd versions. |
|
213 |
for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) { |
|
214 |
Class cls = (Class) i.next(); |
|
215 |
||
216 |
if (cls.getVersion() != bestVersion) { |
|
217 |
Attribute a = makeClassFileVersionAttr(cls.minver, cls.majver); |
|
218 |
if (verbose > 1) { |
|
219 |
String clsVer = cls.getVersionString(); |
|
220 |
String pkgVer = bestVerStr; |
|
221 |
Utils.log.fine("Version "+clsVer+" of "+cls |
|
222 |
+" doesn't match package version " |
|
223 |
+pkgVer); |
|
224 |
} |
|
225 |
// Note: Does not add in "natural" order. (Who cares?) |
|
226 |
cls.addAttribute(a); |
|
227 |
} |
|
228 |
} |
|
229 |
||
230 |
// Decide if we are transmitting a huge resource file: |
|
231 |
for (Iterator i = pkg.files.iterator(); i.hasNext(); ) { |
|
232 |
File file = (File) i.next(); |
|
233 |
long len = file.getFileLength(); |
|
234 |
if (len != (int)len) { |
|
235 |
archiveOptions |= AO_HAVE_FILE_SIZE_HI; |
|
236 |
if (verbose > 0) |
|
237 |
Utils.log.info("Note: Huge resource file "+file.getFileName()+" forces 64-bit sizing"); |
|
238 |
break; |
|
239 |
} |
|
240 |
} |
|
241 |
||
242 |
// Decide if code attributes typically have sub-attributes. |
|
243 |
// In that case, to preserve compact 1-byte code headers, |
|
244 |
// we must declare unconditional presence of code flags. |
|
245 |
int cost0 = 0; |
|
246 |
int cost1 = 0; |
|
247 |
for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) { |
|
248 |
Class cls = (Class) i.next(); |
|
249 |
for (Iterator j = cls.getMethods().iterator(); j.hasNext(); ) { |
|
250 |
Class.Method m = (Class.Method) j.next(); |
|
251 |
if (m.code != null) { |
|
252 |
if (m.code.attributeSize() == 0) { |
|
253 |
// cost of a useless unconditional flags byte |
|
254 |
cost1 += 1; |
|
255 |
} else if (shortCodeHeader(m.code) != LONG_CODE_HEADER) { |
|
256 |
// cost of inflating a short header |
|
257 |
cost0 += 3; |
|
258 |
} |
|
259 |
} |
|
260 |
} |
|
261 |
} |
|
262 |
if (cost0 > cost1) { |
|
263 |
archiveOptions |= AO_HAVE_ALL_CODE_FLAGS; |
|
264 |
} |
|
265 |
if (verbose > 0) |
|
266 |
Utils.log.info("archiveOptions = " |
|
267 |
+"0b"+Integer.toBinaryString(archiveOptions)); |
|
268 |
} |
|
269 |
||
270 |
void writeFileHeader() throws IOException { |
|
271 |
pkg.checkVersion(); |
|
272 |
writeArchiveMagic(); |
|
273 |
writeArchiveHeader(); |
|
274 |
} |
|
275 |
||
276 |
// Local routine used to format fixed-format scalars |
|
277 |
// in the file_header: |
|
278 |
private void putMagicInt32(int val) throws IOException { |
|
279 |
int res = val; |
|
280 |
for (int i = 0; i < 4; i++) { |
|
281 |
archive_magic.putByte(0xFF & (res >>> 24)); |
|
282 |
res <<= 8; |
|
283 |
} |
|
284 |
} |
|
285 |
||
286 |
void writeArchiveMagic() throws IOException { |
|
287 |
putMagicInt32(pkg.magic); |
|
288 |
} |
|
289 |
||
290 |
void writeArchiveHeader() throws IOException { |
|
291 |
// for debug only: number of words optimized away |
|
292 |
int headerDiscountForDebug = 0; |
|
293 |
||
294 |
// AO_HAVE_SPECIAL_FORMATS is set if non-default |
|
295 |
// coding techniques are used, or if there are |
|
296 |
// compressor-defined attributes transmitted. |
|
297 |
boolean haveSpecial = testBit(archiveOptions, AO_HAVE_SPECIAL_FORMATS); |
|
298 |
if (!haveSpecial) { |
|
299 |
haveSpecial |= (band_headers.length() != 0); |
|
300 |
haveSpecial |= (attrDefsWritten.length != 0); |
|
301 |
if (haveSpecial) |
|
302 |
archiveOptions |= AO_HAVE_SPECIAL_FORMATS; |
|
303 |
} |
|
304 |
if (!haveSpecial) |
|
305 |
headerDiscountForDebug += AH_SPECIAL_FORMAT_LEN; |
|
306 |
||
307 |
// AO_HAVE_FILE_HEADERS is set if there is any |
|
308 |
// file or segment envelope information present. |
|
309 |
boolean haveFiles = testBit(archiveOptions, AO_HAVE_FILE_HEADERS); |
|
310 |
if (!haveFiles) { |
|
311 |
haveFiles |= (archiveNextCount > 0); |
|
312 |
haveFiles |= (pkg.default_modtime != NO_MODTIME); |
|
313 |
if (haveFiles) |
|
314 |
archiveOptions |= AO_HAVE_FILE_HEADERS; |
|
315 |
} |
|
316 |
if (!haveFiles) |
|
317 |
headerDiscountForDebug += AH_FILE_HEADER_LEN; |
|
318 |
||
319 |
// AO_HAVE_CP_NUMBERS is set if there are any numbers |
|
320 |
// in the global constant pool. (Numbers are in 15% of classes.) |
|
321 |
boolean haveNumbers = testBit(archiveOptions, AO_HAVE_CP_NUMBERS); |
|
322 |
if (!haveNumbers) { |
|
323 |
haveNumbers |= pkg.cp.haveNumbers(); |
|
324 |
if (haveNumbers) |
|
325 |
archiveOptions |= AO_HAVE_CP_NUMBERS; |
|
326 |
} |
|
327 |
if (!haveNumbers) |
|
328 |
headerDiscountForDebug += AH_CP_NUMBER_LEN; |
|
329 |
||
330 |
assert(pkg.package_majver > 0); // caller must specify! |
|
331 |
archive_header_0.putInt(pkg.package_minver); |
|
332 |
archive_header_0.putInt(pkg.package_majver); |
|
333 |
if (verbose > 0) |
|
334 |
Utils.log.info("Package Version for this segment:"+ |
|
335 |
Package.versionStringOf(pkg.getPackageVersion())); |
|
336 |
archive_header_0.putInt(archiveOptions); // controls header format |
|
337 |
assert(archive_header_0.length() == AH_LENGTH_0); |
|
338 |
||
339 |
final int DUMMY = 0; |
|
340 |
if (haveFiles) { |
|
341 |
assert(archive_header_S.length() == AH_ARCHIVE_SIZE_HI); |
|
342 |
archive_header_S.putInt(DUMMY); // (archiveSize1 >>> 32) |
|
343 |
assert(archive_header_S.length() == AH_ARCHIVE_SIZE_LO); |
|
344 |
archive_header_S.putInt(DUMMY); // (archiveSize1 >>> 0) |
|
345 |
assert(archive_header_S.length() == AH_LENGTH_S); |
|
346 |
} |
|
347 |
||
348 |
// Done with unsized part of header.... |
|
349 |
||
350 |
if (haveFiles) { |
|
351 |
archive_header_1.putInt(archiveNextCount); // usually zero |
|
352 |
archive_header_1.putInt(pkg.default_modtime); |
|
353 |
archive_header_1.putInt(pkg.files.size()); |
|
354 |
} else { |
|
355 |
assert(pkg.files.size() == 0); |
|
356 |
} |
|
357 |
||
358 |
if (haveSpecial) { |
|
359 |
archive_header_1.putInt(band_headers.length()); |
|
360 |
archive_header_1.putInt(attrDefsWritten.length); |
|
361 |
} else { |
|
362 |
assert(band_headers.length() == 0); |
|
363 |
assert(attrDefsWritten.length == 0); |
|
364 |
} |
|
365 |
||
366 |
writeConstantPoolCounts(haveNumbers); |
|
367 |
||
368 |
archive_header_1.putInt(pkg.getAllInnerClasses().size()); |
|
369 |
archive_header_1.putInt(pkg.default_class_minver); |
|
370 |
archive_header_1.putInt(pkg.default_class_majver); |
|
371 |
archive_header_1.putInt(pkg.classes.size()); |
|
372 |
||
373 |
// Sanity: Make sure we came out to 26 (less optional fields): |
|
374 |
assert(archive_header_0.length() + |
|
375 |
archive_header_S.length() + |
|
376 |
archive_header_1.length() |
|
377 |
== AH_LENGTH - headerDiscountForDebug); |
|
378 |
||
379 |
// Figure out all the sizes now, first cut: |
|
380 |
archiveSize0 = 0; |
|
381 |
archiveSize1 = all_bands.outputSize(); |
|
382 |
// Second cut: |
|
383 |
archiveSize0 += archive_magic.outputSize(); |
|
384 |
archiveSize0 += archive_header_0.outputSize(); |
|
385 |
archiveSize0 += archive_header_S.outputSize(); |
|
386 |
// Make the adjustments: |
|
387 |
archiveSize1 -= archiveSize0; |
|
388 |
||
389 |
// Patch the header: |
|
390 |
if (haveFiles) { |
|
391 |
int archiveSizeHi = (int)(archiveSize1 >>> 32); |
|
392 |
int archiveSizeLo = (int)(archiveSize1 >>> 0); |
|
393 |
archive_header_S.patchValue(AH_ARCHIVE_SIZE_HI, archiveSizeHi); |
|
394 |
archive_header_S.patchValue(AH_ARCHIVE_SIZE_LO, archiveSizeLo); |
|
395 |
int zeroLen = UNSIGNED5.getLength(DUMMY); |
|
396 |
archiveSize0 += UNSIGNED5.getLength(archiveSizeHi) - zeroLen; |
|
397 |
archiveSize0 += UNSIGNED5.getLength(archiveSizeLo) - zeroLen; |
|
398 |
} |
|
399 |
if (verbose > 1) |
|
400 |
Utils.log.fine("archive sizes: "+ |
|
401 |
archiveSize0+"+"+archiveSize1); |
|
402 |
assert(all_bands.outputSize() == archiveSize0+archiveSize1); |
|
403 |
} |
|
404 |
||
405 |
void writeConstantPoolCounts(boolean haveNumbers) throws IOException { |
|
406 |
for (int k = 0; k < ConstantPool.TAGS_IN_ORDER.length; k++) { |
|
407 |
byte tag = ConstantPool.TAGS_IN_ORDER[k]; |
|
408 |
int count = pkg.cp.getIndexByTag(tag).size(); |
|
409 |
switch (tag) { |
|
410 |
case CONSTANT_Utf8: |
|
411 |
// The null string is always first. |
|
412 |
if (count > 0) |
|
413 |
assert(pkg.cp.getIndexByTag(tag).get(0) |
|
414 |
== ConstantPool.getUtf8Entry("")); |
|
415 |
break; |
|
416 |
||
417 |
case CONSTANT_Integer: |
|
418 |
case CONSTANT_Float: |
|
419 |
case CONSTANT_Long: |
|
420 |
case CONSTANT_Double: |
|
421 |
// Omit counts for numbers if possible. |
|
422 |
if (!haveNumbers) { |
|
423 |
assert(count == 0); |
|
424 |
continue; |
|
425 |
} |
|
426 |
break; |
|
427 |
} |
|
428 |
archive_header_1.putInt(count); |
|
429 |
} |
|
430 |
} |
|
431 |
||
432 |
protected Index getCPIndex(byte tag) { |
|
433 |
return pkg.cp.getIndexByTag(tag); |
|
434 |
} |
|
435 |
||
436 |
// (The following observations are out of date; they apply only to |
|
437 |
// "banding" the constant pool itself. Later revisions of this algorithm |
|
438 |
// applied the banding technique to every part of the package file, |
|
439 |
// applying the benefits more broadly.) |
|
440 |
||
441 |
// Note: Keeping the data separate in passes (or "bands") allows the |
|
442 |
// compressor to issue significantly shorter indexes for repeated data. |
|
443 |
// The difference in zipped size is 4%, which is remarkable since the |
|
444 |
// unzipped sizes are the same (only the byte order differs). |
|
445 |
||
446 |
// After moving similar data into bands, it becomes natural to delta-encode |
|
447 |
// each band. (This is especially useful if we sort the constant pool first.) |
|
448 |
// Delta encoding saves an extra 5% in the output size (13% of the CP itself). |
|
449 |
// Because a typical delta usees much less data than a byte, the savings after |
|
450 |
// zipping is even better: A zipped delta-encoded package is 8% smaller than |
|
451 |
// a zipped non-delta-encoded package. Thus, in the zipped file, a banded, |
|
452 |
// delta-encoded constant pool saves over 11% (of the total file size) compared |
|
453 |
// with a zipped unbanded file. |
|
454 |
||
455 |
void writeConstantPool() throws IOException { |
|
456 |
IndexGroup cp = pkg.cp; |
|
457 |
||
458 |
if (verbose > 0) Utils.log.info("Writing CP"); |
|
459 |
||
460 |
for (int k = 0; k < ConstantPool.TAGS_IN_ORDER.length; k++) { |
|
461 |
byte tag = ConstantPool.TAGS_IN_ORDER[k]; |
|
462 |
Index index = cp.getIndexByTag(tag); |
|
463 |
||
464 |
Entry[] cpMap = index.cpMap; |
|
465 |
if (verbose > 0) |
|
466 |
Utils.log.info("Writing "+cpMap.length+" "+ConstantPool.tagName(tag)+" entries..."); |
|
467 |
||
468 |
if (optDumpBands) { |
|
469 |
PrintStream ps = new PrintStream(getDumpStream(index, ".idx")); |
|
470 |
printArrayTo(ps, cpMap, 0, cpMap.length); |
|
471 |
ps.close(); |
|
472 |
} |
|
473 |
||
474 |
switch (tag) { |
|
475 |
case CONSTANT_Utf8: |
|
476 |
writeUtf8Bands(cpMap); |
|
477 |
break; |
|
478 |
case CONSTANT_Integer: |
|
479 |
for (int i = 0; i < cpMap.length; i++) { |
|
480 |
NumberEntry e = (NumberEntry) cpMap[i]; |
|
481 |
int x = ((Integer)e.numberValue()).intValue(); |
|
482 |
cp_Int.putInt(x); |
|
483 |
} |
|
484 |
break; |
|
485 |
case CONSTANT_Float: |
|
486 |
for (int i = 0; i < cpMap.length; i++) { |
|
487 |
NumberEntry e = (NumberEntry) cpMap[i]; |
|
488 |
float fx = ((Float)e.numberValue()).floatValue(); |
|
489 |
int x = Float.floatToIntBits(fx); |
|
490 |
cp_Float.putInt(x); |
|
491 |
} |
|
492 |
break; |
|
493 |
case CONSTANT_Long: |
|
494 |
for (int i = 0; i < cpMap.length; i++) { |
|
495 |
NumberEntry e = (NumberEntry) cpMap[i]; |
|
496 |
long x = ((Long)e.numberValue()).longValue(); |
|
497 |
cp_Long_hi.putInt((int)(x >>> 32)); |
|
498 |
cp_Long_lo.putInt((int)(x >>> 0)); |
|
499 |
} |
|
500 |
break; |
|
501 |
case CONSTANT_Double: |
|
502 |
for (int i = 0; i < cpMap.length; i++) { |
|
503 |
NumberEntry e = (NumberEntry) cpMap[i]; |
|
504 |
double dx = ((Double)e.numberValue()).doubleValue(); |
|
505 |
long x = Double.doubleToLongBits(dx); |
|
506 |
cp_Double_hi.putInt((int)(x >>> 32)); |
|
507 |
cp_Double_lo.putInt((int)(x >>> 0)); |
|
508 |
} |
|
509 |
break; |
|
510 |
case CONSTANT_String: |
|
511 |
for (int i = 0; i < cpMap.length; i++) { |
|
512 |
StringEntry e = (StringEntry) cpMap[i]; |
|
513 |
cp_String.putRef(e.ref); |
|
514 |
} |
|
515 |
break; |
|
516 |
case CONSTANT_Class: |
|
517 |
for (int i = 0; i < cpMap.length; i++) { |
|
518 |
ClassEntry e = (ClassEntry) cpMap[i]; |
|
519 |
cp_Class.putRef(e.ref); |
|
520 |
} |
|
521 |
break; |
|
522 |
case CONSTANT_Signature: |
|
523 |
writeSignatureBands(cpMap); |
|
524 |
break; |
|
525 |
case CONSTANT_NameandType: |
|
526 |
for (int i = 0; i < cpMap.length; i++) { |
|
527 |
DescriptorEntry e = (DescriptorEntry) cpMap[i]; |
|
528 |
cp_Descr_name.putRef(e.nameRef); |
|
529 |
cp_Descr_type.putRef(e.typeRef); |
|
530 |
} |
|
531 |
break; |
|
532 |
case CONSTANT_Fieldref: |
|
533 |
writeMemberRefs(tag, cpMap, cp_Field_class, cp_Field_desc); |
|
534 |
break; |
|
535 |
case CONSTANT_Methodref: |
|
536 |
writeMemberRefs(tag, cpMap, cp_Method_class, cp_Method_desc); |
|
537 |
break; |
|
538 |
case CONSTANT_InterfaceMethodref: |
|
539 |
writeMemberRefs(tag, cpMap, cp_Imethod_class, cp_Imethod_desc); |
|
540 |
break; |
|
541 |
default: |
|
542 |
assert(false); |
|
543 |
} |
|
544 |
} |
|
545 |
} |
|
546 |
||
547 |
void writeUtf8Bands(Entry[] cpMap) throws IOException { |
|
548 |
if (cpMap.length == 0) |
|
549 |
return; // nothing to write |
|
550 |
||
551 |
// The first element must always be the empty string. |
|
552 |
assert(cpMap[0].stringValue().equals("")); |
|
553 |
final int SUFFIX_SKIP_1 = 1; |
|
554 |
final int PREFIX_SKIP_2 = 2; |
|
555 |
||
556 |
// Fetch the char arrays, first of all. |
|
557 |
char[][] chars = new char[cpMap.length][]; |
|
558 |
for (int i = 0; i < chars.length; i++) { |
|
559 |
chars[i] = cpMap[i].stringValue().toCharArray(); |
|
560 |
} |
|
561 |
||
562 |
// First band: Write lengths of shared prefixes. |
|
563 |
int[] prefixes = new int[cpMap.length]; // includes 2 skipped zeroes |
|
564 |
char[] prevChars = {}; |
|
565 |
for (int i = 0; i < chars.length; i++) { |
|
566 |
int prefix = 0; |
|
567 |
char[] curChars = chars[i]; |
|
568 |
int limit = Math.min(curChars.length, prevChars.length); |
|
569 |
while (prefix < limit && curChars[prefix] == prevChars[prefix]) |
|
570 |
prefix++; |
|
571 |
prefixes[i] = prefix; |
|
572 |
if (i >= PREFIX_SKIP_2) |
|
573 |
cp_Utf8_prefix.putInt(prefix); |
|
574 |
else |
|
575 |
assert(prefix == 0); |
|
576 |
prevChars = curChars; |
|
577 |
} |
|
578 |
||
579 |
// Second band: Write lengths of unshared suffixes. |
|
580 |
// Third band: Write the char values in the unshared suffixes. |
|
581 |
for (int i = 0; i < chars.length; i++) { |
|
582 |
char[] str = chars[i]; |
|
583 |
int prefix = prefixes[i]; |
|
584 |
int suffix = str.length - prefixes[i]; |
|
585 |
boolean isPacked = false; |
|
586 |
if (suffix == 0) { |
|
587 |
// Zero suffix length is special flag to indicate |
|
588 |
// separate treatment in cp_Utf8_big bands. |
|
589 |
// This suffix length never occurs naturally, |
|
590 |
// except in the one case of a zero-length string. |
|
591 |
// (If it occurs, it is the first, due to sorting.) |
|
592 |
// The zero length string must, paradoxically, be |
|
593 |
// encoded as a zero-length cp_Utf8_big band. |
|
594 |
// This wastes exactly (& tolerably) one null byte. |
|
595 |
isPacked = (i >= SUFFIX_SKIP_1); |
|
596 |
// Do not bother to add an empty "(Utf8_big_0)" band. |
|
597 |
// Also, the initial empty string does not require a band. |
|
598 |
} else if (optBigStrings && effort > 1 && suffix > 100) { |
|
599 |
int numWide = 0; |
|
600 |
for (int n = 0; n < suffix; n++) { |
|
601 |
if (str[prefix+n] > 127) { |
|
602 |
numWide++; |
|
603 |
} |
|
604 |
} |
|
605 |
if (numWide > 100) { |
|
606 |
// Try packing the chars with an alternate encoding. |
|
607 |
isPacked = tryAlternateEncoding(i, numWide, str, prefix); |
|
608 |
} |
|
609 |
} |
|
610 |
if (i < SUFFIX_SKIP_1) { |
|
611 |
// No output. |
|
612 |
assert(!isPacked); |
|
613 |
assert(suffix == 0); |
|
614 |
} else if (isPacked) { |
|
615 |
// Mark packed string with zero-length suffix count. |
|
616 |
// This tells the unpacker to go elsewhere for the suffix bits. |
|
617 |
// Fourth band: Write unshared suffix with alternate coding. |
|
618 |
cp_Utf8_suffix.putInt(0); |
|
619 |
cp_Utf8_big_suffix.putInt(suffix); |
|
620 |
} else { |
|
621 |
assert(suffix != 0); // would be ambiguous |
|
622 |
// Normal string. Save suffix in third and fourth bands. |
|
623 |
cp_Utf8_suffix.putInt(suffix); |
|
624 |
for (int n = 0; n < suffix; n++) { |
|
625 |
int ch = str[prefix+n]; |
|
626 |
cp_Utf8_chars.putInt(ch); |
|
627 |
} |
|
628 |
} |
|
629 |
} |
|
630 |
if (verbose > 0) { |
|
631 |
int normCharCount = cp_Utf8_chars.length(); |
|
632 |
int packCharCount = cp_Utf8_big_chars.length(); |
|
633 |
int charCount = normCharCount + packCharCount; |
|
634 |
Utils.log.info("Utf8string #CHARS="+charCount+" #PACKEDCHARS="+packCharCount); |
|
635 |
} |
|
636 |
} |
|
637 |
||
638 |
private boolean tryAlternateEncoding(int i, int numWide, |
|
639 |
char[] str, int prefix) { |
|
640 |
int suffix = str.length - prefix; |
|
641 |
int[] cvals = new int[suffix]; |
|
642 |
for (int n = 0; n < suffix; n++) { |
|
643 |
cvals[n] = str[prefix+n]; |
|
644 |
} |
|
645 |
CodingChooser cc = getCodingChooser(); |
|
646 |
Coding bigRegular = cp_Utf8_big_chars.regularCoding; |
|
647 |
String bandName = "(Utf8_big_"+i+")"; |
|
648 |
int[] sizes = { 0, 0 }; |
|
649 |
final int BYTE_SIZE = CodingChooser.BYTE_SIZE; |
|
650 |
final int ZIP_SIZE = CodingChooser.ZIP_SIZE; |
|
651 |
if (verbose > 1 || cc.verbose > 1) { |
|
652 |
Utils.log.fine("--- chooseCoding "+bandName); |
|
653 |
} |
|
654 |
CodingMethod special = cc.choose(cvals, bigRegular, sizes); |
|
655 |
Coding charRegular = cp_Utf8_chars.regularCoding; |
|
656 |
if (verbose > 1) |
|
657 |
Utils.log.fine("big string["+i+"] len="+suffix+" #wide="+numWide+" size="+sizes[BYTE_SIZE]+"/z="+sizes[ZIP_SIZE]+" coding "+special); |
|
658 |
if (special != charRegular) { |
|
659 |
int specialZipSize = sizes[ZIP_SIZE]; |
|
660 |
int[] normalSizes = cc.computeSize(charRegular, cvals); |
|
661 |
int normalZipSize = normalSizes[ZIP_SIZE]; |
|
662 |
int minWin = Math.max(5, normalZipSize/1000); |
|
663 |
if (verbose > 1) |
|
664 |
Utils.log.fine("big string["+i+"] normalSize="+normalSizes[BYTE_SIZE]+"/z="+normalSizes[ZIP_SIZE]+" win="+(specialZipSize<normalZipSize-minWin)); |
|
665 |
if (specialZipSize < normalZipSize-minWin) { |
|
666 |
IntBand big = cp_Utf8_big_chars.newIntBand(bandName); |
|
667 |
big.initializeValues(cvals); |
|
668 |
return true; |
|
669 |
} |
|
670 |
} |
|
671 |
return false; |
|
672 |
} |
|
673 |
||
674 |
void writeSignatureBands(Entry[] cpMap) throws IOException { |
|
675 |
for (int i = 0; i < cpMap.length; i++) { |
|
676 |
SignatureEntry e = (SignatureEntry) cpMap[i]; |
|
677 |
cp_Signature_form.putRef(e.formRef); |
|
678 |
for (int j = 0; j < e.classRefs.length; j++) { |
|
679 |
cp_Signature_classes.putRef(e.classRefs[j]); |
|
680 |
} |
|
681 |
} |
|
682 |
} |
|
683 |
||
684 |
void writeMemberRefs(byte tag, Entry[] cpMap, CPRefBand cp_class, CPRefBand cp_desc) throws IOException { |
|
685 |
for (int i = 0; i < cpMap.length; i++) { |
|
686 |
MemberEntry e = (MemberEntry) cpMap[i]; |
|
687 |
cp_class.putRef(e.classRef); |
|
688 |
cp_desc.putRef(e.descRef); |
|
689 |
} |
|
690 |
} |
|
691 |
||
692 |
void writeFiles() throws IOException { |
|
693 |
int numFiles = pkg.files.size(); |
|
694 |
if (numFiles == 0) return; |
|
695 |
int options = archiveOptions; |
|
696 |
boolean haveSizeHi = testBit(options, AO_HAVE_FILE_SIZE_HI); |
|
697 |
boolean haveModtime = testBit(options, AO_HAVE_FILE_MODTIME); |
|
698 |
boolean haveOptions = testBit(options, AO_HAVE_FILE_OPTIONS); |
|
699 |
if (!haveOptions) { |
|
700 |
for (Iterator i = pkg.files.iterator(); i.hasNext(); ) { |
|
701 |
File file = (File) i.next(); |
|
702 |
if (file.isClassStub()) { |
|
703 |
haveOptions = true; |
|
704 |
options |= AO_HAVE_FILE_OPTIONS; |
|
705 |
archiveOptions = options; |
|
706 |
break; |
|
707 |
} |
|
708 |
} |
|
709 |
} |
|
710 |
if (haveSizeHi || haveModtime || haveOptions || !pkg.files.isEmpty()) { |
|
711 |
options |= AO_HAVE_FILE_HEADERS; |
|
712 |
archiveOptions = options; |
|
713 |
} |
|
714 |
||
715 |
for (Iterator i = pkg.files.iterator(); i.hasNext(); ) { |
|
716 |
File file = (File) i.next(); |
|
717 |
file_name.putRef(file.name); |
|
718 |
long len = file.getFileLength(); |
|
719 |
file_size_lo.putInt((int)len); |
|
720 |
if (haveSizeHi) |
|
721 |
file_size_hi.putInt((int)(len >>> 32)); |
|
722 |
if (haveModtime) |
|
723 |
file_modtime.putInt(file.modtime - pkg.default_modtime); |
|
724 |
if (haveOptions) |
|
725 |
file_options.putInt(file.options); |
|
726 |
file.writeTo(file_bits.collectorStream()); |
|
727 |
if (verbose > 1) |
|
728 |
Utils.log.fine("Wrote "+len+" bytes of "+file.name.stringValue()); |
|
729 |
} |
|
730 |
if (verbose > 0) |
|
731 |
Utils.log.info("Wrote "+numFiles+" resource files"); |
|
732 |
} |
|
733 |
||
734 |
void collectAttributeLayouts() { |
|
735 |
maxFlags = new int[ATTR_CONTEXT_LIMIT]; |
|
736 |
allLayouts = new HashMap[ATTR_CONTEXT_LIMIT]; |
|
737 |
for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) { |
|
738 |
allLayouts[i] = new HashMap(); |
|
739 |
} |
|
740 |
// Collect maxFlags and allLayouts. |
|
741 |
for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) { |
|
742 |
Class cls = (Class) i.next(); |
|
743 |
visitAttributeLayoutsIn(ATTR_CONTEXT_CLASS, cls); |
|
744 |
for (Iterator j = cls.getFields().iterator(); j.hasNext(); ) { |
|
745 |
Class.Field f = (Class.Field) j.next(); |
|
746 |
visitAttributeLayoutsIn(ATTR_CONTEXT_FIELD, f); |
|
747 |
} |
|
748 |
for (Iterator j = cls.getMethods().iterator(); j.hasNext(); ) { |
|
749 |
Class.Method m = (Class.Method) j.next(); |
|
750 |
visitAttributeLayoutsIn(ATTR_CONTEXT_METHOD, m); |
|
751 |
if (m.code != null) { |
|
752 |
visitAttributeLayoutsIn(ATTR_CONTEXT_CODE, m.code); |
|
753 |
} |
|
754 |
} |
|
755 |
} |
|
756 |
// If there are many species of attributes, use 63-bit flags. |
|
757 |
for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) { |
|
758 |
int nl = allLayouts[i].size(); |
|
759 |
boolean haveLongFlags = haveFlagsHi(i); |
|
760 |
final int TOO_MANY_ATTRS = 32 /*int flag size*/ |
|
761 |
- 12 /*typical flag bits in use*/ |
|
762 |
+ 4 /*typical number of OK overflows*/; |
|
763 |
if (nl >= TOO_MANY_ATTRS) { // heuristic |
|
764 |
int mask = 1<<(LG_AO_HAVE_XXX_FLAGS_HI+i); |
|
765 |
archiveOptions |= mask; |
|
766 |
haveLongFlags = true; |
|
767 |
if (verbose > 0) |
|
768 |
Utils.log.info("Note: Many "+Attribute.contextName(i)+" attributes forces 63-bit flags"); |
|
769 |
} |
|
770 |
if (verbose > 1) { |
|
771 |
Utils.log.fine(Attribute.contextName(i)+".maxFlags = 0x"+Integer.toHexString(maxFlags[i])); |
|
772 |
Utils.log.fine(Attribute.contextName(i)+".#layouts = "+nl); |
|
773 |
} |
|
774 |
assert(haveFlagsHi(i) == haveLongFlags); |
|
775 |
} |
|
776 |
initAttrIndexLimit(); |
|
777 |
||
778 |
// Standard indexes can never conflict with flag bits. Assert it. |
|
779 |
for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) { |
|
780 |
assert((attrFlagMask[i] & maxFlags[i]) == 0); |
|
781 |
} |
|
782 |
// Collect counts for both predefs. and custom defs. |
|
783 |
// Decide on custom, local attribute definitions. |
|
784 |
backCountTable = new HashMap(); |
|
785 |
attrCounts = new int[ATTR_CONTEXT_LIMIT][]; |
|
786 |
for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) { |
|
787 |
// Now the remaining defs in allLayouts[i] need attr. indexes. |
|
788 |
// Fill up unused flag bits with new defs. |
|
789 |
// Unused bits are those which are not used by predefined attrs, |
|
790 |
// and which are always clear in the classfiles. |
|
791 |
long avHiBits = ~(maxFlags[i] | attrFlagMask[i]); |
|
792 |
assert(attrIndexLimit[i] > 0); |
|
793 |
assert(attrIndexLimit[i] < 64); // all bits fit into a Java long |
|
794 |
avHiBits &= (1L<<attrIndexLimit[i])-1; |
|
795 |
int nextLoBit = 0; |
|
796 |
Map.Entry[] layoutsAndCounts = new Map.Entry[allLayouts[i].size()]; |
|
797 |
allLayouts[i].entrySet().toArray(layoutsAndCounts); |
|
798 |
// Sort by count, most frequent first. |
|
799 |
// Predefs. participate in this sort, though it does not matter. |
|
800 |
Arrays.sort(layoutsAndCounts, new Comparator() { |
|
801 |
public int compare(Object o0, Object o1) { |
|
802 |
Map.Entry e0 = (Map.Entry) o0; |
|
803 |
Map.Entry e1 = (Map.Entry) o1; |
|
804 |
// Primary sort key is count, reversed. |
|
805 |
int r = - ( ((int[])e0.getValue())[0] |
|
806 |
- ((int[])e1.getValue())[0] ); |
|
807 |
if (r != 0) return r; |
|
808 |
return ((Comparable)e0.getKey()).compareTo(e1.getKey()); |
|
809 |
} |
|
810 |
}); |
|
811 |
attrCounts[i] = new int[attrIndexLimit[i]+layoutsAndCounts.length]; |
|
812 |
for (int j = 0; j < layoutsAndCounts.length; j++) { |
|
813 |
Map.Entry e = layoutsAndCounts[j]; |
|
814 |
Attribute.Layout def = (Attribute.Layout) e.getKey(); |
|
815 |
int count = ((int[])e.getValue())[0]; |
|
816 |
int index; |
|
817 |
Integer predefIndex = (Integer) attrIndexTable.get(def); |
|
818 |
if (predefIndex != null) { |
|
819 |
// The index is already set. |
|
820 |
index = predefIndex.intValue(); |
|
821 |
} else if (avHiBits != 0) { |
|
822 |
while ((avHiBits & 1) == 0) { |
|
823 |
avHiBits >>>= 1; |
|
824 |
nextLoBit += 1; |
|
825 |
} |
|
826 |
avHiBits -= 1; // clear low bit; we are using it now |
|
827 |
// Update attrIndexTable: |
|
828 |
index = setAttributeLayoutIndex(def, nextLoBit); |
|
829 |
} else { |
|
830 |
// Update attrIndexTable: |
|
831 |
index = setAttributeLayoutIndex(def, ATTR_INDEX_OVERFLOW); |
|
832 |
} |
|
833 |
||
834 |
// Now that we know the index, record the count of this def. |
|
835 |
attrCounts[i][index] = count; |
|
836 |
||
837 |
// For all callables in the def, keep a tally of back-calls. |
|
838 |
Attribute.Layout.Element[] cbles = def.getCallables(); |
|
839 |
final int[] bc = new int[cbles.length]; |
|
840 |
for (int k = 0; k < cbles.length; k++) { |
|
841 |
assert(cbles[k].kind == Attribute.EK_CBLE); |
|
842 |
if (!cbles[k].flagTest(Attribute.EF_BACK)) { |
|
843 |
bc[k] = -1; // no count to accumulate here |
|
844 |
} |
|
845 |
} |
|
846 |
backCountTable.put(def, bc); |
|
847 |
||
848 |
if (predefIndex == null) { |
|
849 |
// Make sure the package CP can name the local attribute. |
|
850 |
Entry ne = ConstantPool.getUtf8Entry(def.name()); |
|
851 |
String layout = def.layoutForPackageMajver(getPackageMajver()); |
|
852 |
Entry le = ConstantPool.getUtf8Entry(layout); |
|
853 |
requiredEntries.add(ne); |
|
854 |
requiredEntries.add(le); |
|
855 |
if (verbose > 0) { |
|
856 |
if (index < attrIndexLimit[i]) |
|
857 |
Utils.log.info("Using free flag bit 1<<"+index+" for "+count+" occurrences of "+def); |
|
858 |
else |
|
859 |
Utils.log.info("Using overflow index "+index+" for "+count+" occurrences of "+def); |
|
860 |
} |
|
861 |
} |
|
862 |
} |
|
863 |
} |
|
864 |
// Later, when emitting attr_definition_bands, we will look at |
|
865 |
// attrDefSeen and attrDefs at position 32/63 and beyond. |
|
866 |
// The attrIndexTable will provide elements of xxx_attr_indexes bands. |
|
867 |
||
868 |
// Done with scratch variables: |
|
869 |
maxFlags = null; |
|
870 |
allLayouts = null; |
|
871 |
} |
|
872 |
||
873 |
// Scratch variables for processing attributes and flags. |
|
874 |
int[] maxFlags; |
|
875 |
HashMap[] allLayouts; |
|
876 |
||
877 |
void visitAttributeLayoutsIn(int ctype, Attribute.Holder h) { |
|
878 |
// Make note of which flags appear in the class file. |
|
879 |
// Set them in maxFlags. |
|
880 |
maxFlags[ctype] |= h.flags; |
|
881 |
for (Iterator i = h.getAttributes().iterator(); i.hasNext(); ) { |
|
882 |
Attribute a = (Attribute) i.next(); |
|
883 |
Attribute.Layout def = a.layout(); |
|
884 |
int[] count = (int[]) allLayouts[ctype].get(def); |
|
885 |
if (count == null) |
|
886 |
allLayouts[ctype].put(def, count = new int[1]); |
|
887 |
if (count[0] < Integer.MAX_VALUE) |
|
888 |
count[0] += 1; |
|
889 |
} |
|
890 |
} |
|
891 |
||
892 |
Attribute.Layout[] attrDefsWritten; |
|
893 |
||
894 |
void writeAttrDefs() throws IOException { |
|
895 |
ArrayList defList = new ArrayList(); |
|
896 |
for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) { |
|
897 |
int limit = attrDefs[i].size(); |
|
898 |
for (int j = 0; j < limit; j++) { |
|
899 |
int header = i; // ctype |
|
900 |
if (j < attrIndexLimit[i]) { |
|
901 |
header |= ((j + ADH_BIT_IS_LSB) << ADH_BIT_SHIFT); |
|
902 |
assert(header < 0x100); // must fit into a byte |
|
903 |
// (...else header is simply ctype, with zero high bits.) |
|
904 |
if (!testBit(attrDefSeen[i], 1L<<j)) { |
|
905 |
// either undefined or predefined; nothing to write |
|
906 |
continue; |
|
907 |
} |
|
908 |
} |
|
909 |
Attribute.Layout def = (Attribute.Layout) attrDefs[i].get(j); |
|
910 |
defList.add(new Object[]{ new Integer(header), def }); |
|
911 |
assert(new Integer(j).equals(attrIndexTable.get(def))); |
|
912 |
} |
|
913 |
} |
|
914 |
// Sort the new attr defs into some "natural" order. |
|
915 |
int numAttrDefs = defList.size(); |
|
916 |
Object[][] defs = new Object[numAttrDefs][]; |
|
917 |
defList.toArray(defs); |
|
918 |
Arrays.sort(defs, new Comparator() { |
|
919 |
public int compare(Object o0, Object o1) { |
|
920 |
Object[] a0 = (Object[]) o0; |
|
921 |
Object[] a1 = (Object[]) o1; |
|
922 |
// Primary sort key is attr def header. |
|
923 |
int r = ((Comparable)a0[0]).compareTo(a1[0]); |
|
924 |
if (r != 0) return r; |
|
925 |
Object ind0 = attrIndexTable.get(a0[1]); |
|
926 |
Object ind1 = attrIndexTable.get(a1[1]); |
|
927 |
// Secondary sort key is attribute index. |
|
928 |
// (This must be so, in order to keep overflow attr order.) |
|
929 |
assert(ind0 != null); |
|
930 |
assert(ind1 != null); |
|
931 |
return ((Comparable)ind0).compareTo(ind1); |
|
932 |
} |
|
933 |
}); |
|
934 |
attrDefsWritten = new Attribute.Layout[numAttrDefs]; |
|
935 |
PrintStream dump = !optDumpBands ? null |
|
936 |
: new PrintStream(getDumpStream(attr_definition_headers, ".def")); |
|
937 |
int[] indexForDebug = new int[ATTR_CONTEXT_LIMIT]; |
|
938 |
for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) { |
|
939 |
indexForDebug[i] = attrIndexLimit[i]; |
|
940 |
} |
|
941 |
for (int i = 0; i < defs.length; i++) { |
|
942 |
int header = ((Integer)defs[i][0]).intValue(); |
|
943 |
Attribute.Layout def = (Attribute.Layout) defs[i][1]; |
|
944 |
attrDefsWritten[i] = def; |
|
945 |
assert((header & ADH_CONTEXT_MASK) == def.ctype()); |
|
946 |
attr_definition_headers.putByte(header); |
|
947 |
attr_definition_name.putRef(ConstantPool.getUtf8Entry(def.name())); |
|
948 |
String layout = def.layoutForPackageMajver(getPackageMajver()); |
|
949 |
attr_definition_layout.putRef(ConstantPool.getUtf8Entry(layout)); |
|
950 |
// Check that we are transmitting that correct attribute index: |
|
951 |
boolean debug = false; |
|
952 |
assert(debug = true); |
|
953 |
if (debug) { |
|
954 |
int hdrIndex = (header >> ADH_BIT_SHIFT) - ADH_BIT_IS_LSB; |
|
955 |
if (hdrIndex < 0) hdrIndex = indexForDebug[def.ctype()]++; |
|
956 |
int realIndex = ((Integer) attrIndexTable.get(def)).intValue(); |
|
957 |
assert(hdrIndex == realIndex); |
|
958 |
} |
|
959 |
if (dump != null) { |
|
960 |
int index = (header >> ADH_BIT_SHIFT) - ADH_BIT_IS_LSB; |
|
961 |
dump.println(index+" "+def); |
|
962 |
} |
|
963 |
} |
|
964 |
if (dump != null) dump.close(); |
|
965 |
} |
|
966 |
||
967 |
void writeAttrCounts() throws IOException { |
|
968 |
// Write the four xxx_attr_calls bands. |
|
969 |
for (int ctype = 0; ctype < ATTR_CONTEXT_LIMIT; ctype++) { |
|
970 |
MultiBand xxx_attr_bands = attrBands[ctype]; |
|
971 |
IntBand xxx_attr_calls = getAttrBand(xxx_attr_bands, AB_ATTR_CALLS); |
|
972 |
Attribute.Layout[] defs = new Attribute.Layout[attrDefs[ctype].size()]; |
|
973 |
attrDefs[ctype].toArray(defs); |
|
974 |
for (boolean predef = true; ; predef = false) { |
|
975 |
for (int ai = 0; ai < defs.length; ai++) { |
|
976 |
Attribute.Layout def = defs[ai]; |
|
977 |
if (def == null) continue; // unused index |
|
978 |
if (predef != isPredefinedAttr(ctype, ai)) |
|
979 |
continue; // wrong pass |
|
980 |
int totalCount = attrCounts[ctype][ai]; |
|
981 |
if (totalCount == 0) |
|
982 |
continue; // irrelevant |
|
983 |
int[] bc = (int[]) backCountTable.get(def); |
|
984 |
for (int j = 0; j < bc.length; j++) { |
|
985 |
if (bc[j] >= 0) { |
|
986 |
int backCount = bc[j]; |
|
987 |
bc[j] = -1; // close out; do not collect further counts |
|
988 |
xxx_attr_calls.putInt(backCount); |
|
989 |
assert(def.getCallables()[j].flagTest(Attribute.EF_BACK)); |
|
990 |
} else { |
|
991 |
assert(!def.getCallables()[j].flagTest(Attribute.EF_BACK)); |
|
992 |
} |
|
993 |
} |
|
994 |
} |
|
995 |
if (!predef) break; |
|
996 |
} |
|
997 |
} |
|
998 |
} |
|
999 |
||
1000 |
void trimClassAttributes() { |
|
1001 |
for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) { |
|
1002 |
Class cls = (Class) i.next(); |
|
1003 |
// Replace "obvious" SourceFile attrs by null. |
|
1004 |
cls.minimizeSourceFile(); |
|
1005 |
} |
|
1006 |
} |
|
1007 |
||
1008 |
void collectInnerClasses() { |
|
1009 |
// Capture inner classes, removing them from individual classes. |
|
1010 |
// Irregular inner classes must stay local, though. |
|
1011 |
HashMap allICMap = new HashMap(); |
|
1012 |
// First, collect a consistent global set. |
|
1013 |
for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) { |
|
1014 |
Class cls = (Class) i.next(); |
|
1015 |
if (!cls.hasInnerClasses()) continue; |
|
1016 |
for (Iterator j = cls.getInnerClasses().iterator(); j.hasNext(); ) { |
|
1017 |
InnerClass ic = (InnerClass) j.next(); |
|
1018 |
InnerClass pic = (InnerClass) allICMap.put(ic.thisClass, ic); |
|
1019 |
if (pic != null && !pic.equals(ic) && pic.predictable) { |
|
1020 |
// Different ICs. Choose the better to make global. |
|
1021 |
allICMap.put(pic.thisClass, pic); |
|
1022 |
} |
|
1023 |
} |
|
1024 |
} |
|
1025 |
||
1026 |
InnerClass[] allICs = new InnerClass[allICMap.size()]; |
|
1027 |
allICMap.values().toArray(allICs); |
|
1028 |
allICMap = null; // done with it |
|
1029 |
||
1030 |
// Note: The InnerClasses attribute must be in a valid order, |
|
1031 |
// so that A$B always occurs earlier than A$B$C. This is an |
|
1032 |
// important side-effect of sorting lexically by class name. |
|
1033 |
Arrays.sort(allICs); // put in canonical order |
|
1034 |
pkg.setAllInnerClasses(Arrays.asList(allICs)); |
|
1035 |
||
1036 |
// Next, empty out of every local set the consistent entries. |
|
1037 |
// Calculate whether there is any remaining need to have a local |
|
1038 |
// set, and whether it needs to be locked. |
|
1039 |
for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) { |
|
1040 |
Class cls = (Class) i.next(); |
|
1041 |
cls.minimizeLocalICs(); |
|
1042 |
} |
|
1043 |
} |
|
1044 |
||
1045 |
void writeInnerClasses() throws IOException { |
|
1046 |
for (Iterator i = pkg.getAllInnerClasses().iterator(); i.hasNext(); ) { |
|
1047 |
InnerClass ic = (InnerClass) i.next(); |
|
1048 |
int flags = ic.flags; |
|
1049 |
assert((flags & ACC_IC_LONG_FORM) == 0); |
|
1050 |
if (!ic.predictable) { |
|
1051 |
flags |= ACC_IC_LONG_FORM; |
|
1052 |
} |
|
1053 |
ic_this_class.putRef(ic.thisClass); |
|
1054 |
ic_flags.putInt(flags); |
|
1055 |
if (!ic.predictable) { |
|
1056 |
ic_outer_class.putRef(ic.outerClass); |
|
1057 |
ic_name.putRef(ic.name); |
|
1058 |
} |
|
1059 |
} |
|
1060 |
} |
|
1061 |
||
1062 |
/** If there are any extra InnerClasses entries to write which are |
|
1063 |
* not already implied by the global table, put them into a |
|
1064 |
* local attribute. This is expected to be rare. |
|
1065 |
*/ |
|
1066 |
void writeLocalInnerClasses(Class cls) throws IOException { |
|
1067 |
List localICs = cls.getInnerClasses(); |
|
1068 |
class_InnerClasses_N.putInt(localICs.size()); |
|
1069 |
for (Iterator i = localICs.iterator(); i.hasNext(); ) { |
|
1070 |
InnerClass ic = (InnerClass) i.next(); |
|
1071 |
class_InnerClasses_RC.putRef(ic.thisClass); |
|
1072 |
// Is it redundant with the global version? |
|
1073 |
if (ic.equals(pkg.getGlobalInnerClass(ic.thisClass))) { |
|
1074 |
// A zero flag means copy a global IC here. |
|
1075 |
class_InnerClasses_F.putInt(0); |
|
1076 |
} else { |
|
1077 |
int flags = ic.flags; |
|
1078 |
if (flags == 0) |
|
1079 |
flags = ACC_IC_LONG_FORM; // force it to be non-zero |
|
1080 |
class_InnerClasses_F.putInt(flags); |
|
1081 |
class_InnerClasses_outer_RCN.putRef(ic.outerClass); |
|
1082 |
class_InnerClasses_name_RUN.putRef(ic.name); |
|
1083 |
} |
|
1084 |
} |
|
1085 |
} |
|
1086 |
||
1087 |
void writeClassesAndByteCodes() throws IOException { |
|
1088 |
Class[] classes = new Class[pkg.classes.size()]; |
|
1089 |
pkg.classes.toArray(classes); |
|
1090 |
// Note: This code respects the order in which caller put classes. |
|
1091 |
if (verbose > 0) |
|
1092 |
Utils.log.info(" ...scanning "+classes.length+" classes..."); |
|
1093 |
||
1094 |
int nwritten = 0; |
|
1095 |
for (int i = 0; i < classes.length; i++) { |
|
1096 |
// Collect the class body, sans bytecodes. |
|
1097 |
Class cls = classes[i]; |
|
1098 |
if (verbose > 1) |
|
1099 |
Utils.log.fine("Scanning "+cls); |
|
1100 |
||
1101 |
ClassEntry thisClass = cls.thisClass; |
|
1102 |
ClassEntry superClass = cls.superClass; |
|
1103 |
ClassEntry[] interfaces = cls.interfaces; |
|
1104 |
// Encode rare case of null superClass as thisClass: |
|
1105 |
assert(superClass != thisClass); // bad class file!? |
|
1106 |
if (superClass == null) superClass = thisClass; |
|
1107 |
class_this.putRef(thisClass); |
|
1108 |
class_super.putRef(superClass); |
|
1109 |
class_interface_count.putInt(cls.interfaces.length); |
|
1110 |
for (int j = 0; j < interfaces.length; j++) { |
|
1111 |
class_interface.putRef(interfaces[j]); |
|
1112 |
} |
|
1113 |
||
1114 |
writeMembers(cls); |
|
1115 |
writeAttrs(ATTR_CONTEXT_CLASS, cls, cls); |
|
1116 |
||
1117 |
nwritten++; |
|
1118 |
if (verbose > 0 && (nwritten % 1000) == 0) |
|
1119 |
Utils.log.info("Have scanned "+nwritten+" classes..."); |
|
1120 |
} |
|
1121 |
} |
|
1122 |
||
1123 |
void writeMembers(Class cls) throws IOException { |
|
1124 |
List fields = cls.getFields(); |
|
1125 |
class_field_count.putInt(fields.size()); |
|
1126 |
for (Iterator i = fields.iterator(); i.hasNext(); ) { |
|
1127 |
Class.Field f = (Class.Field) i.next(); |
|
1128 |
field_descr.putRef(f.getDescriptor()); |
|
1129 |
writeAttrs(ATTR_CONTEXT_FIELD, f, cls); |
|
1130 |
} |
|
1131 |
||
1132 |
List methods = cls.getMethods(); |
|
1133 |
class_method_count.putInt(methods.size()); |
|
1134 |
for (Iterator i = methods.iterator(); i.hasNext(); ) { |
|
1135 |
Class.Method m = (Class.Method) i.next(); |
|
1136 |
method_descr.putRef(m.getDescriptor()); |
|
1137 |
writeAttrs(ATTR_CONTEXT_METHOD, m, cls); |
|
1138 |
assert((m.code != null) == (m.getAttribute(attrCodeEmpty) != null)); |
|
1139 |
if (m.code != null) { |
|
1140 |
writeCodeHeader(m.code); |
|
1141 |
writeByteCodes(m.code); |
|
1142 |
} |
|
1143 |
} |
|
1144 |
} |
|
1145 |
||
1146 |
void writeCodeHeader(Code c) throws IOException { |
|
1147 |
boolean attrsOK = testBit(archiveOptions, AO_HAVE_ALL_CODE_FLAGS); |
|
1148 |
int na = c.attributeSize(); |
|
1149 |
int sc = shortCodeHeader(c); |
|
1150 |
if (!attrsOK && na > 0) |
|
1151 |
// We must write flags, and can only do so for long headers. |
|
1152 |
sc = LONG_CODE_HEADER; |
|
1153 |
if (verbose > 2) { |
|
1154 |
int siglen = c.getMethod().getArgumentSize(); |
|
1155 |
Utils.log.fine("Code sizes info "+c.max_stack+" "+c.max_locals+" "+c.getHandlerCount()+" "+siglen+" "+na+(sc > 0 ? " SHORT="+sc : "")); |
|
1156 |
} |
|
1157 |
code_headers.putByte(sc); |
|
1158 |
if (sc == LONG_CODE_HEADER) { |
|
1159 |
code_max_stack.putInt(c.getMaxStack()); |
|
1160 |
code_max_na_locals.putInt(c.getMaxNALocals()); |
|
1161 |
code_handler_count.putInt(c.getHandlerCount()); |
|
1162 |
} else { |
|
1163 |
assert(attrsOK || na == 0); |
|
1164 |
assert(c.getHandlerCount() < shortCodeHeader_h_limit); |
|
1165 |
} |
|
1166 |
writeCodeHandlers(c); |
|
1167 |
if (sc == LONG_CODE_HEADER || attrsOK) |
|
1168 |
writeAttrs(ATTR_CONTEXT_CODE, c, c.thisClass()); |
|
1169 |
} |
|
1170 |
||
1171 |
void writeCodeHandlers(Code c) throws IOException { |
|
1172 |
int sum, del; |
|
1173 |
for (int j = 0, jmax = c.getHandlerCount(); j < jmax; j++) { |
|
1174 |
code_handler_class_RCN.putRef(c.handler_class[j]); // null OK |
|
1175 |
// Encode end as offset from start, and catch as offset from end, |
|
1176 |
// because they are strongly correlated. |
|
1177 |
sum = c.encodeBCI(c.handler_start[j]); |
|
1178 |
code_handler_start_P.putInt(sum); |
|
1179 |
del = c.encodeBCI(c.handler_end[j]) - sum; |
|
1180 |
code_handler_end_PO.putInt(del); |
|
1181 |
sum += del; |
|
1182 |
del = c.encodeBCI(c.handler_catch[j]) - sum; |
|
1183 |
code_handler_catch_PO.putInt(del); |
|
1184 |
} |
|
1185 |
} |
|
1186 |
||
1187 |
// Generic routines for writing attributes and flags of |
|
1188 |
// classes, fields, methods, and codes. |
|
1189 |
void writeAttrs(int ctype, |
|
1190 |
final Attribute.Holder h, |
|
1191 |
Class cls) throws IOException { |
|
1192 |
MultiBand xxx_attr_bands = attrBands[ctype]; |
|
1193 |
IntBand xxx_flags_hi = getAttrBand(xxx_attr_bands, AB_FLAGS_HI); |
|
1194 |
IntBand xxx_flags_lo = getAttrBand(xxx_attr_bands, AB_FLAGS_LO); |
|
1195 |
boolean haveLongFlags = haveFlagsHi(ctype); |
|
1196 |
assert(attrIndexLimit[ctype] == (haveLongFlags? 63: 32)); |
|
1197 |
if (h.attributes == null) { |
|
1198 |
xxx_flags_lo.putInt(h.flags); // no extra bits to set here |
|
1199 |
if (haveLongFlags) |
|
1200 |
xxx_flags_hi.putInt(0); |
|
1201 |
return; |
|
1202 |
} |
|
1203 |
if (verbose > 3) |
|
1204 |
Utils.log.fine("Transmitting attrs for "+h+" flags="+Integer.toHexString(h.flags)); |
|
1205 |
||
1206 |
long flagMask = attrFlagMask[ctype]; // which flags are attr bits? |
|
1207 |
long flagsToAdd = 0; |
|
1208 |
int overflowCount = 0; |
|
1209 |
for (ListIterator j = h.attributes.listIterator(); j.hasNext(); ) { |
|
1210 |
Attribute a = (Attribute) j.next(); |
|
1211 |
Attribute.Layout def = a.layout(); |
|
1212 |
int index = ((Integer)attrIndexTable.get(def)).intValue(); |
|
1213 |
assert(attrDefs[ctype].get(index) == def); |
|
1214 |
if (verbose > 3) |
|
1215 |
Utils.log.fine("add attr @"+index+" "+a+" in "+h); |
|
1216 |
if (index < attrIndexLimit[ctype] && testBit(flagMask, 1L<<index)) { |
|
1217 |
if (verbose > 3) |
|
1218 |
Utils.log.fine("Adding flag bit 1<<"+index+" in "+Long.toHexString(flagMask)); |
|
1219 |
assert(!testBit(h.flags, 1L<<index)); |
|
1220 |
flagsToAdd |= (1L<<index); |
|
1221 |
flagMask -= (1L<<index); // do not use this bit twice here |
|
1222 |
} else { |
|
1223 |
// an overflow attr. |
|
1224 |
flagsToAdd |= (1L<<X_ATTR_OVERFLOW); |
|
1225 |
overflowCount += 1; |
|
1226 |
if (verbose > 3) |
|
1227 |
Utils.log.fine("Adding overflow attr #"+overflowCount); |
|
1228 |
IntBand xxx_attr_indexes = getAttrBand(xxx_attr_bands, AB_ATTR_INDEXES); |
|
1229 |
xxx_attr_indexes.putInt(index); |
|
1230 |
// System.out.println("overflow @"+index); |
|
1231 |
} |
|
1232 |
if (def.bandCount == 0) { |
|
1233 |
if (def == attrInnerClassesEmpty) { |
|
1234 |
// Special logic to write this attr. |
|
1235 |
writeLocalInnerClasses((Class) h); |
|
1236 |
continue; |
|
1237 |
} |
|
1238 |
// Empty attr; nothing more to write here. |
|
1239 |
continue; |
|
1240 |
} |
|
1241 |
assert(a.fixups == null); |
|
1242 |
final Band[] ab = (Band[]) attrBandTable.get(def); |
|
1243 |
assert(ab != null); |
|
1244 |
assert(ab.length == def.bandCount); |
|
1245 |
final int[] bc = (int[]) backCountTable.get(def); |
|
1246 |
assert(bc != null); |
|
1247 |
assert(bc.length == def.getCallables().length); |
|
1248 |
// Write one attribute of type def into ab. |
|
1249 |
if (verbose > 2) Utils.log.fine("writing "+a+" in "+h); |
|
1250 |
boolean isCV = (ctype == ATTR_CONTEXT_FIELD && def == attrConstantValue); |
|
1251 |
if (isCV) setConstantValueIndex((Class.Field)h); |
|
1252 |
a.parse(cls, a.bytes(), 0, a.size(), |
|
1253 |
new Attribute.ValueStream() { |
|
1254 |
public void putInt(int bandIndex, int value) { |
|
1255 |
((IntBand) ab[bandIndex]).putInt(value); |
|
1256 |
} |
|
1257 |
public void putRef(int bandIndex, Entry ref) { |
|
1258 |
((CPRefBand) ab[bandIndex]).putRef(ref); |
|
1259 |
} |
|
1260 |
public int encodeBCI(int bci) { |
|
1261 |
Code code = (Code) h; |
|
1262 |
return code.encodeBCI(bci); |
|
1263 |
} |
|
1264 |
public void noteBackCall(int whichCallable) { |
|
1265 |
assert(bc[whichCallable] >= 0); |
|
1266 |
bc[whichCallable] += 1; |
|
1267 |
} |
|
1268 |
}); |
|
1269 |
if (isCV) setConstantValueIndex(null); // clean up |
|
1270 |
} |
|
1271 |
||
1272 |
if (overflowCount > 0) { |
|
1273 |
IntBand xxx_attr_count = getAttrBand(xxx_attr_bands, AB_ATTR_COUNT); |
|
1274 |
xxx_attr_count.putInt(overflowCount); |
|
1275 |
} |
|
1276 |
||
1277 |
xxx_flags_lo.putInt(h.flags | (int)flagsToAdd); |
|
1278 |
if (haveLongFlags) |
|
1279 |
xxx_flags_hi.putInt((int)(flagsToAdd >>> 32)); |
|
1280 |
else |
|
1281 |
assert((flagsToAdd >>> 32) == 0); |
|
1282 |
assert((h.flags & flagsToAdd) == 0) |
|
1283 |
: (h+".flags=" |
|
1284 |
+Integer.toHexString(h.flags)+"^" |
|
1285 |
+Long.toHexString(flagsToAdd)); |
|
1286 |
} |
|
1287 |
||
1288 |
// temporary scratch variables for processing code blocks |
|
1289 |
private Code curCode; |
|
1290 |
private Class curClass; |
|
1291 |
private Entry[] curCPMap; |
|
1292 |
private void beginCode(Code c) { |
|
1293 |
assert(curCode == null); |
|
1294 |
curCode = c; |
|
1295 |
curClass = c.m.thisClass(); |
|
1296 |
curCPMap = c.getCPMap(); |
|
1297 |
} |
|
1298 |
private void endCode() { |
|
1299 |
curCode = null; |
|
1300 |
curClass = null; |
|
1301 |
curCPMap = null; |
|
1302 |
} |
|
1303 |
||
1304 |
// Return an _invokeinit_op variant, if the instruction matches one, |
|
1305 |
// else -1. |
|
1306 |
private int initOpVariant(Instruction i, Entry newClass) { |
|
1307 |
if (i.getBC() != _invokespecial) return -1; |
|
1308 |
MemberEntry ref = (MemberEntry) i.getCPRef(curCPMap); |
|
1309 |
if (ref.descRef.nameRef.stringValue() != "<init>") |
|
1310 |
return -1; |
|
1311 |
ClassEntry refClass = ref.classRef; |
|
1312 |
if (refClass == curClass.thisClass) |
|
1313 |
return _invokeinit_op+_invokeinit_self_option; |
|
1314 |
if (refClass == curClass.superClass) |
|
1315 |
return _invokeinit_op+_invokeinit_super_option; |
|
1316 |
if (refClass == newClass) |
|
1317 |
return _invokeinit_op+_invokeinit_new_option; |
|
1318 |
return -1; |
|
1319 |
} |
|
1320 |
||
1321 |
// Return a _self_linker_op variant, if the instruction matches one, |
|
1322 |
// else -1. |
|
1323 |
private int selfOpVariant(Instruction i) { |
|
1324 |
int bc = i.getBC(); |
|
1325 |
if (!(bc >= _first_linker_op && bc <= _last_linker_op)) return -1; |
|
1326 |
MemberEntry ref = (MemberEntry) i.getCPRef(curCPMap); |
|
1327 |
ClassEntry refClass = ref.classRef; |
|
1328 |
int self_bc = _self_linker_op + (bc - _first_linker_op); |
|
1329 |
if (refClass == curClass.thisClass) |
|
1330 |
return self_bc; |
|
1331 |
if (refClass == curClass.superClass) |
|
1332 |
return self_bc + _self_linker_super_flag; |
|
1333 |
return -1; |
|
1334 |
} |
|
1335 |
||
1336 |
void writeByteCodes(Code code) throws IOException { |
|
1337 |
beginCode(code); |
|
1338 |
IndexGroup cp = pkg.cp; |
|
1339 |
||
1340 |
// true if the previous instruction is an aload to absorb |
|
1341 |
boolean prevAload = false; |
|
1342 |
||
1343 |
// class of most recent new; helps compress <init> calls |
|
1344 |
Entry newClass = null; |
|
1345 |
||
1346 |
for (Instruction i = code.instructionAt(0); i != null; i = i.next()) { |
|
1347 |
// %%% Add a stress mode which issues _ref/_byte_escape. |
|
1348 |
if (verbose > 3) Utils.log.fine(i.toString()); |
|
1349 |
||
1350 |
if (i.isNonstandard() |
|
1351 |
&& (!p200.getBoolean(Utils.COM_PREFIX+"invokedynamic") |
|
1352 |
|| i.getBC() != _xxxunusedxxx)) { |
|
1353 |
// Crash and burn with a complaint if there are funny |
|
1354 |
// bytecodes in this class file. |
|
1355 |
String complaint = code.getMethod() |
|
1356 |
+" contains an unrecognized bytecode "+i |
|
1357 |
+"; please use the pass-file option on this class."; |
|
1358 |
Utils.log.warning(complaint); |
|
1359 |
throw new IOException(complaint); |
|
1360 |
} |
|
1361 |
||
1362 |
if (i.isWide()) { |
|
1363 |
if (verbose > 1) { |
|
1364 |
Utils.log.fine("_wide opcode in "+code); |
|
1365 |
Utils.log.fine(i.toString()); |
|
1366 |
} |
|
1367 |
bc_codes.putByte(_wide); |
|
1368 |
codeHist[_wide]++; |
|
1369 |
} |
|
1370 |
||
1371 |
int bc = i.getBC(); |
|
1372 |
||
1373 |
// Begin "bc_linker" compression. |
|
1374 |
if (bc == _aload_0) { |
|
1375 |
// Try to group aload_0 with a following operation. |
|
1376 |
Instruction ni = code.instructionAt(i.getNextPC()); |
|
1377 |
if (selfOpVariant(ni) >= 0) { |
|
1378 |
prevAload = true; |
|
1379 |
continue; |
|
1380 |
} |
|
1381 |
} |
|
1382 |
||
1383 |
// Test for <init> invocations: |
|
1384 |
int init_bc = initOpVariant(i, newClass); |
|
1385 |
if (init_bc >= 0) { |
|
1386 |
if (prevAload) { |
|
1387 |
// get rid of it |
|
1388 |
bc_codes.putByte(_aload_0); |
|
1389 |
codeHist[_aload_0]++; |
|
1390 |
prevAload = false; //used up |
|
1391 |
} |
|
1392 |
// Write special bytecode. |
|
1393 |
bc_codes.putByte(init_bc); |
|
1394 |
codeHist[init_bc]++; |
|
1395 |
MemberEntry ref = (MemberEntry) i.getCPRef(curCPMap); |
|
1396 |
// Write operand to a separate band. |
|
1397 |
int coding = cp.getOverloadingIndex(ref); |
|
1398 |
bc_initref.putInt(coding); |
|
1399 |
continue; |
|
1400 |
} |
|
1401 |
||
1402 |
int self_bc = selfOpVariant(i); |
|
1403 |
if (self_bc >= 0) { |
|
1404 |
boolean isField = Instruction.isFieldOp(bc); |
|
1405 |
boolean isSuper = (self_bc >= _self_linker_op+_self_linker_super_flag); |
|
1406 |
boolean isAload = prevAload; |
|
1407 |
prevAload = false; //used up |
|
1408 |
if (isAload) |
|
1409 |
self_bc += _self_linker_aload_flag; |
|
1410 |
// Write special bytecode. |
|
1411 |
bc_codes.putByte(self_bc); |
|
1412 |
codeHist[self_bc]++; |
|
1413 |
// Write field or method ref to a separate band. |
|
1414 |
MemberEntry ref = (MemberEntry) i.getCPRef(curCPMap); |
|
1415 |
CPRefBand bc_which = selfOpRefBand(self_bc); |
|
1416 |
Index which_ix = cp.getMemberIndex(ref.tag, ref.classRef); |
|
1417 |
bc_which.putRef(ref, which_ix); |
|
1418 |
continue; |
|
1419 |
} |
|
1420 |
assert(!prevAload); |
|
1421 |
// End "bc_linker" compression. |
|
1422 |
||
1423 |
// Normal bytecode. |
|
1424 |
codeHist[bc]++; |
|
1425 |
switch (bc) { |
|
1426 |
case _tableswitch: // apc: (df, lo, hi, (hi-lo+1)*(label)) |
|
1427 |
case _lookupswitch: // apc: (df, nc, nc*(case, label)) |
|
1428 |
bc_codes.putByte(bc); |
|
1429 |
Instruction.Switch isw = (Instruction.Switch) i; |
|
1430 |
// Note that we do not write the alignment bytes. |
|
1431 |
int apc = isw.getAlignedPC(); |
|
1432 |
int npc = isw.getNextPC(); |
|
1433 |
// write a length specification into the bytecode stream |
|
1434 |
int caseCount = isw.getCaseCount(); |
|
1435 |
bc_case_count.putInt(caseCount); |
|
1436 |
putLabel(bc_label, code, i.getPC(), isw.getDefaultLabel()); |
|
1437 |
for (int j = 0; j < caseCount; j++) { |
|
1438 |
putLabel(bc_label, code, i.getPC(), isw.getCaseLabel(j)); |
|
1439 |
} |
|
1440 |
// Transmit case values in their own band. |
|
1441 |
if (bc == _tableswitch) { |
|
1442 |
bc_case_value.putInt(isw.getCaseValue(0)); |
|
1443 |
} else { |
|
1444 |
for (int j = 0; j < caseCount; j++) { |
|
1445 |
bc_case_value.putInt(isw.getCaseValue(j)); |
|
1446 |
} |
|
1447 |
} |
|
1448 |
// Done with the switch. |
|
1449 |
continue; |
|
1450 |
} |
|
1451 |
||
1452 |
switch (bc) { |
|
1453 |
case _xxxunusedxxx: // %%% pretend this is invokedynamic |
|
1454 |
{ |
|
1455 |
i.setNonstandardLength(3); |
|
1456 |
int refx = i.getShortAt(1); |
|
1457 |
Entry ref = (refx == 0)? null: curCPMap[refx]; |
|
1458 |
// transmit the opcode, carefully: |
|
1459 |
bc_codes.putByte(_byte_escape); |
|
1460 |
bc_escsize.putInt(1); // one byte of opcode |
|
1461 |
bc_escbyte.putByte(bc); // the opcode |
|
1462 |
// transmit the CP reference, carefully: |
|
1463 |
bc_codes.putByte(_ref_escape); |
|
1464 |
bc_escrefsize.putInt(2); // two bytes of ref |
|
1465 |
bc_escref.putRef(ref); // the ref |
|
1466 |
continue; |
|
1467 |
} |
|
1468 |
} |
|
1469 |
||
1470 |
int branch = i.getBranchLabel(); |
|
1471 |
if (branch >= 0) { |
|
1472 |
bc_codes.putByte(bc); |
|
1473 |
putLabel(bc_label, code, i.getPC(), branch); |
|
1474 |
continue; |
|
1475 |
} |
|
1476 |
Entry ref = i.getCPRef(curCPMap); |
|
1477 |
if (ref != null) { |
|
1478 |
if (bc == _new) newClass = ref; |
|
1479 |
if (bc == _ldc) ldcHist[ref.tag]++; |
|
1480 |
CPRefBand bc_which; |
|
1481 |
int vbc = bc; |
|
1482 |
switch (i.getCPTag()) { |
|
1483 |
case CONSTANT_Literal: |
|
1484 |
switch (ref.tag) { |
|
1485 |
case CONSTANT_Integer: |
|
1486 |
bc_which = bc_intref; |
|
1487 |
switch (bc) { |
|
1488 |
case _ldc: vbc = _ildc; break; |
|
1489 |
case _ldc_w: vbc = _ildc_w; break; |
|
1490 |
default: assert(false); |
|
1491 |
} |
|
1492 |
break; |
|
1493 |
case CONSTANT_Float: |
|
1494 |
bc_which = bc_floatref; |
|
1495 |
switch (bc) { |
|
1496 |
case _ldc: vbc = _fldc; break; |
|
1497 |
case _ldc_w: vbc = _fldc_w; break; |
|
1498 |
default: assert(false); |
|
1499 |
} |
|
1500 |
break; |
|
1501 |
case CONSTANT_Long: |
|
1502 |
bc_which = bc_longref; |
|
1503 |
assert(bc == _ldc2_w); |
|
1504 |
vbc = _lldc2_w; |
|
1505 |
break; |
|
1506 |
case CONSTANT_Double: |
|
1507 |
bc_which = bc_doubleref; |
|
1508 |
assert(bc == _ldc2_w); |
|
1509 |
vbc = _dldc2_w; |
|
1510 |
break; |
|
1511 |
case CONSTANT_String: |
|
1512 |
bc_which = bc_stringref; |
|
1513 |
switch (bc) { |
|
1514 |
case _ldc: vbc = _aldc; break; |
|
1515 |
case _ldc_w: vbc = _aldc_w; break; |
|
1516 |
default: assert(false); |
|
1517 |
} |
|
1518 |
break; |
|
1519 |
case CONSTANT_Class: |
|
1520 |
bc_which = bc_classref; |
|
1521 |
switch (bc) { |
|
1522 |
case _ldc: vbc = _cldc; break; |
|
1523 |
case _ldc_w: vbc = _cldc_w; break; |
|
1524 |
default: assert(false); |
|
1525 |
} |
|
1526 |
break; |
|
1527 |
default: |
|
1528 |
bc_which = null; |
|
1529 |
assert(false); |
|
1530 |
} |
|
1531 |
break; |
|
1532 |
case CONSTANT_Class: |
|
1533 |
// Use a special shorthand for the current class: |
|
1534 |
if (ref == curClass.thisClass) ref = null; |
|
1535 |
bc_which = bc_classref; break; |
|
1536 |
case CONSTANT_Fieldref: |
|
1537 |
bc_which = bc_fieldref; break; |
|
1538 |
case CONSTANT_Methodref: |
|
1539 |
bc_which = bc_methodref; break; |
|
1540 |
case CONSTANT_InterfaceMethodref: |
|
1541 |
bc_which = bc_imethodref; break; |
|
1542 |
default: |
|
1543 |
bc_which = null; |
|
1544 |
assert(false); |
|
1545 |
} |
|
1546 |
bc_codes.putByte(vbc); |
|
1547 |
bc_which.putRef(ref); |
|
1548 |
// handle trailing junk |
|
1549 |
if (bc == _multianewarray) { |
|
1550 |
assert(i.getConstant() == code.getByte(i.getPC()+3)); |
|
1551 |
// Just dump the byte into the bipush pile |
|
1552 |
bc_byte.putByte(0xFF & i.getConstant()); |
|
1553 |
} else if (bc == _invokeinterface) { |
|
1554 |
assert(i.getLength() == 5); |
|
1555 |
// Make sure the discarded bytes are sane: |
|
1556 |
assert(i.getConstant() == (1+((MemberEntry)ref).descRef.typeRef.computeSize(true)) << 8); |
|
1557 |
} else { |
|
1558 |
// Make sure there is nothing else to write. |
|
1559 |
assert(i.getLength() == ((bc == _ldc)?2:3)); |
|
1560 |
} |
|
1561 |
continue; |
|
1562 |
} |
|
1563 |
int slot = i.getLocalSlot(); |
|
1564 |
if (slot >= 0) { |
|
1565 |
bc_codes.putByte(bc); |
|
1566 |
bc_local.putInt(slot); |
|
1567 |
int con = i.getConstant(); |
|
1568 |
if (bc == _iinc) { |
|
1569 |
if (!i.isWide()) { |
|
1570 |
bc_byte.putByte(0xFF & con); |
|
1571 |
} else { |
|
1572 |
bc_short.putInt(0xFFFF & con); |
|
1573 |
} |
|
1574 |
} else { |
|
1575 |
assert(con == 0); |
|
1576 |
} |
|
1577 |
continue; |
|
1578 |
} |
|
1579 |
// Generic instruction. Copy the body. |
|
1580 |
bc_codes.putByte(bc); |
|
1581 |
int pc = i.getPC()+1; |
|
1582 |
int npc = i.getNextPC(); |
|
1583 |
if (pc < npc) { |
|
1584 |
// Do a few remaining multi-byte instructions. |
|
1585 |
switch (bc) { |
|
1586 |
case _sipush: |
|
1587 |
bc_short.putInt(0xFFFF & i.getConstant()); |
|
1588 |
break; |
|
1589 |
case _bipush: |
|
1590 |
bc_byte.putByte(0xFF & i.getConstant()); |
|
1591 |
break; |
|
1592 |
case _newarray: |
|
1593 |
bc_byte.putByte(0xFF & i.getConstant()); |
|
1594 |
break; |
|
1595 |
default: |
|
1596 |
assert(false); // that's it |
|
1597 |
} |
|
1598 |
} |
|
1599 |
} |
|
1600 |
bc_codes.putByte(_end_marker); |
|
1601 |
bc_codes.elementCountForDebug++; |
|
1602 |
codeHist[_end_marker]++; |
|
1603 |
endCode(); |
|
1604 |
} |
|
1605 |
||
1606 |
int[] codeHist = new int[1<<8]; |
|
1607 |
int[] ldcHist = new int[20]; |
|
1608 |
void printCodeHist() { |
|
1609 |
assert(verbose > 0); |
|
1610 |
String[] hist = new String[codeHist.length]; |
|
1611 |
int totalBytes = 0; |
|
1612 |
for (int bc = 0; bc < codeHist.length; bc++) { |
|
1613 |
totalBytes += codeHist[bc]; |
|
1614 |
} |
|
1615 |
for (int bc = 0; bc < codeHist.length; bc++) { |
|
1616 |
if (codeHist[bc] == 0) { hist[bc] = ""; continue; } |
|
1617 |
String iname = Instruction.byteName(bc); |
|
1618 |
String count = "" + codeHist[bc]; |
|
1619 |
count = " ".substring(count.length()) + count; |
|
1620 |
String pct = "" + (codeHist[bc] * 10000 / totalBytes); |
|
1621 |
while (pct.length() < 4) pct = "0" + pct; |
|
1622 |
pct = pct.substring(0, pct.length()-2) + "." + pct.substring(pct.length()-2); |
|
1623 |
hist[bc] = count + " " + pct + "% " + iname; |
|
1624 |
} |
|
1625 |
Arrays.sort(hist); |
|
1626 |
System.out.println("Bytecode histogram ["+totalBytes+"]"); |
|
1627 |
for (int i = hist.length; --i >= 0; ) { |
|
1628 |
if (hist[i] == "") continue; |
|
1629 |
System.out.println(hist[i]); |
|
1630 |
} |
|
1631 |
for (int tag = 0; tag < ldcHist.length; tag++) { |
|
1632 |
int count = ldcHist[tag]; |
|
1633 |
if (count == 0) continue; |
|
1634 |
System.out.println("ldc "+ConstantPool.tagName(tag)+" "+count); |
|
1635 |
} |
|
1636 |
} |
|
1637 |
} |