aboutsummaryrefslogtreecommitdiff
path: root/nailgun_launcher/NailgunLauncher.java
blob: 060191964aa2ac825b9eedc72fdde18999e7463d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package cbt;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.security.*;
import java.util.*;
import static cbt.Stage0Lib.*;
import cbt.reflect.TrapSystemExit;
import static java.io.File.pathSeparator;
import java.nio.file.*;
import static java.nio.file.Files.write;

/**
 * This launcher allows to start the JVM without loading anything else permanently into its
 * classpath except for the launcher itself. That's why it is written in Java without
 * dependencies outside the JDK.
 */
public class NailgunLauncher{
  /** Persistent cache for caching classloaders for the JVM life time. */
  private static Map<Object,Object> classLoaderCacheHashMap = new HashMap<Object,Object>();

  public final static SecurityManager initialSecurityManager
    = System.getSecurityManager();

  public static String TARGET = System.getenv("TARGET");
  private static String NAILGUN = "nailgun_launcher/";
  private static String STAGE1 = "stage1/";

  @SuppressWarnings("unchecked")
  public static Object getBuild( Object context ) throws Throwable{
    BuildStage1Result res = buildStage1(
      (long) get(context, "cbtLastModified"),
      (long) get(context, "start"),
      ((File) get(context, "cache")).toString() + "/",
      ((File) get(context, "cbtHome")).toString(),
      ((File) get(context, "compatibilityTarget")).toString() + "/",
      new ClassLoaderCache(
        (HashMap) get(context, "persistentCache")
      ),
      (File) get(context, "cwd"),
      (Boolean) get(context, "loop")
    );
    return
      res
        .classLoader
        .loadClass("cbt.Stage1")
        .getMethod( "getBuild", Object.class, BuildStage1Result.class )
        .invoke(null, context, res);
  }

  public static long nailgunLauncherLastModified = -1; // this initial value should be overwritten, never read

  // wrap for caching
  public static ClassLoader jdkClassLoader = new CbtURLClassLoader(
    new URL[]{},
    ClassLoader.getSystemClassLoader().getParent()
  );

  public static boolean runningViaNailgun = System.out.getClass().getName().equals("com.martiansoftware.nailgun.ThreadLocalPrintStream");

  public static List<File> compatibilitySourceFiles;
  public static List<File> nailgunLauncherSourceFiles;
  public static List<File> stage1SourceFiles;

  public static void main( String[] args ) throws Throwable {
    long _start = System.currentTimeMillis();
    if(args[0].equals("check-alive")){
      System.exit(33);
      return;
    }

    System.setSecurityManager( TrapSystemExit.createSecurityManager(initialSecurityManager) );
    installProxySettings();
    String[] diff = args[0].split("\\.");
    long start = _start - (Long.parseLong(diff[0]) * 1000L) - Long.parseLong(diff[1]);

    // if nailgun didn't install it's threadLocal stdout/err replacements, install CBT's.
    // this hack allows to later swap out System.out/err while still affecting things like
    // scala.Console, which captured them at startup
    try{
      System.out.getClass().getDeclaredField("streams"); // nailgun ThreadLocalPrintStream
      assert(System.out.getClass().getName().equals("com.martiansoftware.nailgun.ThreadLocalPrintStream"));
    } catch( NoSuchFieldException e ){
      System.setOut( new PrintStream(new ThreadLocalOutputStream(System.out), true) );
    }
    try{
      System.err.getClass().getDeclaredField("streams"); // nailgun ThreadLocalPrintStream
      assert(System.err.getClass().getName().equals("com.martiansoftware.nailgun.ThreadLocalPrintStream"));
    } catch( NoSuchFieldException e ){
      System.setErr( new PrintStream(new ThreadLocalOutputStream(System.err), true) );
    }
    // ---------------------

    String CBT_HOME = System.getenv("CBT_HOME");
    String cache = CBT_HOME + "/cache/";
    String compatibilityTarget = CBT_HOME + "/compatibility/" + TARGET;
    // copy cache, so that this thread has a consistent view despite other threads
    // changing their copies
    // replace again before returning, see below
    ClassLoaderCache classLoaderCache = new ClassLoaderCache(
      new HashMap<Object,Object>(classLoaderCacheHashMap)
    );

    String nailgunTarget = CBT_HOME + "/" + NAILGUN + TARGET;
    long nailgunLauncherLastModified = new File( nailgunTarget + "../classes.last-success" ).lastModified();

    File cwd = new File(args[1]);
    boolean loop = args[2].equals("0");

    BuildStage1Result res = buildStage1(
      nailgunLauncherLastModified, start, cache, CBT_HOME, compatibilityTarget, classLoaderCache, cwd, loop
    );

    try{
      int exitCode = (int) res
        .classLoader
        .loadClass("cbt.Stage1")
        .getMethod(
          "run", String[].class, File.class, File.class, boolean.class, BuildStage1Result.class, Map.class
        ).invoke(
          null, (Object) args, new File(cache), new File(CBT_HOME), loop, res, classLoaderCache.hashMap
        );

      System.exit( exitCode );
    } catch (java.lang.reflect.InvocationTargetException e) {
      throw unwrapInvocationTargetException(e);
    } finally {
      // This replaces the cache and should be thread-safe.
      // For competing threads the last one wins with a consistent cache.
      // So worst case, we loose some of the cache that's replaced.
      classLoaderCacheHashMap = classLoaderCache.hashMap;
    }
  }

  public static Throwable unwrapInvocationTargetException(Throwable e){
    if(e instanceof java.lang.reflect.InvocationTargetException){
      return unwrapInvocationTargetException(((java.lang.reflect.InvocationTargetException) e).getCause());
    } else{
      return e;
    }
  }

  public static BuildStage1Result buildStage1(
    final long lastModified, final long start, final String cache, final String cbtHome,
    final String compatibilityTarget, final ClassLoaderCache classLoaderCache, File cwd, boolean loop
  ) throws Throwable {
    _assert(TARGET != null, "environment variable TARGET not defined");
    String nailgunSources = cbtHome + "/" + NAILGUN;
    String nailgunTarget = nailgunSources + TARGET;
    String stage1Sources = cbtHome + "/" + STAGE1;
    String stage1Target = stage1Sources + TARGET;
    String compatibilitySources = cbtHome + "/compatibility";
    String mavenCache = cache + "maven";
    String mavenUrl = "https://repo1.maven.org/maven2";
    File loopFile = new File(cwd + "/target/.cbt-loop.tmp");
    if(loop){
      loopFile.getParentFile().mkdirs();
    }

    ClassLoader rootClassLoader = new CbtURLClassLoader( new URL[]{}, ClassLoader.getSystemClassLoader().getParent() ); // wrap for caching
    EarlyDependencies earlyDeps = new EarlyDependencies(mavenCache, mavenUrl, classLoaderCache, rootClassLoader);

    nailgunLauncherSourceFiles = new ArrayList<File>();
    for( File f: new File(nailgunSources).listFiles() ){
      if( f.isFile() && f.toString().endsWith(".java") ){
        nailgunLauncherSourceFiles.add(f);
      }
    }

    long nailgunLauncherLastModified = new File( nailgunTarget + "../classes.last-success" ).lastModified();

    long compatibilityLastModified;
    if(!compatibilityTarget.startsWith(cbtHome)){
      compatibilityLastModified = new File( compatibilityTarget + "../classes.last-success" ).lastModified();
    } else {
      compatibilitySourceFiles = new ArrayList<File>();
      for( String d: new String[]{
        compatibilitySources,
        cbtHome + "/libraries/interfaces"
      } ){
        for( File f: new File(d).listFiles() ){
          if( f.isFile() && f.toString().endsWith(".java") ){
            compatibilitySourceFiles.add(f);
          }
        }
      }

      if(loop){
        File[] _compatibilitySourceFiles = new File[compatibilitySourceFiles.size()];
        compatibilitySourceFiles.toArray(_compatibilitySourceFiles);
        write(
          loopFile.toPath(),
          (mkString( "\n", _compatibilitySourceFiles ) + "\n").getBytes(),
          StandardOpenOption.CREATE
        );
      }
      compatibilityLastModified = compile( 0L, "", compatibilityTarget, earlyDeps, compatibilitySourceFiles) ;

      if( !classLoaderCache.containsKey( compatibilityTarget, compatibilityLastModified ) ){
        classLoaderCache.put( compatibilityTarget, classLoader(compatibilityTarget, rootClassLoader), compatibilityLastModified );
      }
    }
    final ClassLoader compatibilityClassLoader = classLoaderCache.get( compatibilityTarget, compatibilityLastModified );

    String[] nailgunClasspathArray = append( earlyDeps.classpathArray, nailgunTarget );
    String nailgunClasspath = classpath( nailgunClasspathArray );
    final ClassLoader nailgunClassLoader = new CbtURLClassLoader( new URL[]{}, NailgunLauncher.class.getClassLoader() ); // wrap for caching
    if( !classLoaderCache.containsKey( nailgunClasspath, nailgunLauncherLastModified ) ){
      classLoaderCache.put( nailgunClasspath, nailgunClassLoader, nailgunLauncherLastModified );
    }

    String[] stage1ClasspathArray =
      append( append( nailgunClasspathArray, compatibilityTarget ), stage1Target );
    String stage1Classpath = classpath( stage1ClasspathArray );

    stage1SourceFiles = new ArrayList<File>();
    for( String d: new String[]{
      stage1Sources,
      cbtHome + "/libraries/reflect",
      cbtHome + "/libraries/common-1",
      cbtHome + "/libraries/file"
    } ){
      for( File f: new File(d).listFiles() ){
        if( f.isFile() && (f.toString().endsWith(".scala") || f.toString().endsWith(".java")) ){
          stage1SourceFiles.add(f);
        }
      }
    }

    final long stage1BeforeCompiled = System.currentTimeMillis();
    final long stage0LastModified = Math.max(
      lastModified,
      Math.max( lastModified, compatibilityLastModified )
    );

    if(loop){
      File[] _stage1SourceFiles = new File[stage1SourceFiles.size()];
      stage1SourceFiles.toArray(_stage1SourceFiles);
      write(
        loopFile.toPath(),
        (mkString( "\n", _stage1SourceFiles ) + "\n").getBytes(),
        StandardOpenOption.APPEND
      );
    }

    final long stage1LastModified = compile(
      stage0LastModified, stage1Classpath, stage1Target, earlyDeps, stage1SourceFiles
    );

    if( stage1LastModified < compatibilityLastModified )
      throw new AssertionError(
        "Cache invalidation bug: cbt compatibility layer recompiled, but cbt stage1 did not."
      );

    if( !classLoaderCache.containsKey( stage1Classpath, stage1LastModified ) ){
      classLoaderCache.put(
        stage1Classpath,
        classLoader(
          stage1Target,
          new MultiClassLoader2(
            nailgunClassLoader,
            compatibilityClassLoader,
            earlyDeps.classLoader
          )
        ),
        stage1LastModified
      );
    }
    final ClassLoader stage1classLoader = classLoaderCache.get( stage1Classpath, stage1LastModified );

    return new BuildStage1Result(
      start,
      stage1LastModified,
      stage1classLoader,
      stage1Classpath,
      nailgunClasspath,
      compatibilityTarget
    );
  }
}