Full Code of BytecodeDL/ByteCodeDL for AI

main d7a833973cc8 cached
51 files
133.0 KB
40.8k tokens
1 requests
Download .txt
Repository: BytecodeDL/ByteCodeDL
Branch: main
Commit: d7a833973cc8
Files: 51
Total size: 133.0 KB

Directory structure:
gitextract_s9rsi9xd/

├── .gitignore
├── LICENSE
├── README.md
├── docker/
│   ├── bytecodedl/
│   │   └── Dockerfile
│   └── neo4j-server/
│       └── Dockerfile
├── docker-compose.yml
├── docs/
│   ├── callgraph.md
│   ├── cha-in-ctf.md
│   ├── cha-optimization.md
│   ├── context-insensitive-points-to.md
│   ├── ptaint.md
│   ├── query.md
│   ├── readme.md
│   ├── relation.md
│   ├── souffle.md
│   └── utils.md
├── example/
│   ├── cha-example-1.dl
│   ├── cha-log4shell.dl
│   ├── cs-ptaint-example-1.dl
│   ├── ctf-buggyLoader.dl
│   ├── ctf-ezchain.dl
│   ├── one-callsite-sensitive-pt-example-1.dl
│   ├── one-object-sensitive-pt-example-1.dl
│   ├── one-type-sensitive-pt-example-1.dl
│   ├── pt-noctx-example-1.dl
│   ├── ptaint-example-1.dl
│   ├── ptaint-example-2.dl
│   ├── query-example-1.dl
│   ├── rta-example-1.dl
│   └── simple-cha-log4shell.dl
├── importOuput2Neo4j.sh
├── logic/
│   ├── abstract-context-sensitive-pt.dl
│   ├── cha.dl
│   ├── cs-ptaint.dl
│   ├── inputDeclaration.dl
│   ├── one-callsite-sensitive-pt.dl
│   ├── one-object-sensitive-pt.dl
│   ├── one-type-sensitive-pt.dl
│   ├── pt-noctx.dl
│   ├── ptaint.dl
│   ├── rta.dl
│   ├── simple-cha.dl
│   └── utils.dl
├── neo4j/
│   ├── CallEdgeHeader.csv
│   ├── CallNodeHeader.csv
│   └── ChaEdgeHeader.csv
├── neoImportCall-4.4.sh
├── neoImportCall.sh
├── neoImportChaCall-4.4.sh
├── neoImportChaCall.sh
└── output/
    └── readme.md

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
output/*.csv
.DS_Store
.idea


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
# ByteCodeDL

<div align="center">
	<img src="./bdl-logo.png" alt="ByteCodeDL" width="200">
</div>

A declarative static analysis tool for jvm bytecode based Datalog like CodeQL

## Why ByteCodeDL

ByteCodeDL这个名字是从CodeQL演化的,ByteCode对应Code,DL对应QL,是一款声明式静态分析工具,主要是为了弥补CodeQL无法直接分析字节码的遗憾。

本项目主要有两个目的:

1. 教学目的,帮助大家入门静态分析,本项目将演示如何通过datalog实现一些静态分析算法,比起命令式静态分析,这种方式要简洁很多,学习了基本原理之后,也可以自己DIY规则。
2. 提高挖洞效率,安全研究人员一般拿不到源码,大多数情况只能分析Jar包,然后通过IDEA看反编译之后的代码,效率比较低,希望ByteCodeDL提供的搜索功能、调用图分析功能、污点分析功能,能够提高安全研究人员的挖洞效率。

## Install

1. [download](https://github.com/BytecodeDL/soot-fact-generator/releases/download/v1.0/soot-fact-generator.jar) or [build](https://github.com/BytecodeDL/soot-fact-generator) soot-fact-generator.jar
2. install [souffle](https://souffle-lang.github.io/install) 
3. install [neo4j](https://neo4j.com/download-center/)

## Docker

you can use the docker we builded like docker-compose.yml

## Features

- [x] 搜索功能
- [x] 调用图分析
  - [x] CHA
  - [x] SIMPLE-CHA 
  - [x] RTA
- [ ] 指针分析
  - [x] 上下文无关指针分析
  - [x] 一阶上下文调用点敏感指针分析
  - [x] 一阶上下文对象敏感指针分析
  - [x] 一阶上下文类型敏感指针分析
  - [ ] 可选择上下文敏感指针分析
- [x] 污点分析
  - [x] 上下文无关ptaint
  - [x] 上下文敏感ptaint
- [ ] 输出sarif
- [ ] 实现JackEE
- [ ] 性能优化

## Usage

见docs文件夹

## Support

在使用中遇到什么问题,可以通过

- email: help@bytecodedl.com
- github: issue/discussion
- telegram: [bytecodedl](https://t.me/bytecodedl)

三种途径向我们反馈

## Plugin

- IDEA
  - ByteCodeDL helper [BDLH](https://github.com/BytecodeDL/BDLH)
  - Datalog language plugin [intellij-datalog](https://github.com/BytecodeDL/intellij-datalog)

## Acknowledgement

- 感谢南大的李樾和谭添两位老师,通过他们开设的[程序分析课程](https://pascal-group.bitbucket.io/teaching.html)入门了静态分析这一领域。
- 感谢[Doop](https://bitbucket.org/yanniss/doop) , 提供了soot-fact-generator.jar 。


================================================
FILE: docker/bytecodedl/Dockerfile
================================================
From ubuntu:22.04

LABEL version="1.0.2"
LABEL maintainer="yxxx <yxwuman@gmail.com>"

RUN apt-get update \
    && apt-get install -y vim \
    && apt-get install -y wget \
    && apt-get install -y git \
    && apt-get install -y openjdk-8-jdk

RUN wget https://souffle-lang.github.io/ppa/souffle-key.public -O /usr/share/keyrings/souffle-archive-keyring.gpg \
    && echo "deb [signed-by=/usr/share/keyrings/souffle-archive-keyring.gpg] https://souffle-lang.github.io/ppa/ubuntu/ stable main" | tee /etc/apt/sources.list.d/souffle.list \
    && apt update && apt install -y souffle

RUN wget https://github.com/BytecodeDL/soot-fact-generator/releases/download/v1.4.2/soot-fact-generator-1.4.2.jar

================================================
FILE: docker/neo4j-server/Dockerfile
================================================
From neo4j:5.12.0

LABEL version="1.0.1"
LABEL maintainer="yxxx <yxwuman@gmail.com>"

RUN wget https://github.com/BytecodeDL/bytecodedl-pathfinder-neo4j-procedure/releases/download/v1.0.1/bytecodedl-pathfinder-1.0.1.jar -O /var/lib/neo4j/plugins/bytecodedl-pathfinder-1.0.1.jar

ENV NEO4J_AUTH=neo4j/bytecodedl \
    NEO4J_dbms_security_procedures_unrestricted=bytecodedl.*

================================================
FILE: docker-compose.yml
================================================
version: '2.4'
services:
  bytecodedl:
    image: wuxxxxx/bytecodedl:1.0.2
    restart: always
    command: sleep infinity
    volumes:
        - ./:/bytecodedl
  neo:
    image: wuxxxxx/neo4j-server:5.12.0-bytecodedl-pathfinder-1.0.1 
    restart: always
    ports:
      - "0.0.0.0:7474:7474"
      - "0.0.0.0:7687:7687"
    volumes:
        - ./:/bytecodedl


================================================
FILE: docs/callgraph.md
================================================
# callgraph

这节介绍调用图构造,强烈建议先看这个 [PPT](https://pascal-group.bitbucket.io/lectures/Inter.pdf)

SpeicalMethodInvocation和StaticMethodInvocation的被调用的方法在编译期间就可以确定,VirtualMethodInvocation需要在运行时根据receiver实际类型才能确定被调函数。

如何确定receiver的运行时类型,成为了调用图构造的关键,下面介绍两种调用图的构造算法及其相应的实现。

## Common

先介绍一下公共的部分。

调用图,首先是从一个入口函数开始,然后通过分析入口函数内的函数调用情况,将被调用的函数加入worklist,等待后续的分析。

定义EntryPoint(simplename:symbol, descriptor:symbol, class:Class) 为入口函数,也就是分析的起点,然后把能够调用到的方法加入到Reachable(method:Method, step:number),把调用关系加入到CallGraph(insn:Insn, caller:Method, callee:Method)。

为了能够分析大的应用,这里限制了调用长度,在Reachable(method, step) 中step 表示从入口函数到method的调用步数。

```dl
// 先根据Etrypoint解析出具体的method,加入Reachable
Reachable(method, 0) :- 
    EntryPoint(simplename, descriptor, class),
    Dispatch(simplename, descriptor, class, method).

// special callee可以直接确定,所以可以直接加入到CallGraph
Reachable(callee, n+1),
CallGraph(insn, caller, callee) :-
    // 如果caller能够调用到
    Reachable(caller, n),
    // 并且caller调用步数未超过最大步数
    n < MAXSTEP,
    // 且caller 调用了 callee ,那么这些条件可以推到出callee也能访问到,且步数为n+1 调用图中caller和callee有条边
    SpecialMethodInvocation(insn, _, callee, _, caller).
// 同上
Reachable(callee, n+1),
CallGraph(insn, caller, callee) :-
    Reachable(caller, n),
    n < MAXSTEP,
    StaticMethodInvocation(insn, _, callee, caller).
```

## Class hierarchy analysis (CHA)

CHA调用图算法认为,receiver在实际运行的过程中的类型可以是其声明类型的任意非abstract子类。

```dl
Reachable(callee, n+1),
CallGraph(insn, caller, callee) :-
    Reachable(caller, n),
    n < MAXSTEP,
    // caller 中调用了 receiver.method() 需要根据receiver的声明类型解析
    VirtualMethodInvocation(insn, _, method, receiver, caller),
    // 找到method 对应的方法签名也就是simplename和descriptor
    MethodInfo(method, simplename, _, _, _, descriptor, _),
    // 找到receiver对应的声明类型
    VarType(receiver, class),
    // 找到receiver 自身及其所有的子类
    SubEqClass(subeqclass, class),
    // 排除被abstract修饰的类
    !ClassModifier("abstract", subeqclass),
    // 根据方法签名和类型解析出真正的被调函数callee
    Dispatch(simplename, descriptor, subeqclass, callee).
```

完整的实现见[cha.dl](../logic/cha.dl)

在benchmark使用样例见[cha-exmaple-1.dl](../example/cha-example-1.dl)

创建benchmark facts时可以加上--facts-subset 参数,只生成bechmark中的facts不再连依赖库中的一起解析。具体命令如下

```bash
java8 -jar ~/code/soot-fact-generator/build/libs/soot-fact-generator.jar -i Benchmark-1.0-SNAPSHOT.jar --full -l /Library/Java/JavaVirtualMachines/jdk1.8.0_211.jdk/Contents/Home/jre/lib/rt.jar -d callgraphtest --allow-phantom --generate-jimple --facts-subset APP
```

## Rapid type analysis (RTA)

RTA是CHA的改进版本,RTA调用图算法认为,receiver在实际运行的过程中的类型不仅要满足是声明类型的子类,而且这个子类还要已经创建过实例。

以 https://github.com/BytecodeDL/Benchmark/blob/main/src/main/java/com/bytecodedl/benchmark/demo/VirtualCallDemo1.java 为例介绍 CHA和RTA的区别

```java
public static void main(String[] args) {
    VirtualCallInterface1 vcall2 = new VirtualCallDemo2();
    VirtualCallDemo1 vcall1 = new VirtualCallDemo1(vcall2);
    VirtualCallInterface1 varParent = vcall1.getParent();
    String source = vcall1.source();
    varParent.foo(source);
}
```

在解析`varParent.foo(`时
CHA认为 receiver `varParent`的变量为其声明类型VirtualCallInterface1的所有子类,也就是VirtualCallDemo1, VirtualCallDemo2, VirtualCallDemo3 所以`varParent.foo(`会被解析成也就是VirtualCallDemo1#foo,VirtualCallDemo2#foo,VirtualCallDemo3#foo,存在两条误报边。
RTA认为 receiver `varParent`的变量为其声明类型VirtualCallInterface1的所有子类 和 已实例化类型的交集(两条new语句中的类型),
也就是{VirtualCallDemo1, VirtualCallDemo2, VirtualCallDemo3} 和 {VirtualCallDemo1, VirtualCallDemo2} 的交集,
即 {VirtualCallDemo1, VirtualCallDemo2}, 所以`varParent.foo(`会被解析成VirtualCallDemo1#foo,VirtualCallDemo2#foo 减少了一条误报。

RTA对应的规则和CHA基本一致,总共有两处改变,

一处是增加个新的 relation `InstantiatedClass(insn:Insn, class:Class)` 表示reachable中方法已经实例化的类

另一处改变是在解析虚拟方法时,对subeqclass增加了限制,要求subeqclass还要在InstantiatedClass中。

具体的规则如下

```dl
// 如果method可达
// 且method中创建heap
// heap 的类型是 class 
// 那么class就是已创建实例的类型
InstantiatedClass(insn, class) :-
     Reachable(method, _),
     AssignHeapAllocation(insn, _, heap, _, method, _),
     NormalHeap(heap, class).

 Reachable(callee, n+1),
 CallGraph(insn, caller, callee) :-
     Reachable(caller, n),
     !BanCaller(caller),
     n < MAXSTEP,
     VirtualMethodInvocation(insn, _, method, receiver, caller),
     MethodInfo(method, simplename, _, _, _, descriptor, _),
     VarType(receiver, class),
     SubEqClass(subeqclass, class),
     !ClassModifier("abstract", subeqclass),
     // 限制subeqclass是已创建实例的类型
     InstantiatedClass(_, subeqclass),
     Dispatch(simplename, descriptor, subeqclass, callee).
```

CHA只会存在误报,但是RTA既可能存在误报也可能存在漏报。

## Visualization

调用图的输出结果是callgraph,是调用图中的节点,如果节点一多,不太容易寻找下一个节点,可以借助图数据库neo4j进行可视化。

经测试,通过`neo4j-admin import` 导入的效率最高。 [参考链接](https://neo4j.com/docs/operations-manual/current/tutorial/neo4j-admin-import/) 

导入neo4j docker的步骤为:

1. 执行下面命令将结果输出到output文件夹
   
   ```bash
   souffle -F factsdir -D ~/code/ByteCodeDL/output ~/code/ByteCodeDL/example/cha-example-1.dl
   ```

2. 执行bash importOutput2Neo4j.sh neoImportCall.sh dbname
3. 最后访问 http://ip:7474 登录 neo4j/bytecodedl

注意上述方式只能脱机导入,也就是databasname不能是正在使用的,需要指定个新的,由于社区版neo4j的限制,不能进行多数据库链接,需要通过更改配置文件切换数据库。

可以通过

```cypher
MATCH p=(entry:entrypoint)-[*]->() where entry.method contains "virtualcall.vc2"  RETURN p 
```

查询入口函数开始的调用图,效果如下,点击节点可以在右侧看到详情

![cha-vc2](images/cha-vc2.png)

## Reference
- https://pascal-group.bitbucket.io/lectures/Inter.pdf
- https://neo4j.com/docs/operations-manual/current/tutorial/neo4j-admin-import/
- http://web.cs.ucla.edu/~palsberg/paper/oopsla00.pdf
- https://people.cs.vt.edu/ryder/515/f05/lectures/OOPLs-CallGraphConstr9.pdf

================================================
FILE: docs/cha-in-ctf.md
================================================
# cha in ctf

本文首发于 https://tttang.com/archive/1510/

这篇文章对应的代码分支见 [cha-in-ctf](https://github.com/BytecodeDL/ByteCodeDL/tree/cha-in-ctf/) 最好切换至该分支再进行阅读

这节将分享如何用ByteCodeDL 的 CHA 调用图分析功能,解决两个CTF题目。

## buggyLoader 0ctf-2021-final

这是0ctf 2021 决赛的一道题目,NeSE和r3kapig解出了这个题目。题目地址见 https://github.com/waderwu/My-CTF-Challenges/tree/master/0ctf-2021-final/buggyLoader 。这道题的灵感来自Shiro环境下的CC链构造,准确的说来自zsx的[这篇文章](https://blog.zsxsoft.com/post/35)

难点在于反序列化时无法创建数组类型,导致InvokerTransformer 的字段iArgs只能为null,所以最终只能调用public 无参函数。常见的反序列化最后调用的函数有:

1. JdbcRowSetImpl#getDatabaseMetaData() 和 JdbcRowSetImpl#getParameterMetaData 利用JNDI进行攻击
2. TemplatesImpl#getOutputProperties()

但是上述两类在这个题目都不能用,由于不出网,第一种方式不能用,由于TemplatesImpl的_bytecodes字段为数组,所以第二种方式也不能用。

[Orange](http://blog.orange.tw/2018/03/pwn-ctf-platform-with-java-jrmp-gadget.html)在做强网杯那题的时候,最后使用了[JRMP Client](https://github.com/frohoff/ysoserial/blob/master/src/main/java/ysoserial/payloads/JRMPClient.java) 这个payload,第一次反序列化时,发起RMI请求,然后在RMI处理响应的时候会再次触发反序列化,第二次反序列化就没有任何限制了。这种方式有两种局限,第一种是需要环境能外连,第二种是高版本的JDK下JRMP Client这个payload不能用了(具体的版本我忘了)。

如果这题能够外连,可以先调用JdbcRowSetImpl,利用JNDI发起一次RMI请求,在RMI处理响应时会再次触发反序列化,类似JRMP Client的效果,但是对JDK版本没有限制。

已知的套路都不能用了,这题该怎么做呢?重新找个能够造成危害的public 无参函数:可以直接执行命令/代码或者能够二次反序列化。

第一步我们先筛选出 public 无参函数

```dl
#include "inputDeclaration.dl"
#include "utils.dl"


.decl NonParamPublicMethod(method:Method, class:Class)
.output NonParamPublicMethod

NonParamPublicMethod(method, class) :-
    MethodInfo(method, simplename, _, class, _, _, arity),
    // method 需要被pulic修饰
    MethodModifier("public", method),
    // 排除构造函数
    simplename != "<init>",
    // 参数数量为零
    arity = 0,
    // 类需要能可序列化
    SubClass(class, "java.io.Serializable").
```

JDK中满足条件的一共10459条,如果一条条筛选下来还是比较困难的

我们再进一步做个限制,让这10459初步满足条件的函数,作为入口函数,进行调用图分析,看一下5步之内,有没有可能调用到危险函数。
[example/ctf-buggyLoader.dl](../example/ctf-buggyLoader.dl)

```dl
#define MAXSTEP 5

#include "inputDeclaration.dl"
#include "utils.dl"
#include "cha.dl"


.decl NonParamPublicMethod(method:Method, class:Class)
.output NonParamPublicMethod

// 通过class和函数名定义危险函数
.decl SinkDesc(simplename:symbol, class:Class)

// 加入常见的危险函数
SinkDesc("exec", "java.lang.Runtime").
SinkDesc("<init>", "java.lang.ProcessBuilder").
SinkDesc("start", "java.lang.ProcessImpl").
SinkDesc("loadClass", "java.lang.ClassLoader").
SinkDesc("defineClass", "java.lang.ClassLoader").
SinkDesc("readObject", "java.io.ObjectInputStream").
SinkDesc("readExternal", "java.io.ObjectInputStream").

// 定义具体的危险函数
.decl SinkMethod(method:Method)
.output SinkMethod

// 定义具体的危险函数
.decl EntryMethod(method:Method)

// 根据方法名和类名解析初具体的危险方法
// 子类中的同名方法也认为是危险函数
SinkMethod(method) :-
    SinkDesc(simplename, class),
    SubEqClass(subeqclass, class),
    !ClassModifier("abstract", subeqclass),
    MethodInfo(method, simplename, _, subeqclass, _, _, _).

// 将满足条件的无参函数作为入口方法
EntryMethod(method),
Reachable(method, 0),
NonParamPublicMethod(method, class) :- 
    MethodInfo(method, simplename, _, class, _, _, arity),
    MethodModifier("public", method),
    simplename != "<init>",
    arity = 0,
    SubClass(class, "java.io.Serializable").

// 调用图中节点
.decl CallNode(node:Method, label:symbol)
.output CallNode

// 不是入口节点和危险节点 标记为method
CallNode(node, "method") :-
    !EntryMethod(node),
    !SinkMethod(node),
    Reachable(node, _).

// 危险节点标记为 sink
CallNode(node, "sink") :-
    Reachable(node, _),
    SinkMethod(node).

// 入口节点标记为entry
CallNode(node, "entry") :-
    EntryMethod(node).

// 调用边
.decl CallEdge(caller:Method, callee:Method)
.output CallEdge

CallEdge(caller, callee) :-
    CallGraph(_, caller, callee).
```

通过 bash importOutput2Neo4j.sh neoImportCall.sh dbname 导入

执行查询

```cypher
MATCH p=(e:entry)-[*1..2]->(s:sink) where s.method contains "readObject"  RETURN p
```

长度为1-2的调用到readObject的路径

可以筛选出

```text
<java.security.SignedObject: java.lang.Object getObject()>
```

```text
<java.rmi.MarshalledObject: java.lang.Object get()>
```

但是这俩还是都需要数组字段,不满足我们的需求

对于排查不满足需求的,可以通过下面的方式删除节点,同时删除和这个节点相连的边

```cypher
MATCH (m:method) where ID(m)=42186
DETACH DELETE m
```

长度为4的查询

```cypher
MATCH p=(e:entry)-[*4]->(s:sink) where s.method contains "readObject"  RETURN p
```

```cypher
MATCH p=(e:entry)-[*4]->(s:sink) where s.method contains "readObject" and ID(e)=57653  unwind nodes(p) as n return n.method
```

查询结果

```text
<javax.management.remote.rmi.RMIConnector: void connect()>
<javax.management.remote.rmi.RMIConnector: void connect(java.util.Map)>
<javax.management.remote.rmi.RMIConnector: javax.management.remote.rmi.RMIServer findRMIServer(javax.management.remote.JMXServiceURL,java.util.Map)>
<javax.management.remote.rmi.RMIConnector: javax.management.remote.rmi.RMIServer findRMIServerJRMP(java.lang.String,java.util.Map,boolean)>
<java.io.ObjectInputStream: java.lang.Object readObject()>
```

大致的流程如下

rmiConnector.jmxServiceURL.urlPath -> base64 decode -> ByteArrayInputStream -> ObjectInputStream -> readObject

这个刚好满足我们的要求,最终的解法就是:
readOjbect -> ... -> InvokerTransformer -> RMIConnector#connect() -> .. -> readObject -> 传统的 CC 链

CHA的优点一是快,而是不存在漏报,但是这也是他的缺点,存在大量的误报,实际测试下来发现需要排除的东西还挺多,仍有不少工作量,还有很大的提升空间。后面将尝试利用污点分析对该任务的精度进行提升。

## ezchain hfctf2022

这是虎符CTF 2022年的一道题,当时bk和ty1310解出了这个题目。题目的环境见:https://github.com/waderwu/My-CTF-Challenges/tree/master/hfctf-2022/ezchain 

这也是道反序列化的题,只不过换成了Hessian反序列化,也是内网环境,无法外连。给了Rome第三方库,Marshalsec中包含了这个链,不过最后调用的是JdbcRowSetImpl ,利用JNDI完成攻击。由于无法外连,所以这条路被堵死了。熟悉反序列化的同学,应该能想到可不可以换成TemplatesImpl , 经过调试之后发现也不行,因为Hessian在反序列化的时候不会调用readObject ,导致被transient 修饰的字段_tfactory一直为null,后续调用_tfactory.getExternalExtensionsMap()会触发空指针错误。

所以已公开的东西都用不了了,需要重新找链,通过分析之后Rome链一直能用到调用任意无参数的getter函数,所以我们只要再重新找个getter函数即可。和上题差不多,危险函数可以是能够执行命令/代码或者能够造成二次反序列化。

其实在上题中,我们已经找到了一个满足条件的getter函数,那就是

```text
<java.security.SignedObject: java.lang.Object getObject()>
```

利用这个然后可以造成二次反序列化,然后就可以使用ysoserial中的rome链了,这个解法是二血ty1310队伍提供的。

只要将ctf-buggyLoader.dl中的入口函数限制改一下,就可以用到这个题上

[example/ctf-ezchain.dl](../example/ctf-ezchain.dl)

```dl
EntryMethod(method),
Reachable(method, 0),
NonParamPublicMethod(method, class) :- 
    MethodInfo(method, simplename, _, class, _, _, arity),
    MethodModifier("public", method),
    // 方法名包含get
    contains("get", simplename),
    // 无参数
    arity = 0.
    // hessian反序列化时不要求实现Serializable
```

如果按照这个版本的[cha.dl](https://github.com/BytecodeDL/ByteCodeDL/blob/75a90a8baf9ebbcee573498d8077f61d2a8b338a/logic/cha.dl) 只能找到下面这个,这个我也已经验证可以用。payload我就不给了,大家可以参考UnixPrintServiceLookup进行构造。

```text
<com.sun.corba.se.impl.activation.ServerManagerImpl: int[] getActiveServers()>
<com.sun.corba.se.impl.activation.ServerTableEntry: boolean isValid()>
<com.sun.corba.se.impl.activation.ServerTableEntry: void activate()>
<java.lang.Runtime: java.lang.Process exec(java.lang.String)>     
```

但是并没有找到预期解,这个UnixPrintServiceLookup这个类,这是因为在构造调用图时没有考虑一种间接调用,这种间接调用可以简化成这种

```java
caller(){
    AccessController.doPrivileged(new PrivilegedExceptionAction() {
        public Object run() throws IOException {
            callee();
        }
    }
}
```

由于doPrivileged是native方法,无法进行后续的分析,这里就需要进行个特殊处理,认为caller可以直接调用这个run方法

```dl
CallGraph(insn, caller, callee) :- 
    Reachable(caller, n),
    n < MAXSTEP,
    StaticMethodInvocation(insn, _, method, caller),
    MethodInfo(method, "doPrivileged", _, "java.security.AccessController", _, _, _),
    ActualParam(0, insn, param),
    VarType(param, type),
    MethodInfo(callee, "run", _, type, _, _, 0).
```

改进之后的完整版本[cha.dl](../logic/cha.dl)

然后当长度为设置4的时候就可以查到了

![cha-ezchain-len-4-exec](images/cha-ezchain-len-4-exec.png)

```dl
MATCH p=(e:entry)-[*6]->(s:sink) where s.method contains "exec"  RETURN p
```

长度设置为6,在76880 nodes 1119478 relationships 的情况下就差不来了,不知道建立索引或者啥的会不会好一点


================================================
FILE: docs/cha-optimization.md
================================================
# cha-optimization

本文代码对应的分支是 [cha-optimization](https://github.com/BytecodeDL/ByteCodeDL/tree/cha-optimization)

## 实现&分析

在实际测试中发现,如果路径过长会出现neo4j查询不出来的情况,还需要对CHA进行进一步优化。优化方向有两个:

1. 尽可能减少节点的数量
2. 尽可能减少环路的出现

目前采取的遍历算法,有点类似于从entry出发,进行广度优先遍历(bfs)。实际的节点表现可能是这样的

![callgraph-example](./images/callgraph-entry-bfs.png)

从这张图可以看出,有用的节点其实是标有颜色的那些节点,其中绿色表示entry,红色表示sink。但是在导入的时候其他节点也会被导入。

我们可以通过从sink向上回溯,筛选出那些能够到达sink的节点,就可以把这些有颜色的节点筛选出来。

定义SinkReachable(method:Method, sink:Method, step:number) 表示 method 经过 step步能调用到 sink 。

那么久可以根据CallGraph(insn, caller, callee) 一步步向上回溯了,具体规则见

```dl
// 初始化 sink 到 sink 为 0
SinkReachable(sink, sink, 0) :-
    SinkMethod(sink).

// 如果caller 调用 了 callee
// 且 callee n 步到 sink
// 那么能够推导出 caller n+1 步 能到 sink
SinkReachable(caller, sink, n+1) :-
    n < MAXSTEP,
    SinkReachable(callee, sink, n), 
    CallGraph(_, caller, callee).
```

更近一步我们还可以寻找从entry 到 sink 的最短路径

定义 ShortestPathToSink(caller:Method, sink:Method, step:number) 表示caller 经过最短step步 到达 sink 

```dl
// 筛选出entry 到 sink 的 最短长度 n
ShortestPathToSink(entry, sink, n) :- 
    n = min step : {SinkReachable(entry, sink, step)},
    SinkMethod(sink),
    EntryMethod(entry).

// 如果caller 到 sink 最短距离 为 n
// 且 calle 到 sink 的距离为n-1
// 且 caller 调用 callee
// 那么可以推导出 callee 到 sink 的 最短距离为 n-1
ShortestPathToSink(callee, sink, n-1) :-
    n < MAXSTEP + 1,
    ShortestPathToSink(caller, sink, n),
    SinkReachable(callee, sink, n-1),
    CallGraph(_, caller, callee).
```

这里稍微解释一下

```dl
ShortestPathToSink(entry, sink, n) :-
    n = min step : {SinkReachable(entry, sink, step)},
    SinkMethod(sink),
    EntryMethod(entry).
```

大概的执行顺序是

1. 先从EntryMethod 选出一个 entry
2. 从SinkMethod 选出一个 sink
3. 然后从SinkReachable 找出第一个值为entry 第二个值为sink的数据,从这些数据中选出最小的step

这种就找到entry到sink的最短距离为n

## 使用方法

通过宏定义 可以配置不同的优化级别

1. `#define CHAO 1` 返回的是所有能到sink的节点
2. `#define CHAO 2` 返回的是entry到sink最短路径上的节点
3. 如果没有 CHAO 宏定义 则 返回的是entry在MAXSTEP之内能到达的所有节点

使用样例

[ctf-buggyLoader.dl](../example/ctf-buggyLoader.dl)

```dl
#define MAXSTEP 5
#define CHAO 2

#include "inputDeclaration.dl"
#include "utils.dl"
#include "cha.dl"


.decl NonParamPublicMethod(method:Method, class:Class)
.output NonParamPublicMethod

// 声明sink
SinkDesc("exec", "java.lang.Runtime").
SinkDesc("<init>", "java.lang.ProcessBuilder").
SinkDesc("start", "java.lang.ProcessImpl").
SinkDesc("loadClass", "java.lang.ClassLoader").
SinkDesc("defineClass", "java.lang.ClassLoader").
SinkDesc("readObject", "java.io.ObjectInputStream").
SinkDesc("readExternal", "java.io.ObjectInputStream").

// 声明入口方法
EntryMethod(method),
Reachable(method, 0),
NonParamPublicMethod(method, class) :- 
    MethodInfo(method, simplename, _, class, _, _, arity),
    MethodModifier("public", method),
    simplename != "<init>",
    arity = 0,
    SubClass(class, "java.io.Serializable").

.output SinkMethod
```

## 优化效果

以ctf-buggyLoader为例

1. 无 CHAO 宏定义
   - Nodes: 68561
   - Relations: 1080201
   - Time 1:39.87 s
2. `#define CHAO 1`
   - Nodes: 3864
   - Relations: 55736
   - Time: 20.859 s
3. `#define CHAO 2`
   - Nodes: 722
   - Relations: 3672
   - Time: 20.134 s

优化效果还行,之所以优化之后的时间更短,我猜测可能是IO更浪费时间,因为不优化的CallNode.csv 和 CallEdge.csv 都上百M了 。


================================================
FILE: docs/context-insensitive-points-to.md
================================================
# context-insensitive-points-to

以防后续更新代码,导致与本文描述的有所冲突,建议切换到 [pt-noctx](https://github.com/BytecodeDL/ByteCodeDL/blob/pt-noctx/docs/context-insensitive-points-to.md) 分支进行阅读

## 介绍

本文主要介绍上下文无关指针分析,建议读本文档之前,先学习

- https://pascal-group.bitbucket.io/lectures/PTA.pdf
- https://pascal-group.bitbucket.io/lectures/PTA-FD.pdf
- https://pascal-group.bitbucket.io/lectures/Datalog.pdf
- https://souffle-lang.github.io/components

最主要的是理解这个图
![context-insensitive-pt](./images/context-insensitive-pt.png)

指针分析主要是为了计算指针在运行过程中可能指向的对象,java中指针包括普通的变量,实例的字段,静态字段,以及数组元素等。由于Java多态的特性,不能仅根据声明类型解析函数调用,需要根据变量实际运行时的类型解析,通过指针分析可以得到变量在运行时指向的对象,进而可以得到对象的类型,然后根据类型即可解析出正确的被调函数,从而得到相对准确的函数调用图,准确的函数调用图对于过程间的分析至关重要,因此指针分析被视为Java静态分析的基础。

对象的生成通过关键字new,然后通过指令,在指针之间传播对象信息,指令包括

- new
  - 生成对象
- Assign
  - 变量之间赋值
- Store Instance Field
  - 写入field 写入的其实是x对应的对象实例相应的字段
- Load Instance Field
  - 读取field 读取的其实是x对应的对象实例相应的字段
- Call
  - 首先根据x的指向对象的类型以及函数签名解析出具体函数m
  - 设计到的传播关系有
    - 实际传参数 到 形式参数
    - 形式返回值 到 实际返回值
    - base 到 this

实现的时候还要考虑,类型转换(Cast),读写静态字段(Static Field),读写数组(Array)

指针分析有很多影响因素,包括是否上下文敏感(Context-Sensitive),是否流敏感(Flow-Sensitive),是否字段敏感(Field-Sensitive)等,这些因素会影响指针分析的精度和效率。

本次实现的是上下文不敏感,流不敏感,数组不敏感,字段敏感的指针分析。

- 上下文不敏感
  - 也就是对上下调用的上下文不敏感,也可以理解为没有调用的上下文
- 流不敏感
  - 指令的顺序不影响最终的分析结果,默认所有的分支都能走到
- 数组不敏感
  - 不区分数组中不同索引对应的值
- 字段敏感
  - 区分对象的不同字段

## 实现

[pt-noctx.dl](../logic/pt-noctx.dl) 主要就是将上图的规则用datalog表示。

```dl
// 建立一个Component,主要是为了解决命名冲突
.comp ContextInsensitivePt{
    // 表示 var 变量 指向 heap 这个对象
    .decl VarPointsTo(heap:Heap, var:Var)
    // 表示 baseHeap 这个对象的 field 指向 heap 这个对象
    .decl InstanceFieldPointsTo(heap:Heap, baseHeap:Heap, field:Field)
    // 表示 静态 field 指向 heap 这个对象
    .decl StaticFieldPointsTo(heap:Heap, field:Field)
    // 表示 baseHeap数组中,包含了heap对象
    .decl ArrayIndexPointsTo(heap:Heap, baseHeap:Heap)
    // 表示 在insn指令中 caller 调用了 callee
    .decl CallGraph(insn:Insn, caller:Method, callee:Method)
    // 表示 方法可访问到
    .decl Reachable(method:Method)

    // new
    // 如果 method 方法可访问
    // 且 在method中,将创建号的heap对象赋值给了var变量
    // 那么能够推导出 var变量指向 heap 对象
    VarPointsTo(heap, var) :-
        Reachable(method),
        AssignHeapAllocation(_, _, heap, var, method, _).
    
    // assign
    // 如果method 方法可访问
    // 且 form 变量 指向 heap 对象
    // 且 在method中,将from变量赋值给了to 即 to=form
    // 那么能够推到出 to变量也指向 heap 对象
    VarPointsTo(heap, to) :- 
        Reachable(method),
        VarPointsTo(heap, from),
        AssignLocal(_, _, from, to, method).
    
    // cast
    // 如果method 方法可访问
    // 且 form 变量 指向 heap 对象
    // 且 在method中,将from变量类型转换后赋值给了to 即 to=(T)from
    // 那么能够推到出 to变量也指向 heap 对象
    VarPointsTo(heap, to) :- 
        Reachable(method),
        AssignCast(_, _, from, to, _, method),
        VarPointsTo(heap, from).
    
    // load field
    // 如果method 方法可访问
    // 且 在method中,将base变量的field取出赋值给了to 也就是 to=base.field
    // 且 base 指向 baseHeap 对象
    // 且 baseHeap对象的field指向 heap 对象
    // 那么能够推到出 to 也指向 heap 对象
    VarPointsTo(heap, to) :-
        Reachable(method),
        LoadInstanceField(_, _, to, base, field, method),
        VarPointsTo(baseHeap, base),
        InstanceFieldPointsTo(heap, baseHeap, field).
    
    // store field
    // 如果method 方法可访问
    // 且 在method中,将from存到了变量base的field,也就是base.field=from
    // 且 from 指向 heap 对象
    // 且 base 指向 baseHeap 对象
    // 那么 能够推到出baseHeap对象的field也指向 heap 对象
    InstanceFieldPointsTo(heap, baseHeap, field) :-
        Reachable(method),
        StoreInstanceField(_, _, from, base, field, method),
        VarPointsTo(heap, from),
        VarPointsTo(baseHeap, base).
    
    // load staic field
    // 如果method 方法可访问
    // 且 在method中,将静态field取出赋值给了to 即 to = T.field
    // 且 field 指向 heap 对象
    // 那么可以推导出 to 也指向 heap 对象
    VarPointsTo(heap, to) :-
        Reachable(method),
        LoadStaticField(_, _, to, field, method),
        StaticFieldPointsTo(heap, field).
    
    // store static field
    // 如果method 方法可访问
    // 且在method中,将from存入静态field 即 T.field = from
    // 且 from 指向 heap 对象
    // 那么可以推到出 静态field指向 heap 对象
    StaticFieldPointsTo(heap, field) :-
        Reachable(method),
        StoreStaticField(_, _, from, field, method),
        VarPointsTo(heap, from).
    
    // load from array
    // 如果method可访问
    // 且 从base数组中取出元素到to to = base[i]
    // 且 base 指向 baseHeap 数组对象
    // 且 baseHeap 数组对象中 包含 heap 对象
    // 那么 to 可能指向 heap 
    // 这里的实现未区分取第几个索引
    VarPointsTo(heap, to) :-
        Reachable(method),
        LoadArrayIndex(_, _, to, base, method),
        VarPointsTo(baseHeap, base),
        ArrayIndexPointsTo(heap, baseHeap).

    // store into array
    // 如果method可访问
    // 将 form 存到 base 数组中 即 base[i] = from
    // from 指向 heap 对象 
    // base 指向 baseHeap 数组对象
    // 那么能推导出 baseHeap 数组对象 包含 heap 对象
    ArrayIndexPointsTo(heap, baseHeap) :-
        Reachable(method),
        StoreArrayIndex(_, _, from, base, method),
        VarPointsTo(heap, from),
        VarPointsTo(baseHeap, base).
    
    // 下面开始涉及到过程间的指针分析
    // 先构造调用图
    // Special 和 Static 和 CHA 处理方式一样,编译时callee就确定,不需要再进行解析
    Reachable(callee),
    CallGraph(insn, caller, callee) :- 
        Reachable(caller),
        SpecialMethodInvocation(insn, _, callee, _, caller).
    
    Reachable(callee),
    CallGraph(insn, caller, callee) :- 
        Reachable(caller),
        StaticMethodInvocation(insn, _, callee, caller).
    
    // Virtual Call 需要根据 base 指向 对象 的类型 进行 dispatch
    // caller 要可达
    // 在caller 中 virtual call 了 method
    // 调用时 base 指向 baseHeap 对象
    // baseHeap 对象的类型 为 class
    // 根据method 解析出 被调函数的签名
    // 通过 函数签名 和 实际类型 解析出真正的被调函数callee
    Reachable(callee),
    CallGraph(insn, caller, callee) :- 
        Reachable(caller),
        VirtualMethodInvocation(insn, _, method, base, caller),
        VarPointsTo(baseHeap, base),
        NormalHeap(baseHeap, class),
        MethodInfo(method, simplename, _, _, _, descriptor, _),
        Dispatch(simplename, descriptor, class, callee).
    
    // param
    // 调用图中存在调用 insn
    // 调用时第n个实际参数传的是 变量 arg
    // 被调函数 callee 的 第 n 个 形式参数是 param
    // 如果 arg 指向了heap 对象
    // 那么 param 也指向heap 对象
    VarPointsTo(heap, param) :- 
        CallGraph(insn, _, callee),
        ActualParam(n, insn, arg),
        FormalParam(n, callee, param),
        VarPointsTo(heap, arg).
    
    // return
    // 调用图中存在调用 insn
    // 如果 在callee中,返回语句返回的是var变量
    // 调用后的返回值赋值给了return变量
    // var 变量 指向 heap 对象
    // 那么 return 也指向 heap 对象
    VarPointsTo(heap, return) :- 
        CallGraph(insn, _, callee),
        Return(_, _, var, callee),
        AssignReturnValue(insn, return),
        VarPointsTo(heap, var).
    
    // this
    // 调用图中存在调用 insn
    // 调用时 base 指向 heap
    // 那么调用时callee 的 this 变量 也指向 heap 对象
    VarPointsTo(heap, this) :- 
        CallGraph(insn, _, callee),
        (
            VirtualMethodInvocation(insn, _, _, base, _);
            SpecialMethodInvocation(insn, _, _, base, _)
        ),
        ThisVar(callee, this),
        VarPointsTo(heap, base).
}
```

## 使用样例

[pt-noctx-example-1.dl](../example/pt-noctx-example-1.dl)

```dl
#include "inputDeclaration.dl"
#include "utils.dl"
#include "pt-noctx.dl"

// 实例化 component
.init cipt = ContextInsensitivePt

// 初始化readchable
cipt.Reachable(method) :-
    MethodInfo(method, simplename, _, _, _, descriptor, _),
    simplename = "main",
    descriptor = "([Ljava/lang/String;)V".

.output cipt.VarPointsTo
```

创建benchmark facts

```bash
 java8 -jar soot-fact-generator/build/libs/soot-fact-generator.jar -i Benchmark-1.0-SNAPSHOT.jar --full -l /Library/Java/JavaVirtualMachines/jdk1.8.0_211.jdk/Contents/Home/jre/lib/rt.jar -d pttest --allow-phantom --generate-jimple --facts-subset APP
```

然后执行

```bash
souffle -F factsdir -D ByteCodeDL/output ByteCodeDL/example/pt-noctx-example-1.dl
```

分析结果保存在 output/cipt.VarPointsTo

如果想学习更完善的指针分析,可以看一下这两个repo

- https://github.com/souffle-lang/java-pts
- https://bitbucket.org/yanniss/doop/src

搞学术的可以去看看doop


================================================
FILE: docs/ptaint.md
================================================
# ptaint

## Introduction

主要是根据ptaint这篇论文的思想,将指针分析和污点分析统一起来进行分析,建议先学习下面三份资料

- https://yanniss.github.io/ptaint-oopsla17-prelim.pdf
  - https://www.youtube.com/watch?v=IA08d-kiCy8
- https://pascal-group.bitbucket.io/lectures/Security.pdf

污点分析:which sources can reach which sinks

指针分析:which object sources can reach which variables

指针分析是计算指针在运行过程中可能指向哪些对象,也可以理解为创建之后的对象,会传播到哪些指针。

```java
A a = new A("foo"); // object created
if (*)
   aa = a;          // flows locally
B b = foo(a);       // flows in/out via stack
b.parent = a;       // stored/loaded on heap
```

污点分析是计算sink函数的参数是否是污点,也可以理解为污点源会传播到哪些指针

```java
String a = source.readLine(); // taint source
if (*)
   aa = a;          // flows locally
B b = foo(a);       // flows in/out via stack
b.parent = a;       // stored/loaded on heap
```

两者可以统一成,值在指针之间的传播,也就是在PFG(Pointer Flow Graph)中传播

污点分析和指针分析还多了一些东西,比如污点转移,以及污点消除(净化函数)

```java
String a = source.readLine(); // taint source
if (*)
   aa = a;          // flows locally
B b = foo(a);       // flows in/out via stack
b.parent = a;       // stored/loaded on heap

byte[] aAsbytes = a.getBytes(); // transfer

String aSafe = URLEncoder.encode(a, "UTF-8"); // sanitize
```

Ptaint论文中将污点视为独立的对象,而不是给传统的对象打上污点标记,会创建新的污点对象,和传统的对象分开各自独立沿着相同的PFG传播



按照论文中的给的示例规则得到的实现

[ptaint.dl](https://github.com/BytecodeDL/ByteCodeDL/blob/ptaint/logic/ptaint.dl) 

```dl
.comp PTaint{
    // 指针分析原有的relation
    .decl VarPointsTo(heap:Heap, var:Var)
    .decl InstanceFieldPointsTo(heap:Heap, baseHeap:Heap, field:Field)
    .decl CallGraph(insn:Insn, caller:Method, callee:Method)
    .decl Reachable(method:Method)
    .decl InterProcAssign(from:Var, to:Var)
		
		// 污点分析相关的新relation
		// 表示通过insn指令,创建的新的污点对象heap,包括污点源的生成,以及污点转移时的生成
    .decl TaintHeap(insn:Insn, heap:Heap)
    // 表示调用指令insn发生时,危险函数的参数指向了污点对象heap
    .decl Leak(insn:Insn, heap:Heap)
    // 表示source函数,其返回值表示污点源
    .decl SourceMethod(method:Method)
    // 表示sink函数,其第n个实际参数如果指向污点对象,则表示可能存在安全风险
    .decl SinkMethod(method:Method, n:number)
		// 表示sanitize函数,经过其处理的污点,将不再是污点,也就是说污点无法通过sanitize传播,是在实际参数向形式参数传播时阻断的
    .decl SanitizeMethod(method:Method)
    // 表示sanitize函数的形式参数
    .decl SanitizeMethodParam(var:Var)
		// 筛选出sanitize函数的形式参数
    SanitizeMethodParam(var) :-
        FormalParam(_, method, var),
        SanitizeMethod(method).
		
		// 污点转移相关的
		// base 是 污点 返回值也是污点
    .decl BaseToRetTransfer(method:Method)
    // 参数是污点返回也是污点
    .decl ArgToRetTransfer(method:Method, n:number)
    // 将上面两个合并成一个,或者将污点转移抽象成from变量污染了to变量
    .decl IsTaintedFrom(insn:Insn, from:Var, to:Var)
    // heap 对象 污染了 newHeap对象
    .decl TransferTaint(heap:Heap, newHeap:Heap)
    

    // new
    VarPointsTo(heap, var) :-
        Reachable(method),
        AssignHeapAllocation(_, _, heap, var, method, _).
    
    // assign
    VarPointsTo(heap, to) :- 
        Reachable(method),
        VarPointsTo(heap, from),
        AssignLocal(_, _, from, to, method).
    
    // load field
    VarPointsTo(heap, to) :-
        Reachable(method),
        LoadInstanceField(_, _, to, base, field, method),
        VarPointsTo(baseHeap, base),
        InstanceFieldPointsTo(heap, baseHeap, field).
    
    // store field
    InstanceFieldPointsTo(heap, baseHeap, field) :-
        Reachable(method),
        StoreInstanceField(_, _, from, base, field, method),
        VarPointsTo(heap, from),
        VarPointsTo(baseHeap, base).
    
    // virtual call
    Reachable(callee),
    CallGraph(insn, caller, callee) :- 
        Reachable(caller),
        VirtualMethodInvocation(insn, _, method, base, caller),
        VarPointsTo(baseHeap, base),
        NormalHeap(baseHeap, class),
        MethodInfo(method, simplename, _, _, _, descriptor, _),
        Dispatch(simplename, descriptor, class, callee).
    
    // arg -> param
    InterProcAssign(arg, param) :-
        CallGraph(insn, _, callee),
        ActualParam(n, insn, arg),
        FormalParam(n, callee, param).
    
    // var -> return
    InterProcAssign(var, return) :-
        CallGraph(insn, _, callee),
        Return(_, _, var, callee),
        AssignReturnValue(insn, return).

    // normal heap
    // 正常对象正常传播
    VarPointsTo(heap, to) :- 
        InterProcAssign(from, to),
        VarPointsTo(heap, from),
        // 比起指针分析多了个这个限制,用于限制heap为正常对象
        NormalHeap(heap, _).
    
    // taint heap
    // 阻断污点对象传播到净化函数的形式参数
    VarPointsTo(heap, to) :- 
        InterProcAssign(from, to),
        VarPointsTo(heap, from),
        TaintHeap(_, heap),
        !SanitizeMethodParam(to).
    
    // this
    VarPointsTo(heap, this) :-
        CallGraph(insn, _, callee),
        VirtualMethodInvocation(insn, _, _, base, _),
        VarPointsTo(heap, base),
        ThisVar(callee, this).
    
    // 污点对象的生成
    TaintHeap(insn, heap),
    VarPointsTo(heap, to) :-
        SourceMethod(callee),
        CallGraph(insn, _, callee),
        AssignReturnValue(insn, to),
        heap = cat("NewTainted::", insn).
    
    // 判断sink函数的参数是否指向污点对象
    Leak(insn, heap) :-
        CallGraph(insn, _, callee),
        SinkMethod(callee, n),
        ActualParam(n, insn, arg),
        VarPointsTo(heap, arg),
        TaintHeap(_, heap).
		
		// base -> ret
    IsTaintedFrom(insn, base, ret) :-
        CallGraph(insn, _, callee),
        BaseToRetTransfer(callee),
        VirtualMethodInvocation(insn, _, _, base, _),
        AssignReturnValue(insn, ret).
    // arg -> ret
    IsTaintedFrom(insn, arg, ret) :-
        CallGraph(insn, _, callee),
        ArgToRetTransfer(callee, n),
        ActualParam(n, insn, arg),
        AssignReturnValue(insn, ret).
		
		// 污点转移
		// from 指向了污点对象heap
		// 且from能污染to
		// 那么to也是污点对象,也要指向一个污点对象
		// 这里没有直接让to指向新创建的污点对象
		// 而是先找到to指向的正常对象oldHeap,oldHeap第一个流向的指针var,然后让newHeap也流向指针var,即var指向newHeap
		// 由于oldHeap流向var之后,通过PFG可以流到to,那么newHeap也能流到to,这样也把和var alias的指针一并污染了
    TaintHeap(insn, newHeap),
    TransferTaint(heap, newHeap),
    VarPointsTo(newHeap, var) :- 
        IsTaintedFrom(insn, from, to),
        VarPointsTo(heap, from),
        TaintHeap(_, heap),
        newHeap = cat("TransferTaint::", insn),
        VarPointsTo(oldHeap, to),
        AssignHeapAllocation(_, _, oldHeap, var, _, _).
}
```

[ptaint-example-1.dl](https://github.com/BytecodeDL/ByteCodeDL/blob/ptaint/example/ptaint-example-1.dl)

```
#include "inputDeclaration.dl"
#include "utils.dl"
#include "ptaint.dl"

.init ptaint = PTaint

ptaint.Reachable("<com.bytecodedl.benchmark.demo.TaintDemo3: void main(java.lang.String[])>").

ptaint.SourceMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: java.lang.String Source()>").
ptaint.SinkMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: void Sink(java.lang.String)>", 0).

ptaint.BaseToRetTransfer("<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>").
ptaint.BaseToRetTransfer("<java.lang.StringBuilder: java.lang.String toString()>").

ptaint.ArgToRetTransfer("<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>", 0).

ptaint.SanitizeMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: java.lang.String Sanitize(java.lang.String)>").


.decl TaintVar(var:Var)

TaintVar(var) :-
    ptaint.VarPointsTo(heap, var),
    ptaint.TaintHeap(_, heap).

.output TaintVar

.output ptaint.TaintHeap
.output ptaint.TransferTaint
.output ptaint.VarPointsTo
```

可以看到大部分的规则都是和指针分析一样的,那么我能不能利用之前实现的[pt-noctx.dl](https://github.com/BytecodeDL/ByteCodeDL/blob/pt-noctx/logic/pt-noctx.dl)呢?答案是可以的,但是有一处要稍微改一下就是

```
// param
VarPointsTo(heap, param) :- 
    CallGraph(insn, _, callee),
    ActualParam(n, insn, arg),
    FormalParam(n, callee, param),
    VarPointsTo(heap, arg),
    // 在实际参数向形式参数传播的时候,正常的对象可以任意传播,污点对象还需要考虑被sanitize阻断的问题
    NormalHeap(heap, _).
```

更改后的[pt-noctx.dl](https://github.com/BytecodeDL/ByteCodeDL/blob/ptaint-upgrade/logic/pt-noctx.dl)

更新后的[ptaint.dl](https://github.com/BytecodeDL/ByteCodeDL/blob/ptaint-upgrade/logic/ptaint.dl)

```dl
#include "pt-noctx.dl"

.comp PTaint{
		// 实例上下文无关指针分析
    .init cipt = ContextInsensitivePt
		
		// 定义污点分析相关的
    .decl TaintHeap(insn:Insn, heap:Heap)
    .decl SourceMethod(method:Method)
    .decl SinkMethod(method:Method, n:number)

    .decl SanitizeMethod(method:Method)

    .decl BaseToRetTransfer(method:Method)
    .decl ArgToRetTransfer(method:Method, n:number)
    .decl IsTaintedFrom(insn:Insn, from:Var, to:Var)
    .decl TransferTaint(heap:Heap, newHeap:Heap)
    
    // 阻止污点对象传播到sanitize函数的形式参数
    // taint arg to param
    cipt.VarPointsTo(heap, param) :- 
        cipt.CallGraph(insn, _, callee),
        ActualParam(n, insn, arg),
        FormalParam(n, callee, param),
        cipt.VarPointsTo(heap, arg),
        TaintHeap(_, heap),
        !SanitizeMethod(callee).
    
    
    TaintHeap(insn, heap),
    cipt.VarPointsTo(heap, to) :-
        SourceMethod(callee),
        cipt.CallGraph(insn, _, callee),
        AssignReturnValue(insn, to),
        heap = cat("NewTainted::", insn).

    IsTaintedFrom(insn, base, ret) :-
        cipt.CallGraph(insn, _, callee),
        BaseToRetTransfer(callee),
        VirtualMethodInvocation(insn, _, _, base, _),
        AssignReturnValue(insn, ret).
    
    IsTaintedFrom(insn, arg, ret) :-
        cipt.CallGraph(insn, _, callee),
        ArgToRetTransfer(callee, n),
        ActualParam(n, insn, arg),
        AssignReturnValue(insn, ret).

    TaintHeap(insn, newHeap),
    TransferTaint(heap, newHeap),
    cipt.VarPointsTo(newHeap, var) :- 
        IsTaintedFrom(insn, from, to),
        cipt.VarPointsTo(heap, from),
        TaintHeap(_, heap),
        newHeap = cat("TransferTaint::", insn),
        cipt.VarPointsTo(oldHeap, to),
        AssignHeapAllocation(_, _, oldHeap, var, _, _).
}
```



## Example 1

我们先分析Benchmark中的[TaintDemo3](https://github.com/BytecodeDL/Benchmark/blob/main/src/main/java/com/bytecodedl/benchmark/demo/TaintDemo3.java)

```java
public class TaintDemo3 {
    public static void main(String[] args) {
        TaintDemo3 demo = new TaintDemo3();
        String name = demo.Source();
        demo.test1(name);
    }

    public void test1(String name){
        String sql0= "select * from user where name='" + name + "'";
        String sql1 = sql0;
        String sql = Sanitize(sql1);
        Sink(sql);
    }

    public void Sink(String param){

    }

    public String Sanitize(String param){
        String ret = param.replace('\'', '`');
        return ret;
    }

    public String Source(){
        return "tainted name";
    }
}
```

执行

```bash
// 代码下载到本地
git clone git@github.com:BytecodeDL/Benchmark.git
// 打包
mvn clean package
// 切换目录
cd target
// 生成facts
java8 -jar ~/code/soot-fact-generator/build/libs/soot-fact-generator.jar -i Benchmark-1.0-SNAPSHOT.jar --full -l /Library/Java/JavaVirtualMachines/jdk1.8.0_211.jdk/Contents/Home/jre/lib/rt.jar -d tainttest --allow-phantom --generate-jimple
// 切换目录
cd tainttest
// 执行souffle
souffle -F . -D output ~/code/ByteCodeDL/example/ptaint-example-1.dl
```

然后在ouput目录能够看到`grep "Demo3" TaintVar.csv`结果

```
<com.bytecodedl.benchmark.demo.TaintDemo3: void test1(java.lang.String)>/@parameter0
<com.bytecodedl.benchmark.demo.TaintDemo3: void test1(java.lang.String)>/$stack5
<com.bytecodedl.benchmark.demo.TaintDemo3: void test1(java.lang.String)>/$stack6
<com.bytecodedl.benchmark.demo.TaintDemo3: void test1(java.lang.String)>/$stack7
<com.bytecodedl.benchmark.demo.TaintDemo3: void test1(java.lang.String)>/$stack8
<com.bytecodedl.benchmark.demo.TaintDemo3: void main(java.lang.String[])>/name#_6
<com.bytecodedl.benchmark.demo.TaintDemo3: void test1(java.lang.String)>/name#_0
<com.bytecodedl.benchmark.demo.TaintDemo3: void test1(java.lang.String)>/sql1#_12
<com.bytecodedl.benchmark.demo.TaintDemo3: void test1(java.lang.String)>/sql0#_11
```

可以看到sql1和sql0都是污点,sql不是污点,比较符合我们的预期。

下面介绍如何编写出[ptaint-example-1.dl](https://github.com/BytecodeDL/ByteCodeDL/blob/ptaint-upgrade/example/ptaint-example-1.dl)

首先要实例化Ptaint 并 初始化污点分析的起始方法,在这里起始方法,也就是分析的入口,为TaintDemo3的main函数

```
// 实例化ptaint
.init ptaint = PTaint

// 初始化上下文无关文法的入口函数
ptaint.cipt.Reachable("<com.bytecodedl.benchmark.demo.TaintDemo3: void main(java.lang.String[])>").
```

然后定义Source,Sink和Sanitize函数

```
// 定义source函数
ptaint.SourceMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: java.lang.String Source()>").
// 定义危险函数
ptaint.SinkMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: void Sink(java.lang.String)>", 0).
// 定义净化函数
ptaint.SanitizeMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: java.lang.String Sanitize(java.lang.String)>").
```

接下来就是定义污点转移函数了,这时候只看java代码看不出来东西,这时候需要看soot生成的jimple代码,也就是下面的代码

```jimple
 public void test1(java.lang.String)
    {
        java.lang.StringBuilder $stack5, $stack6, $stack7, $stack8;
        java.lang.String name#_0, sql0#_11, sql1#_12, sql#_13;
        com.bytecodedl.benchmark.demo.TaintDemo3 this#_0;

        this#_0 := @this: com.bytecodedl.benchmark.demo.TaintDemo3;

        name#_0 := @parameter0: java.lang.String;

        $stack5 = new java.lang.StringBuilder;

        specialinvoke $stack5.<java.lang.StringBuilder: void <init>()>();

        $stack6 = virtualinvoke $stack5.<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>("select * from user where name=\'");

        $stack7 = virtualinvoke $stack6.<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>(name#_0);

        $stack8 = virtualinvoke $stack7.<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>("\'");

        sql0#_11 = virtualinvoke $stack8.<java.lang.StringBuilder: java.lang.String toString()>();

        sql1#_12 = sql0#_11;

        sql#_13 = virtualinvoke this#_0.<com.bytecodedl.benchmark.demo.TaintDemo3: java.lang.String Sanitize(java.lang.String)>(sql1#_12);

        virtualinvoke this#_0.<com.bytecodedl.benchmark.demo.TaintDemo3: void Sink(java.lang.String)>(sql#_13);

        return;
    }
```

也就是将字符串的拼接分成了下面几步

```

$stack5 = new java.lang.StringBuilder;

specialinvoke $stack5.<java.lang.StringBuilder: void <init>()>();

$stack6 = virtualinvoke $stack5.<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>("select * from user where name=\'");

$stack7 = virtualinvoke $stack6.<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>(name#_0);

$stack8 = virtualinvoke $stack7.<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>("\'");

sql0#_11 = virtualinvoke $stack8.<java.lang.StringBuilder: java.lang.String toString()>();
```

转换成java就是

```
$stack5 = new StringBuilder();
$stack6 = $stack5.append("select * from user where name=\'");
$stack7 = $stack6.append(name#_0);
$stack8 = $stack7.append("\'");
$sql0#_11 = $stack8.toString();
```

name#_0 是污点变量,由于`$stack7 = $stack6.append(name#_0);` ,我门希望`$stack7`也是污点变量,所以这里应该添加个arg 向 ret的转移。

```
ptaint.ArgToRetTransfer("<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>", 0).
```

由于`$stack7`是污点变量,由于`$stack8 = $stack7.append("\'");` ,我们希望`$stack8`也是污点变量,所以这里应该添加个base 向 ret的转移。

```
ptaint.BaseToRetTransfer("<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>").
```

由于`$stack8`是污点变量,由于`$sql0#_11 = $stack8.toString();`,我们希望`$sql0#_11`也是污点变量,所以这里应该添加个base 向ret的转移。

```
ptaint.BaseToRetTransfer("<java.lang.StringBuilder: java.lang.String toString()>").
```

全部规则如下: [ptaint-example-1.dl](https://github.com/BytecodeDL/ByteCodeDL/blob/ptaint-upgrade/example/ptaint-example-1.dl)

```
#include "inputDeclaration.dl"
#include "utils.dl"
#include "ptaint.dl"

// 实例化ptaint
.init ptaint = PTaint

// 初始化上下文无关文法的入口函数
ptaint.cipt.Reachable("<com.bytecodedl.benchmark.demo.TaintDemo3: void main(java.lang.String[])>").

// 定义source函数
ptaint.SourceMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: java.lang.String Source()>").
// 定义危险函数
ptaint.SinkMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: void Sink(java.lang.String)>", 0).
// 定义净化函数
ptaint.SanitizeMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: java.lang.String Sanitize(java.lang.String)>").

// 定义污点转移函数
ptaint.BaseToRetTransfer("<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>").
ptaint.BaseToRetTransfer("<java.lang.StringBuilder: java.lang.String toString()>").

ptaint.ArgToRetTransfer("<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>", 0).




.decl TaintVar(var:Var)

TaintVar(var) :-
    ptaint.cipt.VarPointsTo(heap, var),
    ptaint.TaintHeap(_, heap).

.output TaintVar

.output ptaint.TaintHeap
.output ptaint.TransferTaint
.output ptaint.cipt.VarPointsTo
```

但是在分析[TaintDemo2](https://github.com/BytecodeDL/Benchmark/blob/main/src/main/java/com/bytecodedl/benchmark/demo/TaintDemo2.java)的时候,就会发现遇到问题了

```java
public class TaintDemo2 {
    public static void main(String[] args) {
        TaintDemo2 demo = new TaintDemo2();
        String name = demo.Source();
        demo.test1(name);
    }

    public void test1(String name){
        String sql = "select * from user where name='" + name + "'";
        sql = Sanitize(sql);
        Sink(sql);
    }

    public void Sink(String param){

    }

    public String Sanitize(String param){
        String ret = param.replace('\'', '`');
        return ret;
    }

    public String Source(){
        return "tainted name";
    }
}
```

对应的jimple为

```
public void test1(java.lang.String)
    {
        java.lang.StringBuilder $stack3, $stack4, $stack5, $stack6;
        java.lang.String name#_0, sql#_11;
        com.bytecodedl.benchmark.demo.TaintDemo2 this#_0;

        this#_0 := @this: com.bytecodedl.benchmark.demo.TaintDemo2;

        name#_0 := @parameter0: java.lang.String;

        $stack3 = new java.lang.StringBuilder;

        specialinvoke $stack3.<java.lang.StringBuilder: void <init>()>();

        $stack4 = virtualinvoke $stack3.<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>("select * from user where name=\'");

        $stack5 = virtualinvoke $stack4.<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>(name#_0);

        $stack6 = virtualinvoke $stack5.<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>("\'");

        sql#_11 = virtualinvoke $stack6.<java.lang.StringBuilder: java.lang.String toString()>();

        sql#_11 = virtualinvoke this#_0.<com.bytecodedl.benchmark.demo.TaintDemo2: java.lang.String Sanitize(java.lang.String)>(sql#_11);

        virtualinvoke this#_0.<com.bytecodedl.benchmark.demo.TaintDemo2: void Sink(java.lang.String)>(sql#_11);

        return;
    }
```

将ptaint-example-1.dl中的TaintDemo3换成TaintDemo2之后后

```
<com.bytecodedl.benchmark.demo.TaintDemo2: void test1(java.lang.String)>/@parameter0
<com.bytecodedl.benchmark.demo.TaintDemo2: void Sink(java.lang.String)>/@parameter0
<com.bytecodedl.benchmark.demo.TaintDemo2: java.lang.String Sanitize(java.lang.String)>/ret#_21
<com.bytecodedl.benchmark.demo.TaintDemo2: void test1(java.lang.String)>/$stack3
<com.bytecodedl.benchmark.demo.TaintDemo2: void test1(java.lang.String)>/$stack4
<com.bytecodedl.benchmark.demo.TaintDemo2: void test1(java.lang.String)>/$stack5
<com.bytecodedl.benchmark.demo.TaintDemo2: void test1(java.lang.String)>/$stack6
<com.bytecodedl.benchmark.demo.TaintDemo2: void main(java.lang.String[])>/name#_6
<com.bytecodedl.benchmark.demo.TaintDemo2: void test1(java.lang.String)>/name#_0
<com.bytecodedl.benchmark.demo.TaintDemo2: void test1(java.lang.String)>/sql#_11
<com.bytecodedl.benchmark.demo.TaintDemo2: void Sink(java.lang.String)>/param#_0
```

会发现`sql#_11` 虽然经过了Sanitize处理,但是还是被标记为了污点变量,这是为什么呢?这是因为目前的分析都是流不敏感的,有没有什么办法解决呢?有在创建facts时加上`--ssa`参数

```
java8 -jar ~/code/soot-fact-generator/build/libs/soot-fact-generator.jar -i Benchmark-1.0-SNAPSHOT.jar --full -l /Library/Java/JavaVirtualMachines/jdk1.8.0_211.jdk/Contents/Home/jre/lib/rt.jar -d tainttest --allow-phantom --generate-jimple --ssa
```

加上这个参数之后会生成shimple,保证每个变量只会被赋值一次,就会变成下面这样

```shimple
public void test1(java.lang.String)
    {
        java.lang.StringBuilder $stack3, $stack4, $stack5, $stack6;
        java.lang.String name#_0, sql#_11, sql_$$A_1#_12;
        com.bytecodedl.benchmark.demo.TaintDemo2 this#_0;

        this#_0 := @this: com.bytecodedl.benchmark.demo.TaintDemo2;

        name#_0 := @parameter0: java.lang.String;

        $stack3 = new java.lang.StringBuilder;

        specialinvoke $stack3.<java.lang.StringBuilder: void <init>()>();

        $stack4 = virtualinvoke $stack3.<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>("select * from user where name=\'");

        $stack5 = virtualinvoke $stack4.<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>(name#_0);

        $stack6 = virtualinvoke $stack5.<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>("\'");

        sql#_11 = virtualinvoke $stack6.<java.lang.StringBuilder: java.lang.String toString()>();

        sql_$$A_1#_12 = virtualinvoke this#_0.<com.bytecodedl.benchmark.demo.TaintDemo2: java.lang.String Sanitize(java.lang.String)>(sql#_11);

        virtualinvoke this#_0.<com.bytecodedl.benchmark.demo.TaintDemo2: void Sink(java.lang.String)>(sql_$$A_1#_12);

        return;
    }
```

原本Sanitize返回的也是`sql#_11` 现在变成了`sql_$$A_1#_12`,这样就能区分原本两个同名变量在不同时刻的值了。

## Example 2

在实际的场景中,比如spring开发框架下,污点源不是来自source函数的返回值,可能来自函数的参数,这种情况该怎么处理呢?

我们还以TaintDemo3为例,我们以test1方法为分析的起点,形式参数name作为污点源。这时候我们需要模拟创建对象,包括test1@this 以及name参数

```
.decl EntryMethod(method:Method)

EntryMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: void test1(java.lang.String)>").


ptaint.cipt.Reachable(method) :-
    EntryMethod(method).

NormalHeap(heap, class),
ptaint.cipt.VarPointsTo(heap, this) :-
    ThisVar(method, this),
    EntryMethod(method),
    VarType(this, class),
    heap = cat("Mock::", class).

NormalHeap(heap, class),
ptaint.TaintHeap(insn, taintHeap),
ptaint.cipt.VarPointsTo(heap, param),
ptaint.cipt.VarPointsTo(taintHeap, param) :- 
    EntryMethod(method),
    FormalParam(_, method, param),
    VarType(param, class),
    heap = cat("Mock::", class),
    taintHeap = cat("NewTainted::", class),
    insn = "Init::Param".
```

其他部分同ptaint-example-1.dl,完整见[ptaint-example-2.dl](https://github.com/BytecodeDL/ByteCodeDL/blob/ptaint-upgrade/example/ptaint-example-2.dl)

```
#include "inputDeclaration.dl"
#include "utils.dl"
#include "ptaint.dl"

.init ptaint = PTaint

// 定义入口函数
.decl EntryMethod(method:Method)

EntryMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: void test1(java.lang.String)>").

// 初始化指针分析入口函数
ptaint.cipt.Reachable(method) :-
    EntryMethod(method).

// test1@this 指向虚拟创建的对象
NormalHeap(heap, class),
ptaint.cipt.VarPointsTo(heap, this) :-
    ThisVar(method, this),
    EntryMethod(method),
    VarType(this, class),
    heap = cat("Mock::", class).

// test1的参数,指向虚拟创建的污点对象和正常对象
NormalHeap(heap, class),
ptaint.TaintHeap(insn, taintHeap),
ptaint.cipt.VarPointsTo(heap, param),
ptaint.cipt.VarPointsTo(taintHeap, param) :- 
    EntryMethod(method),
    FormalParam(_, method, param),
    VarType(param, class),
    heap = cat("Mock::", class),
    taintHeap = cat("NewTainted::", class),
    insn = "Init::Param".


ptaint.SourceMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: java.lang.String Source()>").
ptaint.SinkMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: void Sink(java.lang.String)>", 0).

ptaint.BaseToRetTransfer("<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>").
ptaint.BaseToRetTransfer("<java.lang.StringBuilder: java.lang.String toString()>").

ptaint.ArgToRetTransfer("<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>", 0).

ptaint.SanitizeMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: java.lang.String Sanitize(java.lang.String)>").


.decl TaintVar(var:Var)

TaintVar(var) :-
    ptaint.cipt.VarPointsTo(heap, var),
    ptaint.TaintHeap(_, heap).

.output TaintVar

.output ptaint.TaintHeap
.output ptaint.TransferTaint
.output ptaint.cipt.VarPointsTo
```



================================================
FILE: docs/query.md
================================================
# query

有了前面的铺垫,到这节,我们就可以通过ByteCodeDL ,快速筛选出一些class和method。

## 案例一

比如这位群友的需求
> 有没有啥东西,可以自动找jvm里符合某些要求的类

> 比如 我只想找有两个构造参数的类,其中一个传入的还得是数组参数

> 就这样找,有啥现成的工具么

前置知识,构造函数在jimple中的simplename为`<init>`,souffle中提供了一些[字符串相关的函数](https://souffle-lang.github.io/constraints),如contains,match等

有了前置知识之后,我们可以将上述的问题翻译成下面的三个条件:

1. 方法是构造函数,simplename=`<init>`
2. 构造函数有两个构造参数, arity=2
3. 其中一个构造函数的的参数是数组,contains(`[]`, param)

将上述的条件,翻译成datalog如下
`query-example1.dl`
```
#include "inputDeclaration.dl"

.decl QueryResult(class:Class, method:Method)
.output QueryResult

QueryResult(class, method) :- 
    MethodInfo(method, simplename, param, class, _, _, arity),
    simplename = "<init>",
    contains("[]", param),
    arity = 2.
```
然后执行`souffle -F facts-dir -D output-dir query-example1.dl -j 8` 需要用soot-fact-generator.jar对要分析的jar提前创建好facts,可参考 https://github.com/BytecodeDL/soot-fact-generator

结果示例

```
java.math.BigInteger    <java.math.BigInteger: void <init>(int,byte[])>
java.math.BigInteger    <java.math.BigInteger: void <init>(int,int[])>
java.math.BigInteger    <java.math.BigInteger: void <init>(int[],int)>
java.math.BigInteger    <java.math.BigInteger: void <init>(byte[],int)>
```

## 案例二

待补充

================================================
FILE: docs/readme.md
================================================
# ByteCodeDL

基本需要两部分知识,一部分是程序分析另外一部分是datalog编程。对于程序分析部分的知识,强烈推荐去学习南大的程序分析课程,[视频链接](https://space.bilibili.com/2919428/channel/seriesdetail?sid=1006553) [课程主页](https://pascal-group.bitbucket.io/teaching.html),datalog编程可以通过[souffle](https://souffle-lang.github.io/)的文档学习。

当然后面的教程和使用案例我也会穿插讲解这两部分知识。
建议阅读顺序

1. [souffle.md](souffle.md)
2. [relation.md](relation.md)
3. [utils.md](utils.md)
4. [query.md](query.md)
5. [callgraph.md](callgraph.md)
6. [cha-optimization.md](cha-optimization.md)
7. [cha-in-ctf.md](cha-in-ctf.md)
8. [context-insensitive-points-to.md](context-insensitive-points-to.md)
9. [ptaint](ptaint.md)


================================================
FILE: docs/relation.md
================================================
# relation

## Subtypes

```
// 指令 可以定位出动作(比如call,load,sotre,assign)发生时的代码位置
.type Insn <: symbol
// 变量 
.type Var <: symbol
// 堆 也可以理解为内存中的对象
.type Heap <: symbol
// 字段
.type Field <: symbol
// 方法
.type Method <: symbol
// 类
.type Class <: symbol
```

## Class

- 类名
  - 对应的就是Class这个类型,是一个字符串
- 类的修饰符号
  - `ClassModifier(mod:symbol, class:Class)`
  - 表示`class`存在`mod`这种修饰符
  - `mod`可能是public,private,static等修饰符
  - `class`是形如java.lang.Object这样的类名
- 是否是非接口类
  - `ClassType(class:Class)`
  - 表示`class`是非接口类
- 是否是Interface
  - `InterfaceType(interface:Class)`
  - 表示`interface`是接口类
- 是出现在待分析的应用中还是在第三方库中
  - `ApplicationClass(class:Class)`
    - 表示`class`是应用类
- 直接继承了什么类
  - `DirectSuperclass(child:Class, parent:Class)`
    - 表示`child`直接extend了`parnet`
- 直接实现了什么接口
  - `DirectSuperinterface(child:Class, parent:Class)`
    - 表示`child`直接implement了`parent`

对于方法中有哪些方法和字段,会通过Method和Field相关信息进行反查。

## Method

- 方法的基本信息
  - `MethodInfo(method:Method, simplename:symbol, param:symbol, class:Class, return:Class, jvmDescriptor:symbol, arity:number)`
    - `method` 完整的方法名,如:
    - `simplename` 简单的方法名
    - `param` 参数类型
    - `class` 在哪个class声明的
    - `return` 返回类型
    - `jvmDescriptor` jvm描述符
    - `arity` 参数个数
- 方法的修饰符
  - `MethodModifier(mod:symbol, method:Method)`
- 方法对应的this变量
  - `ThisVar(method:Method, this:Var)`
- 方法的形式参数
  - `FormalParam(n:number, method:Method, param:Var)`
  - method的第n个形式参数为param变量
- 方法的返回值
  - `Return(insn:Insn, index:number, var:Var, method:Method)`
  - method的函数内返回的变量为var
  
Java中方法调用,可以分为三类

- SpecialMethodInvocation
  - 包括private,super,以及构造函数
  - `SpecialMethodInvocation(insn:Insn, index:number, callee:Method, receiver:Var, caller:Method)`
  - 在caller中,通过指令insn,调用了receiver.callee()
- StaticMethodInvocation
  - 静态方法调用
  - `StaticMethodInvocation(insn:Insn, index:number, callee:Method, caller:Method)`
  - 在caller中,通过指令insn调用了静态方法callee
- VirtualMethodInvocation
  - 虚拟方法调用
  - `VirtualMethodInvocation(insn:Insn, index:number, callee:Method, receiver:Var, caller:Method)`
  - 在caller中,通过指令insn,调用了receiver.callee()

SpecialMethodInvocation和StaticMethodInvocation在编译时就能确定被调方法,但是VirtualMethodInvocation由于多态的原因,只有在运行时根据receiver变量的实际类型才能确定具体的被调方法。

以及调用时涉及到的
- 实际参数
  - `ActualParam(n:number, insn:Insn, var:Var)`
  - 在调用insn发生时,实际传入的第n个参数为var
- 函数调用后的返回值赋值
  - `AssignReturnValue(insn:Insn, var:Var)`
  - 在调用insn返回时,将返回结果赋值给var变量

## Field
- 字段的基本信息
  - `FieldInfo(field:Field, declaringType:Class, simplename:symbol, type:Class)`
    - `field` 完整的名称
    - `declaringType` 所属的类
    - `simplename` 字段名
    - `type` 类型
- 字段的修饰符
  - `FieldModifier(modifier:symbol, field:Field)`
- 读取字段,也就是load
  - `LoadInstanceField(insn:Insn, index:number, var:Var, base:Var, field:Field, inMethod:Method)`
  - 表示在inMethod方法中,var = base.field
- 写入字段,也就是store
  - `StoreInstanceField(insn:Insn, index:number, var:Var, base:Var, field:Field, inMethod:Method)`
  - 表示在inMethod中,base.field = var

## Array

- 从数组中读
  - `LoadArrayIndex(insn:Insn, index:number, to:Var, array:Var, inMethod:Method)`
  - 表示在inMethod中,to = array[]
- 往数组中写
  - `StoreArrayIndex(insn:Insn, index:number, from:Var, array:Var, inMethod:Method)`
  - 表示在inMethod中,array[] = from
- 数组中的元素类型
  - `ComponentType(arrayType:Class, componentType:Class)`
  - 表示arrayType中元素的类型为componentType

## Others

- 变量的声明类型
  - `VarType(var:Var, class:Class)`
  - 表示变量var的声明类型为class
- 局部变量赋值
  - `AssignLocal(insn:Insn, index:number, from:Var, to:Var, inMethod: Method)`
  - 表示在inMethod中,to = from
- 类型转换
  - `AssignCast(insn:Insn, index:number, from:Var, to:Var, type:Class, inMethod:Method)`
  - 表示在inMethod中,to = (type) from
- 创建对象赋值
  - `AssignHeapAllocation(insn:Insn, index:number, heap:Heap, var:Var, inMethod:Method, linenumber:number)`
  - 表示在inMethod中,var = new heap()
- 堆中对象对应的类型
  - `NormalHeap(value:Heap, class:Class)`
  - 表示heap的类型为class

================================================
FILE: docs/souffle.md
================================================
# Souffle

## example

Souffle是款Datalog推理引擎,也是著名声明式分析框架Doop默认的引擎。

Datalog = data + logic ,也就是现有的事实加上推理逻辑可以推理出新的事实。
data可以理解为数据库,其中由一个个relation组成,relation可以理解为数据库中的表,表中一列数据表明满足他们满足某种关系。

```
.decl edge(x:number, y:number)
```

上面通过.decl声明了edge这个关系,可以理解为x有条指向y的边,x和y可以理解为变量名称,number理解为变量类型。
添加已有事实有两种方式,一种是通过

```
.decl edge(x:number, y:number)
edge(1, 2).
```

表明节点1到节点2有条边。也可以通过

```
.decl edge(x:number, y:number)
.input edge
```

通过从edge.facts中获取事实,如果edge.facts的内容如下

```
1	2
```

上面表达的效果就是一致的。
再接着看一个完整的例子,example.dl文件内容如下

```
// 声明 edge 表示 节点 x 到 y 有条边
.decl edge(x:number, y:number)
// 表示从edge.facts 读事实
.input edge

// 声明 path 表示 节点 x 到 y 有路径可达
.decl path(x:number, y:number)
// 表示将path的结果输出到path.csv
.output path

// 推理规则,如果x到y有边,那么x到y肯定有长度为1的路径,也就是如果x,y满足关系edge,也一定满足关系path
path(x, y) :- edge(x, y).
// 用到了递归推理,如果x到z有条路径,并且z到y有条边,那么就可以推理出x到y也有路径
path(x, y) :- path(x, z), edge(z, y).
```

如果edge.facts的内容如下

```
1	2
2	3
```
通过执行
```
souffle -F . -D . example.dl
```
- `-F` 指定了facts所在的目录
- `-D` 指定了输出目录
- `example.dl` 指定datalog文件名

最终得到的path.csv内容如下

```
1	2
1	3
2	3
```

表示节点1到节点2有路径,节点1到节点3有路径,节点2到节点3有路径。
上述内容主要来自 https://souffle-lang.github.io/simple

## Type

Souffle中类型除了number类型(和int类似)以外,还有symbol类型(和string类似),这两种都属于Primitive Type,还可以有

- Equivalence Types

    `.type <new-type> = <other-type>`

    ```
    .type myNumber = number
    ```
  
- SubTypes
  
    `type <new-type> <: <other-type>`
    ```
    .type myEvenNumber <: number
    ```
具体可参考 https://souffle-lang.github.io/types

## reference
- https://pascal-group.bitbucket.io/lectures/Datalog.pdf
- https://souffle-lang.github.io/simple
- https://souffle-lang.github.io/types

================================================
FILE: docs/utils.md
================================================
# utils

## Class Hierarchy

需要构建一个类型层次图,用于寻找某个类的子类、父类,或者用于判断两个类之间是否有继承关系。

从bytecode中能够解析出直接继承关系,其中extend对应的是DirectSuperclass , implement对应的是DirectSuperinterface 。

创建个新的relation SubClass(subclass:Class, class:Class) 表示subclass是class的子类。
那么推理规则可以有:

1. 如果满足class x 和 y DirectSuperclass(x, y) 或者DirectSuperinterface(x, y) 那么 x , y 也一定满足 SubClass(x, y)
2. 还需要利用递推,判断非直接的层次关系。如果x 和 z 满足SubClass(x, z) 且 z 和 y 满足 DirectSuperclass(z, y) 或者DirectSuperinterface(z, y) 那么能够推导出 SubClass(x, y)

将上面的规则翻译成datalog如下:

```
SubClass(subclass, class) :- DirectSuperclass(subclass, class).
SubClass(subclass, class) :- DirectSuperinterface(subclass, class).
SubClass(subclass, class) :- 
    (
        DirectSuperclass(subclass, tmp);
        DirectSuperinterface(subclass, tmp)
    ),
    SubClass(tmp, class).
```
其中`;` 表示或,`,` 表示逻辑且

## Method Dispatch

针对VirtualMethodInvocation(insn:Insn, index:number, callee:Method, receiver:Var, caller:Method)调用,其中的callee并不是真实调用,需要根据receiver运行时类型rclass和callee的函数签名sig解析出实际调用的方法。

解析过程分为两种情况:

1. 如果rclass中有实现方法method.sig == sig 且method没有被abstract修饰,则直接返回method
2. 如果rclass没有对应的方法实现,则需要去父类中寻找相同函数签名的方法。

创建新的relation Dispatch(simplename:symbol, descriptor:symbol, class:Class, method:Method) simplename和descriptor 能拼凑成函数签名,class 表示要解析的类型,根据这三个元素能够找到对应的method。

可将上面的规则翻译成如下的datalog

```
Dispatch(simplename, descriptor, class, method) :-
    MethodInfo(method, simplename, _, class, _, descriptor, _),
    !MethodModifier("abstract", method).

Dispatch(simplename, descriptor, class, method) :-
    !MethodInfo(_, simplename, _, class, _, descriptor, _),
    DirectSuperclass(class, superclass),
    Dispatch(simplename, descriptor, superclass, method),
    !MethodModifier("abstract", method).
```
`_` 表示可以为任意值

这部分对应的代码见 `logic/utils.dl`

================================================
FILE: example/cha-example-1.dl
================================================
#define MAXSTEP 8

#include "../logic/cha.dl"


// init entrypoint 
EntryPoint(simplename, descriptor, class) :-
    MethodInfo(_, simplename, _, class, _, descriptor, _),
    simplename = "main",
    descriptor = "([Ljava/lang/String;)V".

================================================
FILE: example/cha-log4shell.dl
================================================
#define MAXSTEP 33
#define CHAO 1

#include "../logic/cha.dl"

BanCaller(method) :-
    MethodInfo(method, _, _, class, _, _, _),
    !contains("org.apache.logging.log4j", class).


SinkDesc("lookup", "javax.naming.Context").

// init entrypoint 
EntryPoint(simplename, descriptor, class) :-
    MethodInfo(_, simplename, _, class, _, descriptor, _),
    simplename = "error",
    class = "org.apache.logging.log4j.spi.AbstractLogger",
    descriptor = "(Ljava/lang/String;)V".

================================================
FILE: example/cs-ptaint-example-1.dl
================================================
#define MAXSTEP 8
//#include "../logic/one-callsite-sensitive-pt.dl"
#include "../logic/cs-ptaint.dl"
#include "../logic/one-object-sensitive-pt.dl"

//.comp MyCallsitePtaint : CSPTaint<HContext, Context>, OneCallsiteSensitivePT{
//}
//.init csptaint = MyCallsitePtaint
.comp MyObjectPtaint : CSPTaint<HContext, Context>, OneObjectSensitivePT{
}


.init csptaint = MyObjectPtaint


csptaint.Reachable("<com.bytecodedl.benchmark.demo.TaintDemo3: void main(java.lang.String[])>", "initCtx", 0).

csptaint.SourceMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: java.lang.String Source()>").
csptaint.SinkMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: void Sink(java.lang.String)>", 0).

csptaint.BaseToRetTransfer("<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>").
csptaint.BaseToRetTransfer("<java.lang.StringBuilder: java.lang.String toString()>").

csptaint.ArgToRetTransfer("<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>", 0).

csptaint.SanitizeMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: java.lang.String Sanitize(java.lang.String)>").


.decl TaintVar(var:Var, vCtx:Context)

TaintVar(var, vCtx) :-
    csptaint.VarPointsTo(heap, _, var, vCtx),
    csptaint.TaintHeap(_, heap).

.output TaintVar

.output csptaint.TaintHeap
.output csptaint.TransferTaint
.output csptaint.VarPointsTo

================================================
FILE: example/ctf-buggyLoader.dl
================================================
#define MAXSTEP 5
#define CHAO 2

#include "../logic/cha.dl"


.decl NonParamPublicMethod(method:Method, class:Class)
.output NonParamPublicMethod


SinkDesc("exec", "java.lang.Runtime").
SinkDesc("<init>", "java.lang.ProcessBuilder").
SinkDesc("start", "java.lang.ProcessImpl").
SinkDesc("loadClass", "java.lang.ClassLoader").
SinkDesc("defineClass", "java.lang.ClassLoader").
SinkDesc("readObject", "java.io.ObjectInputStream").
SinkDesc("readExternal", "java.io.ObjectInputStream").


EntryMethod(method),
Reachable(method, 0),
NonParamPublicMethod(method, class) :- 
    MethodInfo(method, simplename, _, class, _, _, arity),
    MethodModifier("public", method),
    simplename != "<init>",
    arity = 0,
    SubClass(class, "java.io.Serializable").

.output SinkMethod

================================================
FILE: example/ctf-ezchain.dl
================================================
#define MAXSTEP 5
#define CHAO 2

#include "../logic/cha.dl"


.decl NonParamPublicMethod(method:Method, class:Class)
.output NonParamPublicMethod

SinkDesc("exec", "java.lang.Runtime").
SinkDesc("<init>", "java.lang.ProcessBuilder").
SinkDesc("start", "java.lang.ProcessImpl").
SinkDesc("loadClass", "java.lang.ClassLoader").
SinkDesc("defineClass", "java.lang.ClassLoader").
SinkDesc("readObject", "java.io.ObjectInputStream").
SinkDesc("readExternal", "java.io.ObjectInputStream").


EntryMethod(method),
Reachable(method, 0),
NonParamPublicMethod(method, class) :- 
    MethodInfo(method, simplename, _, class, _, _, arity),
    MethodModifier("public", method),
    contains("get", simplename),
    arity = 0.

.output SinkMethod

================================================
FILE: example/one-callsite-sensitive-pt-example-1.dl
================================================
#define MAXSTEP 8
#include "../logic/one-callsite-sensitive-pt.dl"

.init callsitecsDemo1 = OneCallsiteSensitivePT
callsitecsDemo1.Reachable("<com.bytecodedl.benchmark.demo.ContextSensitiveDemo1: void main(java.lang.String[])>", "initCtx", 0).
.output callsitecsDemo1.VarPointsTo

.init callsitecsDemo2 = OneCallsiteSensitivePT
callsitecsDemo2.Reachable("<com.bytecodedl.benchmark.demo.ContextSensitiveDemo2: void main(java.lang.String[])>", "initCtx", 0).
.output callsitecsDemo2.VarPointsTo

================================================
FILE: example/one-object-sensitive-pt-example-1.dl
================================================
#define MAXSTEP 8
#include "../logic/one-object-sensitive-pt.dl"

.init objectDemo1 = OneObjectSensitivePT
objectDemo1.Reachable("<com.bytecodedl.benchmark.demo.ContextSensitiveDemo1: void main(java.lang.String[])>", "initCtx", 0).
.output objectDemo1.VarPointsTo

.init objectDemo2 = OneObjectSensitivePT
objectDemo2.Reachable("<com.bytecodedl.benchmark.demo.ContextSensitiveDemo2: void main(java.lang.String[])>", "initCtx", 0).
.output objectDemo2.VarPointsTo

================================================
FILE: example/one-type-sensitive-pt-example-1.dl
================================================
#define MAXSTEP 8
#include "../logic/one-type-sensitive-pt.dl"

.init typeDemo1 = OneTypeSensitivePT
typeDemo1.Reachable("<com.bytecodedl.benchmark.demo.ContextSensitiveDemo1: void main(java.lang.String[])>", "initCtx", 0).
.output typeDemo1.VarPointsTo

.init typeDemo2 = OneTypeSensitivePT
typeDemo2.Reachable("<com.bytecodedl.benchmark.demo.ContextSensitiveDemo2: void main(java.lang.String[])>", "initCtx", 0).
.output typeDemo2.VarPointsTo

================================================
FILE: example/pt-noctx-example-1.dl
================================================
#include "../logic/pt-noctx.dl"

.init cipt = ContextInsensitivePt

cipt.Reachable(method) :-
    MethodInfo(method, simplename, _, _, _, descriptor, _),
    simplename = "main",
    descriptor = "([Ljava/lang/String;)V".

.output cipt.VarPointsTo


================================================
FILE: example/ptaint-example-1.dl
================================================
#include "../logic/ptaint.dl"

.init ptaint = PTaint

ptaint.Reachable("<com.bytecodedl.benchmark.demo.TaintDemo3: void main(java.lang.String[])>").

ptaint.SourceMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: java.lang.String Source()>").
ptaint.SinkMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: void Sink(java.lang.String)>", 0).

ptaint.BaseToRetTransfer("<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>").
ptaint.BaseToRetTransfer("<java.lang.StringBuilder: java.lang.String toString()>").

ptaint.ArgToRetTransfer("<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>", 0).

ptaint.SanitizeMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: java.lang.String Sanitize(java.lang.String)>").


.decl TaintVar(var:Var)

TaintVar(var) :-
    ptaint.VarPointsTo(heap, var),
    ptaint.TaintHeap(_, heap).

.output TaintVar

.output ptaint.TaintHeap
.output ptaint.TransferTaint
.output ptaint.VarPointsTo

================================================
FILE: example/ptaint-example-2.dl
================================================
#include "../logic/ptaint.dl"

.init ptaint = PTaint

.decl EntryMethod(method:Method)

EntryMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: void test1(java.lang.String)>").


ptaint.Reachable(method) :-
    EntryMethod(method).

NormalHeap(heap, class),
ptaint.VarPointsTo(heap, this) :-
    ThisVar(method, this),
    EntryMethod(method),
    VarType(this, class),
    heap = cat("Mock::", class).

NormalHeap(heap, class),
ptaint.TaintHeap(insn, taintHeap),
ptaint.VarPointsTo(heap, param),
ptaint.VarPointsTo(taintHeap, param) :-
    EntryMethod(method),
    FormalParam(_, method, param),
    VarType(param, class),
    heap = cat("Mock::", class),
    taintHeap = cat("NewTainted::", class),
    insn = "Init::Param".


ptaint.SourceMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: java.lang.String Source()>").
ptaint.SinkMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: void Sink(java.lang.String)>", 0).

ptaint.BaseToRetTransfer("<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>").
ptaint.BaseToRetTransfer("<java.lang.StringBuilder: java.lang.String toString()>").

ptaint.ArgToRetTransfer("<java.lang.StringBuilder: java.lang.StringBuilder append(java.lang.String)>", 0).

ptaint.SanitizeMethod("<com.bytecodedl.benchmark.demo.TaintDemo3: java.lang.String Sanitize(java.lang.String)>").


.decl TaintVar(var:Var)

TaintVar(var) :-
    ptaint.VarPointsTo(heap, var),
    ptaint.TaintHeap(_, heap).

.output TaintVar

.output ptaint.TaintHeap
.output ptaint.TransferTaint
.output ptaint.VarPointsTo

================================================
FILE: example/query-example-1.dl
================================================
#include "../logic/inputDeclaration.dl"

.decl QueryResult(class:Class, method:Method)
.output QueryResult

QueryResult(class, method) :- 
    MethodInfo(method, simplename, param, class, _, _, arity),
    //simplename = "<init>",
    contains("[]", param),
    arity = 1.


================================================
FILE: example/rta-example-1.dl
================================================
#define MAXSTEP 8

#include "../logic/RTA.dl"

.init rta = RTA

rta.EntryPoint("main", "([Ljava/lang/String;)V", "com.bytecodedl.benchmark.demo.VirtualCallDemo1").

================================================
FILE: example/simple-cha-log4shell.dl
================================================
#define MAXSTEP 33

#include "../logic/simple-cha.dl"


SinkDesc("lookup", "javax.naming.Context").

// init entrypoint 
EntryPoint(simplename, descriptor, class) :-
    MethodInfo(_, simplename, _, class, _, descriptor, _),
    simplename = "error",
    class = "org.apache.logging.log4j.spi.AbstractLogger",
    descriptor = "(Ljava/lang/String;)V".


.output EntryPoint
.output EntryMethod
.output SinkMethod
.output SimpleCallGraph

================================================
FILE: importOuput2Neo4j.sh
================================================
#!/bin/bash

docker-compose exec neo bash /bytecodedl/$1 $2
docker-compose restart neo

================================================
FILE: logic/abstract-context-sensitive-pt.dl
================================================
#pragma once
#include "utils.dl"

.comp AbstractContextSensitivePT<HContext, Context>{
    .decl VarPointsTo(heap:Heap, hctx:HContext, var:Var, vCtx:Context)
    .decl InstanceFieldPointsTo(heap:Heap, hctx:Context, baseHeap:Heap, bhCtx:Context, field:Field)
    .decl StaticFieldPointsTo(heap:Heap, hctx:Context, field:Field)
    .decl ArrayIndexPointsTo(heap:Heap, hctx:Context, baseHeap:Heap, bhCtx:Context)
    .decl Reachable(method:Method, ctx:Context, n:number)
    .decl CallGraph(insn:Insn, caller:Method, callerCtx:Context, callee:Method, calleeCtx:Context)

    .decl SelectInvocationContext(callerCtx:Context, invocation:Insn, baseHeap:Heap, hctx:HContext, calleeCtx:Context) overridable
    .decl SelectStaticInvocationContext(callerCtx:Context, invocation:Insn, calleeCtx:Context) overridable

    SelectStaticInvocationContext(callerCtx, insn, calleeCtx) :-
        Reachable(caller, callerCtx, _),
        StaticMethodInvocation(insn, _, _, caller),
        calleeCtx = callerCtx.

    // new
    VarPointsTo(heap, ctx, var, ctx) :-
        Reachable(method, ctx, _),
        AssignHeapAllocation(_, _, heap, var, method, _).

    // assign
    VarPointsTo(heap, hctx, to, ctx) :-
        Reachable(method, ctx, _),
        VarPointsTo(heap, hctx, from, ctx),
        AssignLocal(_, _, from, to, method).

    // cast
    VarPointsTo(heap, hctx, to, ctx) :-
        Reachable(method, ctx, _),
        AssignCast(_, _, from, to, _, method),
        VarPointsTo(heap, hctx, from, ctx).

    // load field
    VarPointsTo(heap, hctx, to, ctx) :-
        Reachable(method, ctx, _),
        LoadInstanceField(_, _, to, base, field, method),
        VarPointsTo(baseHeap, bhCtx, base, ctx),
        InstanceFieldPointsTo(heap, hctx, baseHeap, bhCtx, field).

    // store field
    InstanceFieldPointsTo(heap, hctx, baseHeap, bhCtx, field) :-
        Reachable(method, ctx, _),
        StoreInstanceField(_, _, from, base, field, method),
        VarPointsTo(heap, hctx, from, ctx),
        VarPointsTo(baseHeap, bhCtx, base, ctx).

    // load staic field
    VarPointsTo(heap, hctx, to, ctx) :-
        Reachable(method, ctx, _),
        LoadStaticField(_, _, to, field, method),
        StaticFieldPointsTo(heap, hctx, field).

    // store static field
    StaticFieldPointsTo(heap, hctx, field) :-
        Reachable(method, ctx, _),
        StoreStaticField(_, _, from, field, method),
        VarPointsTo(heap, hctx, from, ctx).

    // load from array
    VarPointsTo(heap, hctx, to, ctx) :-
        Reachable(method, ctx, _),
        LoadArrayIndex(_, _, to, base, method),
        VarPointsTo(baseHeap, bhCtx, base, ctx),
        ArrayIndexPointsTo(heap, hctx, baseHeap, bhCtx).

    // store into array
    ArrayIndexPointsTo(heap, hctx, baseHeap, bhCtx) :-
        Reachable(method, ctx, _),
        StoreArrayIndex(_, _, from, base, method),
        VarPointsTo(heap, hctx, from, ctx),
        VarPointsTo(baseHeap, bhCtx, base, ctx).

    Reachable(callee, calleeCtx, n+1),
    CallGraph(insn, caller, callerCtx, callee, calleeCtx) :-
        Reachable(caller, callerCtx, n),
        n < MAXSTEP,
        SpecialMethodInvocation(insn, _, callee, base, caller),
        VarPointsTo(baseHeap, hctx, base, calleeCtx),
        SelectInvocationContext(callerCtx, insn, baseHeap, hctx, callerCtx).

    Reachable(callee, calleeCtx, n+1),
    CallGraph(insn, caller, callerCtx, callee, calleeCtx) :-
        Reachable(caller, callerCtx, n),
        n < MAXSTEP,
        StaticMethodInvocation(insn, _, callee, caller),
        SelectStaticInvocationContext(callerCtx, insn, calleeCtx).

    Reachable(callee, calleeCtx, n+1),
    CallGraph(insn, caller, callerCtx, callee, calleeCtx) :-
        Reachable(caller, callerCtx, n),
        n < MAXSTEP,
        VirtualMethodInvocation(insn, _, method, base, caller),
        VarPointsTo(baseHeap, hctx, base, callerCtx),
        NormalHeap(baseHeap, class),
        MethodInfo(method, simplename, _, _, _, descriptor, _),
        Dispatch(simplename, descriptor, class, callee),
        SelectInvocationContext(callerCtx, insn, baseHeap, hctx, calleeCtx).

    // param
    VarPointsTo(heap, hctx, param, calleeCtx) :-
        CallGraph(insn, _, callerCtx, callee, calleeCtx),
        ActualParam(n, insn, arg),
        FormalParam(n, callee, param),
        VarPointsTo(heap, hctx, arg, callerCtx),
        NormalHeap(heap, _).

    // return
    VarPointsTo(heap, hctx, return, callerCtx) :-
        CallGraph(insn, _, callerCtx, callee, calleeCtx),
        Return(_, _, var, callee),
        AssignReturnValue(insn, return),
        VarPointsTo(heap, hctx, var, calleeCtx).

    // this
    VarPointsTo(heap, hctx, this, calleeCtx) :-
        CallGraph(insn, _, callerCtx, callee, calleeCtx),
        (
            VirtualMethodInvocation(insn, _, _, base, _);
            SpecialMethodInvocation(insn, _, _, base, _)
        ),
        ThisVar(callee, this),
        VarPointsTo(heap, hctx, base, callerCtx).
}

================================================
FILE: logic/cha.dl
================================================
#pragma once
#include "utils.dl"

.decl EntryPoint(simplename:symbol, descriptor:symbol, class:Class)
.decl Reachable(method:Method, step:number)
.decl SinkDesc(simplename:symbol, class:Class)
.decl SinkMethod(method:Method)
.decl EntryMethod(method:Method)
.decl BanCaller(method:Method)


.decl CallGraph(insn:Insn, caller:Method, callee:Method)

SinkMethod(method) :-
    SinkDesc(simplename, class),
    SubEqClass(subeqclass, class),
    !MethodModifier("abstract", method),
    MethodInfo(method, simplename, _, subeqclass, _, _, _).

EntryMethod(method),
Reachable(method, 0) :- 
    EntryPoint(simplename, descriptor, class),
    Dispatch(simplename, descriptor, class, method).

Reachable(callee, n+1),
CallGraph(insn, caller, callee) :-
    Reachable(caller, n),
    !BanCaller(caller),
    n < MAXSTEP,
    SpecialMethodInvocation(insn, _, callee, _, caller).

Reachable(callee, n+1),
CallGraph(insn, caller, callee) :-
    Reachable(caller, n),
    !BanCaller(caller),
    n < MAXSTEP,
    StaticMethodInvocation(insn, _, callee, caller).

Reachable(callee, n+1),
CallGraph(insn, caller, callee) :-
    Reachable(caller, n),
    !BanCaller(caller),
    n < MAXSTEP,
    VirtualMethodInvocation(insn, _, method, receiver, caller),
    MethodInfo(method, simplename, _, _, _, descriptor, _),
    VarType(receiver, class),
    SubEqClass(subeqclass, class),
    !ClassModifier("abstract", subeqclass),
    Dispatch(simplename, descriptor, subeqclass, callee).

Reachable(callee, n+1),
CallGraph(insn, caller, callee) :- 
    Reachable(caller, n),
    !BanCaller(caller),
    n < MAXSTEP,
    StaticMethodInvocation(insn, _, method, caller),
    MethodInfo(method, "doPrivileged", _, "java.security.AccessController", _, _, _),
    ActualParam(0, insn, param),
    VarType(param, class),
    MethodInfo(callee, "run", _, class, _, _, 0).

// CHAO is CHA OPTIMIZATION LEVEL
#if CHAO > 0

.decl SinkReachable(method:Method, sink:Method, step:number)

SinkReachable(sink, sink, 0) :-
    SinkMethod(sink).

SinkReachable(caller, sink, n+1) :-
    n < MAXSTEP,
    SinkReachable(callee, sink, n),
    CallGraph(_, caller, callee).

#endif

#if CHAO > 1

.decl ShortestPathToSink(caller:Method, sink:Method, step:number)

ShortestPathToSink(entry, sink, n) :-
    n = min step : {SinkReachable(entry, sink, step)},
    SinkMethod(sink),
    EntryMethod(entry).

ShortestPathToSink(callee, sink, n-1) :-
    n < MAXSTEP + 1,
    ShortestPathToSink(caller, sink, n),
    SinkReachable(callee, sink, n-1),
    CallGraph(_, caller, callee).

#endif

.decl RefinedReachable(method:Method)

#ifdef CHAO
    #if CHAO == 1
        RefinedReachable(method) :-
            SinkReachable(method, _, _).
    #endif
    #if CHAO == 2
        RefinedReachable(method) :-
            ShortestPathToSink(method, _, _).
    #endif
#else
    RefinedReachable(method) :-
        Reachable(method, _).
#endif

.decl CallNode(node:Method, label:symbol)
.output CallNode

CallNode(node, "method") :-
    !EntryMethod(node),
    !SinkMethod(node),
    RefinedReachable(node).

CallNode(node, "sink") :-
    RefinedReachable(node),
    SinkMethod(node).

CallNode(node, "entry") :-
    RefinedReachable(node),
    EntryMethod(node).

.decl CallEdge(caller:Method, insn:Insn, callee:Method)
.output CallEdge

CallEdge(caller, insn, callee) :-
    RefinedReachable(caller),
    RefinedReachable(callee),
    CallGraph(insn, caller, callee).


================================================
FILE: logic/cs-ptaint.dl
================================================
#pragma once
#include "utils.dl"
#include "abstract-context-sensitive-pt.dl"

.comp CSPTaint<HContext, Context>{
    //.init cspt = AbstractContextSensitivePT
    //.init cspt = CSPT

    .decl TaintHeap(insn:Insn, heap:Heap)
    .decl SourceMethod(method:Method)
    .decl SinkMethod(method:Method, n:number)

    .decl SanitizeMethod(method:Method)

    .decl BaseToRetTransfer(method:Method)
    .decl ArgToRetTransfer(method:Method, n:number)
    .decl IsTaintedFrom(insn:Insn, from:Var, fromCtx:Context, to:Var, toCtx:Context)
    .decl TransferTaint(heap:Heap, newHeap:Heap)


    // taint arg to param
    VarPointsTo(heap, hctx, param, calleeCtx) :-
        CallGraph(insn, _, callerCtx, callee, calleeCtx),
        ActualParam(n, insn, arg),
        FormalParam(n, callee, param),
        VarPointsTo(heap, hctx, arg, callerCtx),
        TaintHeap(_, heap), // sensitive?
        !SanitizeMethod(callee).


    TaintHeap(insn, heap),
    VarPointsTo(heap, hctx, to, callerCtx):-
        SourceMethod(callee),
        CallGraph(insn, _, callerCtx, callee, _),
        AssignReturnValue(insn, to),
        heap = cat("NewTainted::", insn),
        hctx = "Mock::".

    IsTaintedFrom(insn, base, callerCtx, ret, callerCtx) :-
        CallGraph(insn, _, callerCtx, callee, _),
        BaseToRetTransfer(callee),
        (
            VirtualMethodInvocation(insn, _, _, base, _);
            SpecialMethodInvocation(insn, _, _, base, _)
        ),
        AssignReturnValue(insn, ret).

    IsTaintedFrom(insn, arg, callerCtx, ret, callerCtx) :-
        CallGraph(insn, _, callerCtx, callee, _),
        ArgToRetTransfer(callee, n),
        ActualParam(n, insn, arg),
        AssignReturnValue(insn, ret).

    TaintHeap(insn, newHeap),
    TransferTaint(heap, newHeap),
    VarPointsTo(heap, hctx, var, vCtx) :-
        IsTaintedFrom(insn, from, fromCtx, to, toCtx),
        VarPointsTo(heap, hctx, from, fromCtx),
        TaintHeap(_, heap),
        newHeap = cat("TransferTaint::", insn),
        VarPointsTo(oldHeap, oldHCtx, to, toCtx),
        VarPointsTo(oldHeap, oldHCtx, var, vCtx),
        AssignHeapAllocation(_, _, oldHeap, var, _, _).
}

================================================
FILE: logic/inputDeclaration.dl
================================================
#pragma once

.type Insn <: symbol
.type Var <: symbol
.type Heap <: symbol
.type Field <: symbol
.type Method <: symbol
.type Class <: symbol

// load data from facts
// class

.decl ClassModifier(mod:symbol, class:Class)
.input ClassModifier

.decl ClassType(class:Class)
.input ClassType

.decl InterfaceType(interface:Class)
.input InterfaceType

.decl ApplicationClass(class:Class)
.input ApplicationClass

.decl DirectSuperclass(child:Class, parent:Class)
.input DirectSuperclass

.decl DirectSuperinterface(child:Class, parent:Class)
.input DirectSuperinterface

// method 

.decl MethodInfo(method:Method, simplename:symbol, param:symbol, class:Class, return:Class, jvmDescriptor:symbol, arity:number)
.input MethodInfo(IO=file, filename="Method.facts", delimiter="\t")

.decl MethodModifier(mod:symbol, method:Method)
.input MethodModifier(IO=file, filename="Method-Modifier.facts", delimiter="\t")

.decl ThisVar(method:Method, this:Var)
.input ThisVar

.decl FormalParam(n:number, method:Method, param:Var)
.input FormalParam

.decl Return(insn:Insn, index:number, var:Var, method:Method)
.input Return

.decl VirtualMethodInvocation(insn:Insn, index:number, callee:Method, receiver:Var, caller:Method)
.input VirtualMethodInvocation

.decl StaticMethodInvocation(insn:Insn, index:number, callee:Method, caller:Method)
.input StaticMethodInvocation

.decl SpecialMethodInvocation(insn:Insn, index:number, callee:Method, receiver:Var, caller:Method)
.input SpecialMethodInvocation

.decl ActualParam(n:number, insn:Insn, var:Var)
.input ActualParam

.decl AssignReturnValue(insn:Insn, var:Var)
.input AssignReturnValue

// Field

.decl FieldInfo(field:Field, declaringType:Class, simplename:symbol, type:Class)
.input FieldInfo(IO=file, filename="Field.facts", delimiter="\t")

.decl FieldModifier(modifier:symbol, field:Field)
.input FieldModifier(IO=file, filename="Field-Modifier.facts", delimiter="\t")

.decl LoadInstanceField(insn:Insn, index:number, var:Var, base:Var, field:Field, inMethod:Method)
.input LoadInstanceField

.decl StoreInstanceField(insn:Insn, index:number, var:Var, base:Var, field:Field, inMethod:Method)
.input StoreInstanceField

.decl LoadStaticField(insn:Insn, index:number, var:Var, field:Field, inMethod:Method)
.input LoadStaticField

.decl StoreStaticField(insn:Insn, index:number, var:Var, field:Field, inMethod:Method)
.input StoreStaticField

// Array
.decl LoadArrayIndex(insn:Insn, index:number, to:Var, array:Var, inMethod:Method)
.input LoadArrayIndex

.decl StoreArrayIndex(insn:Insn, index:number, from:Var, array:Var, inMethod:Method)
.input StoreArrayIndex

.decl ComponentType(arrayType:Class, componentType:Class)
.input ComponentType

// others
.decl VarType(var:Var, class:Class)
.input VarType(IO=file, filename="Var-Type.facts", delimiter="\t")

.decl AssignLocal(insn:Insn, index:number, from:Var, to:Var, inMethod: Method)
.input AssignLocal

.decl AssignCast(insn:Insn, index:number, from:Var, to:Var, type:Class, inMethod:Method)
.input AssignCast(IO=file, filename="AssignCast.facts", delimiter="\t")

.decl AssignHeapAllocation(insn:Insn, index:number, heap:Heap, var:Var, inMethod:Method, linenumber:number)
.input AssignHeapAllocation

.decl NormalHeap(value:Heap, class:Class)
.input NormalHeap

================================================
FILE: logic/one-callsite-sensitive-pt.dl
================================================
#pragma once
#include "abstract-context-sensitive-pt.dl"

.type HContext = Insn
.type Context = Insn

.comp OneCallsiteSensitivePT: AbstractContextSensitivePT<HContext, Context>{
    .override SelectInvocationContext
    SelectInvocationContext(callerCtx, insn, baseHeap, hctx, calleeCtx) :-
        Reachable(caller, callerCtx, _),
        (
            SpecialMethodInvocation(insn, _, _, base, caller);
            VirtualMethodInvocation(insn, _, _, base, caller)
        ),
        VarPointsTo(baseHeap, hctx, base, callerCtx),
        calleeCtx = insn.

    SelectStaticInvocationContext(callerCtx, insn, calleeCtx) :-
        Reachable(caller, callerCtx, _),
        StaticMethodInvocation(insn, _, _, caller),
        calleeCtx = insn.
}

================================================
FILE: logic/one-object-sensitive-pt.dl
================================================
#pragma once
#include "abstract-context-sensitive-pt.dl"

.type HContext = Heap
.type Context = Heap

.comp OneObjectSensitivePT: AbstractContextSensitivePT<HContext, Context>{
    .override SelectInvocationContext
    SelectInvocationContext(callerCtx, insn, baseHeap, hctx, calleeCtx) :-
        Reachable(caller, callerCtx, _),
        (
            SpecialMethodInvocation(insn, _, _, base, caller);
            VirtualMethodInvocation(insn, _, _, base, caller)
        ),
        VarPointsTo(baseHeap, hctx, base, callerCtx),
        calleeCtx = baseHeap.
}

================================================
FILE: logic/one-type-sensitive-pt.dl
================================================
#pragma once
#include "abstract-context-sensitive-pt.dl"

.type HContext = Class
.type Context = Class

.comp OneTypeSensitivePT: AbstractContextSensitivePT<HContext, Context>{
    .override SelectInvocationContext
    SelectInvocationContext(callerCtx, insn, baseHeap, hctx, calleeCtx) :-
        Reachable(caller, callerCtx, _),
        (
            SpecialMethodInvocation(insn, _, _, base, caller);
            VirtualMethodInvocation(insn, _, _, base, caller)
        ),
        VarPointsTo(baseHeap, hctx, base, callerCtx),
        AssignHeapAllocation(_, _, baseHeap, _, inmethod, _),
        MethodInfo(inmethod, _, _, inType, _, _, _),
        calleeCtx = inType.
}

================================================
FILE: logic/pt-noctx.dl
================================================
#pragma once
#include "utils.dl"

.comp ContextInsensitivePt{
    .decl VarPointsTo(heap:Heap, var:Var)
    .decl InstanceFieldPointsTo(heap:Heap, baseHeap:Heap, field:Field)
    .decl StaticFieldPointsTo(heap:Heap, field:Field)
    .decl ArrayIndexPointsTo(heap:Heap, baseHeap:Heap)
    .decl CallGraph(insn:Insn, caller:Method, callee:Method)
    .decl Reachable(method:Method)

    // new
    VarPointsTo(heap, var) :-
        Reachable(method),
        AssignHeapAllocation(_, _, heap, var, method, _).
    
    // assign
    VarPointsTo(heap, to) :- 
        Reachable(method),
        VarPointsTo(heap, from),
        AssignLocal(_, _, from, to, method).
    
    // cast
    VarPointsTo(heap, to) :- 
        Reachable(method),
        AssignCast(_, _, from, to, _, method),
        VarPointsTo(heap, from).
    
    // load field
    VarPointsTo(heap, to) :-
        Reachable(method),
        LoadInstanceField(_, _, to, base, field, method),
        VarPointsTo(baseHeap, base),
        InstanceFieldPointsTo(heap, baseHeap, field).
    
    // store field
    InstanceFieldPointsTo(heap, baseHeap, field) :-
        Reachable(method),
        StoreInstanceField(_, _, from, base, field, method),
        VarPointsTo(heap, from),
        VarPointsTo(baseHeap, base).
    
    // load staic field
    VarPointsTo(heap, to) :-
        Reachable(method),
        LoadStaticField(_, _, to, field, method),
        StaticFieldPointsTo(heap, field).
    
    // store static field
    StaticFieldPointsTo(heap, field) :-
        Reachable(method),
        StoreStaticField(_, _, from, field, method),
        VarPointsTo(heap, from).
    
    // load from array
    VarPointsTo(heap, to) :-
        Reachable(method),
        LoadArrayIndex(_, _, to, base, method),
        VarPointsTo(baseHeap, base),
        ArrayIndexPointsTo(heap, baseHeap).

    // store into array
    ArrayIndexPointsTo(heap, baseHeap) :-
        Reachable(method),
        StoreArrayIndex(_, _, from, base, method),
        VarPointsTo(heap, from),
        VarPointsTo(baseHeap, base).
    
    Reachable(callee),
    CallGraph(insn, caller, callee) :- 
        Reachable(caller),
        SpecialMethodInvocation(insn, _, callee, _, caller).
    
    Reachable(callee),
    CallGraph(insn, caller, callee) :- 
        Reachable(caller),
        StaticMethodInvocation(insn, _, callee, caller).
    
    Reachable(callee),
    CallGraph(insn, caller, callee) :- 
        Reachable(caller),
        VirtualMethodInvocation(insn, _, method, base, caller),
        VarPointsTo(baseHeap, base),
        NormalHeap(baseHeap, class),
        MethodInfo(method, simplename, _, _, _, descriptor, _),
        Dispatch(simplename, descriptor, class, callee).
    
    // param
    VarPointsTo(heap, param) :- 
        CallGraph(insn, _, callee),
        ActualParam(n, insn, arg),
        FormalParam(n, callee, param),
        VarPointsTo(heap, arg),
        NormalHeap(heap, _).
    
    // return
    VarPointsTo(heap, return) :- 
        CallGraph(insn, _, callee),
        Return(_, _, var, callee),
        AssignReturnValue(insn, return),
        VarPointsTo(heap, var).
    
    // this
    VarPointsTo(heap, this) :- 
        CallGraph(insn, _, callee),
        (
            VirtualMethodInvocation(insn, _, _, base, _);
            SpecialMethodInvocation(insn, _, _, base, _)
        ),
        ThisVar(callee, this),
        VarPointsTo(heap, base).
}


================================================
FILE: logic/ptaint.dl
================================================
#pragma once
#include "pt-noctx.dl"

.comp PTaint : ContextInsensitivePt{

    .decl TaintHeap(insn:Insn, heap:Heap)
    .decl SourceMethod(method:Method)
    .decl SinkMethod(method:Method, n:number)

    .decl SanitizeMethod(method:Method)

    .decl BaseToRetTransfer(method:Method)
    .decl ArgToRetTransfer(method:Method, n:number)
    .decl IsTaintedFrom(insn:Insn, from:Var, to:Var)
    .decl TransferTaint(heap:Heap, newHeap:Heap)
    
    
    // taint arg to param
    VarPointsTo(heap, param) :-
        CallGraph(insn, _, callee),
        ActualParam(n, insn, arg),
        FormalParam(n, callee, param),
        VarPointsTo(heap, arg),
        TaintHeap(_, heap),
        !SanitizeMethod(callee).
    
    
    TaintHeap(insn, heap),
    VarPointsTo(heap, to) :-
        SourceMethod(callee),
        CallGraph(insn, _, callee),
        AssignReturnValue(insn, to),
        heap = cat("NewTainted::", insn).

    IsTaintedFrom(insn, base, ret) :-
        CallGraph(insn, _, callee),
        BaseToRetTransfer(callee),
        (
            VirtualMethodInvocation(insn, _, _, base, _);
            SpecialMethodInvocation(insn, _, _, base, _)
        ),
        AssignReturnValue(insn, ret).
    
    IsTaintedFrom(insn, arg, ret) :-
        CallGraph(insn, _, callee),
        ArgToRetTransfer(callee, n),
        ActualParam(n, insn, arg),
        AssignReturnValue(insn, ret).

    TaintHeap(insn, newHeap),
    TransferTaint(heap, newHeap),
    VarPointsTo(newHeap, var) :-
        IsTaintedFrom(insn, from, to),
        VarPointsTo(heap, from),
        TaintHeap(_, heap),
        newHeap = cat("TransferTaint::", insn),
        VarPointsTo(oldHeap, to),
        AssignHeapAllocation(_, _, oldHeap, var, _, _).
}

================================================
FILE: logic/rta.dl
================================================
#pragma once
#include "inputDeclaration.dl"
#include "utils.dl"

.comp RTA{
    .decl EntryPoint(simplename:symbol, descriptor:symbol, class:Class)
    .decl Reachable(method:Method, step:number)
    .decl SinkDesc(simplename:symbol, class:Class)
    .decl SinkMethod(method:Method)
    .decl EntryMethod(method:Method)
    .decl BanCaller(method:Method)

    .decl CallGraph(insn:Insn, caller:Method, callee:Method)
    .decl InstantiatedClass(insn:Insn, class:Class)

    SinkMethod(method) :-
        SinkDesc(simplename, class),
        SubEqClass(subeqclass, class),
        !ClassModifier("abstract", subeqclass),
        MethodInfo(method, simplename, _, subeqclass, _, _, _).

    EntryMethod(method),
    Reachable(method, 0) :-
        EntryPoint(simplename, descriptor, class),
        Dispatch(simplename, descriptor, class, method).

    Reachable(callee, n+1),
    CallGraph(insn, caller, callee) :-
        Reachable(caller, n),
        !BanCaller(caller),
        n < MAXSTEP,
        SpecialMethodInvocation(insn, _, callee, _, caller).

    Reachable(callee, n+1),
    CallGraph(insn, caller, callee) :-
        Reachable(caller, n),
        !BanCaller(caller),
        n < MAXSTEP,
        StaticMethodInvocation(insn, _, callee, caller).

    InstantiatedClass(insn, class) :-
        Reachable(method, _),
        AssignHeapAllocation(insn, _, heap, _, method, _),
        NormalHeap(heap, class).

    Reachable(callee, n+1),
    CallGraph(insn, caller, callee) :-
        Reachable(caller, n),
        !BanCaller(caller),
        n < MAXSTEP,
        VirtualMethodInvocation(insn, _, method, receiver, caller),
        MethodInfo(method, simplename, _, _, _, descriptor, _),
        VarType(receiver, class),
        SubEqClass(subeqclass, class),
        !ClassModifier("abstract", subeqclass),
        InstantiatedClass(_, subeqclass),
        Dispatch(simplename, descriptor, subeqclass, callee).

    Reachable(callee, n+1),
    CallGraph(insn, caller, callee) :-
        Reachable(caller, n),
        !BanCaller(caller),
        n < MAXSTEP,
        StaticMethodInvocation(insn, _, method, caller),
        MethodInfo(method, "doPrivileged", _, "java.security.AccessController", _, _, _),
        ActualParam(0, insn, param),
        VarType(param, class),
        MethodInfo(callee, "run", _, class, _, _, 0).
    
    // RTAO is RTA OPTIMIZATION LEVEL
    #if RTAO > 0

    .decl SinkReachable(method:Method, sink:Method, step:number)

    SinkReachable(sink, sink, 0) :-
        SinkMethod(sink).

    SinkReachable(caller, sink, n+1) :-
        n < MAXSTEP,
        SinkReachable(callee, sink, n),
        CallGraph(_, caller, callee).

    #endif

    #if RTAO > 1

    .decl ShortestPathToSink(caller:Method, sink:Method, step:number)

    ShortestPathToSink(entry, sink, n) :-
        n = min step : {SinkReachable(entry, sink, step)},
        SinkMethod(sink),
        EntryMethod(entry).

    ShortestPathToSink(callee, sink, n-1) :-
        n < MAXSTEP + 1,
        ShortestPathToSink(caller, sink, n),
        SinkReachable(callee, sink, n-1),
        CallGraph(_, caller, callee).

    #endif

    .decl RefinedReachable(method:Method)

    #ifdef RTAO
        #if RTAO == 1
            RefinedReachable(method) :-
                SinkReachable(method, _, _).
        #endif
        #if RTAO == 2
            RefinedReachable(method) :-
                ShortestPathToSink(method, _, _).
        #endif
    #else
        RefinedReachable(method) :-
            Reachable(method, _).
    #endif

    .decl CallNode(node:Method, label:symbol)
    .output CallNode

    CallNode(node, "method") :-
        !EntryMethod(node),
        !SinkMethod(node),
        RefinedReachable(node).

    CallNode(node, "sink") :-
        RefinedReachable(node),
        SinkMethod(node).

    CallNode(node, "entry") :-
        RefinedReachable(node),
        EntryMethod(node).

    .decl CallEdge(caller:Method, callee:Method)
    .output CallEdge

    CallEdge(caller, callee) :-
        RefinedReachable(caller),
        RefinedReachable(callee),
        CallGraph(_, caller, callee).
}

================================================
FILE: logic/simple-cha.dl
================================================
#pragma once
#include "utils.dl"

.decl EntryPoint(simplename:symbol, descriptor:symbol, class:Class)
.decl Reachable(method:Method, step:number)
.decl SinkDesc(simplename:symbol, class:Class)
.decl SinkMethod(method:Method)
.decl EntryMethod(method:Method)
.decl BanCaller(method:Method)

BanCaller(method) :-
    MethodInfo(method, simplename, _, class, _, _, _),
    contains("java.util", class).

.output BanCaller


.decl CallGraph(insn:Insn, caller:Method, callee:Method)
.decl SimpleCallGraph(insn:Insn, caller:Method, callee:Method)
.decl ChaGraph(caller:Method, implementation:Method, callee:Method)

SinkMethod(method) :-
    SinkDesc(simplename, class),
    SubEqClass(subeqclass, class),
    !MethodModifier("abstract", method),
    MethodInfo(method, simplename, _, subeqclass, _, _, _).

EntryMethod(method),
Reachable(method, 0) :- 
    EntryPoint(simplename, descriptor, class),
    Dispatch(simplename, descriptor, class, method).

Reachable(callee, n+1),
SimpleCallGraph(insn, caller, callee),
CallGraph(insn, caller, callee) :-
    Reachable(caller, n),
    !BanCaller(caller),
    n < MAXSTEP,
    SpecialMethodInvocation(insn, _, callee, _, caller).

Reachable(callee, n+1),
SimpleCallGraph(insn, caller, callee),
CallGraph(insn, caller, callee) :-
    Reachable(caller, n),
    !BanCaller(caller),
    n < MAXSTEP,
    StaticMethodInvocation(insn, _, callee, caller).

Reachable(method, n+1),
Reachable(callee, n+1),
SimpleCallGraph(insn, caller, method),
CallGraph(insn, caller, callee) :-
    Reachable(caller, n),
    !BanCaller(caller),
    n < MAXSTEP,
    VirtualMethodInvocation(insn, _, method, receiver, caller),
    MethodInfo(method, simplename, _, _, _, descriptor, _),
    VarType(receiver, class),
    SubEqClass(subeqclass, class),
    !ClassModifier("abstract", subeqclass),
    Dispatch(simplename, descriptor, subeqclass, callee).

Reachable(callee, n+1),
SimpleCallGraph(insn, caller, callee),
CallGraph(insn, caller, callee) :- 
    Reachable(caller, n),
    !BanCaller(caller),
    n < MAXSTEP,
    StaticMethodInvocation(insn, _, method, caller),
    MethodInfo(method, "doPrivileged", _, "java.security.AccessController", _, _, _),
    ActualParam(0, insn, param),
    VarType(param, class),
    MethodInfo(callee, "run", _, class, _, _, 0).

ChaGraph(caller, implementation, callee) :-
    Reachable(caller, _),
    MethodInfo(caller, simplename, _, class, _, descriptor, _),
    SubClass(subclass, class),
    Dispatch(simplename, descriptor, subclass, implementation),
    caller != implementation,
    SimpleCallGraph(_, implementation, callee).

.output ChaGraph

.decl CallNode(node:Method, label:symbol)
.output CallNode

CallNode(node, "method") :-
    !EntryMethod(node),
    !SinkMethod(node),
    Reachable(node, _).

CallNode(node, "sink") :-
    Reachable(node, _),
    SinkMethod(node).

CallNode(node, "entry") :-
    Reachable(node, _),
    EntryMethod(node).

.decl CallEdge(caller:Method, callee:Method)
.output CallEdge

CallEdge(caller, callee) :-
    SimpleCallGraph(_, caller, callee).


================================================
FILE: logic/utils.dl
================================================
#pragma once
#include "inputDeclaration.dl"

//self define relation

// Utils
.decl SubClass(subclass:Class, class:Class)
.decl SubEqClass(subeqclass:Class, class:Class)

SubEqClass("byte", "byte").
SubEqClass("byte[]", "byte[]").

SubEqClass(subclass, class) :- SubClass(subclass, class).
SubEqClass(class, class) :- ClassType(class).

SubClass(subclass, class) :- DirectSuperclass(subclass, class).
SubClass(subclass, class) :- DirectSuperinterface(subclass, class).
SubClass(subclass, class) :- 
    (
        DirectSuperclass(subclass, tmp);
        DirectSuperinterface(subclass, tmp)
    ),
    SubClass(tmp, class).

.decl AbstractType(type:Class)

AbstractType(type) :- 
    ClassModifier("abstract", type).

.decl Dispatch(simplename:symbol, descriptor:symbol, class:Class, method:Method)

Dispatch(simplename, descriptor, class, method) :-
    MethodInfo(method, simplename, _, class, _, descriptor, _),
    !MethodModifier("abstract", method).

Dispatch(simplename, descriptor, class, method) :-
    !MethodInfo(_, simplename, _, class, _, descriptor, _),
    DirectSuperclass(class, superclass),
    Dispatch(simplename, descriptor, superclass, method),
    !MethodModifier("abstract", method).


================================================
FILE: neo4j/CallEdgeHeader.csv
================================================
:START_ID(Method)	insn	:END_ID(Method)

================================================
FILE: neo4j/CallNodeHeader.csv
================================================
method:ID(Method)	:LABEL

================================================
FILE: neo4j/ChaEdgeHeader.csv
================================================
:START_ID(Method)	method	:END_ID(Method)

================================================
FILE: neoImportCall-4.4.sh
================================================
#!/bin/bash

dbname=$1$(date "+%m%d%H%M")

neo4j-admin database import full --relationships=Call="/bytecodedl/neo4j/CallEdgeHeader.csv,/bytecodedl/output/.*CallEdge.csv" --nodes="/bytecodedl/neo4j/CallNodeHeader.csv,/bytecodedl/output/.*CallNode.csv"  --delimiter="\t" $dbname

if grep -q "dbms.active_database" /var/lib/neo4j/conf/neo4j.conf; then
    sed -i -E "s/dbms.active_database=\w+/dbms.active_database=$dbname/g" /var/lib/neo4j/conf/neo4j.conf
else
    echo "dbms.active_database=$dbname" >> /var/lib/neo4j/conf/neo4j.conf
fi


================================================
FILE: neoImportCall.sh
================================================
#!/bin/bash

dbname=$1$(date "+%m%d%H%M")

neo4j-admin database import full --nodes="/bytecodedl/neo4j/CallNodeHeader.csv,/bytecodedl/output/.*CallNode.csv" --relationships=Call="/bytecodedl/neo4j/CallEdgeHeader.csv,/bytecodedl/output/CallEdge.csv" --delimiter="\t" $dbname

if grep -q "#initial.dbms.default_database" /var/lib/neo4j/conf/neo4j.conf; then
    sed -i -E "s/#initial.dbms.default_database=\S+/initial.dbms.default_database=$dbname/g" /var/lib/neo4j/conf/neo4j.conf
else
    sed -i -E "s/initial.dbms.default_database=\S+/initial.dbms.default_database=$dbname/g" /var/lib/neo4j/conf/neo4j.conf
fi


================================================
FILE: neoImportChaCall-4.4.sh
================================================
#!/bin/bash

dbname=$1$(date "+%m%d%H%M")

neo4j-admin database import --nodes=Method="/bytecodedl/neo4j/CallNodeHeader.csv,/bytecodedl/output/.*CallNode.csv" --relationships=Call="/bytecodedl/neo4j/CallEdgeHeader.csv,/bytecodedl/output/CallEdge.csv" --relationships=Cha="/bytecodedl/neo4j/ChaEdgeHeader.csv,/bytecodedl/output/ChaGraph.csv" --database=$dbname --delimiter="\t"

if grep -q "dbms.active_database" /var/lib/neo4j/conf/neo4j.conf; then
    sed -i -E "s/dbms.active_database=\w+/dbms.active_database=$dbname/g" /var/lib/neo4j/conf/neo4j.conf
else
    echo "dbms.active_database=$dbname" >> /var/lib/neo4j/conf/neo4j.conf
fi


================================================
FILE: neoImportChaCall.sh
================================================
#!/bin/bash

dbname=$1$(date "+%m%d%H%M")

neo4j-admin database import full --nodes=Method="/bytecodedl/neo4j/CallNodeHeader.csv,/bytecodedl/output/.*CallNode.csv" --relationships=Call="/bytecodedl/neo4j/CallEdgeHeader.csv,/bytecodedl/output/CallEdge.csv" --relationships=Cha="/bytecodedl/neo4j/ChaEdgeHeader.csv,/bytecodedl/output/ChaEdge.csv" --delimiter="\t" $dbname

if grep -q "#initial.dbms.default_database" /var/lib/neo4j/conf/neo4j.conf; then
    sed -i -E "s/#initial.dbms.default_database=\w+/initial.dbms.default_database=$dbname/g" /var/lib/neo4j/conf/neo4j.conf
else
    sed -i -E "s/initial.dbms.default_database=\w+/initial.dbms.default_database=$dbname/g" /var/lib/neo4j/conf/neo4j.conf
fi


================================================
FILE: output/readme.md
================================================
# output

这个目录用于放置输出结果
Download .txt
gitextract_s9rsi9xd/

├── .gitignore
├── LICENSE
├── README.md
├── docker/
│   ├── bytecodedl/
│   │   └── Dockerfile
│   └── neo4j-server/
│       └── Dockerfile
├── docker-compose.yml
├── docs/
│   ├── callgraph.md
│   ├── cha-in-ctf.md
│   ├── cha-optimization.md
│   ├── context-insensitive-points-to.md
│   ├── ptaint.md
│   ├── query.md
│   ├── readme.md
│   ├── relation.md
│   ├── souffle.md
│   └── utils.md
├── example/
│   ├── cha-example-1.dl
│   ├── cha-log4shell.dl
│   ├── cs-ptaint-example-1.dl
│   ├── ctf-buggyLoader.dl
│   ├── ctf-ezchain.dl
│   ├── one-callsite-sensitive-pt-example-1.dl
│   ├── one-object-sensitive-pt-example-1.dl
│   ├── one-type-sensitive-pt-example-1.dl
│   ├── pt-noctx-example-1.dl
│   ├── ptaint-example-1.dl
│   ├── ptaint-example-2.dl
│   ├── query-example-1.dl
│   ├── rta-example-1.dl
│   └── simple-cha-log4shell.dl
├── importOuput2Neo4j.sh
├── logic/
│   ├── abstract-context-sensitive-pt.dl
│   ├── cha.dl
│   ├── cs-ptaint.dl
│   ├── inputDeclaration.dl
│   ├── one-callsite-sensitive-pt.dl
│   ├── one-object-sensitive-pt.dl
│   ├── one-type-sensitive-pt.dl
│   ├── pt-noctx.dl
│   ├── ptaint.dl
│   ├── rta.dl
│   ├── simple-cha.dl
│   └── utils.dl
├── neo4j/
│   ├── CallEdgeHeader.csv
│   ├── CallNodeHeader.csv
│   └── ChaEdgeHeader.csv
├── neoImportCall-4.4.sh
├── neoImportCall.sh
├── neoImportChaCall-4.4.sh
├── neoImportChaCall.sh
└── output/
    └── readme.md
Condensed preview — 51 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (160K chars).
[
  {
    "path": ".gitignore",
    "chars": 29,
    "preview": "output/*.csv\n.DS_Store\n.idea\n"
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 1729,
    "preview": "# ByteCodeDL\n\n<div align=\"center\">\n\t<img src=\"./bdl-logo.png\" alt=\"ByteCodeDL\" width=\"200\">\n</div>\n\nA declarative static"
  },
  {
    "path": "docker/bytecodedl/Dockerfile",
    "chars": 697,
    "preview": "From ubuntu:22.04\n\nLABEL version=\"1.0.2\"\nLABEL maintainer=\"yxxx <yxwuman@gmail.com>\"\n\nRUN apt-get update \\\n    && apt-ge"
  },
  {
    "path": "docker/neo4j-server/Dockerfile",
    "chars": 373,
    "preview": "From neo4j:5.12.0\n\nLABEL version=\"1.0.1\"\nLABEL maintainer=\"yxxx <yxwuman@gmail.com>\"\n\nRUN wget https://github.com/Byteco"
  },
  {
    "path": "docker-compose.yml",
    "chars": 361,
    "preview": "version: '2.4'\nservices:\n  bytecodedl:\n    image: wuxxxxx/bytecodedl:1.0.2\n    restart: always\n    command: sleep infini"
  },
  {
    "path": "docs/callgraph.md",
    "chars": 5494,
    "preview": "# callgraph\n\n这节介绍调用图构造,强烈建议先看这个 [PPT](https://pascal-group.bitbucket.io/lectures/Inter.pdf)\n\nSpeicalMethodInvocation和Sta"
  },
  {
    "path": "docs/cha-in-ctf.md",
    "chars": 7684,
    "preview": "# cha in ctf\n\n本文首发于 https://tttang.com/archive/1510/\n\n这篇文章对应的代码分支见 [cha-in-ctf](https://github.com/BytecodeDL/ByteCodeDL"
  },
  {
    "path": "docs/cha-optimization.md",
    "chars": 3175,
    "preview": "# cha-optimization\n\n本文代码对应的分支是 [cha-optimization](https://github.com/BytecodeDL/ByteCodeDL/tree/cha-optimization)\n\n## 实现"
  },
  {
    "path": "docs/context-insensitive-points-to.md",
    "chars": 7928,
    "preview": "# context-insensitive-points-to\n\n以防后续更新代码,导致与本文描述的有所冲突,建议切换到 [pt-noctx](https://github.com/BytecodeDL/ByteCodeDL/blob/pt"
  },
  {
    "path": "docs/ptaint.md",
    "chars": 23923,
    "preview": "# ptaint\n\n## Introduction\n\n主要是根据ptaint这篇论文的思想,将指针分析和污点分析统一起来进行分析,建议先学习下面三份资料\n\n- https://yanniss.github.io/ptaint-oopsla1"
  },
  {
    "path": "docs/query.md",
    "chars": 1199,
    "preview": "# query\n\n有了前面的铺垫,到这节,我们就可以通过ByteCodeDL ,快速筛选出一些class和method。\n\n## 案例一\n\n比如这位群友的需求\n> 有没有啥东西,可以自动找jvm里符合某些要求的类\n\n> 比如 我只想找有两个"
  },
  {
    "path": "docs/readme.md",
    "chars": 620,
    "preview": "# ByteCodeDL\n\n基本需要两部分知识,一部分是程序分析另外一部分是datalog编程。对于程序分析部分的知识,强烈推荐去学习南大的程序分析课程,[视频链接](https://space.bilibili.com/2919428/c"
  },
  {
    "path": "docs/relation.md",
    "chars": 3821,
    "preview": "# relation\n\n## Subtypes\n\n```\n// 指令 可以定位出动作(比如call,load,sotre,assign)发生时的代码位置\n.type Insn <: symbol\n// 变量 \n.type Var <: sy"
  },
  {
    "path": "docs/souffle.md",
    "chars": 1654,
    "preview": "# Souffle\n\n## example\n\nSouffle是款Datalog推理引擎,也是著名声明式分析框架Doop默认的引擎。\n\nDatalog = data + logic ,也就是现有的事实加上推理逻辑可以推理出新的事实。\ndata"
  },
  {
    "path": "docs/utils.md",
    "chars": 1765,
    "preview": "# utils\n\n## Class Hierarchy\n\n需要构建一个类型层次图,用于寻找某个类的子类、父类,或者用于判断两个类之间是否有继承关系。\n\n从bytecode中能够解析出直接继承关系,其中extend对应的是DirectSupe"
  },
  {
    "path": "example/cha-example-1.dl",
    "chars": 239,
    "preview": "#define MAXSTEP 8\n\n#include \"../logic/cha.dl\"\n\n\n// init entrypoint \nEntryPoint(simplename, descriptor, class) :-\n    Met"
  },
  {
    "path": "example/cha-log4shell.dl",
    "chars": 477,
    "preview": "#define MAXSTEP 33\n#define CHAO 1\n\n#include \"../logic/cha.dl\"\n\nBanCaller(method) :-\n    MethodInfo(method, _, _, class, "
  },
  {
    "path": "example/cs-ptaint-example-1.dl",
    "chars": 1358,
    "preview": "#define MAXSTEP 8\n//#include \"../logic/one-callsite-sensitive-pt.dl\"\n#include \"../logic/cs-ptaint.dl\"\n#include \"../logic"
  },
  {
    "path": "example/ctf-buggyLoader.dl",
    "chars": 775,
    "preview": "#define MAXSTEP 5\n#define CHAO 2\n\n#include \"../logic/cha.dl\"\n\n\n.decl NonParamPublicMethod(method:Method, class:Class)\n.o"
  },
  {
    "path": "example/ctf-ezchain.dl",
    "chars": 734,
    "preview": "#define MAXSTEP 5\n#define CHAO 2\n\n#include \"../logic/cha.dl\"\n\n\n.decl NonParamPublicMethod(method:Method, class:Class)\n.o"
  },
  {
    "path": "example/one-callsite-sensitive-pt-example-1.dl",
    "chars": 492,
    "preview": "#define MAXSTEP 8\n#include \"../logic/one-callsite-sensitive-pt.dl\"\n\n.init callsitecsDemo1 = OneCallsiteSensitivePT\ncalls"
  },
  {
    "path": "example/one-object-sensitive-pt-example-1.dl",
    "chars": 462,
    "preview": "#define MAXSTEP 8\n#include \"../logic/one-object-sensitive-pt.dl\"\n\n.init objectDemo1 = OneObjectSensitivePT\nobjectDemo1.R"
  },
  {
    "path": "example/one-type-sensitive-pt-example-1.dl",
    "chars": 444,
    "preview": "#define MAXSTEP 8\n#include \"../logic/one-type-sensitive-pt.dl\"\n\n.init typeDemo1 = OneTypeSensitivePT\ntypeDemo1.Reachable"
  },
  {
    "path": "example/pt-noctx-example-1.dl",
    "chars": 248,
    "preview": "#include \"../logic/pt-noctx.dl\"\n\n.init cipt = ContextInsensitivePt\n\ncipt.Reachable(method) :-\n    MethodInfo(method, sim"
  },
  {
    "path": "example/ptaint-example-1.dl",
    "chars": 963,
    "preview": "#include \"../logic/ptaint.dl\"\n\n.init ptaint = PTaint\n\nptaint.Reachable(\"<com.bytecodedl.benchmark.demo.TaintDemo3: void "
  },
  {
    "path": "example/ptaint-example-2.dl",
    "chars": 1542,
    "preview": "#include \"../logic/ptaint.dl\"\n\n.init ptaint = PTaint\n\n.decl EntryMethod(method:Method)\n\nEntryMethod(\"<com.bytecodedl.ben"
  },
  {
    "path": "example/query-example-1.dl",
    "chars": 273,
    "preview": "#include \"../logic/inputDeclaration.dl\"\n\n.decl QueryResult(class:Class, method:Method)\n.output QueryResult\n\nQueryResult("
  },
  {
    "path": "example/rta-example-1.dl",
    "chars": 163,
    "preview": "#define MAXSTEP 8\n\n#include \"../logic/RTA.dl\"\n\n.init rta = RTA\n\nrta.EntryPoint(\"main\", \"([Ljava/lang/String;)V\", \"com.by"
  },
  {
    "path": "example/simple-cha-log4shell.dl",
    "chars": 435,
    "preview": "#define MAXSTEP 33\n\n#include \"../logic/simple-cha.dl\"\n\n\nSinkDesc(\"lookup\", \"javax.naming.Context\").\n\n// init entrypoint "
  },
  {
    "path": "importOuput2Neo4j.sh",
    "chars": 86,
    "preview": "#!/bin/bash\n\ndocker-compose exec neo bash /bytecodedl/$1 $2\ndocker-compose restart neo"
  },
  {
    "path": "logic/abstract-context-sensitive-pt.dl",
    "chars": 4975,
    "preview": "#pragma once\n#include \"utils.dl\"\n\n.comp AbstractContextSensitivePT<HContext, Context>{\n    .decl VarPointsTo(heap:Heap, "
  },
  {
    "path": "logic/cha.dl",
    "chars": 3418,
    "preview": "#pragma once\n#include \"utils.dl\"\n\n.decl EntryPoint(simplename:symbol, descriptor:symbol, class:Class)\n.decl Reachable(me"
  },
  {
    "path": "logic/cs-ptaint.dl",
    "chars": 2155,
    "preview": "#pragma once\n#include \"utils.dl\"\n#include \"abstract-context-sensitive-pt.dl\"\n\n.comp CSPTaint<HContext, Context>{\n    //."
  },
  {
    "path": "logic/inputDeclaration.dl",
    "chars": 3264,
    "preview": "#pragma once\n\n.type Insn <: symbol\n.type Var <: symbol\n.type Heap <: symbol\n.type Field <: symbol\n.type Method <: symbol"
  },
  {
    "path": "logic/one-callsite-sensitive-pt.dl",
    "chars": 745,
    "preview": "#pragma once\n#include \"abstract-context-sensitive-pt.dl\"\n\n.type HContext = Insn\n.type Context = Insn\n\n.comp OneCallsiteS"
  },
  {
    "path": "logic/one-object-sensitive-pt.dl",
    "chars": 562,
    "preview": "#pragma once\n#include \"abstract-context-sensitive-pt.dl\"\n\n.type HContext = Heap\n.type Context = Heap\n\n.comp OneObjectSen"
  },
  {
    "path": "logic/one-type-sensitive-pt.dl",
    "chars": 675,
    "preview": "#pragma once\n#include \"abstract-context-sensitive-pt.dl\"\n\n.type HContext = Class\n.type Context = Class\n\n.comp OneTypeSen"
  },
  {
    "path": "logic/pt-noctx.dl",
    "chars": 3434,
    "preview": "#pragma once\n#include \"utils.dl\"\n\n.comp ContextInsensitivePt{\n    .decl VarPointsTo(heap:Heap, var:Var)\n    .decl Instan"
  },
  {
    "path": "logic/ptaint.dl",
    "chars": 1731,
    "preview": "#pragma once\n#include \"pt-noctx.dl\"\n\n.comp PTaint : ContextInsensitivePt{\n\n    .decl TaintHeap(insn:Insn, heap:Heap)\n   "
  },
  {
    "path": "logic/rta.dl",
    "chars": 4112,
    "preview": "#pragma once\n#include \"inputDeclaration.dl\"\n#include \"utils.dl\"\n\n.comp RTA{\n    .decl EntryPoint(simplename:symbol, desc"
  },
  {
    "path": "logic/simple-cha.dl",
    "chars": 3053,
    "preview": "#pragma once\n#include \"utils.dl\"\n\n.decl EntryPoint(simplename:symbol, descriptor:symbol, class:Class)\n.decl Reachable(me"
  },
  {
    "path": "logic/utils.dl",
    "chars": 1207,
    "preview": "#pragma once\n#include \"inputDeclaration.dl\"\n\n//self define relation\n\n// Utils\n.decl SubClass(subclass:Class, class:Class"
  },
  {
    "path": "neo4j/CallEdgeHeader.csv",
    "chars": 38,
    "preview": ":START_ID(Method)\tinsn\t:END_ID(Method)"
  },
  {
    "path": "neo4j/CallNodeHeader.csv",
    "chars": 24,
    "preview": "method:ID(Method)\t:LABEL"
  },
  {
    "path": "neo4j/ChaEdgeHeader.csv",
    "chars": 40,
    "preview": ":START_ID(Method)\tmethod\t:END_ID(Method)"
  },
  {
    "path": "neoImportCall-4.4.sh",
    "chars": 536,
    "preview": "#!/bin/bash\n\ndbname=$1$(date \"+%m%d%H%M\")\n\nneo4j-admin database import full --relationships=Call=\"/bytecodedl/neo4j/Call"
  },
  {
    "path": "neoImportCall.sh",
    "chars": 611,
    "preview": "#!/bin/bash\n\ndbname=$1$(date \"+%m%d%H%M\")\n\nneo4j-admin database import full --nodes=\"/bytecodedl/neo4j/CallNodeHeader.cs"
  },
  {
    "path": "neoImportChaCall-4.4.sh",
    "chars": 636,
    "preview": "#!/bin/bash\n\ndbname=$1$(date \"+%m%d%H%M\")\n\nneo4j-admin database import --nodes=Method=\"/bytecodedl/neo4j/CallNodeHeader."
  },
  {
    "path": "neoImportChaCall.sh",
    "chars": 707,
    "preview": "#!/bin/bash\n\ndbname=$1$(date \"+%m%d%H%M\")\n\nneo4j-admin database import full --nodes=Method=\"/bytecodedl/neo4j/CallNodeHe"
  },
  {
    "path": "output/readme.md",
    "chars": 22,
    "preview": "# output\n\n这个目录用于放置输出结果"
  }
]

About this extraction

This page contains the full source code of the BytecodeDL/ByteCodeDL GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 51 files (133.0 KB), approximately 40.8k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!