aboutsummaryrefslogtreecommitdiff
path: root/processor/src/main/java/org/robolectric/annotation/processing/validator/SdkStore.java
blob: c65076e78f4ccb5f3216f38d0638ebdf80e0c494 (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
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package org.robolectric.annotation.processing.validator;

import static org.robolectric.annotation.Implementation.DEFAULT_SDK;
import static org.robolectric.annotation.processing.validator.ImplementsValidator.CONSTRUCTOR_METHOD_NAME;
import static org.robolectric.annotation.processing.validator.ImplementsValidator.STATIC_INITIALIZER_METHOD_NAME;
import static org.robolectric.annotation.processing.validator.ImplementsValidator.getClassFQName;

import com.sun.tools.javac.code.Type.ArrayType;
import com.sun.tools.javac.code.Type.TypeVar;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import org.robolectric.annotation.Implementation;

class SdkStore {

  private final Set<Sdk> sdks = new TreeSet<>();
  private boolean loaded = false;

  List<Sdk> sdksMatching(Implementation implementation, int classMinSdk, int classMaxSdk) {
    loadSdksOnce();

    int minSdk = implementation == null ? DEFAULT_SDK : implementation.minSdk();
    if (minSdk == DEFAULT_SDK) {
      minSdk = 0;
    }
    if (classMinSdk > minSdk) {
      minSdk = classMinSdk;
    }

    int maxSdk = implementation == null ? -1 : implementation.maxSdk();
    if (maxSdk == -1) {
      maxSdk = Integer.MAX_VALUE;
    }
    if (classMaxSdk != -1 && classMaxSdk < maxSdk) {
      maxSdk = classMaxSdk;
    }

    List<Sdk> matchingSdks = new ArrayList<>();
    for (Sdk sdk : sdks) {
      Integer sdkInt = sdk.sdkInt;
      if (sdkInt >= minSdk && sdkInt <= maxSdk) {
        matchingSdks.add(sdk);
      }
    }
    return matchingSdks;
  }

  private synchronized void loadSdksOnce() {
    if (!loaded) {
      sdks.addAll(loadFromSdksFile("/sdks.txt"));
      loaded = true;
    }
  }

  private static List<Sdk> loadFromSdksFile(String resourceFileName) {
    try (InputStream resIn = SdkStore.class.getResourceAsStream(resourceFileName)) {
      if (resIn == null) {
        throw new RuntimeException("no such resource " + resourceFileName);
      }

      BufferedReader in =
          new BufferedReader(new InputStreamReader(resIn, Charset.defaultCharset()));
      List<Sdk> sdks = new ArrayList<>();
      String line;
      while ((line = in.readLine()) != null) {
        if (!line.startsWith("#")) {
          sdks.add(new Sdk(line));
        }
      }
      return sdks;
    } catch (IOException e) {
      throw new RuntimeException("failed reading " + resourceFileName, e);
    }
  }

  static class Sdk implements Comparable<Sdk> {
    private static final ClassInfo NULL_CLASS_INFO = new ClassInfo();

    private final String path;
    private final JarFile jarFile;
    final int sdkInt;
    private final Map<String, ClassInfo> classInfos = new HashMap<>();
    private static File tempDir;

    Sdk(String path) {
      this.path = path;
      this.jarFile = ensureJar();
      this.sdkInt = readSdkInt();
    }

    /**
     * Matches an `@Implementation` method against the framework method for this SDK.
     *
     * @param sdkClassElem the framework class being shadowed
     * @param methodElement the `@Implementation` method declaration to check
     * @param looseSignatures if `true`, also match any framework method with the same class,
     *     name, return type, and arity of parameters.
     * @return a string describing any problems with this method, or `null` if it checks out.
     */
    public String verifyMethod(TypeElement sdkClassElem, ExecutableElement methodElement,
        boolean looseSignatures) {
      String className = getClassFQName(sdkClassElem);
      ClassInfo classInfo = getClassInfo(className);

      if (classInfo == null) {
        return "No such class " + className;
      }

      MethodExtraInfo sdkMethod = classInfo.findMethod(methodElement, looseSignatures);
      if (sdkMethod == null) {
        return "No such method in " + className;
      }

      MethodExtraInfo implMethod = new MethodExtraInfo(methodElement);
      if (sdkMethod.equals(implMethod)) {
        if (implMethod.isStatic != sdkMethod.isStatic) {
          return "@Implementation for " + methodElement.getSimpleName()
              + " is " + (implMethod.isStatic ? "static" : "not static")
              + " unlike the SDK method";
        }
        if (!implMethod.returnType.equals(sdkMethod.returnType)) {
          return "@Implementation for " + methodElement.getSimpleName()
              + " has a return type of " + implMethod.returnType
              + ", not " + sdkMethod.returnType + " as in the SDK method";
        }
      }

      return null;
    }

    /**
     * Load and analyze bytecode for the specified class, with caching.
     *
     * @param name the name of the class to analyze
     * @return information about the methods in the specified class
     */
    private synchronized ClassInfo getClassInfo(String name) {
      ClassInfo classInfo = classInfos.get(name);
      if (classInfo == null) {
        ClassNode classNode = loadClassNode(name);

        if (classNode == null) {
          classInfos.put(name, NULL_CLASS_INFO);
        } else {
          classInfo = new ClassInfo(classNode);
          classInfos.put(name, classInfo);
        }
      }

      return classInfo == NULL_CLASS_INFO ? null : classInfo;
    }

    /**
     * Determine the API level for this SDK jar by inspecting its `build.prop` file.
     *
     * If the `ro.build.version.codename` value isn't `REL`, this is an unreleased SDK, which
     * is represented as `10000` (see {@link android.os.Build.VERSION_CODES#CUR_DEVELOPMENT}.
     *
     * @return the API level, or `10000`
     */
    private int readSdkInt() {
      Properties properties = new Properties();
      try (InputStream inputStream = jarFile.getInputStream(jarFile.getJarEntry("build.prop"))) {
        properties.load(inputStream);
      } catch (IOException e) {
        throw new RuntimeException("failed to read build.prop from " + path);
      }
      int sdkInt = Integer.parseInt(properties.getProperty("ro.build.version.sdk"));
      String codename = properties.getProperty("ro.build.version.codename");
      if (!"REL".equals(codename)) {
        sdkInt = 10000;
      }

      return sdkInt;
    }

    private JarFile ensureJar() {
      try {
        URI uri = URI.create(path);
        if ("classpath".equals(uri.getScheme())) {
          return new JarFile(copyResourceToFile(uri.getSchemeSpecificPart()));
        } else {
          return new JarFile(path);
        }

      } catch (IOException e) {
        throw new RuntimeException("failed to open SDK " + sdkInt + " at " + path, e);
      }
    }

    private static File copyResourceToFile(String resourcePath) throws IOException {
      if (tempDir == null){
        File tempFile = File.createTempFile("prefix", "suffix");
        tempFile.deleteOnExit();
        tempDir = tempFile.getParentFile();
      }
      InputStream jarIn = SdkStore.class.getClassLoader().getResourceAsStream(resourcePath);
      File outFile = new File(tempDir, new File(resourcePath).getName());
      outFile.deleteOnExit();
      try (FileOutputStream jarOut = new FileOutputStream(outFile)) {
        byte[] buffer = new byte[4096];
        int len;
        while ((len = jarIn.read(buffer)) != -1) {
          jarOut.write(buffer, 0, len);
        }
      }

      return outFile;
    }

    private ClassNode loadClassNode(String name) {
      String classFileName = name.replace('.', '/') + ".class";
      ZipEntry entry = jarFile.getEntry(classFileName);
      if (entry == null) {
        return null;
      }
      try (InputStream inputStream = jarFile.getInputStream(entry)) {
        ClassReader classReader = new ClassReader(inputStream);
        ClassNode classNode = new ClassNode();
        classReader.accept(classNode,
            ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
        return classNode;
      } catch (IOException e) {
        throw new RuntimeException("failed to analyze " + classFileName + " in " + path, e);
      }
    }

    @Override
    public int compareTo(Sdk sdk) {
      return sdk.sdkInt - sdkInt;
    }
  }

  static class ClassInfo {
    private final Map<MethodInfo, MethodExtraInfo> methods = new HashMap<>();
    private final Map<MethodInfo, MethodExtraInfo> erasedParamTypesMethods = new HashMap<>();

    private ClassInfo() {
    }

    public ClassInfo(ClassNode classNode) {
      for (Object aMethod : classNode.methods) {
        MethodNode method = ((MethodNode) aMethod);
        MethodInfo methodInfo = new MethodInfo(method);
        MethodExtraInfo methodExtraInfo = new MethodExtraInfo(method);
        methods.put(methodInfo, methodExtraInfo);
        erasedParamTypesMethods.put(methodInfo.erase(), methodExtraInfo);
      }
    }

    MethodExtraInfo findMethod(ExecutableElement methodElement, boolean looseSignatures) {
      MethodInfo methodInfo = new MethodInfo(methodElement);

      MethodExtraInfo methodExtraInfo = methods.get(methodInfo);
      if (looseSignatures && methodExtraInfo == null) {
        methodExtraInfo = erasedParamTypesMethods.get(methodInfo.erase());
      }
      return methodExtraInfo;
    }
  }

  static class MethodInfo {
    private final String name;
    private final List<String> paramTypes = new ArrayList<>();

    /** Create a MethodInfo from ASM in-memory representation (an Android framework method). */
    public MethodInfo(MethodNode method) {
      this.name = method.name;
      for (Type type : Type.getArgumentTypes(method.desc)) {
        paramTypes.add(type.getClassName().replace('$', '.'));
      }
    }

    /** Create a MethodInfo with all Object params (for looseSignatures=true). */
    public MethodInfo(String name, int size) {
      this.name = name;
      for (int i = 0; i < size; i++) {
        paramTypes.add("java.lang.Object");
      }
    }

    /** Create a MethodInfo from AST (an @Implementation method in a shadow class). */
    public MethodInfo(ExecutableElement methodElement) {
      this.name = cleanMethodName(methodElement);

      for (VariableElement variableElement : methodElement.getParameters()) {
        TypeMirror varTypeMirror = variableElement.asType();
        String paramType = canonicalize(varTypeMirror);
        String paramTypeWithoutGenerics = paramType.replaceAll("<.*", "");
        paramTypes.add(paramTypeWithoutGenerics);
      }
    }

    private String canonicalize(TypeMirror typeMirror) {
      if (typeMirror instanceof TypeVar) {
        return ((TypeVar) typeMirror).getUpperBound().toString();
      } else if (typeMirror instanceof ArrayType) {
        return canonicalize(((ArrayType) typeMirror).elemtype) + "[]";
      } else {
        return typeMirror.toString();
      }
    }

    private String cleanMethodName(ExecutableElement methodElement) {
      String name = methodElement.getSimpleName().toString();
      if (CONSTRUCTOR_METHOD_NAME.equals(name)) {
        return "<init>";
      } else if (STATIC_INITIALIZER_METHOD_NAME.equals(name)) {
        return "<clinit>";
      } else {
        return name;
      }
    }

    public MethodInfo erase() {
      return new MethodInfo(name, paramTypes.size());
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) {
        return true;
      }
      if (o == null || getClass() != o.getClass()) {
        return false;
      }
      MethodInfo that = (MethodInfo) o;
      return Objects.equals(name, that.name)
          && Objects.equals(paramTypes, that.paramTypes);
    }

    @Override
    public int hashCode() {
      return Objects.hash(name, paramTypes);
    }

    @Override
    public String toString() {
      return "MethodInfo{"
          + "name='" + name + '\''
          + ", paramTypes=" + paramTypes
          + '}';
    }
  }

  static class MethodExtraInfo {
    private final boolean isStatic;
    private final String returnType;

    public MethodExtraInfo(MethodNode method) {
      this.isStatic = (method.access & Opcodes.ACC_STATIC) != 0;
      this.returnType = Type.getReturnType(method.desc).getClassName();
    }

    public MethodExtraInfo(ExecutableElement methodElement) {
      this.isStatic = methodElement.getModifiers().contains(Modifier.STATIC);
      this.returnType = methodElement.getReturnType().toString();
    }
  }
}