Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/DirectXShaderCompiler/test/tools/llvm-symbolizer
repos/DirectXShaderCompiler/test/tools/llvm-symbolizer/pdb/pdb.test
RUN: llvm-symbolizer -obj="%p/Inputs/test.exe" < "%p/Inputs/test.exe.input" | \ RUN: FileCheck %s --check-prefix=CHECK RUN: llvm-symbolizer -obj="%p/Inputs/test.exe" -demangle=false < \ RUN: "%p/Inputs/test.exe.input" | FileCheck %s --check-prefix=CHECK-NO-DEMANGLE CHECK: foo(void) CHECK-NEXT: test.cpp:10 CHECK: _main CHECK-NEXT: test.cpp:13:0 CHECK: NS::Foo::bar(void) CHECK-NEXT: test.cpp:6:0 CHECK-NO-DEMANGLE: foo CHECK-NO-DEMANGLE-NEXT: test.cpp:10 CHECK-NO-DEMANGLE: _main CHECK-LINKAGE-NAME-NEXT: test.cpp:13:0 CHECK-NO-DEMANGLE: bar CHECK-LINKAGE-NAME-NEXT: test.cpp:6:0
0
repos/DirectXShaderCompiler/test/tools/llvm-symbolizer/pdb
repos/DirectXShaderCompiler/test/tools/llvm-symbolizer/pdb/Inputs/test.cpp
// To generate the corresponding EXE/PDB, run: // cl /Zi test.cpp namespace NS { struct Foo { void bar() {} }; } void foo() { } int main() { foo(); NS::Foo f; f.bar(); }
0
repos/DirectXShaderCompiler
repos/DirectXShaderCompiler/gcp-pipelines/x86_64-windows-msvc.yml
steps: - name: 'gcr.io/shaderc-build/shader-compiler-team:dxc-win-builder' env: - BUILD_ID=$BUILD_ID - SOURCE_IMAGE=dxc-builder-windows-vs22 - COMMIT_SHA=$COMMIT_SHA logsBucket: 'gs://public-github-building-logs' options: logging: LEGACY pool: name: projects/shaderc-build/locations/us-central1/workerPools/dxc artifacts: objects: location: 'gs://public-directx-shader-compiler/$COMMIT_SHA' paths: - dxc-artifacts.zip
0
repos/DirectXShaderCompiler
repos/DirectXShaderCompiler/gcp-pipelines/x86_64-linux-clang.yml
steps: - name: gcr.io/cloud-builders/git args: ['fetch', '--unshallow'] - name: 'gcr.io/shaderc-build/shader-compiler-team:kokoro-dxc-builder' args: - git - submodule - update - '--init' - name: 'gcr.io/shaderc-build/shader-compiler-team:kokoro-dxc-builder' args: - cmake - '-Bbuild' - '-GNinja' - '-DCMAKE_BUILD_TYPE=Release' - '-DCMAKE_CXX_COMPILER=clang++' - '-DCMAKE_C_COMPILER=clang' - '-DCMAKE_INSTALL_PREFIX=artifacts' - '-DENABLE_SPIRV_CODEGEN=ON' - '-DSPIRV_BUILD_TESTS=ON' - '-DLLVM_ENABLE_WERROR=On' - '-C' - 'cmake/caches/PredefinedParams.cmake' - name: 'gcr.io/shaderc-build/shader-compiler-team:kokoro-dxc-builder' args: - ninja - '-C' - build - name: 'gcr.io/shaderc-build/shader-compiler-team:kokoro-dxc-builder' args: - ninja - '-C' - build - check-all - name: 'gcr.io/shaderc-build/shader-compiler-team:kokoro-dxc-builder' args: - ninja - '-C' - build - install-distribution - name: 'gcr.io/shaderc-build/shader-compiler-team:kokoro-dxc-builder' script: | #!/usr/bin/env bash zip -r dxc-artifacts.zip /workspace/artifacts/* logsBucket: 'gs://public-github-building-logs' options: logging: LEGACY pool: name: projects/shaderc-build/locations/us-central1/workerPools/dxc artifacts: objects: location: 'gs://public-directx-shader-compiler/$COMMIT_SHA' paths: - dxc-artifacts.zip
0
repos/DirectXShaderCompiler
repos/DirectXShaderCompiler/cmake/config-ix.cmake
if( WIN32 AND NOT CYGWIN ) # We consider Cygwin as another Unix set(PURE_WINDOWS 1) endif() include(CheckIncludeFile) include(CheckIncludeFileCXX) include(CheckLibraryExists) include(CheckSymbolExists) include(CheckFunctionExists) include(CheckCXXSourceCompiles) include(TestBigEndian) include(HandleLLVMStdlib) if( UNIX AND NOT BEOS ) # Used by check_symbol_exists: set(CMAKE_REQUIRED_LIBRARIES m) endif() # x86_64 FreeBSD 9.2 requires libcxxrt to be specified explicitly. if( CMAKE_SYSTEM MATCHES "FreeBSD-9.2-RELEASE" AND CMAKE_SIZEOF_VOID_P EQUAL 8 ) list(APPEND CMAKE_REQUIRED_LIBRARIES "cxxrt") endif() # Helper macros and functions macro(add_cxx_include result files) set(${result} "") foreach (file_name ${files}) set(${result} "${${result}}#include<${file_name}>\n") endforeach() endmacro(add_cxx_include files result) function(check_type_exists type files variable) add_cxx_include(includes "${files}") CHECK_CXX_SOURCE_COMPILES(" ${includes} ${type} typeVar; int main() { return 0; } " ${variable}) endfunction() # include checks check_include_file(dirent.h HAVE_DIRENT_H) check_include_file(dlfcn.h HAVE_DLFCN_H) check_include_file(errno.h HAVE_ERRNO_H) check_include_file(execinfo.h HAVE_EXECINFO_H) check_include_file(fcntl.h HAVE_FCNTL_H) check_include_file(inttypes.h HAVE_INTTYPES_H) check_include_file(limits.h HAVE_LIMITS_H) check_include_file(link.h HAVE_LINK_H) check_include_file(malloc.h HAVE_MALLOC_H) check_include_file(malloc/malloc.h HAVE_MALLOC_MALLOC_H) check_include_file(ndir.h HAVE_NDIR_H) if( NOT PURE_WINDOWS ) check_include_file(pthread.h HAVE_PTHREAD_H) endif() check_include_file(signal.h HAVE_SIGNAL_H) check_include_file(stdint.h HAVE_STDINT_H) check_include_file(sys/dir.h HAVE_SYS_DIR_H) check_include_file(sys/ioctl.h HAVE_SYS_IOCTL_H) check_include_file(sys/mman.h HAVE_SYS_MMAN_H) check_include_file(sys/ndir.h HAVE_SYS_NDIR_H) check_include_file(sys/param.h HAVE_SYS_PARAM_H) check_include_file(sys/resource.h HAVE_SYS_RESOURCE_H) check_include_file(sys/stat.h HAVE_SYS_STAT_H) check_include_file(sys/time.h HAVE_SYS_TIME_H) check_include_file(sys/uio.h HAVE_SYS_UIO_H) check_include_file(sys/wait.h HAVE_SYS_WAIT_H) check_include_file(termios.h HAVE_TERMIOS_H) check_include_file(unistd.h HAVE_UNISTD_H) check_include_file(utime.h HAVE_UTIME_H) check_include_file(valgrind/valgrind.h HAVE_VALGRIND_VALGRIND_H) check_include_file(zlib.h HAVE_ZLIB_H) check_include_file(fenv.h HAVE_FENV_H) check_symbol_exists(FE_ALL_EXCEPT "fenv.h" HAVE_DECL_FE_ALL_EXCEPT) check_symbol_exists(FE_INEXACT "fenv.h" HAVE_DECL_FE_INEXACT) check_include_file(mach/mach.h HAVE_MACH_MACH_H) check_include_file(mach-o/dyld.h HAVE_MACH_O_DYLD_H) check_include_file(histedit.h HAVE_HISTEDIT_H) # size_t must be defined before including cxxabi.h on FreeBSD 10.0. check_cxx_source_compiles(" #include <stddef.h> #include <cxxabi.h> int main() { return 0; } " HAVE_CXXABI_H) # library checks if( NOT PURE_WINDOWS ) check_library_exists(pthread pthread_create "" HAVE_LIBPTHREAD) if (HAVE_LIBPTHREAD) check_library_exists(pthread pthread_getspecific "" HAVE_PTHREAD_GETSPECIFIC) check_library_exists(pthread pthread_rwlock_init "" HAVE_PTHREAD_RWLOCK_INIT) check_library_exists(pthread pthread_mutex_lock "" HAVE_PTHREAD_MUTEX_LOCK) else() # this could be Android check_library_exists(c pthread_create "" PTHREAD_IN_LIBC) if (PTHREAD_IN_LIBC) check_library_exists(c pthread_getspecific "" HAVE_PTHREAD_GETSPECIFIC) check_library_exists(c pthread_rwlock_init "" HAVE_PTHREAD_RWLOCK_INIT) check_library_exists(c pthread_mutex_lock "" HAVE_PTHREAD_MUTEX_LOCK) endif() endif() check_library_exists(dl dlopen "" HAVE_LIBDL) check_library_exists(rt clock_gettime "" HAVE_LIBRT) if (LLVM_ENABLE_ZLIB) check_library_exists(z compress2 "" HAVE_LIBZ) else() set(HAVE_LIBZ 0) endif() if (HAVE_HISTEDIT_H) check_library_exists(edit el_init "" HAVE_LIBEDIT) endif() if(LLVM_ENABLE_TERMINFO) set(HAVE_TERMINFO 0) foreach(library tinfo terminfo curses ncurses ncursesw) string(TOUPPER ${library} library_suffix) check_library_exists(${library} setupterm "" HAVE_TERMINFO_${library_suffix}) if(HAVE_TERMINFO_${library_suffix}) set(HAVE_TERMINFO 1) set(TERMINFO_LIBS "${library}") break() endif() endforeach() else() set(HAVE_TERMINFO 0) endif() endif() # function checks check_symbol_exists(arc4random "stdlib.h" HAVE_DECL_ARC4RANDOM) check_symbol_exists(backtrace "execinfo.h" HAVE_BACKTRACE) check_symbol_exists(getpagesize unistd.h HAVE_GETPAGESIZE) check_symbol_exists(getrusage sys/resource.h HAVE_GETRUSAGE) check_symbol_exists(setrlimit sys/resource.h HAVE_SETRLIMIT) check_symbol_exists(isatty unistd.h HAVE_ISATTY) check_symbol_exists(futimens sys/stat.h HAVE_FUTIMENS) check_symbol_exists(futimes sys/time.h HAVE_FUTIMES) if( HAVE_SETJMP_H ) check_symbol_exists(longjmp setjmp.h HAVE_LONGJMP) check_symbol_exists(setjmp setjmp.h HAVE_SETJMP) check_symbol_exists(siglongjmp setjmp.h HAVE_SIGLONGJMP) check_symbol_exists(sigsetjmp setjmp.h HAVE_SIGSETJMP) endif() if( HAVE_SYS_UIO_H ) check_symbol_exists(writev sys/uio.h HAVE_WRITEV) endif() check_symbol_exists(mallctl malloc_np.h HAVE_MALLCTL) check_symbol_exists(mallinfo malloc.h HAVE_MALLINFO) check_symbol_exists(mallinfo2 malloc.h HAVE_MALLINFO2) check_symbol_exists(malloc_zone_statistics malloc/malloc.h HAVE_MALLOC_ZONE_STATISTICS) check_symbol_exists(mkdtemp "stdlib.h;unistd.h" HAVE_MKDTEMP) check_symbol_exists(mkstemp "stdlib.h;unistd.h" HAVE_MKSTEMP) check_symbol_exists(mktemp "stdlib.h;unistd.h" HAVE_MKTEMP) check_symbol_exists(closedir "sys/types.h;dirent.h" HAVE_CLOSEDIR) check_symbol_exists(opendir "sys/types.h;dirent.h" HAVE_OPENDIR) check_symbol_exists(readdir "sys/types.h;dirent.h" HAVE_READDIR) check_symbol_exists(getcwd unistd.h HAVE_GETCWD) check_symbol_exists(gettimeofday sys/time.h HAVE_GETTIMEOFDAY) check_symbol_exists(getrlimit "sys/types.h;sys/time.h;sys/resource.h" HAVE_GETRLIMIT) check_symbol_exists(posix_spawn spawn.h HAVE_POSIX_SPAWN) check_symbol_exists(pread unistd.h HAVE_PREAD) check_symbol_exists(realpath stdlib.h HAVE_REALPATH) check_symbol_exists(sbrk unistd.h HAVE_SBRK) check_symbol_exists(srand48 stdlib.h HAVE_RAND48_SRAND48) if( HAVE_RAND48_SRAND48 ) check_symbol_exists(lrand48 stdlib.h HAVE_RAND48_LRAND48) if( HAVE_RAND48_LRAND48 ) check_symbol_exists(drand48 stdlib.h HAVE_RAND48_DRAND48) if( HAVE_RAND48_DRAND48 ) set(HAVE_RAND48 1 CACHE INTERNAL "are srand48/lrand48/drand48 available?") endif() endif() endif() check_symbol_exists(strtoll stdlib.h HAVE_STRTOLL) check_symbol_exists(strtoq stdlib.h HAVE_STRTOQ) check_symbol_exists(strerror string.h HAVE_STRERROR) check_symbol_exists(strerror_r string.h HAVE_STRERROR_R) check_symbol_exists(strerror_s string.h HAVE_DECL_STRERROR_S) check_symbol_exists(setenv stdlib.h HAVE_SETENV) if( PURE_WINDOWS ) check_symbol_exists(_chsize_s io.h HAVE__CHSIZE_S) check_function_exists(_alloca HAVE__ALLOCA) check_function_exists(__alloca HAVE___ALLOCA) check_function_exists(__chkstk HAVE___CHKSTK) check_function_exists(__chkstk_ms HAVE___CHKSTK_MS) check_function_exists(___chkstk HAVE____CHKSTK) check_function_exists(___chkstk_ms HAVE____CHKSTK_MS) check_function_exists(__ashldi3 HAVE___ASHLDI3) check_function_exists(__ashrdi3 HAVE___ASHRDI3) check_function_exists(__divdi3 HAVE___DIVDI3) check_function_exists(__fixdfdi HAVE___FIXDFDI) check_function_exists(__fixsfdi HAVE___FIXSFDI) check_function_exists(__floatdidf HAVE___FLOATDIDF) check_function_exists(__lshrdi3 HAVE___LSHRDI3) check_function_exists(__moddi3 HAVE___MODDI3) check_function_exists(__udivdi3 HAVE___UDIVDI3) check_function_exists(__umoddi3 HAVE___UMODDI3) check_function_exists(__main HAVE___MAIN) check_function_exists(__cmpdi2 HAVE___CMPDI2) endif() if( HAVE_DLFCN_H ) if( HAVE_LIBDL ) list(APPEND CMAKE_REQUIRED_LIBRARIES dl) endif() check_symbol_exists(dlerror dlfcn.h HAVE_DLERROR) check_symbol_exists(dlopen dlfcn.h HAVE_DLOPEN) if( HAVE_LIBDL ) list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES dl) endif() endif() check_symbol_exists(__GLIBC__ stdio.h LLVM_USING_GLIBC) if( LLVM_USING_GLIBC ) add_llvm_definitions( -D_GNU_SOURCE ) endif() set(headers "sys/types.h") if (HAVE_INTTYPES_H) set(headers ${headers} "inttypes.h") endif() if (HAVE_STDINT_H) set(headers ${headers} "stdint.h") endif() check_type_exists(int64_t "${headers}" HAVE_INT64_T) check_type_exists(uint64_t "${headers}" HAVE_UINT64_T) check_type_exists(u_int64_t "${headers}" HAVE_U_INT64_T) # available programs checks function(llvm_find_program name) string(TOUPPER ${name} NAME) string(REGEX REPLACE "\\." "_" NAME ${NAME}) find_program(LLVM_PATH_${NAME} NAMES ${ARGV}) mark_as_advanced(LLVM_PATH_${NAME}) if(LLVM_PATH_${NAME}) set(HAVE_${NAME} 1 CACHE INTERNAL "Is ${name} available ?") mark_as_advanced(HAVE_${NAME}) else(LLVM_PATH_${NAME}) set(HAVE_${NAME} "" CACHE INTERNAL "Is ${name} available ?") endif(LLVM_PATH_${NAME}) endfunction() if (LLVM_ENABLE_DOXYGEN) llvm_find_program(dot) endif () if( LLVM_ENABLE_FFI ) find_path(FFI_INCLUDE_PATH ffi.h PATHS ${FFI_INCLUDE_DIR}) if( EXISTS "${FFI_INCLUDE_PATH}/ffi.h" ) set(FFI_HEADER ffi.h CACHE INTERNAL "") set(HAVE_FFI_H 1 CACHE INTERNAL "") else() find_path(FFI_INCLUDE_PATH ffi/ffi.h PATHS ${FFI_INCLUDE_DIR}) if( EXISTS "${FFI_INCLUDE_PATH}/ffi/ffi.h" ) set(FFI_HEADER ffi/ffi.h CACHE INTERNAL "") set(HAVE_FFI_FFI_H 1 CACHE INTERNAL "") endif() endif() if( NOT FFI_HEADER ) message(FATAL_ERROR "libffi includes are not found.") endif() find_library(FFI_LIBRARY_PATH ffi PATHS ${FFI_LIBRARY_DIR}) if( NOT FFI_LIBRARY_PATH ) message(FATAL_ERROR "libffi is not found.") endif() list(APPEND CMAKE_REQUIRED_LIBRARIES ${FFI_LIBRARY_PATH}) list(APPEND CMAKE_REQUIRED_INCLUDES ${FFI_INCLUDE_PATH}) check_symbol_exists(ffi_call ${FFI_HEADER} HAVE_FFI_CALL) list(REMOVE_ITEM CMAKE_REQUIRED_INCLUDES ${FFI_INCLUDE_PATH}) list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES ${FFI_LIBRARY_PATH}) else() unset(HAVE_FFI_FFI_H CACHE) unset(HAVE_FFI_H CACHE) unset(HAVE_FFI_CALL CACHE) endif( LLVM_ENABLE_FFI ) # Define LLVM_HAS_ATOMICS if gcc or MSVC atomic builtins are supported. include(CheckAtomic) if( LLVM_ENABLE_PIC ) set(ENABLE_PIC 1) else() set(ENABLE_PIC 0) endif() check_cxx_compiler_flag("-Wno-variadic-macros" SUPPORTS_NO_VARIADIC_MACROS_FLAG) set(USE_NO_MAYBE_UNINITIALIZED 0) set(USE_NO_UNINITIALIZED 0) # Disable gcc's potentially uninitialized use analysis as it presents lots of # false positives. if (CMAKE_COMPILER_IS_GNUCXX) check_cxx_compiler_flag("-Wmaybe-uninitialized" HAS_MAYBE_UNINITIALIZED) if (HAS_MAYBE_UNINITIALIZED) set(USE_NO_MAYBE_UNINITIALIZED 1) else() # Only recent versions of gcc make the distinction between -Wuninitialized # and -Wmaybe-uninitialized. If -Wmaybe-uninitialized isn't supported, just # turn off all uninitialized use warnings. check_cxx_compiler_flag("-Wuninitialized" HAS_UNINITIALIZED) set(USE_NO_UNINITIALIZED ${HAS_UNINITIALIZED}) endif() endif() # By default, we target the host, but this can be overridden at CMake # invocation time. if (NOT DEFINED LLVM_INFERRED_HOST_TRIPLE) include(GetHostTriple) get_host_triple(LLVM_INFERRED_HOST_TRIPLE) endif() set(LLVM_HOST_TRIPLE "${LLVM_INFERRED_HOST_TRIPLE}" CACHE STRING "Host on which LLVM binaries will run") # Determine the native architecture. string(TOLOWER "${LLVM_TARGET_ARCH}" LLVM_NATIVE_ARCH) if( LLVM_NATIVE_ARCH STREQUAL "host" ) string(REGEX MATCH "^[^-]*" LLVM_NATIVE_ARCH ${LLVM_HOST_TRIPLE}) endif () if (LLVM_NATIVE_ARCH MATCHES "i[2-6]86") set(LLVM_NATIVE_ARCH X86) elseif (LLVM_NATIVE_ARCH STREQUAL "x86") set(LLVM_NATIVE_ARCH X86) elseif (LLVM_NATIVE_ARCH STREQUAL "amd64") set(LLVM_NATIVE_ARCH X86) elseif (LLVM_NATIVE_ARCH STREQUAL "x86_64") set(LLVM_NATIVE_ARCH X86) elseif (LLVM_NATIVE_ARCH MATCHES "sparc") set(LLVM_NATIVE_ARCH Sparc) elseif (LLVM_NATIVE_ARCH MATCHES "powerpc") set(LLVM_NATIVE_ARCH PowerPC) elseif (LLVM_NATIVE_ARCH MATCHES "aarch64") set(LLVM_NATIVE_ARCH AArch64) elseif (LLVM_NATIVE_ARCH MATCHES "arm64") set(LLVM_NATIVE_ARCH AArch64) elseif (LLVM_NATIVE_ARCH MATCHES "arm") set(LLVM_NATIVE_ARCH ARM) elseif (LLVM_NATIVE_ARCH MATCHES "mips") set(LLVM_NATIVE_ARCH Mips) elseif (LLVM_NATIVE_ARCH MATCHES "xcore") set(LLVM_NATIVE_ARCH XCore) elseif (LLVM_NATIVE_ARCH MATCHES "msp430") set(LLVM_NATIVE_ARCH MSP430) elseif (LLVM_NATIVE_ARCH MATCHES "hexagon") set(LLVM_NATIVE_ARCH Hexagon) elseif (LLVM_NATIVE_ARCH MATCHES "s390x") set(LLVM_NATIVE_ARCH SystemZ) elseif (LLVM_NATIVE_ARCH MATCHES "wasm32") set(LLVM_NATIVE_ARCH WebAssembly) elseif (LLVM_NATIVE_ARCH MATCHES "wasm64") set(LLVM_NATIVE_ARCH WebAssembly) elseif (LLVM_NATIVE_ARCH MATCHES "riscv64") set(LLVM_NATIVE_ARCH RISCV) elseif (LLVM_NATIVE_ARCH MATCHES "e2k") set(LLVM_NATIVE_ARCH E2K) else () message(FATAL_ERROR "Unknown architecture ${LLVM_NATIVE_ARCH}") endif () # If build targets includes "host", then replace with native architecture. list(FIND LLVM_TARGETS_TO_BUILD "host" idx) if( NOT idx LESS 0 ) list(REMOVE_AT LLVM_TARGETS_TO_BUILD ${idx}) list(APPEND LLVM_TARGETS_TO_BUILD ${LLVM_NATIVE_ARCH}) list(REMOVE_DUPLICATES LLVM_TARGETS_TO_BUILD) endif() list(FIND LLVM_TARGETS_TO_BUILD ${LLVM_NATIVE_ARCH} NATIVE_ARCH_IDX) if (NATIVE_ARCH_IDX EQUAL -1) message(STATUS "Native target ${LLVM_NATIVE_ARCH} is not selected; lli will not JIT code") else () message(STATUS "Native target architecture is ${LLVM_NATIVE_ARCH}") set(LLVM_NATIVE_TARGET LLVMInitialize${LLVM_NATIVE_ARCH}Target) set(LLVM_NATIVE_TARGETINFO LLVMInitialize${LLVM_NATIVE_ARCH}TargetInfo) set(LLVM_NATIVE_TARGETMC LLVMInitialize${LLVM_NATIVE_ARCH}TargetMC) set(LLVM_NATIVE_ASMPRINTER LLVMInitialize${LLVM_NATIVE_ARCH}AsmPrinter) # We don't have an ASM parser for all architectures yet. if (EXISTS ${CMAKE_SOURCE_DIR}/lib/Target/${LLVM_NATIVE_ARCH}/AsmParser/CMakeLists.txt) set(LLVM_NATIVE_ASMPARSER LLVMInitialize${LLVM_NATIVE_ARCH}AsmParser) endif () # We don't have an disassembler for all architectures yet. if (EXISTS ${CMAKE_SOURCE_DIR}/lib/Target/${LLVM_NATIVE_ARCH}/Disassembler/CMakeLists.txt) set(LLVM_NATIVE_DISASSEMBLER LLVMInitialize${LLVM_NATIVE_ARCH}Disassembler) endif () endif () if( MINGW ) set(HAVE_LIBPSAPI 1) set(HAVE_LIBSHELL32 1) # TODO: Check existence of libraries. # include(CheckLibraryExists) endif( MINGW ) if (NOT HAVE_STRTOLL) # Use _strtoi64 if strtoll is not available. check_symbol_exists(_strtoi64 stdlib.h have_strtoi64) if (have_strtoi64) set(HAVE_STRTOLL 1) set(strtoll "_strtoi64") set(strtoull "_strtoui64") endif () endif () if( MSVC ) set(SHLIBEXT ".lib") set(stricmp "_stricmp") set(strdup "_strdup") # See if the DIA SDK is available and usable. set(MSVC_DIA_SDK_DIR "$ENV{VSINSTALLDIR}DIA SDK") # Due to a bug in MSVC 2013's installation software, it is possible # for MSVC 2013 to write the DIA SDK into the Visual Studio 2012 # install directory. If this happens, the installation is corrupt # and there's nothing we can do. It happens with enough frequency # though that we should handle it. We do so by simply checking that # the DIA SDK folder exists. Should this happen you will need to # uninstall VS 2012 and then re-install VS 2013. if (IS_DIRECTORY ${MSVC_DIA_SDK_DIR}) set(HAVE_DIA_SDK 1) else() set(HAVE_DIA_SDK 0) endif() else() set(HAVE_DIA_SDK 0) endif( MSVC ) if( PURE_WINDOWS ) CHECK_CXX_SOURCE_COMPILES(" #include <windows.h> #include <imagehlp.h> extern \"C\" void foo(PENUMLOADED_MODULES_CALLBACK); extern \"C\" void foo(BOOL(CALLBACK*)(PCSTR,ULONG_PTR,ULONG,PVOID)); int main(){return 0;}" HAVE_ELMCB_PCSTR) if( HAVE_ELMCB_PCSTR ) set(WIN32_ELMCB_PCSTR "PCSTR") else() set(WIN32_ELMCB_PCSTR "PSTR") endif() endif( PURE_WINDOWS ) # FIXME: Signal handler return type, currently hardcoded to 'void' set(RETSIGTYPE void) if( LLVM_ENABLE_THREADS ) # Check if threading primitives aren't supported on this platform if( NOT HAVE_PTHREAD_H AND NOT WIN32 ) set(LLVM_ENABLE_THREADS 0) endif() endif() if( LLVM_ENABLE_THREADS ) message(STATUS "Threads enabled.") else( LLVM_ENABLE_THREADS ) message(STATUS "Threads disabled.") endif() if (LLVM_ENABLE_ZLIB ) # Check if zlib is available in the system. if ( NOT HAVE_ZLIB_H OR NOT HAVE_LIBZ ) set(LLVM_ENABLE_ZLIB 0) endif() endif() set(LLVM_PREFIX ${CMAKE_INSTALL_PREFIX}) if (LLVM_ENABLE_DOXYGEN) message(STATUS "Doxygen enabled.") find_package(Doxygen REQUIRED) if (DOXYGEN_FOUND) # If we find doxygen and we want to enable doxygen by default create a # global aggregate doxygen target for generating llvm and any/all # subprojects doxygen documentation. if (LLVM_BUILD_DOCS) add_custom_target(doxygen ALL) endif() option(LLVM_DOXYGEN_EXTERNAL_SEARCH "Enable doxygen external search." OFF) if (LLVM_DOXYGEN_EXTERNAL_SEARCH) set(LLVM_DOXYGEN_SEARCHENGINE_URL "" CACHE STRING "URL to use for external searhc.") set(LLVM_DOXYGEN_SEARCH_MAPPINGS "" CACHE STRING "Doxygen Search Mappings") endif() endif() else() message(STATUS "Doxygen disabled.") endif() if (LLVM_ENABLE_SPHINX) message(STATUS "Sphinx enabled.") find_package(Sphinx REQUIRED) if (LLVM_BUILD_DOCS) add_custom_target(sphinx ALL) endif() else() message(STATUS "Sphinx disabled.") endif() set(LLVM_BINDINGS "") if(WIN32) message(STATUS "Go bindings disabled.") else() find_program(GO_EXECUTABLE NAMES go DOC "go executable") if(GO_EXECUTABLE STREQUAL "GO_EXECUTABLE-NOTFOUND") message(STATUS "Go bindings disabled.") else() execute_process(COMMAND ${GO_EXECUTABLE} run ${CMAKE_SOURCE_DIR}/bindings/go/conftest.go RESULT_VARIABLE GO_CONFTEST) if(GO_CONFTEST STREQUAL "0") set(LLVM_BINDINGS "${LLVM_BINDINGS} go") message(STATUS "Go bindings enabled.") else() message(STATUS "Go bindings disabled, need at least Go 1.2.") endif() endif() endif() find_program(GOLD_EXECUTABLE NAMES ${LLVM_DEFAULT_TARGET_TRIPLE}-ld.gold ld.gold ${LLVM_DEFAULT_TARGET_TRIPLE}-ld ld DOC "The gold linker") set(LLVM_BINUTILS_INCDIR "" CACHE PATH "PATH to binutils/include containing plugin-api.h for gold plugin.") if(APPLE) find_program(LD64_EXECUTABLE NAMES ld DOC "The ld64 linker") endif() include(FindOCaml) include(AddOCaml) if(WIN32) message(STATUS "OCaml bindings disabled.") else() find_package(OCaml) if( NOT OCAML_FOUND ) message(STATUS "OCaml bindings disabled.") else() if( OCAML_VERSION VERSION_LESS "4.00.0" ) message(STATUS "OCaml bindings disabled, need OCaml >=4.00.0.") else() find_ocamlfind_package(ctypes VERSION 0.4 OPTIONAL) if( HAVE_OCAML_CTYPES ) message(STATUS "OCaml bindings enabled.") find_ocamlfind_package(oUnit VERSION 2 OPTIONAL) set(LLVM_BINDINGS "${LLVM_BINDINGS} ocaml") else() message(STATUS "OCaml bindings disabled, need ctypes >=0.4.") endif() endif() endif() endif() string(REPLACE " " ";" LLVM_BINDINGS_LIST "${LLVM_BINDINGS}")
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/ChooseMSVCCRT.cmake
# The macro choose_msvc_crt() takes a list of possible # C runtimes to choose from, in the form of compiler flags, # to present to the user. (MTd for /MTd, etc) # # The macro is invoked at the end of the file. # # CMake already sets CRT flags in the CMAKE_CXX_FLAGS_* and # CMAKE_C_FLAGS_* variables by default. To let the user # override that for each build type: # 1. Detect which CRT is already selected, and reflect this in # LLVM_USE_CRT_* so the user can have a better idea of what # changes they're making. # 2. Replace the flags in both variables with the new flag via a regex. # 3. set() the variables back into the cache so the changes # are user-visible. ### Helper macros: ### macro(make_crt_regex regex crts) set(${regex} "") foreach(crt ${${crts}}) # Trying to match the beginning or end of the string with stuff # like [ ^]+ didn't work, so use a bunch of parentheses instead. set(${regex} "${${regex}}|(^| +)/${crt}($| +)") endforeach(crt) string(REGEX REPLACE "^\\|" "" ${regex} "${${regex}}") endmacro(make_crt_regex) macro(get_current_crt crt_current regex flagsvar) # Find the selected-by-CMake CRT for each build type, if any. # Strip off the leading slash and any whitespace. string(REGEX MATCH "${${regex}}" ${crt_current} "${${flagsvar}}") string(REPLACE "/" " " ${crt_current} "${${crt_current}}") string(STRIP "${${crt_current}}" ${crt_current}) endmacro(get_current_crt) # Replaces or adds a flag to a variable. # Expects 'flag' to be padded with spaces. macro(set_flag_in_var flagsvar regex flag) string(REGEX MATCH "${${regex}}" current_flag "${${flagsvar}}") if("${current_flag}" STREQUAL "") set(${flagsvar} "${${flagsvar}}${${flag}}") else() string(REGEX REPLACE "${${regex}}" "${${flag}}" ${flagsvar} "${${flagsvar}}") endif() string(STRIP "${${flagsvar}}" ${flagsvar}) # Make sure this change gets reflected in the cache/gui. # CMake requires the docstring parameter whenever set() touches the cache, # so get the existing docstring and re-use that. get_property(flagsvar_docs CACHE ${flagsvar} PROPERTY HELPSTRING) set(${flagsvar} "${${flagsvar}}" CACHE STRING "${flagsvar_docs}" FORCE) endmacro(set_flag_in_var) macro(choose_msvc_crt MSVC_CRT) if(LLVM_USE_CRT) message(FATAL_ERROR "LLVM_USE_CRT is deprecated. Use the CMAKE_BUILD_TYPE-specific variables (LLVM_USE_CRT_DEBUG, etc) instead.") endif() make_crt_regex(MSVC_CRT_REGEX ${MSVC_CRT}) foreach(build_type ${CMAKE_CONFIGURATION_TYPES} ${CMAKE_BUILD_TYPE}) string(TOUPPER "${build_type}" build) if (NOT LLVM_USE_CRT_${build}) get_current_crt(LLVM_USE_CRT_${build} MSVC_CRT_REGEX CMAKE_CXX_FLAGS_${build}) set(LLVM_USE_CRT_${build} "${LLVM_USE_CRT_${build}}" CACHE STRING "Specify VC++ CRT to use for ${build_type} configurations." FORCE) set_property(CACHE LLVM_USE_CRT_${build} PROPERTY STRINGS ;${${MSVC_CRT}}) endif(NOT LLVM_USE_CRT_${build}) endforeach(build_type) foreach(build_type ${CMAKE_CONFIGURATION_TYPES} ${CMAKE_BUILD_TYPE}) string(TOUPPER "${build_type}" build) if ("${LLVM_USE_CRT_${build}}" STREQUAL "") set(flag_string " ") else() set(flag_string " /${LLVM_USE_CRT_${build}} ") list(FIND ${MSVC_CRT} ${LLVM_USE_CRT_${build}} idx) if (idx LESS 0) message(FATAL_ERROR "Invalid value for LLVM_USE_CRT_${build}: ${LLVM_USE_CRT_${build}}. Valid options are one of: ${${MSVC_CRT}}") endif (idx LESS 0) message(STATUS "Using ${build_type} VC++ CRT: ${LLVM_USE_CRT_${build}}") endif() foreach(lang C CXX) set_flag_in_var(CMAKE_${lang}_FLAGS_${build} MSVC_CRT_REGEX flag_string) endforeach(lang) endforeach(build_type) endmacro(choose_msvc_crt MSVC_CRT) # List of valid CRTs for MSVC set(MSVC_CRT MD MDd MT MTd) choose_msvc_crt(MSVC_CRT)
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/HCT.cmake
option(HLSL_COPY_GENERATED_SOURCES "Copy generated sources if different" Off) option(HLSL_DISABLE_SOURCE_GENERATION "Disable generation of in-tree sources" Off) mark_as_advanced(HLSL_DISABLE_SOURCE_GENERATION) add_custom_target(HCTGen) find_program(CLANG_FORMAT_EXE NAMES clang-format) if (NOT CLANG_FORMAT_EXE) message(WARNING "Clang-format is not available. Generating included sources is not supported.") if (HLSL_COPY_GENERATED_SOURCES) message(FATAL_ERROR "Generating sources requires clang-format") endif () endif () if (WIN32 AND NOT DEFINED HLSL_AUTOCRLF) find_program(git_executable NAMES git git.exe git.cmd) execute_process(COMMAND ${git_executable} config --get core.autocrlf WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} TIMEOUT 5 RESULT_VARIABLE result OUTPUT_VARIABLE output OUTPUT_STRIP_TRAILING_WHITESPACE) if( result EQUAL 0 ) # This is a little counterintuitive... Because the repo's gitattributes set # text=auto, autocrlf behavior will be enabled for autocrlf true or false. # For reasons unknown to me, autocrlf=input overrides the gitattributes, so # that is the case we need special handling for. set(val On) if (output STREQUAL "input") set(val Off) endif() set(HLSL_AUTOCRLF ${val} CACHE BOOL "Is core.autocrlf enabled in this clone") message(STATUS "Git checkout autocrlf: ${HLSL_AUTOCRLF}") endif() endif() function(add_hlsl_hctgen mode) cmake_parse_arguments(ARG "BUILD_DIR;CODE_TAG" "OUTPUT" "" ${ARGN}) if (NOT ARG_OUTPUT) message(FATAL_ERROR "add_hlsl_hctgen requires OUTPUT argument") endif() if (HLSL_DISABLE_SOURCE_GENERATION AND NOT ARG_BUILD_DIR) return() endif() set(temp_output ${CMAKE_CURRENT_BINARY_DIR}/tmp/${ARG_OUTPUT}) set(full_output ${CMAKE_CURRENT_SOURCE_DIR}/${ARG_OUTPUT}) if (ARG_BUILD_DIR) set(full_output ${CMAKE_CURRENT_BINARY_DIR}/${ARG_OUTPUT}) endif() set(hctgen ${LLVM_SOURCE_DIR}/utils/hct/hctgen.py) set(hctdb ${LLVM_SOURCE_DIR}/utils/hct/hctdb.py) set(hctdb_helper ${LLVM_SOURCE_DIR}/utils/hct/hctdb_instrhelp.py) set(output ${full_output}) set(hct_dependencies ${LLVM_SOURCE_DIR}/utils/hct/gen_intrin_main.txt ${hctgen} ${hctdb} ${hctdb_helper}) get_filename_component(output_extension ${full_output} LAST_EXT) if (CLANG_FORMAT_EXE AND output_extension MATCHES "\.h|\.cpp|\.inl") set(format_cmd COMMAND ${CLANG_FORMAT_EXE} -i ${temp_output}) endif () set(copy_sources Off) if(ARG_BUILD_DIR OR HLSL_COPY_GENERATED_SOURCES) set(copy_sources On) endif() if(ARG_CODE_TAG) set(input_flag --input ${full_output}) if (UNIX) execute_process(COMMAND file ${full_output} OUTPUT_VARIABLE output) if (output MATCHES ".*, with CRLF line terminators") set(force_lf "--force-crlf") endif() endif() list(APPEND hct_dependencies ${full_output}) if (HLSL_COPY_GENERATED_SOURCES) # The generation command both depends on and produces the final output if # source copying is enabled for CODE_TAG sources. That means we need to # create an extra temporary to key the copy step on. set(output ${temp_output}.2) set(second_copy COMMAND ${CMAKE_COMMAND} -E copy_if_different ${temp_output} ${temp_output}.2) endif() endif() # If we're not copying the sources, set the output for the target as the temp # file, and define the verification command if(NOT copy_sources) set(output ${temp_output}) if (CLANG_FORMAT_EXE) # Only verify sources if clang-format is available. set(verification COMMAND ${CMAKE_COMMAND} -E compare_files ${temp_output} ${full_output}) endif() endif() if(WIN32 AND NOT HLSL_AUTOCRLF) set(force_lf "--force-lf") endif() add_custom_command(OUTPUT ${temp_output} COMMAND ${Python3_EXECUTABLE} ${hctgen} ${force_lf} ${mode} --output ${temp_output} ${input_flag} ${format_cmd} COMMENT "Building ${ARG_OUTPUT}..." DEPENDS ${hct_dependencies} ) if(copy_sources) add_custom_command(OUTPUT ${output} COMMAND ${CMAKE_COMMAND} -E copy_if_different ${temp_output} ${full_output} ${second_copy} DEPENDS ${temp_output} COMMENT "Updating ${ARG_OUTPUT}..." ) endif() add_custom_command(OUTPUT ${temp_output}.stamp COMMAND ${verification} COMMAND ${CMAKE_COMMAND} -E touch ${temp_output}.stamp DEPENDS ${output} COMMENT "Verifying clang-format results...") add_custom_target(${mode} DEPENDS ${temp_output}.stamp) add_dependencies(HCTGen ${mode}) endfunction()
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/AddLLVMDefinitions.cmake
# There is no clear way of keeping track of compiler command-line # options chosen via `add_definitions', so we need our own method for # using it on tools/llvm-config/CMakeLists.txt. # Beware that there is no implementation of remove_llvm_definitions. macro(add_llvm_definitions) # We don't want no semicolons on LLVM_DEFINITIONS: foreach(arg ${ARGN}) set(LLVM_DEFINITIONS "${LLVM_DEFINITIONS} ${arg}") endforeach(arg) add_definitions( ${ARGN} ) endmacro(add_llvm_definitions)
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/AddOCaml.cmake
# CMake build rules for the OCaml language. # Assumes FindOCaml is used. # http://ocaml.org/ # # Example usage: # # add_ocaml_library(pkg_a OCAML mod_a OCAMLDEP pkg_b C mod_a_stubs PKG ctypes LLVM core) # # Unnamed parameters: # # * Library name. # # Named parameters: # # OCAML OCaml module names. Imply presence of a corresponding .ml and .mli files. # OCAMLDEP Names of libraries this library depends on. # C C stub sources. Imply presence of a corresponding .c file. # CFLAGS Additional arguments passed when compiling C stubs. # PKG Names of ocamlfind packages this library depends on. # LLVM Names of LLVM libraries this library depends on. # NOCOPY Do not automatically copy sources (.c, .ml, .mli) from the source directory, # e.g. if they are generated. # function(add_ocaml_library name) CMAKE_PARSE_ARGUMENTS(ARG "NOCOPY" "" "OCAML;OCAMLDEP;C;CFLAGS;PKG;LLVM" ${ARGN}) set(src ${CMAKE_CURRENT_SOURCE_DIR}) set(bin ${CMAKE_CURRENT_BINARY_DIR}) set(ocaml_pkgs) foreach( ocaml_pkg ${ARG_PKG} ) list(APPEND ocaml_pkgs "-package" "${ocaml_pkg}") endforeach() set(sources) set(ocaml_inputs) set(ocaml_outputs "${bin}/${name}.cma") if( ARG_C ) list(APPEND ocaml_outputs "${bin}/lib${name}${CMAKE_STATIC_LIBRARY_SUFFIX}") if ( BUILD_SHARED_LIBS ) list(APPEND ocaml_outputs "${bin}/dll${name}${CMAKE_SHARED_LIBRARY_SUFFIX}") endif() endif() if( HAVE_OCAMLOPT ) list(APPEND ocaml_outputs "${bin}/${name}.cmxa" "${bin}/${name}${CMAKE_STATIC_LIBRARY_SUFFIX}") endif() set(ocaml_flags "-lstdc++" "-ldopt" "-L${LLVM_LIBRARY_DIR}" "-ccopt" "-L\\$CAMLORIGIN/.." "-ccopt" "-Wl,-rpath,\\$CAMLORIGIN/.." ${ocaml_pkgs}) foreach( ocaml_dep ${ARG_OCAMLDEP} ) get_target_property(dep_ocaml_flags "ocaml_${ocaml_dep}" OCAML_FLAGS) list(APPEND ocaml_flags ${dep_ocaml_flags}) endforeach() if( NOT BUILD_SHARED_LIBS ) list(APPEND ocaml_flags "-custom") endif() explicit_map_components_to_libraries(llvm_libs ${ARG_LLVM}) foreach( llvm_lib ${llvm_libs} ) list(APPEND ocaml_flags "-l${llvm_lib}" ) endforeach() get_property(system_libs TARGET LLVMSupport PROPERTY LLVM_SYSTEM_LIBS) foreach(system_lib ${system_libs}) list(APPEND ocaml_flags "-l${system_lib}" ) endforeach() string(REPLACE ";" " " ARG_CFLAGS "${ARG_CFLAGS}") set(c_flags "${ARG_CFLAGS} ${LLVM_DEFINITIONS}") foreach( include_dir ${LLVM_INCLUDE_DIR} ${LLVM_MAIN_INCLUDE_DIR} ) set(c_flags "${c_flags} -I${include_dir}") endforeach() foreach( ocaml_file ${ARG_OCAML} ) list(APPEND sources "${ocaml_file}.mli" "${ocaml_file}.ml") list(APPEND ocaml_inputs "${bin}/${ocaml_file}.mli" "${bin}/${ocaml_file}.ml") list(APPEND ocaml_outputs "${bin}/${ocaml_file}.cmi" "${bin}/${ocaml_file}.cmo") if( HAVE_OCAMLOPT ) list(APPEND ocaml_outputs "${bin}/${ocaml_file}.cmx" "${bin}/${ocaml_file}${CMAKE_C_OUTPUT_EXTENSION}") endif() endforeach() foreach( c_file ${ARG_C} ) list(APPEND sources "${c_file}.c") list(APPEND c_inputs "${bin}/${c_file}.c") list(APPEND c_outputs "${bin}/${c_file}${CMAKE_C_OUTPUT_EXTENSION}") endforeach() if( NOT ARG_NOCOPY ) foreach( source ${sources} ) add_custom_command( OUTPUT "${bin}/${source}" COMMAND "${CMAKE_COMMAND}" "-E" "copy" "${src}/${source}" "${bin}" DEPENDS "${src}/${source}" COMMENT "Copying ${source} to build area") endforeach() endif() foreach( c_input ${c_inputs} ) get_filename_component(basename "${c_input}" NAME_WE) add_custom_command( OUTPUT "${basename}${CMAKE_C_OUTPUT_EXTENSION}" COMMAND "${OCAMLFIND}" "ocamlc" "-c" "${c_input}" -ccopt ${c_flags} DEPENDS "${c_input}" COMMENT "Building OCaml stub object file ${basename}${CMAKE_C_OUTPUT_EXTENSION}" VERBATIM) endforeach() set(ocaml_params) foreach( ocaml_input ${ocaml_inputs} ${c_outputs}) get_filename_component(filename "${ocaml_input}" NAME) list(APPEND ocaml_params "${filename}") endforeach() if( APPLE ) set(ocaml_rpath "@executable_path/../../lib") elseif( UNIX ) set(ocaml_rpath "\\$ORIGIN/../../lib") endif() list(APPEND ocaml_flags "-ldopt" "-Wl,-rpath,${ocaml_rpath}") add_custom_command( OUTPUT ${ocaml_outputs} COMMAND "${OCAMLFIND}" "ocamlmklib" "-o" "${name}" ${ocaml_flags} ${ocaml_params} DEPENDS ${ocaml_inputs} ${c_outputs} COMMENT "Building OCaml library ${name}" VERBATIM) add_custom_command( OUTPUT "${bin}/${name}.odoc" COMMAND "${OCAMLFIND}" "ocamldoc" "-I" "${bin}" "-I" "${LLVM_LIBRARY_DIR}/ocaml/" "-dump" "${bin}/${name}.odoc" ${ocaml_pkgs} ${ocaml_inputs} DEPENDS ${ocaml_inputs} ${ocaml_outputs} COMMENT "Building OCaml documentation for ${name}" VERBATIM) add_custom_target("ocaml_${name}" ALL DEPENDS ${ocaml_outputs} "${bin}/${name}.odoc") set_target_properties("ocaml_${name}" PROPERTIES OCAML_FLAGS "-I;${bin}") set_target_properties("ocaml_${name}" PROPERTIES OCAML_ODOC "${bin}/${name}.odoc") foreach( ocaml_dep ${ARG_OCAMLDEP} ) add_dependencies("ocaml_${name}" "ocaml_${ocaml_dep}") endforeach() foreach( llvm_lib ${llvm_libs} ) add_dependencies("ocaml_${name}" "${llvm_lib}") endforeach() set(install_files) set(install_shlibs) foreach( ocaml_output ${ocaml_outputs} ) get_filename_component(ext "${ocaml_output}" EXT) if( NOT (ext STREQUAL ".cmo" OR ext STREQUAL CMAKE_C_OUTPUT_EXTENSION OR ext STREQUAL CMAKE_SHARED_LIBRARY_SUFFIX) ) list(APPEND install_files "${ocaml_output}") elseif( ext STREQUAL CMAKE_SHARED_LIBRARY_SUFFIX) list(APPEND install_shlibs "${ocaml_output}") endif() endforeach() install(FILES ${install_files} DESTINATION lib/ocaml) install(FILES ${install_shlibs} PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE DESTINATION lib/ocaml) foreach( install_file ${install_files} ${install_shlibs} ) get_filename_component(filename "${install_file}" NAME) add_custom_command(TARGET "ocaml_${name}" POST_BUILD COMMAND "${CMAKE_COMMAND}" "-E" "copy" "${install_file}" "${LLVM_LIBRARY_DIR}/ocaml/" COMMENT "Copying OCaml library component ${filename} to intermediate area" VERBATIM) endforeach() endfunction()
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/LLVMProcessSources.cmake
include(AddFileDependencies) include(CMakeParseArguments) function(llvm_replace_compiler_option var old new) # Replaces a compiler option or switch `old' in `var' by `new'. # If `old' is not in `var', appends `new' to `var'. # Example: llvm_replace_compiler_option(CMAKE_CXX_FLAGS_RELEASE "-O3" "-O2") # If the option already is on the variable, don't add it: if( "${${var}}" MATCHES "(^| )${new}($| )" ) set(n "") else() set(n "${new}") endif() if( "${${var}}" MATCHES "(^| )${old}($| )" ) string( REGEX REPLACE "(^| )${old}($| )" " ${n} " ${var} "${${var}}" ) else() set( ${var} "${${var}} ${n}" ) endif() set( ${var} "${${var}}" PARENT_SCOPE ) endfunction(llvm_replace_compiler_option) macro(add_td_sources srcs) file(GLOB tds *.td) if( tds ) source_group("TableGen descriptions" FILES ${tds}) set_source_files_properties(${tds} PROPERTIES HEADER_FILE_ONLY ON) list(APPEND ${srcs} ${tds}) endif() endmacro(add_td_sources) function(add_header_files_for_glob hdrs_out glob) file(GLOB hds ${glob}) set(${hdrs_out} ${hds} PARENT_SCOPE) endfunction(add_header_files_for_glob) function(find_all_header_files hdrs_out additional_headerdirs) add_header_files_for_glob(hds *.h) list(APPEND all_headers ${hds}) foreach(additional_dir ${additional_headerdirs}) add_header_files_for_glob(hds "${additional_dir}/*.h") list(APPEND all_headers ${hds}) add_header_files_for_glob(hds "${additional_dir}/*.inc") list(APPEND all_headers ${hds}) endforeach(additional_dir) set( ${hdrs_out} ${all_headers} PARENT_SCOPE ) endfunction(find_all_header_files) function(llvm_process_sources OUT_VAR) cmake_parse_arguments(ARG "" "" "ADDITIONAL_HEADERS;ADDITIONAL_HEADER_DIRS" ${ARGN}) set(sources ${ARG_UNPARSED_ARGUMENTS}) llvm_check_source_file_list( ${sources} ) if( MSVC_IDE OR XCODE ) # This adds .td and .h files to the Visual Studio solution: add_td_sources(sources) find_all_header_files(hdrs "${ARG_ADDITIONAL_HEADER_DIRS}") if (hdrs) set_source_files_properties(${hdrs} PROPERTIES HEADER_FILE_ONLY ON) endif() set_source_files_properties(${ARG_ADDITIONAL_HEADERS} PROPERTIES HEADER_FILE_ONLY ON) list(APPEND sources ${ARG_ADDITIONAL_HEADERS} ${hdrs}) endif() set( ${OUT_VAR} ${sources} PARENT_SCOPE ) endfunction(llvm_process_sources) function(llvm_check_source_file_list) set(listed ${ARGN}) file(GLOB globbed *.c *.cpp) foreach(g ${globbed}) get_filename_component(fn ${g} NAME) # HLSL Change - case insensitive string(TOLOWER "${fn}" fn_lower) string(TOLOWER "${listed}" listed_lower) # Don't reject hidden files. Some editors create backups in the # same directory as the file. if (NOT "${fn}" MATCHES "^\\.") list(FIND LLVM_OPTIONAL_SOURCES ${fn} idx) if( idx LESS 0 ) list(FIND listed_lower ${fn_lower} idx) # HLSL Change - case insensitive if( idx LESS 0 ) # HLSL Change - support HLSL_IGNORE_SOURCES if( idx LESS 0 ) list(FIND HLSL_IGNORE_SOURCES ${fn} idx) if( idx LESS 0 ) message(SEND_ERROR "Found unknown source file ${g} Please update ${CMAKE_CURRENT_LIST_FILE} or HLSL_IGNORE_SOURCES\n") endif() endif() endif() endif() endif() endforeach() endfunction(llvm_check_source_file_list)
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/FindTAEF.cmake
# Find the TAEF path that supports x86 and x64. get_filename_component(WINDOWS_KIT_10_PATH "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots;KitsRoot10]" ABSOLUTE CACHE) get_filename_component(WINDOWS_KIT_81_PATH "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots;KitsRoot81]" ABSOLUTE CACHE) # Find the TAEF path, it will typically look something like this. # "C:\Program Files (x86)\Windows Kits\8.1\Testing\Development\inc" set(pfx86 "programfiles(x86)") # Work around behavior for environment names allows chars. find_path(TAEF_INCLUDE_DIR # Set variable TAEF_INCLUDE_DIR Wex.Common.h # Find a path with Wex.Common.h HINTS "$ENV{TAEF_PATH}/../../../Include" HINTS "$ENV{TAEF_PATH}/../../../Development/inc" HINTS "${CMAKE_SOURCE_DIR}/external/taef/build/Include" HINTS "${WINDOWS_KIT_10_PATH}/Testing/Development/inc" HINTS "${WINDOWS_KIT_81_PATH}/Testing/Development/inc" DOC "path to TAEF header files" HINTS ) macro(find_taef_libraries targetplatform) set(TAEF_LIBRARIES) foreach(L Te.Common.lib Wex.Common.lib Wex.Logger.lib) find_library(TAEF_LIB_${L} NAMES ${L} HINTS ${TAEF_INCLUDE_DIR}/../Library/${targetplatform} HINTS ${TAEF_INCLUDE_DIR}/../lib/${targetplatform}) set(TAEF_LIBRARIES ${TAEF_LIBRARIES} ${TAEF_LIB_${L}}) endforeach() set(TAEF_COMMON_LIBRARY ${TAEF_LIB_Te.Common.lib}) endmacro(find_taef_libraries) if(CMAKE_C_COMPILER_ARCHITECTURE_ID STREQUAL "ARM64EC") find_taef_libraries(arm64) elseif(CMAKE_C_COMPILER_ARCHITECTURE_ID STREQUAL "ARMV7") find_taef_libraries(arm) else() find_taef_libraries(${CMAKE_C_COMPILER_ARCHITECTURE_ID}) endif() set(TAEF_INCLUDE_DIRS ${TAEF_INCLUDE_DIR}) # Get TAEF binaries path from the header location set(TAEF_NUGET_BIN ${TAEF_INCLUDE_DIR}/../Binaries/Release) set(TAEF_SDK_BIN ${TAEF_INCLUDE_DIR}/../../Runtimes/TAEF) if ((CMAKE_GENERATOR_PLATFORM STREQUAL "x64") OR ("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "x64")) set(TAEF_BIN_ARCH "amd64") set(TAEF_ARCH "x64") elseif ((CMAKE_GENERATOR_PLATFORM STREQUAL "x86") OR ("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "x86")) set(TAEF_BIN_ARCH "x86") set(TAEF_ARCH "x86") elseif ((CMAKE_GENERATOR_PLATFORM MATCHES "ARM64.*") OR ("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" MATCHES "ARM64.*")) set(TAEF_BIN_ARCH "arm64") set(TAEF_ARCH "arm64") elseif ((CMAKE_GENERATOR_PLATFORM MATCHES "ARM.*") OR ("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" MATCHES "ARM.*")) set(TAEF_BIN_ARCH "arm") set(TAEF_ARCH "arm") endif((CMAKE_GENERATOR_PLATFORM STREQUAL "x64") OR ("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "x64")) set (TAEF_ARCH ${TAEF_ARCH} CACHE INTERNAL "arch for taef test") find_program(TAEF_EXECUTABLE te.exe PATHS $ENV{TAEF_PATH} ${CMAKE_SOURCE_DIR}/external/taef/build/Binaries/${TAEF_BIN_ARCH} $ENV{HLSL_TAEF_DIR}/${TAEF_BIN_ARCH} ${TAEF_NUGET_BIN}/${TAEF_ARCH} ${TAEF_SDK_BIN}/${TAEF_ARCH} ${WINDOWS_KIT_10_PATH} ${WINDOWS_KIT_81_PATH} ) if (TAEF_EXECUTABLE) get_filename_component(TAEF_BIN_DIR ${TAEF_EXECUTABLE} DIRECTORY) else() message(FATAL_ERROR "Unable to find TAEF binaries.") endif() include(FindPackageHandleStandardArgs) # handle the QUIETLY and REQUIRED arguments and set TAEF_FOUND to TRUE # if all listed variables are TRUE find_package_handle_standard_args(TAEF DEFAULT_MSG TAEF_COMMON_LIBRARY TAEF_INCLUDE_DIR) mark_as_advanced(TAEF_INCLUDE_DIR TAEF_LIBRARY)
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/VersionFromVCS.cmake
# Adds version control information to the variable VERS. For # determining the Version Control System used (if any) it inspects the # existence of certain subdirectories under CMAKE_CURRENT_SOURCE_DIR. function(add_version_info_from_vcs VERS) string(REPLACE "svn" "" result "${${VERS}}") if( EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.svn" ) set(result "${result}svn") # FindSubversion does not work with symlinks. See PR 8437 if( NOT IS_SYMLINK "${CMAKE_CURRENT_SOURCE_DIR}" ) find_package(Subversion) endif() if( Subversion_FOUND ) subversion_wc_info( ${CMAKE_CURRENT_SOURCE_DIR} Project ) if( Project_WC_REVISION ) set(SVN_REVISION ${Project_WC_REVISION} PARENT_SCOPE) set(result "${result}-r${Project_WC_REVISION}") endif() endif() elseif( EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.git ) set(result "${result}git") # Try to get a ref-id if( EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.git/svn ) find_program(git_executable NAMES git git.exe git.cmd) if( git_executable ) set(is_git_svn_rev_exact false) execute_process(COMMAND ${git_executable} svn log --limit=1 --oneline WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} TIMEOUT 5 RESULT_VARIABLE git_result OUTPUT_VARIABLE git_output) if( git_result EQUAL 0 ) string(REGEX MATCH r[0-9]+ git_svn_rev ${git_output}) string(LENGTH "${git_svn_rev}" rev_length) math(EXPR rev_length "${rev_length}-1") string(SUBSTRING "${git_svn_rev}" 1 ${rev_length} git_svn_rev_number) set(SVN_REVISION ${git_svn_rev_number} PARENT_SCOPE) set(git_svn_rev "-svn-${git_svn_rev}") # Determine if the HEAD points directly at a subversion revision. execute_process(COMMAND ${git_executable} svn find-rev HEAD WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} TIMEOUT 5 RESULT_VARIABLE git_result OUTPUT_VARIABLE git_output) if( git_result EQUAL 0 ) string(STRIP "${git_output}" git_head_svn_rev_number) if( git_head_svn_rev_number EQUAL git_svn_rev_number ) set(is_git_svn_rev_exact true) endif() endif() else() set(git_svn_rev "") endif() execute_process(COMMAND ${git_executable} rev-parse --short HEAD WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} TIMEOUT 5 RESULT_VARIABLE git_result OUTPUT_VARIABLE git_output) if( git_result EQUAL 0 AND NOT is_git_svn_rev_exact ) string(STRIP "${git_output}" git_ref_id) set(GIT_COMMIT ${git_ref_id} PARENT_SCOPE) set(result "${result}${git_svn_rev}-${git_ref_id}") else() set(result "${result}${git_svn_rev}") endif() endif() else() # HLSL Change - if no .git/svn, grab the hash find_program(git_executable NAMES git git.exe git.cmd) if( git_executable ) execute_process(COMMAND ${git_executable} describe --tags --always --dirty WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} TIMEOUT 5 RESULT_VARIABLE git_result OUTPUT_VARIABLE git_output) if( git_result EQUAL 0 ) string(STRIP "${git_output}" git_ref_id) set(result "3.7-${git_ref_id}") else() message (WARNING "failed to run git describe to get version") endif() endif() endif() endif() set(${VERS} ${result} PARENT_SCOPE) endfunction(add_version_info_from_vcs)
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/FindSphinx.cmake
# CMake find_package() Module for Sphinx documentation generator # http://sphinx-doc.org/ # # Example usage: # # find_package(Sphinx) # # If successful the following variables will be defined # SPHINX_FOUND # SPHINX_EXECUTABLE find_program(SPHINX_EXECUTABLE NAMES sphinx-build sphinx-build2 DOC "Path to sphinx-build executable") # Handle REQUIRED and QUIET arguments # this will also set SPHINX_FOUND to true if SPHINX_EXECUTABLE exists include(FindPackageHandleStandardArgs) find_package_handle_standard_args(Sphinx "Failed to locate sphinx-build executable" SPHINX_EXECUTABLE) # Provide options for controlling different types of output option(SPHINX_OUTPUT_HTML "Output standalone HTML files" ON) option(SPHINX_OUTPUT_MAN "Output man pages" ON) option(SPHINX_WARNINGS_AS_ERRORS "When building documentation treat warnings as errors" ON)
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/AddLLVM.cmake
include(LLVMProcessSources) include(LLVM-Config) find_package(Python3 REQUIRED) function(llvm_update_compile_flags name) get_property(sources TARGET ${name} PROPERTY SOURCES) if("${sources}" MATCHES "\\.c(;|$)") set(update_src_props ON) endif() # LLVM_REQUIRES_EH is an internal flag that individual # targets can use to force EH if(LLVM_REQUIRES_EH OR LLVM_ENABLE_EH) # HLSL Change - allow CLANG_CL to use EH. if(NOT (LLVM_REQUIRES_RTTI OR LLVM_ENABLE_RTTI)) message(AUTHOR_WARNING "Exception handling requires RTTI. Enabling RTTI for ${name}") set(LLVM_REQUIRES_RTTI ON) endif() else() if(LLVM_COMPILER_IS_GCC_COMPATIBLE) list(APPEND LLVM_COMPILE_FLAGS "-fno-exceptions") elseif(MSVC) list(APPEND LLVM_COMPILE_DEFINITIONS _HAS_EXCEPTIONS=0) list(APPEND LLVM_COMPILE_FLAGS "/EHs-c-") endif() if (CLANG_CL) # FIXME: Remove this once clang-cl supports SEH list(APPEND LLVM_COMPILE_DEFINITIONS "GTEST_HAS_SEH=0") endif() endif() # LLVM_REQUIRES_RTTI is an internal flag that individual # targets can use to force RTTI if(NOT (LLVM_REQUIRES_RTTI OR LLVM_ENABLE_RTTI)) list(APPEND LLVM_COMPILE_DEFINITIONS GTEST_HAS_RTTI=0) if (LLVM_COMPILER_IS_GCC_COMPATIBLE) list(APPEND LLVM_COMPILE_FLAGS "-fno-rtti") elseif (MSVC) list(APPEND LLVM_COMPILE_FLAGS "/GR-") endif () endif() # HLSL Changes Start if (LLVM_ENABLE_EH) if (MSVC) list(APPEND LLVM_COMPILE_FLAGS "/EHsc") else (MSVC) # This is just the default exception handling on Linux endif (MSVC) endif (LLVM_ENABLE_EH) if (NOT HLSL_ENABLE_DEBUG_ITERATORS) add_definitions(/D_ITERATOR_DEBUG_LEVEL=0) endif (NOT HLSL_ENABLE_DEBUG_ITERATORS) # HLSL Changes End # Assume that; # - LLVM_COMPILE_FLAGS is list. # - PROPERTY COMPILE_FLAGS is string. string(REPLACE ";" " " target_compile_flags "${LLVM_COMPILE_FLAGS}") if(update_src_props) foreach(fn ${sources}) get_filename_component(suf ${fn} EXT) if("${suf}" STREQUAL ".cpp") set_property(SOURCE ${fn} APPEND_STRING PROPERTY COMPILE_FLAGS "${target_compile_flags}") endif() endforeach() else() # Update target props, since all sources are C++. set_property(TARGET ${name} APPEND_STRING PROPERTY COMPILE_FLAGS "${target_compile_flags}") endif() set_property(TARGET ${name} APPEND PROPERTY COMPILE_DEFINITIONS ${LLVM_COMPILE_DEFINITIONS}) endfunction() function(add_llvm_symbol_exports target_name export_file) if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") set(native_export_file "${target_name}.exports") add_custom_command(OUTPUT ${native_export_file} COMMAND sed -e "s/^/_/" < ${export_file} > ${native_export_file} DEPENDS ${export_file} VERBATIM COMMENT "Creating export file for ${target_name}") set_property(TARGET ${target_name} APPEND_STRING PROPERTY LINK_FLAGS " -Wl,-exported_symbols_list,${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}") elseif(LLVM_HAVE_LINK_VERSION_SCRIPT) # Gold and BFD ld require a version script rather than a plain list. set(native_export_file "${target_name}.exports") # FIXME: Don't write the "local:" line on OpenBSD. add_custom_command(OUTPUT ${native_export_file} COMMAND echo "{" > ${native_export_file} COMMAND grep -q "[[:alnum:]]" ${export_file} && echo " global:" >> ${native_export_file} || : COMMAND sed -e "s/$/;/" -e "s/^/ /" < ${export_file} >> ${native_export_file} COMMAND echo " local: *;" >> ${native_export_file} COMMAND echo "};" >> ${native_export_file} DEPENDS ${export_file} VERBATIM COMMENT "Creating export file for ${target_name}") if (${CMAKE_SYSTEM_NAME} MATCHES "SunOS") set_property(TARGET ${target_name} APPEND_STRING PROPERTY LINK_FLAGS " -Wl,-M,${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}") else() set_property(TARGET ${target_name} APPEND_STRING PROPERTY LINK_FLAGS " -Wl,--version-script,${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}") endif() else() set(native_export_file "${target_name}.def") add_custom_command(OUTPUT ${native_export_file} COMMAND ${Python3_EXECUTABLE} -c "import sys;print(''.join(['EXPORTS\\n']+sys.stdin.readlines(),))" < ${export_file} > ${native_export_file} DEPENDS ${export_file} VERBATIM COMMENT "Creating export file for ${target_name}") set(export_file_linker_flag "${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}") if(MSVC) set(export_file_linker_flag "/DEF:\"${export_file_linker_flag}\"") endif() set_property(TARGET ${target_name} APPEND_STRING PROPERTY LINK_FLAGS " ${export_file_linker_flag}") endif() add_custom_target(${target_name}_exports DEPENDS ${native_export_file}) set_target_properties(${target_name}_exports PROPERTIES FOLDER "Misc") get_property(srcs TARGET ${target_name} PROPERTY SOURCES) foreach(src ${srcs}) get_filename_component(extension ${src} EXT) if(extension STREQUAL ".cpp") set(first_source_file ${src}) break() endif() endforeach() # Force re-linking when the exports file changes. Actually, it # forces recompilation of the source file. The LINK_DEPENDS target # property only works for makefile-based generators. # FIXME: This is not safe because this will create the same target # ${native_export_file} in several different file: # - One where we emitted ${target_name}_exports # - One where we emitted the build command for the following object. # set_property(SOURCE ${first_source_file} APPEND PROPERTY # OBJECT_DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}) set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${native_export_file}) add_dependencies(${target_name} ${target_name}_exports) # Add dependency to *_exports later -- CMake issue 14747 list(APPEND LLVM_COMMON_DEPENDS ${target_name}_exports) set(LLVM_COMMON_DEPENDS ${LLVM_COMMON_DEPENDS} PARENT_SCOPE) endfunction(add_llvm_symbol_exports) if(NOT WIN32 AND NOT APPLE) execute_process( COMMAND ${CMAKE_C_COMPILER} -Wl,--version OUTPUT_VARIABLE stdout ERROR_QUIET ) if("${stdout}" MATCHES "GNU gold") set(LLVM_LINKER_IS_GOLD ON) endif() endif() function(add_link_opts target_name) # Don't use linker optimizations in debug builds since it slows down the # linker in a context where the optimizations are not important. if (NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG") # Pass -O3 to the linker. This enabled different optimizations on different # linkers. if(NOT (${CMAKE_SYSTEM_NAME} MATCHES "Darwin|SunOS" OR WIN32)) set_property(TARGET ${target_name} APPEND_STRING PROPERTY LINK_FLAGS " -Wl,-O3") endif() if(LLVM_LINKER_IS_GOLD) # With gold gc-sections is always safe. set_property(TARGET ${target_name} APPEND_STRING PROPERTY LINK_FLAGS " -Wl,--gc-sections") # Note that there is a bug with -Wl,--icf=safe so it is not safe # to enable. See https://sourceware.org/bugzilla/show_bug.cgi?id=17704. endif() if(NOT LLVM_NO_DEAD_STRIP) if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") # ld64's implementation of -dead_strip breaks tools that use plugins. set_property(TARGET ${target_name} APPEND_STRING PROPERTY LINK_FLAGS " -Wl,-dead_strip") elseif(${CMAKE_SYSTEM_NAME} MATCHES "SunOS") set_property(TARGET ${target_name} APPEND_STRING PROPERTY LINK_FLAGS " -Wl,-z -Wl,discard-unused=sections") elseif(NOT WIN32 AND NOT LLVM_LINKER_IS_GOLD) # Object files are compiled with -ffunction-data-sections. # Versions of bfd ld < 2.23.1 have a bug in --gc-sections that breaks # tools that use plugins. Always pass --gc-sections once we require # a newer linker. set_property(TARGET ${target_name} APPEND_STRING PROPERTY LINK_FLAGS " -Wl,--gc-sections") endif() endif() endif() endfunction(add_link_opts) # Set each output directory according to ${CMAKE_CONFIGURATION_TYPES}. # Note: Don't set variables CMAKE_*_OUTPUT_DIRECTORY any more, # or a certain builder, for eaxample, msbuild.exe, would be confused. function(set_output_directory target bindir libdir) # Do nothing if *_OUTPUT_INTDIR is empty. if("${bindir}" STREQUAL "") return() endif() # moddir -- corresponding to LIBRARY_OUTPUT_DIRECTORY. # It affects output of add_library(MODULE). if(WIN32 OR CYGWIN) # DLL platform set(moddir ${bindir}) else() set(moddir ${libdir}) endif() if(NOT "${CMAKE_CFG_INTDIR}" STREQUAL ".") foreach(build_mode ${CMAKE_CONFIGURATION_TYPES}) string(TOUPPER "${build_mode}" CONFIG_SUFFIX) string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} bi ${bindir}) string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} li ${libdir}) string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} mi ${moddir}) set_target_properties(${target} PROPERTIES "RUNTIME_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${bi}) set_target_properties(${target} PROPERTIES "ARCHIVE_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${li}) set_target_properties(${target} PROPERTIES "LIBRARY_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${mi}) endforeach() else() set_target_properties(${target} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${bindir}) set_target_properties(${target} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY ${libdir}) set_target_properties(${target} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${moddir}) endif() endfunction() # If on Windows and building with MSVC, add the resource script containing the # VERSIONINFO data to the project. This embeds version resource information # into the output .exe or .dll. # TODO: Enable for MinGW Windows builds too. # function(add_windows_version_resource_file OUT_VAR) set(sources ${ARGN}) if (WIN32) set(resource_file ${LLVM_SOURCE_DIR}/resources/windows_version_resource.rc) if(EXISTS ${resource_file}) set(sources ${sources} ${resource_file}) source_group("Resource Files" ${resource_file}) set(windows_resource_file ${resource_file} PARENT_SCOPE) endif() endif(WIN32) set(${OUT_VAR} ${sources} PARENT_SCOPE) endfunction(add_windows_version_resource_file) # set_windows_version_resource_properties(name resource_file... # VERSION_MAJOR int # Optional major version number (defaults to LLVM_VERSION_MAJOR) # VERSION_MINOR int # Optional minor version number (defaults to LLVM_VERSION_MINOR) # VERSION_PATCHLEVEL int # Optional patchlevel version number (defaults to LLVM_VERSION_PATCH) # VERSION_STRING # Optional version string (defaults to PACKAGE_VERSION) # PRODUCT_NAME # Optional product name string (defaults to "LLVM") # ) function(set_windows_version_resource_properties name resource_file) cmake_parse_arguments(ARG "" "VERSION_MAJOR;VERSION_MINOR;VERSION_PATCHLEVEL;VERSION_STRING;PRODUCT_NAME" "" ${ARGN}) if (NOT DEFINED ARG_VERSION_MAJOR) set(ARG_VERSION_MAJOR ${LLVM_VERSION_MAJOR}) endif() if (NOT DEFINED ARG_VERSION_MINOR) set(ARG_VERSION_MINOR ${LLVM_VERSION_MINOR}) endif() if (NOT DEFINED ARG_VERSION_PATCHLEVEL) set(ARG_VERSION_PATCHLEVEL ${LLVM_VERSION_PATCH}) endif() if (NOT DEFINED ARG_VERSION_STRING) set(ARG_VERSION_STRING ${PACKAGE_VERSION}) endif() if (NOT DEFINED ARG_PRODUCT_NAME) set(ARG_PRODUCT_NAME "LLVM") endif() if (MSVC) set_property(SOURCE ${resource_file} PROPERTY COMPILE_FLAGS /nologo) endif() set_property(SOURCE ${resource_file} PROPERTY COMPILE_DEFINITIONS "RC_VERSION_FIELD_1=${ARG_VERSION_MAJOR}" "RC_VERSION_FIELD_2=${ARG_VERSION_MINOR}" "RC_VERSION_FIELD_3=${ARG_VERSION_PATCHLEVEL}" "RC_VERSION_FIELD_4=0" "RC_FILE_VERSION=\"${ARG_VERSION_STRING}\"" "RC_INTERNAL_NAME=\"${name}\"" "RC_PRODUCT_NAME=\"${ARG_PRODUCT_NAME}\"" "RC_PRODUCT_VERSION=\"${ARG_VERSION_STRING}\"") # HLSL change begin - set common version if(${HLSL_EMBED_VERSION}) if (DEFINED resource_file) add_dependencies(${name} hlsl_version_autogen) set_property(SOURCE ${resource_file} PROPERTY COMPILE_DEFINITIONS "INCLUDE_HLSL_VERSION_FILE=1") set_property(SOURCE ${resource_file} PROPERTY COMPILE_OPTIONS "-I" "${HLSL_VERSION_LOCATION}") endif (DEFINED resource_file) endif(${HLSL_EMBED_VERSION}) # HLSL change ends endfunction(set_windows_version_resource_properties) # llvm_add_library(name sources... # SHARED;STATIC # STATIC by default w/o BUILD_SHARED_LIBS. # SHARED by default w/ BUILD_SHARED_LIBS. # MODULE # Target ${name} might not be created on unsupported platforms. # Check with "if(TARGET ${name})". # OUTPUT_NAME name # Corresponds to OUTPUT_NAME in target properties. # DEPENDS targets... # Same semantics as add_dependencies(). # LINK_COMPONENTS components... # Same as the variable LLVM_LINK_COMPONENTS. # LINK_LIBS lib_targets... # Same semantics as target_link_libraries(). # ADDITIONAL_HEADERS # May specify header files for IDE generators. # ) function(llvm_add_library name) cmake_parse_arguments(ARG "MODULE;SHARED;STATIC" "OUTPUT_NAME" "ADDITIONAL_HEADERS;DEPENDS;LINK_COMPONENTS;LINK_LIBS;OBJLIBS" ${ARGN}) list(APPEND LLVM_COMMON_DEPENDS ${ARG_DEPENDS}) if(ARG_ADDITIONAL_HEADERS) # Pass through ADDITIONAL_HEADERS. set(ARG_ADDITIONAL_HEADERS ADDITIONAL_HEADERS ${ARG_ADDITIONAL_HEADERS}) endif() if(ARG_OBJLIBS) set(ALL_FILES ${ARG_OBJLIBS}) else() llvm_process_sources(ALL_FILES ${ARG_UNPARSED_ARGUMENTS} ${ARG_ADDITIONAL_HEADERS}) endif() if(ARG_MODULE) if(ARG_SHARED OR ARG_STATIC) message(WARNING "MODULE with SHARED|STATIC doesn't make sense.") endif() if(NOT LLVM_ENABLE_PLUGINS) message(STATUS "${name} ignored -- Loadable modules not supported on this platform.") return() endif() else() if(BUILD_SHARED_LIBS AND NOT ARG_STATIC) set(ARG_SHARED TRUE) endif() if(NOT ARG_SHARED) set(ARG_STATIC TRUE) endif() endif() # Generate objlib if(ARG_SHARED AND ARG_STATIC) # Generate an obj library for both targets. set(obj_name "obj.${name}") add_library(${obj_name} OBJECT EXCLUDE_FROM_ALL ${ALL_FILES} ) llvm_update_compile_flags(${obj_name}) set(ALL_FILES "$<TARGET_OBJECTS:${obj_name}>") # Do add_dependencies(obj) later due to CMake issue 14747. list(APPEND objlibs ${obj_name}) set_target_properties(${obj_name} PROPERTIES FOLDER "Object Libraries") endif() if(ARG_SHARED AND ARG_STATIC) # static set(name_static "${name}_static") if(ARG_OUTPUT_NAME) set(output_name OUTPUT_NAME "${ARG_OUTPUT_NAME}") endif() # DEPENDS has been appended to LLVM_COMMON_LIBS. llvm_add_library(${name_static} STATIC ${output_name} OBJLIBS ${ALL_FILES} # objlib LINK_LIBS ${ARG_LINK_LIBS} LINK_COMPONENTS ${ARG_LINK_COMPONENTS} ) # FIXME: Add name_static to anywhere in TARGET ${name}'s PROPERTY. set(ARG_STATIC) endif() if(ARG_MODULE) add_library(${name} MODULE ${ALL_FILES}) elseif(ARG_SHARED) add_windows_version_resource_file(ALL_FILES ${ALL_FILES}) add_library(${name} SHARED ${ALL_FILES}) else() add_library(${name} STATIC ${ALL_FILES}) endif() if(DEFINED windows_resource_file) set_windows_version_resource_properties(${name} ${windows_resource_file}) set(windows_resource_file ${windows_resource_file} PARENT_SCOPE) endif() set_output_directory(${name} ${LLVM_RUNTIME_OUTPUT_INTDIR} ${LLVM_LIBRARY_OUTPUT_INTDIR}) llvm_update_compile_flags(${name}) add_link_opts( ${name} ) if(ARG_OUTPUT_NAME) set_target_properties(${name} PROPERTIES OUTPUT_NAME ${ARG_OUTPUT_NAME} ) endif() if(ARG_MODULE) set_target_properties(${name} PROPERTIES PREFIX "" SUFFIX ${LLVM_PLUGIN_EXT} ) endif() if(ARG_SHARED) if(WIN32) set_target_properties(${name} PROPERTIES PREFIX "" ) endif() # HLSL Change Begin - Don't generate so versioned files. set_target_properties(${name} PROPERTIES SOVERSION ${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR} VERSION ${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}.${LLVM_VERSION_PATCH}${LLVM_VERSION_SUFFIX} NO_SONAME On) if (APPLE) set_property(TARGET ${name} APPEND_STRING PROPERTY LINK_FLAGS " -Wl,-install_name,@rpath/${CMAKE_SHARED_LIBRARY_PREFIX}${name}${CMAKE_SHARED_LIBRARY_SUFFIX}") elseif(UNIX) set_property(TARGET ${name} APPEND_STRING PROPERTY LINK_FLAGS " -Wl,-soname,${CMAKE_SHARED_LIBRARY_PREFIX}${name}${CMAKE_SHARED_LIBRARY_SUFFIX}") endif() # HLSL Change End - Don't generate so versioned files. endif() if(ARG_MODULE OR ARG_SHARED) # Do not add -Dname_EXPORTS to the command-line when building files in this # target. Doing so is actively harmful for the modules build because it # creates extra module variants, and not useful because we don't use these # macros. set_target_properties( ${name} PROPERTIES DEFINE_SYMBOL "" ) if (LLVM_EXPORTED_SYMBOL_FILE) add_llvm_symbol_exports( ${name} ${LLVM_EXPORTED_SYMBOL_FILE} ) endif() endif() # Add the explicit dependency information for this library. # # It would be nice to verify that we have the dependencies for this library # name, but using get_property(... SET) doesn't suffice to determine if a # property has been set to an empty value. get_property(lib_deps GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_${name}) llvm_map_components_to_libnames(llvm_libs ${ARG_LINK_COMPONENTS} ${LLVM_LINK_COMPONENTS} ) if(CMAKE_VERSION VERSION_LESS 2.8.12) # Link libs w/o keywords, assuming PUBLIC. target_link_libraries(${name} ${ARG_LINK_LIBS} ${lib_deps} ${llvm_libs} ) elseif(ARG_STATIC) target_link_libraries(${name} INTERFACE ${ARG_LINK_LIBS} ${lib_deps} ${llvm_libs} ) else() # We can use PRIVATE since SO knows its dependent libs. target_link_libraries(${name} PRIVATE ${ARG_LINK_LIBS} ${lib_deps} ${llvm_libs} ) endif() if(LLVM_COMMON_DEPENDS) add_dependencies(${name} ${LLVM_COMMON_DEPENDS}) # Add dependencies also to objlibs. # CMake issue 14747 -- add_dependencies() might be ignored to objlib's user. foreach(objlib ${objlibs}) add_dependencies(${objlib} ${LLVM_COMMON_DEPENDS}) endforeach() endif() endfunction() macro(add_llvm_library name) cmake_parse_arguments(ARG "SHARED" "" "" ${ARGN}) if( BUILD_SHARED_LIBS ) llvm_add_library(${name} SHARED ${ARGN}) else() llvm_add_library(${name} ${ARGN}) endif() # The gtest libraries should not be installed or exported as a target if ("${name}" STREQUAL gtest OR "${name}" STREQUAL gtest_main) set(_is_gtest TRUE) else() set(_is_gtest FALSE) set_property( GLOBAL APPEND PROPERTY LLVM_LIBS ${name} ) endif() if( EXCLUDE_FROM_ALL ) set_target_properties( ${name} PROPERTIES EXCLUDE_FROM_ALL ON) elseif(NOT _is_gtest) if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY OR ${name} STREQUAL "LTO") if(ARG_SHARED OR BUILD_SHARED_LIBS) if(WIN32 OR CYGWIN) set(install_type RUNTIME) else() set(install_type LIBRARY) endif() else() set(install_type ARCHIVE) endif() install(TARGETS ${name} EXPORT LLVMExports ${install_type} DESTINATION lib${LLVM_LIBDIR_SUFFIX} COMPONENT ${name}) if (NOT CMAKE_CONFIGURATION_TYPES) add_custom_target(install-${name} DEPENDS ${name} COMMAND "${CMAKE_COMMAND}" -DCMAKE_INSTALL_COMPONENT=${name} -P "${CMAKE_BINARY_DIR}/cmake_install.cmake") endif() endif() set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name}) endif() set_target_properties(${name} PROPERTIES FOLDER "Libraries") endmacro(add_llvm_library name) macro(add_llvm_loadable_module name) llvm_add_library(${name} MODULE ${ARGN}) if(NOT TARGET ${name}) # Add empty "phony" target add_custom_target(${name}) else() if( EXCLUDE_FROM_ALL ) set_target_properties( ${name} PROPERTIES EXCLUDE_FROM_ALL ON) else() if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY) if(WIN32 OR CYGWIN) # DLL platform set(dlldir "bin") else() set(dlldir "lib${LLVM_LIBDIR_SUFFIX}") endif() install(TARGETS ${name} EXPORT LLVMExports LIBRARY DESTINATION ${dlldir} ARCHIVE DESTINATION lib${LLVM_LIBDIR_SUFFIX}) endif() set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name}) endif() endif() set_target_properties(${name} PROPERTIES FOLDER "Loadable modules") endmacro(add_llvm_loadable_module name) macro(add_llvm_executable name) llvm_process_sources( ALL_FILES ${ARGN} ) add_windows_version_resource_file(ALL_FILES ${ALL_FILES}) if( EXCLUDE_FROM_ALL ) add_executable(${name} EXCLUDE_FROM_ALL ${ALL_FILES}) else() add_executable(${name} ${ALL_FILES}) endif() if(DEFINED windows_resource_file) set_windows_version_resource_properties(${name} ${windows_resource_file}) endif() llvm_update_compile_flags(${name}) add_link_opts( ${name} ) # Do not add -Dname_EXPORTS to the command-line when building files in this # target. Doing so is actively harmful for the modules build because it # creates extra module variants, and not useful because we don't use these # macros. set_target_properties( ${name} PROPERTIES DEFINE_SYMBOL "" ) if (LLVM_EXPORTED_SYMBOL_FILE) add_llvm_symbol_exports( ${name} ${LLVM_EXPORTED_SYMBOL_FILE} ) endif(LLVM_EXPORTED_SYMBOL_FILE) set(EXCLUDE_FROM_ALL OFF) set_output_directory(${name} ${LLVM_RUNTIME_OUTPUT_INTDIR} ${LLVM_LIBRARY_OUTPUT_INTDIR}) llvm_config( ${name} ${LLVM_LINK_COMPONENTS} ) if( LLVM_COMMON_DEPENDS ) add_dependencies( ${name} ${LLVM_COMMON_DEPENDS} ) endif( LLVM_COMMON_DEPENDS ) endmacro(add_llvm_executable name) function(export_executable_symbols target) if (NOT MSVC) # MSVC's linker doesn't support exporting all symbols. set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1) endif() endfunction() set (LLVM_TOOLCHAIN_TOOLS llvm-ar llvm-objdump ) macro(add_llvm_tool name) if( NOT LLVM_BUILD_TOOLS ) set(EXCLUDE_FROM_ALL ON) endif() add_llvm_executable(${name} ${ARGN}) list(FIND LLVM_TOOLCHAIN_TOOLS ${name} LLVM_IS_${name}_TOOLCHAIN_TOOL) if (LLVM_IS_${name}_TOOLCHAIN_TOOL GREATER -1 OR NOT LLVM_INSTALL_TOOLCHAIN_ONLY) if( LLVM_BUILD_TOOLS ) install(TARGETS ${name} EXPORT LLVMExports RUNTIME DESTINATION bin COMPONENT ${name}) if (NOT CMAKE_CONFIGURATION_TYPES) add_custom_target(install-${name} DEPENDS ${name} COMMAND "${CMAKE_COMMAND}" -DCMAKE_INSTALL_COMPONENT=${name} -P "${CMAKE_BINARY_DIR}/cmake_install.cmake") endif() endif() endif() if( LLVM_BUILD_TOOLS ) set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name}) endif() set_target_properties(${name} PROPERTIES FOLDER "Tools") endmacro(add_llvm_tool name) macro(add_llvm_example name) if( NOT LLVM_BUILD_EXAMPLES ) set(EXCLUDE_FROM_ALL ON) endif() add_llvm_executable(${name} ${ARGN}) if( LLVM_BUILD_EXAMPLES ) install(TARGETS ${name} RUNTIME DESTINATION examples) endif() set_target_properties(${name} PROPERTIES FOLDER "Examples") endmacro(add_llvm_example name) macro(add_llvm_utility name) add_llvm_executable(${name} ${ARGN}) set_target_properties(${name} PROPERTIES FOLDER "Utils") if( LLVM_INSTALL_UTILS ) install (TARGETS ${name} RUNTIME DESTINATION bin COMPONENT ${name}) if (NOT CMAKE_CONFIGURATION_TYPES) add_custom_target(install-${name} DEPENDS ${name} COMMAND "${CMAKE_COMMAND}" -DCMAKE_INSTALL_COMPONENT=${name} -P "${CMAKE_BINARY_DIR}/cmake_install.cmake") endif() endif() endmacro(add_llvm_utility name) macro(add_llvm_target target_name) include_directories(BEFORE ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}) add_llvm_library(LLVM${target_name} ${ARGN}) set( CURRENT_LLVM_TARGET LLVM${target_name} ) endmacro(add_llvm_target) # Add external project that may want to be built as part of llvm such as Clang, # lld, and Polly. This adds two options. One for the source directory of the # project, which defaults to ${CMAKE_CURRENT_SOURCE_DIR}/${name}. Another to # enable or disable building it with everything else. # Additional parameter can be specified as the name of directory. macro(add_llvm_external_project name) set(add_llvm_external_dir "${ARGN}") if("${add_llvm_external_dir}" STREQUAL "") set(add_llvm_external_dir ${name}) endif() list(APPEND LLVM_IMPLICIT_PROJECT_IGNORE "${CMAKE_CURRENT_SOURCE_DIR}/${add_llvm_external_dir}") string(REPLACE "-" "_" nameUNDERSCORE ${name}) string(TOUPPER ${nameUNDERSCORE} nameUPPER) #TODO: Remove this check in a few days once it has circulated through # buildbots and people's checkouts (cbieneman - July 14, 2015) if("${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}" STREQUAL "${CMAKE_CURRENT_SOURCE_DIR}/${add_llvm_external_dir}") unset(LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR CACHE) endif() if(NOT LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR) set(LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/${add_llvm_external_dir}") else() set(LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR CACHE PATH "Path to ${name} source directory") endif() if (EXISTS ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}/CMakeLists.txt) option(LLVM_EXTERNAL_${nameUPPER}_BUILD "Whether to build ${name} as part of LLVM" ON) if (LLVM_EXTERNAL_${nameUPPER}_BUILD) add_subdirectory(${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR} ${add_llvm_external_dir}) endif() endif() endmacro(add_llvm_external_project) macro(add_llvm_tool_subdirectory name) list(APPEND LLVM_IMPLICIT_PROJECT_IGNORE "${CMAKE_CURRENT_SOURCE_DIR}/${name}") add_subdirectory(${name}) endmacro(add_llvm_tool_subdirectory) macro(ignore_llvm_tool_subdirectory name) list(APPEND LLVM_IMPLICIT_PROJECT_IGNORE "${CMAKE_CURRENT_SOURCE_DIR}/${name}") endmacro(ignore_llvm_tool_subdirectory) function(add_llvm_implicit_external_projects) set(list_of_implicit_subdirs "") file(GLOB sub-dirs "${CMAKE_CURRENT_SOURCE_DIR}/*") foreach(dir ${sub-dirs}) if(IS_DIRECTORY "${dir}") list(FIND LLVM_IMPLICIT_PROJECT_IGNORE "${dir}" tool_subdir_ignore) if( tool_subdir_ignore EQUAL -1 AND EXISTS "${dir}/CMakeLists.txt") get_filename_component(fn "${dir}" NAME) list(APPEND list_of_implicit_subdirs "${fn}") endif() endif() endforeach() foreach(external_proj ${list_of_implicit_subdirs}) add_llvm_external_project("${external_proj}") endforeach() endfunction(add_llvm_implicit_external_projects) # Generic support for adding a unittest. function(add_unittest test_suite test_name) if( NOT LLVM_BUILD_TESTS AND NOT SPIRV_BUILD_TESTS ) # SPIRV change set(EXCLUDE_FROM_ALL ON) endif() include_directories(${LLVM_MAIN_SRC_DIR}/utils/unittest/googletest/include) include_directories(${LLVM_MAIN_SRC_DIR}/utils/unittest/googlemock/include) # HLSL Change - Pulled in from LLVM 4.0 if (NOT LLVM_ENABLE_THREADS) list(APPEND LLVM_COMPILE_DEFINITIONS GTEST_HAS_PTHREAD=0) endif () if (SUPPORTS_NO_VARIADIC_MACROS_FLAG) list(APPEND LLVM_COMPILE_FLAGS "-Wno-variadic-macros") endif () set(LLVM_REQUIRES_RTTI OFF) add_llvm_executable(${test_name} ${ARGN}) set(outdir ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}) set_output_directory(${test_name} ${outdir} ${outdir}) target_link_libraries(${test_name} gtest gtest_main LLVMSupport # gtest needs it for raw_ostream. ) add_dependencies(${test_suite} ${test_name}) get_target_property(test_suite_folder ${test_suite} FOLDER) if (NOT ${test_suite_folder} STREQUAL "NOTFOUND") set_property(TARGET ${test_name} PROPERTY FOLDER "${test_suite_folder}") endif () endfunction() function(llvm_add_go_executable binary pkgpath) cmake_parse_arguments(ARG "ALL" "" "DEPENDS;GOFLAGS" ${ARGN}) if(LLVM_BINDINGS MATCHES "go") # FIXME: This should depend only on the libraries Go needs. get_property(llvmlibs GLOBAL PROPERTY LLVM_LIBS) set(binpath ${CMAKE_BINARY_DIR}/bin/${binary}${CMAKE_EXECUTABLE_SUFFIX}) set(cc "${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1}") set(cxx "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1}") set(cppflags "") get_property(include_dirs DIRECTORY PROPERTY INCLUDE_DIRECTORIES) foreach(d ${include_dirs}) set(cppflags "${cppflags} -I${d}") endforeach(d) set(ldflags "${CMAKE_EXE_LINKER_FLAGS}") add_custom_command(OUTPUT ${binpath} COMMAND ${CMAKE_BINARY_DIR}/bin/llvm-go "cc=${cc}" "cxx=${cxx}" "cppflags=${cppflags}" "ldflags=${ldflags}" ${ARG_GOFLAGS} build -o ${binpath} ${pkgpath} DEPENDS llvm-config ${CMAKE_BINARY_DIR}/bin/llvm-go${CMAKE_EXECUTABLE_SUFFIX} ${llvmlibs} ${ARG_DEPENDS} COMMENT "Building Go executable ${binary}" VERBATIM) if (ARG_ALL) add_custom_target(${binary} ALL DEPENDS ${binpath}) else() add_custom_target(${binary} DEPENDS ${binpath}) endif() endif() endfunction() # This function provides an automatic way to 'configure'-like generate a file # based on a set of common and custom variables, specifically targeting the # variables needed for the 'lit.site.cfg' files. This function bundles the # common variables that any Lit instance is likely to need, and custom # variables can be passed in. function(configure_lit_site_cfg input output) foreach(c ${LLVM_TARGETS_TO_BUILD}) set(TARGETS_BUILT "${TARGETS_BUILT} ${c}") endforeach(c) set(TARGETS_TO_BUILD ${TARGETS_BUILT}) set(SHLIBEXT "${LTDL_SHLIB_EXT}") # Configuration-time: See Unit/lit.site.cfg.in if (CMAKE_CFG_INTDIR STREQUAL ".") set(LLVM_BUILD_MODE ".") else () set(LLVM_BUILD_MODE "%(build_mode)s") endif () # They below might not be the build tree but provided binary tree. set(LLVM_SOURCE_DIR ${LLVM_MAIN_SRC_DIR}) set(LLVM_BINARY_DIR ${LLVM_BINARY_DIR}) string(REPLACE ${CMAKE_CFG_INTDIR} ${LLVM_BUILD_MODE} LLVM_TOOLS_DIR ${LLVM_TOOLS_BINARY_DIR}) string(REPLACE ${CMAKE_CFG_INTDIR} ${LLVM_BUILD_MODE} LLVM_LIBS_DIR ${LLVM_LIBRARY_DIR}) # SHLIBDIR points the build tree. string(REPLACE ${CMAKE_CFG_INTDIR} ${LLVM_BUILD_MODE} SHLIBDIR "${LLVM_SHLIB_OUTPUT_INTDIR}") # FIXME: "ENABLE_SHARED" doesn't make sense, since it is used just for # plugins. We may rename it. if(LLVM_ENABLE_PLUGINS) set(ENABLE_SHARED "1") else() set(ENABLE_SHARED "0") endif() if(LLVM_ENABLE_ASSERTIONS AND NOT MSVC_IDE) set(ENABLE_ASSERTIONS "1") else() set(ENABLE_ASSERTIONS "0") endif() set(HOST_OS ${CMAKE_SYSTEM_NAME}) set(HOST_ARCH ${CMAKE_SYSTEM_PROCESSOR}) set(HOST_CC "${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1}") set(HOST_CXX "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1}") set(HOST_LDFLAGS "${CMAKE_EXE_LINKER_FLAGS}") configure_file(${input} ${output} @ONLY) endfunction() # A raw function to create a lit target. This is used to implement the testuite # management functions. function(add_lit_target target comment) cmake_parse_arguments(ARG "" "" "PARAMS;DEPENDS;ARGS" ${ARGN}) set(LIT_ARGS "${ARG_ARGS} ${LLVM_LIT_ARGS}") separate_arguments(LIT_ARGS) if (NOT CMAKE_CFG_INTDIR STREQUAL ".") list(APPEND LIT_ARGS --param build_mode=${CMAKE_CFG_INTDIR}) endif () if (LLVM_MAIN_SRC_DIR) set (LIT_COMMAND ${Python3_EXECUTABLE} ${LLVM_MAIN_SRC_DIR}/utils/lit/lit.py) else() find_program(LIT_COMMAND llvm-lit) endif () list(APPEND LIT_COMMAND ${LIT_ARGS}) foreach(param ${ARG_PARAMS}) list(APPEND LIT_COMMAND --param ${param}) endforeach() if (ARG_UNPARSED_ARGUMENTS) add_custom_target(${target} COMMAND ${LIT_COMMAND} ${ARG_UNPARSED_ARGUMENTS} COMMENT "${comment}" ${cmake_3_2_USES_TERMINAL} ) else() add_custom_target(${target} COMMAND ${CMAKE_COMMAND} -E echo "${target} does nothing, no tools built.") message(STATUS "${target} does nothing.") endif() if (ARG_DEPENDS) add_dependencies(${target} ${ARG_DEPENDS}) endif() # Tests should be excluded from "Build Solution". set_target_properties(${target} PROPERTIES EXCLUDE_FROM_DEFAULT_BUILD ON) endfunction() # A function to add a set of lit test suites to be driven through 'check-*' targets. function(add_lit_testsuite target comment) cmake_parse_arguments(ARG "" "" "PARAMS;DEPENDS;ARGS" ${ARGN}) # EXCLUDE_FROM_ALL excludes the test ${target} out of check-all. if(NOT EXCLUDE_FROM_ALL) # Register the testsuites, params and depends for the global check rule. set_property(GLOBAL APPEND PROPERTY LLVM_LIT_TESTSUITES ${ARG_UNPARSED_ARGUMENTS}) set_property(GLOBAL APPEND PROPERTY LLVM_LIT_PARAMS ${ARG_PARAMS}) set_property(GLOBAL APPEND PROPERTY LLVM_LIT_DEPENDS ${ARG_DEPENDS}) set_property(GLOBAL APPEND PROPERTY LLVM_LIT_EXTRA_ARGS ${ARG_ARGS}) endif() # Produce a specific suffixed check rule. add_lit_target(${target} ${comment} ${ARG_UNPARSED_ARGUMENTS} PARAMS ${ARG_PARAMS} DEPENDS ${ARG_DEPENDS} ARGS ${ARG_ARGS} ) endfunction() function(add_lit_testsuites project directory) if (NOT CMAKE_CONFIGURATION_TYPES) cmake_parse_arguments(ARG "EXCLUDE_FROM_CHECK_ALL" "FOLDER" "PARAMS;DEPENDS;ARGS" ${ARGN}) if (NOT ARG_FOLDER) set(ARG_FOLDER "Test Subdirectories") endif() # Search recursively for test directories by assuming anything not # in a directory called Inputs contains tests. file(GLOB_RECURSE to_process LIST_DIRECTORIES true ${directory}/*) foreach(lit_suite ${to_process}) if(NOT IS_DIRECTORY ${lit_suite}) continue() endif() string(FIND ${lit_suite} Inputs is_inputs) string(FIND ${lit_suite} Output is_output) if (NOT (is_inputs EQUAL -1 AND is_output EQUAL -1)) continue() endif() # Create a check- target for the directory. string(REPLACE ${directory} "" name_slash ${lit_suite}) if (name_slash) string(REPLACE "/" "-" name_slash ${name_slash}) string(REPLACE "\\" "-" name_dashes ${name_slash}) string(TOLOWER "${project}${name_dashes}" name_var) add_lit_target("check-${name_var}" "Running lit suite ${lit_suite}" ${lit_suite} ${EXCLUDE_FROM_CHECK_ALL} PARAMS ${ARG_PARAMS} DEPENDS ${ARG_DEPENDS} ARGS ${ARG_ARGS} ) set_target_properties(check-${name_var} PROPERTIES FOLDER ${ARG_FOLDER}) endif() endforeach() endif() endfunction()
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/FindOCaml.cmake
# CMake find_package() module for the OCaml language. # Assumes ocamlfind will be used for compilation. # http://ocaml.org/ # # Example usage: # # find_package(OCaml) # # If successful, the following variables will be defined: # OCAMLFIND # OCAML_VERSION # OCAML_STDLIB_PATH # HAVE_OCAMLOPT # # Also provides find_ocamlfind_package() macro. # # Example usage: # # find_ocamlfind_package(ctypes) # # In any case, the following variables are defined: # # HAVE_OCAML_${pkg} # # If successful, the following variables will be defined: # # OCAML_${pkg}_VERSION include( FindPackageHandleStandardArgs ) find_program(OCAMLFIND NAMES ocamlfind) if( OCAMLFIND ) execute_process( COMMAND ${OCAMLFIND} ocamlc -version OUTPUT_VARIABLE OCAML_VERSION OUTPUT_STRIP_TRAILING_WHITESPACE) execute_process( COMMAND ${OCAMLFIND} ocamlc -where OUTPUT_VARIABLE OCAML_STDLIB_PATH OUTPUT_STRIP_TRAILING_WHITESPACE) execute_process( COMMAND ${OCAMLFIND} ocamlc -version OUTPUT_QUIET RESULT_VARIABLE find_ocaml_result) if( find_ocaml_result EQUAL 0 ) set(HAVE_OCAMLOPT TRUE) else() set(HAVE_OCAMLOPT FALSE) endif() endif() find_package_handle_standard_args( OCaml DEFAULT_MSG OCAMLFIND OCAML_VERSION OCAML_STDLIB_PATH) mark_as_advanced( OCAMLFIND) function(find_ocamlfind_package pkg) CMAKE_PARSE_ARGUMENTS(ARG "OPTIONAL" "VERSION" "" ${ARGN}) execute_process( COMMAND "${OCAMLFIND}" "query" "${pkg}" "-format" "%v" RESULT_VARIABLE result OUTPUT_VARIABLE version ERROR_VARIABLE error OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_STRIP_TRAILING_WHITESPACE) if( NOT result EQUAL 0 AND NOT ARG_OPTIONAL ) message(FATAL_ERROR ${error}) endif() if( result EQUAL 0 ) set(found TRUE) else() set(found FALSE) endif() if( found AND ARG_VERSION ) if( version VERSION_LESS ARG_VERSION AND ARG_OPTIONAL ) # If it's optional and the constraint is not satisfied, pretend # it wasn't found. set(found FALSE) elseif( version VERSION_LESS ARG_VERSION ) message(FATAL_ERROR "ocamlfind package ${pkg} should have version ${ARG_VERSION} or newer") endif() endif() string(TOUPPER ${pkg} pkg) set(HAVE_OCAML_${pkg} ${found} PARENT_SCOPE) set(OCAML_${pkg}_VERSION ${version} PARENT_SCOPE) endfunction()
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/GetSVN.cmake
# CMake project that writes Subversion revision information to a header. # # Input variables: # FIRST_SOURCE_DIR - First source directory # FIRST_NAME - The macro prefix for the first repository's info # SECOND_SOURCE_DIR - Second source directory (opt) # SECOND_NAME - The macro prefix for the second repository's info (opt) # HEADER_FILE - The header file to write # # The output header will contain macros FIRST_REPOSITORY and FIRST_REVISION, # and SECOND_REPOSITORY and SECOND_REVISION if requested, where "FIRST" and # "SECOND" are substituted with the names specified in the input variables. # Chop off cmake/modules/GetSVN.cmake get_filename_component(LLVM_DIR "${CMAKE_SCRIPT_MODE_FILE}" PATH) get_filename_component(LLVM_DIR "${LLVM_DIR}" PATH) get_filename_component(LLVM_DIR "${LLVM_DIR}" PATH) # Handle strange terminals set(ENV{TERM} "dumb") macro(get_source_info_svn path revision repository) # If svn is a bat file, find_program(Subversion) doesn't find it. # Explicitly search for that here; Subversion_SVN_EXECUTABLE will override # the find_program call in FindSubversion.cmake. find_program(Subversion_SVN_EXECUTABLE NAMES svn svn.bat) # FindSubversion does not work with symlinks. See PR 8437 if (NOT IS_SYMLINK "${path}") find_package(Subversion) endif() if (Subversion_FOUND) subversion_wc_info( ${path} Project ) if (Project_WC_REVISION) set(${revision} ${Project_WC_REVISION} PARENT_SCOPE) endif() if (Project_WC_URL) set(${repository} ${Project_WC_URL} PARENT_SCOPE) endif() endif() endmacro() macro(get_source_info_git_svn path revision repository) find_program(git_executable NAMES git git.exe git.cmd) if (git_executable) execute_process(COMMAND ${git_executable} svn info WORKING_DIRECTORY ${path} TIMEOUT 5 RESULT_VARIABLE git_result OUTPUT_VARIABLE git_output) if (git_result EQUAL 0) string(REGEX REPLACE "^(.*\n)?Revision: ([^\n]+).*" "\\2" git_svn_rev "${git_output}") set(${revision} ${git_svn_rev} PARENT_SCOPE) string(REGEX REPLACE "^(.*\n)?URL: ([^\n]+).*" "\\2" git_url "${git_output}") set(${repository} ${git_url} PARENT_SCOPE) endif() endif() endmacro() macro(get_source_info_git path revision repository) find_program(git_executable NAMES git git.exe git.cmd) if (git_executable) execute_process(COMMAND ${git_executable} log -1 --pretty=format:%H WORKING_DIRECTORY ${path} TIMEOUT 5 RESULT_VARIABLE git_result OUTPUT_VARIABLE git_output) if (git_result EQUAL 0) set(${revision} ${git_output} PARENT_SCOPE) endif() execute_process(COMMAND ${git_executable} remote -v WORKING_DIRECTORY ${path} TIMEOUT 5 RESULT_VARIABLE git_result OUTPUT_VARIABLE git_output) if (git_result EQUAL 0) string(REGEX REPLACE "^(.*\n)?[^ \t]+[ \t]+([^ \t\n]+)[ \t]+\\(fetch\\).*" "\\2" git_url "${git_output}") set(${repository} "${git_url}" PARENT_SCOPE) endif() endif() endmacro() function(get_source_info path revision repository) if (EXISTS "${path}/.svn") get_source_info_svn("${path}" revision repository) elseif (EXISTS "${path}/.git/svn") get_source_info_git_svn("${path}" revision repository) elseif (EXISTS "${path}/.git") get_source_info_git("${path}" revision repository) endif() endfunction() function(append_info name path) get_source_info("${path}" revision repository) string(STRIP "${revision}" revision) string(STRIP "${repository}" repository) file(APPEND "${HEADER_FILE}.txt" "#define ${name}_REVISION \"${revision}\"\n") file(APPEND "${HEADER_FILE}.txt" "#define ${name}_REPOSITORY \"${repository}\"\n") endfunction() append_info(${FIRST_NAME} "${FIRST_SOURCE_DIR}") if(DEFINED SECOND_SOURCE_DIR) append_info(${SECOND_NAME} "${SECOND_SOURCE_DIR}") endif() # Copy the file only if it has changed. execute_process(COMMAND ${CMAKE_COMMAND} -E copy_if_different "${HEADER_FILE}.txt" "${HEADER_FILE}") file(REMOVE "${HEADER_FILE}.txt")
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/LLVM-Config.cmake
function(get_system_libs return_var) message(AUTHOR_WARNING "get_system_libs no longer needed") set(${return_var} "" PARENT_SCOPE) endfunction() function(link_system_libs target) message(AUTHOR_WARNING "link_system_libs no longer needed") endfunction() function(is_llvm_target_library library return_var) # Sets variable `return_var' to ON if `library' corresponds to a # LLVM supported target. To OFF if it doesn't. set(${return_var} OFF PARENT_SCOPE) string(TOUPPER "${library}" capitalized_lib) string(TOUPPER "${LLVM_ALL_TARGETS}" targets) foreach(t ${targets}) if( capitalized_lib STREQUAL t OR capitalized_lib STREQUAL "LLVM${t}" OR capitalized_lib STREQUAL "LLVM${t}CODEGEN" OR capitalized_lib STREQUAL "LLVM${t}ASMPARSER" OR capitalized_lib STREQUAL "LLVM${t}ASMPRINTER" OR capitalized_lib STREQUAL "LLVM${t}DISASSEMBLER" OR capitalized_lib STREQUAL "LLVM${t}INFO" ) set(${return_var} ON PARENT_SCOPE) break() endif() endforeach() endfunction(is_llvm_target_library) macro(llvm_config executable) explicit_llvm_config(${executable} ${ARGN}) endmacro(llvm_config) function(explicit_llvm_config executable) set( link_components ${ARGN} ) llvm_map_components_to_libnames(LIBRARIES ${link_components}) get_target_property(t ${executable} TYPE) if("x${t}" STREQUAL "xSTATIC_LIBRARY") target_link_libraries(${executable} INTERFACE ${LIBRARIES}) elseif("x${t}" STREQUAL "xSHARED_LIBRARY" OR "x${t}" STREQUAL "xMODULE_LIBRARY") target_link_libraries(${executable} PRIVATE ${LIBRARIES}) else() # Use plain form for legacy user. target_link_libraries(${executable} ${LIBRARIES}) endif() endfunction(explicit_llvm_config) # This is Deprecated function(llvm_map_components_to_libraries OUT_VAR) message(AUTHOR_WARNING "Using llvm_map_components_to_libraries() is deprecated. Use llvm_map_components_to_libnames() instead") explicit_map_components_to_libraries(result ${ARGN}) set( ${OUT_VAR} ${result} ${sys_result} PARENT_SCOPE ) endfunction(llvm_map_components_to_libraries) # This is a variant intended for the final user: # Map LINK_COMPONENTS to actual libnames. function(llvm_map_components_to_libnames out_libs) set( link_components ${ARGN} ) if(NOT LLVM_AVAILABLE_LIBS) # Inside LLVM itself available libs are in a global property. get_property(LLVM_AVAILABLE_LIBS GLOBAL PROPERTY LLVM_LIBS) endif() string(TOUPPER "${LLVM_AVAILABLE_LIBS}" capitalized_libs) # Expand some keywords: list(FIND LLVM_TARGETS_TO_BUILD "${LLVM_NATIVE_ARCH}" have_native_backend) list(FIND link_components "engine" engine_required) if( NOT engine_required EQUAL -1 ) list(FIND LLVM_TARGETS_WITH_JIT "${LLVM_NATIVE_ARCH}" have_jit) if( NOT have_native_backend EQUAL -1 AND NOT have_jit EQUAL -1 ) list(APPEND link_components "jit") list(APPEND link_components "native") else() list(APPEND link_components "interpreter") endif() endif() list(FIND link_components "native" native_required) if( NOT native_required EQUAL -1 ) if( NOT have_native_backend EQUAL -1 ) list(APPEND link_components ${LLVM_NATIVE_ARCH}) endif() endif() # Translate symbolic component names to real libraries: foreach(c ${link_components}) # add codegen, asmprinter, asmparser, disassembler list(FIND LLVM_TARGETS_TO_BUILD ${c} idx) if( NOT idx LESS 0 ) if( TARGET LLVM${c}CodeGen ) list(APPEND expanded_components "LLVM${c}CodeGen") else() if( TARGET LLVM${c} ) list(APPEND expanded_components "LLVM${c}") elseif( NOT c STREQUAL "None" ) # HLSL Change message(FATAL_ERROR "Target ${c} is not in the set of libraries.") endif() endif() if( TARGET LLVM${c}AsmPrinter ) list(APPEND expanded_components "LLVM${c}AsmPrinter") endif() if( TARGET LLVM${c}AsmParser ) list(APPEND expanded_components "LLVM${c}AsmParser") endif() if( TARGET LLVM${c}Desc ) list(APPEND expanded_components "LLVM${c}Desc") endif() if( TARGET LLVM${c}Info ) list(APPEND expanded_components "LLVM${c}Info") endif() if( TARGET LLVM${c}Disassembler ) list(APPEND expanded_components "LLVM${c}Disassembler") endif() elseif( c STREQUAL "native" ) # already processed elseif( c STREQUAL "nativecodegen" ) list(APPEND expanded_components "LLVM${LLVM_NATIVE_ARCH}CodeGen") if( TARGET LLVM${LLVM_NATIVE_ARCH}Desc ) list(APPEND expanded_components "LLVM${LLVM_NATIVE_ARCH}Desc") endif() if( TARGET LLVM${LLVM_NATIVE_ARCH}Info ) list(APPEND expanded_components "LLVM${LLVM_NATIVE_ARCH}Info") endif() elseif( c STREQUAL "backend" ) # same case as in `native'. elseif( c STREQUAL "engine" ) # already processed elseif( c STREQUAL "all" ) list(APPEND expanded_components ${LLVM_AVAILABLE_LIBS}) elseif( c STREQUAL "AllTargetsAsmPrinters" ) # Link all the asm printers from all the targets foreach(t ${LLVM_TARGETS_TO_BUILD}) if( TARGET LLVM${t}AsmPrinter ) list(APPEND expanded_components "LLVM${t}AsmPrinter") endif() endforeach(t) elseif( c STREQUAL "AllTargetsAsmParsers" ) # Link all the asm parsers from all the targets foreach(t ${LLVM_TARGETS_TO_BUILD}) if( TARGET LLVM${t}AsmParser ) list(APPEND expanded_components "LLVM${t}AsmParser") endif() endforeach(t) elseif( c STREQUAL "AllTargetsDescs" ) # Link all the descs from all the targets foreach(t ${LLVM_TARGETS_TO_BUILD}) if( TARGET LLVM${t}Desc ) list(APPEND expanded_components "LLVM${t}Desc") endif() endforeach(t) elseif( c STREQUAL "AllTargetsDisassemblers" ) # Link all the disassemblers from all the targets foreach(t ${LLVM_TARGETS_TO_BUILD}) if( TARGET LLVM${t}Disassembler ) list(APPEND expanded_components "LLVM${t}Disassembler") endif() endforeach(t) elseif( c STREQUAL "AllTargetsInfos" ) # Link all the infos from all the targets foreach(t ${LLVM_TARGETS_TO_BUILD}) if( TARGET LLVM${t}Info ) list(APPEND expanded_components "LLVM${t}Info") endif() endforeach(t) else( NOT idx LESS 0 ) # Canonize the component name: string(TOUPPER "${c}" capitalized) list(FIND capitalized_libs LLVM${capitalized} lib_idx) if( lib_idx LESS 0 ) # The component is unknown. Maybe is an omitted target? is_llvm_target_library(${c} iltl_result) if( NOT iltl_result ) message(FATAL_ERROR "Library `${c}' not found in list of llvm libraries.") endif() else( lib_idx LESS 0 ) list(GET LLVM_AVAILABLE_LIBS ${lib_idx} canonical_lib) list(APPEND expanded_components ${canonical_lib}) endif( lib_idx LESS 0 ) endif( NOT idx LESS 0 ) endforeach(c) set(${out_libs} ${expanded_components} PARENT_SCOPE) endfunction() # Perform a post-order traversal of the dependency graph. # This duplicates the algorithm used by llvm-config, originally # in tools/llvm-config/llvm-config.cpp, function ComputeLibsForComponents. function(expand_topologically name required_libs visited_libs) list(FIND visited_libs ${name} found) if( found LESS 0 ) list(APPEND visited_libs ${name}) set(visited_libs ${visited_libs} PARENT_SCOPE) get_property(lib_deps GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_${name}) foreach( lib_dep ${lib_deps} ) expand_topologically(${lib_dep} "${required_libs}" "${visited_libs}") set(required_libs ${required_libs} PARENT_SCOPE) set(visited_libs ${visited_libs} PARENT_SCOPE) endforeach() list(APPEND required_libs ${name}) set(required_libs ${required_libs} PARENT_SCOPE) endif() endfunction() # Expand dependencies while topologically sorting the list of libraries: function(llvm_expand_dependencies out_libs) set(expanded_components ${ARGN}) set(required_libs) set(visited_libs) foreach( lib ${expanded_components} ) expand_topologically(${lib} "${required_libs}" "${visited_libs}") endforeach() list(REVERSE required_libs) set(${out_libs} ${required_libs} PARENT_SCOPE) endfunction() function(explicit_map_components_to_libraries out_libs) llvm_map_components_to_libnames(link_libs ${ARGN}) llvm_expand_dependencies(expanded_components ${link_libs}) # Return just the libraries included in this build: set(result) foreach(c ${expanded_components}) if( TARGET ${c} ) set(result ${result} ${c}) endif() endforeach(c) set(${out_libs} ${result} PARENT_SCOPE) endfunction(explicit_map_components_to_libraries)
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/CMakeLists.txt
set(LLVM_INSTALL_PACKAGE_DIR share/llvm/cmake) set(llvm_cmake_builddir "${LLVM_BINARY_DIR}/${LLVM_INSTALL_PACKAGE_DIR}") get_property(LLVM_EXPORTS GLOBAL PROPERTY LLVM_EXPORTS) export(TARGETS ${LLVM_EXPORTS} FILE ${llvm_cmake_builddir}/LLVMExports.cmake) get_property(LLVM_AVAILABLE_LIBS GLOBAL PROPERTY LLVM_LIBS) foreach(lib ${LLVM_AVAILABLE_LIBS}) get_property(llvm_lib_deps GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_${lib}) set(all_llvm_lib_deps "${all_llvm_lib_deps}\nset_property(GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_${lib} ${llvm_lib_deps})") endforeach(lib) # Generate LLVMConfig.cmake for the build tree. set(LLVM_CONFIG_CODE " # LLVM_BUILD_* values available only from LLVM build tree. set(LLVM_BUILD_BINARY_DIR \"${LLVM_BINARY_DIR}\") set(LLVM_BUILD_LIBRARY_DIR \"${LLVM_LIBRARY_DIR}\") set(LLVM_BUILD_MAIN_INCLUDE_DIR \"${LLVM_MAIN_INCLUDE_DIR}\") set(LLVM_BUILD_MAIN_SRC_DIR \"${LLVM_MAIN_SRC_DIR}\") ") set(LLVM_CONFIG_INCLUDE_DIRS "${LLVM_MAIN_INCLUDE_DIR}" "${LLVM_INCLUDE_DIR}" ) set(LLVM_CONFIG_LIBRARY_DIRS "${LLVM_LIBRARY_DIR}" ) set(LLVM_CONFIG_CMAKE_DIR "${CMAKE_CURRENT_SOURCE_DIR}") set(LLVM_CONFIG_TOOLS_BINARY_DIR "${LLVM_TOOLS_BINARY_DIR}") set(LLVM_CONFIG_EXPORTS_FILE "${llvm_cmake_builddir}/LLVMExports.cmake") configure_file( LLVMConfig.cmake.in ${llvm_cmake_builddir}/LLVMConfig.cmake @ONLY) # For compatibility with projects that include(LLVMConfig) # via CMAKE_MODULE_PATH, place API modules next to it. # This should be removed in the future. file(COPY . DESTINATION ${llvm_cmake_builddir} FILES_MATCHING PATTERN *.cmake PATTERN .svn EXCLUDE PATTERN CMakeFiles EXCLUDE ) # Generate LLVMConfig.cmake for the install tree. set(LLVM_CONFIG_CODE " # Compute the installation prefix from this LLVMConfig.cmake file location. get_filename_component(LLVM_INSTALL_PREFIX \"\${CMAKE_CURRENT_LIST_FILE}\" PATH)") # Construct the proper number of get_filename_component(... PATH) # calls to compute the installation prefix. string(REGEX REPLACE "/" ";" _count "${LLVM_INSTALL_PACKAGE_DIR}") foreach(p ${_count}) set(LLVM_CONFIG_CODE "${LLVM_CONFIG_CODE} get_filename_component(LLVM_INSTALL_PREFIX \"\${LLVM_INSTALL_PREFIX}\" PATH)") endforeach(p) set(LLVM_CONFIG_INCLUDE_DIRS "\${LLVM_INSTALL_PREFIX}/include") set(LLVM_CONFIG_LIBRARY_DIRS "\${LLVM_INSTALL_PREFIX}/lib\${LLVM_LIBDIR_SUFFIX}") set(LLVM_CONFIG_CMAKE_DIR "\${LLVM_INSTALL_PREFIX}/${LLVM_INSTALL_PACKAGE_DIR}") set(LLVM_CONFIG_TOOLS_BINARY_DIR "\${LLVM_INSTALL_PREFIX}/bin") set(LLVM_CONFIG_EXPORTS_FILE "\${LLVM_CMAKE_DIR}/LLVMExports.cmake") configure_file( LLVMConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/LLVMConfig.cmake @ONLY) # Generate LLVMConfigVersion.cmake for build and install tree. configure_file( LLVMConfigVersion.cmake.in ${llvm_cmake_builddir}/LLVMConfigVersion.cmake @ONLY) if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY) install(EXPORT LLVMExports DESTINATION ${LLVM_INSTALL_PACKAGE_DIR}) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/LLVMConfig.cmake ${llvm_cmake_builddir}/LLVMConfigVersion.cmake LLVM-Config.cmake DESTINATION ${LLVM_INSTALL_PACKAGE_DIR}) install(DIRECTORY . DESTINATION ${LLVM_INSTALL_PACKAGE_DIR} FILES_MATCHING PATTERN *.cmake PATTERN .svn EXCLUDE PATTERN LLVMConfig.cmake EXCLUDE PATTERN LLVMConfigVersion.cmake EXCLUDE PATTERN LLVM-Config.cmake EXCLUDE PATTERN GetHostTriple.cmake EXCLUDE PATTERN VersionFromVCS.cmake EXCLUDE PATTERN CheckAtomic.cmake EXCLUDE) endif()
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/FindD3D12.cmake
# Find the Win10 SDK path. if ("$ENV{WIN10_SDK_PATH}$ENV{WIN10_SDK_VERSION}" STREQUAL "" ) get_filename_component(WIN10_SDK_PATH "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots;KitsRoot10]" ABSOLUTE CACHE) if (CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION) set (WIN10_SDK_VERSION ${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}) else() # CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION may not be defined if, for example, # the Ninja generator is used instead of Visual Studio. Attempt to retrieve the # most recent SDK version from the list of paths under "${WIN10_SDK_PATH}/Include/". file(GLOB sdk_dirs RELATIVE "${WIN10_SDK_PATH}/Include/" "${WIN10_SDK_PATH}/Include/10.*") if (sdk_dirs) list(POP_BACK sdk_dirs WIN10_SDK_VERSION) endif() unset(sdk_dirs) endif() elseif(TRUE) set (WIN10_SDK_PATH $ENV{WIN10_SDK_PATH}) set (WIN10_SDK_VERSION $ENV{WIN10_SDK_VERSION}) endif ("$ENV{WIN10_SDK_PATH}$ENV{WIN10_SDK_VERSION}" STREQUAL "" ) # WIN10_SDK_PATH will be something like C:\Program Files (x86)\Windows Kits\10 # WIN10_SDK_VERSION will be something like 10.0.14393 or 10.0.14393.0; we need the # one that matches the directory name. if (IS_DIRECTORY "${WIN10_SDK_PATH}/Include/${WIN10_SDK_VERSION}.0") set(WIN10_SDK_VERSION "${WIN10_SDK_VERSION}.0") endif (IS_DIRECTORY "${WIN10_SDK_PATH}/Include/${WIN10_SDK_VERSION}.0") # Find the d3d12 and dxgi include path, it will typically look something like this. # C:\Program Files (x86)\Windows Kits\10\Include\10.0.10586.0\um\d3d12.h # C:\Program Files (x86)\Windows Kits\10\Include\10.0.10586.0\shared\dxgi1_4.h find_path(D3D12_INCLUDE_DIR # Set variable D3D12_INCLUDE_DIR d3d12.h # Find a path with d3d12.h HINTS "${WIN10_SDK_PATH}/Include/${WIN10_SDK_VERSION}/um" DOC "path to WIN10 SDK header files" HINTS ) find_path(DXGI_INCLUDE_DIR # Set variable DXGI_INCLUDE_DIR dxgi1_4.h # Find a path with dxgi1_4.h HINTS "${WIN10_SDK_PATH}/Include/${WIN10_SDK_VERSION}/shared" DOC "path to WIN10 SDK header files" HINTS ) set(D3D12_INCLUDE_DIRS ${D3D12_INCLUDE_DIR} ${DXGI_INCLUDE_DIR}) # List of D3D libraries set(D3D12_LIBRARIES d3d12.lib dxgi.lib d3dcompiler.lib) include(FindPackageHandleStandardArgs) # handle the QUIETLY and REQUIRED arguments and set D3D12_FOUND to TRUE # if all listed variables are TRUE find_package_handle_standard_args(D3D12 DEFAULT_MSG D3D12_INCLUDE_DIRS D3D12_LIBRARIES) mark_as_advanced(D3D12_INCLUDE_DIRS D3D12_LIBRARIES)
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/CheckAtomic.cmake
# atomic builtins are required for threading support. INCLUDE(CheckCXXSourceCompiles) # Sometimes linking against libatomic is required for atomic ops, if # the platform doesn't support lock-free atomics. function(check_working_cxx_atomics varname) set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS}) set(CMAKE_REQUIRED_FLAGS "-std=c++11") CHECK_CXX_SOURCE_COMPILES(" #include <atomic> std::atomic<int> x; int main() { return x; } " ${varname}) set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS}) endfunction(check_working_cxx_atomics) # This isn't necessary on MSVC, so avoid command-line switch annoyance # by only running on GCC-like hosts. if (LLVM_COMPILER_IS_GCC_COMPATIBLE) # First check if atomics work without the library. check_working_cxx_atomics(HAVE_CXX_ATOMICS_WITHOUT_LIB) # If not, check if the library exists, and atomics work with it. if(NOT HAVE_CXX_ATOMICS_WITHOUT_LIB) check_library_exists(atomic __atomic_fetch_add_4 "" HAVE_LIBATOMIC) if( HAVE_LIBATOMIC ) list(APPEND CMAKE_REQUIRED_LIBRARIES "atomic") check_working_cxx_atomics(HAVE_CXX_ATOMICS_WITH_LIB) if (NOT HAVE_CXX_ATOMICS_WITH_LIB) message(FATAL_ERROR "Host compiler must support std::atomic!") endif() else() message(FATAL_ERROR "Host compiler appears to require libatomic, but cannot find it.") endif() endif() endif() ## TODO: This define is only used for the legacy atomic operations in ## llvm's Atomic.h, which should be replaced. Other code simply ## assumes C++11 <atomic> works. CHECK_CXX_SOURCE_COMPILES(" #ifdef _MSC_VER #include <Intrin.h> /* Workaround for PR19898. */ #include <windows.h> #endif int main() { #ifdef _MSC_VER volatile LONG val = 1; MemoryBarrier(); InterlockedCompareExchange(&val, 0, 1); InterlockedIncrement(&val); InterlockedDecrement(&val); #else volatile unsigned long val = 1; __sync_synchronize(); __sync_val_compare_and_swap(&val, 1, 0); __sync_add_and_fetch(&val, 1); __sync_sub_and_fetch(&val, 1); #endif return 0; } " LLVM_HAS_ATOMICS) if( NOT LLVM_HAS_ATOMICS ) message(STATUS "Warning: LLVM will be built thread-unsafe because atomic builtins are missing") endif()
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/CrossCompile.cmake
function(llvm_create_cross_target_internal target_name toochain buildtype) if(NOT DEFINED LLVM_${target_name}_BUILD) set(LLVM_${target_name}_BUILD "${CMAKE_BINARY_DIR}/${target_name}") set(LLVM_${target_name}_BUILD ${LLVM_${target_name}_BUILD} PARENT_SCOPE) message(STATUS "Setting native build dir to " ${LLVM_${target_name}_BUILD}) endif(NOT DEFINED LLVM_${target_name}_BUILD) if (EXISTS ${LLVM_MAIN_SRC_DIR}/cmake/platforms/${toolchain}.cmake) set(CROSS_TOOLCHAIN_FLAGS_${target_name} -DCMAKE_TOOLCHAIN_FILE=\"${LLVM_MAIN_SRC_DIR}/cmake/platforms/${toolchain}.cmake\" CACHE STRING "Toolchain file for ${target_name}") endif() add_custom_command(OUTPUT ${LLVM_${target_name}_BUILD} COMMAND ${CMAKE_COMMAND} -E make_directory ${LLVM_${target_name}_BUILD} COMMENT "Creating ${LLVM_${target_name}_BUILD}...") add_custom_command(OUTPUT ${LLVM_${target_name}_BUILD}/CMakeCache.txt COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" ${CROSS_TOOLCHAIN_FLAGS_${target_name}} ${CMAKE_SOURCE_DIR} WORKING_DIRECTORY ${LLVM_${target_name}_BUILD} DEPENDS ${LLVM_${target_name}_BUILD} COMMENT "Configuring ${target_name} LLVM...") add_custom_target(CONFIGURE_LLVM_${target_name} DEPENDS ${LLVM_${target_name}_BUILD}/CMakeCache.txt) set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES ${LLVM_${target_name}_BUILD}) if(NOT IS_DIRECTORY ${LLVM_${target_name}_BUILD}) message(STATUS "Configuring ${target_name} build...") execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${LLVM_${target_name}_BUILD} ) message(STATUS "Configuring ${target_name} targets...") if (buildtype) set(build_type_flags "-DCMAKE_BUILD_TYPE=${buildtype}") endif() execute_process(COMMAND ${CMAKE_COMMAND} ${build_type_flags} -G "${CMAKE_GENERATOR}" -DLLVM_TARGETS_TO_BUILD=${LLVM_TARGETS_TO_BUILD} ${CROSS_TOOLCHAIN_FLAGS_${target_name}} ${CMAKE_SOURCE_DIR} WORKING_DIRECTORY ${LLVM_${target_name}_BUILD} ) endif(NOT IS_DIRECTORY ${LLVM_${target_name}_BUILD}) endfunction() function(llvm_create_cross_target target_name sysroot) llvm_create_cross_target_internal(${target_name} ${sysroot} ${CMAKE_BUILD_TYPE}) endfunction() llvm_create_cross_target_internal(NATIVE "" Release)
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/CoverageReport.cmake
# if coverage reports are not enabled, skip all of this if(NOT LLVM_BUILD_INSTRUMENTED_COVERAGE) return() endif() file(TO_NATIVE_PATH "${LLVM_SOURCE_DIR}/utils/prepare-code-coverage-artifact.py" PREPARE_CODE_COV_ARTIFACT) # llvm-cov and llvm-profdata need to match the host compiler. They can either be # explicitly provided by the user, or we will look them up based on the install # location of the C++ compiler. # HLSL Change Begin - This is probably worth upstreaming. Some Linux packages # install versions of the LLVM tools that are versioned. This handles that case. if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") string(REGEX REPLACE "(^[0-9]+)(\\.[0-9\\.]+)" "-\\1" HOST_LLVM_VERSION_SUFFIX ${CMAKE_CXX_COMPILER_VERSION}) endif() get_filename_component(COMPILER_DIRECTORY ${CMAKE_CXX_COMPILER} DIRECTORY) find_program(LLVM_COV NAMES llvm-cov llvm-cov${HOST_LLVM_VERSION_SUFFIX} PATHS ${COMPILER_DIRECTORY} NO_DEFAULT_PATH) find_program(LLVM_PROFDATA NAMES llvm-profdata llvm-profdata${HOST_LLVM_VERSION_SUFFIX} PATHS ${COMPILER_DIRECTORY} NO_DEFAULT_PATH) # HLSL Change End - Detect versioned tools. if(NOT LLVM_COV OR NOT LLVM_PROFDATA) message(WARNING "Could not find code coverage tools, skipping generating targets. You may explicitly specify LLVM_COV and LLVM_PROFDATA to work around this warning.") return() endif() set(LLVM_CODE_COVERAGE_TARGETS "" CACHE STRING "Targets to generate coverage reports against (defaults to all exported targets if empty)") mark_as_advanced(LLVM_CODE_COVERAGE_TARGETS) # HLSL Change Begin - This is probably worth upstreaming... set(LLVM_CODE_COVERAGE_TEST_TARGETS "" CACHE STRING "Targets to run to generate coverage profiles.") mark_as_advanced(LLVM_CODE_COVERAGE_TEST_TARGETS) if (LLVM_CODE_COVERAGE_TEST_TARGETS) set(COV_DEPENDS DEPENDS ${LLVM_CODE_COVERAGE_TEST_TARGETS}) endif() # HLSL Change End if(NOT LLVM_CODE_COVERAGE_TARGETS) # by default run the coverage report across all the exports provided get_property(COV_TARGETS GLOBAL PROPERTY LLVM_EXPORTS) endif() file(TO_NATIVE_PATH "${CMAKE_BINARY_DIR}/report/" REPORT_DIR) foreach(target ${LLVM_CODE_COVERAGE_TARGETS} ${COV_TARGETS}) get_target_property(target_type ${target} TYPE) if("${target_type}" STREQUAL "SHARED_LIBRARY" OR "${target_type}" STREQUAL "EXECUTABLE") list(APPEND coverage_binaries $<TARGET_FILE:${target}>) endif() endforeach() set(LLVM_COVERAGE_SOURCE_DIRS "" CACHE STRING "Source directories to restrict coverage reports to.") mark_as_advanced(LLVM_COVERAGE_SOURCE_DIRS) foreach(dir ${LLVM_COVERAGE_SOURCE_DIRS}) list(APPEND restrict_flags -restrict ${dir}) endforeach() # Utility target to clear out profile data. # This isn't connected to any dependencies because it is a bit finicky to get # working exactly how a user might want. add_custom_target(clear-profile-data COMMAND ${CMAKE_COMMAND} -E remove_directory ${LLVM_PROFILE_DATA_DIR}) # This currently only works for LLVM, but could be expanded to work for all # sub-projects. The current limitation is based on not having a good way to # automaticall plumb through the targets that we want to run coverage against. add_custom_target(generate-coverage-report COMMAND ${Python3_EXECUTABLE} ${PREPARE_CODE_COV_ARTIFACT} ${LLVM_PROFDATA} ${LLVM_COV} ${LLVM_PROFILE_DATA_DIR} ${REPORT_DIR} ${coverage_binaries} --unified-report ${restrict_flags} WORKING_DIRECTORY ${CMAKE_BINARY_DIR} ${COV_DEPENDS}) # Run tests
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/FindDiaSDK.cmake
# Find the DIA SDK path. # It will typically look something like this: # C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\DIA SDK\include # CMAKE_GENERATOR_INSTANCE has the location of Visual Studio used # i.e. C:/Program Files (x86)/Microsoft Visual Studio/2019/Community set(VS_PATH ${CMAKE_GENERATOR_INSTANCE}) get_filename_component(VS_DIA_INC_PATH "${VS_PATH}/DIA SDK/include" ABSOLUTE CACHE) # Starting in VS 15.2, vswhere is included. # Unclear what the right component to search for is, might be Microsoft.VisualStudio.Component.VC.DiagnosticTools # (although the friendly name of that is C++ profiling tools). The toolset is the most likely target. set(PROGRAMFILES_X86 "ProgramFiles(x86)") execute_process( COMMAND "$ENV{${PROGRAMFILES_X86}}/Microsoft Visual Studio/Installer/vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath OUTPUT_VARIABLE VSWHERE_LATEST ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE ) find_path(DIASDK_INCLUDE_DIR # Set variable DIASDK_INCLUDE_DIR dia2.h # Find a path with dia2.h HINTS "${VS_DIA_INC_PATH}" HINTS "${VSWHERE_LATEST}/DIA SDK/include" HINTS "${MSVC_DIA_SDK_DIR}/include" DOC "path to DIA SDK header files" ) if ((CMAKE_GENERATOR_PLATFORM STREQUAL "x64") OR ("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "x64")) find_library(DIASDK_GUIDS_LIBRARY NAMES diaguids.lib HINTS ${DIASDK_INCLUDE_DIR}/../lib/amd64 ) elseif ((CMAKE_GENERATOR_PLATFORM STREQUAL "ARM") OR ("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "ARM")) find_library(DIASDK_GUIDS_LIBRARY NAMES diaguids.lib HINTS ${DIASDK_INCLUDE_DIR}/../lib/arm ) elseif ((CMAKE_GENERATOR_PLATFORM MATCHES "ARM64.*") OR ("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" MATCHES "ARM64.*")) find_library(DIASDK_GUIDS_LIBRARY NAMES diaguids.lib HINTS ${DIASDK_INCLUDE_DIR}/../lib/arm64 ) else ((CMAKE_GENERATOR_PLATFORM STREQUAL "x64") OR ("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "x64")) find_library(DIASDK_GUIDS_LIBRARY NAMES diaguids.lib HINTS ${DIASDK_INCLUDE_DIR}/../lib ) endif((CMAKE_GENERATOR_PLATFORM STREQUAL "x64") OR ("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "x64")) set(DIASDK_LIBRARIES ${DIASDK_GUIDS_LIBRARY}) set(DIASDK_INCLUDE_DIRS ${DIASDK_INCLUDE_DIR}) include(FindPackageHandleStandardArgs) # handle the QUIETLY and REQUIRED arguments and set DIASDK_FOUND to TRUE # if all listed variables are TRUE find_package_handle_standard_args(DiaSDK DEFAULT_MSG DIASDK_LIBRARIES DIASDK_INCLUDE_DIR) mark_as_advanced(DIASDK_INCLUDE_DIRS DIASDK_LIBRARIES)
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/TableGen.cmake
# LLVM_TARGET_DEFINITIONS must contain the name of the .td file to process. # Extra parameters for `tblgen' may come after `ofn' parameter. # Adds the name of the generated file to TABLEGEN_OUTPUT. function(tablegen project ofn) # Validate calling context. foreach(v ${project}_TABLEGEN_EXE LLVM_MAIN_SRC_DIR LLVM_MAIN_INCLUDE_DIR ) if(NOT ${v}) message(FATAL_ERROR "${v} not set") endif() endforeach() file(GLOB local_tds "*.td") file(GLOB_RECURSE global_tds "${LLVM_MAIN_INCLUDE_DIR}/llvm/*.td") if (IS_ABSOLUTE ${LLVM_TARGET_DEFINITIONS}) set(LLVM_TARGET_DEFINITIONS_ABSOLUTE ${LLVM_TARGET_DEFINITIONS}) else() set(LLVM_TARGET_DEFINITIONS_ABSOLUTE ${CMAKE_CURRENT_SOURCE_DIR}/${LLVM_TARGET_DEFINITIONS}) endif() add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${ofn}.tmp # Generate tablegen output in a temporary file. COMMAND ${${project}_TABLEGEN_EXE} ${ARGN} -I ${CMAKE_CURRENT_SOURCE_DIR} -I ${LLVM_MAIN_SRC_DIR}/lib/Target -I ${LLVM_MAIN_INCLUDE_DIR} ${LLVM_TARGET_DEFINITIONS_ABSOLUTE} -o ${CMAKE_CURRENT_BINARY_DIR}/${ofn}.tmp # The file in LLVM_TARGET_DEFINITIONS may be not in the current # directory and local_tds may not contain it, so we must # explicitly list it here: DEPENDS ${${project}_TABLEGEN_TARGET} ${local_tds} ${global_tds} ${LLVM_TARGET_DEFINITIONS_ABSOLUTE} COMMENT "Building ${ofn}..." ) add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${ofn} # Only update the real output file if there are any differences. # This prevents recompilation of all the files depending on it if there # aren't any. COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_BINARY_DIR}/${ofn}.tmp ${CMAKE_CURRENT_BINARY_DIR}/${ofn} DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${ofn}.tmp COMMENT "Updating ${ofn}..." ) # `make clean' must remove all those generated files: set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${ofn}.tmp ${ofn}) set(TABLEGEN_OUTPUT ${TABLEGEN_OUTPUT} ${CMAKE_CURRENT_BINARY_DIR}/${ofn} PARENT_SCOPE) set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/${ofn} PROPERTIES GENERATED 1) endfunction() # Creates a target for publicly exporting tablegen dependencies. function(add_public_tablegen_target target) if(NOT TABLEGEN_OUTPUT) message(FATAL_ERROR "Requires tablegen() definitions as TABLEGEN_OUTPUT.") endif() add_custom_target(${target} DEPENDS ${TABLEGEN_OUTPUT}) if(LLVM_COMMON_DEPENDS) add_dependencies(${target} ${LLVM_COMMON_DEPENDS}) endif() set_target_properties(${target} PROPERTIES FOLDER "Tablegenning") set(LLVM_COMMON_DEPENDS ${LLVM_COMMON_DEPENDS} ${target} PARENT_SCOPE) endfunction() macro(add_tablegen target project) set(${target}_OLD_LLVM_LINK_COMPONENTS ${LLVM_LINK_COMPONENTS}) set(LLVM_LINK_COMPONENTS ${LLVM_LINK_COMPONENTS} TableGen) add_llvm_utility(${target} ${ARGN}) set(LLVM_LINK_COMPONENTS ${${target}_OLD_LLVM_LINK_COMPONENTS}) set(${project}_TABLEGEN "${target}" CACHE STRING "Native TableGen executable. Saves building one when cross-compiling.") # Upgrade existing LLVM_TABLEGEN setting. if(${project} STREQUAL LLVM) if(${LLVM_TABLEGEN} STREQUAL tblgen) set(LLVM_TABLEGEN "${target}" CACHE STRING "Native TableGen executable. Saves building one when cross-compiling." FORCE) endif() endif() # Effective tblgen executable to be used: set(${project}_TABLEGEN_EXE ${${project}_TABLEGEN} PARENT_SCOPE) set(${project}_TABLEGEN_TARGET ${${project}_TABLEGEN} PARENT_SCOPE) if(LLVM_USE_HOST_TOOLS) if( ${${project}_TABLEGEN} STREQUAL "${target}" ) if (NOT CMAKE_CONFIGURATION_TYPES) set(${project}_TABLEGEN_EXE "${LLVM_NATIVE_BUILD}/bin/${target}") else() set(${project}_TABLEGEN_EXE "${LLVM_NATIVE_BUILD}/Release/bin/${target}") endif() set(${project}_TABLEGEN_EXE ${${project}_TABLEGEN_EXE} PARENT_SCOPE) add_custom_command(OUTPUT ${${project}_TABLEGEN_EXE} COMMAND ${CMAKE_COMMAND} --build . --target ${target} --config Release DEPENDS CONFIGURE_LLVM_NATIVE ${target} WORKING_DIRECTORY ${LLVM_NATIVE_BUILD} COMMENT "Building native TableGen...") add_custom_target(${project}-tablegen-host DEPENDS ${${project}_TABLEGEN_EXE}) set(${project}_TABLEGEN_TARGET ${project}-tablegen-host PARENT_SCOPE) endif() endif() if( MINGW ) if(CMAKE_SIZEOF_VOID_P MATCHES "8") set_target_properties(${target} PROPERTIES LINK_FLAGS -Wl,--stack,16777216) endif(CMAKE_SIZEOF_VOID_P MATCHES "8") endif( MINGW ) if (${project} STREQUAL LLVM AND NOT LLVM_INSTALL_TOOLCHAIN_ONLY) install(TARGETS ${target} EXPORT LLVMExports RUNTIME DESTINATION bin) endif() set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${target}) endmacro()
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/HandleLLVMOptions.cmake
# This CMake module is responsible for interpreting the user defined LLVM_ # options and executing the appropriate CMake commands to realize the users' # selections. # This is commonly needed so make sure it's defined before we include anything # else. string(TOUPPER "${CMAKE_BUILD_TYPE}" uppercase_CMAKE_BUILD_TYPE) include(HandleLLVMStdlib) include(AddLLVMDefinitions) include(CheckCCompilerFlag) include(CheckCXXCompilerFlag) if(NOT LLVM_FORCE_USE_OLD_TOOLCHAIN) if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.7) message(FATAL_ERROR "Host GCC version must be at least 4.7!") endif() elseif(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.1) message(FATAL_ERROR "Host Clang version must be at least 3.1!") endif() if (CMAKE_CXX_SIMULATE_ID MATCHES "MSVC") if (CMAKE_CXX_SIMULATE_VERSION VERSION_LESS 18.0) message(FATAL_ERROR "Host Clang must have at least -fms-compatibility-version=18.0") endif() set(CLANG_CL 1) elseif(NOT LLVM_ENABLE_LIBCXX) # Otherwise, test that we aren't using too old of a version of libstdc++ # with the Clang compiler. This is tricky as there is no real way to # check the version of libstdc++ directly. Instead we test for a known # bug in libstdc++4.6 that is fixed in libstdc++4.7. set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS}) set(OLD_CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES}) set(CMAKE_REQUIRED_FLAGS "-std=c++0x") check_cxx_source_compiles(" #include <atomic> std::atomic<float> x(0.0f); int main() { return (float)x; }" LLVM_NO_OLD_LIBSTDCXX) if(NOT LLVM_NO_OLD_LIBSTDCXX) message(FATAL_ERROR "Host Clang must be able to find libstdc++4.7 or newer!") endif() set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS}) set(CMAKE_REQUIRED_LIBRARIES ${OLD_CMAKE_REQUIRED_LIBRARIES}) endif() elseif(CMAKE_CXX_COMPILER_ID MATCHES "MSVC") if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 18.0) message(FATAL_ERROR "Host Visual Studio must be at least 2013") elseif(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 18.0.31101) message(WARNING "Host Visual Studio should at least be 2013 Update 4 (MSVC 18.0.31101)" " due to miscompiles from earlier versions") endif() endif() endif() if( LLVM_ENABLE_ASSERTIONS ) # MSVC doesn't like _DEBUG on release builds. See PR 4379. # HLSL Note: the above comment referrs to llvm.org problem, not pull request: # https://bugs.llvm.org/show_bug.cgi?id=4379 if( NOT MSVC ) add_definitions( -D_DEBUG ) endif() # On non-Debug builds cmake automatically defines NDEBUG, so we # explicitly undefine it: if( NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" ) add_definitions( -UNDEBUG ) # Also remove /D NDEBUG to avoid MSVC warnings about conflicting defines. foreach (flags_var_to_scrub CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_RELWITHDEBINFO CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELEASE CMAKE_C_FLAGS_RELWITHDEBINFO CMAKE_C_FLAGS_MINSIZEREL) string (REGEX REPLACE "(^| )[/-]D *NDEBUG($| )" " " "${flags_var_to_scrub}" "${${flags_var_to_scrub}}") endforeach() endif() if (LLVM_ASSERTIONS_TRAP) add_definitions( -DLLVM_ASSERTIONS_TRAP ) endif() if (LLVM_ASSERTIONS_NO_STRINGS) add_definitions( -DLLVM_ASSERTIONS_NO_STRINGS ) endif() else() # Disable assertions in Debug builds if( uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" ) add_definitions( -DNDEBUG ) endif() endif() string(TOUPPER "${LLVM_ABI_BREAKING_CHECKS}" uppercase_LLVM_ABI_BREAKING_CHECKS) if( uppercase_LLVM_ABI_BREAKING_CHECKS STREQUAL "WITH_ASSERTS" ) if( LLVM_ENABLE_ASSERTIONS ) set( LLVM_ENABLE_ABI_BREAKING_CHECKS 1 ) endif() elseif( uppercase_LLVM_ABI_BREAKING_CHECKS STREQUAL "FORCE_ON" ) set( LLVM_ENABLE_ABI_BREAKING_CHECKS 1 ) elseif( uppercase_LLVM_ABI_BREAKING_CHECKS STREQUAL "FORCE_OFF" ) # We don't need to do anything special to turn off ABI breaking checks. elseif( NOT DEFINED LLVM_ABI_BREAKING_CHECKS ) # Treat LLVM_ABI_BREAKING_CHECKS like "FORCE_OFF" when it has not been # defined. else() message(FATAL_ERROR "Unknown value for LLVM_ABI_BREAKING_CHECKS: \"${LLVM_ABI_BREAKING_CHECKS}\"!") endif() if(WIN32) set(LLVM_HAVE_LINK_VERSION_SCRIPT 0) if(CYGWIN) set(LLVM_ON_WIN32 0) set(LLVM_ON_UNIX 1) else(CYGWIN) set(LLVM_ON_WIN32 1) set(LLVM_ON_UNIX 0) endif(CYGWIN) else(WIN32) if(UNIX) set(LLVM_ON_WIN32 0) set(LLVM_ON_UNIX 1) if(APPLE) set(LLVM_HAVE_LINK_VERSION_SCRIPT 0) else(APPLE) set(LLVM_HAVE_LINK_VERSION_SCRIPT 1) endif(APPLE) else(UNIX) MESSAGE(SEND_ERROR "Unable to determine platform") endif(UNIX) endif(WIN32) set(EXEEXT ${CMAKE_EXECUTABLE_SUFFIX}) set(LTDL_SHLIB_EXT ${CMAKE_SHARED_LIBRARY_SUFFIX}) # We use *.dylib rather than *.so on darwin. set(LLVM_PLUGIN_EXT ${CMAKE_SHARED_LIBRARY_SUFFIX}) if(APPLE) # Darwin-specific linker flags for loadable modules. set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -Wl,-flat_namespace -Wl,-undefined -Wl,suppress") endif() # Pass -Wl,-z,defs. This makes sure all symbols are defined. Otherwise a DSO # build might work on ELF but fail on MachO/COFF. if(NOT (${CMAKE_SYSTEM_NAME} MATCHES "Darwin" OR WIN32 OR CYGWIN OR ${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD") AND NOT LLVM_USE_SANITIZER) set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,defs") endif() function(append value) foreach(variable ${ARGN}) set(${variable} "${${variable}} ${value}" PARENT_SCOPE) endforeach(variable) endfunction() function(append_if condition value) if (${condition}) foreach(variable ${ARGN}) set(${variable} "${${variable}} ${value}" PARENT_SCOPE) endforeach(variable) endif() endfunction() macro(add_flag_if_supported flag name) check_c_compiler_flag("-Werror ${flag}" "C_SUPPORTS_${name}") append_if("C_SUPPORTS_${name}" "${flag}" CMAKE_C_FLAGS) check_cxx_compiler_flag("-Werror ${flag}" "CXX_SUPPORTS_${name}") append_if("CXX_SUPPORTS_${name}" "${flag}" CMAKE_CXX_FLAGS) endmacro() function(add_flag_or_print_warning flag name) check_c_compiler_flag("-Werror ${flag}" "C_SUPPORTS_${name}") check_cxx_compiler_flag("-Werror ${flag}" "CXX_SUPPORTS_${name}") if (C_SUPPORTS_${name} AND CXX_SUPPORTS_${name}) message(STATUS "Building with ${flag}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}" PARENT_SCOPE) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${flag}" PARENT_SCOPE) else() message(WARNING "${flag} is not supported.") endif() endfunction() if( LLVM_USE_LINKER ) set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS}) set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -fuse-ld=${LLVM_USE_LINKER}") check_cxx_source_compiles("int main() { return 0; }" CXX_SUPPORTS_CUSTOM_LINKER) if ( NOT CXX_SUPPORTS_CUSTOM_LINKER ) message(FATAL_ERROR "Host compiler does not support '-fuse-ld=${LLVM_USE_LINKER}'") endif() set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS}) append("-fuse-ld=${LLVM_USE_LINKER}" CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS) endif() if( LLVM_ENABLE_PIC ) if( XCODE ) # Xcode has -mdynamic-no-pic on by default, which overrides -fPIC. I don't # know how to disable this, so just force ENABLE_PIC off for now. message(WARNING "-fPIC not supported with Xcode.") else() if( NOT WIN32 AND NOT CYGWIN ) # On Windows all code is PIC. MinGW warns if -fPIC is used. add_flag_or_print_warning("-fPIC" FPIC) endif() if( (MINGW AND NOT CLANG) OR CYGWIN ) # MinGW warns if -fvisibility-inlines-hidden is used. else() check_cxx_compiler_flag("-fvisibility-inlines-hidden" SUPPORTS_FVISIBILITY_INLINES_HIDDEN_FLAG) append_if(SUPPORTS_FVISIBILITY_INLINES_HIDDEN_FLAG "-fvisibility-inlines-hidden -fvisibility=hidden" CMAKE_CXX_FLAGS) endif() endif() endif() if( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 ) # TODO: support other platforms and toolchains. if( LLVM_BUILD_32_BITS ) message(STATUS "Building 32 bits executables and libraries.") add_llvm_definitions( -m32 ) set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -m32") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -m32") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -m32") endif( LLVM_BUILD_32_BITS ) endif( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 ) if (LLVM_BUILD_STATIC) set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static") endif() if( XCODE ) # For Xcode enable several build settings that correspond to # many warnings that are on by default in Clang but are # not enabled for historical reasons. For versions of Xcode # that do not support these options they will simply # be ignored. set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_ABOUT_RETURN_TYPE "YES") set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_ABOUT_MISSING_NEWLINE "YES") set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNUSED_VALUE "YES") set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNUSED_VARIABLE "YES") set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_SIGN_COMPARE "YES") set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNUSED_FUNCTION "YES") set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED "YES") set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS "YES") set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNINITIALIZED_AUTOS "YES") set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_BOOL_CONVERSION "YES") set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_EMPTY_BODY "YES") set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_ENUM_CONVERSION "YES") set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_INT_CONVERSION "YES") set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_CONSTANT_CONVERSION "YES") set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_NON_VIRTUAL_DESTRUCTOR "YES") endif() # On Win32 using MS tools, provide an option to set the number of parallel jobs # to use. if( MSVC_IDE ) set(LLVM_COMPILER_JOBS "0" CACHE STRING "Number of parallel compiler jobs. 0 means use all processors. Default is 0.") if( NOT LLVM_COMPILER_JOBS STREQUAL "1" ) if( LLVM_COMPILER_JOBS STREQUAL "0" ) add_llvm_definitions( /MP ) else() message(STATUS "Number of parallel compiler jobs set to " ${LLVM_COMPILER_JOBS}) add_llvm_definitions( /MP${LLVM_COMPILER_JOBS} ) endif() else() message(STATUS "Parallel compilation disabled") endif() endif() if( MSVC ) include(ChooseMSVCCRT) if( NOT (${CMAKE_VERSION} VERSION_LESS 2.8.11) ) # set stack reserved size to ~10MB # CMake previously automatically set this value for MSVC builds, but the # behavior was changed in CMake 2.8.11 (Issue 12437) to use the MSVC default # value (1 MB) which is not enough for us in tasks such as parsing recursive # C++ templates in Clang. set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /STACK:10000000") endif() if( MSVC11 ) add_llvm_definitions(-D_VARIADIC_MAX=10) endif() # Add definitions that make MSVC much less annoying. add_llvm_definitions( # For some reason MS wants to deprecate a bunch of standard functions... -D_CRT_SECURE_NO_DEPRECATE -D_CRT_SECURE_NO_WARNINGS -D_CRT_NONSTDC_NO_DEPRECATE -D_CRT_NONSTDC_NO_WARNINGS -D_SCL_SECURE_NO_DEPRECATE -D_SCL_SECURE_NO_WARNINGS ) set(msvc_warning_flags # Disabled warnings. -wd4146 # Suppress 'unary minus operator applied to unsigned type, result still unsigned' -wd4180 # Suppress 'qualifier applied to function type has no meaning; ignored' -wd4244 # Suppress ''argument' : conversion from 'type1' to 'type2', possible loss of data' -wd4258 # Suppress ''var' : definition from the for loop is ignored; the definition from the enclosing scope is used' -wd4267 # Suppress ''var' : conversion from 'size_t' to 'type', possible loss of data' -wd4291 # Suppress ''declaration' : no matching operator delete found; memory will not be freed if initialization throws an exception' -wd4345 # Suppress 'behavior change: an object of POD type constructed with an initializer of the form () will be default-initialized' -wd4351 # Suppress 'new behavior: elements of array 'array' will be default initialized' -wd4355 # Suppress ''this' : used in base member initializer list' -wd4456 # Suppress 'declaration of 'var' hides local variable' -wd4457 # Suppress 'declaration of 'var' hides function parameter' -wd4458 # Suppress 'declaration of 'var' hides class member' -wd4459 # Suppress 'declaration of 'var' hides global declaration' -wd4503 # Suppress ''identifier' : decorated name length exceeded, name was truncated' -wd4624 # Suppress ''derived class' : destructor could not be generated because a base class destructor is inaccessible' -wd4722 # Suppress 'function' : destructor never returns, potential memory leak -wd4800 # Suppress ''type' : forcing value to bool 'true' or 'false' (performance warning)' -wd4100 # Suppress 'unreferenced formal parameter' -wd4127 # Suppress 'conditional expression is constant' -wd4512 # Suppress 'assignment operator could not be generated' -wd4505 # Suppress 'unreferenced local function has been removed' -wd4610 # Suppress '<class> can never be instantiated' -wd4510 # Suppress 'default constructor could not be generated' -wd4702 # Suppress 'unreachable code' -wd4245 # Suppress 'signed/unsigned mismatch' -wd4706 # Suppress 'assignment within conditional expression' -wd4310 # Suppress 'cast truncates constant value' -wd4701 # Suppress 'potentially uninitialized local variable' -wd4703 # Suppress 'potentially uninitialized local pointer variable' -wd4389 # Suppress 'signed/unsigned mismatch' -wd4611 # Suppress 'interaction between '_setjmp' and C++ object destruction is non-portable' -wd4805 # Suppress 'unsafe mix of type <type> and type <type> in operation' -wd4204 # Suppress 'nonstandard extension used : non-constant aggregate initializer' # Ideally, we'd like this warning to be enabled, but MSVC 2013 doesn't # support the 'aligned' attribute in the way that clang sources requires (for # any code that uses the LLVM_ALIGNAS macro), so this is must be disabled to # avoid unwanted alignment warnings. # When we switch to requiring a version of MSVC that supports the 'alignas' # specifier (MSVC 2015?) this warning can be re-enabled. -wd4324 # Suppress 'structure was padded due to __declspec(align())' # Promoted warnings. # HLSL Change - don't do this - -w14062 # Promote 'enumerator in switch of enum is not handled' to level 1 warning. # Promoted warnings to errors. -we4238 # Promote 'nonstandard extension used : class rvalue used as lvalue' to error. ) # HLSL Changes Start if (HLSL_ENABLE_ANALYZE) append("/analyze" CMAKE_CXX_FLAGS) endif () # Change release to always build debug information out-of-line, but # also enable Reference optimization, ie dead function elimination. append("/Zi" CMAKE_CXX_FLAGS_RELEASE) append("/DEBUG /OPT:REF" CMAKE_SHARED_LINKER_FLAGS_RELEASE) append("/DEBUG /OPT:REF" CMAKE_EXE_LINKER_FLAGS_RELEASE) # HLSL Changes End # Enable warnings if (LLVM_ENABLE_WARNINGS) append("/W4" msvc_warning_flags) # CMake appends /W3 by default, and having /W3 followed by /W4 will result in # cl : Command line warning D9025 : overriding '/W3' with '/W4'. Since this is # a command line warning and not a compiler warning, it cannot be suppressed except # by fixing the command line. string(REGEX REPLACE " /W[0-4]" "" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}") string(REGEX REPLACE " /W[0-4]" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") if (LLVM_ENABLE_PEDANTIC) # No MSVC equivalent available endif (LLVM_ENABLE_PEDANTIC) if (CLANG_CL) append("-Wall -W -Wno-unused-parameter -Wwrite-strings -Wimplicit-fallthrough" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) append("-Wcast-qual" CMAKE_CXX_FLAGS) # Disable unknown pragma warnings because the output is just too long with them. append("-Wno-unknown-pragmas" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) add_flag_if_supported("-Wno-unused-but-set-variable" UNUSED_BUT_SET_VARIABLE) append("-Wno-switch" CMAKE_CXX_FLAGS) append("-Wmissing-field-initializers" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) # enable warnings explicitly. append("-Wnonportable-include-path -Wunused-function" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) append("-Wtrigraphs -Wconstant-logical-operand -Wunused-variable" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) endif (CLANG_CL) endif (LLVM_ENABLE_WARNINGS) if (LLVM_ENABLE_WERROR) append("/WX" msvc_warning_flags) endif (LLVM_ENABLE_WERROR) foreach(flag ${msvc_warning_flags}) append("${flag}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) endforeach(flag) # Disable sized deallocation if the flag is supported. MSVC fails to compile # the operator new overload in User otherwise. check_c_compiler_flag("/WX /Zc:sizedDealloc-" SUPPORTS_SIZED_DEALLOC) append_if(SUPPORTS_SIZED_DEALLOC "/Zc:sizedDealloc-" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) elseif( LLVM_COMPILER_IS_GCC_COMPATIBLE ) if (LLVM_ENABLE_WARNINGS) append("-Wall -W -Wno-unused-parameter -Wwrite-strings -Wimplicit-fallthrough" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) append("-Wcast-qual" CMAKE_CXX_FLAGS) # Disable unknown pragma warnings because the output is just too long with them. append("-Wno-unknown-pragmas" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) if (MINGW) append("-Wno-implicit-fallthrough" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) append("-Wno-missing-exception-spec" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) append("-Wno-reorder-ctor" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) append("-Wno-sign-compare" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) append("-Wno-unused-const-variable" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) append("-Wno-unused-function" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) endif() add_flag_if_supported("-Wno-unused-but-set-variable" UNUSED_BUT_SET_VARIABLE) add_flag_if_supported("-Wno-deprecated-copy" DEPRECATED_COPY) # Colorize GCC output even with ninja's stdout redirection. if (CMAKE_COMPILER_IS_GNUCXX) append("-fdiagnostics-color" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) endif (CMAKE_COMPILER_IS_GNUCXX) # Turn off missing field initializer warnings for gcc to avoid noise from # false positives with empty {}. Turn them on otherwise (they're off by # default for clang). check_cxx_compiler_flag("-Wmissing-field-initializers" CXX_SUPPORTS_MISSING_FIELD_INITIALIZERS_FLAG) if (CXX_SUPPORTS_MISSING_FIELD_INITIALIZERS_FLAG) if (CMAKE_COMPILER_IS_GNUCXX) append("-Wno-missing-field-initializers" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) else() append("-Wmissing-field-initializers" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) endif() endif() append_if(LLVM_ENABLE_PEDANTIC "-pedantic -Wno-long-long" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) # add_flag_if_supported("-Wcovered-switch-default" COVERED_SWITCH_DEFAULT_FLAG) # HLSL Change append("-Wno-switch" CMAKE_CXX_FLAGS) # HLSL Change append_if(USE_NO_UNINITIALIZED "-Wno-uninitialized" CMAKE_CXX_FLAGS) append_if(USE_NO_MAYBE_UNINITIALIZED "-Wno-maybe-uninitialized" CMAKE_CXX_FLAGS) # HLSL Change Starts # Windows' and by extension WinAdapter's non-Windows implementation for IUnknown # use virtual methods without virtual destructor, as that would add two extra # function-pointers to the vtable in turn offsetting those for every subclass, # resulting in ABI mismatches: # https://github.com/microsoft/DirectXShaderCompiler/issues/3783. # The -Wnon-virtual-dtor warning is disabled to allow this, conforming # with MSVC behaviour. # # Check if -Wnon-virtual-dtor warns even though the class is marked final. # # If it does, don't add it. So it won't be added on clang 3.4 and older. # # This also catches cases when -Wnon-virtual-dtor isn't supported by # # the compiler at all. # set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS}) # set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -std=c++11 -Werror=non-virtual-dtor") # CHECK_CXX_SOURCE_COMPILES("class base {public: virtual void anchor();protected: ~base();}; # class derived final : public base { public: ~derived();}; # int main() { return 0; }" # CXX_WONT_WARN_ON_FINAL_NONVIRTUALDTOR) # set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS}) # append_if(CXX_WONT_WARN_ON_FINAL_NONVIRTUALDTOR # "-Wnon-virtual-dtor" CMAKE_CXX_FLAGS) # HLSL Change Ends # Check if -Wcomment is OK with an // comment ending with '\' if the next # line is also a // comment. set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS}) set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -Werror -Wcomment") CHECK_C_SOURCE_COMPILES("// \\\\\\n//\\nint main() {return 0;}" C_WCOMMENT_ALLOWS_LINE_WRAP) set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS}) if (NOT C_WCOMMENT_ALLOWS_LINE_WRAP) append("-Wno-comment" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) endif() endif (LLVM_ENABLE_WARNINGS) append_if(LLVM_ENABLE_WERROR "-Werror" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) if (NOT LLVM_ENABLE_TIMESTAMPS) add_flag_if_supported("-Werror=date-time" WERROR_DATE_TIME) endif () if (LLVM_ENABLE_MODULES) set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS}) set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -fmodules -fcxx-modules") # Check that we can build code with modules enabled, and that repeatedly # including <cassert> still manages to respect NDEBUG properly. CHECK_CXX_SOURCE_COMPILES("#undef NDEBUG #include <cassert> #define NDEBUG #include <cassert> int main() { assert(this code is not compiled); }" CXX_SUPPORTS_MODULES) set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS}) if (CXX_SUPPORTS_MODULES) append_if(CXX_SUPPORTS_MODULES "-fmodules" CMAKE_C_FLAGS) append_if(CXX_SUPPORTS_MODULES "-fmodules -fcxx-modules" CMAKE_CXX_FLAGS) else() message(FATAL_ERROR "LLVM_ENABLE_MODULES is not supported by this compiler") endif() endif(LLVM_ENABLE_MODULES) endif( MSVC ) macro(append_common_sanitizer_flags) # Append -fno-omit-frame-pointer and turn on debug info to get better # stack traces. add_flag_if_supported("-fno-omit-frame-pointer" FNO_OMIT_FRAME_POINTER) if (NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" AND NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "RELWITHDEBINFO") add_flag_if_supported("-gline-tables-only" GLINE_TABLES_ONLY) endif() # Use -O1 even in debug mode, otherwise sanitizers slowdown is too large. if (uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" AND LLVM_OPTIMIZE_SANITIZED_BUILDS) add_flag_if_supported("-O1" O1) endif() endmacro() # Turn on sanitizers if necessary. if(LLVM_USE_SANITIZER) if (LLVM_ON_UNIX) if (LLVM_USE_SANITIZER STREQUAL "Address") append_common_sanitizer_flags() append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) elseif (LLVM_USE_SANITIZER MATCHES "Memory(WithOrigins)?") append_common_sanitizer_flags() append("-fsanitize=memory" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) if(LLVM_USE_SANITIZER STREQUAL "MemoryWithOrigins") append("-fsanitize-memory-track-origins" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) endif() elseif (LLVM_USE_SANITIZER STREQUAL "Undefined") append_common_sanitizer_flags() append("-fsanitize=undefined -fno-sanitize=vptr,function,alignment -fno-sanitize-recover=all" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) elseif (LLVM_USE_SANITIZER STREQUAL "Thread") append_common_sanitizer_flags() append("-fsanitize=thread" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) elseif (LLVM_USE_SANITIZER STREQUAL "Address;Undefined" OR LLVM_USE_SANITIZER STREQUAL "Undefined;Address") append_common_sanitizer_flags() append("-fsanitize=address,undefined -fno-sanitize=vptr,function,alignment -fno-sanitize-recover=all" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) else() message(FATAL_ERROR "Unsupported value of LLVM_USE_SANITIZER: ${LLVM_USE_SANITIZER}") endif() else() if (LLVM_USE_SANITIZER STREQUAL "Address") append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) else() message(FATAL_ERROR "Unsupported value of LLVM_USE_SANITIZER: ${LLVM_USE_SANITIZER}") endif() endif() if (LLVM_USE_SANITIZE_COVERAGE) append("-fsanitize-coverage=edge,indirect-calls,8bit-counters,trace-cmp" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) endif() endif() # Turn on -gsplit-dwarf if requested if(LLVM_USE_SPLIT_DWARF) add_definitions("-gsplit-dwarf") endif() add_llvm_definitions( -D__STDC_CONSTANT_MACROS ) add_llvm_definitions( -D__STDC_FORMAT_MACROS ) add_llvm_definitions( -D__STDC_LIMIT_MACROS ) # clang doesn't print colored diagnostics when invoked from Ninja if (UNIX AND CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND # HLSL Change - Update to CMake 3.13.4 CMAKE_GENERATOR STREQUAL "Ninja") append("-fcolor-diagnostics" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) endif() # HLSL Change Starts # Enable -fms-extensions for clang to use MS uuid extensions for COM. if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") append("-fms-extensions -Wno-language-extension-token" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) endif() # HLSL Change Ends # Add flags for add_dead_strip(). # FIXME: With MSVS, consider compiling with /Gy and linking with /OPT:REF? # But MinSizeRel seems to add that automatically, so maybe disable these # flags instead if LLVM_NO_DEAD_STRIP is set. if(NOT CYGWIN AND NOT WIN32) if(NOT ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" AND NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG") check_c_compiler_flag("-Werror -fno-function-sections" C_SUPPORTS_FNO_FUNCTION_SECTIONS) if (C_SUPPORTS_FNO_FUNCTION_SECTIONS) # Don't add -ffunction-section if it can be disabled with -fno-function-sections. # Doing so will break sanitizers. add_flag_if_supported("-ffunction-sections" FFUNCTION_SECTIONS) endif() add_flag_if_supported("-fdata-sections" FDATA_SECTIONS) endif() endif() if(CYGWIN OR MINGW) # Prune --out-implib from executables. It doesn't make sense even # with --export-all-symbols. string(REGEX REPLACE "-Wl,--out-implib,[^ ]+ " " " CMAKE_C_LINK_EXECUTABLE "${CMAKE_C_LINK_EXECUTABLE}") string(REGEX REPLACE "-Wl,--out-implib,[^ ]+ " " " CMAKE_CXX_LINK_EXECUTABLE "${CMAKE_CXX_LINK_EXECUTABLE}") endif() if(MSVC) # Remove flags here, for exceptions and RTTI. # Each target property or source property should be responsible to control # them. # CL.EXE complains to override flags like "/GR /GR-". string(REGEX REPLACE "(^| ) */EH[-cs]+ *( |$)" "\\1 \\2" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") string(REGEX REPLACE "(^| ) */GR-? *( |$)" "\\1 \\2" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") endif() # Provide public options to globally control RTTI and EH option(LLVM_ENABLE_EH "Enable Exception handling" OFF) option(LLVM_ENABLE_RTTI "Enable run time type information" OFF) if(LLVM_ENABLE_EH AND NOT LLVM_ENABLE_RTTI) message(FATAL_ERROR "Exception handling requires RTTI. You must set LLVM_ENABLE_RTTI to ON") endif() if (MINGW) if (LLVM_ENABLE_EH) append("-fexceptions" CMAKE_CXX_FLAGS) endif() if (LLVM_ENABLE_RTTI) append("-frtti" CMAKE_CXX_FLAGS) endif() endif() # HLSL Change Begin option(LLVM_ENABLE_LTO "Enable building with LTO" ${HLSL_OFFICIAL_BUILD}) if (LLVM_ENABLE_LTO) if(MSVC) if (CMAKE_CONFIGURATION_TYPES) set(_SUFFIX _RELEASE) endif() append("/GL" CMAKE_C_FLAGS${_SUFFIX} CMAKE_CXX_FLAGS${_SUFFIX}) append("/LTCG" CMAKE_MODULE_LINKER_FLAGS${_SUFFIX} CMAKE_MODULE_LINKER_FLAGS${_SUFFIX} CMAKE_EXE_LINKER_FLAGS${_SUFFIX}) else() add_flag_if_supported("-flto" SUPPORTS_FLTO) endif() endif() # HLSL Change End option(LLVM_BUILD_INSTRUMENTED "Build LLVM and tools with PGO instrumentation (experimental)" Off) mark_as_advanced(LLVM_BUILD_INSTRUMENTED) append_if(LLVM_BUILD_INSTRUMENTED "-fprofile-instr-generate='${LLVM_PROFILE_FILE_PATTERN}'" CMAKE_CXX_FLAGS CMAKE_C_FLAGS CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS) option(LLVM_BUILD_INSTRUMENTED_COVERAGE "Build LLVM and tools with Code Coverage instrumentation (experimental)" Off) mark_as_advanced(LLVM_BUILD_INSTRUMENTED_COVERAGE) append_if(LLVM_BUILD_INSTRUMENTED_COVERAGE "-fprofile-instr-generate='${LLVM_PROFILE_FILE_PATTERN}' -fcoverage-mapping" CMAKE_CXX_FLAGS CMAKE_C_FLAGS CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS) # Plugin support # FIXME: Make this configurable. if(WIN32 OR CYGWIN) if(BUILD_SHARED_LIBS) set(LLVM_ENABLE_PLUGINS ON) else() set(LLVM_ENABLE_PLUGINS OFF) endif() else() set(LLVM_ENABLE_PLUGINS ON) endif()
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/AddSphinxTarget.cmake
# Handy function for creating the different Sphinx targets. # # ``builder`` should be one of the supported builders used by # the sphinx-build command. # # ``project`` should be the project name function (add_sphinx_target builder project) set(SPHINX_BUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/${builder}") set(SPHINX_DOC_TREE_DIR "${CMAKE_CURRENT_BINARY_DIR}/_doctrees") set(SPHINX_TARGET_NAME docs-${project}-${builder}) if (SPHINX_WARNINGS_AS_ERRORS) set(SPHINX_WARNINGS_AS_ERRORS_FLAG "-W") else() set(SPHINX_WARNINGS_AS_ERRORS_FLAG "") endif() add_custom_target(${SPHINX_TARGET_NAME} COMMAND ${SPHINX_EXECUTABLE} -b ${builder} -d "${SPHINX_DOC_TREE_DIR}" -q # Quiet: no output other than errors and warnings. ${SPHINX_WARNINGS_AS_ERRORS_FLAG} # Treat warnings as errors if requested "${CMAKE_CURRENT_SOURCE_DIR}" # Source "${SPHINX_BUILD_DIR}" # Output COMMENT "Generating ${builder} Sphinx documentation for ${project} into \"${SPHINX_BUILD_DIR}\"") # When "clean" target is run, remove the Sphinx build directory set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES "${SPHINX_BUILD_DIR}") # We need to remove ${SPHINX_DOC_TREE_DIR} when make clean is run # but we should only add this path once get_property(_CURRENT_MAKE_CLEAN_FILES DIRECTORY PROPERTY ADDITIONAL_MAKE_CLEAN_FILES) list(FIND _CURRENT_MAKE_CLEAN_FILES "${SPHINX_DOC_TREE_DIR}" _INDEX) if (_INDEX EQUAL -1) set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES "${SPHINX_DOC_TREE_DIR}") endif() if (LLVM_BUILD_DOCS) add_dependencies(sphinx ${SPHINX_TARGET_NAME}) # Handle installation if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY) if (builder STREQUAL man) # FIXME: We might not ship all the tools that these man pages describe install(DIRECTORY "${SPHINX_BUILD_DIR}/" # Slash indicates contents of DESTINATION share/man/man1) elseif (builder STREQUAL html) install(DIRECTORY "${SPHINX_BUILD_DIR}" DESTINATION "share/doc/${project}") else() message(WARNING Installation of ${builder} not supported) endif() endif() endif() endfunction()
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/GetHostTriple.cmake
# Returns the host triple. # Invokes config.guess function( get_host_triple var ) if( MSVC ) if( CMAKE_CL_64 ) set( value "x86_64-pc-win32" ) else() set( value "i686-pc-win32" ) endif() elseif( MINGW AND NOT MSYS ) if( CMAKE_SIZEOF_VOID_P EQUAL 8 ) set( value "x86_64-w64-mingw32" ) else() set( value "i686-pc-mingw32" ) endif() else( MSVC ) set(config_guess ${LLVM_MAIN_SRC_DIR}/autoconf/config.guess) execute_process(COMMAND sh ${config_guess} RESULT_VARIABLE TT_RV OUTPUT_VARIABLE TT_OUT OUTPUT_STRIP_TRAILING_WHITESPACE) if( NOT TT_RV EQUAL 0 ) message(FATAL_ERROR "Failed to execute ${config_guess}") endif( NOT TT_RV EQUAL 0 ) set( value ${TT_OUT} ) endif( MSVC ) set( ${var} ${value} PARENT_SCOPE ) message(STATUS "Target triple: ${value}") endfunction( get_host_triple var )
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/HandleLLVMStdlib.cmake
# This CMake module is responsible for setting the standard library to libc++ # if the user has requested it. if(NOT DEFINED LLVM_STDLIB_HANDLED) set(LLVM_STDLIB_HANDLED ON) if(CMAKE_COMPILER_IS_GNUCXX) set(LLVM_COMPILER_IS_GCC_COMPATIBLE ON) elseif( MSVC ) set(LLVM_COMPILER_IS_GCC_COMPATIBLE OFF) elseif( "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang" ) set(LLVM_COMPILER_IS_GCC_COMPATIBLE ON) endif() function(append value) foreach(variable ${ARGN}) set(${variable} "${${variable}} ${value}" PARENT_SCOPE) endforeach(variable) endfunction() include(CheckCXXCompilerFlag) if(LLVM_ENABLE_LIBCXX) if(LLVM_COMPILER_IS_GCC_COMPATIBLE) check_cxx_compiler_flag("-stdlib=libc++" CXX_SUPPORTS_STDLIB) if(CXX_SUPPORTS_STDLIB) append("-stdlib=libc++" CMAKE_CXX_FLAGS CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS) if(LLVM_ENABLE_LIBCXXABI) append("-lc++abi" CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS) endif() else() message(WARNING "Can't specify libc++ with '-stdlib='") endif() else() message(WARNING "Not sure how to specify libc++ for this compiler") endif() endif() endif()
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/LLVMConfig.cmake.in
# This file provides information and services to the final user. @LLVM_CONFIG_CODE@ set(LLVM_VERSION_MAJOR @LLVM_VERSION_MAJOR@) set(LLVM_VERSION_MINOR @LLVM_VERSION_MINOR@) set(LLVM_VERSION_PATCH @LLVM_VERSION_PATCH@) set(LLVM_PACKAGE_VERSION @PACKAGE_VERSION@) set(LLVM_COMMON_DEPENDS @LLVM_COMMON_DEPENDS@) set(LLVM_AVAILABLE_LIBS @LLVM_AVAILABLE_LIBS@) set(LLVM_ALL_TARGETS @LLVM_ALL_TARGETS@) set(LLVM_TARGETS_TO_BUILD @LLVM_TARGETS_TO_BUILD@) set(LLVM_TARGETS_WITH_JIT @LLVM_TARGETS_WITH_JIT@) @all_llvm_lib_deps@ set(TARGET_TRIPLE "@TARGET_TRIPLE@") set(LLVM_ABI_BREAKING_CHECKS @LLVM_ABI_BREAKING_CHECKS@) set(LLVM_ENABLE_ASSERTIONS @LLVM_ENABLE_ASSERTIONS@) set(LLVM_ENABLE_EH @LLVM_ENABLE_EH@) set(LLVM_ENABLE_RTTI @LLVM_ENABLE_RTTI@) set(LLVM_ENABLE_TERMINFO @LLVM_ENABLE_TERMINFO@) set(LLVM_ENABLE_THREADS @LLVM_ENABLE_THREADS@) set(LLVM_ENABLE_ZLIB @LLVM_ENABLE_ZLIB@) set(LLVM_NATIVE_ARCH @LLVM_NATIVE_ARCH@) set(LLVM_ENABLE_PIC @LLVM_ENABLE_PIC@) set(LLVM_ON_UNIX @LLVM_ON_UNIX@) set(LLVM_ON_WIN32 @LLVM_ON_WIN32@) set(LLVM_LIBDIR_SUFFIX @LLVM_LIBDIR_SUFFIX@) set(LLVM_INCLUDE_DIRS "@LLVM_CONFIG_INCLUDE_DIRS@") set(LLVM_LIBRARY_DIRS "@LLVM_CONFIG_LIBRARY_DIRS@") set(LLVM_DEFINITIONS "-D__STDC_LIMIT_MACROS" "-D__STDC_CONSTANT_MACROS") set(LLVM_CMAKE_DIR "@LLVM_CONFIG_CMAKE_DIR@") set(LLVM_TOOLS_BINARY_DIR "@LLVM_CONFIG_TOOLS_BINARY_DIR@") if(NOT TARGET LLVMSupport) include("@LLVM_CONFIG_EXPORTS_FILE@") endif() include(${LLVM_CMAKE_DIR}/LLVM-Config.cmake)
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/modules/LLVMConfigVersion.cmake.in
set(PACKAGE_VERSION "@PACKAGE_VERSION@") # LLVM is API-compatible only with matching major.minor versions # and patch versions not less than that requested. if("@LLVM_VERSION_MAJOR@.@LLVM_VERSION_MINOR@" VERSION_EQUAL "${PACKAGE_FIND_VERSION_MAJOR}.${PACKAGE_FIND_VERSION_MINOR}" AND NOT "@LLVM_VERSION_PATCH@" VERSION_LESS "${PACKAGE_FIND_VERSION_PATCH}") set(PACKAGE_VERSION_COMPATIBLE 1) if("@LLVM_VERSION_PATCH@" VERSION_EQUAL "${PACKAGE_FIND_VERSION_PATCH}") set(PACKAGE_VERSION_EXACT 1) endif() endif()
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/platforms/iOS.cmake
# Toolchain config for iOS. # # Usage: # mkdir build; cd build # cmake ..; make # mkdir ios; cd ios # cmake -DLLVM_IOS_TOOLCHAIN_DIR=/path/to/ios/ndk \ # -DCMAKE_TOOLCHAIN_FILE=../../cmake/platforms/iOS.cmake ../.. # make <target> SET(CMAKE_SYSTEM_NAME Darwin) SET(CMAKE_SYSTEM_VERSION 13) SET(CMAKE_CXX_COMPILER_WORKS True) SET(CMAKE_C_COMPILER_WORKS True) SET(DARWIN_TARGET_OS_NAME ios) IF(NOT DEFINED ENV{SDKROOT}) execute_process(COMMAND xcodebuild -version -sdk iphoneos Path OUTPUT_VARIABLE SDKROOT ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) ELSE() execute_process(COMMAND xcodebuild -version -sdk $ENV{SDKROOT} Path OUTPUT_VARIABLE SDKROOT ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) ENDIF() IF(NOT EXISTS ${SDKROOT}) MESSAGE(FATAL_ERROR "SDKROOT could not be detected!") ENDIF() set(CMAKE_OSX_SYSROOT ${SDKROOT}) IF(NOT CMAKE_C_COMPILER) execute_process(COMMAND xcrun -sdk ${SDKROOT} -find clang OUTPUT_VARIABLE CMAKE_C_COMPILER ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) message(STATUS "Using c compiler ${CMAKE_C_COMPILER}") ENDIF() IF(NOT CMAKE_CXX_COMPILER) execute_process(COMMAND xcrun -sdk ${SDKROOT} -find clang++ OUTPUT_VARIABLE CMAKE_CXX_COMPILER ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) message(STATUS "Using c compiler ${CMAKE_CXX_COMPILER}") ENDIF() IF(NOT CMAKE_AR) execute_process(COMMAND xcrun -sdk ${SDKROOT} -find ar OUTPUT_VARIABLE CMAKE_AR_val ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) SET(CMAKE_AR ${CMAKE_AR_val} CACHE FILEPATH "Archiver") message(STATUS "Using ar ${CMAKE_AR}") ENDIF() IF(NOT CMAKE_RANLIB) execute_process(COMMAND xcrun -sdk ${SDKROOT} -find ranlib OUTPUT_VARIABLE CMAKE_RANLIB_val ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) SET(CMAKE_RANLIB ${CMAKE_RANLIB_val} CACHE FILEPATH "Ranlib") message(STATUS "Using ranlib ${CMAKE_RANLIB}") ENDIF() IF (NOT DEFINED IOS_MIN_TARGET) execute_process(COMMAND xcodebuild -sdk ${SDKROOT} -version SDKVersion OUTPUT_VARIABLE IOS_MIN_TARGET ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) ENDIF() SET(IOS_COMMON_FLAGS "-mios-version-min=${IOS_MIN_TARGET}") SET(CMAKE_C_FLAGS "${IOS_COMMON_FLAGS}" CACHE STRING "toolchain_cflags" FORCE) SET(CMAKE_CXX_FLAGS "${IOS_COMMON_FLAGS}" CACHE STRING "toolchain_cxxflags" FORCE) SET(CMAKE_LINK_FLAGS "${IOS_COMMON_FLAGS}" CACHE STRING "toolchain_linkflags" FORCE)
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/platforms/Android.cmake
# Toolchain config for Android NDK. # This is expected to be used with a standalone Android toolchain (see # docs/STANDALONE-TOOLCHAIN.html in the NDK on how to get one). # # Usage: # mkdir build; cd build # cmake ..; make # mkdir android; cd android # cmake -DLLVM_ANDROID_TOOLCHAIN_DIR=/path/to/android/ndk \ # -DCMAKE_TOOLCHAIN_FILE=../../cmake/platforms/Android.cmake ../.. # make <target> SET(CMAKE_SYSTEM_NAME Linux) IF(NOT CMAKE_C_COMPILER) SET(CMAKE_C_COMPILER ${CMAKE_BINARY_DIR}/../bin/clang) ENDIF() IF(NOT CMAKE_CXX_COMPILER) SET(CMAKE_CXX_COMPILER ${CMAKE_BINARY_DIR}/../bin/clang++) ENDIF() SET(ANDROID "1" CACHE STRING "ANDROID" FORCE) SET(ANDROID_COMMON_FLAGS "-target arm-linux-androideabi --sysroot=${LLVM_ANDROID_TOOLCHAIN_DIR}/sysroot -B${LLVM_ANDROID_TOOLCHAIN_DIR}") SET(CMAKE_C_FLAGS "${ANDROID_COMMON_FLAGS}" CACHE STRING "toolchain_cflags" FORCE) SET(CMAKE_CXX_FLAGS "${ANDROID_COMMON_FLAGS}" CACHE STRING "toolchain_cxxflags" FORCE) SET(CMAKE_EXE_LINKER_FLAGS "-pie" CACHE STRING "toolchain_exelinkflags" FORCE)
0
repos/DirectXShaderCompiler/cmake
repos/DirectXShaderCompiler/cmake/caches/PredefinedParams.cmake
# This file contains the basic options required for building DXC using CMake on # *nix platforms. It is passed to CMake using the `-C` flag and gets processed # before the root CMakeLists.txt file. Only cached variables persist after this # file executes, so all state must be saved into the cache. These variables also # will not override explicit command line parameters, and can only read # parameters that are specified before the `-C` flag. if (DXC_COVERAGE) set(LLVM_BUILD_INSTRUMENTED_COVERAGE ON CACHE BOOL "") set(LLVM_PROFILE_DATA_DIR "${CMAKE_BINARY_DIR}/profile" CACHE STRING "") set(LLVM_CODE_COVERAGE_TARGETS "dxc;dxcompiler" CACHE STRING "") set(LLVM_CODE_COVERAGE_TEST_TARGETS "check-all" CACHE STRING "") endif() set(CMAKE_EXPORT_COMPILE_COMMANDS ON CACHE BOOL "") set(LLVM_APPEND_VC_REV ON CACHE BOOL "") set(LLVM_DEFAULT_TARGET_TRIPLE "dxil-ms-dx" CACHE STRING "") set(LLVM_ENABLE_EH ON CACHE BOOL "") set(LLVM_ENABLE_RTTI ON CACHE BOOL "") set(LLVM_INCLUDE_DOCS OFF CACHE BOOL "") set(LLVM_INCLUDE_EXAMPLES OFF CACHE BOOL "") set(LLVM_OPTIMIZED_TABLEGEN OFF CACHE BOOL "") set(LLVM_TARGETS_TO_BUILD "None" CACHE STRING "") set(LIBCLANG_BUILD_STATIC ON CACHE BOOL "") set(CLANG_BUILD_EXAMPLES OFF CACHE BOOL "") set(CLANG_CL OFF CACHE BOOL "") set(CLANG_ENABLE_ARCMT OFF CACHE BOOL "") set(CLANG_ENABLE_STATIC_ANALYZER OFF CACHE BOOL "") set(HLSL_INCLUDE_TESTS ON CACHE BOOL "") set(ENABLE_SPIRV_CODEGEN ON CACHE BOOL "") set(SPIRV_BUILD_TESTS ON CACHE BOOL "") set(LLVM_ENABLE_TERMINFO OFF CACHE BOOL "")
0
repos/DirectXShaderCompiler
repos/DirectXShaderCompiler/tools/CMakeLists.txt
add_llvm_tool_subdirectory(llvm-config) # Build polly before the tools: the tools link against polly when # LINK_POLLY_INTO_TOOLS is set. if(WITH_POLLY) add_llvm_external_project(polly) else(WITH_POLLY) list(APPEND LLVM_IMPLICIT_PROJECT_IGNORE "${LLVM_MAIN_SRC_DIR}/tools/polly") endif(WITH_POLLY) if( LLVM_BUILD_LLVM_DYLIB ) add_llvm_tool_subdirectory(llvm-shlib) else() ignore_llvm_tool_subdirectory(llvm-shlib) endif() add_llvm_tool_subdirectory(opt) # HLSL Change add_llvm_tool_subdirectory(llvm-as) # HLSL Change add_llvm_tool_subdirectory(llvm-dis) # HLSL Change # add_llvm_tool_subdirectory(llvm-mc) # HLSL Change # HLSL Change Begins if (MSVC) # This target can currently only be built on Windows. add_llvm_tool_subdirectory(dxexp) endif (MSVC) # HLSL Change ends # add_llvm_tool_subdirectory(llc) # HLSL Change # add_llvm_tool_subdirectory(llvm-ar) # HLSL Change # add_llvm_tool_subdirectory(llvm-nm) # HLSL Change # add_llvm_tool_subdirectory(llvm-size) # HLSL Change # add_llvm_tool_subdirectory(llvm-cov) # HLSL Change # add_llvm_tool_subdirectory(llvm-profdata) # HLSL Change add_llvm_tool_subdirectory(llvm-link) # HLSL Change # add_llvm_tool_subdirectory(lli) # HLSL Change add_llvm_tool_subdirectory(llvm-extract) # HLSL Change add_llvm_tool_subdirectory(llvm-diff) # HLSL Change # add_llvm_tool_subdirectory(macho-dump) # HLSL Change # add_llvm_tool_subdirectory(llvm-objdump) # HLSL Change # add_llvm_tool_subdirectory(llvm-readobj) # HLSL Change # add_llvm_tool_subdirectory(llvm-rtdyld) # HLSL Change # add_llvm_tool_subdirectory(llvm-dwarfdump) # HLSL Change # add_llvm_tool_subdirectory(dsymutil) # HLSL Change # add_llvm_tool_subdirectory(llvm-cxxdump) # HLSL Change # HLSL Change - remove llvm-jitlistener conditional on LLVM_USE_INTEL_JITEVENTS # add_llvm_tool_subdirectory(bugpoint) # HLSL Change # add_llvm_tool_subdirectory(bugpoint-passes) # HLSL Change add_llvm_tool_subdirectory(llvm-bcanalyzer) # HLSL Change add_llvm_tool_subdirectory(llvm-stress) # HLSL Change # add_llvm_tool_subdirectory(llvm-mcmarkup) # HLSL Change add_llvm_tool_subdirectory(verify-uselistorder) # HLSL Change # add_llvm_tool_subdirectory(llvm-symbolizer) # HLSL Change # add_llvm_tool_subdirectory(llvm-c-test) # HLSL Change # add_llvm_tool_subdirectory(obj2yaml) # HLSL Change # add_llvm_tool_subdirectory(yaml2obj) # HLSL Change # add_llvm_tool_subdirectory(llvm-go) # HLSL Change # add_llvm_tool_subdirectory(llvm-pdbdump) # HLSL Change if(NOT CYGWIN AND LLVM_ENABLE_PIC) # add_llvm_tool_subdirectory(lto) # HLSL Change # add_llvm_tool_subdirectory(llvm-lto) # HLSL Change else() ignore_llvm_tool_subdirectory(lto) ignore_llvm_tool_subdirectory(llvm-lto) endif() # add_llvm_tool_subdirectory(gold) # HLSL Change add_llvm_external_project(clang) # add_llvm_external_project(llgo) # HLSL Change # add_llvm_external_project(lld) # HLSL Change # add_llvm_external_project(lldb) # HLSL Change # Automatically add remaining sub-directories containing a 'CMakeLists.txt' # file as external projects. # add_llvm_implicit_external_projects() # HLSL Change set(LLVM_COMMON_DEPENDS ${LLVM_COMMON_DEPENDS} PARENT_SCOPE)
0
repos/DirectXShaderCompiler
repos/DirectXShaderCompiler/tools/LLVMBuild.txt
;===- ./tools/LLVMBuild.txt ------------------------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [common] subdirectories = dsymutil llc lli llvm-as llvm-bcanalyzer llvm-cov llvm-diff llvm-dis llvm-dwarfdump llvm-extract llvm-link llvm-mc llvm-mcmarkup llvm-nm llvm-objdump llvm-pdbdump llvm-profdata llvm-rtdyld llvm-size macho-dump opt verify-uselistorder [component_0] type = Group name = Tools parent = $ROOT ; HLSL Changes: remove bugpoint, llvm-ar, llvm-jitlistener, llvm-lto
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/dxexp/dxexp.cpp
/////////////////////////////////////////////////////////////////////////////// // // // dxexp.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides a command-line tool to detect the status of D3D experimental // // feature support for experimental shaders. // // // /////////////////////////////////////////////////////////////////////////////// #define NOMINMAX #define WIN32_LEAN_AND_MEAN #include <atlbase.h> #include <d3d12.h> #include <dxgi1_4.h> #include <stdio.h> #include <windows.h> #pragma comment(lib, "d3d12.lib") #pragma comment(lib, "dxgi.lib") #pragma comment(lib, "dxguid.lib") // A more recent Windows SDK than currently required is needed for these. typedef HRESULT(WINAPI *D3D12EnableExperimentalFeaturesFn)( UINT NumFeatures, __in_ecount(NumFeatures) const IID *pIIDs, __in_ecount_opt(NumFeatures) void *pConfigurationStructs, __in_ecount_opt(NumFeatures) UINT *pConfigurationStructSizes); static const GUID D3D12ExperimentalShaderModelsID = {/* 76f5573e-f13a-40f5-b297-81ce9e18933f */ 0x76f5573e, 0xf13a, 0x40f5, {0xb2, 0x97, 0x81, 0xce, 0x9e, 0x18, 0x93, 0x3f}}; static HRESULT AtlCheck(HRESULT hr) { if (FAILED(hr)) AtlThrow(hr); return hr; } // Not defined in Creators Update version of d3d12.h: #if WDK_NTDDI_VERSION <= NTDDI_WIN10_RS2 #define D3D12_FEATURE_D3D12_OPTIONS3 ((D3D12_FEATURE)21) typedef enum D3D12_COMMAND_LIST_SUPPORT_FLAGS { D3D12_COMMAND_LIST_SUPPORT_FLAG_NONE = 0, D3D12_COMMAND_LIST_SUPPORT_FLAG_DIRECT = (1 << D3D12_COMMAND_LIST_TYPE_DIRECT), D3D12_COMMAND_LIST_SUPPORT_FLAG_BUNDLE = (1 << D3D12_COMMAND_LIST_TYPE_BUNDLE), D3D12_COMMAND_LIST_SUPPORT_FLAG_COMPUTE = (1 << D3D12_COMMAND_LIST_TYPE_COMPUTE), D3D12_COMMAND_LIST_SUPPORT_FLAG_COPY = (1 << D3D12_COMMAND_LIST_TYPE_COPY), D3D12_COMMAND_LIST_SUPPORT_FLAG_VIDEO_DECODE = (1 << 4), D3D12_COMMAND_LIST_SUPPORT_FLAG_VIDEO_PROCESS = (1 << 5) } D3D12_COMMAND_LIST_SUPPORT_FLAGS; typedef enum D3D12_VIEW_INSTANCING_TIER { D3D12_VIEW_INSTANCING_TIER_NOT_SUPPORTED = 0, D3D12_VIEW_INSTANCING_TIER_1 = 1, D3D12_VIEW_INSTANCING_TIER_2 = 2, D3D12_VIEW_INSTANCING_TIER_3 = 3 } D3D12_VIEW_INSTANCING_TIER; typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS3 { BOOL CopyQueueTimestampQueriesSupported; BOOL CastingFullyTypedFormatSupported; DWORD WriteBufferImmediateSupportFlags; D3D12_VIEW_INSTANCING_TIER ViewInstancingTier; BOOL BarycentricsSupported; } D3D12_FEATURE_DATA_D3D12_OPTIONS3; #endif #ifndef NTDDI_WIN10_RS3 #define NTDDI_WIN10_RS3 0x0A000004 #endif #if WDK_NTDDI_VERSION <= NTDDI_WIN10_RS3 #define D3D12_FEATURE_D3D12_OPTIONS4 ((D3D12_FEATURE)23) typedef enum D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER { D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_0, D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_1, } D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER; typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS4 { BOOL ReservedBufferPlacementSupported; D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER SharedResourceCompatibilityTier; BOOL Native16BitShaderOpsSupported; } D3D12_FEATURE_DATA_D3D12_OPTIONS4; #endif #ifndef NTDDI_WIN10_RS4 #define NTDDI_WIN10_RS4 0x0A000005 #endif #if WDK_NTDDI_VERSION <= NTDDI_WIN10_RS4 #define D3D12_FEATURE_D3D12_OPTIONS5 ((D3D12_FEATURE)27) typedef enum D3D12_RENDER_PASS_TIER { D3D12_RENDER_PASS_TIER_0 = 0, D3D12_RENDER_PASS_TIER_1 = 1, D3D12_RENDER_PASS_TIER_2 = 2 } D3D12_RENDER_PASS_TIER; typedef enum D3D12_RAYTRACING_TIER { D3D12_RAYTRACING_TIER_NOT_SUPPORTED = 0, D3D12_RAYTRACING_TIER_1_0 = 10 D3D12_RAYTRACING_TIER_1_1 = 11 } D3D12_RAYTRACING_TIER; typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS5 { BOOL SRVOnlyTiledResourceTier3; D3D12_RENDER_PASS_TIER RenderPassesTier; D3D12_RAYTRACING_TIER RaytracingTier; } D3D12_FEATURE_DATA_D3D12_OPTIONS5; #endif #ifndef NTDDI_WIN10_VB #define NTDDI_WIN10_VB 0x0A000008 #endif #if WDK_NTDDI_VERSION < NTDDI_WIN10_VB #define D3D12_FEATURE_D3D12_OPTIONS7 ((D3D12_FEATURE)32) typedef enum D3D12_MESH_SHADER_TIER { D3D12_MESH_SHADER_TIER_NOT_SUPPORTED = 0, D3D12_MESH_SHADER_TIER_1 = 10 } D3D12_MESH_SHADER_TIER; typedef enum D3D12_SAMPLER_FEEDBACK_TIER { D3D12_SAMPLER_FEEDBACK_TIER_NOT_SUPPORTED = 0, D3D12_SAMPLER_FEEDBACK_TIER_0_9 = 90, D3D12_SAMPLER_FEEDBACK_TIER_1_0 = 100 } D3D12_SAMPLER_FEEDBACK_TIER; typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS7 { D3D12_MESH_SHADER_TIER MeshShaderTier; D3D12_SAMPLER_FEEDBACK_TIER SamplerFeedbackTier; } D3D12_FEATURE_DATA_D3D12_OPTIONS7; #endif #ifndef NTDDI_WIN10_FE #define NTDDI_WIN10_FE 0x0A00000A #endif #if WDK_NTDDI_VERSION < NTDDI_WIN10_FE #define D3D12_FEATURE_D3D12_OPTIONS9 ((D3D12_FEATURE)37) typedef enum D3D12_WAVE_MMA_TIER { D3D12_WAVE_MMA_TIER_NOT_SUPPORTED = 0, D3D12_WAVE_MMA_TIER_1_0 = 10 } D3D12_WAVE_MMA_TIER; typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS9 { BOOL MeshShaderPipelineStatsSupported; BOOL MeshShaderSupportsFullRangeRenderTargetArrayIndex; BOOL AtomicInt64OnTypedResourceSupported; BOOL AtomicInt64OnGroupSharedSupported; BOOL DerivativesInMeshAndAmplificationShadersSupported; D3D12_WAVE_MMA_TIER WaveMMATier; } D3D12_FEATURE_DATA_D3D12_OPTIONS9; #endif #ifndef NTDDI_WIN10_NI #define NTDDI_WIN10_NI 0x0A00000C #endif #if WDK_NTDDI_VERSION <= NTDDI_WIN10_NI #define D3D12_FEATURE_D3D12_OPTIONS14 ((D3D12_FEATURE)43) typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS14 { BOOL AdvancedTextureOpsSupported; BOOL WriteableMSAATexturesSupported; BOOL IndependentFrontAndBackStencilRefMaskSupported; } D3D12_FEATURE_DATA_D3D12_OPTIONS14; #endif #pragma warning(disable : 4063) #define D3D12_RAYTRACING_TIER_1_1 ((D3D12_RAYTRACING_TIER)11) #define D3D_SHADER_MODEL_6_1 ((D3D_SHADER_MODEL)0x61) #define D3D_SHADER_MODEL_6_2 ((D3D_SHADER_MODEL)0x62) #define D3D_SHADER_MODEL_6_3 ((D3D_SHADER_MODEL)0x63) #define D3D_SHADER_MODEL_6_4 ((D3D_SHADER_MODEL)0x64) #define D3D_SHADER_MODEL_6_5 ((D3D_SHADER_MODEL)0x65) #define D3D_SHADER_MODEL_6_6 ((D3D_SHADER_MODEL)0x66) #define D3D_SHADER_MODEL_6_7 ((D3D_SHADER_MODEL)0x67) #define D3D_SHADER_MODEL_6_8 ((D3D_SHADER_MODEL)0x68) #define DXEXP_HIGHEST_SHADER_MODEL D3D_SHADER_MODEL_6_8 static const char *BoolToStrJson(bool value) { return value ? "true" : "false"; } static const char *BoolToStrText(bool value) { return value ? "YES" : "NO"; } static const char *(*BoolToStr)(bool value); static bool IsOutputJson; #define json_printf(...) \ if (IsOutputJson) { \ printf(__VA_ARGS__); \ } #define text_printf(...) \ if (!IsOutputJson) { \ printf(__VA_ARGS__); \ } static const char *ShaderModelToStr(D3D_SHADER_MODEL SM) { switch ((UINT32)SM) { case D3D_SHADER_MODEL_5_1: return "5.1"; case D3D_SHADER_MODEL_6_0: return "6.0"; case D3D_SHADER_MODEL_6_1: return "6.1"; case D3D_SHADER_MODEL_6_2: return "6.2"; case D3D_SHADER_MODEL_6_3: return "6.3"; case D3D_SHADER_MODEL_6_4: return "6.4"; case D3D_SHADER_MODEL_6_5: return "6.5"; case D3D_SHADER_MODEL_6_6: return "6.6"; case D3D_SHADER_MODEL_6_7: return "6.7"; case D3D_SHADER_MODEL_6_8: return "6.8"; default: return "ERROR"; } } static const char *ViewInstancingTierToStr(D3D12_VIEW_INSTANCING_TIER Tier) { switch (Tier) { case D3D12_VIEW_INSTANCING_TIER_NOT_SUPPORTED: return "NO"; case D3D12_VIEW_INSTANCING_TIER_1: return "Tier1"; case D3D12_VIEW_INSTANCING_TIER_2: return "Tier2"; case D3D12_VIEW_INSTANCING_TIER_3: return "Tier3"; default: return "ERROR"; } } static const char *RaytracingTierToStr(D3D12_RAYTRACING_TIER Tier) { switch (Tier) { case D3D12_RAYTRACING_TIER_NOT_SUPPORTED: return "NO"; case D3D12_RAYTRACING_TIER_1_0: return "1.0"; case D3D12_RAYTRACING_TIER_1_1: return "1.1"; default: return "ERROR"; } } static const char *MeshShaderTierToStr(D3D12_MESH_SHADER_TIER Tier) { switch (Tier) { case D3D12_MESH_SHADER_TIER_NOT_SUPPORTED: return "NO"; case D3D12_MESH_SHADER_TIER_1: return "1"; default: return "ERROR"; } } static const char *WaveMatrixTierToStr(D3D12_WAVE_MMA_TIER Tier) { switch (Tier) { case D3D12_WAVE_MMA_TIER_NOT_SUPPORTED: return "NO"; case D3D12_WAVE_MMA_TIER_1_0: return "1"; default: return "ERROR"; } } static HRESULT GetHighestShaderModel(ID3D12Device *pDevice, D3D12_FEATURE_DATA_SHADER_MODEL &DeviceSM) { HRESULT hr = E_INVALIDARG; D3D_SHADER_MODEL SM = DXEXP_HIGHEST_SHADER_MODEL; while (hr == E_INVALIDARG && SM >= D3D_SHADER_MODEL_6_0) { DeviceSM.HighestShaderModel = SM; hr = pDevice->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &DeviceSM, sizeof(DeviceSM)); SM = (D3D_SHADER_MODEL)((UINT32)SM - 1); } return hr; } static HRESULT PrintAdapters() { HRESULT hr = S_OK; char comma = ' '; json_printf("{ \"adapters\" : [\n"); try { CComPtr<IDXGIFactory2> pFactory; AtlCheck(CreateDXGIFactory2(0, IID_PPV_ARGS(&pFactory))); UINT AdapterIndex = 0; for (;;) { CComPtr<IDXGIAdapter1> pAdapter; CComPtr<ID3D12Device> pDevice; HRESULT hrEnum = pFactory->EnumAdapters1(AdapterIndex, &pAdapter); if (hrEnum == DXGI_ERROR_NOT_FOUND) break; AtlCheck(hrEnum); DXGI_ADAPTER_DESC1 AdapterDesc; D3D12_FEATURE_DATA_D3D12_OPTIONS1 DeviceOptions; D3D12_FEATURE_DATA_D3D12_OPTIONS3 DeviceOptions3; D3D12_FEATURE_DATA_D3D12_OPTIONS4 DeviceOptions4; D3D12_FEATURE_DATA_D3D12_OPTIONS5 DeviceOptions5; D3D12_FEATURE_DATA_D3D12_OPTIONS7 DeviceOptions7; D3D12_FEATURE_DATA_D3D12_OPTIONS9 DeviceOptions9; D3D12_FEATURE_DATA_D3D12_OPTIONS14 DeviceOptions14; memset(&DeviceOptions, 0, sizeof(DeviceOptions)); memset(&DeviceOptions3, 0, sizeof(DeviceOptions3)); memset(&DeviceOptions4, 0, sizeof(DeviceOptions4)); memset(&DeviceOptions5, 0, sizeof(DeviceOptions5)); memset(&DeviceOptions7, 0, sizeof(DeviceOptions7)); memset(&DeviceOptions9, 0, sizeof(DeviceOptions9)); memset(&DeviceOptions14, 0, sizeof(DeviceOptions14)); D3D12_FEATURE_DATA_SHADER_MODEL DeviceSM; AtlCheck(pAdapter->GetDesc1(&AdapterDesc)); AtlCheck(D3D12CreateDevice(pAdapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&pDevice))); AtlCheck(pDevice->CheckFeatureSupport( D3D12_FEATURE_D3D12_OPTIONS1, &DeviceOptions, sizeof(DeviceOptions))); pDevice->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS3, &DeviceOptions3, sizeof(DeviceOptions3)); pDevice->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS4, &DeviceOptions4, sizeof(DeviceOptions4)); pDevice->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS5, &DeviceOptions5, sizeof(DeviceOptions5)); pDevice->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &DeviceOptions7, sizeof(DeviceOptions7)); pDevice->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS9, &DeviceOptions9, sizeof(DeviceOptions9)); pDevice->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS14, &DeviceOptions14, sizeof(DeviceOptions14)); AtlCheck(GetHighestShaderModel(pDevice, DeviceSM)); const char *Format = IsOutputJson ? "%c { \"name\": \"%S\", \"sm\": \"%s\", \"wave\": %s, \"i64\": " "%s, \"bary\": %s, \"view-inst\": \"%s\", \"16bit\": %s, " "\"raytracing\": \"%s\", \"mesh\": \"%s\", \"deriv-ms-as\": " "\"%s\", \"wave-matrix\" : \"%s\", \"ato\":\"%s\" }\n" : "%c %S - Highest SM [%s] Wave [%s] I64 [%s] Barycentrics [%s] " "View Instancing [%s] 16bit Support [%s] Raytracing [%s] " "Mesh Shaders [%s] Derivatives in Mesh/Amp Shaders [%s] " "Wave Matrix [%s] Advanced Texture Ops [%s]\n"; printf( Format, comma, AdapterDesc.Description, ShaderModelToStr(DeviceSM.HighestShaderModel), BoolToStr(DeviceOptions.WaveOps), BoolToStr(DeviceOptions.Int64ShaderOps), BoolToStr(DeviceOptions3.BarycentricsSupported), ViewInstancingTierToStr(DeviceOptions3.ViewInstancingTier), BoolToStr(DeviceOptions4.Native16BitShaderOpsSupported), RaytracingTierToStr(DeviceOptions5.RaytracingTier), MeshShaderTierToStr(DeviceOptions7.MeshShaderTier), BoolToStr( DeviceOptions9.DerivativesInMeshAndAmplificationShadersSupported), WaveMatrixTierToStr(DeviceOptions9.WaveMMATier), BoolToStr(DeviceOptions14.AdvancedTextureOpsSupported)); AdapterIndex++; comma = IsOutputJson ? ',' : ' '; } } catch (ATL::CAtlException &e) { hr = e.m_hr; json_printf("%c { \"err\": \"unable to print information for adapters - " "0x%08x\" }\n", comma, (unsigned int)hr); text_printf("%s", "Unable to print information for adapters.\n"); } json_printf(" ] }\n"); return hr; } // Return codes: // 0 - experimental mode worked // 1 - cannot load d3d12.dll // 2 - cannot find D3D12EnableExperimentalFeatures // 3 - experimental shader mode interface unsupported // 4 - other error int main(int argc, const char *argv[]) { BoolToStr = BoolToStrText; IsOutputJson = false; if (argc > 1) { const char *pArg = argv[1]; if (0 == strcmp(pArg, "-?") || 0 == strcmp(pArg, "--?") || 0 == strcmp(pArg, "/?")) { printf("Checks the available of D3D support for experimental shader " "models.\n\n"); printf("dxexp [-json]\n\n"); printf("Sets errorlevel to 0 on success, non-zero for failure cases.\n"); return 4; } else if (0 == strcmp(pArg, "-json") || 0 == strcmp(pArg, "/json")) { IsOutputJson = true; BoolToStr = BoolToStrJson; } else { printf("Unrecognized command line arguments.\n"); return 4; } } DWORD err; HMODULE hRuntime; hRuntime = LoadLibraryW(L"d3d12.dll"); if (hRuntime == NULL) { err = GetLastError(); printf("Failed to load library d3d12.dll - Win32 error %u\n", (unsigned int)err); return 1; } json_printf("{ \"noexp\":\n"); text_printf( "Adapter feature support without experimental shaders enabled:\n"); if (FAILED(PrintAdapters())) { return 4; } FreeLibrary(hRuntime); json_printf(" , \"exp\":"); text_printf( "-------------------------------------------------------------\n"); hRuntime = LoadLibraryW(L"d3d12.dll"); if (hRuntime == NULL) { err = GetLastError(); printf("Failed to load library d3d12.dll - Win32 error %u\n", (unsigned int)err); return 1; } D3D12EnableExperimentalFeaturesFn pD3D12EnableExperimentalFeatures = (D3D12EnableExperimentalFeaturesFn)GetProcAddress( hRuntime, "D3D12EnableExperimentalFeatures"); if (pD3D12EnableExperimentalFeatures == nullptr) { err = GetLastError(); printf("Failed to find export 'D3D12EnableExperimentalFeatures' in " "d3d12.dll - Win32 error %u%s\n", (unsigned int)err, err == ERROR_PROC_NOT_FOUND ? " (The specified procedure could not be found.)" : ""); printf("Consider verifying the operating system version - Creators Update " "or newer " "is currently required.\n"); PrintAdapters(); return 2; } HRESULT hr = pD3D12EnableExperimentalFeatures( 1, &D3D12ExperimentalShaderModelsID, nullptr, nullptr); if (SUCCEEDED(hr)) { text_printf("Experimental shader model feature succeeded.\n"); hr = PrintAdapters(); json_printf("\n}\n"); return (SUCCEEDED(hr)) ? 0 : 4; } else if (hr == E_NOINTERFACE) { text_printf( "Experimental shader model feature failed with error E_NOINTERFACE.\n"); text_printf( "The most likely cause is that Windows Developer mode is not on.\n"); text_printf("See " "https://msdn.microsoft.com/en-us/windows/uwp/get-started/" "enable-your-device-for-development\n"); json_printf("{ \"err\": \"E_NOINTERFACE\" }"); json_printf("\n}\n"); return 3; } else if (hr == E_INVALIDARG) { text_printf( "Experimental shader model feature failed with error E_INVALIDARG.\n"); text_printf("This means the configuration of a feature is incorrect, the " "set of features passed\n" "in are known to be incompatible with each other, or other " "errors occured,\n" "and is generally unexpected for the experimental shader model " "feature.\n"); json_printf("{ \"err\": \"E_INVALIDARG\" }"); json_printf("\n}\n"); return 4; } else { text_printf("Experimental shader model feature failed with unexpected " "HRESULT 0x%08x.\n", (unsigned int)hr); json_printf("{ \"err\": \"0x%08x\" }", (unsigned int)hr); json_printf("\n}\n"); return 4; } }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/dxexp/CMakeLists.txt
# Copyright (C) Microsoft Corporation. All rights reserved. # This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details. add_llvm_tool(dxexp dxexp.cpp ) find_package(D3D12 REQUIRED) target_link_libraries(dxexp ${D3D12_LIBRARIES} dxguid.lib )
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/dxexp/LLVMBuild.txt
; Copyright (C) Microsoft Corporation. All rights reserved. ; This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details. ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Tool name = dxexp parent = Tools required_libraries =
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cov/RenderingSupport.h
//===- RenderingSupport.h - output stream rendering support functions ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_COV_RENDERINGSUPPORT_H #define LLVM_COV_RENDERINGSUPPORT_H #include "llvm/Support/raw_ostream.h" #include <utility> namespace llvm { /// \brief A helper class that resets the output stream's color if needed /// when destroyed. class ColoredRawOstream { ColoredRawOstream(const ColoredRawOstream &OS) = delete; public: raw_ostream &OS; bool IsColorUsed; ColoredRawOstream(raw_ostream &OS, bool IsColorUsed) : OS(OS), IsColorUsed(IsColorUsed) {} ColoredRawOstream(ColoredRawOstream &&Other) : OS(Other.OS), IsColorUsed(Other.IsColorUsed) { // Reset the other IsColorUsed so that the other object won't reset the // color when destroyed. Other.IsColorUsed = false; } ~ColoredRawOstream() { if (IsColorUsed) OS.resetColor(); } }; template <typename T> inline raw_ostream &operator<<(const ColoredRawOstream &OS, T &&Value) { return OS.OS << std::forward<T>(Value); } /// \brief Change the color of the output stream if the `IsColorUsed` flag /// is true. Returns an object that resets the color when destroyed. inline ColoredRawOstream colored_ostream(raw_ostream &OS, raw_ostream::Colors Color, bool IsColorUsed = true, bool Bold = false, bool BG = false) { if (IsColorUsed) OS.changeColor(Color, Bold, BG); return ColoredRawOstream(OS, IsColorUsed); } } #endif // LLVM_COV_RENDERINGSUPPORT_H
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cov/SourceCoverageView.h
//===- SourceCoverageView.h - Code coverage view for source code ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This class implements rendering for code coverage of source code. // //===----------------------------------------------------------------------===// #ifndef LLVM_COV_SOURCECOVERAGEVIEW_H #define LLVM_COV_SOURCECOVERAGEVIEW_H #include "CoverageViewOptions.h" #include "llvm/ProfileData/CoverageMapping.h" #include "llvm/Support/MemoryBuffer.h" #include <vector> namespace llvm { class SourceCoverageView; /// \brief A view that represents a macro or include expansion struct ExpansionView { coverage::CounterMappingRegion Region; std::unique_ptr<SourceCoverageView> View; ExpansionView(const coverage::CounterMappingRegion &Region, std::unique_ptr<SourceCoverageView> View) : Region(Region), View(std::move(View)) {} ExpansionView(ExpansionView &&RHS) : Region(std::move(RHS.Region)), View(std::move(RHS.View)) {} ExpansionView &operator=(ExpansionView &&RHS) { Region = std::move(RHS.Region); View = std::move(RHS.View); return *this; } unsigned getLine() const { return Region.LineStart; } unsigned getStartCol() const { return Region.ColumnStart; } unsigned getEndCol() const { return Region.ColumnEnd; } friend bool operator<(const ExpansionView &LHS, const ExpansionView &RHS) { return LHS.Region.startLoc() < RHS.Region.startLoc(); } }; /// \brief A view that represents a function instantiation struct InstantiationView { StringRef FunctionName; unsigned Line; std::unique_ptr<SourceCoverageView> View; InstantiationView(StringRef FunctionName, unsigned Line, std::unique_ptr<SourceCoverageView> View) : FunctionName(FunctionName), Line(Line), View(std::move(View)) {} InstantiationView(InstantiationView &&RHS) : FunctionName(std::move(RHS.FunctionName)), Line(std::move(RHS.Line)), View(std::move(RHS.View)) {} InstantiationView &operator=(InstantiationView &&RHS) { FunctionName = std::move(RHS.FunctionName); Line = std::move(RHS.Line); View = std::move(RHS.View); return *this; } friend bool operator<(const InstantiationView &LHS, const InstantiationView &RHS) { return LHS.Line < RHS.Line; } }; /// \brief A code coverage view of a specific source file. /// It can have embedded coverage views. class SourceCoverageView { private: /// \brief Coverage information for a single line. struct LineCoverageInfo { uint64_t ExecutionCount; unsigned RegionCount; bool Mapped; LineCoverageInfo() : ExecutionCount(0), RegionCount(0), Mapped(false) {} bool isMapped() const { return Mapped; } bool hasMultipleRegions() const { return RegionCount > 1; } void addRegionStartCount(uint64_t Count) { // The max of all region starts is the most interesting value. addRegionCount(RegionCount ? std::max(ExecutionCount, Count) : Count); ++RegionCount; } void addRegionCount(uint64_t Count) { Mapped = true; ExecutionCount = Count; } }; const MemoryBuffer &File; const CoverageViewOptions &Options; coverage::CoverageData CoverageInfo; std::vector<ExpansionView> ExpansionSubViews; std::vector<InstantiationView> InstantiationSubViews; /// \brief Render a source line with highlighting. void renderLine(raw_ostream &OS, StringRef Line, int64_t LineNumber, const coverage::CoverageSegment *WrappedSegment, ArrayRef<const coverage::CoverageSegment *> Segments, unsigned ExpansionCol); void renderIndent(raw_ostream &OS, unsigned Level); void renderViewDivider(unsigned Offset, unsigned Length, raw_ostream &OS); /// \brief Render the line's execution count column. void renderLineCoverageColumn(raw_ostream &OS, const LineCoverageInfo &Line); /// \brief Render the line number column. void renderLineNumberColumn(raw_ostream &OS, unsigned LineNo); /// \brief Render all the region's execution counts on a line. void renderRegionMarkers(raw_ostream &OS, ArrayRef<const coverage::CoverageSegment *> Segments); static const unsigned LineCoverageColumnWidth = 7; static const unsigned LineNumberColumnWidth = 5; public: SourceCoverageView(const MemoryBuffer &File, const CoverageViewOptions &Options, coverage::CoverageData &&CoverageInfo) : File(File), Options(Options), CoverageInfo(std::move(CoverageInfo)) {} const CoverageViewOptions &getOptions() const { return Options; } /// \brief Add an expansion subview to this view. void addExpansion(const coverage::CounterMappingRegion &Region, std::unique_ptr<SourceCoverageView> View) { ExpansionSubViews.emplace_back(Region, std::move(View)); } /// \brief Add a function instantiation subview to this view. void addInstantiation(StringRef FunctionName, unsigned Line, std::unique_ptr<SourceCoverageView> View) { InstantiationSubViews.emplace_back(FunctionName, Line, std::move(View)); } /// \brief Print the code coverage information for a specific /// portion of a source file to the output stream. void render(raw_ostream &OS, bool WholeFile, unsigned IndentLevel = 0); }; } // namespace llvm #endif // LLVM_COV_SOURCECOVERAGEVIEW_H
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cov/CoverageSummaryInfo.h
//===- CoverageSummaryInfo.h - Coverage summary for function/file ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // These structures are used to represent code coverage metrics // for functions/files. // //===----------------------------------------------------------------------===// #ifndef LLVM_COV_COVERAGESUMMARYINFO_H #define LLVM_COV_COVERAGESUMMARYINFO_H #include "llvm/ProfileData/CoverageMapping.h" #include "llvm/Support/raw_ostream.h" namespace llvm { /// \brief Provides information about region coverage for a function/file. struct RegionCoverageInfo { /// \brief The number of regions that were executed at least once. size_t Covered; /// \brief The number of regions that weren't executed. size_t NotCovered; /// \brief The total number of regions in a function/file. size_t NumRegions; RegionCoverageInfo() : Covered(0), NotCovered(0), NumRegions(0) {} RegionCoverageInfo(size_t Covered, size_t NumRegions) : Covered(Covered), NotCovered(NumRegions - Covered), NumRegions(NumRegions) {} RegionCoverageInfo &operator+=(const RegionCoverageInfo &RHS) { Covered += RHS.Covered; NotCovered += RHS.NotCovered; NumRegions += RHS.NumRegions; return *this; } bool isFullyCovered() const { return Covered == NumRegions; } double getPercentCovered() const { return double(Covered) / double(NumRegions) * 100.0; } }; /// \brief Provides information about line coverage for a function/file. struct LineCoverageInfo { /// \brief The number of lines that were executed at least once. size_t Covered; /// \brief The number of lines that weren't executed. size_t NotCovered; /// \brief The number of lines that aren't code. size_t NonCodeLines; /// \brief The total number of lines in a function/file. size_t NumLines; LineCoverageInfo() : Covered(0), NotCovered(0), NonCodeLines(0), NumLines(0) {} LineCoverageInfo(size_t Covered, size_t NumNonCodeLines, size_t NumLines) : Covered(Covered), NotCovered(NumLines - NumNonCodeLines - Covered), NonCodeLines(NumNonCodeLines), NumLines(NumLines) {} LineCoverageInfo &operator+=(const LineCoverageInfo &RHS) { Covered += RHS.Covered; NotCovered += RHS.NotCovered; NonCodeLines += RHS.NonCodeLines; NumLines += RHS.NumLines; return *this; } bool isFullyCovered() const { return Covered == (NumLines - NonCodeLines); } double getPercentCovered() const { return double(Covered) / double(NumLines - NonCodeLines) * 100.0; } }; /// \brief Provides information about function coverage for a file. struct FunctionCoverageInfo { /// \brief The number of functions that were executed. size_t Executed; /// \brief The total number of functions in this file. size_t NumFunctions; FunctionCoverageInfo() : Executed(0), NumFunctions(0) {} FunctionCoverageInfo(size_t Executed, size_t NumFunctions) : Executed(Executed), NumFunctions(NumFunctions) {} void addFunction(bool Covered) { if (Covered) ++Executed; ++NumFunctions; } bool isFullyCovered() const { return Executed == NumFunctions; } double getPercentCovered() const { return double(Executed) / double(NumFunctions) * 100.0; } }; /// \brief A summary of function's code coverage. struct FunctionCoverageSummary { StringRef Name; uint64_t ExecutionCount; RegionCoverageInfo RegionCoverage; LineCoverageInfo LineCoverage; FunctionCoverageSummary(StringRef Name) : Name(Name), ExecutionCount(0) {} FunctionCoverageSummary(StringRef Name, uint64_t ExecutionCount, const RegionCoverageInfo &RegionCoverage, const LineCoverageInfo &LineCoverage) : Name(Name), ExecutionCount(ExecutionCount), RegionCoverage(RegionCoverage), LineCoverage(LineCoverage) { } /// \brief Compute the code coverage summary for the given function coverage /// mapping record. static FunctionCoverageSummary get(const coverage::FunctionRecord &Function); }; /// \brief A summary of file's code coverage. struct FileCoverageSummary { StringRef Name; RegionCoverageInfo RegionCoverage; LineCoverageInfo LineCoverage; FunctionCoverageInfo FunctionCoverage; FileCoverageSummary(StringRef Name) : Name(Name) {} void addFunction(const FunctionCoverageSummary &Function) { RegionCoverage += Function.RegionCoverage; LineCoverage += Function.LineCoverage; FunctionCoverage.addFunction(/*Covered=*/Function.ExecutionCount > 0); } }; } // namespace llvm #endif // LLVM_COV_COVERAGESUMMARYINFO_H
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cov/SourceCoverageView.cpp
//===- SourceCoverageView.cpp - Code coverage view for source code --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This class implements rendering for code coverage of source code. // //===----------------------------------------------------------------------===// #include "SourceCoverageView.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/LineIterator.h" using namespace llvm; void SourceCoverageView::renderLine( raw_ostream &OS, StringRef Line, int64_t LineNumber, const coverage::CoverageSegment *WrappedSegment, ArrayRef<const coverage::CoverageSegment *> Segments, unsigned ExpansionCol) { Optional<raw_ostream::Colors> Highlight; SmallVector<std::pair<unsigned, unsigned>, 2> HighlightedRanges; // The first segment overlaps from a previous line, so we treat it specially. if (WrappedSegment && WrappedSegment->HasCount && WrappedSegment->Count == 0) Highlight = raw_ostream::RED; // Output each segment of the line, possibly highlighted. unsigned Col = 1; for (const auto *S : Segments) { unsigned End = std::min(S->Col, static_cast<unsigned>(Line.size()) + 1); colored_ostream(OS, Highlight ? *Highlight : raw_ostream::SAVEDCOLOR, Options.Colors && Highlight, /*Bold=*/false, /*BG=*/true) << Line.substr(Col - 1, End - Col); if (Options.Debug && Highlight) HighlightedRanges.push_back(std::make_pair(Col, End)); Col = End; if (Col == ExpansionCol) Highlight = raw_ostream::CYAN; else if (S->HasCount && S->Count == 0) Highlight = raw_ostream::RED; else Highlight = None; } // Show the rest of the line colored_ostream(OS, Highlight ? *Highlight : raw_ostream::SAVEDCOLOR, Options.Colors && Highlight, /*Bold=*/false, /*BG=*/true) << Line.substr(Col - 1, Line.size() - Col + 1); OS << "\n"; if (Options.Debug) { for (const auto &Range : HighlightedRanges) errs() << "Highlighted line " << LineNumber << ", " << Range.first << " -> " << Range.second << "\n"; if (Highlight) errs() << "Highlighted line " << LineNumber << ", " << Col << " -> ?\n"; } } void SourceCoverageView::renderIndent(raw_ostream &OS, unsigned Level) { for (unsigned I = 0; I < Level; ++I) OS << " |"; } void SourceCoverageView::renderViewDivider(unsigned Level, unsigned Length, raw_ostream &OS) { assert(Level != 0 && "Cannot render divider at top level"); renderIndent(OS, Level - 1); OS.indent(2); for (unsigned I = 0; I < Length; ++I) OS << "-"; } /// Format a count using engineering notation with 3 significant digits. static std::string formatCount(uint64_t N) { std::string Number = utostr(N); int Len = Number.size(); if (Len <= 3) return Number; int IntLen = Len % 3 == 0 ? 3 : Len % 3; std::string Result(Number.data(), IntLen); if (IntLen != 3) { Result.push_back('.'); Result += Number.substr(IntLen, 3 - IntLen); } Result.push_back(" kMGTPEZY"[(Len - 1) / 3]); return Result; } void SourceCoverageView::renderLineCoverageColumn(raw_ostream &OS, const LineCoverageInfo &Line) { if (!Line.isMapped()) { OS.indent(LineCoverageColumnWidth) << '|'; return; } std::string C = formatCount(Line.ExecutionCount); OS.indent(LineCoverageColumnWidth - C.size()); colored_ostream(OS, raw_ostream::MAGENTA, Line.hasMultipleRegions() && Options.Colors) << C; OS << '|'; } void SourceCoverageView::renderLineNumberColumn(raw_ostream &OS, unsigned LineNo) { SmallString<32> Buffer; raw_svector_ostream BufferOS(Buffer); BufferOS << LineNo; auto Str = BufferOS.str(); // Trim and align to the right Str = Str.substr(0, std::min(Str.size(), (size_t)LineNumberColumnWidth)); OS.indent(LineNumberColumnWidth - Str.size()) << Str << '|'; } void SourceCoverageView::renderRegionMarkers( raw_ostream &OS, ArrayRef<const coverage::CoverageSegment *> Segments) { unsigned PrevColumn = 1; for (const auto *S : Segments) { if (!S->IsRegionEntry) continue; // Skip to the new region if (S->Col > PrevColumn) OS.indent(S->Col - PrevColumn); PrevColumn = S->Col + 1; std::string C = formatCount(S->Count); PrevColumn += C.size(); OS << '^' << C; } OS << "\n"; if (Options.Debug) for (const auto *S : Segments) errs() << "Marker at " << S->Line << ":" << S->Col << " = " << formatCount(S->Count) << (S->IsRegionEntry ? "\n" : " (pop)\n"); } void SourceCoverageView::render(raw_ostream &OS, bool WholeFile, unsigned IndentLevel) { // The width of the leading columns unsigned CombinedColumnWidth = (Options.ShowLineStats ? LineCoverageColumnWidth + 1 : 0) + (Options.ShowLineNumbers ? LineNumberColumnWidth + 1 : 0); // The width of the line that is used to divide between the view and the // subviews. unsigned DividerWidth = CombinedColumnWidth + 4; // We need the expansions and instantiations sorted so we can go through them // while we iterate lines. std::sort(ExpansionSubViews.begin(), ExpansionSubViews.end()); std::sort(InstantiationSubViews.begin(), InstantiationSubViews.end()); auto NextESV = ExpansionSubViews.begin(); auto EndESV = ExpansionSubViews.end(); auto NextISV = InstantiationSubViews.begin(); auto EndISV = InstantiationSubViews.end(); // Get the coverage information for the file. auto NextSegment = CoverageInfo.begin(); auto EndSegment = CoverageInfo.end(); unsigned FirstLine = NextSegment != EndSegment ? NextSegment->Line : 0; const coverage::CoverageSegment *WrappedSegment = nullptr; SmallVector<const coverage::CoverageSegment *, 8> LineSegments; for (line_iterator LI(File, /*SkipBlanks=*/false); !LI.is_at_eof(); ++LI) { // If we aren't rendering the whole file, we need to filter out the prologue // and epilogue. if (!WholeFile) { if (NextSegment == EndSegment) break; else if (LI.line_number() < FirstLine) continue; } // Collect the coverage information relevant to this line. if (LineSegments.size()) WrappedSegment = LineSegments.back(); LineSegments.clear(); while (NextSegment != EndSegment && NextSegment->Line == LI.line_number()) LineSegments.push_back(&*NextSegment++); // Calculate a count to be for the line as a whole. LineCoverageInfo LineCount; if (WrappedSegment && WrappedSegment->HasCount) LineCount.addRegionCount(WrappedSegment->Count); for (const auto *S : LineSegments) if (S->HasCount && S->IsRegionEntry) LineCount.addRegionStartCount(S->Count); // Render the line prefix. renderIndent(OS, IndentLevel); if (Options.ShowLineStats) renderLineCoverageColumn(OS, LineCount); if (Options.ShowLineNumbers) renderLineNumberColumn(OS, LI.line_number()); // If there are expansion subviews, we want to highlight the first one. unsigned ExpansionColumn = 0; if (NextESV != EndESV && NextESV->getLine() == LI.line_number() && Options.Colors) ExpansionColumn = NextESV->getStartCol(); // Display the source code for the current line. renderLine(OS, *LI, LI.line_number(), WrappedSegment, LineSegments, ExpansionColumn); // Show the region markers. if (Options.ShowRegionMarkers && (!Options.ShowLineStatsOrRegionMarkers || LineCount.hasMultipleRegions()) && !LineSegments.empty()) { renderIndent(OS, IndentLevel); OS.indent(CombinedColumnWidth); renderRegionMarkers(OS, LineSegments); } // Show the expansions and instantiations for this line. unsigned NestedIndent = IndentLevel + 1; bool RenderedSubView = false; for (; NextESV != EndESV && NextESV->getLine() == LI.line_number(); ++NextESV) { renderViewDivider(NestedIndent, DividerWidth, OS); OS << "\n"; if (RenderedSubView) { // Re-render the current line and highlight the expansion range for // this subview. ExpansionColumn = NextESV->getStartCol(); renderIndent(OS, IndentLevel); OS.indent(CombinedColumnWidth + (IndentLevel == 0 ? 0 : 1)); renderLine(OS, *LI, LI.line_number(), WrappedSegment, LineSegments, ExpansionColumn); renderViewDivider(NestedIndent, DividerWidth, OS); OS << "\n"; } // Render the child subview if (Options.Debug) errs() << "Expansion at line " << NextESV->getLine() << ", " << NextESV->getStartCol() << " -> " << NextESV->getEndCol() << "\n"; NextESV->View->render(OS, false, NestedIndent); RenderedSubView = true; } for (; NextISV != EndISV && NextISV->Line == LI.line_number(); ++NextISV) { renderViewDivider(NestedIndent, DividerWidth, OS); OS << "\n"; renderIndent(OS, NestedIndent); OS << ' '; Options.colored_ostream(OS, raw_ostream::CYAN) << NextISV->FunctionName << ":"; OS << "\n"; NextISV->View->render(OS, false, NestedIndent); RenderedSubView = true; } if (RenderedSubView) { renderViewDivider(NestedIndent, DividerWidth, OS); OS << "\n"; } } }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cov/gcov.cpp
//===- gcov.cpp - GCOV compatible LLVM coverage tool ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // llvm-cov is a command line tools to analyze and report coverage information. // //===----------------------------------------------------------------------===// #include "llvm/ADT/SmallString.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Errc.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/GCOV.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Path.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include <system_error> using namespace llvm; static void reportCoverage(StringRef SourceFile, StringRef ObjectDir, const std::string &InputGCNO, const std::string &InputGCDA, bool DumpGCOV, const GCOVOptions &Options) { SmallString<128> CoverageFileStem(ObjectDir); if (CoverageFileStem.empty()) { // If no directory was specified with -o, look next to the source file. CoverageFileStem = sys::path::parent_path(SourceFile); sys::path::append(CoverageFileStem, sys::path::stem(SourceFile)); } else if (sys::fs::is_directory(ObjectDir)) // A directory name was given. Use it and the source file name. sys::path::append(CoverageFileStem, sys::path::stem(SourceFile)); else // A file was given. Ignore the source file and look next to this file. sys::path::replace_extension(CoverageFileStem, ""); std::string GCNO = InputGCNO.empty() ? std::string(CoverageFileStem.str()) + ".gcno" : InputGCNO; std::string GCDA = InputGCDA.empty() ? std::string(CoverageFileStem.str()) + ".gcda" : InputGCDA; GCOVFile GF; ErrorOr<std::unique_ptr<MemoryBuffer>> GCNO_Buff = MemoryBuffer::getFileOrSTDIN(GCNO); if (std::error_code EC = GCNO_Buff.getError()) { errs() << GCNO << ": " << EC.message() << "\n"; return; } GCOVBuffer GCNO_GB(GCNO_Buff.get().get()); if (!GF.readGCNO(GCNO_GB)) { errs() << "Invalid .gcno File!\n"; return; } ErrorOr<std::unique_ptr<MemoryBuffer>> GCDA_Buff = MemoryBuffer::getFileOrSTDIN(GCDA); if (std::error_code EC = GCDA_Buff.getError()) { if (EC != errc::no_such_file_or_directory) { errs() << GCDA << ": " << EC.message() << "\n"; return; } // Clear the filename to make it clear we didn't read anything. GCDA = "-"; } else { GCOVBuffer GCDA_GB(GCDA_Buff.get().get()); if (!GF.readGCDA(GCDA_GB)) { errs() << "Invalid .gcda File!\n"; return; } } if (DumpGCOV) GF.dump(); FileInfo FI(Options); GF.collectLineCounts(FI); FI.print(llvm::outs(), SourceFile, GCNO, GCDA); } int gcovMain(int argc, const char *argv[]) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::list<std::string> SourceFiles(cl::Positional, cl::OneOrMore, cl::desc("SOURCEFILE")); cl::opt<bool> AllBlocks("a", cl::Grouping, cl::init(false), cl::desc("Display all basic blocks")); cl::alias AllBlocksA("all-blocks", cl::aliasopt(AllBlocks)); cl::opt<bool> BranchProb("b", cl::Grouping, cl::init(false), cl::desc("Display branch probabilities")); cl::alias BranchProbA("branch-probabilities", cl::aliasopt(BranchProb)); cl::opt<bool> BranchCount("c", cl::Grouping, cl::init(false), cl::desc("Display branch counts instead " "of percentages (requires -b)")); cl::alias BranchCountA("branch-counts", cl::aliasopt(BranchCount)); cl::opt<bool> LongNames("l", cl::Grouping, cl::init(false), cl::desc("Prefix filenames with the main file")); cl::alias LongNamesA("long-file-names", cl::aliasopt(LongNames)); cl::opt<bool> FuncSummary("f", cl::Grouping, cl::init(false), cl::desc("Show coverage for each function")); cl::alias FuncSummaryA("function-summaries", cl::aliasopt(FuncSummary)); cl::opt<bool> NoOutput("n", cl::Grouping, cl::init(false), cl::desc("Do not output any .gcov files")); cl::alias NoOutputA("no-output", cl::aliasopt(NoOutput)); cl::opt<std::string> ObjectDir( "o", cl::value_desc("DIR|FILE"), cl::init(""), cl::desc("Find objects in DIR or based on FILE's path")); cl::alias ObjectDirA("object-directory", cl::aliasopt(ObjectDir)); cl::alias ObjectDirB("object-file", cl::aliasopt(ObjectDir)); cl::opt<bool> PreservePaths("p", cl::Grouping, cl::init(false), cl::desc("Preserve path components")); cl::alias PreservePathsA("preserve-paths", cl::aliasopt(PreservePaths)); cl::opt<bool> UncondBranch("u", cl::Grouping, cl::init(false), cl::desc("Display unconditional branch info " "(requires -b)")); cl::alias UncondBranchA("unconditional-branches", cl::aliasopt(UncondBranch)); cl::OptionCategory DebugCat("Internal and debugging options"); cl::opt<bool> DumpGCOV("dump", cl::init(false), cl::cat(DebugCat), cl::desc("Dump the gcov file to stderr")); cl::opt<std::string> InputGCNO("gcno", cl::cat(DebugCat), cl::init(""), cl::desc("Override inferred gcno file")); cl::opt<std::string> InputGCDA("gcda", cl::cat(DebugCat), cl::init(""), cl::desc("Override inferred gcda file")); cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n"); GCOVOptions Options(AllBlocks, BranchProb, BranchCount, FuncSummary, PreservePaths, UncondBranch, LongNames, NoOutput); for (const auto &SourceFile : SourceFiles) reportCoverage(SourceFile, ObjectDir, InputGCNO, InputGCDA, DumpGCOV, Options); return 0; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cov/CoverageReport.h
//===- CoverageReport.h - Code coverage report ---------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This class implements rendering of a code coverage report. // //===----------------------------------------------------------------------===// #ifndef LLVM_COV_COVERAGEREPORT_H #define LLVM_COV_COVERAGEREPORT_H #include "CoverageSummaryInfo.h" #include "CoverageViewOptions.h" namespace llvm { /// \brief Displays the code coverage report. class CoverageReport { const CoverageViewOptions &Options; std::unique_ptr<coverage::CoverageMapping> Coverage; void render(const FileCoverageSummary &File, raw_ostream &OS); void render(const FunctionCoverageSummary &Function, raw_ostream &OS); public: CoverageReport(const CoverageViewOptions &Options, std::unique_ptr<coverage::CoverageMapping> Coverage) : Options(Options), Coverage(std::move(Coverage)) {} void renderFunctionReports(ArrayRef<std::string> Files, raw_ostream &OS); void renderFileReports(raw_ostream &OS); }; } #endif // LLVM_COV_COVERAGEREPORT_H
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cov/CoverageViewOptions.h
//===- CoverageViewOptions.h - Code coverage display options -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_COV_COVERAGEVIEWOPTIONS_H #define LLVM_COV_COVERAGEVIEWOPTIONS_H #include "RenderingSupport.h" namespace llvm { /// \brief The options for displaying the code coverage information. struct CoverageViewOptions { bool Debug; bool Colors; bool ShowLineNumbers; bool ShowLineStats; bool ShowRegionMarkers; bool ShowLineStatsOrRegionMarkers; bool ShowExpandedRegions; bool ShowFunctionInstantiations; /// \brief Change the output's stream color if the colors are enabled. ColoredRawOstream colored_ostream(raw_ostream &OS, raw_ostream::Colors Color) const { return llvm::colored_ostream(OS, Color, Colors); } }; } #endif // LLVM_COV_COVERAGEVIEWOPTIONS_H
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cov/CMakeLists.txt
set(LLVM_LINK_COMPONENTS core support object profiledata) add_llvm_tool(llvm-cov llvm-cov.cpp gcov.cpp CodeCoverage.cpp CoverageFilters.cpp CoverageReport.cpp CoverageSummaryInfo.cpp SourceCoverageView.cpp TestingSupport.cpp )
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cov/CoverageFilters.h
//===- CoverageFilters.h - Function coverage mapping filters --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // These classes provide filtering for function coverage mapping records. // //===----------------------------------------------------------------------===// #ifndef LLVM_COV_COVERAGEFILTERS_H #define LLVM_COV_COVERAGEFILTERS_H #include "llvm/ProfileData/CoverageMapping.h" #include <memory> #include <vector> namespace llvm { /// \brief Matches specific functions that pass the requirement of this filter. class CoverageFilter { public: virtual ~CoverageFilter() {} /// \brief Return true if the function passes the requirements of this filter. virtual bool matches(const coverage::FunctionRecord &Function) { return true; } }; /// \brief Matches functions that contain a specific string in their name. class NameCoverageFilter : public CoverageFilter { StringRef Name; public: NameCoverageFilter(StringRef Name) : Name(Name) {} bool matches(const coverage::FunctionRecord &Function) override; }; /// \brief Matches functions whose name matches a certain regular expression. class NameRegexCoverageFilter : public CoverageFilter { StringRef Regex; public: NameRegexCoverageFilter(StringRef Regex) : Regex(Regex) {} bool matches(const coverage::FunctionRecord &Function) override; }; /// \brief Matches numbers that pass a certain threshold. template <typename T> class StatisticThresholdFilter { public: enum Operation { LessThan, GreaterThan }; protected: Operation Op; T Threshold; StatisticThresholdFilter(Operation Op, T Threshold) : Op(Op), Threshold(Threshold) {} /// \brief Return true if the given number is less than /// or greater than the certain threshold. bool PassesThreshold(T Value) const { switch (Op) { case LessThan: return Value < Threshold; case GreaterThan: return Value > Threshold; } return false; } }; /// \brief Matches functions whose region coverage percentage /// is above/below a certain percentage. class RegionCoverageFilter : public CoverageFilter, public StatisticThresholdFilter<double> { public: RegionCoverageFilter(Operation Op, double Threshold) : StatisticThresholdFilter(Op, Threshold) {} bool matches(const coverage::FunctionRecord &Function) override; }; /// \brief Matches functions whose line coverage percentage /// is above/below a certain percentage. class LineCoverageFilter : public CoverageFilter, public StatisticThresholdFilter<double> { public: LineCoverageFilter(Operation Op, double Threshold) : StatisticThresholdFilter(Op, Threshold) {} bool matches(const coverage::FunctionRecord &Function) override; }; /// \brief A collection of filters. /// Matches functions that match any filters contained /// in an instance of this class. class CoverageFilters : public CoverageFilter { protected: std::vector<std::unique_ptr<CoverageFilter>> Filters; public: /// \brief Append a filter to this collection. void push_back(std::unique_ptr<CoverageFilter> Filter); bool empty() const { return Filters.empty(); } bool matches(const coverage::FunctionRecord &Function) override; }; /// \brief A collection of filters. /// Matches functions that match all of the filters contained /// in an instance of this class. class CoverageFiltersMatchAll : public CoverageFilters { public: bool matches(const coverage::FunctionRecord &Function) override; }; } // namespace llvm #endif // LLVM_COV_COVERAGEFILTERS_H
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cov/TestingSupport.cpp
//===- TestingSupport.cpp - Convert objects files into test files --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Object/ObjectFile.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/LEB128.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" #include <functional> #include <system_error> using namespace llvm; using namespace object; int convertForTestingMain(int argc, const char *argv[]) { sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::opt<std::string> InputSourceFile(cl::Positional, cl::Required, cl::desc("<Source file>")); cl::opt<std::string> OutputFilename( "o", cl::Required, cl::desc( "File with the profile data obtained after an instrumented run")); cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n"); auto ObjErr = llvm::object::ObjectFile::createObjectFile(InputSourceFile); if (auto Err = ObjErr.getError()) { errs() << "error: " << Err.message() << "\n"; return 1; } ObjectFile *OF = ObjErr.get().getBinary(); auto BytesInAddress = OF->getBytesInAddress(); if (BytesInAddress != 8) { errs() << "error: 64 bit binary expected\n"; return 1; } // Look for the sections that we are interested in. int FoundSectionCount = 0; SectionRef ProfileNames, CoverageMapping; for (const auto &Section : OF->sections()) { StringRef Name; if (Section.getName(Name)) return 1; if (Name == "__llvm_prf_names") { ProfileNames = Section; } else if (Name == "__llvm_covmap") { CoverageMapping = Section; } else continue; ++FoundSectionCount; } if (FoundSectionCount != 2) return 1; // Get the contents of the given sections. uint64_t ProfileNamesAddress = ProfileNames.getAddress(); StringRef CoverageMappingData; StringRef ProfileNamesData; if (CoverageMapping.getContents(CoverageMappingData) || ProfileNames.getContents(ProfileNamesData)) return 1; int FD; if (auto Err = sys::fs::openFileForWrite(OutputFilename, FD, sys::fs::F_None)) { errs() << "error: " << Err.message() << "\n"; return 1; } raw_fd_ostream OS(FD, true); OS << "llvmcovmtestdata"; encodeULEB128(ProfileNamesData.size(), OS); encodeULEB128(ProfileNamesAddress, OS); OS << ProfileNamesData << CoverageMappingData; return 0; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cov/LLVMBuild.txt
;===- ./tools/llvm-cov/LLVMBuild.txt ---------------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Tool name = llvm-cov parent = Tools required_libraries = ProfileData Support Instrumentation
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cov/CodeCoverage.cpp
//===- CodeCoverage.cpp - Coverage tool based on profiling instrumentation-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // The 'CodeCoverageTool' class implements a command line tool to analyze and // report coverage information using the profiling instrumentation and code // coverage mapping. // //===----------------------------------------------------------------------===// #include "RenderingSupport.h" #include "CoverageFilters.h" #include "CoverageReport.h" #include "CoverageViewOptions.h" #include "SourceCoverageView.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Triple.h" #include "llvm/ProfileData/CoverageMapping.h" #include "llvm/ProfileData/InstrProfReader.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Format.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Path.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Process.h" #include "llvm/Support/Signals.h" #include <functional> #include <system_error> using namespace llvm; using namespace coverage; namespace { /// \brief The implementation of the coverage tool. class CodeCoverageTool { public: enum Command { /// \brief The show command. Show, /// \brief The report command. Report }; /// \brief Print the error message to the error output stream. void error(const Twine &Message, StringRef Whence = ""); /// \brief Return a memory buffer for the given source file. ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile); /// \brief Create source views for the expansions of the view. void attachExpansionSubViews(SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions, CoverageMapping &Coverage); /// \brief Create the source view of a particular function. std::unique_ptr<SourceCoverageView> createFunctionView(const FunctionRecord &Function, CoverageMapping &Coverage); /// \brief Create the main source view of a particular source file. std::unique_ptr<SourceCoverageView> createSourceFileView(StringRef SourceFile, CoverageMapping &Coverage); /// \brief Load the coverage mapping data. Return true if an error occured. std::unique_ptr<CoverageMapping> load(); int run(Command Cmd, int argc, const char **argv); typedef std::function<int(int, const char **)> CommandLineParserType; int show(int argc, const char **argv, CommandLineParserType commandLineParser); int report(int argc, const char **argv, CommandLineParserType commandLineParser); std::string ObjectFilename; CoverageViewOptions ViewOpts; std::string PGOFilename; CoverageFiltersMatchAll Filters; std::vector<std::string> SourceFiles; std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>> LoadedSourceFiles; bool CompareFilenamesOnly; StringMap<std::string> RemappedFilenames; std::string CoverageArch; }; } void CodeCoverageTool::error(const Twine &Message, StringRef Whence) { errs() << "error: "; if (!Whence.empty()) errs() << Whence << ": "; errs() << Message << "\n"; } ErrorOr<const MemoryBuffer &> CodeCoverageTool::getSourceFile(StringRef SourceFile) { // If we've remapped filenames, look up the real location for this file. if (!RemappedFilenames.empty()) { auto Loc = RemappedFilenames.find(SourceFile); if (Loc != RemappedFilenames.end()) SourceFile = Loc->second; } for (const auto &Files : LoadedSourceFiles) if (sys::fs::equivalent(SourceFile, Files.first)) return *Files.second; auto Buffer = MemoryBuffer::getFile(SourceFile); if (auto EC = Buffer.getError()) { error(EC.message(), SourceFile); return EC; } LoadedSourceFiles.emplace_back(SourceFile, std::move(Buffer.get())); return *LoadedSourceFiles.back().second; } void CodeCoverageTool::attachExpansionSubViews(SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions, CoverageMapping &Coverage) { if (!ViewOpts.ShowExpandedRegions) return; for (const auto &Expansion : Expansions) { auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion); if (ExpansionCoverage.empty()) continue; auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename()); if (!SourceBuffer) continue; auto SubViewExpansions = ExpansionCoverage.getExpansions(); auto SubView = llvm::make_unique<SourceCoverageView>( SourceBuffer.get(), ViewOpts, std::move(ExpansionCoverage)); attachExpansionSubViews(*SubView, SubViewExpansions, Coverage); View.addExpansion(Expansion.Region, std::move(SubView)); } } std::unique_ptr<SourceCoverageView> CodeCoverageTool::createFunctionView(const FunctionRecord &Function, CoverageMapping &Coverage) { auto FunctionCoverage = Coverage.getCoverageForFunction(Function); if (FunctionCoverage.empty()) return nullptr; auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename()); if (!SourceBuffer) return nullptr; auto Expansions = FunctionCoverage.getExpansions(); auto View = llvm::make_unique<SourceCoverageView>( SourceBuffer.get(), ViewOpts, std::move(FunctionCoverage)); attachExpansionSubViews(*View, Expansions, Coverage); return View; } std::unique_ptr<SourceCoverageView> CodeCoverageTool::createSourceFileView(StringRef SourceFile, CoverageMapping &Coverage) { auto SourceBuffer = getSourceFile(SourceFile); if (!SourceBuffer) return nullptr; auto FileCoverage = Coverage.getCoverageForFile(SourceFile); if (FileCoverage.empty()) return nullptr; auto Expansions = FileCoverage.getExpansions(); auto View = llvm::make_unique<SourceCoverageView>( SourceBuffer.get(), ViewOpts, std::move(FileCoverage)); attachExpansionSubViews(*View, Expansions, Coverage); for (auto Function : Coverage.getInstantiations(SourceFile)) { auto SubViewCoverage = Coverage.getCoverageForFunction(*Function); auto SubViewExpansions = SubViewCoverage.getExpansions(); auto SubView = llvm::make_unique<SourceCoverageView>( SourceBuffer.get(), ViewOpts, std::move(SubViewCoverage)); attachExpansionSubViews(*SubView, SubViewExpansions, Coverage); if (SubView) { unsigned FileID = Function->CountedRegions.front().FileID; unsigned Line = 0; for (const auto &CR : Function->CountedRegions) if (CR.FileID == FileID) Line = std::max(CR.LineEnd, Line); View->addInstantiation(Function->Name, Line, std::move(SubView)); } } return View; } static bool modifiedTimeGT(StringRef LHS, StringRef RHS) { sys::fs::file_status Status; if (sys::fs::status(LHS, Status)) return false; auto LHSTime = Status.getLastModificationTime(); if (sys::fs::status(RHS, Status)) return false; auto RHSTime = Status.getLastModificationTime(); return LHSTime > RHSTime; } std::unique_ptr<CoverageMapping> CodeCoverageTool::load() { if (modifiedTimeGT(ObjectFilename, PGOFilename)) errs() << "warning: profile data may be out of date - object is newer\n"; auto CoverageOrErr = CoverageMapping::load(ObjectFilename, PGOFilename, CoverageArch); if (std::error_code EC = CoverageOrErr.getError()) { colored_ostream(errs(), raw_ostream::RED) << "error: Failed to load coverage: " << EC.message(); errs() << "\n"; return nullptr; } auto Coverage = std::move(CoverageOrErr.get()); unsigned Mismatched = Coverage->getMismatchedCount(); if (Mismatched) { colored_ostream(errs(), raw_ostream::RED) << "warning: " << Mismatched << " functions have mismatched data. "; errs() << "\n"; } if (CompareFilenamesOnly) { auto CoveredFiles = Coverage.get()->getUniqueSourceFiles(); for (auto &SF : SourceFiles) { StringRef SFBase = sys::path::filename(SF); for (const auto &CF : CoveredFiles) if (SFBase == sys::path::filename(CF)) { RemappedFilenames[CF] = SF; SF = CF; break; } } } return Coverage; } int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::opt<std::string, true> ObjectFilename( cl::Positional, cl::Required, cl::location(this->ObjectFilename), cl::desc("Covered executable or object file.")); cl::list<std::string> InputSourceFiles( cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore); cl::opt<std::string, true> PGOFilename( "instr-profile", cl::Required, cl::location(this->PGOFilename), cl::desc( "File with the profile data obtained after an instrumented run")); cl::opt<std::string> Arch( "arch", cl::desc("architecture of the coverage mapping binary")); cl::opt<bool> DebugDump("dump", cl::Optional, cl::desc("Show internal debug dump")); cl::opt<bool> FilenameEquivalence( "filename-equivalence", cl::Optional, cl::desc("Treat source files as equivalent to paths in the coverage data " "when the file names match, even if the full paths do not")); cl::OptionCategory FilteringCategory("Function filtering options"); cl::list<std::string> NameFilters( "name", cl::Optional, cl::desc("Show code coverage only for functions with the given name"), cl::ZeroOrMore, cl::cat(FilteringCategory)); cl::list<std::string> NameRegexFilters( "name-regex", cl::Optional, cl::desc("Show code coverage only for functions that match the given " "regular expression"), cl::ZeroOrMore, cl::cat(FilteringCategory)); cl::opt<double> RegionCoverageLtFilter( "region-coverage-lt", cl::Optional, cl::desc("Show code coverage only for functions with region coverage " "less than the given threshold"), cl::cat(FilteringCategory)); cl::opt<double> RegionCoverageGtFilter( "region-coverage-gt", cl::Optional, cl::desc("Show code coverage only for functions with region coverage " "greater than the given threshold"), cl::cat(FilteringCategory)); cl::opt<double> LineCoverageLtFilter( "line-coverage-lt", cl::Optional, cl::desc("Show code coverage only for functions with line coverage less " "than the given threshold"), cl::cat(FilteringCategory)); cl::opt<double> LineCoverageGtFilter( "line-coverage-gt", cl::Optional, cl::desc("Show code coverage only for functions with line coverage " "greater than the given threshold"), cl::cat(FilteringCategory)); cl::opt<cl::boolOrDefault> UseColor( "use-color", cl::desc("Emit colored output (default=autodetect)"), cl::init(cl::BOU_UNSET)); auto commandLineParser = [&, this](int argc, const char **argv) -> int { cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n"); ViewOpts.Debug = DebugDump; CompareFilenamesOnly = FilenameEquivalence; ViewOpts.Colors = UseColor == cl::BOU_UNSET ? sys::Process::StandardOutHasColors() : UseColor == cl::BOU_TRUE; // Create the function filters if (!NameFilters.empty() || !NameRegexFilters.empty()) { auto NameFilterer = new CoverageFilters; for (const auto &Name : NameFilters) NameFilterer->push_back(llvm::make_unique<NameCoverageFilter>(Name)); for (const auto &Regex : NameRegexFilters) NameFilterer->push_back( llvm::make_unique<NameRegexCoverageFilter>(Regex)); Filters.push_back(std::unique_ptr<CoverageFilter>(NameFilterer)); } if (RegionCoverageLtFilter.getNumOccurrences() || RegionCoverageGtFilter.getNumOccurrences() || LineCoverageLtFilter.getNumOccurrences() || LineCoverageGtFilter.getNumOccurrences()) { auto StatFilterer = new CoverageFilters; if (RegionCoverageLtFilter.getNumOccurrences()) StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>( RegionCoverageFilter::LessThan, RegionCoverageLtFilter)); if (RegionCoverageGtFilter.getNumOccurrences()) StatFilterer->push_back(llvm::make_unique<RegionCoverageFilter>( RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter)); if (LineCoverageLtFilter.getNumOccurrences()) StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>( LineCoverageFilter::LessThan, LineCoverageLtFilter)); if (LineCoverageGtFilter.getNumOccurrences()) StatFilterer->push_back(llvm::make_unique<LineCoverageFilter>( RegionCoverageFilter::GreaterThan, LineCoverageGtFilter)); Filters.push_back(std::unique_ptr<CoverageFilter>(StatFilterer)); } if (!Arch.empty() && Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) { errs() << "error: Unknown architecture: " << Arch << "\n"; return 1; } CoverageArch = Arch; for (const auto &File : InputSourceFiles) { SmallString<128> Path(File); if (!CompareFilenamesOnly) if (std::error_code EC = sys::fs::make_absolute(Path)) { errs() << "error: " << File << ": " << EC.message(); return 1; } SourceFiles.push_back(Path.str()); } return 0; }; switch (Cmd) { case Show: return show(argc, argv, commandLineParser); case Report: return report(argc, argv, commandLineParser); } return 0; } int CodeCoverageTool::show(int argc, const char **argv, CommandLineParserType commandLineParser) { cl::OptionCategory ViewCategory("Viewing options"); cl::opt<bool> ShowLineExecutionCounts( "show-line-counts", cl::Optional, cl::desc("Show the execution counts for each line"), cl::init(true), cl::cat(ViewCategory)); cl::opt<bool> ShowRegions( "show-regions", cl::Optional, cl::desc("Show the execution counts for each region"), cl::cat(ViewCategory)); cl::opt<bool> ShowBestLineRegionsCounts( "show-line-counts-or-regions", cl::Optional, cl::desc("Show the execution counts for each line, or the execution " "counts for each region on lines that have multiple regions"), cl::cat(ViewCategory)); cl::opt<bool> ShowExpansions("show-expansions", cl::Optional, cl::desc("Show expanded source regions"), cl::cat(ViewCategory)); cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional, cl::desc("Show function instantiations"), cl::cat(ViewCategory)); auto Err = commandLineParser(argc, argv); if (Err) return Err; ViewOpts.ShowLineNumbers = true; ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 || !ShowRegions || ShowBestLineRegionsCounts; ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts; ViewOpts.ShowLineStatsOrRegionMarkers = ShowBestLineRegionsCounts; ViewOpts.ShowExpandedRegions = ShowExpansions; ViewOpts.ShowFunctionInstantiations = ShowInstantiations; auto Coverage = load(); if (!Coverage) return 1; if (!Filters.empty()) { // Show functions for (const auto &Function : Coverage->getCoveredFunctions()) { if (!Filters.matches(Function)) continue; auto mainView = createFunctionView(Function, *Coverage); if (!mainView) { ViewOpts.colored_ostream(outs(), raw_ostream::RED) << "warning: Could not read coverage for '" << Function.Name; outs() << "\n"; continue; } ViewOpts.colored_ostream(outs(), raw_ostream::CYAN) << Function.Name << ":"; outs() << "\n"; mainView->render(outs(), /*WholeFile=*/false); outs() << "\n"; } return 0; } // Show files bool ShowFilenames = SourceFiles.size() != 1; if (SourceFiles.empty()) // Get the source files from the function coverage mapping for (StringRef Filename : Coverage->getUniqueSourceFiles()) SourceFiles.push_back(Filename); for (const auto &SourceFile : SourceFiles) { auto mainView = createSourceFileView(SourceFile, *Coverage); if (!mainView) { ViewOpts.colored_ostream(outs(), raw_ostream::RED) << "warning: The file '" << SourceFile << "' isn't covered."; outs() << "\n"; continue; } if (ShowFilenames) { ViewOpts.colored_ostream(outs(), raw_ostream::CYAN) << SourceFile << ":"; outs() << "\n"; } mainView->render(outs(), /*Wholefile=*/true); if (SourceFiles.size() > 1) outs() << "\n"; } return 0; } int CodeCoverageTool::report(int argc, const char **argv, CommandLineParserType commandLineParser) { auto Err = commandLineParser(argc, argv); if (Err) return Err; auto Coverage = load(); if (!Coverage) return 1; CoverageReport Report(ViewOpts, std::move(Coverage)); if (SourceFiles.empty()) Report.renderFileReports(llvm::outs()); else Report.renderFunctionReports(SourceFiles, llvm::outs()); return 0; } int showMain(int argc, const char *argv[]) { CodeCoverageTool Tool; return Tool.run(CodeCoverageTool::Show, argc, argv); } int reportMain(int argc, const char *argv[]) { CodeCoverageTool Tool; return Tool.run(CodeCoverageTool::Report, argc, argv); }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cov/CoverageReport.cpp
//===- CoverageReport.cpp - Code coverage report -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This class implements rendering of a code coverage report. // //===----------------------------------------------------------------------===// #include "CoverageReport.h" #include "RenderingSupport.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Format.h" using namespace llvm; namespace { /// \brief Helper struct which prints trimmed and aligned columns. struct Column { enum TrimKind { NoTrim, LeftTrim, RightTrim }; enum AlignmentKind { LeftAlignment, RightAlignment }; StringRef Str; unsigned Width; TrimKind Trim; AlignmentKind Alignment; Column(StringRef Str, unsigned Width) : Str(Str), Width(Width), Trim(NoTrim), Alignment(LeftAlignment) {} Column &set(TrimKind Value) { Trim = Value; return *this; } Column &set(AlignmentKind Value) { Alignment = Value; return *this; } void render(raw_ostream &OS) const; }; raw_ostream &operator<<(raw_ostream &OS, const Column &Value) { Value.render(OS); return OS; } } void Column::render(raw_ostream &OS) const { if (Str.size() <= Width) { if (Alignment == RightAlignment) { OS.indent(Width - Str.size()); OS << Str; return; } OS << Str; OS.indent(Width - Str.size()); return; } switch (Trim) { case NoTrim: OS << Str.substr(0, Width); break; case LeftTrim: OS << "..." << Str.substr(Str.size() - Width + 3); break; case RightTrim: OS << Str.substr(0, Width - 3) << "..."; break; } } static Column column(StringRef Str, unsigned Width) { return Column(Str, Width); } template <typename T> static Column column(StringRef Str, unsigned Width, const T &Value) { return Column(Str, Width).set(Value); } static const unsigned FileReportColumns[] = {25, 10, 8, 8, 10, 10}; static const unsigned FunctionReportColumns[] = {25, 10, 8, 8, 10, 8, 8}; /// \brief Prints a horizontal divider which spans across the given columns. template <typename T, size_t N> static void renderDivider(T (&Columns)[N], raw_ostream &OS) { unsigned Length = 0; for (unsigned I = 0; I < N; ++I) Length += Columns[I]; for (unsigned I = 0; I < Length; ++I) OS << '-'; } /// \brief Return the color which correponds to the coverage /// percentage of a certain metric. template <typename T> static raw_ostream::Colors determineCoveragePercentageColor(const T &Info) { if (Info.isFullyCovered()) return raw_ostream::GREEN; return Info.getPercentCovered() >= 80.0 ? raw_ostream::YELLOW : raw_ostream::RED; } void CoverageReport::render(const FileCoverageSummary &File, raw_ostream &OS) { OS << column(File.Name, FileReportColumns[0], Column::LeftTrim) << format("%*u", FileReportColumns[1], (unsigned)File.RegionCoverage.NumRegions); Options.colored_ostream(OS, File.RegionCoverage.isFullyCovered() ? raw_ostream::GREEN : raw_ostream::RED) << format("%*u", FileReportColumns[2], (unsigned)File.RegionCoverage.NotCovered); Options.colored_ostream(OS, determineCoveragePercentageColor(File.RegionCoverage)) << format("%*.2f", FileReportColumns[3] - 1, File.RegionCoverage.getPercentCovered()) << '%'; OS << format("%*u", FileReportColumns[4], (unsigned)File.FunctionCoverage.NumFunctions); Options.colored_ostream( OS, determineCoveragePercentageColor(File.FunctionCoverage)) << format("%*.2f", FileReportColumns[5] - 1, File.FunctionCoverage.getPercentCovered()) << '%'; OS << "\n"; } void CoverageReport::render(const FunctionCoverageSummary &Function, raw_ostream &OS) { OS << column(Function.Name, FunctionReportColumns[0], Column::RightTrim) << format("%*u", FunctionReportColumns[1], (unsigned)Function.RegionCoverage.NumRegions); Options.colored_ostream(OS, Function.RegionCoverage.isFullyCovered() ? raw_ostream::GREEN : raw_ostream::RED) << format("%*u", FunctionReportColumns[2], (unsigned)Function.RegionCoverage.NotCovered); Options.colored_ostream( OS, determineCoveragePercentageColor(Function.RegionCoverage)) << format("%*.2f", FunctionReportColumns[3] - 1, Function.RegionCoverage.getPercentCovered()) << '%'; OS << format("%*u", FunctionReportColumns[4], (unsigned)Function.LineCoverage.NumLines); Options.colored_ostream(OS, Function.LineCoverage.isFullyCovered() ? raw_ostream::GREEN : raw_ostream::RED) << format("%*u", FunctionReportColumns[5], (unsigned)Function.LineCoverage.NotCovered); Options.colored_ostream( OS, determineCoveragePercentageColor(Function.LineCoverage)) << format("%*.2f", FunctionReportColumns[6] - 1, Function.LineCoverage.getPercentCovered()) << '%'; OS << "\n"; } void CoverageReport::renderFunctionReports(ArrayRef<std::string> Files, raw_ostream &OS) { bool isFirst = true; for (StringRef Filename : Files) { if (isFirst) isFirst = false; else OS << "\n"; OS << "File '" << Filename << "':\n"; OS << column("Name", FunctionReportColumns[0]) << column("Regions", FunctionReportColumns[1], Column::RightAlignment) << column("Miss", FunctionReportColumns[2], Column::RightAlignment) << column("Cover", FunctionReportColumns[3], Column::RightAlignment) << column("Lines", FunctionReportColumns[4], Column::RightAlignment) << column("Miss", FunctionReportColumns[5], Column::RightAlignment) << column("Cover", FunctionReportColumns[6], Column::RightAlignment); OS << "\n"; renderDivider(FunctionReportColumns, OS); OS << "\n"; FunctionCoverageSummary Totals("TOTAL"); for (const auto &F : Coverage->getCoveredFunctions(Filename)) { FunctionCoverageSummary Function = FunctionCoverageSummary::get(F); ++Totals.ExecutionCount; Totals.RegionCoverage += Function.RegionCoverage; Totals.LineCoverage += Function.LineCoverage; render(Function, OS); } if (Totals.ExecutionCount) { renderDivider(FunctionReportColumns, OS); OS << "\n"; render(Totals, OS); } } } void CoverageReport::renderFileReports(raw_ostream &OS) { OS << column("Filename", FileReportColumns[0]) << column("Regions", FileReportColumns[1], Column::RightAlignment) << column("Miss", FileReportColumns[2], Column::RightAlignment) << column("Cover", FileReportColumns[3], Column::RightAlignment) << column("Functions", FileReportColumns[4], Column::RightAlignment) << column("Executed", FileReportColumns[5], Column::RightAlignment) << "\n"; renderDivider(FileReportColumns, OS); OS << "\n"; FileCoverageSummary Totals("TOTAL"); for (StringRef Filename : Coverage->getUniqueSourceFiles()) { FileCoverageSummary Summary(Filename); for (const auto &F : Coverage->getCoveredFunctions(Filename)) { FunctionCoverageSummary Function = FunctionCoverageSummary::get(F); Summary.addFunction(Function); Totals.addFunction(Function); } render(Summary, OS); } renderDivider(FileReportColumns, OS); OS << "\n"; render(Totals, OS); }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cov/CoverageFilters.cpp
//===- CoverageFilters.cpp - Function coverage mapping filters ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // These classes provide filtering for function coverage mapping records. // //===----------------------------------------------------------------------===// #include "CoverageFilters.h" #include "CoverageSummaryInfo.h" #include "llvm/Support/Regex.h" using namespace llvm; bool NameCoverageFilter::matches(const coverage::FunctionRecord &Function) { StringRef FuncName = Function.Name; return FuncName.find(Name) != StringRef::npos; } bool NameRegexCoverageFilter::matches(const coverage::FunctionRecord &Function) { return llvm::Regex(Regex).match(Function.Name); } bool RegionCoverageFilter::matches(const coverage::FunctionRecord &Function) { return PassesThreshold(FunctionCoverageSummary::get(Function) .RegionCoverage.getPercentCovered()); } bool LineCoverageFilter::matches(const coverage::FunctionRecord &Function) { return PassesThreshold( FunctionCoverageSummary::get(Function).LineCoverage.getPercentCovered()); } void CoverageFilters::push_back(std::unique_ptr<CoverageFilter> Filter) { Filters.push_back(std::move(Filter)); } bool CoverageFilters::matches(const coverage::FunctionRecord &Function) { for (const auto &Filter : Filters) { if (Filter->matches(Function)) return true; } return false; } bool CoverageFiltersMatchAll::matches(const coverage::FunctionRecord &Function) { for (const auto &Filter : Filters) { if (!Filter->matches(Function)) return false; } return true; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cov/llvm-cov.cpp
//===- llvm-cov.cpp - LLVM coverage tool ----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // llvm-cov is a command line tools to analyze and report coverage information. // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Path.h" #include "llvm/Support/Process.h" #include "llvm/Support/raw_ostream.h" #include <string> using namespace llvm; /// \brief The main entry point for the 'show' subcommand. int showMain(int argc, const char *argv[]); /// \brief The main entry point for the 'report' subcommand. int reportMain(int argc, const char *argv[]); /// \brief The main entry point for the 'convert-for-testing' subcommand. int convertForTestingMain(int argc, const char *argv[]); /// \brief The main entry point for the gcov compatible coverage tool. int gcovMain(int argc, const char *argv[]); /// \brief Top level help. static int helpMain(int argc, const char *argv[]) { errs() << "Usage: llvm-cov {gcov|report|show} [OPTION]...\n\n" << "Shows code coverage information.\n\n" << "Subcommands:\n" << " gcov: Work with the gcov format.\n" << " show: Annotate source files using instrprof style coverage.\n" << " report: Summarize instrprof style coverage information.\n"; return 0; } /// \brief Top level version information. static int versionMain(int argc, const char *argv[]) { cl::PrintVersionMessage(); return 0; } int __cdecl main(int argc, const char **argv) { // HLSL Change - __cdecl // If argv[0] is or ends with 'gcov', always be gcov compatible if (sys::path::stem(argv[0]).endswith_lower("gcov")) return gcovMain(argc, argv); // Check if we are invoking a specific tool command. if (argc > 1) { typedef int (*MainFunction)(int, const char *[]); MainFunction Func = StringSwitch<MainFunction>(argv[1]) .Case("convert-for-testing", convertForTestingMain) .Case("gcov", gcovMain) .Case("report", reportMain) .Case("show", showMain) .Cases("-h", "-help", "--help", helpMain) .Cases("-version", "--version", versionMain) .Default(nullptr); if (Func) { std::string Invocation = std::string(argv[0]) + " " + argv[1]; argv[1] = Invocation.c_str(); return Func(argc - 1, argv + 1); } } if (argc > 1) { if (sys::Process::StandardErrHasColors()) errs().changeColor(raw_ostream::RED); errs() << "Unrecognized command: " << argv[1] << ".\n\n"; if (sys::Process::StandardErrHasColors()) errs().resetColor(); } helpMain(argc, argv); return 1; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cov/CoverageSummaryInfo.cpp
//===- CoverageSummaryInfo.cpp - Coverage summary for function/file -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // These structures are used to represent code coverage metrics // for functions/files. // //===----------------------------------------------------------------------===// #include "CoverageSummaryInfo.h" using namespace llvm; using namespace coverage; FunctionCoverageSummary FunctionCoverageSummary::get(const coverage::FunctionRecord &Function) { // Compute the region coverage size_t NumCodeRegions = 0, CoveredRegions = 0; for (auto &CR : Function.CountedRegions) { if (CR.Kind != CounterMappingRegion::CodeRegion) continue; ++NumCodeRegions; if (CR.ExecutionCount != 0) ++CoveredRegions; } // Compute the line coverage size_t NumLines = 0, CoveredLines = 0; for (unsigned FileID = 0, E = Function.Filenames.size(); FileID < E; ++FileID) { // Find the line start and end of the function's source code // in that particular file unsigned LineStart = std::numeric_limits<unsigned>::max(); unsigned LineEnd = 0; for (auto &CR : Function.CountedRegions) { if (CR.FileID != FileID) continue; LineStart = std::min(LineStart, CR.LineStart); LineEnd = std::max(LineEnd, CR.LineEnd); } unsigned LineCount = LineEnd - LineStart + 1; // Get counters llvm::SmallVector<uint64_t, 16> ExecutionCounts; ExecutionCounts.resize(LineCount, 0); for (auto &CR : Function.CountedRegions) { if (CR.FileID != FileID) continue; // Ignore the lines that were skipped by the preprocessor. auto ExecutionCount = CR.ExecutionCount; if (CR.Kind == CounterMappingRegion::SkippedRegion) { LineCount -= CR.LineEnd - CR.LineStart + 1; ExecutionCount = 1; } for (unsigned I = CR.LineStart; I <= CR.LineEnd; ++I) ExecutionCounts[I - LineStart] = ExecutionCount; } CoveredLines += LineCount - std::count(ExecutionCounts.begin(), ExecutionCounts.end(), 0); NumLines += LineCount; } return FunctionCoverageSummary( Function.Name, Function.ExecutionCount, RegionCoverageInfo(CoveredRegions, NumCodeRegions), LineCoverageInfo(CoveredLines, 0, NumLines)); }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cxxdump/Error.cpp
//===- Error.cxx - system_error extensions for llvm-cxxdump -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This defines a new error_category for the llvm-cxxdump tool. // //===----------------------------------------------------------------------===// #include "Error.h" #include "llvm/Support/ErrorHandling.h" using namespace llvm; namespace { class cxxdump_error_category : public std::error_category { public: const char *name() const LLVM_NOEXCEPT override { return "llvm.cxxdump"; } std::string message(int ev) const override { switch (static_cast<cxxdump_error>(ev)) { case cxxdump_error::success: return "Success"; case cxxdump_error::file_not_found: return "No such file."; case cxxdump_error::unrecognized_file_format: return "Unrecognized file type."; } llvm_unreachable( "An enumerator of cxxdump_error does not have a message defined."); } }; } // namespace namespace llvm { const std::error_category &cxxdump_category() { static cxxdump_error_category o; return o; } } // namespace llvm
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cxxdump/llvm-cxxdump.cpp
//===- llvm-cxxdump.cpp - Dump C++ data in an Object File -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Dumps C++ data resident in object files and archives. // //===----------------------------------------------------------------------===// #include "llvm-cxxdump.h" #include "Error.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/Object/Archive.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Object/SymbolSize.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Endian.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/raw_ostream.h" #include <map> #include <string> #include <system_error> using namespace llvm; using namespace llvm::object; using namespace llvm::support; namespace opts { cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input object files>"), cl::ZeroOrMore); } // namespace opts static int ReturnValue = EXIT_SUCCESS; namespace llvm { static bool error(std::error_code EC) { if (!EC) return false; ReturnValue = EXIT_FAILURE; outs() << "\nError reading file: " << EC.message() << ".\n"; outs().flush(); return true; } } // namespace llvm static void reportError(StringRef Input, StringRef Message) { if (Input == "-") Input = "<stdin>"; errs() << Input << ": " << Message << "\n"; errs().flush(); ReturnValue = EXIT_FAILURE; } static void reportError(StringRef Input, std::error_code EC) { reportError(Input, EC.message()); } static SmallVectorImpl<SectionRef> &getRelocSections(const ObjectFile *Obj, const SectionRef &Sec) { static bool MappingDone = false; static std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap; if (!MappingDone) { for (const SectionRef &Section : Obj->sections()) { section_iterator Sec2 = Section.getRelocatedSection(); if (Sec2 != Obj->section_end()) SectionRelocMap[*Sec2].push_back(Section); } MappingDone = true; } return SectionRelocMap[Sec]; } static bool collectRelocatedSymbols(const ObjectFile *Obj, const SectionRef &Sec, uint64_t SecAddress, uint64_t SymAddress, uint64_t SymSize, StringRef *I, StringRef *E) { uint64_t SymOffset = SymAddress - SecAddress; uint64_t SymEnd = SymOffset + SymSize; for (const SectionRef &SR : getRelocSections(Obj, Sec)) { for (const object::RelocationRef &Reloc : SR.relocations()) { if (I == E) break; const object::symbol_iterator RelocSymI = Reloc.getSymbol(); if (RelocSymI == Obj->symbol_end()) continue; ErrorOr<StringRef> RelocSymName = RelocSymI->getName(); if (error(RelocSymName.getError())) return true; uint64_t Offset = Reloc.getOffset(); if (Offset >= SymOffset && Offset < SymEnd) { *I = *RelocSymName; ++I; } } } return false; } static bool collectRelocationOffsets( const ObjectFile *Obj, const SectionRef &Sec, uint64_t SecAddress, uint64_t SymAddress, uint64_t SymSize, StringRef SymName, std::map<std::pair<StringRef, uint64_t>, StringRef> &Collection) { uint64_t SymOffset = SymAddress - SecAddress; uint64_t SymEnd = SymOffset + SymSize; for (const SectionRef &SR : getRelocSections(Obj, Sec)) { for (const object::RelocationRef &Reloc : SR.relocations()) { const object::symbol_iterator RelocSymI = Reloc.getSymbol(); if (RelocSymI == Obj->symbol_end()) continue; ErrorOr<StringRef> RelocSymName = RelocSymI->getName(); if (error(RelocSymName.getError())) return true; uint64_t Offset = Reloc.getOffset(); if (Offset >= SymOffset && Offset < SymEnd) Collection[std::make_pair(SymName, Offset - SymOffset)] = *RelocSymName; } } return false; } static void dumpCXXData(const ObjectFile *Obj) { struct CompleteObjectLocator { StringRef Symbols[2]; ArrayRef<little32_t> Data; }; struct ClassHierarchyDescriptor { StringRef Symbols[1]; ArrayRef<little32_t> Data; }; struct BaseClassDescriptor { StringRef Symbols[2]; ArrayRef<little32_t> Data; }; struct TypeDescriptor { StringRef Symbols[1]; uint64_t AlwaysZero; StringRef MangledName; }; struct ThrowInfo { uint32_t Flags; }; struct CatchableTypeArray { uint32_t NumEntries; }; struct CatchableType { uint32_t Flags; uint32_t NonVirtualBaseAdjustmentOffset; int32_t VirtualBasePointerOffset; uint32_t VirtualBaseAdjustmentOffset; uint32_t Size; StringRef Symbols[2]; }; std::map<std::pair<StringRef, uint64_t>, StringRef> VFTableEntries; std::map<std::pair<StringRef, uint64_t>, StringRef> TIEntries; std::map<std::pair<StringRef, uint64_t>, StringRef> CTAEntries; std::map<StringRef, ArrayRef<little32_t>> VBTables; std::map<StringRef, CompleteObjectLocator> COLs; std::map<StringRef, ClassHierarchyDescriptor> CHDs; std::map<std::pair<StringRef, uint64_t>, StringRef> BCAEntries; std::map<StringRef, BaseClassDescriptor> BCDs; std::map<StringRef, TypeDescriptor> TDs; std::map<StringRef, ThrowInfo> TIs; std::map<StringRef, CatchableTypeArray> CTAs; std::map<StringRef, CatchableType> CTs; std::map<std::pair<StringRef, uint64_t>, StringRef> VTableSymEntries; std::map<std::pair<StringRef, uint64_t>, int64_t> VTableDataEntries; std::map<std::pair<StringRef, uint64_t>, StringRef> VTTEntries; std::map<StringRef, StringRef> TINames; uint8_t BytesInAddress = Obj->getBytesInAddress(); std::vector<std::pair<SymbolRef, uint64_t>> SymAddr = object::computeSymbolSizes(*Obj); for (auto &P : SymAddr) { object::SymbolRef Sym = P.first; uint64_t SymSize = P.second; ErrorOr<StringRef> SymNameOrErr = Sym.getName(); if (error(SymNameOrErr.getError())) return; StringRef SymName = *SymNameOrErr; object::section_iterator SecI(Obj->section_begin()); if (error(Sym.getSection(SecI))) return; // Skip external symbols. if (SecI == Obj->section_end()) continue; const SectionRef &Sec = *SecI; // Skip virtual or BSS sections. if (Sec.isBSS() || Sec.isVirtual()) continue; StringRef SecContents; if (error(Sec.getContents(SecContents))) return; ErrorOr<uint64_t> SymAddressOrErr = Sym.getAddress(); if (error(SymAddressOrErr.getError())) return; uint64_t SymAddress = *SymAddressOrErr; uint64_t SecAddress = Sec.getAddress(); uint64_t SecSize = Sec.getSize(); uint64_t SymOffset = SymAddress - SecAddress; StringRef SymContents = SecContents.substr(SymOffset, SymSize); // VFTables in the MS-ABI start with '??_7' and are contained within their // own COMDAT section. We then determine the contents of the VFTable by // looking at each relocation in the section. if (SymName.startswith("??_7")) { // Each relocation either names a virtual method or a thunk. We note the // offset into the section and the symbol used for the relocation. collectRelocationOffsets(Obj, Sec, SecAddress, SecAddress, SecSize, SymName, VFTableEntries); } // VBTables in the MS-ABI start with '??_8' and are filled with 32-bit // offsets of virtual bases. else if (SymName.startswith("??_8")) { ArrayRef<little32_t> VBTableData( reinterpret_cast<const little32_t *>(SymContents.data()), SymContents.size() / sizeof(little32_t)); VBTables[SymName] = VBTableData; } // Complete object locators in the MS-ABI start with '??_R4' else if (SymName.startswith("??_R4")) { CompleteObjectLocator COL; COL.Data = ArrayRef<little32_t>( reinterpret_cast<const little32_t *>(SymContents.data()), 3); StringRef *I = std::begin(COL.Symbols), *E = std::end(COL.Symbols); if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I, E)) return; COLs[SymName] = COL; } // Class hierarchy descriptors in the MS-ABI start with '??_R3' else if (SymName.startswith("??_R3")) { ClassHierarchyDescriptor CHD; CHD.Data = ArrayRef<little32_t>( reinterpret_cast<const little32_t *>(SymContents.data()), 3); StringRef *I = std::begin(CHD.Symbols), *E = std::end(CHD.Symbols); if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I, E)) return; CHDs[SymName] = CHD; } // Class hierarchy descriptors in the MS-ABI start with '??_R2' else if (SymName.startswith("??_R2")) { // Each relocation names a base class descriptor. We note the offset into // the section and the symbol used for the relocation. collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize, SymName, BCAEntries); } // Base class descriptors in the MS-ABI start with '??_R1' else if (SymName.startswith("??_R1")) { BaseClassDescriptor BCD; BCD.Data = ArrayRef<little32_t>( reinterpret_cast<const little32_t *>(SymContents.data()) + 1, 5); StringRef *I = std::begin(BCD.Symbols), *E = std::end(BCD.Symbols); if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I, E)) return; BCDs[SymName] = BCD; } // Type descriptors in the MS-ABI start with '??_R0' else if (SymName.startswith("??_R0")) { const char *DataPtr = SymContents.drop_front(BytesInAddress).data(); TypeDescriptor TD; if (BytesInAddress == 8) TD.AlwaysZero = *reinterpret_cast<const little64_t *>(DataPtr); else TD.AlwaysZero = *reinterpret_cast<const little32_t *>(DataPtr); TD.MangledName = SymContents.drop_front(BytesInAddress * 2); StringRef *I = std::begin(TD.Symbols), *E = std::end(TD.Symbols); if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I, E)) return; TDs[SymName] = TD; } // Throw descriptors in the MS-ABI start with '_TI' else if (SymName.startswith("_TI") || SymName.startswith("__TI")) { ThrowInfo TI; TI.Flags = *reinterpret_cast<const little32_t *>(SymContents.data()); collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize, SymName, TIEntries); TIs[SymName] = TI; } // Catchable type arrays in the MS-ABI start with _CTA or __CTA. else if (SymName.startswith("_CTA") || SymName.startswith("__CTA")) { CatchableTypeArray CTA; CTA.NumEntries = *reinterpret_cast<const little32_t *>(SymContents.data()); collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize, SymName, CTAEntries); CTAs[SymName] = CTA; } // Catchable types in the MS-ABI start with _CT or __CT. else if (SymName.startswith("_CT") || SymName.startswith("__CT")) { const little32_t *DataPtr = reinterpret_cast<const little32_t *>(SymContents.data()); CatchableType CT; CT.Flags = DataPtr[0]; CT.NonVirtualBaseAdjustmentOffset = DataPtr[2]; CT.VirtualBasePointerOffset = DataPtr[3]; CT.VirtualBaseAdjustmentOffset = DataPtr[4]; CT.Size = DataPtr[5]; StringRef *I = std::begin(CT.Symbols), *E = std::end(CT.Symbols); if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I, E)) return; CTs[SymName] = CT; } // Construction vtables in the Itanium ABI start with '_ZTT' or '__ZTT'. else if (SymName.startswith("_ZTT") || SymName.startswith("__ZTT")) { collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize, SymName, VTTEntries); } // Typeinfo names in the Itanium ABI start with '_ZTS' or '__ZTS'. else if (SymName.startswith("_ZTS") || SymName.startswith("__ZTS")) { TINames[SymName] = SymContents.slice(0, SymContents.find('\0')); } // Vtables in the Itanium ABI start with '_ZTV' or '__ZTV'. else if (SymName.startswith("_ZTV") || SymName.startswith("__ZTV")) { collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize, SymName, VTableSymEntries); for (uint64_t SymOffI = 0; SymOffI < SymSize; SymOffI += BytesInAddress) { auto Key = std::make_pair(SymName, SymOffI); if (VTableSymEntries.count(Key)) continue; const char *DataPtr = SymContents.substr(SymOffI, BytesInAddress).data(); int64_t VData; if (BytesInAddress == 8) VData = *reinterpret_cast<const little64_t *>(DataPtr); else VData = *reinterpret_cast<const little32_t *>(DataPtr); VTableDataEntries[Key] = VData; } } // Typeinfo structures in the Itanium ABI start with '_ZTI' or '__ZTI'. else if (SymName.startswith("_ZTI") || SymName.startswith("__ZTI")) { // FIXME: Do something with these! } } for (const auto &VFTableEntry : VFTableEntries) { StringRef VFTableName = VFTableEntry.first.first; uint64_t Offset = VFTableEntry.first.second; StringRef SymName = VFTableEntry.second; outs() << VFTableName << '[' << Offset << "]: " << SymName << '\n'; } for (const auto &VBTable : VBTables) { StringRef VBTableName = VBTable.first; uint32_t Idx = 0; for (little32_t Offset : VBTable.second) { outs() << VBTableName << '[' << Idx << "]: " << Offset << '\n'; Idx += sizeof(Offset); } } for (const auto &COLPair : COLs) { StringRef COLName = COLPair.first; const CompleteObjectLocator &COL = COLPair.second; outs() << COLName << "[IsImageRelative]: " << COL.Data[0] << '\n'; outs() << COLName << "[OffsetToTop]: " << COL.Data[1] << '\n'; outs() << COLName << "[VFPtrOffset]: " << COL.Data[2] << '\n'; outs() << COLName << "[TypeDescriptor]: " << COL.Symbols[0] << '\n'; outs() << COLName << "[ClassHierarchyDescriptor]: " << COL.Symbols[1] << '\n'; } for (const auto &CHDPair : CHDs) { StringRef CHDName = CHDPair.first; const ClassHierarchyDescriptor &CHD = CHDPair.second; outs() << CHDName << "[AlwaysZero]: " << CHD.Data[0] << '\n'; outs() << CHDName << "[Flags]: " << CHD.Data[1] << '\n'; outs() << CHDName << "[NumClasses]: " << CHD.Data[2] << '\n'; outs() << CHDName << "[BaseClassArray]: " << CHD.Symbols[0] << '\n'; } for (const auto &BCAEntry : BCAEntries) { StringRef BCAName = BCAEntry.first.first; uint64_t Offset = BCAEntry.first.second; StringRef SymName = BCAEntry.second; outs() << BCAName << '[' << Offset << "]: " << SymName << '\n'; } for (const auto &BCDPair : BCDs) { StringRef BCDName = BCDPair.first; const BaseClassDescriptor &BCD = BCDPair.second; outs() << BCDName << "[TypeDescriptor]: " << BCD.Symbols[0] << '\n'; outs() << BCDName << "[NumBases]: " << BCD.Data[0] << '\n'; outs() << BCDName << "[OffsetInVBase]: " << BCD.Data[1] << '\n'; outs() << BCDName << "[VBPtrOffset]: " << BCD.Data[2] << '\n'; outs() << BCDName << "[OffsetInVBTable]: " << BCD.Data[3] << '\n'; outs() << BCDName << "[Flags]: " << BCD.Data[4] << '\n'; outs() << BCDName << "[ClassHierarchyDescriptor]: " << BCD.Symbols[1] << '\n'; } for (const auto &TDPair : TDs) { StringRef TDName = TDPair.first; const TypeDescriptor &TD = TDPair.second; outs() << TDName << "[VFPtr]: " << TD.Symbols[0] << '\n'; outs() << TDName << "[AlwaysZero]: " << TD.AlwaysZero << '\n'; outs() << TDName << "[MangledName]: "; outs().write_escaped(TD.MangledName.rtrim(StringRef("\0", 1)), /*UseHexEscapes=*/true) << '\n'; } for (const auto &TIPair : TIs) { StringRef TIName = TIPair.first; const ThrowInfo &TI = TIPair.second; auto dumpThrowInfoFlag = [&](const char *Name, uint32_t Flag) { outs() << TIName << "[Flags." << Name << "]: " << (TI.Flags & Flag ? "true" : "false") << '\n'; }; auto dumpThrowInfoSymbol = [&](const char *Name, int Offset) { outs() << TIName << '[' << Name << "]: "; auto Entry = TIEntries.find(std::make_pair(TIName, Offset)); outs() << (Entry == TIEntries.end() ? "null" : Entry->second) << '\n'; }; outs() << TIName << "[Flags]: " << TI.Flags << '\n'; dumpThrowInfoFlag("Const", 1); dumpThrowInfoFlag("Volatile", 2); dumpThrowInfoSymbol("CleanupFn", 4); dumpThrowInfoSymbol("ForwardCompat", 8); dumpThrowInfoSymbol("CatchableTypeArray", 12); } for (const auto &CTAPair : CTAs) { StringRef CTAName = CTAPair.first; const CatchableTypeArray &CTA = CTAPair.second; outs() << CTAName << "[NumEntries]: " << CTA.NumEntries << '\n'; unsigned Idx = 0; for (auto I = CTAEntries.lower_bound(std::make_pair(CTAName, 0)), E = CTAEntries.upper_bound(std::make_pair(CTAName, UINT64_MAX)); I != E; ++I) outs() << CTAName << '[' << Idx++ << "]: " << I->second << '\n'; } for (const auto &CTPair : CTs) { StringRef CTName = CTPair.first; const CatchableType &CT = CTPair.second; auto dumpCatchableTypeFlag = [&](const char *Name, uint32_t Flag) { outs() << CTName << "[Flags." << Name << "]: " << (CT.Flags & Flag ? "true" : "false") << '\n'; }; outs() << CTName << "[Flags]: " << CT.Flags << '\n'; dumpCatchableTypeFlag("ScalarType", 1); dumpCatchableTypeFlag("VirtualInheritance", 4); outs() << CTName << "[TypeDescriptor]: " << CT.Symbols[0] << '\n'; outs() << CTName << "[NonVirtualBaseAdjustmentOffset]: " << CT.NonVirtualBaseAdjustmentOffset << '\n'; outs() << CTName << "[VirtualBasePointerOffset]: " << CT.VirtualBasePointerOffset << '\n'; outs() << CTName << "[VirtualBaseAdjustmentOffset]: " << CT.VirtualBaseAdjustmentOffset << '\n'; outs() << CTName << "[Size]: " << CT.Size << '\n'; outs() << CTName << "[CopyCtor]: " << (CT.Symbols[1].empty() ? "null" : CT.Symbols[1]) << '\n'; } for (const auto &VTTPair : VTTEntries) { StringRef VTTName = VTTPair.first.first; uint64_t VTTOffset = VTTPair.first.second; StringRef VTTEntry = VTTPair.second; outs() << VTTName << '[' << VTTOffset << "]: " << VTTEntry << '\n'; } for (const auto &TIPair : TINames) { StringRef TIName = TIPair.first; outs() << TIName << ": " << TIPair.second << '\n'; } auto VTableSymI = VTableSymEntries.begin(); auto VTableSymE = VTableSymEntries.end(); auto VTableDataI = VTableDataEntries.begin(); auto VTableDataE = VTableDataEntries.end(); for (;;) { bool SymDone = VTableSymI == VTableSymE; bool DataDone = VTableDataI == VTableDataE; if (SymDone && DataDone) break; if (!SymDone && (DataDone || VTableSymI->first < VTableDataI->first)) { StringRef VTableName = VTableSymI->first.first; uint64_t Offset = VTableSymI->first.second; StringRef VTableEntry = VTableSymI->second; outs() << VTableName << '[' << Offset << "]: "; outs() << VTableEntry; outs() << '\n'; ++VTableSymI; continue; } if (!DataDone && (SymDone || VTableDataI->first < VTableSymI->first)) { StringRef VTableName = VTableDataI->first.first; uint64_t Offset = VTableDataI->first.second; int64_t VTableEntry = VTableDataI->second; outs() << VTableName << '[' << Offset << "]: "; outs() << VTableEntry; outs() << '\n'; ++VTableDataI; continue; } } } static void dumpArchive(const Archive *Arc) { for (const Archive::Child &ArcC : Arc->children()) { ErrorOr<std::unique_ptr<Binary>> ChildOrErr = ArcC.getAsBinary(); if (std::error_code EC = ChildOrErr.getError()) { // Ignore non-object files. if (EC != object_error::invalid_file_type) reportError(Arc->getFileName(), EC.message()); continue; } if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get())) dumpCXXData(Obj); else reportError(Arc->getFileName(), cxxdump_error::unrecognized_file_format); } } static void dumpInput(StringRef File) { // If file isn't stdin, check that it exists. if (File != "-" && !sys::fs::exists(File)) { reportError(File, cxxdump_error::file_not_found); return; } // Attempt to open the binary. ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(File); if (std::error_code EC = BinaryOrErr.getError()) { reportError(File, EC); return; } Binary &Binary = *BinaryOrErr.get().getBinary(); if (Archive *Arc = dyn_cast<Archive>(&Binary)) dumpArchive(Arc); else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary)) dumpCXXData(Obj); else reportError(File, cxxdump_error::unrecognized_file_format); } int main(int argc, const char *argv[]) { sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Initialize targets. llvm::InitializeAllTargetInfos(); // Register the target printer for --version. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); cl::ParseCommandLineOptions(argc, argv, "LLVM C++ ABI Data Dumper\n"); // Default to stdin if no filename is specified. if (opts::InputFilenames.size() == 0) opts::InputFilenames.push_back("-"); std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(), dumpInput); return ReturnValue; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cxxdump/CMakeLists.txt
set(LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} Object Support ) add_llvm_tool(llvm-cxxdump llvm-cxxdump.cpp Error.cpp )
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cxxdump/LLVMBuild.txt
;===- ./tools/llvm-cxxdump/LLVMBuild.txt -----------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Tool name = llvm-cxxdump parent = Tools required_libraries = all-targets BitReader Object
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cxxdump/llvm-cxxdump.h
//===-- llvm-cxxdump.h ------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVM_CXXDUMP_LLVM_CXXDUMP_H #define LLVM_TOOLS_LLVM_CXXDUMP_LLVM_CXXDUMP_H #include "llvm/Support/CommandLine.h" #include <string> namespace opts { extern llvm::cl::list<std::string> InputFilenames; } // namespace opts #define LLVM_CXXDUMP_ENUM_ENT(ns, enum) \ { #enum, ns::enum } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-cxxdump/Error.h
//===- Error.h - system_error extensions for llvm-cxxdump -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This declares a new error_category for the llvm-cxxdump tool. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVM_CXXDUMP_ERROR_H #define LLVM_TOOLS_LLVM_CXXDUMP_ERROR_H #include <system_error> namespace llvm { const std::error_category &cxxdump_category(); enum class cxxdump_error { success = 0, file_not_found, unrecognized_file_format, }; inline std::error_code make_error_code(cxxdump_error e) { return std::error_code(static_cast<int>(e), cxxdump_category()); } } // namespace llvm namespace std { template <> struct is_error_code_enum<llvm::cxxdump_error> : std::true_type {}; } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-rtdyld/llvm-rtdyld.cpp
//===-- llvm-rtdyld.cpp - MCJIT Testing Tool ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is a testing tool for use with the MC-JIT LLVM components. // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringMap.h" #include "llvm/DebugInfo/DIContext.h" #include "llvm/DebugInfo/DWARF/DWARFContext.h" #include "llvm/ExecutionEngine/RTDyldMemoryManager.h" #include "llvm/ExecutionEngine/RuntimeDyld.h" #include "llvm/ExecutionEngine/RuntimeDyldChecker.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCDisassembler.h" #include "llvm/MC/MCInstPrinter.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/Object/MachO.h" #include "llvm/Object/SymbolSize.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Memory.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/raw_ostream.h" #include <list> #include <system_error> using namespace llvm; using namespace llvm::object; static cl::list<std::string> InputFileList(cl::Positional, cl::ZeroOrMore, cl::desc("<input file>")); enum ActionType { AC_Execute, AC_PrintObjectLineInfo, AC_PrintLineInfo, AC_PrintDebugLineInfo, AC_Verify }; static cl::opt<ActionType> Action(cl::desc("Action to perform:"), cl::init(AC_Execute), cl::values(clEnumValN(AC_Execute, "execute", "Load, link, and execute the inputs."), clEnumValN(AC_PrintLineInfo, "printline", "Load, link, and print line information for each function."), clEnumValN(AC_PrintDebugLineInfo, "printdebugline", "Load, link, and print line information for each function using the debug object"), clEnumValN(AC_PrintObjectLineInfo, "printobjline", "Like -printlineinfo but does not load the object first"), clEnumValN(AC_Verify, "verify", "Load, link and verify the resulting memory image."), clEnumValEnd)); static cl::opt<std::string> EntryPoint("entry", cl::desc("Function to call as entry point."), cl::init("_main")); static cl::list<std::string> Dylibs("dylib", cl::desc("Add library."), cl::ZeroOrMore); static cl::opt<std::string> TripleName("triple", cl::desc("Target triple for disassembler")); static cl::opt<std::string> MCPU("mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"), cl::value_desc("cpu-name"), cl::init("")); static cl::list<std::string> CheckFiles("check", cl::desc("File containing RuntimeDyld verifier checks."), cl::ZeroOrMore); static cl::opt<uint64_t> TargetAddrStart("target-addr-start", cl::desc("For -verify only: start of phony target address " "range."), cl::init(4096), // Start at "page 1" - no allocating at "null". cl::Hidden); static cl::opt<uint64_t> TargetAddrEnd("target-addr-end", cl::desc("For -verify only: end of phony target address range."), cl::init(~0ULL), cl::Hidden); static cl::opt<uint64_t> TargetSectionSep("target-section-sep", cl::desc("For -verify only: Separation between sections in " "phony target address space."), cl::init(0), cl::Hidden); static cl::list<std::string> SpecificSectionMappings("map-section", cl::desc("For -verify only: Map a section to a " "specific address."), cl::ZeroOrMore, cl::Hidden); static cl::list<std::string> DummySymbolMappings("dummy-extern", cl::desc("For -verify only: Inject a symbol into the extern " "symbol table."), cl::ZeroOrMore, cl::Hidden); /* *** */ // A trivial memory manager that doesn't do anything fancy, just uses the // support library allocation routines directly. class TrivialMemoryManager : public RTDyldMemoryManager { public: SmallVector<sys::MemoryBlock, 16> FunctionMemory; SmallVector<sys::MemoryBlock, 16> DataMemory; uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName) override; uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName, bool IsReadOnly) override; void *getPointerToNamedFunction(const std::string &Name, bool AbortOnFailure = true) override { return nullptr; } bool finalizeMemory(std::string *ErrMsg) override { return false; } // Invalidate instruction cache for sections with execute permissions. // Some platforms with separate data cache and instruction cache require // explicit cache flush, otherwise JIT code manipulations (like resolved // relocations) will get to the data cache but not to the instruction cache. virtual void invalidateInstructionCache(); void addDummySymbol(const std::string &Name, uint64_t Addr) { DummyExterns[Name] = Addr; } RuntimeDyld::SymbolInfo findSymbol(const std::string &Name) override { auto I = DummyExterns.find(Name); if (I != DummyExterns.end()) return RuntimeDyld::SymbolInfo(I->second, JITSymbolFlags::Exported); return RTDyldMemoryManager::findSymbol(Name); } void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override {} void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override {} private: std::map<std::string, uint64_t> DummyExterns; }; uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName) { sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr); FunctionMemory.push_back(MB); return (uint8_t*)MB.base(); } uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName, bool IsReadOnly) { sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr); DataMemory.push_back(MB); return (uint8_t*)MB.base(); } void TrivialMemoryManager::invalidateInstructionCache() { for (int i = 0, e = FunctionMemory.size(); i != e; ++i) sys::Memory::InvalidateInstructionCache(FunctionMemory[i].base(), FunctionMemory[i].size()); for (int i = 0, e = DataMemory.size(); i != e; ++i) sys::Memory::InvalidateInstructionCache(DataMemory[i].base(), DataMemory[i].size()); } static const char *ProgramName; static void Message(const char *Type, const Twine &Msg) { errs() << ProgramName << ": " << Type << ": " << Msg << "\n"; } static int Error(const Twine &Msg) { Message("error", Msg); return 1; } static void loadDylibs() { for (const std::string &Dylib : Dylibs) { if (sys::fs::is_regular_file(Dylib)) { std::string ErrMsg; if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg)) llvm::errs() << "Error loading '" << Dylib << "': " << ErrMsg << "\n"; } else llvm::errs() << "Dylib not found: '" << Dylib << "'.\n"; } } /* *** */ static int printLineInfoForInput(bool LoadObjects, bool UseDebugObj) { assert(LoadObjects || !UseDebugObj); // Load any dylibs requested on the command line. loadDylibs(); // If we don't have any input files, read from stdin. if (!InputFileList.size()) InputFileList.push_back("-"); for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) { // Instantiate a dynamic linker. TrivialMemoryManager MemMgr; RuntimeDyld Dyld(MemMgr, MemMgr); // Load the input memory buffer. ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer = MemoryBuffer::getFileOrSTDIN(InputFileList[i]); if (std::error_code EC = InputBuffer.getError()) return Error("unable to read input: '" + EC.message() + "'"); ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj( ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef())); if (std::error_code EC = MaybeObj.getError()) return Error("unable to create object file: '" + EC.message() + "'"); ObjectFile &Obj = **MaybeObj; OwningBinary<ObjectFile> DebugObj; std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo = nullptr; ObjectFile *SymbolObj = &Obj; if (LoadObjects) { // Load the object file LoadedObjInfo = Dyld.loadObject(Obj); if (Dyld.hasError()) return Error(Dyld.getErrorString()); // Resolve all the relocations we can. Dyld.resolveRelocations(); if (UseDebugObj) { DebugObj = LoadedObjInfo->getObjectForDebug(Obj); SymbolObj = DebugObj.getBinary(); } } std::unique_ptr<DIContext> Context( new DWARFContextInMemory(*SymbolObj,LoadedObjInfo.get())); std::vector<std::pair<SymbolRef, uint64_t>> SymAddr = object::computeSymbolSizes(*SymbolObj); // Use symbol info to iterate functions in the object. for (const auto &P : SymAddr) { object::SymbolRef Sym = P.first; if (Sym.getType() == object::SymbolRef::ST_Function) { ErrorOr<StringRef> Name = Sym.getName(); if (!Name) continue; ErrorOr<uint64_t> AddrOrErr = Sym.getAddress(); if (!AddrOrErr) continue; uint64_t Addr = *AddrOrErr; uint64_t Size = P.second; // If we're not using the debug object, compute the address of the // symbol in memory (rather than that in the unrelocated object file) // and use that to query the DWARFContext. if (!UseDebugObj && LoadObjects) { object::section_iterator Sec(SymbolObj->section_end()); Sym.getSection(Sec); StringRef SecName; Sec->getName(SecName); uint64_t SectionLoadAddress = LoadedObjInfo->getSectionLoadAddress(SecName); if (SectionLoadAddress != 0) Addr += SectionLoadAddress - Sec->getAddress(); } outs() << "Function: " << *Name << ", Size = " << Size << ", Addr = " << Addr << "\n"; DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size); DILineInfoTable::iterator Begin = Lines.begin(); DILineInfoTable::iterator End = Lines.end(); for (DILineInfoTable::iterator It = Begin; It != End; ++It) { outs() << " Line info @ " << It->first - Addr << ": " << It->second.FileName << ", line:" << It->second.Line << "\n"; } } } } return 0; } static int executeInput() { // Load any dylibs requested on the command line. loadDylibs(); // Instantiate a dynamic linker. TrivialMemoryManager MemMgr; RuntimeDyld Dyld(MemMgr, MemMgr); // FIXME: Preserve buffers until resolveRelocations time to work around a bug // in RuntimeDyldELF. // This fixme should be fixed ASAP. This is a very brittle workaround. std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers; // If we don't have any input files, read from stdin. if (!InputFileList.size()) InputFileList.push_back("-"); for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) { // Load the input memory buffer. ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer = MemoryBuffer::getFileOrSTDIN(InputFileList[i]); if (std::error_code EC = InputBuffer.getError()) return Error("unable to read input: '" + EC.message() + "'"); ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj( ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef())); if (std::error_code EC = MaybeObj.getError()) return Error("unable to create object file: '" + EC.message() + "'"); ObjectFile &Obj = **MaybeObj; InputBuffers.push_back(std::move(*InputBuffer)); // Load the object file Dyld.loadObject(Obj); if (Dyld.hasError()) { return Error(Dyld.getErrorString()); } } // Resolve all the relocations we can. Dyld.resolveRelocations(); // Clear instruction cache before code will be executed. MemMgr.invalidateInstructionCache(); // FIXME: Error out if there are unresolved relocations. // Get the address of the entry point (_main by default). void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint); if (!MainAddress) return Error("no definition for '" + EntryPoint + "'"); // Invalidate the instruction cache for each loaded function. for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) { sys::MemoryBlock &Data = MemMgr.FunctionMemory[i]; // Make sure the memory is executable. std::string ErrorStr; sys::Memory::InvalidateInstructionCache(Data.base(), Data.size()); if (!sys::Memory::setExecutable(Data, &ErrorStr)) return Error("unable to mark function executable: '" + ErrorStr + "'"); } // Dispatch to _main(). errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n"; int (*Main)(int, const char**) = (int(*)(int,const char**)) uintptr_t(MainAddress); const char **Argv = new const char*[2]; // Use the name of the first input object module as argv[0] for the target. Argv[0] = InputFileList[0].c_str(); Argv[1] = nullptr; return Main(1, Argv); } static int checkAllExpressions(RuntimeDyldChecker &Checker) { for (const auto& CheckerFileName : CheckFiles) { ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf = MemoryBuffer::getFileOrSTDIN(CheckerFileName); if (std::error_code EC = CheckerFileBuf.getError()) return Error("unable to read input '" + CheckerFileName + "': " + EC.message()); if (!Checker.checkAllRulesInBuffer("# rtdyld-check:", CheckerFileBuf.get().get())) return Error("some checks in '" + CheckerFileName + "' failed"); } return 0; } static std::map<void *, uint64_t> applySpecificSectionMappings(RuntimeDyldChecker &Checker) { std::map<void*, uint64_t> SpecificMappings; for (StringRef Mapping : SpecificSectionMappings) { size_t EqualsIdx = Mapping.find_first_of("="); std::string SectionIDStr = Mapping.substr(0, EqualsIdx); size_t ComaIdx = Mapping.find_first_of(","); if (ComaIdx == StringRef::npos) { errs() << "Invalid section specification '" << Mapping << "'. Should be '<file name>,<section name>=<addr>'\n"; exit(1); } std::string FileName = SectionIDStr.substr(0, ComaIdx); std::string SectionName = SectionIDStr.substr(ComaIdx + 1); uint64_t OldAddrInt; std::string ErrorMsg; std::tie(OldAddrInt, ErrorMsg) = Checker.getSectionAddr(FileName, SectionName, true); if (ErrorMsg != "") { errs() << ErrorMsg; exit(1); } void* OldAddr = reinterpret_cast<void*>(static_cast<uintptr_t>(OldAddrInt)); std::string NewAddrStr = Mapping.substr(EqualsIdx + 1); uint64_t NewAddr; if (StringRef(NewAddrStr).getAsInteger(0, NewAddr)) { errs() << "Invalid section address in mapping '" << Mapping << "'.\n"; exit(1); } Checker.getRTDyld().mapSectionAddress(OldAddr, NewAddr); SpecificMappings[OldAddr] = NewAddr; } return SpecificMappings; } // Scatter sections in all directions! // Remaps section addresses for -verify mode. The following command line options // can be used to customize the layout of the memory within the phony target's // address space: // -target-addr-start <s> -- Specify where the phony target addres range starts. // -target-addr-end <e> -- Specify where the phony target address range ends. // -target-section-sep <d> -- Specify how big a gap should be left between the // end of one section and the start of the next. // Defaults to zero. Set to something big // (e.g. 1 << 32) to stress-test stubs, GOTs, etc. // static void remapSectionsAndSymbols(const llvm::Triple &TargetTriple, TrivialMemoryManager &MemMgr, RuntimeDyldChecker &Checker) { // Set up a work list (section addr/size pairs). typedef std::list<std::pair<void*, uint64_t>> WorklistT; WorklistT Worklist; for (const auto& CodeSection : MemMgr.FunctionMemory) Worklist.push_back(std::make_pair(CodeSection.base(), CodeSection.size())); for (const auto& DataSection : MemMgr.DataMemory) Worklist.push_back(std::make_pair(DataSection.base(), DataSection.size())); // Apply any section-specific mappings that were requested on the command // line. typedef std::map<void*, uint64_t> AppliedMappingsT; AppliedMappingsT AppliedMappings = applySpecificSectionMappings(Checker); // Keep an "already allocated" mapping of section target addresses to sizes. // Sections whose address mappings aren't specified on the command line will // allocated around the explicitly mapped sections while maintaining the // minimum separation. std::map<uint64_t, uint64_t> AlreadyAllocated; // Move the previously applied mappings into the already-allocated map. for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end(); I != E;) { WorklistT::iterator Tmp = I; ++I; AppliedMappingsT::iterator AI = AppliedMappings.find(Tmp->first); if (AI != AppliedMappings.end()) { AlreadyAllocated[AI->second] = Tmp->second; Worklist.erase(Tmp); } } // If the -target-addr-end option wasn't explicitly passed, then set it to a // sensible default based on the target triple. if (TargetAddrEnd.getNumOccurrences() == 0) { if (TargetTriple.isArch16Bit()) TargetAddrEnd = (1ULL << 16) - 1; else if (TargetTriple.isArch32Bit()) TargetAddrEnd = (1ULL << 32) - 1; // TargetAddrEnd already has a sensible default for 64-bit systems, so // there's nothing to do in the 64-bit case. } // Process any elements remaining in the worklist. while (!Worklist.empty()) { std::pair<void*, uint64_t> CurEntry = Worklist.front(); Worklist.pop_front(); uint64_t NextSectionAddr = TargetAddrStart; for (const auto &Alloc : AlreadyAllocated) if (NextSectionAddr + CurEntry.second + TargetSectionSep <= Alloc.first) break; else NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep; AlreadyAllocated[NextSectionAddr] = CurEntry.second; Checker.getRTDyld().mapSectionAddress(CurEntry.first, NextSectionAddr); } // Add dummy symbols to the memory manager. for (const auto &Mapping : DummySymbolMappings) { size_t EqualsIdx = Mapping.find_first_of("="); if (EqualsIdx == StringRef::npos) { errs() << "Invalid dummy symbol specification '" << Mapping << "'. Should be '<symbol name>=<addr>'\n"; exit(1); } std::string Symbol = Mapping.substr(0, EqualsIdx); std::string AddrStr = Mapping.substr(EqualsIdx + 1); uint64_t Addr; if (StringRef(AddrStr).getAsInteger(0, Addr)) { errs() << "Invalid symbol mapping '" << Mapping << "'.\n"; exit(1); } MemMgr.addDummySymbol(Symbol, Addr); } } // Load and link the objects specified on the command line, but do not execute // anything. Instead, attach a RuntimeDyldChecker instance and call it to // verify the correctness of the linked memory. static int linkAndVerify() { // Check for missing triple. if (TripleName == "") { llvm::errs() << "Error: -triple required when running in -verify mode.\n"; return 1; } // Look up the target and build the disassembler. Triple TheTriple(Triple::normalize(TripleName)); std::string ErrorStr; const Target *TheTarget = TargetRegistry::lookupTarget("", TheTriple, ErrorStr); if (!TheTarget) { llvm::errs() << "Error accessing target '" << TripleName << "': " << ErrorStr << "\n"; return 1; } TripleName = TheTriple.getTriple(); std::unique_ptr<MCSubtargetInfo> STI( TheTarget->createMCSubtargetInfo(TripleName, MCPU, "")); assert(STI && "Unable to create subtarget info!"); std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName)); assert(MRI && "Unable to create target register info!"); std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName)); assert(MAI && "Unable to create target asm info!"); MCContext Ctx(MAI.get(), MRI.get(), nullptr); std::unique_ptr<MCDisassembler> Disassembler( TheTarget->createMCDisassembler(*STI, Ctx)); assert(Disassembler && "Unable to create disassembler!"); std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo()); std::unique_ptr<MCInstPrinter> InstPrinter( TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI)); // Load any dylibs requested on the command line. loadDylibs(); // Instantiate a dynamic linker. TrivialMemoryManager MemMgr; RuntimeDyld Dyld(MemMgr, MemMgr); Dyld.setProcessAllSections(true); RuntimeDyldChecker Checker(Dyld, Disassembler.get(), InstPrinter.get(), llvm::dbgs()); // FIXME: Preserve buffers until resolveRelocations time to work around a bug // in RuntimeDyldELF. // This fixme should be fixed ASAP. This is a very brittle workaround. std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers; // If we don't have any input files, read from stdin. if (!InputFileList.size()) InputFileList.push_back("-"); for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) { // Load the input memory buffer. ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer = MemoryBuffer::getFileOrSTDIN(InputFileList[i]); if (std::error_code EC = InputBuffer.getError()) return Error("unable to read input: '" + EC.message() + "'"); ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj( ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef())); if (std::error_code EC = MaybeObj.getError()) return Error("unable to create object file: '" + EC.message() + "'"); ObjectFile &Obj = **MaybeObj; InputBuffers.push_back(std::move(*InputBuffer)); // Load the object file Dyld.loadObject(Obj); if (Dyld.hasError()) { return Error(Dyld.getErrorString()); } } // Re-map the section addresses into the phony target address space and add // dummy symbols. remapSectionsAndSymbols(TheTriple, MemMgr, Checker); // Resolve all the relocations we can. Dyld.resolveRelocations(); // Register EH frames. Dyld.registerEHFrames(); int ErrorCode = checkAllExpressions(Checker); if (Dyld.hasError()) { errs() << "RTDyld reported an error applying relocations:\n " << Dyld.getErrorString() << "\n"; ErrorCode = 1; } return ErrorCode; } int __cdecl main(int argc, char **argv) { // HLSL Change - __cdecl sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); ProgramName = argv[0]; llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. llvm::InitializeAllTargetInfos(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllDisassemblers(); cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n"); switch (Action) { case AC_Execute: return executeInput(); case AC_PrintDebugLineInfo: return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */ true); case AC_PrintLineInfo: return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */false); case AC_PrintObjectLineInfo: return printLineInfoForInput(/* LoadObjects */false,/* UseDebugObj */false); case AC_Verify: return linkAndVerify(); } }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-rtdyld/CMakeLists.txt
set(LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} DebugInfoDWARF ExecutionEngine MC Object RuntimeDyld Support ) add_llvm_tool(llvm-rtdyld llvm-rtdyld.cpp )
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-rtdyld/LLVMBuild.txt
;===- ./tools/llvm-rtdyld/LLVMBuild.txt ------------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Tool name = llvm-rtdyld parent = Tools required_libraries = MC Object RuntimeDyld Support all-targets
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-c-test/main.c
/*===-- main.c - tool for testing libLLVM and llvm-c API ------------------===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* Main file for llvm-c-tests. "Parses" arguments and dispatches. *| |* *| \*===----------------------------------------------------------------------===*/ #include "llvm-c-test.h" #include "llvm-c/BitReader.h" #include "llvm-c/Core.h" #include <stdio.h> #include <stdlib.h> #include <string.h> static void print_usage(void) { fprintf(stderr, "llvm-c-test command\n\n"); fprintf(stderr, " Commands:\n"); fprintf(stderr, " * --module-dump\n"); fprintf(stderr, " Read bytecode from stdin - print disassembly\n\n"); fprintf(stderr, " * --module-list-functions\n"); fprintf(stderr, " Read bytecode from stdin - list summary of functions\n\n"); fprintf(stderr, " * --module-list-globals\n"); fprintf(stderr, " Read bytecode from stdin - list summary of globals\n\n"); fprintf(stderr, " * --targets-list\n"); fprintf(stderr, " List available targets\n\n"); fprintf(stderr, " * --object-list-sections\n"); fprintf(stderr, " Read object file form stdin - list sections\n\n"); fprintf(stderr, " * --object-list-symbols\n"); fprintf(stderr, " Read object file form stdin - list symbols (like nm)\n\n"); fprintf(stderr, " * --disassemble\n"); fprintf(stderr, " Read lines of triple, hex ascii machine code from stdin " "- print disassembly\n\n"); fprintf(stderr, " * --calc\n"); fprintf( stderr, " Read lines of name, rpn from stdin - print generated module\n\n"); } // HLSL Change: changed calling convention to __cdecl int __cdecl main(int argc, char **argv) { LLVMPassRegistryRef pr = LLVMGetGlobalPassRegistry(); LLVMInitializeCore(pr); if (argc == 2 && !strcmp(argv[1], "--module-dump")) { return module_dump(); } else if (argc == 2 && !strcmp(argv[1], "--module-list-functions")) { return module_list_functions(); } else if (argc == 2 && !strcmp(argv[1], "--module-list-globals")) { return module_list_globals(); } else if (argc == 2 && !strcmp(argv[1], "--targets-list")) { return targets_list(); } else if (argc == 2 && !strcmp(argv[1], "--object-list-sections")) { return object_list_sections(); } else if (argc == 2 && !strcmp(argv[1], "--object-list-symbols")) { return object_list_symbols(); } else if (argc == 2 && !strcmp(argv[1], "--disassemble")) { return disassemble(); } else if (argc == 2 && !strcmp(argv[1], "--calc")) { return calc(); } else if (argc == 2 && !strcmp(argv[1], "--add-named-metadata-operand")) { return add_named_metadata_operand(); } else if (argc == 2 && !strcmp(argv[1], "--set-metadata")) { return set_metadata(); } else { print_usage(); } return 1; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-c-test/include-all.c
/*===-- include-all.c - tool for testing libLLVM and llvm-c API -----------===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This file doesn't have any actual code. It just make sure that all *| |* the llvm-c include files are good and doesn't generate any warnings *| |* *| \*===----------------------------------------------------------------------===*/ // FIXME: Autogenerate this list #include "llvm-c/Analysis.h" #include "llvm-c/BitReader.h" #include "llvm-c/BitWriter.h" #include "llvm-c/Core.h" #include "llvm-c/Disassembler.h" #include "llvm-c/ExecutionEngine.h" #include "llvm-c/Initialization.h" #include "llvm-c/LinkTimeOptimizer.h" #include "llvm-c/Linker.h" #include "llvm-c/Object.h" #include "llvm-c/Target.h" #include "llvm-c/TargetMachine.h" #include "llvm-c/Transforms/IPO.h" #include "llvm-c/Transforms/PassManagerBuilder.h" #include "llvm-c/Transforms/Scalar.h" #include "llvm-c/Transforms/Vectorize.h" #include "llvm-c/lto.h"
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-c-test/object.c
/*===-- object.c - tool for testing libLLVM and llvm-c API ----------------===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This file implements the --object-list-sections and --object-list-symbols *| |* commands in llvm-c-test. *| |* *| \*===----------------------------------------------------------------------===*/ #include "llvm-c-test.h" #include "llvm-c/Object.h" #include <stdio.h> #include <stdlib.h> int object_list_sections(void) { LLVMMemoryBufferRef MB; LLVMObjectFileRef O; LLVMSectionIteratorRef sect; char *msg = NULL; if (LLVMCreateMemoryBufferWithSTDIN(&MB, &msg)) { fprintf(stderr, "Error reading file: %s\n", msg); exit(1); } O = LLVMCreateObjectFile(MB); if (!O) { fprintf(stderr, "Error reading object\n"); exit(1); } sect = LLVMGetSections(O); while (!LLVMIsSectionIteratorAtEnd(O, sect)) { printf("'%s': @0x%08" PRIx64 " +%" PRIu64 "\n", LLVMGetSectionName(sect), LLVMGetSectionAddress(sect), LLVMGetSectionSize(sect)); LLVMMoveToNextSection(sect); } LLVMDisposeSectionIterator(sect); LLVMDisposeObjectFile(O); return 0; } int object_list_symbols(void) { LLVMMemoryBufferRef MB; LLVMObjectFileRef O; LLVMSectionIteratorRef sect; LLVMSymbolIteratorRef sym; char *msg = NULL; if (LLVMCreateMemoryBufferWithSTDIN(&MB, &msg)) { fprintf(stderr, "Error reading file: %s\n", msg); exit(1); } O = LLVMCreateObjectFile(MB); if (!O) { fprintf(stderr, "Error reading object\n"); exit(1); } sect = LLVMGetSections(O); sym = LLVMGetSymbols(O); while (!LLVMIsSymbolIteratorAtEnd(O, sym)) { LLVMMoveToContainingSection(sect, sym); printf("%s @0x%08" PRIx64 " +%" PRIu64 " (%s)\n", LLVMGetSymbolName(sym), LLVMGetSymbolAddress(sym), LLVMGetSymbolSize(sym), LLVMGetSectionName(sect)); LLVMMoveToNextSymbol(sym); } LLVMDisposeSymbolIterator(sym); LLVMDisposeObjectFile(O); return 0; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-c-test/calc.c
/*===-- calc.c - tool for testing libLLVM and llvm-c API ------------------===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This file implements the --calc command in llvm-c-test. --calc reads lines *| |* from stdin, parses them as a name and an expression in reverse polish *| |* notation and prints a module with a function with the expression. *| |* *| \*===----------------------------------------------------------------------===*/ #include "llvm-c-test.h" #include "llvm-c/Core.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> typedef LLVMValueRef (*binop_func_t)(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name); static LLVMOpcode op_to_opcode(char op) { switch (op) { case '+': return LLVMAdd; case '-': return LLVMSub; case '*': return LLVMMul; case '/': return LLVMSDiv; case '&': return LLVMAnd; case '|': return LLVMOr; case '^': return LLVMXor; } assert(0 && "unknown operation"); return 0; } #define MAX_DEPTH 32 static LLVMValueRef build_from_tokens(char **tokens, int ntokens, LLVMBuilderRef builder, LLVMValueRef param) { LLVMValueRef stack[MAX_DEPTH]; int depth = 0; int i; for (i = 0; i < ntokens; i++) { char tok = tokens[i][0]; switch (tok) { case '+': case '-': case '*': case '/': case '&': case '|': case '^': if (depth < 2) { printf("stack underflow\n"); return NULL; } stack[depth - 2] = LLVMBuildBinOp(builder, op_to_opcode(tok), stack[depth - 1], stack[depth - 2], ""); depth--; break; case '@': { LLVMValueRef off; if (depth < 1) { printf("stack underflow\n"); return NULL; } off = LLVMBuildGEP(builder, param, &stack[depth - 1], 1, ""); stack[depth - 1] = LLVMBuildLoad(builder, off, ""); break; } default: { char *end; long val = strtol(tokens[i], &end, 0); if (end[0] != '\0') { printf("error parsing number\n"); return NULL; } if (depth >= MAX_DEPTH) { printf("stack overflow\n"); return NULL; } stack[depth++] = LLVMConstInt(LLVMInt64Type(), val, 1); break; } } } if (depth < 1) { printf("stack underflow at return\n"); return NULL; } LLVMBuildRet(builder, stack[depth - 1]); return stack[depth - 1]; } static void handle_line(char **tokens, int ntokens) { char *name = tokens[0]; LLVMValueRef param; LLVMValueRef res; LLVMModuleRef M = LLVMModuleCreateWithName(name); LLVMTypeRef I64ty = LLVMInt64Type(); LLVMTypeRef I64Ptrty = LLVMPointerType(I64ty, 0); LLVMTypeRef Fty = LLVMFunctionType(I64ty, &I64Ptrty, 1, 0); LLVMValueRef F = LLVMAddFunction(M, name, Fty); LLVMBuilderRef builder = LLVMCreateBuilder(); LLVMPositionBuilderAtEnd(builder, LLVMAppendBasicBlock(F, "entry")); LLVMGetParams(F, &param); LLVMSetValueName(param, "in"); res = build_from_tokens(tokens + 1, ntokens - 1, builder, param); if (res) { char *irstr = LLVMPrintModuleToString(M); puts(irstr); LLVMDisposeMessage(irstr); } LLVMDisposeBuilder(builder); LLVMDisposeModule(M); } int calc(void) { tokenize_stdin(handle_line); return 0; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-c-test/CMakeLists.txt
set(LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} BitReader Core MCDisassembler Object Target ) # We should only have llvm-c-test use libLLVM if libLLVM is built with the # default list of components. Using libLLVM with custom components can result in # build failures. set (USE_LLVM_DYLIB FALSE) if (TARGET LLVM) set (USE_LLVM_DYLIB TRUE) if (DEFINED LLVM_DYLIB_COMPONENTS) foreach(c in ${LLVM_LINK_COMPONENTS}) list(FIND LLVM_DYLIB_COMPONENTS ${c} C_IDX) if (C_IDX EQUAL -1) set(USE_LLVM_DYLIB FALSE) break() endif() endforeach() endif() endif() if(USE_LLVM_DYLIB) set(LLVM_LINK_COMPONENTS) endif() if (LLVM_COMPILER_IS_GCC_COMPATIBLE) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu99 -Wstrict-prototypes") endif () add_llvm_tool(llvm-c-test calc.c disassemble.c helpers.c include-all.c main.c module.c metadata.c object.c targets.c ) if(USE_LLVM_DYLIB) target_link_libraries(llvm-c-test LLVM) endif()
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-c-test/llvm-c-test.h
/*===-- llvm-c-test.h - tool for testing libLLVM and llvm-c API -----------===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* Header file for llvm-c-test *| |* *| \*===----------------------------------------------------------------------===*/ #define LLVM_C_TEST_H // helpers.c void tokenize_stdin(void (*cb)(char **tokens, int ntokens)); // module.c int module_dump(void); int module_list_functions(void); int module_list_globals(void); // calc.c int calc(void); // disassemble.c int disassemble(void); // metadata.c int add_named_metadata_operand(void); int set_metadata(void); // object.c int object_list_sections(void); int object_list_symbols(void); // targets.c int targets_list(void); #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-c-test/targets.c
/*===-- targets.c - tool for testing libLLVM and llvm-c API ---------------===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This file implements the --targets command in llvm-c-test. *| |* *| \*===----------------------------------------------------------------------===*/ #include "llvm-c/TargetMachine.h" #include <stdio.h> int targets_list(void) { LLVMTargetRef t; LLVMInitializeAllTargetInfos(); LLVMInitializeAllTargets(); for (t = LLVMGetFirstTarget(); t; t = LLVMGetNextTarget(t)) { printf("%s", LLVMGetTargetName(t)); if (LLVMTargetHasJIT(t)) printf(" (+jit)"); printf("\n - %s\n", LLVMGetTargetDescription(t)); } return 0; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-c-test/disassemble.c
/*===-- disassemble.c - tool for testing libLLVM and llvm-c API -----------===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This file implements the --disassemble command in llvm-c-test. *| |* --disassemble reads lines from stdin, parses them as a triple and hex *| |* machine code, and prints disassembly of the machine code. *| |* *| \*===----------------------------------------------------------------------===*/ #include "llvm-c-test.h" #include "llvm-c/Disassembler.h" #include "llvm-c/Target.h" #include <stdio.h> #include <stdlib.h> #include <string.h> static void pprint(int pos, unsigned char *buf, int len, const char *disasm) { int i; printf("%04x: ", pos); for (i = 0; i < 8; i++) { if (i < len) { printf("%02x ", buf[i]); } else { printf(" "); } } printf(" %s\n", disasm); } static void do_disassemble(const char *triple, const char *features, unsigned char *buf, int siz) { LLVMDisasmContextRef D = LLVMCreateDisasmCPUFeatures(triple, "", features, NULL, 0, NULL, NULL); char outline[1024]; int pos; if (!D) { printf("ERROR: Couldn't create disassembler for triple %s\n", triple); return; } pos = 0; while (pos < siz) { size_t l = LLVMDisasmInstruction(D, buf + pos, siz - pos, 0, outline, sizeof(outline)); if (!l) { pprint(pos, buf + pos, 1, "\t???"); pos++; } else { pprint(pos, buf + pos, l, outline); pos += l; } } LLVMDisasmDispose(D); } static void handle_line(char **tokens, int ntokens) { unsigned char disbuf[128]; size_t disbuflen = 0; const char *triple = tokens[0]; const char *features = tokens[1]; int i; printf("triple: %s, features: %s\n", triple, features); if (!strcmp(features, "NULL")) features = ""; for (i = 2; i < ntokens; i++) { disbuf[disbuflen++] = strtol(tokens[i], NULL, 16); if (disbuflen >= sizeof(disbuf)) { fprintf(stderr, "Warning: Too long line, truncating\n"); break; } } do_disassemble(triple, features, disbuf, disbuflen); } int disassemble(void) { LLVMInitializeAllTargetInfos(); LLVMInitializeAllTargetMCs(); LLVMInitializeAllDisassemblers(); tokenize_stdin(handle_line); return 0; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-c-test/module.c
/*===-- module.c - tool for testing libLLVM and llvm-c API ----------------===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This file implements the --module-dump, --module-list-functions and *| |* --module-list-globals commands in llvm-c-test. *| |* *| \*===----------------------------------------------------------------------===*/ #include "llvm-c-test.h" #include "llvm-c/BitReader.h" #include "llvm-c/Core.h" #include <stdio.h> #include <stdlib.h> #include <string.h> static LLVMModuleRef load_module(void) { LLVMMemoryBufferRef MB; LLVMModuleRef M; char *msg = NULL; if (LLVMCreateMemoryBufferWithSTDIN(&MB, &msg)) { fprintf(stderr, "Error reading file: %s\n", msg); exit(1); } if (LLVMParseBitcode(MB, &M, &msg)) { fprintf(stderr, "Error parsing bitcode: %s\n", msg); LLVMDisposeMemoryBuffer(MB); exit(1); } LLVMDisposeMemoryBuffer(MB); return M; } int module_dump(void) { LLVMModuleRef M = load_module(); char *irstr = LLVMPrintModuleToString(M); puts(irstr); LLVMDisposeMessage(irstr); LLVMDisposeModule(M); return 0; } int module_list_functions(void) { LLVMModuleRef M = load_module(); LLVMValueRef f; f = LLVMGetFirstFunction(M); while (f) { if (LLVMIsDeclaration(f)) { printf("FunctionDeclaration: %s\n", LLVMGetValueName(f)); } else { LLVMBasicBlockRef bb; LLVMValueRef isn; unsigned nisn = 0; unsigned nbb = 0; printf("FunctionDefinition: %s [#bb=%u]\n", LLVMGetValueName(f), LLVMCountBasicBlocks(f)); for (bb = LLVMGetFirstBasicBlock(f); bb; bb = LLVMGetNextBasicBlock(bb)) { nbb++; for (isn = LLVMGetFirstInstruction(bb); isn; isn = LLVMGetNextInstruction(isn)) { nisn++; if (LLVMIsACallInst(isn)) { LLVMValueRef callee = LLVMGetOperand(isn, LLVMGetNumOperands(isn) - 1); printf(" calls: %s\n", LLVMGetValueName(callee)); } } } printf(" #isn: %u\n", nisn); printf(" #bb: %u\n\n", nbb); } f = LLVMGetNextFunction(f); } LLVMDisposeModule(M); return 0; } int module_list_globals(void) { LLVMModuleRef M = load_module(); LLVMValueRef g; g = LLVMGetFirstGlobal(M); while (g) { LLVMTypeRef T = LLVMTypeOf(g); char *s = LLVMPrintTypeToString(T); printf("Global%s: %s %s\n", LLVMIsDeclaration(g) ? "Declaration" : "Definition", LLVMGetValueName(g), s); LLVMDisposeMessage(s); g = LLVMGetNextGlobal(g); } LLVMDisposeModule(M); return 0; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-c-test/metadata.c
/*===-- object.c - tool for testing libLLVM and llvm-c API ----------------===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This file implements the --add-named-metadata-operand and --set-metadata *| |* commands in llvm-c-test. *| |* *| \*===----------------------------------------------------------------------===*/ #include "llvm-c-test.h" #include "llvm-c/Core.h" int add_named_metadata_operand(void) { LLVMModuleRef m = LLVMModuleCreateWithName("Mod"); LLVMValueRef values[] = { LLVMConstInt(LLVMInt32Type(), 0, 0) }; // This used to trigger an assertion LLVMAddNamedMetadataOperand(m, "name", LLVMMDNode(values, 1)); LLVMDisposeModule(m); return 0; } int set_metadata(void) { LLVMBuilderRef b = LLVMCreateBuilder(); LLVMValueRef values[] = { LLVMConstInt(LLVMInt32Type(), 0, 0) }; // This used to trigger an assertion LLVMSetMetadata( LLVMBuildRetVoid(b), LLVMGetMDKindID("kind", 4), LLVMMDNode(values, 1)); LLVMDisposeBuilder(b); return 0; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-c-test/helpers.c
/*===-- helpers.c - tool for testing libLLVM and llvm-c API ---------------===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* Helper functions *| |* *| \*===----------------------------------------------------------------------===*/ #include "llvm-c-test.h" #include <stdio.h> #include <string.h> #define MAX_TOKENS 512 #define MAX_LINE_LEN 1024 void tokenize_stdin(void (*cb)(char **tokens, int ntokens)) { char line[MAX_LINE_LEN]; char *tokbuf[MAX_TOKENS]; while (fgets(line, sizeof(line), stdin)) { int c = 0; if (line[0] == ';' || line[0] == '\n') continue; while (c < MAX_TOKENS) { tokbuf[c] = strtok(c ? NULL : line, " \n"); if (!tokbuf[c]) break; c++; } if (c) cb(tokbuf, c); } }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-objdump/MachODump.cpp
//===-- MachODump.cpp - Object file dumping utility for llvm --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the MachO-specific dumper for llvm-objdump. // //===----------------------------------------------------------------------===// #include "llvm-objdump.h" #include "llvm-c/Disassembler.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/Triple.h" #include "llvm/Config/config.h" #include "llvm/DebugInfo/DIContext.h" #include "llvm/DebugInfo/DWARF/DWARFContext.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCDisassembler.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCInstPrinter.h" #include "llvm/MC/MCInstrDesc.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/Object/MachO.h" #include "llvm/Object/MachOUniversal.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Endian.h" #include "llvm/Support/Format.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Support/GraphWriter.h" #include "llvm/Support/LEB128.h" #include "llvm/Support/MachO.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cstring> #include <system_error> #if HAVE_CXXABI_H #include <cxxabi.h> #endif using namespace llvm; using namespace object; static cl::opt<bool> UseDbg("g", cl::desc("Print line information from debug info if available")); static cl::opt<std::string> DSYMFile("dsym", cl::desc("Use .dSYM file for debug info")); static cl::opt<bool> FullLeadingAddr("full-leading-addr", cl::desc("Print full leading address")); static cl::opt<bool> NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address")); cl::opt<bool> llvm::UniversalHeaders("universal-headers", cl::desc("Print Mach-O universal headers " "(requires -macho)")); cl::opt<bool> llvm::ArchiveHeaders("archive-headers", cl::desc("Print archive headers for Mach-O archives " "(requires -macho)")); cl::opt<bool> ArchiveMemberOffsets("archive-member-offsets", cl::desc("Print the offset to each archive member for " "Mach-O archives (requires -macho and " "-archive-headers)")); cl::opt<bool> llvm::IndirectSymbols("indirect-symbols", cl::desc("Print indirect symbol table for Mach-O " "objects (requires -macho)")); cl::opt<bool> llvm::DataInCode("data-in-code", cl::desc("Print the data in code table for Mach-O objects " "(requires -macho)")); cl::opt<bool> llvm::LinkOptHints("link-opt-hints", cl::desc("Print the linker optimization hints for " "Mach-O objects (requires -macho)")); cl::list<std::string> llvm::DumpSections("section", cl::desc("Prints the specified segment,section for " "Mach-O objects (requires -macho)")); cl::opt<bool> llvm::InfoPlist("info-plist", cl::desc("Print the info plist section as strings for " "Mach-O objects (requires -macho)")); cl::opt<bool> llvm::DylibsUsed("dylibs-used", cl::desc("Print the shared libraries used for linked " "Mach-O files (requires -macho)")); cl::opt<bool> llvm::DylibId("dylib-id", cl::desc("Print the shared library's id for the dylib Mach-O " "file (requires -macho)")); cl::opt<bool> llvm::NonVerbose("non-verbose", cl::desc("Print the info for Mach-O objects in " "non-verbose or numeric form (requires -macho)")); cl::opt<bool> llvm::ObjcMetaData("objc-meta-data", cl::desc("Print the Objective-C runtime meta data for " "Mach-O files (requires -macho)")); cl::opt<std::string> llvm::DisSymName( "dis-symname", cl::desc("disassemble just this symbol's instructions (requires -macho")); static cl::opt<bool> NoSymbolicOperands( "no-symbolic-operands", cl::desc("do not symbolic operands when disassembling (requires -macho)")); static cl::list<std::string> ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"), cl::ZeroOrMore); bool ArchAll = false; static std::string ThumbTripleName; static const Target *GetTarget(const MachOObjectFile *MachOObj, const char **McpuDefault, const Target **ThumbTarget) { // Figure out the target triple. if (TripleName.empty()) { llvm::Triple TT("unknown-unknown-unknown"); llvm::Triple ThumbTriple = Triple(); TT = MachOObj->getArch(McpuDefault, &ThumbTriple); TripleName = TT.str(); ThumbTripleName = ThumbTriple.str(); } // Get the target specific parser. std::string Error; const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error); if (TheTarget && ThumbTripleName.empty()) return TheTarget; *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error); if (*ThumbTarget) return TheTarget; errs() << "llvm-objdump: error: unable to get target for '"; if (!TheTarget) errs() << TripleName; else errs() << ThumbTripleName; errs() << "', see --version and --triple.\n"; return nullptr; } struct SymbolSorter { bool operator()(const SymbolRef &A, const SymbolRef &B) { uint64_t AAddr = (A.getType() != SymbolRef::ST_Function) ? 0 : A.getValue(); uint64_t BAddr = (B.getType() != SymbolRef::ST_Function) ? 0 : B.getValue(); return AAddr < BAddr; } }; // Types for the storted data in code table that is built before disassembly // and the predicate function to sort them. typedef std::pair<uint64_t, DiceRef> DiceTableEntry; typedef std::vector<DiceTableEntry> DiceTable; typedef DiceTable::iterator dice_table_iterator; // This is used to search for a data in code table entry for the PC being // disassembled. The j parameter has the PC in j.first. A single data in code // table entry can cover many bytes for each of its Kind's. So if the offset, // aka the i.first value, of the data in code table entry plus its Length // covers the PC being searched for this will return true. If not it will // return false. static bool compareDiceTableEntries(const DiceTableEntry &i, const DiceTableEntry &j) { uint16_t Length; i.second.getLength(Length); return j.first >= i.first && j.first < i.first + Length; } static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length, unsigned short Kind) { uint32_t Value, Size = 1; switch (Kind) { default: case MachO::DICE_KIND_DATA: if (Length >= 4) { if (!NoShowRawInsn) dumpBytes(ArrayRef<uint8_t>(bytes, 4), outs()); Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; outs() << "\t.long " << Value; Size = 4; } else if (Length >= 2) { if (!NoShowRawInsn) dumpBytes(ArrayRef<uint8_t>(bytes, 2), outs()); Value = bytes[1] << 8 | bytes[0]; outs() << "\t.short " << Value; Size = 2; } else { if (!NoShowRawInsn) dumpBytes(ArrayRef<uint8_t>(bytes, 2), outs()); Value = bytes[0]; outs() << "\t.byte " << Value; Size = 1; } if (Kind == MachO::DICE_KIND_DATA) outs() << "\t@ KIND_DATA\n"; else outs() << "\t@ data in code kind = " << Kind << "\n"; break; case MachO::DICE_KIND_JUMP_TABLE8: if (!NoShowRawInsn) dumpBytes(ArrayRef<uint8_t>(bytes, 1), outs()); Value = bytes[0]; outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n"; Size = 1; break; case MachO::DICE_KIND_JUMP_TABLE16: if (!NoShowRawInsn) dumpBytes(ArrayRef<uint8_t>(bytes, 2), outs()); Value = bytes[1] << 8 | bytes[0]; outs() << "\t.short " << format("%5u", Value & 0xffff) << "\t@ KIND_JUMP_TABLE16\n"; Size = 2; break; case MachO::DICE_KIND_JUMP_TABLE32: case MachO::DICE_KIND_ABS_JUMP_TABLE32: if (!NoShowRawInsn) dumpBytes(ArrayRef<uint8_t>(bytes, 4), outs()); Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; outs() << "\t.long " << Value; if (Kind == MachO::DICE_KIND_JUMP_TABLE32) outs() << "\t@ KIND_JUMP_TABLE32\n"; else outs() << "\t@ KIND_ABS_JUMP_TABLE32\n"; Size = 4; break; } return Size; } static void getSectionsAndSymbols(MachOObjectFile *MachOObj, std::vector<SectionRef> &Sections, std::vector<SymbolRef> &Symbols, SmallVectorImpl<uint64_t> &FoundFns, uint64_t &BaseSegmentAddress) { for (const SymbolRef &Symbol : MachOObj->symbols()) { ErrorOr<StringRef> SymName = Symbol.getName(); if (std::error_code EC = SymName.getError()) report_fatal_error(EC.message()); if (!SymName->startswith("ltmp")) Symbols.push_back(Symbol); } for (const SectionRef &Section : MachOObj->sections()) { StringRef SectName; Section.getName(SectName); Sections.push_back(Section); } bool BaseSegmentAddressSet = false; for (const auto &Command : MachOObj->load_commands()) { if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) { // We found a function starts segment, parse the addresses for later // consumption. MachO::linkedit_data_command LLC = MachOObj->getLinkeditDataLoadCommand(Command); MachOObj->ReadULEB128s(LLC.dataoff, FoundFns); } else if (Command.C.cmd == MachO::LC_SEGMENT) { MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command); StringRef SegName = SLC.segname; if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") { BaseSegmentAddressSet = true; BaseSegmentAddress = SLC.vmaddr; } } } } static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose, uint32_t n, uint32_t count, uint32_t stride, uint64_t addr) { MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand(); uint32_t nindirectsyms = Dysymtab.nindirectsyms; if (n > nindirectsyms) outs() << " (entries start past the end of the indirect symbol " "table) (reserved1 field greater than the table size)"; else if (n + count > nindirectsyms) outs() << " (entries extends past the end of the indirect symbol " "table)"; outs() << "\n"; uint32_t cputype = O->getHeader().cputype; if (cputype & MachO::CPU_ARCH_ABI64) outs() << "address index"; else outs() << "address index"; if (verbose) outs() << " name\n"; else outs() << "\n"; for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) { if (cputype & MachO::CPU_ARCH_ABI64) outs() << format("0x%016" PRIx64, addr + j * stride) << " "; else outs() << format("0x%08" PRIx32, addr + j * stride) << " "; MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand(); uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j); if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) { outs() << "LOCAL\n"; continue; } if (indirect_symbol == (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) { outs() << "LOCAL ABSOLUTE\n"; continue; } if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) { outs() << "ABSOLUTE\n"; continue; } outs() << format("%5u ", indirect_symbol); if (verbose) { MachO::symtab_command Symtab = O->getSymtabLoadCommand(); if (indirect_symbol < Symtab.nsyms) { symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol); SymbolRef Symbol = *Sym; ErrorOr<StringRef> SymName = Symbol.getName(); if (std::error_code EC = SymName.getError()) report_fatal_error(EC.message()); outs() << *SymName; } else { outs() << "?"; } } outs() << "\n"; } } static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) { for (const auto &Load : O->load_commands()) { if (Load.C.cmd == MachO::LC_SEGMENT_64) { MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load); for (unsigned J = 0; J < Seg.nsects; ++J) { MachO::section_64 Sec = O->getSection64(Load, J); uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || section_type == MachO::S_LAZY_SYMBOL_POINTERS || section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || section_type == MachO::S_SYMBOL_STUBS) { uint32_t stride; if (section_type == MachO::S_SYMBOL_STUBS) stride = Sec.reserved2; else stride = 8; if (stride == 0) { outs() << "Can't print indirect symbols for (" << Sec.segname << "," << Sec.sectname << ") " << "(size of stubs in reserved2 field is zero)\n"; continue; } uint32_t count = Sec.size / stride; outs() << "Indirect symbols for (" << Sec.segname << "," << Sec.sectname << ") " << count << " entries"; uint32_t n = Sec.reserved1; PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr); } } } else if (Load.C.cmd == MachO::LC_SEGMENT) { MachO::segment_command Seg = O->getSegmentLoadCommand(Load); for (unsigned J = 0; J < Seg.nsects; ++J) { MachO::section Sec = O->getSection(Load, J); uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || section_type == MachO::S_LAZY_SYMBOL_POINTERS || section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || section_type == MachO::S_SYMBOL_STUBS) { uint32_t stride; if (section_type == MachO::S_SYMBOL_STUBS) stride = Sec.reserved2; else stride = 4; if (stride == 0) { outs() << "Can't print indirect symbols for (" << Sec.segname << "," << Sec.sectname << ") " << "(size of stubs in reserved2 field is zero)\n"; continue; } uint32_t count = Sec.size / stride; outs() << "Indirect symbols for (" << Sec.segname << "," << Sec.sectname << ") " << count << " entries"; uint32_t n = Sec.reserved1; PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr); } } } } } static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) { MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand(); uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry); outs() << "Data in code table (" << nentries << " entries)\n"; outs() << "offset length kind\n"; for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE; ++DI) { uint32_t Offset; DI->getOffset(Offset); outs() << format("0x%08" PRIx32, Offset) << " "; uint16_t Length; DI->getLength(Length); outs() << format("%6u", Length) << " "; uint16_t Kind; DI->getKind(Kind); if (verbose) { switch (Kind) { case MachO::DICE_KIND_DATA: outs() << "DATA"; break; case MachO::DICE_KIND_JUMP_TABLE8: outs() << "JUMP_TABLE8"; break; case MachO::DICE_KIND_JUMP_TABLE16: outs() << "JUMP_TABLE16"; break; case MachO::DICE_KIND_JUMP_TABLE32: outs() << "JUMP_TABLE32"; break; case MachO::DICE_KIND_ABS_JUMP_TABLE32: outs() << "ABS_JUMP_TABLE32"; break; default: outs() << format("0x%04" PRIx32, Kind); break; } } else outs() << format("0x%04" PRIx32, Kind); outs() << "\n"; } } static void PrintLinkOptHints(MachOObjectFile *O) { MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand(); const char *loh = O->getData().substr(LohLC.dataoff, 1).data(); uint32_t nloh = LohLC.datasize; outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n"; for (uint32_t i = 0; i < nloh;) { unsigned n; uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n); i += n; outs() << " identifier " << identifier << " "; if (i >= nloh) return; switch (identifier) { case 1: outs() << "AdrpAdrp\n"; break; case 2: outs() << "AdrpLdr\n"; break; case 3: outs() << "AdrpAddLdr\n"; break; case 4: outs() << "AdrpLdrGotLdr\n"; break; case 5: outs() << "AdrpAddStr\n"; break; case 6: outs() << "AdrpLdrGotStr\n"; break; case 7: outs() << "AdrpAdd\n"; break; case 8: outs() << "AdrpLdrGot\n"; break; default: outs() << "Unknown identifier value\n"; break; } uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n); i += n; outs() << " narguments " << narguments << "\n"; if (i >= nloh) return; for (uint32_t j = 0; j < narguments; j++) { uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n); i += n; outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n"; if (i >= nloh) return; } } } static void PrintDylibs(MachOObjectFile *O, bool JustId) { unsigned Index = 0; for (const auto &Load : O->load_commands()) { if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) || (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB || Load.C.cmd == MachO::LC_LOAD_DYLIB || Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB || Load.C.cmd == MachO::LC_REEXPORT_DYLIB || Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB || Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) { MachO::dylib_command dl = O->getDylibIDLoadCommand(Load); if (dl.dylib.name < dl.cmdsize) { const char *p = (const char *)(Load.Ptr) + dl.dylib.name; if (JustId) outs() << p << "\n"; else { outs() << "\t" << p; outs() << " (compatibility version " << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "." << ((dl.dylib.compatibility_version >> 8) & 0xff) << "." << (dl.dylib.compatibility_version & 0xff) << ","; outs() << " current version " << ((dl.dylib.current_version >> 16) & 0xffff) << "." << ((dl.dylib.current_version >> 8) & 0xff) << "." << (dl.dylib.current_version & 0xff) << ")\n"; } } else { outs() << "\tBad offset (" << dl.dylib.name << ") for name of "; if (Load.C.cmd == MachO::LC_ID_DYLIB) outs() << "LC_ID_DYLIB "; else if (Load.C.cmd == MachO::LC_LOAD_DYLIB) outs() << "LC_LOAD_DYLIB "; else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) outs() << "LC_LOAD_WEAK_DYLIB "; else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) outs() << "LC_LAZY_LOAD_DYLIB "; else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) outs() << "LC_REEXPORT_DYLIB "; else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) outs() << "LC_LOAD_UPWARD_DYLIB "; else outs() << "LC_??? "; outs() << "command " << Index++ << "\n"; } } } } typedef DenseMap<uint64_t, StringRef> SymbolAddressMap; static void CreateSymbolAddressMap(MachOObjectFile *O, SymbolAddressMap *AddrMap) { // Create a map of symbol addresses to symbol names. for (const SymbolRef &Symbol : O->symbols()) { SymbolRef::Type ST = Symbol.getType(); if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data || ST == SymbolRef::ST_Other) { uint64_t Address = Symbol.getValue(); ErrorOr<StringRef> SymNameOrErr = Symbol.getName(); if (std::error_code EC = SymNameOrErr.getError()) report_fatal_error(EC.message()); StringRef SymName = *SymNameOrErr; if (!SymName.startswith(".objc")) (*AddrMap)[Address] = SymName; } } } // GuessSymbolName is passed the address of what might be a symbol and a // pointer to the SymbolAddressMap. It returns the name of a symbol // with that address or nullptr if no symbol is found with that address. static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) { const char *SymbolName = nullptr; // A DenseMap can't lookup up some values. if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) { StringRef name = AddrMap->lookup(value); if (!name.empty()) SymbolName = name.data(); } return SymbolName; } static void DumpCstringChar(const char c) { char p[2]; p[0] = c; p[1] = '\0'; outs().write_escaped(p); } static void DumpCstringSection(MachOObjectFile *O, const char *sect, uint32_t sect_size, uint64_t sect_addr, bool print_addresses) { for (uint32_t i = 0; i < sect_size; i++) { if (print_addresses) { if (O->is64Bit()) outs() << format("%016" PRIx64, sect_addr + i) << " "; else outs() << format("%08" PRIx64, sect_addr + i) << " "; } for (; i < sect_size && sect[i] != '\0'; i++) DumpCstringChar(sect[i]); if (i < sect_size && sect[i] == '\0') outs() << "\n"; } } static void DumpLiteral4(uint32_t l, float f) { outs() << format("0x%08" PRIx32, l); if ((l & 0x7f800000) != 0x7f800000) outs() << format(" (%.16e)\n", f); else { if (l == 0x7f800000) outs() << " (+Infinity)\n"; else if (l == 0xff800000) outs() << " (-Infinity)\n"; else if ((l & 0x00400000) == 0x00400000) outs() << " (non-signaling Not-a-Number)\n"; else outs() << " (signaling Not-a-Number)\n"; } } static void DumpLiteral4Section(MachOObjectFile *O, const char *sect, uint32_t sect_size, uint64_t sect_addr, bool print_addresses) { for (uint32_t i = 0; i < sect_size; i += sizeof(float)) { if (print_addresses) { if (O->is64Bit()) outs() << format("%016" PRIx64, sect_addr + i) << " "; else outs() << format("%08" PRIx64, sect_addr + i) << " "; } float f; memcpy(&f, sect + i, sizeof(float)); if (O->isLittleEndian() != sys::IsLittleEndianHost) sys::swapByteOrder(f); uint32_t l; memcpy(&l, sect + i, sizeof(uint32_t)); if (O->isLittleEndian() != sys::IsLittleEndianHost) sys::swapByteOrder(l); DumpLiteral4(l, f); } } static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1, double d) { outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1); uint32_t Hi, Lo; if (O->isLittleEndian()) { Hi = l1; Lo = l0; } else { Hi = l0; Lo = l1; } // Hi is the high word, so this is equivalent to if(isfinite(d)) if ((Hi & 0x7ff00000) != 0x7ff00000) outs() << format(" (%.16e)\n", d); else { if (Hi == 0x7ff00000 && Lo == 0) outs() << " (+Infinity)\n"; else if (Hi == 0xfff00000 && Lo == 0) outs() << " (-Infinity)\n"; else if ((Hi & 0x00080000) == 0x00080000) outs() << " (non-signaling Not-a-Number)\n"; else outs() << " (signaling Not-a-Number)\n"; } } static void DumpLiteral8Section(MachOObjectFile *O, const char *sect, uint32_t sect_size, uint64_t sect_addr, bool print_addresses) { for (uint32_t i = 0; i < sect_size; i += sizeof(double)) { if (print_addresses) { if (O->is64Bit()) outs() << format("%016" PRIx64, sect_addr + i) << " "; else outs() << format("%08" PRIx64, sect_addr + i) << " "; } double d; memcpy(&d, sect + i, sizeof(double)); if (O->isLittleEndian() != sys::IsLittleEndianHost) sys::swapByteOrder(d); uint32_t l0, l1; memcpy(&l0, sect + i, sizeof(uint32_t)); memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t)); if (O->isLittleEndian() != sys::IsLittleEndianHost) { sys::swapByteOrder(l0); sys::swapByteOrder(l1); } DumpLiteral8(O, l0, l1, d); } } static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) { outs() << format("0x%08" PRIx32, l0) << " "; outs() << format("0x%08" PRIx32, l1) << " "; outs() << format("0x%08" PRIx32, l2) << " "; outs() << format("0x%08" PRIx32, l3) << "\n"; } static void DumpLiteral16Section(MachOObjectFile *O, const char *sect, uint32_t sect_size, uint64_t sect_addr, bool print_addresses) { for (uint32_t i = 0; i < sect_size; i += 16) { if (print_addresses) { if (O->is64Bit()) outs() << format("%016" PRIx64, sect_addr + i) << " "; else outs() << format("%08" PRIx64, sect_addr + i) << " "; } uint32_t l0, l1, l2, l3; memcpy(&l0, sect + i, sizeof(uint32_t)); memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t)); memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t)); memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t)); if (O->isLittleEndian() != sys::IsLittleEndianHost) { sys::swapByteOrder(l0); sys::swapByteOrder(l1); sys::swapByteOrder(l2); sys::swapByteOrder(l3); } DumpLiteral16(l0, l1, l2, l3); } } static void DumpLiteralPointerSection(MachOObjectFile *O, const SectionRef &Section, const char *sect, uint32_t sect_size, uint64_t sect_addr, bool print_addresses) { // Collect the literal sections in this Mach-O file. std::vector<SectionRef> LiteralSections; for (const SectionRef &Section : O->sections()) { DataRefImpl Ref = Section.getRawDataRefImpl(); uint32_t section_type; if (O->is64Bit()) { const MachO::section_64 Sec = O->getSection64(Ref); section_type = Sec.flags & MachO::SECTION_TYPE; } else { const MachO::section Sec = O->getSection(Ref); section_type = Sec.flags & MachO::SECTION_TYPE; } if (section_type == MachO::S_CSTRING_LITERALS || section_type == MachO::S_4BYTE_LITERALS || section_type == MachO::S_8BYTE_LITERALS || section_type == MachO::S_16BYTE_LITERALS) LiteralSections.push_back(Section); } // Set the size of the literal pointer. uint32_t lp_size = O->is64Bit() ? 8 : 4; // Collect the external relocation symbols for the literal pointers. std::vector<std::pair<uint64_t, SymbolRef>> Relocs; for (const RelocationRef &Reloc : Section.relocations()) { DataRefImpl Rel; MachO::any_relocation_info RE; bool isExtern = false; Rel = Reloc.getRawDataRefImpl(); RE = O->getRelocation(Rel); isExtern = O->getPlainRelocationExternal(RE); if (isExtern) { uint64_t RelocOffset = Reloc.getOffset(); symbol_iterator RelocSym = Reloc.getSymbol(); Relocs.push_back(std::make_pair(RelocOffset, *RelocSym)); } } array_pod_sort(Relocs.begin(), Relocs.end()); // Dump each literal pointer. for (uint32_t i = 0; i < sect_size; i += lp_size) { if (print_addresses) { if (O->is64Bit()) outs() << format("%016" PRIx64, sect_addr + i) << " "; else outs() << format("%08" PRIx64, sect_addr + i) << " "; } uint64_t lp; if (O->is64Bit()) { memcpy(&lp, sect + i, sizeof(uint64_t)); if (O->isLittleEndian() != sys::IsLittleEndianHost) sys::swapByteOrder(lp); } else { uint32_t li; memcpy(&li, sect + i, sizeof(uint32_t)); if (O->isLittleEndian() != sys::IsLittleEndianHost) sys::swapByteOrder(li); lp = li; } // First look for an external relocation entry for this literal pointer. auto Reloc = std::find_if( Relocs.begin(), Relocs.end(), [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; }); if (Reloc != Relocs.end()) { symbol_iterator RelocSym = Reloc->second; ErrorOr<StringRef> SymName = RelocSym->getName(); if (std::error_code EC = SymName.getError()) report_fatal_error(EC.message()); outs() << "external relocation entry for symbol:" << *SymName << "\n"; continue; } // For local references see what the section the literal pointer points to. auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(), [&](const SectionRef &R) { return lp >= R.getAddress() && lp < R.getAddress() + R.getSize(); }); if (Sect == LiteralSections.end()) { outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n"; continue; } uint64_t SectAddress = Sect->getAddress(); uint64_t SectSize = Sect->getSize(); StringRef SectName; Sect->getName(SectName); DataRefImpl Ref = Sect->getRawDataRefImpl(); StringRef SegmentName = O->getSectionFinalSegmentName(Ref); outs() << SegmentName << ":" << SectName << ":"; uint32_t section_type; if (O->is64Bit()) { const MachO::section_64 Sec = O->getSection64(Ref); section_type = Sec.flags & MachO::SECTION_TYPE; } else { const MachO::section Sec = O->getSection(Ref); section_type = Sec.flags & MachO::SECTION_TYPE; } StringRef BytesStr; Sect->getContents(BytesStr); const char *Contents = reinterpret_cast<const char *>(BytesStr.data()); switch (section_type) { case MachO::S_CSTRING_LITERALS: for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0'; i++) { DumpCstringChar(Contents[i]); } outs() << "\n"; break; case MachO::S_4BYTE_LITERALS: float f; memcpy(&f, Contents + (lp - SectAddress), sizeof(float)); uint32_t l; memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t)); if (O->isLittleEndian() != sys::IsLittleEndianHost) { sys::swapByteOrder(f); sys::swapByteOrder(l); } DumpLiteral4(l, f); break; case MachO::S_8BYTE_LITERALS: { double d; memcpy(&d, Contents + (lp - SectAddress), sizeof(double)); uint32_t l0, l1; memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t)); memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t), sizeof(uint32_t)); if (O->isLittleEndian() != sys::IsLittleEndianHost) { sys::swapByteOrder(f); sys::swapByteOrder(l0); sys::swapByteOrder(l1); } DumpLiteral8(O, l0, l1, d); break; } case MachO::S_16BYTE_LITERALS: { uint32_t l0, l1, l2, l3; memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t)); memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t), sizeof(uint32_t)); memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t), sizeof(uint32_t)); memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t), sizeof(uint32_t)); if (O->isLittleEndian() != sys::IsLittleEndianHost) { sys::swapByteOrder(l0); sys::swapByteOrder(l1); sys::swapByteOrder(l2); sys::swapByteOrder(l3); } DumpLiteral16(l0, l1, l2, l3); break; } } } } static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect, uint32_t sect_size, uint64_t sect_addr, SymbolAddressMap *AddrMap, bool verbose) { uint32_t stride; if (O->is64Bit()) stride = sizeof(uint64_t); else stride = sizeof(uint32_t); for (uint32_t i = 0; i < sect_size; i += stride) { const char *SymbolName = nullptr; if (O->is64Bit()) { outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " "; uint64_t pointer_value; memcpy(&pointer_value, sect + i, stride); if (O->isLittleEndian() != sys::IsLittleEndianHost) sys::swapByteOrder(pointer_value); outs() << format("0x%016" PRIx64, pointer_value); if (verbose) SymbolName = GuessSymbolName(pointer_value, AddrMap); } else { outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " "; uint32_t pointer_value; memcpy(&pointer_value, sect + i, stride); if (O->isLittleEndian() != sys::IsLittleEndianHost) sys::swapByteOrder(pointer_value); outs() << format("0x%08" PRIx32, pointer_value); if (verbose) SymbolName = GuessSymbolName(pointer_value, AddrMap); } if (SymbolName) outs() << " " << SymbolName; outs() << "\n"; } } static void DumpRawSectionContents(MachOObjectFile *O, const char *sect, uint32_t size, uint64_t addr) { uint32_t cputype = O->getHeader().cputype; if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) { uint32_t j; for (uint32_t i = 0; i < size; i += j, addr += j) { if (O->is64Bit()) outs() << format("%016" PRIx64, addr) << "\t"; else outs() << format("%08" PRIx64, addr) << "\t"; for (j = 0; j < 16 && i + j < size; j++) { uint8_t byte_word = *(sect + i + j); outs() << format("%02" PRIx32, (uint32_t)byte_word) << " "; } outs() << "\n"; } } else { uint32_t j; for (uint32_t i = 0; i < size; i += j, addr += j) { if (O->is64Bit()) outs() << format("%016" PRIx64, addr) << "\t"; else outs() << format("%08" PRIx64, sect) << "\t"; for (j = 0; j < 4 * sizeof(int32_t) && i + j < size; j += sizeof(int32_t)) { if (i + j + sizeof(int32_t) < size) { uint32_t long_word; memcpy(&long_word, sect + i + j, sizeof(int32_t)); if (O->isLittleEndian() != sys::IsLittleEndianHost) sys::swapByteOrder(long_word); outs() << format("%08" PRIx32, long_word) << " "; } else { for (uint32_t k = 0; i + j + k < size; k++) { uint8_t byte_word = *(sect + i + j); outs() << format("%02" PRIx32, (uint32_t)byte_word) << " "; } } } outs() << "\n"; } } } static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF, StringRef DisSegName, StringRef DisSectName); static void DumpProtocolSection(MachOObjectFile *O, const char *sect, uint32_t size, uint32_t addr); static void DumpSectionContents(StringRef Filename, MachOObjectFile *O, bool verbose) { SymbolAddressMap AddrMap; if (verbose) CreateSymbolAddressMap(O, &AddrMap); for (unsigned i = 0; i < DumpSections.size(); ++i) { StringRef DumpSection = DumpSections[i]; std::pair<StringRef, StringRef> DumpSegSectName; DumpSegSectName = DumpSection.split(','); StringRef DumpSegName, DumpSectName; if (DumpSegSectName.second.size()) { DumpSegName = DumpSegSectName.first; DumpSectName = DumpSegSectName.second; } else { DumpSegName = ""; DumpSectName = DumpSegSectName.first; } for (const SectionRef &Section : O->sections()) { StringRef SectName; Section.getName(SectName); DataRefImpl Ref = Section.getRawDataRefImpl(); StringRef SegName = O->getSectionFinalSegmentName(Ref); if ((DumpSegName.empty() || SegName == DumpSegName) && (SectName == DumpSectName)) { uint32_t section_flags; if (O->is64Bit()) { const MachO::section_64 Sec = O->getSection64(Ref); section_flags = Sec.flags; } else { const MachO::section Sec = O->getSection(Ref); section_flags = Sec.flags; } uint32_t section_type = section_flags & MachO::SECTION_TYPE; StringRef BytesStr; Section.getContents(BytesStr); const char *sect = reinterpret_cast<const char *>(BytesStr.data()); uint32_t sect_size = BytesStr.size(); uint64_t sect_addr = Section.getAddress(); outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; if (verbose) { if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) || (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) { DisassembleMachO(Filename, O, SegName, SectName); continue; } if (SegName == "__TEXT" && SectName == "__info_plist") { outs() << sect; continue; } if (SegName == "__OBJC" && SectName == "__protocol") { DumpProtocolSection(O, sect, sect_size, sect_addr); continue; } switch (section_type) { case MachO::S_REGULAR: DumpRawSectionContents(O, sect, sect_size, sect_addr); break; case MachO::S_ZEROFILL: outs() << "zerofill section and has no contents in the file\n"; break; case MachO::S_CSTRING_LITERALS: DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr); break; case MachO::S_4BYTE_LITERALS: DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr); break; case MachO::S_8BYTE_LITERALS: DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr); break; case MachO::S_16BYTE_LITERALS: DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr); break; case MachO::S_LITERAL_POINTERS: DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr, !NoLeadingAddr); break; case MachO::S_MOD_INIT_FUNC_POINTERS: case MachO::S_MOD_TERM_FUNC_POINTERS: DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap, verbose); break; default: outs() << "Unknown section type (" << format("0x%08" PRIx32, section_type) << ")\n"; DumpRawSectionContents(O, sect, sect_size, sect_addr); break; } } else { if (section_type == MachO::S_ZEROFILL) outs() << "zerofill section and has no contents in the file\n"; else DumpRawSectionContents(O, sect, sect_size, sect_addr); } } } } } static void DumpInfoPlistSectionContents(StringRef Filename, MachOObjectFile *O) { for (const SectionRef &Section : O->sections()) { StringRef SectName; Section.getName(SectName); DataRefImpl Ref = Section.getRawDataRefImpl(); StringRef SegName = O->getSectionFinalSegmentName(Ref); if (SegName == "__TEXT" && SectName == "__info_plist") { outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; StringRef BytesStr; Section.getContents(BytesStr); const char *sect = reinterpret_cast<const char *>(BytesStr.data()); outs() << sect; return; } } } // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file // and if it is and there is a list of architecture flags is specified then // check to make sure this Mach-O file is one of those architectures or all // architectures were specified. If not then an error is generated and this // routine returns false. Else it returns true. static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) { if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) { MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O); bool ArchFound = false; MachO::mach_header H; MachO::mach_header_64 H_64; Triple T; if (MachO->is64Bit()) { H_64 = MachO->MachOObjectFile::getHeader64(); T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype); } else { H = MachO->MachOObjectFile::getHeader(); T = MachOObjectFile::getArch(H.cputype, H.cpusubtype); } unsigned i; for (i = 0; i < ArchFlags.size(); ++i) { if (ArchFlags[i] == T.getArchName()) ArchFound = true; break; } if (!ArchFound) { errs() << "llvm-objdump: file: " + Filename + " does not contain " << "architecture: " + ArchFlags[i] + "\n"; return false; } } return true; } static void printObjcMetaData(MachOObjectFile *O, bool verbose); // ProcessMachO() is passed a single opened Mach-O file, which may be an // archive member and or in a slice of a universal file. It prints the // the file name and header info and then processes it according to the // command line options. static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF, StringRef ArchiveMemberName = StringRef(), StringRef ArchitectureName = StringRef()) { // If we are doing some processing here on the Mach-O file print the header // info. And don't print it otherwise like in the case of printing the // UniversalHeaders or ArchiveHeaders. if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind || LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData || (DumpSections.size() != 0)) { outs() << Filename; if (!ArchiveMemberName.empty()) outs() << '(' << ArchiveMemberName << ')'; if (!ArchitectureName.empty()) outs() << " (architecture " << ArchitectureName << ")"; outs() << ":\n"; } if (Disassemble) DisassembleMachO(Filename, MachOOF, "__TEXT", "__text"); if (IndirectSymbols) PrintIndirectSymbols(MachOOF, !NonVerbose); if (DataInCode) PrintDataInCodeTable(MachOOF, !NonVerbose); if (LinkOptHints) PrintLinkOptHints(MachOOF); if (Relocations) PrintRelocations(MachOOF); if (SectionHeaders) PrintSectionHeaders(MachOOF); if (SectionContents) PrintSectionContents(MachOOF); if (DumpSections.size() != 0) DumpSectionContents(Filename, MachOOF, !NonVerbose); if (InfoPlist) DumpInfoPlistSectionContents(Filename, MachOOF); if (DylibsUsed) PrintDylibs(MachOOF, false); if (DylibId) PrintDylibs(MachOOF, true); if (SymbolTable) PrintSymbolTable(MachOOF); if (UnwindInfo) printMachOUnwindInfo(MachOOF); if (PrivateHeaders) printMachOFileHeader(MachOOF); if (ObjcMetaData) printObjcMetaData(MachOOF, !NonVerbose); if (ExportsTrie) printExportsTrie(MachOOF); if (Rebase) printRebaseTable(MachOOF); if (Bind) printBindTable(MachOOF); if (LazyBind) printLazyBindTable(MachOOF); if (WeakBind) printWeakBindTable(MachOOF); } // printUnknownCPUType() helps print_fat_headers for unknown CPU's. static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) { outs() << " cputype (" << cputype << ")\n"; outs() << " cpusubtype (" << cpusubtype << ")\n"; } // printCPUType() helps print_fat_headers by printing the cputype and // pusubtype (symbolically for the one's it knows about). static void printCPUType(uint32_t cputype, uint32_t cpusubtype) { switch (cputype) { case MachO::CPU_TYPE_I386: switch (cpusubtype) { case MachO::CPU_SUBTYPE_I386_ALL: outs() << " cputype CPU_TYPE_I386\n"; outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n"; break; default: printUnknownCPUType(cputype, cpusubtype); break; } break; case MachO::CPU_TYPE_X86_64: switch (cpusubtype) { case MachO::CPU_SUBTYPE_X86_64_ALL: outs() << " cputype CPU_TYPE_X86_64\n"; outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n"; break; case MachO::CPU_SUBTYPE_X86_64_H: outs() << " cputype CPU_TYPE_X86_64\n"; outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n"; break; default: printUnknownCPUType(cputype, cpusubtype); break; } break; case MachO::CPU_TYPE_ARM: switch (cpusubtype) { case MachO::CPU_SUBTYPE_ARM_ALL: outs() << " cputype CPU_TYPE_ARM\n"; outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n"; break; case MachO::CPU_SUBTYPE_ARM_V4T: outs() << " cputype CPU_TYPE_ARM\n"; outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n"; break; case MachO::CPU_SUBTYPE_ARM_V5TEJ: outs() << " cputype CPU_TYPE_ARM\n"; outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n"; break; case MachO::CPU_SUBTYPE_ARM_XSCALE: outs() << " cputype CPU_TYPE_ARM\n"; outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n"; break; case MachO::CPU_SUBTYPE_ARM_V6: outs() << " cputype CPU_TYPE_ARM\n"; outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n"; break; case MachO::CPU_SUBTYPE_ARM_V6M: outs() << " cputype CPU_TYPE_ARM\n"; outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n"; break; case MachO::CPU_SUBTYPE_ARM_V7: outs() << " cputype CPU_TYPE_ARM\n"; outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n"; break; case MachO::CPU_SUBTYPE_ARM_V7EM: outs() << " cputype CPU_TYPE_ARM\n"; outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n"; break; case MachO::CPU_SUBTYPE_ARM_V7K: outs() << " cputype CPU_TYPE_ARM\n"; outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n"; break; case MachO::CPU_SUBTYPE_ARM_V7M: outs() << " cputype CPU_TYPE_ARM\n"; outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n"; break; case MachO::CPU_SUBTYPE_ARM_V7S: outs() << " cputype CPU_TYPE_ARM\n"; outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n"; break; default: printUnknownCPUType(cputype, cpusubtype); break; } break; case MachO::CPU_TYPE_ARM64: switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { case MachO::CPU_SUBTYPE_ARM64_ALL: outs() << " cputype CPU_TYPE_ARM64\n"; outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n"; break; default: printUnknownCPUType(cputype, cpusubtype); break; } break; default: printUnknownCPUType(cputype, cpusubtype); break; } } static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB, bool verbose) { outs() << "Fat headers\n"; if (verbose) outs() << "fat_magic FAT_MAGIC\n"; else outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n"; uint32_t nfat_arch = UB->getNumberOfObjects(); StringRef Buf = UB->getData(); uint64_t size = Buf.size(); uint64_t big_size = sizeof(struct MachO::fat_header) + nfat_arch * sizeof(struct MachO::fat_arch); outs() << "nfat_arch " << UB->getNumberOfObjects(); if (nfat_arch == 0) outs() << " (malformed, contains zero architecture types)\n"; else if (big_size > size) outs() << " (malformed, architectures past end of file)\n"; else outs() << "\n"; for (uint32_t i = 0; i < nfat_arch; ++i) { MachOUniversalBinary::ObjectForArch OFA(UB, i); uint32_t cputype = OFA.getCPUType(); uint32_t cpusubtype = OFA.getCPUSubType(); outs() << "architecture "; for (uint32_t j = 0; i != 0 && j <= i - 1; j++) { MachOUniversalBinary::ObjectForArch other_OFA(UB, j); uint32_t other_cputype = other_OFA.getCPUType(); uint32_t other_cpusubtype = other_OFA.getCPUSubType(); if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype && (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) == (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) { outs() << "(illegal duplicate architecture) "; break; } } if (verbose) { outs() << OFA.getArchTypeName() << "\n"; printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK); } else { outs() << i << "\n"; outs() << " cputype " << cputype << "\n"; outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) << "\n"; } if (verbose && (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) outs() << " capabilities CPU_SUBTYPE_LIB64\n"; else outs() << " capabilities " << format("0x%" PRIx32, (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n"; outs() << " offset " << OFA.getOffset(); if (OFA.getOffset() > size) outs() << " (past end of file)"; if (OFA.getOffset() % (1 << OFA.getAlign()) != 0) outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")"; outs() << "\n"; outs() << " size " << OFA.getSize(); big_size = OFA.getOffset() + OFA.getSize(); if (big_size > size) outs() << " (past end of file)"; outs() << "\n"; outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign()) << ")\n"; } } static void printArchiveChild(Archive::Child &C, bool verbose, bool print_offset) { if (print_offset) outs() << C.getChildOffset() << "\t"; sys::fs::perms Mode = C.getAccessMode(); if (verbose) { // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG. // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG. outs() << "-"; if (Mode & sys::fs::owner_read) outs() << "r"; else outs() << "-"; if (Mode & sys::fs::owner_write) outs() << "w"; else outs() << "-"; if (Mode & sys::fs::owner_exe) outs() << "x"; else outs() << "-"; if (Mode & sys::fs::group_read) outs() << "r"; else outs() << "-"; if (Mode & sys::fs::group_write) outs() << "w"; else outs() << "-"; if (Mode & sys::fs::group_exe) outs() << "x"; else outs() << "-"; if (Mode & sys::fs::others_read) outs() << "r"; else outs() << "-"; if (Mode & sys::fs::others_write) outs() << "w"; else outs() << "-"; if (Mode & sys::fs::others_exe) outs() << "x"; else outs() << "-"; } else { outs() << format("0%o ", Mode); } unsigned UID = C.getUID(); outs() << format("%3d/", UID); unsigned GID = C.getGID(); outs() << format("%-3d ", GID); uint64_t Size = C.getRawSize(); outs() << format("%5" PRId64, Size) << " "; StringRef RawLastModified = C.getRawLastModified(); if (verbose) { unsigned Seconds; if (RawLastModified.getAsInteger(10, Seconds)) outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified; else { // Since cime(3) returns a 26 character string of the form: // "Sun Sep 16 01:03:52 1973\n\0" // just print 24 characters. time_t t = Seconds; outs() << format("%.24s ", ctime(&t)); } } else { outs() << RawLastModified << " "; } if (verbose) { ErrorOr<StringRef> NameOrErr = C.getName(); if (NameOrErr.getError()) { StringRef RawName = C.getRawName(); outs() << RawName << "\n"; } else { StringRef Name = NameOrErr.get(); outs() << Name << "\n"; } } else { StringRef RawName = C.getRawName(); outs() << RawName << "\n"; } } static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) { if (A->hasSymbolTable()) { Archive::child_iterator S = A->getSymbolTableChild(); Archive::Child C = *S; printArchiveChild(C, verbose, print_offset); } for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E; ++I) { Archive::Child C = *I; printArchiveChild(C, verbose, print_offset); } } // ParseInputMachO() parses the named Mach-O file in Filename and handles the // -arch flags selecting just those slices as specified by them and also parses // archive files. Then for each individual Mach-O file ProcessMachO() is // called to process the file based on the command line options. void llvm::ParseInputMachO(StringRef Filename) { // Check for -arch all and verifiy the -arch flags are valid. for (unsigned i = 0; i < ArchFlags.size(); ++i) { if (ArchFlags[i] == "all") { ArchAll = true; } else { if (!MachOObjectFile::isValidArch(ArchFlags[i])) { errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] + "'for the -arch option\n"; return; } } } // Attempt to open the binary. ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename); if (std::error_code EC = BinaryOrErr.getError()) { errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n"; return; } Binary &Bin = *BinaryOrErr.get().getBinary(); if (Archive *A = dyn_cast<Archive>(&Bin)) { outs() << "Archive : " << Filename << "\n"; if (ArchiveHeaders) printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets); for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E; ++I) { ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary(); if (ChildOrErr.getError()) continue; if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) { if (!checkMachOAndArchFlags(O, Filename)) return; ProcessMachO(Filename, O, O->getFileName()); } } return; } if (UniversalHeaders) { if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) printMachOUniversalHeaders(UB, !NonVerbose); } if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) { // If we have a list of architecture flags specified dump only those. if (!ArchAll && ArchFlags.size() != 0) { // Look for a slice in the universal binary that matches each ArchFlag. bool ArchFound; for (unsigned i = 0; i < ArchFlags.size(); ++i) { ArchFound = false; for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), E = UB->end_objects(); I != E; ++I) { if (ArchFlags[i] == I->getArchTypeName()) { ArchFound = true; ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile(); std::string ArchitectureName = ""; if (ArchFlags.size() > 1) ArchitectureName = I->getArchTypeName(); if (ObjOrErr) { ObjectFile &O = *ObjOrErr.get(); if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O)) ProcessMachO(Filename, MachOOF, "", ArchitectureName); } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) { std::unique_ptr<Archive> &A = *AOrErr; outs() << "Archive : " << Filename; if (!ArchitectureName.empty()) outs() << " (architecture " << ArchitectureName << ")"; outs() << "\n"; if (ArchiveHeaders) printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets); for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end(); AI != AE; ++AI) { ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary(); if (ChildOrErr.getError()) continue; if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) ProcessMachO(Filename, O, O->getFileName(), ArchitectureName); } } } } if (!ArchFound) { errs() << "llvm-objdump: file: " + Filename + " does not contain " << "architecture: " + ArchFlags[i] + "\n"; return; } } return; } // No architecture flags were specified so if this contains a slice that // matches the host architecture dump only that. if (!ArchAll) { for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), E = UB->end_objects(); I != E; ++I) { if (MachOObjectFile::getHostArch().getArchName() == I->getArchTypeName()) { ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile(); std::string ArchiveName; ArchiveName.clear(); if (ObjOrErr) { ObjectFile &O = *ObjOrErr.get(); if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O)) ProcessMachO(Filename, MachOOF); } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) { std::unique_ptr<Archive> &A = *AOrErr; outs() << "Archive : " << Filename << "\n"; if (ArchiveHeaders) printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets); for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end(); AI != AE; ++AI) { ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary(); if (ChildOrErr.getError()) continue; if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) ProcessMachO(Filename, O, O->getFileName()); } } return; } } } // Either all architectures have been specified or none have been specified // and this does not contain the host architecture so dump all the slices. bool moreThanOneArch = UB->getNumberOfObjects() > 1; for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), E = UB->end_objects(); I != E; ++I) { ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile(); std::string ArchitectureName = ""; if (moreThanOneArch) ArchitectureName = I->getArchTypeName(); if (ObjOrErr) { ObjectFile &Obj = *ObjOrErr.get(); if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj)) ProcessMachO(Filename, MachOOF, "", ArchitectureName); } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) { std::unique_ptr<Archive> &A = *AOrErr; outs() << "Archive : " << Filename; if (!ArchitectureName.empty()) outs() << " (architecture " << ArchitectureName << ")"; outs() << "\n"; if (ArchiveHeaders) printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets); for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end(); AI != AE; ++AI) { ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary(); if (ChildOrErr.getError()) continue; if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) { if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O)) ProcessMachO(Filename, MachOOF, MachOOF->getFileName(), ArchitectureName); } } } } return; } if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) { if (!checkMachOAndArchFlags(O, Filename)) return; if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) { ProcessMachO(Filename, MachOOF); } else errs() << "llvm-objdump: '" << Filename << "': " << "Object is not a Mach-O file type.\n"; } else errs() << "llvm-objdump: '" << Filename << "': " << "Unrecognized file type.\n"; } typedef std::pair<uint64_t, const char *> BindInfoEntry; typedef std::vector<BindInfoEntry> BindTable; typedef BindTable::iterator bind_table_iterator; // The block of info used by the Symbolizer call backs. struct DisassembleInfo { bool verbose; MachOObjectFile *O; SectionRef S; SymbolAddressMap *AddrMap; std::vector<SectionRef> *Sections; const char *class_name; const char *selector_name; char *method; char *demangled_name; uint64_t adrp_addr; uint32_t adrp_inst; BindTable *bindtable; }; // SymbolizerGetOpInfo() is the operand information call back function. // This is called to get the symbolic information for operand(s) of an // instruction when it is being done. This routine does this from // the relocation information, symbol table, etc. That block of information // is a pointer to the struct DisassembleInfo that was passed when the // disassembler context was created and passed to back to here when // called back by the disassembler for instruction operands that could have // relocation information. The address of the instruction containing operand is // at the Pc parameter. The immediate value the operand has is passed in // op_info->Value and is at Offset past the start of the instruction and has a // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol // names and addends of the symbolic expression to add for the operand. The // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic // information is returned then this function returns 1 else it returns 0. static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset, uint64_t Size, int TagType, void *TagBuf) { struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo; struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf; uint64_t value = op_info->Value; // Make sure all fields returned are zero if we don't set them. memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1)); op_info->Value = value; // If the TagType is not the value 1 which it code knows about or if no // verbose symbolic information is wanted then just return 0, indicating no // information is being returned. if (TagType != 1 || !info->verbose) return 0; unsigned int Arch = info->O->getArch(); if (Arch == Triple::x86) { if (Size != 1 && Size != 2 && Size != 4 && Size != 0) return 0; // First search the section's relocation entries (if any) for an entry // for this section offset. uint32_t sect_addr = info->S.getAddress(); uint32_t sect_offset = (Pc + Offset) - sect_addr; bool reloc_found = false; DataRefImpl Rel; MachO::any_relocation_info RE; bool isExtern = false; SymbolRef Symbol; bool r_scattered = false; uint32_t r_value, pair_r_value, r_type; for (const RelocationRef &Reloc : info->S.relocations()) { uint64_t RelocOffset = Reloc.getOffset(); if (RelocOffset == sect_offset) { Rel = Reloc.getRawDataRefImpl(); RE = info->O->getRelocation(Rel); r_type = info->O->getAnyRelocationType(RE); r_scattered = info->O->isRelocationScattered(RE); if (r_scattered) { r_value = info->O->getScatteredRelocationValue(RE); if (r_type == MachO::GENERIC_RELOC_SECTDIFF || r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) { DataRefImpl RelNext = Rel; info->O->moveRelocationNext(RelNext); MachO::any_relocation_info RENext; RENext = info->O->getRelocation(RelNext); if (info->O->isRelocationScattered(RENext)) pair_r_value = info->O->getScatteredRelocationValue(RENext); else return 0; } } else { isExtern = info->O->getPlainRelocationExternal(RE); if (isExtern) { symbol_iterator RelocSym = Reloc.getSymbol(); Symbol = *RelocSym; } } reloc_found = true; break; } } if (reloc_found && isExtern) { ErrorOr<StringRef> SymName = Symbol.getName(); if (std::error_code EC = SymName.getError()) report_fatal_error(EC.message()); const char *name = SymName->data(); op_info->AddSymbol.Present = 1; op_info->AddSymbol.Name = name; // For i386 extern relocation entries the value in the instruction is // the offset from the symbol, and value is already set in op_info->Value. return 1; } if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF || r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) { const char *add = GuessSymbolName(r_value, info->AddrMap); const char *sub = GuessSymbolName(pair_r_value, info->AddrMap); uint32_t offset = value - (r_value - pair_r_value); op_info->AddSymbol.Present = 1; if (add != nullptr) op_info->AddSymbol.Name = add; else op_info->AddSymbol.Value = r_value; op_info->SubtractSymbol.Present = 1; if (sub != nullptr) op_info->SubtractSymbol.Name = sub; else op_info->SubtractSymbol.Value = pair_r_value; op_info->Value = offset; return 1; } // TODO: // Second search the external relocation entries of a fully linked image // (if any) for an entry that matches this segment offset. // uint32_t seg_offset = (Pc + Offset); return 0; } if (Arch == Triple::x86_64) { if (Size != 1 && Size != 2 && Size != 4 && Size != 0) return 0; // First search the section's relocation entries (if any) for an entry // for this section offset. uint64_t sect_addr = info->S.getAddress(); uint64_t sect_offset = (Pc + Offset) - sect_addr; bool reloc_found = false; DataRefImpl Rel; MachO::any_relocation_info RE; bool isExtern = false; SymbolRef Symbol; for (const RelocationRef &Reloc : info->S.relocations()) { uint64_t RelocOffset = Reloc.getOffset(); if (RelocOffset == sect_offset) { Rel = Reloc.getRawDataRefImpl(); RE = info->O->getRelocation(Rel); // NOTE: Scattered relocations don't exist on x86_64. isExtern = info->O->getPlainRelocationExternal(RE); if (isExtern) { symbol_iterator RelocSym = Reloc.getSymbol(); Symbol = *RelocSym; } reloc_found = true; break; } } if (reloc_found && isExtern) { // The Value passed in will be adjusted by the Pc if the instruction // adds the Pc. But for x86_64 external relocation entries the Value // is the offset from the external symbol. if (info->O->getAnyRelocationPCRel(RE)) op_info->Value -= Pc + Offset + Size; ErrorOr<StringRef> SymName = Symbol.getName(); if (std::error_code EC = SymName.getError()) report_fatal_error(EC.message()); const char *name = SymName->data(); unsigned Type = info->O->getAnyRelocationType(RE); if (Type == MachO::X86_64_RELOC_SUBTRACTOR) { DataRefImpl RelNext = Rel; info->O->moveRelocationNext(RelNext); MachO::any_relocation_info RENext = info->O->getRelocation(RelNext); unsigned TypeNext = info->O->getAnyRelocationType(RENext); bool isExternNext = info->O->getPlainRelocationExternal(RENext); unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext); if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) { op_info->SubtractSymbol.Present = 1; op_info->SubtractSymbol.Name = name; symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum); Symbol = *RelocSymNext; ErrorOr<StringRef> SymNameNext = Symbol.getName(); if (std::error_code EC = SymNameNext.getError()) report_fatal_error(EC.message()); name = SymNameNext->data(); } } // TODO: add the VariantKinds to op_info->VariantKind for relocation types // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT. op_info->AddSymbol.Present = 1; op_info->AddSymbol.Name = name; return 1; } // TODO: // Second search the external relocation entries of a fully linked image // (if any) for an entry that matches this segment offset. // uint64_t seg_offset = (Pc + Offset); return 0; } if (Arch == Triple::arm) { if (Offset != 0 || (Size != 4 && Size != 2)) return 0; // First search the section's relocation entries (if any) for an entry // for this section offset. uint32_t sect_addr = info->S.getAddress(); uint32_t sect_offset = (Pc + Offset) - sect_addr; DataRefImpl Rel; MachO::any_relocation_info RE; bool isExtern = false; SymbolRef Symbol; bool r_scattered = false; uint32_t r_value, pair_r_value, r_type, r_length, other_half; auto Reloc = std::find_if(info->S.relocations().begin(), info->S.relocations().end(), [&](const RelocationRef &Reloc) { uint64_t RelocOffset = Reloc.getOffset(); return RelocOffset == sect_offset; }); if (Reloc == info->S.relocations().end()) return 0; Rel = Reloc->getRawDataRefImpl(); RE = info->O->getRelocation(Rel); r_length = info->O->getAnyRelocationLength(RE); r_scattered = info->O->isRelocationScattered(RE); if (r_scattered) { r_value = info->O->getScatteredRelocationValue(RE); r_type = info->O->getScatteredRelocationType(RE); } else { r_type = info->O->getAnyRelocationType(RE); isExtern = info->O->getPlainRelocationExternal(RE); if (isExtern) { symbol_iterator RelocSym = Reloc->getSymbol(); Symbol = *RelocSym; } } if (r_type == MachO::ARM_RELOC_HALF || r_type == MachO::ARM_RELOC_SECTDIFF || r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF || r_type == MachO::ARM_RELOC_HALF_SECTDIFF) { DataRefImpl RelNext = Rel; info->O->moveRelocationNext(RelNext); MachO::any_relocation_info RENext; RENext = info->O->getRelocation(RelNext); other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff; if (info->O->isRelocationScattered(RENext)) pair_r_value = info->O->getScatteredRelocationValue(RENext); } if (isExtern) { ErrorOr<StringRef> SymName = Symbol.getName(); if (std::error_code EC = SymName.getError()) report_fatal_error(EC.message()); const char *name = SymName->data(); op_info->AddSymbol.Present = 1; op_info->AddSymbol.Name = name; switch (r_type) { case MachO::ARM_RELOC_HALF: if ((r_length & 0x1) == 1) { op_info->Value = value << 16 | other_half; op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16; } else { op_info->Value = other_half << 16 | value; op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16; } break; default: break; } return 1; } // If we have a branch that is not an external relocation entry then // return 0 so the code in tryAddingSymbolicOperand() can use the // SymbolLookUp call back with the branch target address to look up the // symbol and possiblity add an annotation for a symbol stub. if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 || r_type == MachO::ARM_THUMB_RELOC_BR22)) return 0; uint32_t offset = 0; if (r_type == MachO::ARM_RELOC_HALF || r_type == MachO::ARM_RELOC_HALF_SECTDIFF) { if ((r_length & 0x1) == 1) value = value << 16 | other_half; else value = other_half << 16 | value; } if (r_scattered && (r_type != MachO::ARM_RELOC_HALF && r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) { offset = value - r_value; value = r_value; } if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) { if ((r_length & 0x1) == 1) op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16; else op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16; const char *add = GuessSymbolName(r_value, info->AddrMap); const char *sub = GuessSymbolName(pair_r_value, info->AddrMap); int32_t offset = value - (r_value - pair_r_value); op_info->AddSymbol.Present = 1; if (add != nullptr) op_info->AddSymbol.Name = add; else op_info->AddSymbol.Value = r_value; op_info->SubtractSymbol.Present = 1; if (sub != nullptr) op_info->SubtractSymbol.Name = sub; else op_info->SubtractSymbol.Value = pair_r_value; op_info->Value = offset; return 1; } op_info->AddSymbol.Present = 1; op_info->Value = offset; if (r_type == MachO::ARM_RELOC_HALF) { if ((r_length & 0x1) == 1) op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16; else op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16; } const char *add = GuessSymbolName(value, info->AddrMap); if (add != nullptr) { op_info->AddSymbol.Name = add; return 1; } op_info->AddSymbol.Value = value; return 1; } if (Arch == Triple::aarch64) { if (Offset != 0 || Size != 4) return 0; // First search the section's relocation entries (if any) for an entry // for this section offset. uint64_t sect_addr = info->S.getAddress(); uint64_t sect_offset = (Pc + Offset) - sect_addr; auto Reloc = std::find_if(info->S.relocations().begin(), info->S.relocations().end(), [&](const RelocationRef &Reloc) { uint64_t RelocOffset = Reloc.getOffset(); return RelocOffset == sect_offset; }); if (Reloc == info->S.relocations().end()) return 0; DataRefImpl Rel = Reloc->getRawDataRefImpl(); MachO::any_relocation_info RE = info->O->getRelocation(Rel); uint32_t r_type = info->O->getAnyRelocationType(RE); if (r_type == MachO::ARM64_RELOC_ADDEND) { DataRefImpl RelNext = Rel; info->O->moveRelocationNext(RelNext); MachO::any_relocation_info RENext = info->O->getRelocation(RelNext); if (value == 0) { value = info->O->getPlainRelocationSymbolNum(RENext); op_info->Value = value; } } // NOTE: Scattered relocations don't exist on arm64. if (!info->O->getPlainRelocationExternal(RE)) return 0; ErrorOr<StringRef> SymName = Reloc->getSymbol()->getName(); if (std::error_code EC = SymName.getError()) report_fatal_error(EC.message()); const char *name = SymName->data(); op_info->AddSymbol.Present = 1; op_info->AddSymbol.Name = name; switch (r_type) { case MachO::ARM64_RELOC_PAGE21: /* @page */ op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE; break; case MachO::ARM64_RELOC_PAGEOFF12: /* @pageoff */ op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF; break; case MachO::ARM64_RELOC_GOT_LOAD_PAGE21: /* @gotpage */ op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE; break; case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12: /* @gotpageoff */ op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF; break; case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21: /* @tvlppage is not implemented in llvm-mc */ op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP; break; case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12: /* @tvlppageoff is not implemented in llvm-mc */ op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF; break; default: case MachO::ARM64_RELOC_BRANCH26: op_info->VariantKind = LLVMDisassembler_VariantKind_None; break; } return 1; } return 0; } // GuessCstringPointer is passed the address of what might be a pointer to a // literal string in a cstring section. If that address is in a cstring section // it returns a pointer to that string. Else it returns nullptr. static const char *GuessCstringPointer(uint64_t ReferenceValue, struct DisassembleInfo *info) { for (const auto &Load : info->O->load_commands()) { if (Load.C.cmd == MachO::LC_SEGMENT_64) { MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load); for (unsigned J = 0; J < Seg.nsects; ++J) { MachO::section_64 Sec = info->O->getSection64(Load, J); uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; if (section_type == MachO::S_CSTRING_LITERALS && ReferenceValue >= Sec.addr && ReferenceValue < Sec.addr + Sec.size) { uint64_t sect_offset = ReferenceValue - Sec.addr; uint64_t object_offset = Sec.offset + sect_offset; StringRef MachOContents = info->O->getData(); uint64_t object_size = MachOContents.size(); const char *object_addr = (const char *)MachOContents.data(); if (object_offset < object_size) { const char *name = object_addr + object_offset; return name; } else { return nullptr; } } } } else if (Load.C.cmd == MachO::LC_SEGMENT) { MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load); for (unsigned J = 0; J < Seg.nsects; ++J) { MachO::section Sec = info->O->getSection(Load, J); uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; if (section_type == MachO::S_CSTRING_LITERALS && ReferenceValue >= Sec.addr && ReferenceValue < Sec.addr + Sec.size) { uint64_t sect_offset = ReferenceValue - Sec.addr; uint64_t object_offset = Sec.offset + sect_offset; StringRef MachOContents = info->O->getData(); uint64_t object_size = MachOContents.size(); const char *object_addr = (const char *)MachOContents.data(); if (object_offset < object_size) { const char *name = object_addr + object_offset; return name; } else { return nullptr; } } } } } return nullptr; } // GuessIndirectSymbol returns the name of the indirect symbol for the // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe // an address of a symbol stub or a lazy or non-lazy pointer to associate the // symbol name being referenced by the stub or pointer. static const char *GuessIndirectSymbol(uint64_t ReferenceValue, struct DisassembleInfo *info) { MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand(); MachO::symtab_command Symtab = info->O->getSymtabLoadCommand(); for (const auto &Load : info->O->load_commands()) { if (Load.C.cmd == MachO::LC_SEGMENT_64) { MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load); for (unsigned J = 0; J < Seg.nsects; ++J) { MachO::section_64 Sec = info->O->getSection64(Load, J); uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || section_type == MachO::S_LAZY_SYMBOL_POINTERS || section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || section_type == MachO::S_SYMBOL_STUBS) && ReferenceValue >= Sec.addr && ReferenceValue < Sec.addr + Sec.size) { uint32_t stride; if (section_type == MachO::S_SYMBOL_STUBS) stride = Sec.reserved2; else stride = 8; if (stride == 0) return nullptr; uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride; if (index < Dysymtab.nindirectsyms) { uint32_t indirect_symbol = info->O->getIndirectSymbolTableEntry(Dysymtab, index); if (indirect_symbol < Symtab.nsyms) { symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol); SymbolRef Symbol = *Sym; ErrorOr<StringRef> SymName = Symbol.getName(); if (std::error_code EC = SymName.getError()) report_fatal_error(EC.message()); const char *name = SymName->data(); return name; } } } } } else if (Load.C.cmd == MachO::LC_SEGMENT) { MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load); for (unsigned J = 0; J < Seg.nsects; ++J) { MachO::section Sec = info->O->getSection(Load, J); uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || section_type == MachO::S_LAZY_SYMBOL_POINTERS || section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || section_type == MachO::S_SYMBOL_STUBS) && ReferenceValue >= Sec.addr && ReferenceValue < Sec.addr + Sec.size) { uint32_t stride; if (section_type == MachO::S_SYMBOL_STUBS) stride = Sec.reserved2; else stride = 4; if (stride == 0) return nullptr; uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride; if (index < Dysymtab.nindirectsyms) { uint32_t indirect_symbol = info->O->getIndirectSymbolTableEntry(Dysymtab, index); if (indirect_symbol < Symtab.nsyms) { symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol); SymbolRef Symbol = *Sym; ErrorOr<StringRef> SymName = Symbol.getName(); if (std::error_code EC = SymName.getError()) report_fatal_error(EC.message()); const char *name = SymName->data(); return name; } } } } } } return nullptr; } // method_reference() is called passing it the ReferenceName that might be // a reference it to an Objective-C method call. If so then it allocates and // assembles a method call string with the values last seen and saved in // the DisassembleInfo's class_name and selector_name fields. This is saved // into the method field of the info and any previous string is free'ed. // Then the class_name field in the info is set to nullptr. The method call // string is set into ReferenceName and ReferenceType is set to // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call // then both ReferenceType and ReferenceName are left unchanged. static void method_reference(struct DisassembleInfo *info, uint64_t *ReferenceType, const char **ReferenceName) { unsigned int Arch = info->O->getArch(); if (*ReferenceName != nullptr) { if (strcmp(*ReferenceName, "_objc_msgSend") == 0) { if (info->selector_name != nullptr) { if (info->method != nullptr) free(info->method); if (info->class_name != nullptr) { info->method = (char *)malloc(5 + strlen(info->class_name) + strlen(info->selector_name)); if (info->method != nullptr) { strcpy(info->method, "+["); strcat(info->method, info->class_name); strcat(info->method, " "); strcat(info->method, info->selector_name); strcat(info->method, "]"); *ReferenceName = info->method; *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message; } } else { info->method = (char *)malloc(9 + strlen(info->selector_name)); if (info->method != nullptr) { if (Arch == Triple::x86_64) strcpy(info->method, "-[%rdi "); else if (Arch == Triple::aarch64) strcpy(info->method, "-[x0 "); else strcpy(info->method, "-[r? "); strcat(info->method, info->selector_name); strcat(info->method, "]"); *ReferenceName = info->method; *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message; } } info->class_name = nullptr; } } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) { if (info->selector_name != nullptr) { if (info->method != nullptr) free(info->method); info->method = (char *)malloc(17 + strlen(info->selector_name)); if (info->method != nullptr) { if (Arch == Triple::x86_64) strcpy(info->method, "-[[%rdi super] "); else if (Arch == Triple::aarch64) strcpy(info->method, "-[[x0 super] "); else strcpy(info->method, "-[[r? super] "); strcat(info->method, info->selector_name); strcat(info->method, "]"); *ReferenceName = info->method; *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message; } info->class_name = nullptr; } } } } // GuessPointerPointer() is passed the address of what might be a pointer to // a reference to an Objective-C class, selector, message ref or cfstring. // If so the value of the pointer is returned and one of the booleans are set // to true. If not zero is returned and all the booleans are set to false. static uint64_t GuessPointerPointer(uint64_t ReferenceValue, struct DisassembleInfo *info, bool &classref, bool &selref, bool &msgref, bool &cfstring) { classref = false; selref = false; msgref = false; cfstring = false; for (const auto &Load : info->O->load_commands()) { if (Load.C.cmd == MachO::LC_SEGMENT_64) { MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load); for (unsigned J = 0; J < Seg.nsects; ++J) { MachO::section_64 Sec = info->O->getSection64(Load, J); if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 || strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 || strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 || strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 || strncmp(Sec.sectname, "__cfstring", 16) == 0) && ReferenceValue >= Sec.addr && ReferenceValue < Sec.addr + Sec.size) { uint64_t sect_offset = ReferenceValue - Sec.addr; uint64_t object_offset = Sec.offset + sect_offset; StringRef MachOContents = info->O->getData(); uint64_t object_size = MachOContents.size(); const char *object_addr = (const char *)MachOContents.data(); if (object_offset < object_size) { uint64_t pointer_value; memcpy(&pointer_value, object_addr + object_offset, sizeof(uint64_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) sys::swapByteOrder(pointer_value); if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0) selref = true; else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 || strncmp(Sec.sectname, "__objc_superrefs", 16) == 0) classref = true; else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 && ReferenceValue + 8 < Sec.addr + Sec.size) { msgref = true; memcpy(&pointer_value, object_addr + object_offset + 8, sizeof(uint64_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) sys::swapByteOrder(pointer_value); } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0) cfstring = true; return pointer_value; } else { return 0; } } } } // TODO: Look for LC_SEGMENT for 32-bit Mach-O files. } return 0; } // get_pointer_64 returns a pointer to the bytes in the object file at the // Address from a section in the Mach-O file. And indirectly returns the // offset into the section, number of bytes left in the section past the offset // and which section is was being referenced. If the Address is not in a // section nullptr is returned. static const char *get_pointer_64(uint64_t Address, uint32_t &offset, uint32_t &left, SectionRef &S, DisassembleInfo *info, bool objc_only = false) { offset = 0; left = 0; S = SectionRef(); for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) { uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress(); uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize(); if (objc_only) { StringRef SectName; ((*(info->Sections))[SectIdx]).getName(SectName); DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl(); StringRef SegName = info->O->getSectionFinalSegmentName(Ref); if (SegName != "__OBJC" && SectName != "__cstring") continue; } if (Address >= SectAddress && Address < SectAddress + SectSize) { S = (*(info->Sections))[SectIdx]; offset = Address - SectAddress; left = SectSize - offset; StringRef SectContents; ((*(info->Sections))[SectIdx]).getContents(SectContents); return SectContents.data() + offset; } } return nullptr; } static const char *get_pointer_32(uint32_t Address, uint32_t &offset, uint32_t &left, SectionRef &S, DisassembleInfo *info, bool objc_only = false) { return get_pointer_64(Address, offset, left, S, info, objc_only); } // get_symbol_64() returns the name of a symbol (or nullptr) and the address of // the symbol indirectly through n_value. Based on the relocation information // for the specified section offset in the specified section reference. // If no relocation information is found and a non-zero ReferenceValue for the // symbol is passed, look up that address in the info's AddrMap. static const char *get_symbol_64(uint32_t sect_offset, SectionRef S, DisassembleInfo *info, uint64_t &n_value, uint64_t ReferenceValue = 0) { n_value = 0; if (!info->verbose) return nullptr; // See if there is an external relocation entry at the sect_offset. bool reloc_found = false; DataRefImpl Rel; MachO::any_relocation_info RE; bool isExtern = false; SymbolRef Symbol; for (const RelocationRef &Reloc : S.relocations()) { uint64_t RelocOffset = Reloc.getOffset(); if (RelocOffset == sect_offset) { Rel = Reloc.getRawDataRefImpl(); RE = info->O->getRelocation(Rel); if (info->O->isRelocationScattered(RE)) continue; isExtern = info->O->getPlainRelocationExternal(RE); if (isExtern) { symbol_iterator RelocSym = Reloc.getSymbol(); Symbol = *RelocSym; } reloc_found = true; break; } } // If there is an external relocation entry for a symbol in this section // at this section_offset then use that symbol's value for the n_value // and return its name. const char *SymbolName = nullptr; if (reloc_found && isExtern) { n_value = Symbol.getValue(); ErrorOr<StringRef> NameOrError = Symbol.getName(); if (std::error_code EC = NameOrError.getError()) report_fatal_error(EC.message()); StringRef Name = *NameOrError; if (!Name.empty()) { SymbolName = Name.data(); return SymbolName; } } // TODO: For fully linked images, look through the external relocation // entries off the dynamic symtab command. For these the r_offset is from the // start of the first writeable segment in the Mach-O file. So the offset // to this section from that segment is passed to this routine by the caller, // as the database_offset. Which is the difference of the section's starting // address and the first writable segment. // // NOTE: need add passing the database_offset to this routine. // We did not find an external relocation entry so look up the ReferenceValue // as an address of a symbol and if found return that symbol's name. SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap); return SymbolName; } static const char *get_symbol_32(uint32_t sect_offset, SectionRef S, DisassembleInfo *info, uint32_t ReferenceValue) { uint64_t n_value64; return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue); } // These are structs in the Objective-C meta data and read to produce the // comments for disassembly. While these are part of the ABI they are no // public defintions. So the are here not in include/llvm/Support/MachO.h . // The cfstring object in a 64-bit Mach-O file. struct cfstring64_t { uint64_t isa; // class64_t * (64-bit pointer) uint64_t flags; // flag bits uint64_t characters; // char * (64-bit pointer) uint64_t length; // number of non-NULL characters in above }; // The class object in a 64-bit Mach-O file. struct class64_t { uint64_t isa; // class64_t * (64-bit pointer) uint64_t superclass; // class64_t * (64-bit pointer) uint64_t cache; // Cache (64-bit pointer) uint64_t vtable; // IMP * (64-bit pointer) uint64_t data; // class_ro64_t * (64-bit pointer) }; struct class32_t { uint32_t isa; /* class32_t * (32-bit pointer) */ uint32_t superclass; /* class32_t * (32-bit pointer) */ uint32_t cache; /* Cache (32-bit pointer) */ uint32_t vtable; /* IMP * (32-bit pointer) */ uint32_t data; /* class_ro32_t * (32-bit pointer) */ }; struct class_ro64_t { uint32_t flags; uint32_t instanceStart; uint32_t instanceSize; uint32_t reserved; uint64_t ivarLayout; // const uint8_t * (64-bit pointer) uint64_t name; // const char * (64-bit pointer) uint64_t baseMethods; // const method_list_t * (64-bit pointer) uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer) uint64_t ivars; // const ivar_list_t * (64-bit pointer) uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer) uint64_t baseProperties; // const struct objc_property_list (64-bit pointer) }; struct class_ro32_t { uint32_t flags; uint32_t instanceStart; uint32_t instanceSize; uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */ uint32_t name; /* const char * (32-bit pointer) */ uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */ uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */ uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */ uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */ uint32_t baseProperties; /* const struct objc_property_list * (32-bit pointer) */ }; /* Values for class_ro{64,32}_t->flags */ #define RO_META (1 << 0) #define RO_ROOT (1 << 1) #define RO_HAS_CXX_STRUCTORS (1 << 2) struct method_list64_t { uint32_t entsize; uint32_t count; /* struct method64_t first; These structures follow inline */ }; struct method_list32_t { uint32_t entsize; uint32_t count; /* struct method32_t first; These structures follow inline */ }; struct method64_t { uint64_t name; /* SEL (64-bit pointer) */ uint64_t types; /* const char * (64-bit pointer) */ uint64_t imp; /* IMP (64-bit pointer) */ }; struct method32_t { uint32_t name; /* SEL (32-bit pointer) */ uint32_t types; /* const char * (32-bit pointer) */ uint32_t imp; /* IMP (32-bit pointer) */ }; struct protocol_list64_t { uint64_t count; /* uintptr_t (a 64-bit value) */ /* struct protocol64_t * list[0]; These pointers follow inline */ }; struct protocol_list32_t { uint32_t count; /* uintptr_t (a 32-bit value) */ /* struct protocol32_t * list[0]; These pointers follow inline */ }; struct protocol64_t { uint64_t isa; /* id * (64-bit pointer) */ uint64_t name; /* const char * (64-bit pointer) */ uint64_t protocols; /* struct protocol_list64_t * (64-bit pointer) */ uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */ uint64_t classMethods; /* method_list_t * (64-bit pointer) */ uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */ uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */ uint64_t instanceProperties; /* struct objc_property_list * (64-bit pointer) */ }; struct protocol32_t { uint32_t isa; /* id * (32-bit pointer) */ uint32_t name; /* const char * (32-bit pointer) */ uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */ uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */ uint32_t classMethods; /* method_list_t * (32-bit pointer) */ uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */ uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */ uint32_t instanceProperties; /* struct objc_property_list * (32-bit pointer) */ }; struct ivar_list64_t { uint32_t entsize; uint32_t count; /* struct ivar64_t first; These structures follow inline */ }; struct ivar_list32_t { uint32_t entsize; uint32_t count; /* struct ivar32_t first; These structures follow inline */ }; struct ivar64_t { uint64_t offset; /* uintptr_t * (64-bit pointer) */ uint64_t name; /* const char * (64-bit pointer) */ uint64_t type; /* const char * (64-bit pointer) */ uint32_t alignment; uint32_t size; }; struct ivar32_t { uint32_t offset; /* uintptr_t * (32-bit pointer) */ uint32_t name; /* const char * (32-bit pointer) */ uint32_t type; /* const char * (32-bit pointer) */ uint32_t alignment; uint32_t size; }; struct objc_property_list64 { uint32_t entsize; uint32_t count; /* struct objc_property64 first; These structures follow inline */ }; struct objc_property_list32 { uint32_t entsize; uint32_t count; /* struct objc_property32 first; These structures follow inline */ }; struct objc_property64 { uint64_t name; /* const char * (64-bit pointer) */ uint64_t attributes; /* const char * (64-bit pointer) */ }; struct objc_property32 { uint32_t name; /* const char * (32-bit pointer) */ uint32_t attributes; /* const char * (32-bit pointer) */ }; struct category64_t { uint64_t name; /* const char * (64-bit pointer) */ uint64_t cls; /* struct class_t * (64-bit pointer) */ uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */ uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */ uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */ uint64_t instanceProperties; /* struct objc_property_list * (64-bit pointer) */ }; struct category32_t { uint32_t name; /* const char * (32-bit pointer) */ uint32_t cls; /* struct class_t * (32-bit pointer) */ uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */ uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */ uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */ uint32_t instanceProperties; /* struct objc_property_list * (32-bit pointer) */ }; struct objc_image_info64 { uint32_t version; uint32_t flags; }; struct objc_image_info32 { uint32_t version; uint32_t flags; }; struct imageInfo_t { uint32_t version; uint32_t flags; }; /* masks for objc_image_info.flags */ #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0) #define OBJC_IMAGE_SUPPORTS_GC (1 << 1) struct message_ref64 { uint64_t imp; /* IMP (64-bit pointer) */ uint64_t sel; /* SEL (64-bit pointer) */ }; struct message_ref32 { uint32_t imp; /* IMP (32-bit pointer) */ uint32_t sel; /* SEL (32-bit pointer) */ }; // Objective-C 1 (32-bit only) meta data structs. struct objc_module_t { uint32_t version; uint32_t size; uint32_t name; /* char * (32-bit pointer) */ uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */ }; struct objc_symtab_t { uint32_t sel_ref_cnt; uint32_t refs; /* SEL * (32-bit pointer) */ uint16_t cls_def_cnt; uint16_t cat_def_cnt; // uint32_t defs[1]; /* void * (32-bit pointer) variable size */ }; struct objc_class_t { uint32_t isa; /* struct objc_class * (32-bit pointer) */ uint32_t super_class; /* struct objc_class * (32-bit pointer) */ uint32_t name; /* const char * (32-bit pointer) */ int32_t version; int32_t info; int32_t instance_size; uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */ uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */ uint32_t cache; /* struct objc_cache * (32-bit pointer) */ uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */ }; #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask)) // class is not a metaclass #define CLS_CLASS 0x1 // class is a metaclass #define CLS_META 0x2 struct objc_category_t { uint32_t category_name; /* char * (32-bit pointer) */ uint32_t class_name; /* char * (32-bit pointer) */ uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */ uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */ uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */ }; struct objc_ivar_t { uint32_t ivar_name; /* char * (32-bit pointer) */ uint32_t ivar_type; /* char * (32-bit pointer) */ int32_t ivar_offset; }; struct objc_ivar_list_t { int32_t ivar_count; // struct objc_ivar_t ivar_list[1]; /* variable length structure */ }; struct objc_method_list_t { uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */ int32_t method_count; // struct objc_method_t method_list[1]; /* variable length structure */ }; struct objc_method_t { uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */ uint32_t method_types; /* char * (32-bit pointer) */ uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...) (32-bit pointer) */ }; struct objc_protocol_list_t { uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */ int32_t count; // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t * // (32-bit pointer) */ }; struct objc_protocol_t { uint32_t isa; /* struct objc_class * (32-bit pointer) */ uint32_t protocol_name; /* char * (32-bit pointer) */ uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */ uint32_t instance_methods; /* struct objc_method_description_list * (32-bit pointer) */ uint32_t class_methods; /* struct objc_method_description_list * (32-bit pointer) */ }; struct objc_method_description_list_t { int32_t count; // struct objc_method_description_t list[1]; }; struct objc_method_description_t { uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */ uint32_t types; /* char * (32-bit pointer) */ }; inline void swapStruct(struct cfstring64_t &cfs) { sys::swapByteOrder(cfs.isa); sys::swapByteOrder(cfs.flags); sys::swapByteOrder(cfs.characters); sys::swapByteOrder(cfs.length); } inline void swapStruct(struct class64_t &c) { sys::swapByteOrder(c.isa); sys::swapByteOrder(c.superclass); sys::swapByteOrder(c.cache); sys::swapByteOrder(c.vtable); sys::swapByteOrder(c.data); } inline void swapStruct(struct class32_t &c) { sys::swapByteOrder(c.isa); sys::swapByteOrder(c.superclass); sys::swapByteOrder(c.cache); sys::swapByteOrder(c.vtable); sys::swapByteOrder(c.data); } inline void swapStruct(struct class_ro64_t &cro) { sys::swapByteOrder(cro.flags); sys::swapByteOrder(cro.instanceStart); sys::swapByteOrder(cro.instanceSize); sys::swapByteOrder(cro.reserved); sys::swapByteOrder(cro.ivarLayout); sys::swapByteOrder(cro.name); sys::swapByteOrder(cro.baseMethods); sys::swapByteOrder(cro.baseProtocols); sys::swapByteOrder(cro.ivars); sys::swapByteOrder(cro.weakIvarLayout); sys::swapByteOrder(cro.baseProperties); } inline void swapStruct(struct class_ro32_t &cro) { sys::swapByteOrder(cro.flags); sys::swapByteOrder(cro.instanceStart); sys::swapByteOrder(cro.instanceSize); sys::swapByteOrder(cro.ivarLayout); sys::swapByteOrder(cro.name); sys::swapByteOrder(cro.baseMethods); sys::swapByteOrder(cro.baseProtocols); sys::swapByteOrder(cro.ivars); sys::swapByteOrder(cro.weakIvarLayout); sys::swapByteOrder(cro.baseProperties); } inline void swapStruct(struct method_list64_t &ml) { sys::swapByteOrder(ml.entsize); sys::swapByteOrder(ml.count); } inline void swapStruct(struct method_list32_t &ml) { sys::swapByteOrder(ml.entsize); sys::swapByteOrder(ml.count); } inline void swapStruct(struct method64_t &m) { sys::swapByteOrder(m.name); sys::swapByteOrder(m.types); sys::swapByteOrder(m.imp); } inline void swapStruct(struct method32_t &m) { sys::swapByteOrder(m.name); sys::swapByteOrder(m.types); sys::swapByteOrder(m.imp); } inline void swapStruct(struct protocol_list64_t &pl) { sys::swapByteOrder(pl.count); } inline void swapStruct(struct protocol_list32_t &pl) { sys::swapByteOrder(pl.count); } inline void swapStruct(struct protocol64_t &p) { sys::swapByteOrder(p.isa); sys::swapByteOrder(p.name); sys::swapByteOrder(p.protocols); sys::swapByteOrder(p.instanceMethods); sys::swapByteOrder(p.classMethods); sys::swapByteOrder(p.optionalInstanceMethods); sys::swapByteOrder(p.optionalClassMethods); sys::swapByteOrder(p.instanceProperties); } inline void swapStruct(struct protocol32_t &p) { sys::swapByteOrder(p.isa); sys::swapByteOrder(p.name); sys::swapByteOrder(p.protocols); sys::swapByteOrder(p.instanceMethods); sys::swapByteOrder(p.classMethods); sys::swapByteOrder(p.optionalInstanceMethods); sys::swapByteOrder(p.optionalClassMethods); sys::swapByteOrder(p.instanceProperties); } inline void swapStruct(struct ivar_list64_t &il) { sys::swapByteOrder(il.entsize); sys::swapByteOrder(il.count); } inline void swapStruct(struct ivar_list32_t &il) { sys::swapByteOrder(il.entsize); sys::swapByteOrder(il.count); } inline void swapStruct(struct ivar64_t &i) { sys::swapByteOrder(i.offset); sys::swapByteOrder(i.name); sys::swapByteOrder(i.type); sys::swapByteOrder(i.alignment); sys::swapByteOrder(i.size); } inline void swapStruct(struct ivar32_t &i) { sys::swapByteOrder(i.offset); sys::swapByteOrder(i.name); sys::swapByteOrder(i.type); sys::swapByteOrder(i.alignment); sys::swapByteOrder(i.size); } inline void swapStruct(struct objc_property_list64 &pl) { sys::swapByteOrder(pl.entsize); sys::swapByteOrder(pl.count); } inline void swapStruct(struct objc_property_list32 &pl) { sys::swapByteOrder(pl.entsize); sys::swapByteOrder(pl.count); } inline void swapStruct(struct objc_property64 &op) { sys::swapByteOrder(op.name); sys::swapByteOrder(op.attributes); } inline void swapStruct(struct objc_property32 &op) { sys::swapByteOrder(op.name); sys::swapByteOrder(op.attributes); } inline void swapStruct(struct category64_t &c) { sys::swapByteOrder(c.name); sys::swapByteOrder(c.cls); sys::swapByteOrder(c.instanceMethods); sys::swapByteOrder(c.classMethods); sys::swapByteOrder(c.protocols); sys::swapByteOrder(c.instanceProperties); } inline void swapStruct(struct category32_t &c) { sys::swapByteOrder(c.name); sys::swapByteOrder(c.cls); sys::swapByteOrder(c.instanceMethods); sys::swapByteOrder(c.classMethods); sys::swapByteOrder(c.protocols); sys::swapByteOrder(c.instanceProperties); } inline void swapStruct(struct objc_image_info64 &o) { sys::swapByteOrder(o.version); sys::swapByteOrder(o.flags); } inline void swapStruct(struct objc_image_info32 &o) { sys::swapByteOrder(o.version); sys::swapByteOrder(o.flags); } inline void swapStruct(struct imageInfo_t &o) { sys::swapByteOrder(o.version); sys::swapByteOrder(o.flags); } inline void swapStruct(struct message_ref64 &mr) { sys::swapByteOrder(mr.imp); sys::swapByteOrder(mr.sel); } inline void swapStruct(struct message_ref32 &mr) { sys::swapByteOrder(mr.imp); sys::swapByteOrder(mr.sel); } inline void swapStruct(struct objc_module_t &mod) { sys::swapByteOrder(mod.version); sys::swapByteOrder(mod.size); sys::swapByteOrder(mod.name); sys::swapByteOrder(mod.symtab); } inline void swapStruct(struct objc_symtab_t &symtab) { sys::swapByteOrder(symtab.sel_ref_cnt); sys::swapByteOrder(symtab.refs); sys::swapByteOrder(symtab.cls_def_cnt); sys::swapByteOrder(symtab.cat_def_cnt); } inline void swapStruct(struct objc_class_t &objc_class) { sys::swapByteOrder(objc_class.isa); sys::swapByteOrder(objc_class.super_class); sys::swapByteOrder(objc_class.name); sys::swapByteOrder(objc_class.version); sys::swapByteOrder(objc_class.info); sys::swapByteOrder(objc_class.instance_size); sys::swapByteOrder(objc_class.ivars); sys::swapByteOrder(objc_class.methodLists); sys::swapByteOrder(objc_class.cache); sys::swapByteOrder(objc_class.protocols); } inline void swapStruct(struct objc_category_t &objc_category) { sys::swapByteOrder(objc_category.category_name); sys::swapByteOrder(objc_category.class_name); sys::swapByteOrder(objc_category.instance_methods); sys::swapByteOrder(objc_category.class_methods); sys::swapByteOrder(objc_category.protocols); } inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) { sys::swapByteOrder(objc_ivar_list.ivar_count); } inline void swapStruct(struct objc_ivar_t &objc_ivar) { sys::swapByteOrder(objc_ivar.ivar_name); sys::swapByteOrder(objc_ivar.ivar_type); sys::swapByteOrder(objc_ivar.ivar_offset); } inline void swapStruct(struct objc_method_list_t &method_list) { sys::swapByteOrder(method_list.obsolete); sys::swapByteOrder(method_list.method_count); } inline void swapStruct(struct objc_method_t &method) { sys::swapByteOrder(method.method_name); sys::swapByteOrder(method.method_types); sys::swapByteOrder(method.method_imp); } inline void swapStruct(struct objc_protocol_list_t &protocol_list) { sys::swapByteOrder(protocol_list.next); sys::swapByteOrder(protocol_list.count); } inline void swapStruct(struct objc_protocol_t &protocol) { sys::swapByteOrder(protocol.isa); sys::swapByteOrder(protocol.protocol_name); sys::swapByteOrder(protocol.protocol_list); sys::swapByteOrder(protocol.instance_methods); sys::swapByteOrder(protocol.class_methods); } inline void swapStruct(struct objc_method_description_list_t &mdl) { sys::swapByteOrder(mdl.count); } inline void swapStruct(struct objc_method_description_t &md) { sys::swapByteOrder(md.name); sys::swapByteOrder(md.types); } static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue, struct DisassembleInfo *info); // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer // to an Objective-C class and returns the class name. It is also passed the // address of the pointer, so when the pointer is zero as it can be in an .o // file, that is used to look for an external relocation entry with a symbol // name. static const char *get_objc2_64bit_class_name(uint64_t pointer_value, uint64_t ReferenceValue, struct DisassembleInfo *info) { const char *r; uint32_t offset, left; SectionRef S; // The pointer_value can be 0 in an object file and have a relocation // entry for the class symbol at the ReferenceValue (the address of the // pointer). if (pointer_value == 0) { r = get_pointer_64(ReferenceValue, offset, left, S, info); if (r == nullptr || left < sizeof(uint64_t)) return nullptr; uint64_t n_value; const char *symbol_name = get_symbol_64(offset, S, info, n_value); if (symbol_name == nullptr) return nullptr; const char *class_name = strrchr(symbol_name, '$'); if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0') return class_name + 2; else return nullptr; } // The case were the pointer_value is non-zero and points to a class defined // in this Mach-O file. r = get_pointer_64(pointer_value, offset, left, S, info); if (r == nullptr || left < sizeof(struct class64_t)) return nullptr; struct class64_t c; memcpy(&c, r, sizeof(struct class64_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(c); if (c.data == 0) return nullptr; r = get_pointer_64(c.data, offset, left, S, info); if (r == nullptr || left < sizeof(struct class_ro64_t)) return nullptr; struct class_ro64_t cro; memcpy(&cro, r, sizeof(struct class_ro64_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(cro); if (cro.name == 0) return nullptr; const char *name = get_pointer_64(cro.name, offset, left, S, info); return name; } // get_objc2_64bit_cfstring_name is used for disassembly and is passed a // pointer to a cfstring and returns its name or nullptr. static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue, struct DisassembleInfo *info) { const char *r, *name; uint32_t offset, left; SectionRef S; struct cfstring64_t cfs; uint64_t cfs_characters; r = get_pointer_64(ReferenceValue, offset, left, S, info); if (r == nullptr || left < sizeof(struct cfstring64_t)) return nullptr; memcpy(&cfs, r, sizeof(struct cfstring64_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(cfs); if (cfs.characters == 0) { uint64_t n_value; const char *symbol_name = get_symbol_64( offset + offsetof(struct cfstring64_t, characters), S, info, n_value); if (symbol_name == nullptr) return nullptr; cfs_characters = n_value; } else cfs_characters = cfs.characters; name = get_pointer_64(cfs_characters, offset, left, S, info); return name; } // get_objc2_64bit_selref() is used for disassembly and is passed a the address // of a pointer to an Objective-C selector reference when the pointer value is // zero as in a .o file and is likely to have a external relocation entry with // who's symbol's n_value is the real pointer to the selector name. If that is // the case the real pointer to the selector name is returned else 0 is // returned static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue, struct DisassembleInfo *info) { uint32_t offset, left; SectionRef S; const char *r = get_pointer_64(ReferenceValue, offset, left, S, info); if (r == nullptr || left < sizeof(uint64_t)) return 0; uint64_t n_value; const char *symbol_name = get_symbol_64(offset, S, info, n_value); if (symbol_name == nullptr) return 0; return n_value; } static const SectionRef get_section(MachOObjectFile *O, const char *segname, const char *sectname) { for (const SectionRef &Section : O->sections()) { StringRef SectName; Section.getName(SectName); DataRefImpl Ref = Section.getRawDataRefImpl(); StringRef SegName = O->getSectionFinalSegmentName(Ref); if (SegName == segname && SectName == sectname) return Section; } return SectionRef(); } static void walk_pointer_list_64(const char *listname, const SectionRef S, MachOObjectFile *O, struct DisassembleInfo *info, void (*func)(uint64_t, struct DisassembleInfo *info)) { if (S == SectionRef()) return; StringRef SectName; S.getName(SectName); DataRefImpl Ref = S.getRawDataRefImpl(); StringRef SegName = O->getSectionFinalSegmentName(Ref); outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; StringRef BytesStr; S.getContents(BytesStr); const char *Contents = reinterpret_cast<const char *>(BytesStr.data()); for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) { uint32_t left = S.getSize() - i; uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t); uint64_t p = 0; memcpy(&p, Contents + i, size); if (i + sizeof(uint64_t) > S.getSize()) outs() << listname << " list pointer extends past end of (" << SegName << "," << SectName << ") section\n"; outs() << format("%016" PRIx64, S.getAddress() + i) << " "; if (O->isLittleEndian() != sys::IsLittleEndianHost) sys::swapByteOrder(p); uint64_t n_value = 0; const char *name = get_symbol_64(i, S, info, n_value, p); if (name == nullptr) name = get_dyld_bind_info_symbolname(S.getAddress() + i, info); if (n_value != 0) { outs() << format("0x%" PRIx64, n_value); if (p != 0) outs() << " + " << format("0x%" PRIx64, p); } else outs() << format("0x%" PRIx64, p); if (name != nullptr) outs() << " " << name; outs() << "\n"; p += n_value; if (func) func(p, info); } } static void walk_pointer_list_32(const char *listname, const SectionRef S, MachOObjectFile *O, struct DisassembleInfo *info, void (*func)(uint32_t, struct DisassembleInfo *info)) { if (S == SectionRef()) return; StringRef SectName; S.getName(SectName); DataRefImpl Ref = S.getRawDataRefImpl(); StringRef SegName = O->getSectionFinalSegmentName(Ref); outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; StringRef BytesStr; S.getContents(BytesStr); const char *Contents = reinterpret_cast<const char *>(BytesStr.data()); for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) { uint32_t left = S.getSize() - i; uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t); uint32_t p = 0; memcpy(&p, Contents + i, size); if (i + sizeof(uint32_t) > S.getSize()) outs() << listname << " list pointer extends past end of (" << SegName << "," << SectName << ") section\n"; uint32_t Address = S.getAddress() + i; outs() << format("%08" PRIx32, Address) << " "; if (O->isLittleEndian() != sys::IsLittleEndianHost) sys::swapByteOrder(p); outs() << format("0x%" PRIx32, p); const char *name = get_symbol_32(i, S, info, p); if (name != nullptr) outs() << " " << name; outs() << "\n"; if (func) func(p, info); } } static void print_layout_map(const char *layout_map, uint32_t left) { outs() << " layout map: "; do { outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " "; left--; layout_map++; } while (*layout_map != '\0' && left != 0); outs() << "\n"; } static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) { uint32_t offset, left; SectionRef S; const char *layout_map; if (p == 0) return; layout_map = get_pointer_64(p, offset, left, S, info); print_layout_map(layout_map, left); } static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) { uint32_t offset, left; SectionRef S; const char *layout_map; if (p == 0) return; layout_map = get_pointer_32(p, offset, left, S, info); print_layout_map(layout_map, left); } static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info, const char *indent) { struct method_list64_t ml; struct method64_t m; const char *r; uint32_t offset, xoffset, left, i; SectionRef S, xS; const char *name, *sym_name; uint64_t n_value; r = get_pointer_64(p, offset, left, S, info); if (r == nullptr) return; memset(&ml, '\0', sizeof(struct method_list64_t)); if (left < sizeof(struct method_list64_t)) { memcpy(&ml, r, left); outs() << " (method_list_t entends past the end of the section)\n"; } else memcpy(&ml, r, sizeof(struct method_list64_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(ml); outs() << indent << "\t\t entsize " << ml.entsize << "\n"; outs() << indent << "\t\t count " << ml.count << "\n"; p += sizeof(struct method_list64_t); offset += sizeof(struct method_list64_t); for (i = 0; i < ml.count; i++) { r = get_pointer_64(p, offset, left, S, info); if (r == nullptr) return; memset(&m, '\0', sizeof(struct method64_t)); if (left < sizeof(struct method64_t)) { memcpy(&ml, r, left); outs() << indent << " (method_t entends past the end of the section)\n"; } else memcpy(&m, r, sizeof(struct method64_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(m); outs() << indent << "\t\t name "; sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S, info, n_value, m.name); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (m.name != 0) outs() << " + " << format("0x%" PRIx64, m.name); } else outs() << format("0x%" PRIx64, m.name); name = get_pointer_64(m.name + n_value, xoffset, left, xS, info); if (name != nullptr) outs() << format(" %.*s", left, name); outs() << "\n"; outs() << indent << "\t\t types "; sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S, info, n_value, m.types); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (m.types != 0) outs() << " + " << format("0x%" PRIx64, m.types); } else outs() << format("0x%" PRIx64, m.types); name = get_pointer_64(m.types + n_value, xoffset, left, xS, info); if (name != nullptr) outs() << format(" %.*s", left, name); outs() << "\n"; outs() << indent << "\t\t imp "; name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info, n_value, m.imp); if (info->verbose && name == nullptr) { if (n_value != 0) { outs() << format("0x%" PRIx64, n_value) << " "; if (m.imp != 0) outs() << "+ " << format("0x%" PRIx64, m.imp) << " "; } else outs() << format("0x%" PRIx64, m.imp) << " "; } if (name != nullptr) outs() << name; outs() << "\n"; p += sizeof(struct method64_t); offset += sizeof(struct method64_t); } } static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info, const char *indent) { struct method_list32_t ml; struct method32_t m; const char *r, *name; uint32_t offset, xoffset, left, i; SectionRef S, xS; r = get_pointer_32(p, offset, left, S, info); if (r == nullptr) return; memset(&ml, '\0', sizeof(struct method_list32_t)); if (left < sizeof(struct method_list32_t)) { memcpy(&ml, r, left); outs() << " (method_list_t entends past the end of the section)\n"; } else memcpy(&ml, r, sizeof(struct method_list32_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(ml); outs() << indent << "\t\t entsize " << ml.entsize << "\n"; outs() << indent << "\t\t count " << ml.count << "\n"; p += sizeof(struct method_list32_t); offset += sizeof(struct method_list32_t); for (i = 0; i < ml.count; i++) { r = get_pointer_32(p, offset, left, S, info); if (r == nullptr) return; memset(&m, '\0', sizeof(struct method32_t)); if (left < sizeof(struct method32_t)) { memcpy(&ml, r, left); outs() << indent << " (method_t entends past the end of the section)\n"; } else memcpy(&m, r, sizeof(struct method32_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(m); outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name); name = get_pointer_32(m.name, xoffset, left, xS, info); if (name != nullptr) outs() << format(" %.*s", left, name); outs() << "\n"; outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types); name = get_pointer_32(m.types, xoffset, left, xS, info); if (name != nullptr) outs() << format(" %.*s", left, name); outs() << "\n"; outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp); name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info, m.imp); if (name != nullptr) outs() << " " << name; outs() << "\n"; p += sizeof(struct method32_t); offset += sizeof(struct method32_t); } } static bool print_method_list(uint32_t p, struct DisassembleInfo *info) { uint32_t offset, left, xleft; SectionRef S; struct objc_method_list_t method_list; struct objc_method_t method; const char *r, *methods, *name, *SymbolName; int32_t i; r = get_pointer_32(p, offset, left, S, info, true); if (r == nullptr) return true; outs() << "\n"; if (left > sizeof(struct objc_method_list_t)) { memcpy(&method_list, r, sizeof(struct objc_method_list_t)); } else { outs() << "\t\t objc_method_list extends past end of the section\n"; memset(&method_list, '\0', sizeof(struct objc_method_list_t)); memcpy(&method_list, r, left); } if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(method_list); outs() << "\t\t obsolete " << format("0x%08" PRIx32, method_list.obsolete) << "\n"; outs() << "\t\t method_count " << method_list.method_count << "\n"; methods = r + sizeof(struct objc_method_list_t); for (i = 0; i < method_list.method_count; i++) { if ((i + 1) * sizeof(struct objc_method_t) > left) { outs() << "\t\t remaining method's extend past the of the section\n"; break; } memcpy(&method, methods + i * sizeof(struct objc_method_t), sizeof(struct objc_method_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(method); outs() << "\t\t method_name " << format("0x%08" PRIx32, method.method_name); if (info->verbose) { name = get_pointer_32(method.method_name, offset, xleft, S, info, true); if (name != nullptr) outs() << format(" %.*s", xleft, name); else outs() << " (not in an __OBJC section)"; } outs() << "\n"; outs() << "\t\t method_types " << format("0x%08" PRIx32, method.method_types); if (info->verbose) { name = get_pointer_32(method.method_types, offset, xleft, S, info, true); if (name != nullptr) outs() << format(" %.*s", xleft, name); else outs() << " (not in an __OBJC section)"; } outs() << "\n"; outs() << "\t\t method_imp " << format("0x%08" PRIx32, method.method_imp) << " "; if (info->verbose) { SymbolName = GuessSymbolName(method.method_imp, info->AddrMap); if (SymbolName != nullptr) outs() << SymbolName; } outs() << "\n"; } return false; } static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) { struct protocol_list64_t pl; uint64_t q, n_value; struct protocol64_t pc; const char *r; uint32_t offset, xoffset, left, i; SectionRef S, xS; const char *name, *sym_name; r = get_pointer_64(p, offset, left, S, info); if (r == nullptr) return; memset(&pl, '\0', sizeof(struct protocol_list64_t)); if (left < sizeof(struct protocol_list64_t)) { memcpy(&pl, r, left); outs() << " (protocol_list_t entends past the end of the section)\n"; } else memcpy(&pl, r, sizeof(struct protocol_list64_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(pl); outs() << " count " << pl.count << "\n"; p += sizeof(struct protocol_list64_t); offset += sizeof(struct protocol_list64_t); for (i = 0; i < pl.count; i++) { r = get_pointer_64(p, offset, left, S, info); if (r == nullptr) return; q = 0; if (left < sizeof(uint64_t)) { memcpy(&q, r, left); outs() << " (protocol_t * entends past the end of the section)\n"; } else memcpy(&q, r, sizeof(uint64_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) sys::swapByteOrder(q); outs() << "\t\t list[" << i << "] "; sym_name = get_symbol_64(offset, S, info, n_value, q); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (q != 0) outs() << " + " << format("0x%" PRIx64, q); } else outs() << format("0x%" PRIx64, q); outs() << " (struct protocol_t *)\n"; r = get_pointer_64(q + n_value, offset, left, S, info); if (r == nullptr) return; memset(&pc, '\0', sizeof(struct protocol64_t)); if (left < sizeof(struct protocol64_t)) { memcpy(&pc, r, left); outs() << " (protocol_t entends past the end of the section)\n"; } else memcpy(&pc, r, sizeof(struct protocol64_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(pc); outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n"; outs() << "\t\t\t name "; sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S, info, n_value, pc.name); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (pc.name != 0) outs() << " + " << format("0x%" PRIx64, pc.name); } else outs() << format("0x%" PRIx64, pc.name); name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info); if (name != nullptr) outs() << format(" %.*s", left, name); outs() << "\n"; outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n"; outs() << "\t\t instanceMethods "; sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods), S, info, n_value, pc.instanceMethods); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (pc.instanceMethods != 0) outs() << " + " << format("0x%" PRIx64, pc.instanceMethods); } else outs() << format("0x%" PRIx64, pc.instanceMethods); outs() << " (struct method_list_t *)\n"; if (pc.instanceMethods + n_value != 0) print_method_list64_t(pc.instanceMethods + n_value, info, "\t"); outs() << "\t\t classMethods "; sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S, info, n_value, pc.classMethods); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (pc.classMethods != 0) outs() << " + " << format("0x%" PRIx64, pc.classMethods); } else outs() << format("0x%" PRIx64, pc.classMethods); outs() << " (struct method_list_t *)\n"; if (pc.classMethods + n_value != 0) print_method_list64_t(pc.classMethods + n_value, info, "\t"); outs() << "\t optionalInstanceMethods " << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n"; outs() << "\t optionalClassMethods " << format("0x%" PRIx64, pc.optionalClassMethods) << "\n"; outs() << "\t instanceProperties " << format("0x%" PRIx64, pc.instanceProperties) << "\n"; p += sizeof(uint64_t); offset += sizeof(uint64_t); } } static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) { struct protocol_list32_t pl; uint32_t q; struct protocol32_t pc; const char *r; uint32_t offset, xoffset, left, i; SectionRef S, xS; const char *name; r = get_pointer_32(p, offset, left, S, info); if (r == nullptr) return; memset(&pl, '\0', sizeof(struct protocol_list32_t)); if (left < sizeof(struct protocol_list32_t)) { memcpy(&pl, r, left); outs() << " (protocol_list_t entends past the end of the section)\n"; } else memcpy(&pl, r, sizeof(struct protocol_list32_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(pl); outs() << " count " << pl.count << "\n"; p += sizeof(struct protocol_list32_t); offset += sizeof(struct protocol_list32_t); for (i = 0; i < pl.count; i++) { r = get_pointer_32(p, offset, left, S, info); if (r == nullptr) return; q = 0; if (left < sizeof(uint32_t)) { memcpy(&q, r, left); outs() << " (protocol_t * entends past the end of the section)\n"; } else memcpy(&q, r, sizeof(uint32_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) sys::swapByteOrder(q); outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q) << " (struct protocol_t *)\n"; r = get_pointer_32(q, offset, left, S, info); if (r == nullptr) return; memset(&pc, '\0', sizeof(struct protocol32_t)); if (left < sizeof(struct protocol32_t)) { memcpy(&pc, r, left); outs() << " (protocol_t entends past the end of the section)\n"; } else memcpy(&pc, r, sizeof(struct protocol32_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(pc); outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n"; outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name); name = get_pointer_32(pc.name, xoffset, left, xS, info); if (name != nullptr) outs() << format(" %.*s", left, name); outs() << "\n"; outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n"; outs() << "\t\t instanceMethods " << format("0x%" PRIx32, pc.instanceMethods) << " (struct method_list_t *)\n"; if (pc.instanceMethods != 0) print_method_list32_t(pc.instanceMethods, info, "\t"); outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods) << " (struct method_list_t *)\n"; if (pc.classMethods != 0) print_method_list32_t(pc.classMethods, info, "\t"); outs() << "\t optionalInstanceMethods " << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n"; outs() << "\t optionalClassMethods " << format("0x%" PRIx32, pc.optionalClassMethods) << "\n"; outs() << "\t instanceProperties " << format("0x%" PRIx32, pc.instanceProperties) << "\n"; p += sizeof(uint32_t); offset += sizeof(uint32_t); } } static void print_indent(uint32_t indent) { for (uint32_t i = 0; i < indent;) { if (indent - i >= 8) { outs() << "\t"; i += 8; } else { for (uint32_t j = i; j < indent; j++) outs() << " "; return; } } } static bool print_method_description_list(uint32_t p, uint32_t indent, struct DisassembleInfo *info) { uint32_t offset, left, xleft; SectionRef S; struct objc_method_description_list_t mdl; struct objc_method_description_t md; const char *r, *list, *name; int32_t i; r = get_pointer_32(p, offset, left, S, info, true); if (r == nullptr) return true; outs() << "\n"; if (left > sizeof(struct objc_method_description_list_t)) { memcpy(&mdl, r, sizeof(struct objc_method_description_list_t)); } else { print_indent(indent); outs() << " objc_method_description_list extends past end of the section\n"; memset(&mdl, '\0', sizeof(struct objc_method_description_list_t)); memcpy(&mdl, r, left); } if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(mdl); print_indent(indent); outs() << " count " << mdl.count << "\n"; list = r + sizeof(struct objc_method_description_list_t); for (i = 0; i < mdl.count; i++) { if ((i + 1) * sizeof(struct objc_method_description_t) > left) { print_indent(indent); outs() << " remaining list entries extend past the of the section\n"; break; } print_indent(indent); outs() << " list[" << i << "]\n"; memcpy(&md, list + i * sizeof(struct objc_method_description_t), sizeof(struct objc_method_description_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(md); print_indent(indent); outs() << " name " << format("0x%08" PRIx32, md.name); if (info->verbose) { name = get_pointer_32(md.name, offset, xleft, S, info, true); if (name != nullptr) outs() << format(" %.*s", xleft, name); else outs() << " (not in an __OBJC section)"; } outs() << "\n"; print_indent(indent); outs() << " types " << format("0x%08" PRIx32, md.types); if (info->verbose) { name = get_pointer_32(md.types, offset, xleft, S, info, true); if (name != nullptr) outs() << format(" %.*s", xleft, name); else outs() << " (not in an __OBJC section)"; } outs() << "\n"; } return false; } static bool print_protocol_list(uint32_t p, uint32_t indent, struct DisassembleInfo *info); static bool print_protocol(uint32_t p, uint32_t indent, struct DisassembleInfo *info) { uint32_t offset, left; SectionRef S; struct objc_protocol_t protocol; const char *r, *name; r = get_pointer_32(p, offset, left, S, info, true); if (r == nullptr) return true; outs() << "\n"; if (left >= sizeof(struct objc_protocol_t)) { memcpy(&protocol, r, sizeof(struct objc_protocol_t)); } else { print_indent(indent); outs() << " Protocol extends past end of the section\n"; memset(&protocol, '\0', sizeof(struct objc_protocol_t)); memcpy(&protocol, r, left); } if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(protocol); print_indent(indent); outs() << " isa " << format("0x%08" PRIx32, protocol.isa) << "\n"; print_indent(indent); outs() << " protocol_name " << format("0x%08" PRIx32, protocol.protocol_name); if (info->verbose) { name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true); if (name != nullptr) outs() << format(" %.*s", left, name); else outs() << " (not in an __OBJC section)"; } outs() << "\n"; print_indent(indent); outs() << " protocol_list " << format("0x%08" PRIx32, protocol.protocol_list); if (print_protocol_list(protocol.protocol_list, indent + 4, info)) outs() << " (not in an __OBJC section)\n"; print_indent(indent); outs() << " instance_methods " << format("0x%08" PRIx32, protocol.instance_methods); if (print_method_description_list(protocol.instance_methods, indent, info)) outs() << " (not in an __OBJC section)\n"; print_indent(indent); outs() << " class_methods " << format("0x%08" PRIx32, protocol.class_methods); if (print_method_description_list(protocol.class_methods, indent, info)) outs() << " (not in an __OBJC section)\n"; return false; } static bool print_protocol_list(uint32_t p, uint32_t indent, struct DisassembleInfo *info) { uint32_t offset, left, l; SectionRef S; struct objc_protocol_list_t protocol_list; const char *r, *list; int32_t i; r = get_pointer_32(p, offset, left, S, info, true); if (r == nullptr) return true; outs() << "\n"; if (left > sizeof(struct objc_protocol_list_t)) { memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t)); } else { outs() << "\t\t objc_protocol_list_t extends past end of the section\n"; memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t)); memcpy(&protocol_list, r, left); } if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(protocol_list); print_indent(indent); outs() << " next " << format("0x%08" PRIx32, protocol_list.next) << "\n"; print_indent(indent); outs() << " count " << protocol_list.count << "\n"; list = r + sizeof(struct objc_protocol_list_t); for (i = 0; i < protocol_list.count; i++) { if ((i + 1) * sizeof(uint32_t) > left) { outs() << "\t\t remaining list entries extend past the of the section\n"; break; } memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) sys::swapByteOrder(l); print_indent(indent); outs() << " list[" << i << "] " << format("0x%08" PRIx32, l); if (print_protocol(l, indent, info)) outs() << "(not in an __OBJC section)\n"; } return false; } static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) { struct ivar_list64_t il; struct ivar64_t i; const char *r; uint32_t offset, xoffset, left, j; SectionRef S, xS; const char *name, *sym_name, *ivar_offset_p; uint64_t ivar_offset, n_value; r = get_pointer_64(p, offset, left, S, info); if (r == nullptr) return; memset(&il, '\0', sizeof(struct ivar_list64_t)); if (left < sizeof(struct ivar_list64_t)) { memcpy(&il, r, left); outs() << " (ivar_list_t entends past the end of the section)\n"; } else memcpy(&il, r, sizeof(struct ivar_list64_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(il); outs() << " entsize " << il.entsize << "\n"; outs() << " count " << il.count << "\n"; p += sizeof(struct ivar_list64_t); offset += sizeof(struct ivar_list64_t); for (j = 0; j < il.count; j++) { r = get_pointer_64(p, offset, left, S, info); if (r == nullptr) return; memset(&i, '\0', sizeof(struct ivar64_t)); if (left < sizeof(struct ivar64_t)) { memcpy(&i, r, left); outs() << " (ivar_t entends past the end of the section)\n"; } else memcpy(&i, r, sizeof(struct ivar64_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(i); outs() << "\t\t\t offset "; sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S, info, n_value, i.offset); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (i.offset != 0) outs() << " + " << format("0x%" PRIx64, i.offset); } else outs() << format("0x%" PRIx64, i.offset); ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info); if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) { memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) sys::swapByteOrder(ivar_offset); outs() << " " << ivar_offset << "\n"; } else outs() << "\n"; outs() << "\t\t\t name "; sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info, n_value, i.name); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (i.name != 0) outs() << " + " << format("0x%" PRIx64, i.name); } else outs() << format("0x%" PRIx64, i.name); name = get_pointer_64(i.name + n_value, xoffset, left, xS, info); if (name != nullptr) outs() << format(" %.*s", left, name); outs() << "\n"; outs() << "\t\t\t type "; sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info, n_value, i.name); name = get_pointer_64(i.type + n_value, xoffset, left, xS, info); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (i.type != 0) outs() << " + " << format("0x%" PRIx64, i.type); } else outs() << format("0x%" PRIx64, i.type); if (name != nullptr) outs() << format(" %.*s", left, name); outs() << "\n"; outs() << "\t\t\talignment " << i.alignment << "\n"; outs() << "\t\t\t size " << i.size << "\n"; p += sizeof(struct ivar64_t); offset += sizeof(struct ivar64_t); } } static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) { struct ivar_list32_t il; struct ivar32_t i; const char *r; uint32_t offset, xoffset, left, j; SectionRef S, xS; const char *name, *ivar_offset_p; uint32_t ivar_offset; r = get_pointer_32(p, offset, left, S, info); if (r == nullptr) return; memset(&il, '\0', sizeof(struct ivar_list32_t)); if (left < sizeof(struct ivar_list32_t)) { memcpy(&il, r, left); outs() << " (ivar_list_t entends past the end of the section)\n"; } else memcpy(&il, r, sizeof(struct ivar_list32_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(il); outs() << " entsize " << il.entsize << "\n"; outs() << " count " << il.count << "\n"; p += sizeof(struct ivar_list32_t); offset += sizeof(struct ivar_list32_t); for (j = 0; j < il.count; j++) { r = get_pointer_32(p, offset, left, S, info); if (r == nullptr) return; memset(&i, '\0', sizeof(struct ivar32_t)); if (left < sizeof(struct ivar32_t)) { memcpy(&i, r, left); outs() << " (ivar_t entends past the end of the section)\n"; } else memcpy(&i, r, sizeof(struct ivar32_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(i); outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset); ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info); if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) { memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) sys::swapByteOrder(ivar_offset); outs() << " " << ivar_offset << "\n"; } else outs() << "\n"; outs() << "\t\t\t name " << format("0x%" PRIx32, i.name); name = get_pointer_32(i.name, xoffset, left, xS, info); if (name != nullptr) outs() << format(" %.*s", left, name); outs() << "\n"; outs() << "\t\t\t type " << format("0x%" PRIx32, i.type); name = get_pointer_32(i.type, xoffset, left, xS, info); if (name != nullptr) outs() << format(" %.*s", left, name); outs() << "\n"; outs() << "\t\t\talignment " << i.alignment << "\n"; outs() << "\t\t\t size " << i.size << "\n"; p += sizeof(struct ivar32_t); offset += sizeof(struct ivar32_t); } } static void print_objc_property_list64(uint64_t p, struct DisassembleInfo *info) { struct objc_property_list64 opl; struct objc_property64 op; const char *r; uint32_t offset, xoffset, left, j; SectionRef S, xS; const char *name, *sym_name; uint64_t n_value; r = get_pointer_64(p, offset, left, S, info); if (r == nullptr) return; memset(&opl, '\0', sizeof(struct objc_property_list64)); if (left < sizeof(struct objc_property_list64)) { memcpy(&opl, r, left); outs() << " (objc_property_list entends past the end of the section)\n"; } else memcpy(&opl, r, sizeof(struct objc_property_list64)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(opl); outs() << " entsize " << opl.entsize << "\n"; outs() << " count " << opl.count << "\n"; p += sizeof(struct objc_property_list64); offset += sizeof(struct objc_property_list64); for (j = 0; j < opl.count; j++) { r = get_pointer_64(p, offset, left, S, info); if (r == nullptr) return; memset(&op, '\0', sizeof(struct objc_property64)); if (left < sizeof(struct objc_property64)) { memcpy(&op, r, left); outs() << " (objc_property entends past the end of the section)\n"; } else memcpy(&op, r, sizeof(struct objc_property64)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(op); outs() << "\t\t\t name "; sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S, info, n_value, op.name); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (op.name != 0) outs() << " + " << format("0x%" PRIx64, op.name); } else outs() << format("0x%" PRIx64, op.name); name = get_pointer_64(op.name + n_value, xoffset, left, xS, info); if (name != nullptr) outs() << format(" %.*s", left, name); outs() << "\n"; outs() << "\t\t\tattributes "; sym_name = get_symbol_64(offset + offsetof(struct objc_property64, attributes), S, info, n_value, op.attributes); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (op.attributes != 0) outs() << " + " << format("0x%" PRIx64, op.attributes); } else outs() << format("0x%" PRIx64, op.attributes); name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info); if (name != nullptr) outs() << format(" %.*s", left, name); outs() << "\n"; p += sizeof(struct objc_property64); offset += sizeof(struct objc_property64); } } static void print_objc_property_list32(uint32_t p, struct DisassembleInfo *info) { struct objc_property_list32 opl; struct objc_property32 op; const char *r; uint32_t offset, xoffset, left, j; SectionRef S, xS; const char *name; r = get_pointer_32(p, offset, left, S, info); if (r == nullptr) return; memset(&opl, '\0', sizeof(struct objc_property_list32)); if (left < sizeof(struct objc_property_list32)) { memcpy(&opl, r, left); outs() << " (objc_property_list entends past the end of the section)\n"; } else memcpy(&opl, r, sizeof(struct objc_property_list32)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(opl); outs() << " entsize " << opl.entsize << "\n"; outs() << " count " << opl.count << "\n"; p += sizeof(struct objc_property_list32); offset += sizeof(struct objc_property_list32); for (j = 0; j < opl.count; j++) { r = get_pointer_32(p, offset, left, S, info); if (r == nullptr) return; memset(&op, '\0', sizeof(struct objc_property32)); if (left < sizeof(struct objc_property32)) { memcpy(&op, r, left); outs() << " (objc_property entends past the end of the section)\n"; } else memcpy(&op, r, sizeof(struct objc_property32)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(op); outs() << "\t\t\t name " << format("0x%" PRIx32, op.name); name = get_pointer_32(op.name, xoffset, left, xS, info); if (name != nullptr) outs() << format(" %.*s", left, name); outs() << "\n"; outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes); name = get_pointer_32(op.attributes, xoffset, left, xS, info); if (name != nullptr) outs() << format(" %.*s", left, name); outs() << "\n"; p += sizeof(struct objc_property32); offset += sizeof(struct objc_property32); } } static void print_class_ro64_t(uint64_t p, struct DisassembleInfo *info, bool &is_meta_class) { struct class_ro64_t cro; const char *r; uint32_t offset, xoffset, left; SectionRef S, xS; const char *name, *sym_name; uint64_t n_value; r = get_pointer_64(p, offset, left, S, info); if (r == nullptr || left < sizeof(struct class_ro64_t)) return; memset(&cro, '\0', sizeof(struct class_ro64_t)); if (left < sizeof(struct class_ro64_t)) { memcpy(&cro, r, left); outs() << " (class_ro_t entends past the end of the section)\n"; } else memcpy(&cro, r, sizeof(struct class_ro64_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(cro); outs() << " flags " << format("0x%" PRIx32, cro.flags); if (cro.flags & RO_META) outs() << " RO_META"; if (cro.flags & RO_ROOT) outs() << " RO_ROOT"; if (cro.flags & RO_HAS_CXX_STRUCTORS) outs() << " RO_HAS_CXX_STRUCTORS"; outs() << "\n"; outs() << " instanceStart " << cro.instanceStart << "\n"; outs() << " instanceSize " << cro.instanceSize << "\n"; outs() << " reserved " << format("0x%" PRIx32, cro.reserved) << "\n"; outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout) << "\n"; print_layout_map64(cro.ivarLayout, info); outs() << " name "; sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S, info, n_value, cro.name); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (cro.name != 0) outs() << " + " << format("0x%" PRIx64, cro.name); } else outs() << format("0x%" PRIx64, cro.name); name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info); if (name != nullptr) outs() << format(" %.*s", left, name); outs() << "\n"; outs() << " baseMethods "; sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods), S, info, n_value, cro.baseMethods); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (cro.baseMethods != 0) outs() << " + " << format("0x%" PRIx64, cro.baseMethods); } else outs() << format("0x%" PRIx64, cro.baseMethods); outs() << " (struct method_list_t *)\n"; if (cro.baseMethods + n_value != 0) print_method_list64_t(cro.baseMethods + n_value, info, ""); outs() << " baseProtocols "; sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S, info, n_value, cro.baseProtocols); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (cro.baseProtocols != 0) outs() << " + " << format("0x%" PRIx64, cro.baseProtocols); } else outs() << format("0x%" PRIx64, cro.baseProtocols); outs() << "\n"; if (cro.baseProtocols + n_value != 0) print_protocol_list64_t(cro.baseProtocols + n_value, info); outs() << " ivars "; sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S, info, n_value, cro.ivars); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (cro.ivars != 0) outs() << " + " << format("0x%" PRIx64, cro.ivars); } else outs() << format("0x%" PRIx64, cro.ivars); outs() << "\n"; if (cro.ivars + n_value != 0) print_ivar_list64_t(cro.ivars + n_value, info); outs() << " weakIvarLayout "; sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S, info, n_value, cro.weakIvarLayout); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (cro.weakIvarLayout != 0) outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout); } else outs() << format("0x%" PRIx64, cro.weakIvarLayout); outs() << "\n"; print_layout_map64(cro.weakIvarLayout + n_value, info); outs() << " baseProperties "; sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S, info, n_value, cro.baseProperties); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (cro.baseProperties != 0) outs() << " + " << format("0x%" PRIx64, cro.baseProperties); } else outs() << format("0x%" PRIx64, cro.baseProperties); outs() << "\n"; if (cro.baseProperties + n_value != 0) print_objc_property_list64(cro.baseProperties + n_value, info); is_meta_class = (cro.flags & RO_META) ? true : false; } static void print_class_ro32_t(uint32_t p, struct DisassembleInfo *info, bool &is_meta_class) { struct class_ro32_t cro; const char *r; uint32_t offset, xoffset, left; SectionRef S, xS; const char *name; r = get_pointer_32(p, offset, left, S, info); if (r == nullptr) return; memset(&cro, '\0', sizeof(struct class_ro32_t)); if (left < sizeof(struct class_ro32_t)) { memcpy(&cro, r, left); outs() << " (class_ro_t entends past the end of the section)\n"; } else memcpy(&cro, r, sizeof(struct class_ro32_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(cro); outs() << " flags " << format("0x%" PRIx32, cro.flags); if (cro.flags & RO_META) outs() << " RO_META"; if (cro.flags & RO_ROOT) outs() << " RO_ROOT"; if (cro.flags & RO_HAS_CXX_STRUCTORS) outs() << " RO_HAS_CXX_STRUCTORS"; outs() << "\n"; outs() << " instanceStart " << cro.instanceStart << "\n"; outs() << " instanceSize " << cro.instanceSize << "\n"; outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout) << "\n"; print_layout_map32(cro.ivarLayout, info); outs() << " name " << format("0x%" PRIx32, cro.name); name = get_pointer_32(cro.name, xoffset, left, xS, info); if (name != nullptr) outs() << format(" %.*s", left, name); outs() << "\n"; outs() << " baseMethods " << format("0x%" PRIx32, cro.baseMethods) << " (struct method_list_t *)\n"; if (cro.baseMethods != 0) print_method_list32_t(cro.baseMethods, info, ""); outs() << " baseProtocols " << format("0x%" PRIx32, cro.baseProtocols) << "\n"; if (cro.baseProtocols != 0) print_protocol_list32_t(cro.baseProtocols, info); outs() << " ivars " << format("0x%" PRIx32, cro.ivars) << "\n"; if (cro.ivars != 0) print_ivar_list32_t(cro.ivars, info); outs() << " weakIvarLayout " << format("0x%" PRIx32, cro.weakIvarLayout) << "\n"; print_layout_map32(cro.weakIvarLayout, info); outs() << " baseProperties " << format("0x%" PRIx32, cro.baseProperties) << "\n"; if (cro.baseProperties != 0) print_objc_property_list32(cro.baseProperties, info); is_meta_class = (cro.flags & RO_META) ? true : false; } static void print_class64_t(uint64_t p, struct DisassembleInfo *info) { struct class64_t c; const char *r; uint32_t offset, left; SectionRef S; const char *name; uint64_t isa_n_value, n_value; r = get_pointer_64(p, offset, left, S, info); if (r == nullptr || left < sizeof(struct class64_t)) return; memset(&c, '\0', sizeof(struct class64_t)); if (left < sizeof(struct class64_t)) { memcpy(&c, r, left); outs() << " (class_t entends past the end of the section)\n"; } else memcpy(&c, r, sizeof(struct class64_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(c); outs() << " isa " << format("0x%" PRIx64, c.isa); name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info, isa_n_value, c.isa); if (name != nullptr) outs() << " " << name; outs() << "\n"; outs() << " superclass " << format("0x%" PRIx64, c.superclass); name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info, n_value, c.superclass); if (name != nullptr) outs() << " " << name; outs() << "\n"; outs() << " cache " << format("0x%" PRIx64, c.cache); name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info, n_value, c.cache); if (name != nullptr) outs() << " " << name; outs() << "\n"; outs() << " vtable " << format("0x%" PRIx64, c.vtable); name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info, n_value, c.vtable); if (name != nullptr) outs() << " " << name; outs() << "\n"; name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info, n_value, c.data); outs() << " data "; if (n_value != 0) { if (info->verbose && name != nullptr) outs() << name; else outs() << format("0x%" PRIx64, n_value); if (c.data != 0) outs() << " + " << format("0x%" PRIx64, c.data); } else outs() << format("0x%" PRIx64, c.data); outs() << " (struct class_ro_t *)"; // This is a Swift class if some of the low bits of the pointer are set. if ((c.data + n_value) & 0x7) outs() << " Swift class"; outs() << "\n"; bool is_meta_class; print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class); if (is_meta_class == false) { outs() << "Meta Class\n"; print_class64_t(c.isa + isa_n_value, info); } } static void print_class32_t(uint32_t p, struct DisassembleInfo *info) { struct class32_t c; const char *r; uint32_t offset, left; SectionRef S; const char *name; r = get_pointer_32(p, offset, left, S, info); if (r == nullptr) return; memset(&c, '\0', sizeof(struct class32_t)); if (left < sizeof(struct class32_t)) { memcpy(&c, r, left); outs() << " (class_t entends past the end of the section)\n"; } else memcpy(&c, r, sizeof(struct class32_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(c); outs() << " isa " << format("0x%" PRIx32, c.isa); name = get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa); if (name != nullptr) outs() << " " << name; outs() << "\n"; outs() << " superclass " << format("0x%" PRIx32, c.superclass); name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info, c.superclass); if (name != nullptr) outs() << " " << name; outs() << "\n"; outs() << " cache " << format("0x%" PRIx32, c.cache); name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info, c.cache); if (name != nullptr) outs() << " " << name; outs() << "\n"; outs() << " vtable " << format("0x%" PRIx32, c.vtable); name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info, c.vtable); if (name != nullptr) outs() << " " << name; outs() << "\n"; name = get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data); outs() << " data " << format("0x%" PRIx32, c.data) << " (struct class_ro_t *)"; // This is a Swift class if some of the low bits of the pointer are set. if (c.data & 0x3) outs() << " Swift class"; outs() << "\n"; bool is_meta_class; print_class_ro32_t(c.data & ~0x3, info, is_meta_class); if (is_meta_class == false) { outs() << "Meta Class\n"; print_class32_t(c.isa, info); } } static void print_objc_class_t(struct objc_class_t *objc_class, struct DisassembleInfo *info) { uint32_t offset, left, xleft; const char *name, *p, *ivar_list; SectionRef S; int32_t i; struct objc_ivar_list_t objc_ivar_list; struct objc_ivar_t ivar; outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa); if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) { name = get_pointer_32(objc_class->isa, offset, left, S, info, true); if (name != nullptr) outs() << format(" %.*s", left, name); else outs() << " (not in an __OBJC section)"; } outs() << "\n"; outs() << "\t super_class " << format("0x%08" PRIx32, objc_class->super_class); if (info->verbose) { name = get_pointer_32(objc_class->super_class, offset, left, S, info, true); if (name != nullptr) outs() << format(" %.*s", left, name); else outs() << " (not in an __OBJC section)"; } outs() << "\n"; outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name); if (info->verbose) { name = get_pointer_32(objc_class->name, offset, left, S, info, true); if (name != nullptr) outs() << format(" %.*s", left, name); else outs() << " (not in an __OBJC section)"; } outs() << "\n"; outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version) << "\n"; outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info); if (info->verbose) { if (CLS_GETINFO(objc_class, CLS_CLASS)) outs() << " CLS_CLASS"; else if (CLS_GETINFO(objc_class, CLS_META)) outs() << " CLS_META"; } outs() << "\n"; outs() << "\t instance_size " << format("0x%08" PRIx32, objc_class->instance_size) << "\n"; p = get_pointer_32(objc_class->ivars, offset, left, S, info, true); outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars); if (p != nullptr) { if (left > sizeof(struct objc_ivar_list_t)) { outs() << "\n"; memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t)); } else { outs() << " (entends past the end of the section)\n"; memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t)); memcpy(&objc_ivar_list, p, left); } if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(objc_ivar_list); outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n"; ivar_list = p + sizeof(struct objc_ivar_list_t); for (i = 0; i < objc_ivar_list.ivar_count; i++) { if ((i + 1) * sizeof(struct objc_ivar_t) > left) { outs() << "\t\t remaining ivar's extend past the of the section\n"; break; } memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t), sizeof(struct objc_ivar_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(ivar); outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name); if (info->verbose) { name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true); if (name != nullptr) outs() << format(" %.*s", xleft, name); else outs() << " (not in an __OBJC section)"; } outs() << "\n"; outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type); if (info->verbose) { name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true); if (name != nullptr) outs() << format(" %.*s", xleft, name); else outs() << " (not in an __OBJC section)"; } outs() << "\n"; outs() << "\t\t ivar_offset " << format("0x%08" PRIx32, ivar.ivar_offset) << "\n"; } } else { outs() << " (not in an __OBJC section)\n"; } outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists); if (print_method_list(objc_class->methodLists, info)) outs() << " (not in an __OBJC section)\n"; outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache) << "\n"; outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols); if (print_protocol_list(objc_class->protocols, 16, info)) outs() << " (not in an __OBJC section)\n"; } static void print_objc_objc_category_t(struct objc_category_t *objc_category, struct DisassembleInfo *info) { uint32_t offset, left; const char *name; SectionRef S; outs() << "\t category name " << format("0x%08" PRIx32, objc_category->category_name); if (info->verbose) { name = get_pointer_32(objc_category->category_name, offset, left, S, info, true); if (name != nullptr) outs() << format(" %.*s", left, name); else outs() << " (not in an __OBJC section)"; } outs() << "\n"; outs() << "\t\t class name " << format("0x%08" PRIx32, objc_category->class_name); if (info->verbose) { name = get_pointer_32(objc_category->class_name, offset, left, S, info, true); if (name != nullptr) outs() << format(" %.*s", left, name); else outs() << " (not in an __OBJC section)"; } outs() << "\n"; outs() << "\t instance methods " << format("0x%08" PRIx32, objc_category->instance_methods); if (print_method_list(objc_category->instance_methods, info)) outs() << " (not in an __OBJC section)\n"; outs() << "\t class methods " << format("0x%08" PRIx32, objc_category->class_methods); if (print_method_list(objc_category->class_methods, info)) outs() << " (not in an __OBJC section)\n"; } static void print_category64_t(uint64_t p, struct DisassembleInfo *info) { struct category64_t c; const char *r; uint32_t offset, xoffset, left; SectionRef S, xS; const char *name, *sym_name; uint64_t n_value; r = get_pointer_64(p, offset, left, S, info); if (r == nullptr) return; memset(&c, '\0', sizeof(struct category64_t)); if (left < sizeof(struct category64_t)) { memcpy(&c, r, left); outs() << " (category_t entends past the end of the section)\n"; } else memcpy(&c, r, sizeof(struct category64_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(c); outs() << " name "; sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S, info, n_value, c.name); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (c.name != 0) outs() << " + " << format("0x%" PRIx64, c.name); } else outs() << format("0x%" PRIx64, c.name); name = get_pointer_64(c.name + n_value, xoffset, left, xS, info); if (name != nullptr) outs() << format(" %.*s", left, name); outs() << "\n"; outs() << " cls "; sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info, n_value, c.cls); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (c.cls != 0) outs() << " + " << format("0x%" PRIx64, c.cls); } else outs() << format("0x%" PRIx64, c.cls); outs() << "\n"; if (c.cls + n_value != 0) print_class64_t(c.cls + n_value, info); outs() << " instanceMethods "; sym_name = get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S, info, n_value, c.instanceMethods); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (c.instanceMethods != 0) outs() << " + " << format("0x%" PRIx64, c.instanceMethods); } else outs() << format("0x%" PRIx64, c.instanceMethods); outs() << "\n"; if (c.instanceMethods + n_value != 0) print_method_list64_t(c.instanceMethods + n_value, info, ""); outs() << " classMethods "; sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods), S, info, n_value, c.classMethods); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (c.classMethods != 0) outs() << " + " << format("0x%" PRIx64, c.classMethods); } else outs() << format("0x%" PRIx64, c.classMethods); outs() << "\n"; if (c.classMethods + n_value != 0) print_method_list64_t(c.classMethods + n_value, info, ""); outs() << " protocols "; sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S, info, n_value, c.protocols); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (c.protocols != 0) outs() << " + " << format("0x%" PRIx64, c.protocols); } else outs() << format("0x%" PRIx64, c.protocols); outs() << "\n"; if (c.protocols + n_value != 0) print_protocol_list64_t(c.protocols + n_value, info); outs() << "instanceProperties "; sym_name = get_symbol_64(offset + offsetof(struct category64_t, instanceProperties), S, info, n_value, c.instanceProperties); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (c.instanceProperties != 0) outs() << " + " << format("0x%" PRIx64, c.instanceProperties); } else outs() << format("0x%" PRIx64, c.instanceProperties); outs() << "\n"; if (c.instanceProperties + n_value != 0) print_objc_property_list64(c.instanceProperties + n_value, info); } static void print_category32_t(uint32_t p, struct DisassembleInfo *info) { struct category32_t c; const char *r; uint32_t offset, left; SectionRef S, xS; const char *name; r = get_pointer_32(p, offset, left, S, info); if (r == nullptr) return; memset(&c, '\0', sizeof(struct category32_t)); if (left < sizeof(struct category32_t)) { memcpy(&c, r, left); outs() << " (category_t entends past the end of the section)\n"; } else memcpy(&c, r, sizeof(struct category32_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(c); outs() << " name " << format("0x%" PRIx32, c.name); name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info, c.name); if (name != NULL) outs() << " " << name; outs() << "\n"; outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n"; if (c.cls != 0) print_class32_t(c.cls, info); outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods) << "\n"; if (c.instanceMethods != 0) print_method_list32_t(c.instanceMethods, info, ""); outs() << " classMethods " << format("0x%" PRIx32, c.classMethods) << "\n"; if (c.classMethods != 0) print_method_list32_t(c.classMethods, info, ""); outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n"; if (c.protocols != 0) print_protocol_list32_t(c.protocols, info); outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties) << "\n"; if (c.instanceProperties != 0) print_objc_property_list32(c.instanceProperties, info); } static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) { uint32_t i, left, offset, xoffset; uint64_t p, n_value; struct message_ref64 mr; const char *name, *sym_name; const char *r; SectionRef xS; if (S == SectionRef()) return; StringRef SectName; S.getName(SectName); DataRefImpl Ref = S.getRawDataRefImpl(); StringRef SegName = info->O->getSectionFinalSegmentName(Ref); outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; offset = 0; for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) { p = S.getAddress() + i; r = get_pointer_64(p, offset, left, S, info); if (r == nullptr) return; memset(&mr, '\0', sizeof(struct message_ref64)); if (left < sizeof(struct message_ref64)) { memcpy(&mr, r, left); outs() << " (message_ref entends past the end of the section)\n"; } else memcpy(&mr, r, sizeof(struct message_ref64)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(mr); outs() << " imp "; name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info, n_value, mr.imp); if (n_value != 0) { outs() << format("0x%" PRIx64, n_value) << " "; if (mr.imp != 0) outs() << "+ " << format("0x%" PRIx64, mr.imp) << " "; } else outs() << format("0x%" PRIx64, mr.imp) << " "; if (name != nullptr) outs() << " " << name; outs() << "\n"; outs() << " sel "; sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S, info, n_value, mr.sel); if (n_value != 0) { if (info->verbose && sym_name != nullptr) outs() << sym_name; else outs() << format("0x%" PRIx64, n_value); if (mr.sel != 0) outs() << " + " << format("0x%" PRIx64, mr.sel); } else outs() << format("0x%" PRIx64, mr.sel); name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info); if (name != nullptr) outs() << format(" %.*s", left, name); outs() << "\n"; offset += sizeof(struct message_ref64); } } static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) { uint32_t i, left, offset, xoffset, p; struct message_ref32 mr; const char *name, *r; SectionRef xS; if (S == SectionRef()) return; StringRef SectName; S.getName(SectName); DataRefImpl Ref = S.getRawDataRefImpl(); StringRef SegName = info->O->getSectionFinalSegmentName(Ref); outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; offset = 0; for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) { p = S.getAddress() + i; r = get_pointer_32(p, offset, left, S, info); if (r == nullptr) return; memset(&mr, '\0', sizeof(struct message_ref32)); if (left < sizeof(struct message_ref32)) { memcpy(&mr, r, left); outs() << " (message_ref entends past the end of the section)\n"; } else memcpy(&mr, r, sizeof(struct message_ref32)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(mr); outs() << " imp " << format("0x%" PRIx32, mr.imp); name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info, mr.imp); if (name != nullptr) outs() << " " << name; outs() << "\n"; outs() << " sel " << format("0x%" PRIx32, mr.sel); name = get_pointer_32(mr.sel, xoffset, left, xS, info); if (name != nullptr) outs() << " " << name; outs() << "\n"; offset += sizeof(struct message_ref32); } } static void print_image_info64(SectionRef S, struct DisassembleInfo *info) { uint32_t left, offset, swift_version; uint64_t p; struct objc_image_info64 o; const char *r; StringRef SectName; S.getName(SectName); DataRefImpl Ref = S.getRawDataRefImpl(); StringRef SegName = info->O->getSectionFinalSegmentName(Ref); outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; p = S.getAddress(); r = get_pointer_64(p, offset, left, S, info); if (r == nullptr) return; memset(&o, '\0', sizeof(struct objc_image_info64)); if (left < sizeof(struct objc_image_info64)) { memcpy(&o, r, left); outs() << " (objc_image_info entends past the end of the section)\n"; } else memcpy(&o, r, sizeof(struct objc_image_info64)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(o); outs() << " version " << o.version << "\n"; outs() << " flags " << format("0x%" PRIx32, o.flags); if (o.flags & OBJC_IMAGE_IS_REPLACEMENT) outs() << " OBJC_IMAGE_IS_REPLACEMENT"; if (o.flags & OBJC_IMAGE_SUPPORTS_GC) outs() << " OBJC_IMAGE_SUPPORTS_GC"; swift_version = (o.flags >> 8) & 0xff; if (swift_version != 0) { if (swift_version == 1) outs() << " Swift 1.0"; else if (swift_version == 2) outs() << " Swift 1.1"; else outs() << " unknown future Swift version (" << swift_version << ")"; } outs() << "\n"; } static void print_image_info32(SectionRef S, struct DisassembleInfo *info) { uint32_t left, offset, swift_version, p; struct objc_image_info32 o; const char *r; StringRef SectName; S.getName(SectName); DataRefImpl Ref = S.getRawDataRefImpl(); StringRef SegName = info->O->getSectionFinalSegmentName(Ref); outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; p = S.getAddress(); r = get_pointer_32(p, offset, left, S, info); if (r == nullptr) return; memset(&o, '\0', sizeof(struct objc_image_info32)); if (left < sizeof(struct objc_image_info32)) { memcpy(&o, r, left); outs() << " (objc_image_info entends past the end of the section)\n"; } else memcpy(&o, r, sizeof(struct objc_image_info32)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(o); outs() << " version " << o.version << "\n"; outs() << " flags " << format("0x%" PRIx32, o.flags); if (o.flags & OBJC_IMAGE_IS_REPLACEMENT) outs() << " OBJC_IMAGE_IS_REPLACEMENT"; if (o.flags & OBJC_IMAGE_SUPPORTS_GC) outs() << " OBJC_IMAGE_SUPPORTS_GC"; swift_version = (o.flags >> 8) & 0xff; if (swift_version != 0) { if (swift_version == 1) outs() << " Swift 1.0"; else if (swift_version == 2) outs() << " Swift 1.1"; else outs() << " unknown future Swift version (" << swift_version << ")"; } outs() << "\n"; } static void print_image_info(SectionRef S, struct DisassembleInfo *info) { uint32_t left, offset, p; struct imageInfo_t o; const char *r; StringRef SectName; S.getName(SectName); DataRefImpl Ref = S.getRawDataRefImpl(); StringRef SegName = info->O->getSectionFinalSegmentName(Ref); outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; p = S.getAddress(); r = get_pointer_32(p, offset, left, S, info); if (r == nullptr) return; memset(&o, '\0', sizeof(struct imageInfo_t)); if (left < sizeof(struct imageInfo_t)) { memcpy(&o, r, left); outs() << " (imageInfo entends past the end of the section)\n"; } else memcpy(&o, r, sizeof(struct imageInfo_t)); if (info->O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(o); outs() << " version " << o.version << "\n"; outs() << " flags " << format("0x%" PRIx32, o.flags); if (o.flags & 0x1) outs() << " F&C"; if (o.flags & 0x2) outs() << " GC"; if (o.flags & 0x4) outs() << " GC-only"; else outs() << " RR"; outs() << "\n"; } static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) { SymbolAddressMap AddrMap; if (verbose) CreateSymbolAddressMap(O, &AddrMap); std::vector<SectionRef> Sections; for (const SectionRef &Section : O->sections()) { StringRef SectName; Section.getName(SectName); Sections.push_back(Section); } struct DisassembleInfo info; // Set up the block of info used by the Symbolizer call backs. info.verbose = verbose; info.O = O; info.AddrMap = &AddrMap; info.Sections = &Sections; info.class_name = nullptr; info.selector_name = nullptr; info.method = nullptr; info.demangled_name = nullptr; info.bindtable = nullptr; info.adrp_addr = 0; info.adrp_inst = 0; const SectionRef CL = get_section(O, "__OBJC2", "__class_list"); if (CL != SectionRef()) { info.S = CL; walk_pointer_list_64("class", CL, O, &info, print_class64_t); } else { const SectionRef CL = get_section(O, "__DATA", "__objc_classlist"); info.S = CL; walk_pointer_list_64("class", CL, O, &info, print_class64_t); } const SectionRef CR = get_section(O, "__OBJC2", "__class_refs"); if (CR != SectionRef()) { info.S = CR; walk_pointer_list_64("class refs", CR, O, &info, nullptr); } else { const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs"); info.S = CR; walk_pointer_list_64("class refs", CR, O, &info, nullptr); } const SectionRef SR = get_section(O, "__OBJC2", "__super_refs"); if (SR != SectionRef()) { info.S = SR; walk_pointer_list_64("super refs", SR, O, &info, nullptr); } else { const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs"); info.S = SR; walk_pointer_list_64("super refs", SR, O, &info, nullptr); } const SectionRef CA = get_section(O, "__OBJC2", "__category_list"); if (CA != SectionRef()) { info.S = CA; walk_pointer_list_64("category", CA, O, &info, print_category64_t); } else { const SectionRef CA = get_section(O, "__DATA", "__objc_catlist"); info.S = CA; walk_pointer_list_64("category", CA, O, &info, print_category64_t); } const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list"); if (PL != SectionRef()) { info.S = PL; walk_pointer_list_64("protocol", PL, O, &info, nullptr); } else { const SectionRef PL = get_section(O, "__DATA", "__objc_protolist"); info.S = PL; walk_pointer_list_64("protocol", PL, O, &info, nullptr); } const SectionRef MR = get_section(O, "__OBJC2", "__message_refs"); if (MR != SectionRef()) { info.S = MR; print_message_refs64(MR, &info); } else { const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs"); info.S = MR; print_message_refs64(MR, &info); } const SectionRef II = get_section(O, "__OBJC2", "__image_info"); if (II != SectionRef()) { info.S = II; print_image_info64(II, &info); } else { const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo"); info.S = II; print_image_info64(II, &info); } if (info.bindtable != nullptr) delete info.bindtable; } static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) { SymbolAddressMap AddrMap; if (verbose) CreateSymbolAddressMap(O, &AddrMap); std::vector<SectionRef> Sections; for (const SectionRef &Section : O->sections()) { StringRef SectName; Section.getName(SectName); Sections.push_back(Section); } struct DisassembleInfo info; // Set up the block of info used by the Symbolizer call backs. info.verbose = verbose; info.O = O; info.AddrMap = &AddrMap; info.Sections = &Sections; info.class_name = nullptr; info.selector_name = nullptr; info.method = nullptr; info.demangled_name = nullptr; info.bindtable = nullptr; info.adrp_addr = 0; info.adrp_inst = 0; const SectionRef CL = get_section(O, "__OBJC2", "__class_list"); if (CL != SectionRef()) { info.S = CL; walk_pointer_list_32("class", CL, O, &info, print_class32_t); } else { const SectionRef CL = get_section(O, "__DATA", "__objc_classlist"); info.S = CL; walk_pointer_list_32("class", CL, O, &info, print_class32_t); } const SectionRef CR = get_section(O, "__OBJC2", "__class_refs"); if (CR != SectionRef()) { info.S = CR; walk_pointer_list_32("class refs", CR, O, &info, nullptr); } else { const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs"); info.S = CR; walk_pointer_list_32("class refs", CR, O, &info, nullptr); } const SectionRef SR = get_section(O, "__OBJC2", "__super_refs"); if (SR != SectionRef()) { info.S = SR; walk_pointer_list_32("super refs", SR, O, &info, nullptr); } else { const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs"); info.S = SR; walk_pointer_list_32("super refs", SR, O, &info, nullptr); } const SectionRef CA = get_section(O, "__OBJC2", "__category_list"); if (CA != SectionRef()) { info.S = CA; walk_pointer_list_32("category", CA, O, &info, print_category32_t); } else { const SectionRef CA = get_section(O, "__DATA", "__objc_catlist"); info.S = CA; walk_pointer_list_32("category", CA, O, &info, print_category32_t); } const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list"); if (PL != SectionRef()) { info.S = PL; walk_pointer_list_32("protocol", PL, O, &info, nullptr); } else { const SectionRef PL = get_section(O, "__DATA", "__objc_protolist"); info.S = PL; walk_pointer_list_32("protocol", PL, O, &info, nullptr); } const SectionRef MR = get_section(O, "__OBJC2", "__message_refs"); if (MR != SectionRef()) { info.S = MR; print_message_refs32(MR, &info); } else { const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs"); info.S = MR; print_message_refs32(MR, &info); } const SectionRef II = get_section(O, "__OBJC2", "__image_info"); if (II != SectionRef()) { info.S = II; print_image_info32(II, &info); } else { const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo"); info.S = II; print_image_info32(II, &info); } } static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) { uint32_t i, j, p, offset, xoffset, left, defs_left, def; const char *r, *name, *defs; struct objc_module_t mod; SectionRef S, xS; struct objc_symtab_t symtab; struct objc_class_t objc_class; struct objc_category_t objc_category; outs() << "Objective-C segment\n"; S = get_section(O, "__OBJC", "__module_info"); if (S == SectionRef()) return false; SymbolAddressMap AddrMap; if (verbose) CreateSymbolAddressMap(O, &AddrMap); std::vector<SectionRef> Sections; for (const SectionRef &Section : O->sections()) { StringRef SectName; Section.getName(SectName); Sections.push_back(Section); } struct DisassembleInfo info; // Set up the block of info used by the Symbolizer call backs. info.verbose = verbose; info.O = O; info.AddrMap = &AddrMap; info.Sections = &Sections; info.class_name = nullptr; info.selector_name = nullptr; info.method = nullptr; info.demangled_name = nullptr; info.bindtable = nullptr; info.adrp_addr = 0; info.adrp_inst = 0; for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) { p = S.getAddress() + i; r = get_pointer_32(p, offset, left, S, &info, true); if (r == nullptr) return true; memset(&mod, '\0', sizeof(struct objc_module_t)); if (left < sizeof(struct objc_module_t)) { memcpy(&mod, r, left); outs() << " (module extends past end of __module_info section)\n"; } else memcpy(&mod, r, sizeof(struct objc_module_t)); if (O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(mod); outs() << "Module " << format("0x%" PRIx32, p) << "\n"; outs() << " version " << mod.version << "\n"; outs() << " size " << mod.size << "\n"; outs() << " name "; name = get_pointer_32(mod.name, xoffset, left, xS, &info, true); if (name != nullptr) outs() << format("%.*s", left, name); else outs() << format("0x%08" PRIx32, mod.name) << "(not in an __OBJC section)"; outs() << "\n"; r = get_pointer_32(mod.symtab, xoffset, left, xS, &info, true); if (mod.symtab == 0 || r == nullptr) { outs() << " symtab " << format("0x%08" PRIx32, mod.symtab) << " (not in an __OBJC section)\n"; continue; } outs() << " symtab " << format("0x%08" PRIx32, mod.symtab) << "\n"; memset(&symtab, '\0', sizeof(struct objc_symtab_t)); defs_left = 0; defs = nullptr; if (left < sizeof(struct objc_symtab_t)) { memcpy(&symtab, r, left); outs() << "\tsymtab extends past end of an __OBJC section)\n"; } else { memcpy(&symtab, r, sizeof(struct objc_symtab_t)); if (left > sizeof(struct objc_symtab_t)) { defs_left = left - sizeof(struct objc_symtab_t); defs = r + sizeof(struct objc_symtab_t); } } if (O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(symtab); outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n"; r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true); outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs); if (r == nullptr) outs() << " (not in an __OBJC section)"; outs() << "\n"; outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n"; outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n"; if (symtab.cls_def_cnt > 0) outs() << "\tClass Definitions\n"; for (j = 0; j < symtab.cls_def_cnt; j++) { if ((j + 1) * sizeof(uint32_t) > defs_left) { outs() << "\t(remaining class defs entries entends past the end of the " << "section)\n"; break; } memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t)); if (O->isLittleEndian() != sys::IsLittleEndianHost) sys::swapByteOrder(def); r = get_pointer_32(def, xoffset, left, xS, &info, true); outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def); if (r != nullptr) { if (left > sizeof(struct objc_class_t)) { outs() << "\n"; memcpy(&objc_class, r, sizeof(struct objc_class_t)); } else { outs() << " (entends past the end of the section)\n"; memset(&objc_class, '\0', sizeof(struct objc_class_t)); memcpy(&objc_class, r, left); } if (O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(objc_class); print_objc_class_t(&objc_class, &info); } else { outs() << "(not in an __OBJC section)\n"; } if (CLS_GETINFO(&objc_class, CLS_CLASS)) { outs() << "\tMeta Class"; r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true); if (r != nullptr) { if (left > sizeof(struct objc_class_t)) { outs() << "\n"; memcpy(&objc_class, r, sizeof(struct objc_class_t)); } else { outs() << " (entends past the end of the section)\n"; memset(&objc_class, '\0', sizeof(struct objc_class_t)); memcpy(&objc_class, r, left); } if (O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(objc_class); print_objc_class_t(&objc_class, &info); } else { outs() << "(not in an __OBJC section)\n"; } } } if (symtab.cat_def_cnt > 0) outs() << "\tCategory Definitions\n"; for (j = 0; j < symtab.cat_def_cnt; j++) { if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) { outs() << "\t(remaining category defs entries entends past the end of " << "the section)\n"; break; } memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t), sizeof(uint32_t)); if (O->isLittleEndian() != sys::IsLittleEndianHost) sys::swapByteOrder(def); r = get_pointer_32(def, xoffset, left, xS, &info, true); outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] " << format("0x%08" PRIx32, def); if (r != nullptr) { if (left > sizeof(struct objc_category_t)) { outs() << "\n"; memcpy(&objc_category, r, sizeof(struct objc_category_t)); } else { outs() << " (entends past the end of the section)\n"; memset(&objc_category, '\0', sizeof(struct objc_category_t)); memcpy(&objc_category, r, left); } if (O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(objc_category); print_objc_objc_category_t(&objc_category, &info); } else { outs() << "(not in an __OBJC section)\n"; } } } const SectionRef II = get_section(O, "__OBJC", "__image_info"); if (II != SectionRef()) print_image_info(II, &info); return true; } static void DumpProtocolSection(MachOObjectFile *O, const char *sect, uint32_t size, uint32_t addr) { SymbolAddressMap AddrMap; CreateSymbolAddressMap(O, &AddrMap); std::vector<SectionRef> Sections; for (const SectionRef &Section : O->sections()) { StringRef SectName; Section.getName(SectName); Sections.push_back(Section); } struct DisassembleInfo info; // Set up the block of info used by the Symbolizer call backs. info.verbose = true; info.O = O; info.AddrMap = &AddrMap; info.Sections = &Sections; info.class_name = nullptr; info.selector_name = nullptr; info.method = nullptr; info.demangled_name = nullptr; info.bindtable = nullptr; info.adrp_addr = 0; info.adrp_inst = 0; const char *p; struct objc_protocol_t protocol; uint32_t left, paddr; for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) { memset(&protocol, '\0', sizeof(struct objc_protocol_t)); left = size - (p - sect); if (left < sizeof(struct objc_protocol_t)) { outs() << "Protocol extends past end of __protocol section\n"; memcpy(&protocol, p, left); } else memcpy(&protocol, p, sizeof(struct objc_protocol_t)); if (O->isLittleEndian() != sys::IsLittleEndianHost) swapStruct(protocol); paddr = addr + (p - sect); outs() << "Protocol " << format("0x%" PRIx32, paddr); if (print_protocol(paddr, 0, &info)) outs() << "(not in an __OBJC section)\n"; } } static void printObjcMetaData(MachOObjectFile *O, bool verbose) { if (O->is64Bit()) printObjc2_64bit_MetaData(O, verbose); else { MachO::mach_header H; H = O->getHeader(); if (H.cputype == MachO::CPU_TYPE_ARM) printObjc2_32bit_MetaData(O, verbose); else { // This is the 32-bit non-arm cputype case. Which is normally // the first Objective-C ABI. But it may be the case of a // binary for the iOS simulator which is the second Objective-C // ABI. In that case printObjc1_32bit_MetaData() will determine that // and return false. if (printObjc1_32bit_MetaData(O, verbose) == false) printObjc2_32bit_MetaData(O, verbose); } } } // GuessLiteralPointer returns a string which for the item in the Mach-O file // for the address passed in as ReferenceValue for printing as a comment with // the instruction and also returns the corresponding type of that item // indirectly through ReferenceType. // // If ReferenceValue is an address of literal cstring then a pointer to the // cstring is returned and ReferenceType is set to // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr . // // If ReferenceValue is an address of an Objective-C CFString, Selector ref or // Class ref that name is returned and the ReferenceType is set accordingly. // // Lastly, literals which are Symbol address in a literal pool are looked for // and if found the symbol name is returned and ReferenceType is set to // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr . // // If there is no item in the Mach-O file for the address passed in as // ReferenceValue nullptr is returned and ReferenceType is unchanged. static const char *GuessLiteralPointer(uint64_t ReferenceValue, uint64_t ReferencePC, uint64_t *ReferenceType, struct DisassembleInfo *info) { // First see if there is an external relocation entry at the ReferencePC. uint64_t sect_addr = info->S.getAddress(); uint64_t sect_offset = ReferencePC - sect_addr; bool reloc_found = false; DataRefImpl Rel; MachO::any_relocation_info RE; bool isExtern = false; SymbolRef Symbol; for (const RelocationRef &Reloc : info->S.relocations()) { uint64_t RelocOffset = Reloc.getOffset(); if (RelocOffset == sect_offset) { Rel = Reloc.getRawDataRefImpl(); RE = info->O->getRelocation(Rel); if (info->O->isRelocationScattered(RE)) continue; isExtern = info->O->getPlainRelocationExternal(RE); if (isExtern) { symbol_iterator RelocSym = Reloc.getSymbol(); Symbol = *RelocSym; } reloc_found = true; break; } } // If there is an external relocation entry for a symbol in a section // then used that symbol's value for the value of the reference. if (reloc_found && isExtern) { if (info->O->getAnyRelocationPCRel(RE)) { unsigned Type = info->O->getAnyRelocationType(RE); if (Type == MachO::X86_64_RELOC_SIGNED) { ReferenceValue = Symbol.getValue(); } } } // Look for literals such as Objective-C CFStrings refs, Selector refs, // Message refs and Class refs. bool classref, selref, msgref, cfstring; uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref, selref, msgref, cfstring); if (classref && pointer_value == 0) { // Note the ReferenceValue is a pointer into the __objc_classrefs section. // And the pointer_value in that section is typically zero as it will be // set by dyld as part of the "bind information". const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info); if (name != nullptr) { *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref; const char *class_name = strrchr(name, '$'); if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0') { info->class_name = class_name + 2; return name; } } } if (classref) { *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref; const char *name = get_objc2_64bit_class_name(pointer_value, ReferenceValue, info); if (name != nullptr) info->class_name = name; else name = "bad class ref"; return name; } if (cfstring) { *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref; const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info); return name; } if (selref && pointer_value == 0) pointer_value = get_objc2_64bit_selref(ReferenceValue, info); if (pointer_value != 0) ReferenceValue = pointer_value; const char *name = GuessCstringPointer(ReferenceValue, info); if (name) { if (pointer_value != 0 && selref) { *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref; info->selector_name = name; } else if (pointer_value != 0 && msgref) { info->class_name = nullptr; *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref; info->selector_name = name; } else *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr; return name; } // Lastly look for an indirect symbol with this ReferenceValue which is in // a literal pool. If found return that symbol name. name = GuessIndirectSymbol(ReferenceValue, info); if (name) { *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr; return name; } return nullptr; } // SymbolizerSymbolLookUp is the symbol lookup function passed when creating // the Symbolizer. It looks up the ReferenceValue using the info passed via the // pointer to the struct DisassembleInfo that was passed when MCSymbolizer // is created and returns the symbol name that matches the ReferenceValue or // nullptr if none. The ReferenceType is passed in for the IN type of // reference the instruction is making from the values in defined in the header // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific // Out type and the ReferenceName will also be set which is added as a comment // to the disassembled instruction. // #if HAVE_CXXABI_H // If the symbol name is a C++ mangled name then the demangled name is // returned through ReferenceName and ReferenceType is set to // LLVMDisassembler_ReferenceType_DeMangled_Name . #endif // // When this is called to get a symbol name for a branch target then the // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then // SymbolValue will be looked for in the indirect symbol table to determine if // it is an address for a symbol stub. If so then the symbol name for that // stub is returned indirectly through ReferenceName and then ReferenceType is // set to LLVMDisassembler_ReferenceType_Out_SymbolStub. // // When this is called with an value loaded via a PC relative load then // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the // SymbolValue is checked to be an address of literal pointer, symbol pointer, // or an Objective-C meta data reference. If so the output ReferenceType is // set to correspond to that as well as setting the ReferenceName. static const char *SymbolizerSymbolLookUp(void *DisInfo, uint64_t ReferenceValue, uint64_t *ReferenceType, uint64_t ReferencePC, const char **ReferenceName) { struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo; // If no verbose symbolic information is wanted then just return nullptr. if (!info->verbose) { *ReferenceName = nullptr; *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; return nullptr; } const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap); if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) { *ReferenceName = GuessIndirectSymbol(ReferenceValue, info); if (*ReferenceName != nullptr) { method_reference(info, ReferenceType, ReferenceName); if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message) *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub; } else #if HAVE_CXXABI_H if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) { if (info->demangled_name != nullptr) free(info->demangled_name); int status; info->demangled_name = abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status); if (info->demangled_name != nullptr) { *ReferenceName = info->demangled_name; *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name; } else *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; } else #endif *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) { *ReferenceName = GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); if (*ReferenceName) method_reference(info, ReferenceType, ReferenceName); else *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; // If this is arm64 and the reference is an adrp instruction save the // instruction, passed in ReferenceValue and the address of the instruction // for use later if we see and add immediate instruction. } else if (info->O->getArch() == Triple::aarch64 && *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) { info->adrp_inst = ReferenceValue; info->adrp_addr = ReferencePC; SymbolName = nullptr; *ReferenceName = nullptr; *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; // If this is arm64 and reference is an add immediate instruction and we // have // seen an adrp instruction just before it and the adrp's Xd register // matches // this add's Xn register reconstruct the value being referenced and look to // see if it is a literal pointer. Note the add immediate instruction is // passed in ReferenceValue. } else if (info->O->getArch() == Triple::aarch64 && *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri && ReferencePC - 4 == info->adrp_addr && (info->adrp_inst & 0x9f000000) == 0x90000000 && (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) { uint32_t addxri_inst; uint64_t adrp_imm, addxri_imm; adrp_imm = ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3); if (info->adrp_inst & 0x0200000) adrp_imm |= 0xfffffffffc000000LL; addxri_inst = ReferenceValue; addxri_imm = (addxri_inst >> 10) & 0xfff; if (((addxri_inst >> 22) & 0x3) == 1) addxri_imm <<= 12; ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) + (adrp_imm << 12) + addxri_imm; *ReferenceName = GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); if (*ReferenceName == nullptr) *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; // If this is arm64 and the reference is a load register instruction and we // have seen an adrp instruction just before it and the adrp's Xd register // matches this add's Xn register reconstruct the value being referenced and // look to see if it is a literal pointer. Note the load register // instruction is passed in ReferenceValue. } else if (info->O->getArch() == Triple::aarch64 && *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui && ReferencePC - 4 == info->adrp_addr && (info->adrp_inst & 0x9f000000) == 0x90000000 && (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) { uint32_t ldrxui_inst; uint64_t adrp_imm, ldrxui_imm; adrp_imm = ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3); if (info->adrp_inst & 0x0200000) adrp_imm |= 0xfffffffffc000000LL; ldrxui_inst = ReferenceValue; ldrxui_imm = (ldrxui_inst >> 10) & 0xfff; ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) + (adrp_imm << 12) + (ldrxui_imm << 3); *ReferenceName = GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); if (*ReferenceName == nullptr) *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; } // If this arm64 and is an load register (PC-relative) instruction the // ReferenceValue is the PC plus the immediate value. else if (info->O->getArch() == Triple::aarch64 && (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl || *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) { *ReferenceName = GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); if (*ReferenceName == nullptr) *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; } #if HAVE_CXXABI_H else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) { if (info->demangled_name != nullptr) free(info->demangled_name); int status; info->demangled_name = abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status); if (info->demangled_name != nullptr) { *ReferenceName = info->demangled_name; *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name; } } #endif else { *ReferenceName = nullptr; *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; } return SymbolName; } /// \brief Emits the comments that are stored in the CommentStream. /// Each comment in the CommentStream must end with a newline. static void emitComments(raw_svector_ostream &CommentStream, SmallString<128> &CommentsToEmit, formatted_raw_ostream &FormattedOS, const MCAsmInfo &MAI) { // Flush the stream before taking its content. CommentStream.flush(); StringRef Comments = CommentsToEmit.str(); // Get the default information for printing a comment. const char *CommentBegin = MAI.getCommentString(); unsigned CommentColumn = MAI.getCommentColumn(); bool IsFirst = true; while (!Comments.empty()) { if (!IsFirst) FormattedOS << '\n'; // Emit a line of comments. FormattedOS.PadToColumn(CommentColumn); size_t Position = Comments.find('\n'); FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position); // Move after the newline character. Comments = Comments.substr(Position + 1); IsFirst = false; } FormattedOS.flush(); // Tell the comment stream that the vector changed underneath it. CommentsToEmit.clear(); CommentStream.resync(); } static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF, StringRef DisSegName, StringRef DisSectName) { const char *McpuDefault = nullptr; const Target *ThumbTarget = nullptr; const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget); if (!TheTarget) { // GetTarget prints out stuff. return; } if (MCPU.empty() && McpuDefault) MCPU = McpuDefault; std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo()); std::unique_ptr<const MCInstrInfo> ThumbInstrInfo; if (ThumbTarget) ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo()); // Package up features to be passed to target/subtarget std::string FeaturesStr; if (MAttrs.size()) { SubtargetFeatures Features; for (unsigned i = 0; i != MAttrs.size(); ++i) Features.AddFeature(MAttrs[i]); FeaturesStr = Features.getString(); } // Set up disassembler. std::unique_ptr<const MCRegisterInfo> MRI( TheTarget->createMCRegInfo(TripleName)); std::unique_ptr<const MCAsmInfo> AsmInfo( TheTarget->createMCAsmInfo(*MRI, TripleName)); std::unique_ptr<const MCSubtargetInfo> STI( TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr)); MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr); std::unique_ptr<MCDisassembler> DisAsm( TheTarget->createMCDisassembler(*STI, Ctx)); std::unique_ptr<MCSymbolizer> Symbolizer; struct DisassembleInfo SymbolizerInfo; std::unique_ptr<MCRelocationInfo> RelInfo( TheTarget->createMCRelocationInfo(TripleName, Ctx)); if (RelInfo) { Symbolizer.reset(TheTarget->createMCSymbolizer( TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp, &SymbolizerInfo, &Ctx, std::move(RelInfo))); DisAsm->setSymbolizer(std::move(Symbolizer)); } int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI)); // Set the display preference for hex vs. decimal immediates. IP->setPrintImmHex(PrintImmHex); // Comment stream and backing vector. SmallString<128> CommentsToEmit; raw_svector_ostream CommentStream(CommentsToEmit); // FIXME: Setting the CommentStream in the InstPrinter is problematic in that // if it is done then arm64 comments for string literals don't get printed // and some constant get printed instead and not setting it causes intel // (32-bit and 64-bit) comments printed with different spacing before the // comment causing different diffs with the 'C' disassembler library API. // IP->setCommentStream(CommentStream); if (!AsmInfo || !STI || !DisAsm || !IP) { errs() << "error: couldn't initialize disassembler for target " << TripleName << '\n'; return; } // Set up thumb disassembler. std::unique_ptr<const MCRegisterInfo> ThumbMRI; std::unique_ptr<const MCAsmInfo> ThumbAsmInfo; std::unique_ptr<const MCSubtargetInfo> ThumbSTI; std::unique_ptr<MCDisassembler> ThumbDisAsm; std::unique_ptr<MCInstPrinter> ThumbIP; std::unique_ptr<MCContext> ThumbCtx; std::unique_ptr<MCSymbolizer> ThumbSymbolizer; struct DisassembleInfo ThumbSymbolizerInfo; std::unique_ptr<MCRelocationInfo> ThumbRelInfo; if (ThumbTarget) { ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName)); ThumbAsmInfo.reset( ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName)); ThumbSTI.reset( ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr)); ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr)); ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx)); MCContext *PtrThumbCtx = ThumbCtx.get(); ThumbRelInfo.reset( ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx)); if (ThumbRelInfo) { ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer( ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp, &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo))); ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer)); } int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect(); ThumbIP.reset(ThumbTarget->createMCInstPrinter( Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI)); // Set the display preference for hex vs. decimal immediates. ThumbIP->setPrintImmHex(PrintImmHex); } if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) { errs() << "error: couldn't initialize disassembler for target " << ThumbTripleName << '\n'; return; } MachO::mach_header Header = MachOOF->getHeader(); // FIXME: Using the -cfg command line option, this code used to be able to // annotate relocations with the referenced symbol's name, and if this was // inside a __[cf]string section, the data it points to. This is now replaced // by the upcoming MCSymbolizer, which needs the appropriate setup done above. std::vector<SectionRef> Sections; std::vector<SymbolRef> Symbols; SmallVector<uint64_t, 8> FoundFns; uint64_t BaseSegmentAddress; getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns, BaseSegmentAddress); // Sort the symbols by address, just in case they didn't come in that way. std::sort(Symbols.begin(), Symbols.end(), SymbolSorter()); // Build a data in code table that is sorted on by the address of each entry. uint64_t BaseAddress = 0; if (Header.filetype == MachO::MH_OBJECT) BaseAddress = Sections[0].getAddress(); else BaseAddress = BaseSegmentAddress; DiceTable Dices; for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices(); DI != DE; ++DI) { uint32_t Offset; DI->getOffset(Offset); Dices.push_back(std::make_pair(BaseAddress + Offset, *DI)); } array_pod_sort(Dices.begin(), Dices.end()); #ifndef NDEBUG raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls(); #else raw_ostream &DebugOut = nulls(); #endif std::unique_ptr<DIContext> diContext; ObjectFile *DbgObj = MachOOF; // Try to find debug info and set up the DIContext for it. if (UseDbg) { // A separate DSym file path was specified, parse it as a macho file, // get the sections and supply it to the section name parsing machinery. if (!DSYMFile.empty()) { ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = MemoryBuffer::getFileOrSTDIN(DSYMFile); if (std::error_code EC = BufOrErr.getError()) { errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n'; return; } DbgObj = ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef()) .get() .release(); } // Setup the DIContext diContext.reset(new DWARFContextInMemory(*DbgObj)); } if (DumpSections.size() == 0) outs() << "(" << DisSegName << "," << DisSectName << ") section\n"; for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) { StringRef SectName; if (Sections[SectIdx].getName(SectName) || SectName != DisSectName) continue; DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl(); StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR); if (SegmentName != DisSegName) continue; StringRef BytesStr; Sections[SectIdx].getContents(BytesStr); ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()), BytesStr.size()); uint64_t SectAddress = Sections[SectIdx].getAddress(); bool symbolTableWorked = false; // Parse relocations. std::vector<std::pair<uint64_t, SymbolRef>> Relocs; for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) { uint64_t RelocOffset = Reloc.getOffset(); uint64_t SectionAddress = Sections[SectIdx].getAddress(); RelocOffset -= SectionAddress; symbol_iterator RelocSym = Reloc.getSymbol(); Relocs.push_back(std::make_pair(RelocOffset, *RelocSym)); } array_pod_sort(Relocs.begin(), Relocs.end()); // Create a map of symbol addresses to symbol names for use by // the SymbolizerSymbolLookUp() routine. SymbolAddressMap AddrMap; bool DisSymNameFound = false; for (const SymbolRef &Symbol : MachOOF->symbols()) { SymbolRef::Type ST = Symbol.getType(); if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data || ST == SymbolRef::ST_Other) { uint64_t Address = Symbol.getValue(); ErrorOr<StringRef> SymNameOrErr = Symbol.getName(); if (std::error_code EC = SymNameOrErr.getError()) report_fatal_error(EC.message()); StringRef SymName = *SymNameOrErr; AddrMap[Address] = SymName; if (!DisSymName.empty() && DisSymName == SymName) DisSymNameFound = true; } } if (!DisSymName.empty() && !DisSymNameFound) { outs() << "Can't find -dis-symname: " << DisSymName << "\n"; return; } // Set up the block of info used by the Symbolizer call backs. SymbolizerInfo.verbose = !NoSymbolicOperands; SymbolizerInfo.O = MachOOF; SymbolizerInfo.S = Sections[SectIdx]; SymbolizerInfo.AddrMap = &AddrMap; SymbolizerInfo.Sections = &Sections; SymbolizerInfo.class_name = nullptr; SymbolizerInfo.selector_name = nullptr; SymbolizerInfo.method = nullptr; SymbolizerInfo.demangled_name = nullptr; SymbolizerInfo.bindtable = nullptr; SymbolizerInfo.adrp_addr = 0; SymbolizerInfo.adrp_inst = 0; // Same for the ThumbSymbolizer ThumbSymbolizerInfo.verbose = !NoSymbolicOperands; ThumbSymbolizerInfo.O = MachOOF; ThumbSymbolizerInfo.S = Sections[SectIdx]; ThumbSymbolizerInfo.AddrMap = &AddrMap; ThumbSymbolizerInfo.Sections = &Sections; ThumbSymbolizerInfo.class_name = nullptr; ThumbSymbolizerInfo.selector_name = nullptr; ThumbSymbolizerInfo.method = nullptr; ThumbSymbolizerInfo.demangled_name = nullptr; ThumbSymbolizerInfo.bindtable = nullptr; ThumbSymbolizerInfo.adrp_addr = 0; ThumbSymbolizerInfo.adrp_inst = 0; // Disassemble symbol by symbol. for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) { ErrorOr<StringRef> SymNameOrErr = Symbols[SymIdx].getName(); if (std::error_code EC = SymNameOrErr.getError()) report_fatal_error(EC.message()); StringRef SymName = *SymNameOrErr; SymbolRef::Type ST = Symbols[SymIdx].getType(); if (ST != SymbolRef::ST_Function) continue; // Make sure the symbol is defined in this section. bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]); if (!containsSym) continue; // If we are only disassembling one symbol see if this is that symbol. if (!DisSymName.empty() && DisSymName != SymName) continue; // Start at the address of the symbol relative to the section's address. uint64_t Start = Symbols[SymIdx].getValue(); uint64_t SectionAddress = Sections[SectIdx].getAddress(); Start -= SectionAddress; // Stop disassembling either at the beginning of the next symbol or at // the end of the section. bool containsNextSym = false; uint64_t NextSym = 0; uint64_t NextSymIdx = SymIdx + 1; while (Symbols.size() > NextSymIdx) { SymbolRef::Type NextSymType = Symbols[NextSymIdx].getType(); if (NextSymType == SymbolRef::ST_Function) { containsNextSym = Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]); NextSym = Symbols[NextSymIdx].getValue(); NextSym -= SectionAddress; break; } ++NextSymIdx; } uint64_t SectSize = Sections[SectIdx].getSize(); uint64_t End = containsNextSym ? NextSym : SectSize; uint64_t Size; symbolTableWorked = true; DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl(); bool isThumb = (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget; outs() << SymName << ":\n"; DILineInfo lastLine; for (uint64_t Index = Start; Index < End; Index += Size) { MCInst Inst; uint64_t PC = SectAddress + Index; if (!NoLeadingAddr) { if (FullLeadingAddr) { if (MachOOF->is64Bit()) outs() << format("%016" PRIx64, PC); else outs() << format("%08" PRIx64, PC); } else { outs() << format("%8" PRIx64 ":", PC); } } if (!NoShowRawInsn) outs() << "\t"; // Check the data in code table here to see if this is data not an // instruction to be disassembled. DiceTable Dice; Dice.push_back(std::make_pair(PC, DiceRef())); dice_table_iterator DTI = std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(), compareDiceTableEntries); if (DTI != Dices.end()) { uint16_t Length; DTI->second.getLength(Length); uint16_t Kind; DTI->second.getKind(Kind); Size = DumpDataInCode(Bytes.data() + Index, Length, Kind); if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) && (PC == (DTI->first + Length - 1)) && (Length & 1)) Size++; continue; } SmallVector<char, 64> AnnotationsBytes; raw_svector_ostream Annotations(AnnotationsBytes); bool gotInst; if (isThumb) gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC, DebugOut, Annotations); else gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC, DebugOut, Annotations); if (gotInst) { if (!NoShowRawInsn) { dumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, Size), outs()); } formatted_raw_ostream FormattedOS(outs()); Annotations.flush(); StringRef AnnotationsStr = Annotations.str(); if (isThumb) ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI); else IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI); emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo); // Print debug info. if (diContext) { DILineInfo dli = diContext->getLineInfoForAddress(PC); // Print valid line info if it changed. if (dli != lastLine && dli.Line != 0) outs() << "\t## " << dli.FileName << ':' << dli.Line << ':' << dli.Column; lastLine = dli; } outs() << "\n"; } else { unsigned int Arch = MachOOF->getArch(); if (Arch == Triple::x86_64 || Arch == Triple::x86) { outs() << format("\t.byte 0x%02x #bad opcode\n", *(Bytes.data() + Index) & 0xff); Size = 1; // skip exactly one illegible byte and move on. } else if (Arch == Triple::aarch64) { uint32_t opcode = (*(Bytes.data() + Index) & 0xff) | (*(Bytes.data() + Index + 1) & 0xff) << 8 | (*(Bytes.data() + Index + 2) & 0xff) << 16 | (*(Bytes.data() + Index + 3) & 0xff) << 24; outs() << format("\t.long\t0x%08x\n", opcode); Size = 4; } else { errs() << "llvm-objdump: warning: invalid instruction encoding\n"; if (Size == 0) Size = 1; // skip illegible bytes } } } } if (!symbolTableWorked) { // Reading the symbol table didn't work, disassemble the whole section. uint64_t SectAddress = Sections[SectIdx].getAddress(); uint64_t SectSize = Sections[SectIdx].getSize(); uint64_t InstSize; for (uint64_t Index = 0; Index < SectSize; Index += InstSize) { MCInst Inst; uint64_t PC = SectAddress + Index; if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC, DebugOut, nulls())) { if (!NoLeadingAddr) { if (FullLeadingAddr) { if (MachOOF->is64Bit()) outs() << format("%016" PRIx64, PC); else outs() << format("%08" PRIx64, PC); } else { outs() << format("%8" PRIx64 ":", PC); } } if (!NoShowRawInsn) { outs() << "\t"; dumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, InstSize), outs()); } IP->printInst(&Inst, outs(), "", *STI); outs() << "\n"; } else { unsigned int Arch = MachOOF->getArch(); if (Arch == Triple::x86_64 || Arch == Triple::x86) { outs() << format("\t.byte 0x%02x #bad opcode\n", *(Bytes.data() + Index) & 0xff); InstSize = 1; // skip exactly one illegible byte and move on. } else { errs() << "llvm-objdump: warning: invalid instruction encoding\n"; if (InstSize == 0) InstSize = 1; // skip illegible bytes } } } } // The TripleName's need to be reset if we are called again for a different // archtecture. TripleName = ""; ThumbTripleName = ""; if (SymbolizerInfo.method != nullptr) free(SymbolizerInfo.method); if (SymbolizerInfo.demangled_name != nullptr) free(SymbolizerInfo.demangled_name); if (SymbolizerInfo.bindtable != nullptr) delete SymbolizerInfo.bindtable; if (ThumbSymbolizerInfo.method != nullptr) free(ThumbSymbolizerInfo.method); if (ThumbSymbolizerInfo.demangled_name != nullptr) free(ThumbSymbolizerInfo.demangled_name); if (ThumbSymbolizerInfo.bindtable != nullptr) delete ThumbSymbolizerInfo.bindtable; } } //===----------------------------------------------------------------------===// // __compact_unwind section dumping //===----------------------------------------------------------------------===// namespace { template <typename T> static uint64_t readNext(const char *&Buf) { using llvm::support::little; using llvm::support::unaligned; uint64_t Val = support::endian::read<T, little, unaligned>(Buf); Buf += sizeof(T); return Val; } struct CompactUnwindEntry { uint32_t OffsetInSection; uint64_t FunctionAddr; uint32_t Length; uint32_t CompactEncoding; uint64_t PersonalityAddr; uint64_t LSDAAddr; RelocationRef FunctionReloc; RelocationRef PersonalityReloc; RelocationRef LSDAReloc; CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64) : OffsetInSection(Offset) { if (Is64) read<uint64_t>(Contents.data() + Offset); else read<uint32_t>(Contents.data() + Offset); } private: template <typename UIntPtr> void read(const char *Buf) { FunctionAddr = readNext<UIntPtr>(Buf); Length = readNext<uint32_t>(Buf); CompactEncoding = readNext<uint32_t>(Buf); PersonalityAddr = readNext<UIntPtr>(Buf); LSDAAddr = readNext<UIntPtr>(Buf); } }; } /// Given a relocation from __compact_unwind, consisting of the RelocationRef /// and data being relocated, determine the best base Name and Addend to use for /// display purposes. /// /// 1. An Extern relocation will directly reference a symbol (and the data is /// then already an addend), so use that. /// 2. Otherwise the data is an offset in the object file's layout; try to find // a symbol before it in the same section, and use the offset from there. /// 3. Finally, if all that fails, fall back to an offset from the start of the /// referenced section. static void findUnwindRelocNameAddend(const MachOObjectFile *Obj, std::map<uint64_t, SymbolRef> &Symbols, const RelocationRef &Reloc, uint64_t Addr, StringRef &Name, uint64_t &Addend) { if (Reloc.getSymbol() != Obj->symbol_end()) { ErrorOr<StringRef> NameOrErr = Reloc.getSymbol()->getName(); if (std::error_code EC = NameOrErr.getError()) report_fatal_error(EC.message()); Name = *NameOrErr; Addend = Addr; return; } auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl()); SectionRef RelocSection = Obj->getAnyRelocationSection(RE); uint64_t SectionAddr = RelocSection.getAddress(); auto Sym = Symbols.upper_bound(Addr); if (Sym == Symbols.begin()) { // The first symbol in the object is after this reference, the best we can // do is section-relative notation. RelocSection.getName(Name); Addend = Addr - SectionAddr; return; } // Go back one so that SymbolAddress <= Addr. --Sym; section_iterator SymSection = Obj->section_end(); Sym->second.getSection(SymSection); if (RelocSection == *SymSection) { // There's a valid symbol in the same section before this reference. ErrorOr<StringRef> NameOrErr = Sym->second.getName(); if (std::error_code EC = NameOrErr.getError()) report_fatal_error(EC.message()); Name = *NameOrErr; Addend = Addr - Sym->first; return; } // There is a symbol before this reference, but it's in a different // section. Probably not helpful to mention it, so use the section name. RelocSection.getName(Name); Addend = Addr - SectionAddr; } static void printUnwindRelocDest(const MachOObjectFile *Obj, std::map<uint64_t, SymbolRef> &Symbols, const RelocationRef &Reloc, uint64_t Addr) { StringRef Name; uint64_t Addend; if (!Reloc.getObject()) return; findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend); outs() << Name; if (Addend) outs() << " + " << format("0x%" PRIx64, Addend); } static void printMachOCompactUnwindSection(const MachOObjectFile *Obj, std::map<uint64_t, SymbolRef> &Symbols, const SectionRef &CompactUnwind) { assert(Obj->isLittleEndian() && "There should not be a big-endian .o with __compact_unwind"); bool Is64 = Obj->is64Bit(); uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t); uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t); StringRef Contents; CompactUnwind.getContents(Contents); SmallVector<CompactUnwindEntry, 4> CompactUnwinds; // First populate the initial raw offsets, encodings and so on from the entry. for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) { CompactUnwindEntry Entry(Contents.data(), Offset, Is64); CompactUnwinds.push_back(Entry); } // Next we need to look at the relocations to find out what objects are // actually being referred to. for (const RelocationRef &Reloc : CompactUnwind.relocations()) { uint64_t RelocAddress = Reloc.getOffset(); uint32_t EntryIdx = RelocAddress / EntrySize; uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize; CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx]; if (OffsetInEntry == 0) Entry.FunctionReloc = Reloc; else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t)) Entry.PersonalityReloc = Reloc; else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t)) Entry.LSDAReloc = Reloc; else llvm_unreachable("Unexpected relocation in __compact_unwind section"); } // Finally, we're ready to print the data we've gathered. outs() << "Contents of __compact_unwind section:\n"; for (auto &Entry : CompactUnwinds) { outs() << " Entry at offset " << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n"; // 1. Start of the region this entry applies to. outs() << " start: " << format("0x%" PRIx64, Entry.FunctionAddr) << ' '; printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr); outs() << '\n'; // 2. Length of the region this entry applies to. outs() << " length: " << format("0x%" PRIx32, Entry.Length) << '\n'; // 3. The 32-bit compact encoding. outs() << " compact encoding: " << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n'; // 4. The personality function, if present. if (Entry.PersonalityReloc.getObject()) { outs() << " personality function: " << format("0x%" PRIx64, Entry.PersonalityAddr) << ' '; printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc, Entry.PersonalityAddr); outs() << '\n'; } // 5. This entry's language-specific data area. if (Entry.LSDAReloc.getObject()) { outs() << " LSDA: " << format("0x%" PRIx64, Entry.LSDAAddr) << ' '; printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr); outs() << '\n'; } } } //===----------------------------------------------------------------------===// // __unwind_info section dumping //===----------------------------------------------------------------------===// static void printRegularSecondLevelUnwindPage(const char *PageStart) { const char *Pos = PageStart; uint32_t Kind = readNext<uint32_t>(Pos); (void)Kind; assert(Kind == 2 && "kind for a regular 2nd level index should be 2"); uint16_t EntriesStart = readNext<uint16_t>(Pos); uint16_t NumEntries = readNext<uint16_t>(Pos); Pos = PageStart + EntriesStart; for (unsigned i = 0; i < NumEntries; ++i) { uint32_t FunctionOffset = readNext<uint32_t>(Pos); uint32_t Encoding = readNext<uint32_t>(Pos); outs() << " [" << i << "]: " << "function offset=" << format("0x%08" PRIx32, FunctionOffset) << ", " << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n'; } } static void printCompressedSecondLevelUnwindPage( const char *PageStart, uint32_t FunctionBase, const SmallVectorImpl<uint32_t> &CommonEncodings) { const char *Pos = PageStart; uint32_t Kind = readNext<uint32_t>(Pos); (void)Kind; assert(Kind == 3 && "kind for a compressed 2nd level index should be 3"); uint16_t EntriesStart = readNext<uint16_t>(Pos); uint16_t NumEntries = readNext<uint16_t>(Pos); uint16_t EncodingsStart = readNext<uint16_t>(Pos); readNext<uint16_t>(Pos); const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>( PageStart + EncodingsStart); Pos = PageStart + EntriesStart; for (unsigned i = 0; i < NumEntries; ++i) { uint32_t Entry = readNext<uint32_t>(Pos); uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff); uint32_t EncodingIdx = Entry >> 24; uint32_t Encoding; if (EncodingIdx < CommonEncodings.size()) Encoding = CommonEncodings[EncodingIdx]; else Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()]; outs() << " [" << i << "]: " << "function offset=" << format("0x%08" PRIx32, FunctionOffset) << ", " << "encoding[" << EncodingIdx << "]=" << format("0x%08" PRIx32, Encoding) << '\n'; } } static void printMachOUnwindInfoSection(const MachOObjectFile *Obj, std::map<uint64_t, SymbolRef> &Symbols, const SectionRef &UnwindInfo) { assert(Obj->isLittleEndian() && "There should not be a big-endian .o with __unwind_info"); outs() << "Contents of __unwind_info section:\n"; StringRef Contents; UnwindInfo.getContents(Contents); const char *Pos = Contents.data(); //===---------------------------------- // Section header //===---------------------------------- uint32_t Version = readNext<uint32_t>(Pos); outs() << " Version: " << format("0x%" PRIx32, Version) << '\n'; assert(Version == 1 && "only understand version 1"); uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos); outs() << " Common encodings array section offset: " << format("0x%" PRIx32, CommonEncodingsStart) << '\n'; uint32_t NumCommonEncodings = readNext<uint32_t>(Pos); outs() << " Number of common encodings in array: " << format("0x%" PRIx32, NumCommonEncodings) << '\n'; uint32_t PersonalitiesStart = readNext<uint32_t>(Pos); outs() << " Personality function array section offset: " << format("0x%" PRIx32, PersonalitiesStart) << '\n'; uint32_t NumPersonalities = readNext<uint32_t>(Pos); outs() << " Number of personality functions in array: " << format("0x%" PRIx32, NumPersonalities) << '\n'; uint32_t IndicesStart = readNext<uint32_t>(Pos); outs() << " Index array section offset: " << format("0x%" PRIx32, IndicesStart) << '\n'; uint32_t NumIndices = readNext<uint32_t>(Pos); outs() << " Number of indices in array: " << format("0x%" PRIx32, NumIndices) << '\n'; //===---------------------------------- // A shared list of common encodings //===---------------------------------- // These occupy indices in the range [0, N] whenever an encoding is referenced // from a compressed 2nd level index table. In practice the linker only // creates ~128 of these, so that indices are available to embed encodings in // the 2nd level index. SmallVector<uint32_t, 64> CommonEncodings; outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n"; Pos = Contents.data() + CommonEncodingsStart; for (unsigned i = 0; i < NumCommonEncodings; ++i) { uint32_t Encoding = readNext<uint32_t>(Pos); CommonEncodings.push_back(Encoding); outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding) << '\n'; } //===---------------------------------- // Personality functions used in this executable //===---------------------------------- // There should be only a handful of these (one per source language, // roughly). Particularly since they only get 2 bits in the compact encoding. outs() << " Personality functions: (count = " << NumPersonalities << ")\n"; Pos = Contents.data() + PersonalitiesStart; for (unsigned i = 0; i < NumPersonalities; ++i) { uint32_t PersonalityFn = readNext<uint32_t>(Pos); outs() << " personality[" << i + 1 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n'; } //===---------------------------------- // The level 1 index entries //===---------------------------------- // These specify an approximate place to start searching for the more detailed // information, sorted by PC. struct IndexEntry { uint32_t FunctionOffset; uint32_t SecondLevelPageStart; uint32_t LSDAStart; }; SmallVector<IndexEntry, 4> IndexEntries; outs() << " Top level indices: (count = " << NumIndices << ")\n"; Pos = Contents.data() + IndicesStart; for (unsigned i = 0; i < NumIndices; ++i) { IndexEntry Entry; Entry.FunctionOffset = readNext<uint32_t>(Pos); Entry.SecondLevelPageStart = readNext<uint32_t>(Pos); Entry.LSDAStart = readNext<uint32_t>(Pos); IndexEntries.push_back(Entry); outs() << " [" << i << "]: " << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset) << ", " << "2nd level page offset=" << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", " << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n'; } //===---------------------------------- // Next come the LSDA tables //===---------------------------------- // The LSDA layout is rather implicit: it's a contiguous array of entries from // the first top-level index's LSDAOffset to the last (sentinel). outs() << " LSDA descriptors:\n"; Pos = Contents.data() + IndexEntries[0].LSDAStart; int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / (2 * sizeof(uint32_t)); for (int i = 0; i < NumLSDAs; ++i) { uint32_t FunctionOffset = readNext<uint32_t>(Pos); uint32_t LSDAOffset = readNext<uint32_t>(Pos); outs() << " [" << i << "]: " << "function offset=" << format("0x%08" PRIx32, FunctionOffset) << ", " << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n'; } //===---------------------------------- // Finally, the 2nd level indices //===---------------------------------- // Generally these are 4K in size, and have 2 possible forms: // + Regular stores up to 511 entries with disparate encodings // + Compressed stores up to 1021 entries if few enough compact encoding // values are used. outs() << " Second level indices:\n"; for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) { // The final sentinel top-level index has no associated 2nd level page if (IndexEntries[i].SecondLevelPageStart == 0) break; outs() << " Second level index[" << i << "]: " << "offset in section=" << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart) << ", " << "base function offset=" << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n'; Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart; uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos); if (Kind == 2) printRegularSecondLevelUnwindPage(Pos); else if (Kind == 3) printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset, CommonEncodings); else llvm_unreachable("Do not know how to print this kind of 2nd level page"); } } void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) { std::map<uint64_t, SymbolRef> Symbols; for (const SymbolRef &SymRef : Obj->symbols()) { // Discard any undefined or absolute symbols. They're not going to take part // in the convenience lookup for unwind info and just take up resources. section_iterator Section = Obj->section_end(); SymRef.getSection(Section); if (Section == Obj->section_end()) continue; uint64_t Addr = SymRef.getValue(); Symbols.insert(std::make_pair(Addr, SymRef)); } for (const SectionRef &Section : Obj->sections()) { StringRef SectName; Section.getName(SectName); if (SectName == "__compact_unwind") printMachOCompactUnwindSection(Obj, Symbols, Section); else if (SectName == "__unwind_info") printMachOUnwindInfoSection(Obj, Symbols, Section); else if (SectName == "__eh_frame") outs() << "llvm-objdump: warning: unhandled __eh_frame section\n"; } } static void PrintMachHeader(uint32_t magic, uint32_t cputype, uint32_t cpusubtype, uint32_t filetype, uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags, bool verbose) { outs() << "Mach header\n"; outs() << " magic cputype cpusubtype caps filetype ncmds " "sizeofcmds flags\n"; if (verbose) { if (magic == MachO::MH_MAGIC) outs() << " MH_MAGIC"; else if (magic == MachO::MH_MAGIC_64) outs() << "MH_MAGIC_64"; else outs() << format(" 0x%08" PRIx32, magic); switch (cputype) { case MachO::CPU_TYPE_I386: outs() << " I386"; switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { case MachO::CPU_SUBTYPE_I386_ALL: outs() << " ALL"; break; default: outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); break; } break; case MachO::CPU_TYPE_X86_64: outs() << " X86_64"; switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { case MachO::CPU_SUBTYPE_X86_64_ALL: outs() << " ALL"; break; case MachO::CPU_SUBTYPE_X86_64_H: outs() << " Haswell"; break; default: outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); break; } break; case MachO::CPU_TYPE_ARM: outs() << " ARM"; switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { case MachO::CPU_SUBTYPE_ARM_ALL: outs() << " ALL"; break; case MachO::CPU_SUBTYPE_ARM_V4T: outs() << " V4T"; break; case MachO::CPU_SUBTYPE_ARM_V5TEJ: outs() << " V5TEJ"; break; case MachO::CPU_SUBTYPE_ARM_XSCALE: outs() << " XSCALE"; break; case MachO::CPU_SUBTYPE_ARM_V6: outs() << " V6"; break; case MachO::CPU_SUBTYPE_ARM_V6M: outs() << " V6M"; break; case MachO::CPU_SUBTYPE_ARM_V7: outs() << " V7"; break; case MachO::CPU_SUBTYPE_ARM_V7EM: outs() << " V7EM"; break; case MachO::CPU_SUBTYPE_ARM_V7K: outs() << " V7K"; break; case MachO::CPU_SUBTYPE_ARM_V7M: outs() << " V7M"; break; case MachO::CPU_SUBTYPE_ARM_V7S: outs() << " V7S"; break; default: outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); break; } break; case MachO::CPU_TYPE_ARM64: outs() << " ARM64"; switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { case MachO::CPU_SUBTYPE_ARM64_ALL: outs() << " ALL"; break; default: outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); break; } break; case MachO::CPU_TYPE_POWERPC: outs() << " PPC"; switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { case MachO::CPU_SUBTYPE_POWERPC_ALL: outs() << " ALL"; break; default: outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); break; } break; case MachO::CPU_TYPE_POWERPC64: outs() << " PPC64"; switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { case MachO::CPU_SUBTYPE_POWERPC_ALL: outs() << " ALL"; break; default: outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); break; } break; } if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) { outs() << " LIB64"; } else { outs() << format(" 0x%02" PRIx32, (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24); } switch (filetype) { case MachO::MH_OBJECT: outs() << " OBJECT"; break; case MachO::MH_EXECUTE: outs() << " EXECUTE"; break; case MachO::MH_FVMLIB: outs() << " FVMLIB"; break; case MachO::MH_CORE: outs() << " CORE"; break; case MachO::MH_PRELOAD: outs() << " PRELOAD"; break; case MachO::MH_DYLIB: outs() << " DYLIB"; break; case MachO::MH_DYLIB_STUB: outs() << " DYLIB_STUB"; break; case MachO::MH_DYLINKER: outs() << " DYLINKER"; break; case MachO::MH_BUNDLE: outs() << " BUNDLE"; break; case MachO::MH_DSYM: outs() << " DSYM"; break; case MachO::MH_KEXT_BUNDLE: outs() << " KEXTBUNDLE"; break; default: outs() << format(" %10u", filetype); break; } outs() << format(" %5u", ncmds); outs() << format(" %10u", sizeofcmds); uint32_t f = flags; if (f & MachO::MH_NOUNDEFS) { outs() << " NOUNDEFS"; f &= ~MachO::MH_NOUNDEFS; } if (f & MachO::MH_INCRLINK) { outs() << " INCRLINK"; f &= ~MachO::MH_INCRLINK; } if (f & MachO::MH_DYLDLINK) { outs() << " DYLDLINK"; f &= ~MachO::MH_DYLDLINK; } if (f & MachO::MH_BINDATLOAD) { outs() << " BINDATLOAD"; f &= ~MachO::MH_BINDATLOAD; } if (f & MachO::MH_PREBOUND) { outs() << " PREBOUND"; f &= ~MachO::MH_PREBOUND; } if (f & MachO::MH_SPLIT_SEGS) { outs() << " SPLIT_SEGS"; f &= ~MachO::MH_SPLIT_SEGS; } if (f & MachO::MH_LAZY_INIT) { outs() << " LAZY_INIT"; f &= ~MachO::MH_LAZY_INIT; } if (f & MachO::MH_TWOLEVEL) { outs() << " TWOLEVEL"; f &= ~MachO::MH_TWOLEVEL; } if (f & MachO::MH_FORCE_FLAT) { outs() << " FORCE_FLAT"; f &= ~MachO::MH_FORCE_FLAT; } if (f & MachO::MH_NOMULTIDEFS) { outs() << " NOMULTIDEFS"; f &= ~MachO::MH_NOMULTIDEFS; } if (f & MachO::MH_NOFIXPREBINDING) { outs() << " NOFIXPREBINDING"; f &= ~MachO::MH_NOFIXPREBINDING; } if (f & MachO::MH_PREBINDABLE) { outs() << " PREBINDABLE"; f &= ~MachO::MH_PREBINDABLE; } if (f & MachO::MH_ALLMODSBOUND) { outs() << " ALLMODSBOUND"; f &= ~MachO::MH_ALLMODSBOUND; } if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) { outs() << " SUBSECTIONS_VIA_SYMBOLS"; f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS; } if (f & MachO::MH_CANONICAL) { outs() << " CANONICAL"; f &= ~MachO::MH_CANONICAL; } if (f & MachO::MH_WEAK_DEFINES) { outs() << " WEAK_DEFINES"; f &= ~MachO::MH_WEAK_DEFINES; } if (f & MachO::MH_BINDS_TO_WEAK) { outs() << " BINDS_TO_WEAK"; f &= ~MachO::MH_BINDS_TO_WEAK; } if (f & MachO::MH_ALLOW_STACK_EXECUTION) { outs() << " ALLOW_STACK_EXECUTION"; f &= ~MachO::MH_ALLOW_STACK_EXECUTION; } if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) { outs() << " DEAD_STRIPPABLE_DYLIB"; f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB; } if (f & MachO::MH_PIE) { outs() << " PIE"; f &= ~MachO::MH_PIE; } if (f & MachO::MH_NO_REEXPORTED_DYLIBS) { outs() << " NO_REEXPORTED_DYLIBS"; f &= ~MachO::MH_NO_REEXPORTED_DYLIBS; } if (f & MachO::MH_HAS_TLV_DESCRIPTORS) { outs() << " MH_HAS_TLV_DESCRIPTORS"; f &= ~MachO::MH_HAS_TLV_DESCRIPTORS; } if (f & MachO::MH_NO_HEAP_EXECUTION) { outs() << " MH_NO_HEAP_EXECUTION"; f &= ~MachO::MH_NO_HEAP_EXECUTION; } if (f & MachO::MH_APP_EXTENSION_SAFE) { outs() << " APP_EXTENSION_SAFE"; f &= ~MachO::MH_APP_EXTENSION_SAFE; } if (f != 0 || flags == 0) outs() << format(" 0x%08" PRIx32, f); } else { outs() << format(" 0x%08" PRIx32, magic); outs() << format(" %7d", cputype); outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); outs() << format(" 0x%02" PRIx32, (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24); outs() << format(" %10u", filetype); outs() << format(" %5u", ncmds); outs() << format(" %10u", sizeofcmds); outs() << format(" 0x%08" PRIx32, flags); } outs() << "\n"; } static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize, StringRef SegName, uint64_t vmaddr, uint64_t vmsize, uint64_t fileoff, uint64_t filesize, uint32_t maxprot, uint32_t initprot, uint32_t nsects, uint32_t flags, uint32_t object_size, bool verbose) { uint64_t expected_cmdsize; if (cmd == MachO::LC_SEGMENT) { outs() << " cmd LC_SEGMENT\n"; expected_cmdsize = nsects; expected_cmdsize *= sizeof(struct MachO::section); expected_cmdsize += sizeof(struct MachO::segment_command); } else { outs() << " cmd LC_SEGMENT_64\n"; expected_cmdsize = nsects; expected_cmdsize *= sizeof(struct MachO::section_64); expected_cmdsize += sizeof(struct MachO::segment_command_64); } outs() << " cmdsize " << cmdsize; if (cmdsize != expected_cmdsize) outs() << " Inconsistent size\n"; else outs() << "\n"; outs() << " segname " << SegName << "\n"; if (cmd == MachO::LC_SEGMENT_64) { outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n"; outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n"; } else { outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n"; outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n"; } outs() << " fileoff " << fileoff; if (fileoff > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " filesize " << filesize; if (fileoff + filesize > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; if (verbose) { if ((maxprot & ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE)) != 0) outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n"; else { if (maxprot & MachO::VM_PROT_READ) outs() << " maxprot r"; else outs() << " maxprot -"; if (maxprot & MachO::VM_PROT_WRITE) outs() << "w"; else outs() << "-"; if (maxprot & MachO::VM_PROT_EXECUTE) outs() << "x\n"; else outs() << "-\n"; } if ((initprot & ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE)) != 0) outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n"; else { if (initprot & MachO::VM_PROT_READ) outs() << " initprot r"; else outs() << " initprot -"; if (initprot & MachO::VM_PROT_WRITE) outs() << "w"; else outs() << "-"; if (initprot & MachO::VM_PROT_EXECUTE) outs() << "x\n"; else outs() << "-\n"; } } else { outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n"; outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n"; } outs() << " nsects " << nsects << "\n"; if (verbose) { outs() << " flags"; if (flags == 0) outs() << " (none)\n"; else { if (flags & MachO::SG_HIGHVM) { outs() << " HIGHVM"; flags &= ~MachO::SG_HIGHVM; } if (flags & MachO::SG_FVMLIB) { outs() << " FVMLIB"; flags &= ~MachO::SG_FVMLIB; } if (flags & MachO::SG_NORELOC) { outs() << " NORELOC"; flags &= ~MachO::SG_NORELOC; } if (flags & MachO::SG_PROTECTED_VERSION_1) { outs() << " PROTECTED_VERSION_1"; flags &= ~MachO::SG_PROTECTED_VERSION_1; } if (flags) outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n"; else outs() << "\n"; } } else { outs() << " flags " << format("0x%" PRIx32, flags) << "\n"; } } static void PrintSection(const char *sectname, const char *segname, uint64_t addr, uint64_t size, uint32_t offset, uint32_t align, uint32_t reloff, uint32_t nreloc, uint32_t flags, uint32_t reserved1, uint32_t reserved2, uint32_t cmd, const char *sg_segname, uint32_t filetype, uint32_t object_size, bool verbose) { outs() << "Section\n"; outs() << " sectname " << format("%.16s\n", sectname); outs() << " segname " << format("%.16s", segname); if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0) outs() << " (does not match segment)\n"; else outs() << "\n"; if (cmd == MachO::LC_SEGMENT_64) { outs() << " addr " << format("0x%016" PRIx64, addr) << "\n"; outs() << " size " << format("0x%016" PRIx64, size); } else { outs() << " addr " << format("0x%08" PRIx64, addr) << "\n"; outs() << " size " << format("0x%08" PRIx64, size); } if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " offset " << offset; if (offset > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; uint32_t align_shifted = 1 << align; outs() << " align 2^" << align << " (" << align_shifted << ")\n"; outs() << " reloff " << reloff; if (reloff > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " nreloc " << nreloc; if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; uint32_t section_type = flags & MachO::SECTION_TYPE; if (verbose) { outs() << " type"; if (section_type == MachO::S_REGULAR) outs() << " S_REGULAR\n"; else if (section_type == MachO::S_ZEROFILL) outs() << " S_ZEROFILL\n"; else if (section_type == MachO::S_CSTRING_LITERALS) outs() << " S_CSTRING_LITERALS\n"; else if (section_type == MachO::S_4BYTE_LITERALS) outs() << " S_4BYTE_LITERALS\n"; else if (section_type == MachO::S_8BYTE_LITERALS) outs() << " S_8BYTE_LITERALS\n"; else if (section_type == MachO::S_16BYTE_LITERALS) outs() << " S_16BYTE_LITERALS\n"; else if (section_type == MachO::S_LITERAL_POINTERS) outs() << " S_LITERAL_POINTERS\n"; else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS) outs() << " S_NON_LAZY_SYMBOL_POINTERS\n"; else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS) outs() << " S_LAZY_SYMBOL_POINTERS\n"; else if (section_type == MachO::S_SYMBOL_STUBS) outs() << " S_SYMBOL_STUBS\n"; else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS) outs() << " S_MOD_INIT_FUNC_POINTERS\n"; else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS) outs() << " S_MOD_TERM_FUNC_POINTERS\n"; else if (section_type == MachO::S_COALESCED) outs() << " S_COALESCED\n"; else if (section_type == MachO::S_INTERPOSING) outs() << " S_INTERPOSING\n"; else if (section_type == MachO::S_DTRACE_DOF) outs() << " S_DTRACE_DOF\n"; else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS) outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n"; else if (section_type == MachO::S_THREAD_LOCAL_REGULAR) outs() << " S_THREAD_LOCAL_REGULAR\n"; else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL) outs() << " S_THREAD_LOCAL_ZEROFILL\n"; else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES) outs() << " S_THREAD_LOCAL_VARIABLES\n"; else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS) outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n"; else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS) outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n"; else outs() << format("0x%08" PRIx32, section_type) << "\n"; outs() << "attributes"; uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES; if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS) outs() << " PURE_INSTRUCTIONS"; if (section_attributes & MachO::S_ATTR_NO_TOC) outs() << " NO_TOC"; if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS) outs() << " STRIP_STATIC_SYMS"; if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP) outs() << " NO_DEAD_STRIP"; if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT) outs() << " LIVE_SUPPORT"; if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE) outs() << " SELF_MODIFYING_CODE"; if (section_attributes & MachO::S_ATTR_DEBUG) outs() << " DEBUG"; if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS) outs() << " SOME_INSTRUCTIONS"; if (section_attributes & MachO::S_ATTR_EXT_RELOC) outs() << " EXT_RELOC"; if (section_attributes & MachO::S_ATTR_LOC_RELOC) outs() << " LOC_RELOC"; if (section_attributes == 0) outs() << " (none)"; outs() << "\n"; } else outs() << " flags " << format("0x%08" PRIx32, flags) << "\n"; outs() << " reserved1 " << reserved1; if (section_type == MachO::S_SYMBOL_STUBS || section_type == MachO::S_LAZY_SYMBOL_POINTERS || section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS) outs() << " (index into indirect symbol table)\n"; else outs() << "\n"; outs() << " reserved2 " << reserved2; if (section_type == MachO::S_SYMBOL_STUBS) outs() << " (size of stubs)\n"; else outs() << "\n"; } static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit, uint32_t object_size) { outs() << " cmd LC_SYMTAB\n"; outs() << " cmdsize " << st.cmdsize; if (st.cmdsize != sizeof(struct MachO::symtab_command)) outs() << " Incorrect size\n"; else outs() << "\n"; outs() << " symoff " << st.symoff; if (st.symoff > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " nsyms " << st.nsyms; uint64_t big_size; if (Is64Bit) { big_size = st.nsyms; big_size *= sizeof(struct MachO::nlist_64); big_size += st.symoff; if (big_size > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; } else { big_size = st.nsyms; big_size *= sizeof(struct MachO::nlist); big_size += st.symoff; if (big_size > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; } outs() << " stroff " << st.stroff; if (st.stroff > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " strsize " << st.strsize; big_size = st.stroff; big_size += st.strsize; if (big_size > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; } static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst, uint32_t nsyms, uint32_t object_size, bool Is64Bit) { outs() << " cmd LC_DYSYMTAB\n"; outs() << " cmdsize " << dyst.cmdsize; if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command)) outs() << " Incorrect size\n"; else outs() << "\n"; outs() << " ilocalsym " << dyst.ilocalsym; if (dyst.ilocalsym > nsyms) outs() << " (greater than the number of symbols)\n"; else outs() << "\n"; outs() << " nlocalsym " << dyst.nlocalsym; uint64_t big_size; big_size = dyst.ilocalsym; big_size += dyst.nlocalsym; if (big_size > nsyms) outs() << " (past the end of the symbol table)\n"; else outs() << "\n"; outs() << " iextdefsym " << dyst.iextdefsym; if (dyst.iextdefsym > nsyms) outs() << " (greater than the number of symbols)\n"; else outs() << "\n"; outs() << " nextdefsym " << dyst.nextdefsym; big_size = dyst.iextdefsym; big_size += dyst.nextdefsym; if (big_size > nsyms) outs() << " (past the end of the symbol table)\n"; else outs() << "\n"; outs() << " iundefsym " << dyst.iundefsym; if (dyst.iundefsym > nsyms) outs() << " (greater than the number of symbols)\n"; else outs() << "\n"; outs() << " nundefsym " << dyst.nundefsym; big_size = dyst.iundefsym; big_size += dyst.nundefsym; if (big_size > nsyms) outs() << " (past the end of the symbol table)\n"; else outs() << "\n"; outs() << " tocoff " << dyst.tocoff; if (dyst.tocoff > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " ntoc " << dyst.ntoc; big_size = dyst.ntoc; big_size *= sizeof(struct MachO::dylib_table_of_contents); big_size += dyst.tocoff; if (big_size > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " modtaboff " << dyst.modtaboff; if (dyst.modtaboff > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " nmodtab " << dyst.nmodtab; uint64_t modtabend; if (Is64Bit) { modtabend = dyst.nmodtab; modtabend *= sizeof(struct MachO::dylib_module_64); modtabend += dyst.modtaboff; } else { modtabend = dyst.nmodtab; modtabend *= sizeof(struct MachO::dylib_module); modtabend += dyst.modtaboff; } if (modtabend > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " extrefsymoff " << dyst.extrefsymoff; if (dyst.extrefsymoff > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " nextrefsyms " << dyst.nextrefsyms; big_size = dyst.nextrefsyms; big_size *= sizeof(struct MachO::dylib_reference); big_size += dyst.extrefsymoff; if (big_size > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " indirectsymoff " << dyst.indirectsymoff; if (dyst.indirectsymoff > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " nindirectsyms " << dyst.nindirectsyms; big_size = dyst.nindirectsyms; big_size *= sizeof(uint32_t); big_size += dyst.indirectsymoff; if (big_size > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " extreloff " << dyst.extreloff; if (dyst.extreloff > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " nextrel " << dyst.nextrel; big_size = dyst.nextrel; big_size *= sizeof(struct MachO::relocation_info); big_size += dyst.extreloff; if (big_size > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " locreloff " << dyst.locreloff; if (dyst.locreloff > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " nlocrel " << dyst.nlocrel; big_size = dyst.nlocrel; big_size *= sizeof(struct MachO::relocation_info); big_size += dyst.locreloff; if (big_size > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; } static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc, uint32_t object_size) { if (dc.cmd == MachO::LC_DYLD_INFO) outs() << " cmd LC_DYLD_INFO\n"; else outs() << " cmd LC_DYLD_INFO_ONLY\n"; outs() << " cmdsize " << dc.cmdsize; if (dc.cmdsize != sizeof(struct MachO::dyld_info_command)) outs() << " Incorrect size\n"; else outs() << "\n"; outs() << " rebase_off " << dc.rebase_off; if (dc.rebase_off > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " rebase_size " << dc.rebase_size; uint64_t big_size; big_size = dc.rebase_off; big_size += dc.rebase_size; if (big_size > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " bind_off " << dc.bind_off; if (dc.bind_off > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " bind_size " << dc.bind_size; big_size = dc.bind_off; big_size += dc.bind_size; if (big_size > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " weak_bind_off " << dc.weak_bind_off; if (dc.weak_bind_off > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " weak_bind_size " << dc.weak_bind_size; big_size = dc.weak_bind_off; big_size += dc.weak_bind_size; if (big_size > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " lazy_bind_off " << dc.lazy_bind_off; if (dc.lazy_bind_off > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " lazy_bind_size " << dc.lazy_bind_size; big_size = dc.lazy_bind_off; big_size += dc.lazy_bind_size; if (big_size > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " export_off " << dc.export_off; if (dc.export_off > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " export_size " << dc.export_size; big_size = dc.export_off; big_size += dc.export_size; if (big_size > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; } static void PrintDyldLoadCommand(MachO::dylinker_command dyld, const char *Ptr) { if (dyld.cmd == MachO::LC_ID_DYLINKER) outs() << " cmd LC_ID_DYLINKER\n"; else if (dyld.cmd == MachO::LC_LOAD_DYLINKER) outs() << " cmd LC_LOAD_DYLINKER\n"; else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT) outs() << " cmd LC_DYLD_ENVIRONMENT\n"; else outs() << " cmd ?(" << dyld.cmd << ")\n"; outs() << " cmdsize " << dyld.cmdsize; if (dyld.cmdsize < sizeof(struct MachO::dylinker_command)) outs() << " Incorrect size\n"; else outs() << "\n"; if (dyld.name >= dyld.cmdsize) outs() << " name ?(bad offset " << dyld.name << ")\n"; else { const char *P = (const char *)(Ptr) + dyld.name; outs() << " name " << P << " (offset " << dyld.name << ")\n"; } } static void PrintUuidLoadCommand(MachO::uuid_command uuid) { outs() << " cmd LC_UUID\n"; outs() << " cmdsize " << uuid.cmdsize; if (uuid.cmdsize != sizeof(struct MachO::uuid_command)) outs() << " Incorrect size\n"; else outs() << "\n"; outs() << " uuid "; outs() << format("%02" PRIX32, uuid.uuid[0]); outs() << format("%02" PRIX32, uuid.uuid[1]); outs() << format("%02" PRIX32, uuid.uuid[2]); outs() << format("%02" PRIX32, uuid.uuid[3]); outs() << "-"; outs() << format("%02" PRIX32, uuid.uuid[4]); outs() << format("%02" PRIX32, uuid.uuid[5]); outs() << "-"; outs() << format("%02" PRIX32, uuid.uuid[6]); outs() << format("%02" PRIX32, uuid.uuid[7]); outs() << "-"; outs() << format("%02" PRIX32, uuid.uuid[8]); outs() << format("%02" PRIX32, uuid.uuid[9]); outs() << "-"; outs() << format("%02" PRIX32, uuid.uuid[10]); outs() << format("%02" PRIX32, uuid.uuid[11]); outs() << format("%02" PRIX32, uuid.uuid[12]); outs() << format("%02" PRIX32, uuid.uuid[13]); outs() << format("%02" PRIX32, uuid.uuid[14]); outs() << format("%02" PRIX32, uuid.uuid[15]); outs() << "\n"; } static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) { outs() << " cmd LC_RPATH\n"; outs() << " cmdsize " << rpath.cmdsize; if (rpath.cmdsize < sizeof(struct MachO::rpath_command)) outs() << " Incorrect size\n"; else outs() << "\n"; if (rpath.path >= rpath.cmdsize) outs() << " path ?(bad offset " << rpath.path << ")\n"; else { const char *P = (const char *)(Ptr) + rpath.path; outs() << " path " << P << " (offset " << rpath.path << ")\n"; } } static void PrintVersionMinLoadCommand(MachO::version_min_command vd) { if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX) outs() << " cmd LC_VERSION_MIN_MACOSX\n"; else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS) outs() << " cmd LC_VERSION_MIN_IPHONEOS\n"; else outs() << " cmd " << vd.cmd << " (?)\n"; outs() << " cmdsize " << vd.cmdsize; if (vd.cmdsize != sizeof(struct MachO::version_min_command)) outs() << " Incorrect size\n"; else outs() << "\n"; outs() << " version " << ((vd.version >> 16) & 0xffff) << "." << ((vd.version >> 8) & 0xff); if ((vd.version & 0xff) != 0) outs() << "." << (vd.version & 0xff); outs() << "\n"; if (vd.sdk == 0) outs() << " sdk n/a"; else { outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "." << ((vd.sdk >> 8) & 0xff); } if ((vd.sdk & 0xff) != 0) outs() << "." << (vd.sdk & 0xff); outs() << "\n"; } static void PrintSourceVersionCommand(MachO::source_version_command sd) { outs() << " cmd LC_SOURCE_VERSION\n"; outs() << " cmdsize " << sd.cmdsize; if (sd.cmdsize != sizeof(struct MachO::source_version_command)) outs() << " Incorrect size\n"; else outs() << "\n"; uint64_t a = (sd.version >> 40) & 0xffffff; uint64_t b = (sd.version >> 30) & 0x3ff; uint64_t c = (sd.version >> 20) & 0x3ff; uint64_t d = (sd.version >> 10) & 0x3ff; uint64_t e = sd.version & 0x3ff; outs() << " version " << a << "." << b; if (e != 0) outs() << "." << c << "." << d << "." << e; else if (d != 0) outs() << "." << c << "." << d; else if (c != 0) outs() << "." << c; outs() << "\n"; } static void PrintEntryPointCommand(MachO::entry_point_command ep) { outs() << " cmd LC_MAIN\n"; outs() << " cmdsize " << ep.cmdsize; if (ep.cmdsize != sizeof(struct MachO::entry_point_command)) outs() << " Incorrect size\n"; else outs() << "\n"; outs() << " entryoff " << ep.entryoff << "\n"; outs() << " stacksize " << ep.stacksize << "\n"; } static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec, uint32_t object_size) { outs() << " cmd LC_ENCRYPTION_INFO\n"; outs() << " cmdsize " << ec.cmdsize; if (ec.cmdsize != sizeof(struct MachO::encryption_info_command)) outs() << " Incorrect size\n"; else outs() << "\n"; outs() << " cryptoff " << ec.cryptoff; if (ec.cryptoff > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " cryptsize " << ec.cryptsize; if (ec.cryptsize > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " cryptid " << ec.cryptid << "\n"; } static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec, uint32_t object_size) { outs() << " cmd LC_ENCRYPTION_INFO_64\n"; outs() << " cmdsize " << ec.cmdsize; if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64)) outs() << " Incorrect size\n"; else outs() << "\n"; outs() << " cryptoff " << ec.cryptoff; if (ec.cryptoff > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " cryptsize " << ec.cryptsize; if (ec.cryptsize > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " cryptid " << ec.cryptid << "\n"; outs() << " pad " << ec.pad << "\n"; } static void PrintLinkerOptionCommand(MachO::linker_option_command lo, const char *Ptr) { outs() << " cmd LC_LINKER_OPTION\n"; outs() << " cmdsize " << lo.cmdsize; if (lo.cmdsize < sizeof(struct MachO::linker_option_command)) outs() << " Incorrect size\n"; else outs() << "\n"; outs() << " count " << lo.count << "\n"; const char *string = Ptr + sizeof(struct MachO::linker_option_command); uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command); uint32_t i = 0; while (left > 0) { while (*string == '\0' && left > 0) { string++; left--; } if (left > 0) { i++; outs() << " string #" << i << " " << format("%.*s\n", left, string); uint32_t NullPos = StringRef(string, left).find('\0'); uint32_t len = std::min(NullPos, left) + 1; string += len; left -= len; } } if (lo.count != i) outs() << " count " << lo.count << " does not match number of strings " << i << "\n"; } static void PrintSubFrameworkCommand(MachO::sub_framework_command sub, const char *Ptr) { outs() << " cmd LC_SUB_FRAMEWORK\n"; outs() << " cmdsize " << sub.cmdsize; if (sub.cmdsize < sizeof(struct MachO::sub_framework_command)) outs() << " Incorrect size\n"; else outs() << "\n"; if (sub.umbrella < sub.cmdsize) { const char *P = Ptr + sub.umbrella; outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n"; } else { outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n"; } } static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub, const char *Ptr) { outs() << " cmd LC_SUB_UMBRELLA\n"; outs() << " cmdsize " << sub.cmdsize; if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command)) outs() << " Incorrect size\n"; else outs() << "\n"; if (sub.sub_umbrella < sub.cmdsize) { const char *P = Ptr + sub.sub_umbrella; outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n"; } else { outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n"; } } static void PrintSubLibraryCommand(MachO::sub_library_command sub, const char *Ptr) { outs() << " cmd LC_SUB_LIBRARY\n"; outs() << " cmdsize " << sub.cmdsize; if (sub.cmdsize < sizeof(struct MachO::sub_library_command)) outs() << " Incorrect size\n"; else outs() << "\n"; if (sub.sub_library < sub.cmdsize) { const char *P = Ptr + sub.sub_library; outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n"; } else { outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n"; } } static void PrintSubClientCommand(MachO::sub_client_command sub, const char *Ptr) { outs() << " cmd LC_SUB_CLIENT\n"; outs() << " cmdsize " << sub.cmdsize; if (sub.cmdsize < sizeof(struct MachO::sub_client_command)) outs() << " Incorrect size\n"; else outs() << "\n"; if (sub.client < sub.cmdsize) { const char *P = Ptr + sub.client; outs() << " client " << P << " (offset " << sub.client << ")\n"; } else { outs() << " client ?(bad offset " << sub.client << ")\n"; } } static void PrintRoutinesCommand(MachO::routines_command r) { outs() << " cmd LC_ROUTINES\n"; outs() << " cmdsize " << r.cmdsize; if (r.cmdsize != sizeof(struct MachO::routines_command)) outs() << " Incorrect size\n"; else outs() << "\n"; outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n"; outs() << " init_module " << r.init_module << "\n"; outs() << " reserved1 " << r.reserved1 << "\n"; outs() << " reserved2 " << r.reserved2 << "\n"; outs() << " reserved3 " << r.reserved3 << "\n"; outs() << " reserved4 " << r.reserved4 << "\n"; outs() << " reserved5 " << r.reserved5 << "\n"; outs() << " reserved6 " << r.reserved6 << "\n"; } static void PrintRoutinesCommand64(MachO::routines_command_64 r) { outs() << " cmd LC_ROUTINES_64\n"; outs() << " cmdsize " << r.cmdsize; if (r.cmdsize != sizeof(struct MachO::routines_command_64)) outs() << " Incorrect size\n"; else outs() << "\n"; outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n"; outs() << " init_module " << r.init_module << "\n"; outs() << " reserved1 " << r.reserved1 << "\n"; outs() << " reserved2 " << r.reserved2 << "\n"; outs() << " reserved3 " << r.reserved3 << "\n"; outs() << " reserved4 " << r.reserved4 << "\n"; outs() << " reserved5 " << r.reserved5 << "\n"; outs() << " reserved6 " << r.reserved6 << "\n"; } static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) { outs() << " rax " << format("0x%016" PRIx64, cpu64.rax); outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx); outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n"; outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx); outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi); outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n"; outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp); outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp); outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n"; outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9); outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10); outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n"; outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12); outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13); outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n"; outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15); outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n"; outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags); outs() << " cs " << format("0x%016" PRIx64, cpu64.cs); outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n"; outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n"; } static void Print_mmst_reg(MachO::mmst_reg_t &r) { uint32_t f; outs() << "\t mmst_reg "; for (f = 0; f < 10; f++) outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " "; outs() << "\n"; outs() << "\t mmst_rsrv "; for (f = 0; f < 6; f++) outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " "; outs() << "\n"; } static void Print_xmm_reg(MachO::xmm_reg_t &r) { uint32_t f; outs() << "\t xmm_reg "; for (f = 0; f < 16; f++) outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " "; outs() << "\n"; } static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) { outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0]; outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n"; outs() << "\t control: invalid " << fpu.fpu_fcw.invalid; outs() << " denorm " << fpu.fpu_fcw.denorm; outs() << " zdiv " << fpu.fpu_fcw.zdiv; outs() << " ovrfl " << fpu.fpu_fcw.ovrfl; outs() << " undfl " << fpu.fpu_fcw.undfl; outs() << " precis " << fpu.fpu_fcw.precis << "\n"; outs() << "\t\t pc "; if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B) outs() << "FP_PREC_24B "; else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B) outs() << "FP_PREC_53B "; else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B) outs() << "FP_PREC_64B "; else outs() << fpu.fpu_fcw.pc << " "; outs() << "rc "; if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR) outs() << "FP_RND_NEAR "; else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN) outs() << "FP_RND_DOWN "; else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP) outs() << "FP_RND_UP "; else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP) outs() << "FP_CHOP "; outs() << "\n"; outs() << "\t status: invalid " << fpu.fpu_fsw.invalid; outs() << " denorm " << fpu.fpu_fsw.denorm; outs() << " zdiv " << fpu.fpu_fsw.zdiv; outs() << " ovrfl " << fpu.fpu_fsw.ovrfl; outs() << " undfl " << fpu.fpu_fsw.undfl; outs() << " precis " << fpu.fpu_fsw.precis; outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n"; outs() << "\t errsumm " << fpu.fpu_fsw.errsumm; outs() << " c0 " << fpu.fpu_fsw.c0; outs() << " c1 " << fpu.fpu_fsw.c1; outs() << " c2 " << fpu.fpu_fsw.c2; outs() << " tos " << fpu.fpu_fsw.tos; outs() << " c3 " << fpu.fpu_fsw.c3; outs() << " busy " << fpu.fpu_fsw.busy << "\n"; outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw); outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1); outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop); outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n"; outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs); outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2); outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp); outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n"; outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3); outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr); outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask); outs() << "\n"; outs() << "\t fpu_stmm0:\n"; Print_mmst_reg(fpu.fpu_stmm0); outs() << "\t fpu_stmm1:\n"; Print_mmst_reg(fpu.fpu_stmm1); outs() << "\t fpu_stmm2:\n"; Print_mmst_reg(fpu.fpu_stmm2); outs() << "\t fpu_stmm3:\n"; Print_mmst_reg(fpu.fpu_stmm3); outs() << "\t fpu_stmm4:\n"; Print_mmst_reg(fpu.fpu_stmm4); outs() << "\t fpu_stmm5:\n"; Print_mmst_reg(fpu.fpu_stmm5); outs() << "\t fpu_stmm6:\n"; Print_mmst_reg(fpu.fpu_stmm6); outs() << "\t fpu_stmm7:\n"; Print_mmst_reg(fpu.fpu_stmm7); outs() << "\t fpu_xmm0:\n"; Print_xmm_reg(fpu.fpu_xmm0); outs() << "\t fpu_xmm1:\n"; Print_xmm_reg(fpu.fpu_xmm1); outs() << "\t fpu_xmm2:\n"; Print_xmm_reg(fpu.fpu_xmm2); outs() << "\t fpu_xmm3:\n"; Print_xmm_reg(fpu.fpu_xmm3); outs() << "\t fpu_xmm4:\n"; Print_xmm_reg(fpu.fpu_xmm4); outs() << "\t fpu_xmm5:\n"; Print_xmm_reg(fpu.fpu_xmm5); outs() << "\t fpu_xmm6:\n"; Print_xmm_reg(fpu.fpu_xmm6); outs() << "\t fpu_xmm7:\n"; Print_xmm_reg(fpu.fpu_xmm7); outs() << "\t fpu_xmm8:\n"; Print_xmm_reg(fpu.fpu_xmm8); outs() << "\t fpu_xmm9:\n"; Print_xmm_reg(fpu.fpu_xmm9); outs() << "\t fpu_xmm10:\n"; Print_xmm_reg(fpu.fpu_xmm10); outs() << "\t fpu_xmm11:\n"; Print_xmm_reg(fpu.fpu_xmm11); outs() << "\t fpu_xmm12:\n"; Print_xmm_reg(fpu.fpu_xmm12); outs() << "\t fpu_xmm13:\n"; Print_xmm_reg(fpu.fpu_xmm13); outs() << "\t fpu_xmm14:\n"; Print_xmm_reg(fpu.fpu_xmm14); outs() << "\t fpu_xmm15:\n"; Print_xmm_reg(fpu.fpu_xmm15); outs() << "\t fpu_rsrv4:\n"; for (uint32_t f = 0; f < 6; f++) { outs() << "\t "; for (uint32_t g = 0; g < 16; g++) outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " "; outs() << "\n"; } outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1); outs() << "\n"; } static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) { outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno); outs() << " err " << format("0x%08" PRIx32, exc64.err); outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n"; } static void PrintThreadCommand(MachO::thread_command t, const char *Ptr, bool isLittleEndian, uint32_t cputype) { if (t.cmd == MachO::LC_THREAD) outs() << " cmd LC_THREAD\n"; else if (t.cmd == MachO::LC_UNIXTHREAD) outs() << " cmd LC_UNIXTHREAD\n"; else outs() << " cmd " << t.cmd << " (unknown)\n"; outs() << " cmdsize " << t.cmdsize; if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t)) outs() << " Incorrect size\n"; else outs() << "\n"; const char *begin = Ptr + sizeof(struct MachO::thread_command); const char *end = Ptr + t.cmdsize; uint32_t flavor, count, left; if (cputype == MachO::CPU_TYPE_X86_64) { while (begin < end) { if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { memcpy((char *)&flavor, begin, sizeof(uint32_t)); begin += sizeof(uint32_t); } else { flavor = 0; begin = end; } if (isLittleEndian != sys::IsLittleEndianHost) sys::swapByteOrder(flavor); if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { memcpy((char *)&count, begin, sizeof(uint32_t)); begin += sizeof(uint32_t); } else { count = 0; begin = end; } if (isLittleEndian != sys::IsLittleEndianHost) sys::swapByteOrder(count); if (flavor == MachO::x86_THREAD_STATE64) { outs() << " flavor x86_THREAD_STATE64\n"; if (count == MachO::x86_THREAD_STATE64_COUNT) outs() << " count x86_THREAD_STATE64_COUNT\n"; else outs() << " count " << count << " (not x86_THREAD_STATE64_COUNT)\n"; MachO::x86_thread_state64_t cpu64; left = end - begin; if (left >= sizeof(MachO::x86_thread_state64_t)) { memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t)); begin += sizeof(MachO::x86_thread_state64_t); } else { memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t)); memcpy(&cpu64, begin, left); begin += left; } if (isLittleEndian != sys::IsLittleEndianHost) swapStruct(cpu64); Print_x86_thread_state64_t(cpu64); } else if (flavor == MachO::x86_THREAD_STATE) { outs() << " flavor x86_THREAD_STATE\n"; if (count == MachO::x86_THREAD_STATE_COUNT) outs() << " count x86_THREAD_STATE_COUNT\n"; else outs() << " count " << count << " (not x86_THREAD_STATE_COUNT)\n"; struct MachO::x86_thread_state_t ts; left = end - begin; if (left >= sizeof(MachO::x86_thread_state_t)) { memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t)); begin += sizeof(MachO::x86_thread_state_t); } else { memset(&ts, '\0', sizeof(MachO::x86_thread_state_t)); memcpy(&ts, begin, left); begin += left; } if (isLittleEndian != sys::IsLittleEndianHost) swapStruct(ts); if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) { outs() << "\t tsh.flavor x86_THREAD_STATE64 "; if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT) outs() << "tsh.count x86_THREAD_STATE64_COUNT\n"; else outs() << "tsh.count " << ts.tsh.count << " (not x86_THREAD_STATE64_COUNT\n"; Print_x86_thread_state64_t(ts.uts.ts64); } else { outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count " << ts.tsh.count << "\n"; } } else if (flavor == MachO::x86_FLOAT_STATE) { outs() << " flavor x86_FLOAT_STATE\n"; if (count == MachO::x86_FLOAT_STATE_COUNT) outs() << " count x86_FLOAT_STATE_COUNT\n"; else outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n"; struct MachO::x86_float_state_t fs; left = end - begin; if (left >= sizeof(MachO::x86_float_state_t)) { memcpy(&fs, begin, sizeof(MachO::x86_float_state_t)); begin += sizeof(MachO::x86_float_state_t); } else { memset(&fs, '\0', sizeof(MachO::x86_float_state_t)); memcpy(&fs, begin, left); begin += left; } if (isLittleEndian != sys::IsLittleEndianHost) swapStruct(fs); if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) { outs() << "\t fsh.flavor x86_FLOAT_STATE64 "; if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT) outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n"; else outs() << "fsh.count " << fs.fsh.count << " (not x86_FLOAT_STATE64_COUNT\n"; Print_x86_float_state_t(fs.ufs.fs64); } else { outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count " << fs.fsh.count << "\n"; } } else if (flavor == MachO::x86_EXCEPTION_STATE) { outs() << " flavor x86_EXCEPTION_STATE\n"; if (count == MachO::x86_EXCEPTION_STATE_COUNT) outs() << " count x86_EXCEPTION_STATE_COUNT\n"; else outs() << " count " << count << " (not x86_EXCEPTION_STATE_COUNT)\n"; struct MachO::x86_exception_state_t es; left = end - begin; if (left >= sizeof(MachO::x86_exception_state_t)) { memcpy(&es, begin, sizeof(MachO::x86_exception_state_t)); begin += sizeof(MachO::x86_exception_state_t); } else { memset(&es, '\0', sizeof(MachO::x86_exception_state_t)); memcpy(&es, begin, left); begin += left; } if (isLittleEndian != sys::IsLittleEndianHost) swapStruct(es); if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) { outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n"; if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT) outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n"; else outs() << "\t esh.count " << es.esh.count << " (not x86_EXCEPTION_STATE64_COUNT\n"; Print_x86_exception_state_t(es.ues.es64); } else { outs() << "\t esh.flavor " << es.esh.flavor << " esh.count " << es.esh.count << "\n"; } } else { outs() << " flavor " << flavor << " (unknown)\n"; outs() << " count " << count << "\n"; outs() << " state (unknown)\n"; begin += count * sizeof(uint32_t); } } } else { while (begin < end) { if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { memcpy((char *)&flavor, begin, sizeof(uint32_t)); begin += sizeof(uint32_t); } else { flavor = 0; begin = end; } if (isLittleEndian != sys::IsLittleEndianHost) sys::swapByteOrder(flavor); if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { memcpy((char *)&count, begin, sizeof(uint32_t)); begin += sizeof(uint32_t); } else { count = 0; begin = end; } if (isLittleEndian != sys::IsLittleEndianHost) sys::swapByteOrder(count); outs() << " flavor " << flavor << "\n"; outs() << " count " << count << "\n"; outs() << " state (Unknown cputype/cpusubtype)\n"; begin += count * sizeof(uint32_t); } } } static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) { if (dl.cmd == MachO::LC_ID_DYLIB) outs() << " cmd LC_ID_DYLIB\n"; else if (dl.cmd == MachO::LC_LOAD_DYLIB) outs() << " cmd LC_LOAD_DYLIB\n"; else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB) outs() << " cmd LC_LOAD_WEAK_DYLIB\n"; else if (dl.cmd == MachO::LC_REEXPORT_DYLIB) outs() << " cmd LC_REEXPORT_DYLIB\n"; else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB) outs() << " cmd LC_LAZY_LOAD_DYLIB\n"; else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB) outs() << " cmd LC_LOAD_UPWARD_DYLIB\n"; else outs() << " cmd " << dl.cmd << " (unknown)\n"; outs() << " cmdsize " << dl.cmdsize; if (dl.cmdsize < sizeof(struct MachO::dylib_command)) outs() << " Incorrect size\n"; else outs() << "\n"; if (dl.dylib.name < dl.cmdsize) { const char *P = (const char *)(Ptr) + dl.dylib.name; outs() << " name " << P << " (offset " << dl.dylib.name << ")\n"; } else { outs() << " name ?(bad offset " << dl.dylib.name << ")\n"; } outs() << " time stamp " << dl.dylib.timestamp << " "; time_t t = dl.dylib.timestamp; outs() << ctime(&t); outs() << " current version "; if (dl.dylib.current_version == 0xffffffff) outs() << "n/a\n"; else outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "." << ((dl.dylib.current_version >> 8) & 0xff) << "." << (dl.dylib.current_version & 0xff) << "\n"; outs() << "compatibility version "; if (dl.dylib.compatibility_version == 0xffffffff) outs() << "n/a\n"; else outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "." << ((dl.dylib.compatibility_version >> 8) & 0xff) << "." << (dl.dylib.compatibility_version & 0xff) << "\n"; } static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld, uint32_t object_size) { if (ld.cmd == MachO::LC_CODE_SIGNATURE) outs() << " cmd LC_FUNCTION_STARTS\n"; else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO) outs() << " cmd LC_SEGMENT_SPLIT_INFO\n"; else if (ld.cmd == MachO::LC_FUNCTION_STARTS) outs() << " cmd LC_FUNCTION_STARTS\n"; else if (ld.cmd == MachO::LC_DATA_IN_CODE) outs() << " cmd LC_DATA_IN_CODE\n"; else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS) outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n"; else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n"; else outs() << " cmd " << ld.cmd << " (?)\n"; outs() << " cmdsize " << ld.cmdsize; if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command)) outs() << " Incorrect size\n"; else outs() << "\n"; outs() << " dataoff " << ld.dataoff; if (ld.dataoff > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; outs() << " datasize " << ld.datasize; uint64_t big_size = ld.dataoff; big_size += ld.datasize; if (big_size > object_size) outs() << " (past end of file)\n"; else outs() << "\n"; } static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype, uint32_t cputype, bool verbose) { StringRef Buf = Obj->getData(); unsigned Index = 0; for (const auto &Command : Obj->load_commands()) { outs() << "Load command " << Index++ << "\n"; if (Command.C.cmd == MachO::LC_SEGMENT) { MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command); const char *sg_segname = SLC.segname; PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr, SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot, SLC.initprot, SLC.nsects, SLC.flags, Buf.size(), verbose); for (unsigned j = 0; j < SLC.nsects; j++) { MachO::section S = Obj->getSection(Command, j); PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align, S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2, SLC.cmd, sg_segname, filetype, Buf.size(), verbose); } } else if (Command.C.cmd == MachO::LC_SEGMENT_64) { MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command); const char *sg_segname = SLC_64.segname; PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname, SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff, SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot, SLC_64.nsects, SLC_64.flags, Buf.size(), verbose); for (unsigned j = 0; j < SLC_64.nsects; j++) { MachO::section_64 S_64 = Obj->getSection64(Command, j); PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size, S_64.offset, S_64.align, S_64.reloff, S_64.nreloc, S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd, sg_segname, filetype, Buf.size(), verbose); } } else if (Command.C.cmd == MachO::LC_SYMTAB) { MachO::symtab_command Symtab = Obj->getSymtabLoadCommand(); PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size()); } else if (Command.C.cmd == MachO::LC_DYSYMTAB) { MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand(); MachO::symtab_command Symtab = Obj->getSymtabLoadCommand(); PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(), Obj->is64Bit()); } else if (Command.C.cmd == MachO::LC_DYLD_INFO || Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) { MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command); PrintDyldInfoLoadCommand(DyldInfo, Buf.size()); } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER || Command.C.cmd == MachO::LC_ID_DYLINKER || Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) { MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command); PrintDyldLoadCommand(Dyld, Command.Ptr); } else if (Command.C.cmd == MachO::LC_UUID) { MachO::uuid_command Uuid = Obj->getUuidCommand(Command); PrintUuidLoadCommand(Uuid); } else if (Command.C.cmd == MachO::LC_RPATH) { MachO::rpath_command Rpath = Obj->getRpathCommand(Command); PrintRpathLoadCommand(Rpath, Command.Ptr); } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX || Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) { MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command); PrintVersionMinLoadCommand(Vd); } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) { MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command); PrintSourceVersionCommand(Sd); } else if (Command.C.cmd == MachO::LC_MAIN) { MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command); PrintEntryPointCommand(Ep); } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) { MachO::encryption_info_command Ei = Obj->getEncryptionInfoCommand(Command); PrintEncryptionInfoCommand(Ei, Buf.size()); } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) { MachO::encryption_info_command_64 Ei = Obj->getEncryptionInfoCommand64(Command); PrintEncryptionInfoCommand64(Ei, Buf.size()); } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) { MachO::linker_option_command Lo = Obj->getLinkerOptionLoadCommand(Command); PrintLinkerOptionCommand(Lo, Command.Ptr); } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) { MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command); PrintSubFrameworkCommand(Sf, Command.Ptr); } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) { MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command); PrintSubUmbrellaCommand(Sf, Command.Ptr); } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) { MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command); PrintSubLibraryCommand(Sl, Command.Ptr); } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) { MachO::sub_client_command Sc = Obj->getSubClientCommand(Command); PrintSubClientCommand(Sc, Command.Ptr); } else if (Command.C.cmd == MachO::LC_ROUTINES) { MachO::routines_command Rc = Obj->getRoutinesCommand(Command); PrintRoutinesCommand(Rc); } else if (Command.C.cmd == MachO::LC_ROUTINES_64) { MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command); PrintRoutinesCommand64(Rc); } else if (Command.C.cmd == MachO::LC_THREAD || Command.C.cmd == MachO::LC_UNIXTHREAD) { MachO::thread_command Tc = Obj->getThreadCommand(Command); PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype); } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB || Command.C.cmd == MachO::LC_ID_DYLIB || Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB || Command.C.cmd == MachO::LC_REEXPORT_DYLIB || Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB || Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) { MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command); PrintDylibCommand(Dl, Command.Ptr); } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE || Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO || Command.C.cmd == MachO::LC_FUNCTION_STARTS || Command.C.cmd == MachO::LC_DATA_IN_CODE || Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS || Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) { MachO::linkedit_data_command Ld = Obj->getLinkeditDataLoadCommand(Command); PrintLinkEditDataCommand(Ld, Buf.size()); } else { outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd) << ")\n"; outs() << " cmdsize " << Command.C.cmdsize << "\n"; // TODO: get and print the raw bytes of the load command. } // TODO: print all the other kinds of load commands. } } static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &filetype, uint32_t &cputype, bool verbose) { if (Obj->is64Bit()) { MachO::mach_header_64 H_64; H_64 = Obj->getHeader64(); PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype, H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose); filetype = H_64.filetype; cputype = H_64.cputype; } else { MachO::mach_header H; H = Obj->getHeader(); PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds, H.sizeofcmds, H.flags, verbose); filetype = H.filetype; cputype = H.cputype; } } void llvm::printMachOFileHeader(const object::ObjectFile *Obj) { const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj); uint32_t filetype = 0; uint32_t cputype = 0; getAndPrintMachHeader(file, filetype, cputype, !NonVerbose); PrintLoadCommands(file, filetype, cputype, !NonVerbose); } //===----------------------------------------------------------------------===// // export trie dumping //===----------------------------------------------------------------------===// void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) { for (const llvm::object::ExportEntry &Entry : Obj->exports()) { uint64_t Flags = Entry.flags(); bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT); bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION); bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) == MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL); bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) == MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE); bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER); if (ReExport) outs() << "[re-export] "; else outs() << format("0x%08llX ", Entry.address()); // FIXME:add in base address outs() << Entry.name(); if (WeakDef || ThreadLocal || Resolver || Abs) { bool NeedsComma = false; outs() << " ["; if (WeakDef) { outs() << "weak_def"; NeedsComma = true; } if (ThreadLocal) { if (NeedsComma) outs() << ", "; outs() << "per-thread"; NeedsComma = true; } if (Abs) { if (NeedsComma) outs() << ", "; outs() << "absolute"; NeedsComma = true; } if (Resolver) { if (NeedsComma) outs() << ", "; outs() << format("resolver=0x%08llX", Entry.other()); NeedsComma = true; } outs() << "]"; } if (ReExport) { StringRef DylibName = "unknown"; int Ordinal = Entry.other() - 1; Obj->getLibraryShortNameByIndex(Ordinal, DylibName); if (Entry.otherName().empty()) outs() << " (from " << DylibName << ")"; else outs() << " (" << Entry.otherName() << " from " << DylibName << ")"; } outs() << "\n"; } } //===----------------------------------------------------------------------===// // rebase table dumping //===----------------------------------------------------------------------===// namespace { class SegInfo { public: SegInfo(const object::MachOObjectFile *Obj); StringRef segmentName(uint32_t SegIndex); StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset); uint64_t address(uint32_t SegIndex, uint64_t SegOffset); private: struct SectionInfo { uint64_t Address; uint64_t Size; StringRef SectionName; StringRef SegmentName; uint64_t OffsetInSegment; uint64_t SegmentStartAddress; uint32_t SegmentIndex; }; const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset); SmallVector<SectionInfo, 32> Sections; }; } SegInfo::SegInfo(const object::MachOObjectFile *Obj) { // Build table of sections so segIndex/offset pairs can be translated. uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0; StringRef CurSegName; uint64_t CurSegAddress; for (const SectionRef &Section : Obj->sections()) { SectionInfo Info; if (error(Section.getName(Info.SectionName))) return; Info.Address = Section.getAddress(); Info.Size = Section.getSize(); Info.SegmentName = Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl()); if (!Info.SegmentName.equals(CurSegName)) { ++CurSegIndex; CurSegName = Info.SegmentName; CurSegAddress = Info.Address; } Info.SegmentIndex = CurSegIndex - 1; Info.OffsetInSegment = Info.Address - CurSegAddress; Info.SegmentStartAddress = CurSegAddress; Sections.push_back(Info); } } StringRef SegInfo::segmentName(uint32_t SegIndex) { for (const SectionInfo &SI : Sections) { if (SI.SegmentIndex == SegIndex) return SI.SegmentName; } llvm_unreachable("invalid segIndex"); } const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex, uint64_t OffsetInSeg) { for (const SectionInfo &SI : Sections) { if (SI.SegmentIndex != SegIndex) continue; if (SI.OffsetInSegment > OffsetInSeg) continue; if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size)) continue; return SI; } llvm_unreachable("segIndex and offset not in any section"); } StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) { return findSection(SegIndex, OffsetInSeg).SectionName; } uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) { const SectionInfo &SI = findSection(SegIndex, OffsetInSeg); return SI.SegmentStartAddress + OffsetInSeg; } void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) { // Build table of sections so names can used in final output. SegInfo sectionTable(Obj); outs() << "segment section address type\n"; for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) { uint32_t SegIndex = Entry.segmentIndex(); uint64_t OffsetInSeg = Entry.segmentOffset(); StringRef SegmentName = sectionTable.segmentName(SegIndex); StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg); uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg); // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n", SegmentName.str().c_str(), SectionName.str().c_str(), Address, Entry.typeName().str().c_str()); } } static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) { StringRef DylibName; switch (Ordinal) { case MachO::BIND_SPECIAL_DYLIB_SELF: return "this-image"; case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE: return "main-executable"; case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP: return "flat-namespace"; default: if (Ordinal > 0) { std::error_code EC = Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName); if (EC) return "<<bad library ordinal>>"; return DylibName; } } return "<<unknown special ordinal>>"; } //===----------------------------------------------------------------------===// // bind table dumping //===----------------------------------------------------------------------===// void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) { // Build table of sections so names can used in final output. SegInfo sectionTable(Obj); outs() << "segment section address type " "addend dylib symbol\n"; for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) { uint32_t SegIndex = Entry.segmentIndex(); uint64_t OffsetInSeg = Entry.segmentOffset(); StringRef SegmentName = sectionTable.segmentName(SegIndex); StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg); uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg); // Table lines look like: // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard StringRef Attr; if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT) Attr = " (weak_import)"; outs() << left_justify(SegmentName, 8) << " " << left_justify(SectionName, 18) << " " << format_hex(Address, 10, true) << " " << left_justify(Entry.typeName(), 8) << " " << format_decimal(Entry.addend(), 8) << " " << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " " << Entry.symbolName() << Attr << "\n"; } } //===----------------------------------------------------------------------===// // lazy bind table dumping //===----------------------------------------------------------------------===// void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) { // Build table of sections so names can used in final output. SegInfo sectionTable(Obj); outs() << "segment section address " "dylib symbol\n"; for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) { uint32_t SegIndex = Entry.segmentIndex(); uint64_t OffsetInSeg = Entry.segmentOffset(); StringRef SegmentName = sectionTable.segmentName(SegIndex); StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg); uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg); // Table lines look like: // __DATA __got 0x00012010 libSystem ___stack_chk_guard outs() << left_justify(SegmentName, 8) << " " << left_justify(SectionName, 18) << " " << format_hex(Address, 10, true) << " " << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " " << Entry.symbolName() << "\n"; } } //===----------------------------------------------------------------------===// // weak bind table dumping //===----------------------------------------------------------------------===// void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) { // Build table of sections so names can used in final output. SegInfo sectionTable(Obj); outs() << "segment section address " "type addend symbol\n"; for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) { // Strong symbols don't have a location to update. if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) { outs() << " strong " << Entry.symbolName() << "\n"; continue; } uint32_t SegIndex = Entry.segmentIndex(); uint64_t OffsetInSeg = Entry.segmentOffset(); StringRef SegmentName = sectionTable.segmentName(SegIndex); StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg); uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg); // Table lines look like: // __DATA __data 0x00001000 pointer 0 _foo outs() << left_justify(SegmentName, 8) << " " << left_justify(SectionName, 18) << " " << format_hex(Address, 10, true) << " " << left_justify(Entry.typeName(), 8) << " " << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName() << "\n"; } } // get_dyld_bind_info_symbolname() is used for disassembly and passed an // address, ReferenceValue, in the Mach-O file and looks in the dyld bind // information for that address. If the address is found its binding symbol // name is returned. If not nullptr is returned. static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue, struct DisassembleInfo *info) { if (info->bindtable == nullptr) { info->bindtable = new (BindTable); SegInfo sectionTable(info->O); for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) { uint32_t SegIndex = Entry.segmentIndex(); uint64_t OffsetInSeg = Entry.segmentOffset(); uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg); const char *SymbolName = nullptr; StringRef name = Entry.symbolName(); if (!name.empty()) SymbolName = name.data(); info->bindtable->push_back(std::make_pair(Address, SymbolName)); } } for (bind_table_iterator BI = info->bindtable->begin(), BE = info->bindtable->end(); BI != BE; ++BI) { uint64_t Address = BI->first; if (ReferenceValue == Address) { const char *SymbolName = BI->second; return SymbolName; } } return nullptr; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-objdump/llvm-objdump.h
// // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVM_OBJDUMP_LLVM_OBJDUMP_H #define LLVM_TOOLS_LLVM_OBJDUMP_LLVM_OBJDUMP_H #include "llvm/ADT/StringRef.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/DataTypes.h" namespace llvm { namespace object { class COFFObjectFile; class MachOObjectFile; class ObjectFile; class RelocationRef; } extern cl::opt<std::string> TripleName; extern cl::opt<std::string> ArchName; extern cl::opt<std::string> MCPU; extern cl::list<std::string> MAttrs; extern cl::list<std::string> DumpSections; extern cl::opt<bool> Disassemble; extern cl::opt<bool> NoShowRawInsn; extern cl::opt<bool> PrivateHeaders; extern cl::opt<bool> ExportsTrie; extern cl::opt<bool> Rebase; extern cl::opt<bool> Bind; extern cl::opt<bool> LazyBind; extern cl::opt<bool> WeakBind; extern cl::opt<bool> RawClangAST; extern cl::opt<bool> UniversalHeaders; extern cl::opt<bool> ArchiveHeaders; extern cl::opt<bool> IndirectSymbols; extern cl::opt<bool> DataInCode; extern cl::opt<bool> LinkOptHints; extern cl::opt<bool> InfoPlist; extern cl::opt<bool> DylibsUsed; extern cl::opt<bool> DylibId; extern cl::opt<bool> ObjcMetaData; extern cl::opt<std::string> DisSymName; extern cl::opt<bool> NonVerbose; extern cl::opt<bool> Relocations; extern cl::opt<bool> SectionHeaders; extern cl::opt<bool> SectionContents; extern cl::opt<bool> SymbolTable; extern cl::opt<bool> UnwindInfo; extern cl::opt<bool> PrintImmHex; // Various helper functions. bool error(std::error_code ec); bool RelocAddressLess(object::RelocationRef a, object::RelocationRef b); void ParseInputMachO(StringRef Filename); void printCOFFUnwindInfo(const object::COFFObjectFile* o); void printMachOUnwindInfo(const object::MachOObjectFile* o); void printMachOExportsTrie(const object::MachOObjectFile* o); void printMachORebaseTable(const object::MachOObjectFile* o); void printMachOBindTable(const object::MachOObjectFile* o); void printMachOLazyBindTable(const object::MachOObjectFile* o); void printMachOWeakBindTable(const object::MachOObjectFile* o); void printELFFileHeader(const object::ObjectFile *o); void printCOFFFileHeader(const object::ObjectFile *o); void printMachOFileHeader(const object::ObjectFile *o); void printExportsTrie(const object::ObjectFile *o); void printRebaseTable(const object::ObjectFile *o); void printBindTable(const object::ObjectFile *o); void printLazyBindTable(const object::ObjectFile *o); void printWeakBindTable(const object::ObjectFile *o); void printRawClangAST(const object::ObjectFile *o); void PrintRelocations(const object::ObjectFile *o); void PrintSectionHeaders(const object::ObjectFile *o); void PrintSectionContents(const object::ObjectFile *o); void PrintSymbolTable(const object::ObjectFile *o); } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-objdump/ELFDump.cpp
//===-- ELFDump.cpp - ELF-specific dumper -----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file implements the ELF-specific dumper for llvm-objdump. /// //===----------------------------------------------------------------------===// #include "llvm-objdump.h" #include "llvm/Object/ELFObjectFile.h" #include "llvm/Support/Format.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; using namespace llvm::object; template <class ELFT> void printProgramHeaders(const ELFFile<ELFT> *o) { typedef ELFFile<ELFT> ELFO; outs() << "Program Header:\n"; for (typename ELFO::Elf_Phdr_Iter pi = o->program_header_begin(), pe = o->program_header_end(); pi != pe; ++pi) { switch (pi->p_type) { case ELF::PT_LOAD: outs() << " LOAD "; break; case ELF::PT_GNU_STACK: outs() << " STACK "; break; case ELF::PT_GNU_EH_FRAME: outs() << "EH_FRAME "; break; case ELF::PT_INTERP: outs() << " INTERP "; break; case ELF::PT_DYNAMIC: outs() << " DYNAMIC "; break; case ELF::PT_PHDR: outs() << " PHDR "; break; case ELF::PT_TLS: outs() << " TLS "; break; default: outs() << " UNKNOWN "; } const char *Fmt = ELFT::Is64Bits ? "0x%016" PRIx64 " " : "0x%08" PRIx64 " "; outs() << "off " << format(Fmt, (uint64_t)pi->p_offset) << "vaddr " << format(Fmt, (uint64_t)pi->p_vaddr) << "paddr " << format(Fmt, (uint64_t)pi->p_paddr) << format("align 2**%u\n", countTrailingZeros<uint64_t>(pi->p_align)) << " filesz " << format(Fmt, (uint64_t)pi->p_filesz) << "memsz " << format(Fmt, (uint64_t)pi->p_memsz) << "flags " << ((pi->p_flags & ELF::PF_R) ? "r" : "-") << ((pi->p_flags & ELF::PF_W) ? "w" : "-") << ((pi->p_flags & ELF::PF_X) ? "x" : "-") << "\n"; } outs() << "\n"; } void llvm::printELFFileHeader(const object::ObjectFile *Obj) { // Little-endian 32-bit if (const ELF32LEObjectFile *ELFObj = dyn_cast<ELF32LEObjectFile>(Obj)) printProgramHeaders(ELFObj->getELFFile()); // Big-endian 32-bit if (const ELF32BEObjectFile *ELFObj = dyn_cast<ELF32BEObjectFile>(Obj)) printProgramHeaders(ELFObj->getELFFile()); // Little-endian 64-bit if (const ELF64LEObjectFile *ELFObj = dyn_cast<ELF64LEObjectFile>(Obj)) printProgramHeaders(ELFObj->getELFFile()); // Big-endian 64-bit if (const ELF64BEObjectFile *ELFObj = dyn_cast<ELF64BEObjectFile>(Obj)) printProgramHeaders(ELFObj->getELFFile()); }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-objdump/CMakeLists.txt
set(LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} CodeGen DebugInfoDWARF MC MCDisassembler Object Support ) add_llvm_tool(llvm-objdump llvm-objdump.cpp COFFDump.cpp ELFDump.cpp MachODump.cpp )
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-objdump/llvm-objdump.cpp
//===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program is a utility that works like binutils "objdump", that is, it // dumps out a plethora of information about an object file depending on the // flags. // // The flags and output of this program should be near identical to those of // binutils objdump. // //===----------------------------------------------------------------------===// #include "llvm-objdump.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/Triple.h" #include "llvm/CodeGen/FaultMaps.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCDisassembler.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCInstPrinter.h" #include "llvm/MC/MCInstrAnalysis.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCRelocationInfo.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/Object/Archive.h" #include "llvm/Object/ELFObjectFile.h" #include "llvm/Object/COFF.h" #include "llvm/Object/MachO.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Errc.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Format.h" #include "llvm/Support/GraphWriter.h" #include "llvm/Support/Host.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cctype> #include <cstring> #include <system_error> using namespace llvm; using namespace object; static cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore); cl::opt<bool> llvm::Disassemble("disassemble", cl::desc("Display assembler mnemonics for the machine instructions")); static cl::alias Disassembled("d", cl::desc("Alias for --disassemble"), cl::aliasopt(Disassemble)); cl::opt<bool> llvm::Relocations("r", cl::desc("Display the relocation entries in the file")); cl::opt<bool> llvm::SectionContents("s", cl::desc("Display the content of each section")); cl::opt<bool> llvm::SymbolTable("t", cl::desc("Display the symbol table")); cl::opt<bool> llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols")); cl::opt<bool> llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info")); cl::opt<bool> llvm::Bind("bind", cl::desc("Display mach-o binding info")); cl::opt<bool> llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info")); cl::opt<bool> llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info")); cl::opt<bool> llvm::RawClangAST("raw-clang-ast", cl::desc("Dump the raw binary contents of the clang AST section")); static cl::opt<bool> MachOOpt("macho", cl::desc("Use MachO specific object file parser")); static cl::alias MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt)); cl::opt<std::string> llvm::TripleName("triple", cl::desc("Target triple to disassemble for, " "see -version for available targets")); cl::opt<std::string> llvm::MCPU("mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"), cl::value_desc("cpu-name"), cl::init("")); cl::opt<std::string> llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, " "see -version for available targets")); cl::opt<bool> llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the " "headers for each section.")); static cl::alias SectionHeadersShort("headers", cl::desc("Alias for --section-headers"), cl::aliasopt(SectionHeaders)); static cl::alias SectionHeadersShorter("h", cl::desc("Alias for --section-headers"), cl::aliasopt(SectionHeaders)); cl::list<std::string> llvm::MAttrs("mattr", cl::CommaSeparated, cl::desc("Target specific attributes"), cl::value_desc("a1,+a2,-a3,...")); cl::opt<bool> llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling " "instructions, do not print " "the instruction bytes.")); cl::opt<bool> llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information")); static cl::alias UnwindInfoShort("u", cl::desc("Alias for --unwind-info"), cl::aliasopt(UnwindInfo)); cl::opt<bool> llvm::PrivateHeaders("private-headers", cl::desc("Display format specific file headers")); static cl::alias PrivateHeadersShort("p", cl::desc("Alias for --private-headers"), cl::aliasopt(PrivateHeaders)); cl::opt<bool> llvm::PrintImmHex("print-imm-hex", cl::desc("Use hex format for immediate values")); cl::opt<bool> PrintFaultMaps("fault-map-section", cl::desc("Display contents of faultmap section")); static StringRef ToolName; static int ReturnValue = EXIT_SUCCESS; bool llvm::error(std::error_code EC) { if (!EC) return false; outs() << ToolName << ": error reading file: " << EC.message() << ".\n"; outs().flush(); ReturnValue = EXIT_FAILURE; return true; } static void report_error(StringRef File, std::error_code EC) { assert(EC); errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n"; ReturnValue = EXIT_FAILURE; } static const Target *getTarget(const ObjectFile *Obj = nullptr) { // Figure out the target triple. llvm::Triple TheTriple("unknown-unknown-unknown"); if (TripleName.empty()) { if (Obj) { TheTriple.setArch(Triple::ArchType(Obj->getArch())); // TheTriple defaults to ELF, and COFF doesn't have an environment: // the best we can do here is indicate that it is mach-o. if (Obj->isMachO()) TheTriple.setObjectFormat(Triple::MachO); if (Obj->isCOFF()) { const auto COFFObj = dyn_cast<COFFObjectFile>(Obj); if (COFFObj->getArch() == Triple::thumb) TheTriple.setTriple("thumbv7-windows"); } } } else TheTriple.setTriple(Triple::normalize(TripleName)); // Get the target specific parser. std::string Error; const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple, Error); if (!TheTarget) { errs() << ToolName << ": " << Error; return nullptr; } // Update the triple name and return the found target. TripleName = TheTriple.getTriple(); return TheTarget; } bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) { return a.getOffset() < b.getOffset(); } namespace { class PrettyPrinter { public: virtual ~PrettyPrinter(){} virtual void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, uint64_t Address, raw_ostream &OS, StringRef Annot, MCSubtargetInfo const &STI) { outs() << format("%8" PRIx64 ":", Address); if (!NoShowRawInsn) { outs() << "\t"; dumpBytes(Bytes, outs()); } IP.printInst(MI, outs(), "", STI); } }; PrettyPrinter PrettyPrinterInst; class HexagonPrettyPrinter : public PrettyPrinter { public: void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address, raw_ostream &OS) { uint32_t opcode = (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0]; OS << format("%8" PRIx64 ":", Address); if (!NoShowRawInsn) { OS << "\t"; dumpBytes(Bytes.slice(0, 4), OS); OS << format("%08" PRIx32, opcode); } } void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, uint64_t Address, raw_ostream &OS, StringRef Annot, MCSubtargetInfo const &STI) override { std::string Buffer; { raw_string_ostream TempStream(Buffer); IP.printInst(MI, TempStream, "", STI); } StringRef Contents(Buffer); // Split off bundle attributes auto PacketBundle = Contents.rsplit('\n'); // Split off first instruction from the rest auto HeadTail = PacketBundle.first.split('\n'); auto Preamble = " { "; auto Separator = ""; while(!HeadTail.first.empty()) { OS << Separator; Separator = "\n"; printLead(Bytes, Address, OS); OS << Preamble; Preamble = " "; StringRef Inst; auto Duplex = HeadTail.first.split('\v'); if(!Duplex.second.empty()){ OS << Duplex.first; OS << "; "; Inst = Duplex.second; } else Inst = HeadTail.first; OS << Inst; Bytes = Bytes.slice(4); Address += 4; HeadTail = HeadTail.second.split('\n'); } OS << " } " << PacketBundle.second; } }; HexagonPrettyPrinter HexagonPrettyPrinterInst; PrettyPrinter &selectPrettyPrinter(Triple const &Triple) { switch(Triple.getArch()) { default: return PrettyPrinterInst; case Triple::hexagon: return HexagonPrettyPrinterInst; } } } template <class ELFT> static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj, DataRefImpl Rel, SmallVectorImpl<char> &Result) { typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym; typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr; typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel; typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela; const ELFFile<ELFT> &EF = *Obj->getELFFile(); ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a); if (std::error_code EC = SecOrErr.getError()) return EC; const Elf_Shdr *Sec = *SecOrErr; ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link); if (std::error_code EC = SymTabOrErr.getError()) return EC; const Elf_Shdr *SymTab = *SymTabOrErr; assert(SymTab->sh_type == ELF::SHT_SYMTAB || SymTab->sh_type == ELF::SHT_DYNSYM); ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link); if (std::error_code EC = StrTabSec.getError()) return EC; ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec); if (std::error_code EC = StrTabOrErr.getError()) return EC; StringRef StrTab = *StrTabOrErr; uint8_t type; StringRef res; int64_t addend = 0; uint16_t symbol_index = 0; switch (Sec->sh_type) { default: return object_error::parse_failed; case ELF::SHT_REL: { const Elf_Rel *ERel = Obj->getRel(Rel); type = ERel->getType(EF.isMips64EL()); symbol_index = ERel->getSymbol(EF.isMips64EL()); // TODO: Read implicit addend from section data. break; } case ELF::SHT_RELA: { const Elf_Rela *ERela = Obj->getRela(Rel); type = ERela->getType(EF.isMips64EL()); symbol_index = ERela->getSymbol(EF.isMips64EL()); addend = ERela->r_addend; break; } } const Elf_Sym *symb = EF.template getEntry<Elf_Sym>(Sec->sh_link, symbol_index); StringRef Target; ErrorOr<const Elf_Shdr *> SymSec = EF.getSection(symb); if (std::error_code EC = SymSec.getError()) return EC; if (symb->getType() == ELF::STT_SECTION) { ErrorOr<StringRef> SecName = EF.getSectionName(*SymSec); if (std::error_code EC = SecName.getError()) return EC; Target = *SecName; } else { ErrorOr<StringRef> SymName = symb->getName(StrTab); if (!SymName) return SymName.getError(); Target = *SymName; } switch (EF.getHeader()->e_machine) { case ELF::EM_X86_64: switch (type) { case ELF::R_X86_64_PC8: case ELF::R_X86_64_PC16: case ELF::R_X86_64_PC32: { std::string fmtbuf; raw_string_ostream fmt(fmtbuf); fmt << Target << (addend < 0 ? "" : "+") << addend << "-P"; fmt.flush(); Result.append(fmtbuf.begin(), fmtbuf.end()); } break; case ELF::R_X86_64_8: case ELF::R_X86_64_16: case ELF::R_X86_64_32: case ELF::R_X86_64_32S: case ELF::R_X86_64_64: { std::string fmtbuf; raw_string_ostream fmt(fmtbuf); fmt << Target << (addend < 0 ? "" : "+") << addend; fmt.flush(); Result.append(fmtbuf.begin(), fmtbuf.end()); } break; default: res = "Unknown"; } break; case ELF::EM_AARCH64: { std::string fmtbuf; raw_string_ostream fmt(fmtbuf); fmt << Target; if (addend != 0) fmt << (addend < 0 ? "" : "+") << addend; fmt.flush(); Result.append(fmtbuf.begin(), fmtbuf.end()); break; } case ELF::EM_386: case ELF::EM_ARM: case ELF::EM_HEXAGON: case ELF::EM_MIPS: res = Target; break; default: res = "Unknown"; } if (Result.empty()) Result.append(res.begin(), res.end()); return std::error_code(); } static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj, const RelocationRef &RelRef, SmallVectorImpl<char> &Result) { DataRefImpl Rel = RelRef.getRawDataRefImpl(); if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj)) return getRelocationValueString(ELF32LE, Rel, Result); if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj)) return getRelocationValueString(ELF64LE, Rel, Result); if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj)) return getRelocationValueString(ELF32BE, Rel, Result); auto *ELF64BE = cast<ELF64BEObjectFile>(Obj); return getRelocationValueString(ELF64BE, Rel, Result); } static std::error_code getRelocationValueString(const COFFObjectFile *Obj, const RelocationRef &Rel, SmallVectorImpl<char> &Result) { symbol_iterator SymI = Rel.getSymbol(); ErrorOr<StringRef> SymNameOrErr = SymI->getName(); if (std::error_code EC = SymNameOrErr.getError()) return EC; StringRef SymName = *SymNameOrErr; Result.append(SymName.begin(), SymName.end()); return std::error_code(); } static void printRelocationTargetName(const MachOObjectFile *O, const MachO::any_relocation_info &RE, raw_string_ostream &fmt) { bool IsScattered = O->isRelocationScattered(RE); // Target of a scattered relocation is an address. In the interest of // generating pretty output, scan through the symbol table looking for a // symbol that aligns with that address. If we find one, print it. // Otherwise, we just print the hex address of the target. if (IsScattered) { uint32_t Val = O->getPlainRelocationSymbolNum(RE); for (const SymbolRef &Symbol : O->symbols()) { std::error_code ec; ErrorOr<uint64_t> Addr = Symbol.getAddress(); if ((ec = Addr.getError())) report_fatal_error(ec.message()); if (*Addr != Val) continue; ErrorOr<StringRef> Name = Symbol.getName(); if (std::error_code EC = Name.getError()) report_fatal_error(EC.message()); fmt << *Name; return; } // If we couldn't find a symbol that this relocation refers to, try // to find a section beginning instead. for (const SectionRef &Section : O->sections()) { std::error_code ec; StringRef Name; uint64_t Addr = Section.getAddress(); if (Addr != Val) continue; if ((ec = Section.getName(Name))) report_fatal_error(ec.message()); fmt << Name; return; } fmt << format("0x%x", Val); return; } StringRef S; bool isExtern = O->getPlainRelocationExternal(RE); uint64_t Val = O->getPlainRelocationSymbolNum(RE); if (isExtern) { symbol_iterator SI = O->symbol_begin(); advance(SI, Val); ErrorOr<StringRef> SOrErr = SI->getName(); if (!error(SOrErr.getError())) S = *SOrErr; } else { section_iterator SI = O->section_begin(); // Adjust for the fact that sections are 1-indexed. advance(SI, Val - 1); SI->getName(S); } fmt << S; } static std::error_code getRelocationValueString(const MachOObjectFile *Obj, const RelocationRef &RelRef, SmallVectorImpl<char> &Result) { DataRefImpl Rel = RelRef.getRawDataRefImpl(); MachO::any_relocation_info RE = Obj->getRelocation(Rel); unsigned Arch = Obj->getArch(); std::string fmtbuf; raw_string_ostream fmt(fmtbuf); unsigned Type = Obj->getAnyRelocationType(RE); bool IsPCRel = Obj->getAnyRelocationPCRel(RE); // Determine any addends that should be displayed with the relocation. // These require decoding the relocation type, which is triple-specific. // X86_64 has entirely custom relocation types. if (Arch == Triple::x86_64) { bool isPCRel = Obj->getAnyRelocationPCRel(RE); switch (Type) { case MachO::X86_64_RELOC_GOT_LOAD: case MachO::X86_64_RELOC_GOT: { printRelocationTargetName(Obj, RE, fmt); fmt << "@GOT"; if (isPCRel) fmt << "PCREL"; break; } case MachO::X86_64_RELOC_SUBTRACTOR: { DataRefImpl RelNext = Rel; Obj->moveRelocationNext(RelNext); MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type // X86_64_RELOC_UNSIGNED. // NOTE: Scattered relocations don't exist on x86_64. unsigned RType = Obj->getAnyRelocationType(RENext); if (RType != MachO::X86_64_RELOC_UNSIGNED) report_fatal_error("Expected X86_64_RELOC_UNSIGNED after " "X86_64_RELOC_SUBTRACTOR."); // The X86_64_RELOC_UNSIGNED contains the minuend symbol; // X86_64_RELOC_SUBTRACTOR contains the subtrahend. printRelocationTargetName(Obj, RENext, fmt); fmt << "-"; printRelocationTargetName(Obj, RE, fmt); break; } case MachO::X86_64_RELOC_TLV: printRelocationTargetName(Obj, RE, fmt); fmt << "@TLV"; if (isPCRel) fmt << "P"; break; case MachO::X86_64_RELOC_SIGNED_1: printRelocationTargetName(Obj, RE, fmt); fmt << "-1"; break; case MachO::X86_64_RELOC_SIGNED_2: printRelocationTargetName(Obj, RE, fmt); fmt << "-2"; break; case MachO::X86_64_RELOC_SIGNED_4: printRelocationTargetName(Obj, RE, fmt); fmt << "-4"; break; default: printRelocationTargetName(Obj, RE, fmt); break; } // X86 and ARM share some relocation types in common. } else if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) { // Generic relocation types... switch (Type) { case MachO::GENERIC_RELOC_PAIR: // prints no info return std::error_code(); case MachO::GENERIC_RELOC_SECTDIFF: { DataRefImpl RelNext = Rel; Obj->moveRelocationNext(RelNext); MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); // X86 sect diff's must be followed by a relocation of type // GENERIC_RELOC_PAIR. unsigned RType = Obj->getAnyRelocationType(RENext); if (RType != MachO::GENERIC_RELOC_PAIR) report_fatal_error("Expected GENERIC_RELOC_PAIR after " "GENERIC_RELOC_SECTDIFF."); printRelocationTargetName(Obj, RE, fmt); fmt << "-"; printRelocationTargetName(Obj, RENext, fmt); break; } } if (Arch == Triple::x86 || Arch == Triple::ppc) { switch (Type) { case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: { DataRefImpl RelNext = Rel; Obj->moveRelocationNext(RelNext); MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); // X86 sect diff's must be followed by a relocation of type // GENERIC_RELOC_PAIR. unsigned RType = Obj->getAnyRelocationType(RENext); if (RType != MachO::GENERIC_RELOC_PAIR) report_fatal_error("Expected GENERIC_RELOC_PAIR after " "GENERIC_RELOC_LOCAL_SECTDIFF."); printRelocationTargetName(Obj, RE, fmt); fmt << "-"; printRelocationTargetName(Obj, RENext, fmt); break; } case MachO::GENERIC_RELOC_TLV: { printRelocationTargetName(Obj, RE, fmt); fmt << "@TLV"; if (IsPCRel) fmt << "P"; break; } default: printRelocationTargetName(Obj, RE, fmt); } } else { // ARM-specific relocations switch (Type) { case MachO::ARM_RELOC_HALF: case MachO::ARM_RELOC_HALF_SECTDIFF: { // Half relocations steal a bit from the length field to encode // whether this is an upper16 or a lower16 relocation. bool isUpper = Obj->getAnyRelocationLength(RE) >> 1; if (isUpper) fmt << ":upper16:("; else fmt << ":lower16:("; printRelocationTargetName(Obj, RE, fmt); DataRefImpl RelNext = Rel; Obj->moveRelocationNext(RelNext); MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); // ARM half relocs must be followed by a relocation of type // ARM_RELOC_PAIR. unsigned RType = Obj->getAnyRelocationType(RENext); if (RType != MachO::ARM_RELOC_PAIR) report_fatal_error("Expected ARM_RELOC_PAIR after " "ARM_RELOC_HALF"); // NOTE: The half of the target virtual address is stashed in the // address field of the secondary relocation, but we can't reverse // engineer the constant offset from it without decoding the movw/movt // instruction to find the other half in its immediate field. // ARM_RELOC_HALF_SECTDIFF encodes the second section in the // symbol/section pointer of the follow-on relocation. if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) { fmt << "-"; printRelocationTargetName(Obj, RENext, fmt); } fmt << ")"; break; } default: { printRelocationTargetName(Obj, RE, fmt); } } } } else printRelocationTargetName(Obj, RE, fmt); fmt.flush(); Result.append(fmtbuf.begin(), fmtbuf.end()); return std::error_code(); } static std::error_code getRelocationValueString(const RelocationRef &Rel, SmallVectorImpl<char> &Result) { const ObjectFile *Obj = Rel.getObject(); if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj)) return getRelocationValueString(ELF, Rel, Result); if (auto *COFF = dyn_cast<COFFObjectFile>(Obj)) return getRelocationValueString(COFF, Rel, Result); auto *MachO = cast<MachOObjectFile>(Obj); return getRelocationValueString(MachO, Rel, Result); } /// @brief Indicates whether this relocation should hidden when listing /// relocations, usually because it is the trailing part of a multipart /// relocation that will be printed as part of the leading relocation. static bool getHidden(RelocationRef RelRef) { const ObjectFile *Obj = RelRef.getObject(); auto *MachO = dyn_cast<MachOObjectFile>(Obj); if (!MachO) return false; unsigned Arch = MachO->getArch(); DataRefImpl Rel = RelRef.getRawDataRefImpl(); uint64_t Type = MachO->getRelocationType(Rel); // On arches that use the generic relocations, GENERIC_RELOC_PAIR // is always hidden. if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) { if (Type == MachO::GENERIC_RELOC_PAIR) return true; } else if (Arch == Triple::x86_64) { // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows // an X86_64_RELOC_SUBTRACTOR. if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) { DataRefImpl RelPrev = Rel; RelPrev.d.a--; uint64_t PrevType = MachO->getRelocationType(RelPrev); if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR) return true; } } return false; } static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) { const Target *TheTarget = getTarget(Obj); // getTarget() will have already issued a diagnostic if necessary, so // just bail here if it failed. if (!TheTarget) return; // Package up features to be passed to target/subtarget std::string FeaturesStr; if (MAttrs.size()) { SubtargetFeatures Features; for (unsigned i = 0; i != MAttrs.size(); ++i) Features.AddFeature(MAttrs[i]); FeaturesStr = Features.getString(); } std::unique_ptr<const MCRegisterInfo> MRI( TheTarget->createMCRegInfo(TripleName)); if (!MRI) { errs() << "error: no register info for target " << TripleName << "\n"; return; } // Set up disassembler. std::unique_ptr<const MCAsmInfo> AsmInfo( TheTarget->createMCAsmInfo(*MRI, TripleName)); if (!AsmInfo) { errs() << "error: no assembly info for target " << TripleName << "\n"; return; } std::unique_ptr<const MCSubtargetInfo> STI( TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr)); if (!STI) { errs() << "error: no subtarget info for target " << TripleName << "\n"; return; } std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo()); if (!MII) { errs() << "error: no instruction info for target " << TripleName << "\n"; return; } std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo); MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get()); std::unique_ptr<MCDisassembler> DisAsm( TheTarget->createMCDisassembler(*STI, Ctx)); if (!DisAsm) { errs() << "error: no disassembler for target " << TripleName << "\n"; return; } std::unique_ptr<const MCInstrAnalysis> MIA( TheTarget->createMCInstrAnalysis(MII.get())); int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI)); if (!IP) { errs() << "error: no instruction printer for target " << TripleName << '\n'; return; } IP->setPrintImmHex(PrintImmHex); PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName)); StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " : "\t\t\t%08" PRIx64 ": "; // Create a mapping, RelocSecs = SectionRelocMap[S], where sections // in RelocSecs contain the relocations for section S. std::error_code EC; std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap; for (const SectionRef &Section : Obj->sections()) { section_iterator Sec2 = Section.getRelocatedSection(); if (Sec2 != Obj->section_end()) SectionRelocMap[*Sec2].push_back(Section); } // Create a mapping from virtual address to symbol name. This is used to // pretty print the target of a call. std::vector<std::pair<uint64_t, StringRef>> AllSymbols; if (MIA) { for (const SymbolRef &Symbol : Obj->symbols()) { if (Symbol.getType() != SymbolRef::ST_Function) continue; ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress(); if (error(AddressOrErr.getError())) break; uint64_t Address = *AddressOrErr; ErrorOr<StringRef> Name = Symbol.getName(); if (error(Name.getError())) break; if (Name->empty()) continue; AllSymbols.push_back(std::make_pair(Address, *Name)); } array_pod_sort(AllSymbols.begin(), AllSymbols.end()); } for (const SectionRef &Section : Obj->sections()) { if (!Section.isText() || Section.isVirtual()) continue; uint64_t SectionAddr = Section.getAddress(); uint64_t SectSize = Section.getSize(); if (!SectSize) continue; // Make a list of all the symbols in this section. std::vector<std::pair<uint64_t, StringRef>> Symbols; for (const SymbolRef &Symbol : Obj->symbols()) { if (Section.containsSymbol(Symbol)) { ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress(); if (error(AddressOrErr.getError())) break; uint64_t Address = *AddressOrErr; Address -= SectionAddr; if (Address >= SectSize) continue; ErrorOr<StringRef> Name = Symbol.getName(); if (error(Name.getError())) break; Symbols.push_back(std::make_pair(Address, *Name)); } } // Sort the symbols by address, just in case they didn't come in that way. array_pod_sort(Symbols.begin(), Symbols.end()); // Make a list of all the relocations for this section. std::vector<RelocationRef> Rels; if (InlineRelocs) { for (const SectionRef &RelocSec : SectionRelocMap[Section]) { for (const RelocationRef &Reloc : RelocSec.relocations()) { Rels.push_back(Reloc); } } } // Sort relocations by address. std::sort(Rels.begin(), Rels.end(), RelocAddressLess); StringRef SegmentName = ""; if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) { DataRefImpl DR = Section.getRawDataRefImpl(); SegmentName = MachO->getSectionFinalSegmentName(DR); } StringRef name; if (error(Section.getName(name))) break; outs() << "Disassembly of section "; if (!SegmentName.empty()) outs() << SegmentName << ","; outs() << name << ':'; // If the section has no symbol at the start, just insert a dummy one. if (Symbols.empty() || Symbols[0].first != 0) Symbols.insert(Symbols.begin(), std::make_pair(0, name)); SmallString<40> Comments; raw_svector_ostream CommentStream(Comments); StringRef BytesStr; if (error(Section.getContents(BytesStr))) break; ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()), BytesStr.size()); uint64_t Size; uint64_t Index; std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin(); std::vector<RelocationRef>::const_iterator rel_end = Rels.end(); // Disassemble symbol by symbol. for (unsigned si = 0, se = Symbols.size(); si != se; ++si) { uint64_t Start = Symbols[si].first; // The end is either the section end or the beginning of the next symbol. uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first; // If this symbol has the same address as the next symbol, then skip it. if (Start == End) continue; outs() << '\n' << Symbols[si].second << ":\n"; #ifndef NDEBUG raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls(); #else raw_ostream &DebugOut = nulls(); #endif for (Index = Start; Index < End; Index += Size) { MCInst Inst; if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), SectionAddr + Index, DebugOut, CommentStream)) { PIP.printInst(*IP, &Inst, Bytes.slice(Index, Size), SectionAddr + Index, outs(), "", *STI); outs() << CommentStream.str(); Comments.clear(); if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) || MIA->isConditionalBranch(Inst))) { uint64_t Target; if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) { auto TargetSym = std::upper_bound( AllSymbols.begin(), AllSymbols.end(), Target, [](uint64_t LHS, const std::pair<uint64_t, StringRef> &RHS) { return LHS < RHS.first; }); if (TargetSym != AllSymbols.begin()) --TargetSym; else TargetSym = AllSymbols.end(); if (TargetSym != AllSymbols.end()) { outs() << " <" << TargetSym->second; uint64_t Disp = Target - TargetSym->first; if (Disp) outs() << '+' << utohexstr(Disp); outs() << '>'; } } } outs() << "\n"; } else { errs() << ToolName << ": warning: invalid instruction encoding\n"; if (Size == 0) Size = 1; // skip illegible bytes } // Print relocation for instruction. while (rel_cur != rel_end) { bool hidden = getHidden(*rel_cur); uint64_t addr = rel_cur->getOffset(); SmallString<16> name; SmallString<32> val; // If this relocation is hidden, skip it. if (hidden) goto skip_print_rel; // Stop when rel_cur's address is past the current instruction. if (addr >= Index + Size) break; rel_cur->getTypeName(name); if (error(getRelocationValueString(*rel_cur, val))) goto skip_print_rel; outs() << format(Fmt.data(), SectionAddr + addr) << name << "\t" << val << "\n"; skip_print_rel: ++rel_cur; } } } } } void llvm::PrintRelocations(const ObjectFile *Obj) { StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; // Regular objdump doesn't print relocations in non-relocatable object // files. if (!Obj->isRelocatableObject()) return; for (const SectionRef &Section : Obj->sections()) { if (Section.relocation_begin() == Section.relocation_end()) continue; StringRef secname; if (error(Section.getName(secname))) continue; outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n"; for (const RelocationRef &Reloc : Section.relocations()) { bool hidden = getHidden(Reloc); uint64_t address = Reloc.getOffset(); SmallString<32> relocname; SmallString<32> valuestr; if (hidden) continue; Reloc.getTypeName(relocname); if (error(getRelocationValueString(Reloc, valuestr))) continue; outs() << format(Fmt.data(), address) << " " << relocname << " " << valuestr << "\n"; } outs() << "\n"; } } void llvm::PrintSectionHeaders(const ObjectFile *Obj) { outs() << "Sections:\n" "Idx Name Size Address Type\n"; unsigned i = 0; for (const SectionRef &Section : Obj->sections()) { StringRef Name; if (error(Section.getName(Name))) return; uint64_t Address = Section.getAddress(); uint64_t Size = Section.getSize(); bool Text = Section.isText(); bool Data = Section.isData(); bool BSS = Section.isBSS(); std::string Type = (std::string(Text ? "TEXT " : "") + (Data ? "DATA " : "") + (BSS ? "BSS" : "")); outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i, Name.str().c_str(), Size, Address, Type.c_str()); ++i; } } void llvm::PrintSectionContents(const ObjectFile *Obj) { std::error_code EC; for (const SectionRef &Section : Obj->sections()) { StringRef Name; StringRef Contents; if (error(Section.getName(Name))) continue; uint64_t BaseAddr = Section.getAddress(); uint64_t Size = Section.getSize(); if (!Size) continue; outs() << "Contents of section " << Name << ":\n"; if (Section.isBSS()) { outs() << format("<skipping contents of bss section at [%04" PRIx64 ", %04" PRIx64 ")>\n", BaseAddr, BaseAddr + Size); continue; } if (error(Section.getContents(Contents))) continue; // Dump out the content as hex and printable ascii characters. for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) { outs() << format(" %04" PRIx64 " ", BaseAddr + addr); // Dump line of hex. for (std::size_t i = 0; i < 16; ++i) { if (i != 0 && i % 4 == 0) outs() << ' '; if (addr + i < end) outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true) << hexdigit(Contents[addr + i] & 0xF, true); else outs() << " "; } // Print ascii. outs() << " "; for (std::size_t i = 0; i < 16 && addr + i < end; ++i) { if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF)) outs() << Contents[addr + i]; else outs() << "."; } outs() << "\n"; } } } static void PrintCOFFSymbolTable(const COFFObjectFile *coff) { for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) { ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI); StringRef Name; if (error(Symbol.getError())) return; if (error(coff->getSymbolName(*Symbol, Name))) return; outs() << "[" << format("%2d", SI) << "]" << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")" << "(fl 0x00)" // Flag bits, which COFF doesn't have. << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")" << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") " << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") " << "0x" << format("%08x", unsigned(Symbol->getValue())) << " " << Name << "\n"; for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) { if (Symbol->isSectionDefinition()) { const coff_aux_section_definition *asd; if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd))) return; int32_t AuxNumber = asd->getNumber(Symbol->isBigObj()); outs() << "AUX " << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x " , unsigned(asd->Length) , unsigned(asd->NumberOfRelocations) , unsigned(asd->NumberOfLinenumbers) , unsigned(asd->CheckSum)) << format("assoc %d comdat %d\n" , unsigned(AuxNumber) , unsigned(asd->Selection)); } else if (Symbol->isFileRecord()) { const char *FileName; if (error(coff->getAuxSymbol<char>(SI + 1, FileName))) return; StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() * coff->getSymbolTableEntrySize()); outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n'; SI = SI + Symbol->getNumberOfAuxSymbols(); break; } else { outs() << "AUX Unknown\n"; } } } } void llvm::PrintSymbolTable(const ObjectFile *o) { outs() << "SYMBOL TABLE:\n"; if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) { PrintCOFFSymbolTable(coff); return; } for (const SymbolRef &Symbol : o->symbols()) { ErrorOr<uint64_t> AddressOrError = Symbol.getAddress(); if (error(AddressOrError.getError())) continue; uint64_t Address = *AddressOrError; SymbolRef::Type Type = Symbol.getType(); uint32_t Flags = Symbol.getFlags(); section_iterator Section = o->section_end(); if (error(Symbol.getSection(Section))) continue; StringRef Name; if (Type == SymbolRef::ST_Debug && Section != o->section_end()) { Section->getName(Name); } else { ErrorOr<StringRef> NameOrErr = Symbol.getName(); if (error(NameOrErr.getError())) continue; Name = *NameOrErr; } bool Global = Flags & SymbolRef::SF_Global; bool Weak = Flags & SymbolRef::SF_Weak; bool Absolute = Flags & SymbolRef::SF_Absolute; bool Common = Flags & SymbolRef::SF_Common; bool Hidden = Flags & SymbolRef::SF_Hidden; char GlobLoc = ' '; if (Type != SymbolRef::ST_Unknown) GlobLoc = Global ? 'g' : 'l'; char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) ? 'd' : ' '; char FileFunc = ' '; if (Type == SymbolRef::ST_File) FileFunc = 'f'; else if (Type == SymbolRef::ST_Function) FileFunc = 'F'; const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; outs() << format(Fmt, Address) << " " << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' << (Weak ? 'w' : ' ') // Weak? << ' ' // Constructor. Not supported yet. << ' ' // Warning. Not supported yet. << ' ' // Indirect reference to another symbol. << Debug // Debugging (d) or dynamic (D) symbol. << FileFunc // Name of function (F), file (f) or object (O). << ' '; if (Absolute) { outs() << "*ABS*"; } else if (Common) { outs() << "*COM*"; } else if (Section == o->section_end()) { outs() << "*UND*"; } else { if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(o)) { DataRefImpl DR = Section->getRawDataRefImpl(); StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); outs() << SegmentName << ","; } StringRef SectionName; if (error(Section->getName(SectionName))) SectionName = ""; outs() << SectionName; } outs() << '\t'; if (Common || isa<ELFObjectFileBase>(o)) { uint64_t Val = Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize(); outs() << format("\t %08" PRIx64 " ", Val); } if (Hidden) { outs() << ".hidden "; } outs() << Name << '\n'; } } static void PrintUnwindInfo(const ObjectFile *o) { outs() << "Unwind info:\n\n"; if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) { printCOFFUnwindInfo(coff); } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) printMachOUnwindInfo(MachO); else { // TODO: Extract DWARF dump tool to objdump. errs() << "This operation is only currently supported " "for COFF and MachO object files.\n"; return; } } void llvm::printExportsTrie(const ObjectFile *o) { outs() << "Exports trie:\n"; if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) printMachOExportsTrie(MachO); else { errs() << "This operation is only currently supported " "for Mach-O executable files.\n"; return; } } void llvm::printRebaseTable(const ObjectFile *o) { outs() << "Rebase table:\n"; if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) printMachORebaseTable(MachO); else { errs() << "This operation is only currently supported " "for Mach-O executable files.\n"; return; } } void llvm::printBindTable(const ObjectFile *o) { outs() << "Bind table:\n"; if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) printMachOBindTable(MachO); else { errs() << "This operation is only currently supported " "for Mach-O executable files.\n"; return; } } void llvm::printLazyBindTable(const ObjectFile *o) { outs() << "Lazy bind table:\n"; if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) printMachOLazyBindTable(MachO); else { errs() << "This operation is only currently supported " "for Mach-O executable files.\n"; return; } } void llvm::printWeakBindTable(const ObjectFile *o) { outs() << "Weak bind table:\n"; if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) printMachOWeakBindTable(MachO); else { errs() << "This operation is only currently supported " "for Mach-O executable files.\n"; return; } } /// Dump the raw contents of the __clangast section so the output can be piped /// into llvm-bcanalyzer. void llvm::printRawClangAST(const ObjectFile *Obj) { if (outs().is_displayed()) { errs() << "The -raw-clang-ast option will dump the raw binary contents of " "the clang ast section.\n" "Please redirect the output to a file or another program such as " "llvm-bcanalyzer.\n"; return; } StringRef ClangASTSectionName("__clangast"); if (isa<COFFObjectFile>(Obj)) { ClangASTSectionName = "clangast"; } Optional<object::SectionRef> ClangASTSection; for (auto Sec : Obj->sections()) { StringRef Name; Sec.getName(Name); if (Name == ClangASTSectionName) { ClangASTSection = Sec; break; } } if (!ClangASTSection) return; StringRef ClangASTContents; if (error(ClangASTSection.getValue().getContents(ClangASTContents))) { errs() << "Could not read the " << ClangASTSectionName << " section!\n"; return; } outs().write(ClangASTContents.data(), ClangASTContents.size()); } static void printFaultMaps(const ObjectFile *Obj) { const char *FaultMapSectionName = nullptr; if (isa<ELFObjectFileBase>(Obj)) { FaultMapSectionName = ".llvm_faultmaps"; } else if (isa<MachOObjectFile>(Obj)) { FaultMapSectionName = "__llvm_faultmaps"; } else { errs() << "This operation is only currently supported " "for ELF and Mach-O executable files.\n"; return; } Optional<object::SectionRef> FaultMapSection; for (auto Sec : Obj->sections()) { StringRef Name; Sec.getName(Name); if (Name == FaultMapSectionName) { FaultMapSection = Sec; break; } } outs() << "FaultMap table:\n"; if (!FaultMapSection.hasValue()) { outs() << "<not found>\n"; return; } StringRef FaultMapContents; if (error(FaultMapSection.getValue().getContents(FaultMapContents))) { errs() << "Could not read the " << FaultMapContents << " section!\n"; return; } FaultMapParser FMP(FaultMapContents.bytes_begin(), FaultMapContents.bytes_end()); outs() << FMP; } static void printPrivateFileHeader(const ObjectFile *o) { if (o->isELF()) { printELFFileHeader(o); } else if (o->isCOFF()) { printCOFFFileHeader(o); } else if (o->isMachO()) { printMachOFileHeader(o); } } static void DumpObject(const ObjectFile *o) { // Avoid other output when using a raw option. if (!RawClangAST) { outs() << '\n'; outs() << o->getFileName() << ":\tfile format " << o->getFileFormatName() << "\n\n"; } if (Disassemble) DisassembleObject(o, Relocations); if (Relocations && !Disassemble) PrintRelocations(o); if (SectionHeaders) PrintSectionHeaders(o); if (SectionContents) PrintSectionContents(o); if (SymbolTable) PrintSymbolTable(o); if (UnwindInfo) PrintUnwindInfo(o); if (PrivateHeaders) printPrivateFileHeader(o); if (ExportsTrie) printExportsTrie(o); if (Rebase) printRebaseTable(o); if (Bind) printBindTable(o); if (LazyBind) printLazyBindTable(o); if (WeakBind) printWeakBindTable(o); if (RawClangAST) printRawClangAST(o); if (PrintFaultMaps) printFaultMaps(o); } /// @brief Dump each object file in \a a; static void DumpArchive(const Archive *a) { for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e; ++i) { ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary(); if (std::error_code EC = ChildOrErr.getError()) { // Ignore non-object files. if (EC != object_error::invalid_file_type) report_error(a->getFileName(), EC); continue; } if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) DumpObject(o); else report_error(a->getFileName(), object_error::invalid_file_type); } } /// @brief Open file and figure out how to dump it. static void DumpInput(StringRef file) { // If file isn't stdin, check that it exists. if (file != "-" && !sys::fs::exists(file)) { report_error(file, errc::no_such_file_or_directory); return; } // If we are using the Mach-O specific object file parser, then let it parse // the file and process the command line options. So the -arch flags can // be used to select specific slices, etc. if (MachOOpt) { ParseInputMachO(file); return; } // Attempt to open the binary. ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file); if (std::error_code EC = BinaryOrErr.getError()) { report_error(file, EC); return; } Binary &Binary = *BinaryOrErr.get().getBinary(); if (Archive *a = dyn_cast<Archive>(&Binary)) DumpArchive(a); else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary)) DumpObject(o); else report_error(file, object_error::invalid_file_type); } // HLSL Change: changed calling convention to __cdecl int __cdecl main(int argc, char **argv) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. // Initialize targets and assembly printers/parsers. llvm::InitializeAllTargetInfos(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmParsers(); llvm::InitializeAllDisassemblers(); // Register the target printer for --version. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); TripleName = Triple::normalize(TripleName); ToolName = argv[0]; // Defaults to a.out if no filenames specified. if (InputFilenames.size() == 0) InputFilenames.push_back("a.out"); if (!Disassemble && !Relocations && !SectionHeaders && !SectionContents && !SymbolTable && !UnwindInfo && !PrivateHeaders && !ExportsTrie && !Rebase && !Bind && !LazyBind && !WeakBind && !RawClangAST && !(UniversalHeaders && MachOOpt) && !(ArchiveHeaders && MachOOpt) && !(IndirectSymbols && MachOOpt) && !(DataInCode && MachOOpt) && !(LinkOptHints && MachOOpt) && !(InfoPlist && MachOOpt) && !(DylibsUsed && MachOOpt) && !(DylibId && MachOOpt) && !(ObjcMetaData && MachOOpt) && !(DumpSections.size() != 0 && MachOOpt) && !PrintFaultMaps) { cl::PrintHelpMessage(); return 2; } std::for_each(InputFilenames.begin(), InputFilenames.end(), DumpInput); return ReturnValue; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-objdump/LLVMBuild.txt
;===- ./tools/llvm-objdump/LLVMBuild.txt -----------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Tool name = llvm-objdump parent = Tools required_libraries = DebugInfoDWARF MC MCDisassembler MCParser Object all-targets
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-objdump/COFFDump.cpp
//===-- COFFDump.cpp - COFF-specific dumper ---------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file implements the COFF-specific dumper for llvm-objdump. /// It outputs the Win64 EH data structures as plain text. /// The encoding of the unwind codes is described in MSDN: /// http://msdn.microsoft.com/en-us/library/ck9asaa9.aspx /// //===----------------------------------------------------------------------===// #include "llvm-objdump.h" #include "llvm/Object/COFF.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/Format.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/Win64EH.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cstring> #include <system_error> using namespace llvm; using namespace object; using namespace llvm::Win64EH; // Returns the name of the unwind code. static StringRef getUnwindCodeTypeName(uint8_t Code) { switch(Code) { default: llvm_unreachable("Invalid unwind code"); case UOP_PushNonVol: return "UOP_PushNonVol"; case UOP_AllocLarge: return "UOP_AllocLarge"; case UOP_AllocSmall: return "UOP_AllocSmall"; case UOP_SetFPReg: return "UOP_SetFPReg"; case UOP_SaveNonVol: return "UOP_SaveNonVol"; case UOP_SaveNonVolBig: return "UOP_SaveNonVolBig"; case UOP_SaveXMM128: return "UOP_SaveXMM128"; case UOP_SaveXMM128Big: return "UOP_SaveXMM128Big"; case UOP_PushMachFrame: return "UOP_PushMachFrame"; } } // Returns the name of a referenced register. static StringRef getUnwindRegisterName(uint8_t Reg) { switch(Reg) { default: llvm_unreachable("Invalid register"); case 0: return "RAX"; case 1: return "RCX"; case 2: return "RDX"; case 3: return "RBX"; case 4: return "RSP"; case 5: return "RBP"; case 6: return "RSI"; case 7: return "RDI"; case 8: return "R8"; case 9: return "R9"; case 10: return "R10"; case 11: return "R11"; case 12: return "R12"; case 13: return "R13"; case 14: return "R14"; case 15: return "R15"; } } // Calculates the number of array slots required for the unwind code. static unsigned getNumUsedSlots(const UnwindCode &UnwindCode) { switch (UnwindCode.getUnwindOp()) { default: llvm_unreachable("Invalid unwind code"); case UOP_PushNonVol: case UOP_AllocSmall: case UOP_SetFPReg: case UOP_PushMachFrame: return 1; case UOP_SaveNonVol: case UOP_SaveXMM128: return 2; case UOP_SaveNonVolBig: case UOP_SaveXMM128Big: return 3; case UOP_AllocLarge: return (UnwindCode.getOpInfo() == 0) ? 2 : 3; } } // Prints one unwind code. Because an unwind code can occupy up to 3 slots in // the unwind codes array, this function requires that the correct number of // slots is provided. static void printUnwindCode(ArrayRef<UnwindCode> UCs) { assert(UCs.size() >= getNumUsedSlots(UCs[0])); outs() << format(" 0x%02x: ", unsigned(UCs[0].u.CodeOffset)) << getUnwindCodeTypeName(UCs[0].getUnwindOp()); switch (UCs[0].getUnwindOp()) { case UOP_PushNonVol: outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo()); break; case UOP_AllocLarge: if (UCs[0].getOpInfo() == 0) { outs() << " " << UCs[1].FrameOffset; } else { outs() << " " << UCs[1].FrameOffset + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16); } break; case UOP_AllocSmall: outs() << " " << ((UCs[0].getOpInfo() + 1) * 8); break; case UOP_SetFPReg: outs() << " "; break; case UOP_SaveNonVol: outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo()) << format(" [0x%04x]", 8 * UCs[1].FrameOffset); break; case UOP_SaveNonVolBig: outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo()) << format(" [0x%08x]", UCs[1].FrameOffset + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16)); break; case UOP_SaveXMM128: outs() << " XMM" << static_cast<uint32_t>(UCs[0].getOpInfo()) << format(" [0x%04x]", 16 * UCs[1].FrameOffset); break; case UOP_SaveXMM128Big: outs() << " XMM" << UCs[0].getOpInfo() << format(" [0x%08x]", UCs[1].FrameOffset + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16)); break; case UOP_PushMachFrame: outs() << " " << (UCs[0].getOpInfo() ? "w/o" : "w") << " error code"; break; } outs() << "\n"; } static void printAllUnwindCodes(ArrayRef<UnwindCode> UCs) { for (const UnwindCode *I = UCs.begin(), *E = UCs.end(); I < E; ) { unsigned UsedSlots = getNumUsedSlots(*I); if (UsedSlots > UCs.size()) { outs() << "Unwind data corrupted: Encountered unwind op " << getUnwindCodeTypeName((*I).getUnwindOp()) << " which requires " << UsedSlots << " slots, but only " << UCs.size() << " remaining in buffer"; return ; } printUnwindCode(ArrayRef<UnwindCode>(I, E)); I += UsedSlots; } } // Given a symbol sym this functions returns the address and section of it. static std::error_code resolveSectionAndAddress(const COFFObjectFile *Obj, const SymbolRef &Sym, const coff_section *&ResolvedSection, uint64_t &ResolvedAddr) { ErrorOr<uint64_t> ResolvedAddrOrErr = Sym.getAddress(); if (std::error_code EC = ResolvedAddrOrErr.getError()) return EC; ResolvedAddr = *ResolvedAddrOrErr; section_iterator iter(Obj->section_begin()); if (std::error_code EC = Sym.getSection(iter)) return EC; ResolvedSection = Obj->getCOFFSection(*iter); return std::error_code(); } // Given a vector of relocations for a section and an offset into this section // the function returns the symbol used for the relocation at the offset. static std::error_code resolveSymbol(const std::vector<RelocationRef> &Rels, uint64_t Offset, SymbolRef &Sym) { for (std::vector<RelocationRef>::const_iterator I = Rels.begin(), E = Rels.end(); I != E; ++I) { uint64_t Ofs = I->getOffset(); if (Ofs == Offset) { Sym = *I->getSymbol(); return std::error_code(); } } return object_error::parse_failed; } // Given a vector of relocations for a section and an offset into this section // the function resolves the symbol used for the relocation at the offset and // returns the section content and the address inside the content pointed to // by the symbol. static std::error_code getSectionContents(const COFFObjectFile *Obj, const std::vector<RelocationRef> &Rels, uint64_t Offset, ArrayRef<uint8_t> &Contents, uint64_t &Addr) { SymbolRef Sym; if (std::error_code EC = resolveSymbol(Rels, Offset, Sym)) return EC; const coff_section *Section; if (std::error_code EC = resolveSectionAndAddress(Obj, Sym, Section, Addr)) return EC; if (std::error_code EC = Obj->getSectionContents(Section, Contents)) return EC; return std::error_code(); } // Given a vector of relocations for a section and an offset into this section // the function returns the name of the symbol used for the relocation at the // offset. static std::error_code resolveSymbolName(const std::vector<RelocationRef> &Rels, uint64_t Offset, StringRef &Name) { SymbolRef Sym; if (std::error_code EC = resolveSymbol(Rels, Offset, Sym)) return EC; ErrorOr<StringRef> NameOrErr = Sym.getName(); if (std::error_code EC = NameOrErr.getError()) return EC; Name = *NameOrErr; return std::error_code(); } static void printCOFFSymbolAddress(llvm::raw_ostream &Out, const std::vector<RelocationRef> &Rels, uint64_t Offset, uint32_t Disp) { StringRef Sym; if (!resolveSymbolName(Rels, Offset, Sym)) { Out << Sym; if (Disp > 0) Out << format(" + 0x%04x", Disp); } else { Out << format("0x%04x", Disp); } } static void printSEHTable(const COFFObjectFile *Obj, uint32_t TableVA, int Count) { if (Count == 0) return; const pe32_header *PE32Header; if (error(Obj->getPE32Header(PE32Header))) return; uint32_t ImageBase = PE32Header->ImageBase; uintptr_t IntPtr = 0; if (error(Obj->getVaPtr(TableVA, IntPtr))) return; const support::ulittle32_t *P = (const support::ulittle32_t *)IntPtr; outs() << "SEH Table:"; for (int I = 0; I < Count; ++I) outs() << format(" 0x%x", P[I] + ImageBase); outs() << "\n\n"; } static void printLoadConfiguration(const COFFObjectFile *Obj) { // Skip if it's not executable. const pe32_header *PE32Header; if (error(Obj->getPE32Header(PE32Header))) return; if (!PE32Header) return; // Currently only x86 is supported if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_I386) return; const data_directory *DataDir; if (error(Obj->getDataDirectory(COFF::LOAD_CONFIG_TABLE, DataDir))) return; uintptr_t IntPtr = 0; if (DataDir->RelativeVirtualAddress == 0) return; if (error(Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr))) return; auto *LoadConf = reinterpret_cast<const coff_load_configuration32 *>(IntPtr); outs() << "Load configuration:" << "\n Timestamp: " << LoadConf->TimeDateStamp << "\n Major Version: " << LoadConf->MajorVersion << "\n Minor Version: " << LoadConf->MinorVersion << "\n GlobalFlags Clear: " << LoadConf->GlobalFlagsClear << "\n GlobalFlags Set: " << LoadConf->GlobalFlagsSet << "\n Critical Section Default Timeout: " << LoadConf->CriticalSectionDefaultTimeout << "\n Decommit Free Block Threshold: " << LoadConf->DeCommitFreeBlockThreshold << "\n Decommit Total Free Threshold: " << LoadConf->DeCommitTotalFreeThreshold << "\n Lock Prefix Table: " << LoadConf->LockPrefixTable << "\n Maximum Allocation Size: " << LoadConf->MaximumAllocationSize << "\n Virtual Memory Threshold: " << LoadConf->VirtualMemoryThreshold << "\n Process Affinity Mask: " << LoadConf->ProcessAffinityMask << "\n Process Heap Flags: " << LoadConf->ProcessHeapFlags << "\n CSD Version: " << LoadConf->CSDVersion << "\n Security Cookie: " << LoadConf->SecurityCookie << "\n SEH Table: " << LoadConf->SEHandlerTable << "\n SEH Count: " << LoadConf->SEHandlerCount << "\n\n"; printSEHTable(Obj, LoadConf->SEHandlerTable, LoadConf->SEHandlerCount); outs() << "\n"; } // Prints import tables. The import table is a table containing the list of // DLL name and symbol names which will be linked by the loader. static void printImportTables(const COFFObjectFile *Obj) { import_directory_iterator I = Obj->import_directory_begin(); import_directory_iterator E = Obj->import_directory_end(); if (I == E) return; outs() << "The Import Tables:\n"; for (; I != E; I = ++I) { const import_directory_table_entry *Dir; StringRef Name; if (I->getImportTableEntry(Dir)) return; if (I->getName(Name)) return; outs() << format(" lookup %08x time %08x fwd %08x name %08x addr %08x\n\n", static_cast<uint32_t>(Dir->ImportLookupTableRVA), static_cast<uint32_t>(Dir->TimeDateStamp), static_cast<uint32_t>(Dir->ForwarderChain), static_cast<uint32_t>(Dir->NameRVA), static_cast<uint32_t>(Dir->ImportAddressTableRVA)); outs() << " DLL Name: " << Name << "\n"; outs() << " Hint/Ord Name\n"; const import_lookup_table_entry32 *entry; if (I->getImportLookupEntry(entry)) return; for (; entry->Data; ++entry) { if (entry->isOrdinal()) { outs() << format(" % 6d\n", entry->getOrdinal()); continue; } uint16_t Hint; StringRef Name; if (Obj->getHintName(entry->getHintNameRVA(), Hint, Name)) return; outs() << format(" % 6d ", Hint) << Name << "\n"; } outs() << "\n"; } } // Prints export tables. The export table is a table containing the list of // exported symbol from the DLL. static void printExportTable(const COFFObjectFile *Obj) { outs() << "Export Table:\n"; export_directory_iterator I = Obj->export_directory_begin(); export_directory_iterator E = Obj->export_directory_end(); if (I == E) return; StringRef DllName; uint32_t OrdinalBase; if (I->getDllName(DllName)) return; if (I->getOrdinalBase(OrdinalBase)) return; outs() << " DLL name: " << DllName << "\n"; outs() << " Ordinal base: " << OrdinalBase << "\n"; outs() << " Ordinal RVA Name\n"; for (; I != E; I = ++I) { uint32_t Ordinal; if (I->getOrdinal(Ordinal)) return; uint32_t RVA; if (I->getExportRVA(RVA)) return; outs() << format(" % 4d %# 8x", Ordinal, RVA); StringRef Name; if (I->getSymbolName(Name)) continue; if (!Name.empty()) outs() << " " << Name; outs() << "\n"; } } // Given the COFF object file, this function returns the relocations for .pdata // and the pointer to "runtime function" structs. static bool getPDataSection(const COFFObjectFile *Obj, std::vector<RelocationRef> &Rels, const RuntimeFunction *&RFStart, int &NumRFs) { for (const SectionRef &Section : Obj->sections()) { StringRef Name; if (error(Section.getName(Name))) continue; if (Name != ".pdata") continue; const coff_section *Pdata = Obj->getCOFFSection(Section); for (const RelocationRef &Reloc : Section.relocations()) Rels.push_back(Reloc); // Sort relocations by address. std::sort(Rels.begin(), Rels.end(), RelocAddressLess); ArrayRef<uint8_t> Contents; if (error(Obj->getSectionContents(Pdata, Contents))) continue; if (Contents.empty()) continue; RFStart = reinterpret_cast<const RuntimeFunction *>(Contents.data()); NumRFs = Contents.size() / sizeof(RuntimeFunction); return true; } return false; } static void printWin64EHUnwindInfo(const Win64EH::UnwindInfo *UI) { // The casts to int are required in order to output the value as number. // Without the casts the value would be interpreted as char data (which // results in garbage output). outs() << " Version: " << static_cast<int>(UI->getVersion()) << "\n"; outs() << " Flags: " << static_cast<int>(UI->getFlags()); if (UI->getFlags()) { if (UI->getFlags() & UNW_ExceptionHandler) outs() << " UNW_ExceptionHandler"; if (UI->getFlags() & UNW_TerminateHandler) outs() << " UNW_TerminateHandler"; if (UI->getFlags() & UNW_ChainInfo) outs() << " UNW_ChainInfo"; } outs() << "\n"; outs() << " Size of prolog: " << static_cast<int>(UI->PrologSize) << "\n"; outs() << " Number of Codes: " << static_cast<int>(UI->NumCodes) << "\n"; // Maybe this should move to output of UOP_SetFPReg? if (UI->getFrameRegister()) { outs() << " Frame register: " << getUnwindRegisterName(UI->getFrameRegister()) << "\n"; outs() << " Frame offset: " << 16 * UI->getFrameOffset() << "\n"; } else { outs() << " No frame pointer used\n"; } if (UI->getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) { // FIXME: Output exception handler data } else if (UI->getFlags() & UNW_ChainInfo) { // FIXME: Output chained unwind info } if (UI->NumCodes) outs() << " Unwind Codes:\n"; printAllUnwindCodes(ArrayRef<UnwindCode>(&UI->UnwindCodes[0], UI->NumCodes)); outs() << "\n"; outs().flush(); } /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is /// pointing to an executable file. static void printRuntimeFunction(const COFFObjectFile *Obj, const RuntimeFunction &RF) { if (!RF.StartAddress) return; outs() << "Function Table:\n" << format(" Start Address: 0x%04x\n", static_cast<uint32_t>(RF.StartAddress)) << format(" End Address: 0x%04x\n", static_cast<uint32_t>(RF.EndAddress)) << format(" Unwind Info Address: 0x%04x\n", static_cast<uint32_t>(RF.UnwindInfoOffset)); uintptr_t addr; if (Obj->getRvaPtr(RF.UnwindInfoOffset, addr)) return; printWin64EHUnwindInfo(reinterpret_cast<const Win64EH::UnwindInfo *>(addr)); } /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is /// pointing to an object file. Unlike executable, fields in RuntimeFunction /// struct are filled with zeros, but instead there are relocations pointing to /// them so that the linker will fill targets' RVAs to the fields at link /// time. This function interprets the relocations to find the data to be used /// in the resulting executable. static void printRuntimeFunctionRels(const COFFObjectFile *Obj, const RuntimeFunction &RF, uint64_t SectionOffset, const std::vector<RelocationRef> &Rels) { outs() << "Function Table:\n"; outs() << " Start Address: "; printCOFFSymbolAddress(outs(), Rels, SectionOffset + /*offsetof(RuntimeFunction, StartAddress)*/ 0, RF.StartAddress); outs() << "\n"; outs() << " End Address: "; printCOFFSymbolAddress(outs(), Rels, SectionOffset + /*offsetof(RuntimeFunction, EndAddress)*/ 4, RF.EndAddress); outs() << "\n"; outs() << " Unwind Info Address: "; printCOFFSymbolAddress(outs(), Rels, SectionOffset + /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8, RF.UnwindInfoOffset); outs() << "\n"; ArrayRef<uint8_t> XContents; uint64_t UnwindInfoOffset = 0; if (error(getSectionContents( Obj, Rels, SectionOffset + /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8, XContents, UnwindInfoOffset))) return; if (XContents.empty()) return; UnwindInfoOffset += RF.UnwindInfoOffset; if (UnwindInfoOffset > XContents.size()) return; auto *UI = reinterpret_cast<const Win64EH::UnwindInfo *>(XContents.data() + UnwindInfoOffset); printWin64EHUnwindInfo(UI); } void llvm::printCOFFUnwindInfo(const COFFObjectFile *Obj) { if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_AMD64) { errs() << "Unsupported image machine type " "(currently only AMD64 is supported).\n"; return; } std::vector<RelocationRef> Rels; const RuntimeFunction *RFStart; int NumRFs; if (!getPDataSection(Obj, Rels, RFStart, NumRFs)) return; ArrayRef<RuntimeFunction> RFs(RFStart, NumRFs); bool IsExecutable = Rels.empty(); if (IsExecutable) { for (const RuntimeFunction &RF : RFs) printRuntimeFunction(Obj, RF); return; } for (const RuntimeFunction &RF : RFs) { uint64_t SectionOffset = std::distance(RFs.begin(), &RF) * sizeof(RuntimeFunction); printRuntimeFunctionRels(Obj, RF, SectionOffset, Rels); } } void llvm::printCOFFFileHeader(const object::ObjectFile *Obj) { const COFFObjectFile *file = dyn_cast<const COFFObjectFile>(Obj); printLoadConfiguration(file); printImportTables(file); printExportTable(file); }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llc/llc.cpp
//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is the llc code generator driver. It provides a convenient // command-line interface for generating native assembly-language code // or C code, given LLVM bitcode. // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/Triple.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/CodeGen/CommandFlags.h" #include "llvm/CodeGen/LinkAllAsmWriterComponents.h" #include "llvm/CodeGen/LinkAllCodegenComponents.h" #include "llvm/CodeGen/MIRParser/MIRParser.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/IRPrintingPasses.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/Module.h" #include "llvm/IR/Verifier.h" #include "llvm/IRReader/IRReader.h" #include "llvm/MC/SubtargetFeature.h" #include "llvm/Pass.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Support/Host.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PluginLoader.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetSubtargetInfo.h" #include "llvm/Transforms/Utils/Cloning.h" #include <memory> using namespace llvm; // General options for llc. Other pass-specific options are specified // within the corresponding llc passes, and target-specific options // and back-end code generation options are specified with the target machine. // static cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-")); static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename")); static cl::opt<unsigned> TimeCompilations("time-compilations", cl::Hidden, cl::init(1u), cl::value_desc("N"), cl::desc("Repeat compilation N times for timing")); static cl::opt<bool> NoIntegratedAssembler("no-integrated-as", cl::Hidden, cl::desc("Disable integrated assembler")); // Determine optimization level. static cl::opt<char> OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " "(default = '-O2')"), cl::Prefix, cl::ZeroOrMore, cl::init(' ')); static cl::opt<std::string> TargetTriple("mtriple", cl::desc("Override target triple for module")); static cl::opt<bool> NoVerify("disable-verify", cl::Hidden, cl::desc("Do not verify input module")); static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls", cl::desc("Disable simplify-libcalls")); static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden, cl::desc("Show encoding in .s output")); static cl::opt<bool> EnableDwarfDirectory( "enable-dwarf-directory", cl::Hidden, cl::desc("Use .file directives with an explicit directory.")); static cl::opt<bool> AsmVerbose("asm-verbose", cl::desc("Add comments to directives."), cl::init(true)); static cl::opt<bool> CompileTwice("compile-twice", cl::Hidden, cl::desc("Run everything twice, re-using the same pass " "manager and verify the the result is the same."), cl::init(false)); static int compileModule(char **, LLVMContext &); static std::unique_ptr<tool_output_file> GetOutputStream(const char *TargetName, Triple::OSType OS, const char *ProgName) { // If we don't yet have an output filename, make one. if (OutputFilename.empty()) { if (InputFilename == "-") OutputFilename = "-"; else { // If InputFilename ends in .bc or .ll, remove it. StringRef IFN = InputFilename; if (IFN.endswith(".bc") || IFN.endswith(".ll")) OutputFilename = IFN.drop_back(3); else if (IFN.endswith(".mir")) OutputFilename = IFN.drop_back(4); else OutputFilename = IFN; switch (FileType) { case TargetMachine::CGFT_AssemblyFile: if (TargetName[0] == 'c') { if (TargetName[1] == 0) OutputFilename += ".cbe.c"; else if (TargetName[1] == 'p' && TargetName[2] == 'p') OutputFilename += ".cpp"; else OutputFilename += ".s"; } else OutputFilename += ".s"; break; case TargetMachine::CGFT_ObjectFile: if (OS == Triple::Win32) OutputFilename += ".obj"; else OutputFilename += ".o"; break; case TargetMachine::CGFT_Null: OutputFilename += ".null"; break; } } } // Decide if we need "binary" output. bool Binary = false; switch (FileType) { case TargetMachine::CGFT_AssemblyFile: break; case TargetMachine::CGFT_ObjectFile: case TargetMachine::CGFT_Null: Binary = true; break; } // Open the file. std::error_code EC; sys::fs::OpenFlags OpenFlags = sys::fs::F_None; if (!Binary) OpenFlags |= sys::fs::F_Text; auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC, OpenFlags); if (EC) { errs() << EC.message() << '\n'; return nullptr; } return FDOut; } // main - Entry point for the llc compiler. // // HLSL Change: changed calling convention to __cdecl int __cdecl main(int argc, char **argv) { sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); // Enable debug stream buffering. EnableDebugBuffering = true; LLVMContext &Context = getGlobalContext(); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. // Initialize targets first, so that --version shows registered targets. InitializeAllTargets(); InitializeAllTargetMCs(); InitializeAllAsmPrinters(); InitializeAllAsmParsers(); // Initialize codegen and IR passes used by llc so that the -print-after, // -print-before, and -stop-after options work. PassRegistry *Registry = PassRegistry::getPassRegistry(); initializeCore(*Registry); initializeCodeGen(*Registry); initializeLoopStrengthReducePass(*Registry); initializeLowerIntrinsicsPass(*Registry); initializeUnreachableBlockElimPass(*Registry); // Register the target printer for --version. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n"); // Compile the module TimeCompilations times to give better compile time // metrics. for (unsigned I = TimeCompilations; I; --I) if (int RetVal = compileModule(argv, Context)) return RetVal; return 0; } static int compileModule(char **argv, LLVMContext &Context) { // Load the module to be compiled... SMDiagnostic Err; std::unique_ptr<Module> M; std::unique_ptr<MIRParser> MIR; Triple TheTriple; bool SkipModule = MCPU == "help" || (!MAttrs.empty() && MAttrs.front() == "help"); // If user just wants to list available options, skip module loading if (!SkipModule) { if (StringRef(InputFilename).endswith_lower(".mir")) { MIR = createMIRParserFromFile(InputFilename, Err, Context); if (MIR) { M = MIR->parseLLVMModule(); assert(M && "parseLLVMModule should exit on failure"); } } else M = parseIRFile(InputFilename, Err, Context); if (!M) { Err.print(argv[0], errs()); return 1; } // Verify module immediately to catch problems before doInitialization() is // called on any passes. if (!NoVerify && verifyModule(*M, &errs())) { errs() << argv[0] << ": " << InputFilename << ": error: input module is broken!\n"; return 1; } // If we are supposed to override the target triple, do so now. if (!TargetTriple.empty()) M->setTargetTriple(Triple::normalize(TargetTriple)); TheTriple = Triple(M->getTargetTriple()); } else { TheTriple = Triple(Triple::normalize(TargetTriple)); } if (TheTriple.getTriple().empty()) TheTriple.setTriple(sys::getDefaultTargetTriple()); // Get the target specific parser. std::string Error; const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple, Error); if (!TheTarget) { errs() << argv[0] << ": " << Error; return 1; } std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr(); CodeGenOpt::Level OLvl = CodeGenOpt::Default; switch (OptLevel) { default: errs() << argv[0] << ": invalid optimization level.\n"; return 1; case ' ': break; case '0': OLvl = CodeGenOpt::None; break; case '1': OLvl = CodeGenOpt::Less; break; case '2': OLvl = CodeGenOpt::Default; break; case '3': OLvl = CodeGenOpt::Aggressive; break; } TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); Options.DisableIntegratedAS = NoIntegratedAssembler; Options.MCOptions.ShowMCEncoding = ShowMCEncoding; Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory; Options.MCOptions.AsmVerbose = AsmVerbose; std::unique_ptr<TargetMachine> Target( TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RelocModel, CMModel, OLvl)); assert(Target && "Could not allocate target machine!"); // If we don't have a module then just exit now. We do this down // here since the CPU/Feature help is underneath the target machine // creation. if (SkipModule) return 0; assert(M && "Should have exited if we didn't have a module!"); if (FloatABIForCalls != FloatABI::Default) Options.FloatABIType = FloatABIForCalls; // Figure out where we are going to send the output. std::unique_ptr<tool_output_file> Out = GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]); if (!Out) return 1; // Build up all of the passes that we want to do to the module. legacy::PassManager PM; // Add an appropriate TargetLibraryInfo pass for the module's triple. TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple())); // The -disable-simplify-libcalls flag actually disables all builtin optzns. if (DisableSimplifyLibCalls) TLII.disableAllFunctions(); PM.add(new TargetLibraryInfoWrapperPass(TLII)); // Add the target data from the target machine, if it exists, or the module. if (const DataLayout *DL = Target->getDataLayout()) M->setDataLayout(*DL); // Override function attributes based on CPUStr, FeaturesStr, and command line // flags. setFunctionAttributes(CPUStr, FeaturesStr, *M); if (RelaxAll.getNumOccurrences() > 0 && FileType != TargetMachine::CGFT_ObjectFile) errs() << argv[0] << ": warning: ignoring -mc-relax-all because filetype != obj"; { raw_pwrite_stream *OS = &Out->os(); // Manually do the buffering rather than using buffer_ostream, // so we can memcmp the contents in CompileTwice mode SmallVector<char, 0> Buffer; std::unique_ptr<raw_svector_ostream> BOS; if ((FileType != TargetMachine::CGFT_AssemblyFile && !Out->os().supportsSeeking()) || CompileTwice) { BOS = make_unique<raw_svector_ostream>(Buffer); OS = BOS.get(); } AnalysisID StartBeforeID = nullptr; AnalysisID StartAfterID = nullptr; AnalysisID StopAfterID = nullptr; const PassRegistry *PR = PassRegistry::getPassRegistry(); if (!RunPass.empty()) { if (!StartAfter.empty() || !StopAfter.empty()) { errs() << argv[0] << ": start-after and/or stop-after passes are " "redundant when run-pass is specified.\n"; return 1; } const PassInfo *PI = PR->getPassInfo(RunPass); if (!PI) { errs() << argv[0] << ": run-pass pass is not registered.\n"; return 1; } StopAfterID = StartBeforeID = PI->getTypeInfo(); } else { if (!StartAfter.empty()) { const PassInfo *PI = PR->getPassInfo(StartAfter); if (!PI) { errs() << argv[0] << ": start-after pass is not registered.\n"; return 1; } StartAfterID = PI->getTypeInfo(); } if (!StopAfter.empty()) { const PassInfo *PI = PR->getPassInfo(StopAfter); if (!PI) { errs() << argv[0] << ": stop-after pass is not registered.\n"; return 1; } StopAfterID = PI->getTypeInfo(); } } // Ask the target to add backend passes as necessary. if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify, StartBeforeID, StartAfterID, StopAfterID, MIR.get())) { errs() << argv[0] << ": target does not support generation of this" << " file type!\n"; return 1; } // Before executing passes, print the final values of the LLVM options. cl::PrintOptionValues(); // If requested, run the pass manager over the same module again, // to catch any bugs due to persistent state in the passes. Note that // opt has the same functionality, so it may be worth abstracting this out // in the future. SmallVector<char, 0> CompileTwiceBuffer; if (CompileTwice) { std::unique_ptr<Module> M2(llvm::CloneModule(M.get())); PM.run(*M2); CompileTwiceBuffer = Buffer; Buffer.clear(); } PM.run(*M); // Compare the two outputs and make sure they're the same if (CompileTwice) { if (Buffer.size() != CompileTwiceBuffer.size() || (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) != 0)) { errs() << "Running the pass manager twice changed the output.\n" "Writing the result of the second run to the specified output\n" "To generate the one-run comparison binary, just run without\n" "the compile-twice option\n"; Out->os() << Buffer; Out->keep(); return 1; } } if (BOS) { Out->os() << Buffer; } } // Declare success. Out->keep(); return 0; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llc/CMakeLists.txt
set(LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} Analysis AsmPrinter CodeGen Core IRReader MC MIRParser ScalarOpts SelectionDAG Support Target ) # Support plugins. set(LLVM_NO_DEAD_STRIP 1) add_llvm_tool(llc llc.cpp ) export_executable_symbols(llc)
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llc/LLVMBuild.txt
;===- ./tools/llc/LLVMBuild.txt --------------------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Tool name = llc parent = Tools required_libraries = AsmParser BitReader IRReader MIRParser all-targets
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-size/llvm-size.cpp
//===-- llvm-size.cpp - Print the size of each object section -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program is a utility that works like traditional Unix "size", // that is, it prints out the size of each section, and the total size of all // sections. // //===----------------------------------------------------------------------===// #include "llvm/ADT/APInt.h" #include "llvm/Object/Archive.h" #include "llvm/Object/MachO.h" #include "llvm/Object/MachOUniversal.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Format.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <string> #include <system_error> using namespace llvm; using namespace object; enum OutputFormatTy { berkeley, sysv, darwin }; static cl::opt<OutputFormatTy> OutputFormat("format", cl::desc("Specify output format"), cl::values(clEnumVal(sysv, "System V format"), clEnumVal(berkeley, "Berkeley format"), clEnumVal(darwin, "Darwin -m format"), clEnumValEnd), cl::init(berkeley)); static cl::opt<OutputFormatTy> OutputFormatShort( cl::desc("Specify output format"), cl::values(clEnumValN(sysv, "A", "System V format"), clEnumValN(berkeley, "B", "Berkeley format"), clEnumValN(darwin, "m", "Darwin -m format"), clEnumValEnd), cl::init(berkeley)); static bool berkeleyHeaderPrinted = false; static bool moreThanOneFile = false; cl::opt<bool> DarwinLongFormat("l", cl::desc("When format is darwin, use long format " "to include addresses and offsets.")); static cl::list<std::string> ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"), cl::ZeroOrMore); bool ArchAll = false; enum RadixTy { octal = 8, decimal = 10, hexadecimal = 16 }; static cl::opt<unsigned int> Radix("-radix", cl::desc("Print size in radix. Only 8, 10, and 16 are valid"), cl::init(decimal)); static cl::opt<RadixTy> RadixShort(cl::desc("Print size in radix:"), cl::values(clEnumValN(octal, "o", "Print size in octal"), clEnumValN(decimal, "d", "Print size in decimal"), clEnumValN(hexadecimal, "x", "Print size in hexadecimal"), clEnumValEnd), cl::init(decimal)); static cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input files>"), cl::ZeroOrMore); static std::string ToolName; /// @brief If ec is not success, print the error and return true. static bool error(std::error_code ec) { if (!ec) return false; outs() << ToolName << ": error reading file: " << ec.message() << ".\n"; outs().flush(); return true; } /// @brief Get the length of the string that represents @p num in Radix /// including the leading 0x or 0 for hexadecimal and octal respectively. static size_t getNumLengthAsString(uint64_t num) { APInt conv(64, num); SmallString<32> result; conv.toString(result, Radix, false, true); return result.size(); } /// @brief Return the printing format for the Radix. static const char *getRadixFmt(void) { switch (Radix) { case octal: return PRIo64; case decimal: return PRIu64; case hexadecimal: return PRIx64; } return nullptr; } /// @brief Print the size of each Mach-O segment and section in @p MachO. /// /// This is when used when @c OutputFormat is darwin and produces the same /// output as darwin's size(1) -m output. static void PrintDarwinSectionSizes(MachOObjectFile *MachO) { std::string fmtbuf; raw_string_ostream fmt(fmtbuf); const char *radix_fmt = getRadixFmt(); if (Radix == hexadecimal) fmt << "0x"; fmt << "%" << radix_fmt; uint32_t Filetype = MachO->getHeader().filetype; uint64_t total = 0; for (const auto &Load : MachO->load_commands()) { if (Load.C.cmd == MachO::LC_SEGMENT_64) { MachO::segment_command_64 Seg = MachO->getSegment64LoadCommand(Load); outs() << "Segment " << Seg.segname << ": " << format(fmt.str().c_str(), Seg.vmsize); if (DarwinLongFormat) outs() << " (vmaddr 0x" << format("%" PRIx64, Seg.vmaddr) << " fileoff " << Seg.fileoff << ")"; outs() << "\n"; total += Seg.vmsize; uint64_t sec_total = 0; for (unsigned J = 0; J < Seg.nsects; ++J) { MachO::section_64 Sec = MachO->getSection64(Load, J); if (Filetype == MachO::MH_OBJECT) outs() << "\tSection (" << format("%.16s", &Sec.segname) << ", " << format("%.16s", &Sec.sectname) << "): "; else outs() << "\tSection " << format("%.16s", &Sec.sectname) << ": "; outs() << format(fmt.str().c_str(), Sec.size); if (DarwinLongFormat) outs() << " (addr 0x" << format("%" PRIx64, Sec.addr) << " offset " << Sec.offset << ")"; outs() << "\n"; sec_total += Sec.size; } if (Seg.nsects != 0) outs() << "\ttotal " << format(fmt.str().c_str(), sec_total) << "\n"; } else if (Load.C.cmd == MachO::LC_SEGMENT) { MachO::segment_command Seg = MachO->getSegmentLoadCommand(Load); outs() << "Segment " << Seg.segname << ": " << format(fmt.str().c_str(), Seg.vmsize); if (DarwinLongFormat) outs() << " (vmaddr 0x" << format("%" PRIx64, Seg.vmaddr) << " fileoff " << Seg.fileoff << ")"; outs() << "\n"; total += Seg.vmsize; uint64_t sec_total = 0; for (unsigned J = 0; J < Seg.nsects; ++J) { MachO::section Sec = MachO->getSection(Load, J); if (Filetype == MachO::MH_OBJECT) outs() << "\tSection (" << format("%.16s", &Sec.segname) << ", " << format("%.16s", &Sec.sectname) << "): "; else outs() << "\tSection " << format("%.16s", &Sec.sectname) << ": "; outs() << format(fmt.str().c_str(), Sec.size); if (DarwinLongFormat) outs() << " (addr 0x" << format("%" PRIx64, Sec.addr) << " offset " << Sec.offset << ")"; outs() << "\n"; sec_total += Sec.size; } if (Seg.nsects != 0) outs() << "\ttotal " << format(fmt.str().c_str(), sec_total) << "\n"; } } outs() << "total " << format(fmt.str().c_str(), total) << "\n"; } /// @brief Print the summary sizes of the standard Mach-O segments in @p MachO. /// /// This is when used when @c OutputFormat is berkeley with a Mach-O file and /// produces the same output as darwin's size(1) default output. static void PrintDarwinSegmentSizes(MachOObjectFile *MachO) { uint64_t total_text = 0; uint64_t total_data = 0; uint64_t total_objc = 0; uint64_t total_others = 0; for (const auto &Load : MachO->load_commands()) { if (Load.C.cmd == MachO::LC_SEGMENT_64) { MachO::segment_command_64 Seg = MachO->getSegment64LoadCommand(Load); if (MachO->getHeader().filetype == MachO::MH_OBJECT) { for (unsigned J = 0; J < Seg.nsects; ++J) { MachO::section_64 Sec = MachO->getSection64(Load, J); StringRef SegmentName = StringRef(Sec.segname); if (SegmentName == "__TEXT") total_text += Sec.size; else if (SegmentName == "__DATA") total_data += Sec.size; else if (SegmentName == "__OBJC") total_objc += Sec.size; else total_others += Sec.size; } } else { StringRef SegmentName = StringRef(Seg.segname); if (SegmentName == "__TEXT") total_text += Seg.vmsize; else if (SegmentName == "__DATA") total_data += Seg.vmsize; else if (SegmentName == "__OBJC") total_objc += Seg.vmsize; else total_others += Seg.vmsize; } } else if (Load.C.cmd == MachO::LC_SEGMENT) { MachO::segment_command Seg = MachO->getSegmentLoadCommand(Load); if (MachO->getHeader().filetype == MachO::MH_OBJECT) { for (unsigned J = 0; J < Seg.nsects; ++J) { MachO::section Sec = MachO->getSection(Load, J); StringRef SegmentName = StringRef(Sec.segname); if (SegmentName == "__TEXT") total_text += Sec.size; else if (SegmentName == "__DATA") total_data += Sec.size; else if (SegmentName == "__OBJC") total_objc += Sec.size; else total_others += Sec.size; } } else { StringRef SegmentName = StringRef(Seg.segname); if (SegmentName == "__TEXT") total_text += Seg.vmsize; else if (SegmentName == "__DATA") total_data += Seg.vmsize; else if (SegmentName == "__OBJC") total_objc += Seg.vmsize; else total_others += Seg.vmsize; } } } uint64_t total = total_text + total_data + total_objc + total_others; if (!berkeleyHeaderPrinted) { outs() << "__TEXT\t__DATA\t__OBJC\tothers\tdec\thex\n"; berkeleyHeaderPrinted = true; } outs() << total_text << "\t" << total_data << "\t" << total_objc << "\t" << total_others << "\t" << total << "\t" << format("%" PRIx64, total) << "\t"; } /// @brief Print the size of each section in @p Obj. /// /// The format used is determined by @c OutputFormat and @c Radix. static void PrintObjectSectionSizes(ObjectFile *Obj) { uint64_t total = 0; std::string fmtbuf; raw_string_ostream fmt(fmtbuf); const char *radix_fmt = getRadixFmt(); // If OutputFormat is darwin and we have a MachOObjectFile print as darwin's // size(1) -m output, else if OutputFormat is darwin and not a Mach-O object // let it fall through to OutputFormat berkeley. MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj); if (OutputFormat == darwin && MachO) PrintDarwinSectionSizes(MachO); // If we have a MachOObjectFile and the OutputFormat is berkeley print as // darwin's default berkeley format for Mach-O files. else if (MachO && OutputFormat == berkeley) PrintDarwinSegmentSizes(MachO); else if (OutputFormat == sysv) { // Run two passes over all sections. The first gets the lengths needed for // formatting the output. The second actually does the output. std::size_t max_name_len = strlen("section"); std::size_t max_size_len = strlen("size"); std::size_t max_addr_len = strlen("addr"); for (const SectionRef &Section : Obj->sections()) { uint64_t size = Section.getSize(); total += size; StringRef name; if (error(Section.getName(name))) return; uint64_t addr = Section.getAddress(); max_name_len = std::max(max_name_len, name.size()); max_size_len = std::max(max_size_len, getNumLengthAsString(size)); max_addr_len = std::max(max_addr_len, getNumLengthAsString(addr)); } // Add extra padding. max_name_len += 2; max_size_len += 2; max_addr_len += 2; // Setup header format. fmt << "%-" << max_name_len << "s " << "%" << max_size_len << "s " << "%" << max_addr_len << "s\n"; // Print header outs() << format(fmt.str().c_str(), static_cast<const char *>("section"), static_cast<const char *>("size"), static_cast<const char *>("addr")); fmtbuf.clear(); // Setup per section format. fmt << "%-" << max_name_len << "s " << "%#" << max_size_len << radix_fmt << " " << "%#" << max_addr_len << radix_fmt << "\n"; // Print each section. for (const SectionRef &Section : Obj->sections()) { StringRef name; if (error(Section.getName(name))) return; uint64_t size = Section.getSize(); uint64_t addr = Section.getAddress(); std::string namestr = name; outs() << format(fmt.str().c_str(), namestr.c_str(), size, addr); } // Print total. fmtbuf.clear(); fmt << "%-" << max_name_len << "s " << "%#" << max_size_len << radix_fmt << "\n"; outs() << format(fmt.str().c_str(), static_cast<const char *>("Total"), total); } else { // The Berkeley format does not display individual section sizes. It // displays the cumulative size for each section type. uint64_t total_text = 0; uint64_t total_data = 0; uint64_t total_bss = 0; // Make one pass over the section table to calculate sizes. for (const SectionRef &Section : Obj->sections()) { uint64_t size = Section.getSize(); bool isText = Section.isText(); bool isData = Section.isData(); bool isBSS = Section.isBSS(); if (isText) total_text += size; else if (isData) total_data += size; else if (isBSS) total_bss += size; } total = total_text + total_data + total_bss; if (!berkeleyHeaderPrinted) { outs() << " text data bss " << (Radix == octal ? "oct" : "dec") << " hex filename\n"; berkeleyHeaderPrinted = true; } // Print result. fmt << "%#7" << radix_fmt << " " << "%#7" << radix_fmt << " " << "%#7" << radix_fmt << " "; outs() << format(fmt.str().c_str(), total_text, total_data, total_bss); fmtbuf.clear(); fmt << "%7" << (Radix == octal ? PRIo64 : PRIu64) << " " << "%7" PRIx64 " "; outs() << format(fmt.str().c_str(), total, total); } } /// @brief Checks to see if the @p o ObjectFile is a Mach-O file and if it is /// and there is a list of architecture flags specified then check to /// make sure this Mach-O file is one of those architectures or all /// architectures was specificed. If not then an error is generated and /// this routine returns false. Else it returns true. static bool checkMachOAndArchFlags(ObjectFile *o, StringRef file) { if (isa<MachOObjectFile>(o) && !ArchAll && ArchFlags.size() != 0) { MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o); bool ArchFound = false; MachO::mach_header H; MachO::mach_header_64 H_64; Triple T; if (MachO->is64Bit()) { H_64 = MachO->MachOObjectFile::getHeader64(); T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype); } else { H = MachO->MachOObjectFile::getHeader(); T = MachOObjectFile::getArch(H.cputype, H.cpusubtype); } unsigned i; for (i = 0; i < ArchFlags.size(); ++i) { if (ArchFlags[i] == T.getArchName()) ArchFound = true; break; } if (!ArchFound) { errs() << ToolName << ": file: " << file << " does not contain architecture: " << ArchFlags[i] << ".\n"; return false; } } return true; } /// @brief Print the section sizes for @p file. If @p file is an archive, print /// the section sizes for each archive member. static void PrintFileSectionSizes(StringRef file) { // If file is not stdin, check that it exists. if (file != "-") { if (!sys::fs::exists(file)) { errs() << ToolName << ": '" << file << "': " << "No such file\n"; return; } } // Attempt to open the binary. ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file); if (std::error_code EC = BinaryOrErr.getError()) { errs() << ToolName << ": " << file << ": " << EC.message() << ".\n"; return; } Binary &Bin = *BinaryOrErr.get().getBinary(); if (Archive *a = dyn_cast<Archive>(&Bin)) { // This is an archive. Iterate over each member and display its sizes. for (object::Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e; ++i) { ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary(); if (std::error_code EC = ChildOrErr.getError()) { errs() << ToolName << ": " << file << ": " << EC.message() << ".\n"; continue; } if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) { MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o); if (!checkMachOAndArchFlags(o, file)) return; if (OutputFormat == sysv) outs() << o->getFileName() << " (ex " << a->getFileName() << "):\n"; else if (MachO && OutputFormat == darwin) outs() << a->getFileName() << "(" << o->getFileName() << "):\n"; PrintObjectSectionSizes(o); if (OutputFormat == berkeley) { if (MachO) outs() << a->getFileName() << "(" << o->getFileName() << ")\n"; else outs() << o->getFileName() << " (ex " << a->getFileName() << ")\n"; } } } } else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) { // If we have a list of architecture flags specified dump only those. if (!ArchAll && ArchFlags.size() != 0) { // Look for a slice in the universal binary that matches each ArchFlag. bool ArchFound; for (unsigned i = 0; i < ArchFlags.size(); ++i) { ArchFound = false; for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), E = UB->end_objects(); I != E; ++I) { if (ArchFlags[i] == I->getArchTypeName()) { ArchFound = true; ErrorOr<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile(); if (UO) { if (ObjectFile *o = dyn_cast<ObjectFile>(&*UO.get())) { MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o); if (OutputFormat == sysv) outs() << o->getFileName() << " :\n"; else if (MachO && OutputFormat == darwin) { if (moreThanOneFile || ArchFlags.size() > 1) outs() << o->getFileName() << " (for architecture " << I->getArchTypeName() << "): \n"; } PrintObjectSectionSizes(o); if (OutputFormat == berkeley) { if (!MachO || moreThanOneFile || ArchFlags.size() > 1) outs() << o->getFileName() << " (for architecture " << I->getArchTypeName() << ")"; outs() << "\n"; } } } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) { std::unique_ptr<Archive> &UA = *AOrErr; // This is an archive. Iterate over each member and display its // sizes. for (object::Archive::child_iterator i = UA->child_begin(), e = UA->child_end(); i != e; ++i) { ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary(); if (std::error_code EC = ChildOrErr.getError()) { errs() << ToolName << ": " << file << ": " << EC.message() << ".\n"; continue; } if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) { MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o); if (OutputFormat == sysv) outs() << o->getFileName() << " (ex " << UA->getFileName() << "):\n"; else if (MachO && OutputFormat == darwin) outs() << UA->getFileName() << "(" << o->getFileName() << ")" << " (for architecture " << I->getArchTypeName() << "):\n"; PrintObjectSectionSizes(o); if (OutputFormat == berkeley) { if (MachO) { outs() << UA->getFileName() << "(" << o->getFileName() << ")"; if (ArchFlags.size() > 1) outs() << " (for architecture " << I->getArchTypeName() << ")"; outs() << "\n"; } else outs() << o->getFileName() << " (ex " << UA->getFileName() << ")\n"; } } } } } } if (!ArchFound) { errs() << ToolName << ": file: " << file << " does not contain architecture" << ArchFlags[i] << ".\n"; return; } } return; } // No architecture flags were specified so if this contains a slice that // matches the host architecture dump only that. if (!ArchAll) { StringRef HostArchName = MachOObjectFile::getHostArch().getArchName(); for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), E = UB->end_objects(); I != E; ++I) { if (HostArchName == I->getArchTypeName()) { ErrorOr<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile(); if (UO) { if (ObjectFile *o = dyn_cast<ObjectFile>(&*UO.get())) { MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o); if (OutputFormat == sysv) outs() << o->getFileName() << " :\n"; else if (MachO && OutputFormat == darwin) { if (moreThanOneFile) outs() << o->getFileName() << " (for architecture " << I->getArchTypeName() << "):\n"; } PrintObjectSectionSizes(o); if (OutputFormat == berkeley) { if (!MachO || moreThanOneFile) outs() << o->getFileName() << " (for architecture " << I->getArchTypeName() << ")"; outs() << "\n"; } } } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) { std::unique_ptr<Archive> &UA = *AOrErr; // This is an archive. Iterate over each member and display its // sizes. for (object::Archive::child_iterator i = UA->child_begin(), e = UA->child_end(); i != e; ++i) { ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary(); if (std::error_code EC = ChildOrErr.getError()) { errs() << ToolName << ": " << file << ": " << EC.message() << ".\n"; continue; } if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) { MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o); if (OutputFormat == sysv) outs() << o->getFileName() << " (ex " << UA->getFileName() << "):\n"; else if (MachO && OutputFormat == darwin) outs() << UA->getFileName() << "(" << o->getFileName() << ")" << " (for architecture " << I->getArchTypeName() << "):\n"; PrintObjectSectionSizes(o); if (OutputFormat == berkeley) { if (MachO) outs() << UA->getFileName() << "(" << o->getFileName() << ")\n"; else outs() << o->getFileName() << " (ex " << UA->getFileName() << ")\n"; } } } } return; } } } // Either all architectures have been specified or none have been specified // and this does not contain the host architecture so dump all the slices. bool moreThanOneArch = UB->getNumberOfObjects() > 1; for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), E = UB->end_objects(); I != E; ++I) { ErrorOr<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile(); if (UO) { if (ObjectFile *o = dyn_cast<ObjectFile>(&*UO.get())) { MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o); if (OutputFormat == sysv) outs() << o->getFileName() << " :\n"; else if (MachO && OutputFormat == darwin) { if (moreThanOneFile || moreThanOneArch) outs() << o->getFileName() << " (for architecture " << I->getArchTypeName() << "):"; outs() << "\n"; } PrintObjectSectionSizes(o); if (OutputFormat == berkeley) { if (!MachO || moreThanOneFile || moreThanOneArch) outs() << o->getFileName() << " (for architecture " << I->getArchTypeName() << ")"; outs() << "\n"; } } } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) { std::unique_ptr<Archive> &UA = *AOrErr; // This is an archive. Iterate over each member and display its sizes. for (object::Archive::child_iterator i = UA->child_begin(), e = UA->child_end(); i != e; ++i) { ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary(); if (std::error_code EC = ChildOrErr.getError()) { errs() << ToolName << ": " << file << ": " << EC.message() << ".\n"; continue; } if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) { MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o); if (OutputFormat == sysv) outs() << o->getFileName() << " (ex " << UA->getFileName() << "):\n"; else if (MachO && OutputFormat == darwin) outs() << UA->getFileName() << "(" << o->getFileName() << ")" << " (for architecture " << I->getArchTypeName() << "):\n"; PrintObjectSectionSizes(o); if (OutputFormat == berkeley) { if (MachO) outs() << UA->getFileName() << "(" << o->getFileName() << ")" << " (for architecture " << I->getArchTypeName() << ")\n"; else outs() << o->getFileName() << " (ex " << UA->getFileName() << ")\n"; } } } } } } else if (ObjectFile *o = dyn_cast<ObjectFile>(&Bin)) { if (!checkMachOAndArchFlags(o, file)) return; if (OutputFormat == sysv) outs() << o->getFileName() << " :\n"; PrintObjectSectionSizes(o); if (OutputFormat == berkeley) { MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o); if (!MachO || moreThanOneFile) outs() << o->getFileName(); outs() << "\n"; } } else { errs() << ToolName << ": " << file << ": " << "Unrecognized file type.\n"; } // System V adds an extra newline at the end of each file. if (OutputFormat == sysv) outs() << "\n"; } // HLSL Change: changed calling convention to __cdecl int __cdecl main(int argc, char **argv) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::ParseCommandLineOptions(argc, argv, "llvm object size dumper\n"); ToolName = argv[0]; if (OutputFormatShort.getNumOccurrences()) OutputFormat = static_cast<OutputFormatTy>(OutputFormatShort); if (RadixShort.getNumOccurrences()) Radix = RadixShort; for (unsigned i = 0; i < ArchFlags.size(); ++i) { if (ArchFlags[i] == "all") { ArchAll = true; } else { if (!MachOObjectFile::isValidArch(ArchFlags[i])) { outs() << ToolName << ": for the -arch option: Unknown architecture " << "named '" << ArchFlags[i] << "'"; return 1; } } } if (InputFilenames.size() == 0) InputFilenames.push_back("a.out"); moreThanOneFile = InputFilenames.size() > 1; std::for_each(InputFilenames.begin(), InputFilenames.end(), PrintFileSectionSizes); return 0; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-size/CMakeLists.txt
set(LLVM_LINK_COMPONENTS Object Support ) add_llvm_tool(llvm-size llvm-size.cpp )
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-size/LLVMBuild.txt
;===- ./tools/llvm-size/LLVMBuild.txt --------------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Tool name = llvm-size parent = Tools required_libraries = Object
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/lto/lto.cpp
//===-lto.cpp - LLVM Link Time Optimizer ----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Link Time Optimization library. This library is // intended to be used by linker to optimize code at link time. // //===----------------------------------------------------------------------===// #include "llvm-c/lto.h" #include "llvm/ADT/STLExtras.h" #include "llvm/CodeGen/CommandFlags.h" #include "llvm/IR/LLVMContext.h" #include "llvm/LTO/LTOCodeGenerator.h" #include "llvm/LTO/LTOModule.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Signals.h" #include "llvm/Support/TargetSelect.h" // extra command-line flags needed for LTOCodeGenerator static cl::opt<char> OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " "(default = '-O2')"), cl::Prefix, cl::ZeroOrMore, cl::init('2')); static cl::opt<bool> DisableInline("disable-inlining", cl::init(false), cl::desc("Do not run the inliner pass")); static cl::opt<bool> DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false), cl::desc("Do not run the GVN load PRE pass")); static cl::opt<bool> DisableLTOVectorization("disable-lto-vectorization", cl::init(false), cl::desc("Do not run loop or slp vectorization during LTO")); // Holds most recent error string. // *** Not thread safe *** static std::string sLastErrorString; // Holds the initialization state of the LTO module. // *** Not thread safe *** static bool initialized = false; // Holds the command-line option parsing state of the LTO module. static bool parsedOptions = false; // Initialize the configured targets if they have not been initialized. static void lto_initialize() { if (!initialized) { #ifdef LLVM_ON_WIN32 // Dialog box on crash disabling doesn't work across DLL boundaries, so do // it here. llvm::sys::DisableSystemDialogsOnCrash(); #endif InitializeAllTargetInfos(); InitializeAllTargets(); InitializeAllTargetMCs(); InitializeAllAsmParsers(); InitializeAllAsmPrinters(); InitializeAllDisassemblers(); initialized = true; } } namespace { // This derived class owns the native object file. This helps implement the // libLTO API semantics, which require that the code generator owns the object // file. struct LibLTOCodeGenerator : LTOCodeGenerator { LibLTOCodeGenerator() {} LibLTOCodeGenerator(std::unique_ptr<LLVMContext> Context) : LTOCodeGenerator(std::move(Context)) {} std::unique_ptr<MemoryBuffer> NativeObjectFile; }; } DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LibLTOCodeGenerator, lto_code_gen_t) DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LTOModule, lto_module_t) // Convert the subtarget features into a string to pass to LTOCodeGenerator. static void lto_add_attrs(lto_code_gen_t cg) { LTOCodeGenerator *CG = unwrap(cg); if (MAttrs.size()) { std::string attrs; for (unsigned i = 0; i < MAttrs.size(); ++i) { if (i > 0) attrs.append(","); attrs.append(MAttrs[i]); } CG->setAttr(attrs.c_str()); } if (OptLevel < '0' || OptLevel > '3') report_fatal_error("Optimization level must be between 0 and 3"); CG->setOptLevel(OptLevel - '0'); } extern const char* lto_get_version() { return LTOCodeGenerator::getVersionString(); } const char* lto_get_error_message() { return sLastErrorString.c_str(); } bool lto_module_is_object_file(const char* path) { return LTOModule::isBitcodeFile(path); } bool lto_module_is_object_file_for_target(const char* path, const char* target_triplet_prefix) { ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer = MemoryBuffer::getFile(path); if (!Buffer) return false; return LTOModule::isBitcodeForTarget(Buffer->get(), target_triplet_prefix); } bool lto_module_is_object_file_in_memory(const void* mem, size_t length) { return LTOModule::isBitcodeFile(mem, length); } bool lto_module_is_object_file_in_memory_for_target(const void* mem, size_t length, const char* target_triplet_prefix) { std::unique_ptr<MemoryBuffer> buffer(LTOModule::makeBuffer(mem, length)); if (!buffer) return false; return LTOModule::isBitcodeForTarget(buffer.get(), target_triplet_prefix); } lto_module_t lto_module_create(const char* path) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap(LTOModule::createFromFile(path, Options, sLastErrorString)); } lto_module_t lto_module_create_from_fd(int fd, const char *path, size_t size) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap( LTOModule::createFromOpenFile(fd, path, size, Options, sLastErrorString)); } lto_module_t lto_module_create_from_fd_at_offset(int fd, const char *path, size_t file_size, size_t map_size, off_t offset) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap(LTOModule::createFromOpenFileSlice(fd, path, map_size, offset, Options, sLastErrorString)); } lto_module_t lto_module_create_from_memory(const void* mem, size_t length) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap(LTOModule::createFromBuffer(mem, length, Options, sLastErrorString)); } lto_module_t lto_module_create_from_memory_with_path(const void* mem, size_t length, const char *path) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap( LTOModule::createFromBuffer(mem, length, Options, sLastErrorString, path)); } lto_module_t lto_module_create_in_local_context(const void *mem, size_t length, const char *path) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap(LTOModule::createInLocalContext(mem, length, Options, sLastErrorString, path)); } lto_module_t lto_module_create_in_codegen_context(const void *mem, size_t length, const char *path, lto_code_gen_t cg) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap(LTOModule::createInContext(mem, length, Options, sLastErrorString, path, &unwrap(cg)->getContext())); } void lto_module_dispose(lto_module_t mod) { delete unwrap(mod); } const char* lto_module_get_target_triple(lto_module_t mod) { return unwrap(mod)->getTargetTriple().c_str(); } void lto_module_set_target_triple(lto_module_t mod, const char *triple) { return unwrap(mod)->setTargetTriple(triple); } unsigned int lto_module_get_num_symbols(lto_module_t mod) { return unwrap(mod)->getSymbolCount(); } const char* lto_module_get_symbol_name(lto_module_t mod, unsigned int index) { return unwrap(mod)->getSymbolName(index); } lto_symbol_attributes lto_module_get_symbol_attribute(lto_module_t mod, unsigned int index) { return unwrap(mod)->getSymbolAttributes(index); } const char* lto_module_get_linkeropts(lto_module_t mod) { return unwrap(mod)->getLinkerOpts(); } void lto_codegen_set_diagnostic_handler(lto_code_gen_t cg, lto_diagnostic_handler_t diag_handler, void *ctxt) { unwrap(cg)->setDiagnosticHandler(diag_handler, ctxt); } static lto_code_gen_t createCodeGen(bool InLocalContext) { lto_initialize(); TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); LibLTOCodeGenerator *CodeGen = InLocalContext ? new LibLTOCodeGenerator(make_unique<LLVMContext>()) : new LibLTOCodeGenerator(); CodeGen->setTargetOptions(Options); return wrap(CodeGen); } lto_code_gen_t lto_codegen_create(void) { return createCodeGen(/* InLocalContext */ false); } lto_code_gen_t lto_codegen_create_in_local_context(void) { return createCodeGen(/* InLocalContext */ true); } void lto_codegen_dispose(lto_code_gen_t cg) { delete unwrap(cg); } bool lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod) { return !unwrap(cg)->addModule(unwrap(mod)); } void lto_codegen_set_module(lto_code_gen_t cg, lto_module_t mod) { unwrap(cg)->setModule(unwrap(mod)); } bool lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model debug) { unwrap(cg)->setDebugInfo(debug); return false; } bool lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model model) { unwrap(cg)->setCodePICModel(model); return false; } void lto_codegen_set_cpu(lto_code_gen_t cg, const char *cpu) { return unwrap(cg)->setCpu(cpu); } void lto_codegen_set_assembler_path(lto_code_gen_t cg, const char *path) { // In here only for backwards compatibility. We use MC now. } void lto_codegen_set_assembler_args(lto_code_gen_t cg, const char **args, int nargs) { // In here only for backwards compatibility. We use MC now. } void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg, const char *symbol) { unwrap(cg)->addMustPreserveSymbol(symbol); } static void maybeParseOptions(lto_code_gen_t cg) { if (!parsedOptions) { unwrap(cg)->parseCodeGenDebugOptions(); lto_add_attrs(cg); parsedOptions = true; } } bool lto_codegen_write_merged_modules(lto_code_gen_t cg, const char *path) { maybeParseOptions(cg); return !unwrap(cg)->writeMergedModules(path, sLastErrorString); } const void *lto_codegen_compile(lto_code_gen_t cg, size_t *length) { maybeParseOptions(cg); LibLTOCodeGenerator *CG = unwrap(cg); CG->NativeObjectFile = CG->compile(DisableInline, DisableGVNLoadPRE, DisableLTOVectorization, sLastErrorString); if (!CG->NativeObjectFile) return nullptr; *length = CG->NativeObjectFile->getBufferSize(); return CG->NativeObjectFile->getBufferStart(); } bool lto_codegen_optimize(lto_code_gen_t cg) { maybeParseOptions(cg); return !unwrap(cg)->optimize(DisableInline, DisableGVNLoadPRE, DisableLTOVectorization, sLastErrorString); } const void *lto_codegen_compile_optimized(lto_code_gen_t cg, size_t *length) { maybeParseOptions(cg); LibLTOCodeGenerator *CG = unwrap(cg); CG->NativeObjectFile = CG->compileOptimized(sLastErrorString); if (!CG->NativeObjectFile) return nullptr; *length = CG->NativeObjectFile->getBufferSize(); return CG->NativeObjectFile->getBufferStart(); } bool lto_codegen_compile_to_file(lto_code_gen_t cg, const char **name) { maybeParseOptions(cg); return !unwrap(cg)->compile_to_file( name, DisableInline, DisableGVNLoadPRE, DisableLTOVectorization, sLastErrorString); } void lto_codegen_debug_options(lto_code_gen_t cg, const char *opt) { unwrap(cg)->setCodeGenDebugOptions(opt); } unsigned int lto_api_version() { return LTO_API_VERSION; } void lto_codegen_set_should_internalize(lto_code_gen_t cg, bool ShouldInternalize) { unwrap(cg)->setShouldInternalize(ShouldInternalize); } void lto_codegen_set_should_embed_uselists(lto_code_gen_t cg, lto_bool_t ShouldEmbedUselists) { unwrap(cg)->setShouldEmbedUselists(ShouldEmbedUselists); }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/lto/CMakeLists.txt
set(LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} Core LTO MC MCDisassembler Support Target ) set(SOURCES LTODisassembler.cpp lto.cpp ) set(LLVM_EXPORTED_SYMBOL_FILE ${CMAKE_CURRENT_SOURCE_DIR}/lto.exports) add_llvm_library(LTO SHARED ${SOURCES}) install(FILES ${LLVM_MAIN_INCLUDE_DIR}/llvm-c/lto.h DESTINATION include/llvm-c)
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/lto/LTODisassembler.cpp
//===-- LTODisassembler.cpp - LTO Disassembler interface ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This function provides utility methods used by clients of libLTO that want // to use the disassembler. // //===----------------------------------------------------------------------===// #include "llvm-c/lto.h" #include "llvm/Support/TargetSelect.h" using namespace llvm; void lto_initialize_disassembler() { // Initialize targets and assembly printers/parsers. llvm::InitializeAllTargetInfos(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmParsers(); llvm::InitializeAllDisassemblers(); }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/TypeDumper.cpp
//===- TypeDumper.cpp - PDBSymDumper implementation for types *----- C++ *-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "TypeDumper.h" #include "BuiltinDumper.h" #include "ClassDefinitionDumper.h" #include "EnumDumper.h" #include "LinePrinter.h" #include "llvm-pdbdump.h" #include "TypedefDumper.h" #include "llvm/DebugInfo/PDB/IPDBSession.h" #include "llvm/DebugInfo/PDB/PDBSymbolExe.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h" using namespace llvm; TypeDumper::TypeDumper(LinePrinter &P) : PDBSymDumper(true), Printer(P) {} void TypeDumper::start(const PDBSymbolExe &Exe) { auto Enums = Exe.findAllChildren<PDBSymbolTypeEnum>(); Printer.NewLine(); WithColor(Printer, PDB_ColorItem::Identifier).get() << "Enums"; Printer << ": (" << Enums->getChildCount() << " items)"; Printer.Indent(); while (auto Enum = Enums->getNext()) Enum->dump(*this); Printer.Unindent(); auto Typedefs = Exe.findAllChildren<PDBSymbolTypeTypedef>(); Printer.NewLine(); WithColor(Printer, PDB_ColorItem::Identifier).get() << "Typedefs"; Printer << ": (" << Typedefs->getChildCount() << " items)"; Printer.Indent(); while (auto Typedef = Typedefs->getNext()) Typedef->dump(*this); Printer.Unindent(); auto Classes = Exe.findAllChildren<PDBSymbolTypeUDT>(); Printer.NewLine(); WithColor(Printer, PDB_ColorItem::Identifier).get() << "Classes"; Printer << ": (" << Classes->getChildCount() << " items)"; Printer.Indent(); while (auto Class = Classes->getNext()) Class->dump(*this); Printer.Unindent(); } void TypeDumper::dump(const PDBSymbolTypeEnum &Symbol) { if (Symbol.getUnmodifiedTypeId() != 0) return; if (Printer.IsTypeExcluded(Symbol.getName())) return; // Dump member enums when dumping their class definition. if (Symbol.isNested()) return; Printer.NewLine(); EnumDumper Dumper(Printer); Dumper.start(Symbol); } void TypeDumper::dump(const PDBSymbolTypeTypedef &Symbol) { if (Printer.IsTypeExcluded(Symbol.getName())) return; Printer.NewLine(); TypedefDumper Dumper(Printer); Dumper.start(Symbol); } void TypeDumper::dump(const PDBSymbolTypeUDT &Symbol) { if (Symbol.getUnmodifiedTypeId() != 0) return; if (Printer.IsTypeExcluded(Symbol.getName())) return; Printer.NewLine(); if (opts::NoClassDefs) { WithColor(Printer, PDB_ColorItem::Keyword).get() << "class "; WithColor(Printer, PDB_ColorItem::Identifier).get() << Symbol.getName(); } else { ClassDefinitionDumper Dumper(Printer); Dumper.start(Symbol); } }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/TypedefDumper.h
//===- TypedefDumper.h - llvm-pdbdump typedef dumper ---------*- C++ ----*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVMPDBDUMP_TYPEDEFDUMPER_H #define LLVM_TOOLS_LLVMPDBDUMP_TYPEDEFDUMPER_H #include "llvm/DebugInfo/PDB/PDBSymDumper.h" namespace llvm { class LinePrinter; class TypedefDumper : public PDBSymDumper { public: TypedefDumper(LinePrinter &P); void start(const PDBSymbolTypeTypedef &Symbol); void dump(const PDBSymbolTypeArray &Symbol) override; void dump(const PDBSymbolTypeBuiltin &Symbol) override; void dump(const PDBSymbolTypeEnum &Symbol) override; void dump(const PDBSymbolTypeFunctionSig &Symbol) override; void dump(const PDBSymbolTypePointer &Symbol) override; void dump(const PDBSymbolTypeUDT &Symbol) override; private: LinePrinter &Printer; }; } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/ClassDefinitionDumper.cpp
//===- ClassDefinitionDumper.cpp --------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ClassDefinitionDumper.h" #include "EnumDumper.h" #include "FunctionDumper.h" #include "LinePrinter.h" #include "llvm-pdbdump.h" #include "TypedefDumper.h" #include "VariableDumper.h" #include "llvm/DebugInfo/PDB/IPDBSession.h" #include "llvm/DebugInfo/PDB/PDBExtras.h" #include "llvm/DebugInfo/PDB/PDBSymbolData.h" #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeBaseClass.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypePointer.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeVTable.h" #include "llvm/Support/Format.h" using namespace llvm; ClassDefinitionDumper::ClassDefinitionDumper(LinePrinter &P) : PDBSymDumper(true), Printer(P) {} void ClassDefinitionDumper::start(const PDBSymbolTypeUDT &Class) { std::string Name = Class.getName(); WithColor(Printer, PDB_ColorItem::Keyword).get() << Class.getUdtKind() << " "; WithColor(Printer, PDB_ColorItem::Type).get() << Class.getName(); auto Bases = Class.findAllChildren<PDBSymbolTypeBaseClass>(); if (Bases->getChildCount() > 0) { Printer.Indent(); Printer.NewLine(); Printer << ":"; uint32_t BaseIndex = 0; while (auto Base = Bases->getNext()) { Printer << " "; WithColor(Printer, PDB_ColorItem::Keyword).get() << Base->getAccess(); if (Base->isVirtualBaseClass()) WithColor(Printer, PDB_ColorItem::Keyword).get() << " virtual"; WithColor(Printer, PDB_ColorItem::Type).get() << " " << Base->getName(); if (++BaseIndex < Bases->getChildCount()) { Printer.NewLine(); Printer << ","; } } Printer.Unindent(); } Printer << " {"; auto Children = Class.findAllChildren(); if (Children->getChildCount() == 0) { Printer << "}"; return; } // Try to dump symbols organized by member access level. Public members // first, then protected, then private. This might be slow, so it's worth // reconsidering the value of this if performance of large PDBs is a problem. // NOTE: Access level of nested types is not recorded in the PDB, so we have // a special case for them. SymbolGroupByAccess Groups; Groups.insert(std::make_pair(0, SymbolGroup())); Groups.insert(std::make_pair((int)PDB_MemberAccess::Private, SymbolGroup())); Groups.insert( std::make_pair((int)PDB_MemberAccess::Protected, SymbolGroup())); Groups.insert(std::make_pair((int)PDB_MemberAccess::Public, SymbolGroup())); while (auto Child = Children->getNext()) { PDB_MemberAccess Access = Child->getRawSymbol().getAccess(); if (isa<PDBSymbolTypeBaseClass>(*Child)) continue; auto &AccessGroup = Groups.find((int)Access)->second; if (auto Func = dyn_cast<PDBSymbolFunc>(Child.get())) { if (Func->isCompilerGenerated() && opts::ExcludeCompilerGenerated) continue; if (Func->getLength() == 0 && !Func->isPureVirtual() && !Func->isIntroVirtualFunction()) continue; Child.release(); AccessGroup.Functions.push_back(std::unique_ptr<PDBSymbolFunc>(Func)); } else if (auto Data = dyn_cast<PDBSymbolData>(Child.get())) { Child.release(); AccessGroup.Data.push_back(std::unique_ptr<PDBSymbolData>(Data)); } else { AccessGroup.Unknown.push_back(std::move(Child)); } } int Count = 0; Count += dumpAccessGroup((PDB_MemberAccess)0, Groups[0]); Count += dumpAccessGroup(PDB_MemberAccess::Public, Groups[(int)PDB_MemberAccess::Public]); Count += dumpAccessGroup(PDB_MemberAccess::Protected, Groups[(int)PDB_MemberAccess::Protected]); Count += dumpAccessGroup(PDB_MemberAccess::Private, Groups[(int)PDB_MemberAccess::Private]); if (Count > 0) Printer.NewLine(); Printer << "}"; } int ClassDefinitionDumper::dumpAccessGroup(PDB_MemberAccess Access, const SymbolGroup &Group) { if (Group.Functions.empty() && Group.Data.empty() && Group.Unknown.empty()) return 0; int Count = 0; if (Access == PDB_MemberAccess::Private) { Printer.NewLine(); WithColor(Printer, PDB_ColorItem::Keyword).get() << "private"; Printer << ":"; } else if (Access == PDB_MemberAccess::Protected) { Printer.NewLine(); WithColor(Printer, PDB_ColorItem::Keyword).get() << "protected"; Printer << ":"; } else if (Access == PDB_MemberAccess::Public) { Printer.NewLine(); WithColor(Printer, PDB_ColorItem::Keyword).get() << "public"; Printer << ":"; } Printer.Indent(); for (auto iter = Group.Functions.begin(), end = Group.Functions.end(); iter != end; ++iter) { ++Count; (*iter)->dump(*this); } for (auto iter = Group.Data.begin(), end = Group.Data.end(); iter != end; ++iter) { ++Count; (*iter)->dump(*this); } for (auto iter = Group.Unknown.begin(), end = Group.Unknown.end(); iter != end; ++iter) { ++Count; (*iter)->dump(*this); } Printer.Unindent(); return Count; } void ClassDefinitionDumper::dump(const PDBSymbolTypeBaseClass &Symbol) {} void ClassDefinitionDumper::dump(const PDBSymbolData &Symbol) { VariableDumper Dumper(Printer); Dumper.start(Symbol); } void ClassDefinitionDumper::dump(const PDBSymbolFunc &Symbol) { if (Printer.IsSymbolExcluded(Symbol.getName())) return; Printer.NewLine(); FunctionDumper Dumper(Printer); Dumper.start(Symbol, FunctionDumper::PointerType::None); } void ClassDefinitionDumper::dump(const PDBSymbolTypeVTable &Symbol) {} void ClassDefinitionDumper::dump(const PDBSymbolTypeEnum &Symbol) { if (Printer.IsTypeExcluded(Symbol.getName())) return; Printer.NewLine(); EnumDumper Dumper(Printer); Dumper.start(Symbol); } void ClassDefinitionDumper::dump(const PDBSymbolTypeTypedef &Symbol) { if (Printer.IsTypeExcluded(Symbol.getName())) return; Printer.NewLine(); TypedefDumper Dumper(Printer); Dumper.start(Symbol); } void ClassDefinitionDumper::dump(const PDBSymbolTypeUDT &Symbol) {}
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/CompilandDumper.cpp
//===- CompilandDumper.cpp - llvm-pdbdump compiland symbol dumper *- C++ *-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "CompilandDumper.h" #include "LinePrinter.h" #include "llvm-pdbdump.h" #include "llvm/DebugInfo/PDB/IPDBEnumChildren.h" #include "llvm/DebugInfo/PDB/IPDBSession.h" #include "llvm/DebugInfo/PDB/PDBExtras.h" #include "llvm/DebugInfo/PDB/PDBSymbol.h" #include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h" #include "llvm/DebugInfo/PDB/PDBSymbolData.h" #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h" #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h" #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h" #include "llvm/DebugInfo/PDB/PDBSymbolLabel.h" #include "llvm/DebugInfo/PDB/PDBSymbolThunk.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h" #include "llvm/DebugInfo/PDB/PDBSymbolUnknown.h" #include "llvm/Support/Format.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include "FunctionDumper.h" #include <utility> #include <vector> using namespace llvm; CompilandDumper::CompilandDumper(LinePrinter &P) : PDBSymDumper(true), Printer(P) {} void CompilandDumper::dump(const PDBSymbolCompilandDetails &Symbol) {} void CompilandDumper::dump(const PDBSymbolCompilandEnv &Symbol) {} void CompilandDumper::start(const PDBSymbolCompiland &Symbol, bool Children) { std::string FullName = Symbol.getName(); if (Printer.IsCompilandExcluded(FullName)) return; Printer.NewLine(); WithColor(Printer, PDB_ColorItem::Path).get() << FullName; if (!Children) return; auto ChildrenEnum = Symbol.findAllChildren(); Printer.Indent(); while (auto Child = ChildrenEnum->getNext()) Child->dump(*this); Printer.Unindent(); } void CompilandDumper::dump(const PDBSymbolData &Symbol) { if (Printer.IsSymbolExcluded(Symbol.getName())) return; Printer.NewLine(); switch (auto LocType = Symbol.getLocationType()) { case PDB_LocType::Static: Printer << "data: "; WithColor(Printer, PDB_ColorItem::Address).get() << "[" << format_hex(Symbol.getVirtualAddress(), 10) << "]"; break; case PDB_LocType::Constant: Printer << "constant: "; WithColor(Printer, PDB_ColorItem::LiteralValue).get() << "[" << Symbol.getValue() << "]"; break; default: Printer << "data(unexpected type=" << LocType << ")"; } Printer << " "; WithColor(Printer, PDB_ColorItem::Identifier).get() << Symbol.getName(); } void CompilandDumper::dump(const PDBSymbolFunc &Symbol) { if (Symbol.getLength() == 0) return; if (Printer.IsSymbolExcluded(Symbol.getName())) return; Printer.NewLine(); FunctionDumper Dumper(Printer); Dumper.start(Symbol, FunctionDumper::PointerType::None); } void CompilandDumper::dump(const PDBSymbolLabel &Symbol) { if (Printer.IsSymbolExcluded(Symbol.getName())) return; Printer.NewLine(); Printer << "label "; WithColor(Printer, PDB_ColorItem::Address).get() << "[" << format_hex(Symbol.getVirtualAddress(), 10) << "] "; WithColor(Printer, PDB_ColorItem::Identifier).get() << Symbol.getName(); } void CompilandDumper::dump(const PDBSymbolThunk &Symbol) { if (Printer.IsSymbolExcluded(Symbol.getName())) return; Printer.NewLine(); Printer << "thunk "; PDB_ThunkOrdinal Ordinal = Symbol.getThunkOrdinal(); uint64_t VA = Symbol.getVirtualAddress(); if (Ordinal == PDB_ThunkOrdinal::TrampIncremental) { uint64_t Target = Symbol.getTargetVirtualAddress(); WithColor(Printer, PDB_ColorItem::Address).get() << format_hex(VA, 10); Printer << " -> "; WithColor(Printer, PDB_ColorItem::Address).get() << format_hex(Target, 10); } else { WithColor(Printer, PDB_ColorItem::Address).get() << "[" << format_hex(VA, 10) << " - " << format_hex(VA + Symbol.getLength(), 10) << "]"; } Printer << " ("; WithColor(Printer, PDB_ColorItem::Register).get() << Ordinal; Printer << ") "; std::string Name = Symbol.getName(); if (!Name.empty()) WithColor(Printer, PDB_ColorItem::Identifier).get() << Name; } void CompilandDumper::dump(const PDBSymbolTypeTypedef &Symbol) {} void CompilandDumper::dump(const PDBSymbolUnknown &Symbol) { Printer.NewLine(); Printer << "unknown (" << Symbol.getSymTag() << ")"; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/FunctionDumper.cpp
//===- FunctionDumper.cpp ------------------------------------ *- C++ *-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "FunctionDumper.h" #include "BuiltinDumper.h" #include "LinePrinter.h" #include "llvm-pdbdump.h" #include "llvm/DebugInfo/PDB/IPDBSession.h" #include "llvm/DebugInfo/PDB/PDBSymbolData.h" #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h" #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h" #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeArray.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionArg.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypePointer.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h" #include "llvm/Support/Format.h" using namespace llvm; namespace { template <class T> void dumpClassParentWithScopeOperator(const T &Symbol, LinePrinter &Printer, llvm::FunctionDumper &Dumper) { uint32_t ClassParentId = Symbol.getClassParentId(); auto ClassParent = Symbol.getSession().template getConcreteSymbolById<PDBSymbolTypeUDT>( ClassParentId); if (!ClassParent) return; WithColor(Printer, PDB_ColorItem::Type).get() << ClassParent->getName(); Printer << "::"; } } FunctionDumper::FunctionDumper(LinePrinter &P) : PDBSymDumper(true), Printer(P) {} void FunctionDumper::start(const PDBSymbolTypeFunctionSig &Symbol, const char *Name, PointerType Pointer) { auto ReturnType = Symbol.getReturnType(); ReturnType->dump(*this); Printer << " "; uint32_t ClassParentId = Symbol.getClassParentId(); auto ClassParent = Symbol.getSession().getConcreteSymbolById<PDBSymbolTypeUDT>( ClassParentId); PDB_CallingConv CC = Symbol.getCallingConvention(); bool ShouldDumpCallingConvention = true; if ((ClassParent && CC == PDB_CallingConv::Thiscall) || (!ClassParent && CC == PDB_CallingConv::NearStdcall)) { ShouldDumpCallingConvention = false; } if (Pointer == PointerType::None) { if (ShouldDumpCallingConvention) WithColor(Printer, PDB_ColorItem::Keyword).get() << CC << " "; if (ClassParent) { Printer << "("; WithColor(Printer, PDB_ColorItem::Identifier).get() << ClassParent->getName(); Printer << "::)"; } } else { Printer << "("; if (ShouldDumpCallingConvention) WithColor(Printer, PDB_ColorItem::Keyword).get() << CC << " "; if (ClassParent) { WithColor(Printer, PDB_ColorItem::Identifier).get() << ClassParent->getName(); Printer << "::"; } if (Pointer == PointerType::Reference) Printer << "&"; else Printer << "*"; if (Name) WithColor(Printer, PDB_ColorItem::Identifier).get() << Name; Printer << ")"; } Printer << "("; if (auto ChildEnum = Symbol.getArguments()) { uint32_t Index = 0; while (auto Arg = ChildEnum->getNext()) { Arg->dump(*this); if (++Index < ChildEnum->getChildCount()) Printer << ", "; } } Printer << ")"; if (Symbol.isConstType()) WithColor(Printer, PDB_ColorItem::Keyword).get() << " const"; if (Symbol.isVolatileType()) WithColor(Printer, PDB_ColorItem::Keyword).get() << " volatile"; } void FunctionDumper::start(const PDBSymbolFunc &Symbol, PointerType Pointer) { uint64_t FuncStart = Symbol.getVirtualAddress(); uint64_t FuncEnd = FuncStart + Symbol.getLength(); Printer << "func ["; WithColor(Printer, PDB_ColorItem::Address).get() << format_hex(FuncStart, 10); if (auto DebugStart = Symbol.findOneChild<PDBSymbolFuncDebugStart>()) { uint64_t Prologue = DebugStart->getVirtualAddress() - FuncStart; WithColor(Printer, PDB_ColorItem::Offset).get() << "+" << Prologue; } Printer << " - "; WithColor(Printer, PDB_ColorItem::Address).get() << format_hex(FuncEnd, 10); if (auto DebugEnd = Symbol.findOneChild<PDBSymbolFuncDebugEnd>()) { uint64_t Epilogue = FuncEnd - DebugEnd->getVirtualAddress(); WithColor(Printer, PDB_ColorItem::Offset).get() << "-" << Epilogue; } Printer << "] ("; if (Symbol.hasFramePointer()) { WithColor(Printer, PDB_ColorItem::Register).get() << Symbol.getLocalBasePointerRegisterId(); } else { WithColor(Printer, PDB_ColorItem::Register).get() << "FPO"; } Printer << ") "; if (Symbol.isVirtual() || Symbol.isPureVirtual()) WithColor(Printer, PDB_ColorItem::Keyword).get() << "virtual "; auto Signature = Symbol.getSignature(); if (!Signature) { WithColor(Printer, PDB_ColorItem::Identifier).get() << Symbol.getName(); if (Pointer == PointerType::Pointer) Printer << "*"; else if (Pointer == FunctionDumper::PointerType::Reference) Printer << "&"; return; } auto ReturnType = Signature->getReturnType(); ReturnType->dump(*this); Printer << " "; auto ClassParent = Symbol.getClassParent(); PDB_CallingConv CC = Signature->getCallingConvention(); if (Pointer != FunctionDumper::PointerType::None) Printer << "("; if ((ClassParent && CC != PDB_CallingConv::Thiscall) || (!ClassParent && CC != PDB_CallingConv::NearStdcall)) { WithColor(Printer, PDB_ColorItem::Keyword).get() << Signature->getCallingConvention() << " "; } WithColor(Printer, PDB_ColorItem::Identifier).get() << Symbol.getName(); if (Pointer != FunctionDumper::PointerType::None) { if (Pointer == PointerType::Pointer) Printer << "*"; else if (Pointer == FunctionDumper::PointerType::Reference) Printer << "&"; Printer << ")"; } Printer << "("; if (auto Arguments = Symbol.getArguments()) { uint32_t Index = 0; while (auto Arg = Arguments->getNext()) { auto ArgType = Arg->getType(); ArgType->dump(*this); WithColor(Printer, PDB_ColorItem::Identifier).get() << " " << Arg->getName(); if (++Index < Arguments->getChildCount()) Printer << ", "; } } Printer << ")"; if (Symbol.isConstType()) WithColor(Printer, PDB_ColorItem::Keyword).get() << " const"; if (Symbol.isVolatileType()) WithColor(Printer, PDB_ColorItem::Keyword).get() << " volatile"; if (Symbol.isPureVirtual()) Printer << " = 0"; } void FunctionDumper::dump(const PDBSymbolTypeArray &Symbol) { uint32_t ElementTypeId = Symbol.getTypeId(); auto ElementType = Symbol.getSession().getSymbolById(ElementTypeId); if (!ElementType) return; ElementType->dump(*this); Printer << "["; WithColor(Printer, PDB_ColorItem::LiteralValue).get() << Symbol.getLength(); Printer << "]"; } void FunctionDumper::dump(const PDBSymbolTypeBuiltin &Symbol) { BuiltinDumper Dumper(Printer); Dumper.start(Symbol); } void FunctionDumper::dump(const PDBSymbolTypeEnum &Symbol) { dumpClassParentWithScopeOperator(Symbol, Printer, *this); WithColor(Printer, PDB_ColorItem::Type).get() << Symbol.getName(); } void FunctionDumper::dump(const PDBSymbolTypeFunctionArg &Symbol) { // PDBSymbolTypeFunctionArg is just a shim over the real argument. Just drill // through to the real thing and dump it. uint32_t TypeId = Symbol.getTypeId(); auto Type = Symbol.getSession().getSymbolById(TypeId); if (!Type) return; Type->dump(*this); } void FunctionDumper::dump(const PDBSymbolTypeTypedef &Symbol) { dumpClassParentWithScopeOperator(Symbol, Printer, *this); WithColor(Printer, PDB_ColorItem::Type).get() << Symbol.getName(); } void FunctionDumper::dump(const PDBSymbolTypePointer &Symbol) { uint32_t PointeeId = Symbol.getTypeId(); auto PointeeType = Symbol.getSession().getSymbolById(PointeeId); if (!PointeeType) return; if (auto FuncSig = dyn_cast<PDBSymbolTypeFunctionSig>(PointeeType.get())) { FunctionDumper NestedDumper(Printer); PointerType Pointer = Symbol.isReference() ? PointerType::Reference : PointerType::Pointer; NestedDumper.start(*FuncSig, nullptr, Pointer); } else { if (Symbol.isConstType()) WithColor(Printer, PDB_ColorItem::Keyword).get() << "const "; if (Symbol.isVolatileType()) WithColor(Printer, PDB_ColorItem::Keyword).get() << "volatile "; PointeeType->dump(*this); Printer << (Symbol.isReference() ? "&" : "*"); } } void FunctionDumper::dump(const PDBSymbolTypeUDT &Symbol) { WithColor(Printer, PDB_ColorItem::Type).get() << Symbol.getName(); }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/ExternalSymbolDumper.cpp
//===- ExternalSymbolDumper.cpp -------------------------------- *- C++ *-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ExternalSymbolDumper.h" #include "LinePrinter.h" #include "llvm/DebugInfo/PDB/PDBSymbolExe.h" #include "llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h" #include "llvm/Support/Format.h" using namespace llvm; ExternalSymbolDumper::ExternalSymbolDumper(LinePrinter &P) : PDBSymDumper(true), Printer(P) {} void ExternalSymbolDumper::start(const PDBSymbolExe &Symbol) { auto Vars = Symbol.findAllChildren<PDBSymbolPublicSymbol>(); while (auto Var = Vars->getNext()) Var->dump(*this); } void ExternalSymbolDumper::dump(const PDBSymbolPublicSymbol &Symbol) { std::string LinkageName = Symbol.getName(); if (Printer.IsSymbolExcluded(LinkageName)) return; Printer.NewLine(); uint64_t Addr = Symbol.getVirtualAddress(); Printer << "["; WithColor(Printer, PDB_ColorItem::Address).get() << format_hex(Addr, 10); Printer << "] "; WithColor(Printer, PDB_ColorItem::Identifier).get() << LinkageName; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/FunctionDumper.h
//===- FunctionDumper.h --------------------------------------- *- C++ --*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVMPDBDUMP_FUNCTIONDUMPER_H #define LLVM_TOOLS_LLVMPDBDUMP_FUNCTIONDUMPER_H #include "llvm/DebugInfo/PDB/PDBSymDumper.h" namespace llvm { class LinePrinter; class FunctionDumper : public PDBSymDumper { public: FunctionDumper(LinePrinter &P); enum class PointerType { None, Pointer, Reference }; void start(const PDBSymbolTypeFunctionSig &Symbol, const char *Name, PointerType Pointer); void start(const PDBSymbolFunc &Symbol, PointerType Pointer); void dump(const PDBSymbolTypeArray &Symbol) override; void dump(const PDBSymbolTypeBuiltin &Symbol) override; void dump(const PDBSymbolTypeEnum &Symbol) override; void dump(const PDBSymbolTypeFunctionArg &Symbol) override; void dump(const PDBSymbolTypePointer &Symbol) override; void dump(const PDBSymbolTypeTypedef &Symbol) override; void dump(const PDBSymbolTypeUDT &Symbol) override; private: LinePrinter &Printer; }; } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/llvm-pdbdump.h
//===- llvm-pdbdump.h ----------------------------------------- *- C++ --*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVMPDBDUMP_LLVMPDBDUMP_H #define LLVM_TOOLS_LLVMPDBDUMP_LLVMPDBDUMP_H #include "llvm/Support/CommandLine.h" #include "llvm/Support/raw_ostream.h" namespace opts { extern llvm::cl::opt<bool> Compilands; extern llvm::cl::opt<bool> Symbols; extern llvm::cl::opt<bool> Globals; extern llvm::cl::opt<bool> Types; extern llvm::cl::opt<bool> All; extern llvm::cl::opt<bool> ExcludeCompilerGenerated; extern llvm::cl::opt<bool> NoClassDefs; extern llvm::cl::opt<bool> NoEnumDefs; extern llvm::cl::list<std::string> ExcludeTypes; extern llvm::cl::list<std::string> ExcludeSymbols; extern llvm::cl::list<std::string> ExcludeCompilands; } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/LinePrinter.cpp
//===- LinePrinter.cpp ------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "LinePrinter.h" #include "llvm-pdbdump.h" #include "llvm/Support/Regex.h" #include <algorithm> using namespace llvm; LinePrinter::LinePrinter(int Indent, llvm::raw_ostream &Stream) : OS(Stream), IndentSpaces(Indent), CurrentIndent(0) { SetFilters(TypeFilters, opts::ExcludeTypes.begin(), opts::ExcludeTypes.end()); SetFilters(SymbolFilters, opts::ExcludeSymbols.begin(), opts::ExcludeSymbols.end()); SetFilters(CompilandFilters, opts::ExcludeCompilands.begin(), opts::ExcludeCompilands.end()); } void LinePrinter::Indent() { CurrentIndent += IndentSpaces; } void LinePrinter::Unindent() { CurrentIndent = std::max(0, CurrentIndent - IndentSpaces); } void LinePrinter::NewLine() { OS << "\n"; OS.indent(CurrentIndent); } bool LinePrinter::IsTypeExcluded(llvm::StringRef TypeName) { if (TypeName.empty()) return false; for (auto &Expr : TypeFilters) { if (Expr.match(TypeName)) return true; } return false; } bool LinePrinter::IsSymbolExcluded(llvm::StringRef SymbolName) { if (SymbolName.empty()) return false; for (auto &Expr : SymbolFilters) { if (Expr.match(SymbolName)) return true; } return false; } bool LinePrinter::IsCompilandExcluded(llvm::StringRef CompilandName) { if (CompilandName.empty()) return false; for (auto &Expr : CompilandFilters) { if (Expr.match(CompilandName)) return true; } return false; } WithColor::WithColor(LinePrinter &P, PDB_ColorItem C) : OS(P.OS) { if (C == PDB_ColorItem::None) OS.resetColor(); else { raw_ostream::Colors Color; bool Bold; translateColor(C, Color, Bold); OS.changeColor(Color, Bold); } } WithColor::~WithColor() { OS.resetColor(); } void WithColor::translateColor(PDB_ColorItem C, raw_ostream::Colors &Color, bool &Bold) const { switch (C) { case PDB_ColorItem::Address: Color = raw_ostream::YELLOW; Bold = true; return; case PDB_ColorItem::Keyword: Color = raw_ostream::MAGENTA; Bold = true; return; case PDB_ColorItem::Register: case PDB_ColorItem::Offset: Color = raw_ostream::YELLOW; Bold = false; return; case PDB_ColorItem::Type: Color = raw_ostream::CYAN; Bold = true; return; case PDB_ColorItem::Identifier: Color = raw_ostream::CYAN; Bold = false; return; case PDB_ColorItem::Path: Color = raw_ostream::CYAN; Bold = false; return; case PDB_ColorItem::SectionHeader: Color = raw_ostream::RED; Bold = true; return; case PDB_ColorItem::LiteralValue: Color = raw_ostream::GREEN; Bold = true; default: return; } }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/BuiltinDumper.cpp
//===- BuiltinDumper.cpp ---------------------------------------- *- C++ *-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "BuiltinDumper.h" #include "LinePrinter.h" #include "llvm-pdbdump.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h" using namespace llvm; BuiltinDumper::BuiltinDumper(LinePrinter &P) : PDBSymDumper(false), Printer(P) {} void BuiltinDumper::start(const PDBSymbolTypeBuiltin &Symbol) { PDB_BuiltinType Type = Symbol.getBuiltinType(); switch (Type) { case PDB_BuiltinType::Float: if (Symbol.getLength() == 4) WithColor(Printer, PDB_ColorItem::Type).get() << "float"; else WithColor(Printer, PDB_ColorItem::Type).get() << "double"; break; case PDB_BuiltinType::UInt: WithColor(Printer, PDB_ColorItem::Type).get() << "unsigned"; if (Symbol.getLength() == 8) WithColor(Printer, PDB_ColorItem::Type).get() << " __int64"; break; case PDB_BuiltinType::Int: if (Symbol.getLength() == 4) WithColor(Printer, PDB_ColorItem::Type).get() << "int"; else WithColor(Printer, PDB_ColorItem::Type).get() << "__int64"; break; case PDB_BuiltinType::Char: WithColor(Printer, PDB_ColorItem::Type).get() << "char"; break; case PDB_BuiltinType::WCharT: WithColor(Printer, PDB_ColorItem::Type).get() << "wchar_t"; break; case PDB_BuiltinType::Void: WithColor(Printer, PDB_ColorItem::Type).get() << "void"; break; case PDB_BuiltinType::Long: WithColor(Printer, PDB_ColorItem::Type).get() << "long"; break; case PDB_BuiltinType::ULong: WithColor(Printer, PDB_ColorItem::Type).get() << "unsigned long"; break; case PDB_BuiltinType::Bool: WithColor(Printer, PDB_ColorItem::Type).get() << "bool"; break; case PDB_BuiltinType::Currency: WithColor(Printer, PDB_ColorItem::Type).get() << "CURRENCY"; break; case PDB_BuiltinType::Date: WithColor(Printer, PDB_ColorItem::Type).get() << "DATE"; break; case PDB_BuiltinType::Variant: WithColor(Printer, PDB_ColorItem::Type).get() << "VARIANT"; break; case PDB_BuiltinType::Complex: WithColor(Printer, PDB_ColorItem::Type).get() << "complex"; break; case PDB_BuiltinType::Bitfield: WithColor(Printer, PDB_ColorItem::Type).get() << "bitfield"; break; case PDB_BuiltinType::BSTR: WithColor(Printer, PDB_ColorItem::Type).get() << "BSTR"; break; case PDB_BuiltinType::HResult: WithColor(Printer, PDB_ColorItem::Type).get() << "HRESULT"; break; case PDB_BuiltinType::BCD: WithColor(Printer, PDB_ColorItem::Type).get() << "HRESULT"; break; default: WithColor(Printer, PDB_ColorItem::Type).get() << "void"; break; } }