├── .gitignore ├── LICENSE ├── README.md └── src ├── __init__.py ├── build_ast.py ├── build_pdg.py ├── control_flow.py ├── data_flow.py ├── display_graph.py ├── extended_ast.py ├── js_operators.py ├── js_reserved.py ├── node.py ├── parser.js ├── pointer_analysis.py ├── scope.py ├── utility_df.py └── value_filters.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.json 2 | 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | .project 8 | .pydevproject 9 | .metadata/ 10 | 11 | # Node modules 12 | node_modules 13 | package-lock.json 14 | 15 | # C extensions 16 | *.so 17 | 18 | # Distribution / packaging 19 | .Python 20 | env/ 21 | build/ 22 | develop-eggs/ 23 | dist/ 24 | downloads/ 25 | eggs/ 26 | .eggs/ 27 | lib/ 28 | lib64/ 29 | parts/ 30 | sdist/ 31 | var/ 32 | *.egg-info/ 33 | .installed.cfg 34 | *.egg 35 | 36 | # PyInstaller 37 | # Usually these files are written by a python script from a template 38 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 39 | *.manifest 40 | *.spec 41 | 42 | # Installer logs 43 | pip-log.txt 44 | pip-delete-this-directory.txt 45 | 46 | # Unit test / coverage reports 47 | htmlcov/ 48 | .tox/ 49 | .coverage 50 | .coverage.* 51 | .cache 52 | nosetests.xml 53 | coverage.xml 54 | *,cover 55 | .hypothesis/ 56 | 57 | # Translations 58 | *.mo 59 | *.pot 60 | 61 | # Django stuff: 62 | *.log 63 | local_settings.py 64 | 65 | # Flask stuff: 66 | instance/ 67 | .webassets-cache 68 | 69 | # Scrapy stuff: 70 | .scrapy 71 | 72 | # Sphinx documentation 73 | docs/_build/ 74 | 75 | # PyBuilder 76 | target/ 77 | 78 | # IPython Notebook 79 | .ipynb_checkpoints 80 | 81 | # pyenv 82 | .python-version 83 | 84 | # celery beat schedule file 85 | celerybeat-schedule 86 | 87 | # dotenv 88 | .env 89 | 90 | # virtualenv 91 | venv/ 92 | ENV/ 93 | 94 | # Spyder project settings 95 | .spyderproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # PyCharm project settings 101 | .idea/ 102 | 103 | # MacOS files 104 | *.DS_Store 105 | *.idea 106 | -------------------------------------------------------------------------------- /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 | # static-pdg-js: 2 | ## Static JavaScript Analysis: AST, Control Flow, Data Flow, and Pointer Analysis 3 | 4 | 5 | ## Summary 6 | We propose a tool to statically analyze JavaScript code. 7 | To this end, we build the AST (Abstract Syntax Tree) of an input JavaScript file. 8 | To reason about the conditions that have to be met for a specific execution path to be taken, we subsequently add control flow edges to the AST. We refer to the resulting graph as the CFG (Control Flow Graph). 9 | Next, to reason about variable dependencies, we add data flow edges to the CFG. 10 | Finally, to compute variable values, we perform a pointer analysis. 11 | We refer to the resulting graph as the PDG (Program Dependence Graph). 12 | 13 | Please, note that in its current state, the code is a PoC and not a fully-fledged production-ready API. 14 | 15 | 16 | ### CFG and PDG Definitions 17 | We adopt a definition of the CFG that slightly differs from Allen’s as we enhance our AST with control flow edges. This way, we build a joint structure that combines control flow information with the fine-grained AST nodes and edges. 18 | Our PDG also slightly differs from the definition of Ferrante et al. as we chose to add data flow edges to our CFG. This way, we retain information regarding statement order and have a fine-grained representation of the data flows directly at the variable level (as we build the CFG upon the AST). 19 | Additional details can be found in [my dissertation](https://publications.cispa.saarland/3471/7/fass2020thesis.pdf). 20 | 21 | ### Papers based on this Tool 22 | 23 | This code has been used to statically analyze browser extensions. See DoubleX [paper](https://swag.cispa.saarland/papers/fass2021doublex.pdf) & [code](https://github.com/Aurore54F/DoubleX). 24 | Preliminary versions of this code were also used to detect malicious JavaScript samples: HideNoSeek [paper](https://swag.cispa.saarland/papers/fass2019hidenoseek.pdf) & [code](https://github.com/Aurore54F/HideNoSeek) and JStap [paper](https://swag.cispa.saarland/papers/fass2019jstap.pdf) & [code](https://github.com/Aurore54F/JStap). 25 | And to study JavaScript code transformation techniques: [paper](https://swag.cispa.saarland/papers/moog2021statically.pdf) & [code](https://github.com/MarM15/js-transformations). 26 | 27 | 28 | ## Setup 29 | 30 | ``` 31 | install python3 # (tested with 3.7.3 and 3.7.4) 32 | 33 | install nodejs 34 | install npm 35 | cd src 36 | npm install esprima # (tested with 4.0.1) 37 | npm install escodegen # (tested with 1.14.2 and 2.0.0) 38 | ``` 39 | 40 | To install graphviz (only for drawing graphs, not yet documented, please open an issue if interested) 41 | ``` 42 | pip3 install graphviz 43 | On MacOS: install brew and then brew install graphviz 44 | On Linux: sudo apt-get install graphviz 45 | ``` 46 | 47 | ## Usage 48 | 49 | ### Single PDG Generation 50 | 51 | To generate the PDG of a specific *.js file, launch the following python3 commands from the `src` folder location: 52 | ``` 53 | >>> from build_pdg import get_data_flow 54 | >>> pdg = get_data_flow('INPUT_FILE', benchmarks=dict()) 55 | ``` 56 | 57 | Per default, the corresponding PDG will not be stored. To store it in an **existing** PDG_PATH folder, call: 58 | ``` 59 | $ python3 -c "from build_pdg import get_data_flow; get_data_flow('INPUT_FILE', benchmarks=dict(), store_pdgs='PDG_PATH')" 60 | ``` 61 | 62 | Note that we added a timeout of 10 min for the data flow/pointer analysis (cf. line 149 of `src/build_pdg.py`), and a memory limit of 20GB (cf. line 115 of `src/build_pdg.py`). 63 | 64 | ### PDG Generation - Multiprocessing 65 | 66 | Let's consider a directory `DIR` containing several JavaScript files to analyze. To generate the PDGs (= ASTs enhanced with control and data flow, and pointer analysis) of all these files, launch the following shell command from the `src` folder location: 67 | ``` 68 | $ python3 -c "from build_pdg import store_pdg_folder; store_pdg_folder('DIR')" 69 | ``` 70 | 71 | The corresponding PDGs will be stored in `DIR/PDG`. 72 | 73 | Currently, we are using 1 CPU, but you can change that by modifying the variable NUM\_WORKERS from `src/utility_df.py` (the one **line 51**). 74 | 75 | 76 | ## License 77 | 78 | This project is licensed under the terms of the AGPL3 license, which you can find in ```LICENSE```. -------------------------------------------------------------------------------- /src/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aurore54F/static-pdg-js/81dca1c778804eb6e2a45e1a0096f62010cab608/src/__init__.py -------------------------------------------------------------------------------- /src/build_ast.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021 Aurore Fass 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU Affero General Public License as published 5 | # by the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU Affero General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Affero General Public License 14 | # along with this program. If not, see . 15 | 16 | 17 | """ 18 | From JS source code to an Esprima AST exported in JSON. 19 | From JSON to ExtendedAst and Node objects. 20 | From Node objects to JSON. 21 | From JSON to JS source code using Escodegen. 22 | """ 23 | 24 | # Note: improved from HideNoSeek (bugs correction + semantic information to the nodes) 25 | 26 | 27 | import logging 28 | import json 29 | import os 30 | import subprocess 31 | 32 | import node as _node 33 | import extended_ast as _extended_ast 34 | 35 | SRC_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__))) 36 | 37 | 38 | def get_extended_ast(input_file, json_path, remove_json=True): 39 | """ 40 | JavaScript AST production. 41 | 42 | ------- 43 | Parameters: 44 | - input_file: str 45 | Path of the file to produce an AST from. 46 | - json_path: str 47 | Path of the JSON file to temporary store the AST in. 48 | - remove_json: bool 49 | Indicates whether to remove or not the JSON file containing the Esprima AST. 50 | Default: True. 51 | 52 | ------- 53 | Returns: 54 | - ExtendedAst 55 | The extended AST (i.e., contains type, filename, body, sourceType, range, comments, 56 | tokens, and possibly leadingComments) of input_file. 57 | - None if an error occurred. 58 | """ 59 | 60 | try: 61 | produce_ast = subprocess.run(['node', os.path.join(SRC_PATH, 'parser.js'), 62 | input_file, json_path], 63 | stdout=subprocess.PIPE, check=True) 64 | except subprocess.CalledProcessError: 65 | logging.critical('Esprima parsing error for %s', input_file) 66 | return None 67 | 68 | if produce_ast.returncode == 0: 69 | 70 | with open(json_path) as json_data: 71 | esprima_ast = json.loads(json_data.read()) 72 | if remove_json: 73 | os.remove(json_path) 74 | 75 | extended_ast = _extended_ast.ExtendedAst() 76 | extended_ast.filename = input_file 77 | extended_ast.set_type(esprima_ast['type']) 78 | extended_ast.set_body(esprima_ast['body']) 79 | extended_ast.set_source_type(esprima_ast['sourceType']) 80 | extended_ast.set_range(esprima_ast['range']) 81 | extended_ast.set_tokens(esprima_ast['tokens']) 82 | extended_ast.set_comments(esprima_ast['comments']) 83 | if 'leadingComments' in esprima_ast: 84 | extended_ast.set_leading_comments(esprima_ast['leadingComments']) 85 | 86 | return extended_ast 87 | 88 | logging.critical('Esprima could not produce an AST for %s', input_file) 89 | return None 90 | 91 | 92 | def indent(depth_dict): 93 | """ Indentation size. """ 94 | return '\t' * depth_dict 95 | 96 | 97 | def brace(key): 98 | """ Write a word between cases. """ 99 | return '|<' + key + '>' 100 | 101 | 102 | def print_dict(depth_dict, key, value, max_depth, delete_leaf): 103 | """ Print the content of a dict with specific indentation and braces for the keys. """ 104 | if depth_dict <= max_depth: 105 | print('%s%s' % (indent(depth_dict), brace(key))) 106 | beautiful_print_ast(value, depth=depth_dict + 1, max_depth=max_depth, 107 | delete_leaf=delete_leaf) 108 | 109 | 110 | def print_value(depth_dict, key, value, max_depth, delete_leaf): 111 | """ Print a dict value with respect to the indentation. """ 112 | if depth_dict <= max_depth: 113 | if all(dont_consider != key for dont_consider in delete_leaf): 114 | print(indent(depth_dict) + "| %s = %s" % (key, value)) 115 | 116 | 117 | def beautiful_print_ast(ast, delete_leaf, depth=0, max_depth=2 ** 63): 118 | """ 119 | Walking through an AST and printing it beautifully 120 | 121 | ------- 122 | Parameters: 123 | - ast: dict 124 | Contains an Esprima AST of a JS file, i.e., get_extended_ast(, ) 125 | output or get_extended_ast(, ).get_ast() output. 126 | - depth: int 127 | Initial depth of the tree. Default: 0. 128 | - max_depth: int 129 | Indicates the depth up to which the AST is printed. Default: 2**63. 130 | - delete_leaf: list 131 | Contains the leaf that should not be printed (e.g. 'range'). Default: [''], 132 | beware it is mutable. 133 | """ 134 | 135 | for k, v in ast.items(): # Because need k everywhere 136 | if isinstance(v, dict): 137 | print_dict(depth, k, v, max_depth, delete_leaf) 138 | elif isinstance(v, list): 139 | if not v: 140 | print_value(depth, k, v, max_depth, delete_leaf) 141 | for el in v: 142 | if isinstance(el, dict): 143 | print_dict(depth, k, el, max_depth, delete_leaf) 144 | else: 145 | print_value(depth, k, el, max_depth, delete_leaf) 146 | else: 147 | print_value(depth, k, v, max_depth, delete_leaf) 148 | 149 | 150 | def create_node(dico, node_body, parent_node, cond=False, filename=''): 151 | """ Node creation. """ 152 | 153 | if dico is None: # Not a Node, but needed a construct to store, e.g., [, a] = array 154 | node = _node.Node(name='None', parent=parent_node) 155 | parent_node.set_child(node) 156 | node.set_body(node_body) 157 | if cond: 158 | node.set_body_list(True) 159 | node.filename = filename 160 | 161 | elif 'type' in dico: 162 | if dico['type'] == 'FunctionDeclaration': 163 | node = _node.FunctionDeclaration(name=dico['type'], parent=parent_node) 164 | elif dico['type'] == 'FunctionExpression' or dico['type'] == 'ArrowFunctionExpression': 165 | node = _node.FunctionExpression(name=dico['type'], parent=parent_node) 166 | elif dico['type'] == 'ReturnStatement': 167 | node = _node.ReturnStatement(name=dico['type'], parent=parent_node) 168 | elif dico['type'] in _node.STATEMENTS: 169 | node = _node.Statement(name=dico['type'], parent=parent_node) 170 | elif dico['type'] in _node.VALUE_EXPR: 171 | node = _node.ValueExpr(name=dico['type'], parent=parent_node) 172 | elif dico['type'] == 'Identifier': 173 | node = _node.Identifier(name=dico['type'], parent=parent_node) 174 | else: 175 | node = _node.Node(name=dico['type'], parent=parent_node) 176 | 177 | if not node.is_comment(): # Otherwise comments are children and it is getting messy! 178 | parent_node.set_child(node) 179 | node.set_body(node_body) 180 | if cond: 181 | node.set_body_list(True) # Some attributes are stored in a list even when they 182 | # are alone. If we do not respect the initial syntax, Escodegen cannot built the 183 | # JS code back. 184 | node.filename = filename 185 | ast_to_ast_nodes(dico, node) 186 | 187 | 188 | def ast_to_ast_nodes(ast, ast_nodes=_node.Node('Program')): 189 | """ 190 | Convert an AST to Node objects. 191 | 192 | ------- 193 | Parameters: 194 | - ast: dict 195 | Output of get_extended_ast(, ).get_ast(). 196 | - ast_nodes: Node 197 | Current Node to be built. Default: ast_nodes=Node('Program'). Beware, always call the 198 | function indicating the default argument, otherwise the last value will be used 199 | (because the default parameter is mutable). 200 | 201 | ------- 202 | Returns: 203 | - Node 204 | The AST in format Node object. 205 | """ 206 | 207 | if 'filename' in ast: 208 | filename = ast['filename'] 209 | ast_nodes.set_attribute('filename', filename) 210 | else: 211 | filename = '' 212 | 213 | for k in ast: 214 | if k == 'filename' or k == 'loc' or k == 'range' or k == 'value' \ 215 | or (k != 'type' and not isinstance(ast[k], list) 216 | and not isinstance(ast[k], dict)) or k == 'regex': 217 | ast_nodes.set_attribute(k, ast[k]) # range is a list but stored as attributes 218 | if isinstance(ast[k], dict): 219 | if k == 'range': # Case leadingComments as range: {0: begin, 1: end} 220 | ast_nodes.set_attribute(k, ast[k]) 221 | else: 222 | create_node(dico=ast[k], node_body=k, parent_node=ast_nodes, filename=filename) 223 | elif isinstance(ast[k], list): 224 | if not ast[k]: # Case with empty list, e.g. params: [] 225 | ast_nodes.set_attribute(k, ast[k]) 226 | for el in ast[k]: 227 | if isinstance(el, dict): 228 | create_node(dico=el, node_body=k, parent_node=ast_nodes, cond=True, 229 | filename=filename) 230 | elif el is None: # Case [None, {stuff about a}] for [, a] = array 231 | create_node(dico=el, node_body=k, parent_node=ast_nodes, cond=True, 232 | filename=filename) 233 | return ast_nodes 234 | 235 | 236 | def print_ast_nodes(ast_nodes): 237 | """ 238 | Print the Nodes of ast_nodes with their properties. 239 | Debug function. 240 | 241 | ------- 242 | Parameters: 243 | - ast_nodes: Node 244 | Output of ast_to_ast_nodes(, ast_nodes=Node('Program')). 245 | """ 246 | 247 | for child in ast_nodes.children: 248 | print('Parent: ' + child.parent.name) 249 | print('Child: ' + child.name) 250 | print('Id: ' + str(child.id)) 251 | print('Attributes:') 252 | print(child.attributes) 253 | print('Body: ' + str(child.body)) 254 | print('Body_list: ' + str(child.body_list)) 255 | print('Is-leaf: ' + str(child.is_leaf())) 256 | print('-----------------------') 257 | print_ast_nodes(child) 258 | 259 | 260 | def build_json(ast_nodes, dico): 261 | """ 262 | Convert an AST format Node objects to JSON format. 263 | 264 | ------- 265 | Parameters: 266 | - ast_nodes: Node 267 | Output of ast_to_ast_nodes(, ast_nodes=Node('Program')). 268 | - dico: dict 269 | Current dict to be built. 270 | 271 | ------- 272 | Returns: 273 | - dict 274 | The AST in format JSON. 275 | """ 276 | 277 | if ast_nodes.name != 'None': # Nothing interesting in the None Node 278 | dico['type'] = ast_nodes.name 279 | if len(ast_nodes.children) >= 1: 280 | for child in ast_nodes.children: 281 | dico2 = {} 282 | if child.body_list: 283 | if child.body not in dico: 284 | dico[child.body] = [] # Some attributes just have to be stored in a list. 285 | build_json(child, dico2) 286 | if not dico2: # Case [, a] = array -> [None, {stuff about a}] (None and not {}) 287 | dico2 = None # Not sure if it could not be legitimate sometimes 288 | logging.warning('Transformed {} into None for Escodegen; was it legitimate?') 289 | dico[child.body].append(dico2) 290 | else: 291 | build_json(child, dico2) 292 | dico[child.body] = dico2 293 | elif ast_nodes.body_list == 'special': 294 | dico[ast_nodes.body] = [] 295 | else: 296 | pass 297 | for att in ast_nodes.attributes: 298 | dico[att] = ast_nodes.attributes[att] 299 | return dico 300 | 301 | 302 | def save_json(ast_nodes, json_path): 303 | """ 304 | Stores an AST format Node objects in a JSON file. 305 | 306 | ------- 307 | Parameters: 308 | - ast_nodes: Node 309 | Output of ast_to_ast_nodes(, ast_nodes=Node('Program')). 310 | - json_path: str 311 | Path of the JSON file to store the AST in. 312 | """ 313 | 314 | data = build_json(ast_nodes, dico={}) 315 | with open(json_path, 'w') as json_data: 316 | json.dump(data, json_data, indent=4) 317 | 318 | 319 | def get_code(json_path, code_path='1', remove_json=True, test=False): 320 | """ 321 | Convert JSON format back to JavaScript code. 322 | 323 | ------- 324 | Parameters: 325 | - json_path: str 326 | Path of the JSON file to build the code from. 327 | - code_path: str 328 | Path of the file to store the code in. If 1, then displays it to stdout. 329 | - remove_json: bool 330 | Indicates whether to remove or not the JSON file containing the Esprima AST. 331 | Default: True. 332 | - test: bool 333 | Indicates whether we are in test mode. Default: False. 334 | """ 335 | 336 | try: 337 | code = subprocess.run(['node', os.path.join(SRC_PATH, 'generate_js.js'), 338 | json_path, code_path], 339 | stdout=subprocess.PIPE, check=True) 340 | except subprocess.CalledProcessError: 341 | logging.exception('Something went wrong to get the code from the AST for %s', json_path) 342 | return None 343 | 344 | if remove_json: 345 | os.remove(json_path) 346 | if code.returncode != 0: 347 | logging.error('Something wrong happened while converting JS back to code for %s', json_path) 348 | return None 349 | 350 | if code_path == '1': 351 | if test: 352 | print((code.stdout.decode('utf-8')).replace('\n', '')) 353 | return (code.stdout.decode('utf-8')).replace('\n', '') 354 | 355 | return code_path 356 | -------------------------------------------------------------------------------- /src/build_pdg.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021 Aurore Fass 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU Affero General Public License as published 5 | # by the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU Affero General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Affero General Public License 14 | # along with this program. If not, see . 15 | 16 | 17 | """ 18 | Generation and storage of JavaScript PDGs. Possibility for multiprocessing (NUM_WORKERS 19 | defined in utility_df.py). 20 | """ 21 | 22 | import os 23 | import pickle 24 | import logging 25 | import timeit 26 | import json 27 | from multiprocessing import Process, Queue 28 | 29 | import node as _node 30 | import build_ast 31 | import utility_df 32 | import control_flow 33 | import data_flow 34 | import scope as _scope 35 | import display_graph 36 | 37 | # Builds the JS code from the AST, or not, to check for possible bugs in the AST building process. 38 | CHECK_JSON = utility_df.CHECK_JSON 39 | 40 | 41 | def pickle_dump_process(dfg_nodes, store_pdg): 42 | """ Call to pickle.dump """ 43 | pickle.dump(dfg_nodes, open(store_pdg, 'wb')) 44 | 45 | 46 | def function_hoisting(node, entry): 47 | """ Hoists FunctionDeclaration at the beginning of a basic block = Function bloc. """ 48 | 49 | # Will avoid problem if function first called and then defined 50 | for child in node.children: 51 | if child.name == 'FunctionDeclaration': 52 | child.adopt_child(step_daddy=entry) # Sets new parent and deletes old one 53 | function_hoisting(child, entry=child) # New basic block = FunctionDeclaration = child 54 | elif child.name == 'FunctionExpression': 55 | function_hoisting(child, entry=child) # New basic block = FunctionExpression = child 56 | else: 57 | function_hoisting(child, entry=entry) # Current basic block = entry 58 | 59 | 60 | def traverse(node): 61 | """ Debug function, traverse node. """ 62 | 63 | for child in node.children: 64 | print(child.name) 65 | traverse(child) 66 | 67 | 68 | def get_data_flow_process(js_path, benchmarks, store_pdgs): 69 | """ Call to get_data_flow. """ 70 | 71 | try: 72 | # save_path_pdg = js_path.split(".")[0] 73 | get_data_flow(input_file=js_path, benchmarks=benchmarks, store_pdgs=store_pdgs, 74 | beautiful_print=False, check_json=False, save_path_pdg=False) 75 | except Exception as e: 76 | print(e) 77 | raise e 78 | 79 | 80 | def get_data_flow(input_file, benchmarks, store_pdgs=None, check_var=False, beautiful_print=False, 81 | save_path_ast=False, save_path_cfg=False, save_path_pdg=False, 82 | check_json=CHECK_JSON): 83 | """ 84 | Builds the PDG: enhances the AST with CF, DF, and pointer analysis for a given file. 85 | 86 | ------- 87 | Parameters: 88 | - input_file: str 89 | Path of the file to analyze. 90 | - benchmarks: dict 91 | Contains the different micro benchmarks. Should be empty. 92 | - store_pdgs: str 93 | Path of the folder to store the PDG in. 94 | Or None to pursue without storing it. 95 | - check_var: bool 96 | Returns the unknown variables (not the PDG). 97 | - save_path_ast / cfg / pdg: 98 | False --> does neither produce nor store the graphical representation; 99 | None --> produces + displays the graphical representation; 100 | Valid-path --> produces + stores the graphical representation under the name Valid-path. 101 | - beautiful_print: bool 102 | Whether to beautiful print the AST or not. 103 | - check_json: bool 104 | Builds the JS code from the AST, or not, to check for bugs in the AST building process. 105 | 106 | ------- 107 | Returns: 108 | - Node 109 | PDG of the file. 110 | - or None if problems to build the PDG. 111 | - or list of unknown variables if check_var is True. 112 | """ 113 | 114 | start = timeit.default_timer() 115 | utility_df.limit_memory(20*10**9) # Limiting the memory usage to 20GB 116 | if input_file.endswith('.js'): 117 | esprima_json = input_file.replace('.js', '.json') 118 | else: 119 | esprima_json = input_file + '.json' 120 | extended_ast = build_ast.get_extended_ast(input_file, esprima_json) 121 | 122 | benchmarks['errors'] = [] 123 | 124 | if extended_ast is not None: 125 | benchmarks['got AST'] = timeit.default_timer() - start 126 | start = utility_df.micro_benchmark('Successfully got Esprima AST in', 127 | timeit.default_timer() - start) 128 | ast = extended_ast.get_ast() 129 | if beautiful_print: 130 | build_ast.beautiful_print_ast(ast, delete_leaf=[]) 131 | ast_nodes = build_ast.ast_to_ast_nodes(ast, ast_nodes=_node.Node('Program')) 132 | function_hoisting(ast_nodes, ast_nodes) # Hoists FunDecl at a basic block's beginning 133 | 134 | benchmarks['AST'] = timeit.default_timer() - start 135 | start = utility_df.micro_benchmark('Successfully produced the AST in', 136 | timeit.default_timer() - start) 137 | if save_path_ast is not False: 138 | display_graph.draw_ast(ast_nodes, attributes=True, save_path=save_path_ast) 139 | 140 | cfg_nodes = control_flow.control_flow(ast_nodes) 141 | benchmarks['CFG'] = timeit.default_timer() - start 142 | start = utility_df.micro_benchmark('Successfully produced the CFG in', 143 | timeit.default_timer() - start) 144 | if save_path_cfg is not False: 145 | display_graph.draw_cfg(cfg_nodes, attributes=True, save_path=save_path_cfg) 146 | 147 | unknown_var = [] 148 | try: 149 | with utility_df.Timeout(600): # Tries to produce DF within 10 minutes 150 | scopes = [_scope.Scope('Global')] 151 | dfg_nodes, scopes = data_flow.df_scoping(cfg_nodes, scopes=scopes, 152 | id_list=[], entry=1) 153 | # This may have to be added if we want to make the fake hoisting work 154 | # dfg_nodes = data_flow.df_scoping(dfg_nodes, scopes=scopes, id_list=[], entry=1)[0] 155 | except utility_df.Timeout.Timeout: 156 | logging.critical('Building the PDG timed out for %s', input_file) 157 | benchmarks['errors'].append('pdg-timeout') 158 | return _node.Node('Program') # Empty PDG to avoid trying to get the children of None 159 | 160 | # except MemoryError: # Catching it will catch ALL memory errors, 161 | # while we just want to avoid getting over our 20GB limit 162 | # logging.critical('Too much memory used for %s', input_file) 163 | # return _node.Node('Program') # Empty PDG to avoid trying to get the children of None 164 | 165 | benchmarks['PDG'] = timeit.default_timer() - start 166 | utility_df.micro_benchmark('Successfully produced the PDG in', 167 | timeit.default_timer() - start) 168 | if save_path_pdg is not False: 169 | display_graph.draw_pdg(dfg_nodes, attributes=True, save_path=save_path_pdg) 170 | 171 | if check_json: # Looking for possible bugs when building the AST / json doc in build_ast 172 | my_json = esprima_json.replace('.json', '-back.json') 173 | build_ast.save_json(dfg_nodes, my_json) 174 | print(build_ast.get_code(my_json)) 175 | 176 | if check_var: 177 | for scope in scopes: 178 | for unknown in scope.unknown_var: 179 | if not unknown.data_dep_parents: 180 | # If DD: not unknown, can happen because of hoisting FunctionDeclaration 181 | # After second function run, not unknown anymore 182 | logging.warning('The variable %s is not declared in the scope %s', 183 | unknown.attributes['name'], scope.name) 184 | unknown_var.append(unknown) 185 | return unknown_var 186 | 187 | if store_pdgs is not None: 188 | store_pdg = os.path.join(store_pdgs, os.path.basename(input_file.replace('.js', ''))) 189 | pickle_dump_process(dfg_nodes, store_pdg) 190 | json_analysis = os.path.join(store_pdgs, os.path.basename(esprima_json)) 191 | with open(json_analysis, 'w') as json_data: 192 | json.dump(benchmarks, json_data, indent=4, sort_keys=False, default=default, 193 | skipkeys=True) 194 | return dfg_nodes 195 | benchmarks['errors'].append('parsing-error') 196 | return _node.Node('ParsingError') # Empty PDG to avoid trying to get the children of None 197 | 198 | 199 | def default(o): 200 | """ To avoid TypeError, conversion of problematic objects into str. """ 201 | 202 | return str(o) 203 | 204 | 205 | def handle_one_pdg(root, js, store_pdgs): 206 | """ Stores the PDG of js located in root, in store_pdgs. """ 207 | 208 | benchmarks = dict() 209 | if js.endswith('.js'): 210 | print(os.path.join(store_pdgs, js.replace('.js', ''))) 211 | js_path = os.path.join(root, js) 212 | if not os.path.isfile(js_path): 213 | logging.error('The path %s does not exist', js_path) 214 | return False 215 | # Some PDGs lead to Segfault, avoids killing the current process 216 | p = Process(target=get_data_flow_process, args=(js_path, benchmarks, store_pdgs)) 217 | p.start() 218 | p.join() 219 | if p.exitcode != 0: 220 | logging.critical('Something wrong occurred with %s PDG generation', js_path) 221 | return False 222 | return True 223 | 224 | 225 | def worker(my_queue): 226 | """ Worker """ 227 | 228 | while True: 229 | try: 230 | root, js, store_pdgs = my_queue.get(timeout=2) 231 | handle_one_pdg(root, js, store_pdgs) 232 | except Exception as e: 233 | logging.exception(e) 234 | break 235 | 236 | 237 | def store_pdg_folder(folder_js): 238 | """ 239 | Stores the PDGs of the JS files from folder_js. 240 | 241 | ------- 242 | Parameter: 243 | - folder_js: str 244 | Path of the folder containing the files to get the PDG of. 245 | """ 246 | 247 | start = timeit.default_timer() 248 | 249 | my_queue = Queue() 250 | workers = list() 251 | 252 | if not os.path.exists(folder_js): 253 | logging.exception('The path %s does not exist', folder_js) 254 | return 255 | store_pdgs = os.path.join(folder_js, 'PDG') 256 | if not os.path.exists(store_pdgs): 257 | os.makedirs(store_pdgs) 258 | 259 | for root, _, files in os.walk(folder_js): 260 | for js in files: 261 | my_queue.put([root, js, store_pdgs]) 262 | 263 | for _ in range(utility_df.NUM_WORKERS): 264 | p = Process(target=worker, args=(my_queue,)) 265 | p.start() 266 | print("Starting process") 267 | workers.append(p) 268 | 269 | for w in workers: 270 | w.join() 271 | 272 | utility_df.micro_benchmark('Total elapsed time:', timeit.default_timer() - start) 273 | -------------------------------------------------------------------------------- /src/control_flow.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021 Aurore Fass 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU Affero General Public License as published 5 | # by the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU Affero General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Affero General Public License 14 | # along with this program. If not, see . 15 | 16 | 17 | """ 18 | Adds control flow to the AST. 19 | """ 20 | 21 | # Note: slightly improved from HideNoSeek 22 | 23 | 24 | import node as _node 25 | 26 | 27 | def link_expression(node, node_parent): 28 | """ Non-statement node. """ 29 | if node.is_comment(): 30 | pass 31 | else: 32 | node_parent.set_statement_dependency(extremity=node) 33 | return node 34 | 35 | 36 | def epsilon_statement_cf(node): 37 | """ Non-conditional statements. """ 38 | for child in node.children: 39 | if isinstance(child, _node.Statement): 40 | node.set_control_dependency(extremity=child, label='e') 41 | else: 42 | link_expression(node=child, node_parent=node) 43 | 44 | 45 | def do_while_cf(node): 46 | """ DoWhileStatement. """ 47 | # Element 0: body (Statement) 48 | # Element 1: test (Expression) 49 | node.set_control_dependency(extremity=node.children[0], label=True) 50 | link_expression(node=node.children[1], node_parent=node) 51 | 52 | 53 | def for_cf(node): 54 | """ ForStatement. """ 55 | # Element 0: init 56 | # Element 1: test (Expression) 57 | # Element 2: update (Expression) 58 | # Element 3: body (Statement) 59 | """ ForOfStatement. """ 60 | # Element 0: left 61 | # Element 1: right 62 | # Element 2: body (Statement) 63 | i = 0 64 | for child in node.children: 65 | if child.body != 'body': 66 | link_expression(node=child, node_parent=node) 67 | elif not child.is_comment(): 68 | node.set_control_dependency(extremity=child, label=True) 69 | i += 1 70 | 71 | 72 | def if_cf(node): 73 | """ IfStatement. """ 74 | # Element 0: test (Expression) 75 | # Element 1: consequent (Statement) 76 | # Element 2: alternate (Statement) 77 | link_expression(node=node.children[0], node_parent=node) 78 | if len(node.children) > 1: # Not sure why, but can happen... 79 | node.set_control_dependency(extremity=node.children[1], label=True) 80 | if len(node.children) > 2: 81 | if node.children[2].is_comment(): 82 | pass 83 | else: 84 | node.set_control_dependency(extremity=node.children[2], label=False) 85 | 86 | 87 | def try_cf(node): 88 | """ TryStatement. """ 89 | # Element 0: block (Statement) 90 | # Element 1: handler (Statement) / finalizer (Statement) 91 | # Element 2: finalizer (Statement) 92 | node.set_control_dependency(extremity=node.children[0], label=True) 93 | if node.children[1].body == 'handler': 94 | node.set_control_dependency(extremity=node.children[1], label=False) 95 | else: # finalizer 96 | node.set_control_dependency(extremity=node.children[1], label='e') 97 | if len(node.children) > 2: 98 | if node.children[2].body == 'finalizer': 99 | node.set_control_dependency(extremity=node.children[2], label='e') 100 | 101 | 102 | def while_cf(node): 103 | """ WhileStatement. """ 104 | # Element 0: test (Expression) 105 | # Element 1: body (Statement) 106 | link_expression(node=node.children[0], node_parent=node) 107 | node.set_control_dependency(extremity=node.children[1], label=True) 108 | 109 | 110 | def switch_cf(node): 111 | """ SwitchStatement. """ 112 | # Element 0: discriminant 113 | # Element 1: cases (SwitchCase) 114 | 115 | switch_cases = node.children 116 | link_expression(node=switch_cases[0], node_parent=node) 117 | if len(switch_cases) > 1: 118 | # SwitchStatement -> True -> SwitchCase for first one 119 | node.set_control_dependency(extremity=switch_cases[1], label='e') 120 | switch_case_cf(switch_cases[1]) 121 | for i in range(2, len(switch_cases)): 122 | if switch_cases[i].is_comment(): 123 | pass 124 | else: 125 | # SwitchCase -> False -> SwitchCase for the other ones 126 | switch_cases[i - 1].set_control_dependency(extremity=switch_cases[i], label=False) 127 | if i != len(switch_cases) - 1: 128 | switch_case_cf(switch_cases[i]) 129 | else: # Because the last switch is executed per default, i.e. without condition 1st 130 | switch_case_cf(switch_cases[i], last=True) 131 | # Otherwise, we could just have a switch(something) {} 132 | 133 | 134 | def switch_case_cf(node, last=False): 135 | """ SwitchCase. """ 136 | # Element 0: test 137 | # Element 1: consequent (Statement) 138 | nb_child = len(node.children) 139 | if nb_child > 1: 140 | if not last: # As all switches but the last have to respect a condition to enter the branch 141 | link_expression(node=node.children[0], node_parent=node) 142 | j = 1 143 | else: 144 | j = 0 145 | for i in range(j, nb_child): 146 | if node.children[i].is_comment(): 147 | pass 148 | else: 149 | node.set_control_dependency(extremity=node.children[i], label=True) 150 | elif nb_child == 1: 151 | node.set_control_dependency(extremity=node.children[0], label=True) 152 | 153 | 154 | def conditional_statement_cf(node): 155 | """ For the conditional nodes. """ 156 | if node.name == 'DoWhileStatement': 157 | do_while_cf(node) 158 | elif node.name == 'ForStatement' or node.name == 'ForOfStatement'\ 159 | or node.name == 'ForInStatement': 160 | for_cf(node) 161 | elif node.name == 'IfStatement' or node.name == 'ConditionalExpression': 162 | if_cf(node) 163 | elif node.name == 'WhileStatement': 164 | while_cf(node) 165 | elif node.name == 'TryStatement': 166 | try_cf(node) 167 | elif node.name == 'SwitchStatement': 168 | switch_cf(node) 169 | elif node.name == 'SwitchCase': 170 | pass # Already handled in SwitchStatement 171 | 172 | 173 | def control_flow(ast_nodes): 174 | """ 175 | Enhance the AST by adding statement and control dependencies to each Node. 176 | 177 | ------- 178 | Parameters: 179 | - ast_nodes: Node 180 | Output of ast_to_ast_nodes(, ast_nodes=Node('Program')). 181 | 182 | ------- 183 | Returns: 184 | - Node 185 | With statement and control dependencies added. 186 | """ 187 | 188 | for child in ast_nodes.children: 189 | if child.name in _node.EPSILON or child.name in _node.UNSTRUCTURED: 190 | epsilon_statement_cf(child) 191 | elif child.name in _node.CONDITIONAL: 192 | conditional_statement_cf(child) 193 | else: 194 | for grandchild in child.children: 195 | link_expression(node=grandchild, node_parent=child) 196 | control_flow(child) 197 | return ast_nodes 198 | -------------------------------------------------------------------------------- /src/data_flow.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021 Aurore Fass 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU Affero General Public License as published 5 | # by the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU Affero General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Affero General Public License 14 | # along with this program. If not, see . 15 | 16 | 17 | """ 18 | Adds data flow to the AST previously enhanced with control flow. 19 | """ 20 | 21 | # Note: new data flow analysis, going significantly beyond the one of HideNoSeek: 22 | # pointer analysis, function argument passing, parameter flows, handling scope, etc 23 | 24 | 25 | import logging 26 | import copy 27 | 28 | import node as _node 29 | import js_reserved 30 | import scope as _scope 31 | import utility_df 32 | from build_ast import save_json, get_code 33 | from pointer_analysis import map_var2value, compute_update_expression, display_values 34 | from js_operators import get_node_computed_value, get_node_value 35 | 36 | # To print the exceptions encountered while building the PDG, or not 37 | PDG_EXCEPT = utility_df.PDG_EXCEPT 38 | # If function called on itself, then max times to avoid infinite recursion 39 | LIMIT_RETRAVERSE = utility_df.LIMIT_RETRAVERSE 40 | # If iterating through a loop, then max times to avoid infinite loops 41 | LIMIT_LOOP = utility_df.LIMIT_LOOP 42 | 43 | """ 44 | In the following, 45 | - scopes: list of Scope 46 | Stores the variables currently declared and where they should be referred to. 47 | - id_list: list 48 | Stores the id of the node already handled. 49 | - entry: int 50 | Indicates if we are in the global scope (1) or not (0). 51 | 52 | If not stated otherwise, 53 | - node: Node 54 | Current node. 55 | 56 | If not stated otherwise, the defined functions return a list of Scope. 57 | """ 58 | 59 | 60 | def get_pos_identifier(identifier_node, scopes): 61 | """ Position of identifier_node in the corresponding scope. """ 62 | 63 | for scope_index, scope in reversed(list(enumerate(scopes))): 64 | # Search from local scopes to the global one, if no match found 65 | var_index = scope.get_pos_identifier(identifier_node) 66 | if var_index is not None: 67 | return var_index, scope_index # Variable position, corresponding scope index 68 | return None, None 69 | 70 | 71 | def get_nearest_statement(node, answer=None, fun_expr=False): 72 | """ 73 | Gets the statement node nearest to node (using CF). 74 | 75 | ------- 76 | Parameters: 77 | - answer: Node 78 | Such that isinstance(answer, _node.Statement) = True. Used to force taking a statement 79 | node parent of the nearest node (use case: boolean DF). Default: None. 80 | - fun_expr: bool 81 | Specific to FunctionExpression nodes. Default: False. 82 | 83 | ------- 84 | Returns: 85 | - Node: 86 | answer, if given, otherwise the statement node nearest to node. 87 | """ 88 | 89 | if answer is not None: 90 | return answer 91 | 92 | # else: answer is None 93 | 94 | if isinstance(node, _node.Statement)\ 95 | or (fun_expr and isinstance(node, _node.FunctionExpression)): 96 | # To also get the code back from a FunctionExpression node (which is no Statement) 97 | return node 98 | 99 | if len(node.statement_dep_parents) > 1: 100 | logging.warning('Several statement dependencies are joining on the same node %s', 101 | node.name) 102 | return get_nearest_statement(node.parent, fun_expr=fun_expr) 103 | 104 | 105 | def set_data_dep(begin_data_dep, identifier_node, scopes, nearest_statement=None): 106 | """ 107 | Sets the DD from begin_data_dep to identifier_node. Also updates the value of 108 | identifier_node with the value of begin_data_dep. 109 | 110 | ------- 111 | Parameters: 112 | - begin_data_dep: Node 113 | Begin of the DF. 114 | - identifier_node: Node 115 | End of the DF. 116 | - nearest_statement: Node or None 117 | Nearest statement node stored or None. 118 | """ 119 | 120 | begin_data_dep.set_data_dependency(extremity=identifier_node, 121 | nearest_statement=nearest_statement) # Draws DD 122 | identifier_node.set_value(begin_data_dep.value) # Initiates new node to previous value 123 | identifier_node.set_code(begin_data_dep.code) # Initiates new node to previous code 124 | 125 | if begin_data_dep.fun is not None: # The beginning of the DF is a function 126 | function_def = begin_data_dep.fun 127 | how_called = identifier_node.parent 128 | if how_called.name in _node.CALL_EXPR\ 129 | and how_called.children[0].id == identifier_node.id: 130 | # Case from handle_call_expr 131 | pass 132 | else: 133 | # The function may be executed even without CallExpr/TaggedTemplateExpr, but with 134 | # a Promise or a callback; ensures that the function will be retraversed here 135 | logging.debug('Retraversing the function') 136 | # Traverse function again 137 | function_def.set_retraverse() # Sets retraverse property to True 138 | function_scope(node=function_def, scopes=scopes, id_list=[]) 139 | # Not sure if scopes properly handled... 140 | 141 | 142 | def set_df(scope, var_index, identifier_node, scopes): 143 | """ 144 | Sets the DD from the variable in scope at position var_index, to identifier_node. 145 | 146 | ------- 147 | Parameters: 148 | - scope: Scope 149 | List of variables. 150 | - var_index: int 151 | Position of the variable considered in var. 152 | - identifier_node: Node 153 | End of the DF. 154 | """ 155 | 156 | if not isinstance(scope, _scope.Scope): 157 | logging.error('The parameter given should be typed Scope. Got %s', str(scope)) 158 | else: 159 | begin_df = get_nearest_statement(scope.var_list[var_index], scope.var_if2_list[var_index]) 160 | begin_id_df = scope.var_list[var_index] 161 | if isinstance(begin_df, list): 162 | for i, _ in enumerate(begin_df): 163 | set_data_dep(begin_data_dep=begin_df[i], identifier_node=identifier_node, 164 | scopes=scopes) 165 | else: 166 | set_data_dep(begin_data_dep=begin_id_df, identifier_node=identifier_node, 167 | nearest_statement=begin_df, scopes=scopes) 168 | 169 | 170 | def search_identifiers(node, id_list, tab, rec=True): 171 | """ 172 | Searches the Identifier nodes children of node. 173 | 174 | ------- 175 | Parameters: 176 | - tab: list 177 | To store the Identifier nodes found. 178 | - rec: Bool 179 | Indicates whether to go recursively in the node or not. Default: True (i.e. recursive). 180 | 181 | ------- 182 | Returns: 183 | - list 184 | Stores the Identifier nodes found. 185 | """ 186 | 187 | if node.name == 'ObjectExpression': # Only consider the object name, no properties 188 | pass 189 | elif node.name in _node.CALL_EXPR: # Don't want to go there, as param should not be detected 190 | pass 191 | elif node.name == 'Identifier': 192 | """ 193 | MemberExpression can be: 194 | - obj.prop[.prop.prop...]: we consider only obj; 195 | - this.something or window.something: we consider only something. 196 | """ 197 | if node.parent.name == 'MemberExpression': 198 | if node.parent.children[0] == node: # left member 199 | if get_node_computed_value(node) in _node.GLOBAL_VAR: # do nothing if window &co 200 | id_list.append(node.id) # As GLOBAL_VAR are still Identifiers 201 | logging.debug('%s is not the variable\'s name', node.attributes['name']) 202 | 203 | else: 204 | tab.append(node) # store left member as not window &co 205 | 206 | elif node.parent.children[1] == node: # right member 207 | if node.parent.children[0].name == 'ThisExpression'\ 208 | or get_node_computed_value(node.parent.children[0]) in _node.GLOBAL_VAR: 209 | # left member is not a valid Identifier, what about right member? 210 | if get_node_computed_value(node) in _node.GLOBAL_VAR: # ignore right member too 211 | id_list.append(node.id) # As GLOBAL_VAR are still Identifiers 212 | logging.debug('%s is not the variable\'s name', node.attributes['name']) 213 | 214 | else: 215 | tab.append(node) # store right member as not window &co 216 | 217 | else: # left member is a valid Identifier, consider right too only if bracket... 218 | if node.parent.attributes['computed']: # ... notation as could be an index 219 | logging.debug('The variable %s was considered', node.attributes['name']) 220 | tab.append(node) 221 | else: 222 | tab.append(node) # Otherwise this is just a variable 223 | else: 224 | if rec: 225 | for child in node.children: 226 | search_identifiers(child, id_list, tab, rec) 227 | 228 | return tab 229 | 230 | 231 | def assignment_df(identifier_node, scopes, update=False): 232 | """ Adds DD on Identifier nodes. """ 233 | 234 | var_index, scope_index = get_pos_identifier(identifier_node, scopes) 235 | if var_index is not None: # Position of identifier_node 236 | if scope_index == 0: # Global scope 237 | logging.debug('The global variable %s was used', identifier_node.attributes['name']) 238 | else: 239 | logging.debug('The variable %s was used', identifier_node.attributes['name']) 240 | # Data dependency between last time variable used and now 241 | set_df(scopes[scope_index], var_index, identifier_node, scopes=scopes) 242 | if update: # To update last Identifier handler with current one 243 | scopes[scope_index].update_var(var_index, identifier_node) 244 | 245 | elif identifier_node.attributes['name'].lower() not in js_reserved.KNOWN_WORDS_LOWER: 246 | logging.debug('The variable %s is unknown', identifier_node.attributes['name']) 247 | scopes[0].add_unknown_var(identifier_node) 248 | 249 | 250 | def var_decl_df(node, scopes, entry, assignt=False, obj=False, let_const=False): 251 | """ 252 | Handles the variables declared. 253 | 254 | ------- 255 | Parameters: 256 | - node: Node 257 | Node whose name Identifier is. 258 | - assignt: Bool 259 | False if this is a variable declaration with var/let, True if with AssignmentExpression. 260 | Default: False. 261 | - obj: Bool 262 | True if node is an object, False if it is a variable. Default: False. 263 | - let_const: Bool 264 | Specific scope for variables declared with let/const keyword. Default: False. 265 | """ 266 | 267 | if_else_assignt = False 268 | 269 | if let_const or 'let_const' in scopes[-1].name: 270 | # Specific scope for variables declared with let/const keyword 271 | current_scope = scopes[-1:] 272 | elif len(scopes) == 1 or entry == 1\ 273 | or (assignt and get_pos_identifier(node, scopes[1:])[0] is None): 274 | # Only one scope or global scope or (directly assigned and not known as a local variable) 275 | current_scope = scopes[:1] # Global scope 276 | else: 277 | current_scope = scopes[1:] # Local scope 278 | 279 | var_index, scope_index = get_pos_identifier(node, current_scope) 280 | 281 | if var_index is None: 282 | current_scope[-1].add_var(node) # Add variable in the list 283 | if not assignt: 284 | logging.debug('The variable %s was declared', node.attributes['name']) 285 | else: 286 | logging.debug('The global variable %s was declared', node.attributes['name']) 287 | # hoisting(node, scopes) # Hoisting only for FunctionDeclaration 288 | 289 | else: 290 | if assignt: 291 | if obj: # In the case of objects, we will always keep their AST order 292 | logging.debug('The object %s was used and modified', node.attributes['name']) 293 | # Data dependency between last time object used and now 294 | set_df(current_scope[scope_index], var_index, node, scopes=scopes) 295 | else: 296 | logging.debug('The variable %s was modified', node.attributes['name']) 297 | # To update variable provenance + DF (needed for True/False merged with other scope) 298 | current_scope[scope_index].add_var_if2(var_index, node) 299 | if_else_assignt = True 300 | else: 301 | logging.debug('The variable %s was redefined', node.attributes['name']) 302 | 303 | if not if_else_assignt: # Otherwise already added in var_if2 304 | current_scope[scope_index].update_var(var_index, node) # Update last time with current 305 | 306 | 307 | def var_declaration_df(node, scopes, id_list, entry, let_const=False): 308 | """ Handles the node VariableDeclarator: 1) Element0: id, 2) Element1: init. """ 309 | 310 | if node.name == 'VariableDeclarator': 311 | identifiers = search_identifiers(node.children[0], id_list, tab=[]) # Var definition 312 | 313 | if node.children[0].name != 'ObjectPattern': # Traditional variable declaration 314 | for decl in identifiers: 315 | id_list.append(decl.id) 316 | var_decl_df(node=decl, scopes=scopes, entry=entry, let_const=let_const) 317 | if not identifiers: 318 | logging.warning('No identifier variable found') 319 | 320 | else: # Specific case for ObjectPattern 321 | logging.debug('The node %s is an object pattern', node.name) 322 | scopes = obj_pattern_scope(node.children[0], scopes=scopes, id_list=id_list) 323 | 324 | if len(node.children) > 1: # Variable initialized 325 | scopes = data_flow(node.children[1], scopes, id_list=id_list, entry=entry) 326 | map_var2value(node, identifiers) 327 | 328 | elif node.children[0].name != 'ObjectPattern': # Var (so not objPattern) not initialized 329 | for decl in identifiers: 330 | logging.debug('The variable %s was not initialized', decl.attributes['name']) 331 | 332 | else: # ObjectPattern not initialized 333 | logging.debug('The ObjectPattern %s was not initialized', node.children[0].attributes) 334 | 335 | if len(node.children) > 2: 336 | logging.warning('I did not expect a %s node to have more than 2 children', node.name) 337 | 338 | return scopes 339 | 340 | 341 | def assignment_expr_df(node, scopes, id_list, entry, call_expr=False): 342 | """ Handles the node AssignmentExpression: 1) Element0: assignee, 2) Element1: assignt. """ 343 | 344 | operator = None 345 | identifiers = search_identifiers(node.children[0], id_list, tab=[]) 346 | for assignee in identifiers: 347 | id_list.append(assignee.id) 348 | 349 | # 1) To draw DD from old assignee version 350 | if 'operator' in assignee.parent.attributes: 351 | if assignee.parent.attributes['operator'] != '=': # Could be += where assignee is used 352 | operator = assignee.parent.attributes['operator'] 353 | assignment_df(identifier_node=assignee, scopes=scopes) 354 | 355 | # 2) The old assignee version can be replaced by the current one 356 | if (assignee.parent.name == 'MemberExpression' 357 | and assignee.parent.children[0].name != 'ThisExpression' 358 | and 'window' not in assignee.parent.children[0].attributes.values())\ 359 | or (assignee.parent.name == 'MemberExpression' 360 | and assignee.parent.parent.name == 'MemberExpression'): 361 | # assignee is an object, we excluded window/this.var, but not window/this.obj.prop 362 | # logging.warning(assignee.attributes['name']) 363 | if assignee.parent.attributes['computed']: # Access through a table, could be an index 364 | # assignment_df(identifier_node=assignee, scopes=scopes) 365 | # if get_pos_identifier(assignee, scopes)[0] is not None: 366 | var_decl_df(node=assignee, scopes=scopes, assignt=True, obj=True, entry=entry) 367 | else: 368 | if call_expr: 369 | # if get_pos_identifier(assignee, scopes)[0] is not None: 370 | # Only if the obj assignee already defined, avoids DF on console.log 371 | var_decl_df(node=assignee, scopes=scopes, assignt=True, obj=True, 372 | entry=entry) 373 | else: 374 | # if get_pos_identifier(assignee, scopes)[0] is not None: 375 | var_decl_df(node=assignee, scopes=scopes, assignt=True, obj=True, 376 | entry=entry) 377 | else: # assignee is a variable 378 | var_decl_df(node=assignee, scopes=scopes, assignt=True, entry=entry) 379 | 380 | if not identifiers: 381 | logging.warning('No identifier assignee found') 382 | 383 | for i in range(1, len(node.children)): 384 | scopes = data_flow(node.children[i], scopes=scopes, id_list=id_list, entry=entry) 385 | map_var2value(node, identifiers, operator=operator) 386 | 387 | return scopes 388 | 389 | 390 | def update_expr_df(node, scopes, id_list, entry): 391 | """ Handles the node UpdateExpression: Element0: argument. """ 392 | 393 | arguments = search_identifiers(node.children[0], id_list, tab=[]) 394 | for argument in arguments: 395 | # Variable used, modified, used to have 2 data dependencies, one on the original variable 396 | # and one of the variable modified that will be used after. 397 | assignment_df(identifier_node=argument, scopes=scopes) 398 | var_decl_df(node=argument, scopes=scopes, assignt=True, entry=entry) 399 | assignment_df(identifier_node=argument, scopes=scopes) 400 | compute_update_expression(node, argument) 401 | display_values(var=argument, keep_none=False) # Display values 402 | 403 | if not arguments: 404 | logging.warning('No identifier assignee found') 405 | 406 | 407 | def identifier_update(node, scopes, id_list, entry): 408 | """ Adds data flow to the considered node. """ 409 | 410 | identifiers = search_identifiers(node, id_list, rec=False, tab=[]) 411 | # rec=False so as to not get the same Identifier multiple times by going through its family. 412 | for identifier in identifiers: 413 | if identifier.parent.name == 'CatchClause': # As an identifier can be used as a parameter 414 | # Ex: catch(err) {}, err has to be defined here 415 | var_decl_df(node=node, scopes=scopes, entry=entry) 416 | else: 417 | # Note: pointer analysis is wrong here because of update = True stuff... 418 | update = False 419 | check_callee = identifier 420 | while check_callee.parent.name == 'MemberExpression': 421 | check_callee = check_callee.parent 422 | if check_callee.name == 'MemberExpression' and 'callee' in check_callee.body: 423 | update = True 424 | # update is True for CallExpr callee, e.g., arr = []; arr.X(); we want the last arr to 425 | # be the handler for the arr variable, and not the first one 426 | # issue for object using their properties in themselves, perhaps store both 427 | assignment_df(identifier_node=identifier, scopes=scopes, update=update) 428 | 429 | 430 | def hoisting(node, scopes): 431 | """ Checks if unknown variables are in fact function names which were hoisted. """ 432 | 433 | for scope in scopes: 434 | unknown_var_copy = copy.copy(scope.unknown_var) 435 | for unknown in unknown_var_copy: 436 | if node.attributes['name'] == unknown.attributes['name']: 437 | logging.debug('Hoisting, %s was first used, then defined', node.attributes['name']) 438 | node.set_data_dependency(extremity=unknown) 439 | scope.remove_unknown_var(unknown) 440 | 441 | 442 | def function_scope(node, scopes, id_list): 443 | """ Function scope. """ 444 | 445 | fun_expr = False 446 | if isinstance(node, _node.FunctionExpression): 447 | fun_expr = True 448 | 449 | retraverse = node.retraverse # True if we are retraversing the function, False if 1st traversal 450 | 451 | last_scope_inx = len(scopes) 452 | rec = 0 453 | for i in range(last_scope_inx): 454 | for j in range(i + 1, last_scope_inx): 455 | # The 2 functions' scope could be separated, e.g., by a Branch_true scope 456 | if scopes[i].function is not None and scopes[j].function is not None: 457 | if scopes[i].function.id == scopes[j].function.id: 458 | rec += 1 # Count the number of identical Function scopes 459 | 460 | if rec < LIMIT_RETRAVERSE: # To avoid infinite recursion if function called on itself 461 | 462 | scopes.append(_scope.Scope('Function')) # Added function scope 463 | scopes[-1].set_function(node) # Storing entry point to the function 464 | 465 | for child in node.children: 466 | if child.body == 'id': # Function's name 467 | id_list.append(child.id) 468 | if not fun_expr: 469 | if not retraverse: 470 | node.set_fun_name(child) # Function name so that can be used in upper scope 471 | var_decl_df(node=child, scopes=scopes[:-1], entry=0) 472 | if not retraverse: 473 | hoisting(child, scopes) # Only for FunDecl 474 | else: # Name of a FunctionExpression so that it can be used in the function's scope 475 | if not retraverse: 476 | node.set_fun_intern_name(child) 477 | var_decl_df(node=child, scopes=scopes, entry=0) 478 | 479 | if child.body == 'params': # Function's parameters 480 | id_list.append(child.id) 481 | if not retraverse: 482 | node.add_fun_param(child) 483 | if child.name == 'Identifier': 484 | # var_decl_df(node=child, scopes=scopes, entry=0) # No, param should be defined 485 | scopes[-1].add_var(child) # Add param variable in function's scope 486 | else: # Could be, e.g., an ObjectPattern 487 | build_dfg_content(child, scopes=scopes, id_list=id_list, entry=0) 488 | 489 | else: # Function's block 490 | scopes = data_flow(child, scopes=scopes, id_list=id_list, entry=0) 491 | 492 | let_const_scope(node, scopes) # Limit scope when going out of the block 493 | scopes.pop() # Variables declared before entering the function + function name 494 | 495 | if not retraverse: 496 | for el in node.fun_return: 497 | el.set_value(get_node_value(el, initial_node=node)) 498 | 499 | try: 500 | if not fun_expr: 501 | logging.debug('The function %s defined with following parameters %s returns %s', 502 | node.fun_name.attributes['name'], 503 | [el.attributes['name'] for el in node.fun_params], 504 | [el.value for el in node.fun_return]) 505 | else: 506 | logging.debug('The FunExpr defined with following parameters %s returns %s', 507 | [el.attributes['name'] for el in node.fun_params], 508 | [el.value for el in node.fun_return]) 509 | 510 | except KeyError: # If param is not an Identifier, could be, e.g., an ObjectPattern 511 | if not fun_expr: 512 | logging.debug('The function %s defined with following parameters %s returns %s', 513 | node.fun_name.attributes['name'], 514 | [el.name for el in node.fun_params], 515 | [el.value for el in node.fun_return]) 516 | else: 517 | logging.debug('The FunExpr defined with following parameters %s returns %s', 518 | [el.name for el in node.fun_params], 519 | [el.value for el in node.fun_return]) 520 | 521 | return scopes 522 | 523 | 524 | def obj_expr_scope(node, scopes, id_list): 525 | """ ObjectExpression scope. """ 526 | 527 | scopes.append(_scope.Scope('ObjectExpression')) # Added object scope 528 | 529 | for prop in node.children: 530 | for child in prop.children: 531 | if child.body == 'key': 532 | identifiers = search_identifiers(child, id_list, tab=[]) 533 | for param in identifiers: 534 | id_list.append(param.id) 535 | # var_decl_df(node=param, scopes=scopes, entry=0) # No need to store the key?? 536 | hoisting(param, scopes) 537 | 538 | else: 539 | scopes = data_flow(child, scopes=scopes, id_list=id_list, entry=0) 540 | node.set_provenance(child) 541 | 542 | let_const_scope(node, scopes) # Limit scope when going out of the block 543 | scopes.pop() # Back to the initial scope when we are not in the object anymore 544 | 545 | return scopes 546 | 547 | 548 | def obj_pattern_scope(node, scopes, id_list): 549 | """ ObjectPattern scope. """ 550 | 551 | for prop in node.children: 552 | for child in prop.children: 553 | if child.body == 'value': # Actual property name is somewhere here 554 | if not isinstance(child, _node.Identifier): 555 | scopes = data_flow(child, scopes=scopes, id_list=id_list, entry=0) 556 | else: # Actual property name, considered as a variable 557 | id_list.append(child.id) 558 | var_decl_df(node=child, scopes=scopes, entry=0) 559 | 560 | elif child.body == 'key': # Key, but very local to the object, not a variable 561 | pass 562 | else: 563 | logging.warning('The node %s had unexpected properties %s on %s', node.name, 564 | child.body, child.name) 565 | 566 | let_const_scope(node, scopes) # Limit scope when going out of the block 567 | 568 | return scopes 569 | 570 | 571 | def get_var_branch(node_list, scopes, id_list, entry, scope_name): 572 | """ 573 | Statement scope for boolean conditions. 574 | 575 | ------- 576 | Parameters: 577 | - node_list: list of Nodes 578 | Current nodes to be handled. 579 | 580 | ------- 581 | Returns: 582 | - initial_scope, and local_scope and global_scope from the considered branch 583 | """ 584 | 585 | scopes.append(_scope.Scope(scope_name)) # scopes modified for the branch 586 | global_scope = scopes[0].copy_scope() 587 | 588 | for boolean_node in node_list: 589 | scopes = data_flow(boolean_node, scopes=scopes, id_list=id_list, entry=entry) 590 | 591 | local_scope_cf = scopes.pop() # Scope modified in a True/False branch 592 | global_scope_cf = scopes.pop(0) # Global scope modified in a True/False branch 593 | scopes.insert(0, global_scope) # All scopes; do not contain variables declared in a True/False 594 | # branch, but may contain variables previously declared but modified in a True/False branch 595 | 596 | return scopes, local_scope_cf, global_scope_cf 597 | 598 | 599 | def merge_var_boolean_cf(current_scope, scope_true, scope_false): 600 | """ 601 | Merges in scope_true the variables declared in the true and false scope. 602 | 603 | ------- 604 | Parameters: 605 | - current_scope: Scope 606 | Stores the variables declared before entering any conditions and where they should be 607 | referred to. 608 | - scope_true: Scope 609 | Stores the variables currently declared if cond = true and where they should be 610 | referred to. 611 | - scope_false: Scope 612 | Stores the variables currently declared if cond = false and where they should be 613 | referred to. 614 | 615 | ------- 616 | Returns: 617 | - scope_true 618 | """ 619 | 620 | # Merges variables declared/modified in a true/false scope in the true scope 621 | for node_false in scope_false.var_list: 622 | if not any(node_false.attributes['name'] == node_true.attributes['name'] 623 | for node_true in scope_true.var_list): 624 | logging.debug('The variable %s was added to the list', node_false.attributes['name']) 625 | scope_true.add_var(node_false) 626 | 627 | for node_true in scope_true.var_list: 628 | if node_false.attributes['name'] == node_true.attributes['name']\ 629 | and node_false.id != node_true.id: # The var was modified in >=1 branch 630 | var_index = scope_true.get_pos_identifier(node_true) 631 | if any(node_true.id == node.id for node in current_scope.var_list): 632 | logging.debug('The variable %s has been modified in the branch False', 633 | node_false.attributes['name']) 634 | scope_true.update_var(var_index, node_false) 635 | elif any(node_false.id == node.id for node in current_scope.var_list): 636 | logging.debug('The variable %s has been modified in the branch True', 637 | node_true.attributes['name']) 638 | # Already handled, as we work on var_list_true 639 | else: # Both were modified, we refer to the nearest common statement 640 | logging.debug('The variable %s has been modified in the branches True and ' 641 | 'False', node_false.attributes['name']) 642 | scope_true.update_var_if2(var_index, [node_true, node_false]) 643 | 644 | return scope_true # Merged variables declared in the True/False scope 645 | 646 | 647 | def handle_several_branches(todo_true, todo_false, scopes, id_list, entry): 648 | """ 649 | Statement scope. 650 | 651 | ------- 652 | Parameters: 653 | - todo_true: list of Node 654 | From the True branch. 655 | - todo_false: list of Node 656 | From the False branch. 657 | """ 658 | 659 | if todo_true or todo_false: 660 | scopes, local_scope_true, global_scope_true = get_var_branch(todo_true, scopes=scopes, 661 | id_list=id_list, entry=entry, 662 | scope_name='Branch_true') 663 | 664 | scopes, local_scope_false, global_scope_false = get_var_branch(todo_false, scopes=scopes, 665 | id_list=id_list, entry=entry, 666 | scope_name='Branch_false') 667 | 668 | if not global_scope_true.is_equal(global_scope_false): 669 | logging.debug('True and False global scopes are different') 670 | global_scope = merge_var_boolean_cf(scopes[0], global_scope_true, global_scope_false) 671 | scopes.pop(0) 672 | scopes.insert(0, global_scope) 673 | 674 | if not local_scope_true.is_equal(local_scope_false): 675 | logging.debug('True and False local scopes are different') 676 | current_scope = scopes[-1] 677 | 678 | # Merges variables declared in the True/False previous scopes 679 | cond_scope = merge_var_boolean_cf(current_scope, local_scope_true, local_scope_false) 680 | 681 | # Adds variables previously declared in the True/False scope in the current scope 682 | for cond_node in cond_scope.var_list: 683 | if not any(cond_node.attributes['name'] == current_node.attributes['name'] 684 | for current_node in current_scope.var_list): 685 | logging.debug('The variable %s was added to the current variables\' list', 686 | cond_node.attributes['name']) 687 | current_scope.add_var(cond_node) 688 | 689 | # Same for variables declared in both branches 690 | for cond_node_list in cond_scope.var_if2_list: 691 | if isinstance(cond_node_list, list): 692 | current_scope.var_if2_list.extend(cond_node_list) 693 | 694 | # Finally scopes contains all variables defined in the true + false branches 695 | return scopes 696 | 697 | 698 | def statement_scope(node, scopes, id_list, entry): 699 | """ Statement scope. """ 700 | 701 | todo_true = [] 702 | todo_false = [] 703 | if_test = None 704 | 705 | # Statements that do belong after one another 706 | for child_statement_dep in node.statement_dep_children: 707 | child_statement = child_statement_dep.extremity 708 | logging.debug('The node %s has a statement dependency', child_statement.name) 709 | scopes = data_flow(child_statement, scopes=scopes, id_list=id_list, entry=entry) 710 | if child_statement.parent.name in ('IfStatement', 'ConditionalExpression'): 711 | # Checking if we can statically predict the outcome of the if test 712 | if_test = get_node_computed_value(child_statement, initial_node=node) 713 | if not isinstance(if_test, bool): # Could be neither bool nor None 714 | if_test = None # So that must be either True, False or None 715 | logging.debug('The If test is %s', if_test) 716 | 717 | for child_cf_dep in node.control_dep_children: # Control flow statements 718 | child_cf = child_cf_dep.extremity 719 | if isinstance(child_cf_dep.label, bool): # Several branches according to the cond 720 | logging.debug('The node %s has a boolean CF dependency', child_cf.name) 721 | if child_cf_dep.label and (if_test or if_test is None): 722 | todo_true.append(child_cf) # SwitchCase: several True possible 723 | elif not child_cf_dep.label and (not if_test or if_test is None): 724 | todo_false.append(child_cf) 725 | 726 | else: # Epsilon statements 727 | logging.debug('The node %s has an epsilon CF dependency', child_cf.name) 728 | scopes = data_flow(child_cf, scopes=scopes, id_list=id_list, entry=entry) 729 | 730 | # Separate variables if separate true/false branches 731 | scopes = handle_several_branches(todo_true=todo_true, todo_false=todo_false, scopes=scopes, 732 | id_list=id_list, entry=entry) 733 | 734 | let_const_scope(node, scopes) # Limit scope when going out of the block 735 | 736 | return scopes 737 | 738 | 739 | def let_const_scope(node, scopes): 740 | """ Pops scope specific to variables defined with let or const. """ 741 | 742 | if len(scopes) > 1 and scopes[-1].name == "let_const" + str(node.id): 743 | scopes.pop() 744 | elif len(scopes) > 2 and "Branch" in scopes[-1].name\ 745 | and scopes[-2].name == "let_const" + str(node.id): # As special scope for True branches 746 | scopes.pop(-2) 747 | 748 | 749 | def go_out_bloc(scopes, already_in_bloc): 750 | """ Go out of block statement. """ 751 | 752 | if not already_in_bloc: # If we already were in a bloc, we do not want to go out to early 753 | for scope in scopes[::-1]: # In reverse order to check the last scope first 754 | if scope.bloc: 755 | scope.set_in_bloc(False) 756 | break 757 | 758 | 759 | def handle_arg_tagged_template_expr(node, callee, saved_params): 760 | """ 761 | Handles the arguments of a TaggedTemplateExpression node. 762 | 763 | ------- 764 | Parameter: 765 | - callee: Node 766 | FunctionDeclaration or (Arrow)FunctionExpression. 767 | - saved_params: list 768 | If a fun is called inside itself with != params, need to store outer ones. 769 | """ 770 | 771 | template_literal = node.children[1] 772 | template_element = [] # Seems that TemplateElement = similar to Literal and in front 773 | template_element_node = [] # Stores the TemplateElement nodes 774 | standard_param = [] 775 | 776 | for child in template_literal.children: 777 | if child.name == 'TemplateElement': 778 | template_element_node.append(child) 779 | template_element.append(get_node_computed_value(child, initial_node=node)) 780 | else: 781 | standard_param.append(child) 782 | params = [template_element] 783 | params.extend(standard_param) # Params are like that: [all TemplateElement], rest 784 | 785 | for arg in range(1, len(callee.fun_params)): 786 | if arg <= len(standard_param): 787 | # Check if function call has less parameters than function definition 788 | param = get_node_computed_value(standard_param[arg - 1], initial_node=node) 789 | handle_function_params(callee.fun_params[arg], standard_param[arg - 1]) 790 | else: 791 | param = None 792 | saved_params.append(get_node_computed_value(callee.fun_params[arg], initial_node=node)) 793 | callee.fun_params[arg].set_value(param) # Set value of function param from second one 794 | saved_params.append(get_node_computed_value(callee.fun_params[0], initial_node=node)) 795 | callee.fun_params[0].set_value(template_element) # Set value of first function param 796 | 797 | for param in template_element_node: # Links parameters for the TemplateElement nodes 798 | handle_function_params(callee.fun_params[0], param) 799 | 800 | 801 | def handle_function_params(def_param, call_param): 802 | """ Links the function parameter at the definition site with the value at the call site. """ 803 | 804 | # Function parameter at the definition site depends on the value at the call site 805 | def_param.set_provenance(call_param) 806 | # _node.set_provenance_rec(def_param, call_param) 807 | 808 | # Defines the fun_param_X dependency, if it does not already exist to avoid resetting it to [] 809 | if not hasattr(def_param, 'fun_param_children'): 810 | setattr(def_param, 'fun_param_children', []) 811 | 812 | if not hasattr(call_param, 'fun_param_parents'): 813 | setattr(call_param, 'fun_param_parents', []) 814 | 815 | # Links the function parameter definition site to the call site with a fun_param dependency 816 | if call_param.id not in [el.id for el in def_param.fun_param_children]: # Avoids duplicates 817 | def_param.fun_param_children.append(call_param) 818 | call_param.fun_param_parents.append(def_param) 819 | 820 | 821 | def handle_call_expr(node, scopes, callee, fun_expr=False, tagged_template=False): 822 | """ 823 | Handling CallExpression nodes. Can be: 824 | - 1. FunDecl/Expr... CallExpr -> leveraging the data_dep for the mapping process; 825 | - 2. CallExpr... FunDecl -> but hoisted FunDecl to top, so back to case 1.; 826 | - 3. CallExpr(FunExpr) -> case fun_expr=True; 827 | - 4. nothing to do with a FunDecl/Expr -> not handled here because would not be called. 828 | 829 | ------- 830 | Parameters: 831 | - callee: Node 832 | FunctionDeclaration or (Arrow)FunctionExpression. 833 | - fun_expr: bool 834 | True if CallExpr(FunExpr), otherwise False. 835 | """ 836 | 837 | function_def = callee # Handler to the function 838 | if not fun_expr: # Case CallExpr and not CallExpr(FunExpr) 839 | function_def.call_function() # It was called 840 | saved_params = [] # If a fun is called inside itself with != params, need to store outer ones 841 | 842 | # Arguments handling 843 | if tagged_template: 844 | handle_arg_tagged_template_expr(node, callee, saved_params) 845 | else: 846 | for arg, _ in enumerate(function_def.fun_params): 847 | if (1 + arg) < len(node.children): 848 | # Check if function call has less parameters than function definition 849 | saved_params.append(get_node_computed_value(function_def.fun_params[arg], 850 | initial_node=node)) 851 | param = get_node_computed_value(node.children[1 + arg], initial_node=node) 852 | handle_function_params(callee.fun_params[arg], node.children[1 + arg]) 853 | else: 854 | param = None 855 | if isinstance(function_def.fun_params[arg], _node.Value): 856 | function_def.fun_params[arg].set_value(param) # Set value of function param 857 | 858 | if function_def.fun_name is not None: # FunDecl or var where FunExpr stored 859 | function_name = function_def.fun_name.attributes['name'] 860 | else: # FunExpr case, name used to reference the function inside itself 861 | if function_def.fun_intern_name is not None: 862 | function_name = function_def.fun_intern_name.attributes['name'] 863 | else: 864 | function_name = 'Anonymous' 865 | 866 | logging.debug('The function %s was called with following parameters:', 867 | function_name) 868 | for param in function_def.fun_params: 869 | try: 870 | logging.debug('\t- %s = %s', param.attributes['name'], param.value) 871 | except KeyError: # If param is not an Identifier, could be, e.g., a CallExpression 872 | logging.debug('\t- %s = %s', param.name, param.value) 873 | 874 | # Traverse function again 875 | function_def.set_retraverse() # Sets retraverse property to True 876 | scopes = function_scope(node=function_def, scopes=scopes, id_list=[]) 877 | 878 | return_value = None 879 | if function_def.fun_return: 880 | return_value = get_node_value(function_def.fun_return[-1], initial_node=node) 881 | # Last in, only one out 882 | # Beware, NOT get_node_computed_value because we want to compute the value again: the 883 | # previously stored value is the returned value hard coded in the function def before exec 884 | logging.debug('The function %s returns %s', function_name, return_value) 885 | node.set_value(return_value) 886 | 887 | if len(function_def.fun_params) == len(saved_params): 888 | for arg, _ in enumerate(function_def.fun_params): 889 | function_def.fun_params[arg].set_value(saved_params[arg]) # Set old param value 890 | 891 | return scopes 892 | 893 | 894 | def handle_foreach(node): 895 | """ Sets provenance for forEach construct. """ 896 | 897 | if len(node.children) > 1 and node.children[0].body in ('callee', 'tag'): 898 | # arr.forEach(callback); 899 | callee = node.children[0] 900 | call_expr_value = get_node_computed_value(node) 901 | if call_expr_value is not None and '.forEach(' in call_expr_value: 902 | identifiers = [] # To store identifiers on which forEach is called (e.g., arr) 903 | for child in callee.children: 904 | search_identifiers(child, id_list=[], tab=identifiers) 905 | callback = node.children[1] # callback, should be a FunctionExpression 906 | if isinstance(callback, _node.FunctionExpression): 907 | for param in callback.children: 908 | if 'params' in param.body: 909 | for arr in identifiers: 910 | if isinstance(param, _node.Value): 911 | param.set_provenance(arr) # callback params depend on arr object 912 | 913 | 914 | def handle_push(node): 915 | """ Sets provenance for push construct. """ 916 | 917 | if len(node.children) > 1 and node.children[0].body in ('callee', 'tag'): 918 | # arr.push(elt1, ..., eltN); 919 | callee = node.children[0] 920 | call_expr_value = get_node_computed_value(node) 921 | if call_expr_value is not None and '.push(' in call_expr_value: 922 | identifiers = [] # To store identifiers on which push is called (e.g., arr) 923 | for child in callee.children: 924 | search_identifiers(child, id_list=[], tab=identifiers) 925 | elements = node.children[1:] # elements to be pushed 926 | for element in elements: 927 | for arr in identifiers: 928 | if isinstance(arr, _node.Value): 929 | arr.set_provenance_rec(element) # arr object depends on elements 930 | 931 | 932 | def build_dfg_content(child, scopes, id_list, entry): 933 | """ Data dependency for a given node whatever it is. """ 934 | 935 | if child.name == 'VariableDeclaration': # VariableDeclaration data dependencies 936 | 937 | logging.debug('The node %s is a variable declaration', child.name) 938 | 939 | let_const = False 940 | if child.attributes['kind'] != 'var' and scopes[-1].bloc: # let or const in a bloc 941 | let_const = True 942 | let_const_scope_name = 'let_const' + str(child.parent.id) 943 | if scopes[-1].name != let_const_scope_name: # New block scope if not already defined 944 | scopes.append(_scope.Scope(let_const_scope_name)) 945 | 946 | for grandchild in child.children: 947 | scopes = var_declaration_df(grandchild, scopes=scopes, id_list=id_list, entry=entry, 948 | let_const=let_const) 949 | 950 | ################################################################################################ 951 | 952 | elif child.name == 'AssignmentExpression': # AssignmentExpression data dependencies 953 | 954 | logging.debug('The node %s is an assignment expression', child.name) 955 | scopes = assignment_expr_df(child, scopes=scopes, id_list=id_list, entry=entry) 956 | 957 | ################################################################################################ 958 | 959 | elif child.name in _node.CALL_EXPR: 960 | 961 | scopes = df_scoping(child, scopes=scopes, id_list=id_list)[1] 962 | callee = child.children[0] 963 | 964 | tagged_template = bool(child.name == 'TaggedTemplateExpression') 965 | 966 | if isinstance(callee, _node.FunctionExpression): # Case CallExpr(FunExpr) 967 | scopes = handle_call_expr(child, scopes=scopes, callee=callee, 968 | tagged_template=tagged_template, fun_expr=True) 969 | 970 | elif isinstance(get_node_computed_value(callee, initial_node=child), 971 | _node.FunctionExpression): 972 | # Case a = {}; a['b'] = function(){}; a['b'](); --> As a['b'] resolves to a FunExpr 973 | scopes = handle_call_expr(child, scopes=scopes, 974 | callee=get_node_computed_value(callee, initial_node=child), 975 | tagged_template=tagged_template, fun_expr=True) 976 | 977 | else: 978 | identifiers = search_identifiers(callee, id_list=[], tab=[]) 979 | for identifier in identifiers: 980 | for data_dep in identifier.data_dep_parents: 981 | if data_dep.extremity.fun is not None: # Calling a fun that was defined before 982 | callee = data_dep.extremity.fun 983 | scopes = handle_call_expr(child, scopes=scopes, callee=callee, 984 | tagged_template=tagged_template) 985 | break 986 | 987 | handle_foreach(node=child) # Sets provenance for forEach constructs 988 | handle_push(node=child) # Sets provenance for push constructs 989 | 990 | display_values(var=child, keep_none=False, recompute=False) # Display values 991 | 992 | ################################################################################################ 993 | 994 | elif child.name == 'UpdateExpression': # UpdateExpression data dependencies 995 | 996 | logging.debug('The node %s is an update expression', child.name) 997 | update_expr_df(child, scopes=scopes, id_list=id_list, entry=entry) 998 | 999 | ################################################################################################ 1000 | 1001 | elif child.name == 'FunctionDeclaration' or isinstance(child, _node.FunctionExpression): 1002 | # Functions data dependencies 1003 | 1004 | logging.debug('The node %s is a function', child.name) 1005 | scopes = function_scope(node=child, scopes=scopes, id_list=id_list) 1006 | # child.scopes = scopes # Would not work because would lose current scoping info 1007 | 1008 | ################################################################################################ 1009 | 1010 | elif child.name == 'ReturnStatement': # ReturnStatement added to the corresponding fun + DD 1011 | 1012 | logging.debug('The node %s is a return statement', child.name) 1013 | already_in_bloc = scopes[-1].bloc 1014 | scopes[-1].set_in_bloc(True) # We are in a block statement, relevant for let/const 1015 | 1016 | for scope in scopes[::-1]: # In reverse order to check the last scope first 1017 | if scope.name == 'Function': 1018 | fun = scope.function # Looking for the (Arrow)FunctionExpression/Declaration node 1019 | if not isinstance(fun, _node.FunctionDeclaration) \ 1020 | and not isinstance(fun, _node.FunctionExpression): 1021 | logging.error('Expected a Function, got a %s node', fun.name) 1022 | break 1023 | 1024 | fun.add_fun_return(child) # Sets value of ReturnStatement 1025 | 1026 | break 1027 | 1028 | scopes = df_scoping(child, scopes=scopes, id_list=id_list)[1] 1029 | go_out_bloc(scopes, already_in_bloc) # We are not in the block statement anymore 1030 | 1031 | ################################################################################################ 1032 | 1033 | elif child.name == 'ForStatement': # ForStatement: init, test, update, body (Statement) 1034 | 1035 | logging.debug('The node %s is a for statement', child.name) 1036 | already_in_bloc = scopes[-1].bloc 1037 | scopes[-1].set_in_bloc(True) # We are in a block statement, relevant for let/const 1038 | 1039 | if len(child.children) in (3, 4): 1040 | scopes = data_flow(child.children[0], scopes, id_list, entry) # init 1041 | scopes = data_flow(child.children[1], scopes, id_list, entry) # test 1042 | identifiers = [] 1043 | search_identifiers(child.children[0], [], identifiers) 1044 | loop = 0 1045 | test = get_node_computed_value(child.children[1], initial_node=child) 1046 | if test is not True: # Could be None, or perhaps str, int whatever 1047 | test = True # So that go at least one time in the loop 1048 | while get_node_computed_value(child.children[1], initial_node=child) or test: 1049 | # while test do: 1050 | test = False 1051 | loop += 1 1052 | if loop <= LIMIT_LOOP: # To avoid infinite loops 1053 | if len(child.children) == 4: 1054 | scopes = data_flow(child.children[3], scopes, id_list, entry) # body 1055 | scopes = data_flow(child.children[2], scopes, id_list, entry) # update / body 1056 | for identifier in identifiers: 1057 | if len(identifier.data_dep_children) >= 3: 1058 | identifier.data_dep_children[0].extremity.set_value( 1059 | identifier.data_dep_children[2].extremity) # updates test value 1060 | else: 1061 | break # To go out of the while! 1062 | let_const_scope(child, scopes) # Limit scope when going out of the block 1063 | 1064 | else: 1065 | logging.warning('Expected a ForStatement with 3 or 4 children, got only %s', 1066 | len(child.children)) 1067 | scopes = statement_scope(node=child, scopes=scopes, id_list=id_list, entry=entry) 1068 | 1069 | go_out_bloc(scopes, already_in_bloc) # We are not in the block statement anymore 1070 | 1071 | ################################################################################################ 1072 | 1073 | elif child.name in ('ForOfStatement', 'ForInStatement'): # ForOf/InStatement: left, right, body 1074 | 1075 | logging.debug('The node %s is a for statement', child.name) 1076 | already_in_bloc = scopes[-1].bloc 1077 | scopes[-1].set_in_bloc(True) # We are in a block statement, relevant for let/const 1078 | 1079 | if len(child.children) == 3: 1080 | scopes = data_flow(child.children[0], scopes, id_list, entry) # left = var 1081 | scopes = data_flow(child.children[1], scopes, id_list, entry) # right = array 1082 | identifiers = [] 1083 | search_identifiers(child.children[0], [], identifiers) 1084 | # Reference to the ArrayExpr 1085 | obj_value = get_node_computed_value(child.children[1], initial_node=child) 1086 | if len(identifiers) > 1: 1087 | logging.warning('Got %s variables declared in a %s', len(identifiers), child.name) 1088 | for identifier in identifiers: 1089 | if isinstance(obj_value, _node.Node): # Otherwise cannot iterate over Array 1090 | for obj_value_el in obj_value.children: # Iterate over the ArrayExpr elements 1091 | if obj_value_el.name == 'Property': 1092 | prop_value = get_node_computed_value(obj_value_el.children[0], 1093 | initial_node=child) # kvalue 1094 | else: 1095 | prop_value = get_node_computed_value(obj_value_el, 1096 | initial_node=child) # k value 1097 | identifier.set_value(prop_value) 1098 | # Thanks to DD from identifier, will iterate over k value 1099 | scopes = data_flow(child.children[2], scopes, id_list, entry) # body 1100 | 1101 | if not identifiers or identifiers and\ 1102 | (not isinstance(obj_value, _node.Node) or not obj_value.children): 1103 | # So that body still handled 1104 | scopes = data_flow(child.children[2], scopes, id_list, entry) # body 1105 | 1106 | let_const_scope(child, scopes) # Limit scope when going out of the block 1107 | 1108 | else: 1109 | logging.warning('Expected a ForStatement with 3 children, got only %s', 1110 | len(child.children)) 1111 | scopes = statement_scope(node=child, scopes=scopes, id_list=id_list, entry=entry) 1112 | 1113 | go_out_bloc(scopes, already_in_bloc) # We are not in the block statement anymore 1114 | 1115 | ################################################################################################ 1116 | 1117 | elif isinstance(child, _node.Statement) or child.name == 'ConditionalExpression': 1118 | # Statement (statement, epsilon, boolean) data dep and ConditionalExpr = same as IfStatement 1119 | 1120 | logging.debug('The node %s is a statement', child.name) 1121 | already_in_bloc = scopes[-1].bloc 1122 | scopes[-1].set_in_bloc(True) # We are in a block statement, relevant for let/const 1123 | 1124 | scopes = statement_scope(node=child, scopes=scopes, id_list=id_list, entry=entry) 1125 | go_out_bloc(scopes, already_in_bloc) # We are not in the block statement anymore 1126 | 1127 | ################################################################################################ 1128 | 1129 | elif child.name == 'ObjectExpression': # Only consider the object name, no properties 1130 | 1131 | logging.debug('The node %s is an object expression', child.name) 1132 | scopes = obj_expr_scope(child, scopes=scopes, id_list=id_list) 1133 | 1134 | ################################################################################################ 1135 | 1136 | elif child.name == 'ObjectPattern': # Only consider the object name, not the key or properties 1137 | 1138 | logging.debug('The node %s is an object pattern', child.name) 1139 | scopes = obj_pattern_scope(child, scopes=scopes, id_list=id_list) 1140 | 1141 | ################################################################################################ 1142 | 1143 | elif child.name == 'Identifier': # Identifier data dependencies 1144 | 1145 | if child.id not in id_list: 1146 | logging.debug('The variable %s has not been handled yet', child.attributes['name']) 1147 | identifier_update(child, scopes=scopes, id_list=id_list, entry=entry) 1148 | else: 1149 | logging.debug('The variable %s has already been handled', child.attributes['name']) 1150 | 1151 | ################################################################################################ 1152 | 1153 | else: 1154 | scopes = df_scoping(child, scopes=scopes, id_list=id_list)[1] 1155 | 1156 | ################################################################################################ 1157 | 1158 | # for scope in scopes: 1159 | # display_temp('> ' + scope.name, [scope]) 1160 | # display_temp('> Local: ', scopes[1:]) 1161 | # display_temp('> Global: ', scopes[:1]) 1162 | 1163 | return scopes 1164 | 1165 | 1166 | def data_flow(child, scopes, id_list, entry): 1167 | """ Cf build_dfg_content. Added try/catch to see code snippets leading to problems and 1168 | performing the analysis to the end. """ 1169 | 1170 | # scopes = build_dfg_content(child, scopes, id_list, entry) 1171 | 1172 | try: 1173 | scopes = build_dfg_content(child, scopes, id_list, entry) 1174 | 1175 | except utility_df.Timeout.Timeout as e: 1176 | raise e # Will be caught in build_pdg 1177 | 1178 | except Exception as e: 1179 | if PDG_EXCEPT: # Prints the exceptions encountered while building the PDG 1180 | logging.exception(e) 1181 | logging.exception('Something went wrong with the following code snippet, %s', '') 1182 | my_json = 'test.json' 1183 | save_json(child, my_json) # Won't work with multiprocessing 1184 | print(get_code(my_json)) 1185 | else: 1186 | pass 1187 | 1188 | return scopes 1189 | 1190 | 1191 | def df_scoping(cfg_nodes, scopes, id_list, entry=0): 1192 | """ 1193 | Data dependency for the CFG. 1194 | 1195 | ------- 1196 | Parameters: 1197 | - cfg_nodes: Node 1198 | Output of produce_cfg(ast_to_ast_nodes(, ast_nodes=Node('Program'))). 1199 | 1200 | ------- 1201 | Returns: 1202 | - Node 1203 | With data flow dependencies added. 1204 | """ 1205 | 1206 | for child in cfg_nodes.children: 1207 | scopes = data_flow(child, scopes=scopes, id_list=id_list, entry=entry) 1208 | return [cfg_nodes, scopes] 1209 | 1210 | 1211 | def display_temp(title, scopes, print_var_value=True): 1212 | """ Displays known variable names. """ 1213 | 1214 | print(title) 1215 | my_json = 'test.json' 1216 | for scope in scopes: 1217 | print('> ' + scope.name) 1218 | for el in scope.var_list: 1219 | variable = get_node_value(el) 1220 | if not print_var_value: 1221 | print(variable) 1222 | # print(el.attributes['name']) 1223 | else: 1224 | value_node = el.value 1225 | if el.update_value: # To compute the value of NEW variables only 1226 | value = get_node_computed_value(el, keep_none=True) 1227 | else: # The value of old variables should not change with code occurring after them 1228 | value = value_node 1229 | 1230 | print(variable + ' = ' + str(value)) # Get variable value 1231 | if isinstance(value, _node.Node): 1232 | print(value.name, value.attributes, value.id) 1233 | el.set_update_value(False) 1234 | 1235 | # Get code 1236 | if isinstance(value_node, _node.Node): 1237 | save_json(get_nearest_statement(value_node, fun_expr=True), my_json) 1238 | code = get_code(my_json) 1239 | print('\t' + code) 1240 | else: # Case "we don't know the value" or Literal we computed i.e. no Node obj 1241 | if el.code is not None: 1242 | save_json(el.code, my_json) 1243 | code = get_code(my_json) 1244 | print('\t' + code) 1245 | 1246 | 1247 | def display_temp2(title, scopes): 1248 | """ Displays var_if2_list content. """ 1249 | 1250 | print(title) 1251 | for scope in scopes: 1252 | print('> ' + scope.name) 1253 | if scope.var_if2_list is not None: 1254 | for el in scope.var_if2_list: 1255 | print(el) 1256 | -------------------------------------------------------------------------------- /src/display_graph.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021 Aurore Fass 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU Affero General Public License as published 5 | # by the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU Affero General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Affero General Public License 14 | # along with this program. If not, see . 15 | 16 | # Additional permission under GNU GPL version 3 section 7 17 | # 18 | # If you modify this Program, or any covered work, by linking or combining it with 19 | # graphviz (or a modified version of that library), containing parts covered by the 20 | # terms of The Common Public License, the licensors of this Program grant you 21 | # additional permission to convey the resulting work. 22 | 23 | 24 | """ 25 | Display graphs (AST, CFG, PDG) using the graphviz library. 26 | """ 27 | 28 | import graphviz 29 | 30 | import node as _node 31 | 32 | 33 | def append_leaf_attr(node, graph): 34 | """ 35 | Append the leaf's attribute to the graph in graphviz format. 36 | 37 | ------- 38 | Parameters: 39 | - node: Node 40 | Node. 41 | - graph: Digraph/Graph 42 | Graph object. Be careful it is mutable. 43 | """ 44 | 45 | if node.is_leaf(): 46 | leaf_id = str(node.id) + 'leaf_' 47 | graph.attr('node', style='filled', color='lightgoldenrodyellow', 48 | fillcolor='lightgoldenrodyellow') 49 | graph.attr('edge', color='orange') 50 | got_attr, node_attributes = node.get_node_attributes() 51 | if got_attr: # Got attributes 52 | leaf_attr = str(node_attributes) 53 | graph.node(leaf_id, leaf_attr) 54 | graph.edge(str(node.id), leaf_id) 55 | 56 | 57 | def produce_ast(ast_nodes, attributes, graph=graphviz.Graph(comment='AST representation')): 58 | """ 59 | Produce an AST in graphviz format. 60 | 61 | ------- 62 | Parameters: 63 | - ast_nodes: Node 64 | Output of ast_to_ast_nodes(, ast_nodes=Node('Program')). 65 | - graph: Graph 66 | Graph object. Be careful it is mutable. 67 | - attributes: bool 68 | Whether to display the leaf attributes or not. 69 | 70 | ------- 71 | Returns: 72 | - graph 73 | graphviz formatted graph. 74 | """ 75 | 76 | graph.attr('node', color='black', style='filled', fillcolor='white') 77 | graph.attr('edge', color='black') 78 | graph.node(str(ast_nodes.id), ast_nodes.name) 79 | for child in ast_nodes.children: 80 | graph.attr('node', color='black', style='filled', fillcolor='white') 81 | graph.attr('edge', color='black') 82 | graph.edge(str(ast_nodes.id), str(child.id)) 83 | produce_ast(child, attributes, graph) 84 | if attributes: 85 | append_leaf_attr(child, graph) 86 | return graph 87 | 88 | 89 | def draw_ast(ast_nodes, attributes=False, save_path=None): 90 | """ 91 | Plot an AST. 92 | 93 | ------- 94 | Parameters: 95 | - ast_nodes: Node 96 | Output of ast_to_ast_nodes(, ast_nodes=Node('Program')). 97 | - save_path: str 98 | Path of the file to store the AST in. 99 | - attributes: bool 100 | Whether to display the leaf attributes or not. Default: False. 101 | """ 102 | 103 | dot = produce_ast(ast_nodes, attributes) 104 | if save_path is None: 105 | dot.view() 106 | else: 107 | dot.render(save_path, view=False) 108 | graphviz.render(filepath=save_path, engine='dot', format='eps') 109 | dot.clear() 110 | 111 | 112 | def cfg_type_node(child): 113 | """ Different form according to statement node or not. """ 114 | 115 | if isinstance(child, _node.Statement) or child.is_comment(): 116 | return ['box', 'red', 'lightpink'] 117 | return ['ellipse', 'blue', 'lightblue2'] 118 | 119 | 120 | def produce_cfg_one_child(child, data_flow, attributes, 121 | graph=graphviz.Digraph(comment='Control flow representation')): 122 | """ 123 | Produce a CFG in graphviz format. 124 | 125 | ------- 126 | Parameters: 127 | - child: Node 128 | Node to begin with. 129 | - data_flow: bool 130 | Whether to display the data flow or not. Default: False. 131 | - attributes: bool 132 | Whether to display the leaf attributes or not. 133 | - graph: Digraph 134 | Graph object. Be careful it is mutable. 135 | 136 | ------- 137 | Returns: 138 | - graph 139 | graphviz formatted graph. 140 | """ 141 | 142 | type_node = cfg_type_node(child) 143 | graph.attr('node', shape=type_node[0], style='filled', color=type_node[2], 144 | fillcolor=type_node[2]) 145 | graph.attr('edge', color=type_node[1]) 146 | graph.node(str(child.id), child.name) 147 | 148 | for child_statement_dep in child.statement_dep_children: 149 | child_statement = child_statement_dep.extremity 150 | type_node = cfg_type_node(child_statement) 151 | graph.attr('node', shape=type_node[0], color=type_node[2], fillcolor=type_node[2]) 152 | graph.attr('edge', color=type_node[1]) 153 | graph.edge(str(child.id), str(child_statement.id), label=child_statement_dep.label) 154 | produce_cfg_one_child(child_statement, data_flow=data_flow, attributes=attributes, 155 | graph=graph) 156 | if attributes: 157 | append_leaf_attr(child_statement, graph) 158 | 159 | if isinstance(child, _node.Statement): 160 | for child_cf_dep in child.control_dep_children: 161 | child_cf = child_cf_dep.extremity 162 | type_node = cfg_type_node(child_cf) 163 | graph.attr('node', shape=type_node[0], color=type_node[2], fillcolor=type_node[2]) 164 | graph.attr('edge', color=type_node[1]) 165 | graph.edge(str(child.id), str(child_cf.id), label=str(child_cf_dep.label)) 166 | produce_cfg_one_child(child_cf, data_flow=data_flow, attributes=attributes, graph=graph) 167 | if attributes: 168 | append_leaf_attr(child_cf, graph) 169 | 170 | if data_flow: 171 | graph.attr('edge', color='green') 172 | if isinstance(child, _node.Identifier): 173 | for child_data_dep in child.data_dep_children: 174 | child_data = child_data_dep.extremity 175 | type_node = cfg_type_node(child) 176 | graph.attr('node', shape=type_node[0], color=type_node[2], fillcolor=type_node[2]) 177 | graph.edge(str(child.id), str(child_data.id), label=child_data_dep.label) 178 | # No call to the func as already recursive for data/statmt dep on the same nodes 179 | # logging.info("Data dependency on the variable " + child_data.attributes['name']) 180 | graph.attr('edge', color='seagreen') 181 | if hasattr(child, 'fun_param_parents'): # Function parameters flow 182 | for child_param in child.fun_param_parents: 183 | type_node = cfg_type_node(child) 184 | graph.attr('node', shape=type_node[0], color=type_node[2], fillcolor=type_node[2]) 185 | graph.edge(str(child.id), str(child_param.id), label='param') 186 | 187 | return graph 188 | 189 | 190 | def draw_cfg(cfg_nodes, attributes=False, save_path=None): 191 | """ 192 | Plot a CFG. 193 | 194 | ------- 195 | Parameters: 196 | - cfg_nodes: Node 197 | Output of produce_cfg(ast_to_ast_nodes(, ast_nodes=Node('Program'))). 198 | - save_path: str 199 | Path of the file to store the CFG in. 200 | - attributes: bool 201 | Whether to display the leaf attributes or not. Default: False. 202 | """ 203 | 204 | dot = graphviz.Digraph() 205 | for child in cfg_nodes.children: 206 | dot = produce_cfg_one_child(child=child, data_flow=False, attributes=attributes) 207 | if save_path is None: 208 | dot.view() 209 | else: 210 | dot.render(save_path, view=False) 211 | graphviz.render(filepath=save_path, engine='dot', format='eps') 212 | dot.clear() 213 | 214 | 215 | def draw_pdg(dfg_nodes, attributes=False, save_path=None): 216 | """ 217 | Plot a PDG. 218 | 219 | ------- 220 | Parameters: 221 | - dfg_nodes: Node 222 | Output of produce_dfg(produce_cfg(ast_to_ast_nodes(, ast_nodes=Node('Program')))). 223 | - save_path: str 224 | Path of the file to store the PDG in. 225 | - attributes: bool 226 | Whether to display the leaf attributes or not. Default: False. 227 | """ 228 | 229 | dot = graphviz.Digraph() 230 | for child in dfg_nodes.children: 231 | dot = produce_cfg_one_child(child=child, data_flow=True, attributes=attributes) 232 | if save_path is None: 233 | dot.view() 234 | else: 235 | dot.render(save_path, view=False) 236 | graphviz.render(filepath=save_path, engine='dot', format='eps') 237 | dot.clear() 238 | -------------------------------------------------------------------------------- /src/extended_ast.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021 Aurore Fass 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU Affero General Public License as published 5 | # by the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU Affero General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Affero General Public License 14 | # along with this program. If not, see . 15 | 16 | 17 | """ 18 | Definition of the class ExtendedAst: corresponds to the output of Esprima's parse function 19 | with the arguments: {range: true, loc: true, tokens: true, tolerant: true, comment: true}. 20 | """ 21 | 22 | # Note: slightly improved from HideNoSeek 23 | 24 | 25 | class ExtendedAst: 26 | """ Stores the Esprima formatted AST into python objects. """ 27 | 28 | def __init__(self): 29 | self.type = None 30 | self.filename = '' 31 | self.body = [] 32 | self.source_type = None 33 | self.range = [] 34 | self.comments = [] 35 | self.tokens = [] 36 | self.leading_comments = [] 37 | 38 | def get_type(self): 39 | return self.type 40 | 41 | def set_type(self, root): 42 | self.type = root 43 | 44 | def get_body(self): 45 | return self.body 46 | 47 | def set_body(self, body): 48 | self.body = body 49 | 50 | def get_extended_ast(self): 51 | return {'type': self.get_type(), 'body': self.get_body(), 52 | 'sourceType': self.get_source_type(), 'range': self.get_range(), 53 | 'comments': self.get_comments(), 'tokens': self.get_tokens(), 54 | 'filename': self.filename, 55 | 'leadingComments': self.get_leading_comments()} 56 | 57 | def get_ast(self): 58 | return {'type': self.get_type(), 'body': self.get_body(), 'filename': self.filename} 59 | 60 | def get_source_type(self): 61 | return self.source_type 62 | 63 | def set_source_type(self, source_type): 64 | self.source_type = source_type 65 | 66 | def get_range(self): 67 | return self.range 68 | 69 | def set_range(self, ast_range): 70 | self.range = ast_range 71 | 72 | def get_comments(self): 73 | return self.comments 74 | 75 | def set_comments(self, comments): 76 | self.comments = comments 77 | 78 | def get_tokens(self): 79 | return self.tokens 80 | 81 | def set_tokens(self, tokens): 82 | self.tokens = tokens 83 | 84 | def get_leading_comments(self): 85 | return self.leading_comments 86 | 87 | def set_leading_comments(self, leading_comments): 88 | self.leading_comments = leading_comments 89 | -------------------------------------------------------------------------------- /src/js_operators.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021 Aurore Fass 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU Affero General Public License as published 5 | # by the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU Affero General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Affero General Public License 14 | # along with this program. If not, see . 15 | 16 | 17 | """ 18 | Operators computation for pointer analysis; computing values of variables. 19 | """ 20 | 21 | import logging 22 | 23 | import node as _node 24 | 25 | """ 26 | In the following, 27 | - node: Node 28 | Current node. 29 | - initial_node: Node 30 | Node, which we leveraged to compute the value of node (for provenance purpose). 31 | """ 32 | 33 | 34 | def get_node_value(node, initial_node=None, recdepth=0, recvisited=None): 35 | """ Gets the value of node, depending on its type. """ 36 | 37 | if recvisited is None: 38 | recvisited = set() 39 | 40 | if isinstance(node, _node.ValueExpr): 41 | if node.value is not None: # Special case if node references a Node whose value changed 42 | return node.value 43 | 44 | got_attr, node_attributes = node.get_node_attributes() 45 | if got_attr: # Got attributes, returns the value 46 | return node_attributes 47 | 48 | logging.debug('Getting the value from %s', node.name) 49 | 50 | if node.name == 'UnaryExpression': 51 | return compute_unary_expression(node, initial_node=initial_node, 52 | recdepth=recdepth + 1, recvisited=recvisited) 53 | if node.name in ('BinaryExpression', 'LogicalExpression'): 54 | return compute_binary_expression(node, initial_node=initial_node, 55 | recdepth=recdepth + 1, recvisited=recvisited) 56 | if node.name == 'ArrayExpression': 57 | return node 58 | if node.name in ('ObjectExpression', 'ObjectPattern'): 59 | return node 60 | if node.name == 'MemberExpression': 61 | return compute_member_expression(node, initial_node=initial_node, 62 | recdepth=recdepth + 1, recvisited=recvisited) 63 | if node.name == 'ThisExpression': 64 | return 'this' 65 | if isinstance(node, _node.FunctionExpression): 66 | return compute_function_expression(node) 67 | if node.name == 'CallExpression' and isinstance(node.children[0], _node.FunctionExpression): 68 | return node.children[0].fun_name # Function called; mapping to the function name if any 69 | if node.name in _node.CALL_EXPR: 70 | return compute_call_expression(node, initial_node=initial_node, 71 | recdepth=recdepth + 1, recvisited=recvisited) 72 | if node.name == 'ReturnStatement' or node.name == 'BlockStatement': 73 | if node.children: 74 | return get_node_computed_value(node.children[0], initial_node=initial_node, 75 | recdepth=recdepth + 1, recvisited=recvisited) 76 | return None 77 | if node.name == 'TemplateLiteral': 78 | return compute_template_literal(node, initial_node=initial_node, 79 | recdepth=recdepth + 1, recvisited=recvisited) 80 | if node.name == 'ConditionalExpression': 81 | return compute_conditional_expression(node, initial_node=initial_node, 82 | recdepth=recdepth + 1, recvisited=recvisited) 83 | if node.name == 'AssignmentExpression': 84 | return compute_assignment_expression(node, initial_node=initial_node, 85 | recdepth=recdepth + 1, recvisited=recvisited) 86 | if node.name == 'UpdateExpression': 87 | return get_node_computed_value(node.children[0], initial_node=initial_node, 88 | recdepth=recdepth + 1, recvisited=recvisited) 89 | 90 | for child in node.children: 91 | get_node_computed_value(child, initial_node=initial_node, 92 | recdepth=recdepth + 1, recvisited=recvisited) 93 | 94 | logging.warning('Could not get the value of the node %s, whose attributes are %s', 95 | node.name, node.attributes) 96 | 97 | return None 98 | 99 | 100 | def get_node_computed_value(node, initial_node=None, keep_none=False, recdepth=0, recvisited=None): 101 | """ Computes the value of node, depending on its type. """ 102 | 103 | if recvisited is None: 104 | recvisited = set() 105 | 106 | logging.debug("Visiting node: %s", node.attributes) 107 | 108 | if node in recvisited: 109 | if isinstance(node, _node.Value): 110 | logging.debug("Revisiting node: %s %s (value: %s)", node.attributes, initial_node, 111 | node.value) 112 | return node.value 113 | logging.debug("Revisiting node: %s %s (none)", node.attributes, initial_node) 114 | return None 115 | recvisited.add(node) 116 | if recdepth > 1000: 117 | logging.debug("Recursion depth for get_node_computed_value exceeded: %s", node.attributes) 118 | if hasattr(node, "value"): 119 | return node.value 120 | return None 121 | 122 | value = None 123 | if isinstance(initial_node, _node.Value): 124 | logging.debug('%s is depending on %s', initial_node.attributes, node.attributes) 125 | initial_node.set_provenance(node) 126 | 127 | if isinstance(node, _node.Value): # if we already know the value 128 | value = node.value # might be directly a value (int/str) or a Node referring to the value 129 | logging.debug('Computing the value of an %s node, got %s', node.name, value) 130 | 131 | if isinstance(value, _node.Node): # node.value is a Node 132 | # computing actual value 133 | if node.value != node: 134 | value = get_node_computed_value(node.value, initial_node=initial_node, 135 | recdepth=recdepth + 1, recvisited=recvisited) 136 | logging.debug('Its value is a node, computed it and got %s', value) 137 | 138 | if value is None and not keep_none: # node is not an Identifier or is None 139 | # keep_none True is just for display_temp, to avoid having an Identifier variable with 140 | # None value being equal to the variable because of the call to get_node_value on itself 141 | value = get_node_value(node, initial_node=initial_node, 142 | recdepth=recdepth + 1, recvisited=recvisited) 143 | logging.debug('The value should be computed, got %s', value) 144 | 145 | if isinstance(node, _node.Value) and node.name not in _node.CALL_EXPR: 146 | # Do not store value for CallExpr as could have changed and should be recomputed 147 | node.set_value(value) # Stores the value so as not to compute it again 148 | 149 | return value 150 | 151 | 152 | def compute_operators(operator, node_a, node_b, initial_node=None, recdepth=0, recvisited=None): 153 | """ Evaluates node_a operator node_b. """ 154 | 155 | if isinstance(node_a, _node.Node): # Standard case 156 | if isinstance(node_a, _node.Identifier): 157 | # If it is an Identifier, it should have a value, possibly None. 158 | # But the value should not be the Identifier's name. 159 | a = get_node_computed_value(node_a, initial_node=initial_node, keep_none=True, 160 | recdepth=recdepth + 1, recvisited=recvisited) 161 | else: 162 | a = get_node_computed_value(node_a, initial_node=initial_node, 163 | recdepth=recdepth + 1, recvisited=recvisited) 164 | else: # Specific to compute_binary_expression 165 | a = node_a # node_a may not be a Node but already a computed result 166 | if isinstance(node_b, _node.Node): # Standard case 167 | if isinstance(node_b, _node.Identifier): 168 | b = get_node_computed_value(node_b, initial_node=initial_node, keep_none=True, 169 | recdepth=recdepth + 1, recvisited=recvisited) 170 | else: 171 | b = get_node_computed_value(node_b, initial_node=initial_node, 172 | recdepth=recdepth + 1, recvisited=recvisited) 173 | else: # Specific to compute_binary_expression 174 | b = node_b # node_b may not be a Node but already a computed result 175 | 176 | if not isinstance(a, (int, float)) or not isinstance(b, (int, float)): 177 | if operator in ('+=', '+') and (isinstance(a, str) or isinstance(b, str)): 178 | return operator_plus(a, b) 179 | if a is None or b is None: 180 | return None 181 | if (not isinstance(a, str) or isinstance(a, str) and not '.' in a)\ 182 | and (not isinstance(b, str) or isinstance(b, str) and not '.' in b): 183 | # So that if MemExpr could not be fully computed we do not take any hasty decisions 184 | # For ex: data.message.split(-).1.toUpperCase() == POST is undecidable for us 185 | # But abc == abc is not 186 | pass 187 | else: 188 | logging.warning('Unable to compute %s %s %s', a, operator, b) 189 | return None 190 | 191 | try: 192 | if operator in ('+=', '+'): 193 | return operator_plus(a, b) 194 | if operator in ('-=', '-'): 195 | return operator_minus(a, b) 196 | if operator in ('*=', '*'): 197 | return operator_asterisk(a, b) 198 | if operator in ('/=', '/'): 199 | return operator_slash(a, b) 200 | if operator in ('**=', '**'): 201 | return operator_2asterisk(a, b) 202 | if operator in ('%=', '%'): 203 | return operator_modulo(a, b) 204 | if operator == '++': 205 | return operator_plus_plus(a) 206 | if operator == '--': 207 | return operator_minus_minus(a) 208 | if operator in ('==', '==='): 209 | return operator_equal(a, b) 210 | if operator in ('!=', '!=='): 211 | return operator_different(a, b) 212 | if operator == '!': 213 | return operator_not(a) 214 | if operator == '>=': 215 | return operator_bigger_equal(a, b) 216 | if operator == '>': 217 | return operator_bigger(a, b) 218 | if operator == '<=': 219 | return operator_smaller_equal(a, b) 220 | if operator == '<': 221 | return operator_smaller(a, b) 222 | if operator == '&&': 223 | return operator_and(a, b) 224 | if operator == '||': 225 | return operator_or(a, b) 226 | if operator in ('&', '>>', '>>>', '<<', '^', '|', '&=', '>>=', '>>>=', '<<=', '^=', '|=', 227 | 'in', 'instanceof'): 228 | logging.warning('Currently not handling the operator %s', operator) 229 | return None 230 | 231 | except TypeError: 232 | logging.warning('Type problem, could not compute %s %s %s', a, operator, b) 233 | return None 234 | 235 | logging.error('Unknown operator %s', operator) 236 | return None 237 | 238 | 239 | def compute_unary_expression(node, initial_node, recdepth=0, recvisited=None): 240 | """ Evaluates an UnaryExpression node. """ 241 | 242 | compute_unary = get_node_computed_value(node.children[0], initial_node=initial_node, 243 | recdepth=recdepth + 1, recvisited=recvisited) 244 | if compute_unary is None: 245 | return None 246 | if isinstance(compute_unary, bool): 247 | return not compute_unary 248 | if isinstance(compute_unary, (int, float)): 249 | return - compute_unary 250 | if isinstance(compute_unary, str): # So as not to lose the current compute_unary value 251 | return node.attributes['operator'] + compute_unary # Adds the UnaryOp before value 252 | 253 | logging.warning('Could not compute the unary operation %s on %s', 254 | node.attributes['operator'], compute_unary) 255 | return None 256 | 257 | 258 | def compute_binary_expression(node, initial_node, recdepth=0, recvisited=None): 259 | """ Evaluates a BinaryExpression node. """ 260 | 261 | operator = node.attributes['operator'] 262 | node_a = node.children[0] 263 | node_b = node.children[1] 264 | 265 | # node_a operator node_b 266 | return compute_operators(operator, node_a, node_b, initial_node=initial_node, 267 | recdepth=recdepth, recvisited=recvisited) 268 | 269 | 270 | def compute_member_expression(node, initial_node, compute=True, recdepth=0, recvisited=None): 271 | """ Evaluates a MemberExpression node. """ 272 | 273 | obj = node.children[0] 274 | prop = node.children[1] 275 | prop_value = get_node_computed_value(prop, initial_node=initial_node, recdepth=recdepth + 1, 276 | recvisited=recvisited) # Computes the value 277 | obj_value = get_node_computed_value(obj, initial_node=initial_node, 278 | recdepth=recdepth + 1, recvisited=recvisited) 279 | if obj.name == 'ThisExpression' or obj_value in _node.GLOBAL_VAR: 280 | return prop_value 281 | 282 | if not isinstance(obj_value, _node.Node): 283 | # Specific case if we changed an Array/Object type 284 | # var my_array = [[1]]; my_array[0] = 18; e = my_array[0][0]; -> e undefined hence None 285 | # If ArrayExpression or ObjectExpression, we are trying to access an element that does not 286 | # exist anymore, will be displayed as .prop 287 | # Otherwise: obj.prop 288 | if isinstance(obj_value, list): # Special case for TaggedTemplateExpression 289 | if isinstance(prop_value, int): 290 | try: 291 | return obj_value[prop_value] # Params passed in obj_value, cf. data_flow 292 | except IndexError as e: 293 | logging.exception(e) 294 | logging.exception('Could not get the property %s of %s', prop_value, obj_value) 295 | return None 296 | elif isinstance(obj_value, dict): # Special case for already defined objects with new prop 297 | if prop_value in obj_value: 298 | return obj_value[prop_value] # ex: localStorage.firstTime 299 | return None 300 | return display_member_expression_value(node, '', initial_node=initial_node)[0:-1] 301 | 302 | # obj_value.prop_value or obj_value[prop_value] 303 | if obj_value.name == 'Literal' or obj_value.name == 'Identifier': 304 | member_expression_value = obj_value # We already have the value 305 | else: 306 | if isinstance(prop_value, str): # obj_value.prop_value -> prop_value str = object property 307 | obj_prop_list = [] 308 | search_object_property(obj_value, prop_value, obj_prop_list) 309 | if obj_prop_list: # Stores all matches 310 | member_expression_value = None 311 | for obj_prop in obj_prop_list: 312 | member_expression_value, worked = get_property_value(obj_prop, 313 | initial_node=initial_node, 314 | recdepth=recdepth + 1, 315 | recvisited=recvisited) 316 | if worked: # Takes the first one that is working 317 | break 318 | else: 319 | member_expression_value = None 320 | logging.warning('Could not get the property %s of the %s with value %s', 321 | prop_value, obj.name, obj_value) 322 | elif isinstance(prop_value, int): # obj_value[prop_value] -> prop_value int = array index 323 | if len(obj_value.children) > prop_value: 324 | member_expression_value = obj_value.children[prop_value] # We fetch the value 325 | else: 326 | member_expression_value = display_member_expression_value\ 327 | (node, '', initial_node=initial_node)[0:-1] 328 | else: 329 | logging.error('Expected an str or an int, got a %s', type(prop_value)) 330 | member_expression_value = None 331 | 332 | if compute and isinstance(member_expression_value, _node.Node): 333 | # Computes the value 334 | return get_node_computed_value(member_expression_value, initial_node=initial_node, 335 | recdepth=recdepth + 1) 336 | 337 | return member_expression_value # Returns the node referencing the value 338 | 339 | 340 | def search_object_property(node, prop, found_list): 341 | """ Search in an object definition where a given property (-> prop = str) is defined. 342 | Storing all the matches in case the first one is not the right one, e.g., 343 | var obj = { 344 | f1: function(a) {obj.f2(1)}, 345 | f2: function(a) {} 346 | }; 347 | obj.f2(); 348 | By looking for f2, the 1st match is wrong and will lead to an error, the 2nd one is correct.""" 349 | 350 | if 'name' in node.attributes: 351 | if isinstance(prop, str): 352 | if node.attributes['name'] == prop: 353 | # prop is already the value 354 | found_list.append(node) 355 | elif 'value' in node.attributes: 356 | if isinstance(prop, str): 357 | if node.attributes['value'] == prop: 358 | # prop is already the value 359 | found_list.append(node) 360 | 361 | for child in node.children: 362 | search_object_property(child, prop, found_list) 363 | 364 | 365 | def get_property_value(node, initial_node, recdepth=0, recvisited=None): 366 | """ Get the value of an object's property. """ 367 | 368 | if (isinstance(node, _node.Identifier) or node.name == 'Literal')\ 369 | and node.parent.name == 'Property': 370 | prop_value = node.parent.children[1] 371 | if prop_value.name == 'Literal': 372 | return prop_value, True 373 | return get_node_computed_value(prop_value, initial_node=initial_node, recdepth=recdepth + 1, 374 | recvisited=recvisited), True 375 | 376 | logging.warning('Trying to get the property value of %s whose parent is %s', 377 | node.name, node.parent.name) 378 | return None, False 379 | 380 | 381 | def compute_function_expression(node): 382 | """ Computes a (Arrow)FunctionExpression node. """ 383 | 384 | fun_name = node.fun_name 385 | if fun_name is not None: 386 | return fun_name # Mapping to the function's name if any 387 | return node # Otherwise mapping to the FunExpr handler 388 | 389 | 390 | def compute_call_expression(node, initial_node, recdepth=0, recvisited=None): 391 | """ Gets the value of CallExpression with parameters. """ 392 | 393 | if isinstance(initial_node, _node.Value): 394 | initial_node.set_provenance(node) 395 | 396 | callee = node.children[0] 397 | params = '(' 398 | 399 | for arg in range(1, len(node.children)): 400 | # Computes the value of the arguments: a.b...(arg1, arg2...) 401 | params += str(get_node_computed_value(node.children[arg], initial_node=initial_node, 402 | recdepth=recdepth + 1, recvisited=recvisited)) 403 | if arg < len(node.children) - 1: 404 | params += ', ' 405 | 406 | params += ')' 407 | 408 | if isinstance(callee, _node.Identifier): 409 | return str(get_node_computed_value(callee, initial_node=initial_node, 410 | recdepth=recdepth + 1, recvisited=recvisited)) + params 411 | 412 | if callee.name == 'MemberExpression': 413 | value = display_member_expression_value(callee, '', initial_node=initial_node) 414 | value = value[0:-1] + params 415 | return value 416 | # return compute_member_expression(callee) + params # To test if problems here 417 | 418 | if callee.name in _node.CALL_EXPR: 419 | if get_node_computed_value(callee, initial_node=initial_node, recdepth=recdepth + 1, 420 | recvisited=recvisited) is None or params is None: 421 | return None 422 | return get_node_computed_value(callee, initial_node=initial_node, 423 | recdepth=recdepth + 1, recvisited=recvisited) + params 424 | 425 | if callee.name == 'LogicalExpression': # a || b, if a not False a otherwise b 426 | if get_node_computed_value(callee.children[0], initial_node=initial_node, 427 | recdepth=recdepth + 1, recvisited=recvisited) is False: 428 | return get_node_computed_value(callee.children[1], initial_node=initial_node, 429 | recdepth=recdepth + 1, recvisited=recvisited) 430 | return get_node_computed_value(callee.children[0], initial_node=initial_node, 431 | recdepth=recdepth + 1, recvisited=recvisited) 432 | 433 | logging.error('Got a CallExpression on %s with attributes %s and id %s', 434 | callee.name, callee.attributes, callee.id) 435 | return None 436 | 437 | 438 | def compute_template_literal(node, initial_node, recdepth=0, recvisited=None): 439 | """ Gets the value of TemplateLiteral. """ 440 | 441 | template_element = [] # Seems that TemplateElement = similar to Literal and in front 442 | expressions = [] # vs. Expressions has to be computed and are at the end 443 | template_literal = '' 444 | 445 | for child in node.children: 446 | if child.name == 'TemplateElement': # Either that 447 | template_element.append(child) 448 | else: # Or Expressions 449 | expressions.append(child) 450 | 451 | len_template_element = len(template_element) 452 | len_expressions = len(expressions) 453 | 454 | if len_template_element != len_expressions + 1: 455 | logging.error('Unexpected %s with %s TemplateElements and %s Expressions', node.type, 456 | len_template_element, len_expressions) 457 | return None 458 | 459 | for i in range(len_expressions): 460 | # Will concatenate: 1 TemplateElement, 1 Expr, ..., 1 TemplateElement 461 | template_literal += str(get_node_computed_value(template_element[i], 462 | initial_node=initial_node, 463 | recdepth=recdepth + 1, 464 | recvisited=recvisited)) \ 465 | + str(get_node_computed_value(expressions[i], 466 | initial_node=initial_node, 467 | recdepth=recdepth + 1, 468 | recvisited=recvisited)) 469 | template_literal += str(get_node_computed_value(template_element[len_template_element - 1], 470 | initial_node=initial_node, 471 | recdepth=recdepth + 1, 472 | recvisited=recvisited)) 473 | 474 | return template_literal 475 | 476 | 477 | def display_member_expression_value(node, value, initial_node): 478 | """ Displays the value of elements from a MemberExpression. """ 479 | 480 | for child in node.children: 481 | if child.name == 'MemberExpression': 482 | value = display_member_expression_value(child, value, initial_node=initial_node) 483 | else: 484 | value += str(get_node_computed_value(child, initial_node=initial_node)) + '.' 485 | return value 486 | 487 | 488 | def compute_object_expr(node, initial_node): 489 | """ For debug: displays the content of an ObjectExpression. """ 490 | 491 | node_value = '{' 492 | 493 | for prop in node.children: 494 | key = prop.children[0] 495 | key_value = get_node_computed_value(key, initial_node=initial_node) 496 | value = prop.children[1] 497 | value_value = get_node_computed_value(value, initial_node=initial_node) 498 | 499 | prop_value = str(key_value) + ': ' + str(value_value) 500 | node_value += '\n\t' + prop_value 501 | 502 | node_value += '\n}' 503 | return node_value 504 | 505 | 506 | def compute_conditional_expression(node, initial_node, recdepth=0, recvisited=None): 507 | """ Gets the value of a ConditionalExpression. """ 508 | 509 | test = get_node_computed_value(node.children[0], initial_node=initial_node, 510 | recdepth=recdepth + 1, recvisited=recvisited) 511 | consequent = get_node_computed_value(node.children[1], initial_node=initial_node, 512 | recdepth=recdepth + 1, recvisited=recvisited) 513 | alternate = get_node_computed_value(node.children[2], initial_node=initial_node, 514 | recdepth=recdepth + 1, recvisited=recvisited) 515 | if not isinstance(test, bool): 516 | test = None # So that must be either True, False or None 517 | if test is None: 518 | return [alternate, consequent] 519 | if test: 520 | return consequent 521 | return alternate 522 | 523 | 524 | def compute_assignment_expression(node, initial_node, recdepth=0, recvisited=None): 525 | """ Computes the value of an AssignmentExpression node. """ 526 | 527 | var = node.children[0] # Value coming from the right: a = b = value, computing a knowing b 528 | if isinstance(var, _node.Value) and var.value is not None: 529 | return var.value 530 | return get_node_computed_value(var, initial_node=initial_node, 531 | recdepth=recdepth + 1, recvisited=recvisited) 532 | 533 | 534 | def operator_plus(a, b): 535 | """ Evaluates a + b. """ 536 | if isinstance(a, str) or isinstance(b, str): 537 | return str(a) + str(b) 538 | return a + b 539 | 540 | 541 | def operator_minus(a, b): 542 | """ Evaluates a - b. """ 543 | return a - b 544 | 545 | 546 | def operator_asterisk(a, b): 547 | """ Evaluates a * b. """ 548 | return a * b 549 | 550 | 551 | def operator_slash(a, b): 552 | """ Evaluates a / b. """ 553 | if b == 0: 554 | logging.warning('Trying to compute %s / %s', a, b) 555 | return None 556 | return a / b 557 | 558 | 559 | def operator_2asterisk(a, b): 560 | """ Evaluates a ** b. """ 561 | return a ** b 562 | 563 | 564 | def operator_modulo(a, b): 565 | """ Evaluates a % b. """ 566 | return a % b 567 | 568 | 569 | def operator_plus_plus(a): 570 | """ Evaluates a++. """ 571 | return a + 1 572 | 573 | 574 | def operator_minus_minus(a): 575 | """ Evaluates a--. """ 576 | return a - 1 577 | 578 | 579 | def operator_equal(a, b): 580 | """ Evaluates a == b. """ 581 | return a == b 582 | 583 | 584 | def operator_different(a, b): 585 | """ Evaluates a != b. """ 586 | return a != b 587 | 588 | 589 | def operator_not(a): 590 | """ Evaluates !a. """ 591 | return not a 592 | 593 | 594 | def operator_bigger_equal(a, b): 595 | """ Evaluates a >= b. """ 596 | return a >= b 597 | 598 | 599 | def operator_bigger(a, b): 600 | """ Evaluates a > b. """ 601 | return a > b 602 | 603 | 604 | def operator_smaller_equal(a, b): 605 | """ Evaluates a <= b. """ 606 | return a <= b 607 | 608 | 609 | def operator_smaller(a, b): 610 | """ Evaluates a < b. """ 611 | return a < b 612 | 613 | 614 | def operator_and(a, b): 615 | """ Evaluates a and b. """ 616 | return a and b 617 | 618 | 619 | def operator_or(a, b): 620 | """ Evaluates a or b. """ 621 | return a or b 622 | -------------------------------------------------------------------------------- /src/js_reserved.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021 Aurore Fass 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU Affero General Public License as published 5 | # by the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU Affero General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Affero General Public License 14 | # along with this program. If not, see . 15 | 16 | 17 | """ 18 | JavaScript reserved keywords or words known by the interpreter. 19 | """ 20 | 21 | # Note: slightly improved from HideNoSeek (browser extension keywords) 22 | 23 | 24 | RESERVED_WORDS = ["abstract", "arguments", "await", "boolean", "break", "byte", "case", "catch", 25 | "char", "class", "const", "continue", "debugger", "default", "delete", "do", 26 | "double", "else", "enum", "eval", "export", "extends", "false", "final", 27 | "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", 28 | "instanceof", "int", "interface", "let", "long", "native", "new", "null", 29 | "package", "private", "protected", "public", "return", "short", "static", "super", 30 | "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", 31 | "typeof", "var", "void", "volatile", "while", "with", "yield", "Array", 32 | "Date", "eval", "function", "hasOwnProperty", "Infinity", "isFinite", "isNaN", 33 | "isPrototypeOf", "length", "Math", "NaN", "name", "Number", "Object", "prototype", 34 | "String", "toString", "undefined", "valueOf", "getClass", "java", "JavaArray", 35 | "javaClass", "JavaObject", "JavaPackage", "alert", "all", "anchor", "anchors", 36 | "area", "assign", "blur", "button", "checkbox", "clearInterval", "clearTimeout", 37 | "clientInformation", "close", "closed", "confirm", "constructor", "crypto", 38 | "decodeURI", "decodeURIComponent", "defaultStatus", "document", "element", 39 | "elements", "embed", "embeds", "encodeURI", "encodeURIComponent", "escape", 40 | "event", "fileUpload", "focus", "form", "forms", "frame", "innerHeight", 41 | "innerWidth", "layer", "layers", "link", "location", "mimeTypes", "navigate", 42 | "navigator", "frames", "frameRate", "hidden", "history", "image", "images", 43 | "offscreenBuffering", "open", "opener", "option", "outerHeight", "outerWidth", 44 | "packages", "pageXOffset", "pageYOffset", "parent", "parseFloat", "parseInt", 45 | "password", "pkcs11", "plugin", "prompt", "propertyIsEnum", "radio", "reset", 46 | "screenX", "screenY", "scroll", "secure", "select", "self", "setInterval", 47 | "setTimeout", "status", "submit", "taint", "text", "textarea", "top", "unescape", 48 | "untaint", "window", "onblur", "onclick", "onerror", "onfocus", "onkeydown", 49 | "onkeypress", "onkeyup", "onmouseover", "onload", "onmouseup", "onmousedown", 50 | "onsubmit", 51 | "define", "exports", "require", "each", "ActiveXObject", "console", "module", 52 | "Error", "TypeError", "RangeError", "RegExp", "Symbol", "Set"] 53 | 54 | 55 | BROWSER_EXTENSIONS = ['addEventListener', 'browser', 'chrome', 'localStorage', 'postMessage', 56 | 'Promise', 'JSON', 'XMLHttpRequest', '$', 'screen', 'CryptoJS'] 57 | 58 | KNOWN_WORDS_LOWER = [word.lower() for word in RESERVED_WORDS + BROWSER_EXTENSIONS] 59 | -------------------------------------------------------------------------------- /src/node.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021 Aurore Fass 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU Affero General Public License as published 5 | # by the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU Affero General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Affero General Public License 14 | # along with this program. If not, see . 15 | 16 | 17 | """ 18 | Definition of classes: 19 | - Dependence; 20 | - Node; 21 | - Value; 22 | - Identifier(Node, Value); 23 | - ValueExpr(Node, Value); 24 | - Statement(Node); 25 | - ReturnStatement(Statement, Value); 26 | - Function; 27 | - FunctionDeclaration(Statement, Function); 28 | - FunctionExpression(Node, Function) 29 | """ 30 | 31 | # Note: going significantly beyond the node structure of HideNoSeek: 32 | # semantic information to the nodes, which have different properties, e.g., DF on Identifier, 33 | # parameter flows, value handling, provenance tracking, etc 34 | 35 | 36 | import logging 37 | import random 38 | 39 | import utility_df 40 | 41 | EXPRESSIONS = ['AssignmentExpression', 'ArrayExpression', 'ArrowFunctionExpression', 42 | 'AwaitExpression', 'BinaryExpression', 'CallExpression', 'ClassExpression', 43 | 'ConditionalExpression', 'FunctionExpression', 'LogicalExpression', 44 | 'MemberExpression', 'NewExpression', 'ObjectExpression', 'SequenceExpression', 45 | 'TaggedTemplateExpression', 'ThisExpression', 'UnaryExpression', 'UpdateExpression', 46 | 'YieldExpression'] 47 | 48 | EPSILON = ['BlockStatement', 'DebuggerStatement', 'EmptyStatement', 49 | 'ExpressionStatement', 'LabeledStatement', 'ReturnStatement', 50 | 'ThrowStatement', 'WithStatement', 'CatchClause', 'VariableDeclaration', 51 | 'FunctionDeclaration', 'ClassDeclaration'] 52 | 53 | CONDITIONAL = ['DoWhileStatement', 'ForStatement', 'ForOfStatement', 'ForInStatement', 54 | 'IfStatement', 'SwitchCase', 'SwitchStatement', 'TryStatement', 55 | 'WhileStatement', 'ConditionalExpression'] 56 | 57 | UNSTRUCTURED = ['BreakStatement', 'ContinueStatement'] 58 | 59 | STATEMENTS = EPSILON + CONDITIONAL + UNSTRUCTURED 60 | CALL_EXPR = ['CallExpression', 'TaggedTemplateExpression', 'NewExpression'] 61 | VALUE_EXPR = ['Literal', 'ArrayExpression', 'ObjectExpression', 'ObjectPattern'] + CALL_EXPR 62 | COMMENTS = ['Line', 'Block'] 63 | 64 | GLOBAL_VAR = ['window', 'this', 'self', 'top', 'global', 'that'] 65 | 66 | LIMIT_SIZE = utility_df.LIMIT_SIZE # To avoid list values with over 1,000 characters 67 | 68 | 69 | class Dependence: 70 | """ For control, data, comment, and statement dependencies. """ 71 | 72 | def __init__(self, dependency_type, extremity, label, nearest_statement=None): 73 | self.type = dependency_type 74 | self.extremity = extremity 75 | self.nearest_statement = nearest_statement 76 | self.label = label 77 | 78 | 79 | class Node: 80 | """ Defines a Node that is used in the AST. """ 81 | 82 | id = random.randint(0, 2*32) # To limit id collision between 2 ASTs from separate processes 83 | 84 | def __init__(self, name, parent=None): 85 | self.name = name 86 | self.id = Node.id 87 | Node.id += 1 88 | self.filename = '' 89 | self.attributes = {} 90 | self.body = None 91 | self.body_list = False 92 | self.parent = parent 93 | self.children = [] 94 | self.statement_dep_parents = [] 95 | self.statement_dep_children = [] # Between Statement and their non-Statement descendants 96 | 97 | def is_leaf(self): 98 | return not self.children 99 | 100 | def set_attribute(self, attribute_type, node_attribute): 101 | self.attributes[attribute_type] = node_attribute 102 | 103 | def set_body(self, body): 104 | self.body = body 105 | 106 | def set_body_list(self, bool_body_list): 107 | self.body_list = bool_body_list 108 | 109 | def set_parent(self, parent): 110 | self.parent = parent 111 | 112 | def set_child(self, child): 113 | self.children.append(child) 114 | 115 | def adopt_child(self, step_daddy): # child = self changes parent 116 | old_parent = self.parent 117 | old_parent.children.remove(self) # Old parent does not point to the child anymore 118 | step_daddy.children.insert(0, self) # New parent points to the child 119 | self.set_parent(step_daddy) # The child points to its new parent 120 | 121 | def set_statement_dependency(self, extremity): 122 | self.statement_dep_children.append(Dependence('statement dependency', extremity, '')) 123 | extremity.statement_dep_parents.append(Dependence('statement dependency', self, '')) 124 | 125 | # def set_comment_dependency(self, extremity): 126 | # self.statement_dep_children.append(Dependence('comment dependency', extremity, 'c')) 127 | # extremity.statement_dep_parents.append(Dependence('comment dependency', self, 'c')) 128 | 129 | def is_comment(self): 130 | if self.name in COMMENTS: 131 | return True 132 | return False 133 | 134 | def get_node_attributes(self): 135 | """ Get the attributes regex, value or name of a node. """ 136 | node_attribute = self.attributes 137 | if 'regex' in node_attribute: 138 | regex = node_attribute['regex'] 139 | if isinstance(regex, dict) and 'pattern' in regex: 140 | return True, '/' + str(regex['pattern']) + '/' 141 | if 'value' in node_attribute: 142 | value = node_attribute['value'] 143 | if isinstance(value, dict) and 'raw' in value: 144 | return True, value['raw'] 145 | return True, node_attribute['value'] 146 | if 'name' in node_attribute: 147 | return True, node_attribute['name'] 148 | return False, None # Just None was a pb when used in get_node_value as value could be None 149 | 150 | def get_line(self): 151 | """ Gets the line number where a given node is defined. """ 152 | try: 153 | line_begin = self.attributes['loc']['start']['line'] 154 | line_end = self.attributes['loc']['end']['line'] 155 | return str(line_begin) + ' - ' + str(line_end) 156 | except KeyError: 157 | return None 158 | 159 | def get_file(self): 160 | parent = self 161 | while True: 162 | if parent is not None and parent.parent: 163 | parent = parent.parent 164 | else: 165 | break 166 | if parent is not None: 167 | if "filename" in parent.attributes: 168 | return parent.attributes["filename"] 169 | return '' 170 | 171 | 172 | def literal_type(literal_node): 173 | """ Gets the type of a Literal node. """ 174 | 175 | if 'value' in literal_node.attributes: 176 | literal = literal_node.attributes['value'] 177 | if isinstance(literal, str): 178 | return 'String' 179 | if isinstance(literal, int): 180 | return 'Int' 181 | if isinstance(literal, float): 182 | return 'Numeric' 183 | if isinstance(literal, bool): 184 | return 'Bool' 185 | if literal == 'null' or literal is None: 186 | return 'Null' 187 | if 'regex' in literal_node.attributes: 188 | return 'RegExp' 189 | logging.error('The literal %s has an unknown type', literal_node.attributes['raw']) 190 | return None 191 | 192 | 193 | def shorten_value_list(value_list, value_list_shortened, counter=0): 194 | """ When a value is a list, shorten it so that keep at most LIMIT_SIZE characters. """ 195 | 196 | for el in value_list: 197 | if isinstance(el, list): 198 | value_list_shortened.append([]) 199 | counter = shorten_value_list(el, value_list_shortened[-1], counter) 200 | if counter >= LIMIT_SIZE: 201 | return counter 202 | elif isinstance(el, str): 203 | counter += len(el) 204 | if counter < LIMIT_SIZE: 205 | value_list_shortened.append(el) 206 | else: 207 | counter += len(str(el)) 208 | if counter < LIMIT_SIZE: 209 | value_list_shortened.append(el) 210 | return counter 211 | 212 | 213 | def shorten_value_dict(value_dict, value_dict_shortened, counter=0, visited=None): 214 | """ When a value is a dict, shorten it so that keep at most LIMIT_SIZE characters. """ 215 | 216 | if visited is None: 217 | visited = set() 218 | if id(value_dict) in visited: 219 | return counter 220 | visited.add(id(value_dict)) 221 | 222 | for k, v in value_dict.items(): 223 | if isinstance(k, str): 224 | counter += len(k) 225 | if isinstance(v, list): 226 | value_dict_shortened[k] = [] 227 | counter = shorten_value_list(v, value_dict_shortened[k], counter) 228 | if counter >= LIMIT_SIZE: 229 | return counter 230 | elif isinstance(v, dict): 231 | value_dict_shortened[k] = {} 232 | if id(v) in visited: 233 | return counter 234 | counter = shorten_value_dict(v, value_dict_shortened[k], counter, visited) 235 | if counter >= LIMIT_SIZE: 236 | return counter 237 | elif isinstance(v, str): 238 | counter += len(v) 239 | if counter < LIMIT_SIZE: 240 | value_dict_shortened[k] = v 241 | else: 242 | counter += len(str(v)) 243 | if counter < LIMIT_SIZE: 244 | value_dict_shortened[k] = v 245 | return counter 246 | 247 | 248 | class Value: 249 | """ To store the value of a specific node. """ 250 | 251 | def __init__(self): 252 | self.value = None 253 | self.update_value = True 254 | self.provenance_children = [] 255 | self.provenance_parents = [] 256 | self.provenance_children_set = set() 257 | self.provenance_parents_set = set() 258 | self.seen_provenance = set() 259 | 260 | def set_value(self, value): 261 | if isinstance(value, list): # To shorten value if over LIMIT_SIZE characters 262 | value_shortened = [] 263 | counter = shorten_value_list(value, value_shortened) 264 | if counter >= LIMIT_SIZE: 265 | value = value_shortened 266 | logging.warning('Shortened the value of %s %s', self.name, self.attributes) 267 | elif isinstance(value, dict): # To shorten value if over LIMIT_SIZE characters 268 | value_shortened = {} 269 | counter = shorten_value_dict(value, value_shortened) 270 | if counter >= LIMIT_SIZE: 271 | value = value_shortened 272 | logging.warning('Shortened the value of %s %s', self.name, self.attributes) 273 | elif isinstance(value, str): # To shorten value if over LIMIT_SIZE characters 274 | value = value[:LIMIT_SIZE] 275 | self.value = value 276 | 277 | def set_update_value(self, update_value): 278 | self.update_value = update_value 279 | 280 | def set_provenance_dd(self, extremity): # Set Node provenance, set_data_dependency case 281 | # self is the origin of the DD while extremity is the destination of the DD 282 | if extremity.provenance_children: 283 | for child in extremity.provenance_children: 284 | if child not in self.provenance_children_set: 285 | self.provenance_children_set.add(child) 286 | self.provenance_children.append(child) 287 | else: 288 | if extremity not in self.provenance_children_set: 289 | self.provenance_children_set.add(extremity) 290 | self.provenance_children.append(extremity) 291 | if self.provenance_parents: 292 | for parent in self.provenance_parents: 293 | if parent not in extremity.provenance_parents_set: 294 | extremity.provenance_parents_set.add(parent) 295 | extremity.provenance_parents.append(parent) 296 | else: 297 | if self not in extremity.provenance_parents_set: 298 | extremity.provenance_parents_set.add(self) 299 | extremity.provenance_parents.append(self) 300 | 301 | def set_provenance(self, extremity): # Set Node provenance, computed value case 302 | """ 303 | a.b = c 304 | """ 305 | if extremity in self.seen_provenance: 306 | pass 307 | self.seen_provenance.add(extremity) 308 | # extremity was leveraged to compute the value of self 309 | if not isinstance(extremity, Node): # extremity is None: 310 | if self not in self.provenance_parents_set: 311 | self.provenance_parents_set.add(self) 312 | self.provenance_parents.append(self) 313 | elif isinstance(extremity, Value): 314 | if extremity.provenance_parents: 315 | for parent in extremity.provenance_parents: 316 | if parent not in self.provenance_parents_set: 317 | self.provenance_parents_set.add(parent) 318 | self.provenance_parents.append(parent) 319 | else: 320 | if extremity not in self.provenance_parents_set: 321 | self.provenance_parents_set.add(extremity) 322 | self.provenance_parents.append(extremity) 323 | if self.provenance_children: 324 | for child in self.provenance_children: 325 | if child not in extremity.provenance_children_set: 326 | extremity.provenance_children_set.add(child) 327 | extremity.provenance_children.append(child) 328 | else: 329 | if self not in extremity.provenance_children_set: 330 | extremity.provenance_children_set.add(self) 331 | extremity.provenance_children.append(self) 332 | elif isinstance(extremity, Node): # Otherwise very restrictive 333 | self.provenance_parents_set.add(extremity) 334 | self.provenance_parents.append(extremity) 335 | for extremity_child in extremity.children: # Not necessarily useful 336 | self.set_provenance(extremity_child) 337 | 338 | def set_provenance_rec(self, extremity): 339 | self.set_provenance(extremity) 340 | for child in extremity.children: 341 | self.set_provenance_rec(child) 342 | 343 | 344 | class Identifier(Node, Value): 345 | """ Identifier Nodes. DD is on Identifier nodes. """ 346 | 347 | def __init__(self, name, parent): 348 | Node.__init__(self, name, parent) 349 | Value.__init__(self) 350 | self.code = None 351 | self.fun = None 352 | self.data_dep_parents = [] 353 | self.data_dep_children = [] 354 | 355 | def set_code(self, code): 356 | self.code = code 357 | 358 | def set_fun(self, fun): # The Identifier node refers to a function ('s name) 359 | self.fun = fun 360 | 361 | def set_data_dependency(self, extremity, nearest_statement=None): 362 | if extremity not in [el.extremity for el in self.data_dep_children]: # Avoids duplicates 363 | self.data_dep_children.append(Dependence('data dependency', extremity, 'data', 364 | nearest_statement)) 365 | extremity.data_dep_parents.append(Dependence('data dependency', self, 'data', 366 | nearest_statement)) 367 | self.set_provenance_dd(extremity) # Stored provenance 368 | 369 | 370 | class ValueExpr(Node, Value): 371 | """ Nodes from VALUE_EXPR which therefore have a value that should be stored. """ 372 | 373 | def __init__(self, name, parent): 374 | Node.__init__(self, name, parent) 375 | Value.__init__(self) 376 | 377 | 378 | class Statement(Node): 379 | """ Statement Nodes, see STATEMENTS. """ 380 | 381 | def __init__(self, name, parent): 382 | Node.__init__(self, name, parent) 383 | self.control_dep_parents = [] 384 | self.control_dep_children = [] 385 | 386 | def set_control_dependency(self, extremity, label): 387 | self.control_dep_children.append(Dependence('control dependency', extremity, label)) 388 | try: 389 | extremity.control_dep_parents.append(Dependence('control dependency', self, label)) 390 | except AttributeError as e: 391 | logging.debug('Unable to build a CF to go up the tree: %s', e) 392 | 393 | def remove_control_dependency(self, extremity): 394 | for i, _ in enumerate(self.control_dep_children): 395 | elt = self.control_dep_children[i] 396 | if elt.extremity.id == extremity.id: 397 | del self.control_dep_children[i] 398 | try: 399 | del extremity.control_dep_parents[i] 400 | except AttributeError as e: 401 | logging.debug('No CF going up the tree to delete: %s', e) 402 | 403 | 404 | class ReturnStatement(Statement, Value): 405 | """ ReturnStatement Node. It is a Statement that also has the attributes of a Value. """ 406 | 407 | def __init__(self, name, parent): 408 | Statement.__init__(self, name, parent) 409 | Value.__init__(self) 410 | 411 | 412 | class Function: 413 | """ To store function related information. """ 414 | 415 | def __init__(self): 416 | self.fun_name = None 417 | self.fun_params = [] 418 | self.fun_return = [] 419 | self.retraverse = False # Indicates if we are traversing a given node again 420 | self.called = False 421 | 422 | def set_fun_name(self, fun_name): 423 | self.fun_name = fun_name 424 | fun_name.set_fun(self) # Identifier fun_name has a handler to the function declaration self 425 | 426 | def add_fun_param(self, fun_param): 427 | self.fun_params.append(fun_param) 428 | 429 | def add_fun_return(self, fun_return): 430 | # if fun_return.id not in [el.id for el in self.fun_return]: # Avoids duplicates 431 | # Duplicates are okay, because we only consider the last return value from the list 432 | return_id_list = [el.id for el in self.fun_return] 433 | if not return_id_list: 434 | self.fun_return.append(fun_return) 435 | elif fun_return.id != return_id_list[-1]: # Avoids duplicates if already considered one 436 | self.fun_return.append(fun_return) 437 | 438 | def set_retraverse(self): 439 | self.retraverse = True 440 | 441 | def call_function(self): 442 | self.called = True 443 | 444 | 445 | class FunctionDeclaration(Statement, Function): 446 | """ FunctionDeclaration Node. It is a Statement that also has the attributes of a Function. """ 447 | 448 | def __init__(self, name, parent): 449 | Statement.__init__(self, name, parent) 450 | Function.__init__(self) 451 | 452 | 453 | class FunctionExpression(Node, Function): 454 | """ FunctionExpression and ArrowFunctionExpression Nodes. Have the attributes of a Function. """ 455 | 456 | def __init__(self, name, parent): 457 | Node.__init__(self, name, parent) 458 | Function.__init__(self) 459 | self.fun_intern_name = None 460 | 461 | def set_fun_intern_name(self, fun_intern_name): 462 | self.fun_intern_name = fun_intern_name # Name used if FunExpr referenced inside itself 463 | fun_intern_name.set_fun(self) # fun_intern_name has a handler to the function declaration 464 | -------------------------------------------------------------------------------- /src/parser.js: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 Aurore Fass 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU Affero General Public License as published 5 | // by the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU Affero General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU Affero General Public License 14 | // along with this program. If not, see . 15 | 16 | 17 | // Conversion of a JS file into its Esprima AST. 18 | 19 | 20 | module.exports = { 21 | js2ast: js2ast, 22 | }; 23 | 24 | 25 | var esprima = require("esprima"); 26 | var es = require("escodegen"); 27 | var fs = require("fs"); 28 | var process = require("process"); 29 | 30 | 31 | /** 32 | * Extraction of the AST of an input JS file using Esprima. 33 | * 34 | * @param js 35 | * @param json_path 36 | * @returns {*} 37 | */ 38 | function js2ast(js, json_path) { 39 | var text = fs.readFileSync(js).toString('utf-8'); 40 | try { 41 | var ast = esprima.parseModule(text, { 42 | range: true, 43 | loc: true, 44 | tokens: true, 45 | tolerant: true, 46 | comment: true 47 | }); 48 | } catch(e) { 49 | console.error(js, e); 50 | process.exit(1); 51 | } 52 | 53 | // Attaching comments is a separate step for Escodegen 54 | ast = es.attachComments(ast, ast.comments, ast.tokens); 55 | 56 | fs.writeFile(json_path, JSON.stringify(ast), function (err) { 57 | if (err) { 58 | console.error(err); 59 | } 60 | }); 61 | 62 | return ast; 63 | } 64 | 65 | js2ast(process.argv[2], process.argv[3]); 66 | -------------------------------------------------------------------------------- /src/pointer_analysis.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021 Aurore Fass 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU Affero General Public License as published 5 | # by the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU Affero General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Affero General Public License 14 | # along with this program. If not, see . 15 | 16 | 17 | """ 18 | Pointer analysis; mapping a variable to where its value is defined. 19 | """ 20 | 21 | import logging 22 | 23 | import js_operators 24 | from value_filters import get_node_computed_value, display_values 25 | import node as _node 26 | 27 | 28 | """ 29 | In the following and if not stated otherwise, 30 | - node: Node 31 | Current node. 32 | - identifiers: list 33 | List of Identifier nodes whose values we aim at computing. 34 | - operator: None or str (e.g., '+='). 35 | """ 36 | 37 | 38 | def get_node_path(begin_node, destination_node, path): 39 | """ 40 | Find the path between begin_node and destination_node. 41 | ------- 42 | Parameters: 43 | - begin_node: Node 44 | Entry point, origin. 45 | - destination_node: Node 46 | Descendant of begin_node. Destination point. 47 | - path: list 48 | Path between begin_node and destination_node. 49 | Ex: [0, 0, 1] <=> begin_node.children[0].children[0].children[1] = destination_node. 50 | """ 51 | 52 | if begin_node.id == destination_node.id: 53 | return True 54 | 55 | for i, _ in enumerate(begin_node.children): 56 | path.append(i) # Child number i 57 | found = get_node_path(begin_node.children[i], destination_node, path) 58 | if found: 59 | return True 60 | del path[-1] 61 | return False 62 | 63 | 64 | def find_node(var, begin_node, path): 65 | """ Find the node whose path from begin_node is given. """ 66 | 67 | logging.debug('Trying to find the node symmetric from %s using the following path %s from %s', 68 | var.name, path, begin_node.name) 69 | while path: 70 | child_nb = path.pop(0) 71 | try: 72 | begin_node = begin_node.children[child_nb] 73 | except IndexError: # Case Asymmetric mapping, e.g., Array or Object mapped to an Identifier 74 | return begin_node, None 75 | 76 | if not path: # begin_node is already the node we are looking for 77 | return begin_node, None 78 | 79 | # Case Asymmetric mapping, e.g., Identifier mapped to an Array or else 80 | logging.debug('Asymmetric mapping case') 81 | if begin_node.name in ('ArrayExpression', 'ObjectExpression', 'ObjectPattern', 'NewExpression'): 82 | value = begin_node 83 | logging.debug('The value corresponds to node %s', value.name) 84 | return None, value 85 | 86 | return begin_node, None 87 | 88 | 89 | def get_member_expression(node): 90 | """ Returns: 91 | - if a MemberExpression node ascendant was found; 92 | - the furthest MemberExpression ascendant (if True) or node. 93 | - if we are in a window.node or this.node situation. """ 94 | 95 | if node.parent.name != 'MemberExpression': 96 | return False, node, False 97 | 98 | while node.parent.name == 'MemberExpression': 99 | if node.parent.children[0].name == 'ThisExpression'\ 100 | or get_node_computed_value(node.parent.children[0]) in _node.GLOBAL_VAR: 101 | return False, node, True 102 | node = node.parent 103 | return True, node, False 104 | 105 | 106 | def map_var2value(node, identifiers, operator=None): 107 | """ 108 | Map identifier nodes to their corresponding Literal/Identifier values. 109 | 110 | ------- 111 | Parameters: 112 | - node: Node 113 | Entry point, either a VariableDeclaration or AssignmentExpression node. 114 | Therefore: node.children[0] => Identifier = considered variable; 115 | node.children[1] => Identifier/Literal = corresponding value 116 | - identifiers: list 117 | List of Identifier nodes to map to their values. 118 | 119 | Trick: Symmetry between AST left-hand side (declaration) and right-hand side (value). 120 | """ 121 | 122 | if node.name != 'VariableDeclarator' and node.name != 'AssignmentExpression' \ 123 | and node.name != 'Property': 124 | # Could be called on other Nodes because of assignment_expr_df which calculates DD on 125 | # right-hand side elements which may not be variable declarations/assignments anymore 126 | return 127 | 128 | var = node.children[0] 129 | init = node.children[1] 130 | 131 | for decl in identifiers: 132 | # Compute the value for each decl, as it might have changed 133 | logging.debug('Computing a value for the variable %s with id %s', 134 | decl.attributes['name'], decl.id) 135 | 136 | decl.set_update_value(True) # Will be updated when printed in display_temp 137 | member_expr, decl, this_window = get_member_expression(decl) 138 | 139 | path = list() 140 | get_node_path(var, decl, path) 141 | if this_window: 142 | path.pop() # We jump over the MemberExpression parent to keep the symmetry 143 | 144 | if isinstance(init, _node.Identifier) and isinstance(init.value, _node.Node): 145 | try: 146 | logging.debug('The variable %s was initialized with the Identifier %s which already' 147 | ' has a value', decl.attributes['name'], init.attributes['name']) 148 | except KeyError: 149 | logging.debug('The variable %s was initialized with the Identifier %s which already' 150 | ' has a value', decl.name, init.name) 151 | value_node, value = find_node(var, init.value, path) 152 | else: 153 | if isinstance(decl, _node.Identifier): 154 | logging.debug('The variable %s was not initialized with an Identifier or ' 155 | 'it does not already have a value', decl.attributes['name']) 156 | else: 157 | logging.debug('The %s %s was not initialized with an Identifier or ' 158 | 'it does not already have a value', decl.name, decl.attributes) 159 | value_node, value = find_node(var, init, path) 160 | if value_node is not None: 161 | logging.debug('Got the node %s', value_node.name) 162 | 163 | if value is None: 164 | if isinstance(decl, _node.Identifier): 165 | logging.debug('Calculating the value of the variable %s', decl.attributes['name']) 166 | else: 167 | logging.debug('Calculating the value') 168 | if operator is None: 169 | logging.debug('Fetching the value') 170 | # We compute the value ourselves 171 | value = get_node_computed_value(value_node, initial_node=decl) 172 | if isinstance(decl, _node.Identifier): 173 | decl.set_code(node) # Add code 174 | 175 | else: 176 | logging.debug('Found the %s operator, computing the value ourselves', operator) 177 | # We compute the value ourselves: decl operator value_node 178 | value = js_operators.compute_operators(operator, decl, value_node, 179 | initial_node=decl) 180 | if isinstance(decl, _node.Identifier): 181 | decl.set_code(node) # Add code 182 | 183 | else: 184 | decl.set_code(node) # Add code 185 | 186 | if not member_expr: # Standard case, assign the value to the Identifier node 187 | logging.debug('Assigning the value %s to %s', value, decl.attributes['name']) 188 | decl.set_value(value) 189 | if isinstance(value_node, _node.FunctionExpression): 190 | fun_name = decl 191 | if value_node.fun_intern_name is not None: 192 | logging.debug('The variable %s refers to the (Arrow)FunctionExpresion %s', 193 | fun_name.attributes['name'], 194 | value_node.fun_intern_name.attributes['name']) 195 | else: 196 | logging.debug('The variable %s refers to an anonymous (Arrow)FunctionExpresion', 197 | fun_name.attributes['name']) 198 | value_node.set_fun_name(fun_name) 199 | else: 200 | display_values(decl) # Displays values 201 | else: # MemberExpression case 202 | logging.debug('MemberExpression case') 203 | literal_value = update_member_expression(decl, initial_node=decl) 204 | if isinstance(literal_value, _node.Value): # Everything is fine, can store value 205 | logging.debug('The object was defined, set the value of its property') 206 | literal_value.set_value(value) # Modifies value of the node referencing the MemExpr 207 | literal_value.set_provenance_rec(value_node) # Updates provenance 208 | display_values(literal_value) # Displays values 209 | else: # The object is probably a built-in object therefore no handle to get its prop 210 | logging.debug('The object was not defined, stored its property and set its value') 211 | obj, all_prop = define_obj_properties(decl, value, initial_node=decl) 212 | obj.set_value(all_prop) 213 | obj.set_provenance_rec(value_node) # Updates provenance 214 | display_values(obj) 215 | 216 | 217 | def compute_update_expression(node, identifier): 218 | """ Evaluates an UpdateExpression node. """ 219 | 220 | identifier.set_update_value(True) # Will be updated when printed in display_temp 221 | operator = node.attributes['operator'] 222 | value = js_operators.compute_operators(operator, identifier, 0) 223 | identifier.set_value(value) 224 | identifier.set_code(node.parent) 225 | 226 | 227 | def update_member_expression(member_expression_node, initial_node): 228 | """ If a MemberExpression is modified (i.e., left-hand side of an assignment), 229 | modifies the value of the node referencing the MemberExpression. """ 230 | 231 | literal_value = js_operators.compute_member_expression(member_expression_node, 232 | initial_node=initial_node, compute=False) 233 | return literal_value 234 | 235 | 236 | def search_properties(node, tab): 237 | """ Searches the Identifier/Literal nodes properties of a MemberExpression node. """ 238 | 239 | if node.name in ('Identifier', 'Literal'): 240 | if get_node_computed_value(node) not in _node.GLOBAL_VAR: # do nothing if window &co 241 | tab.append(node) # store left member as not window &co 242 | 243 | for child in node.children: 244 | search_properties(child, tab) 245 | 246 | 247 | def define_obj_properties(member_expression_node, value, initial_node): 248 | """ Defines the properties of a built-in object. Returns the object + its properties. """ 249 | 250 | properties = [] 251 | search_properties(member_expression_node, properties) # Got all prop 252 | 253 | obj = properties[0] 254 | obj_init = get_node_computed_value(obj, initial_node=initial_node) 255 | # The obj may already have some properties 256 | properties = properties[1:] 257 | properties_value = [get_node_computed_value(prop, 258 | initial_node=initial_node) for prop in properties] 259 | 260 | # Good for debugging to see dict content, but cannot be used as loses link to variables 261 | # if isinstance(value, _node.Node): 262 | # if value.name in ('ObjectExpression', 'ObjectPattern'): 263 | # value = js_operators.compute_object_expr(value) 264 | 265 | if isinstance(obj_init, dict): # the obj already have properties 266 | all_prop = obj_init # initialize obj with its existing properties 267 | elif isinstance(obj_init, str): # the obj was previously defined with value obj_init 268 | all_prop = {obj_init: {}} # store its previous value as a property to keep it 269 | else: 270 | all_prop = {} # initialize with empty dict 271 | previous_prop = all_prop 272 | for i in range(len(properties_value) - 1): 273 | prop = properties_value[i] 274 | if prop not in previous_prop or not isinstance(previous_prop[prop], dict): 275 | previous_prop[prop] = {} # previous_prop[prop] does not already exist 276 | previous_prop = previous_prop[prop] 277 | previous_prop[properties_value[-1]] = value # prop0.prop1.prop2... = value 278 | 279 | return obj, all_prop 280 | -------------------------------------------------------------------------------- /src/scope.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021 Aurore Fass 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU Affero General Public License as published 5 | # by the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU Affero General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Affero General Public License 14 | # along with this program. If not, see . 15 | 16 | 17 | """ 18 | Definition of class Scope to handle JS scoping rules. 19 | """ 20 | 21 | import copy 22 | 23 | 24 | class Scope: 25 | """ To apply JS scoping rules. """ 26 | 27 | def __init__(self, name=''): 28 | self.name = name 29 | self.var_list = [] 30 | self.var_if2_list = [] # Specific to if constructs with 2 possible variables at the end 31 | self.unknown_var = set() # Unknown variable in a given scope 32 | self.function = None 33 | self.bloc = False # Indicates if we are in a block statement 34 | self.need_to_recompute_var_list = True 35 | self.id_name_list = set() 36 | 37 | def set_name(self, name): 38 | self.name = name 39 | 40 | def set_var_list(self, var_list): 41 | self.var_list = var_list 42 | self.need_to_recompute_var_list = True 43 | 44 | def set_var_if2_list(self, var_if2_list): 45 | self.var_if2_list = var_if2_list 46 | 47 | def set_unknown_var(self, unknown_var): 48 | self.unknown_var = unknown_var 49 | 50 | def set_function(self, function): 51 | self.function = function 52 | 53 | def add_var(self, identifier_node): 54 | self.var_list.append(identifier_node) 55 | self.need_to_recompute_var_list = True 56 | self.var_if2_list.append(None) 57 | 58 | def add_unknown_var(self, unknown): 59 | self.unknown_var.add(unknown) # Set avoids duplicates 60 | 61 | def remove_unknown_var(self, unknown): 62 | self.unknown_var.remove(unknown) 63 | 64 | def update_var(self, index, identifier_node): 65 | self.var_list[index] = identifier_node 66 | self.need_to_recompute_var_list = True 67 | self.var_if2_list[index] = None 68 | 69 | def update_var_if2(self, index, identifier_node_list): 70 | self.var_if2_list[index] = identifier_node_list 71 | 72 | def add_var_if2(self, index, identifier_node): 73 | if not isinstance(self.var_if2_list[index], list): 74 | self.var_if2_list[index] = [] 75 | self.var_if2_list[index].append(identifier_node) 76 | 77 | def is_equal(self, var_list2): 78 | if self.var_list == var_list2.var_list and self.var_if2_list == var_list2.var_if2_list: 79 | return True 80 | return False 81 | 82 | def copy_scope(self): 83 | scope = Scope() 84 | scope.set_name(copy.copy(self.name)) 85 | scope.set_var_list(copy.copy(self.var_list)) 86 | scope.set_var_if2_list(copy.copy(self.var_if2_list)) 87 | scope.set_unknown_var(copy.copy(self.unknown_var)) 88 | scope.set_function(copy.copy(self.function)) 89 | return scope 90 | 91 | def get_pos_identifier(self, identifier_node): 92 | tmp_list = None 93 | if self.need_to_recompute_var_list: 94 | tmp_list = [elt.attributes['name'] for elt in self.var_list] 95 | self.id_name_list = set(tmp_list) 96 | self.need_to_recompute_var_list = False 97 | var_name = identifier_node.attributes['name'] 98 | if var_name in self.id_name_list: 99 | if tmp_list is None: 100 | tmp_list = [elt.attributes['name'] for elt in self.var_list] 101 | return tmp_list.index(var_name) # Position of identifier_node in var_list 102 | return None # None if it is not in the list 103 | 104 | def set_in_bloc(self, bloc): 105 | self.bloc = bloc 106 | -------------------------------------------------------------------------------- /src/utility_df.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021 Aurore Fass 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU Affero General Public License as published 5 | # by the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU Affero General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Affero General Public License 14 | # along with this program. If not, see . 15 | 16 | 17 | """ 18 | Utility file, stores shared information. 19 | """ 20 | 21 | import sys 22 | import resource 23 | import timeit 24 | import logging 25 | import signal 26 | import traceback 27 | 28 | sys.setrecursionlimit(100000) 29 | 30 | 31 | TEST = False 32 | 33 | if TEST: # To test, e.g., the examples 34 | PDG_EXCEPT = True # To print the exceptions encountered while building the PDG 35 | LIMIT_SIZE = 10000 # To avoid list/str values with over 10,000 characters 36 | LIMIT_RETRAVERSE = 1 # If function called on itself, then max times to avoid infinite recursion 37 | LIMIT_LOOP = 5 # If iterating through a loop, then max times to avoid infinite loops 38 | DISPLAY_VAR = True # To display variable values 39 | CHECK_JSON = True # Builds the JS code from the AST, to check for possible bugs in the AST 40 | 41 | NUM_WORKERS = 1 42 | 43 | else: # To run with multiprocessing 44 | PDG_EXCEPT = False # To ignore (pass) the exceptions encountered while building the PDG 45 | LIMIT_SIZE = 10000 # To avoid list/str values with over 10,000 characters 46 | LIMIT_RETRAVERSE = 1 # If function called on itself, then max times to avoid infinite recursion 47 | LIMIT_LOOP = 1 # If iterating through a loop, then max times to avoid infinite loops 48 | DISPLAY_VAR = False # To not display variable values 49 | CHECK_JSON = False # To not build the JS code from the AST 50 | 51 | NUM_WORKERS = 1 # CHANGE THIS ONE 52 | 53 | 54 | class UpperThresholdFilter(logging.Filter): 55 | """ 56 | This allows us to set an upper threshold for the log levels since the setLevel method only 57 | sets a lower one 58 | """ 59 | 60 | def __init__(self, threshold, *args, **kwargs): 61 | self._threshold = threshold 62 | super(UpperThresholdFilter, self).__init__(*args, **kwargs) 63 | 64 | def filter(self, rec): 65 | return rec.levelno <= self._threshold 66 | 67 | 68 | logging.basicConfig(format='%(levelname)s: %(filename)s: %(message)s', level=logging.CRITICAL) 69 | # logging.basicConfig(filename='pdg.log', format='%(levelname)s: %(filename)s: %(message)s', 70 | # level=logging.DEBUG) 71 | # LOGGER = logging.getLogger() 72 | # LOGGER.addFilter(UpperThresholdFilter(logging.CRITICAL)) 73 | 74 | 75 | def micro_benchmark(message, elapsed_time): 76 | """ Micro benchmarks. """ 77 | logging.info('%s %s%s', message, str(elapsed_time), 's') 78 | print('CURRENT STATE %s %s%s' % (message, str(elapsed_time), 's')) 79 | return timeit.default_timer() 80 | 81 | 82 | class Timeout: 83 | """ Timeout class using ALARM signal. """ 84 | 85 | class Timeout(Exception): 86 | """ Timeout class throwing an exception. """ 87 | 88 | def __init__(self, sec): 89 | self.sec = sec 90 | 91 | def __enter__(self): 92 | signal.signal(signal.SIGALRM, self.raise_timeout) 93 | signal.alarm(self.sec) 94 | 95 | def __exit__(self, *args): 96 | signal.alarm(0) # disable alarm 97 | 98 | def raise_timeout(self, *args): 99 | traceback.print_stack(limit=100) 100 | raise Timeout.Timeout() 101 | 102 | 103 | def limit_memory(maxsize): 104 | """ Limiting the memory usage to maxsize (in bytes), soft limit. """ 105 | 106 | soft, hard = resource.getrlimit(resource.RLIMIT_AS) 107 | resource.setrlimit(resource.RLIMIT_AS, (maxsize, hard)) 108 | -------------------------------------------------------------------------------- /src/value_filters.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021 Aurore Fass 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU Affero General Public License as published 5 | # by the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU Affero General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Affero General Public License 14 | # along with this program. If not, see . 15 | 16 | 17 | """ Prints variables with their corresponding value. And logs whether an insecure API was used. """ 18 | 19 | import logging 20 | import node as _node 21 | from js_operators import get_node_computed_value, get_node_value 22 | import utility_df 23 | 24 | INSECURE = ['document.write'] 25 | DISPLAY_VAR = utility_df.DISPLAY_VAR # To display the variables' value or not 26 | 27 | 28 | def is_insecure_there(value): 29 | """ Checks if value is part of an insecure API. """ 30 | 31 | for insecure in INSECURE: 32 | if insecure in value: 33 | logging.debug('Found a call to %s', insecure) 34 | 35 | 36 | def display_values(var, keep_none=True, check_insecure=True, recompute=False): 37 | """ Print var = its value and checks whether the value is part of an insecure API. """ 38 | 39 | if not DISPLAY_VAR: # We do not want the values printed during large-scale analyses 40 | return 41 | 42 | if recompute: # If we store ALL value sometimes we need to recompute them as could have changed 43 | # Currently not executed, check if set_value in get_node_computed_value 44 | value = get_node_value(var) 45 | var.set_value(value) 46 | else: 47 | value = var.value # We store value so as not to compute it AGAIN 48 | if isinstance(value, _node.Node) or value is None: # Only if necessary 49 | value = get_node_computed_value(var, keep_none=keep_none) # Gets variable value 50 | 51 | if isinstance(var, _node.Identifier): 52 | variable = get_node_value(var) 53 | print('\t' + variable + ' = ' + str(value)) # Prints variable = value 54 | 55 | elif var.name in _node.CALL_EXPR + ['ReturnStatement']: 56 | print('\t' + var.name + ' = ' + str(value)) # Prints variable = value) 57 | 58 | if isinstance(value, _node.Node): 59 | print('\t' + value.name, value.attributes, value.id) 60 | 61 | elif isinstance(value, str) and check_insecure: 62 | is_insecure_there(value) # Checks for usage of insecure APIs 63 | --------------------------------------------------------------------------------