net.fabricmc.loader.launch.common.FabricLauncherBase Java Examples

The following examples show how to use net.fabricmc.loader.launch.common.FabricLauncherBase. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FabricTransformer.java    From fabric-loader with Apache License 2.0 6 votes vote down vote up
public static byte[] lwTransformerHook(String name, String transformedName, byte[] bytes) {
	boolean isDevelopment = FabricLauncherBase.getLauncher().isDevelopment();
	EnvType envType = FabricLauncherBase.getLauncher().getEnvironmentType();

	byte[] input = MinecraftGameProvider.TRANSFORMER.transform(name);
	if (input != null) {
		return FabricTransformer.transform(isDevelopment, envType, name, input);
	} else {
		if (bytes != null) {
			return FabricTransformer.transform(isDevelopment, envType, name, bytes);
		} else {
			return null;
		}
	}

}
 
Example #2
Source File: JavaLanguageAdapter.java    From fabric-loader with Apache License 2.0 6 votes vote down vote up
public static Class<?> getClass(String className, Options options) throws ClassNotFoundException, IOException {
	String classFilename = className.replace('.', '/') + ".class";
	InputStream stream = FabricLauncherBase.getLauncher().getResourceAsStream(classFilename);
	if (stream == null) {
		throw new ClassNotFoundException("Could not find or load class " + classFilename);
	}

	ClassReader reader = new ClassReader(stream);
	for (String s : reader.getInterfaces()) {
		if (!canApplyInterface(s)) {
			switch (options.getMissingSuperclassBehavior()) {
				case RETURN_NULL:
					stream.close();
					return null;
				case CRASH:
				default:
					stream.close();
					throw new ClassNotFoundException("Could not find or load class " + s);

			}
		}
	}

	stream.close();
	return FabricLauncherBase.getClass(className);
}
 
Example #3
Source File: FabricLoader.java    From fabric-loader with Apache License 2.0 6 votes vote down vote up
private void setupLanguageAdapters() {
	adapterMap.put("default", DefaultLanguageAdapter.INSTANCE);

	for (ModContainer mod : mods) {
		// add language adapters
		for (Map.Entry<String, String> laEntry : mod.getInfo().getLanguageAdapterDefinitions().entrySet()) {
			if (adapterMap.containsKey(laEntry.getKey())) {
				throw new RuntimeException("Duplicate language adapter key: " + laEntry.getKey() + "! (" + laEntry.getValue() + ", " + adapterMap.get(laEntry.getKey()).getClass().getName() + ")");
			}

			try {
				adapterMap.put(laEntry.getKey(), (LanguageAdapter) Class.forName(laEntry.getValue(), true, FabricLauncherBase.getLauncher().getTargetClassLoader()).getDeclaredConstructor().newInstance());
			} catch (Exception e) {
				throw new RuntimeException("Failed to instantiate language adapter: " + laEntry.getKey(), e);
			}
		}
	}
}
 
Example #4
Source File: EntrypointStorage.java    From fabric-loader with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T getOrCreate(Class<T> type) throws Exception {
	if (object == null) {
		net.fabricmc.loader.language.LanguageAdapter adapter = (net.fabricmc.loader.language.LanguageAdapter) Class.forName(languageAdapter, true, FabricLauncherBase.getLauncher().getTargetClassLoader()).getConstructor().newInstance();
		object = adapter.createInstance(value, options);
	}

	if (object == null || !type.isAssignableFrom(object.getClass())) {
		return null;
	} else {
		//noinspection unchecked
		return (T) object;
	}
}
 
Example #5
Source File: TestMod.java    From fabric-loader with Apache License 2.0 5 votes vote down vote up
@Override
public void onInitialize() {
	if (TestMod.class.getClassLoader() != FabricLauncherBase.getLauncher().getTargetClassLoader()) {
		throw new IllegalStateException("invalid class loader: "+TestMod.class.getClassLoader());
	}

	LOGGER.info("**************************");
	LOGGER.info("Hello from Fabric");
	LOGGER.info("**************************");
}
 
Example #6
Source File: TestMod.java    From fabric-loader with Apache License 2.0 5 votes vote down vote up
/**
 * Entrypoint implementation for preLaunch.
 *
 * <p>Warning: This should normally be in a separate class from later entrypoints to avoid accidentally loading
 * and/or initializing game classes. This is just trivial test code not meant for production use.
 */
@Override
public void onPreLaunch() {
	if (TestMod.class.getClassLoader() != FabricLauncherBase.getLauncher().getTargetClassLoader()) {
		throw new IllegalStateException("invalid class loader: "+TestMod.class.getClassLoader());
	}

	LOGGER.info("In preLaunch (cl "+TestMod.class.getClassLoader()+")");
}
 
Example #7
Source File: JavaLanguageAdapter.java    From fabric-loader with Apache License 2.0 5 votes vote down vote up
private static boolean canApplyInterface(String itfString) throws IOException {
	String className = itfString + ".class";

	// TODO: Be a bit more involved
	switch (itfString) {
		case "net/fabricmc/api/ClientModInitializer":
			if (FabricLoader.getInstance().getEnvironmentType() == EnvType.SERVER) {
				return false;
			}
			break;
		case "net/fabricmc/api/DedicatedServerModInitializer":
			if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) {
				return false;
			}
	}

	InputStream stream = FabricLauncherBase.getLauncher().getResourceAsStream(className);
	if (stream == null) {
		return false;
	}
	ClassReader reader = new ClassReader(stream);

	for (String s : reader.getInterfaces()) {
		if (!canApplyInterface(s)) {
			stream.close();
			return false;
		}
	}

	stream.close();
	return true;
}
 
Example #8
Source File: ModClassLoader_125_FML.java    From fabric-loader with Apache License 2.0 5 votes vote down vote up
/**
 * This is used to find the Minecraft .JAR location.
 *
 * @return The "parent source" file.
 */
public File getParentSource() {
	try {
		return UrlUtil.asFile(UrlUtil.asUrl(FabricLauncherBase.minecraftJar));
	} catch (UrlConversionException e) {
		throw new RuntimeException(e);
	}
}
 
Example #9
Source File: ModClassLoader_125_FML.java    From fabric-loader with Apache License 2.0 5 votes vote down vote up
@Override
protected void addURL(URL url) {
	FabricLauncherBase.getLauncher().propose(url);

	URL[] newLocalUrls = new URL[localUrls.length + 1];
	System.arraycopy(localUrls, 0, newLocalUrls, 0, localUrls.length);
	newLocalUrls[localUrls.length] = url;
	localUrls = newLocalUrls;
}
 
Example #10
Source File: AppletLauncher.java    From fabric-loader with Apache License 2.0 5 votes vote down vote up
public AppletLauncher(File instance, String username, String sessionid, String host, String port, boolean doConnect, boolean fullscreen, boolean demo) {
	gameDir = instance;

	params = new HashMap<>();
	params.put("username", username);
	params.put("sessionid", sessionid);
	params.put("stand-alone", "true");
	if (doConnect) {
		params.put("server", host);
		params.put("port", port);
	}
	params.put("fullscreen", Boolean.toString(fullscreen)); //Required param for vanilla. Forge handles the absence gracefully.
	params.put("demo", Boolean.toString(demo));

	try {
		mcApplet = (Applet) FabricLauncherBase.getLauncher().getTargetClassLoader().loadClass(EntrypointTransformer.appletMainClass)
			.getDeclaredConstructor().newInstance();
		//noinspection ConstantConditions
		if (mcApplet == null) {
			throw new RuntimeException("Could not instantiate MinecraftApplet - is null?");
		}

		this.add(mcApplet, "Center");
	} catch (InstantiationException | InvocationTargetException | IllegalAccessException | NoSuchMethodException | ClassNotFoundException e) {
		throw new RuntimeException(e);
	}
}
 
Example #11
Source File: FabricLoader.java    From fabric-loader with Apache License 2.0 5 votes vote down vote up
@Override
public MappingResolver getMappingResolver() {
	if (mappingResolver == null) {
		mappingResolver = new FabricMappingResolver(
			FabricLauncherBase.getLauncher().getMappingConfiguration()::getMappings,
			FabricLauncherBase.getLauncher().getTargetNamespace()
		);
	}

	return mappingResolver;
}
 
Example #12
Source File: FabricLoader.java    From fabric-loader with Apache License 2.0 5 votes vote down vote up
protected void finishModLoading() {
	// add mods to classpath
	// TODO: This can probably be made safer, but that's a long-term goal
	for (ModContainer mod : mods) {
		if (!mod.getInfo().getId().equals("fabricloader")) {
			FabricLauncherBase.getLauncher().propose(mod.getOriginUrl());
		}
	}

	postprocessModMetadata();
	setupLanguageAdapters();
	setupMods();
}
 
Example #13
Source File: OptifineSetup.java    From OptiFabric with Mozilla Public License 2.0 5 votes vote down vote up
File extractMappings() throws IOException {
	File extractedMappings = new File(versionDir, "mappings.tiny");
	if (extractedMappings.exists()) {
		extractedMappings.delete();
	}
	InputStream mappingStream = FabricLauncherBase.class.getClassLoader().getResourceAsStream("mappings/mappings.tiny");
	FileUtils.copyInputStreamToFile(mappingStream, extractedMappings);
	if (!extractedMappings.exists()) {
		throw new RuntimeException("failed to extract mappings!");
	}
	return extractedMappings;
}
 
Example #14
Source File: MinecraftGameProvider.java    From fabric-loader with Apache License 2.0 5 votes vote down vote up
@Override
public Path getLaunchDirectory() {
	if (arguments == null) {
		return new File(".").toPath();
	}

	return FabricLauncherBase.getLaunchDirectory(arguments).toPath();
}
 
Example #15
Source File: MinecraftGameProvider.java    From fabric-loader with Apache License 2.0 5 votes vote down vote up
@Override
public void acceptArguments(String... argStrs) {
	this.arguments = new Arguments();
	arguments.parse(argStrs);

	FabricLauncherBase.processArgumentMap(arguments, envType);
}
 
Example #16
Source File: MixinServiceKnot.java    From fabric-loader with Apache License 2.0 5 votes vote down vote up
public byte[] getClassBytes(String name, boolean runTransformers) throws ClassNotFoundException, IOException {
	byte[] classBytes = FabricLauncherBase.getLauncher().getClassByteArray(name, runTransformers);

	if (classBytes != null) {
		return classBytes;
	} else {
		throw new ClassNotFoundException(name);
	}
}
 
Example #17
Source File: FabricLoader.java    From fabric-loader with Apache License 2.0 4 votes vote down vote up
public void prepareModInit(File newRunDir, Object gameInstance) {
	if (!frozen) {
		throw new RuntimeException("Cannot instantiate mods when not frozen!");
	}

	if (gameInstance != null && FabricLauncherBase.getLauncher() instanceof Knot) {
		ClassLoader gameClassLoader = gameInstance.getClass().getClassLoader();
		ClassLoader targetClassLoader = FabricLauncherBase.getLauncher().getTargetClassLoader();
		boolean matchesKnot = (gameClassLoader == targetClassLoader);
		boolean containsKnot = false;

		if (matchesKnot) {
			containsKnot = true;
		} else {
			gameClassLoader = gameClassLoader.getParent();
			while (gameClassLoader != null && gameClassLoader.getParent() != gameClassLoader) {
				if (gameClassLoader == targetClassLoader) {
					containsKnot = true;
				}
				gameClassLoader = gameClassLoader.getParent();
			}
		}

		if (!matchesKnot) {
			if (containsKnot) {
				getLogger().info("Environment: Target class loader is parent of game class loader.");
			} else {
				getLogger().warn("\n\n* CLASS LOADER MISMATCH! THIS IS VERY BAD AND WILL PROBABLY CAUSE WEIRD ISSUES! *\n"
					+ " - Expected game class loader: " + FabricLauncherBase.getLauncher().getTargetClassLoader() + "\n"
					+ " - Actual game class loader: " + gameClassLoader + "\n"
					+ "Could not find the expected class loader in game class loader parents!\n");
			}
		}
	}

	this.gameInstance = gameInstance;

	if (gameDir != null) {
		try {
			if (!gameDir.getCanonicalFile().equals(newRunDir.getCanonicalFile())) {
				getLogger().warn("Inconsistent game execution directories: engine says " + newRunDir.getAbsolutePath() + ", while initializer says " + gameDir.getAbsolutePath() + "...");
				setGameDir(newRunDir);
			}
		} catch (IOException e) {
			getLogger().warn("Exception while checking game execution directory consistency!", e);
		}
	} else {
		setGameDir(newRunDir);
	}
}
 
Example #18
Source File: FabricTransformer.java    From fabric-loader with Apache License 2.0 4 votes vote down vote up
public static byte[] transform(boolean isDevelopment, EnvType envType, String name, byte[] bytes) {
	boolean isMinecraftClass = name.startsWith("net.minecraft.") || name.indexOf('.') < 0;
	boolean transformAccess = isMinecraftClass && FabricLauncherBase.getLauncher().getMappingConfiguration().requiresPackageAccessHack();
	boolean environmentStrip = !isMinecraftClass || isDevelopment;
	boolean applyAccessWidener = isMinecraftClass && FabricLoader.INSTANCE.getAccessWidener().getTargets().contains(name);

	if (!transformAccess && !environmentStrip && !applyAccessWidener) {
		return bytes;
	}

	ClassReader classReader = new ClassReader(bytes);
	ClassWriter classWriter = new ClassWriter(0);
	ClassVisitor visitor = classWriter;
	int visitorCount = 0;

	if (applyAccessWidener) {
		visitor = new AccessWidenerVisitor(Opcodes.ASM8, visitor, FabricLoader.INSTANCE.getAccessWidener());
		visitorCount++;
	}

	if (transformAccess) {
		visitor = new PackageAccessFixer(Opcodes.ASM8, visitor);
		visitorCount++;
	}

	if (environmentStrip) {
		EnvironmentStrippingData stripData = new EnvironmentStrippingData(Opcodes.ASM8, envType.toString());
		classReader.accept(stripData, ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES);
		if (stripData.stripEntireClass()) {
			throw new RuntimeException("Cannot load class " + name + " in environment type " + envType);
		}
		if (!stripData.isEmpty()) {
			visitor = new ClassStripper(Opcodes.ASM8, visitor, stripData.getStripInterfaces(), stripData.getStripFields(), stripData.getStripMethods());
			visitorCount++;
		}
	}

	if (visitorCount <= 0) {
		return bytes;
	}

	classReader.accept(visitor, 0);
	return classWriter.toByteArray();
}
 
Example #19
Source File: MixinServiceKnot.java    From fabric-loader with Apache License 2.0 4 votes vote down vote up
public byte[] getClassBytes(String name, String transformedName) throws IOException {
	return FabricLauncherBase.getLauncher().getClassByteArray(name, true);
}
 
Example #20
Source File: MixinServiceKnot.java    From fabric-loader with Apache License 2.0 4 votes vote down vote up
@Override
public Class<?> findClass(String name) throws ClassNotFoundException {
	return FabricLauncherBase.getLauncher().getTargetClassLoader().loadClass(name);
}
 
Example #21
Source File: MixinServiceKnot.java    From fabric-loader with Apache License 2.0 4 votes vote down vote up
@Override
public Class<?> findClass(String name, boolean initialize) throws ClassNotFoundException {
	return Class.forName(name, initialize, FabricLauncherBase.getLauncher().getTargetClassLoader());
}
 
Example #22
Source File: ModClassLoader_125_FML.java    From fabric-loader with Apache License 2.0 4 votes vote down vote up
public ModClassLoader_125_FML() {
	super(new URL[0], FabricLauncherBase.getLauncher().getTargetClassLoader());
	localUrls = new URL[0];
}
 
Example #23
Source File: MixinServiceKnot.java    From fabric-loader with Apache License 2.0 4 votes vote down vote up
@Override
public String getName() {
	return FabricLauncherBase.getLauncher() instanceof Knot ? "Knot/Fabric" : "Launchwrapper/Fabric";
}
 
Example #24
Source File: FabricGlobalPropertyService.java    From fabric-loader with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T getProperty(IPropertyKey key) {
	return (T) FabricLauncherBase.getProperties().get(keyString(key));
}
 
Example #25
Source File: MixinServiceKnot.java    From fabric-loader with Apache License 2.0 4 votes vote down vote up
@Override
public InputStream getResourceAsStream(String name) {
	return FabricLauncherBase.getLauncher().getResourceAsStream(name);
}
 
Example #26
Source File: FabricLoader.java    From fabric-loader with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isDevelopmentEnvironment() {
	return FabricLauncherBase.getLauncher().isDevelopment();
}
 
Example #27
Source File: MixinServiceKnot.java    From fabric-loader with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isClassLoaded(String className) {
	return FabricLauncherBase.getLauncher().isClassLoaded(className);
}
 
Example #28
Source File: MixinServiceKnot.java    From fabric-loader with Apache License 2.0 4 votes vote down vote up
@Override
public String getSideName() {
	return FabricLauncherBase.getLauncher().getEnvironmentType().name();
}
 
Example #29
Source File: FabricLoader.java    From fabric-loader with Apache License 2.0 4 votes vote down vote up
@Override
public EnvType getEnvironmentType() {
	return FabricLauncherBase.getLauncher().getEnvironmentType();
}
 
Example #30
Source File: FabricTweaker.java    From fabric-loader with Apache License 2.0 4 votes vote down vote up
@Override
public void injectIntoClassLoader(LaunchClassLoader launchClassLoader) {
	isDevelopment = Boolean.parseBoolean(System.getProperty("fabric.development", "false"));
	Launch.blackboard.put("fabric.development", isDevelopment);
	setProperties(Launch.blackboard);

	this.launchClassLoader = launchClassLoader;
	launchClassLoader.addClassLoaderExclusion("org.objectweb.asm.");
	launchClassLoader.addClassLoaderExclusion("org.spongepowered.asm.");
	launchClassLoader.addClassLoaderExclusion("net.fabricmc.loader.");

	launchClassLoader.addClassLoaderExclusion("net.fabricmc.api.Environment");
	launchClassLoader.addClassLoaderExclusion("net.fabricmc.api.EnvType");

	GameProvider provider = new MinecraftGameProvider();
	provider.acceptArguments(arguments);

	if (!provider.locateGame(getEnvironmentType(), launchClassLoader)) {
		throw new RuntimeException("Could not locate Minecraft: provider locate failed");
	}

	@SuppressWarnings("deprecation")
	FabricLoader loader = FabricLoader.INSTANCE;
	loader.setGameProvider(provider);
	loader.load();
	loader.freeze();

	launchClassLoader.registerTransformer("net.fabricmc.loader.launch.FabricClassTransformer");

	if (!isDevelopment) {
		// Obfuscated environment
		Launch.blackboard.put("fabric.development", false);
		try {
			String target = getLaunchTarget();
			URL loc = launchClassLoader.findResource(target.replace('.', '/') + ".class");
			JarURLConnection locConn = (JarURLConnection) loc.openConnection();
			File jarFile = UrlUtil.asFile(locConn.getJarFileURL());
			if (!jarFile.exists()) {
				throw new RuntimeException("Could not locate Minecraft: " + jarFile.getAbsolutePath() + " not found");
			}

			FabricLauncherBase.deobfuscate(provider.getGameId(), provider.getNormalizedGameVersion(), provider.getLaunchDirectory(), jarFile.toPath(), this);
		} catch (IOException | UrlConversionException e) {
			throw new RuntimeException("Failed to deobfuscate Minecraft!", e);
		}
	}

	FabricLoader.INSTANCE.getAccessWidener().loadFromMods();

	MinecraftGameProvider.TRANSFORMER.locateEntrypoints(this);

	// Setup Mixin environment
	MixinBootstrap.init();
	FabricMixinBootstrap.init(getEnvironmentType(), FabricLoader.INSTANCE);
	MixinEnvironment.getDefaultEnvironment().setSide(getEnvironmentType() == EnvType.CLIENT ? MixinEnvironment.Side.CLIENT : MixinEnvironment.Side.SERVER);

	EntrypointUtils.invoke("preLaunch", PreLaunchEntrypoint.class, PreLaunchEntrypoint::onPreLaunch);
}