DeadCodeInjectionTransformer.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. import { inject, injectable, } from 'inversify';
  2. import { ServiceIdentifiers } from '../../container/ServiceIdentifiers';
  3. import * as estraverse from '@javascript-obfuscator/estraverse';
  4. import * as ESTree from 'estree';
  5. import { TDeadNodeInjectionCustomNodeFactory } from '../../types/container/custom-nodes/TDeadNodeInjectionCustomNodeFactory';
  6. import { TInitialData } from '../../types/TInitialData';
  7. import { TNodeWithStatements } from '../../types/node/TNodeWithStatements';
  8. import { ICustomNode } from '../../interfaces/custom-nodes/ICustomNode';
  9. import { IOptions } from '../../interfaces/options/IOptions';
  10. import { IRandomGenerator } from '../../interfaces/utils/IRandomGenerator';
  11. import { INodeTransformersRunner } from '../../interfaces/node-transformers/INodeTransformersRunner';
  12. import { IVisitor } from '../../interfaces/node-transformers/IVisitor';
  13. import { DeadCodeInjectionCustomNode } from '../../enums/custom-nodes/DeadCodeInjectionCustomNode';
  14. import { NodeTransformer } from '../../enums/node-transformers/NodeTransformer';
  15. import { NodeType } from '../../enums/node/NodeType';
  16. import { NodeTransformationStage } from '../../enums/node-transformers/NodeTransformationStage';
  17. import { AbstractNodeTransformer } from '../AbstractNodeTransformer';
  18. import { BlockStatementDeadCodeInjectionNode } from '../../custom-nodes/dead-code-injection-nodes/BlockStatementDeadCodeInjectionNode';
  19. import { NodeFactory } from '../../node/NodeFactory';
  20. import { NodeGuards } from '../../node/NodeGuards';
  21. import { NodeStatementUtils } from '../../node/NodeStatementUtils';
  22. import { NodeUtils } from '../../node/NodeUtils';
  23. @injectable()
  24. export class DeadCodeInjectionTransformer extends AbstractNodeTransformer {
  25. /**
  26. * @type {string}
  27. */
  28. private static readonly deadCodeInjectionRootAstHostNodeName: string = 'deadCodeInjectionRootAstHostNode';
  29. /**
  30. * @type {number}
  31. */
  32. private static readonly maxNestedBlockStatementsCount: number = 4;
  33. /**
  34. * @type {number}
  35. */
  36. private static readonly minCollectedBlockStatementsCount: number = 5;
  37. /**
  38. * @type {NodeTransformer[]}
  39. */
  40. private static readonly transformersToRenameBlockScopeIdentifiers: NodeTransformer[] = [
  41. NodeTransformer.LabeledStatementTransformer,
  42. NodeTransformer.ScopeIdentifiersTransformer,
  43. NodeTransformer.ScopeThroughIdentifiersTransformer
  44. ];
  45. /**
  46. * @type {Set <BlockStatement>}
  47. */
  48. private readonly deadCodeInjectionRootAstHostNodeSet: Set <ESTree.BlockStatement> = new Set();
  49. /**
  50. * @type {ESTree.BlockStatement[]}
  51. */
  52. private readonly collectedBlockStatements: ESTree.BlockStatement[] = [];
  53. /**
  54. * @type {number}
  55. */
  56. private collectedBlockStatementsTotalLength: number = 0;
  57. /**
  58. * @type {TDeadNodeInjectionCustomNodeFactory}
  59. */
  60. private readonly deadCodeInjectionCustomNodeFactory: TDeadNodeInjectionCustomNodeFactory;
  61. /**
  62. * @type {INodeTransformersRunner}
  63. */
  64. private readonly transformersRunner: INodeTransformersRunner;
  65. /**
  66. * @param {TDeadNodeInjectionCustomNodeFactory} deadCodeInjectionCustomNodeFactory
  67. * @param {INodeTransformersRunner} transformersRunner
  68. * @param {IRandomGenerator} randomGenerator
  69. * @param {IOptions} options
  70. */
  71. public constructor (
  72. @inject(ServiceIdentifiers.Factory__IDeadCodeInjectionCustomNode)
  73. deadCodeInjectionCustomNodeFactory: TDeadNodeInjectionCustomNodeFactory,
  74. @inject(ServiceIdentifiers.INodeTransformersRunner) transformersRunner: INodeTransformersRunner,
  75. @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator,
  76. @inject(ServiceIdentifiers.IOptions) options: IOptions
  77. ) {
  78. super(randomGenerator, options);
  79. this.deadCodeInjectionCustomNodeFactory = deadCodeInjectionCustomNodeFactory;
  80. this.transformersRunner = transformersRunner;
  81. }
  82. /**
  83. * @param {Node} targetNode
  84. * @returns {boolean}
  85. */
  86. private static isProhibitedNodeInsideCollectedBlockStatement (targetNode: ESTree.Node): boolean {
  87. return NodeGuards.isFunctionDeclarationNode(targetNode) // can break code on strict mode
  88. || NodeGuards.isBreakStatementNode(targetNode)
  89. || NodeGuards.isContinueStatementNode(targetNode)
  90. || NodeGuards.isAwaitExpressionNode(targetNode)
  91. || NodeGuards.isYieldExpressionNode(targetNode)
  92. || NodeGuards.isSuperNode(targetNode)
  93. || (NodeGuards.isForOfStatementNode(targetNode) && targetNode.await);
  94. }
  95. /**
  96. * @param {Node} targetNode
  97. * @returns {boolean}
  98. */
  99. private static isScopeHoistingFunctionDeclaration (targetNode: ESTree.Node): boolean {
  100. if (!NodeGuards.isFunctionDeclarationNode(targetNode)) {
  101. return false;
  102. }
  103. const scopeNode: TNodeWithStatements = NodeStatementUtils.getScopeOfNode(targetNode);
  104. const scopeBody: ESTree.Statement[] = !NodeGuards.isSwitchCaseNode(scopeNode)
  105. ? <ESTree.Statement[]>scopeNode.body
  106. : scopeNode.consequent;
  107. const indexInScope: number = scopeBody.indexOf(targetNode);
  108. if (indexInScope === 0) {
  109. return false;
  110. }
  111. const slicedBody: ESTree.Statement[] = scopeBody.slice(0, indexInScope);
  112. const hostBlockStatementNode: ESTree.BlockStatement = NodeFactory.blockStatementNode(slicedBody);
  113. const functionDeclarationName: string = targetNode.id.name;
  114. let isScopeHoistedFunctionDeclaration: boolean = false;
  115. estraverse.traverse(hostBlockStatementNode, {
  116. enter: (node: ESTree.Node): estraverse.VisitorOption | void => {
  117. if (NodeGuards.isIdentifierNode(node) && node.name === functionDeclarationName) {
  118. isScopeHoistedFunctionDeclaration = true;
  119. return estraverse.VisitorOption.Break;
  120. }
  121. }
  122. });
  123. return isScopeHoistedFunctionDeclaration;
  124. }
  125. /**
  126. * @param {BlockStatement} blockStatementNode
  127. * @returns {boolean}
  128. */
  129. private static isValidCollectedBlockStatementNode (blockStatementNode: ESTree.BlockStatement): boolean {
  130. if (!blockStatementNode.body.length) {
  131. return false;
  132. }
  133. let nestedBlockStatementsCount: number = 0;
  134. let isValidBlockStatementNode: boolean = true;
  135. estraverse.traverse(blockStatementNode, {
  136. enter: (node: ESTree.Node): estraverse.VisitorOption | void => {
  137. if (NodeGuards.isBlockStatementNode(node)) {
  138. nestedBlockStatementsCount++;
  139. }
  140. if (
  141. nestedBlockStatementsCount > DeadCodeInjectionTransformer.maxNestedBlockStatementsCount
  142. || DeadCodeInjectionTransformer.isProhibitedNodeInsideCollectedBlockStatement(node)
  143. || DeadCodeInjectionTransformer.isScopeHoistingFunctionDeclaration(node)
  144. ) {
  145. isValidBlockStatementNode = false;
  146. return estraverse.VisitorOption.Break;
  147. }
  148. }
  149. });
  150. return isValidBlockStatementNode;
  151. }
  152. /**
  153. * @param {BlockStatement} blockStatementNode
  154. * @returns {boolean}
  155. */
  156. private static isValidWrappedBlockStatementNode (blockStatementNode: ESTree.BlockStatement): boolean {
  157. if (!blockStatementNode.body.length) {
  158. return false;
  159. }
  160. let isValidBlockStatementNode: boolean = true;
  161. estraverse.traverse(blockStatementNode, {
  162. enter: (node: ESTree.Node): estraverse.VisitorOption | void => {
  163. if (DeadCodeInjectionTransformer.isScopeHoistingFunctionDeclaration(node)) {
  164. isValidBlockStatementNode = false;
  165. return estraverse.VisitorOption.Break;
  166. }
  167. }
  168. });
  169. if (!isValidBlockStatementNode) {
  170. return false;
  171. }
  172. const parentNodeWithStatements: TNodeWithStatements = NodeStatementUtils
  173. .getParentNodeWithStatements(blockStatementNode);
  174. return parentNodeWithStatements.type !== NodeType.Program;
  175. }
  176. /**
  177. * @param {NodeTransformationStage} nodeTransformationStage
  178. * @returns {IVisitor | null}
  179. */
  180. public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null {
  181. switch (nodeTransformationStage) {
  182. case NodeTransformationStage.DeadCodeInjection:
  183. return {
  184. enter: (node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node | undefined => {
  185. if (parentNode && NodeGuards.isProgramNode(node)) {
  186. this.prepareNode(node, parentNode);
  187. return node;
  188. }
  189. },
  190. leave: (
  191. node: ESTree.Node,
  192. parentNode: ESTree.Node | null
  193. ): ESTree.Node | estraverse.VisitorOption | undefined => {
  194. if (parentNode && NodeGuards.isBlockStatementNode(node)) {
  195. return this.transformNode(node, parentNode);
  196. }
  197. }
  198. };
  199. case NodeTransformationStage.Finalizing:
  200. if (!this.deadCodeInjectionRootAstHostNodeSet.size) {
  201. return null;
  202. }
  203. return {
  204. enter: (
  205. node: ESTree.Node,
  206. parentNode: ESTree.Node | null
  207. ): ESTree.Node | estraverse.VisitorOption |undefined => {
  208. if (parentNode && this.isDeadCodeInjectionRootAstHostNode(node)) {
  209. return this.restoreNode(node, parentNode);
  210. }
  211. }
  212. };
  213. default:
  214. return null;
  215. }
  216. }
  217. /**
  218. * @param {NodeGuards} programNode
  219. * @param {NodeGuards} parentNode
  220. */
  221. public prepareNode (programNode: ESTree.Node, parentNode: ESTree.Node): void {
  222. estraverse.traverse(programNode, {
  223. enter: (node: ESTree.Node): void => {
  224. if (!NodeGuards.isBlockStatementNode(node)) {
  225. return;
  226. }
  227. const clonedBlockStatementNode: ESTree.BlockStatement = NodeUtils.clone(node);
  228. if (!DeadCodeInjectionTransformer.isValidCollectedBlockStatementNode(clonedBlockStatementNode)) {
  229. return;
  230. }
  231. /**
  232. * We should transform identifiers in the dead code block statement to avoid conflicts with original code
  233. */
  234. const transformedBlockStatementNode: ESTree.BlockStatement =
  235. this.makeClonedBlockStatementNodeUnique(clonedBlockStatementNode);
  236. this.collectedBlockStatements.push(transformedBlockStatementNode);
  237. }
  238. });
  239. this.collectedBlockStatementsTotalLength = this.collectedBlockStatements.length;
  240. }
  241. /**
  242. * @param {BlockStatement} blockStatementNode
  243. * @param {NodeGuards} parentNode
  244. * @returns {NodeGuards | VisitorOption}
  245. */
  246. public transformNode (
  247. blockStatementNode: ESTree.BlockStatement,
  248. parentNode: ESTree.Node
  249. ): ESTree.Node | estraverse.VisitorOption {
  250. const canBreakTraverse: boolean = !this.collectedBlockStatements.length
  251. || this.collectedBlockStatementsTotalLength < DeadCodeInjectionTransformer.minCollectedBlockStatementsCount;
  252. if (canBreakTraverse) {
  253. return estraverse.VisitorOption.Break;
  254. }
  255. if (
  256. this.randomGenerator.getMathRandom() > this.options.deadCodeInjectionThreshold
  257. || !DeadCodeInjectionTransformer.isValidWrappedBlockStatementNode(blockStatementNode)
  258. ) {
  259. return blockStatementNode;
  260. }
  261. const minInteger: number = 0;
  262. const maxInteger: number = this.collectedBlockStatements.length - 1;
  263. const randomIndex: number = this.randomGenerator.getRandomInteger(minInteger, maxInteger);
  264. const randomBlockStatementNode: ESTree.BlockStatement = this.collectedBlockStatements.splice(randomIndex, 1)[0];
  265. const isDuplicateBlockStatementNodes: boolean = randomBlockStatementNode === blockStatementNode;
  266. if (isDuplicateBlockStatementNodes) {
  267. return blockStatementNode;
  268. }
  269. return this.replaceBlockStatementNode(blockStatementNode, randomBlockStatementNode, parentNode);
  270. }
  271. /**
  272. * @param {FunctionExpression} deadCodeInjectionRootAstHostNode
  273. * @param {Node} parentNode
  274. * @returns {Node}
  275. */
  276. public restoreNode (deadCodeInjectionRootAstHostNode: ESTree.BlockStatement, parentNode: ESTree.Node): ESTree.Node {
  277. const hostNodeFirstStatement: ESTree.Statement = deadCodeInjectionRootAstHostNode.body[0];
  278. if (!NodeGuards.isFunctionDeclarationNode(hostNodeFirstStatement)) {
  279. throw new Error('Wrong dead code injection root AST host node. Host node should contain `FunctionDeclaration` node');
  280. }
  281. return hostNodeFirstStatement.body;
  282. }
  283. /**
  284. * @param {Node} node
  285. * @returns {boolean}
  286. */
  287. private isDeadCodeInjectionRootAstHostNode (node: ESTree.Node): node is ESTree.BlockStatement {
  288. return NodeGuards.isBlockStatementNode(node) && this.deadCodeInjectionRootAstHostNodeSet.has(node);
  289. }
  290. /**
  291. * Make all identifiers in cloned block statement unique
  292. *
  293. * @param {BlockStatement} clonedBlockStatementNode
  294. * @returns {BlockStatement}
  295. */
  296. private makeClonedBlockStatementNodeUnique (clonedBlockStatementNode: ESTree.BlockStatement): ESTree.BlockStatement {
  297. // should wrap cloned block statement node into function node for correct scope encapsulation
  298. const hostNode: ESTree.Program = NodeFactory.programNode([
  299. NodeFactory.expressionStatementNode(
  300. NodeFactory.functionExpressionNode([], clonedBlockStatementNode)
  301. )
  302. ]);
  303. NodeUtils.parentizeAst(hostNode);
  304. NodeUtils.parentizeNode(hostNode, hostNode);
  305. this.transformersRunner.transform(
  306. hostNode,
  307. DeadCodeInjectionTransformer.transformersToRenameBlockScopeIdentifiers,
  308. NodeTransformationStage.RenameIdentifiers
  309. );
  310. return clonedBlockStatementNode;
  311. }
  312. /**
  313. * @param {BlockStatement} blockStatementNode
  314. * @param {BlockStatement} randomBlockStatementNode
  315. * @param {Node} parentNode
  316. * @returns {BlockStatement}
  317. */
  318. private replaceBlockStatementNode (
  319. blockStatementNode: ESTree.BlockStatement,
  320. randomBlockStatementNode: ESTree.BlockStatement,
  321. parentNode: ESTree.Node
  322. ): ESTree.BlockStatement {
  323. /**
  324. * Should wrap original random block statement node into the parent block statement node (ast root host node)
  325. * with function declaration node. This function declaration node will create block scope for all identifiers
  326. * inside random block statement node and this identifiers won't affect identifiers of the rest AST tree.
  327. */
  328. const deadCodeInjectionRootAstHostNode: ESTree.BlockStatement = NodeFactory.blockStatementNode([
  329. NodeFactory.functionDeclarationNode(
  330. DeadCodeInjectionTransformer.deadCodeInjectionRootAstHostNodeName,
  331. [],
  332. randomBlockStatementNode
  333. )
  334. ]);
  335. /**
  336. * Should store that host node and then extract random block statement node on the `finalizing` stage
  337. */
  338. this.deadCodeInjectionRootAstHostNodeSet.add(deadCodeInjectionRootAstHostNode);
  339. const blockStatementDeadCodeInjectionCustomNode: ICustomNode<TInitialData<BlockStatementDeadCodeInjectionNode>> =
  340. this.deadCodeInjectionCustomNodeFactory(DeadCodeInjectionCustomNode.BlockStatementDeadCodeInjectionNode);
  341. blockStatementDeadCodeInjectionCustomNode.initialize(blockStatementNode, deadCodeInjectionRootAstHostNode);
  342. const newBlockStatementNode: ESTree.BlockStatement = <ESTree.BlockStatement>blockStatementDeadCodeInjectionCustomNode.getNode()[0];
  343. NodeUtils.parentizeNode(newBlockStatementNode, parentNode);
  344. return newBlockStatementNode;
  345. }
  346. }