├── LICENSE ├── README.md ├── _config.yml ├── amt.properties ├── logo.png ├── overview.png ├── pom.xml ├── src └── de │ └── upb │ └── mike │ └── amt │ ├── AMT.java │ ├── Config.java │ ├── Data.java │ ├── Log.java │ ├── Properties.java │ ├── SootObjHashed.java │ ├── Timer.java │ ├── aql │ ├── AQLHandler.java │ └── AQLRunner.java │ ├── conflicresolution │ └── ConflictResolution.java │ ├── evaluation │ └── Comparison.java │ ├── helper │ └── FileManager.java │ ├── manifest │ ├── MergeManifest.java │ └── ParseManifest.java │ └── soot │ ├── InstrumentationTransformer.java │ ├── ParseTransformer.java │ └── SootObject.java ├── test ├── ArrayAccess1.apk ├── ArrayAccess2.apk ├── ArrayAccess3.apk ├── ArrayAccess4.apk ├── ArrayAccess5.apk ├── ArrayCopy1.apk ├── ArrayToString1.apk ├── Echoer.apk ├── HashMapAccess1.apk ├── ListAccess1.apk ├── MultidimensionalArray1.apk └── SendSMS.apk └── testsrc └── de └── upb └── mike └── amt └── MergeTest.java /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 | ![Java 17](https://img.shields.io/badge/java-17-brightgreen.svg) 2 | --- 3 |

4 | 5 |

6 | 7 | # AMT 8 | The *Android Merge Tool (AMT)* does what the name suggests: it merges arbitrary Android apps into a single merged app. 9 | As input it takes a number of Android packages (.apk files) and outputs the merged app as one Android package. 10 | Along with this primary output, a report is generated optionally. 11 | It contains information about the properties (e.g. taint-flows) changed. 12 | 13 |

14 | 15 |

16 | 17 | An overview of the whole approach is illustrated in the figure above. 18 | On the one hand, the first five steps (1 - 5) represent *Phase I*, the app merging process. 19 | Multiple input apps are merged into a single merged app. 20 | On the other hand, Step 6 and 7 stand for *Phase II*. 21 | During this phase it is evaluated how accurately the merged app represents the input apps. 22 | In order to guarantee accurately merged benchmarks Phase II becomes indispensable. 23 | For more information please take a look at the associated [paper](https://ieeexplore.ieee.org/document/8967423) (see Publications). 24 | 25 | ## Usage 26 | Two steps have to be completed in order to use AMT: 27 | - **Step 1: Configuration** 28 | The file *amt.properties* holds the AMT's configuration. 29 | The following options can be configured: 30 | 31 | | Parameter | Meaning | 32 | | --------- | ------- | 33 | | `androidPlatforms=/path/to/Android/sdks/platforms` | The path to the Android platforms directory | 34 | | `apktoolPath=/path/to/apktool` | [ApkTool](https://github.com/iBotPeaches/Apktool) must be installed and this path has to point to the directory containing ApkTool's JAR file | 35 | | `apktoolJar=apktool_2.6.0.jar` | Mostly dependent on ApkTool's version, the JAR's filename should be adapted here. | 36 | | `aqlQuery=Flows IN App('%APP_APK%') USES 'FlowDroid' ?` | When run in *check* or *comparison* mode, an [AQL-Query](https://github.com/FoelliX/AQL-System/wiki/Questions) to execute must be defined here. | 37 | | `comparisonAqlQuery=Flows IN App('%APP_APK%' \| 'COMBINE') USES 'FlowDroid' ?` | The query used for the comparison must be defined here. | 38 | | `outputFolder=output` | Any output is stored in the specified directory | 39 | | `defaultExcludes=android.support.*, com.google.*, androidx.*, kotlin.*` | Packages or classes that are excluded while merging. | 40 | 41 | - **Step 2: Launch** 42 | AMT can be accessed from the command-line as follows: 43 | ````bash 44 | java -jar AMT-2.0.0.jar [optional launch parameters] [list of .apk files] 45 | ```` 46 | for example: 47 | ````bash 48 | java -jar AMT-2.0.0.jar -comparison -d verbose -cfg myConfig.xml A.apk B.apk 49 | ```` 50 | This will launch AMT in comparison mode, shorten its output and use `myConfig.xml` as configuration for the underlying AQL-System. 51 | All launch parameters are listed in the following table: 52 | 53 | | Parameter | Meaning | 54 | | --------- | ------- | 55 | | `-check` | Turns on the optional *check* mode | 56 | | `-comparison` | Turns on the optional *comparison* mode | 57 | | `-c %FILE%`, `-cfg %FILE%`, `-config %FILE%` | This parameter can be used to specify a different config file for the underlying [AQL-System](https://github.com/FoelliX/AQL-System) (By default: *config.xml* is used) | 58 | | `-debug "X"`, `-d "X"`, `-l "X"`, `-loglevel "X"` | The output generated during the execution of this tool can be set to different levels. `X` may be set to: `error`, `warning`, `debug`, `detailed`, `verbose` (ascending precision from left to right). | 59 | 60 | ## Publications 61 | - *App Merging for Benchmark Speed-Up and Analysis Lift-Up* (Felix Pauck, Shikun Zhang) 62 | A-Mobile@ASE 2018 [https://ieeexplore.ieee.org/document/8967423](https://ieeexplore.ieee.org/document/8967423) 63 | 64 | ## License 65 | AMT is licensed under the *GNU General Public License v3* (see [LICENSE](https://github.com/FoelliX/AMT/blob/master/LICENSE)). 66 | 67 | ## Contact 68 | **Felix Pauck** (FoelliX) 69 | Paderborn University 70 | fpauck@mail.uni-paderborn.de 71 | [http://www.FelixPauck.de](http://www.FelixPauck.de) 72 | 73 | ## Links 74 | - AMT requires ApkTool: [https://github.com/iBotPeaches/Apktool](https://github.com/iBotPeaches/Apktool) 75 | - AMT uses the AQL and its system: [https://foellix.github.io/AQL-System](https://foellix.github.io/AQL-System) 76 | - ApkCombiner is a very similar tool: [https://github.com/lilicoding/ApkCombiner](https://github.com/lilicoding/ApkCombiner) -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-slate 2 | title: AMT 3 | description: Android Merge Tool 4 | show_downloads: true 5 | logo: https://foellix.github.io/AMT/logo.png -------------------------------------------------------------------------------- /amt.properties: -------------------------------------------------------------------------------- 1 | androidPlatforms=/path/to/Android/sdks/platforms 2 | apktoolPath=/path/to/apktool 3 | apktoolJar=apktool_2.3.4.jar 4 | aqlQuery=Flows IN App('%APP_APK%') USES 'FlowDroid' ? 5 | comparisonAqlQuery=Flows IN App('%APP_APK%' | 'COMBINE') USES 'FlowDroid' ? 6 | outputFolder=output 7 | defaultExcludes=android.support.*, com.google.*, androidx.*, kotlin.* -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FoelliX/AMT/9a7d6bde7674a3bec65f35e7f25f0d31c4982b81/logo.png -------------------------------------------------------------------------------- /overview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FoelliX/AMT/9a7d6bde7674a3bec65f35e7f25f0d31c4982b81/overview.png -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | de.upb.mike.amt 4 | AMT 5 | 2.0.0 6 | jar 7 | 8 | AMT 9 | Android Merge Tool 10 | https://FoelliX.github.io/AMT 11 | 12 | 13 | UTF-8 14 | 15 | 16 | 17 | clean install 18 | target 19 | 20 | target/classes 21 | src 22 | testsrc 23 | 24 | 25 | 26 | ${project.basedir} 27 | 28 | amt.properties 29 | config*.xml 30 | 31 | ${project.basedir}/target/build 32 | 33 | 34 | ${project.basedir}/apktool 35 | 36 | *.jar 37 | 38 | ${project.basedir}/target/build/apktool 39 | 40 | 41 | 42 | 43 | 44 | org.apache.maven.plugins 45 | maven-compiler-plugin 46 | 3.8.1 47 | 48 | 17 49 | 17 50 | 51 | 52 | 53 | 54 | org.apache.maven.plugins 55 | maven-assembly-plugin 56 | 3.3.0 57 | 58 | 59 | package 60 | 61 | single 62 | 63 | 64 | 65 | 66 | 67 | de.upb.mike.amt.AMT 68 | 69 | 70 | 71 | 72 | jar-with-dependencies 73 | 74 | ${project.basedir}/target/build 75 | ${project.name}-${project.version} 76 | false 77 | 78 | 79 | 80 | 81 | 82 | 83 | org.apache.maven.plugins 84 | maven-surefire-plugin 85 | 2.22.0 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | de.foellix 94 | AQL-System 95 | 2.0.0 96 | 97 | 98 | 99 | 100 | org.junit.jupiter 101 | junit-jupiter 102 | 5.7.0 103 | test 104 | 105 | 106 | 107 | 108 | 109 | Felix Pauck 110 | my@FoelliX.de 111 | FoelliX.de 112 | https://FoelliX.de 113 | 114 | 115 | 116 | 117 | 118 | GNU General Public License v3.0 119 | https://www.gnu.org/licenses/gpl-3.0.txt 120 | 121 | 122 | -------------------------------------------------------------------------------- /src/de/upb/mike/amt/AMT.java: -------------------------------------------------------------------------------- 1 | package de.upb.mike.amt; 2 | 3 | import java.io.File; 4 | import java.io.FileNotFoundException; 5 | import java.io.PrintWriter; 6 | import java.util.ArrayList; 7 | import java.util.Arrays; 8 | import java.util.List; 9 | 10 | import de.foellix.aql.datastructure.Answer; 11 | import de.foellix.aql.datastructure.Flow; 12 | import de.foellix.aql.datastructure.Flows; 13 | import de.foellix.aql.datastructure.handler.AnswerHandler; 14 | import de.foellix.aql.helper.EqualsHelper; 15 | import de.foellix.aql.helper.EqualsOptions; 16 | import de.upb.mike.amt.aql.AQLHandler; 17 | import de.upb.mike.amt.evaluation.Comparison; 18 | import de.upb.mike.amt.helper.FileManager; 19 | import de.upb.mike.amt.manifest.MergeManifest; 20 | import de.upb.mike.amt.manifest.ParseManifest; 21 | import de.upb.mike.amt.soot.SootObject; 22 | 23 | public class AMT { 24 | public static int steps; 25 | 26 | private static boolean OPTION_CHECK = false; 27 | private static boolean OPTION_COMPARISON = false; 28 | private static boolean OPTION_SKIP_MANIFEST = false; 29 | 30 | private String launcherAppPath; 31 | private int appNumber; 32 | 33 | public static void main(String[] args) { 34 | // Launch parameters 35 | int counter = 0; 36 | for (int i = 0; i < args.length; i++) { 37 | if (args[i].equals("-l") || args[i].equals("-loglevel") || args[i].equals("-d") 38 | || args[i].equals("-debug")) { 39 | if (args[i + 1].equals("error") || args[i + 1].equals(String.valueOf(Log.LOG_LEVEL_ERROR))) { 40 | Log.loglevel = Log.LOG_LEVEL_ERROR; 41 | } else if (args[i + 1].equals("warning") || args[i + 1].equals(String.valueOf(Log.LOG_LEVEL_WARNING))) { 42 | Log.loglevel = Log.LOG_LEVEL_WARNING; 43 | } else if (args[i + 1].equals("debug") || args[i + 1].equals(String.valueOf(Log.LOG_LEVEL_DEBUG))) { 44 | Log.loglevel = Log.LOG_LEVEL_DEBUG; 45 | } else if (args[i + 1].equals("detailed") 46 | || args[i + 1].equals(String.valueOf(Log.LOG_LEVEL_DETAILED))) { 47 | Log.loglevel = Log.LOG_LEVEL_DETAILED; 48 | } else if (args[i + 1].equals("verbose") || args[i + 1].equals(String.valueOf(Log.LOG_LEVEL_VERBOSE))) { 49 | Log.loglevel = Log.LOG_LEVEL_VERBOSE; 50 | } else { 51 | Log.loglevel = Log.LOG_LEVEL_NORMAL; 52 | } 53 | counter += 2; 54 | i++; 55 | } else if (args[i].equals("-skipManifest") || args[i].equals("-skip") || args[i].equals("-sm")) { 56 | OPTION_SKIP_MANIFEST = true; 57 | counter++; 58 | } else if (args[i].equals("-check")) { 59 | OPTION_CHECK = true; 60 | counter++; 61 | } else if (args[i].equals("-comparison")) { 62 | OPTION_CHECK = true; 63 | OPTION_COMPARISON = true; 64 | counter++; 65 | } else if (args[i].equals("-c") || args[i].equals("-cfg") || args[i].equals("-config")) { 66 | final File cfgFile = new File(args[i + 1]); 67 | if (cfgFile != null && cfgFile.exists()) { 68 | Config.getInstance().setAqlConfig(cfgFile); 69 | } else { 70 | Log.log("Could not find config file: " + cfgFile.getAbsolutePath(), Log.LOG_LEVEL_ERROR); 71 | } 72 | counter += 2; 73 | i++; 74 | } 75 | } 76 | final List apkFiles = new ArrayList<>(); 77 | for (int i = counter; i < args.length; i++) { 78 | String tempFilename = args[i]; 79 | if (tempFilename.endsWith(" ")) { 80 | tempFilename = tempFilename.substring(0, tempFilename.length() - 1); 81 | } 82 | if (tempFilename.endsWith(",")) { 83 | tempFilename = tempFilename.substring(0, tempFilename.length() - 1); 84 | } 85 | for (final String tempFinalFilename : tempFilename.replaceAll(" ", "").split(",")) { 86 | final File temp = new File(tempFinalFilename); 87 | if (temp.exists()) { 88 | if (temp.isDirectory()) { 89 | for (final File temp2 : FileManager.findApksInFolder(temp)) { 90 | apkFiles.add(temp2); 91 | } 92 | } else { 93 | apkFiles.add(temp); 94 | } 95 | } 96 | } 97 | } 98 | Config.getInstance().setAppPathList(apkFiles); 99 | 100 | // Read properties file 101 | Config.getInstance().setAndroidPlatformPath( 102 | new File(Properties.getInstance().getProperty(Properties.ANDROID_PLATFORMS)).getAbsolutePath()); 103 | Config.getInstance().setSootOutputPath(new File("sootOutput").getAbsolutePath()); 104 | Config.getInstance().setApktoolPath( 105 | new File(Properties.getInstance().getProperty(Properties.APKTOOLPATH)).getAbsolutePath()); 106 | Config.getInstance().setApktoolJar(Properties.getInstance().getProperty(Properties.APKTOOLJAR)); 107 | Config.getInstance().setAqlQuery(Properties.getInstance().getProperty(Properties.AQLQUERY)); 108 | Config.getInstance() 109 | .setComparisonAqlQuery(Properties.getInstance().getProperty(Properties.CPOMPARISON_AQLQUERY)); 110 | Config.getInstance().setOutputFolder(new File(Properties.getInstance().getProperty(Properties.OUTPUTFOLDER))); 111 | Config.getInstance().setDefaultExcludes(Arrays 112 | .asList(Properties.getInstance().getProperty(Properties.DEFAULT_EXCLUDES).replace(" ", "").split(","))); 113 | 114 | // Launch AMT 115 | if (FileManager.deleteDir(Config.getInstance().getSootOutputPath())) { 116 | if (!apkFiles.isEmpty()) { 117 | new AMT().start(); 118 | } else { 119 | Log.log("No input apk given. Please provide one.", Log.LOG_LEVEL_ERROR); 120 | } 121 | } else { 122 | Log.log("Could not delete Soot output folder: " + Config.getInstance().getSootOutputPath(), 123 | Log.LOG_LEVEL_ERROR); 124 | } 125 | } 126 | 127 | private void start() { 128 | steps = 5; 129 | if (OPTION_COMPARISON) { 130 | steps += 2; 131 | } else if (OPTION_CHECK) { 132 | steps += 1; 133 | } 134 | if (OPTION_SKIP_MANIFEST) { 135 | steps--; 136 | } 137 | 138 | final Timer amtTimer = new Timer().start(); 139 | final Timer mergingTimer = new Timer().start(); 140 | 141 | this.appNumber = Config.getInstance().getAppPathList().size(); 142 | StringBuilder sb = new StringBuilder("AMT started! (Merging " + this.appNumber + " apps" 143 | + (OPTION_CHECK ? " + Check" : "") + (OPTION_COMPARISON ? " + Comparison" : "") + ")\n"); 144 | int inputCounter = 0; 145 | for (final File file : Config.getInstance().getAppPathList()) { 146 | sb.append("\t" + ++inputCounter + ". " + file.getAbsolutePath() + "\n"); 147 | } 148 | sb.append("\n"); 149 | Log.log(sb.toString(), Log.LOG_LEVEL_NORMAL); 150 | 151 | Log.log("*** Step 1/" + steps + ": Parsing Manifest ***", Log.LOG_LEVEL_NORMAL); 152 | for (final File file : Config.getInstance().getAppPathList()) { 153 | final ParseManifest parseManifest = new ParseManifest(file); 154 | Data.getInstance().getPackageMap().put(file.getAbsolutePath(), parseManifest.getPackageName()); 155 | if (SootObject.getInstance().getLauncherActivity() == null && parseManifest.containsLauncherActivity()) { 156 | SootObject.getInstance().setLauncherActivity(parseManifest.getLauncherActivity()); 157 | this.launcherAppPath = file.getAbsolutePath(); 158 | Log.log("Launcher-Activity selected: " + SootObject.getInstance().getLauncherActivity() + " (" 159 | + this.launcherAppPath + ")", Log.LOG_LEVEL_DEBUG); 160 | } 161 | } 162 | Log.log("successful!\n\n", Log.LOG_LEVEL_NORMAL); 163 | 164 | Log.log("*** Step 2/" + steps + ": Parsing Apps ***", Log.LOG_LEVEL_NORMAL); 165 | for (final File apkFile : Config.getInstance().getAppPathList()) { 166 | Data.getInstance().putOrGetMapEntry(apkFile); 167 | if (!apkFile.getAbsolutePath().equals(this.launcherAppPath)) { 168 | SootObject.getInstance().parseApp(apkFile.getAbsolutePath(), SootObject.FLAG_READ_NON_LAUNCHER_APPS); 169 | } 170 | } 171 | Log.log("successful!\n\n", Log.LOG_LEVEL_NORMAL); 172 | 173 | Log.log("*** Step 3/" + steps + ": Instrumenting Classes ***", Log.LOG_LEVEL_NORMAL); 174 | for (final File apkFile : Config.getInstance().getAppPathList()) { 175 | if (apkFile.getAbsolutePath().equals(this.launcherAppPath)) { 176 | SootObject.getInstance().parseApp(apkFile.getAbsolutePath(), SootObject.FLAG_MERGE); 177 | } 178 | } 179 | Log.log("successful!\n\n", Log.LOG_LEVEL_NORMAL); 180 | 181 | // Step 4 is triggered in InstrumentationTransformer 182 | 183 | if (!OPTION_SKIP_MANIFEST) { 184 | Log.log("*** Step 5/" + steps + ": Run Apktool (Merge Manifests) ***", Log.LOG_LEVEL_NORMAL); 185 | final MergeManifest mergeManifest = new MergeManifest(); 186 | if (mergeManifest.mergeManifest()) { 187 | Log.log("successful!\n\n", Log.LOG_LEVEL_NORMAL); 188 | } else { 189 | Log.log("failed!\n\n", Log.LOG_LEVEL_NORMAL); 190 | } 191 | } 192 | mergingTimer.stop(); 193 | 194 | if (OPTION_CHECK) { 195 | // CHECK 196 | Log.log("*** Step 6/" + steps + ": Merging Flows ***", Log.LOG_LEVEL_NORMAL); 197 | 198 | // Run both analysis 199 | final AQLHandler aqlHandler = new AQLHandler(); 200 | final Timer singleAnalysisTimer = new Timer().start(); 201 | final Answer unified = aqlHandler.runAQL1(); 202 | singleAnalysisTimer.stop(); 203 | final Timer mergedAnalysisTimer = new Timer().start(); 204 | final Answer analyzed = aqlHandler.runAQL2(); 205 | mergedAnalysisTimer.stop(); 206 | Log.log("successful!\n\n", Log.LOG_LEVEL_NORMAL); 207 | 208 | // Output 209 | sb = new StringBuilder("Check-Result:\n"); 210 | evaluate(sb, unified, analyzed); 211 | sb.append("Analysis time consumed to analyze all input apps:\n\tone by one: " 212 | + singleAnalysisTimer.getTime(Timer.FORMAT_S) + "s\n\tmerged: " 213 | + mergedAnalysisTimer.getTime(Timer.FORMAT_S) + "s"); 214 | final int speedup = (100 - (int) Math.round((Double.valueOf(mergedAnalysisTimer.getTime()).doubleValue() 215 | / Double.valueOf(singleAnalysisTimer.getTime()).doubleValue()) * 100d)); 216 | sb.append( 217 | "\nSpeedUp: " + speedup + "%\n(Time for merging: " + mergingTimer.getTime(Timer.FORMAT_S) + "s)\n"); 218 | 219 | // COMPARISON 220 | if (OPTION_COMPARISON) { 221 | Log.log("*** Step 7/" + steps + ": Comparing to ApkCombiner ***", Log.LOG_LEVEL_NORMAL); 222 | 223 | final Comparison comparison = new Comparison(); 224 | comparison.compare(sb, unified, analyzed, mergingTimer.getTime() + mergedAnalysisTimer.getTime()); 225 | Log.log("successful!\n\n", Log.LOG_LEVEL_NORMAL); 226 | } 227 | 228 | Log.log(sb.toString(), Log.LOG_LEVEL_NORMAL); 229 | } 230 | 231 | final File outputFolder = FileManager.moveToOutput(); 232 | Log.log("Stored in: " + outputFolder.getAbsolutePath() + "\n\n", Log.LOG_LEVEL_NORMAL); 233 | amtTimer.stop(); 234 | Log.log("AMT finished! (" + amtTimer.getTime(Timer.FORMAT_S) + "s)", Log.LOG_LEVEL_NORMAL); 235 | 236 | try (PrintWriter out = new PrintWriter(new File(outputFolder, "log.txt"))) { 237 | out.println(Log.getLog()); 238 | } catch (final FileNotFoundException e) { 239 | Log.log("Could not write logfile. (" + e.getClass().getSimpleName() + ": " + e.getMessage() + ")", 240 | Log.LOG_LEVEL_ERROR); 241 | } 242 | } 243 | 244 | private void evaluate(StringBuilder sb, Answer answerHaystack, Answer answerNeedle) { 245 | final EqualsOptions options = EqualsOptions.DEFAULT.setOption(EqualsOptions.IGNORE_APP, true); 246 | if (EqualsHelper.equals(answerHaystack, answerNeedle, options)) { 247 | sb.append("Success (Answers are equal!)\n"); 248 | } else { 249 | final Answer missingFlows = new Answer(); 250 | missingFlows.setFlows(new Flows()); 251 | final Answer neverFoundFlows = new Answer(); 252 | neverFoundFlows.setFlows(new Flows()); 253 | neverFoundFlows.getFlows().getFlow().addAll(answerNeedle.getFlows().getFlow()); 254 | boolean contained = true; 255 | if (answerHaystack.getFlows() != null && !answerHaystack.getFlows().getFlow().isEmpty()) { 256 | for (final Flow needle : answerHaystack.getFlows().getFlow()) { 257 | boolean found = false; 258 | if (answerNeedle.getFlows() != null && !answerNeedle.getFlows().getFlow().isEmpty()) { 259 | for (final Flow candidate : answerNeedle.getFlows().getFlow()) { 260 | if (EqualsHelper.equals(needle, candidate, options)) { 261 | found = true; 262 | neverFoundFlows.getFlows().getFlow().remove(candidate); 263 | break; 264 | } 265 | } 266 | } 267 | if (!found) { 268 | contained = false; 269 | missingFlows.getFlows().getFlow().add(needle); 270 | } 271 | } 272 | if (!missingFlows.getFlows().getFlow().isEmpty()) { 273 | final File outputMissing = new File( 274 | Config.getInstance().getSootOutputPath() + File.separator + "check_missing.xml"); 275 | AnswerHandler.createXML(missingFlows, outputMissing); 276 | } 277 | if (!neverFoundFlows.getFlows().getFlow().isEmpty()) { 278 | final File outputNeverFound = new File( 279 | Config.getInstance().getSootOutputPath() + File.separator + "check_new.xml"); 280 | AnswerHandler.createXML(neverFoundFlows, outputNeverFound); 281 | } 282 | } 283 | if (contained) { 284 | sb.append("Partial-Success (Answer is contained!)\n"); 285 | } else { 286 | sb.append("Failed (" + missingFlows.getFlows().getFlow().size() + " of " 287 | + answerHaystack.getFlows().getFlow().size() + " flows missing!)\n"); 288 | } 289 | } 290 | } 291 | } 292 | -------------------------------------------------------------------------------- /src/de/upb/mike/amt/Config.java: -------------------------------------------------------------------------------- 1 | package de.upb.mike.amt; 2 | 3 | import java.io.File; 4 | import java.util.List; 5 | 6 | public class Config { 7 | private static Config instance = new Config(); 8 | 9 | private String androidPlatformPath; 10 | private String sootOutputPath; 11 | private String apktoolJar; 12 | private File apktoolPathFile; 13 | private File aqlConfig; 14 | private File outputFolder; 15 | private String aqlQuery; 16 | private String comparisonAqlQuery; 17 | private List appPathList; 18 | private List defaultExcludes; 19 | 20 | private Config() { 21 | } 22 | 23 | public static Config getInstance() { 24 | return instance; 25 | } 26 | 27 | public String getAndroidPlatformPath() { 28 | return this.androidPlatformPath; 29 | } 30 | 31 | public void setAndroidPlatformPath(String androidPlatformPath) { 32 | this.androidPlatformPath = androidPlatformPath; 33 | } 34 | 35 | public String getSootOutputPath() { 36 | return this.sootOutputPath; 37 | } 38 | 39 | public void setSootOutputPath(String sootOutputPath) { 40 | this.sootOutputPath = sootOutputPath; 41 | } 42 | 43 | public File getApktoolPath() { 44 | return this.apktoolPathFile; 45 | } 46 | 47 | public void setApktoolPath(String apktoolPath) { 48 | this.apktoolPathFile = new File(apktoolPath); 49 | } 50 | 51 | public String getApktoolJar() { 52 | return this.apktoolJar; 53 | } 54 | 55 | public void setApktoolJar(String apktoolJar) { 56 | this.apktoolJar = apktoolJar; 57 | } 58 | 59 | public List getAppPathList() { 60 | return this.appPathList; 61 | } 62 | 63 | public void setAppPathList(List appPathList) { 64 | this.appPathList = appPathList; 65 | } 66 | 67 | public File getAqlConfig() { 68 | return this.aqlConfig; 69 | } 70 | 71 | public void setAqlConfig(File aqlConfig) { 72 | this.aqlConfig = aqlConfig; 73 | } 74 | 75 | public void setOutputFolder(File outputFolder) { 76 | this.outputFolder = outputFolder; 77 | } 78 | 79 | public File getOutputFolder() { 80 | return this.outputFolder; 81 | } 82 | 83 | public String getAqlQuery() { 84 | return this.aqlQuery; 85 | } 86 | 87 | public void setAqlQuery(String aqlQuery) { 88 | this.aqlQuery = aqlQuery; 89 | } 90 | 91 | public String getComparisonAqlQuery() { 92 | return this.comparisonAqlQuery; 93 | } 94 | 95 | public void setComparisonAqlQuery(String comparisonAqlQuery) { 96 | this.comparisonAqlQuery = comparisonAqlQuery; 97 | } 98 | 99 | public List getDefaultExcludes() { 100 | return this.defaultExcludes; 101 | } 102 | 103 | public void setDefaultExcludes(List defaultExcludes) { 104 | this.defaultExcludes = defaultExcludes; 105 | } 106 | } -------------------------------------------------------------------------------- /src/de/upb/mike/amt/Data.java: -------------------------------------------------------------------------------- 1 | package de.upb.mike.amt; 2 | 3 | import java.io.File; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | import java.util.concurrent.ConcurrentHashMap; 7 | 8 | import org.w3c.dom.Document; 9 | 10 | import de.foellix.aql.datastructure.Hash; 11 | import de.foellix.aql.helper.HashHelper; 12 | import soot.SootClass; 13 | 14 | public class Data { 15 | private static Data instance = new Data(); 16 | 17 | private Map sootClassMap = new ConcurrentHashMap<>(); 18 | private Map docMap = new HashMap<>(); 19 | private Map lifecycleMethodSignaturesChanged = new ConcurrentHashMap<>(); 20 | private Map classesChanged = new ConcurrentHashMap<>(); 21 | private Map hashMap = new ConcurrentHashMap<>(); 22 | private Map packageMap = new HashMap<>(); 23 | 24 | private Data() { 25 | } 26 | 27 | public static Data getInstance() { 28 | return instance; 29 | } 30 | 31 | public void receiveClass(SootClass sc, File appFile) { 32 | if (!this.sootClassMap.containsKey(sc) && !sc.isPhantom()) { 33 | this.sootClassMap.put(sc, new SootObjHashed(sc.getName(), putOrGetMapEntry(appFile))); 34 | } 35 | } 36 | 37 | public Hash putOrGetMapEntry(File appFile) { 38 | Hash appHash; 39 | if (this.hashMap.containsKey(appFile)) { 40 | appHash = this.hashMap.get(appFile); 41 | } else { 42 | appHash = new Hash(); 43 | appHash.setType(HashHelper.HASH_TYPE_SHA1); 44 | appHash.setValue(HashHelper.sha1Hash(appFile)); 45 | this.hashMap.put(appFile, appHash); 46 | } 47 | return appHash; 48 | } 49 | 50 | public Map getSootClassMap() { 51 | return this.sootClassMap; 52 | } 53 | 54 | public Map getDocMap() { 55 | return this.docMap; 56 | } 57 | 58 | public Map getLifecycleMethodSignaturesChanged() { 59 | return this.lifecycleMethodSignaturesChanged; 60 | } 61 | 62 | public Map getClassesChanged() { 63 | return this.classesChanged; 64 | } 65 | 66 | public Map getPackageMap() { 67 | return this.packageMap; 68 | } 69 | 70 | public Map getHashMap() { 71 | return this.hashMap; 72 | } 73 | } -------------------------------------------------------------------------------- /src/de/upb/mike/amt/Log.java: -------------------------------------------------------------------------------- 1 | package de.upb.mike.amt; 2 | 3 | import java.io.IOException; 4 | import java.io.OutputStream; 5 | import java.io.PrintStream; 6 | import java.text.SimpleDateFormat; 7 | import java.util.Date; 8 | 9 | public class Log { 10 | private static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("MM/dd/yyyy - hh:mm:ss"); 11 | 12 | public static final int LOG_LEVEL_ERROR = -2; 13 | public static final int LOG_LEVEL_WARNING = -1; 14 | public static final int LOG_LEVEL_NORMAL = 1; 15 | public static final int LOG_LEVEL_DEBUG = 2; 16 | public static final int LOG_LEVEL_DETAILED = 3; 17 | public static final int LOG_LEVEL_VERBOSE = 4; 18 | 19 | private static StringBuilder log = new StringBuilder(); 20 | 21 | public static int loglevel = LOG_LEVEL_NORMAL; 22 | public static boolean silence = false; 23 | 24 | private static PrintStream out = System.out; 25 | private static PrintStream err = System.err; 26 | private static PrintStream dummy = new PrintStream(new OutputStream() { 27 | @Override 28 | public void write(int b) throws IOException { 29 | // do nothing 30 | } 31 | }); 32 | 33 | public static void log(String msg, int loglevel) { 34 | if (loglevel <= Log.loglevel) { 35 | msg = DATE_TIME_FORMAT.format(new Date()) + " AMT-Log> " + msg; 36 | log.append(msg + "\n"); 37 | Log.out.println(msg); 38 | } 39 | } 40 | 41 | public static String getLog() { 42 | return log.toString(); 43 | } 44 | 45 | public static void silence(boolean on) { 46 | silence = on; 47 | if (on && loglevel < LOG_LEVEL_DETAILED) { 48 | System.setOut(dummy); 49 | System.setErr(dummy); 50 | } else { 51 | System.setOut(out); 52 | System.setErr(err); 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /src/de/upb/mike/amt/Properties.java: -------------------------------------------------------------------------------- 1 | package de.upb.mike.amt; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.InputStream; 5 | 6 | public class Properties { 7 | private static final String PROPERTIES_FILE = "amt.properties"; 8 | 9 | public static final String ANDROID_PLATFORMS = "androidPlatforms"; 10 | public static final String SOOT_OUTPUTPATH = "sootOutputPath"; 11 | public static final String APKTOOLPATH = "apktoolPath"; 12 | public static final String APKTOOLJAR = "apktoolJar"; 13 | public static final String AQLQUERY = "aqlQuery"; 14 | public static final String CPOMPARISON_AQLQUERY = "comparisonAqlQuery"; 15 | public static final String OUTPUTFOLDER = "outputFolder"; 16 | public static final String DEFAULT_EXCLUDES = "defaultExcludes"; 17 | 18 | private static Properties i = new Properties(); 19 | 20 | private java.util.Properties properties; 21 | 22 | private Properties() { 23 | this.properties = new java.util.Properties(); 24 | try { 25 | final InputStream in = new FileInputStream(PROPERTIES_FILE); 26 | this.properties.load(in); 27 | in.close(); 28 | } catch (final Exception e) { 29 | Log.log("Could not read properties file: " + PROPERTIES_FILE, Log.LOG_LEVEL_ERROR); 30 | } 31 | } 32 | 33 | public static Properties getInstance() { 34 | return i; 35 | } 36 | 37 | public String getProperty(String name) { 38 | return this.properties.getProperty(name); 39 | } 40 | } -------------------------------------------------------------------------------- /src/de/upb/mike/amt/SootObjHashed.java: -------------------------------------------------------------------------------- 1 | package de.upb.mike.amt; 2 | 3 | import de.foellix.aql.datastructure.Hash; 4 | import de.foellix.aql.helper.EqualsHelper; 5 | 6 | public class SootObjHashed { 7 | private String classname; 8 | private Hash hash; 9 | 10 | public SootObjHashed(String sootObjectName, Hash hash) { 11 | super(); 12 | this.classname = sootObjectName; 13 | this.hash = hash; 14 | } 15 | 16 | public String getClassname() { 17 | return classname; 18 | } 19 | 20 | public void setClassname(String classname) { 21 | this.classname = classname; 22 | } 23 | 24 | public Hash getHash() { 25 | return hash; 26 | } 27 | 28 | public void setHash(Hash hash) { 29 | this.hash = hash; 30 | } 31 | 32 | @Override 33 | public int hashCode() { 34 | String toHash = classname + hash.getValue(); 35 | return toHash.hashCode(); 36 | } 37 | 38 | @Override 39 | public boolean equals(Object obj) { 40 | if (this == obj) { 41 | return true; 42 | } 43 | if (obj == null) { 44 | return false; 45 | } 46 | if (getClass() != obj.getClass()) { 47 | return false; 48 | } 49 | SootObjHashed other = (SootObjHashed) obj; 50 | if (classname == null) { 51 | if (other.classname != null) { 52 | return false; 53 | } 54 | } else if (!classname.equals(other.classname)) { 55 | return false; 56 | } 57 | if (hash == null) { 58 | if (other.hash != null) { 59 | return false; 60 | } 61 | } else if (!EqualsHelper.equals(hash, other.hash)) { 62 | return false; 63 | } 64 | return true; 65 | } 66 | 67 | @Override 68 | public String toString() { 69 | return classname + ", " + hash.getValue() + " (" + hash.getType() + ")"; 70 | } 71 | } -------------------------------------------------------------------------------- /src/de/upb/mike/amt/Timer.java: -------------------------------------------------------------------------------- 1 | package de.upb.mike.amt; 2 | 3 | public class Timer { 4 | public static final int FORMAT_MS = 0; 5 | public static final int FORMAT_S = 1; 6 | public static final int FORMAT_M = 2; 7 | public static final int FORMAT_H = 3; 8 | 9 | long start; 10 | long end; 11 | 12 | public Timer() { 13 | start = 0; 14 | end = start; 15 | } 16 | 17 | public Timer start() { 18 | start = System.currentTimeMillis(); 19 | return this; 20 | } 21 | 22 | public Timer stop() { 23 | end = System.currentTimeMillis(); 24 | return this; 25 | } 26 | 27 | public long getTime() { 28 | return getTime(FORMAT_MS); 29 | } 30 | 31 | public long getTime(int format) { 32 | if (start > 0 && end > 0) { 33 | long time = end - start; 34 | if (format >= FORMAT_S) { 35 | time = time / 1000; 36 | } 37 | if (format >= FORMAT_M) { 38 | time = time / 60; 39 | } 40 | if (format >= FORMAT_H) { 41 | time = time / 60; 42 | } 43 | return time; 44 | } else { 45 | return -1; 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /src/de/upb/mike/amt/aql/AQLHandler.java: -------------------------------------------------------------------------------- 1 | package de.upb.mike.amt.aql; 2 | 3 | import java.io.File; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import de.foellix.aql.datastructure.Answer; 8 | import de.foellix.aql.datastructure.Hash; 9 | import de.foellix.aql.datastructure.Reference; 10 | import de.foellix.aql.datastructure.handler.AnswerHandler; 11 | import de.foellix.aql.helper.HashHelper; 12 | import de.foellix.aql.helper.Helper; 13 | import de.upb.mike.amt.Config; 14 | import de.upb.mike.amt.Data; 15 | import de.upb.mike.amt.Log; 16 | import de.upb.mike.amt.SootObjHashed; 17 | 18 | public class AQLHandler { 19 | private List aqlResultList; 20 | private File outputUnified, outputOverapproximated, outputAnalyzed; 21 | 22 | public AQLHandler() { 23 | this.aqlResultList = new ArrayList<>(); 24 | 25 | if (Log.loglevel < Log.LOG_LEVEL_DETAILED) { 26 | de.foellix.aql.Log.setLogLevel(de.foellix.aql.Log.NONE); 27 | } else if (Log.loglevel == Log.LOG_LEVEL_DETAILED) { 28 | de.foellix.aql.Log.setShorten(true); 29 | } else if (Log.loglevel == Log.LOG_LEVEL_VERBOSE) { 30 | de.foellix.aql.Log.setLogLevel(de.foellix.aql.Log.DEBUG_DETAILED); 31 | } 32 | 33 | this.outputUnified = new File(Config.getInstance().getSootOutputPath() + File.separator + "unified.xml"); 34 | this.outputOverapproximated = new File( 35 | Config.getInstance().getSootOutputPath() + File.separator + "overapproximated.xml"); 36 | this.outputAnalyzed = new File(Config.getInstance().getSootOutputPath() + File.separator + "analyzed.xml"); 37 | } 38 | 39 | public Answer runAQL1() { 40 | for (final File apkFile : Config.getInstance().getAppPathList()) { 41 | final String query = new String(Config.getInstance().getAqlQuery()).replaceAll("%APP_APK%", 42 | apkFile.getAbsolutePath().replaceAll("\\\\", "/")); 43 | final AQLRunner aqlObject = new AQLRunner(query); 44 | this.aqlResultList.add(resolveChanges(aqlObject.parseApp(), apkFile)); 45 | } 46 | 47 | AQLRunner.mergeFlows(this.aqlResultList, this.outputOverapproximated, true); 48 | return AQLRunner.mergeFlows(this.aqlResultList, this.outputUnified, false); 49 | } 50 | 51 | public Answer runAQL2() { 52 | final File mergedApk = new File(Config.getInstance().getSootOutputPath() + "/merged.apk"); 53 | if (mergedApk.exists()) { 54 | final String query = new String(Config.getInstance().getAqlQuery()).replaceAll("%APP_APK%", 55 | mergedApk.getAbsolutePath().replaceAll("\\\\", "/")); 56 | final AQLRunner aqlObject = new AQLRunner(query); 57 | final Answer analyzed = aqlObject.parseApp(); 58 | 59 | AnswerHandler.createXML(analyzed, this.outputAnalyzed); 60 | return analyzed; 61 | } 62 | return new Answer(); 63 | } 64 | 65 | private Answer resolveChanges(Answer answer, File appFile) { 66 | final Hash appHash = new Hash(); 67 | appHash.setType(HashHelper.HASH_TYPE_SHA1); 68 | appHash.setValue(HashHelper.sha1Hash(appFile)); 69 | 70 | for (final Reference ref : Helper.getAllReferences(answer, true)) { 71 | final SootObjHashed appSootClass = new SootObjHashed(ref.getClassname(), appHash); 72 | if (Data.getInstance().getClassesChanged().containsKey(appSootClass)) { 73 | ref.setMethod(ref.getMethod().replace(ref.getClassname(), 74 | Data.getInstance().getClassesChanged().get(appSootClass))); 75 | ref.setClassname(Data.getInstance().getClassesChanged().get(appSootClass)); 76 | } 77 | if (Data.getInstance().getLifecycleMethodSignaturesChanged().containsKey(ref.getMethod())) { 78 | ref.setMethod(Data.getInstance().getLifecycleMethodSignaturesChanged().get(ref.getMethod())); 79 | } 80 | } 81 | return answer; 82 | } 83 | } -------------------------------------------------------------------------------- /src/de/upb/mike/amt/aql/AQLRunner.java: -------------------------------------------------------------------------------- 1 | package de.upb.mike.amt.aql; 2 | 3 | import java.io.File; 4 | import java.util.ArrayList; 5 | import java.util.Collection; 6 | import java.util.List; 7 | 8 | import de.foellix.aql.datastructure.Answer; 9 | import de.foellix.aql.datastructure.Flow; 10 | import de.foellix.aql.datastructure.Flows; 11 | import de.foellix.aql.datastructure.Reference; 12 | import de.foellix.aql.datastructure.handler.AnswerHandler; 13 | import de.foellix.aql.helper.EqualsHelper; 14 | import de.foellix.aql.helper.Helper; 15 | import de.foellix.aql.helper.KeywordsAndConstantsHelper; 16 | import de.foellix.aql.system.AQLSystem; 17 | import de.foellix.aql.system.Options; 18 | import de.foellix.aql.system.defaulttools.operators.DefaultUnifyOperator; 19 | import de.upb.mike.amt.Config; 20 | import de.upb.mike.amt.Log; 21 | 22 | public class AQLRunner { 23 | private AQLSystem aqlSystem; 24 | private String query; 25 | 26 | public AQLRunner(String query) { 27 | this.query = query; 28 | this.aqlSystem = new AQLSystem(new Options().setConfig(Config.getInstance().getAqlConfig())); 29 | } 30 | 31 | public Answer parseApp() { 32 | Log.log("Issuing AQL-Query: \"" + this.query + "\"", Log.LOG_LEVEL_DEBUG); 33 | Log.silence(true); 34 | final Collection answerList = this.aqlSystem.queryAndWait(this.query); 35 | Log.silence(false); 36 | 37 | if (answerList != null && answerList.iterator().hasNext()) { 38 | return (Answer) answerList.iterator().next(); 39 | } else { 40 | return new Answer(); 41 | } 42 | } 43 | 44 | public static Answer mergeFlows(List resultList, File outputFile, boolean overapproximate) { 45 | // Apply unify operator 46 | Answer mergedAnswer = new Answer(); 47 | for (final Answer answer : resultList) { 48 | mergedAnswer = new DefaultUnifyOperator().unify(mergedAnswer, answer); 49 | } 50 | if (mergedAnswer.getFlows() == null) { 51 | mergedAnswer.setFlows(new Flows()); 52 | } 53 | 54 | // Over-approximate 55 | if (overapproximate) { 56 | final Collection flowsToAdd = new ArrayList<>(); 57 | for (final Flow flow : mergedAnswer.getFlows().getFlow()) { 58 | final Reference from = Helper.getFrom(flow.getReference()); 59 | final Reference toExists = Helper.getTo(flow.getReference()); 60 | for (final Reference to : Helper.getAllReferences(mergedAnswer)) { 61 | if (to.getType().equals(KeywordsAndConstantsHelper.REFERENCE_TYPE_TO) 62 | && !EqualsHelper.equals(toExists, to)) { 63 | final Flow flowToAdd = new Flow(); 64 | flowToAdd.getReference().add(from); 65 | flowToAdd.getReference().add(to); 66 | flowsToAdd.add(flowToAdd); 67 | } 68 | } 69 | } 70 | mergedAnswer.getFlows().getFlow().addAll(flowsToAdd); 71 | } 72 | 73 | // Write to file 74 | AnswerHandler.createXML(mergedAnswer, outputFile); 75 | 76 | // Return merged answer 77 | return mergedAnswer; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/de/upb/mike/amt/conflicresolution/ConflictResolution.java: -------------------------------------------------------------------------------- 1 | package de.upb.mike.amt.conflicresolution; 2 | 3 | import java.util.Set; 4 | 5 | import de.upb.mike.amt.Data; 6 | import de.upb.mike.amt.Log; 7 | import soot.SootClass; 8 | import soot.util.Chain; 9 | 10 | public class ConflictResolution { 11 | private static int counter = 0; 12 | 13 | private Chain sootClasses; 14 | 15 | public ConflictResolution(Chain initSootClasses) { 16 | this.sootClasses = initSootClasses; 17 | } 18 | 19 | public void resolveConflictOuter(SootClass sootClass, Set innerClasses) { 20 | // Resolve conflicts 21 | if (isConflicted(sootClass.getName())) { 22 | final String oldName = sootClass.getName(); 23 | final String newName = makeUnique(sootClass.getName()); 24 | resolveConflictInner(innerClasses, oldName, newName); 25 | rename(sootClass, oldName, newName, false); 26 | } 27 | 28 | // Add classes 29 | this.sootClasses.add(sootClass); 30 | for (final SootClass innerClass : innerClasses) { 31 | this.sootClasses.add(innerClass); 32 | } 33 | } 34 | 35 | private void resolveConflictInner(Set innerClasses, String outestClassOldName, 36 | String outestClassNewName) { 37 | for (final SootClass sootClass : innerClasses) { 38 | final String oldName = new String(sootClass.getName()); 39 | final String newName = sootClass.getName().replace(outestClassOldName, outestClassNewName); 40 | rename(sootClass, oldName, newName, true); 41 | } 42 | } 43 | 44 | private void rename(SootClass sootClass, String oldName, String newName, boolean innerClass) { 45 | sootClass.rename(newName); 46 | Data.getInstance().getClassesChanged().put(Data.getInstance().getSootClassMap().get(sootClass), newName); 47 | Log.log("Class \"" + oldName + "\" renamed to \"" + newName + "\" (" + (innerClass ? "inner" : "outer") 48 | + " class)", Log.LOG_LEVEL_DETAILED); 49 | } 50 | 51 | private String makeUnique(String name) { 52 | String nameUnique = name; 53 | do { 54 | counter++; 55 | nameUnique = name + "_" + counter; 56 | } while (isConflicted(nameUnique)); 57 | return nameUnique; 58 | } 59 | 60 | private boolean isConflicted(String sootClassName) { 61 | for (final SootClass conflictClass : this.sootClasses) { 62 | final String conflictClassName = conflictClass.getName(); 63 | if (sootClassName.equals(conflictClassName)) { 64 | return true; 65 | } 66 | } 67 | return false; 68 | } 69 | } -------------------------------------------------------------------------------- /src/de/upb/mike/amt/evaluation/Comparison.java: -------------------------------------------------------------------------------- 1 | package de.upb.mike.amt.evaluation; 2 | 3 | import java.io.File; 4 | 5 | import de.foellix.aql.datastructure.Answer; 6 | import de.foellix.aql.datastructure.handler.AnswerHandler; 7 | import de.upb.mike.amt.Config; 8 | import de.upb.mike.amt.Timer; 9 | import de.upb.mike.amt.aql.AQLRunner; 10 | 11 | public class Comparison { 12 | private File outputCombined; 13 | 14 | public void compare(StringBuilder sb, Answer unified, Answer analyzed, long mergedAnalysisTime) { 15 | this.outputCombined = new File(Config.getInstance().getSootOutputPath() + File.separator + "combined.xml"); 16 | final Timer combinedAnalysisTimer = new Timer().start(); 17 | final Answer combined = runAQL(); 18 | combinedAnalysisTimer.stop(); 19 | 20 | final int speedup = (100 - (int) Math.round((Double.valueOf(mergedAnalysisTime).doubleValue() 21 | / Double.valueOf(combinedAnalysisTimer.getTime()).doubleValue()) * 100d)); 22 | 23 | sb.append("\nApkCombiner compared to unified (Combining + Analysis time: " 24 | + combinedAnalysisTimer.getTime(Timer.FORMAT_S) + "s):\n"); 25 | evaluate(sb, unified, combined); 26 | sb.append("\nAMT compared to ApkCombiner (SpeedUp: " + speedup + "%):\n"); 27 | evaluate(sb, combined, analyzed); 28 | } 29 | 30 | public Answer runAQL() { 31 | final StringBuilder sb = new StringBuilder(); 32 | boolean first = true; 33 | for (final File file : Config.getInstance().getAppPathList()) { 34 | if (!first) { 35 | sb.append(", "); 36 | } else { 37 | first = false; 38 | } 39 | sb.append(file.getAbsolutePath()); 40 | } 41 | final String query = Config.getInstance().getComparisonAqlQuery().replaceAll("%APP_APK%", 42 | sb.toString().replaceAll("\\\\", "/")); 43 | final AQLRunner aqlObject = new AQLRunner(query); 44 | final Answer combined = aqlObject.parseApp(); 45 | 46 | AnswerHandler.createXML(combined, this.outputCombined); 47 | return combined; 48 | } 49 | 50 | private void evaluate(StringBuilder sb, Answer answerHaystack, Answer answerNeedle) { 51 | if (answerHaystack == null && answerNeedle == null) { 52 | sb.append("Success (Both answers are null)\n"); 53 | } else if ((answerHaystack != null && answerNeedle == null) 54 | || (answerHaystack == null && answerNeedle != null)) { 55 | sb.append("Failed (One answer is null while the other one is not)\n"); 56 | } else if ((answerHaystack.getFlows() == null && answerNeedle.getFlows() == null) 57 | || ((answerHaystack.getFlows() == null || answerHaystack.getFlows().getFlow().isEmpty()) 58 | && (answerNeedle.getFlows() == null || answerNeedle.getFlows().getFlow().isEmpty()))) { 59 | sb.append("Success (Both answers are empty)\n"); 60 | } else if ((answerHaystack.getFlows() == null 61 | && (answerNeedle != null && !answerNeedle.getFlows().getFlow().isEmpty())) 62 | || (answerNeedle.getFlows() == null 63 | && (answerHaystack != null && !answerHaystack.getFlows().getFlow().isEmpty()))) { 64 | sb.append("Failed (One answer is empty while the other one is not)\n"); 65 | } else if (answerHaystack.getFlows().getFlow().size() == answerNeedle.getFlows().getFlow().size()) { 66 | sb.append("Possible Success (Number of flows: " + answerNeedle.getFlows().getFlow().size() + " equal to " 67 | + answerHaystack.getFlows().getFlow().size() + ")\n"); 68 | } else { 69 | sb.append("Failed (Number of flows: " + answerNeedle.getFlows().getFlow().size() + " unequal to " 70 | + answerHaystack.getFlows().getFlow().size() + ")\n"); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/de/upb/mike/amt/helper/FileManager.java: -------------------------------------------------------------------------------- 1 | package de.upb.mike.amt.helper; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | import com.google.common.io.Files; 9 | 10 | import de.foellix.aql.helper.HashHelper; 11 | import de.foellix.aql.helper.Helper; 12 | import de.upb.mike.amt.Config; 13 | import de.upb.mike.amt.Log; 14 | 15 | public class FileManager { 16 | public static boolean deleteDir(String path) { 17 | return deleteDir(new File(path)); 18 | } 19 | 20 | public static boolean deleteDir(File file) { 21 | if (!file.exists()) { 22 | return true; 23 | } 24 | if (file.isDirectory()) { 25 | for (final File temp : file.listFiles()) { 26 | if (!deleteDir(temp)) { 27 | Log.log("Failed to delete " + temp.getAbsolutePath(), Log.LOG_LEVEL_ERROR); 28 | } 29 | } 30 | } 31 | Log.log("Deleting directory/file: " + file.getAbsolutePath(), Log.LOG_LEVEL_VERBOSE); 32 | return file.delete(); 33 | } 34 | 35 | public static boolean moveFile(String startPath, String endPath) { 36 | final File startFile = new File(startPath); 37 | File endFile = new File(endPath); 38 | if (endFile.isDirectory()) { 39 | endFile = new File(endPath, startFile.getName()); 40 | } 41 | return moveFile(startFile, endFile); 42 | } 43 | 44 | public static boolean moveFile(File startFile, File endFile) { 45 | if (endFile.exists()) { 46 | endFile.delete(); 47 | } 48 | if (!startFile.renameTo(endFile)) { 49 | Log.log("File could not be moved from " + startFile.getAbsolutePath() + " to " + endFile.getAbsolutePath(), 50 | Log.LOG_LEVEL_ERROR); 51 | return false; 52 | } 53 | Log.log("Moved file from " + startFile.getAbsolutePath() + " to " + endFile.getAbsolutePath(), 54 | Log.LOG_LEVEL_VERBOSE); 55 | return true; 56 | } 57 | 58 | public static void copyFile(String startPath, File endPath) { 59 | final File startFile = new File(startPath); 60 | final File endFile = new File(endPath, startFile.getName()); 61 | copyFile(startFile, endFile); 62 | } 63 | 64 | public static void copyFile(File startFile, File endFile) { 65 | if (endFile.exists()) { 66 | endFile.delete(); 67 | } 68 | try { 69 | Files.copy(startFile, endFile); 70 | Log.log("Copied file from " + startFile.getAbsolutePath() + " to " + endFile.getAbsolutePath(), 71 | Log.LOG_LEVEL_VERBOSE); 72 | } catch (final IOException e) { 73 | Log.log("File could not be copied from " + startFile.getAbsolutePath() + " to " + endFile.getAbsolutePath(), 74 | Log.LOG_LEVEL_ERROR); 75 | } 76 | } 77 | 78 | public static File moveToOutput() { 79 | final StringBuilder sb = new StringBuilder(); 80 | for (final File file : Config.getInstance().getAppPathList()) { 81 | sb.append((sb.length() > 0 ? "_" : "") + file.getName().replace(".apk", "")); 82 | } 83 | final File targetFolder = new File(Config.getInstance().getOutputFolder(), HashHelper.sha1Hash(sb.toString())); 84 | if (deleteDir(targetFolder) && targetFolder.mkdirs()) { 85 | final File sootOutputFolder = new File(Config.getInstance().getSootOutputPath()); 86 | for (final File file : sootOutputFolder.listFiles()) { 87 | if (file.getName().endsWith(".xml")) { 88 | file.renameTo(new File(targetFolder, file.getName())); 89 | } else if (file.getName().endsWith(".apk")) { 90 | final StringBuilder tempSB = new StringBuilder(); 91 | for (final File tempFile : Config.getInstance().getAppPathList()) { 92 | tempSB.append(tempFile.getAbsolutePath() + ", "); 93 | } 94 | final File copy = new File(targetFolder.getParentFile(), 95 | Helper.getMultipleApkName(tempSB.toString()) + "_merged.apk"); 96 | try { 97 | if (!copy.exists() || (copy.exists() && copy.delete())) { 98 | Files.copy(file, copy); 99 | } else { 100 | throw new IOException("Could not access file."); 101 | } 102 | } catch (final IOException e) { 103 | Log.log("Copying result to " + copy.getAbsolutePath() + " failed. (" 104 | + e.getClass().getSimpleName() + ": " + e.getMessage() + ")", Log.LOG_LEVEL_WARNING); 105 | } 106 | file.renameTo(new File(targetFolder, "merged.apk")); 107 | } 108 | } 109 | deleteDir(Config.getInstance().getSootOutputPath()); 110 | } 111 | return targetFolder; 112 | } 113 | 114 | public static List findApksInFolder(File folder) { 115 | final List apkFiles = new ArrayList<>(); 116 | for (final File file : folder.listFiles()) { 117 | if (file.isDirectory()) { 118 | apkFiles.addAll(findApksInFolder(file)); 119 | } else if (file.getName().endsWith(".apk")) { 120 | apkFiles.add(file); 121 | } 122 | } 123 | return apkFiles; 124 | } 125 | } -------------------------------------------------------------------------------- /src/de/upb/mike/amt/manifest/MergeManifest.java: -------------------------------------------------------------------------------- 1 | package de.upb.mike.amt.manifest; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.io.InputStreamReader; 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | import javax.xml.parsers.DocumentBuilder; 12 | import javax.xml.parsers.DocumentBuilderFactory; 13 | import javax.xml.transform.Transformer; 14 | import javax.xml.transform.TransformerFactory; 15 | import javax.xml.transform.dom.DOMSource; 16 | import javax.xml.transform.stream.StreamResult; 17 | 18 | import org.w3c.dom.Document; 19 | import org.w3c.dom.Node; 20 | import org.w3c.dom.NodeList; 21 | 22 | import de.upb.mike.amt.Config; 23 | import de.upb.mike.amt.Data; 24 | import de.upb.mike.amt.Log; 25 | import de.upb.mike.amt.SootObjHashed; 26 | import de.upb.mike.amt.helper.FileManager; 27 | 28 | public class MergeManifest { 29 | private static final String ANDROID_NAME = "android:name"; 30 | 31 | private File launcherApp; 32 | private String launcherAppName; 33 | 34 | public MergeManifest() { 35 | this.launcherApp = Config.getInstance().getAppPathList().get(0); 36 | this.launcherAppName = this.launcherApp.getName().substring(0, this.launcherApp.getName().lastIndexOf(".")); 37 | } 38 | 39 | public boolean mergeManifest() { 40 | boolean success = false; 41 | 42 | // Copy apk 43 | final File apkToolApk = new File(Config.getInstance().getApktoolPath(), 44 | Config.getInstance().getAppPathList().get(0).getName()); 45 | FileManager.moveFile(new File(Config.getInstance().getSootOutputPath(), 46 | Config.getInstance().getAppPathList().get(0).getName()), apkToolApk); 47 | 48 | // Modify Manifest 49 | modifyManifest(); 50 | 51 | // Copy back & delete input 52 | if (!FileManager.moveFile(Config.getInstance().getApktoolPath() + "/" + this.launcherAppName + "/dist/" 53 | + this.launcherApp.getName(), Config.getInstance().getSootOutputPath() + "/merged.apk")) { 54 | success = false; 55 | FileManager.moveFile(apkToolApk.getAbsolutePath(), 56 | Config.getInstance().getSootOutputPath() + "/merged.apk"); 57 | } else { 58 | apkToolApk.delete(); 59 | } 60 | 61 | // Delete temporary files and folders of ApkTool 62 | FileManager.deleteDir(Config.getInstance().getApktoolPath() + "/" + this.launcherAppName); 63 | FileManager.deleteDir(Config.getInstance().getApktoolPath() + "/" + this.launcherApp); 64 | 65 | return success; 66 | } 67 | 68 | private void modifyManifest() { 69 | executeCmdCommand("java -jar " + Config.getInstance().getApktoolJar() + " -f d " + this.launcherApp.getName(), 70 | Config.getInstance().getApktoolPath()); 71 | 72 | try { 73 | final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 74 | final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 75 | final File manifestFile = new File( 76 | Config.getInstance().getApktoolPath() + "/" + this.launcherAppName + "/AndroidManifest.xml"); 77 | final Document doc = dBuilder.parse(manifestFile); 78 | final Node manifestNode = doc.getElementsByTagName("manifest").item(0); 79 | final Node applicationNode = doc.getElementsByTagName("application").item(0); 80 | NodeList permissionNodes = doc.getElementsByTagName("uses-permission"); 81 | final List usesPermissions = new ArrayList<>(); 82 | for (int i = 0; i < permissionNodes.getLength(); i++) { 83 | if (permissionNodes.item(i).hasAttributes() 84 | && permissionNodes.item(i).getAttributes().getNamedItem(ANDROID_NAME) != null) { 85 | usesPermissions 86 | .add(permissionNodes.item(i).getAttributes().getNamedItem(ANDROID_NAME).getNodeValue()); 87 | } 88 | } 89 | NodeList activityNodes = doc.getElementsByTagName("activity"); 90 | 91 | for (final Document inputDoc : Data.getInstance().getDocMap().keySet()) { 92 | if (!Data.getInstance().getDocMap().get(inputDoc).getAbsolutePath() 93 | .equals(Config.getInstance().getAppPathList().get(0).getAbsolutePath())) { 94 | // Add permissions 95 | permissionNodes = inputDoc.getElementsByTagName("uses-permission"); 96 | for (int i = 0; i < permissionNodes.getLength(); i++) { 97 | if (permissionNodes.item(i).hasAttributes() 98 | && permissionNodes.item(i).getAttributes().getNamedItem(ANDROID_NAME) != null) { 99 | final String permissionStr = permissionNodes.item(i).getAttributes() 100 | .getNamedItem(ANDROID_NAME).getNodeValue(); 101 | if (!usesPermissions.contains(permissionStr)) { 102 | usesPermissions.add(permissionStr); 103 | manifestNode.insertBefore(doc.importNode(permissionNodes.item(i), true), 104 | manifestNode.getFirstChild()); 105 | Log.log("Permission added to manifest: " + permissionStr, Log.LOG_LEVEL_DETAILED); 106 | } 107 | } 108 | } 109 | // Add activities 110 | activityNodes = inputDoc.getElementsByTagName("activity"); 111 | for (int i = 0; i < activityNodes.getLength(); i++) { 112 | if (activityNodes.item(i).hasAttributes() 113 | && activityNodes.item(i).getAttributes().getNamedItem(ANDROID_NAME) != null) { 114 | String activityStr = activityNodes.item(i).getAttributes().getNamedItem(ANDROID_NAME) 115 | .getNodeValue(); 116 | if (activityStr.startsWith(".")) { 117 | activityStr = Data.getInstance().getPackageMap().get( 118 | Data.getInstance().getDocMap().get(inputDoc).getAbsolutePath()) + activityStr; 119 | } 120 | final SootObjHashed asc = new SootObjHashed(activityStr, 121 | Data.getInstance().getHashMap().get(Data.getInstance().getDocMap().get(inputDoc))); 122 | if (Data.getInstance().getClassesChanged().containsKey(asc)) { 123 | activityStr = Data.getInstance().getClassesChanged().get(asc); 124 | } 125 | 126 | final Node importNode = doc.importNode(activityNodes.item(i), true); 127 | importNode.getAttributes().getNamedItem(ANDROID_NAME).setNodeValue(activityStr); 128 | applicationNode.appendChild(importNode); 129 | 130 | // Delete intent-filter, if launcher 131 | final NodeList intentFilters = importNode.getChildNodes(); 132 | for (int j = 0; j < intentFilters.getLength(); j++) { 133 | final NodeList children = intentFilters.item(j).getChildNodes(); 134 | boolean actionFound = false; 135 | boolean categoryFound = false; 136 | for (int k = 0; k < children.getLength(); k++) { 137 | final Node element = children.item(k); 138 | if (element.hasAttributes()) { 139 | final Node attr = element.getAttributes().getNamedItem(ANDROID_NAME); 140 | if (attr != null) { 141 | final String name = attr.getNodeValue(); 142 | if (element.getNodeName().equals("action")) { 143 | if (name.equals("android.intent.action.MAIN")) { 144 | actionFound = true; 145 | } 146 | } else if (element.getNodeName().equals("category")) { 147 | if (name.equals("android.intent.category.LAUNCHER")) { 148 | categoryFound = true; 149 | } 150 | } 151 | if (actionFound && categoryFound) { 152 | break; 153 | } 154 | } 155 | } 156 | } 157 | if (actionFound && categoryFound) { 158 | importNode.removeChild(intentFilters.item(j)); 159 | j--; 160 | } 161 | } 162 | 163 | Log.log("Activity added to manifest: " + activityStr, Log.LOG_LEVEL_DETAILED); 164 | } 165 | } 166 | // Add everything else 167 | final NodeList other = inputDoc.getElementsByTagName("application").item(0).getChildNodes(); 168 | for (int i = 0; i < other.getLength(); i++) { 169 | if (!other.item(i).getNodeName().equals("activity") 170 | && !other.item(i).getNodeName().equals("#text")) { 171 | 172 | final Node importedNode = doc.importNode(other.item(i), true); 173 | if (importedNode.hasAttributes() 174 | && importedNode.getAttributes().getNamedItem(ANDROID_NAME) != null) { 175 | String nodeNameStr = importedNode.getAttributes().getNamedItem(ANDROID_NAME) 176 | .getNodeValue(); 177 | if (nodeNameStr.startsWith(".")) { 178 | nodeNameStr = Data.getInstance().getPackageMap() 179 | .get(Data.getInstance().getDocMap().get(inputDoc).getAbsolutePath()) 180 | + nodeNameStr; 181 | } 182 | importedNode.getAttributes().getNamedItem(ANDROID_NAME).setNodeValue(nodeNameStr); 183 | } 184 | applicationNode.appendChild(importedNode); 185 | 186 | Log.log(importedNode.getNodeName().substring(0, 1).toUpperCase() 187 | + importedNode.getNodeName().substring(1) + " added to manifest" 188 | + (importedNode.hasAttributes() 189 | && importedNode.getAttributes().getNamedItem(ANDROID_NAME) != null 190 | ? ": " + importedNode.getAttributes().getNamedItem(ANDROID_NAME) 191 | .getNodeValue() 192 | : "."), 193 | Log.LOG_LEVEL_DETAILED); 194 | } 195 | } 196 | } 197 | } 198 | 199 | final TransformerFactory transformerFactory = TransformerFactory.newInstance(); 200 | final Transformer transformer = transformerFactory.newTransformer(); 201 | transformer.transform(new DOMSource(doc), new StreamResult(manifestFile)); 202 | } catch (final Exception e) { 203 | Log.log("Could not merge manifests! (" + e.getClass().getSimpleName() + ": " + e.getMessage() + ")", 204 | Log.LOG_LEVEL_ERROR); 205 | if (Log.loglevel >= Log.LOG_LEVEL_DEBUG) { 206 | e.printStackTrace(); 207 | } 208 | } 209 | 210 | // Replace classes 211 | // for (final File dexFile : new File(Config.getInstance().getSootOutputPath()) 212 | // .listFiles((dir, name) -> name.toLowerCase().endsWith(".dex"))) { 213 | // final File moveTo = new File(Config.getInstance().getApktoolPath(), 214 | // this.launcherAppName + "/" + dexFile.getName()); 215 | // FileManager.moveFile(dexFile, moveTo); 216 | // } 217 | 218 | // Build APK with modified manifest 219 | executeCmdCommand("java -jar " + Config.getInstance().getApktoolJar() + " b " + this.launcherAppName, 220 | Config.getInstance().getApktoolPath()); 221 | } 222 | 223 | private static boolean running = true; 224 | 225 | public static void executeCmdCommand(String command, File workDir) { 226 | try { 227 | final ProcessBuilder pb = new ProcessBuilder(command.split(" ")); 228 | pb.directory(workDir); 229 | Log.log("Executing Apktool: " + command, Log.LOG_LEVEL_DEBUG); 230 | final Process process = pb.start(); 231 | 232 | running = true; 233 | // Pipe output 234 | new Thread(() -> { 235 | final InputStream in = process.getInputStream(); 236 | final BufferedReader br = new BufferedReader(new InputStreamReader(in)); 237 | try { 238 | while (running) { 239 | Thread.sleep(500); 240 | String line = br.readLine(); 241 | while (line != null) { 242 | Log.log(line, Log.LOG_LEVEL_DETAILED); 243 | line = br.readLine(); 244 | } 245 | } 246 | br.close(); 247 | } catch (final IOException | InterruptedException e) { 248 | Log.log("Error while running \"" + command + "\" in \"" + workDir.getAbsolutePath() + "\". (" 249 | + e.getClass().getSimpleName() + ": " + e.getMessage() + ")", Log.LOG_LEVEL_ERROR); 250 | if (Log.loglevel >= Log.LOG_LEVEL_DEBUG) { 251 | e.printStackTrace(); 252 | } 253 | } 254 | }).start(); 255 | // Pipe error-output 256 | new Thread(() -> { 257 | final InputStream err = process.getErrorStream(); 258 | final BufferedReader br = new BufferedReader(new InputStreamReader(err)); 259 | try { 260 | while (running) { 261 | Thread.sleep(500); 262 | String line = br.readLine(); 263 | while (line != null) { 264 | Log.log(line, Log.LOG_LEVEL_DETAILED); 265 | line = br.readLine(); 266 | } 267 | } 268 | br.close(); 269 | } catch (final IOException | InterruptedException e) { 270 | Log.log("Error while running \"" + command + "\" in \"" + workDir.getAbsolutePath() + "\". (" 271 | + e.getClass().getSimpleName() + ": " + e.getMessage() + ")", Log.LOG_LEVEL_ERROR); 272 | if (Log.loglevel >= Log.LOG_LEVEL_DEBUG) { 273 | e.printStackTrace(); 274 | } 275 | } 276 | }).start(); 277 | 278 | process.waitFor(); 279 | running = false; 280 | } catch (IOException | InterruptedException e) { 281 | Log.log("Error while running \"" + command + "\" in \"" + workDir.getAbsolutePath() + "\". (" 282 | + e.getClass().getSimpleName() + ": " + e.getMessage() + ")", Log.LOG_LEVEL_ERROR); 283 | if (Log.loglevel >= Log.LOG_LEVEL_DEBUG) { 284 | e.printStackTrace(); 285 | } 286 | } 287 | } 288 | } 289 | -------------------------------------------------------------------------------- /src/de/upb/mike/amt/manifest/ParseManifest.java: -------------------------------------------------------------------------------- 1 | package de.upb.mike.amt.manifest; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.File; 5 | import java.io.IOException; 6 | 7 | import javax.xml.parsers.DocumentBuilder; 8 | import javax.xml.parsers.DocumentBuilderFactory; 9 | 10 | import org.w3c.dom.Document; 11 | import org.w3c.dom.Node; 12 | import org.w3c.dom.NodeList; 13 | 14 | import de.upb.mike.amt.Data; 15 | import de.upb.mike.amt.Log; 16 | import net.dongliu.apk.parser.ApkParsers; 17 | 18 | public class ParseManifest { 19 | private File appFile; 20 | 21 | private String packageName; 22 | private String launcherActivity; 23 | private boolean containsLauncherActivity; 24 | 25 | public ParseManifest(File appFile) { 26 | this.appFile = appFile; 27 | this.containsLauncherActivity = false; 28 | parse(); 29 | } 30 | 31 | private void parse() { 32 | String manifestAsString = null; 33 | try { 34 | manifestAsString = ApkParsers.getManifestXml(this.appFile); 35 | Log.log("Manifest (" + this.appFile.getAbsolutePath() + ")\n" + manifestAsString, Log.LOG_LEVEL_VERBOSE); 36 | } catch (final IOException e) { 37 | Log.log("Could not read manifest of " + this.appFile.getAbsolutePath() + " (" + e.getClass().getSimpleName() 38 | + ": " + e.getMessage() + ")", Log.LOG_LEVEL_ERROR); 39 | } 40 | 41 | try { 42 | final ByteArrayInputStream input = new ByteArrayInputStream(manifestAsString.getBytes("UTF-8")); 43 | final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 44 | final DocumentBuilder builder = factory.newDocumentBuilder(); 45 | final Document doc = builder.parse(input); 46 | Data.getInstance().getDocMap().put(doc, this.appFile); 47 | 48 | // Package 49 | this.packageName = doc.getElementsByTagName("manifest").item(0).getAttributes().getNamedItem("package") 50 | .getNodeValue(); 51 | Log.log("Package identified: " + this.packageName, Log.LOG_LEVEL_DETAILED); 52 | 53 | // Launcher Activity 54 | final NodeList intentFilters = doc.getElementsByTagName("intent-filter"); 55 | for (int i = 0; i < intentFilters.getLength(); i++) { 56 | final Node intentFilter = intentFilters.item(i); 57 | final NodeList children = intentFilter.getChildNodes(); 58 | 59 | boolean actionFound = false; 60 | boolean categoryFound = false; 61 | for (int j = 0; j < children.getLength(); j++) { 62 | final Node element = children.item(j); 63 | if (element.hasAttributes()) { 64 | final Node attr = element.getAttributes().getNamedItem("android:name"); 65 | if (attr != null) { 66 | final String name = attr.getNodeValue(); 67 | if (element.getNodeName().equals("action")) { 68 | if (name.equals("android.intent.action.MAIN")) { 69 | actionFound = true; 70 | } 71 | } else if (element.getNodeName().equals("category")) { 72 | if (name.equals("android.intent.category.LAUNCHER")) { 73 | categoryFound = true; 74 | } 75 | } 76 | if (actionFound && categoryFound) { 77 | break; 78 | } 79 | } 80 | } 81 | } 82 | 83 | if (actionFound && categoryFound) { 84 | if (intentFilter.getParentNode().getNodeName().equals("activity-alias")) { 85 | this.launcherActivity = intentFilter.getParentNode().getAttributes() 86 | .getNamedItem("android:targetActivity").getNodeValue(); 87 | } else { 88 | this.launcherActivity = intentFilter.getParentNode().getAttributes() 89 | .getNamedItem("android:name").getNodeValue(); 90 | } 91 | if (this.launcherActivity.startsWith(".")) { 92 | this.launcherActivity = this.packageName + this.launcherActivity; 93 | } 94 | this.containsLauncherActivity = true; 95 | Log.log("Launcher-Activity found: " + this.launcherActivity + " (" + this.appFile.getAbsolutePath() 96 | + ")", Log.LOG_LEVEL_DETAILED); 97 | 98 | break; 99 | } 100 | } 101 | } catch (final Exception e) { 102 | Log.log("Could not parse manifest of " + this.appFile.getAbsolutePath() + " (" 103 | + e.getClass().getSimpleName() + ": " + e.getMessage() + ")", Log.LOG_LEVEL_ERROR); 104 | e.printStackTrace(); 105 | } 106 | } 107 | 108 | public String getPackageName() { 109 | return this.packageName; 110 | } 111 | 112 | public String getLauncherActivity() { 113 | return this.launcherActivity; 114 | } 115 | 116 | public boolean containsLauncherActivity() { 117 | return this.containsLauncherActivity; 118 | } 119 | } -------------------------------------------------------------------------------- /src/de/upb/mike/amt/soot/InstrumentationTransformer.java: -------------------------------------------------------------------------------- 1 | package de.upb.mike.amt.soot; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.HashMap; 6 | import java.util.HashSet; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.Set; 10 | 11 | import de.upb.mike.amt.AMT; 12 | import de.upb.mike.amt.Config; 13 | import de.upb.mike.amt.Data; 14 | import de.upb.mike.amt.Log; 15 | import de.upb.mike.amt.conflicresolution.ConflictResolution; 16 | import soot.Body; 17 | import soot.Local; 18 | import soot.Modifier; 19 | import soot.RefType; 20 | import soot.Scene; 21 | import soot.SceneTransformer; 22 | import soot.SootClass; 23 | import soot.SootField; 24 | import soot.SootMethod; 25 | import soot.SootMethodRefImpl; 26 | import soot.Type; 27 | import soot.Unit; 28 | import soot.VoidType; 29 | import soot.jimple.AssignStmt; 30 | import soot.jimple.FieldRef; 31 | import soot.jimple.IdentityStmt; 32 | import soot.jimple.IntConstant; 33 | import soot.jimple.InvokeExpr; 34 | import soot.jimple.InvokeStmt; 35 | import soot.jimple.Jimple; 36 | import soot.jimple.ParameterRef; 37 | import soot.jimple.ReturnVoidStmt; 38 | import soot.jimple.TableSwitchStmt; 39 | import soot.jimple.internal.JAssignStmt; 40 | import soot.jimple.internal.JIdentityStmt; 41 | import soot.jimple.internal.JInvokeStmt; 42 | import soot.jimple.internal.JNewExpr; 43 | import soot.util.Chain; 44 | 45 | public class InstrumentationTransformer extends SceneTransformer { 46 | private static final List ACTIVITY_LIFECYCLE_METHODS = Arrays.asList("onCreate", "onResume", "onStart", 47 | "onRestart", "onPause", "onStop", "onDestory", "OriginalonCreate", "OriginalonResume", "OriginalonStart", 48 | "OriginalonRestart", "OriginalonPause", "OriginalonStop", "OriginalonDestory"); 49 | 50 | private SootClass launcherActivityClass; 51 | private SootMethod launcherActivityInitMethod; 52 | private Body dummyMethodBody; 53 | 54 | private List lcMethodsToCreate = new ArrayList(); 55 | private HashSet lifecycleMethodsSet = new HashSet(); 56 | private static Map initMethodMap = new HashMap(); 57 | 58 | @Override 59 | protected void internalTransform(String phaseName, Map options) { 60 | final Chain appClasses = Scene.v().getApplicationClasses(); 61 | 62 | // Handle launcher classes 63 | for (final SootClass sc : appClasses) { 64 | if (sc.toString().contains(SootObject.getInstance().getLauncherActivity()) && hasActivitySuperClass(sc) 65 | && !sc.isInterface()) { 66 | this.launcherActivityClass = sc; 67 | for (int i = 0; i < sc.getMethods().size(); i++) { 68 | final SootMethod m = sc.getMethods().get(i); 69 | if (ACTIVITY_LIFECYCLE_METHODS.contains(m.getName()) && !m.getName().contains("Original")) { 70 | if (!this.lcMethodsToCreate.contains(m.getName())) { 71 | this.lcMethodsToCreate.add(m.getName()); 72 | } 73 | this.lifecycleMethodsSet.add(m); 74 | i = 0; 75 | 76 | // Rename method 77 | final String originalSignature = m.getSignature(); 78 | m.setName("Original" + m.getName()); 79 | Data.getInstance().getLifecycleMethodSignaturesChanged().put(originalSignature, 80 | m.getSignature()); 81 | Log.log("Method " + originalSignature + " modified to " + m.getSignature(), 82 | Log.LOG_LEVEL_DETAILED); 83 | } else if (m.getName().equals(SootMethod.constructorName)) { 84 | initMethodMap.put(sc.toString(), m); 85 | this.launcherActivityInitMethod = m; 86 | } 87 | } 88 | break; 89 | } 90 | } 91 | if (this.launcherActivityClass == null) { 92 | Log.log("Could not find launcher Activity!", Log.LOG_LEVEL_ERROR); 93 | } 94 | 95 | // Conflict Handling for classes (NEW) 96 | final ConflictResolution conflictResolution = new ConflictResolution(appClasses); 97 | for (final SootClass sc : Data.getInstance().getSootClassMap().keySet()) { 98 | if (!sc.hasOuterClass()) { 99 | final Set subClasses = new HashSet<>(); 100 | for (final SootClass scInner : Data.getInstance().getSootClassMap().keySet()) { 101 | if (scInner.hasOuterClass() && getOuterClasses(scInner).contains(sc)) { 102 | subClasses.add(scInner); 103 | } 104 | } 105 | conflictResolution.resolveConflictOuter(sc, subClasses); 106 | } 107 | } 108 | 109 | // Handle other classes 110 | for (final SootClass sc : Data.getInstance().getSootClassMap().keySet()) { 111 | if (!sc.equals(this.launcherActivityClass) && hasActivitySuperClass(sc) && !sc.isInterface()) { 112 | for (final SootMethod m : sc.getMethods()) { 113 | if (ACTIVITY_LIFECYCLE_METHODS.contains(m.getName())) { 114 | if (!this.lcMethodsToCreate.contains(m.getName())) { 115 | this.lcMethodsToCreate.add(m.getName()); 116 | } 117 | Log.log("Applying modifier on: " + m.getName(), Log.LOG_LEVEL_DETAILED); 118 | m.setModifiers(Modifier.PUBLIC); 119 | this.lifecycleMethodsSet.add(m); 120 | } else if (m.getName().equals(SootMethod.constructorName)) { 121 | initMethodMap.put(sc.toString(), m); 122 | } 123 | } 124 | } 125 | } 126 | 127 | // Instantiate field objects 128 | for (final SootClass sc : Data.getInstance().getSootClassMap().keySet()) { 129 | if (!sc.equals(this.launcherActivityClass) && hasActivitySuperClass(sc) && !sc.isInterface()) { 130 | final String name = sc.getName().replace(".", "_"); 131 | 132 | // Create and initialize fields 133 | final SootField tmpField = new SootField(name, sc.getType(), Modifier.PRIVATE); 134 | this.launcherActivityClass.addField(tmpField); 135 | 136 | // Add local representation 137 | final Body bodyInit = this.launcherActivityInitMethod.retrieveActiveBody(); 138 | final Local tmpLocalField = Jimple.v().newLocal(name + "_local", sc.getType()); 139 | bodyInit.getLocals().add(tmpLocalField); 140 | 141 | // Call "new" statement 142 | final AssignStmt u1 = new JAssignStmt(tmpLocalField, new JNewExpr(sc.getType())); 143 | 144 | // Call Constructor 145 | final SootMethod init = initMethodMap.get(sc.toString()); 146 | final InvokeStmt u2 = new JInvokeStmt( 147 | Jimple.v().newSpecialInvokeExpr(tmpLocalField, new SootMethodRefImpl(init.getDeclaringClass(), 148 | init.getName(), init.getParameterTypes(), init.getReturnType(), false))); 149 | 150 | // Connect local to field 151 | final FieldRef fieldRef = Jimple.v().newInstanceFieldRef(bodyInit.getThisLocal(), tmpField.makeRef()); 152 | final AssignStmt u3 = Jimple.v().newAssignStmt(fieldRef, tmpLocalField); 153 | 154 | // Add statements before return 155 | final List unitsToAdd = new ArrayList<>(); 156 | unitsToAdd.add(u1); 157 | unitsToAdd.add(u2); 158 | unitsToAdd.add(u3); 159 | bodyInit.getUnits().insertBefore(unitsToAdd, findReturnStmt(bodyInit)); 160 | } 161 | } 162 | 163 | // Instrument dummy functions 164 | for (final SootClass sc : appClasses) { 165 | if (sc.toString().equals(SootObject.getInstance().getLauncherActivity())) { 166 | for (final String dummyMethodName : this.lcMethodsToCreate) { 167 | // Create new life-cycle method 168 | Log.log("Create lifecycle method for: " + dummyMethodName, Log.LOG_LEVEL_DETAILED); 169 | SootMethod dummyMethod = null; 170 | if (dummyMethodName.contains("onCreate") && hasActivitySuperClass(sc)) { 171 | final List parameterTypes = new ArrayList<>(); 172 | parameterTypes.add(Scene.v().getSootClass("android.os.Bundle").getType()); 173 | dummyMethod = new SootMethod(dummyMethodName, parameterTypes, VoidType.v(), Modifier.PUBLIC); 174 | } else { 175 | dummyMethod = new SootMethod(dummyMethodName, new ArrayList(), VoidType.v(), 176 | Modifier.PUBLIC); 177 | } 178 | sc.addMethod(dummyMethod); 179 | 180 | // Create body 181 | this.dummyMethodBody = Jimple.v().newBody(dummyMethod); 182 | dummyMethod.setActiveBody(this.dummyMethodBody); 183 | 184 | // This local 185 | final Local thisLocal = getThisLocal(); 186 | 187 | // Random local 188 | final Local randomValueLocal = getRandom(); 189 | 190 | // Create switch case 191 | createSwitchCase(dummyMethodName, dummyMethod, thisLocal, randomValueLocal); 192 | } 193 | } 194 | } 195 | 196 | Log.log("successful!\n\n", Log.LOG_LEVEL_NORMAL); 197 | Log.log("*** Step 4/" + AMT.steps + ": Building Merged App ***", Log.LOG_LEVEL_NORMAL); 198 | } 199 | 200 | private Set getOuterClasses(SootClass scInner) { 201 | final Set outerClasses = new HashSet<>(); 202 | if (scInner.hasOuterClass()) { 203 | outerClasses.add(scInner.getOuterClass()); 204 | outerClasses.addAll(getOuterClasses(scInner.getOuterClass())); 205 | } 206 | return outerClasses; 207 | } 208 | 209 | private Local getThisLocal() { 210 | final Local thisLocal = Jimple.v().newLocal("this", this.launcherActivityClass.getType()); 211 | this.dummyMethodBody.getLocals().addFirst(thisLocal); 212 | final IdentityStmt thisStmt = Jimple.v().newIdentityStmt(thisLocal, 213 | Jimple.v().newThisRef(this.launcherActivityClass.getType())); 214 | this.dummyMethodBody.getUnits().add(thisStmt); 215 | 216 | return thisLocal; 217 | } 218 | 219 | private Local getRandom() { 220 | final Local randomGeneratorLocal = Jimple.v().newLocal("randomGenerator", 221 | Scene.v().getSootClass("java.util.Random").getType()); 222 | this.dummyMethodBody.getLocals().add(randomGeneratorLocal); 223 | final AssignStmt randomNewAssign = new JAssignStmt(randomGeneratorLocal, 224 | new JNewExpr(Scene.v().getSootClass("java.util.Random").getType())); 225 | final InvokeStmt randomGeneratorConstructorCall = Jimple.v().newInvokeStmt(Jimple.v().newSpecialInvokeExpr( 226 | randomGeneratorLocal, Scene.v().getSootClass("java.util.Random").getMethods().get(0).makeRef())); 227 | final Local randomValueLocal = Jimple.v().newLocal("randomValue", RefType.v("java.lang.Integer")); 228 | this.dummyMethodBody.getLocals().add(randomValueLocal); 229 | SootMethod nextInt = null; 230 | for (final SootMethod m : Scene.v().getSootClass("java.util.Random").getMethods()) { 231 | if (m.getSignature().toString().contains("java.util.Random: int next(int)")) { 232 | nextInt = m; 233 | break; 234 | } 235 | } 236 | final InvokeExpr randomGeneratorNextIntCall = Jimple.v().newVirtualInvokeExpr(randomGeneratorLocal, 237 | nextInt.makeRef(), IntConstant.v(Config.getInstance().getAppPathList().size() + 1)); 238 | final AssignStmt randomValueAssign = Jimple.v().newAssignStmt(randomValueLocal, randomGeneratorNextIntCall); 239 | 240 | this.dummyMethodBody.getUnits().add(randomNewAssign); 241 | this.dummyMethodBody.getUnits().add(randomGeneratorConstructorCall); 242 | this.dummyMethodBody.getUnits().add(randomValueAssign); 243 | 244 | return randomValueLocal; 245 | } 246 | 247 | private void createSwitchCase(String dummyMethodName, SootMethod dummyMethod, Local thisLocal, 248 | Local randomValueLocal) { 249 | InvokeStmt defaultInvokeStmt = null; 250 | final List switchStmtList = new ArrayList<>(); 251 | 252 | // Bundle for onCreate 253 | Local bundle = null; 254 | if (dummyMethodName.equals("onCreate")) { 255 | bundle = Jimple.v().newLocal("bundle", Scene.v().getSootClass("android.os.Bundle").getType()); 256 | if (!this.dummyMethodBody.getLocals().contains(bundle)) { 257 | this.dummyMethodBody.getLocals().addLast(bundle); 258 | final JIdentityStmt parameterIdentityStmt = (JIdentityStmt) Jimple.v().newIdentityStmt(bundle, 259 | new ParameterRef(dummyMethod.getParameterType(0), 0)); 260 | this.dummyMethodBody.getUnits().insertBefore(parameterIdentityStmt, 261 | this.dummyMethodBody.getUnits().getFirst()); 262 | } 263 | } 264 | 265 | for (final SootMethod lifecycleMethod : this.lifecycleMethodsSet) { 266 | if (lifecycleMethod.toString().contains(dummyMethodName)) { 267 | // Get local-instance-field or this-variable 268 | final String localName = lifecycleMethod.getDeclaringClass().toString().replace(".", "_") + "_local"; 269 | Local tmpLocal; 270 | if (lifecycleMethod.getDeclaringClass().equals(this.launcherActivityClass)) { 271 | tmpLocal = thisLocal; 272 | } else { 273 | tmpLocal = Jimple.v().newLocal(localName, lifecycleMethod.getDeclaringClass().getType()); 274 | this.dummyMethodBody.getLocals().addFirst(tmpLocal); 275 | 276 | final String name = lifecycleMethod.getDeclaringClass().getName().replace(".", "_"); 277 | final FieldRef fieldRef = Jimple.v().newInstanceFieldRef(thisLocal, 278 | this.launcherActivityClass.getFieldByName(name).makeRef()); 279 | final AssignStmt assignStmt = Jimple.v().newAssignStmt(tmpLocal, fieldRef); 280 | this.dummyMethodBody.getUnits().add(assignStmt); 281 | } 282 | 283 | // Create life-cycle method call 284 | InvokeStmt invokeStmt; 285 | if (dummyMethodName.equals("onCreate")) { 286 | // Add bundle for onCreate 287 | invokeStmt = Jimple.v().newInvokeStmt(Jimple.v().newVirtualInvokeExpr(tmpLocal, 288 | new SootMethodRefImpl(lifecycleMethod.getDeclaringClass(), lifecycleMethod.getName(), 289 | lifecycleMethod.getParameterTypes(), lifecycleMethod.getReturnType(), false), 290 | bundle)); 291 | } else { 292 | // No bundle needed for other life-cycle methods 293 | invokeStmt = Jimple.v() 294 | .newInvokeStmt(Jimple.v().newVirtualInvokeExpr(tmpLocal, 295 | new SootMethodRefImpl(lifecycleMethod.getDeclaringClass(), 296 | lifecycleMethod.getName(), lifecycleMethod.getParameterTypes(), 297 | lifecycleMethod.getReturnType(), false))); 298 | } 299 | if (lifecycleMethod.getDeclaringClass().equals(this.launcherActivityClass)) { 300 | defaultInvokeStmt = invokeStmt; 301 | } 302 | switchStmtList.add(invokeStmt); 303 | } 304 | } 305 | 306 | if (switchStmtList.size() > 1) { 307 | if (defaultInvokeStmt == null) { 308 | defaultInvokeStmt = switchStmtList.get(switchStmtList.size() - 1); 309 | } 310 | final TableSwitchStmt tableSwitch = Jimple.v().newTableSwitchStmt(randomValueLocal, 1, 311 | switchStmtList.size(), switchStmtList, defaultInvokeStmt); 312 | this.dummyMethodBody.getUnits().add(tableSwitch); 313 | for (final Unit stmt : switchStmtList) { 314 | this.dummyMethodBody.getUnits().add(stmt); 315 | this.dummyMethodBody.getUnits().add(Jimple.v().newReturnVoidStmt()); 316 | } 317 | } else { 318 | this.dummyMethodBody.getUnits().addAll(switchStmtList); 319 | } 320 | this.dummyMethodBody.getUnits().add(Jimple.v().newReturnVoidStmt()); 321 | } 322 | 323 | private ReturnVoidStmt findReturnStmt(Body bodyInit) { 324 | for (final Unit u : bodyInit.getUnits()) { 325 | if (u instanceof ReturnVoidStmt) { 326 | return (ReturnVoidStmt) u; 327 | } 328 | } 329 | return null; 330 | } 331 | 332 | private boolean hasActivitySuperClass(SootClass sc) { 333 | if (sc.hasSuperclass()) { 334 | sc = sc.getSuperclass(); 335 | if (sc.getName().equals("android.app.Activity")) { 336 | return true; 337 | } else { 338 | return hasActivitySuperClass(sc); 339 | } 340 | } else { 341 | return false; 342 | } 343 | } 344 | } -------------------------------------------------------------------------------- /src/de/upb/mike/amt/soot/ParseTransformer.java: -------------------------------------------------------------------------------- 1 | package de.upb.mike.amt.soot; 2 | 3 | import java.io.File; 4 | import java.util.Iterator; 5 | import java.util.Map; 6 | 7 | import de.upb.mike.amt.Data; 8 | import de.upb.mike.amt.Log; 9 | import soot.Scene; 10 | import soot.SceneTransformer; 11 | import soot.SootClass; 12 | 13 | public class ParseTransformer extends SceneTransformer { 14 | private File appFile; 15 | 16 | public ParseTransformer(String appFile) { 17 | this.appFile = new File(appFile); 18 | } 19 | 20 | @Override 21 | protected void internalTransform(String phaseName, Map options) { 22 | for (final Iterator iterator = Scene.v().getApplicationClasses().iterator(); iterator.hasNext();) { 23 | final SootClass sc = iterator.next(); 24 | if (!sc.isPhantom()) { 25 | Data.getInstance().receiveClass(sc, this.appFile); 26 | } else { 27 | Log.log("Ignoring class: " + sc.toString(), Log.LOG_LEVEL_DETAILED); 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/de/upb/mike/amt/soot/SootObject.java: -------------------------------------------------------------------------------- 1 | package de.upb.mike.amt.soot; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Collections; 6 | import java.util.List; 7 | 8 | import de.upb.mike.amt.Config; 9 | import de.upb.mike.amt.Data; 10 | import de.upb.mike.amt.Log; 11 | import soot.PackManager; 12 | import soot.Scene; 13 | import soot.SootClass; 14 | import soot.Transform; 15 | import soot.options.Options; 16 | import soot.toDex.DexPrinter; 17 | 18 | public class SootObject { 19 | public static final int FLAG_READ_NON_LAUNCHER_APPS = 1; 20 | public static final int FLAG_MERGE = 2; 21 | 22 | private static SootObject instance = new SootObject(); 23 | 24 | private String launcherActivity; 25 | 26 | private SootObject() { 27 | } 28 | 29 | public static SootObject getInstance() { 30 | return instance; 31 | } 32 | 33 | public void parseApp(String filePath, int flag) { 34 | if (filePath != null) { 35 | Log.log("Running Soot: " + filePath + " (Mode: " + flag + ")", Log.LOG_LEVEL_DEBUG); 36 | } else { 37 | Log.log("Running Soot to merge the app. (Mode: " + flag + ")", Log.LOG_LEVEL_DEBUG); 38 | } 39 | Log.silence(true); 40 | 41 | soot.G.reset(); 42 | 43 | if (Log.loglevel > Log.LOG_LEVEL_DEBUG) { 44 | Options.v().set_debug(true); 45 | } else { 46 | Options.v().set_debug(false); 47 | } 48 | if (Log.loglevel > Log.LOG_LEVEL_VERBOSE) { 49 | Options.v().set_verbose(true); 50 | } else { 51 | Options.v().set_verbose(false); 52 | } 53 | Options.v().set_whole_program(true); 54 | Options.v().set_android_jars(Config.getInstance().getAndroidPlatformPath()); 55 | Options.v().set_allow_phantom_refs(true); 56 | Options.v().set_ignore_resolution_errors(true); 57 | Options.v().set_prepend_classpath(true); 58 | Options.v().set_process_multiple_dex(true); 59 | 60 | final List excludeList = new ArrayList<>(); 61 | excludeList 62 | .addAll(Arrays.asList(new String[] { Data.getInstance().getPackageMap().get(filePath) + ".BuildConfig", 63 | Data.getInstance().getPackageMap().get(filePath) + ".R", 64 | Data.getInstance().getPackageMap().get(filePath) + ".R$*" })); 65 | if (flag != FLAG_MERGE) { 66 | excludeList.addAll(Config.getInstance().getDefaultExcludes()); 67 | } 68 | Log.log("Excluding: " + excludeList.toString(), Log.LOG_LEVEL_DETAILED); 69 | Options.v().set_exclude(excludeList); 70 | 71 | Options.v().set_process_dir(Collections.singletonList(filePath)); 72 | Options.v().set_src_prec(Options.src_prec_apk); 73 | if (flag == FLAG_READ_NON_LAUNCHER_APPS) { 74 | Options.v().set_output_format(Options.output_format_none); 75 | Options.v().set_no_writeout_body_releasing(true); 76 | PackManager.v().getPack("wjtp").add(new Transform("wjtp.ParseTransformer", new ParseTransformer(filePath))); 77 | } else if (flag == FLAG_MERGE) { 78 | Options.v().set_output_format(Options.output_format_dex); 79 | Options.v().set_no_writeout_body_releasing(false); 80 | PackManager.v().getPack("wjtp") 81 | .add(new Transform("wjtp.InstrumentationTransformer", new InstrumentationTransformer())); 82 | } 83 | Scene.v().loadNecessaryClasses(); 84 | PackManager.v().runPacks(); 85 | if (flag == FLAG_MERGE) { 86 | Log.log("Writing APK!", Log.LOG_LEVEL_NORMAL); 87 | final DexPrinter dp = new DexPrinter(); 88 | for (final SootClass c : Scene.v().getApplicationClasses()) { 89 | try { 90 | dp.add(c); 91 | } catch (final RuntimeException e) { 92 | Log.log("Class \"" + c + "\" could not be written to APK. Reason: Invalid code contained! (" 93 | + e.getClass().getSimpleName() + ": " + e.getLocalizedMessage() + ")", Log.LOG_LEVEL_ERROR); 94 | } 95 | } 96 | dp.print(); 97 | } 98 | 99 | Log.silence(false); 100 | Log.log("Soot: done!", Log.LOG_LEVEL_DEBUG); 101 | } 102 | 103 | public String getLauncherActivity() { 104 | return this.launcherActivity; 105 | } 106 | 107 | public void setLauncherActivity(String launcherActivity) { 108 | this.launcherActivity = launcherActivity; 109 | } 110 | } -------------------------------------------------------------------------------- /test/ArrayAccess1.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FoelliX/AMT/9a7d6bde7674a3bec65f35e7f25f0d31c4982b81/test/ArrayAccess1.apk -------------------------------------------------------------------------------- /test/ArrayAccess2.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FoelliX/AMT/9a7d6bde7674a3bec65f35e7f25f0d31c4982b81/test/ArrayAccess2.apk -------------------------------------------------------------------------------- /test/ArrayAccess3.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FoelliX/AMT/9a7d6bde7674a3bec65f35e7f25f0d31c4982b81/test/ArrayAccess3.apk -------------------------------------------------------------------------------- /test/ArrayAccess4.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FoelliX/AMT/9a7d6bde7674a3bec65f35e7f25f0d31c4982b81/test/ArrayAccess4.apk -------------------------------------------------------------------------------- /test/ArrayAccess5.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FoelliX/AMT/9a7d6bde7674a3bec65f35e7f25f0d31c4982b81/test/ArrayAccess5.apk -------------------------------------------------------------------------------- /test/ArrayCopy1.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FoelliX/AMT/9a7d6bde7674a3bec65f35e7f25f0d31c4982b81/test/ArrayCopy1.apk -------------------------------------------------------------------------------- /test/ArrayToString1.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FoelliX/AMT/9a7d6bde7674a3bec65f35e7f25f0d31c4982b81/test/ArrayToString1.apk -------------------------------------------------------------------------------- /test/Echoer.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FoelliX/AMT/9a7d6bde7674a3bec65f35e7f25f0d31c4982b81/test/Echoer.apk -------------------------------------------------------------------------------- /test/HashMapAccess1.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FoelliX/AMT/9a7d6bde7674a3bec65f35e7f25f0d31c4982b81/test/HashMapAccess1.apk -------------------------------------------------------------------------------- /test/ListAccess1.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FoelliX/AMT/9a7d6bde7674a3bec65f35e7f25f0d31c4982b81/test/ListAccess1.apk -------------------------------------------------------------------------------- /test/MultidimensionalArray1.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FoelliX/AMT/9a7d6bde7674a3bec65f35e7f25f0d31c4982b81/test/MultidimensionalArray1.apk -------------------------------------------------------------------------------- /test/SendSMS.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FoelliX/AMT/9a7d6bde7674a3bec65f35e7f25f0d31c4982b81/test/SendSMS.apk -------------------------------------------------------------------------------- /testsrc/de/upb/mike/amt/MergeTest.java: -------------------------------------------------------------------------------- 1 | package de.upb.mike.amt; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertTrue; 4 | 5 | import java.io.File; 6 | 7 | import org.junit.jupiter.api.Test; 8 | 9 | public class MergeTest { 10 | @Test 11 | public void test01() { 12 | final File apk1 = new File("test/ArrayAccess1.apk"); 13 | final File apk2 = new File("test/ArrayAccess2.apk"); 14 | 15 | boolean noException = true; 16 | try { 17 | AMT.main(new String[] { "-l", "verbose", apk1.getAbsolutePath(), apk2.getAbsolutePath() }); 18 | } catch (final Exception e) { 19 | noException = false; 20 | } 21 | 22 | assertTrue(noException); 23 | } 24 | } 25 | --------------------------------------------------------------------------------