Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/content/docs/avm1/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ DU[1] = {n: "Donjon Bouftou", m: new Object()};
## Scope

The evaluator is a **data-script interpreter**: it runs the pure, branch-free operators over
version-accurate value coercion — no control flow, no function calls, no host/display objects. Opcodes
version-accurate value coercion — no control flow, no user function calls (only the `String`, `Number` and
`Boolean` conversions), no host/display objects. Opcodes
outside that subset are recorded in `UnsupportedOpcodes` (or throw when `strict`). AVM2 (`DoABC`) is out
of scope and kept raw.
18 changes: 16 additions & 2 deletions docs/content/docs/avm1/machine.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ description: "How Avm1Machine linearly evaluates a DoAction byte stream into a g

`Avm1Machine` (in `src/ShockwaveFlash.Avm1/Avm1Machine.cs`) is a deliberately small, **linear** AVM1 interpreter. It is built to read *data scripts* — the kind of `DoAction` tag a tool authoring SWFs emits to seed a movie's global variables — not to run arbitrary control flow. It walks a decoded `IReadOnlyList<Action>` from top to bottom, maintains an operand stack, a register file, a constant pool, and a single global object table, and stops at the first `ActionEnd`. The product of a run is the `Avm1Object` held in `Globals`.

The machine does **not** implement jumps, branches, function calls, `with` scopes, timeline control, or object instantiation in any meaningful way. Those opcodes either decode to no-ops with placeholder stack results, or fall through to the unsupported path (see [Unsupported opcodes](#unsupported-opcodes)). This is intentional: the use case is extracting and rewriting the flat name/value pairs a script pushes into globals (for example, the Dofus `lang` files), not faithfully emulating a player.
The machine does **not** implement jumps, branches, user function calls, `with` scopes, timeline control, or object instantiation in any meaningful way. The only calls it evaluates are the built-in conversion functions `String`, `Number` and `Boolean` (see [Conversion calls](#conversion-calls)). The other opcodes either decode to no-ops with placeholder stack results, or fall through to the unsupported path (see [Unsupported opcodes](#unsupported-opcodes)). This is intentional: the use case is extracting and rewriting the flat name/value pairs a script pushes into globals (for example, the Dofus `lang` files), not faithfully emulating a player.

## Running a script

Expand Down Expand Up @@ -128,7 +128,20 @@ Stack-manipulation opcodes:
- `ActionPop` — discard top.
- `ActionPushDuplicate` — pop, push twice.
- `ActionStackSwap` — swap the top two entries.
- `DropArguments` (a helper, not an opcode) pops a count then pops that many values; it backs the placeholder implementations of `ActionNewObject`, `ActionCallMethod`, and `ActionCallFunction`, all of which discard their arguments and push `Undefined` (or a fresh empty `Avm1Object` for `NewObject`).
- `DropArguments` (a helper, not an opcode) pops a count then pops that many values; it backs the placeholder implementations of `ActionNewObject` and `ActionCallMethod`, which discard their arguments and push `Undefined` (or a fresh empty `Avm1Object` for `NewObject`).
- `ActionCallFunction` pops the function name, the argument count and the arguments, then pushes the result of a [conversion call](#conversion-calls), or `Undefined` for any other function.

### Conversion calls

Data scripts often wrap a literal in a call to a built-in conversion function, as in `C.SPEAKING_ITEMS_MSG_COUNT = Number(30);`. When `ActionCallFunction` names one of these three functions, the machine evaluates the call with its own coercion rules:

| Call | Result | No argument |
| --- | --- | --- |
| `String(x)` | `ToStr(x)` | `""` |
| `Number(x)` | `ToNum(x)` | `0` |
| `Boolean(x)` | `ToBool(x)` | `undefined` |

Only the first argument is used; any extra arguments are popped and ignored. Because the result goes through the same version-gated coercion as the operators, `Number("30")` is `30`, `Boolean(0)` is `false`, and `Boolean("0")` is `false` before version 7 and `true` from version 7. Function names match case-insensitively before version 7 (so `number(30)` works in a SWF6 script), and exactly from version 7. Every other function name still evaluates to `Undefined`.

## Operators

Expand Down Expand Up @@ -250,6 +263,7 @@ Summary of the rules that change with `swfVersion`:
- **undefined → string** is empty before version 7, `"undefined"` from version 7.
- **String → number** uses radix sniffing (hex/octal) only on version `>= 6`, and is strict (no trailing garbage) only on version `>= 5`.
- **String → boolean** is "non-empty" on version `>= 7`, numeric-truthiness before that.
- **Conversion call names** (`String`, `Number`, `Boolean`) match case-insensitively before version 7, exactly from version 7.

## Unsupported opcodes

Expand Down
3 changes: 2 additions & 1 deletion docs/content/docs/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ images or SVG — entirely in code, on **.NET 10**. Fast, allocation-light, and

<Callout type="warn" title="Scope">
- No AVM2 (`DoABC`) execution — ABC bytecode is preserved verbatim, never run.
- The AVM1 evaluator is **linear only** (data scripts): no control flow, function calls, or display
- The AVM1 evaluator is **linear only** (data scripts): no control flow, user function calls (only the
`String`, `Number` and `Boolean` conversions), or display
objects.
- The AS2 listing is best-effort, not a full decompiler.
</Callout>
26 changes: 23 additions & 3 deletions src/ShockwaveFlash.Avm1/Avm1Machine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,13 @@ public void Execute(IReadOnlyList<Action> actions, bool strict = false)

case ActionCallFunction:
{
_ = ToStr(Pop());
DropArguments();
_stack.Push(Avm1Value.Undefined);
var name = ToStr(Pop());
var count = (int)ToNum(Pop());
var argument = count > 0 ? Pop() : null;
for (var i = 1; i < count; i++)
Pop();

_stack.Push(CallFunction(name, argument));
break;
}

Expand Down Expand Up @@ -459,6 +463,22 @@ private void DropArguments()
Pop();
}

private Avm1Value CallFunction(string name, Avm1Value? argument)
{
var comparison = _version < 7 ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;

if (string.Equals(name, "String", comparison))
return argument is null ? string.Empty : ToStr(argument);

if (string.Equals(name, "Number", comparison))
return argument is null ? 0.0 : ToNum(argument);

if (string.Equals(name, "Boolean", comparison))
return argument is null ? Avm1Value.Undefined : ToBool(argument);

return Avm1Value.Undefined;
}

internal double ToNum(Avm1Value value)
{
return value switch
Expand Down
135 changes: 135 additions & 0 deletions src/ShockwaveFlash.Tests/Avm1ConversionCallTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
using ShockwaveFlash.Avm1;
using ShockwaveFlash.Avm1.Special;
using ShockwaveFlash.Avm1.Swf4;
using ShockwaveFlash.Avm1.Swf5;
using ShockwaveFlash.Avm1.Types;
using Shouldly;
using Avm1Action = ShockwaveFlash.Avm1.Action;

namespace ShockwaveFlash.Tests;

public sealed class Avm1ConversionCallTests
{
private static Avm1Object Run(byte version, IEnumerable<Avm1Action> statements)
{
var actions = new List<Avm1Action>(statements) { new ActionEnd() };
return Avm1Machine.Run(Avm1Action.EncodeCollection(actions, version), version, strict: true);
}

private static IEnumerable<Avm1Action> Call(string function, params PushValue[] arguments)
{
foreach (var argument in Enumerable.Reverse(arguments))
yield return new ActionPush([argument]);

yield return new ActionPush([PushValue.Integer(arguments.Length), PushValue.String(function)]);
yield return new ActionCallFunction();
}

private static Avm1Value Evaluate(byte version, string function, params PushValue[] arguments)
{
var statement = new List<Avm1Action> { new ActionPush([PushValue.String("x")]) };
statement.AddRange(Call(function, arguments));
statement.Add(new ActionSetVariable());

return Run(version, statement)["x"];
}

private static IEnumerable<Avm1Action> SetConstant(string name, string function, PushValue argument)
{
yield return new ActionPush([PushValue.String("C")]);
yield return new ActionGetVariable();
yield return new ActionPush([PushValue.String(name)]);
foreach (var action in Call(function, argument))
yield return action;
yield return new ActionSetMember();
}

[Fact]
public void Lang_constants_assigned_through_conversion_calls_are_evaluated()
{
var statements = new List<Avm1Action>
{
new ActionPush([PushValue.String("C"), PushValue.Integer(0)]),
new ActionInitObject(),
new ActionSetVariable(),
};
statements.AddRange(SetConstant("CHECK_MAP_FILE_ID", "Boolean", PushValue.Boolean(true)));
statements.AddRange(SetConstant("SPEAKING_ITEMS_MSG_COUNT", "Number", PushValue.Integer(30)));
statements.AddRange(SetConstant("RSS_LINK", "String", PushValue.String("http://example.com/rss")));

var constants = Run(6, statements)["C"].AsObject;

constants["CHECK_MAP_FILE_ID"].ShouldBe(new Avm1Boolean(true));
constants["SPEAKING_ITEMS_MSG_COUNT"].ShouldBe(new Avm1Number(30));
constants["RSS_LINK"].ShouldBe(new Avm1String("http://example.com/rss"));
}

[Fact]
public void String_converts_its_argument()
{
Evaluate(6, "String", PushValue.String("text")).ShouldBe(new Avm1String("text"));
Evaluate(6, "String", PushValue.Double(12.5)).ShouldBe(new Avm1String("12.5"));
Evaluate(6, "String", PushValue.Boolean(true)).ShouldBe(new Avm1String("true"));
Evaluate(6, "String", PushValue.Null()).ShouldBe(new Avm1String("null"));
}

[Fact]
public void String_of_undefined_is_version_gated()
{
Evaluate(6, "String", PushValue.Undefined()).ShouldBe(new Avm1String(string.Empty));
Evaluate(7, "String", PushValue.Undefined()).ShouldBe(new Avm1String("undefined"));
}

[Fact]
public void Number_converts_its_argument()
{
Evaluate(6, "Number", PushValue.Integer(30)).ShouldBe(new Avm1Number(30));
Evaluate(6, "Number", PushValue.String("30")).ShouldBe(new Avm1Number(30));
Evaluate(6, "Number", PushValue.String("0x1F")).ShouldBe(new Avm1Number(31));
Evaluate(6, "Number", PushValue.Boolean(true)).ShouldBe(new Avm1Number(1));
Evaluate(6, "Number", PushValue.String("abc")).AsNumber.ShouldBe(double.NaN);
}

[Fact]
public void Boolean_converts_its_argument()
{
Evaluate(6, "Boolean", PushValue.Boolean(true)).ShouldBe(new Avm1Boolean(true));
Evaluate(6, "Boolean", PushValue.Integer(0)).ShouldBe(new Avm1Boolean(false));
Evaluate(6, "Boolean", PushValue.Integer(5)).ShouldBe(new Avm1Boolean(true));
Evaluate(6, "Boolean", PushValue.Null()).ShouldBe(new Avm1Boolean(false));
}

[Fact]
public void Boolean_of_a_string_is_version_gated()
{
Evaluate(6, "Boolean", PushValue.String("0")).ShouldBe(new Avm1Boolean(false));
Evaluate(7, "Boolean", PushValue.String("0")).ShouldBe(new Avm1Boolean(true));
}

[Fact]
public void Calls_without_arguments_return_the_player_defaults()
{
Evaluate(6, "String").ShouldBe(new Avm1String(string.Empty));
Evaluate(6, "Number").ShouldBe(new Avm1Number(0));
Evaluate(6, "Boolean").ShouldBe(Avm1Value.Undefined);
}

[Fact]
public void Extra_arguments_are_ignored()
{
Evaluate(6, "Number", PushValue.Integer(1), PushValue.Integer(2), PushValue.Integer(3)).ShouldBe(new Avm1Number(1));
}

[Fact]
public void Function_names_are_case_insensitive_before_version_7()
{
Evaluate(6, "number", PushValue.String("5")).ShouldBe(new Avm1Number(5));
Evaluate(7, "number", PushValue.String("5")).ShouldBe(Avm1Value.Undefined);
}

[Fact]
public void Other_functions_still_evaluate_to_undefined()
{
Evaluate(6, "parseInt", PushValue.String("5")).ShouldBe(Avm1Value.Undefined);
}
}
Loading