NativeLibrariesBootstrap .java

com.mojang.blaze3d.platform.NativeLibrariesBootstrap (class): members: isVulkanLoaderAvailable, vulkanLoaderAvailable, CapturingPrintStream, loadLibraries.

com.mojang.blaze3d.platformclass363 linesclient12.5 KB

API Surface (6)

void loadLibraries()
boolean isVulkanLoaderAvailable()
void startCapturing()
String stopCapturing()
void write(final byte[] b, final int off, final int len)
void write(final int b)

Fields & Constants (3)

LOGGER
HEX_FORMAT
vulkanLoaderAvailable

String literals (39)

"jna.tmpdir"
"io.netty.native.workdir"
"Simulated debug crash"
"LWJGL system"
"OpenGL"
"OpenAL"
"freetype"
"shaderc"
"spvc"
"Loading libraries"
"Libraries loaded"
"Loading order"
"Loading index"
"VeryImportant"
"Failed to lock "
"Unexpected probe file contents, expected '"
"', but got '"
"System.out needed before bootstrap"
"<LWJGL debug enabled, not capturing>"
"Loading library "
"Library directory contents"
"java.library.path"
"Contents of shared library directory"
"Contents of java.library.path "

Full Source

NativeLibrariesBootstrap.java363 lines · Minecraft 26.3 · verbatim
1
package com.mojang.blaze3d.platform;
2
3
import com.google.common.base.Stopwatch;
4
import com.google.common.primitives.Ints;
5
import com.mojang.datafixers.util.Pair;
6
import com.mojang.logging.LogUtils;
7
import java.io.ByteArrayOutputStream;
8
import java.io.IOException;
9
import java.io.OutputStream;
10
import java.io.PrintStream;
11
import java.nio.channels.Channels;
12
import java.nio.channels.FileChannel;
13
import java.nio.channels.FileLock;
14
import java.nio.charset.StandardCharsets;
15
import java.nio.file.DirectoryStream;
16
import java.nio.file.Files;
17
import java.nio.file.Path;
18
import java.util.ArrayList;
19
import java.util.Arrays;
20
import java.util.Collections;
21
import java.util.HexFormat;
22
import java.util.List;
23
import java.util.Locale;
24
import java.util.Objects;
25
import java.util.Optional;
26
import java.util.concurrent.TimeUnit;
27
import java.util.function.Supplier;
28
import java.util.stream.Collectors;
29
import net.fabricmc.api.EnvType;
30
import net.fabricmc.api.Environment;
31
import net.minecraft.CrashReport;
32
import net.minecraft.CrashReportCategory;
33
import net.minecraft.ReportedException;
34
import net.minecraft.SharedConstants;
35
import net.minecraft.SuppressForbidden;
36
import net.minecraft.util.NativeModuleLister;
37
import net.minecraft.util.RandomSource;
38
import net.minecraft.util.NativeModuleLister.NativeModuleVersion;
39
import org.apache.commons.io.output.TeeOutputStream;
40
import org.jspecify.annotations.Nullable;
41
import org.lwjgl.Version;
42
import org.lwjgl.openal.ALC;
43
import org.lwjgl.opengl.GL;
44
import org.lwjgl.sdl.SDL;
45
import org.lwjgl.stb.STBImage;
46
import org.lwjgl.system.Configuration;
47
import org.lwjgl.system.Library;
48
import org.lwjgl.system.Platform;
49
import org.lwjgl.util.freetype.FreeType;
50
import org.lwjgl.util.shaderc.Shaderc;
51
import org.lwjgl.util.spvc.Spvc;
52
import org.lwjgl.util.vma.Vma;
53
import org.lwjgl.vulkan.VK;
54
import org.slf4j.Logger;
55
56
@Environment(EnvType.CLIENT)
57
public class NativeLibrariesBootstrap {
58
	private static final Logger LOGGER = LogUtils.getLogger();
59
	private static final HexFormat HEX_FORMAT = HexFormat.of().withUpperCase();
60
	private static boolean vulkanLoaderAvailable;
61
62
	public static void loadLibraries() throws IOException {
63
		Stopwatch stopwatch = Stopwatch.createStarted();
64
		configureLWJGLLibraryPath();
65
		createAndCheckDirectory(Configuration.SHARED_LIBRARY_EXTRACT_PATH.get(""));
66
		createAndCheckDirectory(System.getProperty("jna.tmpdir", ""));
67
		createAndCheckDirectory(System.getProperty("io.netty.native.workdir", ""));
68
		Boolean originalDebugLoader = Configuration.DEBUG_LOADER.get();
69
		Configuration.DEBUG_LOADER.set(true);
70
		Supplier<String> stopCapturing = setupLWJGLCapture();
71
		int libraryIndex = -1;
72
		List<NativeLibrariesBootstrap.LibraryLoadEntry> entries = new ArrayList<>();
73
74
		try {
75
			if (SharedConstants.DEBUG_SIMULATE_LIBRARY_LOAD_FAILURE) {
76
				throw new UnsatisfiedLinkError("Simulated debug crash");
77
			}
78
79
			loadLibrary(stopCapturing, "LWJGL system", NativeLibrariesBootstrap::loadLWJGLSystem);
80
			vulkanLoaderAvailable = tryLoadingVulkan();
81
			entries.add(new NativeLibrariesBootstrap.LibraryLoadEntry("SDL", NativeLibrariesBootstrap::loadSdl));
82
			entries.add(new NativeLibrariesBootstrap.LibraryLoadEntry("OpenGL", NativeLibrariesBootstrap::loadOpenGL));
83
			entries.add(new NativeLibrariesBootstrap.LibraryLoadEntry("OpenAL", NativeLibrariesBootstrap::loadOpenAL));
84
			entries.add(new NativeLibrariesBootstrap.LibraryLoadEntry("STB", NativeLibrariesBootstrap::loadSTB));
85
			entries.add(new NativeLibrariesBootstrap.LibraryLoadEntry("freetype", NativeLibrariesBootstrap::loadFreeType));
86
			if (vulkanLoaderAvailable) {
87
				entries.add(new NativeLibrariesBootstrap.LibraryLoadEntry("shaderc", NativeLibrariesBootstrap::loadShaderc));
88
				entries.add(new NativeLibrariesBootstrap.LibraryLoadEntry("spvc", NativeLibrariesBootstrap::loadSpvc));
89
				entries.add(new NativeLibrariesBootstrap.LibraryLoadEntry("vma", NativeLibrariesBootstrap::loadVma));
90
			}
91
92
			Collections.shuffle(entries);
93
94
			for (libraryIndex = 0; libraryIndex < entries.size(); libraryIndex++) {
95
				NativeLibrariesBootstrap.LibraryLoadEntry e = entries.get(libraryIndex);
96
				loadLibrary(stopCapturing, e.name(), e.loader());
97
			}
98
		} catch (Throwable t) {
99
			CrashReport crashReport = CrashReport.forThrowable(t, "Loading libraries");
100
			CrashReportCategory librariesLoaded = crashReport.addCategory("Libraries loaded");
101
			librariesLoaded.setDetail("Loading order", () -> entries.stream().map(NativeLibrariesBootstrap.LibraryLoadEntry::name).collect(Collectors.joining(",")));
102
			librariesLoaded.setDetail("Loading index", Integer.toString(libraryIndex));
103
			throw new ReportedException(crashReport);
104
		} finally {
105
			stopCapturing.get();
106
			Configuration.DEBUG_LOADER.set(originalDebugLoader);
107
		}
108
109
		long var13 = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS);
110
		LOGGER.debug("Library load time: {} ms", var13);
111
	}
112
113
	private static void createAndCheckDirectory(final String libraryDir) throws IOException {
114
		if (!libraryDir.isEmpty()) {
115
			Path libraryDirPath = Path.of(libraryDir);
116
			Files.createDirectories(libraryDirPath);
117
			RandomSource randomSource = RandomSource.createThreadLocalInstance();
118
			String trollFileName = System.mapLibraryName("VeryImportant" + randomSource.nextInt(9999));
119
			Path probeFile = libraryDirPath.resolve(trollFileName);
120
			byte[] expectedBytes = Ints.toByteArray(randomSource.nextInt());
121
			Files.write(probeFile, expectedBytes);
122
123
			try (
124
				FileChannel fc = FileChannel.open(probeFile);
125
				FileLock lock = tryLock(fc);
126
			) {
127
				if (lock == null) {
128
					throw new IOException("Failed to lock " + probeFile);
129
				}
130
131
				byte[] readBytes = Channels.newInputStream(fc).readAllBytes();
132
				if (!Arrays.equals(expectedBytes, readBytes)) {
133
					throw new IOException(
134
						"Unexpected probe file contents, expected '" + HEX_FORMAT.formatHex(expectedBytes) + "', but got '" + HEX_FORMAT.formatHex(readBytes) + "'"
135
					);
136
				}
137
			} finally {
138
				Files.delete(probeFile);
139
			}
140
		}
141
	}
142
143
	private static @Nullable FileLock tryLock(final FileChannel fc) throws IOException {
144
		for (int i = 0; i < 5; i++) {
145
			FileLock lock = fc.tryLock(0L, Long.MAX_VALUE, true);
146
			if (lock != null) {
147
				return lock;
148
			}
149
150
			try {
151
				Thread.sleep(10L);
152
			} catch (InterruptedException var4) {
153
				break;
154
			}
155
		}
156
157
		return null;
158
	}
159
160
	private static void configureLWJGLLibraryPath() {
161
		String libraryPathString = Configuration.SHARED_LIBRARY_EXTRACT_PATH.get();
162
		if (libraryPathString != null) {
163
			String version = Version.getVersion().replace(' ', '-');
164
			String arch = Platform.getArchitecture().name().toLowerCase(Locale.ROOT);
165
			Path newLibraryDir = Path.of(libraryPathString).resolve(version, arch);
166
			Configuration.SHARED_LIBRARY_EXTRACT_PATH.set(newLibraryDir.toString());
167
		}
168
	}
169
170
	@SuppressForbidden(reason = "System.out needed before bootstrap")
171
	private static Supplier<String> setupLWJGLCapture() {
172
		if (Configuration.DEBUG_STREAM.get() == null && !Configuration.DEBUG.get(false)) {
173
			NativeLibrariesBootstrap.CapturingPrintStream capturingPrintStream = new NativeLibrariesBootstrap.CapturingPrintStream(System.out);
174
			Configuration.DEBUG_STREAM.set(capturingPrintStream);
175
			capturingPrintStream.startCapturing();
176
			return capturingPrintStream::stopCapturing;
177
		} else {
178
			return () -> "<LWJGL debug enabled, not capturing>";
179
		}
180
	}
181
182
	private static void loadLibrary(final Supplier<String> debugCapture, final String name, final Runnable loader) {
183
		try {
184
			LOGGER.debug("Loading {}", name);
185
			loader.run();
186
		} catch (Throwable t) {
187
			CrashReport crashReport = CrashReport.forThrowable(t, "Loading library " + name);
188
			CrashReportCategory libraryInfoCategory = crashReport.addCategory("Library directory contents");
189
			String systemPropertyDir = System.getProperty("java.library.path", "");
190
			String lwjglPropertyDir = Configuration.LIBRARY_PATH.get("");
191
			if (systemPropertyDir.equals(lwjglPropertyDir)) {
192
				libraryInfoCategory.setDetail("Contents of shared library directory", () -> listLibrariesDirectory(systemPropertyDir));
193
			} else {
194
				libraryInfoCategory.setDetail("Contents of java.library.path ", () -> listLibrariesDirectory(systemPropertyDir));
195
				libraryInfoCategory.setDetail("Contents of org.lwjgl.librarypath", () -> listLibrariesDirectory(lwjglPropertyDir));
196
			}
197
198
			libraryInfoCategory.setDetail("LWJGL platform", () -> Platform.get().toString());
199
			libraryInfoCategory.setDetail("LWJGL architecture", () -> Platform.getArchitecture().toString());
200
			CrashReportCategory lwjglDebugLog = crashReport.addCategory("LWJGL debug log");
201
202
			try {
203
				lwjglDebugLog.setDetail("Log", debugCapture.get());
204
			} catch (Throwable e) {
205
				lwjglDebugLog.setDetail("Log", e);
206
			}
207
208
			throw new ReportedException(crashReport);
209
		}
210
	}
211
212
	private static String listLibrariesDirectory(final @Nullable String libraryDirProperty) throws IOException {
213
		if (libraryDirProperty == null || libraryDirProperty.isEmpty()) {
214
			return "<not set>";
215
		}
216
217
		if (libraryDirProperty.contains(";")) {
218
			return "<multiple directories>";
219
		}
220
221
		Path libraryDirPath = Path.of(libraryDirProperty);
222
		if (!Files.isDirectory(libraryDirPath)) {
223
			return "<not a directory>";
224
		}
225
226
		List<Pair<Path, String>> contents = new ArrayList<>();
227
228
		try (DirectoryStream<Path> libraryDir = Files.newDirectoryStream(libraryDirPath)) {
229
			for (Path dirEntry : libraryDir) {
230
				contents.add(Pair.of(dirEntry, identifyFileContents(dirEntry)));
231
			}
232
		}
233
234
		return contents.isEmpty()
235
			? "<empty>"
236
			: "\n" + contents.stream().map(s -> "\t\t" + s.getFirst().getFileName() + ": " + s.getSecond()).collect(Collectors.joining("\n"));
237
	}
238
239
	private static String identifyFileContents(final Path path) {
240
		try {
241
			if (Files.isRegularFile(path)) {
242
				if (path.getFileName().toString().endsWith(".dll")) {
243
					Optional<String> detailedModuleInfo = NativeModuleLister.tryGetModuleVersion(path.toString()).map(NativeModuleVersion::toString);
244
					if (detailedModuleInfo.isPresent()) {
245
						return "module: " + detailedModuleInfo.get();
246
					}
247
				}
248
249
				return Objects.requireNonNullElse(Files.probeContentType(path), "unknown type");
250
			} else {
251
				return "not a file";
252
			}
253
		} catch (Throwable e) {
254
			LOGGER.warn("Failed to get details of file {}", path, e);
255
			return "error: " + e.getMessage();
256
		}
257
	}
258
259
	private static void loadLWJGLSystem() {
260
		Library.initialize();
261
	}
262
263
	private static void loadSdl() {
264
		Objects.requireNonNull(SDL.getLibrary());
265
	}
266
267
	private static void loadOpenGL() {
268
		Objects.requireNonNull(GL.getFunctionProvider());
269
	}
270
271
	private static void loadOpenAL() {
272
		Objects.requireNonNull(ALC.getFunctionProvider());
273
	}
274
275
	private static void loadSTB() {
276
		String lastStbError = STBImage.stbi_failure_reason();
277
		if (lastStbError != null) {
278
			throw new IllegalStateException("No error expected, but got " + lastStbError);
279
		}
280
	}
281
282
	private static boolean tryLoadingVulkan() {
283
		if (Configuration.VULKAN_EXPLICIT_INIT.get() == null) {
284
			Configuration.VULKAN_EXPLICIT_INIT.set(true);
285
		}
286
287
		try {
288
			VK.create();
289
			return true;
290
		} catch (Throwable t) {
291
			LOGGER.warn("Failed to load Vulkan loader", t);
292
			return false;
293
		}
294
	}
295
296
	public static boolean isVulkanLoaderAvailable() {
297
		return vulkanLoaderAvailable;
298
	}
299
300
	private static void loadShaderc() {
301
		Objects.requireNonNull(Shaderc.getLibrary());
302
	}
303
304
	private static void loadSpvc() {
305
		Objects.requireNonNull(Spvc.getLibrary());
306
	}
307
308
	private static void loadVma() {
309
		try {
310
			Vma.vmaDestroyAllocator(0L);
311
		} catch (NullPointerException var1) {
312
		}
313
	}
314
315
	private static void loadFreeType() {
316
		Objects.requireNonNull(FreeType.getLibrary());
317
	}
318
319
	@Environment(EnvType.CLIENT)
320
	private static class CapturingPrintStream extends PrintStream {
321
		private final NativeLibrariesBootstrap.CapturingStream collector;
322
323
		public CapturingPrintStream(final OutputStream out) {
324
			NativeLibrariesBootstrap.CapturingStream logStream = new NativeLibrariesBootstrap.CapturingStream();
325
			super(new TeeOutputStream(out, logStream), false, StandardCharsets.UTF_8);
326
			this.collector = logStream;
327
		}
328
329
		public synchronized void startCapturing() {
330
			this.collector.buffer = new ByteArrayOutputStream();
331
		}
332
333
		public synchronized String stopCapturing() {
334
			ByteArrayOutputStream buffer = this.collector.buffer;
335
			this.collector.buffer = null;
336
			return buffer != null ? buffer.toString(StandardCharsets.UTF_8) : "";
337
		}
338
	}
339
340
	@Environment(EnvType.CLIENT)
341
	private static class CapturingStream extends OutputStream {
342
		private @Nullable ByteArrayOutputStream buffer;
343
344
		@Override
345
		public void write(final byte[] b, final int off, final int len) {
346
			if (this.buffer != null) {
347
				this.buffer.write(b, off, len);
348
			}
349
		}
350
351
		@Override
352
		public void write(final int b) {
353
			if (this.buffer != null) {
354
				this.buffer.write(b);
355
			}
356
		}
357
	}
358
359
	@Environment(EnvType.CLIENT)
360
	private record LibraryLoadEntry(String name, Runnable loader) {
361
	}
362
}
363

Decompiled Minecraft 26.3 source of NativeLibrariesBootstrap (com/mojang/blaze3d/platform/NativeLibrariesBootstrap.java) with Mojang official mappings, stored verbatim on the site.