-
Notifications
You must be signed in to change notification settings - Fork 270
/
Copy pathKnot.java
347 lines (275 loc) · 10.4 KB
/
Knot.java
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
/*
* Copyright 2016 FabricMC
*
* 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 net.fabricmc.loader.impl.launch.knot;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.jar.Manifest;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import net.fabricmc.api.EnvType;
import net.fabricmc.loader.api.entrypoint.PreLaunchEntrypoint;
import net.fabricmc.loader.impl.FabricLoaderImpl;
import net.fabricmc.loader.impl.FormattedException;
import net.fabricmc.loader.impl.game.GameProvider;
import net.fabricmc.loader.impl.launch.FabricLauncherBase;
import net.fabricmc.loader.impl.launch.FabricMixinBootstrap;
import net.fabricmc.loader.impl.util.LoaderUtil;
import net.fabricmc.loader.impl.util.SystemProperties;
import net.fabricmc.loader.impl.util.UrlUtil;
import net.fabricmc.loader.impl.util.log.Log;
import net.fabricmc.loader.impl.util.log.LogCategory;
public final class Knot extends FabricLauncherBase {
private static final boolean IS_DEVELOPMENT = Boolean.parseBoolean(System.getProperty(SystemProperties.DEVELOPMENT, "false"));
protected Map<String, Object> properties = new HashMap<>();
private KnotClassLoaderInterface classLoader;
private EnvType envType;
private final List<Path> classPath = new ArrayList<>();
private GameProvider provider;
private boolean unlocked;
public static void launch(String[] args, EnvType type) {
setupUncaughtExceptionHandler();
try {
Knot knot = new Knot(type);
ClassLoader cl = knot.init(args);
if (knot.provider == null) {
throw new IllegalStateException("Game provider was not initialized! (Knot#init(String[]))");
}
knot.provider.launch(cl);
} catch (FormattedException e) {
handleFormattedException(e);
}
}
public Knot(EnvType type) {
this.envType = type;
}
public ClassLoader init(String[] args) {
setProperties(properties);
// configure fabric vars
if (envType == null) {
String side = System.getProperty(SystemProperties.SIDE);
if (side == null) throw new RuntimeException("Please specify side or use a dedicated Knot!");
switch (side.toLowerCase(Locale.ROOT)) {
case "client":
envType = EnvType.CLIENT;
break;
case "server":
envType = EnvType.SERVER;
break;
default:
throw new RuntimeException("Invalid side provided: must be \"client\" or \"server\"!");
}
}
classPath.clear();
List<String> missing = null;
List<String> unsupported = null;
for (String cpEntry : System.getProperty("java.class.path").split(File.pathSeparator)) {
if (cpEntry.equals("*") || cpEntry.endsWith(File.separator + "*")) {
if (unsupported == null) unsupported = new ArrayList<>();
unsupported.add(cpEntry);
continue;
}
Path path = Paths.get(cpEntry);
if (!Files.exists(path)) {
if (missing == null) missing = new ArrayList<>();
missing.add(cpEntry);
continue;
}
classPath.add(LoaderUtil.normalizeExistingPath(path));
}
if (unsupported != null) Log.warn(LogCategory.KNOT, "Knot does not support wildcard class path entries: %s - the game may not load properly!", String.join(", ", unsupported));
if (missing != null) Log.warn(LogCategory.KNOT, "Class path entries reference missing files: %s - the game may not load properly!", String.join(", ", missing));
provider = createGameProvider(args);
Log.finishBuiltinConfig();
Log.info(LogCategory.GAME_PROVIDER, "Loading %s %s with Fabric Loader %s", provider.getGameName(), provider.getRawGameVersion(), FabricLoaderImpl.VERSION);
// Setup classloader
// TODO: Provide KnotCompatibilityClassLoader in non-exclusive-Fabric pre-1.13 environments?
boolean useCompatibility = provider.requiresUrlClassLoader() || Boolean.parseBoolean(System.getProperty("fabric.loader.useCompatibilityClassLoader", "false"));
classLoader = KnotClassLoaderInterface.create(useCompatibility, isDevelopment(), envType, provider);
ClassLoader cl = classLoader.getClassLoader();
provider.initialize(this);
Thread.currentThread().setContextClassLoader(cl);
FabricLoaderImpl loader = FabricLoaderImpl.INSTANCE;
loader.setGameProvider(provider);
loader.load();
loader.freeze();
FabricLoaderImpl.INSTANCE.loadAccessWideners();
FabricMixinBootstrap.init(getEnvironmentType(), loader);
FabricLauncherBase.finishMixinBootstrapping();
classLoader.initializeTransformers();
provider.unlockClassPath(this);
unlocked = true;
try {
loader.invokeEntrypoints("preLaunch", PreLaunchEntrypoint.class, PreLaunchEntrypoint::onPreLaunch);
} catch (RuntimeException e) {
throw FormattedException.ofLocalized("exception.initializerFailure", e);
}
return cl;
}
private GameProvider createGameProvider(String[] args) {
// fast path with direct lookup
GameProvider embeddedGameProvider = findEmbedddedGameProvider();
if (embeddedGameProvider != null
&& embeddedGameProvider.isEnabled()
&& embeddedGameProvider.locateGame(this, args)) {
return embeddedGameProvider;
}
// slow path with service loader
List<GameProvider> failedProviders = new ArrayList<>();
for (GameProvider provider : ServiceLoader.load(GameProvider.class)) {
if (!provider.isEnabled()) continue; // don't attempt disabled providers and don't include them in the error report
if (provider != embeddedGameProvider // don't retry already failed provider
&& provider.locateGame(this, args)) {
return provider;
}
failedProviders.add(provider);
}
// nothing found
String msg;
if (failedProviders.isEmpty()) {
msg = "No game providers present on the class path!";
} else if (failedProviders.size() == 1) {
msg = String.format("%s game provider couldn't locate the game! "
+ "The game may be absent from the class path, lacks some expected files, suffers from jar "
+ "corruption or is of an unsupported variety/version.",
failedProviders.get(0).getGameName());
} else {
msg = String.format("None of the game providers (%s) were able to locate their game!",
failedProviders.stream().map(GameProvider::getGameName).collect(Collectors.joining(", ")));
}
Log.error(LogCategory.GAME_PROVIDER, msg);
throw new RuntimeException(msg);
}
/**
* Find game provider embedded into the Fabric Loader jar, best effort.
*
* <p>This is faster than going through service loader because it only looks at a single jar.
*/
private static GameProvider findEmbedddedGameProvider() {
try {
Path flPath = UrlUtil.getCodeSource(Knot.class);
if (flPath == null || !flPath.getFileName().toString().endsWith(".jar")) return null; // not a jar
try (ZipFile zf = new ZipFile(flPath.toFile())) {
ZipEntry entry = zf.getEntry("META-INF/services/net.fabricmc.loader.impl.game.GameProvider"); // same file as used by service loader
if (entry == null) return null;
try (InputStream is = zf.getInputStream(entry)) {
byte[] buffer = new byte[100];
int offset = 0;
int len;
while ((len = is.read(buffer, offset, buffer.length - offset)) >= 0) {
offset += len;
if (offset == buffer.length) buffer = Arrays.copyOf(buffer, buffer.length * 2);
}
String content = new String(buffer, 0, offset, StandardCharsets.UTF_8).trim();
if (content.indexOf('\n') >= 0) return null; // potentially more than one entry -> bail out
int pos = content.indexOf('#');
if (pos >= 0) content = content.substring(0, pos).trim();
if (!content.isEmpty()) {
return (GameProvider) Class.forName(content).getConstructor().newInstance();
}
}
}
return null;
} catch (IOException | ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
@Override
public String getTargetNamespace() {
// TODO: Won't work outside of Yarn
return IS_DEVELOPMENT ? "named" : "intermediary";
}
@Override
public List<Path> getClassPath() {
return classPath;
}
@Override
public void addToClassPath(Path path, String... allowedPrefixes) {
Log.debug(LogCategory.KNOT, "Adding " + path + " to classpath.");
classLoader.setAllowedPrefixes(path, allowedPrefixes);
classLoader.addCodeSource(path);
}
@Override
public void setAllowedPrefixes(Path path, String... prefixes) {
classLoader.setAllowedPrefixes(path, prefixes);
}
@Override
public void setValidParentClassPath(Collection<Path> paths) {
classLoader.setValidParentClassPath(paths);
}
@Override
public EnvType getEnvironmentType() {
return envType;
}
@Override
public boolean isClassLoaded(String name) {
return classLoader.isClassLoaded(name);
}
@Override
public Class<?> loadIntoTarget(String name) throws ClassNotFoundException {
return classLoader.loadIntoTarget(name);
}
@Override
public InputStream getResourceAsStream(String name) {
return classLoader.getClassLoader().getResourceAsStream(name);
}
@Override
public ClassLoader getTargetClassLoader() {
KnotClassLoaderInterface classLoader = this.classLoader;
return classLoader != null ? classLoader.getClassLoader() : null;
}
@Override
public byte[] getClassByteArray(String name, boolean runTransformers) throws IOException {
if (!unlocked) throw new IllegalStateException("early getClassByteArray access");
if (runTransformers) {
return classLoader.getPreMixinClassBytes(name);
} else {
return classLoader.getRawClassBytes(name);
}
}
@Override
public Manifest getManifest(Path originPath) {
return classLoader.getManifest(originPath);
}
@Override
public boolean isDevelopment() {
return IS_DEVELOPMENT;
}
@Override
public String getEntrypoint() {
return provider.getEntrypoint();
}
public static void main(String[] args) {
new Knot(null).init(args);
}
static {
LoaderUtil.verifyNotInTargetCl(Knot.class);
LoaderUtil.verifyClasspath();
}
}