├── LICENSE
├── README.md
├── dream.py
├── dream
├── CTransformer.py
├── ControlFlowGraph.py
├── ControlFlowTree.py
├── DataFlowAnalysis.py
├── RuleCompiler.py
├── __init__.py
├── config.py
├── enums.py
├── graph_visitors.py
├── ir
│ ├── __init__.py
│ ├── ast.py
│ ├── expressions.py
│ └── instructions.py
├── json_parser.py
├── logic.py
├── prolog
│ ├── builtin_rules.pl
│ ├── imports.json
│ ├── named_constants_rules.pl
│ ├── predicates.pl
│ ├── queries
│ ├── rules.pl
│ └── rules_src.tr
├── theorem_prover
│ ├── __init__.py
│ └── z3_transformer.py
└── transformations
│ ├── __init__.py
│ └── named_constants.py
└── requirements.txt
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 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 General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # DREAM
2 |
3 | ## Disclaimer
4 |
5 | This code is not supported by [Code Intelligence](https://www.code-intelligence.com). However, many of the techniques are now part of [CI Fuzz](https://www.code-intelligence.com/product-tour) to support our structure-aware fuzzing, grammar fuzzing, and structure detection.
6 |
7 | The results have been published at [NDSS 2015](https://net.cs.uni-bonn.de/fileadmin/ag/martini/Staff/yakdan/dream_ndss2015.pdf).
8 |
9 | ## Introduction
10 |
11 | The current implementation of DREAM is divided into two components:
12 |
13 | 1. **Part 1** is a C++ IDA plugin and performs the following analysis:
14 |
15 | - _IR Lifter_ lifts x86 code into DREAM IR.
16 | - _SSA Transformer_ transforms the Static Single Assignment (SSA) form.
17 | - _Data Flow Analysis_: this includes
18 | - Condition code translation: Transforming the flags used in conditional jump instructions into corresponding high-level conditions
19 | - Expression propagation: propagates definitions to their using instructions. Here, a few heuristics are used to
20 | avoid producing overly complex expressions
21 | - Dead code elimination: It removes dead code.
22 | - _Type Analysis_ recovers elementary types of recovered variables in the function. The implementation is based on
23 | concepts presented in the TIE paper.
24 | - _SSA back translation_ transforms the code out of SSA form. This includes removing the phi functions by representing
25 | their semantics using normal IR code.
26 |
27 | The analysis results of the first part can be exported into a JSON file (check the description of the format of the JSON file).
28 |
29 | 2. **Part 2** is python program that parses the exported JSON file and then perform the following analysis:
30 | - _Control-Flow Structuring_ to recover the control structure of the function by analyzing the control flow graph
31 | in order to represent the control flow using high-level control constructs, e.g., _if-then_ and _while_ statements.
32 | - _Readability improvements_ include several optimizations to improve the readability of the decompiled code.
33 |
34 | ## Part 1
35 |
36 | This gives an overview about the first part of the decompiler.
37 |
38 | ### Installation Requirements
39 |
40 | The code is provided as Visual Studio 2010 Solution and has the following requirements:
41 |
42 | - IDA 6.4 SDK.
43 | - The Boost Graph Library (version 1.55.0) is used for graph algorithms.
44 | - Windows SDK
45 |
46 | The configurations of the solution are taken from [this tutorial](http://www.openrce.org/reference_library/files/ida/idapw.pdf).
47 | The project is configured so that the resulted binary is stored in IDA's plugins folder.
48 | You might need to adjust the project configurations so that the paths points to where the dependencies are installed
49 | on your systems. Currently, the plugin is used in a Windows XP virtual machine.
50 |
51 | ### Usage
52 |
53 | To run the plugin use the key combination `Ctrl + D`. Then a dialog box with several options will pop up.
54 | There, you can choose to export (as a JSON file) a single function or all the functions in the binary.
55 | In both cases you need to specify the folder where the exported function(s) will be stored.
56 | For each function, the corresponding JSON file is named `.json`.
57 |
58 | ###JSON Format
59 | The result of the first analysis is exported in a JSON file, which represents a binary function.
60 |
61 | ```javascript
62 | {
63 | "function_name": // function name
64 | "arguments": // a list of all expressions representing the function arguments
65 | "cfg": // an object representing the cotrol flow graph of the function
66 | }
67 | ```
68 |
69 | #### Control Flow Graph
70 |
71 | This represents the control flow graph of a function and has the following format:
72 |
73 | ```javascript
74 | {
75 | "nodes": // the list of the CFG's nodes
76 | "conditions_map": // a map from edge labeles to the corresponding condition expressions
77 | }
78 | ```
79 |
80 | #### Node
81 |
82 | A node represents a basic block and has the following format:
83 |
84 | ```javascript
85 | {
86 | "id": // a unique number to identify the node
87 | "type": // the type of the node and can be either "Conditional" and "Code" (see the NDSS'15 paper)
88 | "successors": // a list of edges to successor nodes
89 | "instructions": // a list of instructions contained in the node. Clearly, this field is only available in code nodes
90 | }
91 | ```
92 |
93 | #### Successor Edge
94 |
95 | An Edge represents a possible transition of control between two nodes and has the following format:
96 |
97 | ```javascript
98 | {
99 | "id": // the identifier of the successor node. Note the source node is implicitly defined as the Node object containing the endge
100 | "tag": // the label associated of edge. It represent the condition based on which this edge is executed after the source node.
101 | }
102 | ```
103 |
104 | #### Instruction
105 |
106 | An instruction entry represents a statement in DREAM IR and has the following format:
107 |
108 | ```javascript
109 | {
110 | "instruction_type": // The type of statement
111 | "...": // remaining fields depends on the statement type (check the json parser).
112 | }
113 | ```
114 |
115 | #### Expression
116 |
117 | An expression entry represents a expression in DREAM IR and has the following format:
118 |
119 | ```javascript
120 | {
121 | "expression_type": // The type of expression
122 | "...": // remaining fields depends on the expression type (check the json parser).
123 | }
124 | ```
125 |
126 | ## Part 2
127 |
128 | This gives an overview about the second part of the decompiler.
129 |
130 | ### Installation Requirements
131 |
132 | - Some of the dependencies are pip-installable
133 |
134 | ```bash
135 | pip install -r requirements.txt
136 | ```
137 |
138 | - install z3 with Python bindings. Several installations options are possible and explained
139 | ```bash
140 | git clone https://github.com/Z3Prover/z3.git
141 | cd z3
142 | python scripts/mk_make.py --python
143 | cd build
144 | make
145 | sudo make install
146 | ```
147 | - Install [SWI-Prolog](http://www.swi-prolog.org) and
148 | the python library [pyswip](https://github.com/yuce/pyswip) (version 0.2.3).
149 |
150 | Installing SWI-Prolog is available as a package for most major Linux distributions.
151 | Installation steps are explained [here](http://www.swi-prolog.org/build/LinuxDistro.txt).
152 |
153 | The pip-installable version of pyswip is 0.2.2. For this reason, it was excluded from the requirements.txt file.
154 | To install pyswip ```python setup.py install```
155 |
156 | - Install the graph_tool library. Installation steps are explained [here](https://graph-tool.skewed.de/download)
157 |
158 | ### Usage
159 |
160 | To run the decompiler, you can use the following command:
161 |
162 | ```bash
163 | python dream.py (--decompile|--compile-transformation-rules) -i -o [--json] [--split-returns]
164 | ```
165 |
166 | There are two modes available
167 |
168 | 1. **_decompile_**: in this mode a function is chosen to be decompiled. Available options for this mode are:
169 |
170 | - `-i ` specifies the input file that contains the IR of the function to be decompiled.
171 | - `-o ` specifies the output files where the decompiled code is stored.
172 | - `--json` specifies that the input file is in JSON format (as exported by the corresponding IDA plugin)
173 | - `--split-returns` this option causes return nodes (only containing return statements)
174 | with three or more incoming edges to be splitted into several nodes with with a single incoming edge.
175 | In some cases, this leads to a more readable code.
176 |
177 | 2. **_compile-transformation-rules_**: in this mode, transformation rules are compiled into prolog rules, which DREAM
178 | uses to match for the defined patters and replace those patterns as defined by the corresponding transformation rule.
179 | Available options for this mode are:
180 | _ `-i ` specifies the input file that contains the source code of the transformation rules.
181 | _ `-o ` specifies the directory where the compiled rules are stored.
182 | In this directory, two files are created by the compiler:
183 | _ `rules.pl` contains Prolog inference rules
184 | _ `queries` contains the corresponding queries that will be performed by the transformer (`dream/CTransformer.py`)
185 |
186 | The main configurations of DREAM are stored in ``dream/config.py``. Current configurations use the rules contained
187 | in ``dream/prolog``.
188 |
--------------------------------------------------------------------------------
/dream.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2011-2017 Khaled Yakdan.
2 | # All rights reserved.
3 |
4 | import sys
5 | import getopt
6 | from dream.CTransformer import CTransformer
7 | from dream.ControlFlowTree import ControlFlowTree, SequenceNode
8 | from dream.RuleCompiler import RuleCompiler
9 | from dream.ir.ast import AST
10 | from dream.json_parser import JsonGraphParser
11 |
12 |
13 | def decompile_json(in_file, out_file, split_returns=True):
14 | j_parser = JsonGraphParser()
15 | j_parser.graph_from_json(in_file)
16 |
17 | cfg = j_parser.cfg
18 | cfg.remove_empty_code_nodes()
19 |
20 | # print "structuring"
21 | cfg.function_signature = j_parser.get_function_signature()
22 | if cfg.num_vertices() == 0:
23 | ast = AST(SequenceNode(True, []), cfg.function_signature)
24 | ast.write(out_file)
25 | return
26 |
27 | cfg.merge_congruent_variables()
28 | cfg.structure(split_returns)
29 |
30 | # print "side effects"
31 | cft = ControlFlowTree(None)
32 | ast_root = cfg.vertex_properties['ast'][cfg.vertex(0)]
33 | cft.root = ast_root
34 | cft.conditions_map = cfg.conditions_map
35 | cft.replace_basic_blocks_by_sequence(ast_root)
36 | cft.combine_sequence_nodes_with_sequence_children(ast_root)
37 | ast = AST(ast_root, cfg.function_signature)
38 |
39 | c_transformer = CTransformer()
40 | c_transformer.set_ast(ast)
41 | c_transformer.remove_side_effects(cft.conditions_map)
42 | cft.replace_logic_symbols_by_conditions(ast_root)
43 | c_transformer.apply_transformations()
44 | ast.write(out_file)
45 |
46 |
47 | def compile_transformation_rules(in_file, out_dir):
48 | r_compiler = RuleCompiler(in_file, out_dir)
49 | r_compiler.compile()
50 |
51 |
52 | def print_help_message():
53 | print 'dream.py (--decompile|--compile-transformation-rules) ' \
54 | '-i -o [--json] [--split-returns]'
55 |
56 |
57 | def main():
58 | try:
59 | opts, args = getopt.getopt(sys.argv[1:], 'i:o:h',
60 | ['json', 'split-returns', 'decompile', 'compile-transformation-rules', 'help'])
61 | except getopt.GetoptError:
62 | print_help_message()
63 | sys.exit(2)
64 |
65 | opts = dict(opts)
66 |
67 | if '-h' in opts or '--help' in opts:
68 | print_help_message()
69 | exit(0)
70 |
71 | assert '-i' in opts and '-o' in opts
72 | in_file, out_path = opts['-i'], opts['-o']
73 | if '--decompile' in opts:
74 | split_returns = '--split-returns' in opts
75 | if '--json' in opts:
76 | decompile_json(in_file, out_path, split_returns)
77 | elif '--compile-transformation-rules' in opts:
78 | compile_transformation_rules(in_file, out_path)
79 |
80 |
81 | if __name__ == '__main__':
82 | main()
83 |
--------------------------------------------------------------------------------
/dream/DataFlowAnalysis.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2011-2017 Khaled Yakdan.
2 | # All rights reserved.
3 |
4 | from graph_tool.search import dfs_search
5 | from sympy.core.symbol import Symbol
6 | from dream.ir.expressions import LocalVariable, Call
7 | from dream.ir.instructions import Instruction, Assignment
8 | from dream.enums import NodeType
9 | from dream.graph_visitors import DepthFirstSearchVisitor
10 |
11 |
12 | class DataFlowInfo:
13 | def __init__(self, live_in, live_out, reach_in, reach_out):
14 | self.live_in = live_in
15 | self.live_out = live_out
16 | self.reach_in = reach_in
17 | self.reach_out = reach_out
18 | self.id_stmt_map = {}
19 |
20 |
21 | class DataFlowAnalysis:
22 | def __init__(self, cfg, id_stmt_map):
23 | self.cfg = cfg
24 | self.id_stmt_map = id_stmt_map
25 | self.gen_b = {}
26 | self.kill_b = {}
27 | self.in_b = {v: set() for v in self.cfg.vertices()}
28 | self.out_b = {v: set() for v in self.cfg.vertices()}
29 |
30 | self.gen_s = {stmt_id: set() for stmt_id in self.id_stmt_map}
31 | self.kill_s = {stmt_id: set() for stmt_id in self.id_stmt_map}
32 | self.in_s = {stmt_id: set() for stmt_id in self.id_stmt_map}
33 | self.out_s = {stmt_id: set() for stmt_id in self.id_stmt_map}
34 |
35 | self.defs = {}
36 | self.uses = {}
37 |
38 | def sets_changed(self, old_in, old_out):
39 | for v in self.cfg.vertices():
40 | if old_in[v] ^ self.in_b[v] or old_out[v] ^ self.out_b[v]:
41 | return True
42 | return False
43 |
44 | def compute_defs(self):
45 | for stmt_id, stmt in self.id_stmt_map.items():
46 | if isinstance(stmt, Instruction):
47 | for d in [var for var in stmt.defs() if isinstance(var, LocalVariable)]:
48 | if d not in self.defs:
49 | self.defs[d] = set()
50 | self.defs[d].add(stmt_id)
51 |
52 | def compute_uses(self):
53 | for stmt_id, stmt in self.id_stmt_map.items():
54 | used_vars = stmt.uses() if isinstance(stmt, Instruction) else stmt.elements()
55 | for u in [var for var in used_vars if isinstance(var, LocalVariable)]:
56 | if u not in self.uses:
57 | self.uses[u] = set()
58 | self.uses[u].add(stmt_id)
59 |
60 |
61 | class ReachingDefinitionsAnalysis(DataFlowAnalysis):
62 | def __init__(self, cfg, id_stmt_map):
63 | DataFlowAnalysis.__init__(self, cfg, id_stmt_map)
64 | self.defs = {}
65 |
66 | def apply(self):
67 | self.compute_defs()
68 | self.compute_gens_kills()
69 | dfs = DepthFirstSearchVisitor()
70 | dfs_search(self.cfg, self.cfg.vertex(0), dfs)
71 | done = False
72 | while not done:
73 | in_old = {n: {var for var in var_set} for (n, var_set) in self.in_b.items()}
74 | out_old = {n: {var for var in var_set} for (n, var_set) in self.out_b.items()}
75 | for v in reversed(dfs.postorder):
76 | self.in_b[v].clear()
77 | for p in v.in_neighbours():
78 | self.in_b[v].update(self.out_b[p])
79 | self.out_b[v] = self.gen_b[v] | (self.in_b[v] - self.kill_b[v])
80 | done = not self.sets_changed(in_old, out_old)
81 | self.propagate_dataflow_to_statements()
82 |
83 | def compute_gens_kills(self):
84 | for v in self.cfg.vertices():
85 | self.gen_b[v] = set()
86 | self.kill_b[v] = set()
87 | if self.cfg.vertex_properties['type'][v] == NodeType.CODE:
88 | #for stmt in self.cfg.vertex_properties['ast'][v].instructions:
89 | for stmt in self.cfg.vertex_properties['ast'][v].children:
90 | stmt_id = self.id_stmt_map.keys()[self.id_stmt_map.values().index(stmt)]
91 | if isinstance(stmt, Instruction):
92 | for d in stmt.defs():
93 | if isinstance(d, LocalVariable):
94 | self.gen_s[stmt_id] = {stmt_id}
95 | self.kill_s[stmt_id] = self.defs[d] - self.gen_s[stmt_id]
96 | self.gen_b[v] = self.gen_s[stmt_id] | (self.gen_b[v] - self.kill_s[stmt_id])
97 | self.kill_b[v].update(self.kill_s[stmt_id])
98 |
99 | def propagate_dataflow_to_statements(self):
100 | for n in self.cfg.vertices():
101 | reach_in = self.in_b[n]
102 | if self.cfg.vertex_properties['type'][n] == NodeType.CODE:
103 | #for stmt in self.cfg.vertex_properties['ast'][n].instructions:
104 | for stmt in self.cfg.vertex_properties['ast'][n].children:
105 | stmt_id = self.id_stmt_map.keys()[self.id_stmt_map.values().index(stmt)]
106 | self.in_s[stmt_id] = reach_in
107 | self.out_s[stmt_id] = self.gen_s[stmt_id] | (reach_in - self.kill_s[stmt_id])
108 | reach_in = self.out_s[stmt_id]
109 | elif self.cfg.vertex_properties['type'][n] == NodeType.CONDITIONAL:
110 | tag = self.cfg.edge_properties['tag'][self.cfg.edge(n, n.out_neighbours().next())]
111 | cond_expr = self.cfg.conditions_map[tag if isinstance(tag, Symbol) else tag.args[0]]
112 | stmt_id = self.id_stmt_map.keys()[self.id_stmt_map.values().index(cond_expr)]
113 | self.in_s[stmt_id] = self.in_b[n]
114 | self.out_s[stmt_id] = self.out_b[n]
115 | assert reach_in == self.out_b[n], "{0}: {1} != {2}".format(int(n), [int(i) for i in reach_in],
116 | [int(i) for i in self.out_b[n]])
117 |
118 | def reaching_definitions(self, of_var, at_stmt):
119 | reaching_defs = []
120 | for s in self.in_s[at_stmt]:
121 | if of_var in self.id_stmt_map[s].defs():
122 | reaching_defs.append(self.id_stmt_map[s])
123 | return reaching_defs
124 |
125 |
126 | class LivenessAnalysis(DataFlowAnalysis):
127 | def __init__(self, cfg, id_stmt_map):
128 | DataFlowAnalysis.__init__(self, cfg, id_stmt_map)
129 |
130 | def apply(self):
131 | self.compute_gens_kills()
132 | dfs = DepthFirstSearchVisitor()
133 | dfs_search(self.cfg, self.cfg.vertex(0), dfs)
134 | done = False
135 | while not done:
136 | in_old = {n: {var for var in var_set} for (n, var_set) in self.in_b.items()}
137 | out_old = {n: {var for var in var_set} for (n, var_set) in self.out_b.items()}
138 |
139 | for v in dfs.postorder:
140 | self.out_b[v].clear()
141 | for s in v.out_neighbours():
142 | self.out_b[v].update(self.in_b[s])
143 | self.in_b[v] = self.gen_b[v] | (self.out_b[v] - self.kill_b[v])
144 | done = not self.sets_changed(in_old, out_old)
145 | self.propagate_dataflow_to_statements()
146 |
147 | def compute_gens_kills(self):
148 | for v in self.cfg.vertices():
149 | self.gen_b[v] = set()
150 | self.kill_b[v] = set()
151 |
152 | if self.cfg.vertex_properties['type'][v] == NodeType.CODE:
153 | #for stmt in reversed(self.cfg.vertex_properties['ast'][v].instructions):
154 | for stmt in reversed(self.cfg.vertex_properties['ast'][v].children):
155 | stmt_id = self.id_stmt_map.keys()[self.id_stmt_map.values().index(stmt)]
156 | if isinstance(stmt, Call):
157 | defs = set()
158 | uses = {u for u in stmt.elements() if isinstance(u, LocalVariable)}
159 | else:
160 | defs = {d for d in stmt.defs() if isinstance(d, LocalVariable)}
161 | uses = {u for u in stmt.uses() if isinstance(u, LocalVariable)}
162 | self.gen_s[stmt_id] = uses
163 | self.kill_s[stmt_id] = defs
164 | self.gen_b[v] = uses | (self.gen_b[v] - defs)
165 | self.kill_b[v].update(defs)
166 |
167 | elif self.cfg.vertex_properties['type'][v] == NodeType.CONDITIONAL:
168 | tag = self.cfg.edge_properties['tag'][self.cfg.edge(v, v.out_neighbours().next())]
169 | cond_expr = self.cfg.conditions_map[tag if isinstance(tag, Symbol) else tag.args[0]]
170 | stmt_id = self.id_stmt_map.keys()[self.id_stmt_map.values().index(cond_expr)]
171 | self.gen_b[v] = {u for u in cond_expr.elements() if isinstance(u, LocalVariable)}
172 | self.gen_s[stmt_id] = {u for u in cond_expr.elements() if isinstance(u, LocalVariable)}
173 |
174 | def propagate_dataflow_to_statements(self):
175 | for n in self.cfg.vertices():
176 | if self.cfg.vertex_properties['type'][n] == NodeType.CODE:
177 | live_out = self.out_b[n]
178 | #for stmt in reversed(self.cfg.vertex_properties['ast'][n].instructions):
179 | for stmt in reversed(self.cfg.vertex_properties['ast'][n].children):
180 | stmt_id = self.id_stmt_map.keys()[self.id_stmt_map.values().index(stmt)]
181 | self.out_s[stmt_id] = live_out
182 | self.in_s[stmt_id] = self.gen_s[stmt_id] | (live_out - self.kill_s[stmt_id])
183 | live_out = self.in_s[stmt_id]
184 | assert live_out == self.in_b[n]
185 | elif self.cfg.vertex_properties['type'][n] == NodeType.CONDITIONAL:
186 | tag = self.cfg.edge_properties['tag'][self.cfg.edge(n, n.out_neighbours().next())]
187 | cond_expr = self.cfg.conditions_map[tag if isinstance(tag, Symbol) else tag.args[0]]
188 | stmt_id = self.id_stmt_map.keys()[self.id_stmt_map.values().index(cond_expr)]
189 | self.out_s[stmt_id] = self.out_b[n]
190 | self.in_s[stmt_id] = self.gen_s[stmt_id] | (self.out_b[n] - self.kill_s[stmt_id])
191 | assert self.in_s[stmt_id] == self.in_b[n], "{0}: {1} != {2}".format(int(n), [str(i) for i in self.in_s[stmt_id]],
192 | [str(i) for i in self.in_b[n]])
193 |
194 | def is_live_in(self, var, at_stmt):
195 | return var in self.in_s[at_stmt]
196 |
197 | def is_live_out(self, var, at_stmt):
198 | return var in self.out_s[at_stmt]
199 |
200 |
201 | class CongruenceAnalysis(DataFlowAnalysis):
202 | def __init__(self, cfg, id_stmt_map):
203 | DataFlowAnalysis.__init__(self, cfg, id_stmt_map)
204 | self.liveness_alg = LivenessAnalysis(cfg, id_stmt_map)
205 | self.liveness_alg.apply()
206 | self.reaching_alg = ReachingDefinitionsAnalysis(cfg, id_stmt_map)
207 | self.reaching_alg.apply()
208 | self.compute_uses()
209 | self.compute_defs()
210 | self.variables_map = self.compute_variables_map()
211 |
212 | def apply(self):
213 | found_congruences = False
214 | for stmt_id, stmt in self.id_stmt_map.items():
215 | if self.is_copy_stmt(stmt):
216 | # print 'handling: {0} -> {1}'.format(stmt_id, str(stmt))
217 | lhs_var, rhs_var = stmt.lhs_operand, stmt.rhs_operand
218 | if self.all_reaching_definitions_equal(lhs_var, self.uses[rhs_var], rhs_var)\
219 | and self.all_definitions_not_in_live_range(rhs_var, lhs_var):
220 | # print "Congruent Variables: ", lhs_var, rhs_var, lhs_var == rhs_var
221 | if not(lhs_var == rhs_var):
222 | if rhs_var == self.cfg.function_signature.return_value or rhs_var in self.cfg.function_signature.parameters:
223 | self.rename(lhs_var.name, rhs_var.name)
224 | else:
225 | self.rename(rhs_var.name, lhs_var.name)
226 | found_congruences = True
227 |
228 | if found_congruences:
229 | has_emtpy_nodes = False
230 | for v in self.cfg.vertices():
231 | if self.cfg.vertex_properties['type'][v] == NodeType.CODE:
232 | basic_block = self.cfg.vertex_properties['ast'][v]
233 | basic_block.children = [stmt for stmt in basic_block.children
234 | if not self.is_trivial_copy_stmt(stmt)]
235 | if not basic_block.children:
236 | has_emtpy_nodes = True
237 | if has_emtpy_nodes:
238 | self.cfg.remove_empty_code_nodes()
239 |
240 |
241 | def rename(self, old_name, new_name):
242 | for v in self.variables_map[old_name]:
243 | v.name = new_name
244 | self.variables_map[new_name].append(v)
245 | del self.variables_map[old_name]
246 |
247 | def all_definitions_not_in_live_range(self, var_d, of_variable):
248 | if var_d in self.defs:
249 | for d in self.defs[var_d]:
250 | if self.in_live_range(d, of_variable) and not self.is_copy_stmt_(self.id_stmt_map[d], var_d, of_variable):
251 | return False
252 | return True
253 |
254 | def in_live_range(self, stmt_id, of_variable):
255 | return self.liveness_alg.is_live_out(of_variable, stmt_id)
256 |
257 | def all_reaching_definitions_equal(self, variable, at_stmts, value):
258 | for stmt_id in at_stmts:
259 | stmt = self.id_stmt_map[stmt_id]
260 | if not self.is_copy_stmt_(stmt, variable, value) and not self.reaching_value_equals(variable, stmt_id, value):
261 | return False
262 | return True
263 |
264 | def reaching_value_equals(self, of_variable, at_stmt, value):
265 | reaching_defs = self.reaching_alg.reaching_definitions(of_variable, at_stmt)
266 | for def_stmt in reaching_defs:
267 | if not self.is_copy_stmt_(def_stmt, of_variable, value):
268 | return False
269 | return True
270 |
271 | @staticmethod
272 | def is_trivial_copy_stmt(stmt):
273 | return isinstance(stmt, Assignment) and stmt.lhs_operand == stmt.rhs_operand
274 |
275 | @staticmethod
276 | def is_copy_stmt_(stmt, lhs, rhs):
277 | return isinstance(stmt, Assignment) and stmt.lhs_operand == lhs and stmt.rhs_operand == rhs
278 |
279 | @staticmethod
280 | def is_copy_stmt(stmt):
281 | return isinstance(stmt, Assignment)\
282 | and isinstance(stmt.lhs_operand, LocalVariable) \
283 | and isinstance(stmt.rhs_operand, LocalVariable)
284 |
285 | def compute_variables_map(self):
286 | var_map = {}
287 | for stmt in self.id_stmt_map.values():
288 | vars = stmt.defs() + stmt.uses() if isinstance(stmt, Instruction) else stmt.elements()
289 | for v in [var for var in vars if isinstance(var, LocalVariable)]:
290 | if v.name not in var_map:
291 | var_map[v.name] = []
292 | var_map[v.name].append(v)
293 | return var_map
294 |
--------------------------------------------------------------------------------
/dream/RuleCompiler.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2011-2017 Khaled Yakdan.
2 | # All rights reserved.
3 |
4 | import ConfigParser
5 | import getopt
6 | import os
7 | import sys
8 | from pycparser import c_ast, c_lexer, c_parser
9 |
10 |
11 | class RuleID:
12 | INITIAL_ID = 'Id_0'
13 | PARENT_ID = 'ParentId'
14 | CHILDREN_IDs = 'ChildrenIds'
15 | TRANSFORMATION = 'Transformation'
16 |
17 | def __init__(self, initial_value=0):
18 | self.value = initial_value
19 |
20 | def next_id(self):
21 | self.value += 1
22 | return 'Id_{0}'.format(self.value)
23 |
24 |
25 | class RuleHeader:
26 | def __init__(self, func_decl):
27 | assert type(func_decl) == c_ast.FuncDecl
28 | self.name = self.rule_name(func_decl)
29 | self.params = self.param_names(func_decl)
30 | self.ret = None
31 |
32 | @staticmethod
33 | def rule_name(func_decl):
34 | return func_decl.type.declname
35 |
36 | @staticmethod
37 | def param_names(func_decl):
38 | params = [RuleID.PARENT_ID, RuleID.INITIAL_ID, RuleID.CHILDREN_IDs, RuleID.TRANSFORMATION]
39 | for arg in func_decl.args.params:
40 | #TODO consider when types are there
41 | params.append(arg.name.title())
42 | return params
43 |
44 | def __str__(self):
45 | hdr_str = self.name + '('
46 | for param in self.params:
47 | hdr_str += param + ', '
48 | return hdr_str[:-2] + ')'
49 |
50 | def query_string(self):
51 | q_str = self.name + '('
52 | for i in range(0, len(self.params)):
53 | q_str += (self.params[i] if i < 3 else 'Arg_{0}'.format(i - 2)) + ', '
54 | return q_str[:-2] + ')'
55 |
56 |
57 | class TransformationRule:
58 | SPECIAL_VARIABLE_START = '$'
59 |
60 | def __init__(self, rule_ast, rule_transformation):
61 | assert type(rule_ast) == c_ast.FuncDef, 'Transformation rules should be a valid function definition'
62 | self.rule_ast = rule_ast
63 | self.variable_ids = set()
64 | self.rule_body = ['{0} = \'{1}\''.format(RuleID.TRANSFORMATION, rule_transformation.replace("\n", ""))]
65 | self.rule_header = RuleHeader(rule_ast.decl.type)
66 | self.id_generator = RuleID()
67 |
68 | def __str__(self):
69 | rule_str = str(self.rule_header) + ' :-'
70 | for item in self.rule_body:
71 | rule_str += '\n ' + item + ','
72 | return rule_str[:-1] + '.'
73 |
74 | def compile_rule(self):
75 | self.statement_rules(self.rule_ast.body, RuleID.INITIAL_ID, RuleID.PARENT_ID)
76 | variable_ids_list = list(self.variable_ids)
77 | for i in range(0, len(variable_ids_list)):
78 | for j in range(i+1, len(variable_ids_list)):
79 | self.rule_body.append('{0} \= {1}'.format(variable_ids_list[i], variable_ids_list[j]))
80 |
81 | def statement_rules(self, stmt, stmt_id, parent_id):
82 | if type(stmt) == c_ast.Compound:
83 | if len(stmt.block_items) == 1:
84 | self.statement_rules(stmt.block_items[0], stmt_id, parent_id)
85 | else:
86 | block_id = self.next_id()
87 | self.rule_body.append('sequenceT({0}, {1}, {2})'.format(stmt_id, parent_id, block_id))
88 |
89 | items_ids = [self.next_id() for s in stmt.block_items if type(s) != c_ast.Label]
90 |
91 | if stmt_id == RuleID.INITIAL_ID:
92 | self.rule_body.append('{0} = {1}'.format(RuleID.CHILDREN_IDs, self.list_to_string(items_ids)))
93 | else:
94 | self.rule_body.append('length({0}, {1})'.format(block_id, len(items_ids)))
95 |
96 | for idx in range(0, len(stmt.block_items)):
97 | if type(stmt.block_items[idx]) == c_ast.Label:
98 | self.parse_label(stmt.block_items[idx])
99 | else:
100 | self.statement_rules(stmt.block_items[idx], items_ids[idx], stmt_id)
101 | if idx > 0:
102 | self.rule_body.append('directly_after({0}, {1}, {2})'.format(items_ids[idx], items_ids[idx-1], block_id))
103 |
104 | elif type(stmt) == c_ast.While or type(stmt) == c_ast.DoWhile:
105 | # LoopNode(LoopType.PRE_TESTED, get_ast(stmt.stmt), get_ast(stmt.cond))
106 | condition_id = self.next_id()
107 | body_id = self.next_id()
108 | loop_type = 'doWhile' if type(stmt) == c_ast.DoWhile else 'while'
109 | self.rule_body.append('loopT({0}, {1}, \'{2}\', {3}, {4})'.format(stmt_id, parent_id, loop_type, condition_id, body_id))
110 | self.statement_rules(stmt.cond, condition_id, stmt_id)
111 | self.statement_rules(stmt.stmt, body_id, stmt_id)
112 |
113 | elif type(stmt) == c_ast.For:
114 | pass
115 |
116 | elif type(stmt) == c_ast.If:
117 | #ConditionNode(stmt.cond, stmt.iftrue, stmt.iffalse)
118 | condition_id = self.next_id()
119 | true_id = self.next_id() if stmt.iftrue is not None else '\'null\''
120 | false_id = self.next_id() if stmt.iffalse is not None else '\'null\''
121 | self.rule_body.append('ifT({0}, {1}, {2}, {3}, {4})'.format(stmt_id, parent_id, condition_id, true_id, false_id))
122 | self.statement_rules(stmt.cond, condition_id, stmt_id)
123 | if stmt.iftrue is not None:
124 | self.statement_rules(stmt.iftrue, true_id, stmt_id)
125 | if stmt.iffalse is not None:
126 | self.statement_rules(stmt.iffalse, false_id, stmt_id)
127 |
128 | elif type(stmt) == c_ast.Switch:
129 | pass
130 |
131 | elif type(stmt) == c_ast.Assignment:
132 | lhs_id = self.next_id()
133 | rhs_id = self.next_id()
134 | self.rule_body.append('assignT({0}, {1}, {2}, {3})'.format(stmt_id, parent_id, lhs_id, rhs_id))
135 | self.statement_rules(stmt.lvalue, lhs_id, stmt_id)
136 | if stmt.op == c_lexer.CLexer.t_EQUALS:
137 | self.statement_rules(stmt.rvalue, rhs_id, stmt_id)
138 | else:
139 | binary_op = c_ast.BinaryOp(stmt.op[:-1], stmt.lvalue, stmt.rvalue)
140 | self.statement_rules(binary_op, rhs_id, stmt_id)
141 |
142 | elif type(stmt) == c_ast.FuncCall:
143 | args_block_id = self.next_id()
144 | self.rule_body.append('callT({0}, {1}, \'{2}\', {3})'.format(stmt_id, parent_id, stmt.name.name, args_block_id))
145 | self.rule_body.append('length({0}, {1})'.format(args_block_id, len(stmt.args.exprs)))
146 | arg_ids = [self.next_id() for arg in stmt.args.exprs]
147 | for idx in range(0, len(arg_ids)):
148 | self.statement_rules(stmt.args.exprs[idx], arg_ids[idx], stmt_id)
149 | if idx > 0:
150 | self.rule_body.append('directly_after({0}, {1}, {2})'.format(arg_ids[idx], arg_ids[idx - 1], args_block_id))
151 |
152 | elif type(stmt) == c_ast.UnaryOp:
153 | if stmt.op == '*':
154 | addr_expr_id = self.next_id()
155 | self.rule_body.append('memoryT({0}, {1}, {2})'.format(stmt_id, parent_id, addr_expr_id))
156 | self.statement_rules(stmt.expr, addr_expr_id, stmt_id)
157 | elif stmt.op in ['p++', 'p--']:
158 | assignment = c_ast.Assignment(c_lexer.CLexer.t_EQUALS,
159 | stmt.expr,
160 | c_ast.BinaryOp('+',
161 | stmt.expr,
162 | c_ast.Constant('int', 1 if stmt.op == 'p++' else -1)))
163 | self.statement_rules(assignment, stmt_id, parent_id)
164 | else:
165 | self.operation_rules(stmt_id, parent_id, [stmt.expr], stmt.op)
166 |
167 | elif type(stmt) == c_ast.BinaryOp:
168 | if stmt.op == '-':
169 | stmt.op = '+'
170 | if type(stmt.right) == c_ast.Constant and stmt.right.type in ['int', 'float']:
171 | stmt.right.value = '-' + stmt.right.value
172 | else:
173 | stmt.right = c_ast.UnaryOp('-', stmt.right)
174 |
175 | self.operation_rules(stmt_id, parent_id, [stmt.left, stmt.right], stmt.op)
176 |
177 | elif type(stmt) == c_ast.TernaryOp:
178 | cond_id = self.next_id()
179 | true_id = self.next_id()
180 | false_id = self.next_id()
181 | self.rule_body.append('ternaryOperatorT({0}, {1}, {2}, {3}, {4})'.format(stmt_id, parent_id, cond_id, true_id, false_id))
182 | self.statement_rules(stmt.cond, cond_id, stmt_id)
183 | self.statement_rules(stmt.iftrue, true_id, stmt_id)
184 | self.statement_rules(stmt.iffalse, false_id, stmt_id)
185 |
186 | elif type(stmt) == c_ast.ID:
187 | if stmt.name[0] == self.SPECIAL_VARIABLE_START:
188 | self.rule_body.append('{0} = {1}'.format(stmt.name[1:].title(), stmt_id))
189 | else:
190 | self.rule_body.append('identT({0}, {1}, {2})'.format(stmt_id, parent_id, stmt.name.title()))
191 | self.variable_ids.add(stmt.name.title())
192 |
193 | elif type(stmt) == c_ast.Constant:
194 | if stmt.type == 'int':
195 | try:
196 | val = int(stmt.value)
197 | except ValueError:
198 | val = int(stmt.value, 16)
199 | self.rule_body.append('numericLiteralT({0}, {1}, {2})'.format(stmt_id, parent_id, val))
200 | elif type(stmt) == c_ast.Break:
201 | self.rule_body.append('breakT({0}, {1})'.format(stmt_id, parent_id))
202 | elif type(stmt) == c_ast.Return:
203 | op_id = self.id_generator.next_id()
204 | self.rule_body.append('returnT({0}, {1}, {2})'.format(stmt_id, parent_id, op_id))
205 | self.statement_rules(stmt.expr, op_id, stmt_id)
206 | elif type(stmt) == c_ast.Label:
207 | self.parse_label(stmt)
208 | else:
209 | assert False, "unrecognized stmt: {0}\n".format(type(stmt))
210 |
211 | def operation_rules(self, stmt_id, parent_id, arguments, operation_name):
212 | args_block_id = self.next_id()
213 | self.rule_body.append('operationT({0}, {1}, {2}, \'{3}\')'.format(stmt_id, parent_id, args_block_id, operation_name))
214 | self.rule_body.append('length({0}, {1})'.format(args_block_id, len(arguments)))
215 | arg_ids = [self.next_id() for arg in arguments]
216 | for idx in range(0, len(arg_ids)):
217 | self.statement_rules(arguments[idx], arg_ids[idx], stmt_id)
218 | self.rule_body.append('member({0}, {1})'.format(arg_ids[idx], args_block_id))
219 | if not self.is_cumulative(operation_name) and idx > 0:
220 | self.rule_body.append('directly_after({0}, {1}, {2})'.format(arg_ids[idx], arg_ids[idx-1], args_block_id))
221 |
222 | for idx in range(0, len(arg_ids)):
223 | for idx_2 in range(idx+1, len(arg_ids)):
224 | self.rule_body.append('{0} \= {1}'.format(arg_ids[idx], arg_ids[idx_2]))
225 |
226 | @staticmethod
227 | def is_cumulative(op):
228 | return op in ['+', '*', '||', '&&', '|', '&']
229 |
230 | def next_id(self):
231 | return self.id_generator.next_id()
232 |
233 | @staticmethod
234 | def list_to_string(ids):
235 | s = '['
236 | for i in ids:
237 | s += str(i) + ', '
238 | return s[:-2] + ']'
239 |
240 | def parse_label(self, label):
241 | assert label.name == 'META' and type(label.stmt) == c_ast.FuncCall
242 | meta_call = label.stmt
243 | if meta_call.name.name == 'SAME_EXPR':
244 | meta_args = meta_call.args.exprs
245 | self.rule_body.append('same_expression({0}, {1})'.format(meta_args[0].name.title(),
246 | meta_args[1].name.title()))
247 | elif meta_call.name.name == 'INIT_VALUE':
248 | meta_args = meta_call.args.exprs
249 | self.rule_body.append('init_value({0}, {1})'.format(meta_args[0].name.title(),
250 | meta_args[1].name.title()))
251 |
252 |
253 | class RuleCompiler:
254 | def __init__(self, src_file, out_dir):
255 | self.out_dir = out_dir
256 | rules_src = ConfigParser.ConfigParser()
257 | rules_src.read(src_file)
258 | self.rules = [{
259 | 'signature': rules_src.get(rule, 'Signature'),
260 | 'transformation': rules_src.get(rule, 'Transformation')
261 | }
262 | for rule in rules_src.sections()]
263 |
264 | # self.rule_base = open(config.PROLOG['rules'], 'w')
265 | # self.query_base = open(config.PROLOG['queries'], 'w')
266 |
267 | def compile(self):
268 | with open(os.path.join(self.out_dir, 'rules.pl'), 'w') as rule_base, \
269 | open(os.path.join(self.out_dir, 'queries'), 'w') as query_base:
270 | for rule in self.rules:
271 | parser = c_parser.CParser()
272 | rule_ast = parser.parse(rule['signature'], filename='')
273 | if type(rule_ast) == c_ast.FileAST and type(rule_ast.ext[0]) == c_ast.FuncDef:
274 | signature = rule_ast.ext[0]
275 | tr = TransformationRule(signature, rule['transformation'])
276 | tr.compile_rule()
277 | rule_base.write(str(tr) + '\n'*2)
278 | query_base.write(str(tr.rule_header) + '\n')
279 |
280 |
281 | def main():
282 | try:
283 | opts, args = getopt.getopt(sys.argv[1:], 'i:o:')
284 | except getopt.GetoptError:
285 | print 'compile_rule.py -i -o '
286 | sys.exit(2)
287 |
288 | opts = dict(opts)
289 | assert '-i' in opts
290 | in_file = opts['-i']
291 |
292 | out_dir = opts['-o'] if '-o' in opts else os.getcwd()
293 |
294 | r_compiler = RuleCompiler(in_file, out_dir)
295 | r_compiler.compile()
296 |
297 | if __name__ == '__main__':
298 | main()
299 |
--------------------------------------------------------------------------------
/dream/__init__.py:
--------------------------------------------------------------------------------
1 | """ DREAM module """
2 |
3 | import logging
4 | logging.basicConfig(level=logging.INFO)
5 | logging.getLogger("dream").addHandler(logging.NullHandler())
6 |
7 |
--------------------------------------------------------------------------------
/dream/config.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2011-2017 Khaled Yakdan.
2 | # All rights reserved.
3 |
4 | import os
5 |
6 | dream_dir = os.path.dirname(__file__)
7 |
8 | PROLOG = {
9 | "predicates": os.path.join(dream_dir, "prolog/predicates.pl"),
10 | "rules": os.path.join(dream_dir, "prolog/rules.pl"),
11 | "builtin_rules": os.path.join(dream_dir, "prolog/builtin_rules.pl"),
12 | "queries": os.path.join(dream_dir, "prolog/queries"),
13 | "named_constants_rules": os.path.join(dream_dir, "prolog/named_constants_rules.pl"),
14 | }
15 |
16 | IMPORTS = os.path.join(dream_dir, "prolog/imports.json")
17 |
--------------------------------------------------------------------------------
/dream/enums.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2011-2017 Khaled Yakdan.
2 | # All rights reserved.
3 |
4 | class NodeType:
5 | CODE = 1
6 | CONDITIONAL = 2
7 | SWITCH = 3
8 |
--------------------------------------------------------------------------------
/dream/graph_visitors.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2011-2017 Khaled Yakdan.
2 | # All rights reserved.
3 |
4 | from graph_tool.search import DFSVisitor
5 |
6 |
7 | class SliceVisitor(DFSVisitor):
8 | def __init__(self, v_src, v_dst, gSlice):
9 | self.stk = []
10 | self.v_src = v_src
11 | self.v_dst = v_dst
12 | self.gSlice = gSlice
13 | self.graphToSliceNodeMap = {}
14 |
15 | def discover_vertex(self, u):
16 | self.stk.append(u)
17 | if u == self.v_dst:
18 | self.addEdgeSeries()
19 |
20 | def getSlicedNode(self, orig_node):
21 | if orig_node not in self.graphToSliceNodeMap:
22 | slice_node = self.gSlice.add_vertex()
23 | self.graphToSliceNodeMap[orig_node] = slice_node
24 | self.gSlice.vertex_properties['orig'][slice_node] = orig_node
25 | return self.graphToSliceNodeMap[orig_node]
26 |
27 | def addEdgeSeries(self):
28 | for i in range(len(self.stk)):
29 | if i == len(self.stk) - 1:
30 | break
31 | self.addEdge(self.getSlicedNode(self.stk[i]), self.getSlicedNode(self.stk[i+1]))
32 |
33 | def addEdge(self, s, d):
34 | if d not in s.out_neighbours():
35 | self.gSlice.add_edge(s, d)
36 |
37 | def examine_edge(self, e):
38 | while len(self.stk) != 0 and e.source() != self.stk[-1]:
39 | self.stk.pop()
40 | if e.target() in self.graphToSliceNodeMap and e.target() not in self.stk:
41 | self.stk.append(e.target())
42 | self.addEdgeSeries()
43 | self.stk.pop()
44 |
45 |
46 | class DepthFirstSearchVisitor(DFSVisitor):
47 | def __init__(self):
48 | self.postorder = []
49 | self.back_edges = []
50 |
51 | def finish_vertex(self, v):
52 | self.postorder.append(v)
53 |
54 | def back_edge(self, e):
55 | self.back_edges.append(e)
56 |
57 |
--------------------------------------------------------------------------------
/dream/ir/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodeIntelligenceTesting/dream/ef467aa516ae5dc5a466cad11887f517dd302c08/dream/ir/__init__.py
--------------------------------------------------------------------------------
/dream/ir/ast.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2011-2017 Khaled Yakdan.
2 | # All rights reserved.
3 |
4 | import os
5 | from dream.ControlFlowTree import CodeNode, SequenceNode, ConditionNode, BasicBlock, LoopNode, LoopType, SwitchNode, ForNode
6 | from dream.ir.expressions import Expression
7 | from dream.ir.instructions import Instruction
8 | from dream.logic import get_negated_condition
9 |
10 |
11 | class AST:
12 | def __init__(self, root_node, function_signature):
13 | self.root = root_node
14 | self.function_signature = function_signature
15 | self.global_declarations = []
16 |
17 | def write_to_file(self, path):
18 | f = open(path, 'w')
19 | self.write_node(self.root, f, 0)
20 | f.close()
21 |
22 | def write(self, file_name):
23 | dir_name = os.path.dirname(file_name)
24 | if not os.path.exists(dir_name):
25 | os.makedirs(dir_name)
26 |
27 | f = open(file_name, 'w')
28 | for decl in self.global_declarations:
29 | f.write(str(decl) + ';\n')
30 | if self.global_declarations:
31 | f.write('\n')
32 | f.write(str(self.function_signature) + '{\n')
33 | self.write_node(self.root, f, 1)
34 | f.write('}')
35 | f.close()
36 |
37 | def write_f(self, f):
38 | f.write(str(self.function_signature) + '{\n')
39 | self.write_node(self.root, f, 1)
40 | f.write('}')
41 |
42 | def write_node(self, node, f, indent, nested_if=False):
43 | assert not isinstance(node, CodeNode)
44 | assert not isinstance(node, BasicBlock)
45 | if isinstance(node, SequenceNode):
46 | for n in node.children:
47 | self.write_node(n, f, indent)
48 | elif isinstance(node, ConditionNode):
49 | condition_exp = node.condition
50 | negated_condition_exp = get_negated_condition(condition_exp)
51 | cond_str, neg_cond_str = str(condition_exp), str(negated_condition_exp)
52 | cond_str = cond_str #if cond_str[0] != '(' else cond_str[1:-1]
53 | neg_cond_str = neg_cond_str #if neg_cond_str[0] != '(' else neg_cond_str[1:-1]
54 |
55 | then_has_bracket = self.needs_brackets(node.trueChild)
56 | else_has_bracket = self.needs_brackets(node.falseChild)
57 |
58 | if not isinstance(node.trueChild, ConditionNode) and not isinstance(node.falseChild, ConditionNode):
59 | f.write('{0}if({1}){2}\n'.format(self.get_indent_str(indent) if not nested_if else '',
60 | cond_str, '{' if then_has_bracket else ''))
61 | self.write_node(node.trueChild, f, indent+1)
62 | if node.falseChild is not None:
63 | f.write('{0}{1}else{2}\n'.format(self.get_indent_str(indent),
64 | '} ' if then_has_bracket else '',
65 | '{' if else_has_bracket else ''))
66 | self.write_node(node.falseChild, f, indent+1)
67 | if else_has_bracket:
68 | self.write_closing_bracket(indent, f)
69 | elif then_has_bracket:
70 | self.write_closing_bracket(indent, f)
71 | elif isinstance(node.trueChild, ConditionNode) and isinstance(node.falseChild, ConditionNode):
72 | f.write('{0}if({1})\n'.format(self.get_indent_str(indent) if not nested_if else '', cond_str))
73 | self.write_node(node.trueChild, f, indent+1)
74 | f.write('{0}else '.format(self.get_indent_str(indent)))
75 | self.write_node(node.falseChild, f, indent)
76 | elif isinstance(node.trueChild, ConditionNode):
77 | if node.falseChild is None:
78 | f.write('{0}if({1})\n'.format(self.get_indent_str(indent) if not nested_if else '',
79 | cond_str))
80 | self.write_node(node.trueChild, f, indent+1)
81 | else:
82 | f.write('{0}if({1}){2}\n'.format(self.get_indent_str(indent) if not nested_if else '',
83 | neg_cond_str, '{' if else_has_bracket else ''))
84 | self.write_node(node.falseChild, f, indent+1)
85 | f.write('{0}{1}else '.format(self.get_indent_str(indent), '} ' if else_has_bracket else ''))
86 | self.write_node(node.trueChild, f, indent, True)
87 | else:
88 | if node.trueChild is None:
89 | f.write('{0}if({1})\n'.format(self.get_indent_str(indent) if not nested_if else '',
90 | neg_cond_str))
91 | self.write_node(node.falseChild, f, indent+1)
92 | else:
93 | f.write('{0}if({1}){2}\n'.format(self.get_indent_str(indent) if not nested_if else '',
94 | cond_str, '{' if then_has_bracket else ''))
95 | self.write_node(node.trueChild, f, indent+1)
96 | f.write('{0}{1}else '.format(self.get_indent_str(indent), '} ' if then_has_bracket else ''))
97 | self.write_node(node.falseChild, f, indent, True)
98 | elif isinstance(node, LoopNode):
99 | condition_exp = node.condition
100 | cond_str = str(condition_exp)
101 | cond_str = cond_str if cond_str[0] != '(' else cond_str[1:-1]
102 | body_has_brackets = self.needs_brackets(node.body)
103 | if node.type == LoopType.PRE_TESTED or node.type == LoopType.ENDLESS:
104 | f.write("{0}while({1}){2}\n".format(self.get_indent_str(indent),
105 | cond_str, '{' if body_has_brackets else ''))
106 | self.write_node(node.body, f, indent + 1)
107 | if body_has_brackets:
108 | self.write_closing_bracket(indent, f)
109 | elif node.type == LoopType.POST_TESTED:
110 | f.write("{0}do{1}\n".format(self.get_indent_str(indent), '{' if body_has_brackets else ''))
111 | self.write_node(node.body, f, indent + 1)
112 | f.write("{0}{1}while({2});\n".format(self.get_indent_str(indent),
113 | '}' if body_has_brackets else '', cond_str))
114 | elif isinstance(node, ForNode):
115 | body_has_brackets = self.needs_brackets(node.body)
116 | f.write('{0}{1}{2}\n'.format(self.get_indent_str(indent), node.header_str(), '{' if body_has_brackets else ''))
117 | self.write_node(node.body, f, indent + 1)
118 | if body_has_brackets:
119 | self.write_closing_bracket(indent, f)
120 | elif isinstance(node, SwitchNode):
121 | f.write("{0}switch({1}){\n".format(self.get_indent_str(indent), node.testedVariableName))
122 | for c in node.cases:
123 | for v in c.caseValues:
124 | f.write("{0}case {1}:\n".format(self.get_indent_str(indent + 1), v))
125 | self.write_node(c.node, f, indent + 2)
126 | if c.endsWithBreak:
127 | f.write("{0}break\n".format(self.get_indent_str(indent + 2)))
128 | if node.defaultNode is not None:
129 | f.write("{0}default :\n".format(self.get_indent_str(indent + 1)))
130 | self.write_node(node.defaultNode, f, indent + 2)
131 | self.write_closing_bracket(indent, f)
132 | elif isinstance(node, Instruction) or isinstance(node, Expression):
133 | f.write("{0}{1};\n".format(self.get_indent_str(indent), str(node)))
134 |
135 | @staticmethod
136 | def needs_brackets(stmt):
137 | return isinstance(stmt, SequenceNode) and len(stmt.children) > 1
138 |
139 | def write_closing_bracket(self, indent, f):
140 | f.write('{0}{1}\n'.format(self.get_indent_str(indent), '}'))
141 |
142 | @staticmethod
143 | def get_indent_str(indent):
144 | return " " * indent
145 |
--------------------------------------------------------------------------------
/dream/ir/expressions.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2011-2017 Khaled Yakdan.
2 | # All rights reserved.
3 |
4 | from z3 import *
5 |
6 |
7 | class Expression(object):
8 | def __init__(self):
9 | self.is_signed = False
10 |
11 | def __eq__(self, other):
12 | pass
13 |
14 | def replace_child_expr(self, old_expr, new_expr):
15 | pass
16 |
17 | def deep_copy(self):
18 | pass
19 |
20 | def elements(self):
21 | return [self]
22 |
23 | @staticmethod
24 | def is_simple_expr():
25 | return False
26 |
27 | @staticmethod
28 | def is_overwritable():
29 | return False
30 |
31 | @staticmethod
32 | def is_break_node():
33 | return False
34 |
35 | @staticmethod
36 | def is_pure_break():
37 | return False
38 |
39 | #TODO handle this properly
40 | def getLeafNodes(self):
41 | return [self]
42 |
43 | def simplify(self):
44 | return self
45 |
46 | def to_symbolic(self):
47 | raise NotImplementedError('{0}: This method is not implemented yet'.format(type(self)))
48 |
49 |
50 | class LocalVariable(Expression):
51 | def __init__(self, name, type_=None, show_type=False):
52 | self.name = name
53 | self.type = type_
54 | self.show_type = show_type
55 |
56 | def __str__(self):
57 | type_str = str(self.type) + " " if self.type is not None or str(self.type)[0] == "#" else 'int '
58 | return '{0}{1}'.format(type_str if self.show_type else "", str(self.name))
59 |
60 | def __eq__(self, other):
61 | return isinstance(other, LocalVariable) and self.name == other.name
62 |
63 | def __hash__(self):
64 | return hash(self.name)
65 |
66 | def deep_copy(self):
67 | v_copy = LocalVariable(self.name, self.type)
68 | v_copy.show_type = self.show_type
69 | return v_copy
70 |
71 | @staticmethod
72 | def is_simple_expr():
73 | return True
74 |
75 | @staticmethod
76 | def is_overwritable():
77 | return True
78 |
79 | def to_symbolic(self):
80 | if self.type == 'bool':
81 | return BitVec(self.name, 1)
82 | elif self.type == 'char':
83 | return BitVec(self.name, 8)
84 | return BitVec(self.name, 32)#Int(self.name)
85 |
86 |
87 | class GlobalVariable(Expression):
88 | def __init__(self, name, address):
89 | self.name = name
90 | self.address = address
91 |
92 | def __str__(self):
93 | return str(self.name)
94 |
95 | def __eq__(self, other):
96 | return isinstance(other, GlobalVariable) and self.name == other.name
97 |
98 | def deep_copy(self):
99 | return GlobalVariable(self.name, self.address)
100 |
101 | @staticmethod
102 | def is_simple_expr():
103 | return True
104 |
105 | @staticmethod
106 | def is_overwritable():
107 | return True
108 |
109 | def to_symbolic(self):
110 | return BitVec(self.name, 32)#Int(self.name)
111 |
112 |
113 | class Pointer(Expression):
114 | def __init__(self, address, size_in_bytes=4):
115 | self.address = address
116 | self.size_in_bytes = size_in_bytes
117 |
118 | def __str__(self):
119 | return '*' + parenthesize_unless_simple(self.address)
120 | '''return "*(" + str(self.address) + ")"
121 | result = self.array_str()
122 | result = None
123 | return result if result is not None else "*(" + str(self.address) + ")"
124 | '''
125 |
126 | def __eq__(self, other):
127 | return isinstance(other, Pointer) and self.address == other.address
128 |
129 | def replace_child_expr(self, old_expr, new_expr):
130 | if self.address == old_expr:
131 | self.address = new_expr
132 |
133 | def deep_copy(self):
134 | return Pointer(self.address.deep_copy())
135 |
136 | @staticmethod
137 | def is_simple_expr():
138 | return True
139 |
140 | def elements(self):
141 | return [self] + self.address.elements()
142 |
143 | @staticmethod
144 | def is_overwritable():
145 | return True
146 |
147 | def array_str(self):
148 | if isinstance(self.address, AdditionExpression) and len(self.address.operands) == 2:
149 | ops = self.address.operands
150 | if isinstance(ops[0], NumericConstant) and ops[0].value < 100:
151 | return '{0}[{1}]'.format(str(ops[1]), str(ops[0]))
152 | elif isinstance(ops[1], NumericConstant) and ops[1].value < 100:
153 | return '{0}[{1}]'.format(str(ops[0]), str(ops[1]))
154 | return None
155 |
156 |
157 | class StringLiteral(Expression):
158 | def __init__(self, value):
159 | self.value = value
160 |
161 | def __str__(self):
162 | if self.value[0] in ["\"", "\'"]:
163 | return self.value
164 | return "\"" + self.value + "\""
165 |
166 | def __eq__(self, other):
167 | return isinstance(other, StringLiteral) and self.value == other.value
168 |
169 | def deep_copy(self):
170 | return StringLiteral(self.value)
171 |
172 | @staticmethod
173 | def is_simple_expr():
174 | return True
175 |
176 |
177 | class Call(Expression):
178 | def __init__(self, function_pointer, parameters):
179 | self.function_pointer = function_pointer
180 | self.parameters = parameters
181 |
182 | def __str__(self):
183 | return str(self.function_pointer) + ("(" + self.list_to_str(self.parameters) + ")" if self.parameters else "()")
184 |
185 | def __eq__(self, other):
186 | if isinstance(other, Call) and len(other.parameters) == len(self.parameters):
187 | for i in range(0, len(self.parameters)):
188 | if not (other.parameters[i] == self.parameters[i]):
189 | return False
190 | return True
191 | return False
192 |
193 | @staticmethod
194 | def list_to_str(l):
195 | list_str = ""
196 | for x in l:
197 | list_str += str(x) + ", "
198 | return list_str[:-2]
199 |
200 | def replace_child_expr(self, old_expr, new_expr):
201 | for idx in range(0, len(self.parameters)):
202 | if self.parameters[idx] == old_expr:
203 | self.parameters[idx] = new_expr
204 | break
205 |
206 | def deep_copy(self):
207 | return Call(self.function_pointer.deep_copy(), [param.deep_copy() for param in self.parameters])
208 |
209 | def elements(self):
210 | result = []
211 | for param in self.parameters:
212 | result.extend(param.elements())
213 | return result
214 |
215 | def get_func_name(self):
216 | return str(self.function_pointer)
217 |
218 |
219 | class TernaryExpression(Expression):
220 | def __init__(self, first_operand, second_operand, third_operand):
221 | self.first_operand = first_operand
222 | self.second_operand = second_operand
223 | self.third_operand = third_operand
224 |
225 | def __str__(self):
226 | return str(self.first_operand) + " ? " + str(self.second_operand) + " : " + str(self.third_operand)
227 |
228 | def __eq__(self, other):
229 | return isinstance(other, TernaryExpression) and self.first_operand == other.first_operand \
230 | and self.second_operand == other.second_operand and self.third_operand == other.third_operand
231 |
232 | def replace_child_expr(self, old_expr, new_expr):
233 | if self.first_operand == old_expr:
234 | self.first_operand = new_expr
235 | elif self.second_operand == old_expr:
236 | self.second_operand = new_expr
237 | elif self.third_operand == old_expr:
238 | self.third_operand = new_expr
239 |
240 | def deep_copy(self):
241 | return TernaryExpression(self.first_operand.deep_copy(),
242 | self.second_operand.deep_copy(),
243 | self.third_operand.deep_copy())
244 |
245 | def elements(self):
246 | return self.first_operand.elements() + self.second_operand.elements() + self.third_operand.elements()
247 |
248 |
249 | class UnaryExpression(Expression):
250 | def __init__(self, operand):
251 | self.operand = operand
252 |
253 | def replace_child_expr(self, old_expr, new_expr):
254 | if self.operand == old_expr:
255 | self.operand = new_expr
256 |
257 | def elements(self):
258 | return self.operand.elements()
259 |
260 |
261 | class AddressExpression(UnaryExpression):
262 | def __init__(self, operand):
263 | UnaryExpression.__init__(self, operand)
264 |
265 | def __str__(self):
266 | return '&' + parenthesize_unless_simple(self.operand)
267 |
268 | def __eq__(self, other):
269 | return isinstance(other, AddressExpression) and self.operand == other.operand
270 |
271 | def deep_copy(self):
272 | return AddressExpression(self.operand.deep_copy())
273 |
274 |
275 | class LogicalNotExpression(UnaryExpression):
276 | def __init__(self, operand):
277 | UnaryExpression.__init__(self, operand)
278 |
279 | def __str__(self):
280 | return '!' + parenthesize_unless_simple(self.operand)
281 |
282 | def __eq__(self, other):
283 | return isinstance(other, LogicalNotExpression) and self.operand == other.operand
284 |
285 | def deep_copy(self):
286 | return LogicalNotExpression(self.operand.deep_copy())
287 |
288 |
289 | class BitwiseNOT(UnaryExpression):
290 | def __init__(self, operand):
291 | UnaryExpression.__init__(self, operand)
292 |
293 | def __str__(self):
294 | return '~' + parenthesize_unless_simple(self.operand)
295 |
296 | def __eq__(self, other):
297 | return isinstance(other, BitwiseNOT) and self.operand == other.operand
298 |
299 | def deep_copy(self):
300 | return BitwiseNOT(self.operand.deep_copy())
301 |
302 |
303 | class NegationExpression(UnaryExpression):
304 | def __init__(self, operand):
305 | UnaryExpression.__init__(self, operand)
306 |
307 | def __str__(self):
308 | return '-' + parenthesize_unless_simple(self.operand)
309 |
310 | def __eq__(self, other):
311 | return isinstance(other, NegationExpression) and self.operand == other.operand
312 |
313 | def deep_copy(self):
314 | return NegationExpression(self.operand.deep_copy())
315 |
316 | def to_symbolic(self):
317 | return -1 * self.operand.to_symbolic()
318 |
319 |
320 | class NumericConstant(Expression):
321 | def __init__(self, value):
322 | self.value = value
323 |
324 | def __str__(self):
325 | return hex(self.value) if (type(self.value) == int or type(self.value) == long) and abs(self.value) > 5000 else str(self.value)
326 |
327 | def __eq__(self, other):
328 | return isinstance(other, NumericConstant) and self.value == other.value
329 |
330 | def __invert__(self):
331 | return NumericConstant(~self.value)
332 |
333 | def deep_copy(self):
334 | return NumericConstant(self.value)
335 |
336 | @staticmethod
337 | def is_simple_expr():
338 | return True
339 |
340 | def to_symbolic(self):
341 | return self.value
342 |
343 |
344 | class HighLevelCondition(Expression):
345 | def __init__(self, lhs_expression, comparison_string, rhs_expression, is_signed=False):
346 | if type(lhs_expression) == NumericConstant and type(rhs_expression) != NumericConstant:
347 | self.lhsExpression = rhs_expression
348 | self.comparisonString = self.switched_op(comparison_string)
349 | self.rhsExpression = lhs_expression
350 | else:
351 | self.lhsExpression = lhs_expression
352 | self.comparisonString = comparison_string
353 | self.rhsExpression = rhs_expression
354 | self.is_signed = is_signed
355 |
356 | def __str__(self):
357 | if isinstance(self.rhsExpression, NumericConstant) and self.rhsExpression.value == 0:
358 | if self.comparisonString == '==' and hasattr(self.lhsExpression, 'type') and self.lhsExpression.type == 'bool':
359 | return '!{0}'.format(str(self.lhsExpression))
360 | elif self.comparisonString == '!=' and hasattr(self.lhsExpression, 'type') and self.lhsExpression.type == 'bool':
361 | return '{0}'.format(str(self.lhsExpression))
362 | return str(self.lhsExpression) + ' ' + self.comparisonString + ' ' + str(self.rhsExpression)
363 |
364 | def __eq__(self, other):
365 | if not isinstance(other, HighLevelCondition):
366 | return False
367 | return (
368 | self.comparisonString == other.comparisonString and
369 | self.lhsExpression == other.lhsExpression and
370 | self.rhsExpression == other.rhsExpression
371 | ) or (
372 | self.comparisonString == self.switched_op(other.comparisonString) and
373 | self.lhsExpression == other.rhsExpression and
374 | self.rhsExpression == other.lhsExpression
375 | )
376 |
377 | def __invert__(self):
378 | neg_cond = self.deep_copy()
379 | neg_cond.negate()
380 | return neg_cond
381 |
382 | def equals_negated(self, other):
383 | result = False
384 | if isinstance(other, HighLevelCondition):
385 | other.negate()
386 | result = self.__eq__(other)
387 | other.negate()
388 | return result
389 |
390 | def does_test_equality_with_scalar(self, testedVariableName=""):
391 | return self.comparisonString == "==" and isinstance(self.rhsExpression, NumericConstant) \
392 | and (testedVariableName == str(self.lhsExpression) if testedVariableName != "" else True)
393 |
394 | def does_test_larger_than_scalar(self, testedVariableName=""):
395 | return (self.comparisonString == ">=" or self.comparisonString == ">") and isinstance(self.rhsExpression, NumericConstant)\
396 | and (testedVariableName == str(self.lhsExpression) if testedVariableName != "" else True)
397 |
398 | def does_test_smaller_than_scalar(self, testedVariableName=""):
399 | return (self.comparisonString == "<=" or self.comparisonString == "<") and isinstance(self.rhsExpression, NumericConstant)\
400 | and (testedVariableName == str(self.lhsExpression) if testedVariableName != "" else True)
401 |
402 | def does_test_equality_with_value(self, tested_variable_name, tested_value):
403 | return self.comparisonString == "==" and isinstance(self.rhsExpression, NumericConstant)\
404 | and self.rhsExpression.value == tested_value and str(self.lhsExpression) == tested_variable_name
405 |
406 | def negate(self):
407 | if self.comparisonString == "==":
408 | self.comparisonString = "!="
409 | elif self.comparisonString == "!=":
410 | self.comparisonString = "=="
411 | elif self.comparisonString == ">":
412 | self.comparisonString = "<="
413 | elif self.comparisonString == ">=":
414 | self.comparisonString = "<"
415 | elif self.comparisonString == "<":
416 | self.comparisonString = ">="
417 | elif self.comparisonString == "<=":
418 | self.comparisonString = ">"
419 |
420 | @staticmethod
421 | def switched_op(op):
422 | if op == '>':
423 | return '<'
424 | elif op == '>=':
425 | return '<='
426 | elif op == '<':
427 | return '>'
428 | elif op == '<=':
429 | return '>='
430 | else:
431 | return op
432 |
433 | def replace_child_expr(self, old_expr, new_expr):
434 | if self.lhsExpression == old_expr:
435 | self.lhsExpression = new_expr
436 | elif self.rhsExpression == old_expr:
437 | self.rhsExpression = new_expr
438 |
439 | def deep_copy(self):
440 | return HighLevelCondition(self.lhsExpression.deep_copy(), self.comparisonString,
441 | self.rhsExpression.deep_copy(), self.is_signed)
442 |
443 | def elements(self):
444 | return self.lhsExpression.elements() + self.rhsExpression.elements()
445 |
446 | def simplify(self):
447 | if type(self.rhsExpression) == NumericConstant:
448 | if type(self.lhsExpression) == AdditionExpression:
449 | constants = [op.value for op in self.lhsExpression.operands if type(op) == NumericConstant]
450 | if constants:
451 | remaining_ops = [op for op in self.lhsExpression.operands if type(op) != NumericConstant]
452 | self.rhsExpression.value -= sum(constants)
453 | if len(remaining_ops) > 1:
454 | self.lhsExpression.operands = remaining_ops
455 | elif len(remaining_ops) == 1:
456 | self.lhsExpression = remaining_ops[0]
457 | else:
458 | return NumericConstant(1 if self.rhsExpression.value == 0 else 1)
459 | return self
460 |
461 | def to_symbolic(self):
462 | sym_lhs = self.lhsExpression.to_symbolic()
463 | sym_rhs = self.rhsExpression.to_symbolic()
464 | if self.comparisonString == '==':
465 | return sym_lhs == sym_rhs
466 | elif self.comparisonString == '!=':
467 | return sym_lhs != sym_rhs
468 | elif self.comparisonString == '<':
469 | return sym_lhs < sym_rhs if self.is_signed else ULT(sym_lhs, sym_rhs)
470 | elif self.comparisonString == '<=':
471 | return sym_lhs <= sym_rhs if self.is_signed else ULE(sym_lhs, sym_rhs)
472 | elif self.comparisonString == '>':
473 | return sym_lhs > sym_rhs if self.is_signed else UGT(sym_lhs, sym_rhs)
474 | elif self.comparisonString == '>=':
475 | return sym_lhs >= sym_rhs if self.is_signed else UGE(sym_lhs, sym_rhs)
476 |
477 |
478 | class CastExpression(Expression):
479 | def __init__(self, cast_target, cast_expression):
480 | self.cast_target = cast_target
481 | self.cast_expression = cast_expression
482 |
483 | def __str__(self):
484 | return '(' + self.cast_target + ')' + parenthesize_unless_simple(self.cast_expression)
485 |
486 | def __eq__(self, other):
487 | return isinstance(other, CastExpression) and self.cast_target == other.cast_target \
488 | and self.cast_expression == other.cast_expression
489 |
490 | def deep_copy(self):
491 | return CastExpression(self.cast_target, self.cast_expression.deep_copy())
492 |
493 | def elements(self):
494 | return self.cast_expression.elements()
495 |
496 | def replace_child_expr(self, old_expr, new_expr):
497 | if self.cast_expression == old_expr:
498 | self.cast_expression = new_expr
499 |
500 |
501 | class NoncommutativeBinaryExpression(Expression):
502 | def __init__(self, first_operand, second_operand, is_signed=False):
503 | self.first_operand = first_operand
504 | self.second_operand = second_operand
505 | self.is_signed = is_signed
506 |
507 | def replace_child_expr(self, old_expr, new_expr):
508 | if self.first_operand == old_expr:
509 | self.first_operand = new_expr
510 | elif self.second_operand == old_expr:
511 | self.second_operand = new_expr
512 |
513 | def elements(self):
514 | return self.first_operand.elements() + self.second_operand.elements()
515 |
516 | def get_operator(self):
517 | pass
518 |
519 |
520 | class RemainderExpression(NoncommutativeBinaryExpression):
521 | def __init__(self, first_operand, second_operand, is_signed=False):
522 | NoncommutativeBinaryExpression.__init__(self, first_operand, second_operand, is_signed)
523 |
524 | def __str__(self):
525 | return parenthesize_unless_simple(self.first_operand) + " % " + parenthesize_unless_simple(self.second_operand)
526 |
527 | def __eq__(self, other):
528 | return isinstance(other, RemainderExpression) and self.first_operand == other.first_operand \
529 | and self.second_operand == other.second_operand
530 |
531 | def deep_copy(self):
532 | return RemainderExpression(self.first_operand.deep_copy(), self.second_operand.deep_copy(), self.is_signed)
533 |
534 | def get_operator(self):
535 | return '%'
536 |
537 | def to_symbolic(self):
538 | if type(self.second_operand) == NumericConstant and self.second_operand.value == 2:
539 | return Extract(0, 0, self.first_operand.to_symbolic())
540 |
541 | sym_op1, sym_op2 = self.first_operand.to_symbolic(), self.second_operand.to_symbolic()
542 | if self.is_signed:
543 | return sym_op1 % sym_op2
544 | else:
545 | return URem(sym_op1, sym_op2)
546 |
547 |
548 | class ExponentiationExpression(NoncommutativeBinaryExpression):
549 | def __init__(self, first_operand, second_operand):
550 | NoncommutativeBinaryExpression.__init__(self, first_operand, second_operand)
551 |
552 | def __str__(self):
553 | return str(self.first_operand) + " ^ " + str(self.second_operand)
554 |
555 | def __eq__(self, other):
556 | return isinstance(other, ExponentiationExpression) and self.first_operand == other.first_operand \
557 | and self.second_operand == other.second_operand
558 |
559 | def deep_copy(self):
560 | return ExponentiationExpression(self.first_operand.deep_copy(), self.second_operand.deep_copy())
561 |
562 |
563 | class DivisionExpression(NoncommutativeBinaryExpression):
564 | def __init__(self, first_operand, second_operand, is_signed=False):
565 | NoncommutativeBinaryExpression.__init__(self, first_operand, second_operand, is_signed)
566 |
567 | def __str__(self):
568 | return parenthesize_unless_simple(self.first_operand) + ' / ' + parenthesize_unless_simple(self.second_operand)
569 |
570 | def __eq__(self, other):
571 | return isinstance(other, DivisionExpression) and self.first_operand == other.first_operand \
572 | and self.second_operand == other.second_operand
573 |
574 | def deep_copy(self):
575 | return DivisionExpression(self.first_operand.deep_copy(), self.second_operand.deep_copy(), self.is_signed)
576 |
577 | def get_operator(self):
578 | return '/'
579 |
580 | def to_symbolic(self):
581 | sym_op1, sym_op2 = self.first_operand.to_symbolic(), self.second_operand.to_symbolic()
582 | if self.is_signed:
583 | return sym_op1 / sym_op2
584 | else:
585 | return UDiv(sym_op1, sym_op2)
586 |
587 |
588 | class ShiftExpression(NoncommutativeBinaryExpression):
589 | def __init__(self, first_operand, second_operand, shift_operator, is_signed=False):
590 | NoncommutativeBinaryExpression.__init__(self, first_operand, second_operand, is_signed)
591 | self.shift_operator = shift_operator
592 |
593 | def __str__(self):
594 | return parenthesize_unless_simple(self.first_operand) + " {0} ".format(self.shift_operator) \
595 | + parenthesize_unless_simple(self.second_operand)
596 |
597 | def __eq__(self, other):
598 | return isinstance(other, ShiftExpression) and self.first_operand == other.first_operand \
599 | and self.second_operand == other.second_operand and self.shift_operator == other.shift_operator
600 |
601 | def deep_copy(self):
602 | return ShiftExpression(self.first_operand.deep_copy(), self.second_operand.deep_copy(), self.shift_operator, self.is_signed)
603 |
604 | def get_operator(self):
605 | return self.shift_operator
606 |
607 | def to_symbolic(self):
608 | sym_op1, sym_op2 = self.first_operand.to_symbolic(), self.second_operand.to_symbolic()
609 | print sym_op1, sym_op2
610 | if self.shift_operator == '>>':
611 | if self.is_signed:
612 | return sym_op1 >> sym_op2
613 | else:
614 | return LShR(sym_op1, sym_op2)
615 | else:
616 | assert self.shift_operator == '<<'
617 | return sym_op1 << sym_op2
618 |
619 |
620 | class CommutativeAssociativeExpression(Expression):
621 | def __init__(self, operands):
622 | self.operands = operands
623 |
624 | def equal_operands(self, other_operands):
625 | if len(self.operands) != len(other_operands):
626 | return False
627 | other_ops_copy = [op.deep_copy() for op in other_operands]
628 | for op in self.operands:
629 | if op in other_ops_copy:
630 | other_ops_copy.remove(op)
631 | else:
632 | break
633 | return len(other_ops_copy) == 0
634 |
635 | def replace_child_expr(self, old_expr, new_expr):
636 | index = None
637 | for idx in range(0, len(self.operands)):
638 | if self.operands[idx] == old_expr:
639 | index = idx
640 | break
641 | if index is not None:
642 | if type(new_expr) == type(self):
643 | del self.operands[index]
644 | self.operands = self.operands[:index] + new_expr.operands + self.operands[index:]
645 | else:
646 | self.operands[index] = new_expr
647 |
648 | def operands_copy(self):
649 | return [op.deep_copy() for op in self.operands]
650 |
651 | def elements(self):
652 | result = []
653 | for op in self.operands:
654 | result.extend(op.elements())
655 | return result
656 |
657 | def get_operator(self):
658 | pass
659 |
660 |
661 | class AdditionExpression(CommutativeAssociativeExpression):
662 | def __init__(self, operands):
663 | CommutativeAssociativeExpression.__init__(self, operands)
664 |
665 | def __str__(self):
666 | exp_str = ''
667 | for op in self.operands:
668 | if isinstance(op, NegationExpression):
669 | exp_str += ' - ' + parenthesize_unless_simple(op.operand)
670 | elif isinstance(op, NumericConstant) and op.value < 0:
671 | neg_op = NumericConstant(-1 * op.value)
672 | exp_str += ' - ' + str(neg_op)
673 | else:
674 | exp_str += ' + ' + parenthesize_unless_simple_or_same_type(op, AdditionExpression)
675 | return exp_str[3:]
676 |
677 | def __eq__(self, other):
678 | return isinstance(other, AdditionExpression) and self.equal_operands(other.operands)
679 |
680 | def deep_copy(self):
681 | return AdditionExpression(self.operands_copy())
682 |
683 | def get_operator(self):
684 | return '+'
685 |
686 | def to_symbolic(self):
687 | sym_ops = [op.to_symbolic() for op in self.operands]
688 | result = sym_ops[0]
689 | for op in sym_ops[1:]:
690 | result = result + op
691 | return result
692 |
693 |
694 | class MultiplicationExpression(CommutativeAssociativeExpression):
695 | def __init__(self, operands, is_signed=False):
696 | CommutativeAssociativeExpression.__init__(self, operands)
697 | self.is_signed = is_signed
698 |
699 | def __str__(self):
700 | exp_str = ''
701 | for op in self.operands:
702 | exp_str += parenthesize_unless_simple(op) + ' * '
703 | return exp_str[:-3]
704 |
705 | def __eq__(self, other):
706 | return isinstance(other, MultiplicationExpression) and self.equal_operands(other.operands)
707 |
708 | def deep_copy(self):
709 | return MultiplicationExpression(self.operands_copy(), self.is_signed)
710 |
711 | def get_operator(self):
712 | return '*'
713 |
714 |
715 | class CommutativeAssociativeLogicExpression(CommutativeAssociativeExpression):
716 | def __init__(self, operands):
717 | CommutativeAssociativeExpression.__init__(self, operands)
718 |
719 | def get_unique_operands(self):
720 | unique_operands = []
721 | for op in self.operands:
722 | if op not in unique_operands:
723 | unique_operands.append(op)
724 | return unique_operands
725 |
726 | def simplify_operands(self):
727 | self.operands = [op.simplify() for op in self.operands]
728 |
729 | def simplify_condition(self, other_identity, other_cls):
730 | try:
731 | sym = self.to_symbolic()
732 |
733 | except NotImplementedError, e:
734 | print e.message
735 |
736 |
737 |
738 | assert type(self) == ORExpression or type(self) == ANDExpression
739 |
740 | self.simplify_operands()
741 | unique_ops = self.get_unique_operands()
742 | if len(unique_ops) == 1:
743 | return unique_ops[0]
744 | else:
745 | self.operands = unique_ops
746 |
747 | if any(type(op) == NumericConstant and op.value == other_identity for op in self.operands):
748 | return NumericConstant(other_identity)
749 | if any(~op in self.operands for op in self.operands):
750 | return NumericConstant(other_identity)
751 |
752 | new_ops = [op for op in self.operands if type(op) != NumericConstant]
753 | if len(new_ops) != len(self.operands):
754 | if len(new_ops) == 1:
755 | return new_ops[0]
756 | else:
757 | self.operands = new_ops
758 |
759 | if all(type(op) == other_cls for op in self.operands):
760 | common_ops = [x for x in self.operands[0].operands if all(x in op.operands for op in self.operands[1:])]
761 | if common_ops:
762 | common_exp = common_ops[0] if len(common_ops) == 1 else other_cls(common_ops, is_condition=True).simplify()
763 | remaining_ops = []
764 | for op in self.operands:
765 | sub_ops = [x for x in op.operands if x not in common_ops]
766 | remaining_ops.append(sub_ops[0] if len(sub_ops) == 1
767 | else other_cls(sub_ops, is_condition=True).simplify())
768 | return other_cls([common_exp, self.__class__(remaining_ops, is_condition=True).simplify()],
769 | is_condition=True).simplify()
770 |
771 | return self
772 |
773 |
774 | class ANDExpression(CommutativeAssociativeLogicExpression):
775 | def __init__(self, operands, is_condition=False):
776 | CommutativeAssociativeLogicExpression.__init__(self, operands)
777 | self.is_condition = is_condition
778 |
779 | def __str__(self):
780 | exp_str = ''
781 | for op in self.operands:
782 | exp_str += parenthesize_unless_simple_or_same_type(op, HighLevelCondition)
783 | exp_str += ' && ' if self.is_condition else ' & '
784 | return exp_str[:-4 if self.is_condition else -3]
785 |
786 | def __eq__(self, other):
787 | return isinstance(other, ANDExpression) and self.equal_operands(other.operands)
788 |
789 | def __invert__(self):
790 | return ORExpression([~op for op in self.operands], is_condition=self.is_condition)
791 |
792 | def deep_copy(self):
793 | return ANDExpression(self.operands_copy(), self.is_condition)
794 |
795 | def get_operator(self):
796 | return '&&' if self.is_condition else '&'
797 |
798 | def simplify(self):
799 | if not self.is_condition:
800 | return self
801 |
802 | return self.simplify_condition(0, ORExpression)
803 |
804 | self.simplify_operands()
805 | unique_ops = self.get_unique_operands()
806 | if len(unique_ops) == 1:
807 | return unique_ops[0]
808 | else:
809 | self.operands = unique_ops
810 |
811 | if any(type(op) == NumericConstant and op.value == 0 for op in self.operands):
812 | return NumericConstant(0)
813 | if any(~op in self.operands for op in self.operands):
814 | return NumericConstant(0)
815 |
816 | new_ops = [op for op in self.operands if type(op) != NumericConstant]
817 | if len(new_ops) != len(self.operands):
818 | return ANDExpression(new_ops, is_condition=True) if len(new_ops) > 1 else new_ops[0]
819 |
820 | if all(type(op) == ORExpression for op in self.operands):
821 | common_ops = [x for x in self.operands[0].operands if all(x in op.operands for op in self.operands[1:])]
822 | if common_ops:
823 | common_exp = common_ops[0] if len(common_ops) == 1 else ORExpression(common_ops, is_condition=True).simplify()
824 | remaining_ops = []
825 | for op in self.operands:
826 | sub_ops = [x for x in op.operands if x not in common_ops]
827 | remaining_ops.append(sub_ops[0] if len(sub_ops) == 1 else ORExpression(sub_ops, is_condition=True).simplify())
828 | return ORExpression([common_exp, ANDExpression(remaining_ops, is_condition=True).simplify()], is_condition=True).simplify()
829 |
830 | return self
831 |
832 | def to_symbolic(self):
833 | if self.is_condition:
834 | return And([op.to_symbolic() for op in self.operands])
835 | else:
836 | sym_ops = [op.to_symbolic() for op in self.operands]
837 | result = sym_ops[0]
838 | for op in sym_ops[1:]:
839 | result = result & op
840 | return result
841 |
842 |
843 | class ORExpression(CommutativeAssociativeLogicExpression):
844 | def __init__(self, operands, is_condition=False):
845 | CommutativeAssociativeLogicExpression.__init__(self, operands)
846 | self.is_condition = is_condition
847 |
848 | def __str__(self):
849 | exp_str = ''
850 | for op in self.operands:
851 | exp_str += parenthesize_unless_simple_or_same_type(op, HighLevelCondition)
852 | exp_str += ' || ' if self.is_condition else ' | '
853 | return exp_str[:-4 if self.is_condition else -3]
854 |
855 | def __eq__(self, other):
856 | return isinstance(other, ORExpression) and self.equal_operands(other.operands)
857 |
858 | def __invert__(self):
859 | return ANDExpression([~op for op in self.operands], is_condition=self.is_condition)
860 |
861 | def deep_copy(self):
862 | return ORExpression(self.operands_copy(), self.is_condition)
863 |
864 | def get_operator(self):
865 | return '||' if self.is_condition else '|'
866 |
867 | def simplify(self):
868 | if not self.is_condition:
869 | return self
870 |
871 | return self.simplify_condition(1, ANDExpression)
872 |
873 | self.operands = [op.simplify() for op in self.operands]
874 | if any(type(op) == NumericConstant and op.value != 0 for op in self.operands):
875 | return NumericConstant(1)
876 | if any(~op in self.operands for op in self.operands):
877 | return NumericConstant(1)
878 | new_ops = [op for op in self.operands if type(op) != NumericConstant]
879 | if len(new_ops) != len(self.operands):
880 | return ORExpression(new_ops, is_condition=True) if len(new_ops) > 1 else new_ops[0]
881 |
882 | if all(type(op) == ANDExpression for op in self.operands):
883 | common_ops = [x for x in self.operands[0].operands if all(x in op.operands for op in self.operands[1:])]
884 | if common_ops:
885 | common_exp = common_ops[0] if len(common_ops) == 1 else ANDExpression(common_ops, is_condition=True).simplify()
886 | remaining_ops = []
887 | for op in self.operands:
888 | sub_ops = [x for x in op.operands if x not in common_ops]
889 | remaining_ops.append(sub_ops[0] if len(sub_ops) == 1 else ANDExpression(sub_ops, is_condition=True).simplify())
890 | return ANDExpression([common_exp, ORExpression(remaining_ops, is_condition=True).simplify()], is_condition=True).simplify()
891 | return self
892 |
893 | def to_symbolic(self):
894 | if self.is_condition:
895 | return Or([op.to_symbolic() for op in self.operands])
896 | else:
897 | sym_ops = [op.to_symbolic() for op in self.operands]
898 | result = sym_ops[0]
899 | for op in sym_ops[1:]:
900 | result = result | op
901 | return result
902 |
903 |
904 | class XORExpression(CommutativeAssociativeLogicExpression):
905 | def __init__(self, operands):
906 | CommutativeAssociativeLogicExpression.__init__(self, operands)
907 |
908 | def __str__(self):
909 | exp_str = ''
910 | for op in self.operands:
911 | exp_str += parenthesize_unless_simple(op) + ' ^ '
912 | return exp_str[:-3]
913 |
914 | def __eq__(self, other):
915 | return isinstance(other, XORExpression) and self.equal_operands(other.operands)
916 |
917 | def deep_copy(self):
918 | return XORExpression(self.operands_copy())
919 |
920 | def get_operator(self):
921 | return '^'
922 |
923 |
924 | class ArrayIndexing(Expression):
925 | def __init__(self, array, index):
926 | self.array = array
927 | self.index = index
928 |
929 | def __eq__(self, other):
930 | return isinstance(other, ArrayIndexing) and self.array == other.array and self.index == other.index
931 |
932 | def __str__(self):
933 | return "%s[%s]" % (str(self.array), str(self.index))
934 |
935 | def replace_child_expr(self, old_expr, new_expr):
936 | if self.array == old_expr:
937 | self.array = new_expr
938 | elif self.index == old_expr:
939 | self.index = new_expr
940 |
941 | def deep_copy(self):
942 | return ArrayIndexing(self.array.deep_copy(), self.index.deep_copy())
943 |
944 | def elements(self):
945 | return self.array.elements() + self.index.elements()
946 |
947 | @staticmethod
948 | def is_overwritable():
949 | return True
950 |
951 |
952 | class MemberAccess(Expression):
953 | def __init__(self, struct, field, access_operator):
954 | self.struct = struct
955 | self.field = field
956 | self.access_operator = access_operator
957 |
958 | def __eq__(self, other):
959 | return isinstance(other, MemberAccess) and self.struct == other.struct and self.field == other.field \
960 | and self.access_operator == other.access_operator
961 |
962 | def __str__(self):
963 | return "%s%s%s" % (str(self.struct), self.access_operator, str(self.field))
964 |
965 | def replace_child_expr(self, old_expr, new_expr):
966 | if self.struct == old_expr:
967 | self.struct = new_expr
968 | elif self.field == old_expr:
969 | self.field = new_expr
970 |
971 | def deep_copy(self):
972 | return MemberAccess(self.struct.deep_copy(), self.field.deep_copy(), self.access_operator)
973 |
974 | def elements(self):
975 | return self.struct.elements() + self.field.elements()
976 |
977 | @staticmethod
978 | def is_overwritable():
979 | return True
980 |
981 |
982 | class InitializerList(Expression):
983 | def __init__(self, init_elements):
984 | self.init_elements = init_elements
985 |
986 | def __str__(self):
987 | exp_str = "{"
988 | for e in self.init_elements:
989 | exp_str += "%s, " % str(e)
990 | return exp_str[:-2] + "}"
991 |
992 | def elements(self):
993 | result = []
994 | for e in self.init_elements:
995 | result.extend(e.elements())
996 | return result
997 |
998 | def deep_copy(self):
999 | return InitializerList([e.deep_copy() for e in self.init_elements])
1000 |
1001 |
1002 | def parenthesize_unless_simple(expr):
1003 | if expr.is_simple_expr():
1004 | return str(expr)
1005 | else:
1006 | return '(' + str(expr) + ')'
1007 |
1008 |
1009 | def parenthesize_unless_simple_or_same_type(expr, typ):
1010 | if expr.is_simple_expr() or type(expr) == typ:
1011 | return str(expr)
1012 | else:
1013 | return '(' + str(expr) + ')'
--------------------------------------------------------------------------------
/dream/ir/instructions.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2011-2017 Khaled Yakdan.
2 | # All rights reserved.
3 |
4 | from dream.ir.expressions import AdditionExpression, NumericConstant, Pointer, CommutativeAssociativeExpression, NoncommutativeBinaryExpression, NegationExpression, LocalVariable
5 |
6 |
7 | class Instruction(object):
8 | def __init__(self):
9 | pass
10 |
11 | def replace_child_stmt(self, old_stmt, new_stmt):
12 | pass
13 |
14 | def deep_copy(self):
15 | pass
16 |
17 | def defs(self):
18 | return []
19 |
20 | def uses(self):
21 | return []
22 |
23 | def elements(self):
24 | return [self] + self.defs() + self.uses()
25 |
26 | def is_break_node(self):
27 | return False
28 |
29 | @staticmethod
30 | def is_pure_break():
31 | return False
32 |
33 | #TODO handle this properly
34 | def getLeafNodes(self):
35 | return [self]
36 |
37 |
38 | class Assignment(Instruction):
39 | def __init__(self, lhs_operand, rhs_operand):
40 | self.lhs_operand = lhs_operand
41 | self.rhs_operand = rhs_operand
42 |
43 | def __str__(self):
44 | lhs_str = str(self.lhs_operand)
45 | if isinstance(self.rhs_operand, CommutativeAssociativeExpression) \
46 | and self.lhs_operand in self.rhs_operand.operands:
47 | ops_copy = self.rhs_operand.operands[:]
48 | ops_copy.remove(self.lhs_operand)
49 | if len(ops_copy) == 1:
50 | if isinstance(self.rhs_operand, AdditionExpression):
51 | if isinstance(ops_copy[0], NumericConstant):
52 | if ops_copy[0].value == 1:
53 | return lhs_str + '++'
54 | elif ops_copy[0].value == -1:
55 | return lhs_str + '--'
56 | elif ops_copy[0].value > 0:
57 | return lhs_str + ' += ' + str(ops_copy[0])
58 | else:
59 | return lhs_str + ' -= ' + str(-1 * ops_copy[0].value)
60 | elif isinstance(ops_copy[0], NegationExpression):
61 | return lhs_str + ' -= ' + str(ops_copy[0].operand)
62 |
63 | return lhs_str + ' {0}= '.format(self.rhs_operand.get_operator()) + str(ops_copy[0])
64 |
65 | rhs_copy = self.rhs_operand.deep_copy()
66 | rhs_copy.operands = ops_copy
67 | return lhs_str + ' {0}= '.format(rhs_copy.get_operator()) + str(rhs_copy)
68 | elif isinstance(self.rhs_operand, NoncommutativeBinaryExpression) \
69 | and self.lhs_operand == self.rhs_operand.first_operand:
70 | return lhs_str + ' {0}= '.format(self.rhs_operand.get_operator()) + str(self.rhs_operand.second_operand)
71 | return lhs_str + " = " + str(self.rhs_operand)
72 |
73 | @staticmethod
74 | def unary_assignment_str(var, const):
75 | if const == 1:
76 | return str(var) + "++"
77 | elif const == -1:
78 | return str(var) + "--"
79 | elif const > 0:
80 | return str(var) + " += " + str(const)
81 | else:
82 | return str(var) + " -= " + str(-1 * const)
83 |
84 | def replace_child_stmt(self, old_stmt, new_stmt):
85 | if self.lhs_operand == old_stmt:
86 | self.lhs_operand = new_stmt
87 | elif self.rhs_operand == old_stmt:
88 | self.rhs_operand = new_stmt
89 |
90 | def deep_copy(self):
91 | return Assignment(self.lhs_operand.deep_copy(), self.rhs_operand.deep_copy())
92 |
93 | def defs(self):
94 | return [self.lhs_operand]
95 |
96 | def uses(self):
97 | result = self.rhs_operand.elements()
98 | if isinstance(self.lhs_operand, Pointer):
99 | result.extend(self.lhs_operand.address.elements())
100 | return result
101 |
102 | def does_define(self, expr):
103 | return expr in self.defs()
104 |
105 |
106 | class Return(Instruction):
107 | def __init__(self, operand):
108 | self.operand = operand
109 |
110 | def __str__(self):
111 | op_str = " " + str(self.operand) if self.operand is not None else ""
112 | return "return" + op_str
113 |
114 | def replace_child_stmt(self, old_stmt, new_stmt):
115 | if self.operand == old_stmt:
116 | self.operand = new_stmt
117 |
118 | def deep_copy(self):
119 | return Return(self.operand.deep_copy() if self.operand is not None else None)
120 |
121 | def uses(self):
122 | return self.operand.elements() if self.operand is not None else []
123 |
124 |
125 | class Break(Instruction):
126 | def __str__(self):
127 | return 'break'
128 |
129 | def deep_copy(self):
130 | return Break()
131 |
132 | def is_break_node(self):
133 | return True
134 |
135 |
136 | class VariableDeclaration(Instruction):
137 | def __init__(self, variable, initial_value=None):
138 | assert isinstance(variable, LocalVariable)
139 | self.variable = variable
140 | self.variable.show_type = True
141 | self.initial_value = initial_value
142 |
143 | def __str__(self):
144 | init_str = ''
145 | if self.initial_value is None and self.variable.type == 'bool':
146 | init_str = ' = false'
147 | else:
148 | if self.variable.type == 'bool' and isinstance(self.initial_value, NumericConstant):
149 | if self.initial_value.value == 0:
150 | init_str = ' = false'
151 | else:
152 | init_str = ' = true'
153 | elif self.initial_value is not None:
154 | init_str = ' = ' + hex(self.initial_value)
155 | return '{0}{1}'.format(str(self.variable), init_str)
156 |
157 |
158 | class ClassDefinition(Instruction):
159 | def __init__(self, def_str):
160 | self.def_str = def_str
161 |
162 | def __str__(self):
163 | return self.def_str
164 |
165 | def deep_copy(self):
166 | return ClassDefinition(self.def_str)
--------------------------------------------------------------------------------
/dream/json_parser.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2011-2017 Khaled Yakdan.
2 | # All rights reserved.
3 |
4 | import json
5 | from sympy.core.symbol import Symbol
6 | from sympy.logic.boolalg import Not, true
7 | from dream.ControlFlowGraph import ControlFlowGraph, NodeType
8 | from dream.ControlFlowTree import FunctionSignature, SequenceNode
9 | from dream.ir.expressions import (
10 | LocalVariable, GlobalVariable, Pointer, StringLiteral, NumericConstant,
11 | TernaryExpression, AddressExpression, LogicalNotExpression,
12 | NegationExpression, HighLevelCondition, RemainderExpression,
13 | ExponentiationExpression, AdditionExpression, MultiplicationExpression,
14 | ANDExpression, ORExpression, XORExpression, Call, ShiftExpression,
15 | DivisionExpression)
16 | from dream.ir.instructions import Assignment, Return
17 |
18 |
19 | class JsonGraphParser:
20 | def __init__(self):
21 | self.cfg = ControlFlowGraph()
22 | self.g_json = None
23 | # self.symbols_alias_map = {}
24 |
25 | def get_function_signature(self):
26 | parameters = []
27 | for param in self.g_json['arguments']:
28 | parameters.append(self.make_expression(param))
29 | return FunctionSignature(self.g_json['function_name'], parameters,
30 | None)
31 |
32 | def graph_from_json(self, file_name):
33 | f = open(file_name)
34 | self.g_json = json.load(f, encoding='ascii')
35 | f.close()
36 | nodes = self.g_json['cfg']['nodes']
37 |
38 | self.cfg.add_vertex(n=len(nodes))
39 | for n in nodes:
40 | v = self.cfg.vertex(int(n['id']))
41 | node_type = self.get_node_type(n)
42 | self.cfg.vertex_properties['type'][v] = node_type
43 | if node_type == NodeType.CODE:
44 | self.cfg.vertex_properties['ast'][v] = self.construct_ast(n)
45 | self.add_edges(v, n['successors'])
46 | self.cfg.conditions_map = self.construct_conditions_map(self.g_json[
47 | 'cfg']['conditions_map'])
48 |
49 | @staticmethod
50 | def get_node_type(n_json):
51 | if n_json['type'] == 'Code':
52 | return NodeType.CODE
53 | elif n_json['type'] == 'Conditional':
54 | return NodeType.CONDITIONAL
55 | elif n_json['type'] == 'Switch':
56 | return NodeType.SWITCH
57 |
58 | def add_edges(self, v, successors_json):
59 | for s in successors_json:
60 | e = self.cfg.add_edge(v, int(s['node_id']))
61 | label = s['tag'].encode('ascii')
62 | if label == 'None':
63 | self.cfg.edge_properties['tag'][e] = None
64 | elif label[0] == '!':
65 | self.cfg.edge_properties['tag'][e] = Not(Symbol(label[1:]))
66 | else:
67 | self.cfg.edge_properties['tag'][e] = Symbol(label)
68 |
69 | def construct_ast(self, n_json):
70 | ast = SequenceNode(true, [])
71 | for inst in n_json['instructions']:
72 | ast.children.append(self.make_instruction(inst))
73 | return ast
74 |
75 | def make_instruction(self, inst_json):
76 | if inst_json['instruction_type'] == 'Assignment':
77 | return Assignment(
78 | self.make_expression(inst_json['lhsOperand']),
79 | self.make_expression(inst_json['rhsOperand']))
80 | elif inst_json['instruction_type'] == 'CALL':
81 | assert len(inst_json['returns']) <= 1
82 | call_expr = Call(
83 | self.make_expression(inst_json['functionPointer']), [
84 | self.make_expression(exp_json)
85 | for exp_json in inst_json['parameters']
86 | ])
87 | if inst_json['returns']:
88 | return Assignment(
89 | self.make_expression(inst_json['returns'][0]), call_expr)
90 | else:
91 | return call_expr
92 |
93 | elif inst_json['instruction_type'] == 'Return':
94 | return Return(self.make_expression(inst_json['operand']))
95 | else:
96 | print inst_json
97 | assert False, "unsupported instruction type: {0}".format(inst_json[
98 | 'instruction_type'])
99 |
100 | def make_expression(self, exp_json):
101 | if exp_json['expression_type'] == 'LocalVariable':
102 | name = exp_json['name']
103 | type_str = exp_json['type'].strip(
104 | ) if 'type' in exp_json else 'int'
105 | var = LocalVariable(name, type_str if type_str != 'void' else None)
106 | self.cfg.variable_names[var.name] = var
107 | return var
108 |
109 | elif exp_json['expression_type'] == 'GlobalVariable':
110 | name = exp_json['name']
111 | g_var = GlobalVariable(name, int(exp_json['address']))
112 | self.cfg.variable_names[g_var.name] = g_var
113 | return g_var
114 | elif exp_json['expression_type'] == 'PointerExp':
115 | return Pointer(
116 | self.make_expression(exp_json['addressExpression']),
117 | 4) # int(exp_json['size_in_bytes'])
118 | elif exp_json['expression_type'] == 'StringLiteral':
119 | return StringLiteral(exp_json['value'])
120 | elif exp_json['expression_type'] == 'NumericConstant':
121 | value = float(exp_json['value'])
122 | return NumericConstant(
123 | int(value) if value == int(value) else value)
124 | elif exp_json['expression_type'] == 'TernaryExpression':
125 | return TernaryExpression(
126 | self.make_expression(exp_json['firstOperand']),
127 | self.make_expression(exp_json['secondOperand']),
128 | self.make_expression(exp_json['thirdOperand']))
129 | elif exp_json['expression_type'] == 'AddressExpression':
130 | return AddressExpression(self.make_expression(exp_json['operand']))
131 | elif exp_json['expression_type'] == 'LogicalNotExpression':
132 | return LogicalNotExpression(
133 | self.make_expression(exp_json['operand']))
134 | elif exp_json['expression_type'] == 'NegationExpression':
135 | return NegationExpression(
136 | self.make_expression(exp_json['operand']))
137 | elif exp_json['expression_type'] == 'HighLevelCondition':
138 | return HighLevelCondition(
139 | self.make_expression(exp_json['firstOperand']),
140 | exp_json['comparisonOperand'],
141 | self.make_expression(exp_json['secondOperand']), False if
142 | 'isUnsigned' in exp_json and exp_json['isUnsigned'] else True)
143 | elif exp_json['expression_type'] == 'RemainderExpression':
144 | return RemainderExpression(
145 | self.make_expression(exp_json['firstOperand']),
146 | self.make_expression(exp_json['secondOperand']))
147 | elif exp_json['expression_type'] == 'ExponentiationExpression':
148 | return ExponentiationExpression(
149 | self.make_expression(exp_json['firstOperand']),
150 | self.make_expression(exp_json['secondOperand']))
151 | elif exp_json['expression_type'] == 'DivisionExpression':
152 | return DivisionExpression(
153 | self.make_expression(exp_json['firstOperand']),
154 | self.make_expression(exp_json['secondOperand']))
155 | elif exp_json['expression_type'] == 'AdditionExpression':
156 | return AdditionExpression(
157 | [self.make_expression(exp) for exp in exp_json['operands']])
158 | elif exp_json['expression_type'] == 'MultiplicationExpression':
159 | return MultiplicationExpression(
160 | [self.make_expression(exp) for exp in exp_json['operands']])
161 | elif exp_json['expression_type'] == 'ANDExpression':
162 | return ANDExpression(
163 | [self.make_expression(exp) for exp in exp_json['operands']])
164 | elif exp_json['expression_type'] == 'ORExpression':
165 | return ORExpression(
166 | [self.make_expression(exp) for exp in exp_json['operands']])
167 | elif exp_json['expression_type'] == 'XORExpression':
168 | return XORExpression(
169 | [self.make_expression(exp) for exp in exp_json['operands']])
170 | elif exp_json['expression_type'] == 'ShiftExpression':
171 | return ShiftExpression(
172 | self.make_expression(exp_json['firstOperand']),
173 | self.make_expression(exp_json['secondOperand']),
174 | exp_json['operation'])
175 | else:
176 | assert False, "unsupported expression type: {0}".format(exp_json)
177 |
178 | def construct_conditions_map(self, conditions_json):
179 | conditions_map = {}
180 | for tag in conditions_json:
181 | conditions_map[Symbol(tag['tag_name'])] = self.make_expression(tag[
182 | 'tag_condition'])
183 | return conditions_map
184 |
--------------------------------------------------------------------------------
/dream/logic.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2011-2017 Khaled Yakdan.
2 | # All rights reserved.
3 |
4 | from sympy import And, Or, Not, Symbol, true, false
5 | from sympy.logic.boolalg import to_cnf, bool_map, simplify_logic
6 | from ir.expressions import ORExpression, ANDExpression, HighLevelCondition, NumericConstant, LocalVariable, LogicalNotExpression, Call
7 |
8 |
9 | def get_AND_remaining_term(cond_inner, cond_outer):
10 | """conditions must be in CNF form"""
11 | args_inner = list(cond_inner.args) if type(cond_inner) == And else [cond_inner]
12 | args_outer = list(cond_outer.args) if type(cond_outer) == And else [cond_outer]
13 |
14 | if len(args_inner) <= len(args_outer):
15 | args_outer_str = [str(a) for a in args_outer]
16 | for arg in args_inner:
17 | try:
18 | arg_id = args_outer_str.index(str(arg))
19 | del args_outer_str[arg_id]
20 | del args_outer[arg_id]
21 | except ValueError:
22 | if not remove_item_if_exists(arg, args_outer):
23 | return None
24 | args_remaining = true
25 | for arg in args_outer:
26 | args_remaining = And(args_remaining, arg)
27 | return to_cnf(args_remaining, simplify=True)
28 | return None
29 |
30 |
31 | def remove_item_if_exists(item, items_list):
32 | for i in range(0, len(items_list)):
33 | if conditions_equal(item, items_list[i]):
34 | del items_list[i]
35 | return True
36 | return False
37 |
38 |
39 | def conditions_equal(cond1, cond2):
40 | if cond1 == cond2:
41 | return True
42 |
43 | symbols_1 = get_symbols(cond1)
44 | symbols_2 = get_symbols(cond2)
45 | if symbols_1.symmetric_difference(symbols_2):
46 | return False
47 |
48 | cond1_simplified = simplify_logic(cond1)
49 | cond2_simplified = simplify_logic(cond2)
50 | if type(cond1_simplified) != type(cond2_simplified):
51 | return False
52 | elif len(cond1_simplified.args) != len(cond2_simplified.args):
53 | return False
54 |
55 | cond_mapping = bool_map(cond1, cond2)
56 | if type(cond_mapping) != bool:
57 | for k, v in cond_mapping[1].items():
58 | if k != v:
59 | return False
60 | return True
61 | return False
62 |
63 |
64 | def get_symbols(logic_exp):
65 | symbols = set()
66 | if isinstance(logic_exp, Symbol):
67 | symbols.add(logic_exp)
68 | elif isinstance(logic_exp, Not):
69 | symbols.update(get_symbols(logic_exp.args[0]))
70 | elif isinstance(logic_exp, Or) or isinstance(logic_exp, And):
71 | for arg in logic_exp.args:
72 | symbols.update(get_symbols(arg))
73 | else:
74 | assert logic_exp in [true, false], "unrecognized logic expression type: {0}".format(logic_exp)
75 | return symbols
76 |
77 |
78 | def get_arguments_number(cond, ignoreNot=True):
79 | if ignoreNot:
80 | if isinstance(cond, Not) and len(cond.args) == 1 and isinstance(cond.args[0], Symbol):
81 | return 0
82 | num = 0
83 | for arg in cond.args:
84 | num += 1 + get_arguments_number(arg, ignoreNot)
85 | return num
86 |
87 |
88 | def in_conditions_list(cond, cond_list):
89 | for c in cond_list:
90 | if conditions_equal(c, cond):
91 | return True
92 | return False
93 |
94 |
95 | def is_trivial_condition(condition):
96 | return condition == true
97 |
98 |
99 | def has_compound_trivial_condition(condition_list):
100 | compound_condition = false
101 | for c in condition_list:
102 | compound_condition = Or(compound_condition, c)
103 | return is_trivial_condition(simplify_logic(compound_condition))
104 |
105 |
106 | def get_negated_condition(exp):
107 | if isinstance(exp, HighLevelCondition):
108 | return ~exp
109 | elif isinstance(exp, ORExpression):
110 | return ANDExpression([get_negated_condition(op) for op in exp.operands], exp.is_condition)
111 | elif isinstance(exp, ANDExpression):
112 | return ORExpression([get_negated_condition(op) for op in exp.operands], exp.is_condition)
113 | elif isinstance(exp, LogicalNotExpression):
114 | return exp.operand
115 | else:
116 | return LogicalNotExpression(exp)
117 |
118 | #TODO handle later
119 | #else:
120 | # return simplify_logic(Not(exp))
121 | # assert False, "unrecognised expression: {0}".format(exp)
122 |
123 |
124 | def get_condition_from_logic_expression(logic_exp, conditions_map):
125 | #return logic_exp
126 | if not isinstance(logic_exp, Symbol) and not isinstance(logic_exp, Not) and not isinstance(logic_exp, Or) \
127 | and not isinstance(logic_exp, And) and not isinstance(logic_exp, LocalVariable) and not logic_exp == true:
128 | return logic_exp
129 |
130 | logic_exp = simplify_logic(logic_exp)
131 | #return logic_exp
132 | if isinstance(logic_exp, Symbol):
133 | return conditions_map[logic_exp]
134 | elif isinstance(logic_exp, Not):
135 | return get_negated_condition(get_condition_from_logic_expression(logic_exp.args[0], conditions_map))
136 | elif isinstance(logic_exp, Or):
137 | return ORExpression([get_condition_from_logic_expression(arg, conditions_map) for arg in logic_exp.args],
138 | is_condition=True)
139 | elif isinstance(logic_exp, And):
140 | return ANDExpression([get_condition_from_logic_expression(arg, conditions_map) for arg in logic_exp.args],
141 | is_condition=True)
142 | elif logic_exp in [True, true]:
143 | return NumericConstant(1)
144 | elif isinstance(logic_exp, LocalVariable):
145 | return logic_exp
146 | else:
147 | assert False, 'unrecognised logic expression{0}'.format(logic_exp)
148 |
149 |
150 | def alias_free_expression(logic_expr, conditions_map):
151 | #TODO remove first line
152 | return logic_expr
153 | symbols_alias_map = compute_aliases(logic_expr, conditions_map)
154 | return logic_expr.subs(symbols_alias_map)
155 |
156 |
157 | def compute_aliases(logic_expr, conditions_map):
158 | symbols_alias_map = {}
159 | unique_conditions_map = {}
160 | for symbol1 in set(get_symbols(logic_expr)):
161 | condition1 = conditions_map[symbol1]
162 | alias_found = False
163 | for symbol2, condition2 in unique_conditions_map.items():
164 | if condition1 == condition2:
165 | symbols_alias_map[symbol1] = symbol2
166 | alias_found = True
167 | break
168 | elif condition1.equals_negated(condition2):
169 | symbols_alias_map[symbol1] = Not(symbol2)
170 | alias_found = True
171 | break
172 | if not alias_found:
173 | unique_conditions_map[symbol1] = condition1
174 | return symbols_alias_map
175 |
176 |
--------------------------------------------------------------------------------
/dream/prolog/builtin_rules.pl:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2011-2017 Khaled Yakdan.
3 | * All rights reserved.
4 | */
5 |
6 | directly_after(S1, S2, Stmts):-
7 | nth0(Idx1, Stmts, S1),
8 | nth0(Idx2, Stmts, S2),
9 | Idx1 =:= Idx2 + 1.
10 |
11 | after(S1, S2, Stmts):-
12 | nth0(Idx1, Stmts, S1),
13 | nth0(Idx2, Stmts, S2),
14 | Idx1 > Idx2.
15 |
16 | ancestor_node(Node, Ancestor) :-
17 | parent_node(Node, Ancestor).
18 |
19 | ancestor_node(Node, Ancestor) :-
20 | parent_node(Node, Parent),
21 | ancestor_node(Parent, Ancestor).
22 |
23 | get_all_children(Node, Children) :-
24 | findall(Child, ancestor_node(Child, Node), Children).
25 |
26 | common_ancestor(Node1, Node2, Ancestor) :-
27 | (ancestor_node(Node1, Node2), Ancestor = Node2);
28 | (ancestor_node(Node2, Node1), Ancestor = Node1);
29 | (ancestor_node(Node1, Ancestor), ancestor_node(Node2, Ancestor)).
30 |
31 | common_ancestor_list([H|[]], H).
32 |
33 | common_ancestor_list([H1|[H2|T]], Ancestor) :-
34 | common_ancestor(H1, H2, PartialAncestor),
35 | common_ancestor_list([PartialAncestor|T], Ancestor).
36 |
37 | is_last_child(Node, ParentSet) :-
38 | member(Node, ParentSet),
39 | select(Node, ParentSet, Tail),
40 | forall(member(Parent, Tail), ancestor_node(Node, Parent)).
41 |
42 | %nearest_common_ancestor(Nodes, CommonAncestor) :-
43 | % findall(Ancestor, common_ancestor_list(Nodes, Ancestor), AncestorList),
44 | % list_to_set(AncestorList, AncestorSet),
45 | % is_last_child(CommonAncestor, AncestorSet).
46 | %------------------------------------------------------
47 |
48 | all_ancestors(Node, Ancestors) :-
49 | findall(Ancestor, ancestor_node(Node, Ancestor), Ancestors).
50 |
51 | intersect([Set|[]], Set).
52 |
53 | intersect([Set1|[Set2|Rest]], Intersection) :-
54 | intersection(Set1, Set2, Set3),
55 | intersect([Set3|Rest], Intersection).
56 |
57 | nearest_common_ancestor(Nodes, CommonAncestor) :-
58 | findall(Ancestors, (member(Node, Nodes), all_ancestors(Node, Ancestors)), AncestorsSet),
59 | intersect(AncestorsSet, CommonAncestors),
60 | max_list(CommonAncestors, CommonAncestor).
61 |
62 | %------------------------------------------------------
63 |
64 | symbol_uses(Symbol, Uses):-
65 | findall(Use, (logicIdentT(_, Use, Symbol), logicExpressionT(Use, _, _)), Uses).
66 |
67 | multiple_symbol_uses(Symbol, Uses) :-
68 | logicSymbolT(SymbolId, _, Symbol),
69 | symbol_uses(SymbolId, Uses),
70 | length(Uses, UsesNum),
71 | UsesNum > 1.
72 |
73 | in_sequence_ancestor(Sequence, Node, Ancestor) :-
74 | sequenceT(Sequence, _, Children),
75 | member(Ancestor, Children),
76 | (ancestor_node(Node, Ancestor) ; Ancestor =:= Node).
77 |
78 | in_sequence_ancestor_set(Sequence, NodeList, AncestorSet) :-
79 | findall(Ancestor, (member(Node, NodeList), in_sequence_ancestor(Sequence, Node, Ancestor)), AncestorList),
80 | list_to_set(AncestorList, AncestorSet).
81 |
82 |
83 | definitions(Variable, Defs) :-
84 | findall(Def, (assignT(Def, _, LIdent, _), identT(LIdent, Def, Variable)), Defs).
85 |
86 | uses(Variable, Uses) :-
87 | definitions(Variable, Defs),
88 | findall(Use, (identT(_, Use, Variable), not(member(Use, Defs))), Uses).
89 |
90 | non_preserving_use(Variable, NonPreservingUse) :-
91 | (assignT(NonPreservingUse, _, Lhs, _), identT(Lhs, NonPreservingUse, Variable));
92 | (callT(NonPreservingUse, _, _, Parameters), identT(Param, NonPreservingUse, Variable), member(Param, Parameters));
93 | (operationT(NonPreservingUse, _, [Ident], '&'), identT(Ident, NonPreservingUse, Variable)).
94 |
95 |
96 | pre_order_after(AstNode1, AstNode2) :-
97 | pre_order_next(AstNode1, AstNode2).
98 |
99 | pre_order_after(AstNode1, AstNode2) :-
100 | pre_order_next(AstNode1, AstNode1Next),
101 | pre_order_after(AstNode1Next, AstNode2).
102 |
103 | pre_order_before(AstNode1, AstNode2) :-
104 | not(pre_order_after(AstNode1, AstNode2)),
105 | AstNode1 =\= AstNode2.
106 |
107 |
108 | in_neighbours(Node, InNeighbours) :-
109 | findall(Pred, cfg_edge(Pred, Node), InNeighbours).
110 |
111 | path(Source, Target, Path) :-
112 | travel(Source, Target, [Source], ReversedPath),
113 | reverse(ReversedPath, Path).
114 |
115 | path_not_passing_by(Source, Target, NotPassingByNode, Path) :-
116 | travel(Source, Target, [Source], Path),
117 | not(member(NotPassingByNode, Path)).
118 |
119 | travel(Source, Target, Path, [Target|Path]) :-
120 | cfg_edge(Source, Target).
121 |
122 | travel(Source, Target, Visited, Path) :-
123 | cfg_edge(Source, Node),
124 | Node \== Target,
125 | \+member(Node, Visited),
126 | travel(Node, Target, [Node|Visited], Path).
127 |
128 | exists_on_path(Node, Source, Target) :-
129 | path_not_passing_by(Source, Node, Target, _),
130 | path_not_passing_by(Node, Target, Source, _),
131 | !.
132 |
133 | middle_nodes(Source, Target, NodeSet) :-
134 | findall(Node, (path_not_passing_by(Source, Node, Target, _), path_not_passing_by(Node, Target, Source, _)), NodeList),
135 | list_to_set(NodeList, NodeSet).
136 |
137 | middle_nodes_not_passing_by(Source, Target, NotPassingByNode, NodeSet) :-
138 | findall(
139 | Node,
140 | (
141 | path_not_passing_by(Source, Node, Target, Path1),
142 | not(member(NotPassingByNode, Path1)),
143 | path_not_passing_by(Node, Target, Source, Path2),
144 | not(member(NotPassingByNode, Path2))),
145 | NodeList),
146 | list_to_set(NodeList, NodeSet).
147 |
148 | single_def_single_use(Variable, Def, Use) :-
149 | localT(Variable, _, _),
150 | definitions(Variable, Defs),
151 | Defs = [Def|[]],
152 | uses(Variable, Uses),
153 | Uses = [Use|[]],
154 | not(operationT(Use, _, _, '&')),
155 | sequenceT(Sequence, _, Children),
156 | assignT(Def, Sequence, _, _),
157 | in_sequence_ancestor(Sequence, Use, UseAncestor),
158 | after(UseAncestor, Def, Children).
159 |
160 | %nearest_common_ancestor([Def, Use], CommonAncestor),
161 | %sequenceT(CommonAncestor,_, _),
162 | %in_sequence_ancestor(CommonAncestor, Def, InSeqStart),
163 | %in_sequence_ancestor(CommonAncestor, Use, InSeqEnd).
164 |
165 | condition_with_ternary_operation(Condition, Parent) :-
166 | operationT(Condition, Parent, [Lhs, Rhs], OpString),
167 | (OpString = '==' ; OpString = '!='),
168 | (ternaryOperatorT(Lhs, Condition, _, _, _); ternaryOperatorT(Rhs, Condition, _, _, _)).
169 |
170 | endless_to_while(Loop, NegatedCondition) :-
171 | loopT(Loop, _, 'endless', _, Body),
172 | sequenceT(Body, Loop, [ConditionalBreak|_]),
173 | ifT(ConditionalBreak, Body, NegatedCondition, Break, 'null'),
174 | breakT(Break, ConditionalBreak).
175 |
176 | is_assignment_to_variable(Assignment, Variable) :-
177 | assignT(Assignment, _, Lhs, _),
178 | identT(Lhs, Assignment, Variable).
179 |
180 | is_call_using_variable(Call, Variable) :-
181 | callT(Call, _, _, Parameters),
182 | identT(Ident, Call, Variable),
183 | member(Ident, Parameters).
184 |
185 | preserved_variable(Variable, StatementList) :-
186 | forall(member(Statement, StatementList),
187 | not(is_assignment_to_variable(Statement, Variable);is_call_using_variable(Statement, Variable))
188 | ).
189 |
190 | preserved_variable_list(VariableList, StatementList) :-
191 | forall(member(Variable, VariableList), preserved_variable(Variable, StatementList)).
192 |
193 |
194 | %only for renaming loop variables
195 | counting_loop(Loop, CountingVariableSet) :-
196 | ((
197 | forT(Loop, _, InitStatements, _, _, _),
198 | findall(
199 | Variable,
200 | (
201 | assignT(InitStmt, Loop, Lhs, _),
202 | member(InitStmt, InitStatements),
203 | identT(Lhs, InitStmt, Variable)
204 | ),
205 | CountingVariableList
206 | )
207 | );
208 | (
209 | loopT(Loop, _, _, LoopCondition, LoopBody),
210 | sequenceT(LoopBody, Loop, BodyChildren),
211 | findall(
212 | Variable,
213 | (
214 | localT(Variable, _, _),
215 | identT(IdentCond, _, Variable),
216 | identT(IdentBody, _, Variable),
217 | assignT(UpdateStmt, LoopBody, IdentBody, _),
218 | member(UpdateStmt, BodyChildren),
219 | ancestor_node(IdentCond, LoopCondition)
220 | ),
221 | CountingVariableList
222 | )
223 | )),
224 | list_to_set(CountingVariableList, CountingVariableSet),
225 | length(CountingVariableSet, Size),
226 | Size > 0.
227 |
228 | counting_loops(LoopList) :-
229 | findall([Loop, VariableList], counting_loop(Loop, VariableList), LoopList).
230 |
231 | array_index(Index) :-
232 | arrayIndexingT(_, _, _, Ident),
233 | identT(Ident, _, Index).
234 |
235 | is_last_in_pre_order(Node, NodeSet) :-
236 | member(Node, NodeSet),
237 | select(Node, NodeSet, Tail),
238 | forall(member(PreNode, Tail), pre_order_before(Node, PreNode)),!.
239 |
240 | dead_in_statement(Variable, Statement) :-
241 | get_all_children(Statement, Children),
242 | forall(member(Child, Children), Child \= identT(_, _, Variable)).
243 |
244 | dead_in_statements(Variable, StatementList) :-
245 | forall(member(Statement, StatementList), dead_in_statement(Variable, Statement)).
246 |
247 | variables_dead_in_statements(VariableList, StatementList) :-
248 | forall(member(Variable, VariableList), dead_in_statements(Variable, StatementList)).
249 |
250 | for_init_statement(Variable, ForLoop, InitStatement, IntermediateStatements):-
251 | findall(
252 | InitStatement,
253 | (
254 | sequenceT(Sequence, _, Children),
255 | assignT(InitStatement, Sequence, InitLhs, _),
256 | identT(InitLhs, InitStatement, Variable),
257 | member(InitStatement, Children),
258 | in_sequence_ancestor(Sequence, ForLoop, ForLoopAncestor),
259 | after(ForLoopAncestor, InitStatement, Children)
260 | ),
261 | InitStatementCandidates
262 | ),
263 | is_last_in_pre_order(InitStatement, InitStatementCandidates),
264 | middle_nodes(InitStatement, ForLoop, IntermediateStatements),
265 | dead_in_statements(Variable, IntermediateStatements).
266 |
267 | for_loop(ForLoop, ForVariableList) :-
268 | loopT(ForLoop, _, 'while', LoopCondition, LoopBody),
269 | sequenceT(LoopBody, ForLoop, BodyChildren),
270 | findall(
271 | [Variable, InitStatement, AfterInitStatements, UpdateStatement, AfterUpdateStatementList],
272 | (
273 | localT(Variable, _, _),
274 | identT(IdentCond, _, Variable),
275 | ancestor_node(IdentCond, LoopCondition),
276 | identT(IdentBody, _, Variable),
277 | assignT(UpdateStatement, LoopBody, IdentBody, _),
278 | nth0(StartIdx, BodyChildren, UpdateStatement),
279 | findall(NextStatement, (nth0(Idx, BodyChildren, NextStatement), Idx > StartIdx), AfterUpdateStatementList),
280 | dead_in_statements(Variable, AfterUpdateStatementList),
281 | for_init_statement(Variable, ForLoop, InitStatement, AfterInitStatements)
282 | ),
283 | ForVariableListDuplicates
284 | ),
285 | sort(ForVariableListDuplicates, ForVariableList),
286 | length(ForVariableList, Size),
287 | Size > 0.
288 |
289 | break_to_return(Break, BreakParent, Return) :-
290 | breakT(Break, BreakParent),
291 | cfg_edge(Break, Return),
292 | returnT(Return, _, _).
293 |
294 | %return_result(Variable) :-
295 | % findall(Ret, returnT(Ret, _, _), ReturnStmts),
296 | % list_to_set(ReturnStmts, ReturnStmtsSet),
297 | % ReturnStmtsSet = [Return|[]],
298 | % returnT(Return, _, Ident),
299 | % identT(Ident, Return, Variable),
300 | % localT(Variable, _, _).
301 |
302 | return_result(Variable) :-
303 | findall(Var, returned_variable(Var), ReturnedVars),
304 | list_to_set(ReturnedVars, ReturnedVarsSet),
305 | ReturnedVarsSet = [Variable|[]].
306 |
307 | returned_variable(Variable) :-
308 | returnT(Return, _, Ident),
309 | identT(Ident, Return, Variable),
310 | localT(Variable, _, _).
311 |
312 | memory_variable(Pointer) :-
313 | memoryT(Mem, _, Address),
314 | (
315 | (
316 | identT(Address, Mem, Pointer),
317 | localT(Pointer, _, _)
318 | );
319 | (
320 | operationT(Address, Mem, Operands, '+'),
321 | length(Operands, 2),
322 | identT(Op1, Address, Pointer),
323 | localT(Pointer, _, _),
324 | numericLiteralT(Op2, Address, _),
325 | member(Op1, Operands),
326 | member(Op2, Operands)
327 | )
328 | ).
329 |
330 | related_integer(Pointer, RelatedInteger) :-
331 | operationT(Add, _, Operands, '+'),
332 | length(Operands, 2),
333 | identT(IdentPtr, Add, Pointer),
334 | member(IdentPtr, Operands),
335 | identT(IdenInt, Add, RelatedInteger),
336 | localT(RelatedInteger, _, _),
337 | member(IdenInt, Operands),
338 | IdentPtr \= IdenInt.
339 |
340 | related_pointer(Pointer, RelatedPointer) :-
341 | assignT(Assignment, _, Lhs, Rhs),
342 | (
343 | (
344 | identT(Lhs, Assignment, Pointer),
345 | identT(Rhs, Assignment, RelatedPointer),
346 | localT(RelatedPointer, _, _)
347 | )
348 | ;(
349 | identT(Rhs, Assignment, Pointer),
350 | identT(Lhs, Assignment, RelatedPointer),
351 | localT(RelatedPointer, _, _)
352 | )
353 | ).
354 |
355 | find_declaration(Variable, Defs, Uses, CommonAncestor) :-
356 | localT(Variable, _, _),
357 | definitions(Variable, Defs),
358 | length(Defs, DefsSize),
359 | DefsSize >= 0,
360 | uses(Variable, Uses),
361 | append(Defs, Uses, Occurences),
362 | nearest_common_ancestor(Occurences, CommonAncestor).
363 |
364 | same_expression(Exp1, Exp2) :-
365 | identT(Exp1, _, V),
366 | identT(Exp2, _, V).
367 |
368 | same_expression(Exp1, Exp2) :-
369 | numericLiteralT(Exp1, _, V),
370 | numericLiteralT(Exp2, _, V).
371 |
372 | same_expression(Exp1, Exp2) :-
373 | memoryT(Exp1, _, Addr1),
374 | memoryT(Exp2, _, Addr2),
375 | same_expression(Addr1, Addr2).
376 |
377 |
378 | may_array_access(Pointer, Parent) :-
379 | memoryT(Pointer, Parent, Address),
380 | operationT(Address, Pointer, _, '+').
381 |
382 | address_expression_to_pointer(Variable, Def, Uses) :-
383 | localT(Variable, _, _),
384 | definitions(Variable, Defs),
385 | Defs = [Def|[]],
386 | uses(Variable, Uses),
387 | forall(member(Use, Uses), operationT(Use, _, _, '&')).
388 |
389 | % simplifying conditions
390 | set_all_bits_expect_first_and_last(Assign, Parent, V, Exp) :-
391 | assignT(Assign, Parent, Lhs, Rhs),
392 | identT(Lhs, Assign, V),
393 | operationT(Rhs, Assign, Operands, '&'),
394 | length(Operands, 2),
395 | numericLiteralT(Const, Rhs, 2147483649),
396 | member(Const, Operands),
397 | member(Exp, Operands),
398 | Exp \= Const.
399 |
400 | logical_and_or(Exp, Parent) :-
401 | operationT(Exp, Parent, _, Op),
402 | (Op = '||' ; Op = '&&').
403 |
404 | condition(Cond, Parent) :-
405 | ifT(Parent, _, Cond, _, _).
406 |
407 | condition(Cond, Parent) :-
408 | loopT(Parent, _, _, Cond, _).
409 |
410 | condition(Cond, Parent) :-
411 | ternaryOperatorT(Parent, _, Cond, _, _).
412 |
413 | condition(Cond, Parent) :-
414 | assignT(Parent, _, _, Cond),
415 | operationT(Cond, Parent, _, Op),
416 | (Op = '||' ; Op = '&&'; Op = '=='; Op = '!='; Op = '>='; Op = '>'; Op = '<='; Op = '<').
417 |
418 | equality_comparison(Exp, Parent) :-
419 | operationT(Exp, Parent, _, Op),
420 | (Op = '!=' ; Op = '==').
421 |
422 | if_do_while(ParentId, If, DoWhile) :-
423 | ifT(If, ParentId, _, DoWhile, 'null'),
424 | loopT(DoWhile, If, 'doWhile', _, _).
425 |
426 | if_do_while_init(ParentId, If, DoWhile) :-
427 | ifT(If, ParentId, IfCondition, DoWhile, 'null'),
428 | loopT(DoWhile, If, 'doWhile', LoopCondition, _),
429 | operationT(LoopCondition, DoWhile, [Ident1, Ident2], '<'),
430 | identT(Ident1, LoopCondition, Var1),
431 | identT(Ident2, LoopCondition, Var2),
432 | operationT(IfCondition, If, [Ident3, Zero], Op),
433 | identT(Ident3, IfCondition, Var2),
434 | numericLiteralT(Zero, IfCondition, 0),
435 | (Op = '!=' ; Op = '>'),
436 | sequenceT(ParentId, _, Ops),
437 | findall(Def, (assignT(Def, ParentId, Lhs, _), identT(Lhs, Def, Var1), member(Def, Ops), after(If, Def, Ops)), DefsInSequence),
438 | DefsInSequence = [Init|[]],
439 | assignT(Init, ParentId, _, Zero2),
440 | numericLiteralT(Zero2, Init, 0).
441 |
442 | do_while_to_while(ParentId, DoWhile, Init) :-
443 | loopT(DoWhile, ParentId, 'doWhile', LoopCondition, _),
444 | operationT(LoopCondition, DoWhile, [Ident1, Const1], _),
445 | identT(Ident1, LoopCondition, Var1),
446 | numericLiteralT(Const1, LoopCondition, _),
447 | sequenceT(ParentId, _, Ops),
448 | findall(Def, (assignT(Def, ParentId, Lhs, _), identT(Lhs, Def, Var1), member(Def, Ops), after(DoWhile, Def, Ops)), DefsInSequence),
449 | DefsInSequence = [Init|[]],
450 | assignT(Init, ParentId, _, Const2),
451 | numericLiteralT(Const2, Init, _).
452 |
453 | shift_expression(Shift, ParentId) :-
454 | operationT(Shift, ParentId, [_, Const], Op),
455 | (Op = '>>' ; Op = '<<'),
456 | numericLiteralT(Const, Shift, _).
457 |
458 | for_loop(ForLoop) :-
459 | forT(ForLoop, _, _, _, _, _).
460 |
461 | nested_for_loops(UpperStmt, InnerForLoops) :-
462 | findall(ForLoop, (for_loop(ForLoop), ancestor_node(ForLoop, UpperStmt)), InnerForLoops).
463 |
464 | only_used_in_statement(Variable, Stmt) :-
465 | uses(Variable, Uses),
466 | forall(member(Use, Uses), ancestor_node(Use, Stmt)).
--------------------------------------------------------------------------------
/dream/prolog/named_constants_rules.pl:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2011-2017 Khaled Yakdan.
3 | * All rights reserved.
4 | */
5 |
6 | named_constant_compare(Value, Compare) :-
7 | operationT(Compare, _, [_, Const], Op),
8 | numericLiteralT(Const, Compare, Num),
9 | Num = Value,
10 | (Op = '==' ; Op = '!=').
--------------------------------------------------------------------------------
/dream/prolog/predicates.pl:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2011-2017 Khaled Yakdan.
3 | * All rights reserved.
4 | */
5 |
6 | :- dynamic sequenceT/3.
7 | :- dynamic loopT/5.
8 | :- dynamic forT/6.
9 | :- dynamic ifT/5.
10 | :- dynamic switchT/4.
11 | :- dynamic caseT/4.
12 | :- dynamic assignT/4.
13 | :- dynamic callT/4.
14 | :- dynamic returnT/3.
15 | :- dynamic operationT/4.
16 | :- dynamic ternaryOperatorT/5.
17 | :- dynamic numericLiteralT/3.
18 | :- dynamic stringLiteralT/3.
19 | :- dynamic memoryT/3.
20 | :- dynamic localT/3.
21 | :- dynamic globalT/3.
22 | :- dynamic identT/3.
23 | :- dynamic logicSymbolT/3.
24 | :- dynamic arrayIndexingT/4.
25 | :- dynamic breakT/2.
--------------------------------------------------------------------------------
/dream/prolog/queries:
--------------------------------------------------------------------------------
1 | memcpy_1(ParentId, Id_0, ChildrenIds, Transformation, Dst, Src, Len)
2 | memcpy_2(ParentId, Id_0, ChildrenIds, Transformation, Dst, Src, Len)
3 | memcpy_3(ParentId, Id_0, ChildrenIds, Transformation, Dst, Src, Len)
4 | memcpy_4(ParentId, Id_0, ChildrenIds, Transformation, Dst, Src, Len)
5 | strlen_w(ParentId, Id_0, ChildrenIds, Transformation, Len, Str)
6 | strlen_1(ParentId, Id_0, ChildrenIds, Transformation, Len, Str)
7 | strlen_2(ParentId, Id_0, ChildrenIds, Transformation, Len, Str)
8 | wcscmp(ParentId, Id_0, ChildrenIds, Transformation, Wsstr1, Wcstr2, Num, Result)
9 | strncmpi_1(ParentId, Id_0, ChildrenIds, Transformation, Str1, Str2, Result, X)
10 | two_cond(ParentId, Id_0, ChildrenIds, Transformation, A, B, N)
11 | ternary_op(ParentId, Id_0, ChildrenIds, Transformation, Cond, X, V1, V2)
12 | memset_1(ParentId, Id_0, ChildrenIds, Transformation, Ptr, Value, Num)
13 | compund_condition(ParentId, Id_0, ChildrenIds, Transformation, V, Conda, Condb1, Condb2)
14 | parity_1(ParentId, Id_0, ChildrenIds, Transformation, V)
15 |
--------------------------------------------------------------------------------
/dream/prolog/rules.pl:
--------------------------------------------------------------------------------
1 | memcpy_1(ParentId, Id_0, ChildrenIds, Transformation, Dst, Src, Len) :-
2 | Transformation = 'memcpy(dst, src, len);',
3 | sequenceT(Id_0, ParentId, Id_1),
4 | ChildrenIds = [Id_2, Id_3, Id_4],
5 | assignT(Id_2, Id_0, Id_5, Id_6),
6 | identT(Id_5, Id_2, K),
7 | Len = Id_6,
8 | assignT(Id_3, Id_0, Id_7, Id_8),
9 | identT(Id_7, Id_3, D),
10 | Dst = Id_8,
11 | directly_after(Id_3, Id_2, Id_1),
12 | ifT(Id_4, Id_0, Id_9, Id_10, 'null'),
13 | operationT(Id_9, Id_4, Id_11, '!='),
14 | length(Id_11, 2),
15 | identT(Id_12, Id_9, K),
16 | member(Id_12, Id_11),
17 | numericLiteralT(Id_13, Id_9, 0),
18 | member(Id_13, Id_11),
19 | directly_after(Id_13, Id_12, Id_11),
20 | Id_12 \= Id_13,
21 | sequenceT(Id_10, Id_4, Id_14),
22 | length(Id_14, 2),
23 | assignT(Id_15, Id_10, Id_17, Id_18),
24 | identT(Id_17, Id_15, X),
25 | operationT(Id_18, Id_15, Id_19, '+'),
26 | length(Id_19, 2),
27 | Src = Id_20,
28 | member(Id_20, Id_19),
29 | operationT(Id_21, Id_18, Id_22, '-'),
30 | length(Id_22, 1),
31 | Dst2 = Id_23,
32 | member(Id_23, Id_22),
33 | member(Id_21, Id_19),
34 | Id_20 \= Id_21,
35 | loopT(Id_16, Id_10, 'doWhile', Id_24, Id_25),
36 | operationT(Id_24, Id_16, Id_26, '!='),
37 | length(Id_26, 2),
38 | identT(Id_27, Id_24, K),
39 | member(Id_27, Id_26),
40 | numericLiteralT(Id_28, Id_24, 0),
41 | member(Id_28, Id_26),
42 | directly_after(Id_28, Id_27, Id_26),
43 | Id_27 \= Id_28,
44 | sequenceT(Id_25, Id_16, Id_29),
45 | length(Id_29, 4),
46 | assignT(Id_30, Id_25, Id_34, Id_35),
47 | identT(Id_34, Id_30, C),
48 | memoryT(Id_35, Id_30, Id_36),
49 | operationT(Id_36, Id_35, Id_37, '+'),
50 | length(Id_37, 2),
51 | identT(Id_38, Id_36, X),
52 | member(Id_38, Id_37),
53 | identT(Id_39, Id_36, D),
54 | member(Id_39, Id_37),
55 | Id_38 \= Id_39,
56 | assignT(Id_31, Id_25, Id_40, Id_41),
57 | memoryT(Id_40, Id_31, Id_42),
58 | identT(Id_42, Id_40, D),
59 | identT(Id_41, Id_31, C),
60 | directly_after(Id_31, Id_30, Id_29),
61 | assignT(Id_32, Id_25, Id_43, Id_44),
62 | identT(Id_43, Id_32, D),
63 | operationT(Id_44, Id_32, Id_45, '+'),
64 | length(Id_45, 2),
65 | identT(Id_46, Id_44, D),
66 | member(Id_46, Id_45),
67 | numericLiteralT(Id_47, Id_44, 1),
68 | member(Id_47, Id_45),
69 | Id_46 \= Id_47,
70 | directly_after(Id_32, Id_31, Id_29),
71 | assignT(Id_33, Id_25, Id_48, Id_49),
72 | identT(Id_48, Id_33, K),
73 | operationT(Id_49, Id_33, Id_50, '+'),
74 | length(Id_50, 2),
75 | identT(Id_51, Id_49, K),
76 | member(Id_51, Id_50),
77 | numericLiteralT(Id_52, Id_49, -1),
78 | member(Id_52, Id_50),
79 | Id_51 \= Id_52,
80 | directly_after(Id_33, Id_32, Id_29),
81 | directly_after(Id_16, Id_15, Id_14),
82 | directly_after(Id_4, Id_3, Id_1),
83 | same_expression(Dst, Dst2),
84 | C \= X,
85 | C \= K,
86 | C \= D,
87 | X \= K,
88 | X \= D,
89 | K \= D.
90 |
91 | memcpy_2(ParentId, Id_0, ChildrenIds, Transformation, Dst, Src, Len) :-
92 | Transformation = 'memcpy(dst, src, len);',
93 | sequenceT(Id_0, ParentId, Id_1),
94 | ChildrenIds = [Id_2, Id_3, Id_4],
95 | assignT(Id_2, Id_0, Id_5, Id_6),
96 | identT(Id_5, Id_2, Len_Cpy),
97 | Len = Id_6,
98 | assignT(Id_3, Id_0, Id_7, Id_8),
99 | identT(Id_7, Id_3, Src_Cpy),
100 | Src = Id_8,
101 | directly_after(Id_3, Id_2, Id_1),
102 | ifT(Id_4, Id_0, Id_9, Id_10, 'null'),
103 | operationT(Id_9, Id_4, Id_11, '!='),
104 | length(Id_11, 2),
105 | identT(Id_12, Id_9, Len_Cpy),
106 | member(Id_12, Id_11),
107 | numericLiteralT(Id_13, Id_9, 0),
108 | member(Id_13, Id_11),
109 | directly_after(Id_13, Id_12, Id_11),
110 | Id_12 \= Id_13,
111 | sequenceT(Id_10, Id_4, Id_14),
112 | length(Id_14, 4),
113 | assignT(Id_15, Id_10, Id_19, Id_20),
114 | identT(Id_19, Id_15, A),
115 | identT(Id_20, Id_15, Dst),
116 | assignT(Id_16, Id_10, Id_21, Id_22),
117 | identT(Id_21, Id_16, D),
118 | operationT(Id_22, Id_16, Id_23, '+'),
119 | length(Id_23, 2),
120 | identT(Id_24, Id_22, Src_Cpy),
121 | member(Id_24, Id_23),
122 | operationT(Id_25, Id_22, Id_26, '-'),
123 | length(Id_26, 1),
124 | identT(Id_27, Id_25, Dst),
125 | member(Id_27, Id_26),
126 | member(Id_25, Id_23),
127 | Id_24 \= Id_25,
128 | directly_after(Id_16, Id_15, Id_14),
129 | assignT(Id_17, Id_10, Id_28, Id_29),
130 | identT(Id_28, Id_17, I),
131 | identT(Id_29, Id_17, Len_Cpy),
132 | directly_after(Id_17, Id_16, Id_14),
133 | loopT(Id_18, Id_10, 'doWhile', Id_30, Id_31),
134 | operationT(Id_30, Id_18, Id_32, '!='),
135 | length(Id_32, 2),
136 | identT(Id_33, Id_30, I),
137 | member(Id_33, Id_32),
138 | numericLiteralT(Id_34, Id_30, 0),
139 | member(Id_34, Id_32),
140 | directly_after(Id_34, Id_33, Id_32),
141 | Id_33 \= Id_34,
142 | sequenceT(Id_31, Id_18, Id_35),
143 | length(Id_35, 3),
144 | assignT(Id_36, Id_31, Id_39, Id_40),
145 | memoryT(Id_39, Id_36, Id_41),
146 | identT(Id_41, Id_39, A),
147 | memoryT(Id_40, Id_36, Id_42),
148 | operationT(Id_42, Id_40, Id_43, '+'),
149 | length(Id_43, 2),
150 | identT(Id_44, Id_42, D),
151 | member(Id_44, Id_43),
152 | identT(Id_45, Id_42, A),
153 | member(Id_45, Id_43),
154 | Id_44 \= Id_45,
155 | assignT(Id_37, Id_31, Id_46, Id_47),
156 | identT(Id_46, Id_37, A),
157 | operationT(Id_47, Id_37, Id_48, '+'),
158 | length(Id_48, 2),
159 | identT(Id_49, Id_47, A),
160 | member(Id_49, Id_48),
161 | numericLiteralT(Id_50, Id_47, 1),
162 | member(Id_50, Id_48),
163 | Id_49 \= Id_50,
164 | directly_after(Id_37, Id_36, Id_35),
165 | assignT(Id_38, Id_31, Id_51, Id_52),
166 | identT(Id_51, Id_38, I),
167 | operationT(Id_52, Id_38, Id_53, '+'),
168 | length(Id_53, 2),
169 | identT(Id_54, Id_52, I),
170 | member(Id_54, Id_53),
171 | numericLiteralT(Id_55, Id_52, -1),
172 | member(Id_55, Id_53),
173 | Id_54 \= Id_55,
174 | directly_after(Id_38, Id_37, Id_35),
175 | directly_after(Id_18, Id_17, Id_14),
176 | directly_after(Id_4, Id_3, Id_1),
177 | A \= D,
178 | A \= Src_Cpy,
179 | A \= I,
180 | A \= Dst,
181 | A \= Len_Cpy,
182 | D \= Src_Cpy,
183 | D \= I,
184 | D \= Dst,
185 | D \= Len_Cpy,
186 | Src_Cpy \= I,
187 | Src_Cpy \= Dst,
188 | Src_Cpy \= Len_Cpy,
189 | I \= Dst,
190 | I \= Len_Cpy,
191 | Dst \= Len_Cpy.
192 |
193 | memcpy_3(ParentId, Id_0, ChildrenIds, Transformation, Dst, Src, Len) :-
194 | Transformation = 'memcpy(dst, src, len);',
195 | sequenceT(Id_0, ParentId, Id_1),
196 | ChildrenIds = [Id_2, Id_3],
197 | assignT(Id_2, Id_0, Id_4, Id_5),
198 | identT(Id_4, Id_2, D),
199 | operationT(Id_5, Id_2, Id_6, '+'),
200 | length(Id_6, 2),
201 | Src = Id_7,
202 | member(Id_7, Id_6),
203 | operationT(Id_8, Id_5, Id_9, '-'),
204 | length(Id_9, 1),
205 | identT(Id_10, Id_8, Dst),
206 | member(Id_10, Id_9),
207 | member(Id_8, Id_6),
208 | Id_7 \= Id_8,
209 | loopT(Id_3, Id_0, 'doWhile', Id_11, Id_12),
210 | operationT(Id_11, Id_3, Id_13, '!='),
211 | length(Id_13, 2),
212 | identT(Id_14, Id_11, Len),
213 | member(Id_14, Id_13),
214 | numericLiteralT(Id_15, Id_11, 0),
215 | member(Id_15, Id_13),
216 | directly_after(Id_15, Id_14, Id_13),
217 | Id_14 \= Id_15,
218 | sequenceT(Id_12, Id_3, Id_16),
219 | length(Id_16, 4),
220 | assignT(Id_17, Id_12, Id_21, Id_22),
221 | identT(Id_21, Id_17, C),
222 | memoryT(Id_22, Id_17, Id_23),
223 | operationT(Id_23, Id_22, Id_24, '+'),
224 | length(Id_24, 2),
225 | identT(Id_25, Id_23, D),
226 | member(Id_25, Id_24),
227 | identT(Id_26, Id_23, Dst),
228 | member(Id_26, Id_24),
229 | Id_25 \= Id_26,
230 | assignT(Id_18, Id_12, Id_27, Id_28),
231 | memoryT(Id_27, Id_18, Id_29),
232 | identT(Id_29, Id_27, Dst),
233 | identT(Id_28, Id_18, C),
234 | directly_after(Id_18, Id_17, Id_16),
235 | assignT(Id_19, Id_12, Id_30, Id_31),
236 | identT(Id_30, Id_19, Dst),
237 | operationT(Id_31, Id_19, Id_32, '+'),
238 | length(Id_32, 2),
239 | identT(Id_33, Id_31, Dst),
240 | member(Id_33, Id_32),
241 | numericLiteralT(Id_34, Id_31, 1),
242 | member(Id_34, Id_32),
243 | Id_33 \= Id_34,
244 | directly_after(Id_19, Id_18, Id_16),
245 | assignT(Id_20, Id_12, Id_35, Id_36),
246 | identT(Id_35, Id_20, Len),
247 | operationT(Id_36, Id_20, Id_37, '+'),
248 | length(Id_37, 2),
249 | identT(Id_38, Id_36, Len),
250 | member(Id_38, Id_37),
251 | numericLiteralT(Id_39, Id_36, -1),
252 | member(Id_39, Id_37),
253 | Id_38 \= Id_39,
254 | directly_after(Id_20, Id_19, Id_16),
255 | directly_after(Id_3, Id_2, Id_1),
256 | C \= Dst,
257 | C \= D,
258 | C \= Len,
259 | Dst \= D,
260 | Dst \= Len,
261 | D \= Len.
262 |
263 | memcpy_4(ParentId, Id_0, ChildrenIds, Transformation, Dst, Src, Len) :-
264 | Transformation = 'memcpy(dst, src, len);',
265 | sequenceT(Id_0, ParentId, Id_1),
266 | ChildrenIds = [Id_2, Id_3, Id_4],
267 | assignT(Id_2, Id_0, Id_5, Id_6),
268 | identT(Id_5, Id_2, D),
269 | operationT(Id_6, Id_2, Id_7, '+'),
270 | length(Id_7, 2),
271 | Src = Id_8,
272 | member(Id_8, Id_7),
273 | operationT(Id_9, Id_6, Id_10, '-'),
274 | length(Id_10, 1),
275 | identT(Id_11, Id_9, Dst),
276 | member(Id_11, Id_10),
277 | member(Id_9, Id_7),
278 | Id_8 \= Id_9,
279 | assignT(Id_3, Id_0, Id_12, Id_13),
280 | identT(Id_12, Id_3, I),
281 | Len = Id_13,
282 | directly_after(Id_3, Id_2, Id_1),
283 | loopT(Id_4, Id_0, 'doWhile', Id_14, Id_15),
284 | operationT(Id_14, Id_4, Id_16, '!='),
285 | length(Id_16, 2),
286 | identT(Id_17, Id_14, I),
287 | member(Id_17, Id_16),
288 | numericLiteralT(Id_18, Id_14, 0),
289 | member(Id_18, Id_16),
290 | directly_after(Id_18, Id_17, Id_16),
291 | Id_17 \= Id_18,
292 | sequenceT(Id_15, Id_4, Id_19),
293 | length(Id_19, 4),
294 | assignT(Id_20, Id_15, Id_24, Id_25),
295 | identT(Id_24, Id_20, C),
296 | memoryT(Id_25, Id_20, Id_26),
297 | operationT(Id_26, Id_25, Id_27, '+'),
298 | length(Id_27, 2),
299 | identT(Id_28, Id_26, D),
300 | member(Id_28, Id_27),
301 | identT(Id_29, Id_26, Dst),
302 | member(Id_29, Id_27),
303 | Id_28 \= Id_29,
304 | assignT(Id_21, Id_15, Id_30, Id_31),
305 | memoryT(Id_30, Id_21, Id_32),
306 | identT(Id_32, Id_30, Dst),
307 | identT(Id_31, Id_21, C),
308 | directly_after(Id_21, Id_20, Id_19),
309 | assignT(Id_22, Id_15, Id_33, Id_34),
310 | identT(Id_33, Id_22, Dst),
311 | operationT(Id_34, Id_22, Id_35, '+'),
312 | length(Id_35, 2),
313 | identT(Id_36, Id_34, Dst),
314 | member(Id_36, Id_35),
315 | numericLiteralT(Id_37, Id_34, 1),
316 | member(Id_37, Id_35),
317 | Id_36 \= Id_37,
318 | directly_after(Id_22, Id_21, Id_19),
319 | assignT(Id_23, Id_15, Id_38, Id_39),
320 | identT(Id_38, Id_23, I),
321 | operationT(Id_39, Id_23, Id_40, '+'),
322 | length(Id_40, 2),
323 | identT(Id_41, Id_39, I),
324 | member(Id_41, Id_40),
325 | numericLiteralT(Id_42, Id_39, -1),
326 | member(Id_42, Id_40),
327 | Id_41 \= Id_42,
328 | directly_after(Id_23, Id_22, Id_19),
329 | directly_after(Id_4, Id_3, Id_1),
330 | I \= C,
331 | I \= Dst,
332 | I \= D,
333 | C \= Dst,
334 | C \= D,
335 | Dst \= D.
336 |
337 | strlen_w(ParentId, Id_0, ChildrenIds, Transformation, Len, Str) :-
338 | Transformation = 'len = wclen(str);',
339 | sequenceT(Id_0, ParentId, Id_1),
340 | ChildrenIds = [Id_2, Id_3],
341 | assignT(Id_2, Id_0, Id_4, Id_5),
342 | identT(Id_4, Id_2, Len),
343 | numericLiteralT(Id_5, Id_2, 0),
344 | ifT(Id_3, Id_0, Id_6, Id_7, 'null'),
345 | operationT(Id_6, Id_3, Id_8, '!='),
346 | length(Id_8, 2),
347 | memoryT(Id_9, Id_6, Id_11),
348 | identT(Id_11, Id_9, Str),
349 | member(Id_9, Id_8),
350 | identT(Id_10, Id_6, Len),
351 | member(Id_10, Id_8),
352 | directly_after(Id_10, Id_9, Id_8),
353 | Id_9 \= Id_10,
354 | loopT(Id_7, Id_3, 'doWhile', Id_12, Id_13),
355 | operationT(Id_12, Id_7, Id_14, '!='),
356 | length(Id_14, 2),
357 | memoryT(Id_15, Id_12, Id_17),
358 | operationT(Id_17, Id_15, Id_18, '+'),
359 | length(Id_18, 2),
360 | identT(Id_19, Id_17, Str),
361 | member(Id_19, Id_18),
362 | operationT(Id_20, Id_17, Id_21, '*'),
363 | length(Id_21, 2),
364 | identT(Id_22, Id_20, Len),
365 | member(Id_22, Id_21),
366 | numericLiteralT(Id_23, Id_20, 2),
367 | member(Id_23, Id_21),
368 | Id_22 \= Id_23,
369 | member(Id_20, Id_18),
370 | Id_19 \= Id_20,
371 | member(Id_15, Id_14),
372 | numericLiteralT(Id_16, Id_12, 0),
373 | member(Id_16, Id_14),
374 | directly_after(Id_16, Id_15, Id_14),
375 | Id_15 \= Id_16,
376 | assignT(Id_13, Id_7, Id_24, Id_25),
377 | identT(Id_24, Id_13, Len),
378 | operationT(Id_25, Id_13, Id_26, '+'),
379 | length(Id_26, 2),
380 | identT(Id_27, Id_25, Len),
381 | member(Id_27, Id_26),
382 | numericLiteralT(Id_28, Id_25, 1),
383 | member(Id_28, Id_26),
384 | Id_27 \= Id_28,
385 | directly_after(Id_3, Id_2, Id_1),
386 | Str \= Len.
387 |
388 | strlen_1(ParentId, Id_0, ChildrenIds, Transformation, Len, Str) :-
389 | Transformation = 'len = wclen(str);',
390 | sequenceT(Id_0, ParentId, Id_1),
391 | ChildrenIds = [Id_2, Id_3],
392 | ifT(Id_2, Id_0, Id_4, Id_5, 'null'),
393 | operationT(Id_4, Id_2, Id_6, '!='),
394 | length(Id_6, 2),
395 | memoryT(Id_7, Id_4, Id_9),
396 | identT(Id_9, Id_7, Str),
397 | member(Id_7, Id_6),
398 | identT(Id_8, Id_4, Len),
399 | member(Id_8, Id_6),
400 | directly_after(Id_8, Id_7, Id_6),
401 | Id_7 \= Id_8,
402 | loopT(Id_5, Id_2, 'doWhile', Id_10, Id_11),
403 | operationT(Id_10, Id_5, Id_12, '!='),
404 | length(Id_12, 2),
405 | memoryT(Id_13, Id_10, Id_15),
406 | operationT(Id_15, Id_13, Id_16, '+'),
407 | length(Id_16, 2),
408 | identT(Id_17, Id_15, Str),
409 | member(Id_17, Id_16),
410 | identT(Id_18, Id_15, Len),
411 | member(Id_18, Id_16),
412 | Id_17 \= Id_18,
413 | member(Id_13, Id_12),
414 | numericLiteralT(Id_14, Id_10, 0),
415 | member(Id_14, Id_12),
416 | directly_after(Id_14, Id_13, Id_12),
417 | Id_13 \= Id_14,
418 | assignT(Id_11, Id_5, Id_19, Id_20),
419 | identT(Id_19, Id_11, Len),
420 | operationT(Id_20, Id_11, Id_21, '+'),
421 | length(Id_21, 2),
422 | identT(Id_22, Id_20, Len),
423 | member(Id_22, Id_21),
424 | numericLiteralT(Id_23, Id_20, 1),
425 | member(Id_23, Id_21),
426 | Id_22 \= Id_23,
427 | assignT(Id_3, Id_0, Id_24, Id_25),
428 | identT(Id_24, Id_3, Len),
429 | operationT(Id_25, Id_3, Id_26, '+'),
430 | length(Id_26, 2),
431 | identT(Id_27, Id_25, Len),
432 | member(Id_27, Id_26),
433 | numericLiteralT(Id_28, Id_25, -1),
434 | member(Id_28, Id_26),
435 | Id_27 \= Id_28,
436 | directly_after(Id_3, Id_2, Id_1),
437 | Len \= Str.
438 |
439 | strlen_2(ParentId, Id_0, ChildrenIds, Transformation, Len, Str) :-
440 | Transformation = 'len = strlen(str);',
441 | sequenceT(Id_0, ParentId, Id_1),
442 | ChildrenIds = [Id_2, Id_3],
443 | assignT(Id_2, Id_0, Id_4, Id_5),
444 | identT(Id_4, Id_2, Len),
445 | numericLiteralT(Id_5, Id_2, 0),
446 | ifT(Id_3, Id_0, Id_6, Id_7, 'null'),
447 | operationT(Id_6, Id_3, Id_8, '!='),
448 | length(Id_8, 2),
449 | memoryT(Id_9, Id_6, Id_11),
450 | identT(Id_11, Id_9, Str),
451 | member(Id_9, Id_8),
452 | identT(Id_10, Id_6, Len),
453 | member(Id_10, Id_8),
454 | directly_after(Id_10, Id_9, Id_8),
455 | Id_9 \= Id_10,
456 | loopT(Id_7, Id_3, 'doWhile', Id_12, Id_13),
457 | operationT(Id_12, Id_7, Id_14, '!='),
458 | length(Id_14, 2),
459 | memoryT(Id_15, Id_12, Id_17),
460 | operationT(Id_17, Id_15, Id_18, '+'),
461 | length(Id_18, 2),
462 | identT(Id_19, Id_17, Str),
463 | member(Id_19, Id_18),
464 | identT(Id_20, Id_17, Len),
465 | member(Id_20, Id_18),
466 | Id_19 \= Id_20,
467 | member(Id_15, Id_14),
468 | numericLiteralT(Id_16, Id_12, 0),
469 | member(Id_16, Id_14),
470 | directly_after(Id_16, Id_15, Id_14),
471 | Id_15 \= Id_16,
472 | assignT(Id_13, Id_7, Id_21, Id_22),
473 | identT(Id_21, Id_13, Len),
474 | operationT(Id_22, Id_13, Id_23, '+'),
475 | length(Id_23, 2),
476 | identT(Id_24, Id_22, Len),
477 | member(Id_24, Id_23),
478 | numericLiteralT(Id_25, Id_22, 1),
479 | member(Id_25, Id_23),
480 | Id_24 \= Id_25,
481 | directly_after(Id_3, Id_2, Id_1),
482 | Str \= Len.
483 |
484 | wcscmp(ParentId, Id_0, ChildrenIds, Transformation, Wsstr1, Wcstr2, Num, Result) :-
485 | Transformation = 'result = wcscmp(wsStr1, wcStr2);',
486 | loopT(Id_0, ParentId, 'doWhile', Id_1, Id_2),
487 | operationT(Id_1, Id_0, Id_3, '<'),
488 | length(Id_3, 2),
489 | identT(Id_4, Id_1, Wsstr1),
490 | member(Id_4, Id_3),
491 | identT(Id_5, Id_1, Num),
492 | member(Id_5, Id_3),
493 | directly_after(Id_5, Id_4, Id_3),
494 | Id_4 \= Id_5,
495 | sequenceT(Id_2, Id_0, Id_6),
496 | length(Id_6, 8),
497 | assignT(Id_7, Id_2, Id_15, Id_16),
498 | identT(Id_15, Id_7, C1),
499 | memoryT(Id_16, Id_7, Id_17),
500 | identT(Id_17, Id_16, Wsstr1),
501 | ifT(Id_8, Id_2, Id_18, Id_19, Id_20),
502 | operationT(Id_18, Id_8, Id_21, '||'),
503 | length(Id_21, 2),
504 | operationT(Id_22, Id_18, Id_24, '<'),
505 | length(Id_24, 2),
506 | identT(Id_25, Id_22, C1),
507 | member(Id_25, Id_24),
508 | numericLiteralT(Id_26, Id_22, 65),
509 | member(Id_26, Id_24),
510 | directly_after(Id_26, Id_25, Id_24),
511 | Id_25 \= Id_26,
512 | member(Id_22, Id_21),
513 | operationT(Id_23, Id_18, Id_27, '>'),
514 | length(Id_27, 2),
515 | identT(Id_28, Id_23, C1),
516 | member(Id_28, Id_27),
517 | numericLiteralT(Id_29, Id_23, 90),
518 | member(Id_29, Id_27),
519 | directly_after(Id_29, Id_28, Id_27),
520 | Id_28 \= Id_29,
521 | member(Id_23, Id_21),
522 | Id_22 \= Id_23,
523 | assignT(Id_19, Id_8, Id_30, Id_31),
524 | identT(Id_30, Id_19, V1),
525 | identT(Id_31, Id_19, C1),
526 | assignT(Id_20, Id_8, Id_32, Id_33),
527 | identT(Id_32, Id_20, V1),
528 | operationT(Id_33, Id_20, Id_34, '+'),
529 | length(Id_34, 2),
530 | identT(Id_35, Id_33, C1),
531 | member(Id_35, Id_34),
532 | numericLiteralT(Id_36, Id_33, 32),
533 | member(Id_36, Id_34),
534 | Id_35 \= Id_36,
535 | directly_after(Id_8, Id_7, Id_6),
536 | assignT(Id_9, Id_2, Id_37, Id_38),
537 | identT(Id_37, Id_9, C2),
538 | memoryT(Id_38, Id_9, Id_39),
539 | identT(Id_39, Id_38, Wcstr2),
540 | directly_after(Id_9, Id_8, Id_6),
541 | ifT(Id_10, Id_2, Id_40, Id_41, Id_42),
542 | operationT(Id_40, Id_10, Id_43, '||'),
543 | length(Id_43, 2),
544 | operationT(Id_44, Id_40, Id_46, '<'),
545 | length(Id_46, 2),
546 | identT(Id_47, Id_44, C2),
547 | member(Id_47, Id_46),
548 | numericLiteralT(Id_48, Id_44, 65),
549 | member(Id_48, Id_46),
550 | directly_after(Id_48, Id_47, Id_46),
551 | Id_47 \= Id_48,
552 | member(Id_44, Id_43),
553 | operationT(Id_45, Id_40, Id_49, '>'),
554 | length(Id_49, 2),
555 | identT(Id_50, Id_45, C2),
556 | member(Id_50, Id_49),
557 | numericLiteralT(Id_51, Id_45, 90),
558 | member(Id_51, Id_49),
559 | directly_after(Id_51, Id_50, Id_49),
560 | Id_50 \= Id_51,
561 | member(Id_45, Id_43),
562 | Id_44 \= Id_45,
563 | assignT(Id_41, Id_10, Id_52, Id_53),
564 | identT(Id_52, Id_41, V2),
565 | identT(Id_53, Id_41, C2),
566 | assignT(Id_42, Id_10, Id_54, Id_55),
567 | identT(Id_54, Id_42, V2),
568 | operationT(Id_55, Id_42, Id_56, '+'),
569 | length(Id_56, 2),
570 | identT(Id_57, Id_55, C2),
571 | member(Id_57, Id_56),
572 | numericLiteralT(Id_58, Id_55, 32),
573 | member(Id_58, Id_56),
574 | Id_57 \= Id_58,
575 | directly_after(Id_10, Id_9, Id_6),
576 | assignT(Id_11, Id_2, Id_59, Id_60),
577 | identT(Id_59, Id_11, Result),
578 | operationT(Id_60, Id_11, Id_61, '+'),
579 | length(Id_61, 2),
580 | identT(Id_62, Id_60, V1),
581 | member(Id_62, Id_61),
582 | operationT(Id_63, Id_60, Id_64, '-'),
583 | length(Id_64, 1),
584 | identT(Id_65, Id_63, V2),
585 | member(Id_65, Id_64),
586 | member(Id_63, Id_61),
587 | Id_62 \= Id_63,
588 | directly_after(Id_11, Id_10, Id_6),
589 | ifT(Id_12, Id_2, Id_66, Id_67, 'null'),
590 | operationT(Id_66, Id_12, Id_68, '!='),
591 | length(Id_68, 2),
592 | identT(Id_69, Id_66, Result),
593 | member(Id_69, Id_68),
594 | numericLiteralT(Id_70, Id_66, 0),
595 | member(Id_70, Id_68),
596 | directly_after(Id_70, Id_69, Id_68),
597 | Id_69 \= Id_70,
598 | returnT(Id_67, Id_12, Id_71),
599 | identT(Id_71, Id_67, Result),
600 | directly_after(Id_12, Id_11, Id_6),
601 | assignT(Id_13, Id_2, Id_72, Id_73),
602 | identT(Id_72, Id_13, Wsstr1),
603 | operationT(Id_73, Id_13, Id_74, '+'),
604 | length(Id_74, 2),
605 | identT(Id_75, Id_73, Wsstr1),
606 | member(Id_75, Id_74),
607 | numericLiteralT(Id_76, Id_73, 2),
608 | member(Id_76, Id_74),
609 | Id_75 \= Id_76,
610 | directly_after(Id_13, Id_12, Id_6),
611 | assignT(Id_14, Id_2, Id_77, Id_78),
612 | identT(Id_77, Id_14, Wcstr2),
613 | operationT(Id_78, Id_14, Id_79, '+'),
614 | length(Id_79, 2),
615 | identT(Id_80, Id_78, Wcstr2),
616 | member(Id_80, Id_79),
617 | numericLiteralT(Id_81, Id_78, 2),
618 | member(Id_81, Id_79),
619 | Id_80 \= Id_81,
620 | directly_after(Id_14, Id_13, Id_6),
621 | Wsstr1 \= V1,
622 | Wsstr1 \= Wcstr2,
623 | Wsstr1 \= V2,
624 | Wsstr1 \= Num,
625 | Wsstr1 \= Result,
626 | Wsstr1 \= C2,
627 | Wsstr1 \= C1,
628 | V1 \= Wcstr2,
629 | V1 \= V2,
630 | V1 \= Num,
631 | V1 \= Result,
632 | V1 \= C2,
633 | V1 \= C1,
634 | Wcstr2 \= V2,
635 | Wcstr2 \= Num,
636 | Wcstr2 \= Result,
637 | Wcstr2 \= C2,
638 | Wcstr2 \= C1,
639 | V2 \= Num,
640 | V2 \= Result,
641 | V2 \= C2,
642 | V2 \= C1,
643 | Num \= Result,
644 | Num \= C2,
645 | Num \= C1,
646 | Result \= C2,
647 | Result \= C1,
648 | C2 \= C1.
649 |
650 | strncmpi_1(ParentId, Id_0, ChildrenIds, Transformation, Str1, Str2, Result, X) :-
651 | Transformation = 'result = strncmpi(str1, str2, x - str1);',
652 | sequenceT(Id_0, ParentId, Id_1),
653 | ChildrenIds = [Id_2, Id_3],
654 | assignT(Id_2, Id_0, Id_4, Id_5),
655 | identT(Id_4, Id_2, I),
656 | operationT(Id_5, Id_2, Id_6, '+'),
657 | length(Id_6, 2),
658 | identT(Id_7, Id_5, Str2),
659 | member(Id_7, Id_6),
660 | operationT(Id_8, Id_5, Id_9, '-'),
661 | length(Id_9, 1),
662 | identT(Id_10, Id_8, Str1),
663 | member(Id_10, Id_9),
664 | member(Id_8, Id_6),
665 | Id_7 \= Id_8,
666 | loopT(Id_3, Id_0, 'doWhile', Id_11, Id_12),
667 | operationT(Id_11, Id_3, Id_13, '<'),
668 | length(Id_13, 2),
669 | identT(Id_14, Id_11, Str1),
670 | member(Id_14, Id_13),
671 | X = Id_15,
672 | member(Id_15, Id_13),
673 | directly_after(Id_15, Id_14, Id_13),
674 | Id_14 \= Id_15,
675 | sequenceT(Id_12, Id_3, Id_16),
676 | length(Id_16, 7),
677 | assignT(Id_17, Id_12, Id_24, Id_25),
678 | identT(Id_24, Id_17, C1),
679 | memoryT(Id_25, Id_17, Id_26),
680 | identT(Id_26, Id_25, Str1),
681 | ifT(Id_18, Id_12, Id_27, Id_28, Id_29),
682 | operationT(Id_27, Id_18, Id_30, '||'),
683 | length(Id_30, 2),
684 | operationT(Id_31, Id_27, Id_33, '<'),
685 | length(Id_33, 2),
686 | identT(Id_34, Id_31, C1),
687 | member(Id_34, Id_33),
688 | numericLiteralT(Id_35, Id_31, 65),
689 | member(Id_35, Id_33),
690 | directly_after(Id_35, Id_34, Id_33),
691 | Id_34 \= Id_35,
692 | member(Id_31, Id_30),
693 | operationT(Id_32, Id_27, Id_36, '>'),
694 | length(Id_36, 2),
695 | identT(Id_37, Id_32, C1),
696 | member(Id_37, Id_36),
697 | numericLiteralT(Id_38, Id_32, 90),
698 | member(Id_38, Id_36),
699 | directly_after(Id_38, Id_37, Id_36),
700 | Id_37 \= Id_38,
701 | member(Id_32, Id_30),
702 | Id_31 \= Id_32,
703 | assignT(Id_28, Id_18, Id_39, Id_40),
704 | identT(Id_39, Id_28, V1),
705 | identT(Id_40, Id_28, C1),
706 | assignT(Id_29, Id_18, Id_41, Id_42),
707 | identT(Id_41, Id_29, V1),
708 | operationT(Id_42, Id_29, Id_43, '+'),
709 | length(Id_43, 2),
710 | identT(Id_44, Id_42, C1),
711 | member(Id_44, Id_43),
712 | numericLiteralT(Id_45, Id_42, 32),
713 | member(Id_45, Id_43),
714 | Id_44 \= Id_45,
715 | directly_after(Id_18, Id_17, Id_16),
716 | assignT(Id_19, Id_12, Id_46, Id_47),
717 | identT(Id_46, Id_19, C2),
718 | memoryT(Id_47, Id_19, Id_48),
719 | operationT(Id_48, Id_47, Id_49, '+'),
720 | length(Id_49, 2),
721 | identT(Id_50, Id_48, I),
722 | member(Id_50, Id_49),
723 | identT(Id_51, Id_48, Str1),
724 | member(Id_51, Id_49),
725 | Id_50 \= Id_51,
726 | directly_after(Id_19, Id_18, Id_16),
727 | ifT(Id_20, Id_12, Id_52, Id_53, Id_54),
728 | operationT(Id_52, Id_20, Id_55, '||'),
729 | length(Id_55, 2),
730 | operationT(Id_56, Id_52, Id_58, '<'),
731 | length(Id_58, 2),
732 | identT(Id_59, Id_56, C2),
733 | member(Id_59, Id_58),
734 | numericLiteralT(Id_60, Id_56, 65),
735 | member(Id_60, Id_58),
736 | directly_after(Id_60, Id_59, Id_58),
737 | Id_59 \= Id_60,
738 | member(Id_56, Id_55),
739 | operationT(Id_57, Id_52, Id_61, '>'),
740 | length(Id_61, 2),
741 | identT(Id_62, Id_57, C2),
742 | member(Id_62, Id_61),
743 | numericLiteralT(Id_63, Id_57, 90),
744 | member(Id_63, Id_61),
745 | directly_after(Id_63, Id_62, Id_61),
746 | Id_62 \= Id_63,
747 | member(Id_57, Id_55),
748 | Id_56 \= Id_57,
749 | assignT(Id_53, Id_20, Id_64, Id_65),
750 | identT(Id_64, Id_53, V2),
751 | identT(Id_65, Id_53, C2),
752 | assignT(Id_54, Id_20, Id_66, Id_67),
753 | identT(Id_66, Id_54, V2),
754 | operationT(Id_67, Id_54, Id_68, '+'),
755 | length(Id_68, 2),
756 | identT(Id_69, Id_67, C2),
757 | member(Id_69, Id_68),
758 | numericLiteralT(Id_70, Id_67, 32),
759 | member(Id_70, Id_68),
760 | Id_69 \= Id_70,
761 | directly_after(Id_20, Id_19, Id_16),
762 | assignT(Id_21, Id_12, Id_71, Id_72),
763 | identT(Id_71, Id_21, Result),
764 | operationT(Id_72, Id_21, Id_73, '+'),
765 | length(Id_73, 2),
766 | identT(Id_74, Id_72, V1),
767 | member(Id_74, Id_73),
768 | operationT(Id_75, Id_72, Id_76, '-'),
769 | length(Id_76, 1),
770 | identT(Id_77, Id_75, V2),
771 | member(Id_77, Id_76),
772 | member(Id_75, Id_73),
773 | Id_74 \= Id_75,
774 | directly_after(Id_21, Id_20, Id_16),
775 | ifT(Id_22, Id_12, Id_78, Id_79, 'null'),
776 | operationT(Id_78, Id_22, Id_80, '!='),
777 | length(Id_80, 2),
778 | identT(Id_81, Id_78, Result),
779 | member(Id_81, Id_80),
780 | numericLiteralT(Id_82, Id_78, 0),
781 | member(Id_82, Id_80),
782 | directly_after(Id_82, Id_81, Id_80),
783 | Id_81 \= Id_82,
784 | breakT(Id_79, Id_22),
785 | directly_after(Id_22, Id_21, Id_16),
786 | assignT(Id_23, Id_12, Id_83, Id_84),
787 | identT(Id_83, Id_23, Str1),
788 | operationT(Id_84, Id_23, Id_85, '+'),
789 | length(Id_85, 2),
790 | identT(Id_86, Id_84, Str1),
791 | member(Id_86, Id_85),
792 | numericLiteralT(Id_87, Id_84, 1),
793 | member(Id_87, Id_85),
794 | Id_86 \= Id_87,
795 | directly_after(Id_23, Id_22, Id_16),
796 | directly_after(Id_3, Id_2, Id_1),
797 | I \= Str2,
798 | I \= Str1,
799 | I \= V1,
800 | I \= V2,
801 | I \= Result,
802 | I \= C2,
803 | I \= C1,
804 | Str2 \= Str1,
805 | Str2 \= V1,
806 | Str2 \= V2,
807 | Str2 \= Result,
808 | Str2 \= C2,
809 | Str2 \= C1,
810 | Str1 \= V1,
811 | Str1 \= V2,
812 | Str1 \= Result,
813 | Str1 \= C2,
814 | Str1 \= C1,
815 | V1 \= V2,
816 | V1 \= Result,
817 | V1 \= C2,
818 | V1 \= C1,
819 | V2 \= Result,
820 | V2 \= C2,
821 | V2 \= C1,
822 | Result \= C2,
823 | Result \= C1,
824 | C2 \= C1.
825 |
826 | two_cond(ParentId, Id_0, ChildrenIds, Transformation, A, B, N) :-
827 | Transformation = 'if(a || b)return n;',
828 | sequenceT(Id_0, ParentId, Id_1),
829 | ChildrenIds = [Id_2, Id_3],
830 | ifT(Id_2, Id_0, Id_4, Id_5, 'null'),
831 | A = Id_4,
832 | returnT(Id_5, Id_2, Id_6),
833 | N = Id_6,
834 | ifT(Id_3, Id_0, Id_7, Id_8, 'null'),
835 | B = Id_7,
836 | returnT(Id_8, Id_3, Id_9),
837 | N2 = Id_9,
838 | directly_after(Id_3, Id_2, Id_1),
839 | same_expression(N, N2).
840 |
841 | ternary_op(ParentId, Id_0, ChildrenIds, Transformation, Cond, X, V1, V2) :-
842 | Transformation = 'x = cond ? v1 : v2;',
843 | ifT(Id_0, ParentId, Id_1, Id_2, Id_3),
844 | Cond = Id_1,
845 | assignT(Id_2, Id_0, Id_4, Id_5),
846 | identT(Id_4, Id_2, X),
847 | V1 = Id_5,
848 | assignT(Id_3, Id_0, Id_6, Id_7),
849 | identT(Id_6, Id_3, X),
850 | V2 = Id_7.
851 |
852 | memset_1(ParentId, Id_0, ChildrenIds, Transformation, Ptr, Value, Num) :-
853 | Transformation = 'memset(ptr, value, num);',
854 | loopT(Id_0, ParentId, 'doWhile', Id_1, Id_2),
855 | operationT(Id_1, Id_0, Id_3, '!='),
856 | length(Id_3, 2),
857 | identT(Id_4, Id_1, Num),
858 | member(Id_4, Id_3),
859 | numericLiteralT(Id_5, Id_1, 0),
860 | member(Id_5, Id_3),
861 | directly_after(Id_5, Id_4, Id_3),
862 | Id_4 \= Id_5,
863 | sequenceT(Id_2, Id_0, Id_6),
864 | length(Id_6, 3),
865 | assignT(Id_7, Id_2, Id_10, Id_11),
866 | memoryT(Id_10, Id_7, Id_12),
867 | identT(Id_12, Id_10, Ptr),
868 | identT(Id_11, Id_7, Value),
869 | assignT(Id_8, Id_2, Id_13, Id_14),
870 | identT(Id_13, Id_8, Ptr),
871 | operationT(Id_14, Id_8, Id_15, '+'),
872 | length(Id_15, 2),
873 | identT(Id_16, Id_14, Ptr),
874 | member(Id_16, Id_15),
875 | numericLiteralT(Id_17, Id_14, 1),
876 | member(Id_17, Id_15),
877 | Id_16 \= Id_17,
878 | directly_after(Id_8, Id_7, Id_6),
879 | assignT(Id_9, Id_2, Id_18, Id_19),
880 | identT(Id_18, Id_9, Num),
881 | operationT(Id_19, Id_9, Id_20, '+'),
882 | length(Id_20, 2),
883 | identT(Id_21, Id_19, Num),
884 | member(Id_21, Id_20),
885 | numericLiteralT(Id_22, Id_19, -1),
886 | member(Id_22, Id_20),
887 | Id_21 \= Id_22,
888 | directly_after(Id_9, Id_8, Id_6),
889 | Num \= Ptr,
890 | Num \= Value,
891 | Ptr \= Value.
892 |
893 | compund_condition(ParentId, Id_0, ChildrenIds, Transformation, V, Conda, Condb1, Condb2) :-
894 | Transformation = 'v = (!condA && condB1) || (condA && condB2);',
895 | sequenceT(Id_0, ParentId, Id_1),
896 | ChildrenIds = [Id_2, Id_3],
897 | assignT(Id_2, Id_0, Id_4, Id_5),
898 | identT(Id_4, Id_2, V),
899 | Condb1 = Id_5,
900 | ifT(Id_3, Id_0, Id_6, Id_7, 'null'),
901 | Conda = Id_6,
902 | assignT(Id_7, Id_3, Id_8, Id_9),
903 | identT(Id_8, Id_7, V),
904 | Condb2 = Id_9,
905 | directly_after(Id_3, Id_2, Id_1).
906 |
907 | parity_1(ParentId, Id_0, ChildrenIds, Transformation, V) :-
908 | Transformation = 'v % 2 == 0;',
909 | operationT(Id_0, ParentId, Id_1, '!='),
910 | length(Id_1, 2),
911 | operationT(Id_2, Id_0, Id_4, '%'),
912 | length(Id_4, 2),
913 | identT(Id_5, Id_2, V),
914 | member(Id_5, Id_4),
915 | numericLiteralT(Id_6, Id_2, 2),
916 | member(Id_6, Id_4),
917 | directly_after(Id_6, Id_5, Id_4),
918 | Id_5 \= Id_6,
919 | member(Id_2, Id_1),
920 | numericLiteralT(Id_3, Id_0, 1),
921 | member(Id_3, Id_1),
922 | directly_after(Id_3, Id_2, Id_1),
923 | Id_2 \= Id_3.
924 |
925 |
--------------------------------------------------------------------------------
/dream/prolog/rules_src.tr:
--------------------------------------------------------------------------------
1 | [1]
2 | Signature:
3 | memcpy_1(dst, src, len){
4 | k = $len;
5 | d = $dst;
6 | if(k != 0){
7 | x = $src - $dst2;
8 | do{
9 | c = *(x + d);
10 | *(d) = c;
11 | d++;
12 | k--;
13 | }while(k != 0);
14 | }
15 | META: SAME_EXPR(dst, dst2);
16 | }
17 | Transformation:
18 | memcpy(dst, src, len);
19 |
20 |
21 | [2]
22 | Signature:
23 | memcpy_2(dst, src, len){
24 | len_cpy = $len;
25 | src_cpy = $src;
26 | if(len_cpy != 0){
27 | a = dst;
28 | d = src_cpy - dst;
29 | i = len_cpy;
30 | do{
31 | *(a) = *(d + a);
32 | a++;
33 | i--;
34 | }while(i != 0);
35 | }
36 | }
37 |
38 | Transformation:
39 | memcpy(dst, src, len);
40 |
41 | [3]
42 | Signature:
43 | memcpy_3(dst, src, len){
44 | d = $src - dst;
45 | do{
46 | c = *(d + dst);
47 | *(dst) = c;
48 | dst++;
49 | len--;
50 | }while(len != 0);
51 | }
52 | Transformation:
53 | memcpy(dst, src, len);
54 |
55 | [4]
56 | Signature:
57 | memcpy_4(dst, src, len){
58 | d = $src - dst;
59 | i = $len;
60 | do{
61 | c = *(d + dst);
62 | *(dst) = c;
63 | dst++;
64 | i--;
65 | }while(i != 0);
66 | }
67 | Transformation:
68 | memcpy(dst, src, len);
69 |
70 | [5]
71 | Signature:
72 | strlen_w(len, str){
73 | len = 0;
74 | if(*str != len){
75 | do{
76 | len++;
77 | }while(*(str + len * 2) != 0);
78 | }
79 | }
80 | Transformation:
81 | len = wclen(str);
82 |
83 | [6]
84 | Signature:
85 | strlen_1(len, str){
86 | if(*str != len){
87 | do{
88 | len++;
89 | }while(*(str + len) != 0);
90 | }
91 | len--;
92 | }
93 | Transformation:
94 | len = wclen(str);
95 |
96 | [7]
97 | Signature:
98 | strlen_2(len, str){
99 | len = 0;
100 | if(*str != len)
101 | do
102 | len++;
103 | while(*(str + len) != 0);
104 | }
105 | Transformation:
106 | len = strlen(str);
107 |
108 | [8]
109 | Signature:
110 | wcscmp(wsStr1, wcStr2, num, result){
111 | do{
112 | c1 = *wsStr1;
113 | if(c1 < 0x41 || c1 > 0x5a)
114 | v1 = c1;
115 | else
116 | v1 = c1 + 0x20;
117 | c2 = *wcStr2;
118 | if(c2 < 0x41 || c2 > 0x5a)
119 | v2 = c2;
120 | else
121 | v2 = c2 + 0x20;
122 | result = v1 - v2;
123 | if(result != 0)
124 | return result;
125 | wsStr1 += 2;
126 | wcStr2 += 2;
127 | }while(wsStr1 < num);
128 | }
129 | Transformation:
130 | result = wcscmp(wsStr1, wcStr2);
131 |
132 | [9]
133 | Signature:
134 | strncmpi_1(str1, str2, result, x){
135 | i = str2 - str1;
136 | do{
137 | c1 = *str1;
138 | if(c1 < 0x41 || c1 > 0x5a)
139 | v1 = c1;
140 | else
141 | v1 = c1 + 0x20;
142 | c2 = *(i + str1);
143 | if(c2 < 0x41 || c2 > 0x5a)
144 | v2 = c2;
145 | else
146 | v2 = c2 + 0x20;
147 | result = v1 - v2;
148 | if(result != 0)
149 | break;
150 | str1++;
151 | }while(str1 < $x);
152 | }
153 | Transformation:
154 | result = strncmpi(str1, str2, x - str1);
155 |
156 | [10]
157 | Signature:
158 | two_cond(a, b, n){
159 | if($a)
160 | return $n;
161 | if($b)
162 | return $n2;
163 | META: SAME_EXPR(n, n2);
164 | }
165 | Transformation:
166 | if(a || b)
167 | return n;
168 |
169 | [11]
170 | Signature:
171 | ternary_op(cond, x, v1, v2){
172 | if($cond)
173 | x = $v1;
174 | else
175 | x = $v2;
176 | }
177 | Transformation:
178 | x = cond ? v1 : v2;
179 |
180 | [12]
181 | Signature:
182 | memset_1(ptr, value, num){
183 | do{
184 | *ptr = value;
185 | ptr++;
186 | num--;
187 | }while(num != 0);
188 | }
189 | Transformation:
190 | memset(ptr, value, num);
191 |
192 |
193 |
194 | [13]
195 | Signature:
196 | compund_condition(v, condA, condB1, condB2){
197 | v = $condB1;
198 | if($condA)
199 | v = $condB2;
200 | }
201 | Transformation:
202 | v = (!condA && condB1) || (condA && condB2);
203 |
204 | [14]
205 | Signature:
206 | parity_1(v){
207 | v % 2 != 1;
208 | }
209 | Transformation:
210 | v % 2 == 0;
--------------------------------------------------------------------------------
/dream/theorem_prover/__init__.py:
--------------------------------------------------------------------------------
1 | __author__ = 'yakdan'
2 |
--------------------------------------------------------------------------------
/dream/theorem_prover/z3_transformer.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2011-2017 Khaled Yakdan.
2 | # All rights reserved.
3 |
4 | import logging
5 |
6 | from z3 import *
7 |
8 | from dream.ir.expressions import ANDExpression, ORExpression, HighLevelCondition, NumericConstant, \
9 | AdditionExpression, NegationExpression, RemainderExpression
10 |
11 | l = logging.getLogger("dream.z3_transformer")
12 |
13 |
14 | class Z3Simplifier(object):
15 | def __init__(self):
16 | self.variable_map = {}
17 |
18 | def construct_var_map(self, expr):
19 | self.variable_map = {var.name: var for var in expr.elements() if hasattr(var, 'name')}
20 |
21 | def simplify(self, expr):
22 | try:
23 | z3_expr = expr.to_symbolic()
24 | if z3_expr is True:
25 | return NumericConstant(1)
26 | self.construct_var_map(expr)
27 | result = Then('simplify', 'propagate-values', 'ctx-solver-simplify', 'simplify')(z3_expr)
28 | return self.z3_to_expr(result.as_expr())
29 | except NotImplementedError, e:
30 | print e.message
31 | return expr
32 | except Exception, e:
33 | print e.message
34 | return expr
35 |
36 | def z3_to_expr(self, z3_expr):
37 | op_kind = z3_expr.decl().kind()
38 | if is_app_of(z3_expr, Z3_OP_AND):
39 | return ANDExpression([self.z3_to_expr(op) for op in z3_expr.children()], is_condition=True)
40 | elif is_app_of(z3_expr, Z3_OP_OR):
41 | return ORExpression([self.z3_to_expr(op) for op in z3_expr.children()], is_condition=True)
42 | elif is_app_of(z3_expr, Z3_OP_BADD):
43 | return AdditionExpression(self.z3add_args(z3_expr))
44 | elif is_app_of(z3_expr, Z3_OP_BMUL):
45 | assert is_int_value(z3_expr.arg(0)) and z3_expr.arg(0).as_long() == -1
46 | return NegationExpression(self.z3_to_expr(z3_expr.arg(1)))
47 | elif is_app_of(z3_expr, Z3_OP_EXTRACT):
48 | return self.z3extract_to_expr(z3_expr)
49 | elif is_app_of(z3_expr, Z3_OP_BSMOD) or z3_expr.decl().name() == 'bvsmod_i':
50 | return RemainderExpression(self.z3_to_expr(z3_expr.arg(0)), self.z3_to_expr(z3_expr.arg(1)))
51 | elif is_distinct(z3_expr):
52 | return HighLevelCondition(self.z3_to_expr(z3_expr.arg(0)), '!=', self.z3_to_expr(z3_expr.arg(1)))
53 | elif is_eq(z3_expr):
54 | return HighLevelCondition(self.z3_to_expr(z3_expr.arg(0)), '==', self.z3_to_expr(z3_expr.arg(1)))
55 | elif self.is_z3_cmp(z3_expr):
56 | return self.z3cmp_to_expr(z3_expr)
57 | elif is_not(z3_expr):
58 | return ~self.z3_to_expr(z3_expr.arg(0))
59 | elif is_bv_value(z3_expr):
60 | return NumericConstant(z3_expr.as_long())
61 | elif self.is_bv_variable(z3_expr):
62 | return self.variable_map[z3_expr.decl().name()].deep_copy()
63 | else:
64 | l.warning(z3_expr, z3_expr.decl().name(), op_kind)
65 | raise NotImplementedError('Transformation from z3 to DREAM IR is not implemented')
66 |
67 | def z3add_args(self, z3add):
68 | return self.z3add_arg(z3add.arg(0)) + self.z3add_arg(z3add.arg(1))
69 |
70 | def z3add_arg(self, z3add_arg):
71 | args = []
72 | if is_add(z3add_arg):
73 | args.extend(self.z3add_args(z3add_arg))
74 | else:
75 | args.append(self.z3_to_expr(z3add_arg))
76 | return args
77 |
78 | def z3extract_to_expr(self, z3_extract):
79 | high = Z3_get_decl_int_parameter(z3_extract.ctx.ref(), z3_extract.decl().ast, 0)
80 | low = Z3_get_decl_int_parameter(z3_extract.ctx.ref(), z3_extract.decl().ast, 1)
81 | if high == 0 and low == 0:
82 | return RemainderExpression(self.z3_to_expr(z3_extract.arg(0)), NumericConstant(2))
83 | elif high == 31 and low == 31:
84 | return HighLevelCondition(self.z3_to_expr(z3_extract.arg(0)), '<', NumericConstant(0))
85 | else:
86 | print z3_extract
87 | raise NotImplementedError('Transformation from z3 to DREAM IR is not implemented')
88 |
89 | def z3cmp_to_expr(self, z3_cmp):
90 | if self.compares_offset_expr_to_const(z3_cmp):
91 | decl = z3_cmp.decl().kind()
92 | if decl == Z3_OP_UGT:
93 | if is_bv_value(z3_cmp.arg(0)):
94 | return self.z3cmp_to_expr(ULT(z3_cmp.arg(1), z3_cmp.arg(0)))
95 | else:
96 | return ~self.z3cmp_to_expr(ULE(z3_cmp.arg(0), z3_cmp.arg(1)))
97 | elif decl == Z3_OP_UGEQ:
98 | if is_bv_value(z3_cmp.arg(0)):
99 | return self.z3cmp_to_expr(ULE(z3_cmp.arg(1), z3_cmp.arg(0)))
100 | else:
101 | return ~self.z3cmp_to_expr(ULT(z3_cmp.arg(0), z3_cmp.arg(1)))
102 | elif decl == Z3_OP_ULT:
103 | if is_bv_value(z3_cmp.arg(0)):
104 | return ~self.z3cmp_to_expr(ULE(z3_cmp.arg(1), z3_cmp.arg(0)))
105 | else:
106 | return self.z3cmp_offset(z3_cmp)
107 | elif decl == Z3_OP_ULEQ:
108 | if is_bv_value(z3_cmp.arg(0)):
109 | return ~self.z3cmp_to_expr(ULT(z3_cmp.arg(1), z3_cmp.arg(0)))
110 | else:
111 | return self.z3cmp_offset(z3_cmp)
112 | elif decl == Z3_OP_SGT:
113 | if is_bv_value(z3_cmp.arg(0)):
114 | return self.z3cmp_to_expr(z3_cmp.arg(1) < z3_cmp.arg(0))
115 | else:
116 | return ~self.z3cmp_to_expr(z3_cmp.arg(0) <= z3_cmp.arg(1))
117 | elif decl == Z3_OP_SGEQ:
118 | if is_bv_value(z3_cmp.arg(0)):
119 | return self.z3cmp_to_expr(z3_cmp.arg(1) <= z3_cmp.arg(0))
120 | else:
121 | return ~self.z3cmp_to_expr(z3_cmp.arg(0) < z3_cmp.arg(1))
122 | elif decl == Z3_OP_SLT:
123 | if is_bv_value(z3_cmp.arg(0)):
124 | return ~self.z3cmp_to_expr(z3_cmp.arg(1) <= z3_cmp.arg(0))
125 | else:
126 | return self.z3cmp_offset(z3_cmp)
127 | elif decl == Z3_OP_SLEQ:
128 | if is_bv_value(z3_cmp.arg(0)):
129 | return ~self.z3cmp_to_expr(z3_cmp.arg(1) < z3_cmp.arg(0))
130 | else:
131 | return self.z3cmp_offset(z3_cmp)
132 | else:
133 | assert False
134 | else:
135 | return self.z3_cmp_to_condition(z3_cmp)
136 |
137 | def z3cmp_offset(self, z3_less):
138 | decl = z3_less.decl().kind()
139 | z3_add = z3_less.arg(0)
140 | var, alpha = (z3_add.arg(0), z3_add.arg(1)) if is_bv_value(z3_add.arg(1)) else (z3_add.arg(1), z3_add.arg(0))
141 | beta = z3_less.arg(1)
142 | max_val = 1 << alpha.size() if self.is_unsigned_cmp(z3_less) else (1 << (alpha.size() - 1))
143 | high = BitVecVal(beta.as_long() - alpha.as_long(), alpha.size())
144 | low = BitVecVal(max_val - alpha.as_long(), alpha.size())
145 |
146 | simplified_expr = None
147 | if high.as_long() > low.as_long():
148 | if decl == Z3_OP_ULT:
149 | simplified_expr = And(UGE(var, low), ULT(var, high))
150 | elif decl == Z3_OP_ULEQ:
151 | simplified_expr = And(UGE(var, low), ULE(var, high))
152 | elif decl == Z3_OP_SLT:
153 | simplified_expr = And(var >= low, var < high)
154 | elif decl == Z3_OP_SLEQ:
155 | simplified_expr = And(var >= low, var <= high)
156 | else:
157 | if decl == Z3_OP_ULT:
158 | simplified_expr = Or(UGE(var, low), ULT(var, high))
159 | elif decl == Z3_OP_ULEQ:
160 | simplified_expr = Or(UGE(var, low), ULE(var, high))
161 | elif decl == Z3_OP_SLT:
162 | simplified_expr = Or(var >= low, var < high)
163 | elif decl == Z3_OP_SLEQ:
164 | simplified_expr = Or(var >= low, var <= high)
165 | if simplified_expr is not None and self.z3_equivalent(z3_less, simplified_expr):
166 | return self.z3_to_expr(simplified_expr)
167 | else:
168 | return self.z3_cmp_to_condition(z3_less)
169 |
170 | def z3_cmp_to_condition(self, z3cmp_expr):
171 | expr1 = self.z3_to_expr(z3cmp_expr.arg(0))
172 | expr2 = self.z3_to_expr(z3cmp_expr.arg(1))
173 | decl = z3cmp_expr.decl().kind()
174 | if decl == Z3_OP_UGT:
175 | return HighLevelCondition(expr1, '>', expr2)
176 | elif decl == Z3_OP_SGT:
177 | return HighLevelCondition(expr1, '>', expr2, is_signed=True)
178 | elif decl == Z3_OP_UGEQ:
179 | return HighLevelCondition(expr1, '>=', expr2)
180 | elif decl == Z3_OP_SGEQ:
181 | return HighLevelCondition(expr1, '>=', expr2, is_signed=True)
182 | elif decl == Z3_OP_ULT:
183 | return HighLevelCondition(expr1, '<', expr2)
184 | elif decl == Z3_OP_SLT:
185 | return HighLevelCondition(expr1, '<', expr2, is_signed=True)
186 | elif decl == Z3_OP_ULEQ:
187 | return HighLevelCondition(expr1, '<=', expr2)
188 | elif decl == Z3_OP_SLEQ:
189 | return HighLevelCondition(expr1, '<=', expr2, is_signed=True)
190 | else:
191 | assert False
192 |
193 | @staticmethod
194 | def is_z3_cmp(z3_expr):
195 | decl = z3_expr.decl().kind()
196 | return decl == Z3_OP_UGT or decl == Z3_OP_SGT or decl == Z3_OP_UGEQ or decl == Z3_OP_SGEQ or \
197 | decl == Z3_OP_ULT or decl == Z3_OP_SLT or decl == Z3_OP_ULEQ or decl == Z3_OP_SLEQ
198 |
199 | @staticmethod
200 | def is_unsigned_cmp(z3_cmp):
201 | decl = z3_cmp.decl().kind()
202 | return decl == Z3_OP_UGT or decl == Z3_OP_UGEQ or decl == Z3_OP_ULT or decl == Z3_OP_ULEQ
203 |
204 | @staticmethod
205 | def z3_equivalent(z3_expr1, z3_expr2):
206 | s = Solver()
207 | s.add(z3_expr1 != z3_expr2)
208 | return s.check() == unsat
209 |
210 | def compares_offset_expr_to_const(self, z3_expr):
211 | return (is_bv_value(z3_expr.arg(0)) and self.is_offset_expr(z3_expr.arg(1))) or\
212 | (is_bv_value(z3_expr.arg(1)) and self.is_offset_expr(z3_expr.arg(0)))
213 |
214 | def is_offset_expr(self, z3_expr):
215 | return z3_expr.decl().kind() == Z3_OP_BADD and\
216 | ((is_bv_value(z3_expr.arg(0)) and self.is_bv_variable(z3_expr.arg(1))) or
217 | (is_bv_value(z3_expr.arg(1)) and self.is_bv_variable(z3_expr.arg(0))))
218 |
219 | def is_bv_variable(self, z3_expr):
220 | return is_bv(z3_expr) and z3_expr.num_args() == 0 and z3_expr.decl().name() in self.variable_map
221 |
222 | def equivalent(self, e1, e2):
223 | try:
224 | z3_e1, z3_e2 = e1.to_symbolic(), e2.to_symbolic()
225 | return self.z3_equivalent(z3_e1, z3_e2)
226 | except NotImplementedError:
227 | return False
--------------------------------------------------------------------------------
/dream/transformations/__init__.py:
--------------------------------------------------------------------------------
1 | __author__ = 'yakdan'
2 |
--------------------------------------------------------------------------------
/dream/transformations/named_constants.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2011-2017 Khaled Yakdan.
2 | # All rights reserved.
3 |
4 | NAMED_CONSTANTS = {
5 | 0x4D5A: 'EXE_FILE_MZ_HEADER',
6 | 0x5A4D: 'EXE_FILE_MZ_HEADER',
7 | 0x5045: 'EXE_FILE_PE_HEADER',
8 | 0x4550: 'EXE_FILE_PE_HEADER',
9 | 0x4B50: 'ZIP_FILE_SIGNATURE',
10 | 0x504B: 'ZIP_FILE_SIGNATURE',
11 | }
12 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | sympy
2 | pycparser
3 | pydot
4 | #pyswip
5 |
--------------------------------------------------------------------------------