icsharpcode/ILSpy · error · BadImageFormatException

Invalid metadata token for ldtoken instruction.

Error message

Invalid metadata token for ldtoken instruction.

What it means

BadImageFormatException thrown by LdToken when the ldtoken instruction's operand handle kind is neither a type kind nor a member kind. ldtoken accepts only type/m member tokens (TypeDefinition, MethodDefinition, FieldDefinition, and the reference/spec variants the resolver folds in); any other handle kind is invalid.

Source

Thrown at ICSharpCode.Decompiler/IL/ILReader.cs:2188

			}
			foreach (var p in method.Parameters)
			{
				call.Arguments.Add(Ldarg(call.Arguments.Count));
			}
			return new Leave(mainContainer, call);
		}

		ILInstruction LdToken(EntityHandle token)
		{
			if (token.Kind.IsTypeKind())
				return new LdTypeToken(module.ResolveType(token, genericContext));
			if (token.Kind.IsMemberKind())
			{
				var entity = module.ResolveEntity(token, genericContext);
				if (entity is IMember member)
					return new LdMemberToken(member);
			}
			throw new BadImageFormatException("Invalid metadata token for ldtoken instruction.");
		}
	}
}

View on GitHub (pinned to 60c08fcb74)

Solutions

  1. Catch BadImageFormatException around decompilation and report the method as unreadable.
  2. Validate that the ldtoken operand's token table is TypeDef/MethodDef/FieldDef (or the permitted reference kinds) before decompiling when preprocessing.
  3. Re-acquire an untampered copy of the assembly.

Example fix

// before
var code = decompiler.DecompileTypeAsString(typeName);

// after
try
{
    var code = decompiler.DecompileTypeAsString(typeName);
}
catch (BadImageFormatException ex) when (ex.Message.Contains("ldtoken"))
{
    logger.Warn($"Invalid ldtoken operand in {typeName}: {ex.Message}");
}
Defensive patterns

Strategy: try-catch

Validate before calling

void VerifyLdtokenTokens(string path)
{
    using var pe = new PEReader(File.OpenRead(path));
    var md = pe.GetMetadataReader();
    // ldtoken operands must be TypeDef(0x02)/MethodDef(0x06)/FieldDef(0x04) (+ ref/spec); flag others
}

Try / catch

try { var code = decompiler.DecompileTypeAsString(typeName); }
catch (BadImageFormatException ex) when (ex.Message.Contains("ldtoken")) { logger.Warn($"Invalid ldtoken operand: {ex.Message}"); }

Prevention

When it happens

Trigger: An ldtoken operand whose token resolves to a handle that is neither type nor member (e.g. a StandaloneSignature, GenericParameter, or AssemblyReference token); corrupt or hand-edited IL.

Common situations: Obfuscated binaries that rewrite ldtoken operands; truncated/damaged metadata; IL produced by a faulty generator emitting the wrong table for the ldtoken operand.

Related errors


AI-assisted analysis of icsharpcode/ILSpy@60c08fcb74 (2026-08-13). Data as JSON: /api/errors/29237d988b56f45c. Report an issue: GitHub.