docs.dev

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):

EntryMixin packageTarget mapTarget 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.rlmixinsRLInjector.runelite (upstream RuneLite classes)Mixin.value is the internal name, e.g. "net/runelite/client/ui/ClientUI"

Per-run phases:

  1. Pairing — PackageUtil.getPairs(mixinPackage) (util/PackageUtil.java) loads every class in the mixin package and pairs each mixin ClassNode with the API interface it implements ("map of all valid pairings of mixin class and interface"). The interface half is what Injector.applyInterfaces adds to the gamepack class's interfaces list, so injected game classes carry the dev.n3u.api.N* contract at runtime.
  2. Frame planning — identifyMixinTargets collects the obfuscated names of all mixin targets; only those classes are loaded with full stack-map-frame expansion, all others with SKIP_FRAMES (Injector.patch, phase 1).
  3. Interface application — applyInterfaces adds each paired API interface to the target; a missing mapping is a warning-and-continue here, but a hard ClassNotFoundException in the mixin pass (Injector.applyMixins).
  4. Member injection — per mixin: StripLvtInfo.run (strip local-variable tables), field pass (@Inject fields copied into the target; @Shadow fields remapped), BootstrapAttributeCopier.copyBootstrapAttributesAndCallsites (migrate bootstrap-method attributes for invokedynamic), then the method pass below.
  5. Output — gamepack classes are written back into Libs.gamepack (with FieldHookTransformer.instrument + OSGlobalMixin.patch applied per class), an annotation-stripped copy goes to Libs.gamepackClean for -rsdump (StripAnnotationsTransformer removes annotations whose signature contains "Named"), and RuneLite classes are written back into Libs.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):

  1. @Inject — or no annotation at all: unannotated mixin methods are copied into the target. The hasAnnotation(Inject) || !hasAnyAnnotation(method) condition is evaluated by the dispatchers — Injector.applyMixins (Injector.java:162, calling InjectTransformer.patch at :164) and RLInjector.patch (RLInjector.java:47, call at :49); InjectTransformer.patch itself only skips the no-arg constructor (<init>()V) and dedupes by name+descriptor (InjectTransformer.java:24-31).
  2. @MethodHook → MethodHookTransformer — prepends a call to the hook at the start of the named target method.
  3. @Replace → ReplaceTransformer — injects the method as a static replacement and redirects original call sites.
  4. @MethodOverride → MethodOverrideTransformer — full bytecode replacement of the named target method (also valid on constructors).
  5. @Shadow → ShadowTransformer — method proxies and field proxies remapped onto the target member; isRuneLites = true selects the special pipeline that creates generic bridge methods (createGenericBridgeMethod) so a mixin can return types not on the compile-time classpath.
  6. @Construct → ConstructTransformer — turns the annotated method into a factory that news the named gamepack class via a signature-compatible constructor.
  7. @Disable → DisableTransformer — gates the named target method on a boolean condition method.
  8. @FieldHook → registered into FieldHookTransformer's static list and instrumented into all field-access sites later (instrument(ClassNode)); methods with @FieldHook in the gamepack pass are also dispatched here.
  9. @Insert → InsertTransformer — injects the method call at instruction points matched by @At.
  10. @ClassMod → ClassModTransformer — invokes the annotated static method reflectively with the target ClassNode for 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.

AnnotationTargetsAttributesEffect
@Mixintypevalue (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
@Injectmethod, field—Copy member into the target class. Also the fallback for unannotated mixin methods
@Shadowfield, methodvalue (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
@MethodHookmethodvalue (target method name)Call the hook at the beginning of the target method
@ReplacemethodvalueReplace the original method by injecting a static replacement and redirecting calls
@MethodOverridemethod, constructorvalueOverwrite the target method's bytecode with the mixin method's
@Constructmethodvalue (required target class name; Construct.java:18)Generate a factory method constructing the named target class via a signature-compatible constructor
@Disablemethodvalue (condition method name)Conditionally disable the target method based on a boolean return
@FieldHookmethod, fieldvalue (field name)Intercept field write access with the hook's conditional logic
@Insertmethodmethod (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), rawInsert a call after matched instructions; with raw = true the method receives (ClassNode, MethodNode, AbstractInsnNode) and edits bytecode directly
@ClassModmethod—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: value is an AtTarget kind, plus target, owner, opcode, line, local (local-variable slot for STORE matches), constant (@Constant), shift (Shift.HEAD/TAIL). Owners/names resolve through MappingProvider first, then fall back to literal internal names (At javadoc). Note: @Slice is declared on @Insert, not on @At.
  • AtTarget — enum of match kinds: INVOKE, GETFIELD/PUTFIELD/GETSTATIC/PUTSTATIC, NEW, LDC, CHECKCAST, OPCODE, LINE, STORE, … (full list in injector/annotations/AtTarget.java).
  • @Constant — matches an LDC constant by intValue/longValue/floatValue/doubleValue/stringValue/classValue (class constants match the LDC Type'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 from Injector.patch's output loop): expreditor rewrites (PathsGet → n3 paths, Runtime.maxMemory capped 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", the Client.randomDat access hook, the Client.mouseFlag getter forced to false (ICONST_0), isHidden redirected 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:

  1. Namesake interface-carriers — implement their matching dev.n3u.api.N* interface from base-api, which Injector.applyInterfaces then 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.
  2. Auxiliary Client mixins — target Client and implement NClient (not a namesake): NDoActionMixin, NJagexAccountsMixin, NLoginMixin.
  3. Hook-only mixins — implement no interface: NLoginHashMixin, NMidiPcmStreamMixin, NMouseHookMixin, NMouseRecorderMixin, NPlatformInfoMixin, NRandomDatMixin, NRunExceptionMixin, NServerPacketLoggerMixin, NTaskMixin. Injector.applyInterfaces skips them (null API half is legal).

Annotation usage per file (verified by scan):

MixinTargetDSL usage
NClientMixinClient@Inject ×7, @Shadow ×6, @FieldHook; the single @Construct("ClientPacket") is the newClientPacket factory
NDoActionMixin, NJagexAccountsMixin, NLoginHashMixin, NLoginMixin, NMouseHookMixin, NRandomDatMixin, NRunExceptionMixin, NServerPacketLoggerMixinClientsee file
NGameEngineMixinGameEnginelogin event posting (LoginResponse/LoginMessage via @MethodHook), @Disable("processError"), @FieldHook("graphicsGuard")
NPacketWriterMixinPacketWriter@Inject ×34, @Shadow ×8, @MethodHook ×2; posts PacketSent
NBufferMixinBuffer@Inject ×15, @Shadow ×2
NPlatformInfoMixinPlatformInfoplatform hooks (@Inject, @Insert+@At)
NObjectCompositionMixinObjectComposition@Inject, @Insert+@At
NMidiPcmStreamMixin, NMouseRecorderMixinMidiPcmStream / MouseRecorder@Insert+@At (NMouseRecorderMixin also uses LoopSleepInjector)
NMouseHandlerMixinMouseHandler@Inject ×4, @Shadow ×3
NServerPacketMixin, NClientPacketMixin, NPacketBufferNodeMixin, NItemCompositionMixin, NTaskMixinas named@Shadow-based accessors (NTaskMixin adds @FieldHook)
NAccountTypeMixin, NIsaacCipherMixin, NLanguageMixin, NPacketBufferMixinas namedno member annotations — interface-carrier mixins (their API interface is added by applyInterfaces)

rlmixins/ — RuneLite host mixins (18)

MixinTargetPurpose (source-verified unless noted)
RuneLiteMixinnet/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/PluginManagerpreserveSideloadedPlugins (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/ClientUIinjects ClientUIUpdater.inject() (branding/navigation) into lambda$init$6
SplashScreenMixin.../ui/SplashScreencalls ClientUIUpdater.patchSplashScreen ("don't remove, call is injected")
UpdaterMixin.../Updater@MethodOverride("tryUpdate") empty — neutralizes RuneLite's self-update (D10)
EventBusMixin.../eventbus/EventBusremoves 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, ExternalPluginClientMixinsession/discord/external clients@MethodOverride neutralizers
ConfigPanelMixin, PluginListItemMixin, PluginListPanelMixin, PluginPanelMixinUI panelsone @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 — runs dev.n3u.N3Client -safeLaunch -runInjector with fresh injection each launch; optional -PclientHome / -PclientUserHome Gradle properties map to n3client.home / user.home (build.gradle.kts runClient task).
  • Patch generation: .\gradlew.bat generateClientPatches — headless injection that writes build/generated/patches/dev/n3u/patches.zip (plus branding assets), consumed by processResources.
  • Bytecode inspection: -rsdump <path> writes the injected, annotation-stripped gamepack (JarDumper.dump).
  • Focus tests (from AGENTS.md): .\gradlew.bat test runs the suite; root tests relevant here are PatchInputsTest and PluginLookupTest (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.json fails applyMixins with ClassNotFoundException; the interface pass treats the same condition as a warning. Do not "fix" by renaming upstream mapping targets (DECISIONS compatibility boundary).
  • @Insert misses are silent: a missing target method logs Target method not found: ... and returns (injector/pipeline/InsertTransformer.java:57-58), and a pattern with no matches logs No 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.py has no hook-presence check) nor runtime can detect it. Only @ClassMod shape guards abort (e.g. RuneLiteMixin.isolateStorage throwing "RuneLite storage initializer shape changed"). Protect critical @Inserts with an explicit replacement-count guard like isolateStorage'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, MappingProvider state is cleared (Main.java post-injection) — mappings are injection-time only.

Known limits

  • @Nullify has no transformer; patch/PatternBuilder has no callers; RLGlobalMixin is empty (see Architecture and Lifecycle, Known limits).
  • Transformer coverage is exactly the annotation set above; there is no wildcard/target-class filtering beyond @Mixin pairing.
  • The DSL assumes the pinned RuneLite 1.13.6 / revision-242 target (recorded in DECISIONS "Compatibility boundaries" and docs/development/evidence/FOUNDATION_ACCEPTANCE.md in the repository); upstream drift surfaces as @ClassMod shape-guard exceptions, while @Insert misses stay silent (see Invariants).
  • Per-N*Mixin member-level documentation (what each @Shadow/@Inject binds and which client feature consumes it) is not written; the table above is file-level only. The repository tracks extending the mixins/ catalog with member rows for the packet writer and client mixins first (highest annotation density), each verified against base-api N-interfaces and mappings.json.

On this page