added -J option to preserve unmodified files in preexisting jarfile
[org.ibex.tool.git] / src / org / ibex / tool / Compiler.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.tool;
6
7 import java.io.*;
8 import java.util.*;
9 import java.util.zip.*;
10 import java.util.jar.*;
11
12 import java.lang.reflect.*;
13
14 import org.eclipse.jdt.core.compiler.IProblem;
15 import org.eclipse.jdt.internal.compiler.ClassFile;
16 import org.eclipse.jdt.internal.compiler.CompilationResult;
17 //import org.eclipse.jdt.internal.compiler.Compiler;
18 import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
19 import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
20 import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
21 import org.eclipse.jdt.internal.compiler.IProblemFactory;
22 import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
23 import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
24 import org.eclipse.jdt.internal.compiler.env.*;
25 import org.eclipse.jdt.internal.compiler.impl.*;
26 import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
27
28 // FEATURE: add build dependencies like make (grab some Java dependency-checker code off the net?)
29
30 public class Compiler {
31     // Static Entry Point /////////////////////////////////////////////////////
32
33     public static void main(String[] args) throws IOException {
34         boolean verbose = false, veryverbose = false, warnings = true;
35         List srcdir = new ArrayList();
36         String source = null, target = null, blddir = null, mainclass = null;
37         boolean buildjar = false;
38         boolean keepjar = false;
39
40         if (args.length == 0) args = new String[] { "--help" };
41         for (int i=0; i < args.length; i++) {
42             if (args[i].charAt(0) == '-') {
43                 if (args[i].length() == 1) {
44                     System.out.println("Illegal switch: -"); return; }
45                 switch (args[i].charAt(1)) {
46                     case '-':
47                         if (args[i].equals("--help")) printHelp();
48                         else System.out.println("Unknown switch: -");
49                         return;
50                     case 'd':
51                         if (i == args.length - 1) {
52                             System.out.println("Missing parameter: "+args[i]); return; }
53                         if (blddir != null) { System.out.println("cannot specify both -d and -j"); return; }
54                         blddir = args[++i];
55                         break;
56                     case 'J':
57                         keepjar = true;
58                     case 'j':
59                         if (i == args.length - 1) {
60                             System.out.println("Missing parameter: "+args[i]); return; }
61                         if (blddir != null) { System.out.println("cannot specify both -d and -j"); return; }
62                         blddir = args[++i];
63                         buildjar = true;
64                         break;
65                     case 'm':
66                         if (i == args.length - 1) {
67                             System.out.println("Missing parameter: "+args[i]); return; }
68                         mainclass = args[++i];
69                         break;
70                     case 'w':
71                         if (i == args.length - 1) {
72                             System.out.println("Missing parameter: "+args[i]); return; }
73                         warnings = false;
74                         break;
75                     case 's':
76                         if (i == args.length - 1) {
77                             System.out.println("Missing parameter: "+args[i]); return; }
78                         source = args[++i];
79                         break;
80                     case 't':
81                         if (i == args.length - 1) {
82                             System.out.println("Missing parameter: "+args[i]); return; }
83                         target = args[++i];
84                         break;
85                     case 'v':
86                         verbose = true;
87                         break;
88                     case 'V':
89                         veryverbose = true;
90                         break;
91                     case 'h':
92                         printHelp(); return;
93
94                 }
95             } else srcdir.add(args[i]);
96         }
97
98         Compiler c = new Compiler();
99         if (blddir != null) {
100             if (buildjar) c.setBuildJar(blddir, keepjar);
101             else          c.setBuildDir(blddir);
102         }
103         if (source != null) c.setSource(source);
104         if (target != null) c.setTarget(target);
105         if (mainclass != null) c.setMainClass(mainclass);
106
107         String[] s = new String[srcdir.size()];
108         srcdir.toArray(s);
109         c.setSourceDirs(s);
110
111         c.setVerbose(verbose);
112         c.setWarnings(warnings);
113         c.setVeryVerbose(veryverbose);
114         boolean hasErrors = c.compile();
115         if (hasErrors) Runtime.getRuntime().exit(-1);
116         Runtime.getRuntime().exit(0);
117     }
118     private static void printHelp() {
119         System.out.println("Usage java -cp ... org.ibex.tool.Compiler [options] <source dir> ...");
120         System.out.println("Options:");
121         System.out.println("  -d <directory>   Directory to put generated class files in");
122         System.out.println("  -j <jarfile>     Jar file to put generated class files in");
123         System.out.println("     -m <class>    Main-Class for jar file.");
124         System.out.println("  -s <release>     Compile with specified source compatibility.");
125         System.out.println("  -t <release>     Compile with specified class file compatibility.");
126         System.out.println("  -v               Verbose output.");
127         System.out.println("  -V               Very Verbose output.");
128         System.out.println("  -h or --help     Print this message.");
129         System.out.println("");
130     }
131
132
133     // Compiler Interface /////////////////////////////////////////////////////
134
135     private ClassLoader loader = ClassLoader.getSystemClassLoader();
136     private Map loaded = new HashMap();
137     private PrintWriter out = new PrintWriter(System.out);
138     private Preprocessor preprocessor;
139
140     private Source[] sources;
141
142     private File builddir = null;
143     private boolean buildzip = false;
144     private boolean keepzip = false;
145     private ZipOutputStream jarfile = null;
146     private String mainclass = null;
147
148     private String[] sourcedirs = new String[0];
149
150     private PrintWriter warn;
151     private boolean hasErrors;
152     private boolean verbose = false;
153     private boolean veryverbose = false;
154     private boolean warnings = true;
155
156     public Compiler() {
157         List defs = Collections.EMPTY_LIST;
158
159         String define = System.getProperty("org.ibex.tool.preprocessor.define");
160         if (define != null) {
161             defs = new ArrayList();
162             StringTokenizer st = new StringTokenizer(define.toUpperCase(), ",");
163             while (st.hasMoreTokens()) defs.add(st.nextToken().trim());
164         }
165
166         preprocessor = new Preprocessor(null, null, defs);
167     }
168
169     public void setMainClass(String mainclass) { this.mainclass = mainclass; }
170     public void setBuildJar(String dir, boolean keepjar) throws IOException {
171         builddir = new File(dir == null ? "." : dir);
172         buildzip = true;
173         if (keepjar) keepzip = true;
174     }
175     public void setBuildDir(String dir) throws IOException {
176         builddir = new File(dir == null ? "." : dir);
177     }
178
179     public void setSourceDirs(String[] dir) { sourcedirs = dir; }
180
181     /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
182     public void setSource(String v) {
183         if (v.equals("1.1")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_1);
184         else if (v.equals("1.2")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_2);
185         else if (v.equals("1.3")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
186         else if (v.equals("1.4")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
187         else if (v.equals("1.5")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
188         else throw new RuntimeException("I have no idea what Java " + v + " is.  Ask David Crawshaw.");
189     }
190
191     /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
192     public void setTarget(String v) {
193         if (v.equals("1.1")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
194         else if (v.equals("1.2")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
195         else if (v.equals("1.3")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
196         else if (v.equals("1.4")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
197         else if (v.equals("1.5")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
198         else throw new RuntimeException("I have no idea what Java " + v + " is.  Ask David Crawshaw.");
199     }
200
201     public void setVerbose(boolean v) { verbose = v; }
202     public void setVeryVerbose(boolean v) { veryverbose = v; }
203     public void setWarnings(boolean w) { warnings = w; }
204
205     ZipInputStream keptzip = null;
206
207     public boolean compile() throws IOException {
208         List s = new ArrayList();
209
210         if (buildzip) {
211             if (keepzip) {
212                 File f = builddir;
213                 if (f.exists()) {
214                     keptzip = new ZipInputStream(new FileInputStream(f));
215                     f.delete();
216                 }
217             }
218             Manifest m = new Manifest();
219             m.getMainAttributes().putValue("Manifest-Version", "1.0");
220             if (mainclass != null) m.getMainAttributes().putValue("Main-Class", mainclass);
221             jarfile = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(builddir)), m);
222             entries.add("META-INF/MANIFEST.MF");
223         }
224         for (int i=0; i < sourcedirs.length; i++) {
225             File src = new File(sourcedirs[i]);
226             if (!src.exists()) {
227                 if (veryverbose) System.out.println("source directory not found: "+sourcedirs[i]);
228                 continue;
229             }
230             filterSources(s, src, new char[0][], sourcedirs[i]);
231         }
232
233         if (veryverbose) System.out.println("working with "+s.size() +" sources");
234         sources = new Source[s.size()]; s.toArray(sources);
235         ICompilationUnit[] units = new ICompilationUnit[s.size()];
236         int u = 0; for (int i=0; i < sources.length; i++)
237             if (sources[i].compiled == null) units[u++] = sources[i].unit;
238         if (u != units.length) {
239             ICompilationUnit[] newu = new ICompilationUnit[u];
240             System.arraycopy(units, 0, newu, 0, u);
241             units = newu;
242         }
243
244         hasErrors = false;
245
246         StringWriter sw = new StringWriter();
247         StringBuffer w = sw.getBuffer();
248         warn = new PrintWriter(sw);
249
250         org.eclipse.jdt.internal.compiler.Compiler jdt =
251             new org.eclipse.jdt.internal.compiler.Compiler(
252                 env, policy, settings, results, problems);
253         jdt.compile(units);
254
255         if (warnings && !hasErrors) { out.write(w.toString()); out.flush(); }
256         warn = null;
257         try {
258             if (jarfile != null) {
259                 if (keptzip != null) {
260                     byte[] buf = new byte[1024 * 16];
261                     for(ZipEntry ze = keptzip.getNextEntry(); ze != null; ze = keptzip.getNextEntry()) {
262                         if (entries.contains(ze.getName())) continue;
263                         message("   preserving: " + ze.getName());
264                         jarfile.putNextEntry(ze);
265                         while(true) {
266                             int numread = keptzip.read(buf, 0, buf.length);
267                             if (numread == -1) break;
268                             jarfile.write(buf, 0, numread);
269                         }
270                     }
271                 }
272                 jarfile.close();
273             }
274         } catch (Exception e) {
275             e.printStackTrace();
276         }
277         if (verbose) System.out.print(clearing + "   \r");
278         return hasErrors;
279     }
280     List entries = new ArrayList();
281
282     private final FilenameFilter filterSrcs = new FilenameFilter() {
283         public boolean accept(File dir, String name) { return name.endsWith(".java"); }
284     };
285     private final FileFilter filterDirs = new FileFilter() {
286         public boolean accept(File path) { return path.isDirectory(); }
287     };
288
289     private void filterSources(List s, File dir, char[][] pack, String srcdir) {
290         List bclasses = new ArrayList();
291         File bdir = new File(builddir, str(pack, File.separatorChar));
292
293         // add the java files in this directory
294         File[] ja = dir.listFiles(filterSrcs);
295         for (int i=0; i < ja.length; i++) {
296             char[] n = name(classname(ja[i].getName()));
297             Source src = new Source(ja[i], n, pack, srcdir);
298
299             // skip the file if the build version is newer than the source
300             String bclass = new String(n);
301             File bfile = new File(bdir, bclass + ".class");
302             if (bfile.lastModified() > ja[i].lastModified()) {
303                 src.compiled = bytes(bfile);
304                 bclasses.add(bclass);
305             }
306
307             s.add(src);
308         }
309
310         // process the inner classes of any binary files
311         for (int i=0; i < bclasses.size(); i++) {
312             final String bc = (String)bclasses.get(i);
313             final FilenameFilter f = new FilenameFilter() {
314                 public boolean accept(File dir, String name) {
315                     return name.length() > bc.length() && name.startsWith(bc) &&
316                            name.charAt(bc.length()) == '$' && name.endsWith(".class");
317                 }
318             };
319             File[] bfile = bdir.listFiles(f);
320             for (int j=0; j < bfile.length; j++) {
321                 Source src = new Source(bfile[j],
322                     name(classname(bfile[j].getName())), pack, srcdir);
323                 src.compiled = bytes(bfile[j]);
324                 s.add(src);
325             }
326         }
327
328         // add the subdirectories as packages
329         File[] d = dir.listFiles(filterDirs);
330         for (int i=0; i < d.length; i++) {
331             char[][] newpack = new char[pack.length + 1][];
332             for (int j=0; j < pack.length; j++) newpack[j] = pack[j];
333             newpack[pack.length] = d[i].getName().toCharArray();
334             filterSources(s, d[i], newpack, srcdir);
335         }
336     }
337
338
339     /** Represents a file to be compiled. */
340     final class Source {
341         char[] fileName;
342         char[] n; char[][] p;
343         File orig;
344         char[] processed = null;
345         byte[] compiled = null;
346         ClassFileReader reader = null;
347
348         final ICompilationUnit unit = new ICompilationUnit() {
349             public char[] getMainTypeName() { return n; }
350             public char[][] getPackageName() { return p; }
351             public char[] getFileName() { return fileName; }
352             public char[] getContents() {
353                 if (processed != null) return processed;
354
355                 try {
356                     Reader r = new InputStreamReader(new BufferedInputStream(
357                                new FileInputStream(orig)));
358                     StringWriter w = new StringWriter();
359                     Vector err;
360
361                     synchronized (preprocessor) {
362                         preprocessor.setReader(r);
363                         preprocessor.setWriter(w);
364                         err = preprocessor.process();
365                     }
366
367                     if (err.size() > 0) {
368                         for (int i=0; i < err.size(); i++) {
369                             Preprocessor.Warning warn = (Preprocessor.Warning)err.get(i);
370                             out.print(getFileName());
371                             out.print(':');
372                             out.print(warn.getLine());
373                             out.print(':');
374                             out.print(warn instanceof Preprocessor.Error ?
375                                       " error: " : " warning: ");
376                             out.println(warn.getMessage());
377                         }
378                         return null;
379                     }
380
381                     processed  = w.toString().toCharArray();
382                 } catch (IOException e) {
383                     System.out.println("IOException: "+e); // FIXME
384                     return null;
385                 }
386
387                 return processed;
388             }
389         };
390
391         private Source(File o, char[] n, char[][] p, String srcdir) {
392             orig = o; this.n = n; this.p = p;
393             String file = srcdir;
394             file += File.separatorChar +  str(p, File.separatorChar);
395             file += File.separatorChar + new String(n) + ".java";
396             fileName = file.toCharArray();
397         }
398     }
399
400     // Compiler Parameters ////////////////////////////////////////////////////
401
402     // FEATURE: may be able to use this to block access to APIs generated for stack objects
403     final AccessRestriction access = null;
404
405     /** Used by compiler to resolve classes. */
406     final INameEnvironment env = new INameEnvironment() {
407         public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
408         public NameEnvironmentAnswer findType(char[] n, char[][] p) {
409             if (veryverbose) System.out.print("findType: "+ str(p, '.') + "."+new String(n));
410
411             try {
412                 String classname = new String(n);
413                 Class c = Class.forName(str(p, '.') + '.' + classname);
414                 if (veryverbose) System.out.println("  found in classloader: "+ c);
415                 IBinaryType b = (IBinaryType)loaded.get(c);
416                 if (b == null) loaded.put(c, b = new ClassFileReader(
417                     bytes(c), (str(p, '/') + '/' + classname).toCharArray()));
418                 return new NameEnvironmentAnswer(b, access);
419             } catch (ClassNotFoundException e) {
420             } catch (LinkageError e) {
421             } catch (ClassFormatException e) {
422                 e.printStackTrace();
423                 throw new Error("ClassFormatException reading system class: " +
424                     str(p, '.')+new String(n));
425             }
426
427             // cut out searches for java.* packages in sources list
428             if (p.length > 0 && eq(p[0], "java".toCharArray())) {
429                 if (veryverbose) System.out.println("  not found, unknown java.*");
430                 return null;
431             }
432
433             try {
434                 for (int i=0; i < sources.length; i++) {
435                     Source s = sources[i];
436                     if (eq(n, s.n) && eq(p, s.p)) {
437                         if (s.reader != null) {
438                             if (veryverbose) System.out.println("  found reader");
439                             return new NameEnvironmentAnswer(s.reader, access);
440                         }
441                         if (s.compiled != null) {
442                             if (veryverbose) System.out.println("  found compiled, new reader");
443                             s.reader = new ClassFileReader(s.compiled,
444                                 s.orig.getName().toCharArray());
445                             return new NameEnvironmentAnswer(s.reader, access);
446                         }
447                         if (veryverbose) System.out.println("  found unit");
448                         return new NameEnvironmentAnswer(sources[i].unit, access);
449                     }
450                 }
451             } catch (ClassFormatException e) {
452                 e.printStackTrace();
453                 throw new Error("unexpected ClassFormatException resolving compiled class: "+e);
454             }
455             if (veryverbose) System.out.println("  not found");
456             return null;
457         }
458         public boolean isPackage(char[][] parent, char[] name) {
459             if (veryverbose) System.out.println("isPackage: "+ str(parent, '.') + "."+new String(name));
460             String parentName = str(parent, '/');
461             for (int i=0; i < sources.length; i++) {
462                 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
463                 if (eq(pack(sources[i].p), parent) && eq(name(sources[i].p), name)) return true;
464             }
465             return
466                 loader.getResource(parentName + ".class") == null &&
467                 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
468         }
469         public void cleanup() {}
470     };
471
472     /** Used by compiler to decide what do with problems.. */
473     private final IErrorHandlingPolicy policy =
474         DefaultErrorHandlingPolicies.proceedWithAllProblems();
475
476     /** Used by compiler for general options. */
477     private final Map settings = new HashMap();
478     {
479         settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
480         settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
481         settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
482         settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
483     };
484
485     /** Used by compiler for processing compiled classes and their errors. */
486     private final ICompilerRequestor results = new ICompilerRequestor() {
487         public void acceptResult(CompilationResult result) {
488             if (veryverbose) System.out.println("got result: "+result);
489             if (result.hasProblems()) {
490                 boolean err = false;
491                 IProblem[] p = result.getProblems();
492                 PrintWriter o;
493                 for (int i=0; i < p.length; i++) {
494                     if (p[i].isError()) { o = out; err = true; }
495                     else o = warn;
496
497                     o.print(p[i].getOriginatingFileName());
498                     o.print(':');
499                     o.print(p[i].getSourceLineNumber());
500                     o.print(':');
501                     o.print(p[i].isError() ? " error: " : " warning: ");
502                     o.println(p[i].getMessage());
503                 }
504                 out.flush();
505                 if (err) { hasErrors = true; return; }
506             }
507
508             ClassFile[] c = result.getClassFiles();
509             for (int i=0; i < c.length; i++) {
510                 try {
511                     char[][] name = c[i].getCompoundName();
512                     if (verbose) {
513                         String pct = "";
514                         /*+ percent;
515                         percent++;
516                         while (pct.length() < 2) pct = " " + pct;
517                         pct = "(" + pct + "%) ";
518                         */
519                         String printme = " writing: " + pct + str(pack(name),'.') + "." + new String(name(name));
520                         message(printme);
521                     }
522                     if (buildzip) {
523                         try {
524                             jarfile.putNextEntry(new ZipEntry(str(pack(name), '/') + "/" + new String(name(name)) + ".class"));
525                             jarfile.write(c[i].getBytes());
526                             entries.add(str(pack(name), '/') + "/" + new String(name(name)) + ".class");
527                         } catch (java.util.zip.ZipException ze) {
528                             // HACK: horrendous hack
529                             if (ze.getMessage().indexOf("duplicate entry") != -1) {
530                                 //System.out.println("compiler emitted class twice: " + new String(name(name)));
531                             } else {
532                                 throw ze;
533                             }
534                         }
535                     } else {
536                         // build package path to new class file
537                         File path = new File(builddir, str(pack(name), '/'));
538                         if (!path.exists()) path.mkdirs();
539                         // write new class file
540                         path = new File(path, new String(name(name)) + ".class");
541                         OutputStream o = new BufferedOutputStream(new FileOutputStream(path));
542                         o.write(c[i].getBytes());
543                         o.close();
544                     }
545                 } catch (IOException e) {
546                     System.out.println("IOException writing class"); // FIXME
547                     e.printStackTrace();
548                 }
549             }
550         }
551     };
552
553     public static void message(String printme) {
554         if (clearing.length() < printme.length()) clearing = "";
555         else clearing = clearing.substring(printme.length());
556         System.out.print(printme + clearing + "\r");
557         for(clearing = ""; clearing.length() < printme.length() + 5; clearing += " ");
558     }
559
560     int percent = 0;
561     static String clearing = "";
562
563     /** Problem creater for compiler. */
564     private final IProblemFactory problems = new DefaultProblemFactory();
565
566
567     // Helper Functiosn ///////////////////////////////////////////////////////
568
569     /** Convert source file path into class name block.
570      *  eg. in:  java/lang/String.java -> { {java} {lang} {String} } */
571     private static char[][] classname(String name) {
572         String delim = name.indexOf('/') == -1 ? "." : "/";
573         name = name.trim();
574         if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
575         if (name.endsWith(".class")) name = name.substring(0, name.length() - 6);
576         if (name.startsWith(delim)) name = name.substring(1);
577
578         StringTokenizer st = new StringTokenizer(name, delim);
579         char[][] n = new char[st.countTokens()][];
580         for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
581         return n;
582     }
583
584     /** Convert class name into a String. */
585     private static String str(char[][] name, char delim) {
586         StringBuffer b = new StringBuffer();
587         for (int i=0; name != null && i < name.length; i++) {
588             if (name[i] == null || name[i].length == 0) continue;
589             if (i > 0) b.append(delim);
590             b.append(name[i]);
591         }
592         return b.toString();
593     }
594
595     /** Returns the package component of a class name.
596      *  Effectively returns char[length - 1][].  */
597     private static char[][] pack(char[][] c) {
598         char[][] p = new char[c.length - 1][];
599         for (int i=0; i < p.length; i++) p[i] = c[i];
600         return p;
601     }
602
603     /** Returns the direct-name component of a class name.
604      *  eg. String from java.lang.String */
605     private static char[] name(char[][] c) { return c[c.length - 1]; }
606
607     /** Returns true of contents of both char arrays are equal. */
608     private static boolean eq(char[][] c1, char[][] c2) {
609         if (c1 == null || c2 == null) return c1 == c2;
610         if (c1.length != c2.length) return false;
611         for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
612         return true;
613     }
614
615     /** Returns true of contents of both char arrays are equal. */
616     private static boolean eq(char[] c1, char[] c2) {
617         if (c1 == null || c2 == null) return c1 == c2;
618         if (c1.length != c2.length) return false;
619         for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
620         return true;
621     }
622
623     /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
624     private static char[] name(Class c) {
625         return c == null ? null : c.getName().replace('.', '/').toCharArray();
626     }
627
628     /** Returns the type name of a class as per VM Spec 4.3.2. */
629     private static char[] typeName(Class p) {
630         StringBuffer sb = new StringBuffer();
631         typeName(p, sb);
632         return sb.toString().toCharArray();
633     }
634
635     /** Returns the type name of a class as per VM Spec 4.3.2.
636      *  eg. int -> I, String -> Ljava/lang/String; */
637     private static void typeName(Class p, StringBuffer sb) {
638         String name = p.getName();
639         switch (name.charAt(0)) {
640             case 'B': case 'C': case 'D': case 'F': case 'I':
641             case 'J': case 'S': case 'Z': case 'V': case '[':
642                 sb.append(name(p)); break;
643
644             case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
645                       if (name.equals("byte"))    { sb.append('B'); break; }
646             case 'c': if (name.equals("char"))    { sb.append('C'); break; }
647             case 'd': if (name.equals("double"))  { sb.append('D'); break; }
648             case 'f': if (name.equals("float"))   { sb.append('F'); break; }
649             case 'i': if (name.equals("int"))     { sb.append('I'); break; }
650             case 'l': if (name.equals("long"))    { sb.append('J'); break; }
651             case 's': if (name.equals("short"))   { sb.append('S'); break; }
652             case 'v': if (name.equals("void"))    { sb.append('V'); break; }
653             default:
654                 sb.append('L'); sb.append(name(p)); sb.append(';');
655         }
656     }
657
658     /** Returns the descriptor of a method per VM Spec 4.3.3.
659      *  eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
660     private static char[] descriptor(Class[] p, Class r) {
661         StringBuffer sb = new StringBuffer();
662         sb.append('(');
663         if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
664         sb.append(')');
665         if (r != null) typeName(r, sb);
666         return sb.toString().toCharArray();
667     }
668
669     private static byte[] bytes(Class c) {
670         return bytes(c.getResourceAsStream('/' + c.getName().replace('.', '/') + ".class"));
671     }
672     private static byte[] bytes(File bfile) {
673         try { return bytes(new FileInputStream(bfile)); }
674         catch (FileNotFoundException e) { throw new Error("FileNotFoundException reading bytes: "+e); }
675     }
676     private static byte[] bytes(InputStream bin) {
677         byte[] bytes = new byte[2 * 1024];
678         int pos = 0, in = 0;
679         try {
680             while ((in = bin.read(bytes, pos, bytes.length - pos)) != -1) {
681                 pos += in;
682                 if (pos == bytes.length) {
683                     byte[] newbytes= new byte[pos * 2];
684                     System.arraycopy(bytes, 0, newbytes, 0, pos);
685                     bytes = newbytes;
686                 }
687             }
688             bin.close();
689         } catch (IOException e) {
690             e.printStackTrace();
691             throw new Error("IOException reading class file: "+e);
692         }
693
694         if (pos != bytes.length) {
695             byte[] newbytes= new byte[pos * 2];
696             System.arraycopy(bytes, 0, newbytes, 0, pos);
697             bytes = newbytes;
698         }
699
700         return bytes;
701     }
702 }