├── .gitignore
├── CHANGELOG
├── LICENSE
├── README.md
├── example
├── Benign-example
│ └── example.js
└── Malicious-seed
│ └── seed.js
└── src
├── __init__.py
├── ast_js.js
├── bi_list.py
├── build_cfg.py
├── build_dfg.py
├── clone_detection.py
├── clone_metric.py
├── equivalence_classes.py
├── extended_ast.py
├── handle_json.py
├── js_ast.js
├── js_reserved.py
├── node.py
├── pdgs_generation.py
├── samples_generation.py
├── utility_df.py
└── var_list.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # HideNoSeek
2 | Malicious-seed/seed-analysis/
3 | Malicious-seed/PDG
4 | Benign-example/PDG
5 |
6 | # Byte-compiled / optimized / DLL files
7 | __pycache__/
8 | *.py[cod]
9 | *$py.class
10 | .project
11 | .pydevproject
12 | .metadata/
13 |
14 | # Node modules
15 | node_modules
16 | package-lock.json
17 |
18 | # C extensions
19 | *.so
20 |
21 | # Distribution / packaging
22 | .Python
23 | env/
24 | build/
25 | develop-eggs/
26 | dist/
27 | downloads/
28 | eggs/
29 | .eggs/
30 | lib/
31 | lib64/
32 | parts/
33 | sdist/
34 | var/
35 | *.egg-info/
36 | .installed.cfg
37 | *.egg
38 |
39 | # PyInstaller
40 | # Usually these files are written by a python script from a template
41 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
42 | *.manifest
43 | *.spec
44 |
45 | # Installer logs
46 | pip-log.txt
47 | pip-delete-this-directory.txt
48 |
49 | # Unit test / coverage reports
50 | htmlcov/
51 | .tox/
52 | .coverage
53 | .coverage.*
54 | .cache
55 | nosetests.xml
56 | coverage.xml
57 | *,cover
58 | .hypothesis/
59 |
60 | # Translations
61 | *.mo
62 | *.pot
63 |
64 | # Django stuff:
65 | *.log
66 | local_settings.py
67 |
68 | # Flask stuff:
69 | instance/
70 | .webassets-cache
71 |
72 | # Scrapy stuff:
73 | .scrapy
74 |
75 | # Sphinx documentation
76 | docs/_build/
77 |
78 | # PyBuilder
79 | target/
80 |
81 | # IPython Notebook
82 | .ipynb_checkpoints
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # celery beat schedule file
88 | celerybeat-schedule
89 |
90 | # dotenv
91 | .env
92 |
93 | # virtualenv
94 | venv/
95 | ENV/
96 |
97 | # Spyder project settings
98 | .spyderproject
99 |
100 | # Rope project settings
101 | .ropeproject
102 |
103 | # PyCharm project settings
104 | .idea/
105 |
106 | # MacOS files
107 | *.DS_Store
108 | *.idea
109 |
--------------------------------------------------------------------------------
/CHANGELOG:
--------------------------------------------------------------------------------
1 | 2020-03-30: Version 1.0
2 |
3 | Initial release: Static data flow-based analysis of JavaScript files to detect syntactic clones
4 |
5 | * Program Dependency Graph Analysis: static analysis of JavaScript files to build the AST, which we enhance with control and data flow information to build a PDG;
6 | * Slicing-Based Clone Detection: using backward slicing with respect to the control and data flow, we traverse a benign and a malicious AST to detect syntactic clones.
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # HideNoSeek: Camouflaging Malicious JavaScript in Benign ASTs
2 |
3 | This repository contains most of the code of our [CCS'19 paper: "HideNoSeek: Camouflaging Malicious JavaScript in Benign ASTs"](https://swag.cispa.saarland/papers/fass2019hidenoseek.pdf), namely:
4 | - our PDG generation module;
5 | - our clone detection module;
6 | - a part of our clone selection module.
7 |
8 | Please note that in its current state, the code is a Poc and not a fully-fledged production-ready API.
9 |
10 |
11 | ## Summary
12 | HideNoSeek is a novel and generic camouflage attack, which changes the constructs of malicious JavaScript samples to exactly reproduce an existing benign syntax. For this purpose, we statically enhance the Abstract Syntax Trees (ASTs) of valid JavaScript inputs with control and data flow information. We refer to the resulting data structure as Program Dependency Graph (PDG). In particular, HideNoSeek looks for isomorphic subgraphs between the malicious and the benign files. Specifically, it replaces benign sub-ASTs by their malicious equivalents (same syntactic structure) and adjusts the benign data dependencies–without changing the AST–, so that the malicious semantics is kept.
13 |
14 | For ethical reasons, we decided to publish neither the complete code of our clone selection module nor our clone replacement module. Therefore, this HideNoSeek version can be used to **detect** syntactic clones, but not to **rewrite** them.
15 |
16 |
17 | ## Setup
18 |
19 | ```
20 | install python3 # (tested with 3.6.7)
21 | install nodejs # (tested with 8.10.0)
22 | install npm # (tested with 3.5.2)
23 | cd src
24 | npm install escodegen # (tested with 1.9.1)
25 | cd ..
26 | ```
27 |
28 |
29 | ## Usage:
30 |
31 | HideNoSeek works directly at the PDG level. To detect clones between 2 JavaScript folders, you should generate the PDGs beforehand (cf. PDGs Generation) and give them as input to the `src/samples_generation.replace_ast_df_folder` function.
32 |
33 | To detect clones between 2 JavaScript samples, you should give the files' paths directly as input to the `src/samples_generation.replace_ast` function.
34 |
35 | ### PDGs Generation
36 |
37 | To generate the PDGs of the JS files from the folder FOLDER\_NAME, launch the following shell command from the `src` folder location:
38 | ```
39 | $ python3 -c "from pdgs_generation import store_pdg_folder; store_pdg_folder('FOLDER_NAME')"
40 | ```
41 |
42 | The corresponding PDGs will be stored in FOLDER\_NAME/PDG.
43 |
44 |
45 | To generate the PDG of one given JS file INPUT\_FILE, launch the following python3 commands from the `src` folder location:
46 | ```
47 | >>> from pdgs_generation import get_data_flow
48 | >>> pdg = get_data_flow('INPUT_FILE', benchmarks=dict())
49 | ```
50 |
51 | Per default, the corresponding PDG will not be stored. To store it in an existing PDG\_PATH folder, call:
52 | ```
53 | >>> from pdgs_generation import get_data_flow
54 | >>> pdg = get_data_flow('INPUT_FILE', benchmarks=dict(), store_pdgs='PDG_PATH')
55 | ```
56 |
57 | Note that, for this HideNoSeek version, we added a timeout of 60 seconds for the PDG generation process (cf. line 83 of `src/pdgs_generation.py`).
58 |
59 |
60 |
61 | ### Clone Detection
62 |
63 | To find clones between the benign PDGs from the folder FOLDER\_BENIGN\_PDGS and the malicious ones from FOLDER\_MALICIOUS\_PDGS, launch the following python3 command from the `src` folder location:
64 | ```
65 | $ python3 -c "from samples_generation import replace_ast_df_folder; replace_ast_df_folder('FOLDER_BENIGN_PDGS', 'FOLDER_MALICIOUS_PDGS')"
66 | ```
67 |
68 | For each malicious PDG, a folder PDG_NAME-analysis will be created in FOLDER\_MALICIOUS\_PDGS. For each benign PDG analyzed, it will contain a JSON file (name format: benign_malicious.json), which summarizes the main findings, such as identical nodes, the proportion of identical nodes, dissimilar tokens, different benchmarks...
69 | In addition, we display in stdout the benign and malicious code of the reported clones. This can be disabled, e.g., for multiprocessing, by commenting the call to `print_clones` line 153 of `src/samples_generation.py`.
70 |
71 |
72 | To find clones between a benign JS file BENIGN_JS and a malicious one MALICIOUS_JS, launch the following python3 commands from the `src` folder location:
73 | ```
74 | >>> from samples_generation import replace_ast
75 | >>> replace_ast('BENIGN_JS', 'MALICIOUS_JS')
76 | ```
77 |
78 | The outputs, in terms of JSON file and on stdout, are as previously.
79 |
80 |
81 | ### Multiprocessing
82 |
83 | The `src/pdgs_generation.store_pdg_folder` and `src/samples_generation.replace_ast_df_folder` functions are fully parallelized.
84 | In both cases, we are currently using 1 CPU, but you can change that by modifying the variable NUM\_WORKERS from `src/utility_df.py`. If you use more than 1 CPU, you should comment out the call to `print_clones` line 153 of `src/samples_generation.py`.
85 |
86 |
87 | ## Example
88 |
89 | The folder `example/Benign-example` contains `example.js` the benign example from our paper, while `example/Malicious-seed/seed.js` is the malicious seed from our paper.
90 |
91 | To detect clones between these 2 files, launch the following python3 commands from the `src` folder location:
92 | ```
93 | >>> from samples_generation import replace_ast
94 | >>> replace_ast('../example/Benign-example/example.js', '../example/Malicious-seed/seed.js')
95 | ```
96 |
97 | You will get the following output on stdout:
98 | ```
99 | INFO:Successfully selected 2 clones in XXXs
100 | ==============
101 | [, ]
102 | obj.setAttribute('type', 'application/x-shockwave-flash');
103 | obj = document.createElement('object');
104 | [, ]
105 | wscript.run('cmd.exe /c ";"', '0');
106 | wscript = WScript.CreateObject('WScript.Shell');
107 | --
108 | [, ]
109 | obj.setAttribute('tabindex', '-1');
110 | obj = document.createElement('object');
111 | [, ]
112 | wscript.run('cmd.exe /c ";"', '0');
113 | wscript = WScript.CreateObject('WScript.Shell');
114 | --
115 | ==============
116 | INFO:Could find 100.0% of the malicious nodes in the benign AST
117 | ```
118 |
119 | Our tool found 2 clones (each time composed of 2 statements). It means that the whole malicious seed could be rewritten in 2 different ways in the benign example.
120 | In addition, the file `example/Malicious-seed/seed-analysis/example_seed.json`, containing additional clone information, was created.
121 |
122 |
123 | ## Cite this work
124 | If you use HideNoSeek for academic research, you are highly encouraged to cite the following [paper](https://swag.cispa.saarland/papers/fass2019hidenoseek.pdf):
125 | ```
126 | @inproceedings{fass2019hidenoseek,
127 | author="Fass, Aurore and Backes, Michael and Stock, Ben",
128 | title="{\textsc{HideNoSeek}: Camouflaging Malicious JavaScript in Benign ASTs}",
129 | booktitle="ACM CCS",
130 | year="2019"
131 | }
132 | ```
133 |
134 |
135 | ### Abstract:
136 |
137 | In the malware field, learning-based systems have become popular to detect new malicious variants. Nevertheless, attackers with _specific_ and _internal_ knowledge of a target system may be able to produce input samples which are misclassified. In practice, the assumption of _strong attackers_ is not realistic as it implies access to insider information. We instead propose HideNoSeek, a novel and generic camouflage attack, which evades the entire class of detectors based on syntactic features, without needing any information about the system it is trying to evade. Our attack consists of changing the constructs of malicious JavaScript samples to reproduce a benign syntax.
138 |
139 | For this purpose, we automatically rewrite the Abstract Syntax Trees (ASTs) of malicious JavaScript inputs into existing benign ones. In particular, HideNoSeek uses malicious seeds and searches for isomorphic subgraphs between the seeds and traditional benign scripts. Specifically, it replaces benign sub-ASTs by their malicious equivalents (same syntactic structure) and adjusts the benign data dependencies--without changing the AST--, so that the malicious semantics is kept. In practice, we leveraged 23 malicious seeds to generate 91,020 malicious scripts, which perfectly reproduce ASTs of Alexa top 10,000 web pages. Also, we can produce on average 14 different malicious samples with the same AST as each Alexa top 10.
140 |
141 | Overall, a standard trained classifier has 99.98% false negatives with HideNoSeek inputs, while a classifier trained on such samples has over 88.74% false positives, rendering the targeted static detectors unreliable.
142 |
143 |
144 | ## License
145 |
146 | This project is licensed under the terms of the AGPL3 license, which you can find in `LICENSE`.
147 |
--------------------------------------------------------------------------------
/example/Benign-example/example.js:
--------------------------------------------------------------------------------
1 | obj = document.createElement("object");
2 | obj.setAttribute("id", this.internal.flash.id);
3 | obj.setAttribute("type", "application/x-shockwave-flash");
4 | obj.setAttribute("tabindex", "-1");
5 | createParam(obj, "flashvars", flashVars);
6 |
--------------------------------------------------------------------------------
/example/Malicious-seed/seed.js:
--------------------------------------------------------------------------------
1 | wscript = WScript.CreateObject('WScript.Shell');
2 | wscript.run("cmd.exe /c \";\"", "0");
3 |
--------------------------------------------------------------------------------
/src/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Aurore54F/HideNoSeek/d08f4d39c5a33fd124f4e9dbb202e7f5b851dc73/src/__init__.py
--------------------------------------------------------------------------------
/src/ast_js.js:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Aurore Fass
2 | // This program is free software: you can redistribute it and/or modify
3 | // it under the terms of the GNU Affero General Public License as published by
4 | // the Free Software Foundation, either version 3 of the License, or
5 | // (at your option) any later version.
6 |
7 | // This program is distributed in the hope that it will be useful,
8 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | // GNU Affero General Public License for more details.
11 |
12 | // You should have received a copy of the GNU Affero General Public License
13 | // along with this program. If not, see .
14 |
15 | // Conversion of an Esprima AST to JS using Escodegen.
16 |
17 |
18 | module.exports = {
19 | ast2js: ast2js
20 | };
21 |
22 |
23 | var es = require("escodegen");
24 | var fs = require("fs");
25 |
26 |
27 | /**
28 | * Extraction of the JS code from a given AST using Escodegen.
29 | *
30 | * @param json_path
31 | * @param code_path
32 | */
33 | function ast2js(json_path, code_path) {
34 | var ast = fs.readFileSync(json_path).toString('utf-8');
35 | ast = JSON.parse(ast);
36 | if (code_path !== '1') {
37 | fs.writeFile(code_path, es.generate(ast, {comment: true, json: true}), function (err) {
38 | if (err) {
39 | console.error(err);
40 | }
41 | });
42 | }
43 | else {
44 | console.log(es.generate(ast, {comment: true, json: true}));
45 | }
46 | }
47 |
48 | ast2js(process.argv[2], process.argv[3]);
49 |
--------------------------------------------------------------------------------
/src/bi_list.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2020 Aurore Fass
2 | # This program is free software: you can redistribute it and/or modify
3 | # it under the terms of the GNU Affero General Public License as published by
4 | # the Free Software Foundation, either version 3 of the License, or
5 | # (at your option) any later version.
6 |
7 | # This program is distributed in the hope that it will be useful,
8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | # GNU Affero General Public License for more details.
11 |
12 | # You should have received a copy of the GNU Affero General Public License
13 | # along with this program. If not, see .
14 |
15 | """
16 | Definition of the class BiList: similar Node objects between two PDGs.
17 | """
18 |
19 | import logging
20 | import copy
21 |
22 |
23 | class BiList:
24 |
25 | def __init__(self):
26 | self.list1 = []
27 | self.list2 = []
28 |
29 | def append_equivalence(self, elt, my_id):
30 | if my_id == 1:
31 | self.list1.append(elt)
32 | return self
33 | if my_id == 2:
34 | self.list2.append(elt)
35 | return self
36 | logging.error('The id given should be either 1 or 2. Got %s', str(my_id))
37 | return None
38 |
39 | def append_list(self, elt1, elt2):
40 | self.list1.append(elt1)
41 | self.list2.append(elt2)
42 |
43 | def add_elements_begin(self, some_list):
44 | self.list1[:0] = some_list.list1
45 | self.list2[:0] = some_list.list2
46 |
47 | def add_elements_pos(self, pos, some_list):
48 | keep_pos = pos
49 | for elt in some_list.list1:
50 | self.list1.insert(pos, elt)
51 | pos += 1
52 | for elt in some_list.list2:
53 | self.list2.insert(keep_pos, elt)
54 | keep_pos += 1
55 |
56 | def extend_list(self, some_list):
57 | self.list1.extend(some_list.list1)
58 | self.list2.extend(some_list.list2)
59 |
60 | def copy_list(self):
61 | new_list = BiList()
62 | new_list.list1 = copy.copy(self.list1)
63 | new_list.list2 = copy.copy(self.list2)
64 | return new_list
65 |
66 | def is_empty(self):
67 | return not self.list1 and not self.list2
68 |
--------------------------------------------------------------------------------
/src/build_cfg.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 Aurore Fass
2 | # This program is free software: you can redistribute it and/or modify
3 | # it under the terms of the GNU Affero General Public License as published by
4 | # the Free Software Foundation, either version 3 of the License, or
5 | # (at your option) any later version.
6 |
7 | # This program is distributed in the hope that it will be useful,
8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | # GNU Affero General Public License for more details.
11 |
12 | # You should have received a copy of the GNU Affero General Public License
13 | # along with this program. If not, see .
14 |
15 | """
16 | Builds a Control Flow Graph..
17 | """
18 |
19 |
20 | EPSILON = ['BlockStatement', 'DebuggerStatement', 'EmptyStatement',
21 | 'ExpressionStatement', 'LabeledStatement', 'ReturnStatement',
22 | 'ThrowStatement', 'WithStatement', 'CatchClause', 'VariableDeclaration',
23 | 'FunctionDeclaration']
24 |
25 | CONDITIONAL = ['DoWhileStatement', 'ForStatement', 'ForOfStatement', 'ForInStatement',
26 | 'IfStatement', 'SwitchCase', 'SwitchStatement', 'TryStatement',
27 | 'WhileStatement', 'ConditionalExpression']
28 |
29 | UNSTRUCTURED = ['BreakStatement', 'ContinueStatement']
30 |
31 |
32 | # The comments just automatically link to a Statement node somewhere below them.
33 | def extra_comment_node(node, max_children):
34 | """ If a comment has linked to a node. """
35 | if len(node.children) > max_children:
36 | if node.children[max_children].is_comment():
37 | node.set_comment_dependency(extremity=node.children[max_children])
38 |
39 |
40 | def link_expression(node, node_parent):
41 | """ Non-statement node. """
42 | if node.is_comment():
43 | node_parent.set_comment_dependency(extremity=node)
44 | else:
45 | node_parent.set_statement_dependency(extremity=node)
46 | return node
47 |
48 |
49 | def epsilon_statement_cf(node):
50 | """ Non-conditional statements. """
51 | for child in node.children:
52 | if child.is_statement():
53 | node.set_control_dependency(extremity=child, label='e')
54 | else:
55 | link_expression(node=child, node_parent=node)
56 |
57 |
58 | def break_statement_cf(node):
59 | """ BreakStatement, breaks the loop. """
60 | if_cond = node.control_dep_parents[0].extremity.control_dep_parents[0].extremity
61 | block_statmt = if_cond.control_dep_parents[0].extremity
62 | if_all = [elt.extremity for elt in block_statmt.control_dep_children]
63 | for i, _ in enumerate(if_all):
64 | if if_cond.id == if_all[i].id:
65 | break
66 | print(if_all)
67 | if_false = if_all[i+1:]
68 | print(if_false)
69 | for elt in if_false:
70 | print(if_cond.name)
71 | print(if_cond.id)
72 | print(elt.name)
73 | print(elt.id)
74 | if_cond.set_control_dependency(extremity=elt, label=False)
75 | block_statmt.remove_control_dependency(extremity=elt)
76 |
77 |
78 | def do_while_cf(node):
79 | """ DoWhileStatement. """
80 | # Element 0: body (Statement)
81 | # Element 1: test (Expression)
82 | node.set_control_dependency(extremity=node.children[0], label=True)
83 | link_expression(node=node.children[1], node_parent=node)
84 | extra_comment_node(node, 2)
85 |
86 |
87 | def for_cf(node):
88 | """ ForStatement. """
89 | # Element 0: init
90 | # Element 1: test (Expression)
91 | # Element 2: update (Expression)
92 | # Element 3: body (Statement)
93 | """ ForOfStatement. """
94 | # Element 0: left
95 | # Element 1: right
96 | # Element 2: body (Statement)
97 | i = 0
98 | for child in node.children:
99 | if child.body != 'body':
100 | link_expression(node=child, node_parent=node)
101 | elif not child.is_comment():
102 | node.set_control_dependency(extremity=child, label=True)
103 | i += 1
104 | extra_comment_node(node, i)
105 |
106 |
107 | def if_cf(node):
108 | """ IfStatement. """
109 | # Element 0: test (Expression)
110 | # Element 1: consequent (Statement)
111 | # Element 2: alternate (Statement)
112 | link_expression(node=node.children[0], node_parent=node)
113 | node.set_control_dependency(extremity=node.children[1], label=True)
114 | if len(node.children) > 2:
115 | if node.children[2].is_comment():
116 | node.set_comment_dependency(extremity=node.children[2])
117 | else:
118 | node.set_control_dependency(extremity=node.children[2], label=False)
119 | extra_comment_node(node, 3)
120 |
121 |
122 | def try_cf(node):
123 | """ TryStatement. """
124 | # Element 0: block (Statement)
125 | # Element 1: handler (Statement) / finalizer (Statement)
126 | # Element 2: finalizer (Statement)
127 | node.set_control_dependency(extremity=node.children[0], label=True)
128 | if node.children[1].body == 'handler':
129 | node.set_control_dependency(extremity=node.children[1], label=False)
130 | else: # finalizer
131 | node.set_control_dependency(extremity=node.children[1], label='e')
132 | if len(node.children) > 2:
133 | if node.children[2].body == 'finalizer':
134 | node.set_control_dependency(extremity=node.children[2], label='e')
135 | extra_comment_node(node, 3)
136 | else:
137 | extra_comment_node(node, 2)
138 |
139 |
140 | def while_cf(node):
141 | """ WhileStatement. """
142 | # Element 0: test (Expression)
143 | # Element 1: body (Statement)
144 | link_expression(node=node.children[0], node_parent=node)
145 | node.set_control_dependency(extremity=node.children[1], label=True)
146 | extra_comment_node(node, 2)
147 |
148 |
149 | def switch_cf(node):
150 | """ SwitchStatement. """
151 | # Element 0: discriminant
152 | # Element 1: cases (SwitchCase)
153 |
154 | switch_cases = node.children
155 | link_expression(node=switch_cases[0], node_parent=node)
156 | if len(switch_cases) > 1:
157 | # SwitchStatement -> True -> SwitchCase for first one
158 | node.set_control_dependency(extremity=switch_cases[1], label='e')
159 | switch_case_cf(switch_cases[1])
160 | for i in range(2, len(switch_cases)):
161 | if switch_cases[i].is_comment():
162 | node.set_comment_dependency(extremity=switch_cases[i])
163 | else:
164 | # SwitchCase -> False -> SwitchCase for the other ones
165 | switch_cases[i - 1].set_control_dependency(extremity=switch_cases[i], label=False)
166 | if i != len(switch_cases) - 1:
167 | switch_case_cf(switch_cases[i])
168 | else: # Because the last switch is executed per default, i.e. without condition 1st
169 | switch_case_cf(switch_cases[i], last=True)
170 | # Otherwise, we could just have a switch(something) {}
171 |
172 |
173 | def switch_case_cf(node, last=False):
174 | """ SwitchCase. """
175 | # Element 0: test
176 | # Element 1: consequent (Statement)
177 | nb_child = len(node.children)
178 | if nb_child > 1:
179 | if not last: # As all switches but the last has to respect a condition to enter the branch
180 | link_expression(node=node.children[0], node_parent=node)
181 | j = 1
182 | else:
183 | j = 0
184 | for i in range(j, nb_child):
185 | if node.children[i].is_comment():
186 | node.set_comment_dependency(extremity=node.children[i])
187 | else:
188 | node.set_control_dependency(extremity=node.children[i], label=True)
189 | elif nb_child == 1:
190 | node.set_control_dependency(extremity=node.children[0], label=True)
191 |
192 |
193 | def conditional_statement_cf(node):
194 | """ For the conditional nodes. """
195 | if node.name == 'DoWhileStatement':
196 | do_while_cf(node)
197 | elif node.name == 'ForStatement' or node.name == 'ForOfStatement'\
198 | or node.name == 'ForInStatement':
199 | for_cf(node)
200 | elif node.name == 'IfStatement' or node.name == 'ConditionalExpression':
201 | if_cf(node)
202 | elif node.name == 'WhileStatement':
203 | while_cf(node)
204 | elif node.name == 'TryStatement':
205 | try_cf(node)
206 | elif node.name == 'SwitchStatement':
207 | switch_cf(node)
208 | elif node.name == 'SwitchCase':
209 | pass # Already handled in SwitchStatement
210 |
211 |
212 | def unstructured_statement_cf(node):
213 | """ For the unstructured nodes. """
214 | if node.name == 'ContinueStatement':
215 | continue_statement_cf(node)
216 | elif node.name == 'BreakStatement':
217 | break_statement_cf(node)
218 |
219 |
220 | def build_cfg(ast_nodes):
221 | """
222 | Produce a CFG by adding statement and control dependencies to each Node.
223 |
224 | -------
225 | Parameters:
226 | - ast_nodes: Node
227 | Output of ast_to_ast_nodes(, ast_nodes=Node('Program')).
228 |
229 | -------
230 | Returns:
231 | - Node
232 | With statement and control dependencies added.
233 | """
234 |
235 | for child in ast_nodes.children:
236 | if child.name in EPSILON or child.name in UNSTRUCTURED:
237 | epsilon_statement_cf(child)
238 | elif child.name in CONDITIONAL:
239 | conditional_statement_cf(child)
240 | else:
241 | for grandchild in child.children:
242 | if not grandchild.is_statement():
243 | link_expression(node=grandchild, node_parent=child)
244 | else:
245 | child.set_control_dependency(extremity=grandchild, label='e')
246 | build_cfg(child)
247 | return ast_nodes
248 |
--------------------------------------------------------------------------------
/src/build_dfg.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 Aurore Fass
2 | # This program is free software: you can redistribute it and/or modify
3 | # it under the terms of the GNU Affero General Public License as published by
4 | # the Free Software Foundation, either version 3 of the License, or
5 | # (at your option) any later version.
6 |
7 | # This program is distributed in the hope that it will be useful,
8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | # GNU Affero General Public License for more details.
11 |
12 | # You should have received a copy of the GNU Affero General Public License
13 | # along with this program. If not, see .
14 |
15 | """
16 | Builds a Code Dependency Graph..
17 | """
18 |
19 | import logging
20 | import copy
21 |
22 | import js_reserved
23 | import var_list
24 |
25 |
26 | DECLARATIONS = ['VariableDeclaration', 'FunctionDeclaration']
27 | EXPRESSIONS = ['AssignmentExpression', 'ArrayExpression', 'ArrowFunctionExpression',
28 | 'AwaitExpression', 'BinaryExpression', 'CallExpression', 'ClassExpression',
29 | 'ConditionalExpression', 'FunctionExpression', 'LogicalExpression',
30 | 'MemberExpression', 'NewExpression', 'ObjectExpression', 'SequenceExpression',
31 | 'TaggedTemplateExpression', 'ThisExpression', 'UnaryExpression', 'UpdateExpression',
32 | 'YieldExpression']
33 |
34 |
35 | def get_pos_identifier(identifier_node, my_var_list):
36 | """
37 | Position of identifier_node in var_list.
38 |
39 | -------
40 | Parameters:
41 | - identifier_node: Node
42 | Node whose name Identifier is.
43 | - my_var_list: VarList
44 | Stores the variables currently declared and where they should be referred to.
45 |
46 | -------
47 | Returns:
48 | - int
49 | The position of identifier_node in var_list.
50 | - or None if it is not in the list.
51 | """
52 |
53 | id_name_list = [elt.attributes['name'] for elt in my_var_list.var_list]
54 | var_name = identifier_node.attributes['name']
55 | if var_name in id_name_list:
56 | return id_name_list.index(var_name)
57 | return None
58 |
59 |
60 | def get_nearest_statement(node, answer=None):
61 | """
62 | Gets the statement node nearest to node (using CF).
63 |
64 | -------
65 | Parameters:
66 | - node: Node
67 | Current node.
68 | - answer: Node
69 | Such as answer.is_statement() = True. Used to force taking a statement node parent
70 | of the nearest node (use case: boolean data flow dependencies). Default: None.
71 |
72 | -------
73 | Returns:
74 | - Node:
75 | answer, if given, otherwise the statement node nearest to node.
76 | """
77 |
78 | if answer is not None:
79 | return answer
80 | else:
81 | if node.is_statement():
82 | return node
83 | else:
84 | if len(node.statement_dep_parents) > 1:
85 | logging.warning('Several statement dependencies are joining on the same node %s',
86 | node.name)
87 | # return get_nearest_statement(node.statement_dep_parents[0].extremity)
88 | return get_nearest_statement(node.parent)
89 |
90 |
91 | def is_descendant(node1, node2):
92 | """
93 | Indicates whether node1 is a descendant of node2 (using CF).
94 |
95 | -------
96 | Parameters:
97 | - node1: Node
98 | - node2: Node
99 |
100 | -------
101 | Returns:
102 | - Bool
103 | """
104 |
105 | if node2.id == node1.id:
106 | return True
107 | if node2.is_leaf():
108 | return False
109 |
110 | res = []
111 | for child in node2.control_dep_children:
112 | res.append(is_descendant(node1, child.extremity))
113 | for child in node2.statement_dep_children:
114 | res.append(is_descendant(node1, child.extremity))
115 | if True in res:
116 | return True
117 | return False
118 |
119 |
120 | def get_nearest_common_statement(node1, node2):
121 | """
122 | Gets the nearest common statement node between two statement nodes node1 and node2
123 | (using CF).
124 |
125 | -------
126 | Parameters:
127 | - node1: Node
128 | - node2: Node
129 |
130 | -------
131 | Returns:
132 | - Node:
133 | Nearest common statement node between node1 and node2.
134 | """
135 |
136 | nearest_statement1 = get_nearest_statement(node1)
137 | nearest_statement2 = get_nearest_statement(node2)
138 | if nearest_statement1.id == nearest_statement2.id:
139 | return nearest_statement1
140 | if is_descendant(nearest_statement1, nearest_statement2):
141 | return get_nearest_common_statement(nearest_statement1.control_dep_parents[0].extremity,
142 | nearest_statement2)
143 | return get_nearest_common_statement(nearest_statement1,
144 | nearest_statement2.control_dep_parents[0].extremity)
145 |
146 |
147 | def set_df(var, var_index, identifier_node):
148 | """
149 | Sets the data flow dependencies from the statement node nearest to the variable in var at
150 | position var_index, to the statement node nearest to identifier_node.
151 |
152 | -------
153 | Parameters:
154 | - var: VarList
155 | Either var_loc or var_glob
156 | - var_index: int
157 | Position of the variable considered in var.
158 | - identifier_node: Node
159 | End of the DF.
160 | """
161 |
162 | if not isinstance(var, var_list.VarList):
163 | logging.error('The parameter given should be typed var_list.VarList. Got %s', str(var))
164 | else:
165 | begin_df = get_nearest_statement(var.var_list[var_index], var.ref_list[var_index])
166 | begin_id_df = var.var_list[var_index]
167 | if isinstance(begin_df, list):
168 | for i, _ in enumerate(begin_df):
169 | get_nearest_statement(begin_df[i]).\
170 | set_data_dependency(extremity=get_nearest_statement(identifier_node),
171 | begin=begin_df[i], end=identifier_node)
172 | else:
173 | begin_df.set_data_dependency(extremity=get_nearest_statement(identifier_node),
174 | begin=begin_id_df, end=identifier_node)
175 |
176 |
177 | def assignment_df(identifier_node, var_loc, var_glob, unknown_var):
178 | """
179 | Add data flow for Identifiers.
180 |
181 | -------
182 | Parameters:
183 | - identifier_node: Node
184 | Node whose name Identifier is.
185 | - var_loc: VarList
186 | Stores the variables currently declared and where they should be referred to.
187 | - var_glob: VarList
188 | Stores the global variables currently declared and where they should be referred to.
189 | - unknown_var: list
190 | Contains the variables currently not defined (could be valid because of hosting,
191 | therefore we check them later again).
192 | """
193 |
194 | # Position of identifier in the list a
195 | var_index = get_pos_identifier(identifier_node, var_loc)
196 | if var_index is not None:
197 | logging.debug('The variable %s was used', identifier_node.attributes['name'])
198 | # Data dependency between last time variable used and now
199 | set_df(var_loc, var_index, identifier_node)
200 |
201 | else:
202 | var_index = get_pos_identifier(identifier_node, var_glob)
203 | if var_index is not None:
204 | logging.debug('The global variable %s was used', identifier_node.attributes['name'])
205 | # Data dependency between last time variable used and now
206 | set_df(var_glob, var_index, identifier_node)
207 | elif identifier_node.attributes['name'].lower() not in js_reserved.RESERVED_WORDS_LOWER:
208 | unknown_var.append(identifier_node) # TODO: handle scope of unknown var
209 |
210 |
211 | def var_decl_df(node, var_loc, var_glob, unknown_var, entry, assignt=False, obj=False):
212 | """
213 | Handles the variables declared.
214 |
215 | -------
216 | Parameters:
217 | - node: Node
218 | Node whose name Identifier is.
219 | - var_loc: VarList
220 | Stores the variables currently declared and where they should be referred to.
221 | - var_glob: VarList
222 | Stores the global variables currently declared and where they should be referred to.
223 | - unknown_var: list
224 | Contains the variables currently not defined (could be valid because of hosting,
225 | therefore we check them later again).
226 | - entry: int
227 | Indicates if we are in the global scope (1) or not (0).
228 | - assignt: Bool
229 | False if this is a variable declaration with var/let, True if with AssignmentExpression.
230 | Default: False.
231 | - obj: Bool
232 | True if node an object is, False if it is a variable. Default: False.
233 | """
234 |
235 | if entry == 1 or (assignt and get_pos_identifier(node, var_loc) is None):
236 | # Global scope or (directly assigned and not known as a local variable)
237 | my_var_list = var_glob
238 | else:
239 | my_var_list = var_loc
240 |
241 | var_index = get_pos_identifier(node, my_var_list)
242 | if var_index is None:
243 | my_var_list.add_var(node) # Add variable in the list
244 | if not assignt:
245 | logging.debug('The variable %s was declared', node.attributes['name'])
246 | else:
247 | logging.debug('The global variable %s was declared', node.attributes['name'])
248 | # hoisting(node, unknown_var) # Hoisting only for FunctionDeclaration
249 | else:
250 | if assignt:
251 | if obj: # In the case of objects, we will always keep their AST order
252 | logging.debug('The object %s was used and modified', node.attributes['name'])
253 | # Data dependency between last time object used and now
254 | set_df(my_var_list, var_index, node)
255 | else:
256 | logging.debug('The variable %s was modified', node.attributes['name'])
257 | else:
258 | logging.debug('The variable %s was redefined', node.attributes['name'])
259 | # Order in the case that assignt and obj are true: data flow before modifying object
260 | my_var_list.update_var(var_index, node) # Update last time with current
261 |
262 |
263 | def var_declaration_df(node, var_loc, var_glob, unknown_var, id_list, entry):
264 | """
265 | Handles the node VariableDeclaration:
266 | # Element0: id
267 | # Element1: init
268 |
269 | -------
270 | Parameters:
271 | - node: Node
272 | Node whose name should be VariableDeclarator.
273 | - var_loc: VarList
274 | Stores the variables currently declared and where they should be referred to.
275 | - var_glob: VarList
276 | Stores the global variables currently declared and where they should be referred to.
277 | - unknown_var: list
278 | Contains the variables currently not defined (could be valid because of hosting,
279 | therefore we check them later again).
280 | - id_list: list
281 | Stores the id of the node already handled.
282 | - entry: int
283 | Indicates if we are in the global scope (1) or not (0).
284 | """
285 |
286 | if node.name == 'VariableDeclarator':
287 | identifiers = search_identifiers(node.children[0], id_list, tab=[]) # Variable definition
288 | for decl in identifiers:
289 | id_list.append(decl.id)
290 | var_decl_df(node=decl, var_loc=var_loc, var_glob=var_glob, unknown_var=unknown_var,
291 | entry=entry)
292 | if not identifiers:
293 | logging.warning('No identifier variable found')
294 |
295 | if len(node.children) > 1: # Variable initialized
296 | var_loc = build_dfg(node.children[1], var_loc, var_glob, unknown_var=unknown_var,
297 | id_list=id_list, entry=entry)
298 | """
299 | search_handle_fun_expr(node, var_loc, var_glob, id_list)
300 | identifiers = search_identifiers(node.children[1], id_list, tab=[])
301 | for init in identifiers:
302 | if init.id not in id_list:
303 | id_list.append(init.id)
304 | assignment_df(identifier_node=init, var_loc=var_loc, var_glob=var_glob)
305 | """
306 | else:
307 | logging.debug('The variable %s was not initialized', decl.attributes['name'])
308 |
309 | # else: # Could be a Line (comment)
310 | # logging.warning('Expected a VariableDeclarator node, but got a ' + node.name)
311 | return var_loc
312 |
313 |
314 | def limit_scope(var_loc):
315 | """
316 | Handles the scope of let/const variable declarations.
317 |
318 | -------
319 | Parameter:
320 | - var_loc: VarList
321 | Stores the variables currently declared and where they should be referred to.
322 | """
323 |
324 | if var_loc.get_limit():
325 | var_loc.set_limit(False)
326 | var_loc.var_list = var_loc.get_before_limit_list()
327 |
328 |
329 | def search_identifiers(node, id_list, tab, rec=True):
330 | """
331 | Searches the Identifier nodes children of node.
332 | -------
333 | Parameters:
334 | - node: Node
335 | Current node.
336 | - id_list: list
337 | Stores the id of the node already handled.
338 | - tab: list
339 | To store the Identifier nodes found.
340 | - rec: Bool
341 | Indicates whether to go recursively in the node or not. Default: True (i.e. recursive).
342 |
343 | -------
344 | Returns:
345 | - list
346 | Stores the Identifier nodes found.
347 | """
348 |
349 | if node.name == 'ObjectExpression': # Only consider the object name, no properties
350 | pass
351 | elif node.name == 'Identifier':
352 | """
353 | MemberExpression can be:
354 | - obj.prop[.prop.prop...]: we consider only obj;
355 | - this.something or window.something: we consider only something.
356 | """
357 | if node.parent.name == 'MemberExpression':
358 | if node.parent.children[0] == node: # current = obj, this or window
359 | # if node.attributes['name'].lower() in js_reserved.RESERVED_WORDS_LOWER:
360 | if node.attributes['name'] == 'this' or node.attributes['name'] == 'window':
361 | id_list.append(node.id) # As window an Identifier is
362 | logging.debug('%s is not the variable\'s name', node.attributes['name'])
363 | prop = node.parent.children[1]
364 | if prop.name == 'Identifier':
365 | tab.append(prop) # We want the something after this/window
366 | else:
367 | tab.append(node) # otherwise current = obj, which we store
368 | elif node.parent.children[0].name == 'ThisExpression': # Parent of this=ThisExpression
369 | tab.append(node) # node is actually node.parent.children[1]
370 | else:
371 | if node.parent.attributes['computed']: # Access through a table, could be an index
372 | logging.debug('The variable %s was considered', node.attributes['name'])
373 | tab.append(node)
374 | else:
375 | tab.append(node) # Otherwise this is just a variable
376 | else:
377 | if rec:
378 | for child in node.children:
379 | search_identifiers(child, id_list, tab, rec)
380 | return tab
381 |
382 |
383 | def assignment_expr_df(node, var_loc, var_glob, unknown_var, id_list, entry, call_expr=False):
384 | """
385 | Handles the node AssignmentExpression:
386 | # Element0: left (referred to as assignee)
387 | # Element1: right (referred to as assignt)
388 |
389 | -------
390 | Parameters:
391 | - node: Node
392 | Node whose name should be VariableDeclarator.
393 | - var_loc: VarList
394 | Stores the variables currently declared and where they should be referred to.
395 | - var_glob: VarList
396 | Stores the global variables currently declared and where they should be referred to.
397 | - unknown_var: list
398 | Contains the variables currently not defined (could be valid because of hosting,
399 | therefore we check them later again).
400 | - id_list: list
401 | Stores the id of the node already handled.
402 | - entry: int
403 | Indicates if we are in the global scope (1) or not (0).
404 | """
405 |
406 | identifiers = search_identifiers(node.children[0], id_list, tab=[])
407 | for assignee in identifiers:
408 | id_list.append(assignee.id)
409 | if (assignee.parent.name == 'MemberExpression'
410 | and assignee.parent.children[0].name != 'ThisExpression'
411 | and 'window' not in assignee.parent.children[0].attributes.values())\
412 | or (assignee.parent.name == 'MemberExpression'
413 | and assignee.parent.parent.name == 'MemberExpression'):
414 | # assignee is an object, we excluded window/this.var, but not window/this.obj.prop
415 | # logging.warning(assignee.attributes['name'])
416 | if assignee.parent.attributes['computed']: # Access through a table, could be an index
417 | assignment_df(identifier_node=assignee, var_loc=var_loc, var_glob=var_glob,
418 | unknown_var=unknown_var)
419 | else:
420 | if call_expr:
421 | if (get_pos_identifier(assignee, var_loc) is not None
422 | or get_pos_identifier(assignee, var_glob) is not None):
423 | # Only if the obj assignee already defined, avoids DF on console.log
424 | var_decl_df(node=assignee, var_loc=var_loc, var_glob=var_glob, assignt=True,
425 | obj=True, entry=entry, unknown_var=unknown_var)
426 | else:
427 | var_decl_df(node=assignee, var_loc=var_loc, var_glob=var_glob, assignt=True,
428 | obj=True, entry=entry, unknown_var=unknown_var)
429 | else: # assignee is a variable
430 | var_decl_df(node=assignee, var_loc=var_loc, var_glob=var_glob, assignt=True,
431 | entry=entry, unknown_var=unknown_var)
432 |
433 | if 'operator' in assignee.parent.attributes:
434 | if assignee.parent.attributes['operator'] != '=': # Could be += where assignee is used
435 | assignment_df(identifier_node=assignee, var_loc=var_loc, var_glob=var_glob,
436 | unknown_var=unknown_var)
437 |
438 | if not identifiers:
439 | logging.warning('No identifier assignee found')
440 |
441 | for i in range(1, len(node.children)):
442 | var_loc = build_dfg(node.children[i], var_loc, var_glob, unknown_var=unknown_var,
443 | id_list=id_list, entry=entry)
444 | """
445 | identifiers = search_identifiers(node.children[1], id_list, tab=[])
446 | for assignt in identifiers:
447 | id_list.append(assignt.id)
448 | assignment_df(identifier_node=assignt, var_loc=var_loc, var_glob=var_glob)
449 | """
450 | return var_loc
451 |
452 |
453 | def update_expr_df(node, var_loc, var_glob, unknown_var, id_list, entry):
454 | """
455 | Handles the node UpdateExpression:
456 | # Element0: argument
457 |
458 | -------
459 | Parameters:
460 | - node: Node
461 | Node whose name should be VariableDeclarator.
462 | - var_loc: VarList
463 | Stores the variables currently declared and where they should be referred to.
464 | - var_glob: VarList
465 | Stores the global variables currently declared and where they should be referred to.
466 | - unknown_var: list
467 | Contains the variables currently not defined (could be valid because of hosting,
468 | therefore we check them later again).
469 | - id_list: list
470 | Stores the id of the node already handled.
471 | - entry: int
472 | Indicates if we are in the global scope (1) or not (0).
473 | """
474 |
475 | arguments = search_identifiers(node.children[0], id_list, tab=[])
476 | for argument in arguments:
477 | # Variable used, modified, used to have 2 data dependencies, one on the original variable
478 | # and one of the variable modified that will be used after.
479 | assignment_df(identifier_node=argument, var_loc=var_loc, var_glob=var_glob,
480 | unknown_var=unknown_var)
481 | var_decl_df(node=argument, var_loc=var_loc, var_glob=var_glob, unknown_var=unknown_var,
482 | assignt=True, entry=entry)
483 | assignment_df(identifier_node=argument, var_loc=var_loc, var_glob=var_glob,
484 | unknown_var=unknown_var)
485 |
486 | if not arguments:
487 | logging.warning('No identifier assignee found')
488 |
489 |
490 | def identifier_update(node, var_loc, var_glob, unknown_var, id_list, entry):
491 | """
492 | Adds data flow dependency to the considered node.
493 | -------
494 | Parameters:
495 | - node: Node
496 | Current node.
497 | - var_loc: VarList
498 | Stores the variables currently declared and where they should be referred to.
499 | - var_glob: VarList
500 | Stores the global variables currently declared and where they should be referred to.
501 | - unknown_var: list
502 | Contains the variables currently not defined (could be valid because of hosting,
503 | therefore we check them later again).
504 | - id_list: list
505 | Stores the id of the node already handled.
506 | - entry: int
507 | Indicates if we are in the global scope (1) or not (0).
508 | """
509 |
510 | identifiers = search_identifiers(node, id_list, rec=False, tab=[])
511 | # rec=False so as to not get the same Identifier multiple times by going through its family.
512 | for identifier in identifiers:
513 | if identifier.parent.name == 'CatchClause': # As an identifier can be used as a parameter
514 | # Ex: catch(err) {}, err has to be defined here
515 | var_decl_df(node=node, var_loc=var_loc, var_glob=var_glob, unknown_var=unknown_var,
516 | entry=entry)
517 | else:
518 | assignment_df(identifier_node=identifier, var_loc=var_loc, var_glob=var_glob,
519 | unknown_var=unknown_var)
520 |
521 |
522 | def search_function_expression(node, tab):
523 | """ Seaches the FunctionExpression nodes descendant of node. """
524 |
525 | if node.name == 'FunctionExpression':
526 | tab.append(node)
527 | else:
528 | for child in node.children:
529 | search_function_expression(child, tab)
530 | return tab
531 |
532 |
533 | def link_fun_expr(node):
534 | """
535 | Make the link between a function expression and the variable where it may be stored.
536 |
537 | -------
538 | Parameter:
539 | - node: Node
540 | FunctionExpression node.
541 |
542 | -------
543 | Returns:
544 | - Node
545 | Variable referring to the function expression.
546 | """
547 |
548 | fun_expr_node = node
549 |
550 | while node.name != 'VariableDeclarator' and node.name != 'AssignmentExpression'\
551 | and node.name != 'Property' and node.name != 'Program':
552 | if node.name == 'CallExpression':
553 | break # To avoid e.g. assigning a to ex, var ex = fun(function(a) {return a});
554 | node = node.parent
555 |
556 | if node.name == 'VariableDeclarator' or node.name == 'AssignmentExpression'\
557 | or node.name == 'Property':
558 | variables = search_identifiers(node.children[0], id_list=[], tab=[])
559 |
560 | functions = search_function_expression(node.children[1], tab=[])
561 |
562 | for i, _ in enumerate(functions):
563 | if fun_expr_node.id == functions[i].id:
564 | node_nb = i # Position of the function expression name in the function_names list
565 | break
566 |
567 | if 'node_nb' in locals():
568 | if len(variables) != len(functions):
569 | logging.warning('Trying to map %s FunctionExpression nodes to %s '
570 | + 'VariableDecaration nodes',
571 | str(len(functions)), str(len(variables)))
572 | else:
573 | fun_expr_def = variables[node_nb] # Variable storing the function expression
574 | anonym = True
575 | for child in fun_expr_node.children:
576 | if child.body == 'id':
577 | logging.debug('The variable %s refers to the function expression %s',
578 | fun_expr_def.attributes['name'], child.attributes['name'])
579 | anonym = False
580 | elif anonym:
581 | logging.debug('The variable %s refers to an anonymous function ',
582 | fun_expr_def.attributes['name'])
583 | anonym = False
584 | return fun_expr_def
585 | return None
586 |
587 |
588 | def hoisting(node, unknown_var):
589 | """
590 | Checks if unknown variables are in fact function names which were hoisted.
591 |
592 | -------
593 | Parameters:
594 | - node: Node
595 | Node corresponding to a function's name.
596 | - unknown_var: list
597 | Contains the variables currently not defined (could be valid because of hosting,
598 | therefore we check them later again).
599 | """
600 |
601 | unknown_var_copy = copy.copy(unknown_var)
602 | for unknown in unknown_var_copy:
603 | if node.attributes['name'] == unknown.attributes['name']:
604 | logging.debug('Using hoisting, the function %s was first used, then defined',
605 | node.attributes['name'])
606 | get_nearest_statement(node).set_data_dependency(extremity=get_nearest_statement(
607 | unknown), begin=node, end=unknown)
608 | unknown_var.remove(unknown)
609 |
610 |
611 | def function_scope(node, var_loc, var_glob, unknown_var, id_list, fun_expr):
612 | """
613 | Function scope for local variables.
614 |
615 | -------
616 | Parameters:
617 | - node: Node
618 | Current node.
619 | - var_loc: VarList
620 | Stores the variables currently declared and where they should be referred to.
621 | - var_glob: VarList
622 | Stores the global variables currently declared and where they should be referred to.
623 | - unknown_var: list
624 | Contains the variables currently not defined (could be valid because of hosting,
625 | therefore we check them later again).
626 | - id_list: list
627 | Stores the id of the node already handled.
628 | - fun_expr: bool
629 | Indicates if we handle a function declaration or expression. In the expression case,
630 | the function cannot be called from an outer scope.
631 |
632 | -------
633 | Returns:
634 | - VarList
635 | Variables declared and where they should be referred to before entering the function.
636 | """
637 |
638 | out_var_list = var_loc.copy_var_list() # save var_loc before
639 | # use it in the function scope
640 | for child in node.children:
641 | if child.body == 'id' or child.body == 'params':
642 | identifiers = search_identifiers(child, id_list, tab=[])
643 | for param in identifiers:
644 | id_list.append(param.id)
645 | if child.body == 'id' and not fun_expr:
646 | # Stores the function name, so that it can be used in the upper scope
647 | # out_var_list.add_var(child, fun=True)
648 | var_decl_df(node=param, var_loc=out_var_list, var_glob=var_glob,
649 | unknown_var=unknown_var, entry=0)
650 | var_loc = out_var_list.copy_var_list() # to know the function name in the func
651 | hoisting(param, unknown_var)
652 | else:
653 | var_decl_df(node=param, var_loc=var_loc, var_glob=var_glob,
654 | unknown_var=unknown_var, entry=0)
655 |
656 | else:
657 | var_loc = build_dfg(child, var_loc=var_loc, var_glob=var_glob, unknown_var=unknown_var,
658 | id_list=id_list, entry=0)
659 |
660 | if fun_expr:
661 | link_fun_expr(node)
662 | # fun_expr_var = link_fun_expr(node)
663 | # if fun_expr_var is not None:
664 | # hoisting(fun_expr_var, unknown_var) # Hoisting only for FunctionDeclaration
665 |
666 | limit_scope(var_loc=var_loc)
667 |
668 | return out_var_list # back to the old var_loc.var_list when we are not in the function anymore
669 |
670 |
671 | def obj_expr_scope(node, var_loc, var_glob, unknown_var, id_list):
672 | """
673 | ObjectExpression scope for local variables.
674 |
675 | -------
676 | Parameters:
677 | - node: Node
678 | Current node.
679 | - var_loc: VarList
680 | Stores the variables currently declared and where they should be referred to.
681 | - var_glob: VarList
682 | Stores the global variables currently declared and where they should be referred to.
683 | - unknown_var: list
684 | Contains the variables currently not defined (could be valid because of hosting,
685 | therefore we check them later again).
686 | - id_list: list
687 | Stores the id of the node already handled.
688 |
689 | -------
690 | Returns:
691 | - VarList
692 | Variables declared and where they should be referred to before entering the function.
693 | """
694 |
695 | out_var_list = var_loc.copy_var_list() # save var_loc before
696 | # use it in the object scope
697 | for prop in node.children:
698 | for child in prop.children:
699 | if child.body == 'key':
700 | identifiers = search_identifiers(child, id_list, tab=[])
701 | for param in identifiers:
702 | id_list.append(param.id)
703 | var_decl_df(node=param, var_loc=var_loc, var_glob=var_glob,
704 | unknown_var=unknown_var, entry=0)
705 | hoisting(param, unknown_var)
706 |
707 | else:
708 | var_loc = build_dfg(child, var_loc=var_loc, var_glob=var_glob,
709 | unknown_var=unknown_var, id_list=id_list, entry=0)
710 |
711 | limit_scope(var_loc=var_loc)
712 |
713 | return out_var_list # back to the old var_loc.var_list when we are not in the object anymore
714 |
715 |
716 | def boolean_cf_dep(node_list, var_loc, var_glob, unknown_var, id_list, entry):
717 | """
718 | Statement scope for boolean conditions.
719 |
720 | -------
721 | Parameters:
722 | - node_list: list of Nodes
723 | Current nodes to be handled.
724 | - var_loc: VarList
725 | Stores the variables currently declared and where they should be referred to.
726 | - var_glob: VarList
727 | Stores the global variables currently declared and where they should be referred to.
728 | - unknown_var: list
729 | Contains the variables currently not defined (could be valid because of hosting,
730 | therefore we check them later again).
731 | - id_list: list
732 | Stores the id of the node already handled.
733 | - entry: int
734 | Indicates if we are in the global scope (1) or not (0).
735 |
736 | -------
737 | Returns:
738 | - var_loc
739 | In its input state.
740 |
741 | - SwitchCase: several True possible
742 | """
743 |
744 | temp_list_loc = var_loc.copy_var_list()
745 | temp_list_glob = var_glob.copy_var_list()
746 |
747 | for boolean_node in node_list:
748 | # var_loc.var_list modified for the branch
749 | var_loc = build_dfg(boolean_node, var_loc=var_loc, var_glob=var_glob,
750 | unknown_var=unknown_var, id_list=id_list, entry=entry)
751 |
752 | return [temp_list_loc, temp_list_glob, var_loc] # returns the initial variables list + var_loc
753 |
754 |
755 | def merge_var_boolean_cf(var_list_before_cond, var_list_true, var_list_false):
756 | """
757 | Merges in var_list_true the variables declared on a true and false branches.
758 |
759 | -------
760 | Parameters:
761 | - var_list_before_cond: VarList
762 | Stores the variables declared before entering any conditions and where they should be
763 | referred to.
764 | - var_list_true: VarList
765 | Stores the variables currently declared if cond = true and where they should be
766 | referred to.
767 | - var_list_false: VarList
768 | Stores the variables currently declared if cond = false and where they should be
769 | referred to.
770 | """
771 |
772 | # display_temp('True', var_list_true)
773 | # display_temp('False', var_list_false)
774 | for node_false in var_list_false.var_list:
775 | if not any(node_false.attributes['name'] == node_true.attributes['name']
776 | for node_true in var_list_true.var_list):
777 | logging.debug('The variable %s was added to the list', node_false.attributes['name'])
778 | var_list_true.add_var(node_false)
779 | for node_true in var_list_true.var_list:
780 | if node_false.attributes['name'] == node_true.attributes['name']\
781 | and node_false.id != node_true.id: # The variable was modified in >=1 branch
782 | var_index = get_pos_identifier(node_true, var_list_true)
783 | if any(node_true.id == node.id for node in var_list_before_cond.var_list):
784 | logging.debug('The variable %s has been modified in the branch False',
785 | node_false.attributes['name'])
786 | var_list_true.update_var(var_index, node_false)
787 | elif any(node_false.id == node.id for node in var_list_before_cond.var_list):
788 | logging.debug('The variable %s has been modified in the branch True',
789 | node_true.attributes['name'])
790 | # Already handled, as we work on var_list_true
791 | else: # Both were modified, we refer to the nearest common statement
792 | logging.debug('The variable %s has been modified in the branches True and '
793 | + 'False', node_false.attributes['name'])
794 | # var_list_true.update_el_ref(var_index,
795 | # get_nearest_common_statement(node_true, node_false))
796 | var_list_true.update_el_ref(var_index, [node_true, node_false])
797 |
798 |
799 | def display_temp(title, temp):
800 | """ Display known variable's name. """
801 |
802 | print(title)
803 | for el in temp.var_list:
804 | print(el.attributes['name'])
805 | # print(el.id)
806 |
807 |
808 | def statement_scope(node, var_loc, var_glob, unknown_var, id_list, entry):
809 | """
810 | Statement scope.
811 |
812 | -------
813 | Parameters:
814 | - node: Node
815 | Current node.
816 | - var_loc: VarList
817 | Stores the variables currently declared and where they should be referred to.
818 | - var_glob: VarList
819 | Stores the global variables currently declared and where they should be referred to.
820 | - unknown_var: list
821 | Contains the variables currently not defined (could be valid because of hosting,
822 | therefore we check them later again).
823 | - id_list: list
824 | Stores the id of the node already handled.
825 | - entry: int
826 | Indicates if we are in the global scope (1) or not (0).
827 | """
828 |
829 | todo_true = []
830 | todo_false = []
831 |
832 | # Statements that do belong after one another
833 | for child_statement_dep in node.statement_dep_children:
834 | child_statement = child_statement_dep.extremity
835 | logging.debug('The node %s has a statement dependency', child_statement.name)
836 | var_loc = build_dfg(child_statement, var_loc=var_loc, var_glob=var_glob,
837 | unknown_var=unknown_var, id_list=id_list, entry=entry)
838 |
839 | for child_cf_dep in node.control_dep_children: # Control flow statements
840 | child_cf = child_cf_dep.extremity
841 | if isinstance(child_cf_dep.label, bool): # Several branches according to the cond
842 | logging.debug('The node %s has a boolean CF dependency', child_cf.name)
843 | var_list_before_cond_loc = var_loc.copy_var_list()
844 | var_list_before_cond_glob = var_glob.copy_var_list()
845 | if child_cf_dep.label:
846 | todo_true.append(child_cf) # In reality does not contain only true variables
847 | else:
848 | todo_false.append(child_cf)
849 |
850 | else: # Epsilon statements
851 | logging.debug('The node %s has an epsilon CF dependency', child_cf.name)
852 | var_loc = build_dfg(child_cf, var_loc=var_loc, var_glob=var_glob,
853 | unknown_var=unknown_var, id_list=id_list, entry=entry)
854 |
855 | # Separate variables if separate true/false branches
856 | [var_list_temp_loc, var_list_temp_glob, var_loc] = boolean_cf_dep(todo_true, var_loc=var_loc,
857 | var_glob=var_glob,
858 | unknown_var=unknown_var,
859 | id_list=id_list, entry=entry)
860 | [_, _, var_list_temp_loc] = boolean_cf_dep(todo_false, var_loc=var_list_temp_loc,
861 | var_glob=var_list_temp_glob, unknown_var=unknown_var,
862 | id_list=id_list, entry=entry)
863 |
864 | if not var_loc.is_equal(var_list_temp_loc): # Here we have
865 | # var_loc: variables declared in a branch when the condition was true
866 | # var_list_temp_loc: variables declared in a branch when the condition was false
867 | merge_var_boolean_cf(var_list_before_cond_loc, var_loc, var_list_temp_loc)
868 | # Finally var_loc contains all variables defined in the true + false branches
869 |
870 | if not var_glob.is_equal(var_list_temp_glob): # Here we have
871 | # var_glob: variables declared in a branch when the condition was true
872 | # var_list_temp_glob: variables declared in a branch when the condition was false
873 | merge_var_boolean_cf(var_list_before_cond_glob, var_glob, var_list_temp_glob)
874 | # Finally var_glob contains all variables defined in the true + false branches
875 |
876 | limit_scope(var_loc=var_loc)
877 |
878 | return var_loc
879 |
880 |
881 | def build_df_variable_declaration(node, var_loc, var_glob, unknown_var, id_list, entry):
882 | """ VariableDeclaration data dependencies. """
883 |
884 | logging.debug('The node %s is a variable declaration', node.name)
885 | for child in node.children:
886 | var_loc = var_declaration_df(child, var_loc=var_loc, var_glob=var_glob,
887 | unknown_var=unknown_var, id_list=id_list, entry=entry)
888 | return var_loc
889 |
890 |
891 | def build_df_assignment(node, var_loc, var_glob, unknown_var, id_list, entry):
892 | """ AssignmentExpression data dependencies. """
893 |
894 | logging.debug('The node %s is an assignment expression', node.name)
895 | var_loc = assignment_expr_df(node, var_loc=var_loc, var_glob=var_glob,
896 | unknown_var=unknown_var, id_list=id_list, entry=entry)
897 | return var_loc
898 |
899 |
900 | def build_df_call_expr(node, var_loc, var_glob, unknown_var, id_list, entry):
901 | """ CallExpression on object data dependencies. """
902 |
903 | logging.debug('The node %s is a call expression on an object', node.name)
904 | var_loc = assignment_expr_df(node, var_loc=var_loc, var_glob=var_glob, unknown_var=unknown_var,
905 | id_list=id_list, entry=entry, call_expr=True)
906 | return var_loc
907 |
908 |
909 | def build_df_update(node, var_loc, var_glob, unknown_var, id_list, entry):
910 | """ UpdateExpression data dependencies. """
911 |
912 | logging.debug('The node %s is an update expression', node.name)
913 | update_expr_df(node, var_loc=var_loc, var_glob=var_glob, unknown_var=unknown_var,
914 | id_list=id_list, entry=entry)
915 |
916 |
917 | def build_df_function(node, var_loc, var_glob, unknown_var, id_list, fun_expr=False):
918 | """ FunctionDeclaration and FunctionExpression data dependencies. """
919 |
920 | logging.debug('The node %s is a function declaration', node.name)
921 | return function_scope(node=node, var_loc=var_loc, var_glob=var_glob, unknown_var=unknown_var,
922 | id_list=id_list, fun_expr=fun_expr)
923 |
924 |
925 | def build_df_statement(node, var_loc, var_glob, unknown_var, id_list, entry):
926 | """ Statement (statement, epsilon, boolean) data dependencies. """
927 |
928 | logging.debug('The node %s is a statement', node.name)
929 | return statement_scope(node=node, var_loc=var_loc, var_glob=var_glob,
930 | unknown_var=unknown_var, id_list=id_list, entry=entry)
931 |
932 |
933 | def build_df_identifier(node, var_loc, var_glob, unknown_var, id_list, entry):
934 | """ Identifier data dependencies. """
935 |
936 | if node.id not in id_list:
937 | logging.debug('The variable %s has not been handled yet', node.attributes['name'])
938 | identifier_update(node, var_loc=var_loc, var_glob=var_glob, unknown_var=unknown_var,
939 | id_list=id_list, entry=entry)
940 | else:
941 | logging.debug('The variable %s has already been handled', node.attributes['name'])
942 |
943 |
944 | def build_dfg(child, var_loc, var_glob, unknown_var, id_list, entry):
945 | """
946 | Data dependency for a given node whatever it is.
947 |
948 | -------
949 | Parameters:
950 | - child: Node
951 | Current node to be handled.
952 | - var_loc: VarList
953 | Stores the variables currently declared and where they should be referred to.
954 | - var_glob: VarList
955 | Stores the global variables currently declared and where they should be referred to.
956 | - unknown_var: list
957 | Contains the variables currently not defined (could be valid because of hosting,
958 | therefore we check them later again).
959 | - id_list: list
960 | Stores the id of the node already handled.
961 | - entry: int
962 | Indicates if we are in the global scope (1) or not (0).
963 |
964 | -------
965 | Returns:
966 | - list
967 | Variables currently declared.
968 | """
969 |
970 | if child.name == 'VariableDeclaration':
971 | if child.attributes['kind'] != 'var': # let or const
972 | if not var_loc.limited_scope.before_limit_list: # If before_list is empty
973 | var_loc.set_before_limit_list(var_loc.var_list) # We fill it
974 | # Otherwise it stays as it is
975 |
976 | var_loc = build_df_variable_declaration(child, var_loc=var_loc, var_glob=var_glob,
977 | unknown_var=unknown_var, id_list=id_list,
978 | entry=entry)
979 | var_loc.set_limit(True) # To limit the visibility only to the upper block
980 | for node in var_loc.var_list:
981 | # If we have a node that is not in the before_list and has not been handled yet
982 | if not any(node.id == before_node.id for before_node
983 | in var_loc.limited_scope.before_limit_list)\
984 | and not any(node.id == after_node.id for after_node
985 | in var_loc.limited_scope.after_limit_list):
986 | logging.debug('The variable %s has a limited scope', node.attributes['name'])
987 | var_loc.add_el_limit_list(node) # Add to after_list
988 | else:
989 | var_loc = build_df_variable_declaration(child, var_loc=var_loc, var_glob=var_glob,
990 | unknown_var=unknown_var, id_list=id_list,
991 | entry=entry)
992 |
993 | elif child.name == 'AssignmentExpression':
994 | var_loc = build_df_assignment(child, var_loc=var_loc, var_glob=var_glob,
995 | unknown_var=unknown_var, id_list=id_list, entry=entry)
996 |
997 | elif (child.name == 'CallExpression' and child.children[0].name == 'MemberExpression'
998 | and child.children[0].children[0].name != 'ThisExpression'
999 | and 'window' not in child.children[0].children[0].attributes.values())\
1000 | or (child.name == 'CallExpression' and child.children[0].name == 'MemberExpression'
1001 | and child.children[0].parent.name == 'MemberExpression'):
1002 | var_loc = build_df_call_expr(child, var_loc=var_loc, var_glob=var_glob,
1003 | unknown_var=unknown_var, id_list=id_list, entry=entry)
1004 |
1005 | elif child.name == 'UpdateExpression':
1006 | build_df_update(child, var_loc=var_loc, var_glob=var_glob, unknown_var=unknown_var,
1007 | id_list=id_list, entry=entry)
1008 |
1009 | elif child.name == 'FunctionDeclaration':
1010 | var_loc = build_df_function(child, var_loc=var_loc, var_glob=var_glob,
1011 | unknown_var=unknown_var, id_list=id_list)
1012 |
1013 | elif child.name == 'FunctionExpression':
1014 | var_loc = build_df_function(child, var_loc=var_loc, var_glob=var_glob,
1015 | unknown_var=unknown_var, id_list=id_list, fun_expr=True)
1016 |
1017 | elif child.is_statement():
1018 | var_loc = build_df_statement(child, var_loc=var_loc, var_glob=var_glob,
1019 | unknown_var=unknown_var, id_list=id_list, entry=entry)
1020 |
1021 | elif child.name == 'ObjectExpression': # Only consider the object name, no properties
1022 | var_loc = obj_expr_scope(child, var_loc=var_loc, var_glob=var_glob, unknown_var=unknown_var,
1023 | id_list=id_list)
1024 |
1025 | elif child.name == 'Identifier':
1026 | build_df_identifier(child, var_loc=var_loc, var_glob=var_glob, unknown_var=unknown_var,
1027 | id_list=id_list, entry=entry)
1028 |
1029 | else:
1030 | var_loc = df_scoping(child, var_loc=var_loc, var_glob=var_glob, unknown_var=unknown_var,
1031 | id_list=id_list)[1]
1032 | # display_temp('> Local: ', var_loc)
1033 | # display_temp('> Global: ', var_glob)
1034 |
1035 | return var_loc
1036 |
1037 |
1038 | def df_scoping(cfg_nodes, var_loc, var_glob, unknown_var, id_list, entry=0):
1039 | """
1040 | Data dependency for a complete CFG.
1041 |
1042 | -------
1043 | Parameters:
1044 | - cfg_nodes: Node
1045 | Output of produce_cfg(ast_to_ast_nodes(, ast_nodes=Node('Program'))).
1046 | - var_loc: VarList
1047 | Stores the variables currently declared and where they should be referred to.
1048 | - var_glob: VarList
1049 | Stores the global variables currently declared and where they should be referred to.
1050 | - unknown_var: list
1051 | Contains the variables currently not defined (could be valid because of hosting,
1052 | therefore we check them later again).
1053 | - id_list: list
1054 | Stores the id of the node already handled.
1055 | - entry: int
1056 | Indicates if we are in the global scope (1) or not (0). Default: 0.
1057 |
1058 | -------
1059 | Returns:
1060 | - Node
1061 | With data flow dependencies added.
1062 | """
1063 |
1064 | for child in cfg_nodes.children:
1065 | var_loc = build_dfg(child, var_loc=var_loc, var_glob=var_glob, unknown_var=unknown_var,
1066 | id_list=id_list, entry=entry)
1067 | return [cfg_nodes, var_loc]
1068 |
--------------------------------------------------------------------------------
/src/clone_detection.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2020 Aurore Fass
2 | # This program is free software: you can redistribute it and/or modify
3 | # it under the terms of the GNU Affero General Public License as published by
4 | # the Free Software Foundation, either version 3 of the License, or
5 | # (at your option) any later version.
6 |
7 | # This program is distributed in the hope that it will be useful,
8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | # GNU Affero General Public License for more details.
11 |
12 | # You should have received a copy of the GNU Affero General Public License
13 | # along with this program. If not, see .
14 |
15 | """
16 | 2. Find all clones.
17 | """
18 |
19 | from equivalence_classes import *
20 | from clone_metric import *
21 |
22 |
23 | LEAF_STATEMENTS = ['BreakStatement', 'ContinueStatement']
24 |
25 |
26 | def data_or_control(node, label):
27 | """ Return the node statement, data or control dependencies. Parents or children."""
28 |
29 | if label == 'statement':
30 | return node.statement_dep_children
31 | if label == 'control_c':
32 | return node.control_dep_children
33 | if label == 'control':
34 | return node.control_dep_parents
35 | if label == 'data':
36 | return node.data_dep_parents
37 | logging.error('Expected \'data\' or \'control\', got %s instead', label)
38 | return None
39 |
40 |
41 | def traverse(node, tab):
42 | """ Traverses a node and stores its descendants.
43 | Can be responsible for a stack overflow. Did not find a solution yet and
44 | traverse_statement_node is too incomplete. """
45 |
46 | for child in node.children:
47 | if not child.is_comment():
48 | tab.append(child)
49 | traverse(child, tab)
50 | return tab
51 |
52 |
53 | def handle_statement_node(node, non_statement_list, label):
54 | """
55 | Traverses a Statement node by following the statement / control dependencies.
56 | Idea: to detect clones we are working at the statement level. Therefore we add to the list
57 | all the nodes that belong to the considered node (statement dependencies). For example, an
58 | IfStatement node HAS to be stored together with its condition. The ensemble represents the
59 | IfStatement. The body on the other hand is linked by a CF dependency and will be handled
60 | somewhere else.
61 |
62 | -------
63 | Parameters:
64 | - node: Node
65 | Node to be traversed.
66 | - non_statement_list: list
67 | Contains the nodes traversed so far.
68 | - label: 'data' or 'control'
69 | Indicates if we are handling data or control dependencies.
70 | """
71 |
72 | for child_cf_dep in data_or_control(node, label):
73 | child_cf = child_cf_dep.extremity
74 | non_statement_list.append(child_cf)
75 | traverse_statement_node(child_cf, non_statement_list, init=0)
76 |
77 |
78 | def traverse_statement_node(node, non_statement_list, init=1):
79 | """
80 | Traverses a Statement node by following the statement dependencies. Also considers CF
81 | dependencies if there is a direct parent with a statement dependency.
82 |
83 | -------
84 | Parameters:
85 | - node: Node
86 | Node to be traversed.
87 | - non_statement_list: list
88 | Contains the nodes traversed so far.
89 | - init: 1 or 0
90 | Indicates if this is the first time (1) that the algorithm is run. Default: 1.
91 |
92 | -------
93 | Returns:
94 | - list
95 | Contains the type (Node.name) of the nodes traversed in node.
96 | """
97 |
98 | handle_statement_node(node, non_statement_list, label='statement')
99 | if init == 0:
100 | # Only if the nodes here are linked with a statement flow to their parent
101 | handle_statement_node(node, non_statement_list, label='control_c')
102 | return non_statement_list
103 |
104 |
105 | def search_handled_nodes(node1, node2, all_clones_list):
106 | """
107 | Searches the nodes that have already been handled, so as not to do backward slicing again.
108 |
109 | -------
110 | Parameters:
111 | - node1: Node
112 | Statement node 1.
113 | - node2: Node
114 | Statement node 2.
115 | - all_clones_list: list of BiList()
116 | Contains the clones that have already been found so far.
117 | """
118 |
119 | current_clone_list = all_clones_list[-1] # current clone list stored last
120 |
121 | for i, _ in enumerate(current_clone_list.list1):
122 | if current_clone_list.list1[i].parent.id == node1.id\
123 | and current_clone_list.list2[i].parent.id == node2.id:
124 | # Case where a node n is a clone and its parent n-1 too. We just store n-1 to avoid
125 | # duplicate (as n is in n-1)
126 | logging.debug(current_clone_list.list1[i].name + ' is a descendant of ' + node1.name)
127 | del current_clone_list.list1[i]
128 | del current_clone_list.list2[i]
129 | current_clone_list.append_list(node1, node2) # Otherwise: new pair of clones
130 | follow_dependencies(node1, node2, all_clones_list)
131 |
132 |
133 | def find_clones(node1, node2, all_clones_list, tab_handled, jump=0, jump_match=0):
134 | """
135 | Compare two statement nodes. We consider that they are equal (return True) iff:
136 | - they have the same type (referred to as Node.name);
137 | - they have the same statement dependencies till the leaf;
138 | - they have the same control dependencies till the leaf; beware we consider only control
139 | dependencies that originated from a statement dependency. Otherwise CF are handled
140 | somewhere else;
141 | - they have the same number of dependencies.
142 |
143 | -------
144 | Parameters:
145 | - node1: Node
146 | Statement node 1.
147 | - node2: Node
148 | Statement node 2.
149 | - all_clones_list: list of BiList()
150 | Contains the clones that have already been found so far.
151 | - tab_handled: list
152 | Contains the node id which have already been handled/jumped over. Use case: when no
153 | match can be found, we do backward slicing on the benign node to try to find a match.
154 | - jump: int
155 | Jumps over a sibling DD. Default: 0.
156 | - jump_match: int
157 | Jumps over a sibling DD and matches. Default: 0.
158 | """
159 |
160 | if node1.name == node2.name:
161 | belongs_node1 = traverse(node1, tab=[])
162 | belongs_node2 = traverse(node2, tab=[])
163 |
164 | if [elt1.name for elt1 in belongs_node1] == [elt2.name for elt2 in belongs_node2]:
165 | logging.debug('Clone found at the ' + node1.name + ' level, between node id '
166 | + str(node1.id) + ' and ' + str(node2.id))
167 |
168 | if jump_match > 0:
169 | # 3 - The clones are independent and should not be stored together
170 | current_clone_list = all_clones_list[-1] # current clone list stored last
171 | current_clone_list_copy = current_clone_list.copy_list()
172 | del current_clone_list_copy.list1[-1]
173 | del current_clone_list_copy.list2[-1]
174 | # 4 - Still, we keep the clones history
175 | all_clones_list.append(current_clone_list_copy)
176 | tab_handled.append(str(node1.id) + '_' + str(node2.id))
177 | search_handled_nodes(node1, node2, all_clones_list)
178 |
179 | if jump != 0:
180 | # 2 - and we have a match
181 | jump_match += 1
182 | return [jump, jump_match]
183 |
184 | for parent_f1_dep in data_or_control(node1, 'data'): # Jump over benign DD if not match found
185 | jump += 1 # 1 - If the loop is iterated several times
186 | parent_f1 = parent_f1_dep.extremity
187 | if str(parent_f1.id) + '_' + str(node2.id) not in tab_handled:
188 | logging.debug('Jump over a data dependency of the benign file, to test the benign node '
189 | + str(parent_f1.id) + ' with the malicious ' + str(node2.id))
190 | tab_handled.append(str(parent_f1.id) + '_' + str(node2.id))
191 | [jump, jump_match] = find_clones(parent_f1, node2, all_clones_list, tab_handled, jump,
192 | jump_match)
193 | return [jump, jump_match]
194 |
195 |
196 | def follow_dependency(node1, node2, label, all_clones_list):
197 | """
198 | Given two statement nodes, does backward slicing to find clones.
199 |
200 | -------
201 | Parameters:
202 | - node1: Node
203 | Statement node 1.
204 | - node2: Node
205 | Statement node 2.
206 | - label: 'data' or 'control'
207 | Indicates if we are handling data or control dependencies.
208 | - all_clones_list: list of BiList()
209 | Contains the clones that have already been found so far.
210 | """
211 |
212 | for parent_f1_dep in data_or_control(node1, label):
213 | parent_f1 = parent_f1_dep.extremity
214 | if node1.id != parent_f1_dep.extremity.id: # To avoid infinite loops if DD on oneself
215 | for parent_f2_dep in data_or_control(node2, label):
216 | parent_f2 = parent_f2_dep.extremity
217 | if node2.id != parent_f2_dep.extremity.id: # To avoid infinite loops
218 | find_clones(parent_f1, parent_f2, all_clones_list, tab_handled=[])
219 |
220 |
221 | def follow_dependencies(node1, node2, all_clones_list):
222 | """
223 | Given two statement nodes, does backward slicing to find clones.
224 |
225 | -------
226 | Parameters:
227 | - node1: Node
228 | Statement node 1.
229 | - node2: Node
230 | Statement node 2.
231 | - all_clones_list: list of BiList()
232 | Contains the clones that have already been found so far.
233 | """
234 |
235 | follow_dependency(node1, node2, 'control', all_clones_list)
236 | follow_dependency(node1, node2, 'data', all_clones_list)
237 |
238 | """
239 | if node1.name != 'Program' and node2.name != 'Program':
240 | if node1.parent.name == 'Program' or node2.parent.name == 'Program':
241 | find_clones(node1.parent, node2.parent, all_clones_list)
242 | """
243 |
244 |
245 | def annotate_clone(all_clones_list, res_dict):
246 | """
247 | Sets the nodes' clone attribute to true, when the nodes are in a clone.
248 |
249 | -------
250 | Parameter:
251 | - all_clones_list: list of BiList()
252 | Contains the clones that have been found.
253 | - res_dict: dict
254 | Contains the different results obtained so far.
255 | """
256 |
257 | res_dict['similar'] = list()
258 | for clone in all_clones_list:
259 | for node in clone.list1:
260 | node.set_clone_true()
261 | for child in traverse(node, tab=[]):
262 | child.set_clone_true()
263 | for node in clone.list2:
264 | node.set_clone_true()
265 | list_per_statement = list()
266 | if not node.is_comment():
267 | list_per_statement.append(node.name)
268 | for child in traverse(node, tab=[]):
269 | child.set_clone_true()
270 | if not child.is_comment():
271 | list_per_statement.append(child.name)
272 | res_dict['similar'].append(list_per_statement)
273 |
274 |
275 | def find_all_clones(dfg_nodes1, dfg_nodes2):
276 | """
277 | Given an EquivalenceClass object, tests all the nodes with one another to detect clones.
278 |
279 | -------
280 | Parameters:
281 | - dfg_nodes1: Node
282 | PDG of the benign file.
283 | - dfg_nodes2: Node
284 | PDG of the malicious file.
285 |
286 | -------
287 | Returns:
288 | - list of BiList()
289 | Contains the groups of clones, after duplicate deletion, found at the end.
290 | """
291 |
292 | equivalence_classes = get_equivalence_classes(dfg_nodes1, dfg_nodes2, equivalence_classes={})
293 | all_clones_list, tab_handled = [], []
294 | for equivalence_class in equivalence_classes.values():
295 | for node2 in equivalence_class.list2:
296 | for node1 in equivalence_class.list1:
297 | all_clones_list.append(BiList())
298 | find_clones(node1, node2, all_clones_list, tab_handled=tab_handled)
299 | if all_clones_list[-1].is_empty():
300 | all_clones_list.remove(all_clones_list[-1])
301 | # print_clones(all_clones_list)
302 | return all_clones_list
303 |
304 |
305 | def dissimilar(malicious_node, res_dict):
306 | if not malicious_node.clone:
307 | if not malicious_node.is_comment():
308 | res_dict['dissimilar'].append(malicious_node.name)
309 | for child in malicious_node.children:
310 | dissimilar(child, res_dict)
311 |
312 |
313 | def get_percentage_cloned_node(node, cloned=0, total=0):
314 | """
315 | Gets the number of nodes in node that are cloned of nodes in another PDG,
316 | as well as the total number of nodes.
317 |
318 | -------
319 | Parameters:
320 | - node: Node
321 | Current node to analyze.
322 | - cloned: int
323 | Number of cloned nodes.
324 | - total: int
325 | Total number of nodes.
326 |
327 | -------
328 | Returns:
329 | - list
330 | * Elt1: int, number of cloned nodes;
331 | * Elt2: int, total number of nodes.
332 | """
333 |
334 | for child in node.children:
335 | if child.clone:
336 | cloned += 1
337 | total += 1
338 | elif not child.is_comment():
339 | total += 1
340 | [cloned, total] = get_percentage_cloned_node(child, cloned=cloned, total=total)
341 | return [cloned, total]
342 |
343 |
344 | def get_percentage_cloned(dfg_nodes1, dfg_nodes2, res_dict):
345 | """
346 | Gets the percentage of the nodes in dfg_nodes1 that are in dfg_nodes2, and the contrary.
347 |
348 | -------
349 | Parameters:
350 | - dfg_nodes1: Node
351 | PDG of the benign file.
352 | - dfg_nodes2: Node
353 | PDG of the malicious file.
354 | - res_dict: dict
355 | Contains the different results obtained so far.
356 | """
357 |
358 | [clone1d, total1] = get_percentage_cloned_node(dfg_nodes1)
359 | [clone2d, total2] = get_percentage_cloned_node(dfg_nodes2)
360 |
361 | res_dict['%benign'] = [clone1d, total1]
362 | res_dict['%malicious'] = [clone2d, total2]
363 |
364 | """
365 | if (100 * clone2d / total2) > 90:
366 | print(str(100*clone1d/total1) + '% of ' + str(dfg_nodes1.id) + ' is in '
367 | + str(dfg_nodes2.id) + '. It represents ' + str(clone1d) + '/' + str(total1))
368 | print(str(100 * clone2d / total2) + '% of ' + str(dfg_nodes2.id) + ' is in '
369 | + str(dfg_nodes1.id) + '. It represents ' + str(clone2d) + '/' + str(total2))
370 | """
371 |
372 | return clone2d / total2
373 |
--------------------------------------------------------------------------------
/src/clone_metric.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2020 Aurore Fass
2 | # This program is free software: you can redistribute it and/or modify
3 | # it under the terms of the GNU Affero General Public License as published by
4 | # the Free Software Foundation, either version 3 of the License, or
5 | # (at your option) any later version.
6 |
7 | # This program is distributed in the hope that it will be useful,
8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | # GNU Affero General Public License for more details.
11 |
12 | # You should have received a copy of the GNU Affero General Public License
13 | # along with this program. If not, see .
14 |
15 | """
16 | 3. Define metric to deduplicate clones.
17 | For ethical reasons, we choose not to publish our complete code to select clones. Specifically, we:
18 | - still choose the largest clone and not a subsumed version of it;
19 | - still maximize the proportion of identical tokens between the benign and the crafted samples,
20 | but if they do not match, we do not suggest how to modify them for them to match;
21 | - do not minimize the distance between the nodes inside a clone (minimize_delta_between_clones).
22 |
23 | Also, and of course, we did not publish 4. Clone replacement.
24 | """
25 |
26 | from handle_json import *
27 |
28 |
29 | def search_literal(node, tab):
30 | """
31 | Searches the Literal nodes descendants of node.
32 | -------
33 | Parameters:
34 | - nodes: Node
35 | Current node to test.
36 | - tab: list
37 | Will contain the Literal nodes found.
38 |
39 | -------
40 | Returns:
41 | - list
42 | Stores the Literal nodes found.
43 | """
44 |
45 | if isinstance(node, list):
46 | for elt in node:
47 | search_literal(elt, tab)
48 | else:
49 | if node.name == 'Literal':
50 | tab.append(node)
51 | else:
52 | for child in node.children:
53 | search_literal(child, tab)
54 | return tab
55 |
56 |
57 | def print_clones(all_clones_list):
58 | """ Print the JS code of the clones detected. """
59 |
60 | my_json = 'my-json.json'
61 | print('==============')
62 | for el in all_clones_list:
63 | print(el.list1)
64 | for elt in el.list1:
65 | save_json(elt, my_json)
66 | get_code(my_json, test=True)
67 |
68 | print(el.list2)
69 | for elt in el.list2:
70 | save_json(elt, my_json)
71 | get_code(my_json, test=True)
72 | print('--')
73 | print('==============')
74 |
75 |
76 | def change_literal(all_clones_list, res_dict):
77 | """ Reports Tokens that do not match, while the ASTs matched. """
78 |
79 | for clone_list in all_clones_list:
80 | literal_list_mal = search_literal(clone_list.list2, tab=[])
81 | literal_list_ben = search_literal(clone_list.list1, tab=[])
82 |
83 | for i, _ in enumerate(literal_list_ben):
84 | literal_mal = literal_list_mal[i].literal_type()
85 | literal_ben = literal_list_ben[i].literal_type()
86 |
87 | if literal_mal != literal_ben:
88 | logging.info('The tokens of %s and %s do not match',
89 | literal_list_mal[i].attributes['raw'],
90 | literal_list_ben[i].attributes['raw'])
91 | res_dict['pb_tokens'].append([literal_mal, literal_ben])
92 |
93 | # Possible modifications suggested
94 |
95 |
96 | def same_tokens(all_clones_list, clone_list_a, clone_list_b, i, j):
97 | """
98 | Some clones can be found several times in a given file. As a metric, we would like two
99 | clones to share the same Tokens (since they already share an AST, the extra check is
100 | done on the Literals).
101 |
102 | -------
103 | Parameters:
104 | - all_clones_list: list of BiList()
105 | Contains the clones that have been found.
106 | - clone_list_a: list
107 | Corresponds to all the clones found in file A (when analyzed against file B).
108 | - clone_list_b: list
109 | Corresponds to all the clones found in file B (when analyzed against file A).
110 | - i, j: int
111 | Correspond to indexes such as clone_list_a[i] = clone_list_a[j].
112 |
113 | -------
114 | Returns:
115 | - list
116 | * Elt1: int, index to be tested next;
117 | * Elt2: int, index to be tested next.
118 | """
119 |
120 | logging.debug('A clone was found twice')
121 |
122 | tokens_a = [literal.literal_type() for literal in search_literal(clone_list_a[i], tab=[])]
123 | tokens_bi = [literal.literal_type() for literal in search_literal(clone_list_b[i], tab=[])]
124 | tokens_bj = [literal.literal_type() for literal in search_literal(clone_list_b[j], tab=[])]
125 |
126 | if tokens_a == tokens_bi and tokens_a == tokens_bj:
127 | logging.debug('The same tokens could be found twice')
128 | # No clones selection for the open source version
129 | # [i, j] = minimize_delta_between_clones(all_clones_list, clone_list_b, i, j)
130 | elif tokens_a == tokens_bi:
131 | logging.debug('The same tokens could be found')
132 | all_clones_list.remove(all_clones_list[j]) # To have the real index
133 | j -= 1 # Otherwise we miss an index, since j-old + 1 is now at position j-new
134 | elif tokens_a == tokens_bj:
135 | logging.debug('The same tokens could be found')
136 | all_clones_list.remove(all_clones_list[i]) # To have the real index
137 | i -= 1 # Otherwise we miss an index, since i-old + 1 is now at position i-new,
138 | # so i should not get i + 1
139 | j = i + 1 # Otherwise we miss indexes, as we get a new i value, j should be reset too
140 | else:
141 | logging.debug('The same tokens could not be found on this iteration')
142 | # No clones selection for the open source version
143 | # [i, j] = minimize_delta_between_clones(all_clones_list, clone_list_b, i, j)
144 |
145 | return [i, j]
146 |
147 |
148 | def remove_subsumed_clones(all_clones_list, clone_list1, clone_list2, i, j):
149 | """
150 | Some clones can be found several times in a given file. As a metric, we consider the
151 | biggest one and delete subsumed clones.
152 |
153 | -------
154 | Parameters:
155 | - all_clones_list: list of BiList()
156 | Contains the clones that have been found.
157 | - clone_list1: list
158 | Corresponds to all the clones found in the file 1 (when analyzed against file 2).
159 | - clone_list2: list
160 | Corresponds to all the clones found in the file 2 (when analyzed against file 1).
161 | - i, j: int
162 | Correspond to indexes in the clone_listx.
163 |
164 | -------
165 | Returns:
166 | - list
167 | * Elt1: int, index to be tested next;
168 | * Elt2: int, index to be tested next.
169 | """
170 |
171 | if len(clone_list2[i]) > len(clone_list2[j])\
172 | and all(elt in clone_list2[i] for elt in clone_list2[j]):
173 | all_clones_list.remove(all_clones_list[j])
174 | j -= 1 # Otherwise we miss an index, since j-old + 1 is now at position j-new
175 |
176 | elif len(clone_list2[i]) < len(clone_list2[j])\
177 | and all(elt in clone_list2[j] for elt in clone_list2[i]):
178 | all_clones_list.remove(all_clones_list[i])
179 | i -= 1 # Otherwise we miss an index, since i-old + 1 is now at position i-new,
180 | # so i should not get i + 1
181 | j = i + 1 # Otherwise we miss indexes, as we get a new i value, j should be reset too
182 |
183 | elif len(clone_list1[i]) > len(clone_list1[j])\
184 | and all(elt in clone_list1[i] for elt in clone_list1[j]):
185 | all_clones_list.remove(all_clones_list[j])
186 | j -= 1 # Otherwise we miss an index, since j-old + 1 is now at position j-new
187 |
188 | elif len(clone_list1[i]) < len(clone_list1[j])\
189 | and all(elt in clone_list1[j] for elt in clone_list1[i]):
190 | all_clones_list.remove(all_clones_list[i])
191 | i -= 1 # Otherwise we miss an index, since i-old + 1 is now at position i-new,
192 | # so i should not get i + 1
193 | j = i + 1 # Otherwise we miss indexes, as we get a new i value, j should be reset too
194 |
195 | return [i, j]
196 |
197 |
198 | def remove_duplicate_clones(all_clones_list, res_dict):
199 | """
200 | Because of backward slicing, some clones are reported twice, store them only once.
201 | Sometimes several clones are found. As a metric, we consider the distance between the nodes
202 | forming a clone, which should be minimized.
203 |
204 | -------
205 | Parameters:
206 | - all_clones_list: list of BiList()
207 | Contains the clones that have been found.
208 | - res_dict: dict
209 | Contains the different results obtained so far.
210 | """
211 |
212 | i = 0
213 | while i < len(all_clones_list): # To iterate over the modified list
214 | store_i = i
215 | j = i + 1
216 | while j < len(all_clones_list): # To iterate over the modified list
217 | if i < store_i:
218 | i = store_i # i should not be reset under its value
219 | clone_list1 = [clone_list.list1 for clone_list in all_clones_list]
220 | clone_list2 = [clone_list.list2 for clone_list in all_clones_list]
221 |
222 | if clone_list1[i] == clone_list1[j] and clone_list2[i] == clone_list2[j]:
223 | logging.debug('The exact same clone was reported twice %s and %s. Kept only one ',
224 | str(clone_list1[i]), str(clone_list2[i]))
225 | all_clones_list.remove(all_clones_list[j])
226 | j -= 1 # Otherwise we miss an index, since j-old + 1 is now at position j-new
227 |
228 | elif clone_list1[i] == clone_list1[j]:
229 | [i, j] = same_tokens(all_clones_list, clone_list1, clone_list2, i, j)
230 | elif clone_list2[i] == clone_list2[j]:
231 | [i, j] = same_tokens(all_clones_list, clone_list2, clone_list1, i, j)
232 |
233 | else:
234 | [i, j] = remove_subsumed_clones(all_clones_list, clone_list1, clone_list2, i, j)
235 |
236 | j += 1
237 | i += 1
238 | res_dict['pb_tokens'] = list()
239 | change_literal(all_clones_list, res_dict)
240 |
--------------------------------------------------------------------------------
/src/equivalence_classes.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2020 Aurore Fass
2 | # This program is free software: you can redistribute it and/or modify
3 | # it under the terms of the GNU Affero General Public License as published by
4 | # the Free Software Foundation, either version 3 of the License, or
5 | # (at your option) any later version.
6 |
7 | # This program is distributed in the hope that it will be useful,
8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | # GNU Affero General Public License for more details.
11 |
12 | # You should have received a copy of the GNU Affero General Public License
13 | # along with this program. If not, see .
14 |
15 | """
16 | 1. Find pairs of clone (equivalence class).
17 | """
18 |
19 |
20 | from bi_list import *
21 |
22 |
23 | def get_equivalence_classes_graph(pdg, my_id, equivalence_classes):
24 | """
25 | Get the equivalence classes (i.e. the node type defined as Node.name) present in graph.
26 |
27 | -------
28 | Parameters:
29 | - pdg: Node
30 | PDG considered.
31 | - my_id: int, either 1 or 2
32 | Indicates if we are handling graph1 or graph2.
33 | - equivalence_classes: list of EquivalenceClass
34 | Stores the equivalence classes present in graph.
35 |
36 | -------
37 | Returns:
38 | - list of EquivalenceClass
39 | Equivalence classes currently used.
40 | """
41 |
42 | for child in pdg.children:
43 | # if child.statement_dep_parents:
44 | # pass # Do nothing if the child is linked to his parent through a statement dependency
45 | if child.is_statement():
46 | if child.control_dep_children:
47 | pass # Do nothing as will be tested using backward slicing if it matches
48 | else:
49 | if child.name in equivalence_classes.keys():
50 | logging.debug('A new %s was added to the equivalence class', child.name)
51 | else:
52 | logging.debug('The equivalence class %s was created', child.name)
53 | equivalence_classes[child.name] = BiList()
54 | equivalence_classes[child.name].append_equivalence(child, my_id)
55 | get_equivalence_classes_graph(child, my_id, equivalence_classes)
56 | return equivalence_classes
57 |
58 |
59 | def get_equivalence_classes(graph1, graph2, equivalence_classes):
60 | """
61 | Get the equivalence classes (i.e. the node type defined as Node.name) present in
62 | graph1 and graph2.
63 |
64 | -------
65 | Parameters:
66 | - graph1: Node
67 | PDG1.
68 | - graph2: Node
69 | PDG2.
70 | - equivalence_classes: list of EquivalenceClass
71 | Stores the equivalence classes present in graph.
72 |
73 | -------
74 | Returns:
75 | - list of EquivalenceClass
76 | Equivalence classes currently used.
77 | """
78 |
79 | get_equivalence_classes_graph(graph1, my_id=1, equivalence_classes=equivalence_classes)
80 | get_equivalence_classes_graph(graph2, my_id=2, equivalence_classes=equivalence_classes)
81 | return equivalence_classes
82 |
--------------------------------------------------------------------------------
/src/extended_ast.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 Aurore Fass
2 | # This program is free software: you can redistribute it and/or modify
3 | # it under the terms of the GNU Affero General Public License as published by
4 | # the Free Software Foundation, either version 3 of the License, or
5 | # (at your option) any later version.
6 |
7 | # This program is distributed in the hope that it will be useful,
8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | # GNU Affero General Public License for more details.
11 |
12 | # You should have received a copy of the GNU Affero General Public License
13 | # along with this program. If not, see .
14 |
15 | """
16 | Definition of the class ExtendedAst: corresponds to the output of Esprima's parse function
17 | with the arguments: {range: true, tokens: true, comment: true}.
18 | """
19 |
20 |
21 | class ExtendedAst:
22 |
23 | def __init__(self):
24 | self.type = None
25 | self.body = []
26 | self.source_type = None
27 | self.range = []
28 | self.comments = []
29 | self.tokens = []
30 | self.leading_comments = []
31 |
32 | def get_type(self):
33 | return self.type
34 |
35 | def set_type(self, root):
36 | self.type = root
37 |
38 | def get_body(self):
39 | return self.body
40 |
41 | def set_body(self, body):
42 | self.body = body
43 |
44 | def get_extended_ast(self):
45 | return {'type': self.get_type(), 'body': self.get_body(),
46 | 'sourceType': self.get_source_type(), 'range': self.get_range(),
47 | 'comments': self.get_comments(), 'tokens': self.get_tokens(),
48 | 'leadingComments': self.get_leading_comments()}
49 |
50 | def get_ast(self):
51 | return {'type': self.get_type(), 'body': self.get_body()}
52 |
53 | def get_source_type(self):
54 | return self.source_type
55 |
56 | def set_source_type(self, source_type):
57 | self.source_type = source_type
58 |
59 | def get_range(self):
60 | return self.range
61 |
62 | def set_range(self, ast_range):
63 | self.range = ast_range
64 |
65 | def get_comments(self):
66 | return self.comments
67 |
68 | def set_comments(self, comments):
69 | self.comments = comments
70 |
71 | def get_tokens(self):
72 | return self.tokens
73 |
74 | def set_tokens(self, tokens):
75 | self.tokens = tokens
76 |
77 | def get_leading_comments(self):
78 | return self.leading_comments
79 |
80 | def set_leading_comments(self, leading_comments):
81 | self.leading_comments = leading_comments
82 |
--------------------------------------------------------------------------------
/src/handle_json.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 Aurore Fass
2 | # This program is free software: you can redistribute it and/or modify
3 | # it under the terms of the GNU Affero General Public License as published by
4 | # the Free Software Foundation, either version 3 of the License, or
5 | # (at your option) any later version.
6 |
7 | # This program is distributed in the hope that it will be useful,
8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | # GNU Affero General Public License for more details.
11 |
12 | # You should have received a copy of the GNU Affero General Public License
13 | # along with this program. If not, see .
14 |
15 | """
16 | From the JS source code to the Esprima AST exported in JSON.
17 | From JSON to ExtendedAst and Node objects.
18 | From Node objects to JSON.
19 | From JSON to the JS source code using Escodegen.
20 | """
21 |
22 |
23 | import json
24 | import os
25 | from subprocess import run, PIPE
26 |
27 | from node import *
28 | from extended_ast import *
29 |
30 | SRC_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__)))
31 |
32 |
33 | def get_extended_ast(input_file, json_path='1', remove_json=True):
34 | """
35 | JavaScript AST production.
36 |
37 | -------
38 | Parameters:
39 | - input_file: str
40 | Path of the file to produce an AST from.
41 | - json_path: str
42 | Path of the JSON file to temporary store the AST in.
43 | - remove_json: bool
44 | Indicates whether to remove or not the JSON file containing the Esprima AST.
45 | Default: True.
46 |
47 | -------
48 | Returns:
49 | - ExtendedAst
50 | The extended AST (i.e., contains type, body, sourceType, range, comments, tokens and
51 | possibly leadingComments) of input_file.
52 | - None if an error occurred.
53 | """
54 |
55 | produce_ast = run(['node', os.path.join(SRC_PATH, 'js_ast.js'), input_file, json_path],
56 | stdout=PIPE)
57 | if produce_ast.returncode == 0:
58 | if json_path == '1':
59 | ast = produce_ast.stdout.decode('utf-8').replace('\n', '')
60 | return ast.split('##!!**##')
61 | else:
62 | with open(json_path) as json_data:
63 | esprima_ast = json.loads(json_data.read())
64 | if remove_json:
65 | os.remove(json_path)
66 |
67 | extended_ast = ExtendedAst()
68 | extended_ast.set_type(esprima_ast['type'])
69 | extended_ast.set_body(esprima_ast['body'])
70 | extended_ast.set_source_type(esprima_ast['sourceType'])
71 | extended_ast.set_range(esprima_ast['range'])
72 | extended_ast.set_tokens(esprima_ast['tokens'])
73 | extended_ast.set_comments(esprima_ast['comments'])
74 | if 'leadingComments' in esprima_ast:
75 | extended_ast.set_leading_comments(esprima_ast['leadingComments'])
76 |
77 | return extended_ast
78 | logging.error('Esprima could not produce an AST for %s', input_file)
79 | return None
80 |
81 |
82 | def indent(depth_dict):
83 | """ Indentation size. """
84 | return '\t' * depth_dict
85 |
86 |
87 | def brace(key):
88 | """ Write a word between cases. """
89 | return '|<' + key + '>'
90 |
91 |
92 | def print_dict(depth_dict, key, value, max_depth, delete_leaf):
93 | """ Print the content of a dict with specific indentation and braces for the keys. """
94 | if depth_dict <= max_depth:
95 | print('%s%s' % (indent(depth_dict), brace(key)))
96 | beautiful_print_ast(value, depth=depth_dict + 1, max_depth=max_depth,
97 | delete_leaf=delete_leaf)
98 |
99 |
100 | def print_value(depth_dict, key, value, max_depth, delete_leaf):
101 | """ Print a dict value with respect to the indentation. """
102 | if depth_dict <= max_depth:
103 | if all(dont_consider != key for dont_consider in delete_leaf):
104 | print(indent(depth_dict) + "| %s = %s" % (key, value))
105 |
106 |
107 | def beautiful_print_ast(ast, delete_leaf, depth=0, max_depth=2**63):
108 | """
109 | Walking through an AST and printing it beautifully
110 |
111 | -------
112 | Parameters:
113 | - ast: dict
114 | Contains an Esprima AST of a JS file, i.e., get_extended_ast(, )
115 | output or get_extended_ast(, ).get_ast() output.
116 | - depth: int
117 | Initial depth of the tree. Default: 0.
118 | - max_depth: int
119 | Indicates the depth up to which the AST is printed. Default: 2**63.
120 | - delete_leaf: list
121 | Contains the leaf that should not be printed (e.g. 'range'). Default: [''],
122 | beware it is mutable.
123 | """
124 |
125 | for k, v in ast.items(): # Because need k everywhere
126 | if isinstance(v, dict):
127 | print_dict(depth, k, v, max_depth, delete_leaf)
128 | elif isinstance(v, list):
129 | if not v:
130 | print_value(depth, k, v, max_depth, delete_leaf)
131 | for el in v:
132 | if isinstance(el, dict):
133 | print_dict(depth, k, el, max_depth, delete_leaf)
134 | else:
135 | print_value(depth, k, el, max_depth, delete_leaf)
136 | else:
137 | print_value(depth, k, v, max_depth, delete_leaf)
138 |
139 |
140 | def create_node(dico, node_body, parent_node, cond=False):
141 | """ Node creation. """
142 | if 'type' in dico:
143 | node = Node(name=dico['type'], parent=parent_node)
144 | parent_node.set_child(node)
145 | node.set_body(node_body)
146 | if cond:
147 | node.set_body_list(True) # Some attributes are stored in a list even when they
148 | # are alone. If we do not respect the initial syntax, Escodegen cannot built the
149 | # JS code back.
150 | ast_to_ast_nodes(dico, node)
151 |
152 |
153 | def ast_to_ast_nodes(ast, ast_nodes=Node('Program')):
154 | """
155 | Convert an AST to Node objects.
156 |
157 | -------
158 | Parameters:
159 | - ast: dict
160 | Output of get_extended_ast(, ).get_ast().
161 | - ast_nodes: Node
162 | Current Node to be built. Default: ast_nodes=Node('Program'). Beware, always call the
163 | function indicating the default argument, otherwise the last value will be used
164 | (because the default parameter is mutable).
165 |
166 | -------
167 | Returns:
168 | - Node
169 | The AST in format Node object.
170 | """
171 |
172 | for k in ast:
173 | if k == 'range' or (k != 'type' and not isinstance(ast[k], list)
174 | and not isinstance(ast[k], dict)) or k == 'regex':
175 | ast_nodes.set_attribute(k, ast[k]) # range is a list but stored as attributes
176 | if isinstance(ast[k], dict):
177 | if k == 'range': # Case leadingComments as range: {0: begin, 1: end}
178 | ast_nodes.set_attribute(k, ast[k])
179 | else:
180 | create_node(dico=ast[k], node_body=k, parent_node=ast_nodes)
181 | elif isinstance(ast[k], list):
182 | if not ast[k]: # Case with empty list, e.g. params: []
183 | ast_nodes.set_attribute(k, ast[k])
184 | for el in ast[k]:
185 | if isinstance(el, dict):
186 | create_node(dico=el, node_body=k, parent_node=ast_nodes, cond=True)
187 | return ast_nodes
188 |
189 |
190 | def print_ast_nodes(ast_nodes):
191 | """
192 | Print the Nodes of ast_nodes with their properties.
193 | Debug function.
194 |
195 | -------
196 | Parameters:
197 | - ast_nodes: Node
198 | Output of ast_to_ast_nodes(, ast_nodes=Node('Program')).
199 | """
200 |
201 | for child in ast_nodes.children:
202 | print('Parent: ' + child.parent.name)
203 | print('Child: ' + child.name)
204 | print('Id: ' + str(child.id))
205 | print('Attributes:')
206 | print(child.attributes)
207 | print('Body: ' + str(child.body))
208 | print('Body_list: ' + str(child.body_list))
209 | print('Is-leaf: ' + str(child.is_leaf()))
210 | print('-----------------------')
211 | print_ast_nodes(child)
212 |
213 |
214 | def build_json(ast_nodes, dico):
215 | """
216 | Convert an AST format Node objects to JSON format.
217 |
218 | -------
219 | Parameters:
220 | - ast_nodes: Node
221 | Output of ast_to_ast_nodes(, ast_nodes=Node('Program')).
222 | - dico: dict
223 | Current dict to be built.
224 |
225 | -------
226 | Returns:
227 | - dict
228 | The AST in format JSON.
229 | """
230 |
231 | dico['type'] = ast_nodes.name
232 | if len(ast_nodes.children) >= 1:
233 | for child in ast_nodes.children:
234 | dico2 = {}
235 | if child.body_list:
236 | if child.body not in dico:
237 | dico[child.body] = [] # Some attributes just have to be stored in a list.
238 | build_json(child, dico2)
239 | dico[child.body].append(dico2)
240 | else:
241 | build_json(child, dico2)
242 | dico[child.body] = dico2
243 | elif ast_nodes.body_list == 'special':
244 | dico[ast_nodes.body] = []
245 | else:
246 | pass
247 | for att in ast_nodes.attributes:
248 | dico[att] = ast_nodes.attributes[att]
249 | return dico
250 |
251 |
252 | def save_json(ast_nodes, json_path):
253 | """
254 | Convert an AST format Node objects to JSON format.
255 |
256 | -------
257 | Parameters:
258 | - ast_nodes: Node
259 | Output of ast_to_ast_nodes(, ast_nodes=Node('Program')).
260 | - json_path: str
261 | Path of the JSON file to store the AST in.
262 | """
263 |
264 | data = build_json(ast_nodes, dico={})
265 | with open(json_path, 'w') as json_data:
266 | json.dump(data, json_data, indent=4)
267 |
268 |
269 | def get_code(json_path, code_path='1', remove_json=True, test=False):
270 | """
271 | Convert JSON format back to JavaScript code.
272 |
273 | -------
274 | Parameters:
275 | - json_path: str
276 | Path of the JSON file to build the code from.
277 | - code_path: str
278 | Path of the file to store the code in. If 1, then displays it to stdout.
279 | - remove_json: bool
280 | Indicates whether to remove or not the JSON file containing the Esprima AST.
281 | Default: True.
282 | - test: bool
283 | Indicates wether we are in test mode. Default: False.
284 | """
285 |
286 | code = run(['node', os.path.join(SRC_PATH, 'ast_js.js'), json_path, code_path], stdout=PIPE)
287 | if remove_json:
288 | os.remove(json_path)
289 | if code.returncode != 0:
290 | logging.error('Something wrong happened during the conversion back to the code')
291 | return None
292 | elif code_path == '1':
293 | if test:
294 | print((code.stdout.decode('utf-8')).replace('\n', ''))
295 | return (code.stdout.decode('utf-8')).replace('\n', '')
296 | return code_path
297 |
--------------------------------------------------------------------------------
/src/js_ast.js:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Aurore Fass
2 | // This program is free software: you can redistribute it and/or modify
3 | // it under the terms of the GNU Affero General Public License as published by
4 | // the Free Software Foundation, either version 3 of the License, or
5 | // (at your option) any later version.
6 |
7 | // This program is distributed in the hope that it will be useful,
8 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | // GNU Affero General Public License for more details.
11 |
12 | // You should have received a copy of the GNU Affero General Public License
13 | // along with this program. If not, see .
14 |
15 | // Conversion of a JS file into its Esprima AST.
16 |
17 |
18 | module.exports = {
19 | js2ast: js2ast,
20 | };
21 |
22 |
23 | var esprima = require("esprima");
24 | var es = require("escodegen");
25 | var fs = require("fs");
26 |
27 |
28 | /**
29 | * Extraction of the AST of an input JS file using Esprima.
30 | *
31 | * @param js
32 | * @param json_path
33 | * @returns {*}
34 | */
35 | function js2ast(js, json_path) {
36 | var text = fs.readFileSync(js).toString('utf-8');
37 | var ast = esprima.parse(text, {range: true, tokens: true, comment: true}, function (node) {
38 | console.log(node.type);
39 | //console.log(node.range);
40 | });
41 | console.log('##!!**##');
42 | for (var i in ast.tokens) {
43 | console.log(ast.tokens[i].type)
44 | }
45 |
46 | if (json_path !== '1') {
47 | // Attaching comments is a separate step for Escodegen
48 | ast = es.attachComments(ast, ast.comments, ast.tokens);
49 |
50 | fs.writeFile(json_path, JSON.stringify(ast), function (err) {
51 | if (err) {
52 | console.error(err);
53 | }
54 | //console.log("The AST has been successfully saved in " + json_path);
55 | });
56 |
57 | return ast;
58 | }
59 | }
60 |
61 | js2ast(process.argv[2], process.argv[3]);
62 |
--------------------------------------------------------------------------------
/src/js_reserved.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 Aurore Fass
2 | # This program is free software: you can redistribute it and/or modify
3 | # it under the terms of the GNU Affero General Public License as published by
4 | # the Free Software Foundation, either version 3 of the License, or
5 | # (at your option) any later version.
6 |
7 | # This program is distributed in the hope that it will be useful,
8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | # GNU Affero General Public License for more details.
11 |
12 | # You should have received a copy of the GNU Affero General Public License
13 | # along with this program. If not, see .
14 |
15 | """
16 | JavaScript reserved keywords or words known by the interpreter.
17 | """
18 |
19 | RESERVED_WORDS = ["abstract", "arguments", "await", "boolean", "break", "byte", "case", "catch",
20 | "char", "class", "const", "continue", "debugger", "default", "delete", "do",
21 | "double", "else", "enum", "eval", "export", "extends", "false", "final",
22 | "finally", "float", "for", "function", "goto", "if", "implements", "import", "in",
23 | "instanceof", "int", "interface", "let", "long", "native", "new", "null",
24 | "package", "private", "protected", "public", "return", "short", "static", "super",
25 | "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try",
26 | "typeof", "var", "void", "volatile", "while", "with", "yield", "Array",
27 | "Date", "eval", "function", "hasOwnProperty", "Infinity", "isFinite", "isNaN",
28 | "isPrototypeOf", "length", "Math", "NaN", "name", "Number", "Object", "prototype",
29 | "String", "toString", "undefined", "valueOf", "getClass", "java", "JavaArray",
30 | "javaClass", "JavaObject", "JavaPackage", "alert", "all", "anchor", "anchors",
31 | "area", "assign", "blur", "button", "checkbox", "clearInterval", "clearTimeout",
32 | "clientInformation", "close", "closed", "confirm", "constructor", "crypto",
33 | "decodeURI", "decodeURIComponent", "defaultStatus", "document", "element",
34 | "elements", "embed", "embeds", "encodeURI", "encodeURIComponent", "escape",
35 | "event", "fileUpload", "focus", "form", "forms", "frame", "innerHeight",
36 | "innerWidth", "layer", "layers", "link", "location", "mimeTypes", "navigate",
37 | "navigator", "frames", "frameRate", "hidden", "history", "image", "images",
38 | "offscreenBuffering", "open", "opener", "option", "outerHeight", "outerWidth",
39 | "packages", "pageXOffset", "pageYOffset", "parent", "parseFloat", "parseInt",
40 | "password", "pkcs11", "plugin", "prompt", "propertyIsEnum", "radio", "reset",
41 | "screenX", "screenY", "scroll", "secure", "select", "self", "setInterval",
42 | "setTimeout", "status", "submit", "taint", "text", "textarea", "top", "unescape",
43 | "untaint", "window", "onblur", "onclick", "onerror", "onfocus", "onkeydown",
44 | "onkeypress", "onkeyup", "onmouseover", "onload", "onmouseup", "onmousedown",
45 | "onsubmit",
46 | "define", "exports", "require", "each", "ActiveXObject", "console", "module",
47 | "Error", "TypeError", "RangeError", "RegExp", "Symbol", "Set"]
48 |
49 |
50 | RESERVED_WORDS_LOWER = [word.lower() for word in RESERVED_WORDS]
51 |
--------------------------------------------------------------------------------
/src/node.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 Aurore Fass
2 | # This program is free software: you can redistribute it and/or modify
3 | # it under the terms of the GNU Affero General Public License as published by
4 | # the Free Software Foundation, either version 3 of the License, or
5 | # (at your option) any later version.
6 |
7 | # This program is distributed in the hope that it will be useful,
8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | # GNU Affero General Public License for more details.
11 |
12 | # You should have received a copy of the GNU Affero General Public License
13 | # along with this program. If not, see .
14 |
15 | """
16 | Definition of classes Dependence and Node.
17 | """
18 |
19 | import logging
20 |
21 |
22 | class Dependence:
23 |
24 | def __init__(self, dependency_type, extremity, label, begin=None, end=None):
25 | self.type = dependency_type
26 | self.extremity = extremity
27 | self.id_begin = begin
28 | self.id_end = end
29 | self.label = label
30 |
31 | def get_type(self):
32 | return self.type
33 |
34 | def set_type(self, dependency_type):
35 | self.type = dependency_type
36 |
37 | def get_extremity(self):
38 | return self.extremity
39 |
40 | def set_extremity(self, extremity):
41 | self.extremity = extremity
42 |
43 | def get_id_begin(self):
44 | return self.id_begin
45 |
46 | def set_id_begin(self, id_begin):
47 | self.id_begin = id_begin
48 |
49 | def get_id_end(self):
50 | return self.id_end
51 |
52 | def set_id_end(self, id_end):
53 | self.id_end = id_end
54 |
55 | def get_label(self):
56 | return self.label
57 |
58 | def set_label(self, label):
59 | self.label = label
60 |
61 |
62 | class Node:
63 | id = 0
64 |
65 | def __init__(self, name, parent=None):
66 | self.name = name
67 | self.id = Node.id
68 | Node.id += 1
69 | self.clone = False
70 | self.attributes = {}
71 | self.body = None
72 | self.body_list = False
73 | self.parent = parent
74 | self.children = []
75 | self.data_dep_parents = []
76 | self.data_dep_children = []
77 | self.control_dep_parents = []
78 | self.control_dep_children = []
79 | self.comment_dep_parents = []
80 | self.comment_dep_children = []
81 | self.statement_dep_parents = []
82 | self.statement_dep_children = []
83 |
84 | def get_name(self):
85 | return self.name
86 |
87 | def set_name(self, name):
88 | self.name = name
89 |
90 | def get_id(self):
91 | return self.id
92 |
93 | def set_id(self, node_id):
94 | self.id = node_id
95 |
96 | def set_clone_true(self):
97 | self.clone = True
98 |
99 | def get_attributes(self):
100 | return self.attributes
101 |
102 | def is_leaf(self):
103 | return not self.children
104 |
105 | def is_statement(self):
106 | statements = ['BlockStatement', 'BreakStatement', 'ContinueStatement', 'DoWhileStatement',
107 | 'DebuggerStatement', 'EmptyStatement', 'ExpressionStatement', 'ForStatement',
108 | 'ForOfStatement', 'ForInStatement', 'IfStatement', 'LabeledStatement',
109 | 'ReturnStatement', 'SwitchStatement', 'ThrowStatement', 'TryStatement',
110 | 'WhileStatement', 'WithStatement',
111 | 'VariableDeclaration', 'CatchClause', 'SwitchCase', 'ConditionalExpression',
112 | 'FunctionDeclaration', 'ClassDeclaration']
113 | if self.name in statements:
114 | return True
115 | return False
116 |
117 | def is_comment(self):
118 | comments = ['Line', 'Block']
119 | if self.name in comments:
120 | return True
121 | return False
122 |
123 | def get_attribute(self, attribute_type):
124 | return self.attributes[attribute_type]
125 |
126 | def get_type(self):
127 | return self.get_attribute('type')
128 |
129 | def get_value(self):
130 | return self.get_attribute('name')
131 |
132 | def get_range(self):
133 | return self.get_attribute('range')
134 |
135 | def set_attribute(self, attribute_type, node_attribute):
136 | self.attributes[attribute_type] = node_attribute
137 |
138 | def set_type(self, node_type):
139 | self.set_attribute('type', node_type)
140 |
141 | def set_value(self, node_value):
142 | self.set_attribute('name', node_value)
143 |
144 | def set_range(self, node_range):
145 | self.set_attribute('range', node_range)
146 |
147 | def get_body(self):
148 | return self.body
149 |
150 | def set_body(self, body):
151 | self.body = body
152 |
153 | def get_body_list(self):
154 | return self.body_list
155 |
156 | def set_body_list(self, bool_body_list):
157 | self.body_list = bool_body_list
158 |
159 | def get_parent(self):
160 | return self.parent
161 |
162 | def set_parent(self, parent):
163 | self.parent = parent
164 |
165 | def get_children(self):
166 | return self.children
167 |
168 | def set_child(self, child):
169 | self.children.append(child)
170 |
171 | def literal_type(self):
172 | if 'value' in self.attributes:
173 | literal = self.attributes['value']
174 | if isinstance(literal, str):
175 | return 'String'
176 | elif isinstance(literal, int):
177 | return 'Int'
178 | elif isinstance(literal, float):
179 | return 'Numeric'
180 | elif isinstance(literal, bool):
181 | return 'Bool'
182 | elif literal == 'null' or literal is None:
183 | return 'Null'
184 | if 'regex' in self.attributes:
185 | return 'RegExp'
186 | if self.name != 'Literal':
187 | logging.warning('The node %s is not a Literal', self.name)
188 | else:
189 | logging.warning('The literal %s has an unknown type', self.attributes['raw'])
190 | return None
191 |
192 | def get_data_dependencies(self, im_src=True):
193 | if im_src:
194 | return [['data dependency', dep.extremity.name, dep.label]
195 | for dep in self.data_dep_children]
196 | return [['data dependency', dep.extremity.name, dep.label]
197 | for dep in self.data_dep_parents]
198 |
199 | def set_data_dependency(self, extremity, begin, end):
200 | self.data_dep_children.append(Dependence('data dependency', extremity, 'data', begin, end))
201 | extremity.data_dep_parents.append(Dependence('data dependency', self, 'data', begin, end))
202 |
203 | def get_control_dependencies(self, im_src=True):
204 | if im_src:
205 | return [['control dependency', dep.extremity.name, dep.label]
206 | for dep in self.control_dep_children]
207 | return [['control dependency', dep.extremity.name, dep.label]
208 | for dep in self.control_dep_parents]
209 |
210 | def set_control_dependency(self, extremity, label):
211 | self.control_dep_children.append(Dependence('control dependency', extremity, label))
212 | extremity.control_dep_parents.append(Dependence('control dependency', self, label))
213 |
214 | def set_comment_dependency(self, extremity):
215 | self.comment_dep_children.append(Dependence('comment dependency', extremity, 'c'))
216 | extremity.comment_dep_parents.append(Dependence('comment dependency', self, 'c'))
217 |
218 | def remove_control_dependency(self, extremity):
219 | for i, _ in enumerate(self.control_dep_children):
220 | elt = self.control_dep_children[i]
221 | if elt.extremity.id == extremity.id:
222 | del self.control_dep_children[i]
223 | del extremity.control_dep_parents[i]
224 |
225 | def get_statement_dependencies(self, im_src=True):
226 | if im_src:
227 | return [['statement dependency', dep.extremity.name, dep.label]
228 | for dep in self.statement_dep_children]
229 | return [['statement dependency', dep.extremity.name, dep.label]
230 | for dep in self.statement_dep_parents]
231 |
232 | def set_statement_dependency(self, extremity):
233 | self.statement_dep_children.append(Dependence('statement dependency', extremity, 's'))
234 | extremity.statement_dep_parents.append(Dependence('statement dependency', self, 's'))
235 |
--------------------------------------------------------------------------------
/src/pdgs_generation.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 Aurore Fass
2 | # This program is free software: you can redistribute it and/or modify
3 | # it under the terms of the GNU Affero General Public License as published by
4 | # the Free Software Foundation, either version 3 of the License, or
5 | # (at your option) any later version.
6 |
7 | # This program is distributed in the hope that it will be useful,
8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | # GNU Affero General Public License for more details.
11 |
12 | # You should have received a copy of the GNU Affero General Public License
13 | # along with this program. If not, see .
14 |
15 | """
16 | Generation and storage of JavaScript PDGs. Possibility for multiprocessing (NUM_WORKERS
17 | defined in utility_df.py).
18 | """
19 |
20 | import pickle
21 | from multiprocessing import Process, Queue
22 |
23 | from utility_df import *
24 | from handle_json import *
25 | from build_cfg import *
26 | from build_dfg import *
27 | from var_list import *
28 |
29 |
30 | GIT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
31 |
32 |
33 | def pickle_dump_process(dfg_nodes, store_pdg):
34 | """ Call to pickle.dump """
35 |
36 | pickle.dump(dfg_nodes, open(store_pdg, 'wb'))
37 |
38 |
39 | def get_data_flow(input_file, benchmarks, store_pdgs=None, check_var=False):
40 | """
41 | Produces the PDG of a given file.
42 |
43 | -------
44 | Parameters:
45 | - input_file: str
46 | Path of the file to study.
47 | - benchmarks: dict
48 | Contains the different microbenchmarks. Should be empty.
49 | - store_pdgs: str
50 | Path of the folder to store the PDG in.
51 | Or None to pursue without storing it.
52 | - check_var: bool
53 | Build PDG just to check if our malicious variables are undefined. Default: False.
54 |
55 | -------
56 | Returns:
57 | - Node
58 | PDG of the file
59 | - or None.
60 | """
61 |
62 | start = timeit.default_timer()
63 | if input_file.endswith('.js'):
64 | esprima_json = input_file.replace('.js', '.json')
65 | else:
66 | esprima_json = input_file + '.json'
67 | extended_ast = get_extended_ast(input_file, esprima_json)
68 | if extended_ast is not None:
69 | benchmarks['got AST'] = timeit.default_timer() - start
70 | start = micro_benchmark('Successfully got Esprima AST in', timeit.default_timer() - start)
71 | ast = extended_ast.get_ast()
72 | # beautiful_print_ast(ast, delete_leaf=[])
73 | ast_nodes = ast_to_ast_nodes(ast, ast_nodes=Node('Program'))
74 | benchmarks['AST'] = timeit.default_timer() - start
75 | start = micro_benchmark('Successfully produced the AST in', timeit.default_timer() - start)
76 | # draw_ast(ast_nodes, attributes=True, save_path=save_path_ast)
77 | cfg_nodes = build_cfg(ast_nodes)
78 | benchmarks['CFG'] = timeit.default_timer() - start
79 | start = micro_benchmark('Successfully produced the CFG in', timeit.default_timer() - start)
80 | # draw_cfg(cfg_nodes, attributes=True, save_path=save_path_cfg)
81 | unknown_var = []
82 | try:
83 | with Timeout(60): # Tries to produce DF within 60s
84 | dfg_nodes = df_scoping(cfg_nodes, var_loc=VarList(), var_glob=VarList(),
85 | unknown_var=unknown_var, id_list=[], entry=1)[0]
86 | except Timeout.Timeout:
87 | logging.exception('Timed out for %s', input_file)
88 | return None
89 | # draw_pdg(dfg_nodes, attributes=True, save_path=save_path_pdg)
90 | for unknown in unknown_var:
91 | logging.warning('The variable ' + unknown.attributes['name'] + ' is not declared')
92 | if check_var:
93 | return unknown_var
94 | benchmarks['PDG'] = timeit.default_timer() - start
95 | micro_benchmark('Successfully produced the PDG in', timeit.default_timer() - start)
96 | if store_pdgs is not None:
97 | store_pdg = os.path.join(store_pdgs, os.path.basename(input_file.replace('.js', '')))
98 | # pickle.dump(dfg_nodes, open(store_pdg, 'wb'))
99 | # I don't know why, but some PDGs lead to Segfault, this way it does not kill the
100 | # current process at least
101 | p = Process(target=pickle_dump_process, args=(dfg_nodes, store_pdg))
102 | p.start()
103 | p.join()
104 | if p.exitcode != 0:
105 | logging.error('Something wrong occurred to pickle the PDG of %s', store_pdg)
106 | if os.path.isfile(store_pdg) and os.stat(store_pdg).st_size == 0:
107 | os.remove(store_pdg)
108 | return dfg_nodes
109 | return None
110 |
111 |
112 | def handle_one_pdg(root, js, store_pdgs):
113 | """ Stores the PDG of js located in root, in store_pdgs. """
114 |
115 | benchmarks = dict()
116 | print(os.path.join(store_pdgs, js.replace('.js', '')))
117 | get_data_flow(input_file=os.path.join(root, js), benchmarks=benchmarks,
118 | store_pdgs=store_pdgs)
119 |
120 |
121 | def worker(my_queue):
122 | """ Worker """
123 |
124 | while True:
125 | try:
126 | item = my_queue.get(timeout=2)
127 | handle_one_pdg(item[0], item[1], item[2])
128 | except Exception as e:
129 | break
130 |
131 |
132 | def store_pdg_folder(folder_js):
133 | """
134 | Stores the PDGs of the JS files from folder_js.
135 |
136 | -------
137 | Parameters:
138 | - folder_js: str
139 | Path of the folder containing the files to get the PDG of.
140 | """
141 |
142 | start = timeit.default_timer()
143 |
144 | my_queue = Queue()
145 | workers = list()
146 |
147 | if not os.path.exists(folder_js):
148 | logging.exception('The path %s does not exist', folder_js)
149 | return
150 | store_pdgs = os.path.join(folder_js, 'PDG')
151 | if not os.path.exists(store_pdgs):
152 | os.makedirs(store_pdgs)
153 |
154 | for root, _, files in os.walk(folder_js):
155 | for js in files:
156 | my_queue.put([root, js, store_pdgs])
157 |
158 | for i in range(NUM_WORKERS):
159 | p = Process(target=worker, args=(my_queue,))
160 | p.start()
161 | print("Starting process")
162 | workers.append(p)
163 |
164 | for w in workers:
165 | w.join()
166 |
167 | micro_benchmark('Total elapsed time:', timeit.default_timer() - start)
168 |
--------------------------------------------------------------------------------
/src/samples_generation.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2020 Aurore Fass
2 | # This program is free software: you can redistribute it and/or modify
3 | # it under the terms of the GNU Affero General Public License as published by
4 | # the Free Software Foundation, either version 3 of the License, or
5 | # (at your option) any later version.
6 |
7 | # This program is distributed in the hope that it will be useful,
8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | # GNU Affero General Public License for more details.
11 |
12 | # You should have received a copy of the GNU Affero General Public License
13 | # along with this program. If not, see .
14 |
15 | """
16 | For HideNoSeek: Generation and storage of malicious JavaScript instances with a benign AST.
17 | For the open-source version: Searching for clones between 2 JavaScript instances
18 | (the functions' description have not been updated for this specific version).
19 | Possibility for multiprocessing (NUM_WORKERS defined in utility_df.py).
20 | """
21 |
22 | import pickle
23 | from multiprocessing import Process, Queue
24 |
25 | from utility_df import *
26 | from pdgs_generation import get_data_flow
27 | from clone_detection import *
28 |
29 |
30 | def worker(my_queue, start):
31 | """ Worker """
32 |
33 | while True:
34 | try:
35 | item = my_queue.get(timeout=2)
36 | # print(item)
37 | analyze_valid_pdgs(item[0], item[1], item[2])
38 | except Exception as e:
39 | break
40 | print('Total elapsed time: ' + str(timeit.default_timer() - start) + 's')
41 |
42 |
43 | def replace_ast_df_folder(benign_pdgs, malicious_pdgs):
44 | """
45 | Replaces some benign parts of benign file with malicious ones. Loops over JS directories.
46 |
47 | -------
48 | Parameters:
49 | - benign_pdgs: str
50 | Path of the folder containing benign PDGs to test.
51 | - malicious_pdgs: str
52 | Path of the folder containing malicious PDGs to test.
53 | """
54 |
55 | start = timeit.default_timer()
56 |
57 | my_queue = Queue()
58 | workers = list()
59 |
60 | for malicious_pdg in os.listdir(malicious_pdgs):
61 |
62 | json_analysis = os.path.join(os.path.dirname(malicious_pdgs), malicious_pdg + '-analysis')
63 | if not os.path.exists(json_analysis):
64 | os.makedirs(json_analysis)
65 |
66 | for benign_pdg in os.listdir(benign_pdgs):
67 | my_queue.put([os.path.join(benign_pdgs, benign_pdg),
68 | os.path.join(malicious_pdgs, malicious_pdg),
69 | json_analysis])
70 | # time.sleep(0.1) # Just enough to let the Queue finish
71 |
72 | for i in range(NUM_WORKERS):
73 | p = Process(target=worker, args=(my_queue, start,))
74 | p.start()
75 | print("Starting process")
76 | workers.append(p)
77 |
78 | for w in workers:
79 | w.join()
80 |
81 |
82 | def unpickle_pdg(pdg_path):
83 | """ Tries to unpickle a PDG. """
84 |
85 | try:
86 | pdg = pickle.load(open(pdg_path, 'rb'))
87 | return pdg
88 | except IsADirectoryError as error_message:
89 | logging.exception('%s %s%s %s', 'Tried to unpickle the directory', pdg_path, ':',
90 | str(error_message))
91 | return None
92 |
93 |
94 | def analyze_valid_pdgs(benign_pdg_path, malicious_pdg_path, json_analysis):
95 | """ Take one benign and one malicious PDG paths and call the replace_ast_df function if both of
96 | them are valid. """
97 |
98 | results = dict()
99 | dfg_nodes_benign = unpickle_pdg(benign_pdg_path)
100 | if dfg_nodes_benign is not None:
101 | dfg_nodes_malicious = unpickle_pdg(malicious_pdg_path)
102 | if dfg_nodes_malicious is not None:
103 | print('Analysis of ' + os.path.basename(malicious_pdg_path) + ' and '
104 | + os.path.basename(benign_pdg_path) + '\n')
105 | results['malicious'] = malicious_pdg_path
106 | results['benign'] = benign_pdg_path
107 | replace_ast_df(dfg_nodes_benign, dfg_nodes_malicious, results, json_analysis)
108 |
109 |
110 | def replace_ast_df(dfg_nodes_benign, dfg_nodes_malicious, res_dict, json_analysis):
111 | """
112 | Replaces benign sub ASTs with their malicious equivalents.
113 |
114 | -------
115 | Parameters:
116 | - dfg_nodes_benign: Node
117 | PDG of the benign file considered.
118 | - dfg_nodes_malicious: Node
119 | PDG of the malicious file considered.
120 | - res_dict: dict
121 | Contains the different results obtained so far.
122 | - json_analysis: str
123 | Path of the directory to store the JSON analysis file.
124 |
125 | -------
126 | Returns:
127 | - list
128 | Contains the clones found between the benign and malicious AST.
129 | - or None.
130 | """
131 |
132 | start = timeit.default_timer()
133 | benchmarks = dict()
134 |
135 | malicious = os.path.basename(res_dict['malicious'])
136 | benign = os.path.basename(res_dict['benign'])
137 |
138 | all_clones_list = find_all_clones(dfg_nodes_benign, dfg_nodes_malicious)
139 | benchmarks['Clones detected'] = timeit.default_timer() - start
140 | start = micro_benchmark('Successfully detected ' + str(len(all_clones_list))
141 | + ' clones without duplicate suppression in',
142 | timeit.default_timer() - start)
143 |
144 | remove_duplicate_clones(all_clones_list, res_dict) # Modified version
145 | annotate_clone(all_clones_list, res_dict)
146 | res_dict['dissimilar'] = list()
147 | dissimilar(dfg_nodes_malicious, res_dict)
148 | benchmarks['Clones selected'] = timeit.default_timer() - start
149 | micro_benchmark('Successfully selected ' + str(len(all_clones_list))
150 | + ' clones in', timeit.default_timer() - start)
151 |
152 | nb_clones = get_percentage_cloned(dfg_nodes_benign, dfg_nodes_malicious, res_dict)
153 | print_clones(all_clones_list) # Comment for multiprocessing!
154 |
155 | logging.info('Could find %s%% of the malicious nodes in the benign AST', nb_clones * 100)
156 |
157 | if nb_clones * 100 == 100: # Only if malicious AST can be found in benign one
158 | res_dict['benchmarks'] = benchmarks
159 |
160 | with open(os.path.join(json_analysis, benign.replace('.js', '') + '_'\
161 | + malicious.replace('.js', '') + '.json'),
162 | 'w') as json_data:
163 | json.dump(res_dict, json_data)
164 |
165 | return all_clones_list
166 |
167 | res_dict['benchmarks'] = benchmarks
168 | with open(os.path.join(json_analysis, benign.replace('.js', '') + '_'\
169 | + malicious.replace('.js', '') + '.json'),
170 | 'w') as json_data:
171 | json.dump(res_dict, json_data)
172 |
173 | return None
174 |
175 |
176 | def replace_ast(input_benign, input_malicious):
177 | """
178 | Replaces some benign parts of a given file with malicious ones.
179 |
180 | -------
181 | Parameters:
182 | - input_benign: str
183 | Path of the benign file considered.
184 | - input_malicious: str
185 | Path of the malicious file considered.
186 |
187 | -------
188 | Returns:
189 | - list
190 | Contains the clones found between the benign and malicious AST.
191 | - or None.
192 | """
193 |
194 | benchmarks = dict()
195 | json_analysis = input_malicious.replace('.js', '') + '-analysis'
196 | if not os.path.exists(json_analysis):
197 | os.makedirs(json_analysis)
198 | start = timeit.default_timer()
199 |
200 | dfg_nodes_benign = get_data_flow(input_file=input_benign, benchmarks=benchmarks)
201 | dfg_nodes_malicious = get_data_flow(input_file=input_malicious, benchmarks=benchmarks)
202 | if dfg_nodes_benign is not None and dfg_nodes_malicious is not None:
203 | res_dict = dict()
204 | res_dict['malicious'] = input_malicious
205 | res_dict['benign'] = input_benign
206 | replaced_ast = replace_ast_df(dfg_nodes_benign, dfg_nodes_malicious, res_dict=res_dict,
207 | json_analysis=json_analysis)
208 | # same_ast(benign_file, malicious_file)
209 | micro_benchmark('Elapsed time:', timeit.default_timer() - start)
210 | return replaced_ast
211 | return None
212 |
--------------------------------------------------------------------------------
/src/utility_df.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 Aurore Fass
2 | # This program is free software: you can redistribute it and/or modify
3 | # it under the terms of the GNU Affero General Public License as published by
4 | # the Free Software Foundation, either version 3 of the License, or
5 | # (at your option) any later version.
6 |
7 | # This program is distributed in the hope that it will be useful,
8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | # GNU Affero General Public License for more details.
11 |
12 | # You should have received a copy of the GNU Affero General Public License
13 | # along with this program. If not, see .
14 |
15 | """
16 | Utility file, stores shared information.
17 | """
18 |
19 | import sys
20 | import timeit
21 | import logging
22 | import signal
23 |
24 |
25 | sys.setrecursionlimit(400000)
26 |
27 | NUM_WORKERS = 1
28 |
29 |
30 | class UpperThresholdFilter(logging.Filter):
31 | """
32 | This allows us to set an upper threshold for the log levels since the setLevel method only
33 | sets a lower one
34 | """
35 |
36 | def __init__(self, threshold, *args, **kwargs):
37 | self._threshold = threshold
38 | super(UpperThresholdFilter, self).__init__(*args, **kwargs)
39 |
40 | def filter(self, rec):
41 | return rec.levelno <= self._threshold
42 |
43 |
44 | logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)
45 | LOGGER = logging.getLogger()
46 | LOGGER.addFilter(UpperThresholdFilter(logging.CRITICAL))
47 |
48 |
49 | def micro_benchmark(message, elapsed_time):
50 | """ Micro benchmarks. """
51 | logging.info('%s %s%s', message, str(elapsed_time), 's')
52 | return timeit.default_timer()
53 |
54 |
55 | class Timeout:
56 | """ Timeout class using ALARM signal. """
57 |
58 | class Timeout(Exception):
59 | pass
60 |
61 | def __init__(self, sec):
62 | self.sec = sec
63 |
64 | def __enter__(self):
65 | signal.signal(signal.SIGALRM, self.raise_timeout)
66 | signal.alarm(self.sec)
67 |
68 | def __exit__(self, *args):
69 | signal.alarm(0) # disable alarm
70 |
71 | def raise_timeout(self, *args):
72 | raise Timeout.Timeout()
73 |
--------------------------------------------------------------------------------
/src/var_list.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 Aurore Fass
2 | # This program is free software: you can redistribute it and/or modify
3 | # it under the terms of the GNU Affero General Public License as published by
4 | # the Free Software Foundation, either version 3 of the License, or
5 | # (at your option) any later version.
6 |
7 | # This program is distributed in the hope that it will be useful,
8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | # GNU Affero General Public License for more details.
11 |
12 | # You should have received a copy of the GNU Affero General Public License
13 | # along with this program. If not, see .
14 |
15 | """
16 | Definition of class VarList.
17 | """
18 |
19 | import copy
20 |
21 |
22 | class LimitedScope:
23 |
24 | def __init__(self):
25 | self.limit = False
26 | self.before_limit_list = []
27 | self.after_limit_list = []
28 |
29 |
30 | class VarList:
31 |
32 | def __init__(self):
33 | self.var_list = []
34 | self.ref_list = []
35 | self.fun_list = []
36 | self.limited_scope = LimitedScope()
37 |
38 | def get_var_list(self):
39 | return self.var_list
40 |
41 | def get_ref_list(self):
42 | return self.ref_list
43 |
44 | def set_var_list(self, var_list):
45 | self.var_list = var_list
46 |
47 | def set_ref_list(self, ref_list):
48 | self.ref_list = ref_list
49 |
50 | def get_fun_list(self):
51 | return self.fun_list
52 |
53 | def set_fun_list(self, fun_list):
54 | self.fun_list = fun_list
55 |
56 | def add_el_ref(self, answer):
57 | self.ref_list.append(answer)
58 |
59 | def update_el_ref(self, index, answer):
60 | self.ref_list[index] = answer
61 |
62 | def add_el_fun(self, fun):
63 | self.fun_list.append(fun)
64 |
65 | def update_el_fun(self, index, fun):
66 | self.fun_list[index] = fun
67 |
68 | def add_var(self, identifier_node, answer=None, fun=False):
69 | self.var_list.append(identifier_node)
70 | self.add_el_ref(answer)
71 | self.add_el_fun(fun)
72 |
73 | def update_var(self, index, identifier_node, answer=None, fun=False):
74 | self.var_list[index] = identifier_node
75 | self.update_el_ref(index, answer)
76 | self.update_el_fun(index, fun)
77 |
78 | def is_equal(self, var_list2):
79 | if self.var_list == var_list2.var_list and self.ref_list == var_list2.ref_list\
80 | and self.fun_list == var_list2.fun_list:
81 | return True
82 | return False
83 |
84 | def copy_var_list(self):
85 | var_list = VarList()
86 | var_list.set_var_list(copy.copy(self.var_list))
87 | var_list.set_ref_list(copy.copy(self.ref_list))
88 | var_list.set_fun_list(copy.copy(self.fun_list))
89 | return var_list
90 |
91 | def get_limit(self):
92 | return self.limited_scope.limit
93 |
94 | def set_limit(self, limit):
95 | self.limited_scope.limit = limit
96 |
97 | def get_before_limit_list(self):
98 | return self.limited_scope.before_limit_list
99 |
100 | def set_before_limit_list(self, limit_list):
101 | self.limited_scope.before_limit_list = copy.copy(limit_list)
102 |
103 | def get_after_limit_list(self):
104 | return self.limited_scope.after_limit_list
105 |
106 | def set_after_limit_list(self, limit_list):
107 | self.limited_scope.after_limit_list = copy.copy(limit_list)
108 |
109 | def add_el_limit_list(self, el):
110 | self.limited_scope.after_limit_list.append(el)
111 |
112 | def reset_limited_scope(self):
113 | self.set_limit(False)
114 | self.set_before_limit_list([])
115 | self.set_after_limit_list([])
116 |
--------------------------------------------------------------------------------