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