Commit interceptor-lib from GAPID @ 9492539f1

* This library will be used to replace the PLT hooking for most core
  functions, and is generally more reliable. It still fails in some
  cases though when the target function is not patchable.
* To build, it requires LLVM. See README.md for instructions on building
  a compatible LLVM for use.
This commit is contained in:
baldurk
2018-01-31 18:24:12 +00:00
parent b7aa522769
commit 64c9e93831
31 changed files with 3308 additions and 0 deletions
+8
View File
@@ -112,6 +112,14 @@ The following libraries and components are incorporated into RenderDoc, listed h
Used to simplify Android workflows by distributing some tools from the android SDK, as well as patching android manifest files to enable debugging.
* `interceptor-lib <https://github.com/google/gapid>`_ - Copyright (c) 2017, Google Inc., distributed under the Apache 2.0 License.
Taken from the GAPID project, used to inject hooks into android library functions if LLVM is available at build-time.
* `LLVM <http://llvm.org/>`_ - Copyright (c) 2003-2017 University of Illinois at Urbana-Champaign, distributed under the University of Illinois/NCSA Open Source License.
Used to support interceptor-lib to inject hooks into android library functions.
Thanks
------
+58
View File
@@ -0,0 +1,58 @@
# Copyright (C) 2017 Google 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.
set(LLVM_CCACHE_BUILD OFF)
if(NOT CMAKE_HOST_WIN32)
find_program(CCACHE_FOUND ccache)
if(CCACHE_FOUND)
set(LLVM_CCACHE_BUILD ON)
endif()
endif()
function(llvm_abi android_abi out)
if (${android_abi} STREQUAL "arm64-v8a")
set(${out} "AArch64" PARENT_SCOPE)
elseif(${android_abi} STREQUAL "armeabi-v7a")
set(${out} "ARM" PARENT_SCOPE)
elseif(${android_abi} STREQUAL "x86")
set(${out} "X86" PARENT_SCOPE)
else()
message(FATAL_ERROR "Unsupported architecture for building LLVM: ${android_abi}")
endif()
endfunction()
llvm_abi(ANDROID_ABI target_arch)
file(GLOB sources
"lib/*.h" "lib/*.cc"
"lib/${target_arch}/*.h" "lib/${target_arch}/*.cc"
)
if (ANDROID_ABI STREQUAL "arm64-v8a")
set(LLVM_TARGET_ARCH "${target_arch}")
set(LLVM_HOST_TRIPLE "aarch64-unknown-linux-android")
elseif(ANDROID_ABI STREQUAL "armeabi-v7a")
set(LLVM_TARGET_ARCH "${target_arch}")
set(LLVM_HOST_TRIPLE "armv8.2a-unknown-linux-android")
elseif(ANDROID_ABI STREQUAL "x86")
set(LLVM_TARGET_ARCH "${target_arch}")
set(LLVM_HOST_TRIPLE "i386-unknown-linux-android")
else()
message(FATAL_ERROR "Unsupported architecture for building LLVM: ${LLVM_TARGET_ARCH}")
endif()
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
add_subdirectory(lib)
set(interceptor_libs ${interceptor_libs} PARENT_SCOPE)
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"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.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"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.
"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).
"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.
"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."
"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.
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.
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.
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:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(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
(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.
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.
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.
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.
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.
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.
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.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2017 Google 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.
+73
View File
@@ -0,0 +1,73 @@
# interceptor-lib
This interceptor-lib is taken from Google's [gapid project](https://github.com/google/gapid/tree/master/gapii/interceptor-lib), under the Apache 2.0 License.
Minor modifications have been made to include it in RenderDoc's build system.
# LICENSE
See [LICENSE](LICENSE) file in this directory.
# LLVM Build instructions
To use this in RenderDoc you must set `-DLLVM_DIR=/path/to/llvm` pointing to a compatible build of LLVM 4.0 for the target you are building. Below are instructions on how to build that compatible LLVM.
You'll need the Android NDK r16b, and you'll need python available in your path.
### These instructions currently do not work for cygwin. I have not been able to figure out how to build LLVM for android from windows. If you know a way, it is welcome.
Before we get started, I found the LLVMHello pass would fail to compile on both windows and linux, so simply comment the `add_subdirectory(Hello)` line in `lib/Transforms/CMakeLists.txt` as well as removing the LLVMHello line in `test/CMakeLists.txt`.
On windows if you checked out git outside of cygwin and are building inside it, then the config.guess script might have dos newlines which will cause it to fail. If you run into problems with config.guess or config-ix.cmake, try running unix2dos on config.guess. If running outside of cygwin at all you might find that it fails to launch to fetch the default during the arm build process - just comment out that call and replace it with a default value.
To begin, clone llvm at the `release_40` tag:
```
git clone -b release_40 --depth=10 https://github.com/llvm-mirror/llvm
```
Now make a `build_native` folder and do a plain build, to create llvm-tblgen. We'll use this when making the android builds:
```
cd path/to/llvm
mkdir build_native
cd build_native
cmake ..
make -j$(nproc) llvm-tblgen
readlink -f bin/llvm-tblgen # remember this path
```
Next we'll make `build_arm32` and `build_arm64` folders and build for each. The instructions are listed once here, pointing out where things need to change between one and the other:
```
cd path/to/llvm
mkdir build_arm32 # or build_arm64
cd build_arm32 # or build_arm64
LLVM_ANDROID_ABI=armeabi-v7a # this is arm64-v8a for arm64
LLVM_TRIPLE=armv8.2a-unknown-linux-android # this is aarch64-unknown-linux-android for arm64
LLVM_ARCH=ARM # this is AArch64 for arm64
TBLGEN_PATH=/path/from/above/to/bin/llvm-tblgen
NDK_PATH=/path/to/ndk16
TARGET_PATH=/path/to/llvm/install_arm32 # or /path/to/llvm/install_arm64 for arm64
cmake -DLLVM_HOST_TRIPLE:STRING=$LLVM_TRIPLE -LLVM_TARGET_ARCH:STRING=$LLVM_ARCH -DLLVM_TARGETS_TO_BUILD:STRING=$LLVM_ARCH -DANDROID_ABI=$LLVM_ANDROID_ABI -DANDROID_NATIVE_API_LEVEL=21 -DANDROID_TOOLCHAIN=clang -DCMAKE_TOOLCHAIN_FILE:PATH=$NDK_PATH/build/cmake/android.toolchain.cmake -DCMAKE_INSTALL_PREFIX=$TARGET_PATH -DCMAKE_BUILD_TYPE=RelWithDebInfo -DLLVM_BUILD_RUNTIME=Off -DLLVM_INCLUDE_TESTS=Off -DLLVM_INCLUDE_EXAMPLES=Off -DLLVM_ENABLE_BACKTRACES=Off -DLLVM_TABLEGEN=$TBLGEN_PATH -DLLVM_BUILD_TOOLS=Off -DLLVM_INCLUDE_TOOLS=Off -DLLVM_USE_HOST_TOOLS=Off ..
make -j8 install
```
There is one extra step needed to copy some non-public headers into the install, that are required by interceptor-lib. From the `build_armXX` folder:
```
cp -R ../lib/Target/ARM/MCTargetDesc/ $TARGET_PATH/include/
# for arm32
cp ./lib/Target/ARM/ARM*.inc $TARGET_PATH/include/MCTargetDesc/
# for arm64
cp ./lib/Target/AArch64/AArch64*.inc $TARGET_PATH/include/MCTargetDesc/
```
Then you can set `-DLLVM_DIR=/path/to/llvm/install_armXX/lib/cmake/llvm` when building renderdoc and you should see a line saying that LLVM is being used to compile interceptor-lib!
@@ -0,0 +1,74 @@
/*
* Copyright (C) 2017 Google 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 INTERCEPTOR_INTERCEPTOR_H_
#define INTERCEPTOR_INTERCEPTOR_H_
// -----------------------------------------------------------------------------
// extern "C" interface designed for users who dlopen the interceptor-lib
// instead of linking against it. The API for these functions using C structures
// only to support users compiled with different STL library and to support
// usesrs who want to use dlopen/dlsym for loading the library.
// -----------------------------------------------------------------------------
extern "C" {
// Initializes the internal state of the interceptor library and returns a baton
// what have to be passed in to every other function. If called multiple times
// then multiple independent copies of the interceptor will be created.
void *InitializeInterceptor();
// Terminate an instance of the interceptor, deletes the trampolines set up by
// the instance and frees up all resources allocated by it. After this call the
// baton is a dangling pointer and passing it to any of the API function is
// undefined behaviour.
void TerminateInterceptor(void *interceptor);
// Find a function in the application by it's mangled symbol name by searching
// both the public symbol table and the internal symbol table if available. The
// returned pointer can be used to call the function after casted to the
// approptiate type or can be passed to other functions provided by the
// interceptor. If failes to find a symbol with the given name or more then 1
// symbol found then nullptr is returned.
void *FindFunctionByName(void *interceptor, const char *symbol_name);
// Intercepts a function specified by "old_function" with the one specified by
// "new_function". If "callback_function" is not nullptr then a callback stub
// is generated and returned in the pointer specified by "callback_function"
// what can be used to call the original (not intercepted) function after
// casting it to the correct function signature. If an "error_callback" is
// specifed then it will be called for every error encountered during
// interception with the baton specified in "error_callback_baton" and the error
// message itself. The return value of the function will specify if the
// interception was successfull (return true) or not (return false). In case
// of an interception failure the error_callback (if specified) called at least
// once and the original function isn't modified.
bool InterceptFunction(void *interceptor, void *old_function,
void *new_function, void **callback_function = nullptr,
void (*error_callback)(void *, const char *) = nullptr,
void *error_callback_baton = nullptr);
// Intercepts a function specifyind by "symbol_name" if exactly 1 symbol matches
// the specified name. The function has the same semantics as InterceptFunction
// regarding all other argument.
bool InterceptSymbol(void *interceptor, const char *symbol_name,
void *new_function, void **callback_function,
void (*error_callback)(void *, const char *) = nullptr,
void *error_callback_baton = nullptr);
} // extern "C"
#endif // INTERCEPTOR_INTERCEPTOR_H_
@@ -0,0 +1,229 @@
/*
* Copyright (C) 2017 Google 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 INTERCEPTOR_INTERCEPTOR_HPP_
#define INTERCEPTOR_INTERCEPTOR_HPP_
#include <array>
#include <sstream>
#include <string>
#include "interceptor.h"
//------------------------------------------------------------------------------
// Header only C++ wrapper interface around the basic extren "C" interface for
// convinince. The interface simplifies the usecase when linking agains the
// interceptor-lib with automated resource management and with adding a list
// of templatized functions for type safety and for intercepting multiple
// symbols with a single target function.
//------------------------------------------------------------------------------
class Interceptor {
public:
Interceptor() { interceptor_ = ::InitializeInterceptor(); }
~Interceptor() { ::TerminateInterceptor(interceptor_); }
void *FindFunctionByName(const char *symbol_name) {
return ::FindFunctionByName(interceptor_, symbol_name);
}
template <typename Ret, typename... Args>
bool InterceptFunction(Ret (*old_function)(Args...),
Ret (*new_function)(Args...),
Ret (**callback_function)(Args...),
std::string *error_message = nullptr);
template <typename Ret, typename... Args>
bool InterceptFunction(const char *symbol_name, Ret (*new_function)(Args...),
Ret (**callback_function)(Args...),
std::string *error_message = nullptr);
// Template class to define the type of the replacement function for
// intercepting a function with the given signature. The replacement function
// needs the same arguments as the original function with an additional
// argument what is a function poinetr with the type of the intercepted
// functions (C++ member functions are treated as free functions with this as
// the first argument).
template <typename DATA, typename FUN_TYPE>
struct CallbackSignature;
template <typename DATA, typename RET, typename... ARGS>
struct CallbackSignature<DATA, RET(ARGS...)> {
using type = RET (*)(DATA, RET (*)(ARGS...), ARGS...);
};
template <typename DATA, typename FUN_TYPE,
typename CallbackSignature<DATA, FUN_TYPE>::type FUN,
size_t FUN_COUNT>
bool InterceptMultipleFunction(
const std::array<std::pair<DATA, std::string>, FUN_COUNT> &functions,
std::string *error_message = nullptr);
private:
void *interceptor_;
// Helper method for collecting the error messages into a string stream
static void ErrorCollector(void *baton, const char *message) {
std::ostringstream *oss = static_cast<std::ostringstream *>(baton);
(*oss) << message << '\n';
}
// The following helper classes are used for implementing
// InterceptMultipleFunction using heavy template metaprogramming. The goal
// of the metaprogramming is to generate a unique function stub for every
// symbol passed in to InterceptMultiple function so we have a unique jump
// target for each intercepted function what can add the information required
// to execute the callback (address of the compensation function) to the
// actual intercepting function. Without the unique jump targets it would be
// impossible to call the original function from the replacement function
// what would mean thet replacement functions couldn't be shared between
// intercepted symbols.
template <typename DATA, size_t N, typename RET, typename... ARGS>
struct SignleFunctionInterceptor {
template <RET (*FUN)(DATA, RET (*)(ARGS...), ARGS...)>
static bool Impl(Interceptor &inteptor, const char *symbol_name, DATA data,
std::string *error_message);
template <RET (*FUN)(DATA, RET (*)(ARGS...), ARGS...)>
static RET TrampolineFunction(ARGS... args);
static DATA s_data;
static RET (*s_callback)(ARGS...);
};
template <typename DATA, typename FUN_TYPE,
typename CallbackSignature<DATA, FUN_TYPE>::type FUN,
size_t FUN_COUNT, size_t N>
struct MultiFunctionInterceptor;
template <typename DATA, typename RET, typename... ARGS,
RET (*FUN)(DATA, RET (*)(ARGS...), ARGS...), size_t FUN_COUNT,
size_t N>
struct MultiFunctionInterceptor<DATA, RET(ARGS...), FUN, FUN_COUNT, N> {
static bool Impl(
Interceptor &interceptor,
const std::array<std::pair<DATA, std::string>, FUN_COUNT> &functions,
std::string *error_message);
};
};
template <typename Ret, typename... Args>
bool Interceptor::InterceptFunction(Ret (*old_function)(Args...),
Ret (*new_function)(Args...),
Ret (**callback_function)(Args...),
std::string *error_message) {
std::ostringstream error_oss;
void *error_callback_baton = &error_oss;
void (*error_callback)(void *, const char *) =
error_message ? &ErrorCollector : nullptr;
bool res =
::InterceptFunction(interceptor_, reinterpret_cast<void *>(old_function),
reinterpret_cast<void *>(new_function),
reinterpret_cast<void **>(callback_function),
error_callback, error_callback_baton);
if (error_message) *error_message = error_oss.str();
return res;
}
template <typename Ret, typename... Args>
bool Interceptor::InterceptFunction(const char *symbol_name,
Ret (*new_function)(Args...),
Ret (**callback_function)(Args...),
std::string *error_message) {
std::ostringstream error_oss;
void *error_callback_baton = &error_oss;
void (*error_callback)(void *, const char *) =
error_message ? &ErrorCollector : nullptr;
bool res = ::InterceptSymbol(interceptor_, symbol_name,
reinterpret_cast<void *>(new_function),
reinterpret_cast<void **>(callback_function),
error_callback, error_callback_baton);
if (error_message) *error_message = error_oss.str();
return res;
}
template <typename DATA, typename FUN_TYPE,
typename Interceptor::CallbackSignature<DATA, FUN_TYPE>::type FUN,
size_t FUN_COUNT>
bool Interceptor::InterceptMultipleFunction(
const std::array<std::pair<DATA, std::string>, FUN_COUNT> &functions,
std::string *error_message) {
if (error_message) error_message->clear();
return MultiFunctionInterceptor<DATA, FUN_TYPE, FUN, FUN_COUNT,
FUN_COUNT>::Impl(*this, functions,
error_message);
}
template <typename DATA, size_t N, typename RET, typename... ARGS>
template <RET (*FUN)(DATA, RET (*)(ARGS...), ARGS...)>
RET Interceptor::SignleFunctionInterceptor<
DATA, N, RET, ARGS...>::TrampolineFunction(ARGS... args) {
return FUN(s_data, s_callback, std::forward<ARGS>(args)...);
}
template <typename DATA, size_t N, typename RET, typename... ARGS>
template <RET (*FUN)(DATA, RET (*)(ARGS...), ARGS...)>
bool Interceptor::SignleFunctionInterceptor<DATA, N, RET, ARGS...>::Impl(
Interceptor &interceptor, const char *symbol_name, DATA data,
std::string *error_message) {
s_data = data;
return interceptor.InterceptFunction(symbol_name, &TrampolineFunction<FUN>,
&s_callback, error_message);
}
template <typename DATA, typename RET, typename... ARGS,
RET (*FUN)(DATA, RET (*)(ARGS...), ARGS...), size_t FUN_COUNT,
size_t N>
bool Interceptor::
MultiFunctionInterceptor<DATA, RET(ARGS...), FUN, FUN_COUNT, N>::Impl(
Interceptor &interceptor,
const std::array<std::pair<DATA, std::string>, FUN_COUNT> &functions,
std::string *error_message) {
bool res =
MultiFunctionInterceptor<DATA, RET(ARGS...), FUN, FUN_COUNT, N - 1>::Impl(
interceptor, functions, error_message);
if (!functions[N - 1].second.empty()) {
std::string temp_str;
res &= SignleFunctionInterceptor<DATA, N - 1, RET, ARGS...>::template Impl<
FUN>(interceptor, functions[N - 1].second.c_str(),
functions[N - 1].first, error_message ? &temp_str : nullptr);
if (error_message && !temp_str.empty()) error_message->append(temp_str);
}
return res;
}
template <typename DATA, typename RET, typename... ARGS,
RET (*FUN)(DATA, RET (*)(ARGS...), ARGS...), size_t FUN_COUNT>
struct Interceptor::MultiFunctionInterceptor<DATA, RET(ARGS...), FUN, FUN_COUNT,
0> {
static bool Impl(
Interceptor &interceptor,
const std::array<std::pair<DATA, std::string>, FUN_COUNT> &functions,
std::string *error_message) {
return true;
}
};
template <typename DATA, size_t N, typename RET, typename... ARGS>
RET (*Interceptor::SignleFunctionInterceptor<
DATA, N, RET, ARGS...>::s_callback)(ARGS...) = nullptr;
template <typename DATA, size_t N, typename RET, typename... ARGS>
DATA Interceptor::SignleFunctionInterceptor<DATA, N, RET, ARGS...>::s_data;
#endif // INTERCEPTOR_INTERCEPTOR_H_
@@ -0,0 +1,219 @@
/*
* Copyright (C) 2017 Google 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.
*/
#include "target_aarch64.h"
#include <cassert>
#include <memory>
#include "MCTargetDesc/AArch64MCTargetDesc.h"
#include "llvm/ADT/Triple.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstBuilder.h"
#include "code_generator.h"
#include "disassembler.h"
using namespace interceptor;
static llvm::Triple GetTriple() {
llvm::Triple triple(llvm::sys::getProcessTriple());
assert(triple.getArch() == llvm::Triple::aarch64 &&
"Invalid default host triple for target");
return triple;
}
CodeGenerator *TargetAARCH64::GetCodeGenerator(void *address,
size_t start_alignment) {
return CodeGenerator::Create(GetTriple(), start_alignment);
}
Disassembler *TargetAARCH64::CreateDisassembler(void *address) {
return Disassembler::Create(GetTriple());
}
std::vector<TrampolineConfig> TargetAARCH64::GetTrampolineConfigs(
uintptr_t start_address) const {
std::vector<TrampolineConfig> configs;
configs.push_back({FIRST_4G_TRAMPOLINE, false, 0x10000, 0xffffffff});
configs.push_back({FULL_TRAMPOLINE, false, 0, 0xffffffffffffffff});
return configs;
}
Error TargetAARCH64::EmitTrampoline(const TrampolineConfig &config,
CodeGenerator &codegen, void *source,
void *target) {
switch (config.type) {
case FIRST_4G_TRAMPOLINE: {
uint64_t target_addr = reinterpret_cast<uintptr_t>(target);
if (target_addr > 0xffffffff)
return Error("Target address is out of range for the trampoline");
uint32_t target_addr32 = target_addr;
codegen.AddInstruction(
llvm::MCInstBuilder(llvm::AArch64::LDRWl)
.addReg(llvm::AArch64::X17)
.addExpr(codegen.CreateDataExpr(target_addr32)));
codegen.AddInstruction(
llvm::MCInstBuilder(llvm::AArch64::BR).addReg(llvm::AArch64::X17));
return Error();
}
case FULL_TRAMPOLINE: {
uint64_t target_addr = reinterpret_cast<uintptr_t>(target);
codegen.AddInstruction(llvm::MCInstBuilder(llvm::AArch64::LDRXl)
.addReg(llvm::AArch64::X17)
.addExpr(codegen.CreateDataExpr(target_addr)));
codegen.AddInstruction(
llvm::MCInstBuilder(llvm::AArch64::BR).addReg(llvm::AArch64::X17));
return Error();
}
}
return Error("Unsupported trampoline type");
}
static void *calculatePcRelativeAddress(void *data, size_t pc_offset,
size_t offset, bool page_align) {
uintptr_t data_addr = reinterpret_cast<uintptr_t>(data);
assert((data_addr & 3) == 0 && "Unaligned data address");
assert((pc_offset & 3) == 0 && "Unaligned PC offset");
data_addr += pc_offset; // Add the PC
if (page_align) {
data_addr &= ~0x0fff; // Align to 4KB
offset <<= 12;
}
data_addr += offset; // Add the offset
return reinterpret_cast<void *>(data_addr);
}
// IP1 (second intra-procedure-call scratch register) is X17 and it is used in
// the trampoline so we need special handling for it.
static bool hasIP1Operand(const llvm::MCInst &inst) {
for (size_t i = 0; i < inst.getNumOperands(); ++i) {
const llvm::MCOperand &op = inst.getOperand(i);
if (op.isReg() && op.getReg() == llvm::AArch64::X17) return true;
}
return false;
}
Error TargetAARCH64::RewriteInstruction(const llvm::MCInst &inst,
CodeGenerator &codegen, void *data,
size_t offset,
bool &possible_end_of_function) {
switch (inst.getOpcode()) {
case llvm::AArch64::ADDXri:
case llvm::AArch64::ANDXri:
case llvm::AArch64::LDRXui:
case llvm::AArch64::MOVNWi:
case llvm::AArch64::MOVNXi:
case llvm::AArch64::MOVZWi:
case llvm::AArch64::MOVZXi:
case llvm::AArch64::MRS:
case llvm::AArch64::ORRWrs:
case llvm::AArch64::ORRXrs:
case llvm::AArch64::STPDi:
case llvm::AArch64::STPXi:
case llvm::AArch64::STPXpre:
case llvm::AArch64::STRBBui:
case llvm::AArch64::STRSui:
case llvm::AArch64::STRWui:
case llvm::AArch64::STRXpre:
case llvm::AArch64::STRXui:
case llvm::AArch64::SUBSWri:
case llvm::AArch64::SUBSXri:
case llvm::AArch64::SUBXri: {
if (hasIP1Operand(inst))
return Error(
"Instruction not handled yet when one of the operand is IP1 (%s "
"(OpcodeId: %d))",
codegen.PrintInstruction(inst).c_str(), inst.getOpcode());
possible_end_of_function = false;
codegen.AddInstruction(inst);
break;
}
case llvm::AArch64::ADRP: {
uint32_t Rd = inst.getOperand(0).getReg();
uint64_t imm = inst.getOperand(1).getImm();
possible_end_of_function = false;
if (hasIP1Operand(inst))
return Error(
"Instruction not handled yet when one of the operand is IP1 (%s "
"(OpcodeId: %d))",
codegen.PrintInstruction(inst).c_str(), inst.getOpcode());
uint64_t addr = reinterpret_cast<uintptr_t>(
calculatePcRelativeAddress(data, offset, imm, true));
codegen.AddInstruction(llvm::MCInstBuilder(llvm::AArch64::LDRXl)
.addReg(Rd)
.addExpr(codegen.CreateDataExpr(addr)));
break;
}
case llvm::AArch64::B: {
uint64_t imm = inst.getOperand(0).getImm() << 2;
possible_end_of_function = true;
uint64_t addr = reinterpret_cast<uintptr_t>(
calculatePcRelativeAddress(data, offset, imm, false));
codegen.AddInstruction(llvm::MCInstBuilder(llvm::AArch64::LDRXl)
.addReg(llvm::AArch64::X17)
.addExpr(codegen.CreateDataExpr(addr)));
codegen.AddInstruction(
llvm::MCInstBuilder(llvm::AArch64::BR).addReg(llvm::AArch64::X17));
break;
}
case llvm::AArch64::BL: {
uint64_t imm = inst.getOperand(0).getImm() << 2;
possible_end_of_function = true;
uint64_t addr = reinterpret_cast<uintptr_t>(
calculatePcRelativeAddress(data, offset, imm, false));
codegen.AddInstruction(llvm::MCInstBuilder(llvm::AArch64::LDRXl)
.addReg(llvm::AArch64::X17)
.addExpr(codegen.CreateDataExpr(addr)));
codegen.AddInstruction(
llvm::MCInstBuilder(llvm::AArch64::BLR).addReg(llvm::AArch64::X17));
break;
}
case llvm::AArch64::CBZX: {
uint32_t Rt = inst.getOperand(0).getReg();
uint64_t imm = inst.getOperand(1).getImm() << 2;
possible_end_of_function = false;
if (hasIP1Operand(inst))
return Error(
"Instruction not handled yet when one of the operand is IP0 (%s "
"(OpcodeId: %d))",
codegen.PrintInstruction(inst).c_str(), inst.getOpcode());
uint64_t addr = reinterpret_cast<uintptr_t>(
calculatePcRelativeAddress(data, offset, imm, false));
codegen.AddInstruction(
llvm::MCInstBuilder(llvm::AArch64::CBNZX).addReg(Rt).addImm(12 >> 2));
codegen.AddInstruction(llvm::MCInstBuilder(llvm::AArch64::LDRXl)
.addReg(llvm::AArch64::X17)
.addExpr(codegen.CreateDataExpr(addr)));
codegen.AddInstruction(
llvm::MCInstBuilder(llvm::AArch64::BR).addReg(llvm::AArch64::X17));
break;
}
default: {
possible_end_of_function = true;
return Error("Unhandled instruction: %s (OpcodeId: %d)",
codegen.PrintInstruction(inst).c_str(), inst.getOpcode());
}
}
return Error();
}
@@ -0,0 +1,52 @@
/*
* Copyright (C) 2017 Google 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 INTERCEPTOR_AARCH64_TARGET_AARCH64_H_
#define INTERCEPTOR_AARCH64_TARGET_AARCH64_H_
#include "target.h"
namespace interceptor {
class TargetAARCH64 : public Target {
public:
CodeGenerator *GetCodeGenerator(void *address,
size_t start_alignment) override;
Disassembler *CreateDisassembler(void *address) override;
size_t GetCodeAlignment() const override { return 4; }
std::vector<TrampolineConfig> GetTrampolineConfigs(
uintptr_t start_address) const override;
Error EmitTrampoline(const TrampolineConfig &config, CodeGenerator &codegen,
void *source, void *target) override;
Error RewriteInstruction(const llvm::MCInst &inst, CodeGenerator &codegen,
void *data, size_t offset,
bool &possible_end_of_function) override;
private:
enum TrampolineType {
FULL_TRAMPOLINE = 0, // Full trampoline with an absolute jump
FIRST_4G_TRAMPOLINE = 1, // Can target the first 4GB of the memory
};
};
} // end of namespace interceptor
#endif // INTERCEPTOR_AARCH64_TARGET_AARCH64_H_
+373
View File
@@ -0,0 +1,373 @@
/*
* Copyright (C) 2017 Google 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.
*/
#include "target_arm.h"
#include <memory>
#include "MCTargetDesc/ARMBaseInfo.h"
#include "MCTargetDesc/ARMMCTargetDesc.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstBuilder.h"
#include "code_generator.h"
#include "disassembler.h"
using namespace interceptor;
static bool IsThumb(void *ptr) { return reinterpret_cast<uintptr_t>(ptr) & 1; }
static bool IsThumb(const CodeGenerator &codegen) {
llvm::Triple::ArchType arch =
codegen.GetSubtargetInfo().getTargetTriple().getArch();
return arch == llvm::Triple::thumb || arch == llvm::Triple::thumbeb;
}
static llvm::Triple GetTriple(void *addr) {
llvm::Triple triple(llvm::sys::getProcessTriple());
assert((triple.getArch() == llvm::Triple::arm ||
triple.getArch() == llvm::Triple::thumb) &&
"Invalid default host triple for target");
if (IsThumb(addr)) {
llvm::StringRef arm_name = triple.getArchName();
std::string thumb_name("thumb");
thumb_name += arm_name.substr(3);
triple.setArchName(thumb_name);
}
return triple;
}
CodeGenerator *TargetARM::GetCodeGenerator(void *address,
size_t start_alignment) {
return CodeGenerator::Create(GetTriple(address), start_alignment);
}
Disassembler *TargetARM::CreateDisassembler(void *address) {
return Disassembler::Create(GetTriple(address));
}
void *TargetARM::GetLoadAddress(void *addr) {
uintptr_t addr_val = reinterpret_cast<uintptr_t>(addr);
addr_val &= ~1;
return reinterpret_cast<void *>(addr_val);
}
void *TargetARM::FixupCallbackFunction(void *old_function, void *new_function) {
if (IsThumb(old_function)) {
uintptr_t new_func_addr = reinterpret_cast<uintptr_t>(new_function);
new_func_addr |= 1;
return reinterpret_cast<void *>(new_func_addr);
}
return new_function;
}
std::vector<TrampolineConfig> TargetARM::GetTrampolineConfigs(
uintptr_t start_address) const {
std::vector<TrampolineConfig> configs;
configs.push_back({FULL_TRAMPOLINE, false, 0, 0xffffffff});
return configs;
}
Error TargetARM::EmitTrampoline(const TrampolineConfig &config,
CodeGenerator &codegen, void *source,
void *target) {
switch (config.type) {
case FULL_TRAMPOLINE: {
uint32_t target_addr = (uintptr_t)target;
if (IsThumb(codegen)) {
codegen.AddInstruction(
llvm::MCInstBuilder(llvm::ARM::t2LDRpci)
.addReg(llvm::ARM::PC)
.addExpr(codegen.CreateDataExpr(target_addr)));
} else {
codegen.AddInstruction(llvm::MCInstBuilder(llvm::ARM::LDRi12)
.addReg(llvm::ARM::PC)
.addExpr(codegen.CreateDataExpr(target_addr))
.addImm(0)
.addImm(llvm::ARMCC::AL)
.addImm(0));
}
return Error();
}
}
return Error("Unsupported trampoline type");
}
static void *calculatePcRelativeAddressArm(void *data, size_t pc_offset,
size_t offset) {
uintptr_t data_addr = reinterpret_cast<uintptr_t>(data);
assert((data_addr & 3) == 0 && "Unaligned data address");
assert((pc_offset & 3) == 0 && "Unaligned PC offset");
data_addr += pc_offset; // Add the PC
data_addr += 8; // Add the 8 byte implicit offset
data_addr += offset; // Add the offset
return reinterpret_cast<void *>(data_addr);
}
static void *calculatePcRelativeAddressThumb(void *data, size_t pc_offset,
size_t offset, bool align) {
uintptr_t data_addr = reinterpret_cast<uintptr_t>(data);
assert((data_addr & 1) == 0 && "Unaligned data address");
assert((pc_offset & 1) == 0 && "Unaligned PC offset");
data_addr += pc_offset; // Add the PC
data_addr += 1; // Add 1 for the thumb bit
data_addr += 4; // Add the 4 byte implicit offset
if (align) data_addr &= ~3; // Align to 4 byte
data_addr += offset; // Add the offset
return reinterpret_cast<void *>(data_addr);
}
static uint32_t getThumbPc(void *data, size_t offset) {
uintptr_t data_addr = reinterpret_cast<uintptr_t>(data);
data_addr += offset;
data_addr += 4;
data_addr &= ~1;
return data_addr;
}
static bool hasPcOperand(const llvm::MCInst &inst) {
for (size_t i = 0; i < inst.getNumOperands(); ++i) {
const llvm::MCOperand &op = inst.getOperand(i);
if (op.isReg() && op.getReg() == llvm::ARM::PC) return true;
}
return false;
}
Error TargetARM::RewriteInstruction(const llvm::MCInst &inst,
CodeGenerator &codegen, void *data,
size_t offset,
bool &possible_end_of_function) {
switch (inst.getOpcode()) {
case llvm::ARM::tADDspi:
case llvm::ARM::tSUBspi: {
possible_end_of_function = false;
codegen.AddInstruction(inst);
break;
}
case llvm::ARM::MRC:
case llvm::ARM::MOVi16:
case llvm::ARM::tMOVi8: {
uint32_t RdRt = inst.getOperand(0).getReg();
possible_end_of_function = (RdRt == llvm::ARM::PC);
codegen.AddInstruction(inst);
break;
}
case llvm::ARM::t2LDMIA_UPD: {
possible_end_of_function = hasPcOperand(inst);
codegen.AddInstruction(inst);
break;
}
case llvm::ARM::CMPrr:
case llvm::ARM::LDR_PRE_IMM:
case llvm::ARM::LDR_PRE_REG:
case llvm::ARM::LDR_POST_IMM:
case llvm::ARM::LDR_POST_REG:
case llvm::ARM::LDRH_PRE:
case llvm::ARM::LDRH_POST:
case llvm::ARM::LDRH:
case llvm::ARM::LDRB_PRE_IMM:
case llvm::ARM::LDRB_PRE_REG:
case llvm::ARM::LDRB_POST_IMM:
case llvm::ARM::LDRB_POST_REG:
case llvm::ARM::LDRBi12:
case llvm::ARM::LDRSH_PRE:
case llvm::ARM::LDRSH_POST:
case llvm::ARM::LDRSH:
case llvm::ARM::LDRSB_PRE:
case llvm::ARM::LDRSB_POST:
case llvm::ARM::LDRSB:
case llvm::ARM::STR_PRE_IMM:
case llvm::ARM::STR_PRE_REG:
case llvm::ARM::STR_POST_IMM:
case llvm::ARM::STR_POST_REG:
case llvm::ARM::STRi12:
case llvm::ARM::STRH_PRE:
case llvm::ARM::STRH_POST:
case llvm::ARM::STRH:
case llvm::ARM::STRB_PRE_IMM:
case llvm::ARM::STRB_PRE_REG:
case llvm::ARM::STRB_POST_IMM:
case llvm::ARM::STRB_POST_REG:
case llvm::ARM::STRBi12:
case llvm::ARM::MOVr:
case llvm::ARM::STMDA_UPD:
case llvm::ARM::STMDB_UPD:
case llvm::ARM::STRD:
case llvm::ARM::STRD_PRE:
case llvm::ARM::SUBri:
case llvm::ARM::tADDi3:
case llvm::ARM::tADDi8:
case llvm::ARM::tADDrSP:
case llvm::ARM::tADDrSPi:
case llvm::ARM::tBIC:
case llvm::ARM::tCMPi8:
case llvm::ARM::tLDRi:
case llvm::ARM::tLDRspi:
case llvm::ARM::tLSRri:
case llvm::ARM::tMOVr:
case llvm::ARM::tPUSH:
case llvm::ARM::tSTRspi:
case llvm::ARM::tSUBrr:
case llvm::ARM::t2ADDri:
case llvm::ARM::t2ADDri12:
case llvm::ARM::t2BICri:
case llvm::ARM::t2BICrr:
case llvm::ARM::t2CMPri:
case llvm::ARM::t2LDRi12:
case llvm::ARM::t2LDRDi8:
case llvm::ARM::t2LDRD_PRE:
case llvm::ARM::t2LDRD_POST:
case llvm::ARM::t2MOVi:
case llvm::ARM::t2MOVr:
case llvm::ARM::t2MOVTi16:
case llvm::ARM::t2STMDB_UPD:
case llvm::ARM::t2STR_PRE:
case llvm::ARM::t2STRDi8:
case llvm::ARM::t2STRD_PRE:
case llvm::ARM::t2STRD_POST:
case llvm::ARM::t2SUBri:
case llvm::ARM::VSTMDDB_UPD: {
if (hasPcOperand(inst))
return Error(
"Instruction not handled yet when one of the operand is PC");
possible_end_of_function = false;
codegen.AddInstruction(inst);
break;
}
case llvm::ARM::tADDhirr: {
uint32_t Rdn = inst.getOperand(0).getReg();
uint32_t Rm = inst.getOperand(2).getReg();
possible_end_of_function = (Rdn == llvm::ARM::PC);
if (Rm == llvm::ARM::PC) {
if (Rdn == llvm::ARM::PC) return Error("'add pc, pc' is UNPREDICTABLE");
uint32_t pc_value = getThumbPc(data, offset);
uint32_t scratch_reg =
Rdn != llvm::ARM::R0 ? llvm::ARM::R0 : llvm::ARM::R1;
codegen.AddInstruction(
llvm::MCInstBuilder(llvm::ARM::tPUSH).addImm(0).addImm(0).addReg(
scratch_reg));
codegen.AddInstruction(llvm::MCInstBuilder(llvm::ARM::tLDRpci)
.addReg(scratch_reg)
.addExpr(codegen.CreateDataExpr(pc_value)));
codegen.AddInstruction(llvm::MCInstBuilder(llvm::ARM::tADDhirr)
.addReg(Rdn)
.addImm(0)
.addReg(scratch_reg));
codegen.AddInstruction(
llvm::MCInstBuilder(llvm::ARM::tPOP).addImm(0).addImm(0).addReg(
scratch_reg));
} else {
codegen.AddInstruction(inst);
}
break;
}
case llvm::ARM::LDRi12: {
uint32_t Rt = inst.getOperand(0).getReg();
uint32_t Rn = inst.getOperand(1).getReg();
int64_t imm = inst.getOperand(2).getImm();
int64_t p = inst.getOperand(3).getImm();
possible_end_of_function = (Rt == llvm::ARM::PC);
if (Rn == llvm::ARM::PC) {
void *load_source =
calculatePcRelativeAddressArm(data, offset, imm);
uint32_t load_data = 0;
memcpy(&load_data, load_source, sizeof(uint32_t));
codegen.AddInstruction(llvm::MCInstBuilder(llvm::ARM::LDRi12)
.addReg(Rt)
.addExpr(codegen.CreateDataExpr(load_data))
.addImm(0)
.addImm(p)
.addImm(0));
} else {
codegen.AddInstruction(inst);
}
break;
}
case llvm::ARM::tLDRpci:
case llvm::ARM::t2LDRpci: {
uint32_t Rt = inst.getOperand(0).getReg();
int64_t imm = inst.getOperand(1).getImm();
possible_end_of_function = (Rt == llvm::ARM::PC);
void *load_source =
calculatePcRelativeAddressThumb(data, offset, imm, true);
uint32_t load_data = 0;
memcpy(&load_data, load_source, sizeof(uint32_t));
llvm::MCInst new_inst = inst; // TODO: Use MCInstBuilder
new_inst.getOperand(1) =
llvm::MCOperand::createExpr(codegen.CreateDataExpr(load_data));
codegen.AddInstruction(new_inst);
break;
}
case llvm::ARM::Bcc: {
uint32_t pred = inst.getOperand(0).getImm();
uint32_t imm = inst.getOperand(1).getImm();
possible_end_of_function = true;
void *target = calculatePcRelativeAddressArm(data, offset, imm);
uint32_t target_addr = reinterpret_cast<uintptr_t>(target);
codegen.AddInstruction(llvm::MCInstBuilder(llvm::ARM::LDRi12)
.addReg(llvm::ARM::PC)
.addExpr(codegen.CreateDataExpr(target_addr))
.addImm(0)
.addImm(pred)
.addImm(0));
break;
}
case llvm::ARM::t2B: {
uint32_t imm = inst.getOperand(0).getImm();
possible_end_of_function = true;
void *target = calculatePcRelativeAddressThumb(data, offset, imm, false);
uint32_t target_addr = reinterpret_cast<uintptr_t>(target);
codegen.AddInstruction(llvm::MCInstBuilder(llvm::ARM::t2LDRpci)
.addReg(llvm::ARM::PC)
.addExpr(codegen.CreateDataExpr(target_addr)));
break;
}
case llvm::ARM::tBL: {
uint32_t imm = inst.getOperand(2).getImm();
possible_end_of_function = false;
uint32_t lr_offset = 5 + codegen.GetAlignmentOffset(4);
codegen.AddInstruction(llvm::MCInstBuilder(llvm::ARM::t2ADDri12)
.addReg(llvm::ARM::LR) // Rd
.addReg(llvm::ARM::PC) // Rn
.addImm(lr_offset) // imm
.addImm(0) // -
.addImm(0) // -
.addReg(llvm::ARM::R0)); // S
void *target = calculatePcRelativeAddressThumb(data, offset, imm, false);
uint32_t target_addr = reinterpret_cast<uintptr_t>(target);
codegen.AddInstruction(llvm::MCInstBuilder(llvm::ARM::t2LDRpci)
.addReg(llvm::ARM::PC)
.addExpr(codegen.CreateDataExpr(target_addr)));
break;
}
default: {
possible_end_of_function = true;
return Error("Unhandled instruction: %s (OpcodeId: %d)",
codegen.PrintInstruction(inst).c_str(), inst.getOpcode());
}
}
return Error();
}
+55
View File
@@ -0,0 +1,55 @@
/*
* Copyright (C) 2017 Google 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 INTERCEPTOR_ARM_TARGET_ARM_H_
#define INTERCEPTOR_ARM_TARGET_ARM_H_
#include "target.h"
namespace interceptor {
class TargetARM : public Target {
public:
CodeGenerator *GetCodeGenerator(void *address,
size_t start_alignment) override;
Disassembler *CreateDisassembler(void *address) override;
size_t GetCodeAlignment() const override { return 4; }
void *GetLoadAddress(void *addr) override;
std::vector<TrampolineConfig> GetTrampolineConfigs(
uintptr_t start_address) const override;
Error EmitTrampoline(const TrampolineConfig &config, CodeGenerator &codegen,
void *source, void *target) override;
Error RewriteInstruction(const llvm::MCInst &inst, CodeGenerator &codegen,
void *data, size_t offset,
bool &possible_end_of_function) override;
void *FixupCallbackFunction(void *old_function, void *new_function) override;
private:
enum TrampolineType {
FULL_TRAMPOLINE = 0, // Full trampoline with an absolute jump
};
};
} // end of namespace interceptor
#endif // INTERCEPTOR_ARM_TARGET_ARM_H_
+66
View File
@@ -0,0 +1,66 @@
# Copyright (C) 2017 Google 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.
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
include_directories(${LLVM_INCLUDE_DIRS})
add_definitions(${LLVM_DEFINITIONS})
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-rtti")
set(sources
code_generator.cc
constant_pool_data_expr.cc
disassembler.cc
error.cc
interceptor.cc
linker.cc
memory_manager.cc
target.cc)
set(interceptor_arch_libs)
foreach(TARGET ${LLVM_TARGETS_TO_BUILD})
file(GLOB arch_sources ${TARGET}/*.cc)
list(APPEND sources ${arch_sources})
set(needed_libs
${TARGET}AsmParser
${TARGET}Desc
${TARGET}Disassembler
${TARGET}AsmPrinter
${TARGET}Info)
if(${TARGET} STREQUAL "AArch64")
list(APPEND needed_libs ${TARGET}Utils)
endif()
llvm_map_components_to_libnames(arch_libs ${needed_libs})
list(APPEND interceptor_arch_libs ${arch_libs})
endforeach()
llvm_map_components_to_libnames(interceptor_general_libs
MCDisassembler
Object
MCParser
BitReader
MC
Core
Support)
set(interceptor_libs z ${interceptor_arch_libs} ${interceptor_general_libs} PARENT_SCOPE)
add_library(interceptor_lib OBJECT
${sources})
+188
View File
@@ -0,0 +1,188 @@
/*
* Copyright (C) 2017 Google 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.
*/
#include "target_x86.h"
#include <memory>
#include "MCTargetDesc/X86MCTargetDesc.h"
#include "llvm/ADT/Triple.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstBuilder.h"
#include "code_generator.h"
#include "disassembler.h"
using namespace interceptor;
static llvm::Triple GetTriple() {
llvm::Triple triple(llvm::sys::getProcessTriple());
assert(triple.getArch() == llvm::Triple::x86 &&
"Invalid default host triple for target");
return triple;
}
CodeGenerator *TargetX86::GetCodeGenerator(void *address,
size_t start_alignment) {
return CodeGenerator::Create(GetTriple(), start_alignment);
}
Disassembler *TargetX86::CreateDisassembler(void *address) {
return Disassembler::Create(GetTriple());
}
std::vector<TrampolineConfig> TargetX86::GetTrampolineConfigs(
uintptr_t start_address) const {
std::vector<TrampolineConfig> configs;
configs.push_back({FULL_TRAMPOLINE, false, 0, 0xffffffff});
return configs;
}
Error TargetX86::EmitTrampoline(const TrampolineConfig &config,
CodeGenerator &codegen, void *source,
void *target) {
switch (config.type) {
case FULL_TRAMPOLINE: {
uintptr_t target_addr = reinterpret_cast<uintptr_t>(target);
codegen.AddInstruction(
llvm::MCInstBuilder(llvm::X86::JMP_4).addImm(target_addr));
return Error();
}
}
return Error("Unsupported trampoline type");
}
static uintptr_t calculatePcRelativeAddress(void *data, int64_t pc_offset,
size_t offset, size_t instr_size) {
uintptr_t data_addr = reinterpret_cast<uintptr_t>(data);
data_addr += pc_offset;
data_addr += offset;
data_addr += instr_size;
return data_addr;
}
// Checks if the given address is the address of the __x86.get_pc_thunk.bx
// function with comparing the instruction sequence to the following opcodes:
// MOVL (%esp), %ebx; RETL
// Additionally we detect functions with NOP instructions between the above
// sepcified instructions.
static Error IsGetPcThunk(TargetX86 *target, void *address, bool &res) {
std::unique_ptr<Disassembler> disassembler(
target->CreateDisassembler(address));
if (!disassembler) return Error("Failed to create disassembler");
// The decode state represent the next instruction we are expecting
enum class DetectState : uint8_t {
MOV,
RET
};
DetectState state = DetectState::MOV;
size_t offset = 0;
while (true) {
llvm::MCInst inst;
uint64_t inst_size = 0;
if (!disassembler->GetInstruction(address, offset, inst, inst_size))
return Error("Failed to disassemble instruction at %p + %zd", address,
offset);
switch (inst.getOpcode()) {
case llvm::X86::NOOP:
case llvm::X86::NOOPL:
case llvm::X86::NOOPW:
break;
case llvm::X86::RET:
case llvm::X86::RETL:
case llvm::X86::RETW:
res = (state == DetectState::RET);
return Error();
case llvm::X86::MOV32rm:
if (state != DetectState::MOV) {
res = false;
return Error();
} else if (inst.getNumOperands() < 2) {
res = false;
return Error();
}
const llvm::MCOperand &op0 = inst.getOperand(0),
op1 = inst.getOperand(1);
if (!op0.isReg() || op0.getReg() != llvm::X86::EBX || !op1.isReg() ||
op1.getReg() != llvm::X86::ESP) {
res = false;
return Error();
}
state = DetectState::RET;
break;
}
offset += inst_size;
}
}
Error TargetX86::RewriteInstruction(const llvm::MCInst &inst,
CodeGenerator &codegen, void *data,
size_t offset,
bool &possible_end_of_function) {
switch (inst.getOpcode()) {
case llvm::X86::AND32rr:
case llvm::X86::AND32mr:
case llvm::X86::AND32ri8:
case llvm::X86::AND32mi8:
case llvm::X86::AND32i32:
case llvm::X86::AND32ri:
case llvm::X86::AND32mi:
case llvm::X86::AND32rm:
case llvm::X86::LEA32r:
case llvm::X86::MOV32ao32:
case llvm::X86::MOV32rm:
case llvm::X86::MOV32rr:
case llvm::X86::PUSH32r:
case llvm::X86::SUB32ri:
case llvm::X86::SUB32ri8: {
possible_end_of_function = false;
codegen.AddInstruction(inst);
break;
}
case llvm::X86::CALLpcrel32: {
if (inst.getNumOperands() != 1)
return Error("CALL <rel32> not supported when has more then 1 operand");
possible_end_of_function = false;
uintptr_t target_addr = calculatePcRelativeAddress(
data, inst.getOperand(0).getImm(), offset, 5);
bool is_get_pc_thunk = false;
Error error = IsGetPcThunk(this, reinterpret_cast<void *>(target_addr),
is_get_pc_thunk);
if (error.Fail()) return error;
if (is_get_pc_thunk) {
uintptr_t return_value = calculatePcRelativeAddress(data, 0, offset, 5);
codegen.AddInstruction(llvm::MCInstBuilder(llvm::X86::MOV32ri)
.addReg(llvm::X86::EBX)
.addImm(return_value));
} else {
codegen.AddInstruction(
llvm::MCInstBuilder(llvm::X86::CALLpcrel32).addImm(target_addr));
}
break;
}
default: {
possible_end_of_function = true;
return Error("Unhandled instruction: %s (OpcodeId: %d)",
codegen.PrintInstruction(inst).c_str(), inst.getOpcode());
}
}
return Error();
}
+51
View File
@@ -0,0 +1,51 @@
/*
* Copyright (C) 2017 Google 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 INTERCEPTOR_X86_TARGET_X86_H_
#define INTERCEPTOR_X86_TARGET_X86_H_
#include "target.h"
namespace interceptor {
class TargetX86 : public Target {
public:
CodeGenerator *GetCodeGenerator(void *address,
size_t start_alignment) override;
Disassembler *CreateDisassembler(void *address) override;
size_t GetCodeAlignment() const override { return 4; }
std::vector<TrampolineConfig> GetTrampolineConfigs(
uintptr_t start_address) const override;
Error EmitTrampoline(const TrampolineConfig &config, CodeGenerator &codegen,
void *source, void *target) override;
Error RewriteInstruction(const llvm::MCInst &inst, CodeGenerator &codegen,
void *data, size_t offset,
bool &possible_end_of_function) override;
private:
enum TrampolineType {
FULL_TRAMPOLINE = 0, // Full trampoline with an absolute jump
};
};
} // end of namespace interceptor
#endif // INTERCEPTOR_X86_TARGET_X86_H_
+142
View File
@@ -0,0 +1,142 @@
/*
* Copyright (C) 2017 Google 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.
*/
#include "code_generator.h"
using namespace interceptor;
CodeGenerator::CodeGenerator(const llvm::Triple &triple, size_t start_alignment)
: start_alignment_(start_alignment), triple_(triple), code_stream_(code_) {
// Set the start alignment of the stream to match with the specified value
for (size_t i = 0; i < start_alignment_; ++i) code_stream_.write((char)0);
}
CodeGenerator *CodeGenerator::Create(const llvm::Triple &triple,
size_t start_alignment) {
std::unique_ptr<CodeGenerator> codegen(
new CodeGenerator(triple, start_alignment));
if (codegen->Initialize()) return codegen.release();
return nullptr;
}
void CodeGenerator::AddInstruction(const llvm::MCInst &inst) {
size_t offset = code_.size();
llvm::SmallVector<llvm::MCFixup, 4> new_fixups;
codegen_->encodeInstruction(inst, code_stream_, new_fixups, *sti_);
// We have to offset the fixups with the offset of the generated instruction
// in the data stream because encodeInstruction emits them as if it is
// writing the new instructions from the beginning of the stream.
for (llvm::MCFixup &fixup : new_fixups)
fixup.setOffset(fixup.getOffset() + offset);
fixups_.insert(fixups_.end(), new_fixups.begin(), new_fixups.end());
}
bool CodeGenerator::Initialize() {
std::string error;
const llvm::Target *target =
llvm::TargetRegistry::lookupTarget(triple_.str().c_str(), error);
if (!target) return false;
mri_.reset(target->createMCRegInfo(triple_.str().c_str()));
if (!mri_) return false;
sti_.reset(target->createMCSubtargetInfo(triple_.str().c_str(), "", ""));
if (!sti_) return false;
mii_.reset(target->createMCInstrInfo());
if (!mii_) return false;
llvm::MCTargetOptions options;
asmb_.reset(target->createMCAsmBackend(*mri_, triple_.str(), "", options));
if (!asmb_) return false;
ctx_.reset(new llvm::MCContext(nullptr, mri_.get(), nullptr));
codegen_.reset(target->createMCCodeEmitter(*mii_, *mri_, *ctx_));
if (!codegen_) return false;
// These are used only for logging and error reporting. Don't fail if we
// haven't managed to create them.
asmi_.reset(target->createMCAsmInfo(*mri_, triple_.str().c_str()));
if (asmi_) {
ipr_.reset(target->createMCInstPrinter(llvm::Triple(triple_), 0, *asmi_,
*mii_, *mri_));
}
return true;
}
size_t CodeGenerator::LayoutCode() {
for (const ConstantPoolDataExpr *pool : const_pool_exprs_)
const_cast<ConstantPoolDataExpr *>(pool)->allocate(code_stream_);
return code_.size() - start_alignment_;
}
Error CodeGenerator::LinkCode(uintptr_t location) {
for (const ConstantPoolDataExpr *pool : const_pool_exprs_)
const_cast<ConstantPoolDataExpr *>(pool)->setBaseLocation(location);
for (const llvm::MCFixup &fixup : fixups_) {
const llvm::MCExpr *expr = fixup.getValue();
llvm::MCValue mc_value;
uint64_t value = 0;
if (!expr->evaluateAsRelocatable(mc_value, nullptr, &fixup))
return Error("Failed to evalue the value of an MCFixup");
value = mc_value.getConstant();
int flags = asmb_->getFixupKindInfo(fixup.getKind()).Flags;
bool pc_rel = flags & llvm::MCFixupKindInfo::FKF_IsPCRel;
bool align_pc = flags & llvm::MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
if (pc_rel) {
uint64_t offset = fixup.getOffset();
if (align_pc) offset &= ~0x3;
value -= offset;
value -= location;
}
asmb_->applyFixup(fixup, code_.data(), code_.size(), value, pc_rel);
}
if (start_alignment_ != 0)
code_.erase(code_.begin(), code_.begin() + start_alignment_);
return Error();
}
const llvm::SmallVectorImpl<char> &CodeGenerator::GetCode() const {
return code_;
}
const llvm::MCSubtargetInfo &CodeGenerator::GetSubtargetInfo() const {
return *sti_;
}
uint32_t CodeGenerator::GetAlignmentOffset(uint32_t alignment_base) const {
return code_.size() % alignment_base;
}
std::string CodeGenerator::PrintInstruction(const llvm::MCInst &inst) {
std::string s;
llvm::raw_string_ostream os(s);
if (ipr_)
ipr_->printInst(&inst, os, "", *sti_);
else
inst.dump_pretty(os, nullptr, " ");
return os.str();
}
+100
View File
@@ -0,0 +1,100 @@
/*
* Copyright (C) 2017 Google 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 INTERCEPTOR_CONSTNT_POOL_DATA_EXPR_H_
#define INTERCEPTOR_CONSTNT_POOL_DATA_EXPR_H_
#include <memory>
#include <string>
#include <vector>
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCDisassembler/MCDisassembler.h"
#include "llvm/MC/MCFixupKindInfo.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCValue.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "constant_pool_data_expr.h"
#include "error.h"
namespace interceptor {
class CodeGenerator {
public:
static CodeGenerator *Create(const llvm::Triple &triple,
size_t start_alignment = 0);
void AddInstruction(const llvm::MCInst &inst);
size_t LayoutCode();
Error LinkCode(uintptr_t location);
const llvm::SmallVectorImpl<char> &GetCode() const;
uint32_t GetAlignmentOffset(uint32_t alignment_base) const;
template <typename T, size_t A = alignof(T)>
const llvm::MCExpr *CreateDataExpr(T value, size_t alignment = A);
const llvm::MCSubtargetInfo &GetSubtargetInfo() const;
std::string PrintInstruction(const llvm::MCInst &inst);
private:
CodeGenerator(const llvm::Triple &triple, size_t start_alignment);
bool Initialize();
size_t start_alignment_;
llvm::Triple triple_;
std::unique_ptr<llvm::MCRegisterInfo> mri_;
std::unique_ptr<llvm::MCSubtargetInfo> sti_;
std::unique_ptr<llvm::MCInstrInfo> mii_;
std::unique_ptr<llvm::MCInstPrinter> ipr_;
std::unique_ptr<llvm::MCAsmBackend> asmb_;
std::unique_ptr<llvm::MCAsmInfo> asmi_;
std::unique_ptr<llvm::MCContext> ctx_;
std::unique_ptr<llvm::MCCodeEmitter> codegen_;
std::vector<llvm::MCInst> instructions_;
std::vector<const ConstantPoolDataExpr *> const_pool_exprs_;
llvm::SmallVector<char, 32> code_;
llvm::raw_svector_ostream code_stream_;
llvm::SmallVector<llvm::MCFixup, 8> fixups_;
};
template <typename T, size_t A>
const llvm::MCExpr *CodeGenerator::CreateDataExpr(T value, size_t alignment) {
const llvm::MCExpr *value_exp = llvm::MCConstantExpr::create(value, *ctx_);
const_pool_exprs_.emplace_back(
ConstantPoolDataExpr::Create(value_exp, sizeof(T), alignment, *ctx_));
return const_pool_exprs_.back();
}
} // end of namespace interceptor
#endif // INTERCEPTOR_CONSTNT_POOL_DATA_EXPR_H_
@@ -0,0 +1,100 @@
/*
* Copyright (C) 2017 Google 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.
*/
#include "constant_pool_data_expr.h"
using namespace interceptor;
ConstantPoolDataExpr::ConstantPoolDataExpr(const llvm::MCExpr *expr,
size_t size, size_t alignment)
: expr_(expr),
size_(size),
alignment_(alignment),
allocated_(false),
base_location_(0) {}
const ConstantPoolDataExpr *ConstantPoolDataExpr::Create(
const llvm::MCExpr *expr, size_t size, size_t alignment,
llvm::MCContext &ctx) {
return new (ctx) ConstantPoolDataExpr(expr, size, alignment);
}
void ConstantPoolDataExpr::printImpl(llvm::raw_ostream &,
const llvm::MCAsmInfo *) const {}
void ConstantPoolDataExpr::fixELFSymbolsInTLSFixups(llvm::MCAssembler &) const {
}
void ConstantPoolDataExpr::visitUsedExpr(llvm::MCStreamer &Streamer) const {
Streamer.visitUsedExpr(*expr_);
}
llvm::MCFragment *ConstantPoolDataExpr::findAssociatedFragment() const {
llvm_unreachable("FIXME: what goes here?");
}
bool ConstantPoolDataExpr::evaluateAsRelocatableImpl(
llvm::MCValue &res, const llvm::MCAsmLayout *,
const llvm::MCFixup *) const {
if (!allocated_) return false;
res = llvm::MCValue::get(base_location_);
return true;
}
bool ConstantPoolDataExpr::allocate(llvm::raw_ostream &data) {
llvm::MCValue val;
if (!expr_->evaluateAsRelocatable(val, nullptr, nullptr)) return false;
base_location_ += data.tell();
while (base_location_ % alignment_ != 0) {
data.write((char)0);
base_location_++;
}
switch (size_) {
case 1: {
uint8_t value = val.getConstant();
data.write((char *)&value, sizeof(value));
break;
}
case 2: {
uint16_t value = val.getConstant();
data.write((char *)&value, sizeof(value));
break;
}
case 4: {
uint32_t value = val.getConstant();
data.write((char *)&value, sizeof(value));
break;
}
case 8: {
uint64_t value = val.getConstant();
data.write((char *)&value, sizeof(value));
break;
}
default: {
assert(false && "Unsupported alignment");
return false;
}
}
allocated_ = true;
return true;
}
void ConstantPoolDataExpr::setBaseLocation(uintptr_t location) {
base_location_ += location;
}
@@ -0,0 +1,66 @@
/*
* Copyright (C) 2017 Google 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 INTERCEPTOR_CONSTANT_POOL_DATA_EXPR_H_
#define INTERCEPTOR_CONSTANT_POOL_DATA_EXPR_H_
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCValue.h"
#include "llvm/Support/raw_ostream.h"
namespace interceptor {
class ConstantPoolDataExpr : public llvm::MCTargetExpr {
public:
void printImpl(llvm::raw_ostream &, const llvm::MCAsmInfo *) const override;
void visitUsedExpr(llvm::MCStreamer &Streamer) const override;
llvm::MCFragment *findAssociatedFragment() const override;
bool evaluateAsRelocatableImpl(llvm::MCValue &res, const llvm::MCAsmLayout *,
const llvm::MCFixup *) const override;
void fixELFSymbolsInTLSFixups(llvm::MCAssembler &) const override;
bool allocate(llvm::raw_ostream &data);
void setBaseLocation(uintptr_t location);
static const ConstantPoolDataExpr *Create(const llvm::MCExpr *expr,
size_t size, size_t alignment,
llvm::MCContext &ctx);
static bool classof(const MCExpr *E) {
return E->getKind() == MCExpr::Target;
}
private:
ConstantPoolDataExpr(const llvm::MCExpr *expr, size_t size, size_t alignment);
const llvm::MCExpr *expr_;
const size_t size_;
const size_t alignment_;
bool allocated_;
uintptr_t base_location_;
};
} // end of namespace interceptor
#endif // INTERCEPTOR_CONSTANT_POOL_DATA_EXPR_H_
+62
View File
@@ -0,0 +1,62 @@
/*
* Copyright (C) 2017 Google 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.
*/
#include "disassembler.h"
using namespace interceptor;
Disassembler::Disassembler(const llvm::Triple &triple) : triple_(triple) {}
Disassembler *Disassembler::Create(const llvm::Triple &triple) {
std::unique_ptr<Disassembler> disassembler(new Disassembler(triple));
if (disassembler->Initialize()) return disassembler.release();
return nullptr;
}
bool Disassembler::Initialize() {
std::string error;
const llvm::Target *target =
llvm::TargetRegistry::lookupTarget(triple_.str().c_str(), error);
if (!target) return false;
sti_.reset(target->createMCSubtargetInfo(triple_.str().c_str(), "", ""));
if (!sti_) return false;
mri_.reset(target->createMCRegInfo(triple_.str().c_str()));
if (!mri_) return false;
ctx_.reset(new llvm::MCContext(nullptr, mri_.get(), nullptr));
dis_.reset(target->createMCDisassembler(*sti_, *ctx_));
if (!dis_) return false;
return true;
}
bool Disassembler::GetInstruction(const void *data, size_t offset,
llvm::MCInst &inst, uint64_t &inst_size) {
const uint8_t *data_p = static_cast<const uint8_t *>(data);
llvm::ArrayRef<uint8_t> data_arr(data_p + offset, 32);
auto status = dis_->getInstruction(inst, inst_size, data_arr, offset,
llvm::nulls(), llvm::nulls());
switch (status) {
case llvm::MCDisassembler::Success:
return true;
case llvm::MCDisassembler::Fail:
case llvm::MCDisassembler::SoftFail:
return false;
}
llvm_unreachable("Unexpected decode status");
}
+57
View File
@@ -0,0 +1,57 @@
/*
* Copyright (C) 2017 Google 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 INTERCEPTOR_DISASSEMBLER_H_
#define INTERCEPTOR_DISASSEMBLER_H_
#include <memory>
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCDisassembler/MCDisassembler.h"
#include "llvm/MC/MCFixupKindInfo.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCValue.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
namespace interceptor {
class Disassembler {
public:
static Disassembler *Create(const llvm::Triple &triple);
bool GetInstruction(const void *data, size_t offset, llvm::MCInst &inst,
uint64_t &inst_size);
private:
Disassembler(const llvm::Triple &triple);
bool Initialize();
llvm::Triple triple_;
std::unique_ptr<llvm::MCRegisterInfo> mri_;
std::unique_ptr<llvm::MCSubtargetInfo> sti_;
std::unique_ptr<llvm::MCContext> ctx_;
std::unique_ptr<llvm::MCDisassembler> dis_;
};
} // end of namespace interceptor
#endif // INTERCEPTOR_DISASSEMBLER_H_
+40
View File
@@ -0,0 +1,40 @@
/*
* Copyright (C) 2017 Google 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.
*/
#include "error.h"
#include <cstdio>
#include <vector>
using namespace interceptor;
Error::Error(const char *format, ...) {
va_list args, copy_args;
va_start(args, format);
va_copy(copy_args, args);
char buf[1024];
size_t len = vsnprintf(buf, sizeof(buf), format, args);
va_end(args);
if (len >= sizeof(buf)) {
std::vector<char> buf2(len + 1);
vsnprintf(buf2.data(), buf2.size(), format, args);
va_end(copy_args);
message_.assign(buf2.data());
} else {
message_.assign(buf);
}
}
+41
View File
@@ -0,0 +1,41 @@
/*
* Copyright (C) 2017 Google 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 INTERCEPTOR_ERROR_H_
#define INTERCEPTOR_ERROR_H_
#include <string>
namespace interceptor {
class Error {
public:
Error() = default;
Error(const char *format, ...) __attribute__((format(printf, 2, 3)));
bool Fail() const { return !Success(); }
bool Success() const { return message_.empty(); }
bool operator()() const { return Success(); }
const std::string &GetMessage() const { return message_; }
private:
std::string message_;
};
} // end of namespace interceptor
#endif // INTERCEPTOR_ERROR_H_
+399
View File
@@ -0,0 +1,399 @@
/*
* Copyright (C) 2017 Google 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.
*/
#include "interceptor.h"
#include <sys/mman.h>
#include <unistd.h>
#include <map>
#include <memory>
#include <mutex>
#include <sstream>
#include <unordered_map>
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCDisassembler/MCDisassembler.h"
#include "llvm/MC/MCFixupKindInfo.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstBuilder.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCValue.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "code_generator.h"
#include "linker.h"
#include "memory_manager.h"
#include "target.h"
#if defined(__arm__)
#include "ARM/target_arm.h"
#elif defined(__arm64__) || defined(__aarch64__)
#include "AArch64/target_aarch64.h"
#elif defined(__i386__)
#include "X86/target_x86.h"
#endif
using namespace interceptor;
namespace interceptor {
class InterceptorImpl {
public:
InterceptorImpl();
~InterceptorImpl();
Error InterceptFunction(void *old_function, void *new_function,
void **callback_function);
Error InterceptFunction(const char *symbol_name, void *new_function,
void **callback_function);
void *FindFunctionByName(const char *symbol_name);
private:
Error WriteMemory(void *target, const void *source, size_t num,
bool is_executable);
Error GetTrampolineSize(const TrampolineConfig &config, void *old_function,
void *new_function, size_t &trampoline_size);
Error InstallTrampoline(const TrampolineConfig &config, void *old_function,
void *new_function);
Error RewriteInstructions(void *old_function, size_t rewrite_size,
std::unique_ptr<CodeGenerator> &codegen);
Error CreateCompensationFunction(void *old_function, size_t rewrite_size,
void **callback_function);
Linker linker_;
std::unique_ptr<Target> target_;
std::unique_ptr<MemoryManager> executable_memory_;
std::unordered_map<void *, std::vector<uint8_t>> original_codes_;
};
} // end of namespace interceptor
extern "C" {
void *InitializeInterceptor() { return new InterceptorImpl(); }
void TerminateInterceptor(void *interceptor) {
delete static_cast<InterceptorImpl *>(interceptor);
}
void *FindFunctionByName(void *interceptor, const char *symbol_name) {
return static_cast<InterceptorImpl *>(interceptor)
->FindFunctionByName(symbol_name);
}
bool InterceptFunction(void *interceptor, void *old_function,
void *new_function, void **callback_function,
void (*error_callback)(void *, const char *),
void *error_callback_baton) {
Error error =
static_cast<InterceptorImpl *>(interceptor)
->InterceptFunction(old_function, new_function, callback_function);
if (error_callback && error.Fail()) {
std::ostringstream oss;
oss << "Intercepting function at " << old_function
<< " failed: " << error.GetMessage();
error_callback(error_callback_baton, oss.str().c_str());
}
return error.Success();
}
bool InterceptSymbol(void *interceptor, const char *symbol_name,
void *new_function, void **callback_function,
void (*error_callback)(void *, const char *),
void *error_callback_baton) {
Error error =
static_cast<InterceptorImpl *>(interceptor)
->InterceptFunction(symbol_name, new_function, callback_function);
if (error_callback && error.Fail()) {
std::ostringstream oss;
oss << "Intercepting '" << symbol_name
<< "' failed: " << error.GetMessage();
error_callback(error_callback_baton, oss.str().c_str());
}
return error.Success();
}
} // extern "C"
static void InitializeLLVM() {
static std::once_flag flag;
std::call_once(flag, []() {
llvm::InitializeAllTargetInfos();
llvm::InitializeAllTargetMCs();
llvm::InitializeAllDisassemblers();
});
}
static Error ChangePageProtection(void *ptr, size_t size, int prot) {
uintptr_t page_size = getpagesize();
uintptr_t page_mask = ~(page_size - 1);
uintptr_t ptr_val = reinterpret_cast<uintptr_t>(ptr);
uintptr_t base = ptr_val & page_mask;
uintptr_t end = (ptr_val + size + page_size - 1) & page_mask;
if (mprotect(reinterpret_cast<void *>(base), end - base, prot) != 0)
return Error("Failed to change protection for %p to %x", ptr, prot);
return Error();
}
InterceptorImpl::InterceptorImpl()
: executable_memory_(new MemoryManager(PROT_EXEC | PROT_READ,
MAP_PRIVATE | MAP_ANONYMOUS)) {
InitializeLLVM();
#if defined(__arm__)
target_.reset(new TargetARM());
#elif defined(__arm64__) || defined(__aarch64__)
target_.reset(new TargetAARCH64());
#elif defined(__i386__)
target_.reset(new TargetX86());
#else
assert(false && "Not supported architecture!");
#endif
}
InterceptorImpl::~InterceptorImpl() {
for (const auto &code : original_codes_)
WriteMemory(code.first, code.second.data(), code.second.size(), true);
}
Error InterceptorImpl::WriteMemory(void *target, const void *source, size_t num,
bool is_executable) {
int prot = PROT_READ;
if (is_executable) prot |= PROT_EXEC;
Error error = ChangePageProtection(target, num, prot | PROT_WRITE);
if (error.Fail()) return error;
memcpy(target, source, num);
error = ChangePageProtection(target, num, prot);
if (error.Fail()) return error;
return error;
}
static size_t GetCodeAligment(Target *target, void *function) {
uintptr_t load_address =
reinterpret_cast<uintptr_t>(target->GetLoadAddress(function));
return load_address % target->GetCodeAlignment();
}
Error InterceptorImpl::GetTrampolineSize(const TrampolineConfig &config,
void *old_function, void *new_function,
size_t &trampoline_size) {
size_t initial_alignment = GetCodeAligment(target_.get(), old_function);
std::unique_ptr<CodeGenerator> codegen(
target_->GetCodeGenerator(old_function, initial_alignment));
if (!codegen) return Error("Failed to create a code generator!");
Error error =
target_->EmitTrampoline(config, *codegen, old_function, new_function);
if (error.Fail()) return error;
trampoline_size = codegen->LayoutCode();
return Error();
}
Error InterceptorImpl::InstallTrampoline(const TrampolineConfig &config,
void *old_function,
void *new_function) {
size_t initial_alignment = GetCodeAligment(target_.get(), old_function);
std::unique_ptr<CodeGenerator> codegen(
target_->GetCodeGenerator(old_function, initial_alignment));
if (!codegen) return Error("Failed to create a code generator!");
Error error =
target_->EmitTrampoline(config, *codegen, old_function, new_function);
if (error.Fail()) return error;
codegen->LayoutCode();
void *load_address = target_->GetLoadAddress(old_function);
codegen->LinkCode(reinterpret_cast<uintptr_t>(load_address));
const llvm::SmallVectorImpl<char> &trampoline = codegen->GetCode();
std::vector<uint8_t> original_code(trampoline.size());
memcpy(original_code.data(), load_address, trampoline.size());
error = WriteMemory(load_address, trampoline.data(), trampoline.size(), true);
if (error.Fail()) return error;
original_codes_.emplace(load_address, std::move(original_code));
return Error();
}
Error InterceptorImpl::RewriteInstructions(
void *old_function, size_t rewrite_size,
std::unique_ptr<CodeGenerator> &codegen) {
codegen.reset(target_->GetCodeGenerator(old_function, 0));
if (!codegen) return Error("Failed to create codegen");
std::unique_ptr<Disassembler> disassembler(
target_->CreateDisassembler(old_function));
if (!disassembler) return Error("Failed to create disassembler");
size_t offset = 0;
void *func_addr = target_->GetLoadAddress(old_function);
bool reached_end_of_function = false;
while (offset < rewrite_size && !reached_end_of_function) {
llvm::MCInst inst;
uint64_t inst_size = 0;
if (!disassembler->GetInstruction(func_addr, offset, inst, inst_size))
return Error("Failed to disassemble instruction at %p + %zd", func_addr,
offset);
Error error = target_->RewriteInstruction(inst, *codegen, func_addr, offset,
reached_end_of_function);
if (error.Fail()) return error;
offset += inst_size;
}
if (offset < rewrite_size)
return Error(
"End of function reached after %zd byte when rewriting %zd bytes",
offset, rewrite_size);
uint8_t *target_addr = static_cast<uint8_t *>(old_function) + offset;
TrampolineConfig full_config = target_->GetFullTrampolineConfig();
Error error =
target_->EmitTrampoline(full_config, *codegen, nullptr, target_addr);
if (error.Fail()) return error;
return Error();
}
Error InterceptorImpl::CreateCompensationFunction(void *old_function,
size_t rewrite_size,
void **callback_function) {
std::unique_ptr<CodeGenerator> codegen;
Error error = RewriteInstructions(old_function, rewrite_size, codegen);
if (error.Fail()) return error;
size_t code_size = codegen->LayoutCode();
void *target =
executable_memory_->Allocate(code_size, target_->GetCodeAlignment());
if (!target) return Error("Failed to allocate executable memory");
error = codegen->LinkCode(reinterpret_cast<uintptr_t>(target));
if (error.Fail()) return error;
const llvm::SmallVectorImpl<char> &instructions = codegen->GetCode();
error = WriteMemory(target, instructions.data(), instructions.size(), true);
if (error.Fail()) return error;
*callback_function = target_->FixupCallbackFunction(old_function, target);
return Error();
}
Error InterceptorImpl::InterceptFunction(void *old_function, void *new_function,
void **callback_function) {
if (!callback_function) {
// TODO: Verify that the function is long enough for placing a trampoline
// inside it. If it isn't then currently we are overwriting the
// beginning of the next function as well causing potential SIGILL.
// We don't have to set up a callback function so installing a trampoline
// without generating compensation instructions is sufficient.
TrampolineConfig full_config = target_->GetFullTrampolineConfig();
return InstallTrampoline(full_config, old_function, new_function);
}
uintptr_t old_address = reinterpret_cast<uintptr_t>(old_function);
size_t aligned_full_trampoline_size = 0;
TrampolineConfig full_config = target_->GetFullTrampolineConfig();
Error error = GetTrampolineSize(full_config, nullptr, new_function,
aligned_full_trampoline_size);
if (error.Fail()) return error;
std::vector<TrampolineConfig> configs =
target_->GetTrampolineConfigs(old_address);
for (const auto &config : configs) {
if (config.IsFullTrampoline()) {
size_t trampoline_size = 0;
error = GetTrampolineSize(config, old_function, new_function,
trampoline_size);
if (error.Fail()) return error;
error = CreateCompensationFunction(old_function, trampoline_size,
callback_function);
if (error.Fail()) return error;
return InstallTrampoline(config, old_function, new_function);
} else {
void *intermediate_trampoline = executable_memory_->Allocate(
aligned_full_trampoline_size, target_->GetCodeAlignment(),
config.start_address, config.end_address);
if (!intermediate_trampoline) continue;
size_t trampoline_size = 0;
error = GetTrampolineSize(config, old_function, intermediate_trampoline,
trampoline_size);
if (error.Fail()) return error;
error = CreateCompensationFunction(old_function, trampoline_size,
callback_function);
if (error.Fail()) return error;
error =
InstallTrampoline(full_config, intermediate_trampoline, new_function);
if (error.Fail()) return error;
return InstallTrampoline(config, old_function, intermediate_trampoline);
}
}
return Error("Failed to find a suitable trampoline");
}
Error InterceptorImpl::InterceptFunction(const char *symbol_name,
void *new_function,
void **callback_function) {
linker_.RefreshSymbolList();
std::vector<Linker::Symbol> symbols = linker_.FindSymbols(symbol_name);
if (symbols.empty())
return Error("Failed to find symbol with name '%s'", symbol_name);
if (symbols.size() > 1)
return Error("More then 1 symbol found with name '%s'", symbol_name);
const Linker::Symbol &symbol = symbols.front();
return InterceptFunction(reinterpret_cast<void *>(symbol.address),
new_function, callback_function);
}
void *InterceptorImpl::FindFunctionByName(const char *symbol_name) {
if (!symbol_name) return nullptr;
linker_.RefreshSymbolList();
std::vector<Linker::Symbol> symbols = linker_.FindSymbols(symbol_name);
if (symbols.empty()) return nullptr;
if (symbols.size() > 1) return nullptr;
return reinterpret_cast<void *>(symbols.front().address);
}
+215
View File
@@ -0,0 +1,215 @@
/*
* Copyright (C) 2017 Google 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.
*/
#include "linker.h"
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "llvm/Object/Binary.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/Error.h"
// link.h #define EV_NONE on android what is used as an enum value inside llvm
// so it have to be included after the llvm libraries to avoid the compilation
// error.
#include <link.h>
#include "error.h"
using namespace interceptor;
static std::vector<std::string> GetLibrarySearchPaths() {
if (sizeof(void *) == 4) return {"/system/lib", "/vendor/lib"};
if (sizeof(void *) == 8) return {"/system/lib64", "/vendor/lib64"};
return {};
}
static uintptr_t read_address(const char *buffer) {
for (uintptr_t addr = 0; true; ++buffer) {
if (*buffer >= '0' && *buffer <= '9') {
addr *= 16;
addr += (*buffer) - '0';
} else if (*buffer >= 'a' && (*buffer) <= 'f') {
addr *= 16;
addr += (*buffer) - 'a' + 10;
} else {
return addr;
}
}
}
// Try to find the full path of the library mapped at a given address based on
// the /proc/self/maps file. This code path is used when the linker reports a
// library with file name only what is not located on the default search path
// or if the linker reports a library with bogus library name.
static std::string FindLibraryAtAddress(uintptr_t base_address) {
FILE *f = fopen("/proc/self/maps", "r");
if (f == nullptr) return "";
char buffer[512];
std::string path;
while (fgets(buffer, sizeof(buffer), f)) {
uintptr_t start_addr = read_address(buffer);
if (start_addr == base_address) {
const char *last_space = buffer - 1, *last_alpha = buffer;
for (const char *it = buffer; *it; ++it) {
if (*it == ' ')
last_space = it;
else if (std::isalnum(*it))
last_alpha = it;
}
path.assign(last_space + 1, last_alpha - last_space);
}
}
fclose(f);
return path;
}
static std::string FindLibrary(const char *name, uintptr_t base_address) {
// Absolue library path
if (name[0] == '/') {
if (llvm::sys::fs::exists(name)) return name;
return "";
}
// Relative library path
std::vector<std::string> search_paths = GetLibrarySearchPaths();
for (const std::string &dir : search_paths) {
std::string path = dir + '/' + name;
if (llvm::sys::fs::exists(path)) return path;
}
// Finding the library based on absolute and relative path is failed. Try to
// find it based on the base address in /proc/self/maps
std::string path = FindLibraryAtAddress(base_address);
if (llvm::sys::fs::exists(path)) return path;
return "";
}
Error Linker::ParseLibrary(const char *name, uintptr_t base_address) {
std::string library_path = FindLibrary(name, base_address);
if (library_path.empty())
return Error("Failed to find file for library: %s", name);
llvm::Expected<llvm::object::OwningBinary<llvm::object::Binary>>
binary_or_err = llvm::object::createBinary(library_path);
if (!binary_or_err) {
std::error_code ec = llvm::errorToErrorCode(binary_or_err.takeError());
return Error("Failed to create llvm::object::Binary for '%s' (%s)",
library_path.c_str(), ec.message().c_str());
}
llvm::object::Binary &binary = *binary_or_err.get().getBinary();
llvm::object::ObjectFile *obj_file =
llvm::dyn_cast<llvm::object::ObjectFile>(&binary);
if (!obj_file || !llvm::isa<llvm::object::ELFObjectFileBase>(obj_file))
return Error("Failer to convert '%s' to an object file",
library_path.c_str());
for (const auto &symbol : obj_file->symbols()) {
llvm::Expected<llvm::StringRef> symbol_name_or_err = symbol.getName();
if (!symbol_name_or_err || symbol_name_or_err->empty()) continue;
std::string symbol_name = symbol_name_or_err->str();
uint32_t flags = symbol.getFlags();
uintptr_t address = 0;
if (flags & llvm::object::SymbolRef::SF_Absolute) {
llvm::Expected<uint64_t> exp_address = symbol.getAddress();
if (!exp_address) continue;
address = exp_address.get();
} else {
llvm::Expected<llvm::object::section_iterator> section_or_err =
symbol.getSection();
if (!section_or_err) continue;
llvm::object::section_iterator section = section_or_err.get();
if (section == obj_file->section_end()) continue; // Undefined symbol
llvm::Expected<uint64_t> exp_address = symbol.getAddress();
if (!exp_address) continue;
address = base_address + exp_address.get();
}
if (flags & llvm::object::SymbolRef::SF_Thumb) address |= 1;
AddSymbol(symbol_name, address,
llvm::object::ELFSymbolRef(symbol).getSize(), flags);
}
return Error();
}
void Linker::AddSymbol(const std::string &name, uintptr_t address, size_t size,
uint32_t flags) {
Symbol symbol{name, address, size, flags};
addr_to_symbol_.emplace(address, symbol);
name_to_symbol_.emplace(name, symbol);
}
std::vector<Linker::Symbol> Linker::FindSymbols(const char *name) {
RefreshSymbolList();
std::vector<Symbol> symbols;
auto symbol_range = name_to_symbol_.equal_range(name);
for (auto it = symbol_range.first; it != symbol_range.second; ++it)
symbols.push_back(it->second);
return symbols;
}
static int CollectLibrary(struct dl_phdr_info *info, size_t size, void *data) {
std::map<uintptr_t, std::string> *libraries =
static_cast<std::map<uintptr_t, std::string> *>(data);
const char *file_name = info->dlpi_name;
if (file_name == nullptr) return 0;
uintptr_t base_address = info->dlpi_addr;
libraries->emplace(base_address, file_name);
return 0;
}
void Linker::RefreshSymbolList() {
std::map<uintptr_t, std::string> libraries;
dl_iterate_phdr(CollectLibrary, &libraries);
bool changed = false;
if (libraries.size() == loaded_libraries_.size()) {
for (const auto &it : loaded_libraries_) {
if (libraries.count(it.first) != 1 || libraries[it.first] != it.second) {
changed = true;
break;
}
}
} else {
changed = true;
}
if (changed) {
addr_to_symbol_.clear();
name_to_symbol_.clear();
loaded_libraries_.swap(libraries);
for (const auto &it : loaded_libraries_)
ParseLibrary(it.second.c_str(), it.first);
}
}
+55
View File
@@ -0,0 +1,55 @@
/*
* Copyright (C) 2017 Google 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 INTERCEPTOR_LINKER_H_
#define INTERCEPTOR_LINKER_H_
#include <cstddef>
#include <map>
#include <string>
#include <vector>
#include "error.h"
namespace interceptor {
class Linker {
public:
struct Symbol {
std::string name;
uintptr_t address;
size_t size;
uint32_t flags;
};
void RefreshSymbolList();
std::vector<Symbol> FindSymbols(const char *name);
private:
Error ParseLibrary(const char *name, uintptr_t base_address);
void AddSymbol(const std::string &name, uintptr_t address, size_t size,
uint32_t flags);
std::map<uintptr_t, std::string> loaded_libraries_;
std::multimap<uintptr_t, Symbol> addr_to_symbol_;
std::multimap<std::string, Symbol> name_to_symbol_;
};
} // end of namespace interceptor
#endif // INTERCEPTOR_LINKER_H_
@@ -0,0 +1,79 @@
/*
* Copyright (C) 2017 Google 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.
*/
#include "memory_manager.h"
#include <sys/mman.h>
#include <unistd.h>
#include <cassert>
#ifndef PAGE_SIZE
#define PAGE_SIZE 0x1000
#endif
using namespace interceptor;
MemoryManager::MemoryManager(int prot, int flags)
: prot_(prot), flags_(flags) {}
MemoryManager::~MemoryManager() {
for (const auto &alloc : allocations_)
munmap(reinterpret_cast<void *>(alloc.start()), alloc.size());
}
void *MemoryManager::Allocate(size_t size, size_t alignment,
uintptr_t range_start, uintptr_t range_end) {
assert(size > 0 && "Can't allocate 0 or negative amount of memory.");
assert(size <= PAGE_SIZE && "Can't allocate more then PAGE_SIZE memory");
assert(PAGE_SIZE % alignment == 0 &&
"Can met alignment requiremenet not "
"satisfied by a page boundary");
for (Allocation &alloc : allocations_) {
if (void *addr = alloc.Alloc(size, alignment, range_start, range_end))
return addr;
if (range_start >= alloc.start() && range_start <= alloc.end())
range_start = alloc.end();
}
void *target = mmap(reinterpret_cast<void *>(range_start), PAGE_SIZE, prot_,
flags_, 0, 0);
if (!target) return nullptr;
allocations_.emplace_back(target, PAGE_SIZE);
return allocations_.back().Alloc(size, alignment, range_start, range_end);
}
void *MemoryManager::Allocation::Alloc(size_t size, size_t alignment,
uintptr_t range_start,
uintptr_t range_end) {
size_t new_offset = CalculateNewOffset(size, alignment);
if (new_offset + size > size_) return nullptr; // Doesn't fit
uintptr_t address = reinterpret_cast<uintptr_t>(start_ + new_offset);
if (address < range_start || address > range_end)
return nullptr; // Out of range
offset_ = new_offset + size;
return start_ + new_offset;
}
size_t MemoryManager::Allocation::CalculateNewOffset(size_t size,
size_t alignment) const {
size_t new_offset = offset_;
if (new_offset % alignment != 0)
new_offset += alignment - (new_offset % alignment);
return new_offset;
}
+65
View File
@@ -0,0 +1,65 @@
/*
* Copyright (C) 2017 Google 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 INTERCEPTOR_MEMORY_MANAGER_H_
#define INTERCEPTOR_MEMORY_MANAGER_H_
#include <cstddef>
#include <cstdint>
#include <limits>
#include <vector>
namespace interceptor {
class MemoryManager {
public:
MemoryManager(int prot, int flags);
~MemoryManager();
void *Allocate(size_t size, size_t alignment,
uintptr_t range_start = std::numeric_limits<uintptr_t>::min(),
uintptr_t range_end = std::numeric_limits<uintptr_t>::max());
private:
class Allocation {
public:
Allocation(void *start, size_t size)
: start_(static_cast<uint8_t *>(start)), size_(size), offset_(0) {}
uintptr_t start() const { return reinterpret_cast<uintptr_t>(start_); }
uintptr_t end() const { return start() + size_; }
size_t size() const { return size_; }
void *Alloc(size_t size, size_t alignment, uintptr_t range_start,
uintptr_t range_end);
private:
uint8_t *const start_;
const size_t size_;
size_t offset_;
size_t CalculateNewOffset(size_t size, size_t alignment) const;
};
const int prot_;
const int flags_;
std::vector<Allocation> allocations_;
};
} // end of namespace interceptor
#endif // INTERCEPTOR_MEMORY_MANAGER_H_
+25
View File
@@ -0,0 +1,25 @@
/*
* Copyright (C) 2017 Google 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.
*/
#include "target.h"
using namespace interceptor;
TrampolineConfig Target::GetFullTrampolineConfig() const {
TrampolineConfig config = GetTrampolineConfigs(0).back();
assert(config.IsFullTrampoline());
return config;
}
+107
View File
@@ -0,0 +1,107 @@
/*
* Copyright (C) 2017 Google 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 INTERCEPTOR_TARGET_H_
#define INTERCEPTOR_TARGET_H_
#include <cstdint>
#include <memory>
#include <vector>
#include "llvm/MC/MCInst.h"
#include "code_generator.h"
#include "disassembler.h"
#include "error.h"
namespace interceptor {
struct TrampolineConfig {
uint32_t type; // Architecture specific value
bool require_source; // Using relative or absolute jump
uintptr_t start_address; // First address it can jump to
uintptr_t end_address; // Last address it can jump to
// Returns true if the trampoline can jump from any address in the address
// space to any other address and false otherwise.
bool IsFullTrampoline() const {
return !require_source &&
start_address == std::numeric_limits<uintptr_t>::min() &&
end_address == std::numeric_limits<uintptr_t>::max();
}
};
class Target {
public:
virtual ~Target() = default;
// Create a new code generator with the specified start alignment what can
// generate code with the same ISA pointed by the address (e.g. thumb vs arm).
virtual CodeGenerator *GetCodeGenerator(void *address,
size_t start_alignment) = 0;
// Create a disassebler what can disassamble code coming from the specified
// address.
virtual Disassembler *CreateDisassembler(void *address) = 0;
// Get the maximum alignment required by the target by any instruction in any
// of the supported ISA.
virtual size_t GetCodeAlignment() const = 0;
// Return a load address from a function pointer. Have to be implemented for
// architectures where some bits of the function pointers contain meta-data
// (e.g. thumb bit)
virtual void *GetLoadAddress(void *addr) { return addr; }
// Returns the full list of avaiulable trampolines on the given architecture
// sorted to increasing order by the total size of instructions (including
// data) inside the trampoline.
virtual std::vector<TrampolineConfig> GetTrampolineConfigs(
uintptr_t start_address) const = 0;
// Return the configuartion of the full trampoline what have to be able to
// jump to any address inside the process's address space.
TrampolineConfig GetFullTrampolineConfig() const;
// Emit a trampoline with the given config into the code generator what will
// jump to the specified target address if it is placed into the location
// specified by the source address.
virtual Error EmitTrampoline(const TrampolineConfig &config,
CodeGenerator &codegen, void *source,
void *target) = 0;
// Rewrite the specified instruction read from "data + offset "into the code
// generator with a set of instructions with the exact same effect but without
// any limitation about the location they have to be placed at. Additionally
// it sets the "possible_end_of_function" flag to true if the instruction can
// be the last one inside a function and to false otherwise.
virtual Error RewriteInstruction(const llvm::MCInst &inst,
CodeGenerator &codegen, void *data,
size_t offset,
bool &possible_end_of_function) = 0;
// Convert the pointer specified by "new_function" from a memory load address
// to a function pointer with the same ISA as the function pointed by
// "old_function". Have to be implemented for architectures where some bits of
// the function pointers contain meta-data (e.g. thumb bit).
virtual void *FixupCallbackFunction(void *old_function, void *new_function) {
return new_function;
}
};
} // end of namespace interceptor
#endif // INTERCEPTOR_TARGET_H_
+39
View File
@@ -107,6 +107,15 @@
<ItemGroup>
<ClInclude Include="3rdparty\android\android_manifest.h" />
<ClInclude Include="3rdparty\catch\catch.hpp" />
<ClInclude Include="3rdparty\interceptor-lib\lib\AArch64\target_aarch64.h" />
<ClInclude Include="3rdparty\interceptor-lib\lib\ARM\target_arm.h" />
<ClInclude Include="3rdparty\interceptor-lib\lib\code_generator.h" />
<ClInclude Include="3rdparty\interceptor-lib\lib\constant_pool_data_expr.h" />
<ClInclude Include="3rdparty\interceptor-lib\lib\disassembler.h" />
<ClInclude Include="3rdparty\interceptor-lib\lib\error.h" />
<ClInclude Include="3rdparty\interceptor-lib\lib\linker.h" />
<ClInclude Include="3rdparty\interceptor-lib\lib\memory_manager.h" />
<ClInclude Include="3rdparty\interceptor-lib\lib\target.h" />
<ClInclude Include="3rdparty\jpeg-compressor\jpgd.h" />
<ClInclude Include="3rdparty\jpeg-compressor\jpge.h" />
<ClInclude Include="3rdparty\lz4\lz4.h" />
@@ -205,6 +214,36 @@
</ItemGroup>
<ItemGroup>
<ClCompile Include="3rdparty\catch\catch.cpp" />
<ClCompile Include="3rdparty\interceptor-lib\lib\AArch64\target_aarch64.cc">
<ExcludedFromBuild>true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="3rdparty\interceptor-lib\lib\ARM\target_arm.cc">
<ExcludedFromBuild>true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="3rdparty\interceptor-lib\lib\code_generator.cc">
<ExcludedFromBuild>true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="3rdparty\interceptor-lib\lib\constant_pool_data_expr.cc">
<ExcludedFromBuild>true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="3rdparty\interceptor-lib\lib\disassembler.cc">
<ExcludedFromBuild>true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="3rdparty\interceptor-lib\lib\error.cc">
<ExcludedFromBuild>true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="3rdparty\interceptor-lib\lib\interceptor.cc">
<ExcludedFromBuild>true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="3rdparty\interceptor-lib\lib\linker.cc">
<ExcludedFromBuild>true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="3rdparty\interceptor-lib\lib\memory_manager.cc">
<ExcludedFromBuild>true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="3rdparty\interceptor-lib\lib\target.cc">
<ExcludedFromBuild>true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="3rdparty\jpeg-compressor\jpgd.cpp">
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<ForcedIncludeFiles>
+66
View File
@@ -115,6 +115,15 @@
<Filter Include="3rdparty\android">
<UniqueIdentifier>{6e798cbc-0eae-4f48-9d7c-f3fe58bd32dc}</UniqueIdentifier>
</Filter>
<Filter Include="3rdparty\interceptor-lib">
<UniqueIdentifier>{0362a726-a8e6-436e-b523-893693163440}</UniqueIdentifier>
</Filter>
<Filter Include="3rdparty\interceptor-lib\ARM">
<UniqueIdentifier>{cb120bec-b864-4240-9b04-369ce8d60316}</UniqueIdentifier>
</Filter>
<Filter Include="3rdparty\interceptor-lib\AArch64">
<UniqueIdentifier>{7894d954-a38a-450f-9780-a38f73df1208}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="maths\camera.h">
@@ -390,6 +399,33 @@
<ClInclude Include="3rdparty\android\android_manifest.h">
<Filter>3rdparty\android</Filter>
</ClInclude>
<ClInclude Include="3rdparty\interceptor-lib\lib\code_generator.h">
<Filter>3rdparty\interceptor-lib</Filter>
</ClInclude>
<ClInclude Include="3rdparty\interceptor-lib\lib\constant_pool_data_expr.h">
<Filter>3rdparty\interceptor-lib</Filter>
</ClInclude>
<ClInclude Include="3rdparty\interceptor-lib\lib\disassembler.h">
<Filter>3rdparty\interceptor-lib</Filter>
</ClInclude>
<ClInclude Include="3rdparty\interceptor-lib\lib\error.h">
<Filter>3rdparty\interceptor-lib</Filter>
</ClInclude>
<ClInclude Include="3rdparty\interceptor-lib\lib\linker.h">
<Filter>3rdparty\interceptor-lib</Filter>
</ClInclude>
<ClInclude Include="3rdparty\interceptor-lib\lib\memory_manager.h">
<Filter>3rdparty\interceptor-lib</Filter>
</ClInclude>
<ClInclude Include="3rdparty\interceptor-lib\lib\target.h">
<Filter>3rdparty\interceptor-lib</Filter>
</ClInclude>
<ClInclude Include="3rdparty\interceptor-lib\lib\ARM\target_arm.h">
<Filter>3rdparty\interceptor-lib\ARM</Filter>
</ClInclude>
<ClInclude Include="3rdparty\interceptor-lib\lib\AArch64\target_aarch64.h">
<Filter>3rdparty\interceptor-lib\AArch64</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="maths\camera.cpp">
@@ -686,6 +722,36 @@
<ClCompile Include="android\android_manifest.cpp">
<Filter>Android</Filter>
</ClCompile>
<ClCompile Include="3rdparty\interceptor-lib\lib\code_generator.cc">
<Filter>3rdparty\interceptor-lib</Filter>
</ClCompile>
<ClCompile Include="3rdparty\interceptor-lib\lib\constant_pool_data_expr.cc">
<Filter>3rdparty\interceptor-lib</Filter>
</ClCompile>
<ClCompile Include="3rdparty\interceptor-lib\lib\disassembler.cc">
<Filter>3rdparty\interceptor-lib</Filter>
</ClCompile>
<ClCompile Include="3rdparty\interceptor-lib\lib\error.cc">
<Filter>3rdparty\interceptor-lib</Filter>
</ClCompile>
<ClCompile Include="3rdparty\interceptor-lib\lib\interceptor.cc">
<Filter>3rdparty\interceptor-lib</Filter>
</ClCompile>
<ClCompile Include="3rdparty\interceptor-lib\lib\linker.cc">
<Filter>3rdparty\interceptor-lib</Filter>
</ClCompile>
<ClCompile Include="3rdparty\interceptor-lib\lib\memory_manager.cc">
<Filter>3rdparty\interceptor-lib</Filter>
</ClCompile>
<ClCompile Include="3rdparty\interceptor-lib\lib\target.cc">
<Filter>3rdparty\interceptor-lib</Filter>
</ClCompile>
<ClCompile Include="3rdparty\interceptor-lib\lib\ARM\target_arm.cc">
<Filter>3rdparty\interceptor-lib\ARM</Filter>
</ClCompile>
<ClCompile Include="3rdparty\interceptor-lib\lib\AArch64\target_aarch64.cc">
<Filter>3rdparty\interceptor-lib\AArch64</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<None Include="os\win32\comexport.def">
+2
View File
@@ -37,5 +37,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
{\field{\*\fldinst{HYPERLINK "{\pntext\f1\'B7\tab}https://github.com/philsquared/Catch"}}{\fldrslt{\ul\cf1 https://github.com/philsquared/Catch}}}\f0\fs22\line Catch distributed under the Boost Software License. Copyright (c) 2012 Two Blue Cubes Ltd.\par
{\field{\*\fldinst{HYPERLINK "{\pntext\f1\'B7\tab}https://pugixml.org"}}{\fldrslt{\ul\cf1 https://pugixml.org}}}\f0\fs22\line pugixml distributed under the MIT License. Copyright (c) 2006-2017 Arseny Kapoulkine.\par
{\field{\*\fldinst{HYPERLINK "{\pntext\f1\'B7\tab}https://source.android.com"}}{\fldrslt{\ul\cf1 https://source.android.com}}}\f0\fs22\line components of AOSP distributed under the Apache 2.0 License. Copyright (c) 2006-2016 The Android Open Source Project.\par
{\field{\*\fldinst{HYPERLINK "{\pntext\f1\'B7\tab}https://github.com/google/gapid"}}{\fldrslt{\ul\cf1 https://github.com/google/gapid}}}\f0\fs22\line interceptor-lib distributed under the Apache 2.0 License. Copyright (c) 2017, Google Inc.\par
{\field{\*\fldinst{HYPERLINK "{\pntext\f1\'B7\tab}http://llvm.org"}}{\fldrslt{\ul\cf1 https://source.android.com}}}\f0\fs22\line LLVM distributed under the University of Illinois/NCSA Open Source License. Copyright (c) 2003-2017 University of Illinois at Urbana-Champaign.\par
}