aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/java_tools/buildjar/java/com/google/devtools/build/java/turbine/javac/JavacTurbineCompiler.java
blob: 3ee4d204c05121df3e360f39a4dc2a7ae4e63559 (plain)
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
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.java.turbine.javac;

import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import com.google.devtools.build.buildjar.javac.plugins.dependency.StrictJavaDepsPlugin;
import com.google.devtools.build.java.turbine.javac.JavacTurbineCompileResult.Status;
import com.sun.source.util.JavacTask;
import com.sun.tools.javac.api.ClientCodeWrapper.Trusted;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.file.CacheFSInfo;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.util.Context;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.FileSystem;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Nullable;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
import javax.tools.StandardLocation;

/** Performs a javac-based turbine compilation given a {@link JavacTurbineCompileRequest}. */
public class JavacTurbineCompiler {

  static JavacTurbineCompileResult compile(JavacTurbineCompileRequest request) throws IOException {

    Map<String, byte[]> files = new LinkedHashMap<>();
    Status status;
    StringWriter sw = new StringWriter();
    ImmutableList.Builder<FormattedDiagnostic> diagnostics = ImmutableList.builder();
    Context context = new Context();

    try (PrintWriter pw = new PrintWriter(sw)) {
      setupContext(context, request.strictJavaDepsPlugin(), request.transitivePlugin());
      CacheFSInfo.preRegister(context);
      try (FileSystem fs = Jimfs.newFileSystem(Configuration.forCurrentPlatform());
          JavacFileManager fm = new ClassloaderMaskingFileManager()) {
        JavacTask task =
            JavacTool.create()
                .getTask(
                    pw,
                    fm,
                    diagnostic -> diagnostics.add(formatDiagnostic(diagnostic)),
                    request.javacOptions(),
                    ImmutableList.of() /*classes*/,
                    fm.getJavaFileObjectsFromPaths(request.sources()),
                    context);

        Path classes = fs.getPath("classes");
        Files.createDirectories(classes);
        Path sources = fs.getPath("sources");
        Files.createDirectories(sources);

        fm.setContext(context);
        fm.setLocationFromPaths(StandardLocation.SOURCE_PATH, Collections.<Path>emptyList());
        fm.setLocationFromPaths(StandardLocation.CLASS_PATH, request.classPath());
        // The bootclasspath may legitimately be empty if --release is being used.
        Collection<Path> bootClassPath = request.bootClassPath();
        if (!bootClassPath.isEmpty()) {
          fm.setLocationFromPaths(StandardLocation.PLATFORM_CLASS_PATH, bootClassPath);
        }
        fm.setLocationFromPaths(
            StandardLocation.ANNOTATION_PROCESSOR_PATH, request.processorClassPath());
        fm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, ImmutableList.of(classes));
        fm.setLocationFromPaths(StandardLocation.SOURCE_OUTPUT, ImmutableList.of(sources));

        status = task.call() ? Status.OK : Status.ERROR;

        // collect class output
        Files.walkFileTree(
            classes,
            new SimpleFileVisitor<Path>() {
              @Override
              public FileVisitResult visitFile(Path path, BasicFileAttributes attrs)
                  throws IOException {
                files.put(classes.relativize(path).toString(), Files.readAllBytes(path));
                return FileVisitResult.CONTINUE;
              }
            });

      } catch (Throwable t) {
        t.printStackTrace(pw);
        status = Status.ERROR;
      }
    }

    return new JavacTurbineCompileResult(
        ImmutableMap.copyOf(files), status, sw.toString(), diagnostics.build(), context);
  }

  private static FormattedDiagnostic formatDiagnostic(
      Diagnostic<? extends JavaFileObject> diagnostic) {
    StringBuilder message = new StringBuilder();
    if (diagnostic.getSource() != null) {
      message.append(diagnostic.getSource().getName());
      if (diagnostic.getLineNumber() != -1) {
        message.append(':').append(diagnostic.getLineNumber());
      }
      message.append(": ");
    }
    message.append(diagnostic.getKind().toString().toLowerCase(Locale.getDefault()));
    message.append(": ").append(diagnostic.getMessage(Locale.getDefault()));
    return new FormattedDiagnostic(diagnostic, message.toString());
  }

  /** Mask the annotation processor classpath to avoid version skew. */
  @Trusted
  private static class ClassloaderMaskingFileManager extends JavacFileManager {

    private static Context getContext() {
      Context context = new Context();
      CacheFSInfo.preRegister(context);
      return context;
    }

    public ClassloaderMaskingFileManager() {
      super(getContext(), false, UTF_8);
    }

    @Override
    protected ClassLoader getClassLoader(URL[] urls) {
      return new URLClassLoader(
          urls,
          new ClassLoader(null) {
            @Override
            protected Class<?> findClass(String name) throws ClassNotFoundException {
              Class<?> c = Class.forName(name);
              if (name.startsWith("com.sun.source.") || name.startsWith("com.sun.tools.")) {
                return c;
              }
              if (c.getClassLoader() == null
                  || Objects.equals(getClassLoaderName(c.getClassLoader()), "platform")) {
                return c;
              }
              throw new ClassNotFoundException(name);
            }
          });
    }
  }

  // TODO(cushon): remove this use of reflection if Java 9 is released.
  private static String getClassLoaderName(ClassLoader classLoader) {
    Method method;
    try {
      method = ClassLoader.class.getMethod("getName");
    } catch (NoSuchMethodException e) {
      // ClassLoader#getName doesn't exist in JDK 8 and earlier.
      return null;
    }
    try {
      return (String) method.invoke(classLoader, new Object[] {});
    } catch (ReflectiveOperationException e) {
      throw new LinkageError(e.getMessage(), e);
    }
  }

  static void setupContext(
      Context context, @Nullable StrictJavaDepsPlugin sjd, JavacTransitive transitive) {
    JavacTurbineJavaCompiler.preRegister(context, sjd, transitive);
  }
}