mirror of
https://github.com/lifting-bits/mcsema
synced 2026-06-08 15:31:09 +00:00
API improvements. Must be used with the api_improvements branches of Remill and Anvill (#666)
* API improvements. Must be used with the api_improvements branch of both Remill and McSema fixes for x86 and running the lifted code with klee * Update dockerfile to clone anvill * update remill commit id * Add python3 to dockerfile * update python3 * disable abi script * Updated cmake to find anvill * Update main.cpp * update find_package for anvill * WIP:updated prebuild cfg * update prebuild cfg files * enable abi build for testsuite * Fix memory leak * install missing package for testcases * frontend: Reflect cfg file changes in dyninst frontend. * frontend: Update local files copyrights to reflect overall change to agplv3. * fix failing testcases * update test cfgs * Fix test failure with local state pointer * set the flag to use local state_ptr in default mode Co-authored-by: kumarak <iit.akshay@gmail.com> Co-authored-by: Lukas Korencik <xkorenc1@fi.muni.cz>
This commit is contained in:
+1
-1
@@ -1 +1 @@
|
||||
86a6424d58cca6504a93bf7dc4363f14be9e216f
|
||||
5af012219674f2e1b0691748e6d62ad4d1817b86
|
||||
|
||||
+74
-68
@@ -1,16 +1,17 @@
|
||||
# Copyright (c) 2018 Trail of Bits, Inc.
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# 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 Affero General Public License for more details.
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
project(mcsema)
|
||||
cmake_minimum_required(VERSION 3.2)
|
||||
@@ -81,19 +82,79 @@ set_source_files_properties(${PROJECT_PROTOBUFHEADERFILES} PROPERTIES
|
||||
COMPILE_FLAGS "-Wno-sign-conversion -Wno-shorten-64-to-32 -Wno-conversion"
|
||||
)
|
||||
|
||||
# llvm
|
||||
find_package(LLVM REQUIRED CONFIG HINTS ${FINDPACKAGE_LLVM_HINTS})
|
||||
|
||||
string(REPLACE "." ";" LLVM_VERSION_LIST ${LLVM_PACKAGE_VERSION})
|
||||
list(GET LLVM_VERSION_LIST 0 LLVM_MAJOR_VERSION)
|
||||
list(GET LLVM_VERSION_LIST 1 LLVM_MINOR_VERSION)
|
||||
set(REMILL_LLVM_VERSION "${LLVM_MAJOR_VERSION}.${LLVM_MINOR_VERSION}")
|
||||
|
||||
#
|
||||
# target settings
|
||||
#
|
||||
|
||||
set(MCSEMA_LIFT mcsema-lift-${REMILL_LLVM_VERSION})
|
||||
|
||||
add_executable(${MCSEMA_LIFT}
|
||||
${PROJECT_PROTOBUFSOURCEFILES}
|
||||
|
||||
mcsema/Arch/Arch.cpp
|
||||
|
||||
mcsema/CFG/CFG.cpp
|
||||
|
||||
mcsema/BC/Callback.cpp
|
||||
mcsema/BC/External.cpp
|
||||
mcsema/BC/Function.cpp
|
||||
mcsema/BC/Instruction.cpp
|
||||
mcsema/BC/Legacy.cpp
|
||||
mcsema/BC/Lift.cpp
|
||||
mcsema/BC/Optimize.cpp
|
||||
mcsema/BC/Segment.cpp
|
||||
mcsema/BC/Util.cpp
|
||||
|
||||
tools/mcsema_lift/Lift.cpp
|
||||
)
|
||||
|
||||
# Copy mcsema-disass in
|
||||
add_custom_command(
|
||||
TARGET protobuf_python_module_ida POST_BUILD
|
||||
DEPENDS {PROJECT_PROTOBUFPYTHONMODULE}
|
||||
COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_PROTOBUFPYTHONMODULE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/mcsema_disass/ida7
|
||||
)
|
||||
|
||||
# this is needed for the #include directives with absolutes paths to work correctly; it must
|
||||
# also be set to PUBLIC since mcsema-lift includes some files directly
|
||||
list(APPEND PROJECT_INCLUDEDIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
add_dependencies(${MCSEMA_LIFT}
|
||||
semantics
|
||||
protobuf_python_module_ida
|
||||
protobuf_python_module_binja)
|
||||
|
||||
#
|
||||
# libraries
|
||||
#
|
||||
|
||||
# remill
|
||||
if(NOT TARGET remill)
|
||||
if("${PLATFORM_NAME}" STREQUAL "windows")
|
||||
set(REMILL_FINDPACKAGE_HINTS HINTS "${CMAKE_INSTALL_PREFIX}/remill/lib")
|
||||
endif()
|
||||
|
||||
find_package(remill REQUIRED ${REMILL_FINDPACKAGE_HINTS})
|
||||
endif()
|
||||
|
||||
list(APPEND PROJECT_LIBRARIES remill)
|
||||
list(APPEND PROJECT_INCLUDEDIRECTORIES ${remill_INCLUDE_DIRS})
|
||||
|
||||
# llvm
|
||||
find_package(LLVM REQUIRED CONFIG HINTS ${FINDPACKAGE_LLVM_HINTS})
|
||||
# anvill
|
||||
if(NOT TARGET anvill-${REMILL_LLVM_VERSION})
|
||||
find_package(anvill REQUIRED)
|
||||
if(NOT anvill_FOUND)
|
||||
message(FATAL_ERROR "McSema depends upon Anvill being cloned into Remill's tools directory")
|
||||
endif()
|
||||
endif()
|
||||
list(APPEND PROJECT_LIBRARIES anvill-${REMILL_LLVM_VERSION})
|
||||
|
||||
if (LLVM_Z3_INSTALL_DIR)
|
||||
set(need_z3 TRUE)
|
||||
@@ -111,9 +172,6 @@ if(need_z3)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
string(REPLACE "." ";" LLVM_VERSION_LIST ${LLVM_PACKAGE_VERSION})
|
||||
list(GET LLVM_VERSION_LIST 0 LLVM_MAJOR_VERSION)
|
||||
list(GET LLVM_VERSION_LIST 1 LLVM_MINOR_VERSION)
|
||||
|
||||
set(LLVM_LIBRARIES
|
||||
LLVMCore LLVMSupport LLVMAnalysis LLVMipo LLVMIRReader
|
||||
@@ -138,58 +196,6 @@ list(APPEND PROJECT_LIBRARIES glog::glog)
|
||||
find_package(gflags REQUIRED)
|
||||
list(APPEND PROJECT_LIBRARIES gflags)
|
||||
|
||||
|
||||
#
|
||||
# target settings
|
||||
#
|
||||
|
||||
set(MCSEMA_LLVM_VERSION "${LLVM_MAJOR_VERSION}.${LLVM_MINOR_VERSION}")
|
||||
set(MCSEMA_LIFT mcsema-lift-${MCSEMA_LLVM_VERSION})
|
||||
|
||||
add_executable(${MCSEMA_LIFT}
|
||||
${PROJECT_PROTOBUFSOURCEFILES}
|
||||
|
||||
mcsema/Arch/ABI.cpp
|
||||
mcsema/Arch/Arch.cpp
|
||||
|
||||
mcsema/CFG/CFG.cpp
|
||||
|
||||
mcsema/BC/Callback.cpp
|
||||
mcsema/BC/External.cpp
|
||||
mcsema/BC/Function.cpp
|
||||
mcsema/BC/Instruction.cpp
|
||||
mcsema/BC/Legacy.cpp
|
||||
mcsema/BC/Lift.cpp
|
||||
mcsema/BC/Optimize.cpp
|
||||
mcsema/BC/Segment.cpp
|
||||
mcsema/BC/Util.cpp
|
||||
|
||||
tools/mcsema_lift/Lift.cpp
|
||||
)
|
||||
|
||||
|
||||
# Copy mcsema-disass in
|
||||
add_custom_command(
|
||||
TARGET protobuf_python_module_ida POST_BUILD
|
||||
DEPENDS {PROJECT_PROTOBUFPYTHONMODULE}
|
||||
COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_PROTOBUFPYTHONMODULE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/mcsema_disass/ida
|
||||
)
|
||||
|
||||
add_custom_command(
|
||||
TARGET protobuf_python_module_binja POST_BUILD
|
||||
DEPENDS {PROJECT_PROTOBUFPYTHONMODULE}
|
||||
COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_PROTOBUFPYTHONMODULE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/mcsema_disass/binja
|
||||
)
|
||||
|
||||
# this is needed for the #include directives with absolutes paths to work correctly; it must
|
||||
# also be set to PUBLIC since mcsema-lift includes some files directly
|
||||
list(APPEND PROJECT_INCLUDEDIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
add_dependencies(${MCSEMA_LIFT}
|
||||
semantics protobuf_python_module_ida
|
||||
protobuf_python_module_binja
|
||||
)
|
||||
|
||||
#
|
||||
# target settings
|
||||
#
|
||||
|
||||
+6
-3
@@ -23,18 +23,21 @@ RUN apt-get update && \
|
||||
# Build-time dependencies go here
|
||||
FROM trailofbits/cxx-common:llvm${LLVM_VERSION}-${DISTRO_BASE}-${ARCH} as deps
|
||||
ARG LIBRARIES
|
||||
|
||||
RUN apt-get update && \
|
||||
apt-get install -qqy python2.7 libc6-dev wget liblzma-dev zlib1g-dev libtinfo-dev curl git build-essential ninja-build ccache && \
|
||||
apt-get install -qqy python2.7 python3 python3-pip libc6-dev wget liblzma-dev zlib1g-dev libtinfo-dev curl git build-essential ninja-build libselinux1-dev libbsd-dev ccache && \
|
||||
if [ "$(uname -m)" = "x86_64" ]; then dpkg --add-architecture i386 && apt-get update && apt-get install -qqy gcc-multilib g++-multilib zip zlib1g-dev:i386; fi && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
rm -rf /var/lib/apt/lists/* && \
|
||||
pip3 install ccsyspath
|
||||
|
||||
# needed for 20.04 support until we migrate to py3
|
||||
RUN curl https://bootstrap.pypa.io/get-pip.py --output get-pip.py && python2.7 get-pip.py
|
||||
|
||||
RUN update-alternatives --install /usr/bin/python2 python2 /usr/bin/python2.7 1
|
||||
|
||||
WORKDIR /
|
||||
COPY .remill_commit_id ./
|
||||
RUN git clone https://github.com/lifting-bits/remill.git && \
|
||||
git clone https://github.com/lifting-bits/anvill.git remill/tools/anvill && \
|
||||
cd remill && \
|
||||
echo "Using remill commit $(cat ../.remill_commit_id)" && \
|
||||
git checkout $(cat ../.remill_commit_id)
|
||||
|
||||
@@ -1,176 +1,661 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
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.
|
||||
|
||||
1. Definitions.
|
||||
Preamble
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are 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.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
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.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
0. Definitions.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
"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.
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
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.
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
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.
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
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.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
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.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
1. Source Code.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
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.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
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.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
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.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
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.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
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. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
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 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 work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
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 AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
@@ -79,6 +79,8 @@ Why would anyone translate binaries *back* to bitcode?
|
||||
| [Python](https://www.python.org/) | 2.7 |
|
||||
| [Python Package Index](https://pypi.python.org/pypi) | Latest |
|
||||
| [python-protobuf](https://pypi.python.org/pypi/protobuf) | 3.2.0 |
|
||||
| [python-clang](https://pypi.org/project/clang/) | 3.5.0 |
|
||||
| [ccsyspath](https://pypi.org/project/ccsyspath/) | 1.1.0 |
|
||||
| [IDA Pro](https://www.hex-rays.com/products/ida) | 7.1+ |
|
||||
| [Binary Ninja](https://binary.ninja/) | Latest |
|
||||
| [Dyninst](https://www.dyninst.org/) | 9.3.2 |
|
||||
@@ -87,16 +89,13 @@ Why would anyone translate binaries *back* to bitcode?
|
||||
|
||||
### Docker
|
||||
|
||||
#### Step 1: Clone McSema
|
||||
#### Step 1: Download Dockerfile
|
||||
|
||||
```sh
|
||||
git clone --depth 1 https://github.com/lifting-bits/mcsema.git
|
||||
cd mcsema
|
||||
```
|
||||
`wget https://raw.githubusercontent.com/lifting-bits/mcsema/master/tools/Dockerfile`
|
||||
|
||||
#### Step 2: Add your disassembler (optional)
|
||||
#### Step 2: Add your disassembler
|
||||
|
||||
Currently IDA, Binary Ninja, and Dyninst are supported for control-flow recovery, it's left as an exercise to the reader to install your disassembler of choice in a Dockerfile, but an example of installing Binary Ninja is provided (remember for Docker that paths need to be relative to where you built from):
|
||||
Currently IDA, Binary Ninja, and Dyninst are supported for control-flow recovery, it's left as an exercise to the reader to install your disassembler of choice, but an example of installing Binary Ninja is provided (remember for Docker that paths need to be relative to where you built from):
|
||||
```
|
||||
ADD local-relative/path/to/binaryninja/ /root/binaryninja/
|
||||
ADD local-relative/path/to/.binaryninja/ /root/.binaryninja/ # <- Make sure there's no `lastrun` file
|
||||
|
||||
-1248
File diff suppressed because it is too large
Load Diff
@@ -1,102 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef MCSEMA_ARCH_ABI_H_
|
||||
#define MCSEMA_ARCH_ABI_H_
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "remill/BC/Compat/CallingConvention.h"
|
||||
|
||||
namespace llvm {
|
||||
class Type;
|
||||
} // namespace llvm
|
||||
namespace mcsema {
|
||||
|
||||
struct ArgConstraint {
|
||||
std::string var_name;
|
||||
const int accepted_val_kinds;
|
||||
};
|
||||
|
||||
// Generic functions for reading/writing to the register/stack state in a way
|
||||
// that respects a supplied calling convention.
|
||||
class CallingConvention {
|
||||
public:
|
||||
explicit CallingConvention(llvm::CallingConv::ID cc_);
|
||||
|
||||
llvm::Value *LoadNextArgument(llvm::BasicBlock *block,
|
||||
llvm::Type *goal_type=nullptr,
|
||||
bool is_byval=false);
|
||||
|
||||
void StoreReturnValue(llvm::BasicBlock *block, llvm::Value *ret_val);
|
||||
|
||||
void StoreArguments(llvm::BasicBlock *block,
|
||||
const std::vector<llvm::Value *> &arg_vals);
|
||||
|
||||
void FreeArguments(llvm::BasicBlock *block);
|
||||
|
||||
void AllocateReturnAddress(llvm::BasicBlock *block);
|
||||
void FreeReturnAddress(llvm::BasicBlock *block);
|
||||
|
||||
llvm::Value *LoadReturnValue(llvm::BasicBlock *block,
|
||||
llvm::Type *goal_type=nullptr);
|
||||
|
||||
llvm::Value *LoadStackPointer(llvm::BasicBlock *block);
|
||||
|
||||
void StoreStackPointer(llvm::BasicBlock *block, llvm::Value *new_val);
|
||||
|
||||
const char *StackPointerVarName(void) const {
|
||||
return sp_name;
|
||||
}
|
||||
|
||||
void StoreThreadPointer(llvm::BasicBlock *block, llvm::Value *new_val);
|
||||
|
||||
const char *ThreadPointerVarName(void) const {
|
||||
return tp_name;
|
||||
}
|
||||
|
||||
private:
|
||||
void StoreVectorRetValue(llvm::BasicBlock *block,
|
||||
llvm::Value *ret_val,
|
||||
llvm::VectorType *goal_type);
|
||||
|
||||
llvm::Value *LoadVectorArgument(llvm::BasicBlock *block,
|
||||
llvm::VectorType *goal_type);
|
||||
llvm::Value *LoadNextSimpleArgument(llvm::BasicBlock *block,
|
||||
llvm::Type *goal_type);
|
||||
|
||||
const char *GetVarForNextArgument(llvm::Type *val_type);
|
||||
const char *GetVarForNextReturn(llvm::Type *val_type);
|
||||
|
||||
llvm::CallingConv::ID cc;
|
||||
uint64_t used_reg_bitmap;
|
||||
uint64_t used_return_bitmap;
|
||||
uint64_t num_loaded_stack_bytes;
|
||||
uint64_t num_stored_stack_bytes;
|
||||
const char * const sp_name;
|
||||
const char * const tp_name;
|
||||
const std::vector<ArgConstraint> ®_table;
|
||||
const std::vector<ArgConstraint> &return_table;
|
||||
CallingConvention(void) = delete;
|
||||
};
|
||||
|
||||
// Return the address of the base of the TLS data.
|
||||
llvm::Value *GetTLSBaseAddress(llvm::IRBuilder<> &ir);
|
||||
|
||||
} // namespace mcsema
|
||||
|
||||
#endif // MCSEMA_ARCH_ABI_H_
|
||||
+25
-14
@@ -1,19 +1,22 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "mcsema/Arch/Arch.h"
|
||||
|
||||
#include <glog/logging.h>
|
||||
|
||||
#include <unordered_set>
|
||||
@@ -21,6 +24,7 @@
|
||||
#include <llvm/ADT/ArrayRef.h>
|
||||
|
||||
#include <llvm/IR/BasicBlock.h>
|
||||
#include <llvm/IR/Constants.h>
|
||||
#include <llvm/IR/Function.h>
|
||||
#include <llvm/IR/Instruction.h>
|
||||
#include <llvm/IR/Instructions.h>
|
||||
@@ -31,24 +35,31 @@
|
||||
#include <llvm/Support/TargetRegistry.h>
|
||||
#include <llvm/Support/TargetSelect.h>
|
||||
|
||||
#include "remill/Arch/Arch.h"
|
||||
#include <remill/Arch/Arch.h>
|
||||
|
||||
#include "mcsema/Arch/Arch.h"
|
||||
#include "mcsema/BC/Util.h"
|
||||
|
||||
namespace mcsema {
|
||||
|
||||
extern std::shared_ptr<llvm::LLVMContext> gContext;
|
||||
|
||||
const remill::Arch *gArch = nullptr;
|
||||
std::unique_ptr<const remill::Arch> gArch(nullptr);
|
||||
|
||||
bool InitArch(const std::string &os, const std::string &arch) {
|
||||
LOG(INFO)
|
||||
<< "Initializing for " << arch << " code on " << os;
|
||||
|
||||
gArch = remill::GetTargetArch(*gContext);
|
||||
remill::Arch::GetTargetArch(*gContext).swap(gArch);
|
||||
gWordType = llvm::Type::getIntNTy(
|
||||
*gContext, static_cast<unsigned>(gArch->address_size));
|
||||
|
||||
gWordMask = 0;
|
||||
if (32 == gArch->address_size) {
|
||||
gWordMask = static_cast<uint32_t>(~0u);
|
||||
} else {
|
||||
gWordMask = ~gWordMask;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
+14
-15
@@ -1,22 +1,23 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef MCSEMA_ARCH_ARCH_H_
|
||||
#define MCSEMA_ARCH_ARCH_H_
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace remill {
|
||||
@@ -25,10 +26,8 @@ class Arch;
|
||||
|
||||
namespace mcsema {
|
||||
|
||||
extern const remill::Arch *gArch;
|
||||
extern std::unique_ptr<const remill::Arch> gArch;
|
||||
|
||||
bool InitArch(const std::string &os, const std::string &arch);
|
||||
|
||||
} // namespace mcsema
|
||||
|
||||
#endif // MCSEMA_ARCH_ARCH_H_
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
# Copyright (c) 2017 Trail of Bits, Inc.
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# 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 Affero General Public License for more details.
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
enable_language(ASM)
|
||||
|
||||
@@ -206,10 +207,19 @@ else()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
|
||||
if(DEFINED REMILL_INCLUDE_LOCATION)
|
||||
set(REMILL_INCLUDE "-I${REMILL_INCLUDE_LOCATION}")
|
||||
endif()
|
||||
|
||||
if(DEFINED REMILL_SOURCE_DIR)
|
||||
set(REMILL_SOURCE "-I${REMILL_SOURCE_DIR}")
|
||||
endif()
|
||||
|
||||
# Create a runtime.
|
||||
add_custom_command(
|
||||
OUTPUT runtime_32.o
|
||||
COMMAND "${CMAKE_CXX_COMPILER}" -std=gnu++11 -isystem "${REMILL_INCLUDE_LOCATION}" -isystem "${MCSEMA_SOURCE_DIR}" -m32 -fPIC -c "${CMAKE_CURRENT_SOURCE_DIR}/Runtime.cpp" -o runtime_32.o
|
||||
COMMAND "${CMAKE_CXX_COMPILER}" -std=gnu++11 "${REMILL_INCLUDE}" "${REMILL_SOURCE}" "${REMILL_SOURCE_DIR}" -I"${MCSEMA_SOURCE_DIR}" -m32 -fPIC -c "${CMAKE_CURRENT_SOURCE_DIR}/Runtime.cpp" -o runtime_32.o
|
||||
DEPENDS Runtime.cpp
|
||||
COMMENT "Building 32-bit runtime"
|
||||
)
|
||||
@@ -225,7 +235,7 @@ set_source_files_properties(
|
||||
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
|
||||
add_custom_command(
|
||||
OUTPUT runtime_64.o
|
||||
COMMAND "${CMAKE_CXX_COMPILER}" -std=gnu++11 -isystem "${REMILL_INCLUDE_LOCATION}" -isystem "${MCSEMA_SOURCE_DIR}" -m64 -fPIC -c "${CMAKE_CURRENT_SOURCE_DIR}/Runtime.cpp" -o runtime_64.o
|
||||
COMMAND "${CMAKE_CXX_COMPILER}" -std=gnu++11 "${REMILL_INCLUDE}" "${REMILL_SOURCE}" -I"${MCSEMA_SOURCE_DIR}" -m64 -fPIC -c "${CMAKE_CURRENT_SOURCE_DIR}/Runtime.cpp" -o runtime_64.o
|
||||
DEPENDS Runtime.cpp
|
||||
COMMENT "Building 64-bit runtime"
|
||||
)
|
||||
@@ -237,3 +247,21 @@ if(CMAKE_SIZEOF_VOID_P EQUAL 8)
|
||||
GENERATED True
|
||||
)
|
||||
endif()
|
||||
|
||||
add_runtime(runtime_x86
|
||||
SOURCES "Runtime.cpp"
|
||||
ADDRESS_SIZE 32
|
||||
BCFLAGS "-xc++" "-m32" "-std=gnu++17" "-Wno-deprecated-declarations"
|
||||
INCLUDEDIRECTORIES "${CMAKE_SOURCE_DIR}" "${MCSEMA_SOURCE_DIR}" "${REMILL_INCLUDE_LOCATION}"
|
||||
INSTALLDESTINATION "${install_folder}/lib"
|
||||
)
|
||||
|
||||
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
|
||||
add_runtime(runtime_amd64
|
||||
SOURCES "Runtime.cpp"
|
||||
ADDRESS_SIZE 64
|
||||
BCFLAGS "-xc++" "-m64" "-std=gnu++17" "-Wno-deprecated-declarations"
|
||||
INCLUDEDIRECTORIES "${CMAKE_SOURCE_DIR}" "${MCSEMA_SOURCE_DIR}" "${REMILL_INCLUDE_LOCATION}"
|
||||
INSTALLDESTINATION "${install_folder}/lib"
|
||||
)
|
||||
endif()
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef MCSEMA_ARCH_X86_RUNTIME_REGISTERS_H_
|
||||
@@ -77,23 +78,23 @@
|
||||
#define R14D gpr.r14.dword
|
||||
#define R15D gpr.r15.dword
|
||||
|
||||
#define RAX gpr.rax.qword
|
||||
#define RBX gpr.rbx.qword
|
||||
#define RCX gpr.rcx.qword
|
||||
#define RDX gpr.rdx.qword
|
||||
#define RSI gpr.rsi.qword
|
||||
#define RDI gpr.rdi.qword
|
||||
#define RSP gpr.rsp.qword
|
||||
#define RBP gpr.rbp.qword
|
||||
#define R8 gpr.r8.qword
|
||||
#define R9 gpr.r9.qword
|
||||
#define R10 gpr.r10.qword
|
||||
#define R11 gpr.r11.qword
|
||||
#define R12 gpr.r12.qword
|
||||
#define R13 gpr.r13.qword
|
||||
#define R14 gpr.r14.qword
|
||||
#define R15 gpr.r15.qword
|
||||
#define RIP gpr.rip.qword
|
||||
#define RAX gpr.rax.aword
|
||||
#define RBX gpr.rbx.aword
|
||||
#define RCX gpr.rcx.aword
|
||||
#define RDX gpr.rdx.aword
|
||||
#define RSI gpr.rsi.aword
|
||||
#define RDI gpr.rdi.aword
|
||||
#define RSP gpr.rsp.aword
|
||||
#define RBP gpr.rbp.aword
|
||||
#define R8 gpr.r8.aword
|
||||
#define R9 gpr.r9.aword
|
||||
#define R10 gpr.r10.aword
|
||||
#define R11 gpr.r11.aword
|
||||
#define R12 gpr.r12.aword
|
||||
#define R13 gpr.r13.aword
|
||||
#define R14 gpr.r14.aword
|
||||
#define R15 gpr.r15.aword
|
||||
#define RIP gpr.rip.aword
|
||||
|
||||
#define SS seg.ss
|
||||
#define ES seg.es
|
||||
|
||||
@@ -1,27 +1,32 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <cstdio>
|
||||
#include <cfenv>
|
||||
#include <cfloat>
|
||||
#include <inttypes.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#define HAS_FEATURE_AVX 1
|
||||
#define HAS_FEATURE_AVX512 0
|
||||
#define ADDRESS_SIZE_BITS 64
|
||||
|
||||
#ifndef ADDRESS_SIZE_BITS
|
||||
# define ADDRESS_SIZE_BITS 64
|
||||
#endif
|
||||
|
||||
#include "remill/Arch/X86/Runtime/State.h"
|
||||
#include "mcsema/Arch/X86/Runtime/Registers.h"
|
||||
@@ -34,6 +39,12 @@
|
||||
# define PRIx32 "x"
|
||||
#endif
|
||||
|
||||
#if ADDRESS_SIZE_BITS == 64
|
||||
# define PRIxADDR PRIx64
|
||||
#else
|
||||
# define PRIxADDR PRIx32
|
||||
#endif
|
||||
|
||||
extern "C" {
|
||||
|
||||
// Debug registers.
|
||||
@@ -130,16 +141,15 @@ Memory *__remill_sync_hyper_call(
|
||||
}
|
||||
|
||||
Memory *__mcsema_reg_tracer(State &state, addr_t, Memory *memory) {
|
||||
const char *format = nullptr;
|
||||
if (sizeof(void *) == 8) {
|
||||
fprintf(
|
||||
stderr,
|
||||
"RIP=%" PRIx64 ",RAX=%" PRIx64 ",RBX=%" PRIx64
|
||||
",RCX=%" PRIx64 ",RDX=%" PRIx64 ",RSI=%" PRIx64
|
||||
",RDI=%" PRIx64 ",RBP=%" PRIx64 ",RSP=%" PRIx64
|
||||
",R8=%" PRIx64 ",R9=%" PRIx64 ",R10=%" PRIx64
|
||||
",R11=%" PRIx64 ",R12=%" PRIx64 ",R13=%" PRIx64
|
||||
",R14=%" PRIx64 ",R15=%" PRIx64 "\n",
|
||||
"RIP=%" PRIxADDR ",RAX=%" PRIxADDR ",RBX=%" PRIxADDR
|
||||
",RCX=%" PRIxADDR ",RDX=%" PRIxADDR ",RSI=%" PRIxADDR
|
||||
",RDI=%" PRIxADDR ",RBP=%" PRIxADDR ",RSP=%" PRIxADDR
|
||||
",R8=%" PRIxADDR ",R9=%" PRIxADDR ",R10=%" PRIxADDR
|
||||
",R11=%" PRIxADDR ",R12=%" PRIxADDR ",R13=%" PRIxADDR
|
||||
",R14=%" PRIxADDR ",R15=%" PRIxADDR "\n",
|
||||
|
||||
state.RIP, state.RAX, state.RBX, state.RCX, state.RDX, state.RSI,
|
||||
state.RDI, state.RBP, state.RSP, state.R8, state.R9, state.R10,
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
+454
-338
File diff suppressed because it is too large
Load Diff
+14
-24
@@ -1,21 +1,21 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef MCSEMA_BC_CALLBACK_H_
|
||||
#define MCSEMA_BC_CALLBACK_H_
|
||||
#pragma once
|
||||
|
||||
namespace llvm {
|
||||
|
||||
@@ -23,19 +23,11 @@ class Function;
|
||||
|
||||
} // namespace llvm
|
||||
namespace mcsema {
|
||||
struct NativeObject;
|
||||
|
||||
// Get a callback function for an internal function that can be referenced by
|
||||
// internal code.
|
||||
llvm::Function *GetNativeToLiftedCallback(const NativeObject *cfg_func);
|
||||
|
||||
// Get a callback function for an internal function that can be referenced by
|
||||
// external code.
|
||||
llvm::Function *GetNativeToLiftedEntryPoint(const NativeObject *cfg_func);
|
||||
struct NativeFunction;
|
||||
|
||||
// Get a callback function for an external function that can be referenced by
|
||||
// internal code.
|
||||
llvm::Function *GetLiftedToNativeExitPoint(const NativeObject *cfg_func);
|
||||
llvm::Function *GetLiftedToNativeExitPoint(const NativeFunction *cfg_func);
|
||||
|
||||
enum ExitPointKind {
|
||||
kExitPointJump,
|
||||
@@ -47,5 +39,3 @@ enum ExitPointKind {
|
||||
llvm::Function *GetLiftedToNativeExitPoint(ExitPointKind);
|
||||
|
||||
} // namespace mcsema
|
||||
|
||||
#endif // MCSEMA_BC_CALLBACK_H_
|
||||
|
||||
+86
-129
@@ -1,20 +1,24 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "mcsema/BC/External.h"
|
||||
|
||||
#include <glog/logging.h>
|
||||
#include <gflags/gflags.h>
|
||||
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
@@ -24,144 +28,97 @@
|
||||
#include <llvm/IR/Module.h>
|
||||
#include <llvm/IR/Type.h>
|
||||
|
||||
#include "remill/Arch/Arch.h"
|
||||
#include "remill/Arch/Name.h"
|
||||
#include "remill/BC/Annotate.h"
|
||||
#include <anvill/Decl.h>
|
||||
|
||||
#include <remill/Arch/Arch.h>
|
||||
#include <remill/Arch/Name.h>
|
||||
#include <remill/BC/Annotate.h>
|
||||
|
||||
#include "mcsema/Arch/Arch.h"
|
||||
#include "mcsema/BC/Callback.h"
|
||||
#include "mcsema/BC/External.h"
|
||||
#include "mcsema/BC/Util.h"
|
||||
#include "mcsema/CFG/CFG.h"
|
||||
|
||||
DECLARE_bool(explicit_args);
|
||||
|
||||
namespace mcsema {
|
||||
namespace {
|
||||
|
||||
// For an external named `external`, return a function with the prototype
|
||||
// `uintptr_t external(uintptr_t arg0, uintptr_t arg1, ...);`.
|
||||
//
|
||||
// TODO(pag,car,artem): Handle floating point types eventually.
|
||||
static void DeclareExternal(
|
||||
const NativeExternalFunction *cfg_func) {
|
||||
|
||||
std::vector<llvm::Type *> tys(cfg_func->num_args, gWordType);
|
||||
|
||||
auto extfun = llvm::Function::Create(
|
||||
llvm::FunctionType::get(gWordType, tys, false),
|
||||
llvm::GlobalValue::ExternalLinkage,
|
||||
cfg_func->name, gModule.get());
|
||||
|
||||
if (cfg_func->is_weak) {
|
||||
extfun->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
|
||||
}
|
||||
|
||||
extfun->setCallingConv(cfg_func->cc);
|
||||
extfun->addFnAttr(llvm::Attribute::NoInline);
|
||||
|
||||
remill::Annotate<remill::CFGExternal>(extfun);
|
||||
}
|
||||
|
||||
static llvm::GlobalValue::ThreadLocalMode ThreadLocalMode(
|
||||
const NativeObject *cfg_obj) {
|
||||
if (cfg_obj->is_thread_local) {
|
||||
return llvm::GlobalValue::GeneralDynamicTLSModel;
|
||||
} else {
|
||||
return llvm::GlobalValue::NotThreadLocal;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Declare external functions.
|
||||
void DeclareExternals(const NativeModule *cfg_module) {
|
||||
for (const auto &entry : cfg_module->name_to_extern_func) {
|
||||
auto cfg_func = reinterpret_cast<const NativeExternalFunction *>(
|
||||
entry.second->Get());
|
||||
|
||||
CHECK(cfg_func->is_external)
|
||||
<< "Trying to declare function " << cfg_func->name << " as external.";
|
||||
|
||||
CHECK_NE(cfg_func->name, cfg_func->lifted_name);
|
||||
|
||||
// The "actual" external function.
|
||||
if (!gModule->getFunction(cfg_func->name)) {
|
||||
LOG(INFO)
|
||||
<< "Adding external function " << cfg_func->name;
|
||||
DeclareExternal(cfg_func);
|
||||
llvm::Constant *NativeExternalFunction::Pointer(void) const {
|
||||
const auto prev_function = function;
|
||||
function = gModule->getFunction(name);
|
||||
if (!function && decl) {
|
||||
function = decl->DeclareInModule(name, *gModule);
|
||||
if (!prev_function) {
|
||||
module->AddNameToAddress(name, ea);
|
||||
}
|
||||
}
|
||||
|
||||
// Declare external variables.
|
||||
for (const auto &entry : cfg_module->name_to_extern_var) {
|
||||
auto cfg_var = reinterpret_cast<const NativeExternalVariable *>(
|
||||
entry.second->Get());
|
||||
if (function) {
|
||||
|
||||
auto ll_var = gModule->getGlobalVariable(cfg_var->name,
|
||||
true /* AllowInternal */);
|
||||
if (!ll_var) {
|
||||
LOG(INFO)
|
||||
<< "Adding external variable " << cfg_var->name;
|
||||
if (function == prev_function) {
|
||||
return prev_function;
|
||||
}
|
||||
|
||||
llvm::Type* var_type = nullptr;
|
||||
|
||||
CHECK_NE(0, cfg_var->size)
|
||||
<< "The size of the external variable ["
|
||||
<< cfg_var->name << "] cannot be zero";
|
||||
|
||||
// Handle external variables of up to 128 bits as intgers
|
||||
// Anything else is treated as an array of bytes
|
||||
switch(cfg_var->size) {
|
||||
case 0:
|
||||
// Why is this zero length? This should never happen
|
||||
// Attempt a fix and output a warning
|
||||
LOG(ERROR)
|
||||
<< "The variable [" << cfg_var->name
|
||||
<< "] has size of zero. Assuming it should be size 1";
|
||||
var_type = llvm::Type::getInt8Ty(*gContext);
|
||||
break;
|
||||
case 1: // 8 bit integer
|
||||
case 2: // 16 bit integer
|
||||
case 4: // 32 bit integer
|
||||
case 8: // 64 bit integer
|
||||
case 16: // 128 bit integer
|
||||
var_type = llvm::Type::getIntNTy(
|
||||
*gContext, static_cast<unsigned>(cfg_var->size * 8));
|
||||
break;
|
||||
|
||||
// An array of bytes
|
||||
default: {
|
||||
auto byte_type = llvm::Type::getInt8Ty(*gContext);
|
||||
var_type = llvm::ArrayType::get(byte_type, static_cast<unsigned>(cfg_var->size));
|
||||
break;
|
||||
}
|
||||
// The function exists and isn't varargs; use it.
|
||||
if (is_weak) {
|
||||
if (function->isDeclaration()) {
|
||||
function->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
|
||||
} else {
|
||||
function->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
|
||||
}
|
||||
|
||||
auto linkage = llvm::GlobalValue::ExternalLinkage;
|
||||
ll_var = new llvm::GlobalVariable(*gModule, var_type, false,
|
||||
linkage, nullptr, cfg_var->name,
|
||||
nullptr, ThreadLocalMode(cfg_var));
|
||||
if (cfg_var->ea) {
|
||||
ll_var->setAlignment(1 << __builtin_ctzl(cfg_var->ea));
|
||||
}
|
||||
|
||||
// This could happen if the variable is declared as a segment variable,
|
||||
// but is not exported, and there is also another exported/imported
|
||||
// global of the same name.
|
||||
//
|
||||
// TODO(pag): Another reasonable interpretation of this is to rename the
|
||||
// existing symbol so that the names don't clash.
|
||||
} else {
|
||||
LOG_IF(ERROR, !ll_var->hasExternalLinkage())
|
||||
<< "Variable '" << cfg_var->name
|
||||
<< "' is external but was not previously declared as such";
|
||||
|
||||
ll_var->setLinkage(llvm::GlobalValue::ExternalLinkage);
|
||||
function->setLinkage(llvm::GlobalValue::ExternalLinkage);
|
||||
}
|
||||
|
||||
if (!cfg_var->address) {
|
||||
cfg_var->address = llvm::ConstantExpr::getPtrToInt(ll_var, gWordType);
|
||||
remill::Annotate<remill::CFGExternal>(function);
|
||||
|
||||
return function;
|
||||
|
||||
// The function doesn't exist in the module, and we need to declare it with
|
||||
// the information we have from CFG extraction.
|
||||
} else {
|
||||
CHECK(is_external);
|
||||
std::vector<llvm::Type *> param_types(num_args, gWordType);
|
||||
|
||||
module->AddNameToAddress(name, ea);
|
||||
|
||||
function = llvm::Function::Create(
|
||||
llvm::FunctionType::get(gWordType, param_types, false),
|
||||
llvm::GlobalValue::ExternalLinkage,
|
||||
name, gModule.get());
|
||||
|
||||
if (is_weak) {
|
||||
function->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
|
||||
}
|
||||
|
||||
function->setCallingConv(cc);
|
||||
|
||||
function->removeFnAttr(llvm::Attribute::InlineHint);
|
||||
function->removeFnAttr(llvm::Attribute::AlwaysInline);
|
||||
function->removeFnAttr(llvm::Attribute::ReadNone);
|
||||
function->removeFnAttr(llvm::Attribute::ReadOnly);
|
||||
function->removeFnAttr(llvm::Attribute::ArgMemOnly);
|
||||
|
||||
function->addFnAttr(llvm::Attribute::NoInline);
|
||||
function->addFnAttr(llvm::Attribute::NoBuiltin);
|
||||
|
||||
remill::Annotate<remill::CFGExternal>(function);
|
||||
return function;
|
||||
}
|
||||
}
|
||||
|
||||
llvm::Constant *NativeExternalVariable::Pointer(void) const {
|
||||
CHECK(is_external);
|
||||
CHECK_NOTNULL(segment);
|
||||
const auto seg = segment->Get();
|
||||
CHECK(seg->is_external);
|
||||
CHECK_EQ(ea, seg->ea);
|
||||
CHECK(!seg->padding);
|
||||
return seg->Pointer();
|
||||
}
|
||||
|
||||
llvm::Constant *NativeExternalVariable::Address(void) const {
|
||||
return llvm::ConstantExpr::getPtrToInt(Pointer(), gWordType);
|
||||
}
|
||||
|
||||
} // namespace mcsema
|
||||
|
||||
+13
-15
@@ -1,21 +1,21 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef MCSEMA_BC_EXTERNAL_H_
|
||||
#define MCSEMA_BC_EXTERNAL_H_
|
||||
#pragma once
|
||||
|
||||
#include <llvm/IR/CallingConv.h>
|
||||
|
||||
@@ -30,8 +30,6 @@ namespace CallingConv {
|
||||
namespace mcsema {
|
||||
struct NativeModule;
|
||||
|
||||
void DeclareExternals(const NativeModule *cfg_module);
|
||||
//void DeclareExternals(const NativeModule *cfg_module);
|
||||
|
||||
} // namespace mcsema
|
||||
|
||||
#endif // MCSEMA_BC_EXTERNAL_H_
|
||||
|
||||
+1208
-544
File diff suppressed because it is too large
Load Diff
+12
-14
@@ -1,21 +1,21 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef MCSEMA_BC_FUNCTION_H_
|
||||
#define MCSEMA_BC_FUNCTION_H_
|
||||
#pragma once
|
||||
|
||||
namespace mcsema {
|
||||
struct NativeModule;
|
||||
@@ -25,5 +25,3 @@ void DeclareLiftedFunctions(const NativeModule *cfg_module);
|
||||
bool DefineLiftedFunctions(const NativeModule *cfg_module);
|
||||
|
||||
} // namespace mcsema
|
||||
|
||||
#endif // MCSEMA_BC_FUNCTION_H_
|
||||
|
||||
+85
-272
@@ -1,19 +1,22 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "Instruction.h"
|
||||
|
||||
#include <glog/logging.h>
|
||||
|
||||
#include <sstream>
|
||||
@@ -28,137 +31,69 @@
|
||||
#include <llvm/IR/Module.h>
|
||||
#include <llvm/IR/Type.h>
|
||||
|
||||
#include "Instruction.h"
|
||||
#include "remill/Arch/Arch.h"
|
||||
#include "remill/Arch/Instruction.h"
|
||||
#include "remill/BC/Util.h"
|
||||
|
||||
#include "mcsema/Arch/Arch.h"
|
||||
|
||||
#include "mcsema/BC/Callback.h"
|
||||
#include "mcsema/BC/Instruction.h"
|
||||
#include "mcsema/BC/Lift.h"
|
||||
#include "mcsema/BC/Util.h"
|
||||
|
||||
#include "mcsema/CFG/CFG.h"
|
||||
|
||||
|
||||
namespace mcsema {
|
||||
|
||||
namespace {
|
||||
|
||||
// Load the address of a register.
|
||||
static llvm::Value *LoadRegAddress(llvm::BasicBlock *block,
|
||||
std::string reg_name) {
|
||||
return remill::FindVarInFunction(block->getParent(), reg_name);
|
||||
}
|
||||
|
||||
// Load the value of a register.
|
||||
static llvm::Value *LoadRegValue(llvm::BasicBlock *block,
|
||||
std::string reg_name) {
|
||||
return new llvm::LoadInst(LoadRegAddress(block, reg_name), "", block);
|
||||
}
|
||||
|
||||
static llvm::Value *LoadAddressRegVal(llvm::BasicBlock *block,
|
||||
const remill::Operand::Register ®,
|
||||
llvm::ConstantInt *zero) {
|
||||
if (reg.name.empty()) {
|
||||
return zero;
|
||||
}
|
||||
|
||||
auto value = LoadRegValue(block, reg.name);
|
||||
auto value_type = llvm::dyn_cast<llvm::IntegerType>(value->getType());
|
||||
auto word_type = zero->getType();
|
||||
|
||||
CHECK(value_type)
|
||||
<< "Register " << reg.name << " expected to be an integer.";
|
||||
|
||||
auto value_size = value_type->getBitWidth();
|
||||
auto word_size = word_type->getBitWidth();
|
||||
CHECK(value_size <= word_size)
|
||||
<< "Register " << reg.name << " expected to be no larger than the "
|
||||
<< "machine word size (" << word_type->getBitWidth() << " bits).";
|
||||
|
||||
if (value_size < word_size) {
|
||||
value = new llvm::ZExtInst(value, word_type, "", block);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
static bool IsFramePointerReg(const remill::Operand::Register ®) {
|
||||
|
||||
if (reg.name.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (mcsema::gArch->IsAMD64()) {
|
||||
return reg.name == "RBP";
|
||||
} else if (mcsema::gArch->IsX86()) {
|
||||
return reg.name == "EBP";
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool IsStackPointerReg(const remill::Operand::Register ®) {
|
||||
|
||||
if (reg.name.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (mcsema::gArch->IsAMD64()) {
|
||||
return reg.name == "RSP";
|
||||
} else if (mcsema::gArch->IsX86()) {
|
||||
return reg.name == "ESP";
|
||||
} else if (mcsema::gArch->IsAArch64()) {
|
||||
return reg.name == "SP" || reg.name == "WSP";
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
InstructionLifter::~InstructionLifter(void) {}
|
||||
|
||||
InstructionLifter::InstructionLifter(const remill::IntrinsicTable *intrinsics_,
|
||||
TranslationContext &ctx_)
|
||||
: remill::InstructionLifter(gArch, intrinsics_),
|
||||
: remill::InstructionLifter(gArch.get(), intrinsics_),
|
||||
ctx(ctx_) {}
|
||||
|
||||
// Lift a single instruction into a basic block.
|
||||
remill::LiftStatus InstructionLifter::LiftIntoBlock(
|
||||
remill::Instruction &inst, llvm::BasicBlock *block_) {
|
||||
remill::Instruction &inst, llvm::BasicBlock *block_, bool is_delayed) {
|
||||
|
||||
inst_ptr = &inst;
|
||||
block = block_;
|
||||
mem_ref = GetAddress(ctx.cfg_inst->mem);
|
||||
imm_ref = GetMaskedAddress(ctx.cfg_inst->imm);
|
||||
disp_ref = GetMaskedAddress(ctx.cfg_inst->disp);
|
||||
|
||||
if (ctx.cfg_inst) {
|
||||
mem_ref = GetAddress(ctx.cfg_inst->mem);
|
||||
imm_ref = GetAddress(ctx.cfg_inst->imm);
|
||||
disp_ref = GetAddress(ctx.cfg_inst->disp);
|
||||
} else {
|
||||
mem_ref = nullptr;
|
||||
imm_ref = nullptr;
|
||||
disp_ref = nullptr;
|
||||
}
|
||||
|
||||
mem_ref_used = false;
|
||||
disp_ref_used = false;
|
||||
imm_ref_used = false;
|
||||
|
||||
auto status = this->remill::InstructionLifter::LiftIntoBlock(inst, block);
|
||||
auto status = this->remill::InstructionLifter::LiftIntoBlock(
|
||||
inst, block, is_delayed);
|
||||
|
||||
// If we have semantics for the instruction, then make sure that we were
|
||||
// able to match cross-reference information to the instruction's operands.
|
||||
if (remill::kLiftedInstruction == status) {
|
||||
if (mem_ref && !mem_ref_used) {
|
||||
LOG(FATAL)
|
||||
LOG(ERROR)
|
||||
<< "Unused memory reference operand to " << std::hex
|
||||
<< ctx.cfg_inst->mem->target_ea << " in instruction "
|
||||
<< inst.Serialize() << std::dec;
|
||||
}
|
||||
|
||||
if (imm_ref && !imm_ref_used) {
|
||||
LOG(FATAL)
|
||||
LOG(ERROR)
|
||||
<< "Unused immediate operand reference to " << std::hex
|
||||
<< ctx.cfg_inst->imm->target_ea << " in instruction "
|
||||
<< inst.Serialize() << std::dec;
|
||||
}
|
||||
|
||||
if (disp_ref && !disp_ref_used) {
|
||||
LOG(FATAL)
|
||||
LOG(ERROR)
|
||||
<< "Unused displacement operand reference to " << std::hex
|
||||
<< ctx.cfg_inst->disp->target_ea << " in instruction "
|
||||
<< inst.Serialize() << std::dec;
|
||||
@@ -168,149 +103,72 @@ remill::LiftStatus InstructionLifter::LiftIntoBlock(
|
||||
return status;
|
||||
}
|
||||
|
||||
llvm::Value *InstructionLifter::GetMaskedAddress(const NativeXref *cfg_xref) {
|
||||
auto addr = GetAddress(cfg_xref);
|
||||
if (!addr || !cfg_xref->mask) {
|
||||
return addr;
|
||||
}
|
||||
//// Returns `true` if a given cross-reference is self-referential. That is,
|
||||
//// we'll have something like `jmp cs:EnterCriticalSection`, which references
|
||||
//// `EnterCriticalSection` in the `.idata` section of a PE file. But this
|
||||
//// location is our only "place" for the external `EnterCriticalSection`, so
|
||||
//// we point it back at itself.
|
||||
//static bool IsSelfReferential(const NativeXref *cfg_xref) {
|
||||
// if (!cfg_xref->target_segment) {
|
||||
// return false;
|
||||
// }
|
||||
//
|
||||
// auto it = cfg_xref->target_segment->entries.find(cfg_xref->target_ea);
|
||||
// if (it == cfg_xref->target_segment->entries.end()) {
|
||||
// return false;
|
||||
// }
|
||||
//
|
||||
// const auto &entry = it->second;
|
||||
// if (!entry.xref) {
|
||||
// return false;
|
||||
// }
|
||||
//
|
||||
// return entry.xref->target_ea == entry.ea;
|
||||
//}
|
||||
|
||||
auto mask = llvm::ConstantInt::get(word_type, cfg_xref->mask);
|
||||
llvm::IRBuilder<> ir(block);
|
||||
return ir.CreateAnd(addr, mask);
|
||||
}
|
||||
|
||||
// Returns `true` if a given cross-reference is self-referential. That is,
|
||||
// we'll have something like `jmp cs:EnterCriticalSection`, which references
|
||||
// `EnterCriticalSection` in the `.idata` section of a PE file. But this
|
||||
// location is our only "place" for the external `EnterCriticalSection`, so
|
||||
// we point it back at itself.
|
||||
static bool IsSelfReferential(const NativeXref *cfg_xref) {
|
||||
if (!cfg_xref->target_segment) {
|
||||
return false;
|
||||
}
|
||||
|
||||
auto it = cfg_xref->target_segment->entries.find(cfg_xref->target_ea);
|
||||
if (it == cfg_xref->target_segment->entries.end()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto &entry = it->second;
|
||||
if (!entry.xref) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return entry.xref->target_ea == entry.ea;
|
||||
}
|
||||
|
||||
llvm::Value *InstructionLifter::GetAddress(const NativeXref *cfg_xref) {
|
||||
llvm::Value *InstructionLifter::GetAddress(
|
||||
const NativeInstructionXref *cfg_xref) {
|
||||
if (!cfg_xref) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
llvm::IRBuilder<> ir(block);
|
||||
if (auto cfg_func = cfg_xref->func) {
|
||||
llvm::Function *func = nullptr;
|
||||
llvm::Value *func_val = nullptr;
|
||||
|
||||
// If this is a lifted function, then create a wrapper around it. The
|
||||
// idea is that this reference to a lifted function can be leaked to
|
||||
// native code as a callback, and so native code calling it must be able
|
||||
// to swap into the lifted context.
|
||||
if (cfg_func->is_external) {
|
||||
if (IsSelfReferential(cfg_xref)) {
|
||||
LOG(WARNING)
|
||||
<< "Reference from " << std::hex << cfg_xref->ea
|
||||
<< " to self-referential function reference "
|
||||
<< cfg_xref->target_name << " at " << cfg_xref->target_ea
|
||||
<< " being lifted as address into "
|
||||
<< cfg_xref->target_segment->name << std::dec;
|
||||
|
||||
return LiftEA(cfg_xref->target_segment, cfg_xref->target_ea);
|
||||
|
||||
} else {
|
||||
func = gModule->getFunction(cfg_func->name);
|
||||
}
|
||||
} else {
|
||||
func = GetNativeToLiftedCallback(cfg_func);
|
||||
}
|
||||
|
||||
CHECK(func != nullptr)
|
||||
<< "Can't resolve reference to function "
|
||||
<< cfg_func->name << " from " << std::hex << inst_ptr->pc << std::dec;
|
||||
|
||||
func_val = func;
|
||||
|
||||
// Functions attributed with weak linkage may be defined, but aren't
|
||||
// necessarily. What you end up getting is code that checks if the function
|
||||
// pointer is non-null, and if so, calls the function.
|
||||
//
|
||||
// mov rax, cs:__gmon_start___ptr
|
||||
// test rax, rax
|
||||
//
|
||||
// In the CFG, we get `__gmon_start__` instead of `__gmon_start___ptr`,
|
||||
// but we don't want to actually read the machine code bytes of
|
||||
// `__gmon_start__`, which is likely to be an ELF thunk. So we throw in
|
||||
// an extra layer of indirection here.
|
||||
//
|
||||
#if 0
|
||||
// TODO(akshayk): Discuss a better solution to handle the weak external functions
|
||||
// It causes the garbage address for _ZNSt12out_of_rangeD1Ev
|
||||
|
||||
// TODO(pag): This is an awful hack for now that won't generalize.
|
||||
if (func->hasExternalWeakLinkage()) {
|
||||
LOG(ERROR)
|
||||
<< "Adding pseudo-load of weak function " << cfg_func->name
|
||||
<< " at " << std::hex << inst_ptr->pc << std::dec;
|
||||
|
||||
auto temp_loc = ir.CreateAlloca(func->getType());
|
||||
ir.CreateStore(func, temp_loc);
|
||||
func_val = temp_loc;
|
||||
}
|
||||
#endif
|
||||
|
||||
return ir.CreatePtrToInt(func_val, word_type);
|
||||
|
||||
} else if (auto cfg_var = cfg_xref->var) {
|
||||
if (cfg_var->address) {
|
||||
return cfg_var->address;
|
||||
}
|
||||
|
||||
LOG(ERROR)
|
||||
<< "Variable " << cfg_var->name << " at " << std::hex << cfg_var->ea
|
||||
<< std::dec << " was not lifted.";
|
||||
// Fall through.
|
||||
if (cfg_xref->mask) {
|
||||
return LiftXrefInCode(cfg_xref->target_ea & cfg_xref->mask);
|
||||
} else {
|
||||
return LiftXrefInCode(cfg_xref->target_ea);
|
||||
}
|
||||
|
||||
CHECK(cfg_xref->target_segment != nullptr)
|
||||
<< "A non-function, non-variable cross-reference from "
|
||||
<< std::hex << inst_ptr->pc << " to " << cfg_xref->target_ea << std::dec
|
||||
<< " must be in a known segment.";
|
||||
|
||||
return LiftEA(cfg_xref->target_segment, cfg_xref->target_ea);
|
||||
}
|
||||
|
||||
llvm::Value *InstructionLifter::LiftImmediateOperand(
|
||||
remill::Instruction &inst, llvm::BasicBlock *block,
|
||||
llvm::Argument *arg, remill::Operand &op) {
|
||||
auto arg_type = arg->getType();
|
||||
if (imm_ref) {
|
||||
if (imm_ref && !imm_ref_used) {
|
||||
imm_ref_used = true;
|
||||
|
||||
llvm::DataLayout data_layout(gModule.get());
|
||||
auto arg_size = data_layout.getTypeSizeInBits(arg_type);
|
||||
|
||||
CHECK(arg_size <= gArch->address_size)
|
||||
CHECK(arg_size <= arch->address_size)
|
||||
<< "Immediate operand size " << op.size << " of "
|
||||
<< op.Serialize() << " in instuction " << std::hex << inst.pc
|
||||
<< " is wider than the architecture pointer size ("
|
||||
<< std::dec << gArch->address_size << ").";
|
||||
<< std::dec << arch->address_size << ").";
|
||||
|
||||
if (arg_type != imm_ref->getType() && arg_size < gArch->address_size) {
|
||||
if (arg_type != imm_ref->getType() && arg_size < arch->address_size) {
|
||||
llvm::IRBuilder<> ir(block);
|
||||
imm_ref = ir.CreateTrunc(imm_ref, arg_type);
|
||||
}
|
||||
|
||||
return imm_ref;
|
||||
|
||||
} else if (op.size == arch->address_size &&
|
||||
4096 <= op.imm.val) {
|
||||
auto seg = ctx.cfg_module->TryGetSegment(op.imm.val);
|
||||
LOG_IF(WARNING, seg != nullptr)
|
||||
<< "Immediate operand '" << op.Serialize()
|
||||
<< "' of instruction " << inst.Serialize()
|
||||
<< " is a missed cross-reference candidate";
|
||||
}
|
||||
|
||||
return this->remill::InstructionLifter::LiftImmediateOperand(
|
||||
@@ -331,31 +189,6 @@ llvm::Value *InstructionLifter::LiftAddressOperand(
|
||||
inst, block, arg, op);
|
||||
}
|
||||
|
||||
// Check if the instruction is referring to stack variable
|
||||
if (ctx.cfg_inst->stack_var) {
|
||||
llvm::IRBuilder<> ir(block);
|
||||
auto base = ir.CreatePtrToInt(ctx.cfg_inst->stack_var->llvm_var, word_type);
|
||||
auto map_it = ctx.cfg_inst->stack_var->refs.find(ctx.cfg_inst->ea);
|
||||
if (map_it != ctx.cfg_inst->stack_var->refs.end()) {
|
||||
auto var_offset = llvm::ConstantInt::get(
|
||||
word_type, static_cast<uint64_t>(map_it->second), true);
|
||||
base = ir.CreateAdd(base, var_offset);
|
||||
LOG(INFO)
|
||||
<< "Lifting stack variable access at : " << std::hex << map_it->first
|
||||
<< " var_offset " << map_it->second << std::dec
|
||||
<< " variable name " << ctx.cfg_inst->stack_var->name;
|
||||
|
||||
if (!mem.index_reg.name.empty()) {
|
||||
auto zero = llvm::ConstantInt::get(word_type, 0, false);
|
||||
auto index = LoadAddressRegVal(block, mem.index_reg, zero);
|
||||
auto scale = llvm::ConstantInt::get(
|
||||
word_type, static_cast<uint64_t>(mem.scale), true);
|
||||
return ir.CreateAdd(base, ir.CreateMul(index, scale));
|
||||
}
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
if ((mem.base_reg.name.empty() && mem.index_reg.name.empty()) ||
|
||||
(mem.base_reg.name == "PC" && mem.index_reg.name.empty())) {
|
||||
|
||||
@@ -368,6 +201,18 @@ llvm::Value *InstructionLifter::LiftAddressOperand(
|
||||
return disp_ref;
|
||||
}
|
||||
|
||||
} else if ((mem.base_reg.name.empty() && mem.index_reg.name.empty()) ||
|
||||
(mem.base_reg.name == "NEXT_PC" && mem.index_reg.name.empty())) {
|
||||
|
||||
if (mem_ref) {
|
||||
mem_ref_used = true;
|
||||
return mem_ref;
|
||||
|
||||
} else if (disp_ref) {
|
||||
disp_ref_used = true;
|
||||
return disp_ref;
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
// It's a reference located in the displacement. We'll clear out the
|
||||
@@ -381,8 +226,8 @@ llvm::Value *InstructionLifter::LiftAddressOperand(
|
||||
llvm::IRBuilder<> ir(block);
|
||||
return ir.CreateAdd(dynamic_addr, disp_ref);
|
||||
|
||||
} else if (mem_ref && static_cast<uint64_t>(op.addr.displacement) ==
|
||||
ctx.cfg_inst->mem->target_ea) {
|
||||
} else if (mem_ref && (static_cast<uint64_t>(op.addr.displacement) ==
|
||||
ctx.cfg_inst->mem->target_ea)) {
|
||||
LOG(ERROR)
|
||||
<< "IDA probably incorrectly decoded memory operand "
|
||||
<< op.Serialize() << " of instruction " << std::hex << inst.pc
|
||||
@@ -401,36 +246,4 @@ llvm::Value *InstructionLifter::LiftAddressOperand(
|
||||
inst, block, arg, op);
|
||||
}
|
||||
|
||||
// Lift the register operand to a value.
|
||||
llvm::Value *InstructionLifter::LiftRegisterOperand(
|
||||
remill::Instruction &inst, llvm::BasicBlock *block,
|
||||
llvm::Argument *arg, remill::Operand &op) {
|
||||
|
||||
auto ® = op.reg;
|
||||
|
||||
// Check if the instruction is referring to the base pointer which
|
||||
// might be accessing stack variable indirectly
|
||||
if (ctx.cfg_inst->stack_var) {
|
||||
if ((IsFramePointerReg(reg) || IsStackPointerReg(reg)) &&
|
||||
(op.action == remill::Operand::kActionRead)) {
|
||||
llvm::IRBuilder<> ir(block);
|
||||
auto variable = ir.CreatePtrToInt(
|
||||
ctx.cfg_inst->stack_var->llvm_var, word_type);
|
||||
auto map_it = ctx.cfg_inst->stack_var->refs.find(ctx.cfg_inst->ea);
|
||||
if (map_it != ctx.cfg_inst->stack_var->refs.end()) {
|
||||
auto var_offset = llvm::ConstantInt::get(
|
||||
word_type, static_cast<uint64_t>(map_it->second), true);
|
||||
variable = ir.CreateAdd(variable, var_offset);
|
||||
}
|
||||
LOG(INFO)
|
||||
<< "Lifting stack variable reference at : " << std::hex
|
||||
<< ctx.cfg_inst->ea << std::dec;
|
||||
return variable;
|
||||
}
|
||||
}
|
||||
|
||||
return this->remill::InstructionLifter::LiftRegisterOperand(
|
||||
inst, block, arg, op);
|
||||
}
|
||||
|
||||
} // namespace mcsema
|
||||
|
||||
+16
-23
@@ -1,21 +1,21 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef MCSEMA_BC_INSTRUCTION_H_
|
||||
#define MCSEMA_BC_INSTRUCTION_H_
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
@@ -36,7 +36,7 @@ class IntrinsicTable;
|
||||
|
||||
namespace mcsema {
|
||||
|
||||
struct NativeXref;
|
||||
struct NativeInstructionXref;
|
||||
struct TranslationContext;
|
||||
|
||||
class InstructionLifter : public remill::InstructionLifter {
|
||||
@@ -48,7 +48,8 @@ class InstructionLifter : public remill::InstructionLifter {
|
||||
|
||||
// Lift a single instruction into a basic block.
|
||||
remill::LiftStatus LiftIntoBlock(remill::Instruction &inst,
|
||||
llvm::BasicBlock *block) override;
|
||||
llvm::BasicBlock *block,
|
||||
bool is_delayed) override;
|
||||
|
||||
protected:
|
||||
|
||||
@@ -62,15 +63,9 @@ class InstructionLifter : public remill::InstructionLifter {
|
||||
remill::Instruction &inst, llvm::BasicBlock *block,
|
||||
llvm::Argument *arg, remill::Operand &mem) override;
|
||||
|
||||
// Lift a register operand to a value.
|
||||
llvm::Value *LiftRegisterOperand(
|
||||
remill::Instruction &inst, llvm::BasicBlock *block,
|
||||
llvm::Argument *arg, remill::Operand ®) override;
|
||||
|
||||
private:
|
||||
|
||||
llvm::Value *GetAddress(const NativeXref *cfg_xref);
|
||||
llvm::Value *GetMaskedAddress(const NativeXref *cfg_xref);
|
||||
llvm::Value *GetAddress(const NativeInstructionXref *cfg_xref);
|
||||
|
||||
TranslationContext &ctx;
|
||||
|
||||
@@ -87,5 +82,3 @@ class InstructionLifter : public remill::InstructionLifter {
|
||||
};
|
||||
|
||||
} // namespace mcsema
|
||||
|
||||
#endif // MCSEMA_BC_INSTRUCTION_H_
|
||||
|
||||
+13
-33
@@ -1,19 +1,22 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "Legacy.h"
|
||||
|
||||
#include <gflags/gflags.h>
|
||||
#include <glog/logging.h>
|
||||
|
||||
@@ -45,24 +48,6 @@ namespace mcsema {
|
||||
namespace legacy {
|
||||
namespace {
|
||||
|
||||
// Remove calls to error-related intrinsics.
|
||||
static void ImplementErrorIntrinsic(const char *name) {
|
||||
auto func = gModule->getFunction(name);
|
||||
if (!func) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto void_type = llvm::Type::getVoidTy(*gContext);
|
||||
auto abort_func = gModule->getOrInsertFunction(
|
||||
"abort", llvm::FunctionType::get(void_type, false));
|
||||
|
||||
func->setLinkage(llvm::GlobalValue::InternalLinkage);
|
||||
|
||||
llvm::IRBuilder<> ir(llvm::BasicBlock::Create(*gContext, "", func));
|
||||
ir.CreateCall(abort_func);
|
||||
ir.CreateRet(remill::NthArgument(func, remill::kMemoryPointerArgNum));
|
||||
}
|
||||
|
||||
// Create the node for a `mcsema_real_eip` annotation.
|
||||
static llvm::MDNode *CreateInstAnnotation(llvm::Function *F, uint64_t addr) {
|
||||
auto addr_val = llvm::ConstantInt::get(gWordType, addr);
|
||||
@@ -146,10 +131,5 @@ void PropagateInstAnnotations(void) {
|
||||
}
|
||||
}
|
||||
|
||||
void DowngradeModule(void) {
|
||||
ImplementErrorIntrinsic("__remill_error");
|
||||
ImplementErrorIntrinsic("__remill_missing_block");
|
||||
}
|
||||
|
||||
} // namespace legacy
|
||||
} // namespace mcsema
|
||||
|
||||
+12
-15
@@ -1,21 +1,21 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef MCSEMA_BC_LEGACY_H_
|
||||
#define MCSEMA_BC_LEGACY_H_
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
@@ -25,8 +25,6 @@ class Function;
|
||||
namespace mcsema {
|
||||
namespace legacy {
|
||||
|
||||
void DowngradeModule(void);
|
||||
|
||||
// Create a `mcsema_real_eip` annotation, and annotate every unannotated
|
||||
// instruction with this new annotation.
|
||||
void AnnotateInsts(llvm::Function *func, uint64_t pc);
|
||||
@@ -37,4 +35,3 @@ void PropagateInstAnnotations(void);
|
||||
} // namespace legacy
|
||||
} // namespace mcsema
|
||||
|
||||
#endif // MCSEMA_BC_LEGACY_H_
|
||||
|
||||
+98
-58
@@ -1,19 +1,22 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "Lift.h"
|
||||
|
||||
#include <gflags/gflags.h>
|
||||
#include <glog/logging.h>
|
||||
|
||||
@@ -55,7 +58,6 @@
|
||||
#include "mcsema/BC/External.h"
|
||||
#include "mcsema/BC/Function.h"
|
||||
#include "mcsema/BC/Legacy.h"
|
||||
#include "mcsema/BC/Lift.h"
|
||||
#include "mcsema/BC/Optimize.h"
|
||||
#include "mcsema/BC/Segment.h"
|
||||
#include "mcsema/BC/Util.h"
|
||||
@@ -70,22 +72,32 @@ namespace {
|
||||
|
||||
// Add entrypoint functions for any exported functions.
|
||||
static void ExportFunctions(const NativeModule *cfg_module) {
|
||||
for (auto ea : cfg_module->exported_funcs) {
|
||||
auto cfg_func = cfg_module->ea_to_func.at(ea)->Get();
|
||||
CHECK(gModule->getFunction(cfg_func->lifted_name) != nullptr)
|
||||
<< "Cannot find lifted version of exported function "
|
||||
<< cfg_func->lifted_name;
|
||||
for (auto [ea, cfg_func] : cfg_module->ea_to_func) {
|
||||
(void) ea;
|
||||
|
||||
LOG(INFO)
|
||||
<< "Exporting function " << cfg_func->name;
|
||||
if (cfg_func->function) {
|
||||
cfg_func->function = gModule->getFunction(cfg_func->name);
|
||||
}
|
||||
|
||||
auto ep = GetNativeToLiftedEntryPoint(cfg_func);
|
||||
ep->setLinkage(llvm::GlobalValue::ExternalLinkage);
|
||||
ep->setVisibility(llvm::GlobalValue::DefaultVisibility);
|
||||
|
||||
remill::TieFunctions(ep, gModule->getFunction(cfg_func->lifted_name));
|
||||
remill::Annotate<remill::EntrypointFunction>(ep);
|
||||
if (auto ep = cfg_func->function; ep) {
|
||||
if (cfg_func->is_exported) {
|
||||
LOG(INFO)
|
||||
<< "Exporting function " << cfg_func->name;
|
||||
// remill::TieFunctions(ep, gModule->getFunction(cfg_func->lifted_name));
|
||||
remill::Annotate<remill::EntrypointFunction>(ep);
|
||||
ep->setLinkage(llvm::GlobalValue::ExternalLinkage);
|
||||
ep->setVisibility(llvm::GlobalValue::DefaultVisibility);
|
||||
|
||||
} else {
|
||||
ep->setVisibility(llvm::GlobalValue::HiddenVisibility);
|
||||
ep->setLinkage(llvm::GlobalValue::PrivateLinkage);
|
||||
if (!ep->hasNUsesOrMore(1)) {
|
||||
LOG(INFO)
|
||||
<< "Removing function " << cfg_func->name;
|
||||
ep->eraseFromParent();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,7 +146,8 @@ static void DefineDebugGetRegState(void) {
|
||||
|
||||
auto state_ptr_type = reg_state->getType();
|
||||
auto reg_func_type = llvm::FunctionType::get(state_ptr_type, false);
|
||||
// ExternalWeakLinkage causes crash with --explicit_args. The function is not available in the library
|
||||
// ExternalWeakLinkage causes crash with --explicit_args. The function is not
|
||||
// available in the library
|
||||
get_reg_state = llvm::Function::Create(
|
||||
reg_func_type, llvm::GlobalValue::ExternalLinkage,
|
||||
"__mcsema_debug_get_reg_state", gModule.get());
|
||||
@@ -146,43 +159,81 @@ static void DefineDebugGetRegState(void) {
|
||||
get_reg_state->addFnAttr(llvm::Attribute::OptimizeNone);
|
||||
}
|
||||
|
||||
// Define some of the remill error intrinsics.
|
||||
static void DefineErrorIntrinsics(llvm::FunctionType *lifted_func_type) {
|
||||
const char *func_names[] = {"__remill_error", "__remill_missing_block"};
|
||||
auto trap = llvm::Intrinsic::getDeclaration(gModule.get(), llvm::Intrinsic::trap);
|
||||
for (auto func_name : func_names) {
|
||||
auto func = gModule->getFunction(func_name);
|
||||
if (!func) {
|
||||
continue;
|
||||
}
|
||||
if (func->isDeclaration()) {
|
||||
llvm::IRBuilder<> ir(llvm::BasicBlock::Create(*gContext, "", func));
|
||||
ir.CreateCall(trap);
|
||||
ir.CreateUnreachable();
|
||||
}
|
||||
// Remove calls to error-related intrinsics.
|
||||
static void ImplementErrorIntrinsic(const char *name) {
|
||||
auto func = gModule->getFunction(name);
|
||||
if (!func || !func->isDeclaration()) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto void_type = llvm::Type::getVoidTy(*gContext);
|
||||
auto abort_func = gModule->getFunction("abort");
|
||||
if (!abort_func) {
|
||||
abort_func = llvm::Function::Create(
|
||||
llvm::FunctionType::get(void_type, false),
|
||||
llvm::GlobalValue::ExternalLinkage,
|
||||
"abort",
|
||||
gModule.get());
|
||||
|
||||
abort_func->addFnAttr(llvm::Attribute::NoReturn);
|
||||
|
||||
// Might be an externally-defined function :-/
|
||||
} else if (abort_func->getFunctionType()->getNumParams() ||
|
||||
!abort_func->getFunctionType()->getReturnType()->isVoidTy()) {
|
||||
abort_func = llvm::Intrinsic::getDeclaration(
|
||||
gModule.get(), llvm::Intrinsic::trap);
|
||||
}
|
||||
|
||||
func->setLinkage(llvm::GlobalValue::InternalLinkage);
|
||||
func->removeFnAttr(llvm::Attribute::NoInline);
|
||||
func->removeFnAttr(llvm::Attribute::OptimizeNone);
|
||||
func->addFnAttr(llvm::Attribute::NoReturn);
|
||||
func->addFnAttr(llvm::Attribute::InlineHint);
|
||||
func->addFnAttr(llvm::Attribute::AlwaysInline);
|
||||
|
||||
llvm::IRBuilder<> ir(llvm::BasicBlock::Create(*gContext, "", func));
|
||||
|
||||
ir.CreateCall(abort_func);
|
||||
ir.CreateUnreachable();
|
||||
}
|
||||
|
||||
// Define some of the remill error intrinsics.
|
||||
static void DefineErrorIntrinsics(void) {
|
||||
ImplementErrorIntrinsic("__remill_error");
|
||||
ImplementErrorIntrinsic("__remill_missing_block");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool LiftCodeIntoModule(const NativeModule *cfg_module) {
|
||||
TranslationContext::TranslationContext(void) {}
|
||||
|
||||
DeclareExternals(cfg_module);
|
||||
TranslationContext::~TranslationContext(void) {}
|
||||
|
||||
bool LiftCodeIntoModule(const NativeModule *cfg_module) {
|
||||
DeclareLiftedFunctions(cfg_module);
|
||||
|
||||
DeclareDataSegments(cfg_module);
|
||||
// Lift the blocks of instructions into the declared functions.
|
||||
if (!DefineLiftedFunctions(cfg_module)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
DefineErrorIntrinsics();
|
||||
|
||||
// Optimize the lifted bitcode.
|
||||
OptimizeModule(cfg_module);
|
||||
|
||||
// Segments are only filled in after the lifted function declarations,
|
||||
// external vars, and segments are declared so that cross-references to
|
||||
// lifted things can be resolved.
|
||||
DefineDataSegments(cfg_module);
|
||||
|
||||
auto lifted_func_type = remill::LiftedFunctionType(gModule.get());
|
||||
// Generate code to call pre-`main` function static object constructors, and
|
||||
// post-`main` functions destructors.
|
||||
CallInitFiniCode(cfg_module);
|
||||
|
||||
// Lift the blocks of instructions into the declared functions.
|
||||
if (!DefineLiftedFunctions(cfg_module)) {
|
||||
return false;
|
||||
}
|
||||
// Remove leftover Remill intrinsics, and lower memory access intrincis into
|
||||
// `load` and `store` instructions.
|
||||
CleanUpModule(cfg_module);
|
||||
|
||||
// Add entrypoint functions for any exported functions.
|
||||
ExportFunctions(cfg_module);
|
||||
@@ -190,20 +241,9 @@ bool LiftCodeIntoModule(const NativeModule *cfg_module) {
|
||||
// Export any variables that should be externally visible.
|
||||
ExportVariables(cfg_module);
|
||||
|
||||
// Generate code to call pre-`main` function static object constructors, and
|
||||
// post-`main` functions destructors.
|
||||
CallInitFiniCode(cfg_module);
|
||||
|
||||
if (FLAGS_legacy_mode) {
|
||||
legacy::DowngradeModule();
|
||||
}
|
||||
|
||||
OptimizeModule();
|
||||
|
||||
if (FLAGS_explicit_args) {
|
||||
DefineGCCStackGuard();
|
||||
DefineDebugGetRegState();
|
||||
DefineErrorIntrinsics(lifted_func_type);
|
||||
}
|
||||
|
||||
if (!FLAGS_pc_annotation.empty()) {
|
||||
|
||||
+39
-20
@@ -1,31 +1,38 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef MCSEMA_BC_LIFT_H_
|
||||
#define MCSEMA_BC_LIFT_H_
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "remill/Arch/Instruction.h"
|
||||
|
||||
namespace remill {
|
||||
class InstructionLifter;
|
||||
} // namespace remill
|
||||
|
||||
namespace llvm {
|
||||
class AllocaInst;
|
||||
class BasicBlock;
|
||||
class Function;
|
||||
class Value;
|
||||
} // namespace llvm
|
||||
|
||||
namespace mcsema {
|
||||
@@ -34,20 +41,32 @@ struct NativeModule;
|
||||
struct NativeFunction;
|
||||
struct NativeBlock;
|
||||
struct NativeInstruction;
|
||||
struct NativePreservedRegisters;
|
||||
|
||||
struct TranslationContext {
|
||||
remill::InstructionLifter *lifter;
|
||||
const NativeModule *cfg_module;
|
||||
const NativeFunction *cfg_func;
|
||||
const NativeBlock *cfg_block;
|
||||
const NativeInstruction *cfg_inst;
|
||||
llvm::Function *lifted_func;
|
||||
TranslationContext(void);
|
||||
~TranslationContext(void);
|
||||
|
||||
remill::InstructionLifter *lifter = nullptr;
|
||||
const NativeModule *cfg_module = nullptr;
|
||||
const NativeFunction *cfg_func = nullptr;
|
||||
const NativeBlock *cfg_block = nullptr;
|
||||
const NativeInstruction *cfg_inst = nullptr;
|
||||
llvm::Function *lifted_func = nullptr;
|
||||
std::unordered_map<uint64_t, llvm::BasicBlock *> ea_to_block;
|
||||
std::unordered_map<uint64_t, llvm::BasicBlock *> lp_to_block;
|
||||
std::vector<std::pair<llvm::Value *, llvm::Value *>> preserved_regs;
|
||||
std::unordered_map<uint64_t, const NativePreservedRegisters *>
|
||||
func_preserved_regs;
|
||||
remill::Instruction inst;
|
||||
remill::Instruction delayed_inst;
|
||||
std::vector<std::tuple<uint64_t, bool, uint64_t>> work_list;
|
||||
|
||||
llvm::BasicBlock *entry_block{nullptr};
|
||||
llvm::Value *stack_ptr_var{nullptr};
|
||||
llvm::Value *frame_ptr_var{nullptr};
|
||||
};
|
||||
|
||||
bool LiftCodeIntoModule(const NativeModule *cfg_module);
|
||||
|
||||
} // namespace mcsema
|
||||
|
||||
#endif // MCSEMA_BC_LIFT_H_
|
||||
|
||||
+1671
-148
File diff suppressed because it is too large
Load Diff
+18
-15
@@ -1,26 +1,29 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef MCSEMA_BC_OPTIMIZE_H_
|
||||
#define MCSEMA_BC_OPTIMIZE_H_
|
||||
#pragma once
|
||||
|
||||
namespace mcsema {
|
||||
|
||||
void OptimizeModule(void);
|
||||
struct NativeModule;
|
||||
|
||||
void OptimizeModule(const NativeModule *cfg_module);
|
||||
|
||||
// Remove some of the Remill intrinsics.
|
||||
void CleanUpModule(const NativeModule *cfg_module);
|
||||
|
||||
} // namespace mcsema
|
||||
|
||||
#endif // MCSEMA_BC_OPTIMIZE_H_
|
||||
|
||||
+337
-257
@@ -1,23 +1,27 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "mcsema/BC/Segment.h"
|
||||
|
||||
#include <gflags/gflags.h>
|
||||
#include <glog/logging.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <iomanip>
|
||||
#include <limits>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
@@ -36,9 +40,7 @@
|
||||
#include <remill/BC/Util.h>
|
||||
|
||||
#include "mcsema/Arch/Arch.h"
|
||||
#include "mcsema/Arch/ABI.h"
|
||||
#include "mcsema/BC/Callback.h"
|
||||
#include "mcsema/BC/Segment.h"
|
||||
#include "mcsema/BC/Util.h"
|
||||
#include "mcsema/CFG/CFG.h"
|
||||
|
||||
@@ -57,25 +59,23 @@ DEFINE_string(libc_destructor, "",
|
||||
"function returns. For example, on GNU-based systems, this is "
|
||||
"typically `__libc_csu_fini`.");
|
||||
|
||||
DEFINE_bool(force_embed_data_refs, false,
|
||||
"Should data-to-code and data-to-data cross-references be force-"
|
||||
"embedded within data segments? This is a good option to enable "
|
||||
"when using McSema-produced bitcode in KLEE, as it avoids doing "
|
||||
"lazy cross-reference initialization.");
|
||||
|
||||
DECLARE_bool(disable_aliases);
|
||||
|
||||
namespace mcsema {
|
||||
namespace {
|
||||
|
||||
// Returns `true` if all the bytes in `data` are zero.
|
||||
static bool IsZero(const std::string &data) {
|
||||
for (auto b : data) {
|
||||
if (b) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Lets us decide if we can use a constant aggregate zero value, i.e.
|
||||
// direct LLVM to put this data into the `.bss` segment.
|
||||
static bool IsZero(const NativeSegment *cfg_seg) {
|
||||
for (const auto &cfg_seg_entry : cfg_seg->entries) {
|
||||
auto &entry = cfg_seg_entry.second;
|
||||
if (!entry.blob || !IsZero(entry.blob->data)) {
|
||||
const auto &entry = cfg_seg_entry.second;
|
||||
if (!entry.blob || !entry.blob->is_zero) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -86,19 +86,38 @@ static bool IsZero(const NativeSegment *cfg_seg) {
|
||||
// byte arrays, interspersed with cross-references, which will be represented
|
||||
// as (pointers casted to) integers.
|
||||
static llvm::StructType *GetSegmentType(const NativeSegment *cfg_seg) {
|
||||
std::stringstream ss;
|
||||
ss << cfg_seg->lifted_name << "_type";
|
||||
const auto type_name = ss.str();
|
||||
|
||||
auto seg_type = gModule->getTypeByName(type_name);
|
||||
if (seg_type) {
|
||||
return seg_type;
|
||||
}
|
||||
|
||||
std::vector<llvm::Type *> entry_types;
|
||||
|
||||
auto byte_type = llvm::Type::getInt8Ty(*gContext);
|
||||
|
||||
if (cfg_seg->padding) {
|
||||
auto arr_type = llvm::ArrayType::get(byte_type, cfg_seg->padding);
|
||||
entry_types.push_back(arr_type);
|
||||
}
|
||||
|
||||
for (const auto &cfg_seg_entry : cfg_seg->entries) {
|
||||
auto &entry = cfg_seg_entry.second;
|
||||
const auto &entry = cfg_seg_entry.second;
|
||||
if (entry.blob) {
|
||||
auto arr_type = llvm::ArrayType::get(byte_type, entry.blob->data.size());
|
||||
auto arr_type = llvm::ArrayType::get(byte_type, entry.blob->size);
|
||||
entry_types.push_back(arr_type);
|
||||
|
||||
} else if (entry.xref) {
|
||||
auto val_type = llvm::Type::getIntNTy(
|
||||
*gContext, static_cast<unsigned>(entry.xref->width * 8));
|
||||
entry_types.push_back(val_type);
|
||||
const auto entry_size = entry.xref->width * 8;
|
||||
if (entry_size == gArch->address_size) {
|
||||
entry_types.push_back(llvm::Type::getInt8PtrTy(*gContext, 0));
|
||||
} else {
|
||||
entry_types.push_back(llvm::Type::getIntNTy(
|
||||
*gContext, static_cast<unsigned>(entry_size)));
|
||||
}
|
||||
|
||||
} else {
|
||||
LOG(FATAL)
|
||||
@@ -107,17 +126,14 @@ static llvm::StructType *GetSegmentType(const NativeSegment *cfg_seg) {
|
||||
}
|
||||
}
|
||||
|
||||
std::stringstream ss;
|
||||
ss << cfg_seg->lifted_name << "_type";
|
||||
|
||||
auto seg_type = llvm::StructType::create(entry_types, ss.str(), true);
|
||||
seg_type = llvm::StructType::create(entry_types, type_name, true);
|
||||
CHECK(nullptr != seg_type)
|
||||
<< "Unable to create structure type for segment " << cfg_seg->name
|
||||
<< " beginning at " << std::hex << cfg_seg->ea;
|
||||
|
||||
llvm::DataLayout data_layout(gModule.get());
|
||||
auto seg_size = data_layout.getTypeAllocSize(seg_type);
|
||||
CHECK(seg_size == cfg_seg->size)
|
||||
CHECK_EQ(seg_size, (cfg_seg->size + cfg_seg->padding))
|
||||
<< "Size of structure type of segment " << cfg_seg->name
|
||||
<< " is " << seg_size << " but was expected to be " << cfg_seg->size;
|
||||
|
||||
@@ -127,80 +143,12 @@ static llvm::StructType *GetSegmentType(const NativeSegment *cfg_seg) {
|
||||
static llvm::GlobalValue::ThreadLocalMode ThreadLocalMode(
|
||||
const NativeObject *cfg_obj) {
|
||||
if (cfg_obj->is_thread_local) {
|
||||
return llvm::GlobalValue::GeneralDynamicTLSModel;
|
||||
return llvm::GlobalValue::InitialExecTLSModel;
|
||||
} else {
|
||||
return llvm::GlobalValue::NotThreadLocal;
|
||||
}
|
||||
}
|
||||
|
||||
static llvm::GlobalVariable *GlobalVariable(
|
||||
const NativeSegment *cfg_seg, std::string lifted_name) {
|
||||
auto seg_type = GetSegmentType(cfg_seg);
|
||||
|
||||
auto seg_var = new llvm::GlobalVariable(
|
||||
*gModule, seg_type, cfg_seg->is_read_only,
|
||||
llvm::GlobalValue::InternalLinkage, nullptr,
|
||||
lifted_name, nullptr, ThreadLocalMode(cfg_seg));
|
||||
|
||||
if (cfg_seg->is_exported) {
|
||||
seg_var->setLinkage(llvm::GlobalValue::ExternalLinkage);
|
||||
}
|
||||
|
||||
return seg_var;
|
||||
}
|
||||
|
||||
// Declare a data segment, and return a global value pointing to that segment.
|
||||
static void DeclareSegment(const NativeSegment *cfg_seg) {
|
||||
cfg_seg->seg_var = gModule->getGlobalVariable(cfg_seg->lifted_name);
|
||||
|
||||
if (cfg_seg->seg_var) {
|
||||
// If the variable is exported and zero initialized (not having xrefs),
|
||||
// No need to initialize these variables
|
||||
if (cfg_seg->is_exported && cfg_seg->seg_var->hasExternalLinkage()) {
|
||||
cfg_seg->needs_initializer = !IsZero(cfg_seg);
|
||||
} else {
|
||||
// If there is a variable with the same name, rename the variable
|
||||
// and set the needs_initializer flag;
|
||||
std::stringstream ss;
|
||||
ss << "internal_" << cfg_seg->lifted_name;
|
||||
cfg_seg->seg_var = GlobalVariable(cfg_seg, ss.str());
|
||||
|
||||
LOG(ERROR)
|
||||
<< "Segment variable '" << cfg_seg->lifted_name
|
||||
<< "' was already defined";
|
||||
|
||||
cfg_seg->needs_initializer = true;
|
||||
}
|
||||
} else {
|
||||
cfg_seg->seg_var = GlobalVariable(cfg_seg, cfg_seg->lifted_name);
|
||||
}
|
||||
}
|
||||
|
||||
// Declare named variables that point into the data segment. The program being
|
||||
// lifted may have cross-references that addresses meaningfully named (global)
|
||||
// variables within a segment, so we want to try to preserve those names,
|
||||
// treating them as GEPs into the segment's data.
|
||||
static void DeclareVariables(const NativeModule *cfg_module) {
|
||||
for (auto &entry : cfg_module->ea_to_var) {
|
||||
auto cfg_var = reinterpret_cast<const NativeVariable *>(
|
||||
entry.second->Get());
|
||||
|
||||
if (cfg_var && cfg_var->is_external) {
|
||||
continue;
|
||||
}
|
||||
|
||||
CHECK(cfg_var && cfg_var->segment && !cfg_var->name.empty())
|
||||
<< "Invalid variable at " << std::hex << entry.first;
|
||||
|
||||
auto cfg_seg = cfg_var->segment;
|
||||
CHECK(cfg_var->ea >= cfg_seg->ea)
|
||||
<< "Variable " << cfg_var->name << " at " << std::hex << cfg_var->ea
|
||||
<< " is incorrectly assigned to the segment " << cfg_seg->name;
|
||||
|
||||
cfg_var->address = LiftEA(cfg_seg, cfg_var->ea);
|
||||
}
|
||||
}
|
||||
|
||||
// Create a McSema-specific constructor/destructor function, and add it to the
|
||||
// corresponding LLVM-specific array.
|
||||
static llvm::Function *CreateMcSemaInitFiniImpl(
|
||||
@@ -274,15 +222,13 @@ static llvm::Function *CreateMcSemaInitFiniImpl(
|
||||
|
||||
static llvm::Function *GetOrCreateMcSemaConstructor(void) {
|
||||
static llvm::Function *gInitFunc = nullptr;
|
||||
if (!gInitFunc) {
|
||||
gInitFunc = CreateMcSemaInitFiniImpl(
|
||||
"__mcsema_constructor", "llvm.global_ctors");
|
||||
|
||||
// Make sure that the `__mcsema_constructor` calls the xref initializer
|
||||
// as it's first thing.
|
||||
llvm::IRBuilder<> ir(&(gInitFunc->front().front()));
|
||||
ir.CreateCall(GetOrCreateMcSemaInitializer());
|
||||
if (gInitFunc) {
|
||||
return gInitFunc;
|
||||
}
|
||||
|
||||
gInitFunc = CreateMcSemaInitFiniImpl(
|
||||
"__mcsema_constructor", "llvm.global_ctors");
|
||||
|
||||
return gInitFunc;
|
||||
}
|
||||
|
||||
@@ -313,28 +259,33 @@ static llvm::Function *GetOrCreateMcSemaDestructor(void) {
|
||||
// handle them by emulating this runtime initialization. We create a special
|
||||
// constructor function of our own, `__mcsema_constructor`, that will contain
|
||||
// code that can do these initializations.
|
||||
static void LazyInitXRef(const NativeXref *xref, llvm::Type *extern_addr_type,
|
||||
static void LazyInitXRef(const NativeXref *xref,
|
||||
llvm::Constant *target_addr_const) {
|
||||
auto init_func = GetOrCreateMcSemaInitializer();
|
||||
llvm::BasicBlock *block = &init_func->back();
|
||||
llvm::IRBuilder<> ir(block);
|
||||
ir.SetInsertPoint(&block->front());
|
||||
|
||||
auto seg = xref->segment->seg_var;
|
||||
if (seg->isConstant()) {
|
||||
if (xref->segment->is_external) {
|
||||
LOG(ERROR)
|
||||
<< "Ignoring lazy initialization of cross-reference to "
|
||||
<< std::hex << xref->target_ea << " at " << xref->ea
|
||||
<< " in external segment '" << xref->segment->name << "' at "
|
||||
<< xref->segment->ea << std::dec;
|
||||
return;
|
||||
}
|
||||
|
||||
auto seg = llvm::dyn_cast<llvm::GlobalVariable>(xref->segment->Pointer());
|
||||
if (seg->isConstant()) {
|
||||
LOG(WARNING)
|
||||
<< "Marking " << seg->getName().str() << " as non-constant to "
|
||||
<< "support lazy initialization of reference to " << xref->target_name
|
||||
<< " from " << std::hex << xref->ea;
|
||||
<< "support lazy initialization of reference to " << std::hex
|
||||
<< xref->target_ea << " from " << xref->ea << std::dec;
|
||||
seg->setConstant(false);
|
||||
}
|
||||
|
||||
if (!target_addr_const || target_addr_const->isNullValue()) {
|
||||
LOG_IF(FATAL, !xref->var)
|
||||
<< "Cannot perform lazy relocation of non-variable cross-reference "
|
||||
<< "from " << std::hex << xref->ea << " to " << xref->target_ea
|
||||
<< std::dec << " (" << xref->target_name << ")";
|
||||
target_addr_const = xref->var->address;
|
||||
if (target_addr_const->isNullValue()) {
|
||||
return;
|
||||
}
|
||||
|
||||
llvm::Value *target_addr = target_addr_const;
|
||||
@@ -343,8 +294,8 @@ static void LazyInitXRef(const NativeXref *xref, llvm::Type *extern_addr_type,
|
||||
case NativeXref::kAbsoluteFixup: {
|
||||
CHECK(!xref->var || !xref->var->is_thread_local)
|
||||
<< "Cannot do absolute fixup from " << std::hex << xref->ea
|
||||
<< " to thread-local variable " << xref->target_name << " at "
|
||||
<< std::hex << xref->target_ea;
|
||||
<< " to thread-local variable at "
|
||||
<< std::hex << xref->target_ea << std::dec;
|
||||
// `target_addr` already has the right value.
|
||||
break;
|
||||
}
|
||||
@@ -352,13 +303,12 @@ static void LazyInitXRef(const NativeXref *xref, llvm::Type *extern_addr_type,
|
||||
case NativeXref::kThreadLocalOffsetFixup: {
|
||||
CHECK(xref->var != nullptr)
|
||||
<< "Non-variable thread-local cross-reference from "
|
||||
<< std::hex << xref->ea << " to " << xref->target_ea << std::dec
|
||||
<< " (" << xref->target_name << ")";
|
||||
<< std::hex << xref->ea << " to " << xref->target_ea << std::dec;
|
||||
|
||||
CHECK(xref->var->is_thread_local)
|
||||
<< "Cannot do thread-local fixup from " << std::hex << xref->ea
|
||||
<< " to non-thread-local variable " << xref->target_name << " at "
|
||||
<< std::hex << xref->target_ea;
|
||||
<< " to non-thread-local variable at "
|
||||
<< std::hex << xref->target_ea << std::dec;
|
||||
|
||||
static llvm::Value *thread_base = nullptr;
|
||||
if (!thread_base) {
|
||||
@@ -369,40 +319,45 @@ static void LazyInitXRef(const NativeXref *xref, llvm::Type *extern_addr_type,
|
||||
}
|
||||
}
|
||||
|
||||
if (xref->width < gArch->address_size) {
|
||||
target_addr = ir.CreateTrunc(target_addr, extern_addr_type);
|
||||
}
|
||||
|
||||
auto addr_of_xref = LiftEA(xref->segment, xref->ea);
|
||||
auto ptr_to_xref = ir.CreateIntToPtr(
|
||||
addr_of_xref, llvm::PointerType::get(extern_addr_type, 0));
|
||||
|
||||
ir.CreateStore(target_addr, ptr_to_xref);
|
||||
auto addr_of_xref = LiftXrefInData(xref->segment, xref->ea, false);
|
||||
ir.CreateStore(target_addr, addr_of_xref);
|
||||
}
|
||||
|
||||
// Fill in the contents of the data segment.
|
||||
static llvm::Constant *FillDataSegment(const NativeSegment *cfg_seg,
|
||||
static llvm::Constant *FillDataSegment(const NativeModule *cfg_module,
|
||||
const NativeSegment *cfg_seg,
|
||||
llvm::StructType *seg_type) {
|
||||
if (IsZero(cfg_seg)) {
|
||||
return llvm::ConstantAggregateZero::get(seg_type);
|
||||
}
|
||||
|
||||
unsigned i = 0;
|
||||
|
||||
std::vector<llvm::Constant *> entry_vals;
|
||||
for (const auto &cfg_seg_entry : cfg_seg->entries) {
|
||||
|
||||
// We might add some padding on the beginning of this
|
||||
unsigned i = 0;
|
||||
if (cfg_seg->padding) {
|
||||
auto byte_type = llvm::Type::getInt8Ty(*gContext);
|
||||
auto arr_type = llvm::ArrayType::get(byte_type, cfg_seg->padding);
|
||||
entry_vals.push_back(llvm::ConstantAggregateZero::get(arr_type));
|
||||
++i;
|
||||
}
|
||||
|
||||
for (auto &cfg_seg_entry : cfg_seg->entries) {
|
||||
auto &entry = cfg_seg_entry.second;
|
||||
auto entry_type = seg_type->getContainedType(i++);
|
||||
|
||||
// This entry is an opaque sequence of bytes.
|
||||
if (entry.blob) {
|
||||
if (IsZero(entry.blob->data)) {
|
||||
if (entry.blob->is_zero) {
|
||||
entry_vals.push_back(llvm::ConstantAggregateZero::get(entry_type));
|
||||
|
||||
} else {
|
||||
} else if (auto bytes = cfg_module->FindBytes(entry.blob->ea, entry.blob->size);
|
||||
bytes && bytes.Size() == entry.blob->size) {
|
||||
|
||||
const llvm::StringRef str_data(bytes.ToString().data(), bytes.Size());
|
||||
auto data = llvm::ConstantDataArray::getString(
|
||||
*gContext, entry.blob->data, false /* AddNull */);
|
||||
*gContext, str_data, false /* AddNull */);
|
||||
|
||||
CHECK(data->getType() == entry_type)
|
||||
<< "Type mismatch: Got "
|
||||
@@ -411,94 +366,91 @@ static llvm::Constant *FillDataSegment(const NativeSegment *cfg_seg,
|
||||
<< remill::LLVMThingToString(entry_type);
|
||||
|
||||
entry_vals.push_back(data);
|
||||
|
||||
} else {
|
||||
LOG(ERROR)
|
||||
<< "Could not find data backing " << std::hex << entry.blob->ea
|
||||
<< std::dec << " in segment " << cfg_seg->name;
|
||||
entry_vals.push_back(llvm::ConstantAggregateZero::get(entry_type));
|
||||
}
|
||||
|
||||
// This entry is a cross-reference.
|
||||
} else {
|
||||
CHECK(nullptr != entry.xref)
|
||||
<< "Empty entry at " << std::hex << entry.ea
|
||||
<< " in segment " << cfg_seg->name;
|
||||
} else if (entry.xref) {
|
||||
|
||||
auto val_size = static_cast<unsigned>(entry.xref->width * 8);
|
||||
auto val_type = llvm::Type::getIntNTy(*gContext, val_size);
|
||||
auto &xref = entry.xref;
|
||||
llvm::Constant *val = nullptr;
|
||||
|
||||
CHECK(val_size <= gArch->address_size)
|
||||
CHECK((entry.xref->width * 8) <= gArch->address_size)
|
||||
<< "Cross-reference at " << std::hex
|
||||
<< xref->ea << " to " << std::hex << xref->target_ea
|
||||
<< " is too wide at " << entry.xref->width << " bytes";
|
||||
|
||||
CHECK(val_type == entry_type)
|
||||
<< entry.xref->width << "-byte cross-reference at " << std::hex
|
||||
<< xref->ea << " to " << std::hex << xref->target_ea
|
||||
<< " doesn't match the type of the segment entry "
|
||||
<< remill::LLVMThingToString(entry_type);
|
||||
auto be_lazy = false;
|
||||
|
||||
// Pointer to a (possibly external) function.
|
||||
if (auto cfg_func = xref->func) {
|
||||
if (cfg_func->is_external) {
|
||||
val = gModule->getFunction(cfg_func->name);
|
||||
} else {
|
||||
val = GetNativeToLiftedCallback(cfg_func);
|
||||
}
|
||||
|
||||
val = llvm::ConstantExpr::getPtrToInt(val, gWordType);
|
||||
CHECK(val != nullptr)
|
||||
<< "Can't insert cross reference to function "
|
||||
<< cfg_func->name << " at " << std::hex << cfg_seg_entry.first
|
||||
<< " in segment " << cfg_seg->name;
|
||||
if (xref->func) {
|
||||
const auto cfg_func = xref->func->Get();
|
||||
val = cfg_func->Pointer();
|
||||
|
||||
// Pointer to a global (possibly external) variable.
|
||||
} else if (auto cfg_var = xref->var) {
|
||||
if (cfg_var->is_external || cfg_var->is_thread_local) {
|
||||
LOG(INFO)
|
||||
<< "Adding runtime initializer for cross reference to variable "
|
||||
<< cfg_var->name << " at " << std::hex << cfg_seg_entry.first
|
||||
<< " in segment " << cfg_seg->name;
|
||||
LazyInitXRef(xref.get(), val_type, val);
|
||||
val = llvm::Constant::getNullValue(gWordType);
|
||||
} else {
|
||||
val = cfg_var->address;
|
||||
}
|
||||
|
||||
CHECK(val != nullptr)
|
||||
<< "Can't insert cross reference to variable "
|
||||
<< cfg_var->name << " at " << std::hex << cfg_seg_entry.first
|
||||
<< " in segment " << cfg_seg->name;
|
||||
} else if (xref->var) {
|
||||
const auto cfg_var = xref->var->Get();
|
||||
val = cfg_var->Pointer();
|
||||
be_lazy = cfg_var->is_external || cfg_var->is_thread_local;
|
||||
|
||||
// Pointer to an unnamed location inside of a data segment.
|
||||
} else if (xref->target_segment) {
|
||||
const auto target_seg = xref->target_segment;
|
||||
val = LiftXrefInData(target_seg, xref->target_ea, false);
|
||||
be_lazy = target_seg->is_external || target_seg->is_thread_local;
|
||||
|
||||
} else {
|
||||
val = LiftEA(xref->target_segment, xref->target_ea);
|
||||
}
|
||||
|
||||
// Scale and add the value in. We need to fit it to its original width.
|
||||
if (val_size > gArch->address_size) {
|
||||
val = llvm::ConstantExpr::getZExt(val, val_type);
|
||||
|
||||
// Pointer truncation is generating the weird code for static
|
||||
// initialization of segment variables which is causing problem
|
||||
// during recompilations. Use Lazy initialization of the variable
|
||||
// segXXXX__gcc_except_table
|
||||
// Wrongly generated static initializer looks like following:
|
||||
// .long _ZTI12out_of_range&-1
|
||||
// .long _ZTI17special_condition&-1
|
||||
} else if (val_size < gArch->address_size) {
|
||||
if (xref->var != nullptr) {
|
||||
LazyInitXRef(xref.get(), val_type, val);
|
||||
val = llvm::ConstantInt::getNullValue(val_type);
|
||||
val = llvm::ConstantInt::get(gWordType, xref->target_ea);
|
||||
if (entry_type->isPointerTy()) {
|
||||
val = llvm::ConstantExpr::getIntToPtr(val, entry_type);
|
||||
} else {
|
||||
val = llvm::ConstantExpr::getTrunc(val, val_type);
|
||||
val = llvm::ConstantExpr::getIntToPtr(
|
||||
val, llvm::Type::getInt8PtrTy(*gContext));
|
||||
}
|
||||
}
|
||||
|
||||
CHECK(val->getType() == entry_type)
|
||||
auto val_type = llvm::dyn_cast<llvm::PointerType>(val->getType());
|
||||
CHECK_NOTNULL(val_type);
|
||||
|
||||
if (val_type->getAddressSpace()) {
|
||||
val_type = llvm::PointerType::get(val_type->getElementType(), 0);
|
||||
val = llvm::ConstantExpr::getAddrSpaceCast(val, val_type);
|
||||
}
|
||||
|
||||
if (entry_type->isIntegerTy()) {
|
||||
val = llvm::ConstantExpr::getPtrToInt(val, gWordType);
|
||||
if ((gArch->address_size / 8) > xref->width) {
|
||||
val = llvm::ConstantExpr::getTrunc(val, entry_type);
|
||||
be_lazy = true;
|
||||
}
|
||||
|
||||
} else if (val_type != entry_type) {
|
||||
CHECK(entry_type->isPointerTy());
|
||||
val = llvm::ConstantExpr::getBitCast(val, entry_type);
|
||||
}
|
||||
|
||||
if (be_lazy && !FLAGS_force_embed_data_refs) {
|
||||
LazyInitXRef(xref.get(), val);
|
||||
val = llvm::Constant::getNullValue(entry_type);
|
||||
}
|
||||
|
||||
CHECK_EQ(val->getType(), entry_type)
|
||||
<< "Type mismatch: Got "
|
||||
<< remill::LLVMThingToString(val->getType())
|
||||
<< " but expected "
|
||||
<< remill::LLVMThingToString(entry_type);
|
||||
|
||||
entry_vals.push_back(val);
|
||||
|
||||
} else {
|
||||
LOG(FATAL)
|
||||
<< "Empty entry at " << std::hex << entry.ea
|
||||
<< " in segment " << cfg_seg->name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -506,68 +458,196 @@ static llvm::Constant *FillDataSegment(const NativeSegment *cfg_seg,
|
||||
}
|
||||
|
||||
// Fill all the data segments in a given region.
|
||||
static void FillSegment(const NativeSegment *cfg_seg) {
|
||||
auto seg = cfg_seg->seg_var;
|
||||
if (cfg_seg->needs_initializer) {
|
||||
CHECK_NOTNULL(seg);
|
||||
auto seg_type = llvm::dyn_cast<llvm::StructType>(remill::GetValueType(seg));
|
||||
|
||||
// This might be null if there are two lifted variables with same name and one of them is exported
|
||||
// and the exported variable is having xrefs or notnull.
|
||||
CHECK_NOTNULL(seg_type);
|
||||
seg->setInitializer(FillDataSegment(cfg_seg, seg_type));
|
||||
static void FillSegment(const NativeModule *cfg_module,
|
||||
const NativeSegment *cfg_seg) {
|
||||
if (cfg_seg->entries.empty()) {
|
||||
CHECK(cfg_seg->is_external && !cfg_seg->is_exported);
|
||||
return;
|
||||
}
|
||||
|
||||
auto seg = llvm::dyn_cast<llvm::GlobalVariable>(cfg_seg->Pointer());
|
||||
CHECK_NOTNULL(seg);
|
||||
if (seg->hasInitializer()) {
|
||||
return; // Already initialized, e.g. due to `->Get()`.
|
||||
}
|
||||
|
||||
auto seg_type = llvm::dyn_cast<llvm::StructType>(remill::GetValueType(seg));
|
||||
|
||||
// This might be null if there are two lifted variables with same name and
|
||||
// one of them is exported and the exported variable is having xrefs or
|
||||
// notnull.
|
||||
CHECK_NOTNULL(seg_type);
|
||||
seg->setInitializer(FillDataSegment(cfg_module, cfg_seg, seg_type));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
|
||||
llvm::Constant *NativeVariable::Pointer(void) const {
|
||||
CHECK(!is_external);
|
||||
CHECK_NOTNULL(segment);
|
||||
const auto cfg_seg = segment->Get();
|
||||
CHECK(!cfg_seg->is_external);
|
||||
|
||||
const auto &alias_name = is_exported && !name.empty() ? name : lifted_name;
|
||||
auto alias = gModule->getNamedAlias(alias_name);
|
||||
if (alias) {
|
||||
return alias;
|
||||
}
|
||||
|
||||
auto ret = LiftXrefInData(segment, ea, false /* cast_to_int */);
|
||||
if (!FLAGS_disable_aliases && is_exported) {
|
||||
auto ptr_type = llvm::dyn_cast<llvm::PointerType>(ret->getType());
|
||||
auto alias = llvm::GlobalAlias::create(
|
||||
ptr_type->getElementType(), ptr_type->getAddressSpace(),
|
||||
llvm::GlobalValue::ExternalLinkage, alias_name, ret, gModule.get());
|
||||
ret = alias;
|
||||
|
||||
module->AddNameToAddress(alias_name, ea);
|
||||
|
||||
if (cfg_seg->is_thread_local) {
|
||||
alias->setThreadLocalMode(llvm::GlobalValue::InitialExecTLSModel);
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
llvm::Constant *NativeVariable::Address(void) const {
|
||||
return llvm::ConstantExpr::getPtrToInt(Pointer(), gWordType);
|
||||
}
|
||||
|
||||
llvm::Constant *NativeSegment::Address(void) const {
|
||||
auto ret = llvm::ConstantExpr::getPtrToInt(Pointer(), gWordType);
|
||||
if (padding) {
|
||||
ret = llvm::ConstantExpr::getAdd(
|
||||
ret, llvm::ConstantInt::get(gWordType, padding));
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
llvm::Constant *NativeSegment::Pointer(void) const {
|
||||
const auto &var_name = (is_exported || is_external) ? name : lifted_name;
|
||||
|
||||
auto lifted_var = gModule->getGlobalVariable(
|
||||
var_name, true /* AllowInternal */);
|
||||
|
||||
if (lifted_var) {
|
||||
return lifted_var;
|
||||
}
|
||||
|
||||
module->AddNameToAddress(var_name, ea);
|
||||
|
||||
if (is_external) {
|
||||
LOG(INFO)
|
||||
<< "Adding external segment " << name << " at "
|
||||
<< std::hex << ea << std::dec;
|
||||
|
||||
llvm::Type* var_type = nullptr;
|
||||
|
||||
CHECK_NE(0, size)
|
||||
<< "The size of the external variable '" << name << "' at "
|
||||
<< std::hex << ea << std::dec << " cannot be zero";
|
||||
|
||||
// Handle external variables of up to 128 bits as intgers
|
||||
// Anything else is treated as an array of bytes
|
||||
switch(size) {
|
||||
case 0:
|
||||
// Why is this zero length? This should never happen
|
||||
// Attempt a fix and output a warning
|
||||
LOG(ERROR)
|
||||
<< "The variable '" << name << "' at " << std::hex << ea
|
||||
<< std::dec << " has size of zero; Assuming it should be size 1";
|
||||
var_type = llvm::Type::getInt8Ty(*gContext);
|
||||
break;
|
||||
case 1: // 8 bit integer
|
||||
case 2: // 16 bit integer
|
||||
case 4: // 32 bit integer
|
||||
case 8: // 64 bit integer
|
||||
case 16: // 128 bit integer
|
||||
var_type = llvm::Type::getIntNTy(
|
||||
*gContext, static_cast<unsigned>(size * 8u));
|
||||
break;
|
||||
|
||||
// An array of bytes
|
||||
default: {
|
||||
auto byte_type = llvm::Type::getInt8Ty(*gContext);
|
||||
var_type = llvm::ArrayType::get(
|
||||
byte_type, static_cast<unsigned>(size));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
lifted_var = new llvm::GlobalVariable(
|
||||
*gModule, var_type, false, llvm::GlobalValue::ExternalLinkage,
|
||||
nullptr, var_name, nullptr, ThreadLocalMode(this));
|
||||
|
||||
} else {
|
||||
const auto linkage = is_exported ?
|
||||
llvm::GlobalValue::ExternalLinkage :
|
||||
llvm::GlobalValue::InternalLinkage;
|
||||
LOG(INFO)
|
||||
<< "Adding internal segment " << name;
|
||||
|
||||
lifted_var = new llvm::GlobalVariable(
|
||||
*gModule, GetSegmentType(this), is_read_only,
|
||||
linkage, nullptr, var_name, nullptr,
|
||||
ThreadLocalMode(this));
|
||||
}
|
||||
|
||||
if (ea) {
|
||||
const auto alignment = 1u << __builtin_ctzl(ea - padding);
|
||||
#if LLVM_VERSION_NUMBER >= LLVM_VERSION(10, 0)
|
||||
lifted_var->setAlignment(llvm::MaybeAlign(alignment));
|
||||
#else
|
||||
lifted_var->setAlignment(alignment);
|
||||
#endif
|
||||
}
|
||||
|
||||
return lifted_var;
|
||||
}
|
||||
|
||||
llvm::Function *GetOrCreateMcSemaInitializer(void) {
|
||||
static llvm::Function *gInitFunc = nullptr;
|
||||
if (!gInitFunc) {
|
||||
LOG(INFO)
|
||||
<< "Creating __mcsema_early_init function to pre-initialize runtime.";
|
||||
|
||||
gInitFunc = llvm::Function::Create(
|
||||
llvm::FunctionType::get(llvm::Type::getVoidTy(*gContext), false),
|
||||
llvm::GlobalValue::InternalLinkage,
|
||||
"__mcsema_early_init", gModule.get());
|
||||
|
||||
auto bool_type = llvm::Type::getInt1Ty(*gContext);
|
||||
auto check_var = new llvm::GlobalVariable(
|
||||
*gModule, bool_type, false, llvm::GlobalValue::InternalLinkage,
|
||||
llvm::Constant::getNullValue(bool_type));
|
||||
|
||||
auto entry = llvm::BasicBlock::Create(*gContext, "", gInitFunc);
|
||||
auto already_done = llvm::BasicBlock::Create(*gContext, "", gInitFunc);
|
||||
auto lazy_xref = llvm::BasicBlock::Create(*gContext, "", gInitFunc);
|
||||
|
||||
llvm::IRBuilder<> ir(entry);
|
||||
|
||||
auto guard = ir.CreateLoad(check_var, true);
|
||||
ir.CreateCondBr(guard, already_done, lazy_xref);
|
||||
|
||||
ir.SetInsertPoint(already_done);
|
||||
ir.CreateRetVoid();
|
||||
|
||||
// Last basic block will have lazy xrefs injected into it.
|
||||
ir.SetInsertPoint(lazy_xref);
|
||||
ir.CreateStore(llvm::ConstantInt::get(bool_type, 1), check_var, true);
|
||||
ir.CreateRetVoid();
|
||||
if (gInitFunc) {
|
||||
return gInitFunc;
|
||||
}
|
||||
|
||||
LOG(INFO)
|
||||
<< "Creating __mcsema_early_init function to pre-initialize runtime.";
|
||||
|
||||
gInitFunc = llvm::Function::Create(
|
||||
llvm::FunctionType::get(llvm::Type::getVoidTy(*gContext), false),
|
||||
llvm::GlobalValue::InternalLinkage,
|
||||
"__mcsema_early_init", gModule.get());
|
||||
|
||||
auto bool_type = llvm::Type::getInt1Ty(*gContext);
|
||||
auto check_var = new llvm::GlobalVariable(
|
||||
*gModule, bool_type, false, llvm::GlobalValue::InternalLinkage,
|
||||
llvm::Constant::getNullValue(bool_type));
|
||||
|
||||
auto entry = llvm::BasicBlock::Create(*gContext, "", gInitFunc);
|
||||
auto already_done = llvm::BasicBlock::Create(*gContext, "", gInitFunc);
|
||||
auto lazy_xref = llvm::BasicBlock::Create(*gContext, "", gInitFunc);
|
||||
|
||||
llvm::IRBuilder<> ir(entry);
|
||||
|
||||
auto guard = ir.CreateLoad(check_var, true);
|
||||
ir.CreateCondBr(guard, already_done, lazy_xref);
|
||||
|
||||
ir.SetInsertPoint(already_done);
|
||||
ir.CreateRetVoid();
|
||||
|
||||
// Last basic block will have lazy xrefs injected into it.
|
||||
ir.SetInsertPoint(lazy_xref);
|
||||
ir.CreateStore(llvm::ConstantInt::get(bool_type, 1), check_var, true);
|
||||
ir.CreateRetVoid();
|
||||
|
||||
return gInitFunc;
|
||||
}
|
||||
|
||||
void DeclareDataSegments(const NativeModule *cfg_module) {
|
||||
for (auto &cfg_seg_entry : cfg_module->segments) {
|
||||
DeclareSegment(cfg_seg_entry.second.get());
|
||||
}
|
||||
|
||||
DeclareVariables(cfg_module);
|
||||
}
|
||||
|
||||
void DefineDataSegments(const NativeModule *cfg_module) {
|
||||
for (auto &cfg_seg_entry : cfg_module->segments) {
|
||||
FillSegment(cfg_seg_entry.second.get());
|
||||
for (const auto &cfg_seg : cfg_module->segments) {
|
||||
FillSegment(cfg_module, cfg_seg.get());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -587,7 +667,7 @@ bool DetectAndSetInitFiniCode(const NativeModule *cfg_module) {
|
||||
|
||||
for (const auto &cfg_func : cfg_module->ea_to_func) {
|
||||
for (auto &init_fini_func : init_fini_pairs) {
|
||||
if (cfg_func.second->name == init_fini_func.first) {
|
||||
if (cfg_func.second->name == init_fini_func.first) {
|
||||
init_fini_func.second = true;
|
||||
}
|
||||
}
|
||||
@@ -616,19 +696,19 @@ void CallInitFiniCode(const NativeModule *cfg_module) {
|
||||
}
|
||||
|
||||
for (const auto &entry : cfg_module->ea_to_func) {
|
||||
auto &cfg_func = entry.second;
|
||||
const auto &cfg_func = entry.second;
|
||||
llvm::Function *callback = nullptr;
|
||||
llvm::Instruction *insert_point = nullptr;
|
||||
|
||||
if (FLAGS_libc_constructor.size() &&
|
||||
FLAGS_libc_constructor == cfg_func->name) {
|
||||
callback = GetNativeToLiftedCallback(cfg_func.get());
|
||||
callback = llvm::dyn_cast<llvm::Function>(cfg_func->Pointer());
|
||||
auto init_func = GetOrCreateMcSemaConstructor();
|
||||
insert_point = &(init_func->front().back());
|
||||
|
||||
} else if (FLAGS_libc_destructor.size() &&
|
||||
FLAGS_libc_destructor == cfg_func->name) {
|
||||
callback = GetNativeToLiftedCallback(cfg_func.get());
|
||||
callback = llvm::dyn_cast<llvm::Function>(cfg_func->Pointer());
|
||||
auto fini_func = GetOrCreateMcSemaDestructor();
|
||||
insert_point = &(fini_func->front().front());
|
||||
}
|
||||
|
||||
+13
-16
@@ -1,22 +1,21 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef MCSEMA_BC_SEGMENT_H_
|
||||
#define MCSEMA_BC_SEGMENT_H_
|
||||
|
||||
#pragma once
|
||||
|
||||
namespace llvm {
|
||||
class Function;
|
||||
@@ -27,10 +26,8 @@ struct NativeModule;
|
||||
|
||||
llvm::Function *GetOrCreateMcSemaInitializer(void);
|
||||
|
||||
void DeclareDataSegments(const NativeModule *cfg_module);
|
||||
//void DeclareDataSegments(const NativeModule *cfg_module);
|
||||
void DefineDataSegments(const NativeModule *cfg_module);
|
||||
void CallInitFiniCode(const NativeModule *cfg_module);
|
||||
|
||||
} // namespace mcsema
|
||||
|
||||
#endif // MCSEMA_BC_SEGMENT_H_
|
||||
|
||||
+194
-36
@@ -1,20 +1,24 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "mcsema/BC/Util.h"
|
||||
|
||||
#include <glog/logging.h>
|
||||
#include <gflags/gflags.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
@@ -26,51 +30,205 @@
|
||||
#include <llvm/IR/Module.h>
|
||||
#include <llvm/IR/Type.h>
|
||||
|
||||
#include "remill/Arch/Arch.h"
|
||||
#include "remill/Arch/Name.h"
|
||||
#include "remill/BC/Util.h"
|
||||
#include "remill/BC/Version.h"
|
||||
#include "remill/OS/OS.h"
|
||||
#include <remill/Arch/Arch.h>
|
||||
#include <remill/Arch/Name.h>
|
||||
#include <remill/BC/Compat/GlobalValue.h>
|
||||
#include <remill/BC/Util.h>
|
||||
#include <remill/BC/Version.h>
|
||||
#include <remill/OS/OS.h>
|
||||
|
||||
#include "mcsema/Arch/Arch.h"
|
||||
#include "mcsema/BC/Util.h"
|
||||
|
||||
DEFINE_bool(disable_aliases, false, "Disable using global aliases for accessing data/registers in the bitcode");
|
||||
|
||||
namespace mcsema {
|
||||
|
||||
std::shared_ptr<llvm::LLVMContext> gContext = nullptr;
|
||||
llvm::IntegerType *gWordType = nullptr;
|
||||
uint64_t gWordMask = 0;
|
||||
std::unique_ptr<llvm::Module> gModule = nullptr;
|
||||
llvm::Constant *gZero = nullptr;
|
||||
|
||||
llvm::Value *GetConstantInt(unsigned size, uint64_t value) {
|
||||
return llvm::ConstantInt::get(llvm::Type::getIntNTy(*gContext, size), value);
|
||||
return llvm::ConstantInt::get(
|
||||
llvm::Type::getIntNTy(*gContext, size), value);
|
||||
}
|
||||
|
||||
// Return the type of a lifted function.
|
||||
llvm::FunctionType *LiftedFunctionType(void) {
|
||||
static llvm::FunctionType *func_type = nullptr;
|
||||
if (!func_type) {
|
||||
func_type = remill::LiftedFunctionType(gModule.get());
|
||||
}
|
||||
return func_type;
|
||||
// Get a lifted representation of a reference (in code) to `ea`.
|
||||
llvm::Constant *LiftXrefInCode(uint64_t ea) {
|
||||
return llvm::ConstantExpr::getAdd(
|
||||
gZero,
|
||||
llvm::ConstantInt::get(gWordType, ea & gWordMask, false));
|
||||
}
|
||||
|
||||
// Translate `ea` into an LLVM value that is an address that points into the
|
||||
// lifted segment associated with `seg`.
|
||||
llvm::Constant *LiftEA(const NativeSegment *cfg_seg, uint64_t ea) {
|
||||
// Get a lifted representation of a reference (in data) to `ea`.
|
||||
llvm::Constant *LiftXrefInData(const NativeSegment *cfg_seg, uint64_t ea,
|
||||
bool cast_to_int) {
|
||||
CHECK(cfg_seg != nullptr);
|
||||
CHECK(cfg_seg->ea <= ea);
|
||||
CHECK(ea < (cfg_seg->ea + cfg_seg->size));
|
||||
|
||||
auto seg = gModule->getGlobalVariable(cfg_seg->lifted_name, true);
|
||||
CHECK(seg != nullptr)
|
||||
<< "Cannot find global variable " << cfg_seg->lifted_name
|
||||
<< " for segment " << cfg_seg->name
|
||||
<< " when trying to lift EA " << std::hex << ea;
|
||||
std::stringstream ss;
|
||||
ss << "data_" << std::hex << ea;
|
||||
auto alias_name = ss.str();
|
||||
|
||||
auto offset = ea - cfg_seg->ea;
|
||||
return llvm::ConstantExpr::getAdd(
|
||||
llvm::ConstantExpr::getPtrToInt(seg, gWordType),
|
||||
llvm::ConstantInt::get(gWordType, offset));
|
||||
llvm::Constant *ptr = nullptr;
|
||||
if (auto alias = gModule->getNamedAlias(alias_name); alias) {
|
||||
ptr = alias;
|
||||
|
||||
} else {
|
||||
auto seg_var = llvm::dyn_cast<llvm::GlobalVariable>(
|
||||
cfg_seg->Get()->Pointer());
|
||||
|
||||
auto seg_type = remill::GetValueType(seg_var);
|
||||
llvm::DataLayout dl(gModule.get());
|
||||
|
||||
llvm::SmallVector<llvm::Value *, 8> gep_index_list;
|
||||
auto i32_type = llvm::Type::getInt32Ty(*gContext);
|
||||
gep_index_list.push_back(llvm::ConstantInt::get(i32_type, 0));
|
||||
const auto goal_offset = (ea - cfg_seg->ea) + cfg_seg->padding;
|
||||
auto [offset, type] = remill::BuildIndexes(
|
||||
dl, seg_type, 0, goal_offset, gep_index_list);
|
||||
|
||||
ptr = seg_var;
|
||||
if (offset) {
|
||||
(void) type;
|
||||
ptr = llvm::ConstantExpr::getInBoundsGetElementPtr(
|
||||
seg_type, seg_var, gep_index_list);
|
||||
}
|
||||
|
||||
if (offset < goal_offset) {
|
||||
auto i8_type = llvm::Type::getInt8Ty(*gContext);
|
||||
ptr = llvm::ConstantExpr::getBitCast(
|
||||
ptr, llvm::PointerType::get(i8_type, 0));
|
||||
ptr = llvm::ConstantExpr::getInBoundsGetElementPtr(
|
||||
i8_type, ptr,
|
||||
llvm::ConstantInt::get(i32_type, goal_offset - offset, false));
|
||||
}
|
||||
|
||||
if (!FLAGS_disable_aliases && !cfg_seg->is_external) {
|
||||
auto ptr_type = llvm::dyn_cast<llvm::PointerType>(ptr->getType());
|
||||
ptr = llvm::GlobalAlias::create(
|
||||
ptr_type->getElementType(), ptr_type->getAddressSpace(),
|
||||
seg_var->getLinkage(), alias_name, ptr, gModule.get());
|
||||
}
|
||||
}
|
||||
|
||||
if (cast_to_int) {
|
||||
return llvm::ConstantExpr::getPtrToInt(ptr, gWordType);
|
||||
} else {
|
||||
return ptr;
|
||||
}
|
||||
}
|
||||
|
||||
// Create a global register state pointer to pass to lifted functions.
|
||||
llvm::Constant *GetStatePointer(void) {
|
||||
static llvm::Constant *state_ptr = nullptr;
|
||||
if (state_ptr) {
|
||||
return state_ptr;
|
||||
}
|
||||
|
||||
auto state_type = gArch->StateStructType();
|
||||
|
||||
// State is initialized with zeroes. Each callback/entrypoint set
|
||||
// appropriate value to stack pointer. This is needed because of
|
||||
// thread_local
|
||||
auto state_init = llvm::ConstantAggregateZero::get(state_type);
|
||||
const auto state_ptr_var = new llvm::GlobalVariable(
|
||||
*gModule, state_type, false, llvm::GlobalValue::ExternalLinkage,
|
||||
state_init, "__mcsema_reg_state", nullptr,
|
||||
llvm::GlobalValue::InitialExecTLSModel);
|
||||
|
||||
state_ptr = state_ptr_var;
|
||||
if (state_ptr_var->getType()->getPointerAddressSpace() != 0) {
|
||||
state_ptr = llvm::ConstantExpr::getAddrSpaceCast(
|
||||
state_ptr, llvm::PointerType::get(state_type, 0));
|
||||
}
|
||||
|
||||
return state_ptr;
|
||||
}
|
||||
|
||||
// Return the address of the base of the TLS data.
|
||||
llvm::Value *GetTLSBaseAddress(llvm::IRBuilder<> &ir) {
|
||||
enum {
|
||||
kGSAddressSpace = 256U,
|
||||
kFSAddressSpace = 257U,
|
||||
|
||||
// From inside of the TEB.
|
||||
kWin32TLSPointerIndex = 0x2c,
|
||||
kWin64TLSPointerIndex = 0x58
|
||||
};
|
||||
|
||||
if (gArch->IsAArch64()) {
|
||||
|
||||
#if LLVM_VERSION(3, 7) >= LLVM_VERSION_NUMBER
|
||||
LOG(ERROR)
|
||||
<< "LLVM 3.7 and below have no thread pointer-related "
|
||||
<< "intrinsics; using NULL as the base of TLS.";
|
||||
return llvm::ConstantInt::get(gWordType, 0);
|
||||
#else
|
||||
# if LLVM_VERSION(3, 8) >= LLVM_VERSION_NUMBER
|
||||
if (gArch->IsAArch64()) {
|
||||
LOG(ERROR)
|
||||
<< "Assuming the `llvm.arm.thread.pointer` intrinsic gets us the base "
|
||||
<< "of thread-local storage.";
|
||||
auto func = llvm::Intrinsic::getDeclaration(
|
||||
gModule.get(), llvm::Intrinsic::arm_thread_pointer);
|
||||
if (func) {
|
||||
return ir.CreatePtrToInt(ir.CreateCall(func), gWordType);
|
||||
}
|
||||
}
|
||||
# endif
|
||||
LOG(ERROR)
|
||||
<< "Assuming the `thread.pointer` intrinsic gets us the base "
|
||||
<< "of thread-local storage.";
|
||||
auto func = llvm::Intrinsic::getDeclaration(
|
||||
gModule.get(), llvm::Intrinsic::thread_pointer);
|
||||
return ir.CreatePtrToInt(ir.CreateCall(func), gWordType);
|
||||
#endif
|
||||
|
||||
// 64-bit x86.
|
||||
} else if (gArch->IsAMD64()) {
|
||||
llvm::ConstantInt *base = nullptr;
|
||||
unsigned addr_space = 0;
|
||||
if (remill::kOSWindows == gArch->os_name) {
|
||||
base = llvm::ConstantInt::get(gWordType, kWin64TLSPointerIndex);
|
||||
addr_space = kGSAddressSpace;
|
||||
} else if (remill::kOSLinux == gArch->os_name) {
|
||||
base = llvm::ConstantInt::get(gWordType, 0);
|
||||
addr_space = kFSAddressSpace;
|
||||
}
|
||||
|
||||
if (base) {
|
||||
auto tls_base_ptr = ir.CreateIntToPtr(
|
||||
base, llvm::PointerType::get(gWordType, addr_space));
|
||||
return ir.CreateLoad(tls_base_ptr);
|
||||
}
|
||||
|
||||
// 32-bit x86.
|
||||
} else if (gArch->IsX86()) {
|
||||
llvm::ConstantInt *base = nullptr;
|
||||
unsigned addr_space = 0;
|
||||
if (remill::kOSWindows == gArch->os_name) {
|
||||
base = llvm::ConstantInt::get(gWordType, kWin32TLSPointerIndex);
|
||||
addr_space = kFSAddressSpace;
|
||||
} else if (remill::kOSLinux == gArch->os_name) {
|
||||
base = llvm::ConstantInt::get(gWordType, 0);
|
||||
addr_space = kGSAddressSpace;
|
||||
}
|
||||
|
||||
if (base) {
|
||||
auto tls_base_ptr = ir.CreateIntToPtr(
|
||||
base, llvm::PointerType::get(gWordType, addr_space));
|
||||
return ir.CreateLoad(tls_base_ptr);
|
||||
}
|
||||
}
|
||||
|
||||
LOG(FATAL)
|
||||
<< "Cannot generate code to find the thread base pointer for arch "
|
||||
<< remill::GetArchName(gArch->arch_name) << " and OS "
|
||||
<< remill::GetOSName(gArch->os_name);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
} // namespace mcsema
|
||||
|
||||
+25
-20
@@ -1,21 +1,21 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef MCSEMA_BC_UTIL_H_
|
||||
#define MCSEMA_BC_UTIL_H_
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <list>
|
||||
@@ -43,17 +43,22 @@ struct NativeSegment;
|
||||
extern std::shared_ptr<llvm::LLVMContext> gContext;
|
||||
extern llvm::IntegerType *gWordType;
|
||||
extern std::unique_ptr<llvm::Module> gModule;
|
||||
|
||||
extern llvm::Constant *gZero;
|
||||
extern uint64_t gWordMask;
|
||||
|
||||
llvm::Value *GetConstantInt(unsigned size, uint64_t value);
|
||||
|
||||
// Return the type of a lifted function.
|
||||
llvm::FunctionType *LiftedFunctionType(void);
|
||||
// Get a lifted representation of a reference (in code) to `ea`.
|
||||
llvm::Constant *LiftXrefInCode(uint64_t ea);
|
||||
|
||||
// Translate `ea` into an LLVM value that is an address that points into the
|
||||
// lifted segment associated with `seg`.
|
||||
llvm::Constant *LiftEA(const NativeSegment *seg, uint64_t ea);
|
||||
// Get a lifted representation of a reference (in data) to `ea`.
|
||||
llvm::Constant *LiftXrefInData(const NativeSegment *cfg_seg, uint64_t ea,
|
||||
bool cast_to_int=true);
|
||||
|
||||
// Create a global register state pointer to pass to lifted functions.
|
||||
llvm::Constant *GetStatePointer(void);
|
||||
|
||||
// Return the address of the base of the TLS data.
|
||||
llvm::Value *GetTLSBaseAddress(llvm::IRBuilder<> &ir);
|
||||
|
||||
} // namespace mcsema
|
||||
|
||||
#endif // MCSEMA_BC_UTIL_H_
|
||||
|
||||
+887
-401
File diff suppressed because it is too large
Load Diff
+310
-94
@@ -1,17 +1,18 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
@@ -24,10 +25,16 @@
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
#include <llvm/ADT/SmallVector.h>
|
||||
#include <llvm/ADT/StringRef.h>
|
||||
#include <llvm/IR/CallingConv.h>
|
||||
|
||||
#include <anvill/Program.h>
|
||||
|
||||
namespace llvm {
|
||||
class Constant;
|
||||
class Function;
|
||||
class FunctionType;
|
||||
class GlobalVariable;
|
||||
} // namespace llvm
|
||||
namespace mcsema {
|
||||
@@ -35,34 +42,43 @@ namespace mcsema {
|
||||
struct NativeVariable;
|
||||
struct NativeStackVariable;
|
||||
struct NativeExceptionFrame;
|
||||
struct NativeFunction;
|
||||
|
||||
struct NativeExternalVariable;
|
||||
struct NativeExternalFunction;
|
||||
|
||||
struct NativeFunction;
|
||||
struct NativeModule;
|
||||
struct NativeSegment;
|
||||
struct NativeXref;
|
||||
|
||||
struct NativePreservedRegisters {
|
||||
llvm::SmallVector<std::string, 16> reg_names;
|
||||
};
|
||||
|
||||
// A cross reference (xref) from an instruction to something.
|
||||
struct NativeInstructionXref {
|
||||
public:
|
||||
// Target ea of the xref.
|
||||
uint64_t target_ea{0};
|
||||
|
||||
// Bitmask to apply to this xref. Zero if none.
|
||||
uint64_t mask{0};
|
||||
};
|
||||
|
||||
struct NativeInstruction {
|
||||
uint64_t ea = 0;
|
||||
uint64_t lp_ea = 0;
|
||||
std::string bytes;
|
||||
uint64_t ea{0};
|
||||
uint64_t lp_ea{0};
|
||||
|
||||
const NativeXref *flow = nullptr;
|
||||
const NativeXref *mem = nullptr;
|
||||
const NativeXref *imm = nullptr;
|
||||
const NativeXref *disp = nullptr;
|
||||
const NativeXref *offset_table = nullptr;
|
||||
|
||||
const NativeStackVariable *stack_var = nullptr;
|
||||
|
||||
bool does_not_return;
|
||||
const NativeInstructionXref *flow{nullptr};
|
||||
const NativeInstructionXref *mem{nullptr};
|
||||
const NativeInstructionXref *imm{nullptr};
|
||||
const NativeInstructionXref *disp{nullptr};
|
||||
const NativeInstructionXref *offset_table{nullptr};
|
||||
};
|
||||
|
||||
struct NativeBlock {
|
||||
uint64_t ea = 0;
|
||||
std::vector<std::unique_ptr<NativeInstruction>> instructions;
|
||||
std::unordered_set<uint64_t> successor_eas;
|
||||
uint64_t ea{0};
|
||||
uint64_t last_inst_ea{0};
|
||||
llvm::SmallVector<uint64_t, 2> successor_eas;
|
||||
bool is_referenced_by_data{false};
|
||||
};
|
||||
|
||||
// Generic object used in the binary. This includes both internally and
|
||||
@@ -70,100 +86,218 @@ struct NativeBlock {
|
||||
// have meaningful and unique effective addresses, usually pointing to
|
||||
// some kind of relocation section within the binary.
|
||||
struct NativeObject {
|
||||
NativeObject(void);
|
||||
explicit NativeObject(NativeModule *module_);
|
||||
virtual ~NativeObject(void) = default;
|
||||
|
||||
// Module containing this object.
|
||||
NativeModule * const module;
|
||||
|
||||
// Forwarding pointer to resolve duplicates and such.
|
||||
mutable NativeObject *forward;
|
||||
|
||||
uint64_t ea = 0;
|
||||
std::string name; // Name in the binary.
|
||||
uint64_t ea{0};
|
||||
|
||||
// Some segments don't begin on page boundaries, and so we often add
|
||||
// padding bytes to the beginning of the LLVM global variable that
|
||||
// represents the segment to fill its size out so that we can page-align
|
||||
// the segment. This is important on fixed-width architectures like AArch64
|
||||
// because often two instructions are used to compute an address: one
|
||||
// instruction for the high bits, and another for the low bits. Often, the
|
||||
// instruction used for the low bits is an OR instruction. This means that
|
||||
// the original low N bits of a given effective address, and the lifted low
|
||||
// N bits corresponding to logically the same object, must match, else some
|
||||
// bits might be "lost". If ADDs were always used then this wouldn't be
|
||||
// a problem, but such is life.
|
||||
uint64_t padding{0};
|
||||
|
||||
mutable std::string name; // Name in the binary.
|
||||
std::string lifted_name; // Name in the bitcode.
|
||||
|
||||
bool is_external = false;
|
||||
bool is_exported = false;
|
||||
bool is_thread_local = false;
|
||||
// TODO(pag): Rework all these booleans into a comprehensive visibility
|
||||
// enumaration that captures the various behaviours.
|
||||
bool is_external{false};
|
||||
bool is_exported{false};
|
||||
bool is_thread_local{false};
|
||||
|
||||
void ForwardTo(NativeObject *dest) const;
|
||||
|
||||
virtual llvm::Constant *Pointer(void) const;
|
||||
virtual llvm::Constant *Address(void) const;
|
||||
|
||||
protected:
|
||||
const NativeObject *Get(void) const;
|
||||
NativeObject *Get(void);
|
||||
};
|
||||
|
||||
// Global variable defined inside of the lifted binary.
|
||||
struct NativeVariable : public NativeObject {
|
||||
const NativeSegment *segment = nullptr;
|
||||
mutable llvm::Constant *address = nullptr;
|
||||
public:
|
||||
using NativeObject::NativeObject;
|
||||
|
||||
virtual ~NativeVariable(void) = default;
|
||||
|
||||
const NativeSegment *segment{nullptr};
|
||||
|
||||
llvm::Constant *Pointer(void) const override;
|
||||
llvm::Constant *Address(void) const override;
|
||||
|
||||
inline const NativeVariable *Get(void) const {
|
||||
return reinterpret_cast<const NativeVariable *>(this->NativeObject::Get());
|
||||
}
|
||||
|
||||
NativeVariable *Get(void) {
|
||||
return reinterpret_cast<NativeVariable *>(this->NativeObject::Get());
|
||||
}
|
||||
};
|
||||
|
||||
// Function that is defined inside the binary.
|
||||
struct NativeFunction : public NativeObject {
|
||||
std::unordered_map<uint64_t, std::unique_ptr<NativeBlock>> blocks;
|
||||
std::vector<struct NativeStackVariable *> stack_vars;
|
||||
std::vector<struct NativeExceptionFrame *> eh_frame;
|
||||
mutable llvm::Function *function = nullptr;
|
||||
mutable llvm::Value *stack_ptr_var = nullptr;
|
||||
mutable llvm::Value *frame_ptr_var = nullptr;
|
||||
};
|
||||
public:
|
||||
using NativeObject::NativeObject;
|
||||
|
||||
struct NativeStackVariable : public NativeObject {
|
||||
uint64_t size = 0;
|
||||
int64_t offset = 0;
|
||||
std::unordered_map<uint64_t, int64_t> refs;
|
||||
mutable llvm::Value *llvm_var = nullptr;
|
||||
virtual ~NativeFunction(void) = default;
|
||||
|
||||
inline const NativeFunction *Get(void) const {
|
||||
return reinterpret_cast<const NativeFunction *>(this->NativeObject::Get());
|
||||
}
|
||||
|
||||
NativeFunction *Get(void) {
|
||||
return reinterpret_cast<NativeFunction *>(this->NativeObject::Get());
|
||||
}
|
||||
|
||||
llvm::SmallVector<std::unique_ptr<NativeExceptionFrame>, 2> eh_frame;
|
||||
|
||||
// Defined in `Callback.cpp`.
|
||||
llvm::Constant *Pointer(void) const override;
|
||||
llvm::Constant *Address(void) const override;
|
||||
|
||||
bool IsNoReturn(void) const;
|
||||
|
||||
mutable const anvill::FunctionDecl *decl{nullptr};
|
||||
mutable llvm::Function *function{nullptr};
|
||||
mutable llvm::Function *lifted_function{nullptr};
|
||||
mutable llvm::Function *callable_lifted_function{nullptr};
|
||||
|
||||
std::vector<const NativeBlock *> blocks;
|
||||
};
|
||||
|
||||
struct NativeExceptionFrame : public NativeObject {
|
||||
uint64_t start_ea = 0;
|
||||
uint64_t end_ea = 0;
|
||||
uint64_t lp_ea = 0;
|
||||
uint64_t action_index = 0;
|
||||
mutable llvm::Value *lp_var = nullptr;
|
||||
public:
|
||||
using NativeObject::NativeObject;
|
||||
virtual ~NativeExceptionFrame(void) = default;
|
||||
|
||||
uint64_t start_ea{0};
|
||||
uint64_t end_ea{0};
|
||||
uint64_t lp_ea{0};
|
||||
uint64_t action_index{0};
|
||||
mutable llvm::Value *lp_var{nullptr};
|
||||
std::unordered_map<uint64_t, NativeExternalVariable *> type_var;
|
||||
};
|
||||
|
||||
// Function that is defined outside of the binary.
|
||||
struct NativeExternalFunction : public NativeFunction {
|
||||
NativeExternalFunction(void);
|
||||
public:
|
||||
explicit NativeExternalFunction(NativeModule *module_);
|
||||
virtual ~NativeExternalFunction(void) = default;
|
||||
|
||||
inline const NativeExternalFunction *Get(void) const {
|
||||
return reinterpret_cast<const NativeExternalFunction *>(
|
||||
this->NativeObject::Get());
|
||||
}
|
||||
|
||||
NativeExternalFunction *Get(void) {
|
||||
return reinterpret_cast<NativeExternalFunction *>(this->NativeObject::Get());
|
||||
}
|
||||
|
||||
// Defined in `External.cpp`.
|
||||
llvm::Constant *Pointer(void) const override;
|
||||
|
||||
bool is_weak{false};
|
||||
unsigned num_args{0};
|
||||
|
||||
bool is_explicit = false;
|
||||
bool is_weak = false;
|
||||
unsigned num_args = 0;
|
||||
llvm::CallingConv::ID cc;
|
||||
};
|
||||
|
||||
// Global variable defined outside of the lifted binary.
|
||||
struct NativeExternalVariable : public NativeVariable {
|
||||
uint64_t size = 0;
|
||||
bool is_weak;
|
||||
public:
|
||||
using NativeVariable::NativeVariable;
|
||||
|
||||
virtual ~NativeExternalVariable(void) = default;
|
||||
|
||||
inline const NativeExternalVariable *Get(void) const {
|
||||
return reinterpret_cast<const NativeExternalVariable *>(
|
||||
this->NativeObject::Get());
|
||||
}
|
||||
|
||||
NativeExternalVariable *Get(void) {
|
||||
return reinterpret_cast<NativeExternalVariable *>(this->NativeObject::Get());
|
||||
}
|
||||
|
||||
// Defined in `External.cpp`.
|
||||
llvm::Constant *Pointer(void) const override;
|
||||
llvm::Constant *Address(void) const override;
|
||||
|
||||
uint64_t size{0};
|
||||
bool is_weak{false};
|
||||
};
|
||||
|
||||
// A cross-reference to something.
|
||||
// A cross-reference (xref) from data to something.
|
||||
struct NativeXref {
|
||||
enum FixupKind {
|
||||
enum FixupKind : uint32_t {
|
||||
kAbsoluteFixup,
|
||||
kThreadLocalOffsetFixup
|
||||
};
|
||||
|
||||
uint64_t width = 0; // In bytes.
|
||||
uint64_t ea = 0; // Location of the xref within its segment.
|
||||
uint64_t mask = 0; // Bitmask to apply to this xref. Zero if none.
|
||||
const NativeSegment *segment = nullptr; // Segment containing the xref.
|
||||
// Width (in bytes) of this cross-reference. This only makes sense for xrefs
|
||||
// embedded in the data section.
|
||||
uint32_t width{0};
|
||||
|
||||
uint64_t target_ea = 0;
|
||||
std::string target_name;
|
||||
const NativeSegment *target_segment = nullptr; // Target segment of the xref, if any.
|
||||
// Fixup type of this data-to-something xref.
|
||||
FixupKind fixup_kind{kAbsoluteFixup};
|
||||
|
||||
FixupKind fixup_kind;
|
||||
// Location of the xref within its segment.
|
||||
uint64_t ea{0};
|
||||
|
||||
const NativeVariable *var = nullptr;
|
||||
const NativeFunction *func = nullptr;
|
||||
// Target ea of the xref.
|
||||
uint64_t target_ea{0};
|
||||
|
||||
// Bitmask to apply to this xref. Zero if none.
|
||||
uint64_t mask{0};
|
||||
|
||||
// Segment containing `ea`.
|
||||
mutable const NativeSegment *segment{nullptr};
|
||||
|
||||
// Segment containin `target_ea`.
|
||||
mutable const NativeSegment *target_segment{nullptr};
|
||||
|
||||
// Global variable associated with `target_ea`.
|
||||
const NativeVariable *var{nullptr};
|
||||
|
||||
// Function associated with `target_ea`.
|
||||
const NativeFunction *func{nullptr};
|
||||
};
|
||||
|
||||
struct NativeBlob {
|
||||
uint64_t ea = 0;
|
||||
std::string data;
|
||||
uint64_t ea{0};
|
||||
unsigned size{0};
|
||||
bool is_zero{false};
|
||||
};
|
||||
|
||||
struct NativeSegment : public NativeObject {
|
||||
public:
|
||||
using NativeObject::NativeObject;
|
||||
|
||||
virtual ~NativeSegment(void) = default;
|
||||
|
||||
inline const NativeSegment *Get(void) const {
|
||||
return reinterpret_cast<const NativeSegment *>(this->NativeObject::Get());
|
||||
}
|
||||
|
||||
NativeSegment *Get(void) {
|
||||
return reinterpret_cast<NativeSegment *>(this->NativeObject::Get());
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
Entry(void) = default;
|
||||
Entry(uint64_t, uint64_t, NativeXref *, NativeBlob *);
|
||||
@@ -174,45 +308,127 @@ struct NativeSegment : public NativeObject {
|
||||
std::unique_ptr<NativeBlob> blob;
|
||||
};
|
||||
|
||||
uint64_t size = 0;
|
||||
bool is_read_only = false;
|
||||
// Size, in bytes, of this segment.
|
||||
uint64_t size{0};
|
||||
|
||||
// Whether or not this segment is read-only.
|
||||
bool is_read_only{false};
|
||||
|
||||
// The external variable associated with this segment, if any.
|
||||
mutable NativeExternalVariable *as_extern_var{nullptr};
|
||||
|
||||
// Partition of entries, which are either cross-references, or opaque
|
||||
// blobs of bytes. The ordering of entries is significant.
|
||||
std::map<uint64_t, Entry> entries;
|
||||
|
||||
mutable bool needs_initializer = true;
|
||||
mutable llvm::GlobalVariable *seg_var = nullptr;
|
||||
// Get or lazily create a global variable for this segment.
|
||||
//
|
||||
// NOTE(pag): Defined in Segment.cpp.
|
||||
llvm::Constant *Pointer(void) const override;
|
||||
llvm::Constant *Address(void) const override;
|
||||
};
|
||||
|
||||
// NOTE(pag): Using an `std::map` (as opposed to an `std::unordered_map`) is
|
||||
// intentional so that we can get the ordering of `NativeSegment`s
|
||||
// by their `ea`s.
|
||||
using SegmentMap = std::map<uint64_t, std::unique_ptr<NativeSegment>>;
|
||||
struct NativeModule : anvill::Program {
|
||||
|
||||
struct NativeModule {
|
||||
std::unordered_set<uint64_t> exported_vars;
|
||||
std::unordered_set<uint64_t> exported_funcs;
|
||||
|
||||
SegmentMap segments;
|
||||
// NOTE(pag): Using an `std::map` (as opposed to an `std::unordered_map`) is
|
||||
// intentional so that we can get the ordering of `NativeSegment`s
|
||||
// by their `ea`s.
|
||||
std::map<uint64_t, const NativeSegment *> ea_to_seg;
|
||||
|
||||
std::unordered_map<uint64_t, std::unique_ptr<NativeFunction>> ea_to_func;
|
||||
std::vector<std::unique_ptr<NativeVariable>> variables;
|
||||
std::vector<std::unique_ptr<NativeFunction>> functions;
|
||||
|
||||
std::unordered_map<std::string, const NativeExternalFunction *>
|
||||
name_to_extern_func;
|
||||
// The lifted segments, including those invented for external variables.
|
||||
//
|
||||
// NOTE(pag): These are sorted by segment size (smallest first).
|
||||
std::vector<std::unique_ptr<NativeSegment>> segments;
|
||||
std::vector<std::unique_ptr<NativeSegment>> unused_segments;
|
||||
|
||||
// All known basic blocks.
|
||||
std::unordered_map<uint64_t, std::unique_ptr<NativeBlock>> ea_to_block;
|
||||
|
||||
// All known instructions and their cross-references.
|
||||
std::unordered_map<uint64_t, std::unique_ptr<NativeInstruction>> ea_to_inst;
|
||||
|
||||
// All local and global functions.
|
||||
std::unordered_map<uint64_t, const NativeFunction *> ea_to_func;
|
||||
|
||||
// Represent global and external variables.
|
||||
std::unordered_map<uint64_t, std::unique_ptr<NativeVariable>> ea_to_var;
|
||||
std::unordered_map<std::string, const NativeExternalVariable *>
|
||||
name_to_extern_var;
|
||||
std::unordered_map<uint64_t, const NativeVariable *> ea_to_var;
|
||||
|
||||
NativeFunction *TryGetFunction(uint64_t ea) const;
|
||||
NativeVariable *TryGetVariable(uint64_t ea) const;
|
||||
const NativeSegment *TryGetSegment(llvm::StringRef name) const;
|
||||
const NativeSegment *TryGetSegment(uint64_t ea) const;
|
||||
const NativeFunction *TryGetFunction(uint64_t ea) const;
|
||||
const NativeVariable *TryGetVariable(uint64_t ea) const;
|
||||
|
||||
std::vector<std::unique_ptr<NativeVariable>> dead_vars;
|
||||
// Try to get the block containing `inst_ea`.
|
||||
const NativeBlock *TryGetBlock(
|
||||
uint64_t inst_ea, const NativeBlock *curr) const;
|
||||
|
||||
// Try to get the instruction at `ea`.
|
||||
const NativeInstruction *TryGetInstruction(uint64_t ea) const;
|
||||
|
||||
NativeSegment *TryGetSegment(uint64_t ea);
|
||||
NativeFunction *TryGetFunction(uint64_t ea);
|
||||
NativeVariable *TryGetVariable(uint64_t ea);
|
||||
|
||||
// Sets of registers that may be preserved.
|
||||
std::vector<NativePreservedRegisters> preserved_regs;
|
||||
|
||||
// Backup vector of instruction bytes.
|
||||
std::vector<std::unique_ptr<std::string>> inst_bytes;
|
||||
|
||||
// Maps effective addresses to sets of registers that are preserved around
|
||||
// the instruction at this address. This corresponds to registers preserved
|
||||
// around a function call.
|
||||
std::unordered_map<uint64_t, const NativePreservedRegisters *>
|
||||
ea_to_inst_preserved_regs;
|
||||
|
||||
// Maps effective addresses to sets of registers that are killed just after
|
||||
// the instruction at this address.
|
||||
std::unordered_map<uint64_t, const NativePreservedRegisters *>
|
||||
ea_to_inst_killed_regs;
|
||||
|
||||
// Maps effective addresses to sets of registers that are preserved around
|
||||
// the instruction at this address. This corresponds to registers preserved
|
||||
// around a function call.
|
||||
std::unordered_multimap<uint64_t, std::pair<uint64_t, const NativePreservedRegisters *>>
|
||||
ea_to_range_preserved_regs;
|
||||
|
||||
template <typename T>
|
||||
void ForEachInstructionPreservedRegister(uint64_t ea, T cb) const {
|
||||
auto reg_set_it = ea_to_inst_preserved_regs.find(ea);
|
||||
if (reg_set_it != ea_to_inst_preserved_regs.end()) {
|
||||
for (const auto ®_name : reg_set_it->second->reg_names) {
|
||||
cb(reg_name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void ForEachInstructionKilledRegister(uint64_t ea, T cb) const {
|
||||
auto reg_set_it = ea_to_inst_killed_regs.find(ea);
|
||||
if (reg_set_it != ea_to_inst_killed_regs.end()) {
|
||||
for (const auto ®_name : reg_set_it->second->reg_names) {
|
||||
cb(reg_name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void ForEachRangePreservedRegister(uint64_t ea, T cb) const {
|
||||
for (auto reg_set_it = ea_to_range_preserved_regs.find(ea);
|
||||
(reg_set_it != ea_to_range_preserved_regs.end() &&
|
||||
reg_set_it->first == ea);
|
||||
++reg_set_it) {
|
||||
cb(reg_set_it->second.first, *(reg_set_it->second.second));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
NativeModule *ReadProtoBuf(const std::string &file_name,
|
||||
uint64_t pointer_size);
|
||||
|
||||
} // namespace mcsema
|
||||
} // namespace mcsema
|
||||
|
||||
+89
-53
@@ -1,16 +1,18 @@
|
||||
// Copyright (c) 2017 Trail of Bits, Inc.
|
||||
// Copyright (c) 2020 Trail of Bits, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// 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 Affero General Public License for more details.
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
syntax = "proto2";
|
||||
|
||||
@@ -29,16 +31,25 @@ syntax = "proto2";
|
||||
|
||||
package mcsema;
|
||||
|
||||
message PreservationRange {
|
||||
required int64 begin_ea = 1;
|
||||
optional int64 end_ea = 2;
|
||||
}
|
||||
|
||||
message PreservedRegisters {
|
||||
// List of registers that are preserved.
|
||||
repeated string registers = 1;
|
||||
|
||||
// Address of a call instruction around which the registers are preserved,
|
||||
// or of function bodies. In the case of function bodies, we will have
|
||||
// one range per (entry, exit) pair, i.e. if a function has N returns,
|
||||
// then we'll have N ranges.
|
||||
repeated PreservationRange ranges = 2;
|
||||
}
|
||||
|
||||
// A cross-reference contained within an instruction.
|
||||
// Similar to reference from Segment
|
||||
message CodeReference {
|
||||
enum TargetType {
|
||||
// Examples: callq 8c0 <_ZN1AC2EPKc>
|
||||
CodeTarget = 0;
|
||||
// Example: lea 0x20094a(%rip),%rdi # 201049 <global>
|
||||
DataTarget = 1;
|
||||
}
|
||||
|
||||
enum OperandType {
|
||||
// Example: mov $0x617400,%r8d
|
||||
ImmediateOperand = 0;
|
||||
@@ -59,32 +70,21 @@ message CodeReference {
|
||||
OffsetTable = 4;
|
||||
}
|
||||
|
||||
enum Location {
|
||||
Internal = 0;
|
||||
// Is it to external symbol?
|
||||
External = 1;
|
||||
}
|
||||
required OperandType operand_type = 1;
|
||||
required int64 ea = 2;
|
||||
|
||||
required TargetType target_type = 1;
|
||||
required OperandType operand_type = 2;
|
||||
required Location location = 3;
|
||||
required int64 ea = 4;
|
||||
|
||||
// For aarch64, since instruction are 32-bit and there may be the need to
|
||||
// build up 64-bit address
|
||||
optional int64 mask = 5;
|
||||
optional string name = 6;
|
||||
// For aarch64 since instruction are 32-bit and there may be the need to build
|
||||
// up 64-bit address across multiple instructions using immediate/displacement operands.
|
||||
optional int64 mask = 3;
|
||||
}
|
||||
|
||||
// An instruction inside of a block.
|
||||
message Instruction {
|
||||
required int64 ea = 1;
|
||||
required bytes bytes = 2;
|
||||
repeated CodeReference xrefs = 3;
|
||||
optional bool local_noreturn = 4;
|
||||
repeated CodeReference xrefs = 2;
|
||||
|
||||
// Address of the landing pad
|
||||
optional uint64 lp_ea = 5;
|
||||
optional uint64 lp_ea = 3;
|
||||
}
|
||||
|
||||
// A basic block of instructions inside of a function.
|
||||
@@ -92,6 +92,45 @@ message Block {
|
||||
required int64 ea = 1;
|
||||
repeated Instruction instructions = 2;
|
||||
repeated int64 successor_eas = 3;
|
||||
required bool is_referenced_by_data = 4;
|
||||
}
|
||||
|
||||
// The location of something stored in a relative position in memory.
|
||||
message MemoryLocation {
|
||||
required string register = 1; // Base register.
|
||||
optional int64 offset = 2; // Displacement from the base register.
|
||||
}
|
||||
|
||||
message ValueDecl {
|
||||
required string type = 1;
|
||||
|
||||
// The value is either resident in memory or in a register.
|
||||
optional MemoryLocation memory = 2;
|
||||
optional string register = 3;
|
||||
|
||||
optional string name = 4;
|
||||
}
|
||||
|
||||
enum CallingConvention {
|
||||
C = 0;
|
||||
X86_StdCall = 64;
|
||||
X86_FastCall = 65;
|
||||
X86_ThisCall = 70;
|
||||
X86_64_SysV = 78;
|
||||
Win64 = 79;
|
||||
X86_VectorCall = 80;
|
||||
X86_RegCall = 92;
|
||||
AArch64_VectorCall = 97;
|
||||
}
|
||||
|
||||
message FunctionDecl {
|
||||
repeated ValueDecl parameters = 1;
|
||||
repeated ValueDecl return_values = 2;
|
||||
required ValueDecl return_address = 3;
|
||||
required ValueDecl return_stack_pointer = 4;
|
||||
required bool is_variadic = 5;
|
||||
required bool is_noreturn = 6;
|
||||
required CallingConvention calling_convention = 7;
|
||||
}
|
||||
|
||||
// A function with an implementation inside of the binary.
|
||||
@@ -102,8 +141,10 @@ message Function {
|
||||
// Can someone else link against the code and use this function?
|
||||
required bool is_entrypoint = 3;
|
||||
optional string name = 4;
|
||||
repeated StackVariable stack_vars = 5;
|
||||
repeated ExceptionFrame eh_frame = 6;
|
||||
repeated ExceptionFrame eh_frame = 5;
|
||||
|
||||
// Anvill specification of this function.
|
||||
optional FunctionDecl decl = 6;
|
||||
}
|
||||
|
||||
/* A function that is used or referenced within binary, but not implemented
|
||||
@@ -121,17 +162,22 @@ message ExternalFunction {
|
||||
}
|
||||
|
||||
required string name = 1;
|
||||
|
||||
// Address of relocation. Other entry with ea of thunk can be added as well
|
||||
required int64 ea = 2;
|
||||
|
||||
required CallingConvention cc = 3;
|
||||
|
||||
// Does this function return?
|
||||
required bool has_return = 4;
|
||||
required bool no_return = 5;
|
||||
required int32 argument_count = 6;
|
||||
|
||||
// Linkage information
|
||||
required bool is_weak = 7;
|
||||
optional string signature = 8;
|
||||
|
||||
// Anvill specification of this function.
|
||||
optional FunctionDecl decl = 8;
|
||||
}
|
||||
|
||||
// A named symbol defined outside of the binary. For example, `stderr`.
|
||||
@@ -174,11 +220,8 @@ message DataReference {
|
||||
required int32 width = 2;
|
||||
|
||||
// Information about the target of the cross-reference.
|
||||
required int64 target_ea = 4;
|
||||
required string target_name = 5;
|
||||
required bool target_is_code = 6;
|
||||
|
||||
required TargetFixupKind target_fixup_kind = 8;
|
||||
required int64 target_ea = 3;
|
||||
required TargetFixupKind target_fixup_kind = 4;
|
||||
}
|
||||
|
||||
/* Represents a named location within a data segment. Variables will often
|
||||
@@ -218,16 +261,6 @@ message ExceptionFrame {
|
||||
repeated ExternalVariable ttype = 7;
|
||||
}
|
||||
|
||||
// This is optional information, but leads to better lift
|
||||
message StackVariable {
|
||||
required string name = 1;
|
||||
required uint64 size = 2;
|
||||
required int64 sp_offset = 3;
|
||||
optional bool has_frame = 4;
|
||||
optional string reg_name = 5;
|
||||
repeated Reference ref_eas = 6;
|
||||
}
|
||||
|
||||
// Global variable from original binary
|
||||
message GlobalVariable {
|
||||
required int64 ea = 1;
|
||||
@@ -280,4 +313,7 @@ message Module {
|
||||
repeated ExternalVariable external_vars = 5;
|
||||
|
||||
repeated GlobalVariable global_vars = 8;
|
||||
|
||||
repeated PreservedRegisters preserved_regs = 9;
|
||||
repeated PreservedRegisters dead_regs = 10;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,61 +1,20 @@
|
||||
# Copyright (c) 2018 Trail of Bits, Inc.
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# 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 Affero General Public License for more details.
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
cmake_minimum_required(VERSION 3.2)
|
||||
project(linux_abi)
|
||||
|
||||
function(add_runtime_helper target_name source_file address_bit_size)
|
||||
message(" > Generating Linux ABI target: ${target_name}")
|
||||
add_subdirectory(X86)
|
||||
|
||||
# Visual C++ requires C++14
|
||||
if(WIN32)
|
||||
set(required_cpp_standard "c++14")
|
||||
else()
|
||||
set(required_cpp_standard "c++11")
|
||||
endif()
|
||||
|
||||
if(DEFINED WIN32)
|
||||
set(install_folder "${CMAKE_INSTALL_PREFIX}/mcsema/${MCSEMA_LLVM_VERSION}/ABI/linux")
|
||||
else()
|
||||
set(install_folder "${CMAKE_INSTALL_PREFIX}/share/mcsema/${MCSEMA_LLVM_VERSION}/ABI/linux")
|
||||
endif()
|
||||
|
||||
if("${source_file}" MATCHES "\.c$")
|
||||
set(bc_build_flags "-xc" "-m${address_bit_size}" "-std=gnu11" "-Wno-deprecated-declarations")
|
||||
elseif("${source_file}" MATCHES "\.cpp$")
|
||||
set(bc_build_flags "-xc++" "-m${address_bit_size}" "-std=gnu++14" "-Wno-deprecated-declarations")
|
||||
else()
|
||||
# assume defaults work
|
||||
message(WARNING " > WARNING: Unknown file extension for ${source_file}")
|
||||
set(bc_build_flags "")
|
||||
endif()
|
||||
|
||||
message("Build flags: ${bc_build_flags}")
|
||||
add_runtime(${target_name}
|
||||
SOURCES ${source_file}
|
||||
ADDRESS_SIZE ${address_bit_size}
|
||||
BCFLAGS ${bc_build_flags}
|
||||
INCLUDEDIRECTORIES "${CMAKE_SOURCE_DIR}"
|
||||
INSTALLDESTINATION "${install_folder}"
|
||||
DEPENDENCIES ${ARGN}
|
||||
)
|
||||
endfunction()
|
||||
|
||||
add_runtime_helper(ABI_exceptions_x86 "ABI_exceptions.cpp" 32)
|
||||
add_runtime_helper(ABI_libc_x86 "ABI_libc.c" 32 "ABI_libc.h")
|
||||
|
||||
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
|
||||
add_runtime_helper(ABI_exceptions_amd64 "ABI_exceptions.cpp" 64)
|
||||
add_runtime_helper(ABI_libc_amd64 "ABI_libc.c" 64 "ABI_libc.h")
|
||||
endif()
|
||||
|
||||
@@ -56,107 +56,107 @@ extern char *gets(char *s);
|
||||
#include <rpcsvc/rstat.h>
|
||||
//#include <rpcsvc/yp.h>
|
||||
//#include <rpcsvc/nfs_prot.h>
|
||||
#include <rpcsvc/rquota.h>
|
||||
//#include <rpcsvc/rquota.h>
|
||||
//#include <rpcsvc/yp_prot.h>
|
||||
#include <rpcsvc/bootparam_prot.h>
|
||||
#include <netipx/ipx.h>
|
||||
//#include <_G_config.h>
|
||||
//#include <libio.h>
|
||||
#include <_G_config.h>
|
||||
#include <libio.h>
|
||||
#include <strings.h>
|
||||
#include <nss.h>
|
||||
#include <netrom/netrom.h>
|
||||
#include <malloc.h>
|
||||
#include <x86_64-linux-gnu/ieee754.h>
|
||||
#include <x86_64-linux-gnu/sys/timerfd.h>
|
||||
#include <x86_64-linux-gnu/sys/timeb.h>
|
||||
#include <x86_64-linux-gnu/sys/unistd.h>
|
||||
#include <x86_64-linux-gnu/sys/debugreg.h>
|
||||
#include <x86_64-linux-gnu/sys/utsname.h>
|
||||
#include <x86_64-linux-gnu/sys/ioctl.h>
|
||||
#include <x86_64-linux-gnu/sys/reg.h>
|
||||
#include <x86_64-linux-gnu/sys/socketvar.h>
|
||||
#include <x86_64-linux-gnu/sys/sysinfo.h>
|
||||
#include <x86_64-linux-gnu/sys/socket.h>
|
||||
#include <x86_64-linux-gnu/sys/poll.h>
|
||||
#include <x86_64-linux-gnu/sys/vt.h>
|
||||
#include <x86_64-linux-gnu/sys/uio.h>
|
||||
#include <x86_64-linux-gnu/sys/msg.h>
|
||||
#include <x86_64-linux-gnu/sys/stat.h>
|
||||
#include <x86_64-linux-gnu/sys/klog.h>
|
||||
#include <x86_64-linux-gnu/sys/termios.h>
|
||||
#include <x86_64-linux-gnu/sys/ipc.h>
|
||||
#include <x86_64-linux-gnu/sys/mtio.h>
|
||||
#include <x86_64-linux-gnu/sys/ttychars.h>
|
||||
#include <x86_64-linux-gnu/sys/select.h>
|
||||
//#include <x86_64-linux-gnu/sys/ultrasound.h>
|
||||
#include <x86_64-linux-gnu/sys/times.h>
|
||||
#include <x86_64-linux-gnu/sys/un.h>
|
||||
#include <x86_64-linux-gnu/sys/eventfd.h>
|
||||
#include <x86_64-linux-gnu/sys/xattr.h>
|
||||
#include <x86_64-linux-gnu/sys/fanotify.h>
|
||||
#include <x86_64-linux-gnu/sys/statvfs.h>
|
||||
#include <x86_64-linux-gnu/sys/shm.h>
|
||||
#include <x86_64-linux-gnu/sys/resource.h>
|
||||
#include <x86_64-linux-gnu/sys/raw.h>
|
||||
#include <x86_64-linux-gnu/sys/syslog.h>
|
||||
#include <x86_64-linux-gnu/sys/syscall.h>
|
||||
#include <x86_64-linux-gnu/sys/epoll.h>
|
||||
#include <x86_64-linux-gnu/sys/quota.h>
|
||||
#include <x86_64-linux-gnu/sys/ptrace.h>
|
||||
//#include <x86_64-linux-gnu/sys/stropts.h>
|
||||
#include <x86_64-linux-gnu/sys/cdefs.h>
|
||||
#include <x86_64-linux-gnu/sys/personality.h>
|
||||
#include <x86_64-linux-gnu/sys/dir.h>
|
||||
#include <x86_64-linux-gnu/sys/swap.h>
|
||||
#include <x86_64-linux-gnu/sys/user.h>
|
||||
#include <x86_64-linux-gnu/sys/ucontext.h>
|
||||
#include <x86_64-linux-gnu/sys/bitypes.h>
|
||||
#include <x86_64-linux-gnu/sys/vtimes.h>
|
||||
#include <x86_64-linux-gnu/sys/gmon_out.h>
|
||||
#include <x86_64-linux-gnu/sys/signal.h>
|
||||
#include <x86_64-linux-gnu/sys/fcntl.h>
|
||||
#include <x86_64-linux-gnu/sys/prctl.h>
|
||||
#include <x86_64-linux-gnu/sys/inotify.h>
|
||||
#include <x86_64-linux-gnu/sys/kd.h>
|
||||
#include <x86_64-linux-gnu/sys/errno.h>
|
||||
#include <x86_64-linux-gnu/sys/profil.h>
|
||||
#include <x86_64-linux-gnu/sys/acct.h>
|
||||
#include <x86_64-linux-gnu/sys/sem.h>
|
||||
#include <x86_64-linux-gnu/sys/perm.h>
|
||||
#include <x86_64-linux-gnu/sys/signalfd.h>
|
||||
#include <x86_64-linux-gnu/sys/sysmacros.h>
|
||||
#include <x86_64-linux-gnu/sys/param.h>
|
||||
#include <x86_64-linux-gnu/sys/reboot.h>
|
||||
//#include <x86_64-linux-gnu/sys/kdaemon.h>
|
||||
#include <x86_64-linux-gnu/sys/auxv.h>
|
||||
#include <x86_64-linux-gnu/sys/file.h>
|
||||
#include <x86_64-linux-gnu/sys/sysctl.h>
|
||||
#include <x86_64-linux-gnu/sys/wait.h>
|
||||
#include <x86_64-linux-gnu/sys/mman.h>
|
||||
#include <x86_64-linux-gnu/sys/mount.h>
|
||||
#include <x86_64-linux-gnu/sys/sendfile.h>
|
||||
#include <x86_64-linux-gnu/sys/soundcard.h>
|
||||
#include <x86_64-linux-gnu/sys/ttydefaults.h>
|
||||
#include <x86_64-linux-gnu/sys/gmon.h>
|
||||
#include <x86_64-linux-gnu/sys/fsuid.h>
|
||||
#include <x86_64-linux-gnu/sys/procfs.h>
|
||||
#include <x86_64-linux-gnu/sys/timex.h>
|
||||
#include <x86_64-linux-gnu/sys/vfs.h>
|
||||
#include <x86_64-linux-gnu/sys/queue.h>
|
||||
#include <x86_64-linux-gnu/sys/statfs.h>
|
||||
#include <x86_64-linux-gnu/sys/pci.h>
|
||||
#include <x86_64-linux-gnu/sys/types.h>
|
||||
#include <x86_64-linux-gnu/sys/io.h>
|
||||
//#include <x86_64-linux-gnu/sys/ustat.h>
|
||||
#include <x86_64-linux-gnu/sys/vlimit.h>
|
||||
#include <x86_64-linux-gnu/sys/time.h>
|
||||
#include <x86_64-linux-gnu/a.out.h>
|
||||
#include <x86_64-linux-gnu/gnu/stubs.h>
|
||||
#include <x86_64-linux-gnu/gnu/stubs-64.h>
|
||||
#include <x86_64-linux-gnu/gnu/libc-version.h>
|
||||
//#include <x86_64-linux-gnu/gnu/option-groups.h>
|
||||
#include <x86_64-linux-gnu/gnu/lib-names.h>
|
||||
#include <x86_64-linux-gnu/fpu_control.h>
|
||||
#include <ieee754.h>
|
||||
#include <sys/timerfd.h>
|
||||
#include <sys/timeb.h>
|
||||
#include <sys/unistd.h>
|
||||
#include <sys/debugreg.h>
|
||||
#include <sys/utsname.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/reg.h>
|
||||
#include <sys/socketvar.h>
|
||||
#include <sys/sysinfo.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/poll.h>
|
||||
#include <sys/vt.h>
|
||||
#include <sys/uio.h>
|
||||
#include <sys/msg.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/klog.h>
|
||||
#include <sys/termios.h>
|
||||
#include <sys/ipc.h>
|
||||
#include <sys/mtio.h>
|
||||
#include <sys/ttychars.h>
|
||||
#include <sys/select.h>
|
||||
//#include <sys/ultrasound.h>
|
||||
#include <sys/times.h>
|
||||
#include <sys/un.h>
|
||||
#include <sys/eventfd.h>
|
||||
#include <sys/xattr.h>
|
||||
//#include <sys/fanotify.h>
|
||||
#include <sys/statvfs.h>
|
||||
#include <sys/shm.h>
|
||||
#include <sys/resource.h>
|
||||
#include <sys/raw.h>
|
||||
#include <sys/syslog.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/epoll.h>
|
||||
#include <sys/quota.h>
|
||||
#include <sys/ptrace.h>
|
||||
//#include <sys/stropts.h>
|
||||
#include <sys/cdefs.h>
|
||||
#include <sys/personality.h>
|
||||
#include <sys/dir.h>
|
||||
#include <sys/swap.h>
|
||||
#include <sys/user.h>
|
||||
#include <sys/ucontext.h>
|
||||
#include <sys/bitypes.h>
|
||||
#include <sys/vtimes.h>
|
||||
#include <sys/gmon_out.h>
|
||||
#include <sys/signal.h>
|
||||
#include <sys/fcntl.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <sys/inotify.h>
|
||||
#include <sys/kd.h>
|
||||
#include <sys/errno.h>
|
||||
#include <sys/profil.h>
|
||||
#include <sys/acct.h>
|
||||
#include <sys/sem.h>
|
||||
#include <sys/perm.h>
|
||||
#include <sys/signalfd.h>
|
||||
#include <sys/sysmacros.h>
|
||||
#include <sys/param.h>
|
||||
#include <sys/reboot.h>
|
||||
//#include <sys/kdaemon.h>
|
||||
//#include <sys/auxv.h>
|
||||
#include <sys/file.h>
|
||||
#include <sys/sysctl.h>
|
||||
#include <sys/wait.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/mount.h>
|
||||
#include <sys/sendfile.h>
|
||||
#include <sys/soundcard.h>
|
||||
#include <sys/ttydefaults.h>
|
||||
#include <sys/gmon.h>
|
||||
#include <sys/fsuid.h>
|
||||
#include <sys/procfs.h>
|
||||
#include <sys/timex.h>
|
||||
#include <sys/vfs.h>
|
||||
#include <sys/queue.h>
|
||||
#include <sys/statfs.h>
|
||||
#include <sys/pci.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/io.h>
|
||||
#include <sys/ustat.h>
|
||||
#include <sys/vlimit.h>
|
||||
#include <sys/time.h>
|
||||
#include <a.out.h>
|
||||
#include <gnu/stubs.h>
|
||||
#include <gnu/stubs-64.h>
|
||||
#include <gnu/libc-version.h>
|
||||
//#include <gnu/option-groups.h>
|
||||
#include <gnu/lib-names.h>
|
||||
#include <fpu_control.h>
|
||||
#include <string.h>
|
||||
#include <poll.h>
|
||||
#include <locale.h>
|
||||
@@ -207,9 +207,10 @@ extern char *gets(char *s);
|
||||
#include <assert.h>
|
||||
#include <fmtmsg.h>
|
||||
#include <endian.h>
|
||||
//#include <stropts.h>
|
||||
#include <stropts.h>
|
||||
#include <values.h>
|
||||
#include <crypt.h>
|
||||
#include <xlocale.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sgtty.h>
|
||||
@@ -253,7 +254,7 @@ extern char *gets(char *s);
|
||||
#include <libgen.h>
|
||||
#include <sched.h>
|
||||
#include <gshadow.h>
|
||||
//#include <rpc/des_crypt.h>
|
||||
#include <rpc/des_crypt.h>
|
||||
#include <rpc/xdr.h>
|
||||
#include <rpc/auth_des.h>
|
||||
#include <rpc/pmap_prot.h>
|
||||
@@ -267,7 +268,7 @@ extern char *gets(char *s);
|
||||
#include <rpc/rpc.h>
|
||||
#include <rpc/svc.h>
|
||||
#include <rpc/auth_unix.h>
|
||||
//#include <rpc/rpc_des.h>
|
||||
#include <rpc/rpc_des.h>
|
||||
#include <rpc/types.h>
|
||||
#include <rpc/auth.h>
|
||||
#include <wait.h>
|
||||
@@ -292,7 +293,8 @@ extern char *gets(char *s);
|
||||
#include <elf.h>
|
||||
#include <tar.h>
|
||||
#include <fts.h>
|
||||
//#include <ustat.h>
|
||||
#include <ustat.h>
|
||||
#include <time.h>
|
||||
#include <err.h>
|
||||
#include <netax25/ax25.h>
|
||||
#include "klee_defs.h"
|
||||
@@ -0,0 +1,92 @@
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
cmake_minimum_required(VERSION 3.2)
|
||||
project(linux_abi)
|
||||
|
||||
function(add_runtime_helper target_name source_file address_bit_size)
|
||||
message(" > Generating Linux ABI target: ${target_name}")
|
||||
|
||||
# Visual C++ requires C++14
|
||||
if(WIN32)
|
||||
set(required_cpp_standard "c++14")
|
||||
else()
|
||||
set(required_cpp_standard "c++11")
|
||||
endif()
|
||||
|
||||
if(DEFINED WIN32)
|
||||
set(install_folder "${CMAKE_INSTALL_PREFIX}/mcsema/${REMILL_LLVM_VERSION}/ABI/linux")
|
||||
else()
|
||||
set(install_folder "${CMAKE_INSTALL_PREFIX}/share/mcsema/${REMILL_LLVM_VERSION}/ABI/linux")
|
||||
endif()
|
||||
|
||||
if("${source_file}" MATCHES "\.c$")
|
||||
set(bc_build_flags "-femit-all-decls" "-xc" "-m${address_bit_size}" "-std=gnu11" "-Wno-deprecated-declarations")
|
||||
elseif("${source_file}" MATCHES "\.cpp$")
|
||||
set(bc_build_flags "-femit-all-decls" "-xc++" "-m${address_bit_size}" "-std=gnu++14" "-Wno-deprecated-declarations")
|
||||
else()
|
||||
# assume defaults work
|
||||
message(WARNING " > WARNING: Unknown file extension for ${source_file}")
|
||||
set(bc_build_flags "")
|
||||
endif()
|
||||
|
||||
message("Build flags: ${bc_build_flags}")
|
||||
add_runtime(${target_name}
|
||||
SOURCES ${source_file}
|
||||
ADDRESS_SIZE ${address_bit_size}
|
||||
BCFLAGS ${bc_build_flags}
|
||||
INCLUDEDIRECTORIES "${CMAKE_SOURCE_DIR}"
|
||||
INSTALLDESTINATION "${install_folder}"
|
||||
DEPENDENCIES ${ARGN}
|
||||
)
|
||||
endfunction()
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/ABI_libc.c ${CMAKE_CURRENT_SOURCE_DIR}/ABI_libc.h
|
||||
DEPENDS ${source_file}
|
||||
COMMAND env TRAILOFBITS_LIBRARIES=${LIBRARY_REPOSITORY_ROOT} python3 ${CMAKE_CURRENT_SOURCE_DIR}/../generate_abi_wrapper.py
|
||||
--arch "amd64" --type "c" --input ${CMAKE_CURRENT_SOURCE_DIR}/ABI_libc.pph --output ${CMAKE_CURRENT_SOURCE_DIR}/ABI_libc.c
|
||||
)
|
||||
|
||||
#add_custom_command(
|
||||
# OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/ABI_libc_x86.c ${CMAKE_CURRENT_SOURCE_DIR}/ABI_libc.h
|
||||
# DEPENDS ${source_file}
|
||||
# COMMAND env TRAILOFBITS_LIBRARIES=${LIBRARY_REPOSITORY_ROOT} python3 ${CMAKE_CURRENT_SOURCE_DIR}/../generate_abi_wrapper.py
|
||||
# --arch "x86" --type "c" --input ${CMAKE_CURRENT_SOURCE_DIR}/ABI_libc.pph --output ${CMAKE_CURRENT_SOURCE_DIR}/ABI_libc_x86.c
|
||||
#)
|
||||
|
||||
#add_custom_command(
|
||||
# OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/ABI_libcpp_amd64.c
|
||||
# DEPENDS ${source_file}
|
||||
# COMMAND env TRAILOFBITS_LIBRARIES=${LIBRARY_REPOSITORY_ROOT} python ${CMAKE_CURRENT_SOURCE_DIR}/../generate_abi_wrapper.py
|
||||
# --arch "amd64" --type "cpp" --input ${CMAKE_CURRENT_SOURCE_DIR}/ABI_libc.pph --output ${CMAKE_CURRENT_SOURCE_DIR}/ABI_libcpp_amd64.c
|
||||
#)
|
||||
|
||||
#add_custom_command(
|
||||
# OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/ABI_libcpp_x86.c
|
||||
# DEPENDS ${source_file}
|
||||
# COMMAND env TRAILOFBITS_LIBRARIES=${LIBRARY_REPOSITORY_ROOT} python ${CMAKE_CURRENT_SOURCE_DIR}/../generate_abi_wrapper.py
|
||||
# --arch "x86" --type "cpp" --input ${CMAKE_CURRENT_SOURCE_DIR}/ABI_libc.pph --output ${CMAKE_CURRENT_SOURCE_DIR}/ABI_libcpp_x86.c
|
||||
#)
|
||||
|
||||
add_runtime_helper(ABI_exceptions_x86 "ABI_exceptions.cpp" 32)
|
||||
add_runtime_helper(ABI_libc_x86 "ABI_libc.c" 32 "ABI_libc.h")
|
||||
#add_runtime_helper(ABI_libcpp_x86 "ABI_libcpp_x86.c" 32 "ABI_libc.h")
|
||||
|
||||
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
|
||||
add_runtime_helper(ABI_exceptions_amd64 "ABI_exceptions.cpp" 64)
|
||||
add_runtime_helper(ABI_libc_amd64 "ABI_libc.c" 64 "ABI_libc.h")
|
||||
# add_runtime_helper(ABI_libcpp_amd64 "ABI_libcpp_amd64.c" 32 "ABI_libc.h")
|
||||
endif()
|
||||
@@ -0,0 +1,5 @@
|
||||
#include "stddef.h"
|
||||
void klee_make_symbolic(void *addr, size_t nbytes, const char *name);
|
||||
void klee_assume(uintptr_t condition);
|
||||
void klee_alloc(unsigned int size);
|
||||
void klee_dealloc(void *ptr);
|
||||
@@ -0,0 +1,276 @@
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import os
|
||||
import sys
|
||||
import argparse
|
||||
import logging
|
||||
from collections import defaultdict
|
||||
|
||||
|
||||
tob_path = os.environ['TRAILOFBITS_LIBRARIES']
|
||||
cc_path = tob_path + "/llvm/bin/clang"
|
||||
|
||||
try:
|
||||
import ccsyspath
|
||||
syspath = ccsyspath.system_include_paths(cc_path)
|
||||
print(syspath)
|
||||
except ImportError:
|
||||
syspath = list()
|
||||
|
||||
|
||||
SUPPORTED_ARCH = ["x86", "amd64"]
|
||||
|
||||
SUPPORTED_LIBRARY_TYPE = ["c", "cpp"]
|
||||
|
||||
ARCH_NAME = ""
|
||||
|
||||
ABI_LIBRARY_TYPE = "c"
|
||||
|
||||
logging.basicConfig(filename="debug.log",level=logging.DEBUG)
|
||||
|
||||
cc_pragma = """
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated"
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
|
||||
"""
|
||||
|
||||
cc_header = """
|
||||
// mcsema ABI library, automatically generated by generate_abi_wrapper.py
|
||||
|
||||
extern char *gets(char *s);
|
||||
|
||||
__attribute__((used))
|
||||
void *__mcsema_externs[] = {
|
||||
"""
|
||||
|
||||
FUNCDECL_LIST = defaultdict(list)
|
||||
|
||||
FUNCDECL_MANGLED_NAME = defaultdict(list)
|
||||
|
||||
LOCAL_HEADERS = []
|
||||
|
||||
# Check if the file exist at the given paths
|
||||
def file_exist(all_dirs, file):
|
||||
""" Check if file exist.
|
||||
"""
|
||||
for dir in all_dirs:
|
||||
path = str(dir) + '/' + str(file)
|
||||
if os.path.exists(path):
|
||||
return True
|
||||
return os.path.exists(str(file))
|
||||
|
||||
# Process the function types and remove the `__attribute__((...))` identifier
|
||||
# from the function types
|
||||
def process_function_types(type_string):
|
||||
""" Pre-process the function types for the Funcdecl
|
||||
"""
|
||||
split_string = type_string.split(' ')
|
||||
return ' '.join(str for str in split_string if '__attribute__' not in str)
|
||||
|
||||
def get_function_pointer(type_string):
|
||||
""" convert the function types to the pointer type
|
||||
"""
|
||||
return type_string[0:type_string.find('(')-1] + " (*)" + type_string[type_string.find('('):]
|
||||
|
||||
def is_valid_type(type_string):
|
||||
if "_Complex" in type_string or 'typeof' in type_string:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
def is_blacklisted_func(func_name):
|
||||
if 'operator' in func_name:
|
||||
return True
|
||||
return False
|
||||
|
||||
def visit_func_decl(node):
|
||||
""" Visit the function decl node and create a map of
|
||||
function name with the mangled name
|
||||
"""
|
||||
try:
|
||||
from clang.cindex import CursorKind, TypeKind
|
||||
|
||||
except ImportError:
|
||||
return
|
||||
|
||||
if node.kind == CursorKind.FUNCTION_DECL:
|
||||
func_name = node.spelling
|
||||
mangled_name = node.mangled_name
|
||||
if not is_blacklisted_func(func_name):
|
||||
func_type = process_function_types(node.type.spelling)
|
||||
if is_valid_type(func_type):
|
||||
FUNCDECL_LIST[func_name].append([mangled_name, get_function_pointer(func_type), node.location])
|
||||
else:
|
||||
FUNCDECL_LIST[func_name].append([mangled_name, 'void *', node.location])
|
||||
|
||||
for i in node.get_children():
|
||||
visit_func_decl(i)
|
||||
|
||||
|
||||
def write_cc_file(hfile, outfile):
|
||||
""" Generate ABI library source for the c headers;
|
||||
"""
|
||||
basename = os.path.splitext(hfile)[0]
|
||||
|
||||
# generate the abi lib cc file
|
||||
with open(outfile, "w") as s:
|
||||
s.write(cc_pragma)
|
||||
s.write("\n\n")
|
||||
s.write("#include \"{}\"".format(hfile))
|
||||
s.write("\n\n")
|
||||
s.write(cc_header)
|
||||
s.write("\n")
|
||||
for key in FUNCDECL_LIST.keys():
|
||||
type_values = FUNCDECL_LIST[key]
|
||||
for type in type_values:
|
||||
s.write(" //{}\n".format(repr(type[2])))
|
||||
s.write(" (void *)({}),\n".format(key))
|
||||
s.write("};\n")
|
||||
print("Number of functions: {}".format(len(FUNCDECL_LIST)))
|
||||
|
||||
def write_cxx_file(hfile, outfile):
|
||||
""" Generate ABI library source for the c headers;
|
||||
"""
|
||||
basename = os.path.splitext(hfile)[0]
|
||||
|
||||
# generate the abi lib cc file
|
||||
with open(outfile, "w") as s:
|
||||
s.write(cc_pragma)
|
||||
s.write("\n\n")
|
||||
s.write("#include \"{}\"".format(hfile))
|
||||
s.write("\n\n")
|
||||
s.write(cc_header)
|
||||
s.write("\n")
|
||||
for key in FUNCDECL_LIST.iterkeys():
|
||||
key_values = FUNCDECL_LIST[key]
|
||||
for value in key_values:
|
||||
s.write(" //{} {}\n".format(repr(value[2]), value[0]))
|
||||
# get the mangled name
|
||||
s.write("// (void *)({}),\n".format(key))
|
||||
s.write("};\n")
|
||||
print("Number of functions: {}".format(len(FUNCDECL_LIST)))
|
||||
|
||||
def write_library_file(hfile, outfile):
|
||||
""" Generate the library files """
|
||||
try:
|
||||
import clang.cindex
|
||||
cc_index = clang.cindex.Index.create()
|
||||
libc_type = 'c++' if ABI_LIBRARY_TYPE == "cpp" else 'c'
|
||||
if ARCH_NAME.lower() == 'amd64'.lower():
|
||||
tu = cc_index.parse(hfile, args=['-x', libc_type, '-m64'])
|
||||
|
||||
elif ARCH_NAME.lower() == 'x86'.lower():
|
||||
tu = cc_index.parse(hfile, args=['-x', libc_type, '-m32'])
|
||||
|
||||
else:
|
||||
print("Unsupported architecture")
|
||||
|
||||
visit_func_decl(tu.cursor)
|
||||
|
||||
except ImportError:
|
||||
libc_type = 'c++' if ABI_LIBRARY_TYPE == "cpp" else 'c'
|
||||
pass
|
||||
|
||||
if libc_type is 'c':
|
||||
write_cc_file(hfile, outfile)
|
||||
elif libc_type is 'c++':
|
||||
write_cxx_file(hfile, outfile)
|
||||
|
||||
def write_header_file(file, headers):
|
||||
basename = os.path.splitext(file)
|
||||
gen_filename = basename[0] + ".h"
|
||||
print(gen_filename)
|
||||
print(headers)
|
||||
with open(gen_filename, "w") as s:
|
||||
s.write("\n")
|
||||
s.write("// {}\n".format(cc_path))
|
||||
s.write("#ifndef {}_H\n".format(os.path.basename(basename[0]).upper()))
|
||||
s.write("#define {}_H\n".format(os.path.basename(basename[0]).upper()))
|
||||
s.write("""
|
||||
#ifndef __has_include
|
||||
# define __has_include(x) 1
|
||||
#endif
|
||||
|
||||
#define _GNU_SOURCE 1
|
||||
#define _REGEX_RE_COMP
|
||||
#define _BSD_SOURCE 1
|
||||
|
||||
""")
|
||||
s.write("\n")
|
||||
for entry in headers:
|
||||
s.write("#if __has_include(<{}>)\n".format(entry))
|
||||
s.write("# include <{}>\n".format(entry))
|
||||
s.write("#endif\n")
|
||||
for entry in LOCAL_HEADERS:
|
||||
s.write("#if __has_include(\"{}\")\n".format(entry))
|
||||
s.write("# include \"{}\"\n".format(entry))
|
||||
s.write("#endif\n")
|
||||
s.write("\n#endif\n")
|
||||
s.flush()
|
||||
return gen_filename
|
||||
|
||||
|
||||
def parse_headers(infile, outfile):
|
||||
header_files = set()
|
||||
with open(infile, "rb") as f:
|
||||
headers = f.readlines()
|
||||
headers = [x.strip() for x in headers if x.startswith(b"#include")]
|
||||
header_files = [x[x.find(b"<")+1:x.find(b">")] for x in headers if x != ""]
|
||||
for entry in headers:
|
||||
if len(entry.split(b"\"")) > 1:
|
||||
LOCAL_HEADERS.append(entry.split(b"\"")[1])
|
||||
header_files = [x for x in header_files if file_exist(syspath, x)]
|
||||
hfile = write_header_file(infile, header_files)
|
||||
write_library_file(hfile, outfile)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
|
||||
parser.add_argument(
|
||||
'--arch',
|
||||
help='Name of the architecture.',
|
||||
required=True)
|
||||
|
||||
parser.add_argument(
|
||||
'--type',
|
||||
help='ABI Library types c/c++.',
|
||||
required=True)
|
||||
|
||||
parser.add_argument(
|
||||
"--input",
|
||||
help="The input pre-processed header file",
|
||||
required=True)
|
||||
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
help="The output file generated with the script",
|
||||
required=True)
|
||||
|
||||
args = parser.parse_args(args=sys.argv[1:])
|
||||
|
||||
ARCH_NAME = args.arch
|
||||
if ARCH_NAME not in SUPPORTED_ARCH:
|
||||
logger.debug("Arch {} is not supported!".format(args.arch))
|
||||
|
||||
ABI_LIBRARY_TYPE = args.type
|
||||
if ABI_LIBRARY_TYPE not in SUPPORTED_LIBRARY_TYPE:
|
||||
logger.debug("Library type {} not supported!".format(args.type))
|
||||
|
||||
syspath.append(os.path.dirname(os.path.abspath(args.input)))
|
||||
parse_headers(args.input, args.output)
|
||||
+11
-10
@@ -1,17 +1,18 @@
|
||||
/*
|
||||
* Copyright (c) 2017 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#define MCSEMA_VERSION_STRING "@MCSEMA_VERSION_STRING@"
|
||||
|
||||
@@ -1,5 +1,20 @@
|
||||
#!/bin/sh
|
||||
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# Needed to process multiple arguments to docker image
|
||||
|
||||
V=""
|
||||
|
||||
+11
-10
@@ -1,16 +1,17 @@
|
||||
# Copyright (c) 2017 Trail of Bits, Inc.
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# 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 Affero General Public License for more details.
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import argparse
|
||||
import multiprocessing
|
||||
|
||||
+11
-10
@@ -1,17 +1,18 @@
|
||||
#!/usr/bin/env python
|
||||
# Copyright (c) 2017 Trail of Bits, Inc.
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# 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 Affero General Public License for more details.
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
|
||||
+16
-10
@@ -1,17 +1,19 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Copyright (c) 2017 Trail of Bits, Inc.
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# 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 Affero General Public License for more details.
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specifi
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"
|
||||
SOURCE_DIR="${SCRIPT_DIR}/../"
|
||||
@@ -141,7 +143,11 @@ linux_initialize() {
|
||||
libstdc++6:i386 \
|
||||
zlib1g-dev:i386 \
|
||||
liblzma-dev:i386 \
|
||||
libtinfo-dev:i386
|
||||
libtinfo-dev:i386
|
||||
|
||||
# install clang and ccsyspath for ABI libraries generation
|
||||
pip install clang ccsyspath
|
||||
|
||||
if [ $? -ne 0 ] ; then
|
||||
printf " x Could not install the required dependencies\n"
|
||||
return 1
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
# Copyright (c) 2019 Trail of Bits, Inc.
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# 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 Affero General Public License for more details.
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
class Colors:
|
||||
class c:
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (c) 2019 Trail of Bits, Inc.
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# 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 Affero General Public License for more details.
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import argparse
|
||||
import os
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (c) 2019 Trail of Bits, Inc.
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# 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 Affero General Public License for more details.
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import argparse
|
||||
import operator
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (c) 2019 Trail of Bits, Inc.
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# 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 Affero General Public License for more details.
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import os
|
||||
import shutil
|
||||
|
||||
@@ -1,3 +1,18 @@
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import json
|
||||
import operator
|
||||
import os
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (c) 2019 Trail of Bits, Inc.
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# 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 Affero General Public License for more details.
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import argparse
|
||||
import difflib
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
# Copyright (c) 2019 Trail of Bits, Inc.
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# 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 Affero General Public License for more details.
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import os
|
||||
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
# Copyright (c) 2017 Trail of Bits, Inc.
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# 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 Affero General Public License for more details.
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specifi
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# CMAKE_C_COMPILER or CMAKE_CXX_COMPILER *must* be set before project()
|
||||
# otherwise it causes infinite loops for some cmake versions
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,4 +1,20 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
set -e
|
||||
|
||||
ARCHS=("x86" "amd64")
|
||||
|
||||
@@ -15,7 +15,7 @@ project(ls_amd64)
|
||||
cmake_minimum_required(VERSION 3.2)
|
||||
|
||||
set(PROJECT_CXXFLAGS -Wall -Werror)
|
||||
set(PROJECT_LINKERFLAGS -lm)
|
||||
set(PROJECT_LINKERFLAGS -lm -lselinux)
|
||||
|
||||
AddBinaryTest(${PROJECT_NAME}
|
||||
BINARY ${PROJECT_NAME}
|
||||
|
||||
@@ -15,7 +15,7 @@ project(nc_amd64)
|
||||
cmake_minimum_required(VERSION 3.2)
|
||||
|
||||
set(PROJECT_CXXFLAGS -Wall -Werror)
|
||||
set(PROJECT_LINKERFLAGS -lm -lresolv)
|
||||
set(PROJECT_LINKERFLAGS -lm -lresolv -lbsd)
|
||||
|
||||
AddBinaryTest(${PROJECT_NAME}
|
||||
BINARY ${PROJECT_NAME}
|
||||
|
||||
@@ -2,7 +2,7 @@ project(xz_amd64)
|
||||
cmake_minimum_required(VERSION 3.2)
|
||||
|
||||
set(PROJECT_CXXFLAGS -Wall -Werror)
|
||||
set(PROJECT_LINKERFLAGS -lm -ldl -llzma)
|
||||
set(PROJECT_LINKERFLAGS -lm -ldl -llzma -lpthread)
|
||||
|
||||
AddBinaryTest(${PROJECT_NAME}
|
||||
BINARY ${PROJECT_NAME}
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
#!/usr/bin/env python2
|
||||
|
||||
# Copyright (c) 2017 Trail of Bits, Inc.
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# 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 Affero General Public License for more details.
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specifi
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
+12
-10
@@ -1,17 +1,19 @@
|
||||
#!/usr/bin/env python
|
||||
# Copyright (c) 2017 Trail of Bits, Inc.
|
||||
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# 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 Affero General Public License for more details.
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import argparse
|
||||
import itertools
|
||||
|
||||
+12
-10
@@ -1,17 +1,19 @@
|
||||
#!/usr/bin/env python
|
||||
# Copyright (c) 2017 Trail of Bits, Inc.
|
||||
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# 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 Affero General Public License for more details.
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import os.path
|
||||
import subprocess
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
#!/usr/bin/env python
|
||||
# Copyright (c) 2017 Trail of Bits, Inc.
|
||||
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# 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 Affero General Public License for more details.
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import argparse
|
||||
import os
|
||||
@@ -24,7 +26,7 @@ import traceback
|
||||
import textwrap
|
||||
|
||||
|
||||
SUPPORTED_OS = ('linux', 'windows',)
|
||||
SUPPORTED_OS = ('linux', 'macos', 'windows', 'solaris')
|
||||
SUPPORTED_ARCH = ('x86', 'x86_avx', 'x86_avx512',
|
||||
'amd64', 'amd64_avx', 'amd64_avx512',
|
||||
'aarch64')
|
||||
@@ -98,7 +100,7 @@ def main():
|
||||
arg_parser.add_argument(
|
||||
'--entrypoint',
|
||||
help="The entrypoint where disassembly should begin",
|
||||
required=True)
|
||||
required=False)
|
||||
|
||||
args, command_args = arg_parser.parse_known_args()
|
||||
|
||||
@@ -149,10 +151,7 @@ def main():
|
||||
ret = 1
|
||||
try:
|
||||
if 'ida' in args.disassembler:
|
||||
if 'idat' in args.disassembler:
|
||||
import ida7.disass as disass
|
||||
else:
|
||||
import ida.disass as disass
|
||||
import ida7.disass as disass
|
||||
ret = disass.execute(args, fixed_command_args)
|
||||
# in case IDA somehow says success, but no output was generated
|
||||
if not os.path.isfile(args.output):
|
||||
@@ -165,11 +164,7 @@ def main():
|
||||
# remove the zero-sized file
|
||||
os.unlink(args.output)
|
||||
ret = 1
|
||||
elif 'binja' in args.disassembler or 'binaryninja' in args.disassembler:
|
||||
if not _find_binary_ninja(args.disassembler):
|
||||
arg_parser.error("Could not `import binaryninja`. Is it in your PYTHONPATH?")
|
||||
from binja.cfg import get_cfg
|
||||
ret = get_cfg(args, fixed_command_args)
|
||||
|
||||
elif 'dyninst' in args.disassembler:
|
||||
# TODO: This can almost certainly be done in cleaner way
|
||||
pass_args = [
|
||||
|
||||
@@ -1,637 +0,0 @@
|
||||
# Copyright (c) 2017 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import argparse
|
||||
import binaryninja as binja
|
||||
from binaryninja.enums import (
|
||||
SymbolType, TypeClass,
|
||||
LowLevelILOperation, RegisterValueType,
|
||||
InstructionTextTokenType
|
||||
)
|
||||
import logging
|
||||
import os
|
||||
from Queue import Queue
|
||||
from collections import defaultdict
|
||||
|
||||
import CFG_pb2
|
||||
import util
|
||||
import xrefs
|
||||
import jmptable
|
||||
import vars
|
||||
from debug import *
|
||||
|
||||
log = logging.getLogger(util.LOGNAME)
|
||||
|
||||
BINJA_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
DISASS_DIR = os.path.dirname(BINJA_DIR)
|
||||
|
||||
EXT_MAP = {}
|
||||
EXT_DATA_MAP = {}
|
||||
JMP_TABLES = []
|
||||
|
||||
CCONV_TYPES = {
|
||||
'C': CFG_pb2.ExternalFunction.CallerCleanup,
|
||||
'E': CFG_pb2.ExternalFunction.CalleeCleanup,
|
||||
'F': CFG_pb2.ExternalFunction.FastCall
|
||||
}
|
||||
|
||||
BINJA_CCONV_TYPES = {
|
||||
'cdecl': CFG_pb2.ExternalFunction.CallerCleanup,
|
||||
'stdcall': CFG_pb2.ExternalFunction.CalleeCleanup,
|
||||
'fastcall': CFG_pb2.ExternalFunction.FastCall
|
||||
}
|
||||
|
||||
RECOVERED = set()
|
||||
TO_RECOVER = Queue()
|
||||
|
||||
RECOVER_OPTS = {
|
||||
'stack_vars': False
|
||||
}
|
||||
|
||||
def queue_func(addr):
|
||||
if addr not in RECOVERED:
|
||||
TO_RECOVER.put(addr)
|
||||
|
||||
|
||||
def func_has_return_type(func):
|
||||
rtype = func.function_type.return_value.type_class
|
||||
return rtype != TypeClass.VoidTypeClass
|
||||
|
||||
|
||||
def recover_ext_func(bv, pb_mod, sym):
|
||||
""" Recover external function information
|
||||
Uses the map of predefined externals if possible
|
||||
|
||||
Args:
|
||||
bv (binja.BinaryView)
|
||||
pb_mod (CFG_pb2.Module)
|
||||
sym (binaryninja.types.Symbol)
|
||||
"""
|
||||
DEBUG("Recovering external function {} at {:x}".format(sym.name, sym.address))
|
||||
if sym.name in EXT_MAP:
|
||||
DEBUG('Found defined external function: {} @ {:x}'.format(sym.name, sym.address))
|
||||
|
||||
args, cconv, ret, sign = EXT_MAP[sym.name]
|
||||
func = bv.get_function_at(sym.address)
|
||||
if func is None:
|
||||
return
|
||||
|
||||
pb_extfn = pb_mod.external_funcs.add()
|
||||
pb_extfn.name = sym.name
|
||||
pb_extfn.ea = sym.address
|
||||
pb_extfn.argument_count = args
|
||||
pb_extfn.cc = cconv
|
||||
pb_extfn.has_return = func_has_return_type(func)
|
||||
pb_extfn.no_return = ret == 'Y'
|
||||
pb_extfn.is_weak = False # TODO: figure out how to decide this
|
||||
|
||||
else:
|
||||
WARN("External function is not part of defs file")
|
||||
|
||||
func = bv.get_function_at(sym.address)
|
||||
ftype = func.function_type
|
||||
|
||||
pb_extfn = pb_mod.external_funcs.add()
|
||||
pb_extfn.name = sym.name
|
||||
pb_extfn.ea = sym.address
|
||||
pb_extfn.argument_count = len(ftype.parameters)
|
||||
pb_extfn.has_return = func_has_return_type(func)
|
||||
pb_extfn.no_return = not ftype.can_return
|
||||
pb_extfn.is_weak = False # TODO: figure out how to decide this
|
||||
|
||||
# Assume cdecl if the type is unknown
|
||||
cconv = ftype.calling_convention
|
||||
if cconv is not None and cconv.name in BINJA_CCONV_TYPES:
|
||||
pb_extfn.cc = BINJA_CCONV_TYPES[str(cconv)]
|
||||
else:
|
||||
pb_extfn.cc = CFG_pb2.ExternalFunction.CallerCleanup
|
||||
|
||||
|
||||
def recover_ext_var(bv, pb_mod, sym):
|
||||
""" Recover external variable information
|
||||
|
||||
Args:
|
||||
bv (binja.BinaryView)
|
||||
pb_mod (CFG_pb2.Module)
|
||||
sym (binja.types.Symbol)
|
||||
"""
|
||||
if sym.name in EXT_DATA_MAP:
|
||||
DEBUG("Recovering external variable {} at {:x}".format(sym.name, sym.address))
|
||||
|
||||
pb_extvar = pb_mod.external_vars.add()
|
||||
pb_extvar.name = sym.name
|
||||
pb_extvar.ea = sym.address
|
||||
pb_extvar.size = EXT_DATA_MAP[sym.name]
|
||||
pb_extvar.is_weak = False # TODO: figure out how to decide this
|
||||
pb_extvar.is_thread_local = util.is_tls_section(bv, sym.address)
|
||||
else:
|
||||
ERROR("Unknown external variable {} at {:x}".format(sym.name, sym.address))
|
||||
|
||||
|
||||
def recover_externals(bv, pb_mod):
|
||||
"""Recover info about all external symbols"""
|
||||
DEBUG("Recovering externals")
|
||||
DEBUG_PUSH()
|
||||
for sym in bv.get_symbols():
|
||||
if sym.type == SymbolType.ImportedFunctionSymbol:
|
||||
recover_ext_func(bv, pb_mod, sym)
|
||||
|
||||
if sym.type == SymbolType.ImportedDataSymbol:
|
||||
recover_ext_var(bv, pb_mod, sym)
|
||||
DEBUG_POP()
|
||||
|
||||
_BYTE_WIDTH_NAME = {4: "dword", 8: "qword"}
|
||||
|
||||
def recover_section_cross_references(bv, pb_seg, real_sect, sect_start, sect_end):
|
||||
""" Find references to other code/data in this section
|
||||
|
||||
Args:
|
||||
bv (binja.BinaryView)
|
||||
pb_seg (CFG_pb2.Segment)
|
||||
real_sect (binja.binaryview.Section)
|
||||
sect_start (int)
|
||||
sect_end (int)
|
||||
"""
|
||||
entry_width = util.clamp(real_sect.align, 4, bv.address_size)
|
||||
read_val = {4: util.read_dword,
|
||||
8: util.read_qword}[entry_width]
|
||||
|
||||
DEBUG("Recovering references in [{:x}, {:x}) of section {}".format(
|
||||
sect_start, sect_end, real_sect.name))
|
||||
|
||||
DEBUG_PUSH()
|
||||
for addr in xrange(sect_start, sect_end, entry_width):
|
||||
xref = read_val(bv, addr)
|
||||
|
||||
if not util.is_valid_addr(bv, xref):
|
||||
continue
|
||||
|
||||
# Skip this xref if it's a jmp table entry
|
||||
if any(xref in tbl.targets for tbl in JMP_TABLES):
|
||||
continue
|
||||
|
||||
width_name = _BYTE_WIDTH_NAME.get(entry_width, "{}-byte".format(entry_width))
|
||||
DEBUG("Adding {} reference from {:x} to {:x}".format(width_name, addr, xref))
|
||||
|
||||
pb_ref = pb_seg.xrefs.add()
|
||||
pb_ref.ea = addr
|
||||
pb_ref.width = entry_width
|
||||
pb_ref.target_ea = xref
|
||||
pb_ref.target_name = util.find_symbol_name(bv, xref)
|
||||
pb_ref.target_is_code = util.is_code(bv, xref)
|
||||
|
||||
if util.is_tls_section(bv, addr):
|
||||
pb_ref.target_fixup_kind = CFG_pb2.DataReference.OffsetFromThreadBase
|
||||
else:
|
||||
pb_ref.target_fixup_kind = CFG_pb2.DataReference.Absolute
|
||||
|
||||
DEBUG_POP()
|
||||
|
||||
|
||||
def recover_section_vars(bv, pb_seg, sect_start, sect_end):
|
||||
""" Gather any symbols that point to data in this section
|
||||
|
||||
Args:x
|
||||
bv (binja.BinaryView)
|
||||
pb_seg (CFG_pb2.Segment)
|
||||
sect_start (int)
|
||||
sect_end (int)
|
||||
"""
|
||||
|
||||
DEBUG("Recovering variables in [{:x}, {:x}) of section {}".format(
|
||||
sect_start, sect_end, pb_seg.name))
|
||||
DEBUG_PUSH()
|
||||
for sym in bv.get_symbols():
|
||||
# Ignore functions and externals
|
||||
if sym.type in [SymbolType.FunctionSymbol,
|
||||
SymbolType.ImportedFunctionSymbol,
|
||||
SymbolType.ImportedDataSymbol,
|
||||
SymbolType.ImportAddressSymbol]:
|
||||
continue
|
||||
|
||||
if sect_start <= sym.address < sect_end:
|
||||
DEBUG("Adding variable {} at {:x}".format(sym.name, sym.address))
|
||||
pb_segvar = pb_seg.vars.add()
|
||||
pb_segvar.ea = sym.address
|
||||
pb_segvar.name = sym.name
|
||||
|
||||
DEBUG_POP()
|
||||
|
||||
def recover_sections(bv, pb_mod):
|
||||
# Collect all address to split on
|
||||
sec_addrs = set()
|
||||
for sect in bv.sections.values():
|
||||
sec_addrs.add(sect.start)
|
||||
sec_addrs.add(sect.end)
|
||||
|
||||
global_starts = [gvar.ea for gvar in pb_mod.global_vars]
|
||||
sec_addrs.update(global_starts)
|
||||
|
||||
# Process all the split segments
|
||||
sec_splits = sorted(list(sec_addrs))
|
||||
for start_addr, end_addr in zip(sec_splits[:-1], sec_splits[1:]):
|
||||
real_sect = util.get_section_at(bv, start_addr)
|
||||
|
||||
# Ignore any gaps
|
||||
if real_sect is None:
|
||||
continue
|
||||
|
||||
DEBUG("Recovering [{:x}, {:x}) from segment {}".format(
|
||||
start_addr, end_addr, real_sect.name))
|
||||
|
||||
pb_seg = pb_mod.segments.add()
|
||||
pb_seg.name = real_sect.name
|
||||
pb_seg.ea = start_addr
|
||||
pb_seg.data = bv.read(start_addr, end_addr - start_addr)
|
||||
pb_seg.is_external = util.is_section_external(bv, real_sect)
|
||||
pb_seg.read_only = not util.is_readable(bv, start_addr)
|
||||
pb_seg.is_thread_local = util.is_tls_section(bv, start_addr)
|
||||
|
||||
sym = bv.get_symbol_at(start_addr)
|
||||
pb_seg.is_exported = sym is not None and start_addr in global_starts
|
||||
if pb_seg.is_exported and sym.name != real_sect.name:
|
||||
pb_seg.variable_name = sym.name
|
||||
|
||||
recover_section_vars(bv, pb_seg, start_addr, end_addr)
|
||||
recover_section_cross_references(bv, pb_seg, real_sect, start_addr, end_addr)
|
||||
|
||||
|
||||
def is_local_noreturn(bv, il):
|
||||
"""
|
||||
Args:
|
||||
bv (binja.BinaryView)
|
||||
il (binja.LowLevelILInstruction):
|
||||
|
||||
Returns:
|
||||
bool
|
||||
"""
|
||||
if il.operation in [LowLevelILOperation.LLIL_CALL,
|
||||
LowLevelILOperation.LLIL_JUMP,
|
||||
LowLevelILOperation.LLIL_GOTO]:
|
||||
# Resolve the destination address
|
||||
tgt_addr = None
|
||||
dst = il.dest
|
||||
|
||||
# GOTOs have an il index as the arg
|
||||
if isinstance(dst, int):
|
||||
tgt_addr = il.function[dst].address
|
||||
|
||||
# Others will have an expression as the argument
|
||||
elif isinstance(dst, binja.LowLevelILInstruction):
|
||||
# Immediate address
|
||||
if dst.operation in [LowLevelILOperation.LLIL_CONST,
|
||||
LowLevelILOperation.LLIL_CONST_PTR]:
|
||||
tgt_addr = dst.constant
|
||||
|
||||
# Register
|
||||
elif dst.operation == LowLevelILOperation.LLIL_REG:
|
||||
# Attempt to resolve the register value
|
||||
func = il.function.source_function
|
||||
reg_val = func.get_reg_value_at(il.address, dst.src)
|
||||
if reg_val.type == RegisterValueType.ConstantValue:
|
||||
tgt_addr = reg_val.value
|
||||
|
||||
# If a target address was recovered, check if it's in a noreturn function
|
||||
if tgt_addr is not None:
|
||||
tgt_func = util.get_func_containing(bv, tgt_addr)
|
||||
return not tgt_func.function_type.can_return
|
||||
|
||||
# Other instructions that terminate control flow
|
||||
return il.operation in [LowLevelILOperation.LLIL_TRAP,
|
||||
LowLevelILOperation.LLIL_BP]
|
||||
|
||||
|
||||
_CFG_INST_XREF_TYPE_TO_NAME = {
|
||||
CFG_pb2.CodeReference.ImmediateOperand: "imm",
|
||||
CFG_pb2.CodeReference.MemoryOperand: "mem",
|
||||
CFG_pb2.CodeReference.MemoryDisplacementOperand: "disp",
|
||||
CFG_pb2.CodeReference.ControlFlowOperand: "flow"
|
||||
}
|
||||
|
||||
|
||||
def add_xref(bv, pb_inst, target, mask, optype):
|
||||
xref = pb_inst.xrefs.add()
|
||||
xref.ea = target
|
||||
xref.operand_type = optype
|
||||
|
||||
debug_mask = ""
|
||||
if mask:
|
||||
xref.mask = mask
|
||||
debug_mask = " & {:x}".format(mask)
|
||||
|
||||
sym_name = util.find_symbol_name(bv, target)
|
||||
if len(sym_name) > 0:
|
||||
xref.name = sym_name
|
||||
|
||||
if util.is_code(bv, target):
|
||||
xref.target_type = CFG_pb2.CodeReference.CodeTarget
|
||||
debug_type = "code"
|
||||
else:
|
||||
xref.target_type = CFG_pb2.CodeReference.DataTarget
|
||||
debug_type = "data"
|
||||
|
||||
if util.is_external_ref(bv, target):
|
||||
xref.location = CFG_pb2.CodeReference.External
|
||||
debug_loc = "external"
|
||||
else:
|
||||
xref.location = CFG_pb2.CodeReference.Internal
|
||||
debug_loc = "internal"
|
||||
|
||||
# If the target happens to be a function, queue it for recovery
|
||||
if bv.get_function_at(target) is not None:
|
||||
queue_func(target)
|
||||
|
||||
debug_op = _CFG_INST_XREF_TYPE_TO_NAME[optype]
|
||||
|
||||
return "({} {} {} {:x}{} {})".format(
|
||||
debug_type, debug_op, debug_loc, target, debug_mask, sym_name)
|
||||
|
||||
def read_inst_bytes(bv, il):
|
||||
""" Get the opcode bytes for an instruction
|
||||
Args:
|
||||
bv (binja.BinaryView)
|
||||
il (binja.LowLevelILInstruction)
|
||||
Returns:
|
||||
str
|
||||
"""
|
||||
inst_len = bv.get_instruction_length(il.address)
|
||||
return bv.read(il.address, inst_len)
|
||||
|
||||
|
||||
def recover_inst(bv, func, pb_block, pb_inst, il, all_il, is_last):
|
||||
"""
|
||||
Args:
|
||||
bv (binja.BinaryView)
|
||||
pb_inst (CFG_pb2.Instruction)
|
||||
il (binaryninja.lowlevelil.LowLevelILInstruction)
|
||||
all_il (list): Collection of all il instructions at this address
|
||||
(e.g. all instructions expanded from a cmov)
|
||||
"""
|
||||
pb_inst.ea = il.address
|
||||
pb_inst.bytes = read_inst_bytes(bv, il)
|
||||
|
||||
# Search all il instructions at the current address for xrefs
|
||||
refs = set()
|
||||
for il_exp in all_il:
|
||||
refs.update(xrefs.get_xrefs(bv, func, il_exp))
|
||||
|
||||
debug_refs = []
|
||||
|
||||
# Add all discovered xrefs to pb_inst
|
||||
for ref in refs:
|
||||
debug_refs.append(add_xref(bv, pb_inst, ref.addr, ref.mask, ref.cfg_type))
|
||||
|
||||
if is_local_noreturn(bv, il):
|
||||
pb_inst.local_noreturn = True
|
||||
|
||||
# Add the target of a tail call as a successor
|
||||
if util.is_jump_tail_call(bv, il):
|
||||
tgt = il.dest.constant
|
||||
pb_block.successor_eas.append(tgt)
|
||||
|
||||
table = jmptable.get_jmptable(bv, il)
|
||||
if table is not None:
|
||||
debug_refs.append(add_xref(bv, pb_inst, table.base_addr, 0, CFG_pb2.CodeReference.MemoryDisplacementOperand))
|
||||
JMP_TABLES.append(table)
|
||||
|
||||
# Add any missing successors
|
||||
for tgt in table.targets:
|
||||
if tgt not in pb_block.successor_eas:
|
||||
pb_block.successor_eas.append(tgt)
|
||||
|
||||
DEBUG("I: {:x} {}".format(il.address, " ".join(debug_refs)))
|
||||
|
||||
if is_last:
|
||||
if len(pb_block.successor_eas):
|
||||
DEBUG(" Successors: {}".format(", ".join("{:x}".format(ea) for ea in pb_block.successor_eas)))
|
||||
else:
|
||||
DEBUG(" No successors")
|
||||
|
||||
|
||||
def add_block(pb_func, block):
|
||||
"""
|
||||
Args:
|
||||
pb_func (CFG_pb2.Function)
|
||||
block (binaryninja.basicblock.BasicBlock)
|
||||
|
||||
Returns:
|
||||
CFG_pb2.Block
|
||||
"""
|
||||
DEBUG("BB: {:x}".format(block.start))
|
||||
pb_block = pb_func.blocks.add()
|
||||
pb_block.ea = block.start
|
||||
pb_block.successor_eas.extend(edge.target.start for edge in block.outgoing_edges)
|
||||
return pb_block
|
||||
|
||||
|
||||
def fix_tail_call_targets(bv, func):
|
||||
"""
|
||||
Binja will "inline" tail calls into the current function, resulting in the
|
||||
same blocks appearing in multiple functions. This detects if this happened
|
||||
and defines a function at the first inlined block so nothing is duplicated
|
||||
|
||||
Args:
|
||||
bv (binja.BinaryView)
|
||||
func (binja.Function)
|
||||
"""
|
||||
for block in func.basic_blocks:
|
||||
# This will return a list of all basic blocks starting at the same address
|
||||
# The same block appearing in different functions (after inlining)
|
||||
# will appear as multiple `BasicBlock`s
|
||||
all_blocks = bv.get_basic_blocks_at(block.start)
|
||||
|
||||
# There should only be a single block found
|
||||
if len(all_blocks) > 1:
|
||||
log.debug('Block 0x%x exists in multiple functions, defining a new function here', block.start)
|
||||
|
||||
# Define a function here and reanalyze
|
||||
# All blocks contained in this new function will not be picked up
|
||||
# in the remainder of this loop after analysis
|
||||
bv.add_function(block.start)
|
||||
bv.update_analysis_and_wait()
|
||||
|
||||
|
||||
def recover_function(bv, pb_mod, addr, is_entry=False):
|
||||
func = bv.get_function_at(addr)
|
||||
if func is None:
|
||||
log.error('No function defined at 0x%x, skipping', addr)
|
||||
return
|
||||
|
||||
if func.symbol.type == SymbolType.ImportedFunctionSymbol:
|
||||
# Externals are recovered later, skip this
|
||||
log.warn("Skipping external function '%s' in main CFG recovery", func.symbol.name)
|
||||
return
|
||||
|
||||
# Initialize the protobuf for this function
|
||||
DEBUG("Recovering function {} at {:x}".format(func.symbol.name, addr))
|
||||
|
||||
pb_func = pb_mod.funcs.add()
|
||||
pb_func.ea = addr
|
||||
pb_func.is_entrypoint = is_entry
|
||||
pb_func.name = func.symbol.name
|
||||
|
||||
# Recover all basic blocks
|
||||
il_groups = util.collect_il_groups(func.lifted_il)
|
||||
var_refs = defaultdict(list)
|
||||
for block in func:
|
||||
DEBUG_PUSH()
|
||||
pb_block = add_block(pb_func, block)
|
||||
DEBUG_PUSH()
|
||||
|
||||
# Recover every instruction in the block
|
||||
insts = list(block.disassembly_text)
|
||||
for inst in insts:
|
||||
# Skip over anything that isn't an instruction
|
||||
if inst.tokens[0].type != InstructionTextTokenType.InstructionToken:
|
||||
continue
|
||||
il = func.get_lifted_il_at(inst.address)
|
||||
all_il = il_groups[inst.address]
|
||||
|
||||
pb_inst = pb_block.instructions.add()
|
||||
recover_inst(bv, func, pb_block, pb_inst, il, all_il, is_last=inst==insts[-1])
|
||||
|
||||
# Find any references to stack vars in this instruction
|
||||
if RECOVER_OPTS['stack_vars']:
|
||||
vars.find_stack_var_refs(bv, inst, il, var_refs)
|
||||
|
||||
DEBUG_POP()
|
||||
DEBUG_POP()
|
||||
|
||||
# Recover stack variables
|
||||
if RECOVER_OPTS['stack_vars']:
|
||||
vars.recover_stack_vars(pb_func, func, var_refs)
|
||||
|
||||
|
||||
def recover_cfg(bv, args):
|
||||
pb_mod = CFG_pb2.Module()
|
||||
pb_mod.name = os.path.basename(bv.file.filename)
|
||||
|
||||
# Find the chosen entrypoint in the binary
|
||||
if args.entrypoint not in bv.symbols:
|
||||
log.fatal('Entrypoint not found: %s', args.entrypoint)
|
||||
entry_addr = bv.symbols[args.entrypoint].address
|
||||
|
||||
# Recover the entrypoint func separately
|
||||
log.debug('Recovering CFG')
|
||||
recover_function(bv, pb_mod, entry_addr, is_entry=True)
|
||||
|
||||
# Recover any discovered functions until there are none left
|
||||
while not TO_RECOVER.empty():
|
||||
addr = TO_RECOVER.get()
|
||||
|
||||
if addr in RECOVERED:
|
||||
continue
|
||||
RECOVERED.add(addr)
|
||||
|
||||
recover_function(bv, pb_mod, addr)
|
||||
|
||||
log.debug('Recovering Globals')
|
||||
vars.recover_globals(bv, pb_mod)
|
||||
|
||||
log.debug('Processing Segments')
|
||||
recover_sections(bv, pb_mod)
|
||||
|
||||
log.debug('Recovering Externals')
|
||||
recover_externals(bv, pb_mod)
|
||||
|
||||
return pb_mod
|
||||
|
||||
|
||||
def parse_defs_file(bv, path):
|
||||
log.debug('Parsing %s', path)
|
||||
with open(path) as f:
|
||||
for line in f.readlines():
|
||||
# Skip comments/empty lines
|
||||
if len(line.strip()) == 0 or line[0] == '#':
|
||||
continue
|
||||
|
||||
if line.startswith('DATA:'):
|
||||
# DATA: (name) (PTR | size)
|
||||
_, dname, dsize = line.split()
|
||||
if 'PTR' in dsize:
|
||||
dsize = bv.address_size
|
||||
EXT_DATA_MAP[dname] = int(dsize)
|
||||
else:
|
||||
# (name) (# args) (cconv) (ret) [(sign) | None]
|
||||
fname, args, cconv, ret, sign = (line.split() + [None])[:5]
|
||||
|
||||
if cconv not in CCONV_TYPES:
|
||||
log.fatal('Unknown calling convention: %s', cconv)
|
||||
exit(1)
|
||||
|
||||
if ret not in ['Y', 'N']:
|
||||
log.fatal('Unknown return type: %s', ret)
|
||||
exit(1)
|
||||
|
||||
EXT_MAP[fname] = (int(args), CCONV_TYPES[cconv], ret, sign)
|
||||
|
||||
|
||||
def get_cfg(args, fixed_args):
|
||||
# Parse any additional args
|
||||
parser = argparse.ArgumentParser()
|
||||
|
||||
parser.add_argument(
|
||||
'--recover-stack-vars',
|
||||
help='Flag to enable stack variable recovery',
|
||||
default=False,
|
||||
action='store_true')
|
||||
|
||||
parser.add_argument(
|
||||
"--std-defs",
|
||||
action='append',
|
||||
type=str,
|
||||
default=[],
|
||||
help="std_defs file: definitions and calling conventions of imported functions and data")
|
||||
|
||||
extra_args = parser.parse_args(fixed_args)
|
||||
|
||||
if extra_args.recover_stack_vars:
|
||||
RECOVER_OPTS['stack_vars'] = True
|
||||
|
||||
# Setup logger
|
||||
util.init_logger(args.log_file)
|
||||
|
||||
# Load the binary in binja
|
||||
bv = util.load_binary(args.binary)
|
||||
|
||||
# Once for good measure.
|
||||
bv.add_analysis_option("linearsweep")
|
||||
bv.update_analysis_and_wait()
|
||||
|
||||
# Twice for good luck!
|
||||
bv.add_analysis_option("linearsweep")
|
||||
bv.update_analysis_and_wait()
|
||||
|
||||
# Collect all paths to defs files
|
||||
log.debug('Parsing definitions files')
|
||||
def_paths = set(map(os.path.abspath, extra_args.std_defs))
|
||||
def_paths.add(os.path.join(DISASS_DIR, 'defs', '{}.txt'.format(args.os))) # default defs file
|
||||
|
||||
# Parse all of the defs files
|
||||
for fpath in def_paths:
|
||||
if os.path.isfile(fpath):
|
||||
parse_defs_file(bv, fpath)
|
||||
else:
|
||||
log.warn('%s is not a file', fpath)
|
||||
|
||||
# Recover module
|
||||
log.debug('Starting analysis')
|
||||
pb_mod = recover_cfg(bv, args)
|
||||
|
||||
# Save cfg
|
||||
log.debug('Saving to file: %s', args.output)
|
||||
with open(args.output, 'wb') as f:
|
||||
f.write(pb_mod.SerializeToString())
|
||||
|
||||
return 0
|
||||
@@ -1,40 +0,0 @@
|
||||
# Copyright (c) 2017 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import logging
|
||||
import util
|
||||
|
||||
log = logging.getLogger(util.LOGNAME)
|
||||
|
||||
|
||||
_DEBUG_PREFIX = ""
|
||||
|
||||
def DEBUG_PUSH():
|
||||
global _DEBUG_PREFIX
|
||||
_DEBUG_PREFIX += " "
|
||||
|
||||
def DEBUG_POP():
|
||||
global _DEBUG_PREFIX
|
||||
_DEBUG_PREFIX = _DEBUG_PREFIX[:-2]
|
||||
|
||||
def DEBUG(s):
|
||||
log.debug("{}{}".format(_DEBUG_PREFIX, str(s)))
|
||||
|
||||
def WARN(s):
|
||||
log.warn("{}{}".format(_DEBUG_PREFIX, str(s)))
|
||||
|
||||
def ERROR(s):
|
||||
log.error("{}{}".format(_DEBUG_PREFIX, str(s)))
|
||||
|
||||
|
||||
@@ -1,144 +0,0 @@
|
||||
# Copyright (c) 2017 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import binaryninja as binja
|
||||
from binaryninja.enums import (
|
||||
LowLevelILOperation, MediumLevelILOperation, RegisterValueType
|
||||
)
|
||||
import logging
|
||||
import util
|
||||
from debug import *
|
||||
|
||||
log = logging.getLogger(util.LOGNAME)
|
||||
|
||||
|
||||
class JMPTable(object):
|
||||
""" Simple container for jump table info """
|
||||
def __init__(self, bv, rel_base, targets, rel_off=0):
|
||||
self.rel_off = rel_off
|
||||
self.rel_base = rel_base
|
||||
|
||||
# Calculate the absolute base address
|
||||
mask = (1 << bv.address_size * 8) - 1
|
||||
self.base_addr = (self.rel_base + self.rel_off) & mask
|
||||
|
||||
self.targets = [t & mask for t in targets]
|
||||
|
||||
|
||||
|
||||
def search_mlil_displ(il, ptr=False, _neg=False):
|
||||
""" Searches for a MLIL_CONST[_PTR] as a child of an ADD or SUB
|
||||
|
||||
Args:
|
||||
il (binja.LowLevelILInstruction): Instruction to parse
|
||||
ptr (bool): Searches for CONST_PTR instead of CONST if True
|
||||
_neg (bool): Used internally to negate the final output if needed
|
||||
|
||||
Returns:
|
||||
int: located value
|
||||
"""
|
||||
# The il may be inside a MLIL_LOAD
|
||||
if il.operation == MediumLevelILOperation.MLIL_LOAD:
|
||||
return search_mlil_displ(il.src, ptr, _neg)
|
||||
|
||||
# Continue left/right for ADD/SUB only
|
||||
if il.operation in [MediumLevelILOperation.MLIL_ADD,
|
||||
MediumLevelILOperation.MLIL_SUB]:
|
||||
_neg = (il.operation == MediumLevelILOperation.MLIL_SUB)
|
||||
return (search_mlil_displ(il.left, ptr, _neg) or
|
||||
search_mlil_displ(il.right, ptr, _neg))
|
||||
|
||||
# Terminate when we find a constant
|
||||
const_type = MediumLevelILOperation.MLIL_CONST_PTR if ptr else MediumLevelILOperation.MLIL_CONST
|
||||
if il.operation == const_type:
|
||||
return il.constant * (-1 if _neg else 1)
|
||||
|
||||
# DEBUG('Reached end of expr: {}'.format(il))
|
||||
|
||||
|
||||
def get_jmptable(bv, il):
|
||||
""" Gathers jump table information (if any) being referenced at the given il
|
||||
|
||||
Args:
|
||||
bv (binja.BinaryView)
|
||||
il (binja.LowLevelILInstruction)
|
||||
|
||||
Returns:
|
||||
JMPTable: Jump table info if found, None otherwise
|
||||
"""
|
||||
# Rule out other instructions
|
||||
op = il.operation
|
||||
if op not in [LowLevelILOperation.LLIL_JUMP_TO, LowLevelILOperation.LLIL_JUMP]:
|
||||
return None
|
||||
|
||||
# Ignore any jmps that have an immediate address
|
||||
if il.dest.operation in [LowLevelILOperation.LLIL_CONST,
|
||||
LowLevelILOperation.LLIL_CONST_PTR]:
|
||||
return None
|
||||
|
||||
# Ignore any jmps that have an immediate dereference (i.e. thunks)
|
||||
if il.dest.operation == LowLevelILOperation.LLIL_LOAD and \
|
||||
il.dest.src.operation in [LowLevelILOperation.LLIL_CONST,
|
||||
LowLevelILOperation.LLIL_CONST_PTR]:
|
||||
return None
|
||||
|
||||
func = il.function.source_function
|
||||
il_func = func.low_level_il
|
||||
|
||||
# Gather all targets of the jump in case binja didn't lift this to LLIL_JUMP_TO
|
||||
successors = []
|
||||
tgt_table = func.get_low_level_il_at(il.address).dest.possible_values
|
||||
if tgt_table.type == RegisterValueType.LookupTableValue:
|
||||
successors.extend(tgt_table.mapping.values())
|
||||
|
||||
# Should be able to find table info now
|
||||
tbl = None
|
||||
|
||||
# Jumping to a register
|
||||
if il.dest.operation == LowLevelILOperation.LLIL_REG:
|
||||
# This is likely a relative offset table
|
||||
# Go up to MLIL and walk back a few instructions to find the values we need
|
||||
mlil_func = func.medium_level_il
|
||||
|
||||
# (Roughly) find the MLIL instruction at this jump
|
||||
inst_idx = func.get_low_level_il_at(il.address).instr_index
|
||||
mlil_idx = il_func.get_medium_level_il_instruction_index(inst_idx)
|
||||
|
||||
# Find a MLIL_LOAD with the address/offset we need
|
||||
while mlil_idx > 0:
|
||||
mlil = mlil_func[mlil_idx]
|
||||
if mlil.operation == MediumLevelILOperation.MLIL_SET_VAR and \
|
||||
mlil.src.operation == MediumLevelILOperation.MLIL_LOAD:
|
||||
# Possible jump table info here, try parsing it
|
||||
base = search_mlil_displ(mlil.src, ptr=True)
|
||||
offset = search_mlil_displ(mlil.src)
|
||||
|
||||
# If it worked return the table info
|
||||
if None not in [base, offset]:
|
||||
tbl = JMPTable(bv, base, successors, offset)
|
||||
break
|
||||
|
||||
# Keep walking back
|
||||
mlil_idx -= 1
|
||||
|
||||
# Full jump expression
|
||||
else:
|
||||
# Parse out the base address
|
||||
base = util.search_displ_base(il.dest)
|
||||
if base is not None:
|
||||
tbl = JMPTable(bv, base, successors)
|
||||
|
||||
if tbl is not None:
|
||||
DEBUG("Found jump table at {:x} with offset {:x}".format(tbl.base_addr, tbl.rel_off))
|
||||
return tbl
|
||||
@@ -1,341 +0,0 @@
|
||||
# Copyright (c) 2017 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import binaryninja as binja
|
||||
from binaryninja.enums import (
|
||||
Endianness, LowLevelILOperation, SectionSemantics
|
||||
)
|
||||
import inspect
|
||||
import logging
|
||||
import magic
|
||||
import re
|
||||
import struct
|
||||
from collections import defaultdict
|
||||
|
||||
LOGNAME = 'binja.cfg'
|
||||
log = logging.getLogger(LOGNAME)
|
||||
|
||||
|
||||
class StackFormatter(logging.Formatter):
|
||||
def __init__(self, fmt=None, datefmt=None):
|
||||
logging.Formatter.__init__(self, fmt, datefmt)
|
||||
self.stack_base = len(inspect.stack()) + 7
|
||||
|
||||
def format(self, record):
|
||||
record.indent = ' ' * (len(inspect.stack()) - self.stack_base)
|
||||
res = logging.Formatter.format(self, record)
|
||||
del record.indent
|
||||
return res
|
||||
|
||||
|
||||
def init_logger(log_file):
|
||||
formatter = StackFormatter('[%(levelname)s] %(indent)s%(message)s')
|
||||
handler = logging.FileHandler(log_file)
|
||||
handler.setFormatter(formatter)
|
||||
|
||||
log.addHandler(handler)
|
||||
log.setLevel(logging.DEBUG)
|
||||
|
||||
|
||||
ENDIAN_TO_STRUCT = {
|
||||
Endianness.LittleEndian: '<',
|
||||
Endianness.BigEndian: '>'
|
||||
}
|
||||
|
||||
|
||||
def read_dword(bv, addr):
|
||||
# type: (binja.BinaryView, int) -> int
|
||||
# Pad the data if fewer than 4 bytes are read
|
||||
endianness = ENDIAN_TO_STRUCT[bv.endianness]
|
||||
data = bv.read(addr, 4)
|
||||
padded_data = '{{:\x00{}4s}}'.format(endianness).format(data)
|
||||
fmt = '{}L'.format(endianness)
|
||||
return struct.unpack(fmt, padded_data)[0]
|
||||
|
||||
|
||||
def read_qword(bv, addr):
|
||||
# type: (binja.BinaryView, int) -> int
|
||||
# Pad the data if fewer than 8 bytes are read
|
||||
endianness = ENDIAN_TO_STRUCT[bv.endianness]
|
||||
data = bv.read(addr, 8)
|
||||
padded_data = '{{:\x00{}8s}}'.format(endianness).format(data)
|
||||
fmt = '{}Q'.format(endianness)
|
||||
return struct.unpack(fmt, padded_data)[0]
|
||||
|
||||
|
||||
def load_binary(path):
|
||||
magic_type = magic.from_file(path)
|
||||
if 'ELF' in magic_type:
|
||||
bv_type = binja.BinaryViewType['ELF']
|
||||
elif 'PE32' in magic_type:
|
||||
bv_type = binja.BinaryViewType['PE']
|
||||
elif 'Mach-O' in magic_type:
|
||||
bv_type = binja.BinaryViewType['Mach-O']
|
||||
else:
|
||||
bv_type = binja.BinaryViewType['Raw']
|
||||
|
||||
# Can't do anything with Raw type
|
||||
log.fatal('Unknown binary type: "{}", exiting'.format(magic_type))
|
||||
exit(1)
|
||||
|
||||
log.debug('Loading binary in binja...')
|
||||
bv = bv_type.open(path)
|
||||
bv.update_analysis_and_wait()
|
||||
|
||||
# NOTE: at the moment binja will not load a binary
|
||||
# that doesn't have an entry point
|
||||
if len(bv) == 0:
|
||||
log.error('Binary could not be loaded in binja, is it linked?')
|
||||
exit(1)
|
||||
|
||||
return bv
|
||||
|
||||
|
||||
def find_symbol_name(bv, addr):
|
||||
"""Attempt to find a symbol for a given address
|
||||
|
||||
Args:
|
||||
bv (binja.BinaryView)
|
||||
addr (int): Address the symbol should point to
|
||||
|
||||
Returns:
|
||||
(str): Symbol name if found, empty string otherwise
|
||||
|
||||
"""
|
||||
sym = bv.get_symbol_at(addr)
|
||||
if sym is not None:
|
||||
return sym.name
|
||||
return ''
|
||||
|
||||
|
||||
def get_func_containing(bv, addr):
|
||||
""" Finds the function, if any, containing the given address
|
||||
Args:
|
||||
bv (binja.BinaryView)
|
||||
addr (int)
|
||||
|
||||
Returns:
|
||||
binja.Function
|
||||
"""
|
||||
funcs = bv.get_functions_containing(addr)
|
||||
return funcs[0] if funcs is not None else None
|
||||
|
||||
|
||||
def get_section_at(bv, addr):
|
||||
"""Returns the section in the binary that contains the given address"""
|
||||
if not is_valid_addr(bv, addr):
|
||||
return None
|
||||
|
||||
for sec in bv.sections.values():
|
||||
if sec.start <= addr < sec.end:
|
||||
return sec
|
||||
return None
|
||||
|
||||
|
||||
def is_external_ref(bv, addr):
|
||||
sym = bv.get_symbol_at(addr)
|
||||
return sym is not None and 'Import' in sym.type.name
|
||||
|
||||
|
||||
def is_valid_addr(bv, addr):
|
||||
return bv.get_segment_at(addr) is not None
|
||||
|
||||
|
||||
def is_code(bv, addr):
|
||||
"""Returns `True` if the given address lies in a code section"""
|
||||
# This is a bit more specific than checking if a segment is executable,
|
||||
# Binja will classify a section as ReadOnlyCode or ReadOnlyData, though
|
||||
# both sections are still in an executable segment
|
||||
sec = get_section_at(bv, addr)
|
||||
return sec is not None and sec.semantics == SectionSemantics.ReadOnlyCodeSectionSemantics
|
||||
|
||||
|
||||
def is_executable(bv, addr):
|
||||
"""Returns `True` if the given address lies in an executable segment"""
|
||||
seg = bv.get_segment_at(addr)
|
||||
return seg is not None and seg.executable
|
||||
|
||||
|
||||
def is_readable(bv, addr):
|
||||
"""Returns `True` if the given address lies in a readable segment"""
|
||||
seg = bv.get_segment_at(addr)
|
||||
return seg is not None and seg.writable
|
||||
|
||||
|
||||
def is_writeable(bv, addr):
|
||||
"""Returns `True` if the given address lies in a writable segment"""
|
||||
seg = bv.get_segment_at(addr)
|
||||
return seg is not None and seg.readable
|
||||
|
||||
|
||||
def is_ELF(bv):
|
||||
return bv.view_type == 'ELF'
|
||||
|
||||
|
||||
def is_PE(bv):
|
||||
return bv.view_type == 'PE'
|
||||
|
||||
|
||||
def clamp(val, vmin, vmax):
|
||||
return min(vmax, max(vmin, val))
|
||||
|
||||
|
||||
# Caching results of is_section_external
|
||||
_EXT_SECTIONS = set()
|
||||
_INT_SECTIONS = set()
|
||||
|
||||
|
||||
def is_section_external(bv, sect):
|
||||
"""Returns `True` if the given section contains only external references
|
||||
|
||||
Args:
|
||||
bv (binja.BinaryView)
|
||||
sect (binja.binaryview.Section)
|
||||
"""
|
||||
if sect.start in _EXT_SECTIONS:
|
||||
return True
|
||||
|
||||
if sect.start in _INT_SECTIONS:
|
||||
return False
|
||||
|
||||
if is_ELF(bv):
|
||||
if re.search(r'\.(got|plt)', sect.name):
|
||||
_EXT_SECTIONS.add(sect.start)
|
||||
return True
|
||||
|
||||
if is_PE(bv):
|
||||
if '.idata' in sect.name:
|
||||
_EXT_SECTIONS.add(sect.start)
|
||||
return True
|
||||
|
||||
_INT_SECTIONS.add(sect.start)
|
||||
return False
|
||||
|
||||
|
||||
def is_tls_section(bv, addr):
|
||||
sect_names = (sect.name for sect in bv.get_sections_at(addr))
|
||||
return any(sect in ['.tbss', '.tdata', '.tls'] for sect in sect_names)
|
||||
|
||||
|
||||
def _search_phrase_op(il, target_op):
|
||||
""" Helper for finding parts of a phrase[+displacement] il """
|
||||
op = il.operation
|
||||
|
||||
# Handle starting points
|
||||
if op == LowLevelILOperation.LLIL_SET_REG:
|
||||
return _search_phrase_op(il.src, target_op)
|
||||
|
||||
if op == LowLevelILOperation.LLIL_STORE:
|
||||
return _search_phrase_op(il.dest, target_op)
|
||||
|
||||
# The phrase il may be inside a LLIL_LOAD
|
||||
if op == LowLevelILOperation.LLIL_LOAD:
|
||||
return _search_phrase_op(il.src, target_op)
|
||||
|
||||
# Continue left/right at an ADD
|
||||
if op == LowLevelILOperation.LLIL_ADD:
|
||||
return (_search_phrase_op(il.left, target_op) or
|
||||
_search_phrase_op(il.right, target_op))
|
||||
|
||||
# Continue left/right at an ADD
|
||||
if op == LowLevelILOperation.LLIL_SUB:
|
||||
return (_search_phrase_op(il.left, target_op) or
|
||||
_search_phrase_op(il.right, target_op))
|
||||
|
||||
# Continue left/right at an ADD
|
||||
if op == LowLevelILOperation.LLIL_CMP_E:
|
||||
return (_search_phrase_op(il.left, target_op) or
|
||||
_search_phrase_op(il.right, target_op))
|
||||
|
||||
# Terminate when constant is found
|
||||
if op == target_op:
|
||||
return il
|
||||
|
||||
|
||||
def search_phrase_reg(il):
|
||||
""" Searches for the register used in a phrase
|
||||
ex: dword [ebp + 0x8] -> ebp
|
||||
|
||||
Args:
|
||||
il (binja.LowLevelILInstruction): Instruction to parse
|
||||
|
||||
Returns:
|
||||
str: register name
|
||||
"""
|
||||
res = _search_phrase_op(il, LowLevelILOperation.LLIL_REG)
|
||||
if res is not None:
|
||||
return res.src.name
|
||||
|
||||
|
||||
def search_displ_base(il):
|
||||
""" Searches for the base address used in a phrase[+displacement]
|
||||
ex: dword [eax * 4 + 0x08040000] -> 0x08040000
|
||||
dword [ebp + 0x8] -> 0x8
|
||||
|
||||
Args:
|
||||
il (binja.LowLevelILInstruction): Instruction to parse
|
||||
|
||||
Returns:
|
||||
int: base address
|
||||
"""
|
||||
res = _search_phrase_op(il, LowLevelILOperation.LLIL_CONST)
|
||||
if res is not None:
|
||||
# Interpret the string representation to avoid sign issues
|
||||
return int(res.tokens[0].text, 16)
|
||||
|
||||
|
||||
def is_jump_tail_call(bv, il):
|
||||
""" Returns `True` if the given il is a jump to another function """
|
||||
return il.operation == LowLevelILOperation.LLIL_JUMP and \
|
||||
il.dest.operation == LowLevelILOperation.LLIL_CONST_PTR and \
|
||||
get_jump_tail_call_target(bv, il) is not None
|
||||
|
||||
|
||||
def get_jump_tail_call_target(bv, il):
|
||||
""" Get the target function of a tail-call.
|
||||
|
||||
Returns:
|
||||
binja.Function
|
||||
"""
|
||||
try:
|
||||
return bv.get_function_at(il.dest.constant)
|
||||
except:
|
||||
return None
|
||||
|
||||
|
||||
def collect_il_groups(il_func):
|
||||
""" Gather all il instructions grouped by address
|
||||
Some instructions (cmov, set, etc.) get expanded into multiple il
|
||||
instructions when lifted, but `Function.get_lifted_il_at` will only return the first
|
||||
of all the il instructions at an address. This will group all the il instructions
|
||||
into a map of address to expanded instructions as follows:
|
||||
|
||||
{
|
||||
addr1 => [single il instruction],
|
||||
addr2 => [expanded il 1, expanded il 2, ...],
|
||||
...
|
||||
}
|
||||
|
||||
Args:
|
||||
il_func: IL function to gather all il groups from
|
||||
|
||||
Returns:
|
||||
dict: Map from address to all IL instructions at that address
|
||||
|
||||
"""
|
||||
il_map = defaultdict(list)
|
||||
for blk in il_func:
|
||||
for il in blk:
|
||||
il_map[il.address].append(il)
|
||||
return il_map
|
||||
@@ -1,160 +0,0 @@
|
||||
# Copyright (c) 2017 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import binaryninja as binja
|
||||
from binaryninja.enums import (
|
||||
SymbolType, TypeClass, InstructionTextTokenType,
|
||||
LowLevelILOperation
|
||||
)
|
||||
|
||||
import logging
|
||||
import util
|
||||
from debug import *
|
||||
|
||||
log = logging.getLogger(util.LOGNAME)
|
||||
|
||||
SYM_IGNORE = [
|
||||
'__data_start',
|
||||
'__dso_handle',
|
||||
'__init_array_start',
|
||||
'__init_array_end',
|
||||
'__TMC_END__',
|
||||
'__JCR_END__',
|
||||
'__elf_header',
|
||||
'_DYNAMIC'
|
||||
]
|
||||
|
||||
|
||||
def recover_globals(bv, pb_mod):
|
||||
# Sort symbols by address so we can estimate size if needed
|
||||
# TODO(krx): I'd prefer to find a better way to identify globals
|
||||
# than going through and filtering all variable symbols in certain sections
|
||||
syms = []
|
||||
for sym in bv.symbols.values():
|
||||
if isinstance(sym, list):
|
||||
for dup_sym in sym:
|
||||
syms.append(dup_sym)
|
||||
else:
|
||||
syms.append(sym)
|
||||
|
||||
for i, sym in enumerate(syms):
|
||||
if sym.name in SYM_IGNORE:
|
||||
continue
|
||||
|
||||
# Binja picks up a couple of symbols outside of named sections
|
||||
sect = util.get_section_at(bv, sym.address)
|
||||
if sect is None:
|
||||
continue
|
||||
|
||||
if sym.type == SymbolType.DataSymbol and \
|
||||
not util.is_executable(bv, sym.address) and \
|
||||
not util.is_section_external(bv, sect):
|
||||
log.debug('Recovering global %s @ 0x%x', sym.name, sym.address)
|
||||
pb_gvar = pb_mod.global_vars.add()
|
||||
pb_gvar.ea = sym.address
|
||||
pb_gvar.name = sym.name
|
||||
|
||||
# Look at the variable type to determine size
|
||||
data_var = bv.get_data_var_at(sym.address)
|
||||
if data_var.type.type_class == TypeClass.VoidTypeClass:
|
||||
# Estimate size based on the address of the next symbol
|
||||
if sym is not syms[-1]:
|
||||
pb_gvar.size = syms[i + 1].address - sym.address
|
||||
else:
|
||||
# Edge case for the last symbol
|
||||
# Take end of the section as the "next symbol" instead
|
||||
sec = util.get_section_at(bv, sym.address)
|
||||
pb_gvar.size = sec.end - sym.address
|
||||
else:
|
||||
pb_gvar.size = data_var.type.width
|
||||
|
||||
|
||||
def recover_stack_vars(pb_func, func, var_refs):
|
||||
"""
|
||||
Args:
|
||||
pb_func (CFG_pb2.Function)
|
||||
func (binaryninja.Function)
|
||||
var_refs (dict): map of all var references in the form {var_name => [(addr, off), ...]}
|
||||
"""
|
||||
# Go through all variables on the stack (in order of storage)
|
||||
stack_vars = sorted(func.stack_layout, key=lambda var: var.storage)
|
||||
for i, svar in enumerate(stack_vars):
|
||||
pb_svar = pb_func.stack_vars.add()
|
||||
pb_svar.name = svar.name
|
||||
pb_svar.sp_offset = svar.storage
|
||||
|
||||
# Var types in binja don't account for arrays
|
||||
# Estimate size based on the offset of the next variable
|
||||
if svar is not stack_vars[-1]:
|
||||
pb_svar.size = stack_vars[i + 1].storage - svar.storage
|
||||
else:
|
||||
# Edge case for the last variable, the offset is the size
|
||||
pb_svar.size = svar.storage
|
||||
|
||||
# Add all references to this variable
|
||||
for addr, off in var_refs[svar.name]:
|
||||
pb_svref = pb_svar.ref_eas.add()
|
||||
pb_svref.inst_ea = addr
|
||||
pb_svref.offset = off - svar.storage
|
||||
|
||||
|
||||
def _sp_name(bv):
|
||||
return bv.arch.stack_pointer
|
||||
|
||||
|
||||
def _bp_name(bv):
|
||||
# TODO(krx): this is currently specific to x86/amd64
|
||||
return 'rbp' if _sp_name(bv) == 'rsp' else 'ebp'
|
||||
|
||||
|
||||
def _find_var_name(inst):
|
||||
for tok in inst.tokens:
|
||||
if tok.type == InstructionTextTokenType.LocalVariableToken:
|
||||
return tok.text
|
||||
return None
|
||||
|
||||
|
||||
def _is_moving_sp(bv, il):
|
||||
if il.operation == LowLevelILOperation.LLIL_SET_REG and \
|
||||
il.src.operation in [LowLevelILOperation.LLIL_ADD, LowLevelILOperation.LLIL_SUB]:
|
||||
dst = il.dest.name
|
||||
src = il.src.left.src.name
|
||||
return dst == src == _sp_name(bv)
|
||||
return False
|
||||
|
||||
|
||||
def find_stack_var_refs(bv, inst, il, var_refs):
|
||||
""" Attempts to find references to a stack variable in a given instruction
|
||||
Args:
|
||||
bv (binaryninja.BinaryView)
|
||||
inst (binaryninja.DisassemblyTextLine)
|
||||
il (binaryninja.LowLevelILInstruction)
|
||||
var_refs (dict): map of currently known var references in the form {var_name => [(addr, off), ...]}
|
||||
"""
|
||||
# Ignore instructions where we just add/sub sp
|
||||
if _is_moving_sp(bv, il):
|
||||
return
|
||||
|
||||
# Find a local var being referenced here
|
||||
var_name = _find_var_name(inst)
|
||||
if var_name is None:
|
||||
return
|
||||
|
||||
# Pull out info about the phrase in this instruction
|
||||
reg = util.search_phrase_reg(il)
|
||||
off = util.search_displ_base(il) or 0
|
||||
|
||||
# If this is accessing a local var, save the ref info
|
||||
if reg in [_sp_name(bv), _bp_name(bv)]:
|
||||
var_refs[var_name].append((il.address, off))
|
||||
@@ -1,231 +0,0 @@
|
||||
# Copyright (c) 2017 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import binaryninja as binja
|
||||
from binaryninja.enums import LowLevelILOperation
|
||||
import logging
|
||||
|
||||
import CFG_pb2
|
||||
import util
|
||||
from debug import *
|
||||
|
||||
log = logging.getLogger(util.LOGNAME)
|
||||
|
||||
|
||||
class XRef(object):
|
||||
IMMEDIATE = 0
|
||||
MEMORY = 1
|
||||
DISPLACEMENT = 2
|
||||
CONTROLFLOW = 3
|
||||
|
||||
TYPE_TO_CFG = {
|
||||
IMMEDIATE : CFG_pb2.CodeReference.ImmediateOperand,
|
||||
MEMORY : CFG_pb2.CodeReference.MemoryOperand,
|
||||
DISPLACEMENT : CFG_pb2.CodeReference.MemoryDisplacementOperand,
|
||||
CONTROLFLOW : CFG_pb2.CodeReference.ControlFlowOperand
|
||||
}
|
||||
|
||||
def __init__(self, addr, reftype, mask=0):
|
||||
self.addr = addr
|
||||
self.type = reftype
|
||||
self.mask = mask
|
||||
|
||||
@property
|
||||
def cfg_type(self):
|
||||
return self.TYPE_TO_CFG[self.type]
|
||||
|
||||
def __repr__(self):
|
||||
return '<XREF: 0x{:x} {}>'.format(self.addr, CFG_pb2.CodeReference.OperandType.Name(self.cfg_type))
|
||||
|
||||
def __eq__(self, other):
|
||||
if not isinstance(other, XRef):
|
||||
return NotImplemented
|
||||
return self.addr == other.addr and \
|
||||
self.type == other.type
|
||||
|
||||
def __hash__(self):
|
||||
return hash((self.addr, self.type))
|
||||
|
||||
_NO_XREFS = set()
|
||||
|
||||
_IGNORED_XREF_OP_TYPES = (LowLevelILOperation.LLIL_JUMP,
|
||||
LowLevelILOperation.LLIL_JUMP_TO,
|
||||
LowLevelILOperation.LLIL_UNIMPL,
|
||||
LowLevelILOperation.LLIL_UNIMPL_MEM)
|
||||
|
||||
|
||||
_CONST_XREF_OP_TYPES = [LowLevelILOperation.LLIL_CONST_PTR]
|
||||
|
||||
_LOAD_STORE_OP_TYPES = (LowLevelILOperation.LLIL_LOAD,
|
||||
LowLevelILOperation.LLIL_STORE)
|
||||
|
||||
_CONST_OR_CONST_PTR_TYPES = (binja.RegisterValueType.ConstantValue,
|
||||
binja.RegisterValueType.ConstantPointerValue)
|
||||
|
||||
_AARCH64_ADRP_XREFS = {}
|
||||
|
||||
def _get_aarch64_partial_xref(bv, func, il, dis):
|
||||
"""" Figure out the final destination referenced by an ADRP+ADD instruction
|
||||
combination on AArch64."""
|
||||
|
||||
if func.arch.name != 'aarch64':
|
||||
return None
|
||||
|
||||
if il.address in _AARCH64_ADRP_XREFS:
|
||||
return _AARCH64_ADRP_XREFS[il.address]
|
||||
|
||||
if not dis.startswith('adrp '):
|
||||
return None
|
||||
|
||||
next_address = il.address + bv.get_instruction_length(il.address)
|
||||
next_dis = bv.get_disassembly(next_address)
|
||||
if not next_dis.startswith('add '):
|
||||
return None
|
||||
|
||||
next_il = func.get_low_level_il_at(next_address)
|
||||
value = next_il.get_reg_value_after(next_il.dest)
|
||||
|
||||
if value.type not in _CONST_OR_CONST_PTR_TYPES:
|
||||
return None
|
||||
|
||||
_AARCH64_ADRP_XREFS[il.address] = XRef(value.value, XRef.DISPLACEMENT, mask=-4096L)
|
||||
_AARCH64_ADRP_XREFS[next_address] = XRef(value.value, XRef.IMMEDIATE, mask=4095)
|
||||
|
||||
return _AARCH64_ADRP_XREFS[il.address]
|
||||
|
||||
|
||||
def get_xrefs(bv, func, il):
|
||||
global _LAST_UNUSED_REFS
|
||||
|
||||
refs = set()
|
||||
dis = bv.get_disassembly(il.address)
|
||||
|
||||
# TODO(pag): This is an ugly hack for the ADRP instruction on AArch64.
|
||||
ref = _get_aarch64_partial_xref(bv, func, il, dis)
|
||||
if ref is not None:
|
||||
refs.add(ref)
|
||||
else:
|
||||
reftype = XRef.IMMEDIATE
|
||||
|
||||
# PC-relative displacement for AArch64's `adr` instruction.
|
||||
if func.arch.name == 'aarch64' and dis.startswith('adr '):
|
||||
reftype = XRef.DISPLACEMENT
|
||||
|
||||
_fill_xrefs_internal(bv, il, refs, reftype)
|
||||
|
||||
# TODO(pag): Another ugly hack to deal with a specific flavor of jump
|
||||
# table that McSema doesn't handle very well. The specific form
|
||||
# is:
|
||||
#
|
||||
# .text:00000000004009AC ADRP X1, #asc_400E5C@PAGE ; "\b"
|
||||
# .text:00000000004009B0 ADD X1, X1, #asc_400E5C@PAGEOFF ; "\b"
|
||||
# .text:00000000004009B4 LDR W0, [X1,W0,UXTW#2]
|
||||
# .text:00000000004009B8 ADR X1, loc_4009C4 <-- point to a block
|
||||
# .text:00000000004009BC ADD X0, X1, W0,SXTW#2
|
||||
# .text:00000000004009C0 BR X0
|
||||
#
|
||||
# We don't have good ways of referencing basic blocks, so if we
|
||||
# left the reference from `4009B8` to `4009C4`, then that would
|
||||
# be computed in terms of the location in memory of the copied
|
||||
# `.text` segment in the lifted binary.
|
||||
#
|
||||
# We could handle this via a jump-offset table with offset of
|
||||
# `4009B8`, but we don't yet support this variant of jump table
|
||||
# in jmptable.py.
|
||||
if dis.startswith('adr ') and len(refs):
|
||||
ref = refs.pop()
|
||||
if util.is_code(bv, ref.addr) and not bv.get_function_at(ref.addr):
|
||||
DEBUG("WARNING: Omitting reference to non-function code address {:x}".format(ref.addr))
|
||||
else:
|
||||
refs.add(ref) # Add it back in.
|
||||
|
||||
return refs
|
||||
|
||||
|
||||
def _fill_xrefs_internal(bv, il, refs, reftype=XRef.IMMEDIATE, parent=None):
|
||||
""" Recursively gather xrefs in an IL instruction
|
||||
|
||||
Args:
|
||||
bv (binja.BinaryView)
|
||||
il (binja.LowLevelILInstruction)
|
||||
reftype (int)
|
||||
parent (binja.LowLevelILInstruction)
|
||||
|
||||
Returns:
|
||||
set[XRef]
|
||||
"""
|
||||
global _NO_XREFS, _IGNORED_XREF_OP_TYPES, _CONST_XREF_OF_TYPES
|
||||
global _LOAD_STORE_OP_TYPES
|
||||
|
||||
if not isinstance(il, binja.LowLevelILInstruction):
|
||||
return _NO_XREFS
|
||||
|
||||
# Update reftype using il information
|
||||
op = il.operation
|
||||
|
||||
# Detect a tail call target
|
||||
# This is the only instance where a LLIL_JUMP is considered
|
||||
if util.is_jump_tail_call(bv, il):
|
||||
target = util.get_jump_tail_call_target(bv, il)
|
||||
DEBUG('Tail call from {:x} to {:x}'.format(il.address, target.start))
|
||||
return _fill_xrefs_internal(bv, il.dest, refs, XRef.CONTROLFLOW, il)
|
||||
|
||||
# Some instruction types are ignored
|
||||
if op in _IGNORED_XREF_OP_TYPES:
|
||||
return _NO_XREFS
|
||||
|
||||
elif op == LowLevelILOperation.LLIL_CALL:
|
||||
# Any xref in here will be a control flow target
|
||||
reftype = XRef.CONTROLFLOW
|
||||
|
||||
elif op in _LOAD_STORE_OP_TYPES:
|
||||
|
||||
# Choose the correct operand to look at
|
||||
mem_il = il.src if op == LowLevelILOperation.LLIL_LOAD else il.dest
|
||||
|
||||
# Loading from memory
|
||||
# Check if we're using a displacement in this
|
||||
if mem_il.operation in _CONST_XREF_OP_TYPES:
|
||||
# No displacement
|
||||
reftype = XRef.MEMORY
|
||||
else:
|
||||
reftype = XRef.DISPLACEMENT
|
||||
|
||||
# In a load/store, only the operand that references memory gets the new reftype
|
||||
# The other operand(s) start at the default (immediate) again
|
||||
_fill_xrefs_internal(bv, mem_il, refs, reftype, il)
|
||||
for oper in il.operands:
|
||||
if oper != mem_il:
|
||||
_fill_xrefs_internal(bv, oper, refs)
|
||||
|
||||
elif op in _CONST_XREF_OP_TYPES:
|
||||
# Hit a value, if this is a reference we can save the xref
|
||||
if util.is_valid_addr(bv, il.constant):
|
||||
# A displacement might be incorrectly classified as an immediate at this point
|
||||
if reftype == XRef.IMMEDIATE and parent is not None:
|
||||
# There's some other expression including this value
|
||||
# look at the disassembly to figure out if this is actually a displacement
|
||||
dis = bv.get_disassembly(il.address)
|
||||
if '[' in dis and ']' in dis:
|
||||
# Fix the reftype depending on how this value is used
|
||||
if parent.operation == LowLevelILOperation.LLIL_SET_REG:
|
||||
reftype = XRef.MEMORY
|
||||
else:
|
||||
reftype = XRef.DISPLACEMENT
|
||||
|
||||
refs.add(XRef(il.constant, reftype))
|
||||
|
||||
# Continue searching operands for xrefs
|
||||
for oper in il.operands:
|
||||
_fill_xrefs_internal(bv, oper, refs, reftype, il)
|
||||
@@ -36,6 +36,7 @@ DATA: _end PTR
|
||||
|
||||
|
||||
__assert_fail 4 C Y
|
||||
__assert_c99 3 C Y
|
||||
__cxa_atexit 5 C N
|
||||
__cxa_guard_acquire 5 C N
|
||||
__cxa_guard_release 5 C N
|
||||
@@ -1569,7 +1570,7 @@ ass_add_font 4 C N
|
||||
ass_alloc_event 1 C N
|
||||
ass_alloc_style 1 C N
|
||||
ass_clear_fonts 1 C N
|
||||
__assert 3 C N
|
||||
__assert 3 C Y
|
||||
__assert_perror_fail 4 C Y
|
||||
ass_flush_events 1 C N
|
||||
ass_fonts_update 1 C N
|
||||
@@ -2382,7 +2383,6 @@ bfd_set_section_size 3 C N
|
||||
bfd_set_start_address 2 C N
|
||||
bfd_set_symtab 3 C N
|
||||
bfd_simple_get_relocated_section_contents 4 C N
|
||||
bfd_sparclinux_size_dynamic_sections 2 C N
|
||||
bfd_sprintf_vma 3 C N
|
||||
bfd_stat 2 C N
|
||||
bfd_sunos_get_needed_list 2 C N
|
||||
@@ -20190,7 +20190,6 @@ print_insn_s390 2 C N
|
||||
print_insn_sh 2 C N
|
||||
print_insn_sh64 2 C N
|
||||
print_insn_sh64x_media 2 C N
|
||||
print_insn_sparc 2 C N
|
||||
print_insn_spu 2 C N
|
||||
print_insn_tic30 2 C N
|
||||
print_insn_tic4x 2 C N
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
/*
|
||||
* Copyright (c) 2018 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "CFGWriter.h"
|
||||
@@ -190,8 +191,8 @@ void ResolveOffsetTable(const std::set<Dyninst::Address> &successors,
|
||||
auto cfg_inst = cfg_block->mutable_instructions(
|
||||
cfg_block->instructions_size() - 1);
|
||||
if (!cfg_inst->xrefs_size()) {
|
||||
AddCodeXref(cfg_inst, CodeReference::DataTarget, CodeReference::OffsetTable,
|
||||
CodeReference::Internal, table_ea.value());
|
||||
AddCodeXref(cfg_inst, CodeReference::OffsetTable,
|
||||
table_ea.value());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,8 +283,6 @@ CFGWriter::CFGWriter(mcsema::Module &m,
|
||||
}
|
||||
}
|
||||
|
||||
GetNoReturns();
|
||||
|
||||
// Calculate where can magic section start without
|
||||
// potentialy overwriting part of the binary
|
||||
//TODO(lukas): Move out
|
||||
@@ -359,50 +358,9 @@ void CFGWriter::Write() {
|
||||
}
|
||||
}
|
||||
|
||||
WriteLocalVariables();
|
||||
module.set_name(FLAGS_binary);
|
||||
}
|
||||
|
||||
// TODO(lukas): Need to get all xrefs for local variable
|
||||
void CFGWriter::WriteLocalVariables() {
|
||||
// We need to get SymtabAPI version of functions
|
||||
std::vector<SymtabAPI::Function *> funcs;
|
||||
symtab.getAllFunctions(funcs);
|
||||
for (auto func : funcs) {
|
||||
auto cfg_func = ctx.func_map.find(func->getOffset());
|
||||
if (cfg_func == ctx.func_map.end()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
std::vector<SymtabAPI::localVar *> locals;
|
||||
func->getLocalVariables(locals);
|
||||
|
||||
// getParams resets the vector passed to it
|
||||
std::vector<SymtabAPI::localVar *> params;
|
||||
func->getParams(params);
|
||||
for (auto a : params) {
|
||||
locals.push_back(a);
|
||||
}
|
||||
|
||||
for (auto local : locals) {
|
||||
auto cfg_var = cfg_func->second->add_stack_vars();
|
||||
cfg_var->set_name(local->getName());
|
||||
cfg_var->set_size(local->getType()->getSize());
|
||||
auto location_list = local->getLocationLists();
|
||||
|
||||
LOG(INFO)
|
||||
<< std::hex << "Found local variable with name " << local->getName()
|
||||
<< " with size: " << local->getType()->getSize();
|
||||
|
||||
for (auto &location : location_list) {
|
||||
cfg_var->set_sp_offset(location.frameOffset);
|
||||
LOG(INFO) << std::hex << "\tat sp_offset: 0x" << location.frameOffset;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CFGWriter::WriteExternalVariables() {
|
||||
std::vector<SymtabAPI::Symbol *> symbols;
|
||||
symbols = section_m.GetExternalRelocs(
|
||||
@@ -682,7 +640,6 @@ void CFGWriter::WriteInstruction(InstructionAPI::Instruction *instruction,
|
||||
instBytes += (int)instruction->rawByte(offset);
|
||||
}
|
||||
|
||||
cfg_instruction->set_bytes(instBytes);
|
||||
cfg_instruction->set_ea(addr);
|
||||
|
||||
std::vector<InstructionAPI::Operand> operands;
|
||||
@@ -779,18 +736,6 @@ void CFGWriter::CheckDisplacement(Dyninst::InstructionAPI::Expression *expr,
|
||||
}
|
||||
}
|
||||
|
||||
void CFGWriter::GetNoReturns() {
|
||||
for (auto f : code_object.funcs()) {
|
||||
if (f->retstatus() == ParseAPI::NORETURN) {
|
||||
no_ret_funcs.insert(f->name());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool CFGWriter::IsNoReturn(const std::string &name) {
|
||||
return no_ret_funcs.find(name) != no_ret_funcs.end();
|
||||
}
|
||||
|
||||
|
||||
//TODO(lukas): This is hacky
|
||||
void CFGWriter::HandleCallInstruction(InstructionAPI::Instruction *instruction,
|
||||
@@ -826,9 +771,6 @@ void CFGWriter::HandleCallInstruction(InstructionAPI::Instruction *instruction,
|
||||
}
|
||||
}
|
||||
|
||||
if (IsNoReturn(cfg_instruction->mutable_xrefs(0)->name())) {
|
||||
cfg_instruction->set_local_noreturn(true);
|
||||
}
|
||||
}
|
||||
|
||||
Address CFGWriter::immediateNonCall(InstructionAPI::Immediate* imm,
|
||||
@@ -839,9 +781,7 @@ Address CFGWriter::immediateNonCall(InstructionAPI::Immediate* imm,
|
||||
if (!ctx.HandleCodeXref({addr, a, cfg_instruction}, section_m, false)) {
|
||||
if (section_m.IsCode(a)) {
|
||||
AddCodeXref(cfg_instruction,
|
||||
CodeReference::DataTarget,
|
||||
CodeReference::ImmediateOperand,
|
||||
CodeReference::Internal,
|
||||
a);
|
||||
|
||||
LOG(INFO) << std::hex
|
||||
@@ -951,7 +891,6 @@ void CFGWriter::HandleNonCallInstruction(
|
||||
// in CrossXref<mcsema::Instruction>
|
||||
if (ctx.HandleCodeXref({0, *a, cfg_instruction}, section_m)) {
|
||||
auto cfg_xref = GetLastXref(cfg_instruction);
|
||||
cfg_xref->set_target_type(CodeReference::CodeTarget);
|
||||
cfg_xref->set_operand_type(CodeReference::ControlFlowOperand);
|
||||
}
|
||||
direct_values[i] = *a;
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
/*
|
||||
* Copyright (c) 2018 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
@@ -55,7 +56,6 @@ private:
|
||||
void WriteGlobalVariables();
|
||||
void SweepStubs();
|
||||
void WriteInternalFunctions();
|
||||
void WriteLocalVariables();
|
||||
|
||||
void WriteFunctionBlocks(Dyninst::ParseAPI::Function *func,
|
||||
mcsema::Function *cfg_internal_func);
|
||||
@@ -97,9 +97,6 @@ private:
|
||||
|
||||
bool HandleXref(mcsema::Instruction *, Dyninst::Address, bool force=true);
|
||||
|
||||
bool IsNoReturn(const std::string& str);
|
||||
void GetNoReturns();
|
||||
|
||||
void CheckDisplacement(Dyninst::InstructionAPI::Expression *,
|
||||
mcsema::Instruction *);
|
||||
bool IsExternal(Dyninst::Address addr) const;
|
||||
@@ -113,8 +110,6 @@ private:
|
||||
ExternalFunctionManager ext_funcs_m;
|
||||
SectionManager section_m;
|
||||
|
||||
std::unordered_set<std::string> no_ret_funcs;
|
||||
|
||||
std::map<Dyninst::Address, CrossXref<mcsema::Segment>> code_xrefs_to_resolve;
|
||||
std::map<Dyninst::Address, CrossXref<mcsema::Instruction>> inst_xrefs_to_resolve;
|
||||
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
# Copyright (c) 2018 Trail of Bits, Inc.
|
||||
# Copyright (c) 2020 Trail of Bits, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
# 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 Affero General Public License for more details.
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
if (NOT UNIX)
|
||||
message (ERROR "The Dyninst frontend currently does not support this OS")
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
/*
|
||||
* Copyright (c) 2018 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "ExternalFunctionManager.h"
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
/*
|
||||
* Copyright (c) 2018 Trail of Bits, Inc.
|
||||
* Copyright (c) 2020 Trail of Bits, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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 Affero General Public License for more details.
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user