aboutsummaryrefslogtreecommitdiff
path: root/nativeruntime/src/main/java/org/robolectric/nativeruntime/DefaultNativeRuntimeLoader.java
blob: 3892453dda1d807fe8ca10ee25ee1dbbc5468983 (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
package org.robolectric.nativeruntime;

import static android.os.Build.VERSION_CODES.O;
import static com.google.common.base.StandardSystemProperty.OS_ARCH;
import static com.google.common.base.StandardSystemProperty.OS_NAME;

import android.database.CursorWindow;
import android.os.Build;
import com.google.auto.service.AutoService;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Files;
import com.google.common.io.Resources;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
import javax.annotation.Priority;
import org.robolectric.pluginapi.NativeRuntimeLoader;
import org.robolectric.util.PerfStatsCollector;
import org.robolectric.util.TempDirectory;
import org.robolectric.util.inject.Injector;

/** Loads the Robolectric native runtime. */
@AutoService(NativeRuntimeLoader.class)
@Priority(Integer.MIN_VALUE)
public class DefaultNativeRuntimeLoader implements NativeRuntimeLoader {
  protected static final AtomicBoolean loaded = new AtomicBoolean(false);

  private static final AtomicReference<NativeRuntimeLoader> nativeRuntimeLoader =
      new AtomicReference<>();

  private TempDirectory extractDirectory;

  public static void injectAndLoad() {
    // Ensure a single instance.
    synchronized (nativeRuntimeLoader) {
      if (nativeRuntimeLoader.get() == null) {
        Injector injector = new Injector.Builder(CursorWindow.class.getClassLoader()).build();
        NativeRuntimeLoader loader = injector.getInstance(NativeRuntimeLoader.class);
        nativeRuntimeLoader.set(loader);
      }
    }
    nativeRuntimeLoader.get().ensureLoaded();
  }

  @Override
  public synchronized void ensureLoaded() {
    if (loaded.get()) {
      return;
    }

    if (!isSupported()) {
      String errorMessage =
          String.format(
              "The Robolectric native runtime is not supported on %s (%s)",
              OS_NAME.value(), OS_ARCH.value());
      throw new AssertionError(errorMessage);
    }
    loaded.set(true);

    try {
      PerfStatsCollector.getInstance()
          .measure(
              "loadNativeRuntime",
              () -> {
                extractDirectory = new TempDirectory("nativeruntime");
                System.setProperty(
                    "robolectric.nativeruntime.languageTag", Locale.getDefault().toLanguageTag());
                if (Build.VERSION.SDK_INT >= O) {
                  maybeCopyFonts(extractDirectory);
                }
                maybeCopyIcuData(extractDirectory);
                loadLibrary(extractDirectory);
              });
    } catch (IOException e) {
      throw new AssertionError("Unable to load Robolectric native runtime library", e);
    }
  }

  /** Attempts to load the ICU dat file. This is only relevant for native graphics. */
  private void maybeCopyIcuData(TempDirectory tempDirectory) throws IOException {
    URL icuDatUrl;
    try {
      icuDatUrl = Resources.getResource("icu/icudt68l.dat");
    } catch (IllegalArgumentException e) {
      return;
    }
    Path icuPath = tempDirectory.create("icu");
    Path icuDatPath = tempDirectory.getBasePath().resolve("icu/icudt68l.dat");
    Resources.asByteSource(icuDatUrl).copyTo(Files.asByteSink(icuDatPath.toFile()));
    System.setProperty("icu.dir", icuPath.toAbsolutePath().toString());
  }

  /**
   * Attempts to copy the system fonts to a temporary directory. This is only relevant for native
   * graphics.
   */
  private void maybeCopyFonts(TempDirectory tempDirectory) throws IOException {
    URI fontsUri = null;
    try {
      fontsUri = Resources.getResource("fonts/").toURI();
    } catch (IllegalArgumentException | URISyntaxException e) {
      return;
    }

    FileSystem zipfs = null;

    if ("jar".equals(fontsUri.getScheme())) {
      zipfs = FileSystems.newFileSystem(fontsUri, ImmutableMap.of("create", "true"));
    }

    Path fontsInputPath = Paths.get(fontsUri);
    Path fontsOutputPath = tempDirectory.create("fonts");

    try (Stream<Path> pathStream = java.nio.file.Files.walk(fontsInputPath)) {
      Iterator<Path> fileIterator = pathStream.iterator();
      while (fileIterator.hasNext()) {
        Path path = fileIterator.next();
        // Avoid copying parent directory.
        if ("fonts".equals(path.getFileName().toString())) {
          continue;
        }
        String fontPath = "fonts/" + path.getFileName();
        URL resource = Resources.getResource(fontPath);
        Path outputPath = tempDirectory.getBasePath().resolve(fontPath);
        Resources.asByteSource(resource).copyTo(Files.asByteSink(outputPath.toFile()));
      }
    }
    System.setProperty(
        "robolectric.nativeruntime.fontdir",
        // Android's FontListParser expects a trailing slash for the base font directory.
        fontsOutputPath.toAbsolutePath() + File.separator);
    if (zipfs != null) {
      zipfs.close();
    }
  }

  private void loadLibrary(TempDirectory tempDirectory) throws IOException {
    String libraryName = System.mapLibraryName("robolectric-nativeruntime");
    System.setProperty(
        "robolectric.nativeruntime.languageTag", Locale.getDefault().toLanguageTag());
    Path libraryPath = tempDirectory.getBasePath().resolve(libraryName);
    URL libraryResource = Resources.getResource(nativeLibraryPath());
    Resources.asByteSource(libraryResource).copyTo(Files.asByteSink(libraryPath.toFile()));
    System.load(libraryPath.toAbsolutePath().toString());
  }

  private static boolean isSupported() {
    return ("mac".equals(osName()) && ("aarch64".equals(arch()) || "x86_64".equals(arch())))
        || ("linux".equals(osName()) && "x86_64".equals(arch()))
        || ("windows".equals(osName()) && "x86_64".equals(arch()));
  }

  private static String nativeLibraryPath() {
    String os = osName();
    String arch = arch();
    return String.format(
        "native/%s/%s/%s", os, arch, System.mapLibraryName("robolectric-nativeruntime"));
  }

  private static String osName() {
    String osName = OS_NAME.value().toLowerCase(Locale.US);
    if (osName.contains("linux")) {
      return "linux";
    } else if (osName.contains("mac")) {
      return "mac";
    } else if (osName.contains("win")) {
      return "windows";
    }
    return "unknown";
  }

  private static String arch() {
    String arch = OS_ARCH.value().toLowerCase(Locale.US);
    if (arch.equals("x86_64") || arch.equals("amd64")) {
      return "x86_64";
    }
    return arch;
  }

  @VisibleForTesting
  static boolean isLoaded() {
    return loaded.get();
  }

  @VisibleForTesting
  Path getDirectory() {
    return extractDirectory == null ? null : extractDirectory.getBasePath();
  }

  @VisibleForTesting
  static void resetLoaded() {
    loaded.set(false);
  }
}