Repository: ALSchwalm/dwarfexport Branch: master Commit: b955cf1e2f5c Files: 29 Total size: 102.4 KB Directory structure: gitextract_2p7ia_lt/ ├── LICENSE ├── MSVC.mk ├── Makefile ├── Makefile.MSVC ├── Makefile.osx ├── README.md ├── bin/ │ ├── dwarfexport.p64 │ ├── dwarfexport.plw │ ├── dwarfexport.plx │ ├── dwarfexport.plx64 │ ├── dwarfexport.pmc │ └── dwarfexport.pmc64 ├── deps/ │ ├── Makefile-libdwarf.MSVC │ ├── Makefile-libelf.MSVC │ ├── lib/ │ │ └── .gitignore │ ├── libdwarf-helpers/ │ │ ├── config.h │ │ ├── libdwarf/ │ │ │ └── libdwarf.h │ │ └── libdwarf.h │ └── libelf-helpers/ │ ├── config.h │ ├── libelf/ │ │ ├── elf_repl.h │ │ ├── libelf.h │ │ └── sys_elf.h │ └── sys_elf.h ├── lib/ │ ├── libdwarf32.a │ └── libelf32.a └── src/ ├── dwarfexport.cpp ├── dwarfexport.h ├── dwarfgen.cpp └── platform.cpp ================================================ FILE CONTENTS ================================================ ================================================ FILE: LICENSE ================================================ GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice ================================================ FILE: MSVC.mk ================================================ !IF "$(PLATFORM)" == "x86" OBJSUFFIX=.obj32 LIBSUFFIX=.lib DLLSUFFIX=.dll IDALIB=x86_win_vc_32\ida.lib IDACXXFLAGS=/D__X86__ GCCLIKECFLAGS=/D__i386 !ELSEIF "$(PLATFORM)" == "x64" OBJSUFFIX=.obj64 LIBSUFFIX=64.lib DLLSUFFIX=64.dll IDALIB=x64_win_vc_64\ida.lib IDACXXFLAGS=/D__X64__ /D__EA64__ GCCLIKECFLAGS=/D__x86_64 !ELSE !ERROR Unsupported platform !ENDIF CC=cl CXX=cl AR=lib LD=link LDFLAGS=/DEBUG RM=del COMMONCFLAGS=/O2 /Z7 /W3 $(GCCLIKECFLAGS) COMMONCXXFLAGS=$(COMMONCFLAGS) /EHsc ================================================ FILE: Makefile ================================================ CXX ?= g++ CXXFLAGS=-m32 -fPIC -shared -Wall -Wextra -std=c++11 LDFLAGS+=-static-libgcc -static-libstdc++ LIBS=-lida lib/libelf32.a lib/libdwarf32.a INCLUDES=-I$(IDASDK_PATH)/include -I$(IDA_PATH)/plugins/hexrays_sdk/include DWARFEXPORT_SRC = $(wildcard src/*.cpp) all: bin/dwarfexport.plx bin/dwarfexport.plx64 bin/dwarfexport.plx: $(DWARFEXPORT_SRC) $(CXX) $(LDFLAGS) $(DWARFEXPORT_SRC) $(CXXFLAGS) \ -L. \ -L$(IDA_PATH) \ $(INCLUDES) \ -D__LINUX__ $(LIBS) -o bin/dwarfexport.plx bin/dwarfexport.plx64: $(DWARFEXPORT_SRC) $(CXX) $(LDFLAGS) $(DWARFEXPORT_SRC) $(CXXFLAGS) \ -L. \ -L$(IDA_PATH) \ $(INCLUDES) \ -D__LINUX__ -D__EA64__ $(LIBS) -o bin/dwarfexport.plx64 clean: rm -f bin/dwarfexport.plx bin/dwarfexport.plx64 ================================================ FILE: Makefile.MSVC ================================================ !include MSVC.mk CXXFLAGS=$(COMMONCXXFLAGS) \ $(IDACXXFLAGS) \ /D__NT__ \ /DUSE_STANDARD_FILE_FUNCTIONS \ /I"$(IDASDK_PATH)"\include \ /I"$(IDA_PATH)"\plugins\hexrays_sdk\include \ /Ideps\libdwarf-helpers \ /Ideps\libdwarf\libdwarf \ /Ideps\libelf-helpers \ /Ideps\libelf-0.8.13\lib OBJECTS=src\dwarfexport$(OBJSUFFIX) \ src\dwarfgen$(OBJSUFFIX) \ src\platform$(OBJSUFFIX) all: bin\dwarfexport$(DLLSUFFIX) bin\dwarfexport$(DLLSUFFIX): $(OBJECTS) \ deps\lib\libdwarf$(LIBSUFFIX) \ deps\lib\libelf$(LIBSUFFIX) $(LD) /DLL $(LDFLAGS) /OUT:$@ $(OBJECTS) \ deps\lib\libdwarf$(LIBSUFFIX) \ deps\lib\libelf$(LIBSUFFIX) \ "$(IDASDK_PATH)"\lib\$(IDALIB) deps\lib\libdwarf$(LIBSUFFIX): deps\Makefile-libdwarf.MSVC cd deps $(MAKE) /f Makefile-libdwarf.MSVC cd .. deps\lib\libelf$(LIBSUFFIX): deps\Makefile-libelf.MSVC cd deps $(MAKE) /f Makefile-libelf.MSVC cd .. .cpp$(OBJSUFFIX): $(CXX) /c $(CXXFLAGS) /Fo:$@ $< clean: $(RM) $(OBJECTS) bin\dwarfexport$(DLLSUFFIX) cd deps $(MAKE) /f Makefile-libdwarf.MSVC clean $(MAKE) /f Makefile-libelf.MSVC clean cd .. ================================================ FILE: Makefile.osx ================================================ CXX ?= clang++ MACSDK=$(shell xcrun --show-sdk-path --sdk macosx) CXXFLAGS=-m32 -fPIC -shared -Wall -Wextra -std=c++14 -isysroot $(MACSDK) -stdlib=libc++ -DUSE_DANGEROUS_FUNCTIONS=1 -DUSE_STANDARD_FILE_FUNCTIONS=1 LDFLAGS=-Lthirdparty/libelf-0.8.13/lib -Lthirdparty/libdwarf/libdwarf LIBS=-lelf -ldwarf -lz INCLUDES=-I$(IDASDK_PATH)/include -I$(IDA_PATH)/plugins/hexrays_sdk/include -Ithirdparty/libdwarf -I/usr/local/include DWARFEXPORT_SRC = $(wildcard src/*.cpp) all: check-env bin/dwarfexport.pmc bin/dwarfexport.pmc64 bin/dwarfexport.pmc: $(DWARFEXPORT_SRC) $(CXX) $(LDFLAGS) $(DWARFEXPORT_SRC) $(CXXFLAGS) \ -L. \ -L$(IDA_PATH) \ $(INCLUDES) \ -D__MAC__ $(LIBS) -lida -o bin/dwarfexport.pmc bin/dwarfexport.pmc64: $(DWARFEXPORT_SRC) $(CXX) $(LDFLAGS) $(DWARFEXPORT_SRC) $(CXXFLAGS) \ -L. \ -L$(IDA_PATH) \ $(INCLUDES) \ -D__MAC__ -D__EA64__ $(LIBS) -lida64 -o bin/dwarfexport.pmc64 clean: rm -f bin/dwarfexport.pmc bin/dwarfexport.pmc64 install: cp -f bin/dwarfexport.pmc $(IDA_PATH)/plugins/ cp -f bin/dwarfexport.pmc64 $(IDA_PATH)/plugins/ check-env: ifndef IDASDK_PATH $(error IDASDK_PATH is undefined) endif ifndef IDA_PATH $(error IDA_PATH is undefined) endif .PHONY: check-env ================================================ FILE: README.md ================================================ This Project is Unmaintained ============================ Due to a change in occupation, I no longer have access to IDA, so this project is unmaintained. If you are interested in becoming a maintainer, please let me know. Otherwise, it is unlikely I'll will merge anything but trivial merge requests. dwarfexport =========== `dwarfexport` is an IDA Pro plugin that allows the user to export `dwarf` debug information. This can then be imported in to gdb and other tools, allowing you to debug using info you have recovered in IDA even when you cannot connect the IDA debugger. Usage ----- Pre-compiled copies of `dwarfexport` are available in the `bin` folder of this project. Just add these files to your IDA `plugins` folder (plx and plx64 for linux, plw and p64 for windows) and you will have a new option "Edit->Plugins->Export Dwarf Debug Info". Click this and select a folder for the output. The plugin will generate two files in the output directory. One will be a `.c` file with the decompiled functions from the Hexrays decompiler. The other is a `.dbg` file that contains the debug information. *Note that because the plugin performs decompilation on every function in the binary, it can take a while to run.* Move these to the device you want to debug on and load gdb (e.x, `gdb a.out`). You will have full debug information, like normal gdb with source (shown below using TUI mode): ![debugging in gdb](/resources/screenshot.png) *Note: You may need to run `list` to get the source file loaded.* Options ------- The following options are available from the plugin GUI `Use Decompiler`: On architectures where the decompiler is available, opt out of using it. `Attach Debug Info`: When checked, a `.dbg` file is created with the debug information. However, this will only work if the target is an ELF file. When the target is not an ELF file, uncheck this option to create a group of binary files (one for reach ELF section that would have been created). Building On Linux ----------------- `dwarfexport` depends on the IDA SDK as well as a `libdwarf`. Once you have these available (a statically compiled copy of `libdwarf` is provided), you can set the environment variables IDASDK\_PATH and IDA\_PATH to the SDK path and your IDA folder location respectively. Then build the plugin using `make`. Building On Windows ------------------- Windows build can be performed using MSVC Compiler (cl.exe) and NMAKE (nmake.exe). First, download and extract [libdwarf]( https://sourceforge.net/p/libdwarf/code/ci/master/tree/) source code into `deps/libdwarf` and [libelf]( https://fossies.org/linux/misc/old/libelf-0.8.13.tar.gz/) source code into `deps/libelf-0.8.13`. The commands below assume WSL/MinGW/Cygwin, but you can use any other method that you prefer. ``` $ git clone git://git.code.sf.net/p/libdwarf/code deps/libdwarf $ (cd deps/libdwarf && git checkout 988618dc8be8) $ curl https://fossies.org/linux/misc/old/libelf-0.8.13.tar.gz | tar -C deps -xz ``` Then, NMAKE can be invoked through x86 or x64 Native Tools Command Prompt for VS (depending on whether you need 32-bit or 64-bit plugin) as follows: ``` dwarfexport> nmake /f Makefile.MSVC IDA_PATH="C:\Program Files\IDA 7.2" IDASDK_PATH="C:\Program Files\IDA 7.2\sdk" ``` 32-bit version will be placed into `bin\dwarfexport.dll`, 64-bit version will be placed into `bin\dwarfexport64.dll`. Building on macOS ----------------- To build dwarfexport on macOS, you must build and install 32-bit versions of libelf and libdwarf. ``` # Download, build, and install libelf (it's a libdwarf prereq) $ mkdir -p thirdparty $ pushd thirdparty $ wget http://www.mr511.de/software/libelf-0.8.13.tar.gz $ tar zxf libelf-0.8.13.tar.gz $ pushd libelf-0.8.13 $ CFLAGS=-m32 CXXFLAGS=-m32 ./configure $ make && make install $ popd # Clone, build, and install libdwarf $ git clone git@github.com:tomhughes/libdwarf.git $ pushd libdwarf/ $ CFLAGS=-m32 CXXFLAGS=-m32 ./configure $ make && make install $ popd $ popd # Build dwarfexport for macos $ IDA_PATH="/Applications/IDA\ Pro\ 6.95/idaq.app/Contents/MacOS/" IDASDK_PATH="" make -f Makefile.osx ``` Adding Support for Other Architectures -------------------------------------- There are three functions that need to be modified to add support for a new architectures. They are all located in `platform.cpp`: `translate_register_num`: Translates from IDA register numbers to DWARF numbers. The IDA register numbering can be found by running `idaapi.ph_get_regnames()`. The index of a register in the returned list is its 'IDA register number'. A variety of resources exist to find the DWARF mapping for a given architecture. For example, [wine](https://source.winehq.org/source/dlls/dbghelp/cpu_x86_64.c) has the numbers for some architectures (see `x86_64_map_dwarf_register`). `disassembler_lvar_reg_and_offset`: This function should set the `reg` and `offset` parameters to a dwarf register and the offset from that register that should be used to read from a stack variable 'member'. So `reg` will typically be a register containing a pointer to the top or bottom of the stack (so `DW_OP_breg5` is register 5 which is EBP on x86), and the offset will then be the offset from the bottom or top of the stack. `decompiler_lvar_reg_and_offset`: On architectures supporting the decompiler, this function should be modified to perform the same work as the above function, but with a `lvar_t` from the Hexrays decompiler. Note that it may be acceptable to reuse the disassembler logic. License ------- `dwarfexport` is licensed under the terms of the LGPLv2.1. See the LICENSE file for details. ================================================ FILE: deps/Makefile-libdwarf.MSVC ================================================ !include ..\MSVC.mk CFLAGS=$(COMMONCFLAGS) /DHAVE_CONFIG_H /Ilibdwarf-helpers /Ilibdwarf/libdwarf # Adapted by a simple search-and-replace from am_libdwarf_la_OBJECTS # variable in libdwarf\libdwarf\Makefile.in. OBJECTS=libdwarf\libdwarf\dwarf_abbrev$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_alloc$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_arange$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_debuglink$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_die_deliv$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_dnames$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_dsc$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_elf_access$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_elf_load_headers$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_elfread$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_elf_rel_detector$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_error$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_form$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_frame$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_frame2$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_funcs$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_gdbindex$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_generic_init$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_global$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_groups$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_harmless$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_init_finish$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_leb$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_line$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_loc$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_machoread$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_macro$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_macro5$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_names$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_object_detector$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_object_read_common$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_original_elf_init$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_peread$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_print_lines$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_pubtypes$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_query$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_ranges$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_str_offsets$(OBJSUFFIX) \ libdwarf\libdwarf\dwarfstring$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_stringsection$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_tied$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_tsearchhash$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_types$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_util$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_vars$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_weaks$(OBJSUFFIX) \ libdwarf\libdwarf\dwarf_xu_index$(OBJSUFFIX) \ libdwarf\libdwarf\malloc_check$(OBJSUFFIX) \ libdwarf\libdwarf\pro_alloc$(OBJSUFFIX) \ libdwarf\libdwarf\pro_arange$(OBJSUFFIX) \ libdwarf\libdwarf\pro_die$(OBJSUFFIX) \ libdwarf\libdwarf\pro_dnames$(OBJSUFFIX) \ libdwarf\libdwarf\pro_encode_nm$(OBJSUFFIX) \ libdwarf\libdwarf\pro_error$(OBJSUFFIX) \ libdwarf\libdwarf\pro_expr$(OBJSUFFIX) \ libdwarf\libdwarf\pro_finish$(OBJSUFFIX) \ libdwarf\libdwarf\pro_forms$(OBJSUFFIX) \ libdwarf\libdwarf\pro_frame$(OBJSUFFIX) \ libdwarf\libdwarf\pro_funcs$(OBJSUFFIX) \ libdwarf\libdwarf\pro_init$(OBJSUFFIX) \ libdwarf\libdwarf\pro_line$(OBJSUFFIX) \ libdwarf\libdwarf\pro_log_extra_flag_strings$(OBJSUFFIX) \ libdwarf\libdwarf\pro_macinfo$(OBJSUFFIX) \ libdwarf\libdwarf\pro_pubnames$(OBJSUFFIX) \ libdwarf\libdwarf\pro_reloc$(OBJSUFFIX) \ libdwarf\libdwarf\pro_reloc_stream$(OBJSUFFIX) \ libdwarf\libdwarf\pro_reloc_symbolic$(OBJSUFFIX) \ libdwarf\libdwarf\pro_section$(OBJSUFFIX) \ libdwarf\libdwarf\pro_types$(OBJSUFFIX) \ libdwarf\libdwarf\pro_vars$(OBJSUFFIX) \ libdwarf\libdwarf\pro_weaks$(OBJSUFFIX) lib\libdwarf$(LIBSUFFIX): $(OBJECTS) $(AR) -OUT:$@ $(OBJECTS) .c$(OBJSUFFIX): $(CC) /c $(CFLAGS) /Fo:$@ $< clean: $(RM) $(OBJECTS) lib\libdwarf$(LIBSUFFIX) ================================================ FILE: deps/Makefile-libelf.MSVC ================================================ !include ..\MSVC.mk CFLAGS=$(COMMONCFLAGS) /DHAVE_CONFIG_H /Ilibelf-helpers /Ilibelf-0.8.13\lib # Adapted by a simple search-and-replace from SRCS* # variables in libelf-0.8.13\lib. OBJECTS=libelf-0.8.13\lib\begin$(OBJSUFFIX) \ libelf-0.8.13\lib\cntl$(OBJSUFFIX) \ libelf-0.8.13\lib\end$(OBJSUFFIX) \ libelf-0.8.13\lib\errmsg$(OBJSUFFIX) \ libelf-0.8.13\lib\errno$(OBJSUFFIX) \ libelf-0.8.13\lib\fill$(OBJSUFFIX) \ libelf-0.8.13\lib\flag$(OBJSUFFIX) \ libelf-0.8.13\lib\getarhdr$(OBJSUFFIX) \ libelf-0.8.13\lib\getarsym$(OBJSUFFIX) \ libelf-0.8.13\lib\getbase$(OBJSUFFIX) \ libelf-0.8.13\lib\getdata$(OBJSUFFIX) \ libelf-0.8.13\lib\getident$(OBJSUFFIX) \ libelf-0.8.13\lib\getscn$(OBJSUFFIX) \ libelf-0.8.13\lib\hash$(OBJSUFFIX) \ libelf-0.8.13\lib\kind$(OBJSUFFIX) \ libelf-0.8.13\lib\ndxscn$(OBJSUFFIX) \ libelf-0.8.13\lib\newdata$(OBJSUFFIX) \ libelf-0.8.13\lib\newscn$(OBJSUFFIX) \ libelf-0.8.13\lib\next$(OBJSUFFIX) \ libelf-0.8.13\lib\nextscn$(OBJSUFFIX) \ libelf-0.8.13\lib\rand$(OBJSUFFIX) \ libelf-0.8.13\lib\rawdata$(OBJSUFFIX) \ libelf-0.8.13\lib\rawfile$(OBJSUFFIX) \ libelf-0.8.13\lib\strptr$(OBJSUFFIX) \ libelf-0.8.13\lib\update$(OBJSUFFIX) \ libelf-0.8.13\lib\version$(OBJSUFFIX) \ libelf-0.8.13\lib\checksum$(OBJSUFFIX) \ libelf-0.8.13\lib\getaroff$(OBJSUFFIX) \ libelf-0.8.13\lib\32.fsize$(OBJSUFFIX) \ libelf-0.8.13\lib\32.getehdr$(OBJSUFFIX) \ libelf-0.8.13\lib\32.getphdr$(OBJSUFFIX) \ libelf-0.8.13\lib\32.getshdr$(OBJSUFFIX) \ libelf-0.8.13\lib\32.newehdr$(OBJSUFFIX) \ libelf-0.8.13\lib\32.newphdr$(OBJSUFFIX) \ libelf-0.8.13\lib\32.xlatetof$(OBJSUFFIX) \ libelf-0.8.13\lib\cook$(OBJSUFFIX) \ libelf-0.8.13\lib\data$(OBJSUFFIX) \ libelf-0.8.13\lib\input$(OBJSUFFIX) \ libelf-0.8.13\lib\assert$(OBJSUFFIX) \ libelf-0.8.13\lib\nlist$(OBJSUFFIX) \ libelf-0.8.13\lib\opt.delscn$(OBJSUFFIX) \ libelf-0.8.13\lib\x.remscn$(OBJSUFFIX) \ libelf-0.8.13\lib\x.movscn$(OBJSUFFIX) \ libelf-0.8.13\lib\x.elfext$(OBJSUFFIX) \ libelf-0.8.13\lib\64.xlatetof$(OBJSUFFIX) \ libelf-0.8.13\lib\gelfehdr$(OBJSUFFIX) \ libelf-0.8.13\lib\gelfphdr$(OBJSUFFIX) \ libelf-0.8.13\lib\gelfshdr$(OBJSUFFIX) \ libelf-0.8.13\lib\gelftrans$(OBJSUFFIX) \ libelf-0.8.13\lib\swap64$(OBJSUFFIX) \ libelf-0.8.13\lib\verdef_32_tof$(OBJSUFFIX) \ libelf-0.8.13\lib\verdef_32_tom$(OBJSUFFIX) \ libelf-0.8.13\lib\verdef_64_tof$(OBJSUFFIX) \ libelf-0.8.13\lib\verdef_64_tom$(OBJSUFFIX) lib\libelf$(LIBSUFFIX): $(OBJECTS) $(AR) -OUT:$@ $(OBJECTS) .c$(OBJSUFFIX): $(CC) /c $(CFLAGS) /Fo:$@ $< clean: $(RM) $(OBJECTS) lib\libelf$(LIBSUFFIX) ================================================ FILE: deps/lib/.gitignore ================================================ ================================================ FILE: deps/libdwarf-helpers/config.h ================================================ #define HAVE_MALLOC_H 1 ================================================ FILE: deps/libdwarf-helpers/libdwarf/libdwarf.h ================================================ #include "..\libdwarf.h" ================================================ FILE: deps/libdwarf-helpers/libdwarf.h ================================================ #include "..\libdwarf\libdwarf\libdwarf.h.in" ================================================ FILE: deps/libelf-helpers/config.h ================================================ #include "..\libelf-0.8.13\lib\config.h.w32" ================================================ FILE: deps/libelf-helpers/libelf/elf_repl.h ================================================ #include "..\libelf-0.8.13\lib\elf_repl.h" ================================================ FILE: deps/libelf-helpers/libelf/libelf.h ================================================ #include "..\libelf-0.8.13\lib\libelf.h" ================================================ FILE: deps/libelf-helpers/libelf/sys_elf.h ================================================ #include "..\sys_elf.h" ================================================ FILE: deps/libelf-helpers/sys_elf.h ================================================ #include "..\libelf-0.8.13\lib\sys_elf.h.w32" ================================================ FILE: src/dwarfexport.cpp ================================================ #include #include #include #include #include #include #include #include #include #include #include #include "dwarfexport.h" static bool has_decompiler = false; std::ofstream logger; hexdsp_t *hexdsp = NULL; // A mapping of IDA types to dwarf types using type_record_t = std::map; /** * Add a dwarf type definitions to the compilation unit 'cu' representing * the IDA type 'type'. This is implemented for structs, const types, * arrays, and pointer types using the following 'add_*_type' functions. * * @returns The dwarf DIE associated with the new type (or the existing one) */ static Dwarf_P_Die get_or_add_type(Dwarf_P_Debug dbg, Dwarf_P_Die cu, const tinfo_t &type, type_record_t &record); static Dwarf_P_Die add_struct_type(Dwarf_P_Debug dbg, Dwarf_P_Die cu, const tinfo_t &type, type_record_t &record) { if (!type.is_struct()) { dwarfexport_error("add_struct_type: type is not struct"); } dwarfexport_log("Adding structure type"); Dwarf_P_Die die; Dwarf_Error err = 0; die = dwarf_new_die(dbg, DW_TAG_structure_type, cu, NULL, NULL, NULL, &err); record[type] = die; // Add type name std::string name = type.dstr(); if (dwarf_add_AT_name(die, &name[0], &err) == NULL) { dwarfexport_error("dwarf_add_AT_name failed: ", dwarf_errmsg(err)); } dwarfexport_log(" Name = ", name); // Add type size auto size = type.get_size(); if (size != BADSIZE && dwarf_add_AT_unsigned_const(dbg, die, DW_AT_byte_size, size, &err) == NULL) { dwarfexport_error("dwarf_add_AT_unsigned_const failed: ", dwarf_errmsg(err)); } dwarfexport_log(" Size = ", size); auto member_count = type.get_udt_nmembers(); if (member_count == -1) { dwarfexport_error("add_struct_type: get_udt_nmembers error"); } dwarfexport_log(" Member Count = ", member_count); for (int i = 0; i < member_count; ++i) { udt_member_t member; member.offset = i; type.find_udt_member(STRMEM_INDEX, &member); auto member_type = member.type; auto member_die = dwarf_new_die(dbg, DW_TAG_member, die, NULL, NULL, NULL, &err); // Add member type auto member_type_die = get_or_add_type(dbg, cu, member_type, record); if (dwarf_add_AT_reference(dbg, member_die, DW_AT_type, member_type_die, &err) == nullptr) { dwarfexport_error("dwarf_add_AT_reference failed: ", dwarf_errmsg(err)); } // Add member name auto member_name = member.name; if (dwarf_add_AT_name(member_die, &member_name[0], &err) == NULL) { dwarfexport_error("dwarf_add_AT_name failed: ", dwarf_errmsg(err)); } dwarfexport_log(" Adding Member: ", &member_name[0]); // Add member location in struct Dwarf_P_Expr loc_expr = dwarf_new_expr(dbg, &err); if (dwarf_add_expr_gen(loc_expr, DW_OP_plus_uconst, member.offset / 8, 0, &err) == DW_DLV_NOCOUNT) { dwarfexport_error("dwarf_add_expr_gen failed: ", dwarf_errmsg(err)); } if (dwarf_add_AT_location_expr(dbg, member_die, DW_AT_data_member_location, loc_expr, &err) == nullptr) { dwarfexport_error("dwarf_add_AT_location_expr failed: ", dwarf_errmsg(err)); } } return die; } static Dwarf_P_Die add_array_type(Dwarf_P_Debug dbg, Dwarf_P_Die cu, const tinfo_t &type, type_record_t &record) { if (!type.is_array()) { dwarfexport_error("add_array_type: type is not array"); } dwarfexport_log("Adding array type"); Dwarf_P_Die die; Dwarf_Error err = 0; die = dwarf_new_die(dbg, DW_TAG_array_type, cu, NULL, NULL, NULL, &err); record[type] = die; auto element_type = type; element_type.remove_ptr_or_array(); auto element_die = get_or_add_type(dbg, cu, element_type, record); if (dwarf_add_AT_reference(dbg, die, DW_AT_type, element_die, &err) == nullptr) { dwarfexport_error("dwarf_add_AT_reference failed: ", dwarf_errmsg(err)); } auto elems = type.get_array_nelems(); if (elems != -1) { elems -= 1; dwarfexport_log(" Number of elements = ", elems); auto subrange = dwarf_new_die(dbg, DW_TAG_subrange_type, die, NULL, NULL, NULL, &err); if (dwarf_add_AT_unsigned_const(dbg, subrange, DW_AT_upper_bound, elems, &err) == NULL) { dwarfexport_error("dwarf_add_AT_unsigned_const failed: ", dwarf_errmsg(err)); tinfo_t size_type; qstring name; // Try to get size_t and use it for the index type if (parse_decl2(idati, "size_t x;", &name, &size_type, PT_SIL)) { auto index_die = get_or_add_type(dbg, cu, size_type, record); if (dwarf_add_AT_reference(dbg, subrange, DW_AT_type, index_die, &err) == nullptr) { dwarfexport_error("dwarf_add_AT_reference failed: ", dwarf_errmsg(err)); } if (dwarf_add_AT_reference(dbg, die, DW_AT_sibling, index_die, &err) == nullptr) { dwarfexport_error("dwarf_add_AT_reference failed: ", dwarf_errmsg(err)); } } } } return die; } static Dwarf_P_Die add_const_type(Dwarf_P_Debug dbg, Dwarf_P_Die cu, const tinfo_t &type, type_record_t &record) { if (!type.is_const()) { dwarfexport_error("add_const_type: type is not const"); } dwarfexport_log("Adding const type"); Dwarf_P_Die die; Dwarf_Error err = 0; die = dwarf_new_die(dbg, DW_TAG_const_type, cu, NULL, NULL, NULL, &err); record[type] = die; auto without_const = type; without_const.clr_const(); auto child_die = get_or_add_type(dbg, cu, without_const, record); if (dwarf_add_AT_reference(dbg, die, DW_AT_type, child_die, &err) == nullptr) { dwarfexport_error("dwarf_add_AT_reference failed: ", dwarf_errmsg(err)); } return die; } static Dwarf_P_Die add_ptr_type(Dwarf_P_Debug dbg, Dwarf_P_Die cu, const tinfo_t &type, type_record_t &record) { if (!type.is_ptr()) { dwarfexport_error("add_ptr_type: type is not a pointer"); } dwarfexport_log("Adding pointer type"); Dwarf_P_Die die; Dwarf_Error err = 0; die = dwarf_new_die(dbg, DW_TAG_pointer_type, cu, NULL, NULL, NULL, &err); record[type] = die; auto without_ptr = type; without_ptr.remove_ptr_or_array(); auto child_die = get_or_add_type(dbg, cu, without_ptr, record); if (dwarf_add_AT_reference(dbg, die, DW_AT_type, child_die, &err) == nullptr) { dwarfexport_error("dwarf_add_AT_reference failed: ", dwarf_errmsg(err)); } if (dwarf_add_AT_unsigned_const(dbg, die, DW_AT_byte_size, sizeof(ea_t), &err) == NULL) { dwarfexport_error("dwarf_add_AT_unsigned_const failed: ", dwarf_errmsg(err)); } return die; } static Dwarf_P_Die get_or_add_type(Dwarf_P_Debug dbg, Dwarf_P_Die cu, const tinfo_t &type, type_record_t &record) { if (record.find(type) != record.end()) { return record[type]; } dwarfexport_log("Adding new type"); Dwarf_P_Die die; Dwarf_Error err = 0; // special cases for const, ptr, array, and struct if (type.is_const()) { die = add_const_type(dbg, cu, type, record); return die; } else if (type.is_ptr()) { die = add_ptr_type(dbg, cu, type, record); return die; } else if (type.is_array()) { die = add_array_type(dbg, cu, type, record); return die; } else if (type.is_struct()) { die = add_struct_type(dbg, cu, type, record); return die; } die = dwarf_new_die(dbg, DW_TAG_base_type, cu, NULL, NULL, NULL, &err); if (die == NULL) { dwarfexport_error("dwarf_new_die failed: ", dwarf_errmsg(err)); } // Add type name std::string name = type.dstr(); if (dwarf_add_AT_name(die, &name[0], &err) == NULL) { dwarfexport_error("dwarf_add_AT_name failed: ", dwarf_errmsg(err)); } dwarfexport_log(" Name = ", name); // Add type size std::size_t size = type.get_size(); if (size != BADSIZE && dwarf_add_AT_unsigned_const(dbg, die, DW_AT_byte_size, size, &err) == NULL) { dwarfexport_error("dwarf_add_AT_unsigned_const failed: ", dwarf_errmsg(err)); } dwarfexport_log(" Size = ", size); record[type] = die; return die; } /** * For a given IDA decompiler variable 'var' from a given function * 'cfunc', add a dwarf variable to the provided function DIE 'func_die'. * * * @returns The dwarf DIE associated with the new variable */ static Dwarf_P_Die add_variable(Dwarf_P_Debug dbg, Dwarf_P_Die cu, Dwarf_P_Die func_die, cfuncptr_t cfunc, const lvar_t &var, type_record_t &record) { Dwarf_P_Die die; Dwarf_Error err = 0; die = dwarf_new_die(dbg, DW_TAG_variable, func_die, NULL, NULL, NULL, &err); // Add var type. We could check for 'typed' here, but this is sometimes // returns strange values (bug?), and I think lvars in the decompiled view // must be types, so skip the check. auto var_type = var.type(); auto var_type_die = get_or_add_type(dbg, cu, var_type, record); if (dwarf_add_AT_reference(dbg, die, DW_AT_type, var_type_die, &err) == nullptr) { dwarfexport_error("dwarf_add_AT_reference failed: ", dwarf_errmsg(err)); } auto name = var.name; if (dwarf_add_AT_name(die, &name[0], &err) == NULL) { dwarfexport_error("dwarf_add_AT_name failed: ", dwarf_errmsg(err)); } dwarfexport_log("Adding local variable: ", &name[0]); if (var.is_stk_var()) { auto loc_expr = decompiler_stack_lvar_location(dbg, cfunc, var); if (loc_expr) { if (dwarf_add_AT_location_expr(dbg, die, DW_AT_location, loc_expr, &err) == nullptr) { dwarfexport_error("dwarf_add_AT_location_expr failed: ", dwarf_errmsg(err)); } } } else if (!var.is_arg_var() && var.location.is_reg1()) { // Try to get the DWARF register number from the IDA register number. // For whatever reason, the mapping is different for registers when // passing arguments, so we don't do those. auto reg_num = translate_register_num(var.location.reg1()); if (reg_num != -1) { dwarfexport_log("Translated IDA register #", var.location.reg1(), " to #", reg_num); Dwarf_P_Expr loc_expr = dwarf_new_expr(dbg, &err); if (dwarf_add_expr_gen(loc_expr, DW_OP_regx, reg_num, 0, &err) == DW_DLV_NOCOUNT) { dwarfexport_error("dwarf_add_expr_gen failed: ", dwarf_errmsg(err)); } if (dwarf_add_AT_location_expr(dbg, die, DW_AT_location, loc_expr, &err) == nullptr) { dwarfexport_error("dwarf_add_AT_location_expr failed: ", dwarf_errmsg(err)); } } else { dwarfexport_log("Unable to translate register #", reg_num); } } return die; } /** * Adds a DWARF variable to the provided function 'func_die' for each * variable in the IDA disassembly view. */ static void add_disassembler_func_info(std::shared_ptr info, Dwarf_P_Die func_die, Dwarf_P_Die cu, func_t *func, type_record_t &record) { auto dbg = info->dbg; Dwarf_Error err = 0; auto frame = get_frame(func); if (frame == nullptr) { return; } for (std::size_t i = 0; i < frame->memqty; ++i) { auto name = get_member_name2(frame->members[i].id); // Ignore these special 'variables' if (name == " s" || name == " r") { continue; } dwarfexport_log("Adding local variable: ", &name[0]); Dwarf_P_Die die; die = dwarf_new_die(dbg, DW_TAG_variable, func_die, NULL, NULL, NULL, &err); if (dwarf_add_AT_name(die, &name[0], &err) == NULL) { dwarfexport_error("dwarf_add_AT_name failed: ", dwarf_errmsg(err)); } auto loc_expr = disassembler_stack_lvar_location(dbg, func, &frame->members[i]); if (loc_expr == nullptr) { continue; } auto member_struct = get_sptr(&frame->members[i]); if (member_struct) { tinfo_t type; if (guess_tinfo2(member_struct->id, &type) == GUESS_FUNC_OK) { auto var_type_die = get_or_add_type(dbg, cu, type, record); if (dwarf_add_AT_reference(dbg, die, DW_AT_type, var_type_die, &err) == nullptr) { dwarfexport_error("dwarf_add_AT_reference failed: ", dwarf_errmsg(err)); } } } if (dwarf_add_AT_location_expr(dbg, die, DW_AT_location, loc_expr, &err) == nullptr) { dwarfexport_error("dwarf_add_AT_location_expr failed: ", dwarf_errmsg(err)); } } } /** * Adds a DWARF variable to the provided function 'func_die' for each * variable in the IDA decompiler view. * * @param info A handle returned by a previous call to 'generate_dwarf_object' * @param cu The dwarf compilation unit containing the function * @param func_die The dwarf function to add variables and line info for * @param func The IDA function handle for this function * @param file An output file stream used for storing the decompiled source * @param linecount The current number of lines in 'file' * @param file_index The dwarf file index associated with 'cu' * @param symbol_index The symbol index associated with the function (unused) * @param record The type record to update when adding variable types */ static void add_decompiler_func_info(std::shared_ptr info, Dwarf_P_Die cu, Dwarf_P_Die func_die, func_t *func, std::ostream &file, int &linecount, Dwarf_Unsigned file_index, Dwarf_Unsigned symbol_index, type_record_t &record) { auto dbg = info->dbg; auto err = info->err; hexrays_failure_t hf; cfuncptr_t cfunc = decompile(func, &hf); if (cfunc == nullptr) { dwarfexport_log("Failed to decompile function at ", func->startEA); return; } // Add lvars (from decompiler) auto &lvars = *cfunc->get_lvars(); for (std::size_t i = 0; i < lvars.size(); ++i) { if (lvars[i].name.size()) { add_variable(dbg, cu, func_die, cfunc, lvars[i], record); } } // Add line info const auto &sv = cfunc->get_pseudocode(); const auto &bounds = cfunc->get_boundaries(); const auto &eamap = cfunc->get_eamap(); ea_t previous_line_addr = 0; for (std::size_t i = 0; i < sv.size(); ++i, ++linecount) { char buf[MAXSTR]; const char *line = sv[i].line.c_str(); tag_remove(line, buf, MAXSTR); auto stripped_buf = std::string(buf); file << stripped_buf + "\n"; dwarfexport_log("Processing line: ", stripped_buf); ctree_item_t item; std::size_t index = stripped_buf.find_first_not_of(' '); if (index == std::string::npos) { continue; } // For each column in the line, try to find a cexpr_t that has an // address inside the function, then emit a dwarf source line info // for that. ea_t lowest_line_addr = 0, highest_line_addr = 0; for (; index < stripped_buf.size(); ++index) { if (!cfunc->get_line_item(line, index, true, nullptr, &item, nullptr)) { continue; } // item.get_ea returns strange values, so use the item_t ea for exprs // for now if (item.citype != VDI_EXPR || !item.it->is_expr()) { continue; } ea_t addr = item.e->ea; // The address for this expression is outside of this function, // so something strange is happening. Just ignore it. if (addr == (ea_t)-1 || addr < func->startEA || addr > func->endEA) { continue; } // Get the bounds of the expression. This fixes issues where the arguments // to a multi-line function call were not correctly handled. ea_t expr_lowest_addr = addr, expr_highest_addr = addr; if (eamap.count(addr)) { const auto &expr_areaset = bounds.at(eamap.at(addr).at(0)); // TODO: the area set may not be sorted this way expr_lowest_addr = expr_areaset.getarea(0).startEA; expr_highest_addr = expr_areaset.lastarea().endEA - 1; } // In some situations, there are multiple lines that have the same // 'lowest' point. To avoid mapping multiple lines to the same address, we // try to ensure that the address associated with a given line is the // lowest one that is still higher than the highest address of the // previous line. if (!lowest_line_addr || expr_lowest_addr < lowest_line_addr) { if (!previous_line_addr || expr_lowest_addr > previous_line_addr) { lowest_line_addr = expr_lowest_addr; } } if (!highest_line_addr || expr_highest_addr > highest_line_addr) { highest_line_addr = expr_highest_addr; } } if (!lowest_line_addr && highest_line_addr && highest_line_addr > previous_line_addr) { lowest_line_addr = previous_line_addr + 1; } if (lowest_line_addr) { dwarfexport_log("Mapping line #", linecount, " to address ", lowest_line_addr); dwarf_lne_set_address(dbg, lowest_line_addr, 0, &err); dwarf_add_line_entry(dbg, file_index, lowest_line_addr, linecount, index, true, false, &err); previous_line_addr = highest_line_addr; } } // Add a little space between the functions file << "\n\n"; linecount += 2; } static Dwarf_P_Die add_function(std::shared_ptr info, Options &options, Dwarf_P_Die cu, func_t *func, std::ostream &file, int &linecount, Dwarf_Unsigned file_index, type_record_t &record) { auto dbg = info->dbg; auto err = info->err; Dwarf_P_Die die; die = dwarf_new_die(dbg, DW_TAG_subprogram, cu, nullptr, nullptr, nullptr, &err); if (die == nullptr) { dwarfexport_error("dwarf_new_die failed: ", dwarf_errmsg(err)); } // Add frame base // TODO: what to do for non-bp based frames Dwarf_P_Expr loc_expr = dwarf_new_expr(dbg, &err); if (dwarf_add_expr_gen(loc_expr, DW_OP_call_frame_cfa, 0, 0, &err) == DW_DLV_NOCOUNT) { dwarfexport_error("dwarf_add_expr_gen failed: ", dwarf_errmsg(err)); } if (dwarf_add_AT_location_expr(dbg, die, DW_AT_frame_base, loc_expr, &err) == nullptr) { dwarfexport_error("dwarf_add_AT_location_expr failed: ", dwarf_errmsg(err)); } // Add function name auto name = get_long_name(func->startEA); char *c_name = &*name.begin(); if (dwarf_add_AT_name(die, c_name, &err) == nullptr) { dwarfexport_error("dwarf_add_AT_name failed: ", dwarf_errmsg(err)); } auto mangled_name = get_true_name(func->startEA); if (dwarf_add_AT_string(dbg, die, DW_AT_linkage_name, &mangled_name[0], &err) == nullptr) { dwarfexport_error("dwarf_add_AT_string failed: ", dwarf_errmsg(err)); } dwarfexport_log("Adding function ", &name[0], " (", &mangled_name[0], ")"); // Add ret type tinfo_t func_type_info; if (get_tinfo2(func->startEA, &func_type_info)) { auto rettype = func_type_info.get_rettype(); auto rettype_die = get_or_add_type(dbg, cu, rettype, record); if (dwarf_add_AT_reference(dbg, die, DW_AT_type, rettype_die, &err) == nullptr) { dwarfexport_error("dwarf_add_AT_reference failed: ", dwarf_errmsg(err)); } } // Add function bounds dwarf_add_AT_targ_address(dbg, die, DW_AT_low_pc, func->startEA, 0, &err); dwarf_add_AT_targ_address(dbg, die, DW_AT_high_pc, func->endEA - 1, 0, &err); auto is_named = has_name(getFlags(func->startEA)); if (has_decompiler && options.use_decompiler() && (!options.only_decompile_named_funcs() || (options.only_decompile_named_funcs() && is_named))) { // Add location declaration dwarf_add_AT_unsigned_const(dbg, die, DW_AT_decl_file, file_index, &err); dwarf_add_AT_unsigned_const(dbg, die, DW_AT_decl_line, linecount, &err); // The start of every function should have a line entry dwarf_add_line_entry(dbg, file_index, func->startEA, linecount, 0, true, false, &err); add_decompiler_func_info(info, cu, die, func, file, linecount, file_index, 0, record); } else { add_disassembler_func_info(info, cu, die, func, record); } return die; } /** * Add all structures to the debug output. This is useful for allowing casts * to types in the debugger that may not have actually been used at the time * the debug info was being exported. */ void add_structures(Dwarf_P_Debug dbg, Dwarf_P_Die cu, type_record_t &record) { dwarfexport_log("Adding unused types"); for (auto idx = get_first_struc_idx(); idx != BADADDR; idx = get_next_struc_idx(idx)) { auto tid = get_struc_by_idx(idx); tinfo_t type; if (guess_tinfo2(tid, &type) == GUESS_FUNC_OK) { get_or_add_type(dbg, cu, type, record); } } } /** * Add dwarf info for the global variables in this file. These entries are * not given a textual representation, only a location and type. */ void add_global_variables(Dwarf_P_Debug dbg, Dwarf_P_Die cu, type_record_t &record) { dwarfexport_log("Adding global variables"); Dwarf_Error err = 0; auto seg_count = get_segm_qty(); for (auto i = 0; i < seg_count; ++i) { auto seg = getnseg(i); if (seg->type != SEG_DATA && seg->type != SEG_BSS) { continue; } for (auto addr = seg->startEA; addr < seg->endEA; ++addr) { char name[MAXSTR]; if (!get_name(BADADDR, addr, name, MAXSTR)) { continue; } tinfo_t type; if (guess_tinfo2(addr, &type) != GUESS_FUNC_OK) { continue; } dwarfexport_log("Adding global variable"); dwarfexport_log(" name = ", name); dwarfexport_log(" location = ", addr); auto die = dwarf_new_die(dbg, DW_TAG_variable, cu, NULL, NULL, NULL, &err); auto var_type_die = get_or_add_type(dbg, cu, type, record); if (dwarf_add_AT_name(die, name, &err) == NULL) { dwarfexport_error("dwarf_add_AT_name failed: ", dwarf_errmsg(err)); } if (dwarf_add_AT_reference(dbg, die, DW_AT_type, var_type_die, &err) == nullptr) { dwarfexport_error("dwarf_add_AT_reference failed: ", dwarf_errmsg(err)); } // FIXME: this won't work in shared libs Dwarf_P_Expr loc_expr = dwarf_new_expr(dbg, &err); if (dwarf_add_expr_addr_b(loc_expr, addr, 0, &err) == DW_DLV_NOCOUNT) { dwarfexport_error("dwarf_add_expr_gen failed: ", dwarf_errmsg(err)); } if (dwarf_add_AT_location_expr(dbg, die, DW_AT_location, loc_expr, &err) == nullptr) { dwarfexport_error("dwarf_add_AT_location_expr failed: ", dwarf_errmsg(err)); } } } } void add_debug_info(std::shared_ptr info, std::ostream &sourcefile, Options &options) { auto dbg = info->dbg; auto err = info->err; Dwarf_P_Die cu; cu = dwarf_new_die(dbg, DW_TAG_compile_unit, nullptr, nullptr, nullptr, nullptr, &err); if (cu == nullptr) { dwarfexport_error("dwarf_new_die failed: ", dwarf_errmsg(err)); } Dwarf_Unsigned file_index = 0; if (options.use_decompiler()) { if (dwarf_add_AT_name(cu, &options.c_filename()[0], &err) == nullptr) { dwarfexport_error("dwarf_add_AT_name failed: ", dwarf_errmsg(err)); } auto dir_index = dwarf_add_directory_decl(dbg, &options.dwarf_source_path[0], &err); file_index = dwarf_add_file_decl(dbg, &options.c_filename()[0], dir_index, 0, 0, &err); dwarf_add_AT_comp_dir(cu, &options.dwarf_source_path[0], &err); } int linecount = 1; type_record_t record; auto seg_qty = get_segm_qty(); for (std::size_t segn = 0; segn < seg_qty; ++segn) { auto seg = getnseg(segn); if (seg == nullptr) { dwarfexport_error("Unable to getnseg() segment number ", segn); } // Only consider EXEC segments // TODO: Skip plt/got? if (!(seg->perm & SEGPERM_EXEC) && seg->type != SEG_CODE) { dwarfexport_log("Segment #", segn, " is not executable. Skipping."); continue; } char segname[MAXSTR]; get_true_segm_name(seg, segname, sizeof(segname)); dwarfexport_log("Adding functions from: ", segname); func_t *f = get_func(seg->startEA); if (f == nullptr) { // In some cases, the start of the section may not actually be a function, // so get the first available function. f = get_next_func(seg->startEA); if (f == nullptr) { dwarfexport_log("Skipping ", lsegname, " because it has no functions"); continue; } } for (; f != nullptr; f = get_next_func(f->startEA)) { if (f->startEA > seg->endEA) { break; } add_function(info, options, cu, f, sourcefile, linecount, file_index, record); } if (dwarf_add_die_to_debug(dbg, cu, &err) != DW_DLV_OK) { dwarfexport_error("dwarf_add_die_to_debug failed: ", dwarf_errmsg(err)); } } // Add the global variables (but don't add a file location) add_global_variables(dbg, cu, record); // Add any other structures add_structures(dbg, cu, record); } int idaapi init(void) { if (init_hexrays_plugin()) { msg("dwarfexport: Using decompiler\n"); has_decompiler = true; } else { msg("dwarfexport: No decompiler found\n"); } return PLUGIN_OK; } void idaapi run(int) { try { auto default_options = (has_decompiler) ? Options::ATTACH_DEBUG_INFO | Options::USE_DECOMPILER : Options::ATTACH_DEBUG_INFO; Options options(".", default_options); get_input_file_path(options.filepath, QMAXPATH); get_root_filename(options.filename, QMAXPATH); char *filepath_end = strrchr(options.filepath, PATH_SEP); if (filepath_end != nullptr) { *(filepath_end + 1) = '\0'; } const char *dialog = "STARTITEM 0\n" "Dwarf Export\n\n" "Select the location to save the exported data:\n" "\n" "Export Options\n \n" "\n" "\n" ">\n"; if (AskUsingForm_c(dialog, options.filepath, &options.export_options) == 1) { if (options.verbose()) { logger = std::ofstream("dwarfexport.log"); msg("Verbose mode enabled. Logging to dwarfexport.log\n"); } if (!options.attach_debug_info()) { dwarfexport_log("Generating detached debug info"); } if (options.only_decompile_named_funcs()) { dwarfexport_log("Only decompiling named functions"); } std::ofstream sourcefile; if (options.use_decompiler()) { dwarfexport_log("Using decompiler with exported source filename: ", options.c_filename()); sourcefile = std::ofstream(options.c_filename()); } dwarfexport_log("Setting up DWARF object"); auto info = generate_dwarf_object(options); dwarfexport_log("Adding DWARF debug information"); add_debug_info(info, sourcefile, options); dwarfexport_log("Writing out DWARF file to disk"); write_dwarf_file(info, options); } } catch (const std::exception &e) { std::string msg = "A dwarfexport error occurred: " + std::string(e.what()); warning(msg.c_str()); } catch (...) { warning("A dwarfexport error occurred"); } } plugin_t PLUGIN = { IDP_INTERFACE_VERSION, PLUGIN_UNL, // plugin flags init, // initialize nullptr, // terminate. this pointer may be nullptr. run, // invoke plugin nullptr, // long comment about the plugin nullptr, // multiline help about the plugin "Export Dwarf Debug Info", // the preferred short name of the plugin nullptr // the preferred hotkey to run the plugin }; ================================================ FILE: src/dwarfexport.h ================================================ #ifndef DWARFEXPORT_HPP #define DWARFEXPORT_HPP #include #include #include #include #include #include #include #include [[noreturn]] inline void dwarfexport_error_impl(const std::string &s) { throw std::runtime_error(s); } template inline void dwarfexport_error_impl(const std::string &s, Arg arg, Args... args) { std::ostringstream os; os << arg; dwarfexport_error_impl(s + os.str(), args...); } #define dwarfexport_error(...) \ dwarfexport_error_impl(__FILE__, ":", __LINE__, " ", __VA_ARGS__) extern std::ofstream logger; inline void dwarfexport_log_impl(const std::string &s) { logger << s << std::endl; } template inline void dwarfexport_log_impl(const std::string &s, Arg arg, Args... args) { if (logger.is_open()) { std::ostringstream os; os << arg; dwarfexport_log_impl(s + os.str(), args...); } } #define dwarfexport_log(...) dwarfexport_log_impl(__VA_ARGS__) enum class Mode { BIT32, BIT64 }; struct DwarfGenInfo { Elf *elf = nullptr; Mode mode = (sizeof(ea_t) == 4) ? (Mode::BIT32) : (Mode::BIT64); Dwarf_P_Debug dbg; Dwarf_Error err = 0; }; struct Options { enum { USE_DECOMPILER = 1 << 0, ONLY_DECOMPILE_NAMED_FUNCS = 1 << 1, ATTACH_DEBUG_INFO = 1 << 2, VERBOSE = 1 << 3, }; char filepath[QMAXPATH]; char filename[QMAXPATH]; std::string dwarf_source_path; unsigned short export_options; bool use_decompiler() const { return export_options & USE_DECOMPILER; } bool attach_debug_info() const { return export_options & ATTACH_DEBUG_INFO; } bool only_decompile_named_funcs() const { return export_options & ONLY_DECOMPILE_NAMED_FUNCS; } bool verbose() const { return export_options & VERBOSE; } std::string c_filename() const { return filename + std::string(".c"); } std::string dbg_filename() const { return filename + std::string(".dbg"); } Options(std::string _source_path, unsigned short options) : dwarf_source_path{_source_path}, export_options{options} {} }; std::shared_ptr generate_dwarf_object(const Options &options); void write_dwarf_file(std::shared_ptr info, const Options &options); int translate_register_num(int ida_reg_num); Dwarf_P_Expr decompiler_stack_lvar_location(Dwarf_P_Debug dbg, cfuncptr_t cfunc, const lvar_t &var); Dwarf_P_Expr disassembler_stack_lvar_location(Dwarf_P_Debug dbg, func_t *func, member_t *member); #ifdef __NT__ #define PATH_SEP '\\' #else #define PATH_SEP '/' #endif /* The following strtabdata class is used (heavily) modified from 'dwarfgen', the original copyright notice below: Copyright (C) 2010-2016 David Anderson. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the example nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY David Anderson ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL David Anderson BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ class strtabdata { public: strtabdata() : data_(new char[1000]), datalen_(1000), nexttouse_(0) { data_[0] = 0; nexttouse_ = 1; }; ~strtabdata() { delete[] data_; }; void loadExistingTable(char *data, int length) { auto new_data = new char[length * 2]; memcpy(new_data, data, length); delete[] data_; data_ = new_data; datalen_ = length * 2; nexttouse_ = length; } unsigned addString(const std::string &newstr) { // The 1 is for the terminating null byte. unsigned nsz = newstr.size() + 1; unsigned needed = nexttouse_ + nsz; if (needed >= datalen_) { unsigned baseincr = nsz; unsigned altincr = datalen_ * 2; if (altincr > baseincr) { baseincr = altincr; } unsigned newsize = datalen_ + baseincr; char *newdata = new char[newsize]; memcpy(newdata, data_, nexttouse_); delete[] data_; data_ = newdata; datalen_ = newsize; } memcpy(data_ + nexttouse_, newstr.c_str(), nsz); unsigned newstrindex = nexttouse_; nexttouse_ += nsz; return newstrindex; }; void *exposedata() { return (void *)data_; }; unsigned exposelen() const { return nexttouse_; }; private: char *data_; // datalen_ is the size in bytes pointed to by data_ . unsigned datalen_; // nexttouse_ is the index of the next (unused) byte in // data_ , so it is also the amount of space in data_ that // is in use. unsigned nexttouse_; }; #endif ================================================ FILE: src/dwarfgen.cpp ================================================ /* Windows specific header files */ #ifdef HAVE_STDAFX_H #include "stdafx.h" #endif /* HAVE_STDAFX_H */ #ifndef __NT__ #define O_BINARY 0 #endif #include #include #include "dwarfexport.h" static int add_section_header_string(Elf *elf, const char *name) { // The stored data has to live until the file is written, so just // store it statically static strtabdata strtab; std::size_t sh_index; if (elf_getshstrndx(elf, &sh_index) == -1) { dwarfexport_error("elf_getshstrndx() failed: ", elf_errmsg(-1)); } auto strscn = elf_getscn(elf, sh_index); if (strscn == NULL) { dwarfexport_error("elf_getscn() failed: ", elf_errmsg(-1)); } GElf_Shdr shdr; if (gelf_getshdr(strscn, &shdr) == NULL) { dwarfexport_error("gelf_getshdr() failed: ", elf_errmsg(-1)); } Elf_Data *data; if ((data = elf_getdata(strscn, NULL)) == NULL) { dwarfexport_error("elf_getdata() failed: ", elf_errmsg(-1)); } strtab.loadExistingTable((char *)data->d_buf, data->d_size); auto ret = strtab.addString(name); data->d_buf = strtab.exposedata(); data->d_size = strtab.exposelen(); shdr.sh_size = data->d_size; if (!gelf_update_shdr(strscn, &shdr)) { dwarfexport_error("Unable to gelf_update_shdr()", elf_errmsg(-1)); } return ret; } static int attached_info_callback(const char *name, int size, Dwarf_Unsigned type, Dwarf_Unsigned flags, Dwarf_Unsigned link, Dwarf_Unsigned info, Dwarf_Unsigned *sect_name_symbol_index, void *userdata, int *) { DwarfGenInfo &geninfo = *(DwarfGenInfo *)userdata; auto elf = geninfo.elf; if (strncmp(name, ".rel", 4) == 0) { return 0; } Elf_Scn *scn = elf_newscn(elf); if (!scn) { dwarfexport_error("Unable to elf_newscn(): ", elf_errmsg(-1)); } GElf_Shdr shdr; if (!gelf_getshdr(scn, &shdr)) { dwarfexport_error("Unable to elf_getshdr(): ", elf_errmsg(-1)); } shdr.sh_type = type; shdr.sh_flags = flags; shdr.sh_addr = 0; shdr.sh_link = link; shdr.sh_info = info; shdr.sh_addralign = 1; shdr.sh_name = add_section_header_string(elf, name); // We set these correctly later shdr.sh_size = 0; shdr.sh_offset = 0; shdr.sh_entsize = 0; if (!gelf_update_shdr(scn, &shdr)) { dwarfexport_error("Unable to gelf_update_shdr()", elf_errmsg(-1)); } return elf_ndxscn(scn); } static std::vector detached_sections; static int detached_info_callback(const char *name, int size, Dwarf_Unsigned type, Dwarf_Unsigned flags, Dwarf_Unsigned link, Dwarf_Unsigned info, Dwarf_Unsigned *sect_name_symbol_index, void *userdata, int *) { detached_sections.push_back(name); return detached_sections.size() - 1; } std::shared_ptr generate_dwarf_object(const Options &options) { auto info = std::make_shared(); auto err = info->err; int ptrsizeflagbit = DW_DLC_POINTER32; int offsetsizeflagbit = DW_DLC_OFFSET32; if (info->mode == Mode::BIT64) { ptrsizeflagbit = DW_DLC_POINTER64; } // We don't use the dwarf relocations, so it probably doesn't matter what // we put here const char *isa_name = (info->mode == Mode::BIT32) ? "x86" : "x86_64"; const char *dwarf_version = "V2"; int endian = (inf.mf) ? DW_DLC_TARGET_BIGENDIAN : DW_DLC_TARGET_LITTLEENDIAN; Dwarf_Ptr errarg = 0; decltype(&attached_info_callback) callback; if (options.attach_debug_info()) { callback = &attached_info_callback; } else { callback = &detached_info_callback; } int res = dwarf_producer_init(DW_DLC_WRITE | DW_DLC_SYMBOLIC_RELOCATIONS | ptrsizeflagbit | offsetsizeflagbit | endian, callback, 0, errarg, (void *)info.get(), isa_name, dwarf_version, 0, &info->dbg, &err); if (res != DW_DLV_OK) { dwarfexport_error("dwarf_producer_init failed: ", dwarf_errmsg(err)); } res = dwarf_pro_set_default_string_form(info->dbg, DW_FORM_string, &err); if (res != DW_DLV_OK) { dwarfexport_error("dwarf_pro_set_default_string_form failed: ", dwarf_errmsg(err)); } return info; } static Elf_Scn *get_last_section(Elf *elf) { std::size_t count, max_offset = 0, max_size = 0; GElf_Shdr shdr; Elf_Scn *last_scn; if (elf_getshdrnum(elf, &count) == -1) { dwarfexport_error("elf_getshdrnum() failed: ", elf_errmsg(-1)); } for (std::size_t i = 0; i < count; ++i) { Elf_Scn *scn = elf_getscn(elf, i); if (!gelf_getshdr(scn, &shdr)) { dwarfexport_error("elf_getshdr() failed: ", elf_errmsg(-1)); } if (shdr.sh_type == SHT_NOBITS) { continue; } if (shdr.sh_offset > max_offset || (shdr.sh_offset == max_offset && shdr.sh_size > max_size)) { last_scn = scn; max_offset = shdr.sh_offset; max_size = shdr.sh_size; } } return last_scn; } static off_t get_current_data_offset(Elf_Scn *scn) { Elf_Data *data = NULL; off_t offset = 0; while ((data = elf_getdata(scn, data)) != NULL) { if (data->d_off >= offset) { offset = data->d_off + data->d_size; } // This shouldn't be necessary, but libelf complains the // version is unknown otherwise. data->d_version = EV_CURRENT; } return offset; } static void add_data_to_section_end(Elf *elf, Elf_Scn *scn, void *bytes, std::size_t length, Elf_Type type) { auto data_offset = get_current_data_offset(scn); Elf_Data *ed = elf_newdata(scn); if (!ed) { dwarfexport_error("elf_newdata() failed: ", elf_errmsg(-1)); } ed->d_buf = bytes; ed->d_type = type; ed->d_size = length; ed->d_align = 1; ed->d_version = EV_CURRENT; ed->d_off = data_offset; // Update the section size and offset Elf_Scn *last_scn = get_last_section(elf); GElf_Shdr shdr, last_shdr; if (!gelf_getshdr(scn, &shdr) || !gelf_getshdr(last_scn, &last_shdr)) { dwarfexport_error("elf_getshdr() failed: ", elf_errmsg(-1)); } if (!shdr.sh_offset) { shdr.sh_offset = last_shdr.sh_offset + last_shdr.sh_size; } shdr.sh_size += length; if (!gelf_update_shdr(scn, &shdr)) { dwarfexport_error("gelf_update_shdr() failed: ", elf_errmsg(-1)); } } static void add_debug_section_data(std::shared_ptr info) { auto dbg = info->dbg; auto elf = info->elf; auto err = info->err; // Invokes the callback to create the needed sections Dwarf_Signed sectioncount = dwarf_transform_to_disk_form(dbg, &err); if (sectioncount == DW_DLV_NOCOUNT) { dwarfexport_error("dwarf_transform_to_disk_form() failed: ", dwarf_errmsg(err)); } for (Dwarf_Signed d = 0; d < sectioncount; ++d) { Dwarf_Signed elf_section_index = 0; Dwarf_Unsigned length = 0; Dwarf_Ptr bytes = dwarf_get_section_bytes(dbg, d, &elf_section_index, &length, &err); if (bytes == NULL) { dwarfexport_error("dwarf_get_section_bytes() failed: ", dwarf_errmsg(err)); } Elf_Scn *scn = elf_getscn(elf, elf_section_index); if (scn == NULL) { dwarfexport_error("Unable to elf_getscn on disk transform: ", elf_errmsg(-1)); } add_data_to_section_end(elf, scn, bytes, length, ELF_T_BYTE); } } static void log_elf(Elf *elf) { GElf_Ehdr ehdr; int scn_index; Elf_Scn *scn; GElf_Shdr shdr; if (gelf_getehdr(elf, &ehdr) != &ehdr) dwarfexport_error("gelf_getehdr() failed: ", elf_errmsg(-1)); for (scn_index = 1; scn_index < ehdr.e_shnum; scn_index++) { if ((scn = elf_getscn(elf, scn_index)) == NULL) dwarfexport_error("getshdr() failed: ", elf_errmsg(-1)); if (gelf_getshdr(scn, &shdr) != &shdr) dwarfexport_error("getshdr() failed: ", elf_errmsg(-1)); dwarfexport_log("Section #", scn_index, ": sh_name=", shdr.sh_name, ", sh_type=", shdr.sh_type, ", sh_flags=", shdr.sh_flags, ", sh_addr=", shdr.sh_addr, ", sh_offset=", shdr.sh_offset, ", sh_size=", shdr.sh_size, ", sh_link=", shdr.sh_link, ", sh_info=", shdr.sh_info, ", sh_addralign=", shdr.sh_addralign, ", sh_entsize=", shdr.sh_entsize); } } static void generate_copy_with_dbg_info(std::shared_ptr info, const std::string &src, const std::string &dst) { int fd_in = -1, fd_out = -1; Elf *elf_in = 0, *elf_out = 0; Elf_Scn *scn_in, *scn_out; GElf_Ehdr ehdr_in, ehdr_out; int scn_index = 0; if (elf_version(EV_CURRENT) == EV_NONE) dwarfexport_error("ELF library initialization failed: ", elf_errmsg(-1)); if ((fd_in = open(src.c_str(), O_RDONLY | O_BINARY, 0)) < 0) dwarfexport_error("open failed: ", src); if ((elf_in = elf_begin(fd_in, ELF_C_READ, NULL)) == NULL) dwarfexport_error("elf_begin() (read) failed: ", elf_errmsg(-1)); if (gelf_getehdr(elf_in, &ehdr_in) != &ehdr_in) dwarfexport_error("gelf_getehdr() failed: ", elf_errmsg(-1)); /* Checks and warns */ if (elf_kind(elf_in) != ELF_K_ELF) { dwarfexport_error(src, " : ", dst, " must be an ELF file."); } /* open output elf */ if ((fd_out = open(dst.c_str(), O_WRONLY | O_CREAT | O_BINARY, 0777)) < 0) dwarfexport_error("open failed: ", dst); if ((elf_out = elf_begin(fd_out, ELF_C_WRITE, NULL)) == NULL) dwarfexport_error("elf_begin() (write) failed: ", elf_errmsg(-1)); /* create new elf header */ if (gelf_newehdr(elf_out, ehdr_in.e_ident[EI_CLASS]) == 0) dwarfexport_error("gelf_newehdr() failed: ", elf_errmsg(-1)); info->elf = elf_out; /* Some compilers produce binaries with non-adjacent or overlapping sections, * so we cannot use the automatic layout. Suppress it and use the exact * layout from the input. */ if (elf_flagelf(elf_out, ELF_C_SET, ELF_F_LAYOUT | ELF_F_LAYOUT_OVERLAP) == 0) dwarfexport_error("elf_flagelf failed: ", elf_errmsg(-1)); if (gelf_getehdr(elf_out, &ehdr_out) != &ehdr_out) dwarfexport_error("gelf_getehdr() failed: ", elf_errmsg(-1)); ehdr_out = ehdr_in; if (gelf_update_ehdr(elf_out, &ehdr_out) == 0) dwarfexport_error("gelf_update_ehdr() failed: ", elf_errmsg(-1)); GElf_Phdr phdr_in, phdr_out; int ph_ndx; if (ehdr_in.e_phnum && gelf_newphdr(elf_out, ehdr_in.e_phnum) == 0) dwarfexport_error("gelf_newphdr() failed: ", elf_errmsg(-1)); for (ph_ndx = 0; ph_ndx < ehdr_in.e_phnum; ++ph_ndx) { if (gelf_getphdr(elf_in, ph_ndx, &phdr_in) != &phdr_in) dwarfexport_error("gelf_getphdr() failed: ", elf_errmsg(-1)); if (gelf_getphdr(elf_out, ph_ndx, &phdr_out) != &phdr_out) dwarfexport_error("gelf_getphdr() failed: ", elf_errmsg(-1)); phdr_out = phdr_in; if (gelf_update_phdr(elf_out, ph_ndx, &phdr_out) == 0) dwarfexport_error("gelf_update_phdr() failed: ", elf_errmsg(-1)); } /* copy sections to new elf */ Elf_Data *data_in, *data_out; GElf_Shdr shdr_in, shdr_out; for (scn_index = 1; scn_index < ehdr_in.e_shnum; scn_index++) { if ((scn_in = elf_getscn(elf_in, scn_index)) == NULL) dwarfexport_error("getshdr() failed: ", elf_errmsg(-1)); if ((scn_out = elf_newscn(elf_out)) == NULL) dwarfexport_error("elf_newscn() failed: ", elf_errmsg(-1)); if (gelf_getshdr(scn_in, &shdr_in) != &shdr_in) dwarfexport_error("getshdr() failed: ", elf_errmsg(-1)); data_in = NULL; while ((data_in = elf_getdata(scn_in, data_in)) != NULL) { if ((data_out = elf_newdata(scn_out)) == NULL) dwarfexport_error("elf_newdata() failed: ", elf_errmsg(-1)); *data_out = *data_in; } if (gelf_getshdr(scn_out, &shdr_out) != &shdr_out) dwarfexport_error("gelf_getshdr() failed: ", elf_errmsg(-1)); shdr_out = shdr_in; if (gelf_update_shdr(scn_out, &shdr_out) == 0) dwarfexport_error("gelf_update_shdr() failed: ", elf_errmsg(-1)); } dwarfexport_log("After copying the original sections:"); log_elf(elf_out); add_debug_section_data(info); dwarfexport_log("After adding the debug sections:"); log_elf(elf_out); // Get the current last section (to fix section header and string table loc) auto last_scn = get_last_section(elf_out); GElf_Shdr last_shdr; if (gelf_getshdr(last_scn, &last_shdr) != &last_shdr) dwarfexport_error("gelf_getshdr() failed: ", elf_errmsg(-1)); // Fix the section header string table start location std::size_t shstrndx = 0; if (elf_getshdrstrndx(elf_out, &shstrndx) == -1) dwarfexport_error("elf_getshdrstrndx() failed: ", elf_errmsg(-1)); Elf_Scn *shstr_scn = elf_getscn(elf_out, shstrndx); GElf_Shdr shstr_shdr; if (!gelf_getshdr(shstr_scn, &shstr_shdr)) dwarfexport_error("elf_getshdr() failed: ", elf_errmsg(-1)); shstr_shdr.sh_offset = last_shdr.sh_offset + last_shdr.sh_size; if (!gelf_update_shdr(shstr_scn, &shstr_shdr)) dwarfexport_error("gelf_update_shdr() failed: ", elf_errmsg(-1)); // Fix the section header start location ehdr_out.e_shoff = shstr_shdr.sh_offset + shstr_shdr.sh_size; if (gelf_update_ehdr(elf_out, &ehdr_out) == 0) dwarfexport_error("gelf_update_ehdr() failed: ", elf_errmsg(-1)); dwarfexport_log("After fixing various offsets:"); log_elf(elf_out); if (elf_update(elf_out, ELF_C_WRITE) < 0) dwarfexport_error("elf_update() failed: ", elf_errmsg(-1)); elf_end(elf_out); close(fd_out); elf_end(elf_in); close(fd_in); } void generate_detached_dbg_info(std::shared_ptr info, const std::string &path) { auto dbg = info->dbg; auto err = info->err; // Invokes the callback to create the needed sections Dwarf_Signed sectioncount = dwarf_transform_to_disk_form(dbg, &err); if (sectioncount == DW_DLV_NOCOUNT) { dwarfexport_error("dwarf_transform_to_disk_form() failed: ", dwarf_errmsg(err)); } int fd = 0; int prev_section_index = -1; for (Dwarf_Signed d = 0; d < sectioncount; ++d) { Dwarf_Signed section_index = 0; Dwarf_Unsigned length = 0; Dwarf_Ptr bytes = dwarf_get_section_bytes(dbg, d, §ion_index, &length, &err); if (bytes == NULL) { dwarfexport_error("dwarf_get_section_bytes() failed: ", dwarf_errmsg(err)); } auto section_name = detached_sections.at(section_index).substr(1); std::string fullpath = path + PATH_SEP + section_name; // We're in a different section, so open a new fd if (prev_section_index != section_index) { if (fd != 0) { close(fd); } // strip the leading '.' on the section name fd = open(fullpath.c_str(), O_WRONLY | O_CREAT, 0777); if (fd < 0) { dwarfexport_error("open failed: ", path); } prev_section_index = section_index; } // TODO: this is not necessarily an error if (write(fd, bytes, length) != length) { dwarfexport_error("write() failed"); } } } void write_dwarf_file(std::shared_ptr info, const Options &options) { if (options.attach_debug_info()) { generate_copy_with_dbg_info(info, options.filename, options.dbg_filename()); } else { generate_detached_dbg_info(info, options.filepath); } dwarf_producer_finish(info->dbg, 0); } ================================================ FILE: src/platform.cpp ================================================ #include #include #include #include #include #include "dwarfexport.h" /** * IDA uses a different register numbering scheme internally, so * we need to convert that to the DWARF one. * * FIXME: for some reason, this doesn't work for registers when used * to pass arguments. */ // For both amd64 and i386, IDA produces the following register list: // // idaapi.ph_get_regnames() = // ['ax', 'cx', 'dx', 'bx', 'sp', 'bp', // 'si', 'di', 'r8', 'r9', 'r10', 'r11', // 'r12', 'r13', 'r14', 'r15', 'al', // 'cl', 'dl', 'bl', 'ah', 'ch', 'dh', // 'bh', 'spl', 'bpl', 'sil', 'dil', 'ip', // 'es', 'cs', 'ss', 'ds', 'fs', 'gs', 'cf', // 'zf', 'sf', 'of', 'pf', 'af', 'tf', 'if', // 'df', 'efl', 'st0', 'st1', 'st2', 'st3', // 'st4', 'st5', 'st6', 'st7', 'fpctrl', // 'fpstat', 'fptags', 'mm0', 'mm1', 'mm2', // 'mm3', 'mm4', 'mm5', 'mm6', 'mm7', 'xmm0', // 'xmm1', 'xmm2', 'xmm3', 'xmm4', 'xmm5', // 'xmm6', 'xmm7', 'xmm8', 'xmm9', 'xmm10', // 'xmm11', 'xmm12', 'xmm13', 'xmm14', 'xmm15', // 'mxcsr', 'ymm0', 'ymm1', 'ymm2', 'ymm3', // 'ymm4', 'ymm5', 'ymm6', 'ymm7', 'ymm8', // 'ymm9', 'ymm10', 'ymm11', 'ymm12', 'ymm13', // 'ymm14', 'ymm15', 'bnd0', 'bnd1', 'bnd2', // 'bnd3', 'xmm16', 'xmm17', 'xmm18', 'xmm19', // 'xmm20', 'xmm21', 'xmm22', 'xmm23', 'xmm24', // 'xmm25', 'xmm26', 'xmm27', 'xmm28', 'xmm29', // 'xmm30', 'xmm31', 'ymm16', 'ymm17', 'ymm18', // 'ymm19', 'ymm20', 'ymm21', 'ymm22', 'ymm23', // 'ymm24', 'ymm25', 'ymm26', 'ymm27', 'ymm28', // 'ymm29', 'ymm30', 'ymm31', 'zmm0', 'zmm1', // 'zmm2', 'zmm3', 'zmm4', 'zmm5', 'zmm6', 'zmm7', // 'zmm8', 'zmm9', 'zmm10', 'zmm11', 'zmm12', // 'zmm13', 'zmm14', 'zmm15', 'zmm16', 'zmm17', // 'zmm18', 'zmm19', 'zmm20', 'zmm21', 'zmm22', // 'zmm23', 'zmm24', 'zmm25', 'zmm26', 'zmm27', // 'zmm28', 'zmm29', 'zmm30', 'zmm31', 'k0', 'k1', // 'k2', 'k3', 'k4', 'k5', 'k6', 'k7'] static int translate_amd64(int ida_reg_num) { // Numbers from http://source.winehq.org/source/dlls/dbghelp/cpu_x86_64.c#L739 enum AMD64 { RAX = 0, RDX = 1, RCX = 2, RBX = 3, RSI = 4, RDI = 5, RBP = 6, RSP = 7, R8 = 8, R9 = 9, R10 = 10, R11 = 11, R12 = 12, R13 = 13, R14 = 14, R15 = 15, RIP = 16, XMM0 = 17, ST0 = 33, ST1 = 34, ST2 = 35, ST3 = 36, ST4 = 37, ST5 = 38, ST6 = 39, ST7 = 40, EFLAGS = 49, ES = 50, CS = 51, SS = 52, DS = 53, FS = 54, GS = 55, TR = 62, LDTR = 63, MXCSR = 64, CTRL = 65, STAT = 66 }; int low_number_mapping[] = { RAX, RCX, RDX, RBX, RSP, RBP, RSI, RDI, R8, R9, R10, R11, R12, R13, R14, R15, RAX, RCX, RDX, RBX, RAX, RCX, RDX, RBX, RSP, RBP, RSI, RDI, -1, // ip? ES, CS, SS, DS, FS, GS, EFLAGS, EFLAGS, EFLAGS, EFLAGS, EFLAGS, EFLAGS, EFLAGS, EFLAGS, EFLAGS, EFLAGS, ST0, ST1, ST2, ST3, ST4, ST5, ST6, ST7, CTRL, STAT, -1 // fptags? }; if (ida_reg_num < 56) { return low_number_mapping[ida_reg_num]; } else if (ida_reg_num >= 56 && ida_reg_num < 64) { return XMM0 + (ida_reg_num - 56); } else if (ida_reg_num >= 64 && ida_reg_num < 80) { return XMM0 + (ida_reg_num - 64); } else { return -1; } } static int translate_i386(int ida_reg_num) { // Numbers from http://source.winehq.org/source/dlls/dbghelp/cpu_i386.c#L517 enum I386 { EAX = 0, ECX = 1, EDX = 2, EBX = 3, ESP = 4, EBP = 5, ESI = 6, EDI = 7, EIP = 8, EFLAGS = 9, CS = 10, SS = 11, DS = 12, ES = 13, FS = 14, GS = 15, ST0 = 16, ST1 = 17, ST2 = 18, ST3 = 19, ST4 = 20, ST5 = 21, ST6 = 22, ST7 = 23, CTRL = 24, STAT = 25, TAG = 25, FPCS = 26, FPIP = 27, FPDS = 29, FPDO = 30, XMM0 = 32, MXCSR = 40 }; int low_number_mapping[] = { EAX, ECX, EDX, EBX, ESP, EBP, ESI, EDI, }; if (ida_reg_num < sizeof(low_number_mapping) / sizeof(low_number_mapping[0])) { return low_number_mapping[ida_reg_num]; } else { return -1; } } // http://infocenter.arm.com/help/topic/com.arm.doc.ihi0040b/IHI0040B_aadwarf.pdf // // idaapi.ph_get_regnames() = // ['R0', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7', 'R8', 'R9', 'R10', 'R11', // 'R12', 'SP', 'LR', 'PC', 'CPSR', 'CPSR_flg', 'SPSR', 'SPSR_flg', 'T', // 'CS', 'DS', 'acc0', 'FPSID', 'FPSCR', 'FPEXC', 'FPINST', 'FPINST2', // 'MVFR0', 'MVFR1', 'APSR', 'IAPSR', 'EAPSR', 'XPSR', 'IPSR', 'EPSR', // 'IEPSR', 'MSP', 'PSP', 'PRIMASK', 'BASEPRI', 'BASEPRI_MAX', 'FAULTMASK', // 'CONTROL', 'Q0', 'Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7', 'Q8', 'Q9', // 'Q10', 'Q11', 'Q12','Q13', 'Q14', 'Q15', 'D0', 'D1', 'D2', 'D3', 'D4', // 'D5', 'D6', 'D7', 'D8', 'D9', 'D10', 'D11', 'D12', 'D13', 'D14', 'D15', // 'D16', 'D17', 'D18', 'D19', 'D20', 'D21', 'D22', 'D23', 'D24', 'D25', // 'D26', 'D27', 'D28', 'D29', 'D30', 'D31', 'S0', 'S1', 'S2', 'S3', 'S4', // 'S5', 'S6', 'S7', 'S8', 'S9', 'S10', 'S11', 'S12', 'S13', 'S14', 'S15', // 'S16', 'S17', 'S18', 'S19', 'S20', 'S21', 'S22', 'S23', 'S24', 'S25', // 'S26', 'S27', 'S28', 'S29', 'S30', 'S31', 'CF', 'ZF', 'NF', 'VF', 'X0', // 'X1', 'X2', 'X3', 'X4', 'X5', 'X6', 'X7', 'X8', 'X9', 'X10', 'X11', 'X12', // 'X13', 'X14', 'X15', 'X16', 'X17', 'X18', 'X19', 'X20', 'X21', 'X22', // 'X23', 'X24', 'X25', 'X26', 'X27', 'X28', 'X29', 'X30', 'XZR', 'SP', 'PC', // 'V0', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'V11', // 'V12', 'V13', 'V14', 'V15', 'V16', 'V17', 'V18', 'V19', 'V20', 'V21', // 'V22', 'V23', 'V24', 'V25', 'V26', 'V27', 'V28', 'V29', 'V30', 'V31'] static int translate_arm(int ida_reg_num) { enum ARM { R0 = 0, R1 = 1, R2 = 2, R3 = 3, R4 = 4, R5 = 5, R6 = 6, R7 = 7, R8 = 8, R9 = 9, R10 = 10, R11 = 11, R12 = 12, SP = 13, LR = 14, PC = 15, CPSR = 16, }; int low_number_mapping[] = {R0, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, R12, SP, LR, PC, CPSR}; if (ida_reg_num < sizeof(low_number_mapping) / sizeof(low_number_mapping[0])) { return low_number_mapping[ida_reg_num]; } else { return -1; } } int translate_register_num(int ida_reg_num) { auto reg_num = (ida_reg_num / 8) - 1; if (reg_num == -1) { return -1; } switch (ph.id) { case PLFM_386: return (inf.is_64bit()) ? translate_amd64(reg_num) : translate_i386(reg_num); case PLFM_ARM: return (inf.is_64bit()) ? -1 : translate_arm(reg_num); default: return -1; } } static bool disassembler_lvar_reg_and_offset(func_t *func, member_t *member, int *reg, int *offset); static bool decompiler_lvar_reg_and_offset(cfuncptr_t cfunc, const lvar_t &var, int *reg, int *offset) { // FIXME: Due to current IDA limitations, stkoff may not always return a // useful value: https://forum.hex-rays.com/viewtopic.php?f=4&t=4154 switch (ph.id) { case PLFM_386: if (inf.is_64bit()) { *reg = DW_OP_breg7; // rsp *offset = var.location.stkoff(); } else { // On 32bit intel, just use the disassembler logic auto func = get_func(cfunc->entry_ea); auto frame = get_frame(func); if (frame == nullptr) { return false; } auto member = get_member_by_name(frame, &var.name[0]); if (member == nullptr) { return false; } return disassembler_lvar_reg_and_offset(func, member, reg, offset); } return true; case PLFM_ARM: if (inf.is_64bit()) { return false; } else { *reg = DW_OP_breg13; // SP *offset = var.location.stkoff(); } default: return false; } } Dwarf_P_Expr decompiler_stack_lvar_location(Dwarf_P_Debug dbg, cfuncptr_t cfunc, const lvar_t &var) { Dwarf_Error err = 0; Dwarf_P_Expr loc_expr = dwarf_new_expr(dbg, &err); int stack_reg, stack_offset; if (!decompiler_lvar_reg_and_offset(cfunc, var, &stack_reg, &stack_offset)) { dwarfexport_log("Unable to calculate location on stack"); return nullptr; } dwarfexport_log("Variable located at ", stack_offset, " bytes from register #", stack_reg); if (dwarf_add_expr_gen(loc_expr, stack_reg, stack_offset, 0, &err) == DW_DLV_NOCOUNT) { dwarfexport_error("dwarf_add_expr_gen failed: ", dwarf_errmsg(err)); } return loc_expr; } static bool disassembler_lvar_reg_and_offset(func_t *func, member_t *member, int *reg, int *offset) { switch (ph.id) { case PLFM_386: if (inf.is_64bit()) { *reg = DW_OP_breg7; // rsp *offset = member->soff; } else { *reg = DW_OP_breg5; // ebp auto frame = get_frame(func); auto size = get_struc_size(frame->id); auto saved_regs = get_member_by_name(frame, " s"); if (saved_regs == nullptr) { return false; } auto saved_regs_off = saved_regs->soff; auto s_offset = size - (size - saved_regs_off); int offset_from_base = member->soff - s_offset; if (offset_from_base > 0) { offset_from_base += 16; } *offset = offset_from_base; } return true; case PLFM_ARM: if (inf.is_64bit()) { return false; } else { *reg = DW_OP_breg11; // r11 auto frame = get_frame(func); auto size = get_struc_size(frame->id); // NOTE: This assumes arm saved-registers is always 4 on 32 bit platforms. // Needed because there is no magic ' s' member for arm. auto saved_regs_off = size - 4; auto s_offset = size - (size - saved_regs_off); int offset_from_base = member->soff - s_offset; *offset = offset_from_base; } return true; default: return false; } } Dwarf_P_Expr disassembler_stack_lvar_location(Dwarf_P_Debug dbg, func_t *func, member_t *member) { Dwarf_Error err = 0; Dwarf_P_Expr loc_expr = dwarf_new_expr(dbg, &err); int stack_reg, stack_offset; if (!disassembler_lvar_reg_and_offset(func, member, &stack_reg, &stack_offset)) { dwarfexport_log("Unable to calculate location on stack"); return nullptr; } dwarfexport_log("Variable located at ", stack_offset, " bytes from register #", stack_reg); if (dwarf_add_expr_gen(loc_expr, stack_reg, stack_offset, 0, &err) == DW_DLV_NOCOUNT) { dwarfexport_error("dwarf_add_expr_gen failed: ", dwarf_errmsg(err)); } return loc_expr; }