Skip to content

Commit

Permalink
fix constant propagation
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzoferre committed Sep 13, 2024
1 parent b488056 commit 61861a5
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
8 changes: 7 additions & 1 deletion src/techniques/statics/constant-propagation.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,13 @@ export default function (babel) {
enter(path) {
const { node, scope } = path;
const { id, init } = node;
if (!t.isLiteral(init) && !t.isUnaryExpression(init)) return;
if (
!t.isLiteral(init) &&
!t.isUnaryExpression(init) &&
(!t.isArrayExpression(init) ||
init.elements.some(element => !t.isLiteral(element)))
)
return;
const binding = scope.getBinding(id.name);
if (!binding) return;
if (!binding.constant) return;
Expand Down
31 changes: 25 additions & 6 deletions test/test-static-techniques.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,12 @@ test("transform sequence expression", () => {
var a = 1;
var b = 1;
a = 2, b = 2;
console.log(a);
console.log(b);
`
)
),
`var a = 1; var b = 1; a = 2; b = 2;`
`console.log(2); console.log(2);`
);
});

Expand Down Expand Up @@ -110,9 +112,18 @@ describe("reachability of function", () => {
});

test("reachable function", () => {
assert.strictEqual(
removeNewLinesAndTabs(
deobfuscate(`function a() {Math.random();} console.log(a());`)
),
`function a() { Math.random(); } console.log(a());`
);
});

test("reachable function with an empty body", () => {
assert.strictEqual(
removeNewLinesAndTabs(deobfuscate(`function a() {} console.log(a());`)),
`function a() {} console.log(a());`
`console.log();`
);
});
});
Expand Down Expand Up @@ -151,13 +162,21 @@ describe("defeating object mapping", () => {
});

describe("constant folding", () => {
test("constant propagation", () => {
test("constant propagation of a literal value", () => {
assert.strictEqual(deobfuscate(`var a = 5; console.log(a);`), `console.log(5);`);
});
test("non constant value", () => {
test("constant propagation of an array expression that has literal values", () => {
assert.strictEqual(
removeNewLinesAndTabs(deobfuscate(`var a = 5; a += 1; console.log(a);`)),
`var a = 5; a += 1; console.log(a);`
deobfuscate(`var a = [1,2,3]; console.log(a);`),
`console.log([1, 2, 3]);`
);
});
test("constant propagation of an array expression that does not contain literal values", () => {
assert.strictEqual(
removeNewLinesAndTabs(
deobfuscate(`var a = [1, 2, Math.random()]; console.log(a);`)
),
`var a = [1, 2, Math.random()]; console.log(a);`
);
});
});
Expand Down

0 comments on commit 61861a5

Please sign in to comment.