Injection DSL
The n3Client bytecode injection DSL — annotations, transformers, mixin pairing, the gamepack and RuneLite mixin catalogs, and pipeline failure behavior.
n3Client's bytecode injection DSL: the annotation set, the transformers that consume them, how mixin classes are paired with targets, and the two mixin catalogs (mixins/ for the gamepack, rlmixins/ for the RuneLite host). Lifecycle context (when injection runs, how the output is packaged and replayed as patches) is in Architecture and Lifecycle. Everything here is read from current source; live behavior is not asserted. Source of truth: docs/development/injection-dsl.md in the n3Client repository.
Pipeline overview
Two entry points run the same transformer machinery over different artifact maps (client/Main.java:93-103):
| Entry | Mixin package | Target map | Target resolution |
|---|---|---|---|
Injector.patch() (injector/Injector.java:29) | dev.n3u.mixins (Injector.java:25) | Injector.gamepack (obfuscated game classes from the pinned gamepack jar) | Via MappingProvider over src/main/resources/dev/n3u/injector/mappings.json (Mixin.value is the mapped name, e.g. "Client"), or interface containment when isInterface = true |
RLInjector.patch() (injector/RLInjector.java:23) | dev.n3u.rlmixins | RLInjector.runelite (upstream RuneLite classes) | Mixin.value is the internal name, e.g. "net/runelite/client/ui/ClientUI" |
Per-run phases:
- Pairing —
PackageUtil.getPairs(mixinPackage)(util/PackageUtil.java) loads every class in the mixin package and pairs each mixinClassNodewith the API interface it implements ("map of all valid pairings of mixin class and interface"). The interface half is whatInjector.applyInterfacesadds to the gamepack class'sinterfaceslist, so injected game classes carry thedev.n3u.api.N*contract at runtime. - Frame planning —
identifyMixinTargetscollects the obfuscated names of all mixin targets; only those classes are loaded with full stack-map-frame expansion, all others withSKIP_FRAMES(Injector.patch, phase 1). - Interface application —
applyInterfacesadds each paired API interface to the target; a missing mapping is a warning-and-continue here, but a hardClassNotFoundExceptionin the mixin pass (Injector.applyMixins). - Member injection — per mixin:
StripLvtInfo.run(strip local-variable tables), field pass (@Injectfields copied into the target;@Shadowfields remapped),BootstrapAttributeCopier.copyBootstrapAttributesAndCallsites(migrate bootstrap-method attributes for invokedynamic), then the method pass below. - Output — gamepack classes are written back into
Libs.gamepack(withFieldHookTransformer.instrument+OSGlobalMixin.patchapplied per class), an annotation-stripped copy goes toLibs.gamepackCleanfor-rsdump(StripAnnotationsTransformerremoves annotations whose signature contains"Named"), and RuneLite classes are written back intoLibs.runelite. Signed classes (SignerMapper.shouldIgnore) are dropped entirely — they are always reloaded from the original jar.
Transformer dispatch order
Within each mixin method, Injector.applyMixins checks annotations in this fixed order (injector/Injector.java applyMixins; RLInjector.patch uses the same order minus the method-level @FieldHook branch):
@Inject— or no annotation at all: unannotated mixin methods are copied into the target. ThehasAnnotation(Inject) || !hasAnyAnnotation(method)condition is evaluated by the dispatchers —Injector.applyMixins(Injector.java:162, callingInjectTransformer.patchat:164) andRLInjector.patch(RLInjector.java:47, call at:49);InjectTransformer.patchitself only skips the no-arg constructor (<init>()V) and dedupes by name+descriptor (InjectTransformer.java:24-31).@MethodHook→MethodHookTransformer— prepends a call to the hook at the start of the named target method.@Replace→ReplaceTransformer— injects the method as a static replacement and redirects original call sites.@MethodOverride→MethodOverrideTransformer— full bytecode replacement of the named target method (also valid on constructors).@Shadow→ShadowTransformer— method proxies and field proxies remapped onto the target member;isRuneLites = trueselects the special pipeline that creates generic bridge methods (createGenericBridgeMethod) so a mixin can return types not on the compile-time classpath.@Construct→ConstructTransformer— turns the annotated method into a factory thatnews the named gamepack class via a signature-compatible constructor.@Disable→DisableTransformer— gates the named target method on a boolean condition method.@FieldHook→ registered intoFieldHookTransformer's static list and instrumented into all field-access sites later (instrument(ClassNode)); methods with@FieldHookin the gamepack pass are also dispatched here.@Insert→InsertTransformer— injects the method call at instruction points matched by@At.@ClassMod→ClassModTransformer— invokes the annotated static method reflectively with the targetClassNodefor arbitrary direct edits.
A method may carry several annotations; each matching transformer runs.
Annotation reference
All annotations are RUNTIME retention, defined in injector/annotations/. Semantics below are from the annotation javadocs and the consuming transformer source.
| Annotation | Targets | Attributes | Effect |
|---|---|---|---|
@Mixin | type | value (target name), isInterface ("identify by extending RL API interface" — target found by scanning gamepack classes for one implementing the named interface) | Marks a mixin class; establishes the target |
@Inject | method, field | — | Copy member into the target class. Also the fallback for unannotated mixin methods |
@Shadow | field, method | value (target member name), isRuneLites (target resolved through the RuneLite-injected pipeline with generic bridge support; Shadow.java:25, consumed via ShadowTransformer) | Bind a mixin member to the target's member; field reads/writes and method calls hit the real target |
@MethodHook | method | value (target method name) | Call the hook at the beginning of the target method |
@Replace | method | value | Replace the original method by injecting a static replacement and redirecting calls |
@MethodOverride | method, constructor | value | Overwrite the target method's bytecode with the mixin method's |
@Construct | method | value (required target class name; Construct.java:18) | Generate a factory method constructing the named target class via a signature-compatible constructor |
@Disable | method | value (condition method name) | Conditionally disable the target method based on a boolean return |
@FieldHook | method, field | value (field name) | Intercept field write access with the hook's conditional logic |
@Insert | method | method (target), desc (target method descriptor filter, default ""), at (@At pattern), all (all matches vs first), ordinal (match index, -1 = last), slice (@Slice limits the search region), raw | Insert a call after matched instructions; with raw = true the method receives (ClassNode, MethodNode, AbstractInsnNode) and edits bytecode directly |
@ClassMod | method | — | Run the method for direct class edits (raw ASM on the ClassNode) |
@Nullify | — | — | Defined in source but consumed by no transformer (repository-wide reference scan) — reserved/unused |
Pattern-matching support annotations (nested in @Insert/used by matchers):
@At— instruction pattern:valueis anAtTargetkind, plustarget,owner,opcode,line,local(local-variable slot forSTOREmatches),constant(@Constant),shift(Shift.HEAD/TAIL). Owners/names resolve throughMappingProviderfirst, then fall back to literal internal names (Atjavadoc). Note:@Sliceis declared on@Insert, not on@At.AtTarget— enum of match kinds:INVOKE,GETFIELD/PUTFIELD/GETSTATIC/PUTSTATIC,NEW,LDC,CHECKCAST,OPCODE,LINE,STORE, … (full list ininjector/annotations/AtTarget.java).@Constant— matches an LDC constant byintValue/longValue/floatValue/doubleValue/stringValue/classValue(class constants match the LDCType's class name;Constant.java:42,InstructionMatcher.java:310-312).@Slice— limits pattern search to a method region.Shift— insert position relative to the match:HEAD(before) /TAIL(after, default).
Support types in injector/types/: InstructionMatcher (pattern matching), CopyMethodVisitor, FieldHookDef (registered field-hook definition). Helper injector/util/expreditor/ is an expression-rewrite framework (ExprEditor.instrument(ClassNode[, MethodNode]) with overridable edit(FieldAccess|MethodCall|ArrayAccess|LiteralValue|NewInstance)); its only production consumers are the impls/ rewriters used by OSGlobalMixin — PathsGetReplacer, ModifyResourceLoading, ReplaceMethodByString, RuntimeMaxMemoryReplacer, SystemPropertyReplacer, IntegerLiteralReplacer.
Global mixins
OSGlobalMixin.patch(injector/OSGlobalMixin.java) runs on every gamepack class (called fromInjector.patch's output loop): expreditor rewrites (PathsGet→ n3 paths,Runtime.maxMemorycapped at 805,306,368 L, system-property redirects, integer-literal replacement-1094877034), music loading rewrites under-noMusic/-min, every"user.home"LDC rewritten to"n3client.cacheHome", theClient.randomDataccess hook, theClient.mouseFlaggetter forced tofalse(ICONST_0),isHiddenredirected for headless mode, and the login welcome string rebranded unless-incognito.RLGlobalMixin.patch(injector/RLGlobalMixin.java) is the RuneLite-side counterpart and is currently empty.
Mixin catalogs
mixins/ — gamepack mixins (26 active, 27 files)
NDeviceIDMixin.java is fully commented out (device-id hooking disabled; the release note - disable hwid spoofing, build.gradle.kts:431, corroborates the intent) and is not counted below. Active mixins take three shapes, verified from their implements clauses:
- Namesake interface-carriers — implement their matching
dev.n3u.api.N*interface frombase-api, whichInjector.applyInterfacesthen adds to the game class:NAccountTypeMixin→NAccountType,NBufferMixin→NBuffer,NClientMixin→NClient,NClientPacketMixin→NClientPacket,NGameEngineMixin→NGameEngine,NIsaacCipherMixin→NIsaacCipher,NItemCompositionMixin→NItemComposition,NLanguageMixin→NLanguage,NMouseHandlerMixin→NMouseHandler,NObjectCompositionMixin→NObjectComposition,NPacketBufferMixin→NPacketBuffer,NPacketBufferNodeMixin→NPacketBufferNode,NPacketWriterMixin→NPacketWriter,NServerPacketMixin→NServerPacket. - Auxiliary
Clientmixins — targetClientand implementNClient(not a namesake):NDoActionMixin,NJagexAccountsMixin,NLoginMixin. - Hook-only mixins — implement no interface:
NLoginHashMixin,NMidiPcmStreamMixin,NMouseHookMixin,NMouseRecorderMixin,NPlatformInfoMixin,NRandomDatMixin,NRunExceptionMixin,NServerPacketLoggerMixin,NTaskMixin.Injector.applyInterfacesskips them (null API half is legal).
Annotation usage per file (verified by scan):
| Mixin | Target | DSL usage |
|---|---|---|
NClientMixin | Client | @Inject ×7, @Shadow ×6, @FieldHook; the single @Construct("ClientPacket") is the newClientPacket factory |
NDoActionMixin, NJagexAccountsMixin, NLoginHashMixin, NLoginMixin, NMouseHookMixin, NRandomDatMixin, NRunExceptionMixin, NServerPacketLoggerMixin | Client | see file |
NGameEngineMixin | GameEngine | login event posting (LoginResponse/LoginMessage via @MethodHook), @Disable("processError"), @FieldHook("graphicsGuard") |
NPacketWriterMixin | PacketWriter | @Inject ×34, @Shadow ×8, @MethodHook ×2; posts PacketSent |
NBufferMixin | Buffer | @Inject ×15, @Shadow ×2 |
NPlatformInfoMixin | PlatformInfo | platform hooks (@Inject, @Insert+@At) |
NObjectCompositionMixin | ObjectComposition | @Inject, @Insert+@At |
NMidiPcmStreamMixin, NMouseRecorderMixin | MidiPcmStream / MouseRecorder | @Insert+@At (NMouseRecorderMixin also uses LoopSleepInjector) |
NMouseHandlerMixin | MouseHandler | @Inject ×4, @Shadow ×3 |
NServerPacketMixin, NClientPacketMixin, NPacketBufferNodeMixin, NItemCompositionMixin, NTaskMixin | as named | @Shadow-based accessors (NTaskMixin adds @FieldHook) |
NAccountTypeMixin, NIsaacCipherMixin, NLanguageMixin, NPacketBufferMixin | as named | no member annotations — interface-carrier mixins (their API interface is added by applyInterfaces) |
rlmixins/ — RuneLite host mixins (18)
| Mixin | Target | Purpose (source-verified unless noted) |
|---|---|---|
RuneLiteMixin | net/runelite/client/RuneLite | @ClassMod isolateStorage: redirects RUNELITE_DIR to ClientPaths.RUNELITE and empties copyJagexCache (fresh-data D09); shape-verified (IllegalStateException on drift). Raw @Insert in main adds the rlInstance static field used by RLClientThread |
PluginManagerMixin | .../plugins/PluginManager | preserveSideloadedPlugins (sideload dir → ClientPaths.PLUGINS, D15); loadSideLoadPlugins swaps PluginClassLoader → dev.n3u.services.hotswapper.PluginClassLoader; loadPlugins widens plugin superclass check to Plugin.class.isAssignableFrom and forces developer mode unless -incognito; loadCorePlugins builds dev.n3u.model.RuneLite + GameManager.init + Install.injectBuiltInPlugins and filters core plugins (min-mode allow-list, disallowed prefixes, shaded-jar devtools filter) |
ClientUIMixin | .../ui/ClientUI | injects ClientUIUpdater.inject() (branding/navigation) into lambda$init$6 |
SplashScreenMixin | .../ui/SplashScreen | calls ClientUIUpdater.patchSplashScreen ("don't remove, call is injected") |
UpdaterMixin | .../Updater | @MethodOverride("tryUpdate") empty — neutralizes RuneLite's self-update (D10) |
EventBusMixin | .../eventbus/EventBus | removes a Preconditions.checkArgument from register (purpose inference — see Architecture and Lifecycle, Events) |
RuneLiteModuleMixin | .../RuneLiteModule | @ClassMod + @Insert; uses GuiceBindingInjector for host DI adjustments |
ReflectUtilMixin | .../util/ReflectUtil | "Keep RuneLite's lookup path, supplying module access for the native plugin loader" (class javadoc) |
ClientSessionManagerMixin, DiscordServiceMixin, ExternalPluginClientMixin | session/discord/external clients | @MethodOverride neutralizers |
ConfigPanelMixin, PluginListItemMixin, PluginListPanelMixin, PluginPanelMixin | UI panels | one @Insert+@At each routing panels through runelite/ShellTheme restylers ("a restyle failure must never break shell construction", ShellTheme javadoc) |
ColorSchemeMixin | .../ui/ColorScheme | @Insert into <clinit> redefines the BRAND_ORANGE static field with the n3 brand color (putStaticField) |
PluginToggleButtonMixin | .../config/PluginToggleButton | @Insert into <clinit> wraps the switcher_on.png load with ImageUtil.recolorImage(..., ColorScheme.BRAND_ORANGE) (getStaticField "net/runelite/client/ui/ColorScheme") |
TopLevelConfigPanelMixin | .../config/TopLevelConfigPanel | @Insert after the last addTab in <init> appends the "n3 Plugins" tab backed by dev/n3u/ui/sdn/NExternalsPanel |
Worked examples
1. Gamepack mixin with events — excerpt from mixins/NGameEngineMixin.java (production source; elisions marked ..., omitting the @Shadow("graphicsGuard")/@FieldHook("graphicsGuard") pair and the @MethodHook("setLoginResponse") hook):
@Mixin("GameEngine")
public class NGameEngineMixin implements NGameEngine
{
@Shadow("logger")
public static Logger logger;
@Disable("processError")
public static boolean processError(String message, Throwable error) { ... return false; }
@MethodHook("getLoginError")
public static void onGetLoginError(int code)
{
Static.post(LoginResponse.fromIndex(code));
}
}Reading: the class implements dev.n3u.api.NGameEngine (added to the game class by applyInterfaces); @Shadow("logger") binds the obfuscated static field; @Disable gates the client error dialog; the @MethodHook posts a LoginResponse onto the bus via Static.post.
2. Raw RuneLite insert — rlmixins/ClientUIMixin.java (verbatim):
@Mixin("net/runelite/client/ui/ClientUI")
public class ClientUIMixin {
@Insert(
method = "lambda$init$6",
at = @At(value = AtTarget.INVOKE, owner = "net/runelite/client/ui/ClientUI", target = "updateFrameConfig"),
ordinal = -1
)
public static void initN() {
ClientUIUpdater.inject();
}
}Both examples are extracted from compiling production source (exercised by the build's injection pipeline); they were not separately compiled or executed in this documentation session.
Running the pipeline
- IDE/dev injection:
.\gradlew.bat runClient— runsdev.n3u.N3Client -safeLaunch -runInjectorwith fresh injection each launch; optional-PclientHome/-PclientUserHomeGradle properties map ton3client.home/user.home(build.gradle.ktsrunClienttask). - Patch generation:
.\gradlew.bat generateClientPatches— headless injection that writesbuild/generated/patches/dev/n3u/patches.zip(plus branding assets), consumed byprocessResources. - Bytecode inspection:
-rsdump <path>writes the injected, annotation-stripped gamepack (JarDumper.dump). - Focus tests (from
AGENTS.md):.\gradlew.bat testruns the suite; root tests relevant here arePatchInputsTestandPluginLookupTest(see Architecture and Lifecycle, Tests).
Invariants and failure behavior
- Annotation dispatch order is fixed (section above); a member may be processed by several transformers.
- Mappings are authoritative: a mixin target missing from
mappings.jsonfailsapplyMixinswithClassNotFoundException; the interface pass treats the same condition as a warning. Do not "fix" by renaming upstream mapping targets (DECISIONS compatibility boundary). @Insertmisses are silent: a missing target method logsTarget method not found: ...and returns (injector/pipeline/InsertTransformer.java:57-58), and a pattern with no matches logsNo matching instructions found for pattern in method: ...(InsertTransformer.java:71) — injection continues, the hook is simply absent from the generated patches, and neither CI (check_distribution.pyhas no hook-presence check) nor runtime can detect it. Only@ClassModshape guards abort (e.g.RuneLiteMixin.isolateStoragethrowing"RuneLite storage initializer shape changed"). Protect critical@Inserts with an explicit replacement-count guard likeisolateStorage's.- Signed classes never receive modified bytecode; they are skipped at injection output and reloaded from the original jar at classload time (
SignerMapper+RLClassLoader). - Frame expansion is selective; a new mixin automatically extends the full-frame target set via
identifyMixinTargets. - After injection,
MappingProviderstate is cleared (Main.javapost-injection) — mappings are injection-time only.
Known limits
@Nullifyhas no transformer;patch/PatternBuilderhas no callers;RLGlobalMixinis empty (see Architecture and Lifecycle, Known limits).- Transformer coverage is exactly the annotation set above; there is no wildcard/target-class filtering beyond
@Mixinpairing. - The DSL assumes the pinned RuneLite 1.13.6 / revision-242 target (recorded in DECISIONS "Compatibility boundaries" and
docs/development/evidence/FOUNDATION_ACCEPTANCE.mdin the repository); upstream drift surfaces as@ClassModshape-guard exceptions, while@Insertmisses stay silent (see Invariants). - Per-
N*Mixinmember-level documentation (what each@Shadow/@Injectbinds and which client feature consumes it) is not written; the table above is file-level only. The repository tracks extending themixins/catalog with member rows for the packet writer and client mixins first (highest annotation density), each verified againstbase-apiN-interfaces andmappings.json.
Architecture and Lifecycle
The root launcher module — module map, startup sequence, classloading, the bytecode pipeline, events, threading, readiness, shutdown, and Gradle ownership.
Development Testing
How the n3Client automated suite is organized — per-module test roots, conventions, the fresh-root policy, the manager security scan wall, and how to run the tests.